# Copyright 2008-2012 Cumulus Systems Incorporated.
# All Rights Reserved.
#
# This file contains the code to process the Raw Performance data for the HNAS Server whose IP Address is passed as argument to this script.
#
# @param : IP Address - HNAS SMU IP Address
#
# @param : Server IP Address - HNAS Server IP Address
#
# @return : In case of Success, returns 0. In case of Failure, returns 1.
#
# Sample command: perl hnasPerfDataGenerator.pl <SMU IP Address>  <Server IP Address> <Node ID>
#
#!/usr/bin/perl -w

# It is used for strict compilation.
use strict;

# It is used to get base file name from the complete file name.
use File::Basename;

# It is used to get the current date and time.
use Time::HiRes qw(gettimeofday);

use POSIX "strftime";

# This is used to create folder recursively.
use File::Path qw(mkpath);

# It is used to dump the complex data structure.
use Data::Dumper;

#use XML::Simple;

use File::Path;
# ----------------------------------------------------------------------------------------------------------------------------------------------------
# GLOBAL Variables
# ----------------------------------------------------------------------------------------------------------------------------------------------------

#megha default location
#use constant APP_HOME => "/cygdrive/f/Megha/HNAS/work/megha/server/deploy";
use constant APP_HOME => "/usr/local/megha";
#use constant APP_HOME => "/usr/local/megha";

# Contain Probe Version number.
my $probeVersion = "10";

# This variable is used to store the path of probe properties files. It is required to read the the HNAS credentials from the .properties
# file specific to the input HNAS IP address.
my $propFilePath = "";

# This variable is used to store the name of .properties file which corresponds to the input HNAS IP address.
my $propFileName = "";

# This variable is used to store the complete name of log file.
my $logFile = "";

# This variable is used to store the file handle of log file.
my $LOG_HANDLE;

# This variable is used to store the return status of function calls.
my $status = 0;

# This variable is used to store the HNAS SMU IP Address.
my $hnasSMUIpAddress = "";

# This variable is used to store the HNAS Server IP Address.
my $hnasServerIpAddress = "";

#This variable is used to store the HNAS Node ID
my $hnasServerNodeID;

# This variable is used to store the location of HNAS runtime files.
my $hnasRunTimeLocation = "";

# This variable is used to store the complete path of app.properties file.
my $appPropertiesFilePath = "";

# This variable is used to store the Site name.
my $siteName = "";

# This variable is used to store the path where perf data folder hase to be moved.
my $finalPerfFolder = "";

# This variable is used to store the path which temporary perf has to been created in time. 
my $tempPerfDumpPath = "";

# This variable is used as the FILE handle for current counter performance data file. This file contains counter specific performance data for 15
# minutes.
my $PERF_FILE;

# This hash is used to store the complete Performance data to generate all MARS specific files/folders which contains the Performance data for 15
# minutes.
my %perfData = ();


# This variable resource display names required to create the folder hierarchy for performance data
# TODO populate this hash by reading the resource.xml
my %resourceNameHash = (
        "hnasSystem" => "HNAS System",
        "hnasNode" => "HNAS Node",
        "hnasEVS" => "HNAS EVS",
        "hnasFS" => "HNAS FS",
        "hnasStoragePool" => "HNAS Storage Pool",
        "hnasSystemDevice" => "HNAS System Device",
    );


# ----------------------------------------------------------------------------------------------------------------------------------------------------
# Main function
# ----------------------------------------------------------------------------------------------------------------------------------------------------
    
# Initialize the environment.
$status = init();
if (0 != $status)
{
    logMsg("Error: Call to init() failed.");
    goto EXIT;
}

processRawDataFromTempFolders();

# De-init the environment.
deInit();

EXIT:

    exit $status;

# ----------------------------------------------------------------------------------------------------------------------------------------------------
# Sub-routines
# ----------------------------------------------------------------------------------------------------------------------------------------------------

# This function is used to initialize the environment to run the Perl script correctly.
#
# @affected global variables :
#   $propFilePath
#   $logFile
#   $LOG_HANDLE
#   $hnasSMUIpAddress
#   $hnasServerIpAddress
#   $appPropertiesFilePath
#   $tempPerfDumpPath
#
# @return :
#   0 if Success
#   1 if Error
sub init
{
    # This variable is used to store the return value of function calls.
    my $retVal = 0;

    # This variable is used to store the base folder path on the probe.
    my $baseFolder = "";

    # Set base folder.
    $baseFolder = APP_HOME;

    #for appending current date to our log file
    my ($seconds, $microseconds) = gettimeofday;
    my $currentTime = strftime("%Y-%m-%d %H:%M:%S", localtime($seconds));
    my($date,$time)=split(' ',$currentTime,2);
    
    $logFile = $baseFolder."/logs/hnasPerlScript.".$date.".log";

    # Open the log file.
    open($LOG_HANDLE, ">>", $logFile) or die "Error: Not able to open the file: [$logFile].";

    # If number of command line arguments are not correct then quit.
    my $args = $#ARGV + 1;
    if (3 != $args)
    {
        print "perl hnasPerfDataGenerator.pl <SMU IP Address>  <Server IP Address> <Node ID>\n";
        logMsg("Error: Number of arguments to hnasPerfDataGenerator.pl are not correct.");
        logMsg("perl hnasPerfDataGenerator.pl <SMU IP Address>  <Server IP Address> <Node ID>.");
        logMsg("Input arguments = ".$args);
        $retVal = 1;
        goto EXIT;
    }

    # Get the HNAS Storage IP Addrss from command line argument.
    $hnasSMUIpAddress = $ARGV[0];
    
    # Get the HNAS server Ip address from the command line argument.
    $hnasServerIpAddress = $ARGV[1];
    
    #has node ID
    $hnasServerNodeID = $ARGV[2];

    logMsg("Info: Input SMU IP Address = [$hnasSMUIpAddress]");
    logMsg("Info: Input Server IP Address = [$hnasServerIpAddress]");
    
    # Set different paths.
    $propFilePath = $baseFolder."/conf/probe";
    logMsg("Info: Properties file path: [$propFilePath].");

    # Get the name of .properties file corresponding to HNAS Storage.
    $status = getPropertyFileName();
    if (0 != $status)
    {
        logMsg("Error: Call to getPropertyFileName() failed.");
        $retVal = 1;

        goto EXIT;
    }
   
    # Read the .properties file corresponding to HNAS Storage.
    $status = readPropertyFile();
    if (0 != $status)
    {
        logMsg("Error: Call to readPropertyFile() failed.");
        $retVal = 1;

        goto EXIT;
    }

    # This variable is used to store the path of Probe folder in db/probe.
    my $hnasProbeFolder = $baseFolder."/db/probe/".$siteName."/HNAS_".$hnasSMUIpAddress."_".$hnasServerIpAddress;
    logMsg("Info: Creating folder: [$hnasProbeFolder].");

    # Create the folder for this HNAS Probe in the probe folder.
    unless (defined eval {mkpath($hnasProbeFolder)})
    {
        logMsg("Error: Not able to create folder: [$hnasProbeFolder].");
        $retVal = 1;

        goto EXIT;
    }
    
    # Set the path where temporary perf data gets dumped.
    $tempPerfDumpPath = $hnasProbeFolder."/".$hnasServerNodeID."/TempPerfData";
    logMsg("Info: Creating temp Perf data path: [$tempPerfDumpPath].");

    # Create the folder for temporary perf data.
    unless (defined eval {mkpath($tempPerfDumpPath)})
    {
        logMsg("Error: Not able to create folder: [$tempPerfDumpPath].");
        $retVal = 1;

        goto EXIT;
    }

    # Set the path where temporary perf data gets dumped.
    $finalPerfFolder = $hnasProbeFolder."/".$hnasServerNodeID."/perf";
    logMsg("Info: Creating final Perf data path: [$finalPerfFolder].");

    # Create the folder for temporary perf data.
    unless (defined eval {mkpath($finalPerfFolder)})
    {
        logMsg("Error: Not able to create folder: [$finalPerfFolder].");
        $retVal = 1;

        goto EXIT;
    }    
    
    # Set the complete path of app.properties file.
    $appPropertiesFilePath = $baseFolder."/conf/app.properties";
    logMsg("Info: app.properties file path: [$appPropertiesFilePath].");

    # Read the content of app.properties file.
    $retVal = readAppPropertyFile();
    if (0 != $retVal)
    {
        logMsg("Error: Call to readAppPropertyFile() failed.");
        $retVal = 1;

        goto EXIT;
    }
    
    
    # This component will read resourceDef.xml and will populate the resourceName hash lookup.
    #

    # create object
    #my $xml = new XML::Simple;

    # read XML file
    #my $data = $xml->XMLin($baseFolder."/conf/ResourceDef.xml");    
    
    #foreach (@{$data->{'ResourceDef'}}){
        
        #if ( exists($resourceNameHash{$_->{'type'}} )) {
         #       $resourceNameHash{$_->{'type'}} = $_->{'displayName'};
        #}            
    #}
    
    
EXIT:

    return $retVal;
}


# This function starts scanning tempPerfData folder for given probe.
# It will scan raw data from the folder YYYYMMDD_hhmmss and create mars format perf data in perf folder of probe.
# if above steps are successful it will clean the raw data folder from TempPerfData folder and
# rename the folder in perf as .DONE to be cosnumed by JAVA coce
sub processRawDataFromTempFolders
{
    
    logMsg("Info: started to process raw performance by scanning the folders in TempPerfData.");
    
    # This varialbe is used to store the unsorted list of Perf folder names. We are using hash object to save the directory name so that sorting will
    # be easy.
    my %folderHash = ();

    # This variable is used to store the sorted list of Perf folder names.
    my @sortedFolderList = ();
  
    # Get the complete name of all files/folders present in the base folder for raw performance data.
    opendir(DIR, $tempPerfDumpPath) or die $!;
    
    # Loop through every object name.
    while (my $objName = readdir(DIR)) 
    {
        # If current object is a directory then only we will process
        if (not -d $tempPerfDumpPath."/".$objName)
        {
            next;
        }
        
        my $dirName = $objName;
        
        # if directory name don't match pattern YYYYMMDD_hhmmss then ignore it
        if($dirName !~ /^\d\d\d\d\d\d\d\d_\d\d\d\d\d\d$/ ) {
            next;
        }        
        
        my $rawFileName = $tempPerfDumpPath."/".$objName."/hnasPerf.dump";
        # if this folder dosn't contain this hnasPerf.dump then ignore it
        if( not -e $rawFileName) {
            next;
        }        
        $folderHash{$dirName} = $dirName;
    }
    
    closedir(DIR);
    
    # Make the sorted list of folder as we have to process oldest folder first.
    for my $key (sort {$a<=>$b} keys %folderHash)
    {
        push(@sortedFolderList, $key);
    }

    
    foreach my $folderName (@sortedFolderList)
    {
        my $rawPerfFile = $tempPerfDumpPath."/".$folderName."/hnasPerf.dump";
        
        # process the raw perf file and update the global hash data structure 
        processRawPerfFile($rawPerfFile);
        
        # 
        dumpPerfData($folderName);
        
        cleanRawDataNFinish($folderName);
    
        % perfData = ();
    }
}

sub cleanRawDataNFinish() {
     # This variable is used to store the return value of function calls.
    my $retVal = 0;
    
    my ($folderName)  = (@_);

    # We need to rename the folder in <Site-name>/perf folder from "<timestamp>_<timestamp>" to "<timestamp>_<timestamp>.DONE" so that Java
    # Performance code can use it. It is to avoid the case that Perl script is in the middle of updating "<timestamp>_<timestamp>" folder and Java
    # code start using it.
    
    #old 
    my $oldFolderName = $finalPerfFolder."/".$folderName;
    
    # Genearate the new folder.
    my $newFolderName = $finalPerfFolder."/".$folderName.".DONE";

    # TODO: Check the return value.
    rename($oldFolderName, $newFolderName);
    logMsg("Info: Renamed [$oldFolderName] to [$newFolderName].");
        

    my @files = glob("'".$tempPerfDumpPath."/".$folderName."/*'");
    foreach my $file (@files)
    {
        logMsg("Info: Deleting file: [$file].");

        if (1 != unlink($file))
        {
            logMsg("Error: File delete failed. File: [$file].");
            $retVal = 1;
        
            goto EXIT;
        }
    }
    
    if (1 != rmtree($tempPerfDumpPath."/".$folderName))
    {
        logMsg("Error: Folder delete failed. File: [$tempPerfDumpPath."/".$folderName].");
        $retVal = 1;
        
        goto EXIT;
    }

EXIT:

    # Clear the list for files which was used in the last MARS Perf cycle.
    logMsg("Info: Clearing variables used in current Perl collection cycle.");


    return $retVal;
}




sub processRawPerfFile() {
    my ($rawPerfFile) = (@_);
    
    # It is used to indicate the beginning of HNAS Performance data in the raw performance data file.
    my $perfDataStart = 0;
    my $firstLine = 0;
    
    logMsg("Info: Reading raw performance data from file :".$rawPerfFile);

    open(PERF_DUMP, $rawPerfFile) or die logMsg("Error: Not able to open the file: [$rawPerfFile].");
    
    my %hash = ();
        
    # Loop through the content of "hnasPerf.dump" file.
    while (my $line  = <PERF_DUMP>)
    {
        # Remove the new line character.
        chomp($line);
        
        #$line =~ s/^\R//g;
        $line=~s/[\r\n]+//g;
        if ($line =~ /(.+)\$\s*rusc/)
        {
            $perfDataStart = 1;
            next;
        }
        # Process the current line only if reached at Performance data part in the file.
        if (1 == $perfDataStart)
        {
            if ($line =~ /(.+)\$\s*/) {
                last;
            }
            
            if($firstLine == 0) {
                my @headers = csvsplit($line);
                 
                my $index=0;
                foreach my $val (@headers) {
                    $hash{$index}->{"attrIdAtsignature"} = $val;
                    if(! defined $hash{$index}->{"values"}  ) {
                        $hash{$index}->{"values"} = [];
                    }
                    $index = $index +1;
                }
                $firstLine = 1 ;
            }else {
                my @values = csvsplit($line);
                my $index=0;
                foreach my $val (@values) {
                     if ($val =~ /\d/) {
                        push(@{$hash{$index}->{"values"}} , $val);                        
                     }else {
                        push(@{$hash{$index}->{"values"}} , " ");
                     }                     
                     $index = $index +1;
                }
            }
        }
    }
    
    close (PERF_DUMP);
    
    
    foreach my $index (keys %hash) {
        my $attrIdAtSingrature = $hash{$index}->{"attrIdAtsignature"};
        my @values = @{$hash{$index}->{"values"}};
        my ($attrId, $resSignature ,$resType) = $attrIdAtSingrature =~ m/(\S+)@((\S+)#\S+)/g;
        
        my $i=0;
        foreach my $val (@values) {
            updatePerfData($resType, $resSignature, $attrId, $i,$val);
            $i = $i +1;
        }
    }
}



# This function is used to update the global hash variable which contain all information which is required to generate the one set of MARS Perf data.
#
# @affected global variables :
#   None
#
# @return :
#   0 if Success
#   1 if incomplete data found in the file.
sub updatePerfData
{
    my ($resourceType, $resourceName, $counterName, $time, $counterVal) = @_;

    # If we get '-' as the counter value then ignore that value.
    if ("-" eq $counterVal)
    {
        $counterVal = "";
    }

    #print Dumper(\%perfData);

    # Check whether Hash for storing the Perf data for Resource "$resourceType" is already exist or not. If yes then use it.
    my $resourcePerfHash = ();
    if (exists $perfData{$resourceType})
    {
        $resourcePerfHash = $perfData{$resourceType};
    }
    
    #print Dumper(\%$resourcePerfHash);

    # Check whether Hash for storing the Perf data for Counter "$counterName" in Resource "$resourceType" is already exist or not. If yes then use it.
    my $counterPerfHash  = ();
    if (exists $resourcePerfHash->{$counterName})
    {
        $counterPerfHash = $resourcePerfHash->{$counterName};
    }

    # Check whether Hash for storing the Perf data for Resource instance "$resourceName" for Counter "$counterName" is already exist or not. If yes
    # then use it.
    my $resourceInstancePerfHash = ();
    if (exists $counterPerfHash->{$resourceName})
    {
        $resourceInstancePerfHash = $counterPerfHash->{$resourceName};
    }
    
    #print Dumper(\%$resourceInstancePerfHash);

    #print Dumper(\%$counterPerfHash);

    # Check whether Perf value for Time "$time" for Counter "$counterName" in Resource instance "$resourceName" is already exist or not. If yes then
    # use it.
    my $perfVal = 0;
    if (exists $resourceInstancePerfHash->{$time})
    {
        $perfVal = $resourceInstancePerfHash->{$time};
    }

    $perfVal = $counterVal;

    # Now update the final Perf data container.
    $resourceInstancePerfHash->{$time} = $perfVal;
    $counterPerfHash->{$resourceName} = \%$resourceInstancePerfHash;
    $resourcePerfHash->{$counterName} = \%$counterPerfHash;
    $perfData{$resourceType} = \%$resourcePerfHash;

    #print "After Dump\n";
    #print Dumper(\%perfData);
}



# This function is used to dump final Performance data in MARS format.
#
# @affected global variables :
#   %selectedFolderForPerfData
#   $PERF_FILE
#
# @return :
#   0 if Success
#   1 if Error
sub dumpPerfData
{
    # This variable is used to store the return value of function calls.
    my $retVal = 0;

    my ($currentFolder) = (@_);    
    # This variable is used to store the complete path of folder where perf data for the current cycle will be stored.
    my $marsCurrentPerfFolder = $finalPerfFolder."/".$currentFolder;
    
    logMsg("Info: Creating Folder: [$marsCurrentPerfFolder].");
    unless (defined eval {mkpath($marsCurrentPerfFolder)})
    {
        logMsg("Error: Not able to create Perf date folder.");

        $retVal = 1;
        goto EXIT;
    }

    my $resourcePerfHash = ();
    my $resourceInstancePerfHash = ();
    my $counterPerfHash  = ();
    my $perfVal = 0;

    logMsg("Info: Start processing of final Perf data for current cycle.");

    # Loop through the list of all resource whose Perf data is available.
    for my $resourceType (keys %perfData)
    {
        # TODO populate the Resource folder by reading the 
        # This variable is used to store the complete path of folder where current resource specific data will be stored.
        my $resourceFolder = $marsCurrentPerfFolder."/".$resourceNameHash{$resourceType};        

        # Create the folder with Resource name inside the MARS Perf folder for the current cycle.
        unless (defined eval {mkpath($resourceFolder)})
        {
            logMsg("Error: Not able to create Perf Resource folder. Name = [$resourceFolder].");

            $retVal = 1;
            goto EXIT;
        }

        $resourcePerfHash = $perfData{$resourceType};
        
        # Loop through the list of Perf counters for the current Resource.
        for my $counterName (keys %$resourcePerfHash)
        {
            # Create the Perf file for the current counter.
            my $perfFile = $resourceFolder."/".$counterName.".txt";
            open($PERF_FILE, ">", $perfFile ) or die logMsg("Error: Not able to open the file: [$perfFile].");

            # Dump the Perf metadata in the counter Perf file.
            prepareProbeMetadata();

            $counterPerfHash = $resourcePerfHash->{$counterName};

            # Loop thourgh the list of all Resource instances in the current Perf counter.
            for my $resourceName (keys %$counterPerfHash)
            {
                $resourceInstancePerfHash = $counterPerfHash->{$resourceName};

                # This variable is used to construct the comma separated list of Perf data point for the current cycle.
                my $perfDataPoints = "";

                # This variable is used to decide whether we encountered the first Perf data point or not.
                my $isFirst = 1;

                # Loop thorough the list of all Perf data point for the current counter.
                for my $time (keys %$resourceInstancePerfHash)
                {
                    $perfVal = $resourceInstancePerfHash->{$time};

                    # If it the first Perf data point then initialize $perfDataPoints with the first Perf data point.
                    if (1 == $isFirst)
                    {
                        $perfDataPoints = $perfVal;

                        $isFirst = 0;
                    }
                    # If we already got the first Perf data point then start concatenating the Perf data points.
                    else
                    {
                        $perfDataPoints = $perfDataPoints.",".$perfVal;
                    }
                }
                
                # Dump the data for current Resource instance the counter Perf file.
                print $PERF_FILE "$resourceName".","."$perfDataPoints\n";
            }

            close($PERF_FILE);
        }
    }

EXIT:

    return $retVal;
}



sub csvsplit {
        my $line = shift;
        my $sep = (shift or ',');

        return () unless $line;

        my @cells;
        $line =~ s/\r?\n$//;

        my $re = qr/(?:^|$sep)(?:"([^"]*)"|([^$sep]*))/;

        while($line =~ /$re/g) {
                my $value = defined $1 ? $1 : $2;
                push @cells, (defined $value ? $value : '');
        }

        return @cells;
}



# This function is used to update the HNAS Performance file with the Metadata information about the Probe.
#
# @affected global variables :
#   None
#
# @return :
#   0 if Success
#   1 if Error
sub prepareProbeMetadata
{   
    print $PERF_FILE "%meta\n";
    print $PERF_FILE "probe_id:".$siteName."_".$hnasSMUIpAddress."_".$hnasServerIpAddress."\n";
    print $PERF_FILE "probe_type:HNAS\n";
    print $PERF_FILE "probe_site:$siteName\n";
    print $PERF_FILE "probe_server:$hnasServerIpAddress\n";
    print $PERF_FILE "probe_version:$probeVersion\n";
    print $PERF_FILE "collection_interval:60\n";
    print $PERF_FILE "number_of_samples:15\n";
    print $PERF_FILE "%meta\n";    
    return 0;
}



# This function is used to search all files present in $propFilePath folder and find the correct .properties file
# corresponding to input HNAS SMU IP Address and HNAS Server IP Address .
#
# @affected global variables :
#   $propFileName
#
# @return :
#   0 if found correct .properties file
#   1 if not found correct .properties file
sub getPropertyFileName
{
    # It is used to get the list of all .properties files present in the "probe" folder.
    my @files = ();

    # It is used to check whether we have found the correct .properties file for the HNAS Storage.
    my $foundFile = 0;

    logMsg("Info: Getting the list of files present in: [$propFilePath].");

    # Get the list of all .properties files.
    @files = glob($propFilePath."/*.properties");
    
    # Check each .properties file in the folder.
    foreach my $propFileNameInList (@files)
    {
        logMsg("Info: Found properties file: [$propFileNameInList].");
        
        # Extract the file name from the complete file path.
        my $fileName = basename($propFileNameInList);

        # Check whether we are looking at correct .properties file.
        if ($fileName =~ /^HNAS_(\S+)_(\S+).properties$/)
        {
            # Match the given IP Address to find the correct .properties file because there could be multiple HNAS properties files present in the
            # folder.
            if ($hnasSMUIpAddress eq $1 && $hnasServerIpAddress eq $2)
            {
                logMsg("Info: Found correct properties file: [$fileName].");
    
                $propFileName = $propFileNameInList;
                $foundFile = 1;

                last;
            }
        }
    }
    
    # If we found the correct .properties file then return with Success.
    if (1 == $foundFile)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

# This function is used to read the .properties file which corresponds to the input HNAS IP address. 
# This function will read siteName from the respective .properties file.
# @affected global variables :
#   $siteName
#
# @return :
#   0 if Success
#   1 if Error
sub readPropertyFile
{
    # This variable is used to store the return code for this function.
    my $retVal = 0;

    logMsg("Info: Reading file: $propFileName");

    open(PROP_FILE, $propFileName) or die logMsg("Error: Not able to open the file: [$propFileName].");

    # Loop through the content of .properties file.
    while (<PROP_FILE>)
    {
        # Remove the new line character.
        chomp;

        if ($_ =~ /^SiteName=(.+)(\s*)$/)
        {
                $siteName = $1;
        }
        else
        {
            # Current line is of no use. So ignore it.
        }
    }
    
    if ("" eq $siteName)
    {
        logMsg("Error: Site name is not present in the properties file.");
        $retVal = 1;

        goto EXIT;
    }

EXIT:

    close(PROP_FILE);

    return $retVal;
}

# ----------------------------------------------------------------------------------------------------------------------------------------------------

# This function is used to read HNAS related information from the app.properties file.
#
# @affected global variables :
#   $hnasRunTimeLocation
#
# @return :
#   0 if found correct information.
#   1 if not found correct information.
sub readAppPropertyFile
{
    # This variable is used to store the return value of function calls.
    my $retVal = 0;

    logMsg("Info: Reading file: $appPropertiesFilePath");

    open(PROP_FILE, $appPropertiesFilePath) or die logMsg("Error: Not able to open the file: [$appPropertiesFilePath].");

    # Loop through the content of app.properties file.
    while (<PROP_FILE>)
    {
        # Remove the new line character.
        chomp;

        # Look for "HNAS.runtime.location" property.
        if ($_ =~ /^(\s*)HNAS.runtime.location=(\s*)(.+)(\s*)$/)
        {
            $hnasRunTimeLocation = $3;
        }
        else
        {
            # Current line is of no use. So ignore it.
        }
    }

    #my $baseFolder = "";
    #Set base folder.
    #$baseFolder = APP_HOME;    
    #$hnasRunTimeLocation = $baseFolder."/hnas";
    
    if ("" eq $hnasRunTimeLocation)
    {
        logMsg("Error: HNAS.runtime.location property not found in app.properties file.");
        $retVal = 1;

        goto EXIT;
    }

EXIT:

    close(PROP_FILE);

    return $retVal;
}

# ----------------------------------------------------------------------------------------------------------------------------------------------------

# This function is used to log a message in the log file. It logs the message in the following format:
# [YYYY-MM-DD HH:MM:ss,SSS]  [HNAS-<IP Address>] [Verifier|Conf|Perf] <Log message>
#
# @param :
#   $_[0] - Log message.
#
# @affected global variables :
#   None
#
# @return :
#   Nothing
sub logMsg
{
    # This variable store the current date and time in a specific format as: [YYYY-MM-DD HH:MM:ss,SSS]
    my $currentTime = "";

    # Read input parameter.
    (my $logMsg) = @_;

    # Get the current date and time.
    my ($seconds, $microseconds) = gettimeofday;    
    
    $currentTime = strftime("%Y-%m-%d %H:%M:%S", localtime($seconds));
    $currentTime = "[".$currentTime.",".$microseconds."]";

    # Construct the final log message.
    my $finalMsg = $currentTime." [HNAS-".$hnasSMUIpAddress."-".$hnasServerIpAddress."-".$hnasServerNodeID."] [Perf-Processor] ".$logMsg."\n";

    # Dump the final log message in log file.
    print $LOG_HANDLE $finalMsg;
}

# ----------------------------------------------------------------------------------------------------------------------------------------------------

# This function is used to de-initialize the environment.
#
# @affected global variables :
#   $LOG_HANDLE
#
# @return :
#   None
sub deInit
{
    close($LOG_HANDLE);
}

# ----------------------------------------------------------------------------------------------------------------------------------------------------
