#!/usr/bin/perl

#############################################################
## @file alarm
# @brief   This utility is used for check the system resources
#          and report if they are changed
# @details
# @autor   Petr Kascheev, Alexander Kolotov
# @version 1.00 - Initial version
# @version 1.01 - SNMP trap generation by Sergey Ivin
# @version 1.02 - Two colons were removed before shared functions and variables.
# @version 1.03 - check for user has been changed for group.
# @version 1.04 - Get rid of using external tools when we can use builtin ones.


use lib "/opt/nortel/base/lib/";

use warnings;
use strict;
use common_variables;
use common_functions;
use basedb;
use baselog;
use base_snmp;
use base_system;

my $ALARMS_DB = "$PATH_DB/alarms";

my %resource_type = (
                     mem => 'mem',
                     cpu => 'cpu',
                     dev => '\/dev\/'
                    );

my %message_type = (
                    CRIT => 'CRITICAL',
                    WARN => 'WARNING'
                   );

my %comparison_type = (
                       gt => 'greater than',
                       lt => 'less than',
                       eq => 'equal',
                       ne => 'not equal'
                      );

my %messages = (
                'WARN_mem_SET'   => 'OSM0018',
                'WARN_mem_CLEAR' => 'OSM0019',
                'CRIT_mem_SET'   => 'OSM0020',
                'CRIT_mem_CLEAR' => 'OSM0021',
                'WARN_cpu_SET'   => 'OSM0022',
                'WARN_cpu_CLEAR' => 'OSM0023',
                'CRIT_cpu_SET'   => 'OSM0024',
                'CRIT_cpu_CLEAR' => 'OSM0025',
                'WARN_dev_SET'   => 'OSM0026',
                'WARN_dev_CLEAR' => 'OSM0027',
                'CRIT_dev_SET'   => 'OSM0028',
                'CRIT_dev_CLEAR' => 'OSM0029'
               );

my %db = (
          SET   => '1',
          CLEAR => '0',
         );

# Pieces which key consist from.
my @KEY_PARTS = qw/monit_service type resource markID/;

# Sequence of chars which is used to separate pieces in the key
my $KEY_SEP = '###';

sub is_correct_resource($);
sub is_correct_type($);
sub is_correct_tag($);
sub is_correct_value($);
sub get_cpu_info();
sub get_cpu_usage();
sub get_mem_usage();
sub get_device_space_usage($);
sub get_usage($);
sub find_and_clear_alarms($);
sub check_and_send_alarm($);
sub display_alarms($);
sub generate_key($);
sub parse_key($$);
sub modify_key(@);
sub show_message($);
sub db_lock($);
sub db_unlock($);
sub default_message();

exit(main());

########################################################################
# This subroutine verifies resource parameter by using %resource_type
#  INPUT: $word - passed parameter
# OUTPUT: $TRUE  - resource is valid
#         $FALSE - resource is not valid
########################################################################
sub is_correct_resource($)
{
   my $res = shift @_;

   if (($res =~ /^$resource_type{dev}\w+$/) || (exists $resource_type{$res}))
   {
      return $TRUE;
   }

   return $FALSE;
} ## end sub is_correct_resource($)

########################################################################
# This subroutine verifies type of message parameter by
# using %message_type
#  INPUT: $word - passed parameter
# OUTPUT: $TRUE  - type of message is valid
#         $FALSE - type of message is not valid
########################################################################
sub is_correct_type($)
{
   my $type = shift @_;

   if (exists $message_type{$type})
   {
      return $TRUE;
   }

   return $FALSE;
} ## end sub is_correct_type($)

########################################################################
# This subroutine verifies comparison tag parameter by
# using %comparison_type
#  INPUT: $word - passed parameter
# OUTPUT: $TRUE  - comparison tag is valid
#         $FALSE - comparison tag is not valid
########################################################################
sub is_correct_tag($)
{
   my $tag = shift @_;

   if (exists $comparison_type{$tag})
   {
      return $TRUE;
   }

   return $FALSE;
} ## end sub is_correct_tag($)

########################################################################
# This subroutine verifies value. It must be an integer between 0 and 100
#  INPUT: $word - passed parameter
# OUTPUT: $TRUE  - value is valid
#         $FALSE - value is not valid
########################################################################
sub is_correct_value($)
{
   my $value = shift @_;

   if ($value =~ /^\d+$/)
   {
      if (($value > 0) && ($value < 100))
      {
         return $TRUE;
      }
   } ## end if ($value =~ /^\d+$/)

   return $FALSE;
} ## end sub is_correct_value($)

###############################################################################
# @fn get_cpu_info()
# @brief   Get cpu usage info
# @details This subroutine uses /proc/stat in order to get the information about
#          the amount of time, that the system spent in user mode, user mode with
#          low priority (nice), system mode, and the idle task etc (see
#          man proc). Calculations of the total amount of time and the amount of
#          time in user mode are the same as in Monit:
#              Total = user + nice + system + idle + wait + irq + softirq
#              User  = user + nice
# @param none
# @return $cpu_total - the total amount of time.
#         $cpu_user -  the amount of time in user mode.
#         They  will be 'undef' if some error happens
# @note
sub get_cpu_info()
{
   my $cpu;
   my $cpufd;
   my @cpu_usage;
   my $cpu_total = undef;
   my $cpu_user  = undef;

   # Get data from /proc/stat
   unless (-e '/proc/stat')
   {
      baselog($LOG_ERROR, 'There is no resource for getting statistics of CPU usage');
      return ($cpu_total, $cpu_user);
   }

   # Get data from /proc/stat
   unless (open $cpufd, '<', '/proc/stat')
   {
      baselog($LOG_ERROR, "Can not open /proc/stat: $!");
      return ($cpu_total, $cpu_user);
   }

   ($cpu) = grep {/^cpu\s/} <$cpufd>;

   unless (close $cpufd)
   {
      baselog($LOG_ERROR, "Can not close /proc/stat: $!");
   }

   unless ($cpu)
   {
      baselog($LOG_ERROR, 'Can not read statistics of CPU usage');
      return ($cpu_total, $cpu_user);
   }

   baselog($LOG_DEBUG, $cpu);

   $cpu =~ s/cpu\s+//;

   @cpu_usage = split /\s+/, $cpu;

   # Get sums
   if (scalar(@cpu_usage) < 7)
   {
      baselog($LOG_ERROR, 'Can not get CPU usage: unsupported kernel is found');
   }
   else
   {

      # user + nice + system + idle + wait + irq + softirq
      $cpu_total += $_ foreach @cpu_usage;

      # user + nice
      $cpu_user = $cpu_usage[0] + $cpu_usage[1];

      baselog($LOG_DEBUG, "CPU total: $cpu_total; CPU user: $cpu_user");
   } ## end else [ if (scalar(@cpu_usage)...

   return ($cpu_total, $cpu_user);
} ## end sub get_cpu_info()

########################################################################
# This subroutine calculates CPU load. There is no way to get CPU load
# in the current moment by using some proc-file or command, but there is
# possibility to get the amount of time, that the system spent in user
# mode, user mode with low priority (nice), system mode, and the idle
# task etc (see man proc). So, it is necessary to get these data twice
# with a small delay. The difference between the first data and the
# second ones allows to get percent of CPU load.
#  INPUT: None
# OUTPUT: $percent - percent of memory usage. It will be 'undef' if
#                    some error happens
########################################################################
sub get_cpu_usage()
{
   my $cpu_total     = 0;
   my $old_cpu_total = 0;
   my $cpu_user      = 0;
   my $old_cpu_user  = 0;
   my $percent       = undef;

   # Get data for the first time
   ($old_cpu_total, $old_cpu_user) = get_cpu_info();
   if (defined $old_cpu_total)
   {

      # one-second delay
      sleep(1);

      # Get data for the second time
      ($cpu_total, $cpu_user) = get_cpu_info();
      if (defined $cpu_total)
      {

         # Calculate percent of CPU load
         if (($cpu_total - $old_cpu_total) > 0)
         {
            $percent = sprintf("%.1f", ($cpu_user - $old_cpu_user) / ($cpu_total - $old_cpu_total) * 100);
            baselog($LOG_DEBUG, "CPU usage: $percent");
         }
         else
         {
            baselog($LOG_ERROR, "Can not calculate CPU usage");
         }

      } ## end if (defined $cpu_total...
   } ## end if (defined $old_cpu_total...

   return $percent;
} ## end sub get_cpu_usage()

###############################################################################
# @fn get_mem_usage()
# @brief   Get mem usage info
# @details This subroutine calculates memory usage. This information is extracted
#          from /proc/meminfo file.
#          Calculation of the free memory value is the same as in Monit: Free
#          memory is the sum of MemFree, Buffers and Cached
# @param none
# @return $percent - percent of memory usage. It will be 'undef' if some
#                    error happens
#         $msg     - the message about memory usage.
# @note
sub get_mem_usage()
{
   my %meminfo = ('MemTotal:', 0, 'MemFree:', 0, 'Buffers:', 0, 'Cached:', 0);
   my @attrs = ();
   my $free_memory;
   my $used_memory;
   my $percent = undef;
   my $msg     = '';

   # Get data from /proc/meminfo
   unless (open MEM, '<', '/proc/meminfo')
   {
      baselog($LOG_ERROR, "Can not open /proc/meminfo: $!");
      return ($percent, '');
   }
   while (<MEM>)
   {
      @attrs = split /\s+/, $_;
      baselog($LOG_DEBUG, join(' ', @attrs));

      # Get data only for the specified fields.
      $meminfo{$attrs[0]} = $attrs[1] if exists $meminfo{$attrs[0]};
   } ## end while (<MEM>)
   unless (close MEM)
   {
      baselog($LOG_ERROR, "Can not close /proc/meminfo: $!");
   }

   # Free memory is the sum of MemFree, Buffers and Cached
   $free_memory = $meminfo{'MemFree:'} + $meminfo{'Buffers:'} + $meminfo{'Cached:'};
   $used_memory = $meminfo{'MemTotal:'} - $free_memory;

   baselog($LOG_DEBUG, "MEM total: $meminfo{'MemTotal:'}; MEM used: $used_memory");

   # Calculate percent of memory usage
   if ($meminfo{'MemTotal:'} > 0)
   {
      $percent = sprintf('%.1f', $used_memory / $meminfo{'MemTotal:'} * 100);
      $msg = "Current allocated $used_memory Kbytes, maximum available $free_memory Kbytes.";
      baselog($LOG_DEBUG, "MEM usage: $percent");
   } ## end if ($meminfo{'MemTotal:'...
   else
   {
      baselog($LOG_ERROR, 'Can not calculate MEM usage');
   }

   return ($percent, $msg);
} ## end sub get_mem_usage()

###############################################################################
# @fn get_device_space_usage($)
# @brief   This subroutine calculates a device space usage. It uses 'df' command
#          for this.
# @details 
# @param   $dev - path to the device
# @return  $percent - percent of the device space usage. It will be
#                    'undef' if some error happens
#          $msg     - the message about the device space usage.
# @note
sub get_device_space_usage($)
{
   my $dev = shift @_;

   my $devinfo;
   my @attrs = ();
   my $free_dev;
   my $used_dev;
   my $percent = undef;
   my $msg     = '';
   my @df      = ();

   # Get data by using 'df'. Process the line with the device data only
   unless (do_system([$DF, '-B', '1', $dev], {$dsOUT => \@df}))
   {
      baselog($LOG_ERROR, "Can not get device $dev space usage");
      return ($percent, '');
   }
   ($devinfo) = grep {/$dev/} @df;

   # df retruns line from 6 elements:
   #   path to device
   #   total space in bytes
   #   used space in bytes
   #   free space in bytes (reduced by space reserved by root)
   #   percantage of used space
   #   mount point
   @attrs = split /\s+/, $devinfo;

   baselog($LOG_DEBUG, $devinfo);

   # Calculate percent of the device space usage
   if ((scalar(@attrs) > 4) && ($attrs[1] > 0))
   {

      # used / total
      # used space is calculated from total space and free space, because
      # space reserved by root is needed to take into account
      $percent = sprintf('%.1f', ($attrs[1] - $attrs[3]) / $attrs[1] * 100);
      $msg = "Only ${attrs[3]} bytes remain.";
      baselog($LOG_DEBUG, "device $dev space usage: $percent");
   } ## end if ((scalar(@attrs) > ...
   else
   {
      baselog($LOG_ERROR, "Can not calculate device $dev space usage");
   }

   return ($percent, $msg);
} ## end sub get_device_space_usage($)

########################################################################
# This subroutines gets the information about current state of the
# system and fills 'percent' and 'rest_of_message' of the hash
#  INPUT: $self - refference to the hash with data
# OUTPUT: $TRUE  - the hash is filled by new data
#         $FALSE - some error happens
########################################################################
sub get_usage($)
{
   my $self = shift @_;

   if ($self->{is_system_wide})
   {
      if ($self->{resource} eq "cpu")
      {
         $self->{percent} = get_cpu_usage();
      }
      elsif ($self->{resource} eq "mem")
      {
         ($self->{percent}, $self->{rest_of_message}) = get_mem_usage();
      }
      else
      {
         ($self->{percent}, $self->{rest_of_message}) = get_device_space_usage($self->{resource});
      }

      return $FALSE unless defined $self->{percent};

      baselog($LOG_DEBUG, $self->{resource} . " usage: " . $self->{percent});
   } ## end if ($self->{is_system_wide...

   return $TRUE;
} ## end sub get_usage($)

########################################################################
# This subroutine generates the hash key. If some the key's piece is
# undefined, the key will be generated partly.
#  INPUT: $self - refference to the hash with data
# OUTPUT: $key  - the generated key
########################################################################
sub generate_key($)
{
   my $self = shift @_;

   my $key = '';

   foreach my $piece (@KEY_PARTS)
   {

      # Generate the key until the corresponding piece is not empty
      # string. Since the monit_service can be empty the key is
      # generated anyway
      if (($key eq '') || ((defined $self->{$piece}) && ($self->{$piece} ne '')))
      {
         $key .= $self->{$piece} . $KEY_SEP;
      }
      else
      {
         last;
      }
   } ## end foreach my $piece (@KEY_PARTS...

   return $key;
} ## end sub generate_key($)

########################################################################
# This subroutine split the hash key in order to get its components. The
# order of components is described in the generate_key subroutine.
#  INPUT: $_[0] - refference to the hash with data
#         $_[1] - parsing key
# OUTPUT: $TRUE  - key is parsed successfully
#         $FALSE - key is not parsed
########################################################################
sub parse_key($$)
{
   my $self = shift @_;
   my $key  = shift @_;

   my @tmparr = split /$KEY_SEP/, $key;
   if (scalar(@tmparr) == 0)
   {
      return $FALSE;
   }

   my $i = 0;
   foreach my $piece (@KEY_PARTS)
   {
      $self->{$piece} = $tmparr[$i];
      $i++;
   }

   return $TRUE;
} ## end sub parse_key($$)

########################################################################
# This subroutine display status of all known alarms
#  INPUT: $self - refference to the hash with data
# OUTPUT: $OK    - the information is displayed corectly
#         $ERROR - some error happens
########################################################################
sub display_alarms($)
{
   my $self = shift @_;

   my ($monit_service, $type, $key_value) = ();
   my $ret = $OK;

   # Lock alarms DB file
   if (!db_lock($self))
   {
      return $ERROR;
   }

   my @hkeys = keys(%{$self->{hash_db}});

   if (scalar(@hkeys) > 0)
   {
      print " Service                   Type     Resource   ID              | Value\n";
      print " ========================= ======== ========== =============== | =====\n";

      foreach my $key (@hkeys)
      {
         baselog($LOG_DEBUG, "$key is found");

         if (!parse_key($self, $key))
         {
            baselog($LOG_ERROR, "A wrong key is found\n", $TRUE);
            $ret = $ERROR;
            last;
         } ## end if (!parse_key($self, ...

         $monit_service = ($self->{monit_service} eq '') ? "system-wide-test" : $self->{monit_service};
         $type          = $message_type{$self->{type}};
         $key_value     = $self->{hash_db}->{$key};

         printf " %-25s %-8s %-10s %-15s | %-5s\n", $monit_service, $type, $self->{resource}, $self->{markID}, $key_value;
      } ## end foreach my $key (@hkeys)
   } ## end if (scalar(@hkeys) > 0...
   else
   {
      baselog($LOG_INFO, "No alarms configured\n", $TRUE);
   }

   # Unlock alarms DB file
   if (!db_unlock($self))
   {
      return $ERROR;
   }

   return $ret;
} ## end sub display_alarms($)

########################################################################
# This subroutine modifies the correspong key in alarms DB. The new
# value of the key is passed as the third argument
#  INPUT: $_[0] - refference to the hash with data
#         $_[1] - key
#         $_[2] - action
# OUTPUT: None
########################################################################
sub modify_key(@)
{
   my $self   = shift @_;
   my $key    = shift @_;
   my $action = shift @_;

   $self->{is_condition_true} = $TRUE;
   $self->{flag_of_message}   = $action;
   $self->{hash_db}->{$key}   = $db{$action};
   baselog($LOG_DEBUG, "$key is " . $db{$action});
} ## end sub modify_key(@)

########################################################################
# This subroutine finds alarms which is set for the given service and
# clear them
#  INPUT: $self - refference to the hash with data
# OUTPUT: $OK    - all alarms were processed correctly
#         $ERROR - some error happens
########################################################################
sub find_and_clear_alarms($)
{
   my $self = shift @_;

   my %tmp_res = ();

   # Lock alarms DB file
   if (!db_lock($self))
   {
      return $ERROR;
   }

   # Since only 'monit_service' is defined, the subroutine returns
   # a key which consists from one component only (e.g. 'solid###' for
   # the solid application or '###' for the system wide alarms)
   my $short_key = generate_key($self);
   baselog($LOG_DEBUG, "The short key is '$short_key'");

   baselog($LOG_DEBUG, join(" ", keys(%{$self->{hash_db}})));

   foreach my $key (keys(%{$self->{hash_db}}))
   {

      # Filter the alarms which match the short key
      if ($key =~ /^$short_key/)
      {
         baselog($LOG_DEBUG, "$key is matched");

         # Clear the alarms
         if ($self->{hash_db}->{$key} eq $db{SET})
         {

            # Get attributes of the key
            if (!parse_key($self, $key))
            {
               baselog($LOG_WARNING, "A wrong key is found: $key");
               next;
            }

            modify_key($self, $key, "CLEAR");

            # Calculate the current value of the resource usage. In order
            # to do not calculate usage of the same resource the
            # provious caclulated value is stored in the %tmp_res hash.
            if (defined $tmp_res{$self->{resource}})
            {
               $self->{percent}         = $tmp_res{$self->{resource}};
               $self->{rest_of_message} = $tmp_res{'m' . $self->{resource}};
            }
            else
            {
               $self->{percent} = undef;
               get_usage($self);

               # For not the system wide alarms $self->{percent} will be
               # undefined
               if (defined $self->{percent})
               {
                  $tmp_res{$self->{resource}} = $self->{percent};
                  $self->{rest_of_message} .= " FORCED";
                  $tmp_res{'m' . $self->{resource}} = $self->{rest_of_message};
               } ## end if (defined $self->{percent...
               else
               {
                  push @{$self->{other}}, ". FORCED";
               }
            } ## end else [ if (defined $tmp_res{$self...

            $self->{cmp_tag} = 'lt';

            show_message($self);
         } ## end if ($self->{hash_db}->...
      } ## end if ($key =~ /^$short_key/...
   } ## end foreach my $key (keys(%{$self...

   # Unlock alarms DB file
   if (!db_unlock($self))
   {
      return $ERROR;
   }

   return $OK;
} ## end sub find_and_clear_alarms($)

########################################################################
# This subroutine checks if alarm satisfies the condition if it does,
# sends a alarm
#  INPUT: $self - refference to the hash with data
# OUTPUT: None
########################################################################
sub check_and_send_alarm($)
{
   my $self = shift @_;

   # Get the information about current state of the system
   if (!get_usage($self))
   {
      return $ERROR;
   }

   # Lock alarms DB file
   if (!db_lock($self))
   {
      return $ERROR;
   }

   # Generate hash key
   my $key = generate_key($self);
   baselog($LOG_DEBUG, "The key is '$key'");

   # Make a decision whether the message should be printed:
   # If 'comparison tag' is 'eq' or 'ne' - the message should be printed
   # If 'comparison tag' is 'lt' and the SET-message has been already
   #     printed - the CLEAR-message should be printed
   # If 'comparison tag' is 'gt' and the SET-message has not been already
   #     printed - the SET-message should be printed
   # The current state of the system is checked as well for the system
   # wide requests.
   if ($self->{cmp_tag} eq "lt")
   {
      if ((!$self->{is_system_wide}) || ($self->{percent} < $self->{value}))
      {
         if (   (defined $self->{hash_db}->{$key})
             && ($self->{hash_db}->{$key} eq $db{SET}))
         {
            modify_key($self, $key, "CLEAR");
         }
      } ## end if ((!$self->{is_system_wide...
   } ## end if ($self->{cmp_tag} eq...
   elsif ($self->{cmp_tag} eq "gt")
   {
      if ((!$self->{is_system_wide}) || ($self->{percent} > $self->{value}))
      {
         if (   (!defined $self->{hash_db}->{$key})
             || ($self->{hash_db}->{$key} ne $db{SET}))
         {
            modify_key($self, $key, "SET");
         }
      } ## end if ((!$self->{is_system_wide...
   } ## end elsif ($self->{cmp_tag} eq...
   elsif ($self->{cmp_tag} =~ /^(eq|ne)$/)
   {
      $self->{is_condition_true} = $TRUE;
   }

   show_message($self);

   # Unlock alarms DB file
   if (!db_unlock($self))
   {
      return $ERROR;
   }

   return $OK;
} ## end sub check_and_send_alarm($)

########################################################################
# This subroutine generates an message and sends it to the baselog
# subsystem
#  INPUT: $self - refference to the hash with data
# OUTPUT: $TRUE  - the message is generated
#         $FALSE - the message is not generated
########################################################################
sub show_message($)
{
   my $self = shift @_;

   if ($self->{is_condition_true})
   {
      my $message;
      my $key;

      # It is necessary to get data from hash only if the test is the system
      # wide and the comparison tag is either 'gt' or 'lt' ($flag_of_message
      # equals either 'SET' or 'CLEAR')
      if (($self->{is_system_wide}) && ($self->{flag_of_message} ne ""))
      {
         my $is_dev = $FALSE;

         # Get the message from %messages
         if ($self->{resource} =~ /^\/dev\//)
         {
            $is_dev = $TRUE;
            $key    = $self->{type} . "_dev_" . $self->{flag_of_message};
         }
         else
         {
            $key = $self->{type} . "_" . $self->{resource} . "_" . $self->{flag_of_message};
         }
         my $msg_id = $messages{$key};
         $message = $message_type{$self->{type}} . " " . $self->{flag_of_message} . ": " . $SNMP_MSGS{$msg_id}->{'msg'};

         # Substitude the real value
         $message =~ s/%THRESHOLD%/$self->{value}/;
         $message =~ s/%REST%/$self->{rest_of_message}/;

         # Expand the message
         if ($is_dev == $TRUE)
         {
            $message =~ s/%PARTITION%/$self->{resource}/;
            send_snmp_trap($msg_id, {PARTITION => $self->{'resource'}, THRESHOLD => $self->{'value'}, REST => $self->{'rest_of_message'}});
         }
         else
         {
            send_snmp_trap($msg_id, {THRESHOLD => $self->{'value'}, REST => $self->{'rest_of_message'}});
         }
      } ## end if (($self->{is_system_wide...
      else
      {

         # The message for the process-specific requests and for
         # 'eq'/'ne' requests.
         $message = $message_type{$self->{type}};
         $message .= " $self->{flag_of_message}:" if $self->{flag_of_message} ne "";
         $message .= " $self->{monit_service}($self->{monit_process_pid})" if $self->{monit_process_pid} ne "";
         $message .= " $self->{resource} usage " . $comparison_type{$self->{cmp_tag}} . " $self->{value} " . "@{$self->{other}}";
      } ## end else [ if (($self->{is_system_wide...

      baselog($LOG_EMERG, $message);
      return $TRUE;
   } ## end if ($self->{is_condition_true...

   return $FALSE;
} ## end sub show_message($)
########################################################################
# This subroutine checks whether the alarms DB exists and lock it.
#  INPUT: $self - refference to the hash with data
# OUTPUT: $TRUE  - DB is locked successfully
#         $FALSE - Some error happens
########################################################################
sub db_lock($)
{
   my $self = shift @_;

   # Create alarms DB
   if (!basedb_create($ALARMS_DB))
   {
      return $FALSE;
   }

   # Lock alarms DB file and get the hash linked with this DB
   ($self->{basedbDESC}, $self->{hash_db}) = basedb_lock($ALARMS_DB);
   if ((!$self->{basedbDESC}) || (!$self->{hash_db}))
   {
      baselog($LOG_ERROR, "Can not initialize DB hash");
      return $FALSE;
   }

   return $TRUE;
} ## end sub db_lock($)

########################################################################
# This subroutine unlocks the alarms DB.
#  INPUT: $self - refference to the hash with data
# OUTPUT: $TRUE  - DB is unlocked successfully
#         $FALSE - Some error happens
########################################################################
sub db_unlock($)
{
   my $self = shift @_;

   # Unlock alarms DB file
   unless (basedb_unlock($self->{basedbDESC}, $self->{hash_db}))
   {
      baselog($LOG_ERROR, "Can not unlock DB file!");
      return $FALSE;
   }

   return $TRUE;
} ## end sub db_unlock($)

########################################################################
# This subroutine prints usage help
#  INPUT: None
# OUTPUT: None
########################################################################
sub default_message()
{
   $0 =~ s/.*\/(.*)$/$1/egi;
   print "Usage:
\t$0 <CRIT/WARN> <cpu/mem/path-to-device> <mark ID> <eq/ne/gt/lt> <value>
or
\t$0 --clear [service]
or
\t$0 --show
";

} ## end sub default_message()

########################################################################
# The main subroutine of the utility. It parses the passed arguments,
# checks them, analyzes the resources, updates the data base and
# generates the message.
########################################################################
sub main
{
   my %self = (
               resource          => '',     #type of monitored resource
               type              => '',     #type of message
               markID            => '',     #unique identificator
               cmp_tag           => '',     #comparison tag
               value             => 0,      #value for comparison
               other             => undef,  #other args
               rest_of_message   => '',
               flag_of_message   => '',
               is_condition_true => $FALSE,
               percent           => undef,
               hash_db           => undef,  # data base hash
               basedbDESC        => undef,  #db file descriptor
               is_system_wide    => $TRUE,  #is the monitored resource is system wide?
               monit_service     => '',
               monit_process_pid => ''
              );

   if (warning_if_not_root_uid())
   {
      return $ERROR;
   }

   # Check passsed parameters
   if (!defined @ARGV)
   {
      baselog($LOG_ERROR, "Insufficient number of arguments provided\n", $TRUE);
      default_message();

      return $ERROR;
   } ## end if (!defined @ARGV)

   baselog($LOG_DEBUG, join(" ", @ARGV));

   if (($ARGV[0] eq "-h") || ($ARGV[0] eq "--help"))
   {
      default_message();
      return $OK;
   }
   elsif ($ARGV[0] eq "--show")
   {

      # Find and display all alarms
      my $ret = display_alarms(\%self);

      return $ret;
   } ## end elsif ($ARGV[0] eq "--show"...
   elsif ($ARGV[0] eq "--remove-db")
   {
      if (-e $ALARMS_DB)
      {
         baselog($LOG_DEBUG, "Try to remove $ALARMS_DB db");

         # Remove alarms DB file
         if (!basedb_remove($ALARMS_DB))
         {
            return $ERROR;
         }
      } ## end if (-e $ALARMS_DB)
      return $OK;
   } ## end elsif ($ARGV[0] eq "--remove-db"...
   elsif ($ARGV[0] eq "--clear")
   {

      if (scalar(@ARGV) > 2)
      {
         baselog($LOG_ERROR, "Incorrect number of arguments provided\n", $TRUE);
         default_message();

         return $ERROR;
      } ## end if (scalar(@ARGV) > 2)
      elsif (scalar(@ARGV) == 2)
      {

         # a service name can be provided together with the 'clear' option
         $self{monit_service}     = $ARGV[1];
         $self{monit_process_pid} = "unknown";

         $self{is_system_wide} = $FALSE;
      } ## end elsif (scalar(@ARGV) == 2...

      baselog($LOG_DEBUG, "MONIT_SERVICE: '$self{monit_service}'; MONIT_PROCESS_PID: '$self{monit_process_pid}'");

      # Find and clear all alarms for the given service
      find_and_clear_alarms(\%self);

      return $OK;
   } ## end elsif ($ARGV[0] eq "--clear"...
   elsif (scalar(@ARGV) < 5)
   {
      baselog($LOG_ERROR, "Incorrect number of arguments provided\n", $TRUE);
      default_message();

      return $ERROR;
   } ## end elsif (scalar(@ARGV) < 5)

   #parsing input parameters
   #<CRIT/WARN> <cpu/mem/path-to-device> <mark ID> <eq/ne/gt/lt> <value>
   $self{type}     = $ARGV[0];
   $self{resource} = $ARGV[1];
   $self{markID}   = $ARGV[2];
   $self{cmp_tag}  = $ARGV[3];
   $self{value}    = $ARGV[4];
   @{$self{other}} = @ARGV[5 .. $#ARGV];

   unless (is_correct_type($self{type}))
   {
      baselog($LOG_ERROR, "Incorrect type provided: $self{type}\n", $TRUE);
      return $ERROR;
   }
   unless (is_correct_resource($self{resource}))
   {
      baselog($LOG_ERROR, "Incorrect resource provided: $self{resource}\n", $TRUE);
      return $ERROR;
   }
   unless (is_correct_tag($self{cmp_tag}))
   {
      baselog($LOG_ERROR, "Incorrect comparison tag provided: $self{cmp_tag}\n", $TRUE);
      return $ERROR;
   }
   unless (is_correct_value($self{value}))
   {
      baselog($LOG_ERROR, "Incorrect value provided: $self{value}\n", $TRUE);
      return $ERROR;
   }

   # Get environment variables
   if ($ENV{MONIT_PROCESS_PID})
   {
      $self{monit_process_pid} = $ENV{MONIT_PROCESS_PID};
      $self{monit_service}     = ($ENV{MONIT_SERVICE}) ? $ENV{MONIT_SERVICE} : "";

      $self{is_system_wide} = $FALSE;
   } ## end if ($ENV{MONIT_PROCESS_PID...

   baselog($LOG_DEBUG, "MONIT_SERVICE: '$self{monit_service}'; MONIT_PROCESS_PID: '$self{monit_process_pid}'");

   # Check the condition and send an alarm
   if (check_and_send_alarm(\%self) == $ERROR)
   {
      return $ERROR;
   }

   return $OK;
} ## end sub main

