codetoad.com
  ASP Shopping CartForum & BBS
  - all for $20 from CodeToad Plus!
  
  Home || ASP | ASP.Net | C++/C# | DHTML | HTML | Java | Javascript | Perl | VB | XML || CodeToad Plus! || Forums || RAM 
Search Site:
Search Forums:
  Perl Script - File Handling.  tskarthikeyan at 09:21 on Tuesday, May 06, 2008
 

Hello Friends,

i have a base code perl file for appending a file. Some times it doesnt append the file correctly. Some times that file is removed. some times the new entry only appended. The other existing entries are removed from the file.

This perl file gets the inputs from the Java GUI and update a .cfg file with the new inputs. basically this is for scheduled backup it includes,the backuptime, backupfile, hostname like that.


I attached that perl file. Please have a look on this code and provide your comments please.

Thanks in advance.


#!/usr/local/bin/perl
#
# FILE: addSchedPlan.pl
#
# PROJECT: OS-KERNEL - SMF
#
#
# ABSTRACT: add a Scheduler plan for a specified schedulable command,
# to local Scheduler server;
# the command can be planned only if proper configured into
# SMF.cfg configuration file;
# It return '0' for correct executions, '1' for blocking
# problems and '>1' for warnings;
# it modify files:
# - SMF_INSTANCE_DIR/tools/scheduler/conf/schedulercmd.cfg
# - SMF_INSTANCE_DIR/tools/scheduler/conf/schedulerdb.dat
#
#-------------------------------------------------------

use strict;
use Getopt::Long;
use English;
use File::Copy;

use lib "/alcatel/7.1/Kernel/lib/lib_perl/";
use lib "/usr/Systems/CMC_1-CMC217-2.1-11D9/SMF/lib_perl/";


use commonutil;
use Remotizer;
use TmpTraceLog;
use FileUtility;
use HostHelper;
use errors;
use axcommon;


# generic vars:
# -------------
$OUTPUT_AUTOFLUSH++;

my $NMS_SYSTEM = "CMC";
my $NMS_INSTANCE = "1-CMC217-2.1-11D9";
my $SMF_INSTANCE_DIR = "/usr/Systems/CMC_1-CMC217-2.1-11D9/SMF";
my $SWM_INSTANCE_DIR = "/usr/Systems/CMC_1-CMC217-2.1-11D9/ngnSwmServer";
my $NMS_INSTANCE_DIR = "/usr/Systems/CMC_1-CMC217-2.1-11D9";
my $SMFCFG = $NMS_INSTANCE_DIR . "/NGN_swm" . "/Kernel/conf/SMF.cfg";
my $tmpfile = $SWM_INSTANCE_DIR ."/tmp/$$.dat";


my $RESTART_SCHED_SRV = "$SMF_INSTANCE_DIR/tools/scheduler/script/restartSchedSrv.sh"; # restart script for scheduler server
my $SCHED_CFG_FILE = "$SMF_INSTANCE_DIR/tools/scheduler/conf/schedulercmd.cfg"; # main scheduler command cfg file
my @SCHED_CFG_FILE_CONT = ();

my $SCHED_DB_FILE = "$SMF_INSTANCE_DIR/tools/scheduler/conf/schedulerdb.dat"; # main scheduler command data base file
my @SCHED_DB_FILE_CONT = ();

my $outFile = "$NMS_INSTANCE_DIR/maintenance/trace/ngnSwmSmfPlan.out"; #TODO
my $errFile = "$NMS_INSTANCE_DIR/maintenance/trace/ngnSwmSmfPlan.err"; #TODO


my $SMF_MASTER_WS = axcommon::get_master(); # master ws for SMF
my @SLAVE_WS = axcommon::get_osws(); # slaves, master included
my $localWs = HostHelper::HostName($NMS_SYSTEM, $NMS_INSTANCE); # current host name
my @OTHER_WS = @SLAVE_WS; # other topology ws (all ws without local ws)
push @OTHER_WS, $SMF_MASTER_WS;
@OTHER_WS = grep { $_ ne $localWs } @OTHER_WS;

my $NMS_USER = SMFgetKeyword($NMS_SYSTEM, $NMS_INSTANCE, "NMS_USER"); # current main user
my $NMS_GROUP = SMFgetKeyword($NMS_SYSTEM, $NMS_INSTANCE, "NMS_GROUP"); # current main user group

my @currCmdNames = (); # current commands names into $SCHED_CFG_FILE
my %entireCmd; # command to be scheduled
my %currCmd; # new hash (without kernel keys) to add into $SCHED_DB_FILE
my %newCmdDb; # hash of $SCHED_CFG_FILE about command to add
my ($day, $hour, $min, $sec);
my $tmp;

my $timezone;
my $etccmd;


#set the env var
#---------------
$etccmd = "/etc/TIMEZONE";
system($etccmd);


# Obtain the Timezone from the system
#-------------------------------------

#$timezone = $ENV{'TZ'};
#$timezone = substr($timezone,0,3);

# Adding the TimeZone ID from the system
----------------------------------------
$timezone = $ARGV[5];


my $cmdName=$ARGV[0];

GetOptions( h => \&::usage, # (OPTIONAL) '-h' starts the 'usage'

);


# check parameters:
# -----------------
if ((not defined $cmdName) )
{
usage();
}

defineStdOut();
defineStdErr();



# get current local Scheduler configuration (array of hash):
# ----------------------------------------------------------
if (-f $SCHED_CFG_FILE) {
$tmp = eval(readRemoteFile($SCHED_CFG_FILE, $localWs));
if ($EVAL_ERROR) {
#SMFerror("addPlan", "addPlan - incorrect format of file \"$SCHED_CFG_FILE\" on \"$localWs\" ws ($EVAL_ERROR)");
logMsg("addPlan - incorrect format of file \"$SCHED_CFG_FILE\" on \"$localWs\" ws ($EVAL_ERROR)");

exit(1);
}
if ($tmp) {
@SCHED_CFG_FILE_CONT = @$tmp; # get eval of current $SCHED_CFG_FILE content
}
else {
#SMFerror("addPlan", "addPlan - no plannable command found in local Scheduler server configuration ($localWs)");
logMsg("addPlan - no plannable command found in local Scheduler server configuration ($localWs)");
exit(1);
}

# get current commands names:
foreach $tmp (@SCHED_CFG_FILE_CONT) {
push @currCmdNames, $tmp->{name}; # generic element = hash reference
}
}
else {
#SMFerror("addPlan", "addPlan - no such file on \"$localWs\" ws ($SCHED_CFG_FILE)");
logMsg("addPlan - no such file on \"$localWs\" ws ($SCHED_CFG_FILE)");
exit(1);
}


# check that required command names exists in current configuration:
if (not grep /$cmdName/, @currCmdNames)
{
#SMFerror("addPlan", "addPlan - required \"$cmdName\" plan not found (verify congruence of file \"$SCHED_CFG_FILE\" on \"$localWs\" ws)");
logMsg("addPlan - required \"$cmdName\" plan not found (verify congruence of file \"$SCHED_CFG_FILE\" on \"$localWs\" ws)");
exit(3); ##213
}


# get command to be scheduled:
foreach $tmp (@SCHED_CFG_FILE_CONT)
{
%entireCmd = %$tmp;
if ($entireCmd{name} eq $cmdName)
{
$currCmd{name} = $entireCmd{name};
$currCmd{parameters} = $entireCmd{parameters};
$currCmd{description} = $entireCmd{description};
$currCmd{command} = $entireCmd{command};

last;
} # now '%currCmd' contains required command default keys (no Kernel keys)
} # now '%entireCmd' contains required command with all keys (kernel keys included)


# check Kernel parameters for schedule command action:
# ----------------------------------------------------
#if ((not defined $entireCmd{p_name}) || (not defined $entireCmd{rep_step}))
if ((not defined $entireCmd{p_name}))
{
#SMFerror("addPlan", "addPlan - selected \"$cmdName\" command cannot be automatically planned (check SCHEDULER configuration into local \"SMF.cfg\" files)");
logMsg("addPlan - selected \"$cmdName\" command cannot be automatically planned (check SCHEDULER configuration into local \"SMF.cfg\" files)");
exit(1);
}

if (not defined $entireCmd{p_comment})
{ # COMMENT (optional)
$entireCmd{p_comment} = "";
}


$entireCmd{not_week} = $ARGV[1];


$entireCmd{rep_step} =$ARGV[2];



$entireCmd{activate} = 1; # default value (activate configured plan)




# build new hash to be added into $SCHED_DB_FILE:
# -----------------------------------------------
$newCmdDb{name} = $entireCmd{p_name}; # plan name (string)

$newCmdDb{tz} = $timezone; # time zone (obtained from env var TZ)
$newCmdDb{comments} = $entireCmd{p_comment}; # command comment (string)
$newCmdDb{rep} = $entireCmd{rep_step}; # even repetition (seconds) [seconds for repetition interval]
$newCmdDb{state} = $entireCmd{activate}; # state = 1 means activate plan
$newCmdDb{weekend} = $entireCmd{not_week}; # not on weekend (boolean) [1 if not on weekend]
$newCmdDb{cmd} = {%currCmd};

# set start/stop schedule time (set start/stop values to exec command forever):
my %startStop;

# TODO my @act_time = split(":",$entireCmd{activation_time});

my @start_vals=split(":",$ARGV[3]);

$startStop{second} = $start_vals[5];
$startStop{minute} = $start_vals[4];
$startStop{hour} = $start_vals[3];
$startStop{day} = $start_vals[2]; # start at fixed date: 01:01:1970
$startStop{month} = $start_vals[1] - 1;
$startStop{year} = $start_vals[0];
#$startStop{timezone} = "GMT"; # fixed value
$startStop{timezone} = $timezone; # timezone obtained from env var
$newCmdDb{startAt} = {%startStop}; # hash reference

my @stop_vals=split(":",$ARGV[4]);

$startStop{second} = $stop_vals[5]; # stop at fixed value: 00:00:00 of 01:01:3000
$startStop{minute} = $stop_vals[4];
$startStop{hour} = $stop_vals[3];
$startStop{day} = $stop_vals[2];
$startStop{month} = $stop_vals[1] - 1;
$startStop{year} = $stop_vals[0];
#$startStop{timezone} = "GMT"; # fixed value
$startStop{timezone} = $timezone; # obtained from env var
$newCmdDb{stopAt} = {%startStop}; # hash reference




# get current local Scheduler db file content (array of hash):
# ------------------------------------------------------------
$tmp = getSchedDb($localWs, $entireCmd{p_name});
if (not defined $tmp) {
exit(1); # error message already shown
}
@SCHED_DB_FILE_CONT = @$tmp;


# write new version of "$SCHED_DB_FILE" on "$localWs" ws and (if required) align other ws:
# ----------------------------------------------------------------------------------------
my $warnings = 1; # if $warnings > 1, there are warnings - do not put this line before in the script
push @SCHED_DB_FILE_CONT, {%newCmdDb}; # add built command to commands repository
SMFnote("addPlan", "addPlan - updating local Scheduler plan repository ($localWs) ...");
#if (writeHashOnFile($SCHED_DB_FILE, "SCHED_CMD", $localWs, @SCHED_DB_FILE_CONT)) { # by 'commonutil.pm'
if (writeHashOnFile($tmpfile, "SCHED_CMD", $localWs, @SCHED_DB_FILE_CONT)) { # by 'commonutil.pm'
#SMFerror("addPlan", "addPlan - problems writing \"$SCHED_DB_FILE\" on \"$localWs\" ws");
#SMFwarning("addPlan", "addPlan - local Scheduler plan repository not updated ($localWs)");
logMsg("addPlan - problems writing \"$SCHED_DB_FILE\" on \"$localWs\" ws");
$warnings++;
}

#copy local file to scheddb
#--------------------------

my $success = 1;
sleep(3);
$success = copy($tmpfile,$SCHED_DB_FILE);
if($success == 0)
{
unlink($tmpfile);
logMsg("Could not copy \"$SCHED_DB_FILE\"");
exit(4); #Could not copy file
}
else
{
logMsg("Copied \"$SCHED_DB_FILE\"");
}


# restart Scheduler server on Master:
#SMFnote("addPlan", "addPlan - restarting local Scheduler server ($localWs) ...");
logMsg("addPlan - restarting local Scheduler server ($localWs) ...");
if (RemoteExecWithErrorCode($localWs, $RESTART_SCHED_SRV, "root", $NMS_SYSTEM, $NMS_INSTANCE)) {
#SMFerror("addPlan", "addPlan - during Scheduler server restart on \"$localWs\" ws");
logMsg("addPlan - during Scheduler server restart on \"$localWs\" ws");
$warnings++;
}

unlink($tmpfile);

my $addToAll = 0;

if (defined $addToAll)
{ # add current new plan to other scheduler servers repositories
foreach $tmp (@OTHER_WS) {

# get current Scheduler db file content from current ws:
#SMFnote("addPlan", "addPlan - updating \"$tmp\" Scheduler server plan repository ...");
logMsg("addPlan - updating \"$tmp\" Scheduler server plan repository ...");
my $tmp1 = getSchedDb($tmp, $entireCmd{p_name});
if (not defined $tmp1) {
#SMFerror("addPlan", "addPlan - problems getting Scheduler server plan repository on \"$tmp\" ws");
#SMFwarning("addPlan", "addPlan - Scheduler server plan repository not updated on \"$tmp\" ws");
logMsg("addPlan - problems getting Scheduler server plan repository on \"$tmp\" ws");
$warnings++;
next;
}
@SCHED_DB_FILE_CONT = @$tmp1;

# add new built plan to current plan repository:
push @SCHED_DB_FILE_CONT, {%newCmdDb};

# write new version of "$SCHED_DB_FILE" on current ws:

#if (writeHashOnFile($SCHED_DB_FILE, "SCHED_CMD", $tmp, @SCHED_DB_FILE_CONT)) { # by 'commonutil.pm'
if (writeHashOnFile($tmpfile, "SCHED_CMD", $tmp, @SCHED_DB_FILE_CONT)) { # by 'commonutil.pm'
#SMFerror("addPlan", "addPlan - problems writing \"$SCHED_DB_FILE\" on \"$tmp\" ws");
#SMFwarning("addPlan", "addPlan - Scheduler server plan repository not updated on \"$tmp\" ws");
logMsg("addPlan - problems writing \"$SCHED_DB_FILE\" on \"$tmp\" ws");
$warnings++;
next;
}

sleep(3);
$success = copy($tmpfile,$SCHED_DB_FILE);
if($success == 0)
{
unlink($tmpfile);
logMsg("Could not copy \"$SCHED_DB_FILE\" on \$tmp\"");
#exit(4); #Could not copy file in the presentation server.
}
else
{
logMsg("Copied \"$SCHED_DB_FILE\"");
}


# restart Scheduler server on current ws:
#SMFnote("addPlan", "addPlan - restarting Scheduler server on \"$tmp\" ws ...");
logMsg("addPlan - restarting Scheduler server on \"$tmp\" ws ...");
if (RemoteExecWithErrorCode($tmp, $RESTART_SCHED_SRV, "root", $NMS_SYSTEM, $NMS_INSTANCE)) {
#SMFerror("addPlan", "addPlan - during restart Scheduler server on \"$tmp\" ws");
logMsg("addPlan - during restart Scheduler server on \"$tmp\" ws");
$warnings++;
}
unlink($tmpfile);
}
}


# end script:
# -----------
if (($warnings - 1) == 0) {
#SMFnote("addPlan", "addPlan - operation is successful");
logMsg("addPlan - operation is successful");
}
else {
#SMFwarning("addPlan", "addPlan - end operation with errors or warnings");
logMsg("addPlan - end operation with errors or warnings");
}
exit($warnings - 1);


#################################################################################


#-------------------------------------------------------------
# Method name : getSchedDb
#
# Description : get '$SCHED_DB_FILE' file content from argument ws;
# it return an hash array where argument plan name
# will not be included;
# it returns undef in case of problems;
#-------------------------------------------------------------
sub getSchedDb()
{
my $sourceWs = shift;
my $currPlanName = shift;
my @arrayToReturn = ();


# get current Scheduler db file content (array of hash) from $sourceWs:
# [check if plan already scheduled; overwrite it in this case]
# ------------------------------------------------------------
if (-f $SCHED_DB_FILE) {
$tmp = eval(readRemoteFile($SCHED_DB_FILE, $sourceWs));
if ($EVAL_ERROR) {
#SMFerror("addPlan", "addPlan - incorrect format of file \"$SCHED_DB_FILE\" in \"$sourceWs\" ws ($EVAL_ERROR)");
logMsg("addPlan - incorrect format of file \"$SCHED_DB_FILE\" in \"$sourceWs\" ws ($EVAL_ERROR)");
return undef;
}
my @tmpArray = ();
if ($tmp) {
@tmpArray = @$tmp; # get eval of current $SCHED_DB_FILE content
}

# get existing plans (check if current plan name already present):
foreach $tmp (@tmpArray) {
my %tmp_hash = %$tmp;
my $tmp1 = $tmp_hash{name};
if ($tmp_hash{name} ne $currPlanName) { # current plan name must be different to new plan
push @arrayToReturn, {%tmp_hash}; # get existing plan
}
else {
#SMFerror("addPlan", "addPlan - plan already exists for \"$cmdName\" on \"$localWs\" ws)");
logMsg("addPlan - plan already exists for \"$cmdName\" on \"$sourceWs\" ws)");
exit(2); ##213
#SMFwarning("addPlan", "addPlan - a plan named \"".$entireCmd{p_name}."\" already exists in \"$SCHED_DB_FILE\" - OVERWRITE IT");
#$warnings++;
}
}
}

return \@arrayToReturn;
}

#-------------------------------------------------------------
# Method name : logMsg
#-------------------------------------------------------------

sub logMsg
{
my $msg = $_[0];
my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = localtime(time);
my $ft = POSIX::strftime( "%Y-%m-%d %H:%M:%S", $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst );

printf( STDOUT "%s [%d]: %s\n", $ft, $$, $msg );
}


#-------------------------------------------------------------
# Method name : defineStdOut
#-------------------------------------------------------------

sub defineStdOut
{
if ( defined($outFile) )
{
open( OUT, ">> $outFile" ) or errorExit( 1, "can't open $outFile: $!" );
open( STDOUT, ">&OUT " ) or errorExit( 1, "can't dup stderr to $outFile: $!" );
select(STDOUT);
$| = 1;
}
}


#-------------------------------------------------------------
# Method name : defineStdErr
#-------------------------------------------------------------

sub defineStdErr
{
if ( defined($errFile) )
{
open( ERR, ">> $errFile" ) or die "can't open $errFile: $!\n";
open( STDERR, ">&ERR " ) or die "can't dup stderr to $errFile: $!\n";
select(STDERR);
$| = 1;
}
}



#-------------------------------------------------------------
# Method name : usage
#-------------------------------------------------------------
sub usage
{
print qq(

NAME:

'/forum/addPlan.html': (OS-Kernel utility for SMF) add a Scheduler plan for
a specified schedulable action command to the local
Scheduler server

USAGE:

addPlan.pl -cmd command_name [-h]

-h show this help message


NOTE: an action command can be planned only if it is proper configured
for this purpose into a 'SMF.cfg' configuration file;

);
exit(1);
}

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

exit(0);




  Re: Perl Script - File Handling.  hermanningjaldsson at 12:23 on Tuesday, May 06, 2008
 

you surely do have a sense of humor.




  Re: Perl Script - File Handling.  tskarthikeyan at 06:37 on Thursday, May 08, 2008
 

Hello mimir,

Excuse me if my question hurts you. I am new to Perl. Now i am learning perl(beginner level). Sorry.

  Re: Perl Script - File Handling.  tskarthikeyan at 08:03 on Thursday, May 08, 2008
 

Hello Friends,

The cfg file is in this below format,

[
{
regno => 101,
name => <name string>,
details => {
dob => [ day => 08,
mon => 07,
year => 77
],
doj => [ dat => 08,
mon => 05,
year =. 08
]
}
emailid => <email>
}
]

I need to append this file with the new inputs in Perl Script.

Please give me an idea how to do this in Perl.




  Re: Perl Script - File Handling.  tskarthikeyan at 08:05 on Thursday, May 08, 2008
 

The Above data file is existing in many systems which are interconnected. i need to update the same file in all the systems whereever it is residing. please give me your suggestions how to do this using Perl Scripting.








CodeToad Experts

Can't find the answer?
Our Site experts are answering questions for free in the CodeToad forums








Recent Forum Threads
•  Digital.Canal.Software.V2013
•  Altair_HyperWorks_12.0.1_Win64
•  Global.mapper.V15.0
•  ESI.PAM-RTM.V2010.0
•  KISSsoft.03.2013E.SP5
•  Technical.Toolboxes.Pipeline.Toolbox.2013.Enterprise.v15.0.0
•  Simprotek.Simprosys.V3.0
•  Ricardo.SABR.V6.0p1
•  PSIM.V9.2


Recent Articles
ASP GetTempName
Decode and Encode UTF-8
ASP GetFile
ASP FolderExists
ASP FileExists
ASP OpenTextFile
ASP FilesystemObject
ASP CreateFolder
ASP CreateTextFile
Javascript Get Selected Text


© Copyright codetoad.com 2001-2013