From fb911143fe96b4b8cca93b2aed2697a23a902078 Mon Sep 17 00:00:00 2001 From: Mark Gurevich Date: Thu, 21 Jul 2016 13:27:40 -0400 Subject: [PATCH] perltidy all perl files, part 2 --- perl-xCAT/db2man | 233 +- xCAT-OpenStack-baremetal/xpod2man | 205 +- xCAT-OpenStack/db2man | 297 +- xCAT-OpenStack/sbin/makeclouddata | 27 +- xCAT-SoftLayer/bin/getslnodes | 136 +- xCAT-SoftLayer/bin/khrem | 45 +- xCAT-SoftLayer/bin/modifygrub | 525 +-- xCAT-SoftLayer/bin/pushinitrd | 525 +-- xCAT-SoftLayer/xpod2man | 205 +- xCAT-buildkit/bin/buildkit | 3570 +++++++++-------- xCAT-client/bin/copycds-cdrom | 29 +- xCAT-client/bin/db2sqlsetup | 1575 ++++---- xCAT-client/bin/genimage | 438 +- xCAT-client/bin/mysqlsetup | 473 +-- xCAT-client/bin/pasu | 499 +-- xCAT-client/bin/pgsqlsetup | 695 ++-- xCAT-client/bin/pping | 279 +- xCAT-client/bin/ppping | 280 +- xCAT-client/bin/prsync | 198 +- xCAT-client/bin/pscp | 190 +- xCAT-client/bin/psh | 289 +- xCAT-client/bin/rinstall | 69 +- xCAT-client/bin/updatenode | 127 +- xCAT-client/bin/wcons | 264 +- xCAT-client/bin/wvid | 36 +- xCAT-client/bin/xcatDBcmds | 58 +- xCAT-client/bin/xcatclient | 78 +- xCAT-client/bin/xcatclientnnr | 25 +- xCAT-client/bin/xcoll | 26 +- xCAT-client/bin/xcsv | 30 +- xCAT-client/bin/xdsh | 269 +- xCAT-client/bin/xdshbak | 12 +- xCAT-client/podchecker | 43 +- xCAT-client/sbin/dumpxCATdb | 308 +- xCAT-client/sbin/restorexCATdb | 248 +- xCAT-client/sbin/tabrestore | 48 +- xCAT-client/sbin/xdshcoll | 10 +- xCAT-client/share/xcat/tools/groupfiles4dsh | 8 +- xCAT-client/xpod2man | 211 +- xCAT-confluent/xpod2man | 205 +- xCAT-genesis-builder/findmcprpms | 24 +- xCAT-probe/subcmds/discovery | 34 +- xCAT-probe/subcmds/image | 42 +- xCAT-probe/subcmds/osdeploy | 5 +- xCAT-probe/subcmds/switch-macmap | 27 +- xCAT-probe/subcmds/xcatmn | 2 +- xCAT-probe/xcatprobe | 4 +- xCAT-rmc/scripts/check_ftpd | 5 +- xCAT-rmc/scripts/check_xcatd | 5 +- .../scripts/email-hierarchical-batch-event | 107 +- xCAT-rmc/scripts/email-hierarchical-event | 71 +- xCAT-rmc/scripts/errmsgque | 188 +- xCAT-rmc/scripts/log-hierarchical-batch-event | 114 +- xCAT-rmc/scripts/log-hierarchical-event | 78 +- xCAT-rmc/scripts/logevent_simple | 53 +- xCAT-rmc/scripts/logeventtoteal | 160 +- xCAT-rmc/scripts/logeventtoxcat | 147 +- xCAT-rmc/scripts/mkrmcresources | 1008 ++--- xCAT-rmc/scripts/monaixsyslog | 293 +- xCAT-rmc/scripts/monerrorlog | 573 +-- xCAT-rmc/scripts/msg-hierarchical-batch-event | 105 +- xCAT-rmc/scripts/msg-hierarchical-event | 68 +- xCAT-rmc/scripts/mtime | 114 +- xCAT-rmc/scripts/rmcmetrixmon | 214 +- xCAT-rmc/scripts/updatexcatnodestatus | 286 +- xCAT-server/bin/replaycons | 104 +- xCAT-server/build-readme | 121 +- xCAT-server/sbin/chtab | 166 +- xCAT-server/sbin/configmic | 178 +- xCAT-server/sbin/flashmic | 87 +- xCAT-server/sbin/pcp_collect | 363 +- xCAT-server/sbin/proxydhcp-xcat | 141 +- xCAT-server/sbin/restartxcatd | 79 +- xCAT-server/sbin/rshell_api | 24 +- xCAT-server/sbin/runsqlcmd | 173 +- xCAT-server/sbin/stopstartxcatd | 36 +- xCAT-server/sbin/updateSNimage | 12 +- xCAT-server/sbin/xcat_traphandler | 775 ++-- xCAT-server/sbin/xcatconfig | 1387 +++---- xCAT-server/sbin/xcatd | 1933 ++++----- xCAT-server/sbin/xcatdebug | 110 +- xCAT-server/sbin/xcatnodemon | 56 +- xCAT-server/sbin/xcatsnap | 253 +- xCAT-server/share/xcat/cons/blade | 58 +- xCAT-server/share/xcat/cons/fsp | 206 +- xCAT-server/share/xcat/cons/hmc | 84 +- xCAT-server/share/xcat/cons/hpblade | 60 +- xCAT-server/share/xcat/cons/ipmi | 96 +- xCAT-server/share/xcat/cons/ivm | 91 +- xCAT-server/share/xcat/cons/kvm | 44 +- xCAT-server/share/xcat/cons/multiple | 209 +- xCAT-server/share/xcat/cons/xen | 41 +- xCAT-server/share/xcat/ib/scripts/annotatelog | 634 +-- xCAT-server/share/xcat/ib/scripts/getGuids | 199 +- xCAT-server/share/xcat/ib/scripts/healthCheck | 313 +- .../xcat/netboot/add-on/torque/pbsnodestat | 14 +- .../share/xcat/netboot/debian/genimage | 1406 +++---- .../share/xcat/netboot/fedora12/genimage | 1181 +++--- .../share/xcat/netboot/fedora12/geninitrd | 1328 +++--- xCAT-server/share/xcat/netboot/mic/genimage | 285 +- xCAT-server/share/xcat/netboot/rh/genimage | 1709 ++++---- .../share/xcat/netboot/rh/genimage.rh4 | 1366 +++---- xCAT-server/share/xcat/netboot/sles/genimage | 1910 ++++----- .../share/xcat/netboot/sles/genimage.yum | 900 +++-- xCAT-server/share/xcat/netboot/suse/genimage | 1296 +++--- .../share/xcat/netboot/ubuntu/genimage | 1827 ++++----- xCAT-server/share/xcat/scripts/cfm2xcat | 29 +- xCAT-server/share/xcat/scripts/csm2xcat | 32 +- xCAT-server/share/xcat/scripts/insptbls | 157 +- xCAT-server/share/xcat/scripts/mkay4z | 1433 +++---- xCAT-server/share/xcat/scripts/xcatvio.script | 123 +- xCAT-server/share/xcat/tools/detect_dhcpd | 386 +- xCAT-server/share/xcat/tools/mac2linklocal | 10 +- xCAT-server/share/xcat/tools/mktoolscenter | 555 +-- xCAT-server/share/xcat/tools/nodesw | 869 ++-- .../share/xcat/tools/powervm/configvios | 305 +- .../xcat/tools/powervm/installsshforvios | 3 +- xCAT-server/share/xcat/tools/reorgtbls | 126 +- xCAT-server/share/xcat/tools/rmblade | 112 +- xCAT-server/share/xcat/tools/rmnodecfg | 71 +- xCAT-server/share/xcat/tools/xCATreg | 2140 +++++----- xCAT-server/xCAT-wsapi/xcatrhevh.cgi | 49 +- xCAT-server/xCAT-wsapi/xcatws.cgi | 1332 +++--- .../installation/customize_sleep_for_sn | 30 +- .../testcase/installation/pre_deploy_sn | 19 +- xCAT-test/restapitest | 355 +- xCAT-test/xcattest | 800 ++-- xCAT-test/xmlapi/xmldriver | 14 +- xCAT-test/xmlapi/xmldriver.old | 15 +- xCAT-test/xmlapi/xmldriver.org | 10 +- xCAT-vlan/xpod2man | 205 +- xCAT/postscripts/HPCbootstatus.aix | 95 +- xCAT/postscripts/aixremoteshell | 384 +- xCAT/postscripts/aixswupdate | 42 +- xCAT/postscripts/config_bootnicsea | 44 +- xCAT/postscripts/configeth_aix | 129 +- xCAT/postscripts/configfirewall | 103 +- xCAT/postscripts/confignimsh | 32 +- xCAT/postscripts/db2install | 126 +- xCAT/postscripts/odbcsetup | 32 +- xCAT/postscripts/redirectps | 20 +- xCAT/postscripts/servicenode | 588 +-- xCAT/postscripts/setupnfsv4replication | 14 +- xCAT/postscripts/startsyncfiles.aix | 44 +- xCAT/postscripts/xcataixpost | 870 ++-- xCAT/postscripts/xcataixscript | 75 +- 146 files changed, 25471 insertions(+), 24077 deletions(-) diff --git a/perl-xCAT/db2man b/perl-xCAT/db2man index 233fd2fd3..da35965e9 100755 --- a/perl-xCAT/db2man +++ b/perl-xCAT/db2man @@ -16,12 +16,12 @@ use xCAT::Table; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = "$ENV{'HOME'}/tmp"; if (system("mkdir -p $cachedir")) { die "Error: could not create $cachedir.\n"; } -my $isaix = ($^O =~ /^aix/i); +my $isaix = ($^O =~ /^aix/i); my $skiponaix = 'route|group'; my $poddir5 = 'pods/man5'; @@ -36,51 +36,53 @@ writesummarypage("$poddir5/xcatdb.5.pod", xCAT::Table->getDescriptions(), \%{xCA # Build the pod man page for each object definition my $defspecref = \%{xCAT::Schema::defspec}; foreach my $defkey (keys %$defspecref) { - my $def = $defspecref->{$defkey}; - my $attrs = $def->{'attrs'}; + my $def = $defspecref->{$defkey}; + my $attrs = $def->{'attrs'}; writedefmanpage("$poddir7/$defkey.7.pod", $defkey, $attrs); } # Build the pod man page for each table. my $tabspecref = \%xCAT::Schema::tabspec; foreach my $tablekey (keys %$tabspecref) { - my $table = $tabspecref->{$tablekey}; - my $summary = $table->{table_desc}; - my $colorder = $table->{cols}; + my $table = $tabspecref->{$tablekey}; + my $summary = $table->{table_desc}; + my $colorder = $table->{cols}; my $descriptions = $table->{descriptions}; writepodmanpage("$poddir5/$tablekey.5.pod", $tablekey, $summary, $colorder, $descriptions); } my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the man page for each pod. #mkdir($mandir) or die "Error: could not create $mandir.\n"; print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { - if ($isaix && grep(/\/($skiponaix)\.\d\.pod$/, $podfile)) { print "Skipping $podfile\n"; next; } + if ($isaix && grep(/\/($skiponaix)\.\d\.pod$/, $podfile)) { print "Skipping $podfile\n"; next; } my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -89,62 +91,62 @@ exit; # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man5:man7", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man5:man7", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } # Create the xcatdb man page that gives a summary description of each table. sub writesummarypage { - my $file = shift; # relative path file name of the man page - my $descriptions = shift; # a hash containing the description of each table - my $defdescriptions = shift; # a hash containing the description of each object definition + my $file = shift; # relative path file name of the man page + my $descriptions = shift; # a hash containing the description of each table + my $defdescriptions = shift; # a hash containing the description of each object definition - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME An overview of the xCAT database. @@ -316,11 +318,11 @@ The object types are: =over 2 EOS1 -foreach my $def (sort keys %$defdescriptions) { - print FILE "\n=item L<$def(7)|$def.7>\n"; -} + foreach my $def (sort keys %$defdescriptions) { + print FILE "\n=item L<$def(7)|$def.7>\n"; + } - print FILE <<"EOS2"; + print FILE <<"EOS2"; =back @@ -336,11 +338,11 @@ The tables are: =over 2 EOS2 -foreach my $table (sort keys %$descriptions) { - print FILE "\n=item L<$table(5)|$table.5>\n\n".$descriptions->{$table}."\n"; -} + foreach my $table (sort keys %$descriptions) { + print FILE "\n=item L<$table(5)|$table.5>\n\n" . $descriptions->{$table} . "\n"; + } - print FILE <<"EOS3"; + print FILE <<"EOS3"; =back @@ -349,47 +351,49 @@ foreach my $table (sort keys %$descriptions) { B, B, B, B, B, B, B, B EOS3 - close FILE; + close FILE; } # Create the man page for one object definition. sub writedefmanpage { - my $file = shift; # relative path file name of the man page - my $defname = shift; # name of object - my $attrs = shift; # reference to the array of attributes + my $file = shift; # relative path file name of the man page + my $defname = shift; # name of object + my $attrs = shift; # reference to the array of attributes - # Go thru the attributes, collecting the descriptions - # Note: this logic is loosely taken from DBobjectdefs.pm - my %attrlist; # holds the attr name as the key, and the description & tables as value - foreach my $this_attr (@$attrs) { + # Go thru the attributes, collecting the descriptions + # Note: this logic is loosely taken from DBobjectdefs.pm + my %attrlist; # holds the attr name as the key, and the description & tables as value + foreach my $this_attr (@$attrs) { my $attr = $this_attr->{attr_name}; my $desc = $this_attr->{description}; my ($table, $at) = split(/\./, $this_attr->{tabentry}); if (!defined($desc)) { - # description key not there, so go to the corresponding - # entry in tabspec to get the description + + # description key not there, so go to the corresponding + # entry in tabspec to get the description my $schema = xCAT::Table->getTableSchema($table); $desc = $schema->{descriptions}->{$at}; } - # Attr names can appear more than once, if they are in multiple tables. - # We will keep track of that based on the table attribute, because that can be duplicated too - if (!defined($attrlist{$attr})) { - $attrlist{$attr}->{'tables'} = []; # initialize the array, so we can check it below - } - my $tableattr = "$table.$at"; - if (!grep(/^$tableattr$/, @{$attrlist{$attr}->{'tables'}})) { - # there can be multiple entries that refer to the same table attribute - # if this is a new table attribute, then save the attr name and description - push @{$attrlist{$attr}->{'tables'}}, $tableattr; - push @{$attrlist{$attr}->{'descriptions'}}, $desc; - } - } + # Attr names can appear more than once, if they are in multiple tables. + # We will keep track of that based on the table attribute, because that can be duplicated too + if (!defined($attrlist{$attr})) { + $attrlist{$attr}->{'tables'} = []; # initialize the array, so we can check it below + } + my $tableattr = "$table.$at"; + if (!grep(/^$tableattr$/, @{ $attrlist{$attr}->{'tables'} })) { - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + # there can be multiple entries that refer to the same table attribute + # if this is a new table attribute, then save the attr name and description + push @{ $attrlist{$attr}->{'tables'} }, $tableattr; + push @{ $attrlist{$attr}->{'descriptions'} }, $desc; + } + } - print FILE <<"EOS1"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + + print FILE <<"EOS1"; =head1 NAME B<$defname> - a logical object definition in the xCAT database. @@ -398,9 +402,9 @@ B<$defname> - a logical object definition in the xCAT database. EOS1 - print FILE "B<$defname Attributes:> I<" . join('>, I<',sort(keys(%attrlist))) . ">\n"; + print FILE "B<$defname Attributes:> I<" . join('>, I<', sort(keys(%attrlist))) . ">\n"; - print FILE <<"EOS2"; + print FILE <<"EOS2"; =head1 DESCRIPTION @@ -415,15 +419,17 @@ parentheses, what tables each attribute is stored in. EOS2 -foreach my $a (sort keys %attrlist) { - my $d = join("\n\nor\n\n", @{$attrlist{$a}->{'descriptions'}}); - #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them - my $t = '(' . join(', ',@{$attrlist{$a}->{'tables'}}) . ')'; - #print FILE "\nB<$a> - $d\n"; - print FILE "\n=item B<$a> $t\n\n$d\n"; -} + foreach my $a (sort keys %attrlist) { + my $d = join("\n\nor\n\n", @{ $attrlist{$a}->{'descriptions'} }); - print FILE <<"EOS3"; + #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them + my $t = '(' . join(', ', @{ $attrlist{$a}->{'tables'} }) . ')'; + + #print FILE "\nB<$a> - $d\n"; + print FILE "\n=item B<$a> $t\n\n$d\n"; + } + + print FILE <<"EOS3"; =back @@ -432,21 +438,21 @@ foreach my $a (sort keys %attrlist) { B, B, B, B EOS3 - close FILE; + close FILE; } # Create the man page for one table. sub writepodmanpage { - my $file = shift; # relative path file name of the man page - my $tablename = shift; # name of table - my $summary = shift; # description of table - my $colorder = shift; # the order in which the table attributes should be presented in - my $descriptions = shift; # a hash containing the description of each attribute + my $file = shift; # relative path file name of the man page + my $tablename = shift; # name of table + my $summary = shift; # description of table + my $colorder = shift; # the order in which the table attributes should be presented in + my $descriptions = shift; # a hash containing the description of each attribute - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<"EOS1"; + print FILE <<"EOS1"; =head1 NAME B<$tablename> - a table in the xCAT database. @@ -455,9 +461,9 @@ B<$tablename> - a table in the xCAT database. EOS1 - print FILE "B<$tablename Attributes:> I<" . join('>, I<',@$colorder) . ">\n"; + print FILE "B<$tablename Attributes:> I<" . join('>, I<', @$colorder) . ">\n"; - print FILE <<"EOS2"; + print FILE <<"EOS2"; =head1 DESCRIPTION @@ -469,14 +475,15 @@ $summary EOS2 -foreach my $a (@$colorder) { - my $d = $descriptions->{$a}; - #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them - #print FILE "\nB<$a> - $d\n"; - print FILE "\n=item B<$a>\n\n$d\n"; -} + foreach my $a (@$colorder) { + my $d = $descriptions->{$a}; - print FILE <<"EOS3"; + #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them + #print FILE "\nB<$a> - $d\n"; + print FILE "\n=item B<$a>\n\n$d\n"; + } + + print FILE <<"EOS3"; =back @@ -485,5 +492,5 @@ foreach my $a (@$colorder) { B, B, B, B EOS3 - close FILE; + close FILE; } diff --git a/xCAT-OpenStack-baremetal/xpod2man b/xCAT-OpenStack-baremetal/xpod2man index bb7d7aa39..5a2b973f0 100755 --- a/xCAT-OpenStack-baremetal/xpod2man +++ b/xCAT-OpenStack-baremetal/xpod2man @@ -8,16 +8,18 @@ # done relative to that. use strict; + #use lib '.'; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = '/tmp'; my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the cmd overview page. @@ -28,12 +30,12 @@ my @pods = getPodList($poddir); print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } @@ -42,15 +44,17 @@ my @dummyPods = createDummyPods($poddir, \@pods); # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + #print "$podfile, $htmlfile, $poddir, $htmldir\n"; convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -67,73 +71,78 @@ exit; # if that pod does not exist, create an empty one that will satisfy pod2html # keep track of all dummy pods created, so they can be removed later sub createDummyPods { - my ($poddir, $pods) = @_; - my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; - #print "Running cmd: ", $cmd, "\n"; - my @lines = `$cmd`; - if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } - #my @lines; - #system($cmd); - my @dummyPods; - foreach my $l (@lines) { - #print "$l\n"; - my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line - # The above line should create the array with every other entry being the man page name - # and every other entry is the section # (5 or 7) - my $cmd; - while ($cmd=shift @matches) { - #foreach my $m (@matches) { - my $section = shift @matches; - my $filename = "$poddir/man$section/$cmd.$section.pod"; - #print "$filename\n"; - if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } - } - } - - - # Create these empty files - print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; - mkdir "$poddir/man7"; - foreach my $d (@dummyPods) { - if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } - else { close TMP; } - } - - return @dummyPods; + my ($poddir, $pods) = @_; + my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; + + #print "Running cmd: ", $cmd, "\n"; + my @lines = `$cmd`; + if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } + + #my @lines; + #system($cmd); + my @dummyPods; + foreach my $l (@lines) { + + #print "$l\n"; + my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line + # The above line should create the array with every other entry being the man page name + # and every other entry is the section # (5 or 7) + my $cmd; + while ($cmd = shift @matches) { + + #foreach my $m (@matches) { + my $section = shift @matches; + my $filename = "$poddir/man$section/$cmd.$section.pod"; + + #print "$filename\n"; + if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } + } + } + + + # Create these empty files + print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; + mkdir "$poddir/man7"; + foreach my $d (@dummyPods) { + if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } + else { close TMP; } + } + + return @dummyPods; } # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the xcat man page that gives a summary description of each xcat cmd. # Not used sub writesummarypage { - my $file = shift; # relative path file name of the man page - # the rest of @_ contains the pod files that describe each cmd + my $file = shift; # relative path file name of the man page + # the rest of @_ contains the pod files that describe each cmd - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME B - extreme Cluster Administration Tool. @@ -159,56 +168,58 @@ i.e. all the commands in section 1, then the commands in section 3, etc. =over 12 EOS1 -# extract the summary for each cmd from its man page -foreach my $manpage (@_) { - my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; - # Suck in the whole file, then we will parse it. - open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; - my @contents = ; - my $wholemanpage = join('', @contents); - close(MANPAGE); - # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline - my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; - if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } - if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } - $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off - $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off - print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n".$description."\n"; -} + # extract the summary for each cmd from its man page + foreach my $manpage (@_) { + my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; -# Artificially add the xcattest cmd, because the xCAT-test rpm will add this -print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + # Suck in the whole file, then we will parse it. + open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; + my @contents = ; + my $wholemanpage = join('', @contents); + close(MANPAGE); - print FILE <<"EOS3"; + # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline + my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; + if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } + if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } + $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off + $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off + print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n" . $description . "\n"; + } + + # Artificially add the xcattest cmd, because the xCAT-test rpm will add this + print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + + print FILE <<"EOS3"; =back EOS3 - close FILE; + close FILE; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man1", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man1", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } diff --git a/xCAT-OpenStack/db2man b/xCAT-OpenStack/db2man index 7b7ee5057..45512ff23 100755 --- a/xCAT-OpenStack/db2man +++ b/xCAT-OpenStack/db2man @@ -18,14 +18,15 @@ use strict; use lib 'lib/perl'; use xCAT_schema::Clouds; + #use xCAT::Table; use Pod::Man; use Pod::Html; -my $VERBOSE = 1; # set this to 1 for debugging -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $VERBOSE = 1; # set this to 1 for debugging +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = '/tmp'; my $poddir5 = 'pods/man5'; @@ -40,21 +41,21 @@ writesummarypage("$poddir5/xcat-openstack-db.5.pod", getTableDescriptions(), get # Build the pod man page for each object definition my $defspecref = getDefRef(); foreach my $defkey (keys %$defspecref) { - my $def = $defspecref->{$defkey}; - my $attrs = $def->{'attrs'}; - my $podfile = "$poddir7/$defkey.7.pod"; - verbose("Writing pod file for $defkey"); + my $def = $defspecref->{$defkey}; + my $attrs = $def->{'attrs'}; + my $podfile = "$poddir7/$defkey.7.pod"; + verbose("Writing pod file for $defkey"); writedefmanpage($podfile, $defkey, $attrs); } # Build the pod man page for each table. my $tabspecref = getTableRef(); foreach my $tablekey (keys %$tabspecref) { - my $table = $tabspecref->{$tablekey}; - my $summary = $table->{table_desc}; - my $colorder = $table->{cols}; + my $table = $tabspecref->{$tablekey}; + my $summary = $table->{table_desc}; + my $colorder = $table->{cols}; my $descriptions = $table->{descriptions}; - verbose("Writing pod file for $tablekey"); + verbose("Writing pod file for $tablekey"); writepodmanpage("$poddir5/$tablekey.5.pod", $tablekey, $summary, $colorder, $descriptions); } @@ -65,13 +66,13 @@ verbose('Pod list:' . "@pods"); print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; - verbose("Converting $podfile to $manfile"); + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; + verbose("Converting $podfile to $manfile"); convertpod2man($podfile, $manfile, $section); } @@ -79,16 +80,17 @@ my @dummyPods = createDummyPods($poddir); # Build the html page for each pod. print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } - verbose("Converting $podfile to $htmlfile"); + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + verbose("Converting $podfile to $htmlfile"); convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -107,76 +109,78 @@ sub getTableRef { return \%xCAT_schema::Clouds::tabspec; } sub getTableList { return keys %xCAT_schema::Clouds::tabspec; } # Returns a reference to the db schema hash for the specified table. -sub getTableSchema { return $xCAT_schema::Clouds::tabspec{$_[0]}; } +sub getTableSchema { return $xCAT_schema::Clouds::tabspec{ $_[0] }; } # Return a reference to a hash where each key is the table name and each value is the table description. sub getTableDescriptions { - # List each table name and the value for table_desc. - my $ret = {}; - #my @a = keys %{$xCAT_schema::Clouds::tabspec{nodelist}}; print 'a=', @a, "\n"; - foreach my $t (getTableList()) { $ret->{$t} = getTableSchema($t)->{table_desc}; } - return $ret; + + # List each table name and the value for table_desc. + my $ret = {}; + + #my @a = keys %{$xCAT_schema::Clouds::tabspec{nodelist}}; print 'a=', @a, "\n"; + foreach my $t (getTableList()) { $ret->{$t} = getTableSchema($t)->{table_desc}; } + return $ret; } # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man5:man7", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man5:man7", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } # Create the xcat-openstack-db man page that gives a summary description of each table. sub writesummarypage { - my $file = shift; # relative path file name of the man page - my $descriptions = shift; # a hash containing the description of each table - my $defdescriptions = shift; # a hash containing the description of each object definition + my $file = shift; # relative path file name of the man page + my $descriptions = shift; # a hash containing the description of each table + my $defdescriptions = shift; # a hash containing the description of each object definition - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME An overview of the xCAT OpenStack database objects and tables. @@ -205,12 +209,12 @@ The object types are: =over 2 EOS1 -foreach my $def (sort keys %$defdescriptions) { - if ($def eq 'node') { print FILE "\n=item L<$def(7)|node-openstack.7>\n"; } # can not overwrite the node man page in xcat-core - else { print FILE "\n=item L<$def(7)|$def.7>\n"; } -} + foreach my $def (sort keys %$defdescriptions) { + if ($def eq 'node') { print FILE "\n=item L<$def(7)|node-openstack.7>\n"; } # can not overwrite the node man page in xcat-core + else { print FILE "\n=item L<$def(7)|$def.7>\n"; } + } - print FILE <<"EOS2"; + print FILE <<"EOS2"; =back @@ -226,11 +230,11 @@ The tables are: =over 2 EOS2 -foreach my $table (sort keys %$descriptions) { - print FILE "\n=item L<$table(5)|$table.5>\n\n".$descriptions->{$table}."\n"; -} + foreach my $table (sort keys %$descriptions) { + print FILE "\n=item L<$table(5)|$table.5>\n\n" . $descriptions->{$table} . "\n"; + } - print FILE <<"EOS3"; + print FILE <<"EOS3"; =back @@ -239,50 +243,52 @@ foreach my $table (sort keys %$descriptions) { B, B, B, B, B, B, B, B EOS3 - close FILE; + close FILE; } # Create the man page for one object definition. sub writedefmanpage { - my $file = shift; # relative path file name of the man page - my $defname = shift; # name of object - my $attrs = shift; # reference to the array of attributes + my $file = shift; # relative path file name of the man page + my $defname = shift; # name of object + my $attrs = shift; # reference to the array of attributes - # Make exception for the node object, because we can not overwrite the node man page from xcat-core - if ($defname eq 'node') { $file = "$poddir7/node-openstack.7.pod"; } + # Make exception for the node object, because we can not overwrite the node man page from xcat-core + if ($defname eq 'node') { $file = "$poddir7/node-openstack.7.pod"; } - # Go thru the attributes, collecting the descriptions - # Note: this logic is loosely taken from DBobjectdefs.pm - my %attrlist; # holds the attr name as the key, and the description & tables as value - foreach my $this_attr (@$attrs) { + # Go thru the attributes, collecting the descriptions + # Note: this logic is loosely taken from DBobjectdefs.pm + my %attrlist; # holds the attr name as the key, and the description & tables as value + foreach my $this_attr (@$attrs) { my $attr = $this_attr->{attr_name}; my $desc = $this_attr->{description}; my ($table, $at) = split(/\./, $this_attr->{tabentry}); if (!defined($desc)) { - # description key not there, so go to the corresponding - # entry in tabspec to get the description + + # description key not there, so go to the corresponding + # entry in tabspec to get the description my $schema = getTableSchema($table); $desc = $schema->{descriptions}->{$at}; } - # Attr names can appear more than once, if they are in multiple tables. - # We will keep track of that based on the table attribute, because that can be duplicated too - if (!defined($attrlist{$attr})) { - $attrlist{$attr}->{'tables'} = []; # initialize the array, so we can check it below - } - my $tableattr = "$table.$at"; - if (!grep(/^$tableattr$/, @{$attrlist{$attr}->{'tables'}})) { - # there can be multiple entries that refer to the same table attribute - # if this is a new table attribute, then save the attr name and description - push @{$attrlist{$attr}->{'tables'}}, $tableattr; - push @{$attrlist{$attr}->{'descriptions'}}, $desc; - } - } + # Attr names can appear more than once, if they are in multiple tables. + # We will keep track of that based on the table attribute, because that can be duplicated too + if (!defined($attrlist{$attr})) { + $attrlist{$attr}->{'tables'} = []; # initialize the array, so we can check it below + } + my $tableattr = "$table.$at"; + if (!grep(/^$tableattr$/, @{ $attrlist{$attr}->{'tables'} })) { - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + # there can be multiple entries that refer to the same table attribute + # if this is a new table attribute, then save the attr name and description + push @{ $attrlist{$attr}->{'tables'} }, $tableattr; + push @{ $attrlist{$attr}->{'descriptions'} }, $desc; + } + } - print FILE <<"EOS1"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + + print FILE <<"EOS1"; =head1 NAME B<$defname> - a logical object definition in the xCAT database. @@ -291,9 +297,9 @@ B<$defname> - a logical object definition in the xCAT database. EOS1 - print FILE "B<$defname Attributes:> I<" . join('>, I<',sort(keys(%attrlist))) . ">\n"; + print FILE "B<$defname Attributes:> I<" . join('>, I<', sort(keys(%attrlist))) . ">\n"; - print FILE <<"EOS2"; + print FILE <<"EOS2"; =head1 DESCRIPTION @@ -308,45 +314,46 @@ parentheses, what tables each attribute is stored in. EOS2 -foreach my $a (sort keys %attrlist) { - my $d = join("\nor\n", @{$attrlist{$a}->{'descriptions'}}); - $d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them - my $t = '(' . join(', ',@{$attrlist{$a}->{'tables'}}) . ')'; - #print FILE "\nB<$a> - $d\n"; - print FILE "\n=item B<$a> $t\n\n$d\n"; -} + foreach my $a (sort keys %attrlist) { + my $d = join("\nor\n", @{ $attrlist{$a}->{'descriptions'} }); + $d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them + my $t = '(' . join(', ', @{ $attrlist{$a}->{'tables'} }) . ')'; - print FILE <<"EOS3"; + #print FILE "\nB<$a> - $d\n"; + print FILE "\n=item B<$a> $t\n\n$d\n"; + } + + print FILE <<"EOS3"; =back EOS3 -if ($defname eq 'node') { - print FILE "B man page.>\n\n"; -} + if ($defname eq 'node') { + print FILE "B man page.>\n\n"; + } - print FILE <<"EOS4"; + print FILE <<"EOS4"; =head1 SEE ALSO B, B, B, B EOS4 - close FILE; + close FILE; } # Create the man page for one table. sub writepodmanpage { - my $file = shift; # relative path file name of the man page - my $tablename = shift; # name of table - my $summary = shift; # description of table - my $colorder = shift; # the order in which the table attributes should be presented in - my $descriptions = shift; # a hash containing the description of each attribute + my $file = shift; # relative path file name of the man page + my $tablename = shift; # name of table + my $summary = shift; # description of table + my $colorder = shift; # the order in which the table attributes should be presented in + my $descriptions = shift; # a hash containing the description of each attribute - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<"EOS1"; + print FILE <<"EOS1"; =head1 NAME B<$tablename> - a table in the xCAT database. @@ -355,9 +362,9 @@ B<$tablename> - a table in the xCAT database. EOS1 - print FILE "B<$tablename Attributes:> I<" . join('>, I<',@$colorder) . ">\n"; + print FILE "B<$tablename Attributes:> I<" . join('>, I<', @$colorder) . ">\n"; - print FILE <<"EOS2"; + print FILE <<"EOS2"; =head1 DESCRIPTION @@ -369,14 +376,15 @@ $summary EOS2 -foreach my $a (@$colorder) { - my $d = $descriptions->{$a}; - #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them - #print FILE "\nB<$a> - $d\n"; - print FILE "\n=item B<$a>\n\n$d\n"; -} + foreach my $a (@$colorder) { + my $d = $descriptions->{$a}; - print FILE <<"EOS3"; + #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them + #print FILE "\nB<$a> - $d\n"; + print FILE "\n=item B<$a>\n\n$d\n"; + } + + print FILE <<"EOS3"; =back @@ -385,7 +393,7 @@ foreach my $a (@$colorder) { B, B, B, B EOS3 - close FILE; + close FILE; } @@ -393,19 +401,20 @@ EOS3 # we need to create an empty one that will satisfy pod2html. # Returns all dummy pods created, so they can be removed later sub createDummyPods { - my $poddir = shift @_; + my $poddir = shift @_; - # Also add xcattest.1.pod and buildkit.1.pod, because the xcat.1.pod summary page refers to it - push @dummyPods, "$poddir/man7/node.7.pod"; - push @dummyPods, "$poddir/man5/xcatdb.5.pod"; - - # Create these empty files - print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; - #mkdir "$poddir/man7"; - foreach my $d (@dummyPods) { - if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } - else { close TMP; } - } - - return @dummyPods; + # Also add xcattest.1.pod and buildkit.1.pod, because the xcat.1.pod summary page refers to it + push @dummyPods, "$poddir/man7/node.7.pod"; + push @dummyPods, "$poddir/man5/xcatdb.5.pod"; + + # Create these empty files + print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; + + #mkdir "$poddir/man7"; + foreach my $d (@dummyPods) { + if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } + else { close TMP; } + } + + return @dummyPods; } diff --git a/xCAT-OpenStack/sbin/makeclouddata b/xCAT-OpenStack/sbin/makeclouddata index 583d7c549..77ba1ace5 100755 --- a/xCAT-OpenStack/sbin/makeclouddata +++ b/xCAT-OpenStack/sbin/makeclouddata @@ -4,7 +4,7 @@ # Used as a standard client cmd that can be used for xcat cmds that do not have # noderange as an argument. See xcatclient for additional documentation. -# To put the cloud command only in xCAT-OpenStack, just copy the ../bin/xcatclientnnr +# To put the cloud command only in xCAT-OpenStack, just copy the ../bin/xcatclientnnr # as makeclouddata command here. we couldn't sym link the command makecloudata # to this script ../bin/xcatclientnnr in xCAT-OpenStack.spec. @@ -17,40 +17,41 @@ use strict; my $bname = basename($0); my $cmdref; -if ($bname =~ /xcatclientnnr/) { $cmdref->{command}->[0]=shift @ARGV; } # xcatclientnnr was invoked directly and the 1st arg is cmd name that is used to locate the plugin -else { $cmdref->{command}->[0] = $bname; } # the cmd was sym linked to xcatclientnnr +if ($bname =~ /xcatclientnnr/) { $cmdref->{command}->[0] = shift @ARGV; } # xcatclientnnr was invoked directly and the 1st arg is cmd name that is used to locate the plugin +else { $cmdref->{command}->[0] = $bname; } # the cmd was sym linked to xcatclientnnr $cmdref->{cwd}->[0] = cwd(); my $data; + # allows our plugins to get the stdin of the cmd that invoked the plugin -if ( (($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}) ) +if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'})) { my $rout; - my $rin=""; - vec($rin,fileno(STDIN),1)=1; - my $nfound=select($rout=$rin,"","",1); + my $rin = ""; + vec($rin, fileno(STDIN), 1) = 1; + my $nfound = select($rout = $rin, "", "", 1); if ($nfound) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } else { if (-p STDIN) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } -push (@{$cmdref->{arg}}, @ARGV); +push(@{ $cmdref->{arg} }, @ARGV); foreach (keys %ENV) { if (/^XCAT_/) { $cmdref->{environment}->{$_} = $ENV{$_}; } } -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-SoftLayer/bin/getslnodes b/xCAT-SoftLayer/bin/getslnodes index 5903054eb..2486a9743 100755 --- a/xCAT-SoftLayer/bin/getslnodes +++ b/xCAT-SoftLayer/bin/getslnodes @@ -7,37 +7,39 @@ use strict; use Getopt::Long; use Data::Dumper; + #$Data::Dumper::Maxdepth=2; # Globals - these are set once and then only read. my $HELP; my $VERBOSE; -my %CONFIG; # attributes read from config file +my %CONFIG; # attributes read from config file my $usage = sub { - my $exitcode = shift @_; - print "Usage: getslnodes [-?|-h|--help] [-v|--verbose] []\n\n"; - if (!$exitcode) { - print "getslnodes queries your SoftLayer account and gets attributes for each\n"; - print "server. The attributes can be piped to 'mkdef -z' to define the nodes\n"; - print "in the xCAT DB so that xCAT can manage them. getslnodes\n"; - print "requires a .slconfig file in your home directory that contains your\n"; - print "SoftLayer userid, API key, and location of API perl module, in attr=val format.\n"; - } - exit $exitcode; + my $exitcode = shift @_; + print "Usage: getslnodes [-?|-h|--help] [-v|--verbose] []\n\n"; + if (!$exitcode) { + print "getslnodes queries your SoftLayer account and gets attributes for each\n"; + print "server. The attributes can be piped to 'mkdef -z' to define the nodes\n"; + print "in the xCAT DB so that xCAT can manage them. getslnodes\n"; + print "requires a .slconfig file in your home directory that contains your\n"; + print "SoftLayer userid, API key, and location of API perl module, in attr=val format.\n"; + } + exit $exitcode; }; # Process the cmd line args Getopt::Long::Configure("bundling"); + #Getopt::Long::Configure("pass_through"); Getopt::Long::Configure("no_pass_through"); -if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE)) { $usage->(1); } +if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE)) { $usage->(1); } -if ($HELP) { $usage->(0); } -if (scalar(@ARGV)>1) { $usage->(1); } -my $hnmatch = $ARGV[0]; # if they specified a hostname match, only show svrs that start with that +if ($HELP) { $usage->(0); } +if (scalar(@ARGV) > 1) { $usage->(1); } +my $hnmatch = $ARGV[0]; # if they specified a hostname match, only show svrs that start with that -readconf("$ENV{HOME}/.slconfig"); # get the userid and api key from the config file +readconf("$ENV{HOME}/.slconfig"); # get the userid and api key from the config file my $slinstalled = eval { push @INC, $CONFIG{apidir}; require SoftLayer::API::SOAP; }; if (!$slinstalled) { die "$@\nError: either the SoftLayer::API::SOAP perl module is not installed, or some dependencies are missing. Download it using 'git clone https://github.com/softlayer/softlayer-api-perl-client', put the directory in ~/.slconfig , and ensure its dependencies are installed."; } @@ -50,43 +52,47 @@ $client->setObjectMask($mask); #print $client->fault; #print $client->faultstring; #print "\n"; - -my $hw = $client->getHardware(); + +my $hw = $client->getHardware(); my $servers = $hw->result; foreach my $server (@$servers) { - if ($server->{fullyQualifiedDomainName} =~ m/$hnmatch/) { - print "\n".$server->{hostname}.":\n"; - print "\tobjtype=node\n"; - print "\tgroups=slnode,ipmi,all\n"; - print "\tmgt=ipmi\n"; - print "\tbmc=".$server->{remoteManagementComponent}->{ipmiIpAddress}."\n"; - print "\tbmcusername=".$server->{remoteManagementAccounts}->[0]->{username}."\n"; - print "\tbmcpassword=".$server->{remoteManagementAccounts}->[0]->{password}."\n"; + if ($server->{fullyQualifiedDomainName} =~ m/$hnmatch/) { + print "\n" . $server->{hostname} . ":\n"; + print "\tobjtype=node\n"; + print "\tgroups=slnode,ipmi,all\n"; + print "\tmgt=ipmi\n"; + print "\tbmc=" . $server->{remoteManagementComponent}->{ipmiIpAddress} . "\n"; + print "\tbmcusername=" . $server->{remoteManagementAccounts}->[0]->{username} . "\n"; + print "\tbmcpassword=" . $server->{remoteManagementAccounts}->[0]->{password} . "\n"; - # find the 1st active private nic that is not the bmc - foreach my $nic (@{$server->{backendNetworkComponents}}) { - #print "nic:\n"; foreach my $key (keys(%$nic)) { print " $key = ", $nic->{$key}, "\n"; } - if ($nic->{status} eq 'ACTIVE' && $nic->{name} eq 'eth' && $nic->{macAddress} && $nic->{primaryIpAddress}) { - # found it - print "\tmac=".$nic->{macAddress}."\n"; - print "\tip=".$nic->{primaryIpAddress}."\n"; - } - } - #print "\tip=".$server->{privateIpAddress}."\n"; # getting this from the backendNetworkComponents instead - print "\tserial=".$server->{manufacturerSerialNumber}."\n"; - print "\tnetboot=xnba\n"; - print "\tarch=x86_64\n"; - print "\tusercomment=hostname:".$server->{fullyQualifiedDomainName}.", user:".$server->{operatingSystem}->{passwords}->[0]->{username}.", pw:".$server->{operatingSystem}->{passwords}->[0]->{password}."\n"; + # find the 1st active private nic that is not the bmc + foreach my $nic (@{ $server->{backendNetworkComponents} }) { - verbose('SoftLayer API bare metal server entry: ' . Dumper($server)); - #print Dumper($server->{remoteManagementAccounts}); - #print "#Softlayer_account_info_for ".$server->{fullyQualifiedDomainName} . " Username: "; - #print $server->{operatingSystem}->{passwords}->[0]->{username} . " Password: "; - #print $server->{operatingSystem}->{passwords}->[0]->{password}. "\n"; - #print "nodeadd ".$server->{hostname}." groups=saptest ipmi.password=".$server->{remoteManagementAccounts}->[0]->{password}." ipmi.bmc=".$server->{remoteManagementComponent}->{ipmiIpAddress}; - #print " mac.mac=".$server->{backendNetworkComponents}->[0]->{macAddress}; - #print " hosts.ip=".$server->{privateIpAddress} ."\n"; - } + #print "nic:\n"; foreach my $key (keys(%$nic)) { print " $key = ", $nic->{$key}, "\n"; } + if ($nic->{status} eq 'ACTIVE' && $nic->{name} eq 'eth' && $nic->{macAddress} && $nic->{primaryIpAddress}) { + + # found it + print "\tmac=" . $nic->{macAddress} . "\n"; + print "\tip=" . $nic->{primaryIpAddress} . "\n"; + } + } + + #print "\tip=".$server->{privateIpAddress}."\n"; # getting this from the backendNetworkComponents instead + print "\tserial=" . $server->{manufacturerSerialNumber} . "\n"; + print "\tnetboot=xnba\n"; + print "\tarch=x86_64\n"; + print "\tusercomment=hostname:" . $server->{fullyQualifiedDomainName} . ", user:" . $server->{operatingSystem}->{passwords}->[0]->{username} . ", pw:" . $server->{operatingSystem}->{passwords}->[0]->{password} . "\n"; + + verbose('SoftLayer API bare metal server entry: ' . Dumper($server)); + + #print Dumper($server->{remoteManagementAccounts}); + #print "#Softlayer_account_info_for ".$server->{fullyQualifiedDomainName} . " Username: "; + #print $server->{operatingSystem}->{passwords}->[0]->{username} . " Password: "; + #print $server->{operatingSystem}->{passwords}->[0]->{password}. "\n"; + #print "nodeadd ".$server->{hostname}." groups=saptest ipmi.password=".$server->{remoteManagementAccounts}->[0]->{password}." ipmi.bmc=".$server->{remoteManagementComponent}->{ipmiIpAddress}; + #print " mac.mac=".$server->{backendNetworkComponents}->[0]->{macAddress}; + #print " hosts.ip=".$server->{privateIpAddress} ."\n"; + } } exit(0); @@ -98,23 +104,23 @@ sub verbose { if ($VERBOSE) { print shift, "\n"; } } # Read the config file. Format is attr=val on each line. Should contain at leas the userid and apikey. # This function fills in the global %CONFIG hash. sub readconf { - my $conffile = shift @_; - open(FILE, $conffile) || die "Error: can not open config file $conffile: $!\n"; - while () { - my $line = $_; - chomp($line); - if ($line =~ /^#/ || $line =~/^\s*$/) { next; } # skip comment lines - my ($key, $value) = split(/\s*=\s*/, $line, 2); - if (!defined($value)) { die "Error: line '$line' does not have format attribute=value\n"; } - $CONFIG{$key} = $value; - } - close FILE; - verbose('%CONFIG hash: ' . Dumper(\%CONFIG)); + my $conffile = shift @_; + open(FILE, $conffile) || die "Error: can not open config file $conffile: $!\n"; + while () { + my $line = $_; + chomp($line); + if ($line =~ /^#/ || $line =~ /^\s*$/) { next; } # skip comment lines + my ($key, $value) = split(/\s*=\s*/, $line, 2); + if (!defined($value)) { die "Error: line '$line' does not have format attribute=value\n"; } + $CONFIG{$key} = $value; + } + close FILE; + verbose('%CONFIG hash: ' . Dumper(\%CONFIG)); - # the config file needs to contain at least the userid and api key - if (!defined($CONFIG{userid}) || !defined($CONFIG{apikey}) || !defined($CONFIG{apidir})) { - die "Error: the config file must contain values for userid, apikey, and apidir.\n"; - } + # the config file needs to contain at least the userid and api key + if (!defined($CONFIG{userid}) || !defined($CONFIG{apikey}) || !defined($CONFIG{apidir})) { + die "Error: the config file must contain values for userid, apikey, and apidir.\n"; + } } #$mask = "mask[operatingSystem.passwords]"; diff --git a/xCAT-SoftLayer/bin/khrem b/xCAT-SoftLayer/bin/khrem index ac212c484..682edcc5e 100755 --- a/xCAT-SoftLayer/bin/khrem +++ b/xCAT-SoftLayer/bin/khrem @@ -5,6 +5,7 @@ use strict; use Getopt::Long; use Data::Dumper; + #$Data::Dumper::Maxdepth=2; # Globals - these are set once and then only read. @@ -13,37 +14,41 @@ my $VERBOSE; my $file = '~/.ssh/known_hosts'; my $usage = sub { - my $exitcode = shift @_; - print "Usage: khrem \n"; + my $exitcode = shift @_; + print "Usage: khrem \n"; print " Removes the entries in the .ssh/known_hosts file associated with this node.\n"; - exit $exitcode; + exit $exitcode; }; # Process the cmd line args Getopt::Long::Configure("bundling"); + #Getopt::Long::Configure("pass_through"); Getopt::Long::Configure("no_pass_through"); -if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE)) { $usage->(1); } +if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE)) { $usage->(1); } if ($HELP) { $usage->(0); } -if (scalar(@ARGV)!=1) { $usage->(1); } -my $node = $ARGV[0]; # if they specified a hostname match, only show svrs that start with that +if (scalar(@ARGV) != 1) { $usage->(1); } +my $node = $ARGV[0]; # if they specified a hostname match, only show svrs that start with that my @output = runcmd("host $node"); my $hostname; my $line = shift @output; + #print "line=$line\n"; if ($line =~ m/is an alias for /) { ($hostname) = $line =~ m/is an alias for ([^\.]+)/; + #print "hostname=$hostname\n"; $line = shift @output; - } +} + #print "line=$line\n"; my ($ip) = $line =~ m/has address (.+)$/; if (defined($hostname)) { print "Removing entries from $file for: $node, $hostname, $ip\n"; runcmd("sed -i '/^$node/d;/^$hostname/d;/^$ip/d' $file"); - } +} else { print "Removing entries from $file for: $node, $ip\n"; runcmd("sed -i '/^$node/d;/^$ip/d' $file"); @@ -66,23 +71,23 @@ sub runcmd my ($cmd) = @_; my $rc; - $cmd .= ' 2>&1' ; + $cmd .= ' 2>&1'; verbose($cmd); - my @output; - if (wantarray) { - @output = `$cmd`; - $rc = $?; - } - else { - system($cmd); - $rc = $?; - } + my @output; + if (wantarray) { + @output = `$cmd`; + $rc = $?; + } + else { + system($cmd); + $rc = $?; + } if ($rc) { $rc = $rc >> 8; - if ($rc > 0) { die "Error: rc $rc return from cmd: $cmd\n"; } - else { die "Error: system error returned from cmd: $cmd\n"; } + if ($rc > 0) { die "Error: rc $rc return from cmd: $cmd\n"; } + else { die "Error: system error returned from cmd: $cmd\n"; } } elsif (wantarray) { return @output; } } diff --git a/xCAT-SoftLayer/bin/modifygrub b/xCAT-SoftLayer/bin/modifygrub index 6e8645bfb..ebfa29dc2 100755 --- a/xCAT-SoftLayer/bin/modifygrub +++ b/xCAT-SoftLayer/bin/modifygrub @@ -18,226 +18,235 @@ my $PROVMETHOD; my $XCATNETBOOTTITLE = 'xCAT network boot kernel and initrd'; my $usage = sub { - my $exitcode = shift @_; - print "Usage: modifygrub [-?|-h|--help] [-v|--verbose] [--dryrun] [-w ] [-p \n\n"; - if (!$exitcode) { - print "Modify the grub config file on the node to boot the specified kernel and initrd.\n"; - } - exit $exitcode; + my $exitcode = shift @_; + print "Usage: modifygrub [-?|-h|--help] [-v|--verbose] [--dryrun] [-w ] [-p \n\n"; + if (!$exitcode) { + print "Modify the grub config file on the node to boot the specified kernel and initrd.\n"; + } + exit $exitcode; }; my $file = '/etc/os-release'; -if (-f $file) { - # - # SLES and RHEL also have /etc/os-release file, so actually need to open the file - # and look for Ubuntu in the 'NAME=' lines before declaring Ubuntu - # - open my $info, $file or die "Could not open $file: $!"; - while( my $line = <$info>) { - if (index($line, 'NAME=') != -1) { - if ($line =~ /Ubuntu/i) { - die "This script does not support Ubuntu at this time.\n"; - } - } - } - close $info; +if (-f $file) { + # + # SLES and RHEL also have /etc/os-release file, so actually need to open the file + # and look for Ubuntu in the 'NAME=' lines before declaring Ubuntu + # + open my $info, $file or die "Could not open $file: $!"; + while (my $line = <$info>) { + if (index($line, 'NAME=') != -1) { + if ($line =~ /Ubuntu/i) { + die "This script does not support Ubuntu at this time.\n"; + } + } + } + close $info; } # Process the cmd line args Getopt::Long::Configure("bundling"); + #Getopt::Long::Configure("pass_through"); Getopt::Long::Configure("no_pass_through"); -if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE, 'dryrun' => \$DRYRUN, 'w|waittime=s' => \$WAITTIME, 'p|provmethod=s' => \$PROVMETHOD)) { $usage->(1); } +if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE, 'dryrun' => \$DRYRUN, 'w|waittime=s' => \$WAITTIME, 'p|provmethod=s' => \$PROVMETHOD)) { $usage->(1); } if ($HELP) { $usage->(0); } if (scalar(@ARGV) != 4) { $usage->(1); } -if (!defined($WAITTIME)) { $WAITTIME = 60; } # seconds to wait after configuring the nic (to let the switch handle the state change) +if (!defined($WAITTIME)) { $WAITTIME = 60; } # seconds to wait after configuring the nic (to let the switch handle the state change) my %args; -$args{kernelpath} = $ARGV[0]; -$args{initrdpath} = $ARGV[1]; +$args{kernelpath} = $ARGV[0]; +$args{initrdpath} = $ARGV[1]; $args{kernelparms} = $ARGV[2]; -$args{mnip} = $ARGV[3]; +$args{mnip} = $ARGV[3]; + +addKernelParms(\%args); # replace and add some parms to args{kernelparms} +updateGrub(\%args); # update the grub config with an entry filled with the info in args -addKernelParms(\%args); # replace and add some parms to args{kernelparms} -updateGrub(\%args); # update the grub config with an entry filled with the info in args - exit(0); # Add ip and net info to the kernel parms. Modifies the kernelparms value of the args hash passed in. sub addKernelParms { - my $args = shift @_; + my $args = shift @_; - # replace '!myipfn!' with the mn ip - my $mnip = $args->{mnip}; - $args->{kernelparms} =~ s/!myipfn!/$mnip/g; + # replace '!myipfn!' with the mn ip + my $mnip = $args->{mnip}; + $args->{kernelparms} =~ s/!myipfn!/$mnip/g; - # replace with the nodename - my $nodename = $ENV{NODE}; # this env var is set by xdsh - $args->{kernelparms} =~ s//$nodename/g; - # get node ip and add it to the kernel parms - my ($nic, $ip, $netmask, $network, $broadcast, $gateway, $mac) = getNodeIpInfo($args); - if (!$ip) { die "Error: could not find the NIC that would connect to the xCAT mgmt node's IP (".$args->{mnip}.").\n"; } + # replace with the nodename + my $nodename = $ENV{NODE}; # this env var is set by xdsh + $args->{kernelparms} =~ s//$nodename/g; - #if (defined($PROVMETHOD) && $PROVMETHOD eq 'sysclone') { - if ($args->{kernelpath} =~ m/genesis\.kernel\.x86_64/) { - # genesis case, add additional parms for sysclone or nodeset shell - my $bootif = $mac; - $bootif =~ s/:/-/g; - $bootif = "BOOTIF=01-$bootif"; - # DEVICE=eth0 IPADDR=10.0.0.99 NETMASK=255.255.255.0 NETWORK=10.0.0.0 BROADCAST=10.0.0.255 GATEWAY=10.0.0.1 GATEWAYDEV=eth0 - #todo: should we also add ETHER_SLEEP=$WAITTIME textmode=1 dns=$mnip ? - $args->{kernelparms} .= " $bootif IPADDR=$ip NETMASK=$netmask NETWORK=$network BROADCAST=$broadcast GATEWAY=$gateway HOSTNAME=$nodename DEVICE=$nic GATEWAYDEV=$nic"; - } - else { # scripted install (kickstart or autoyast) - if ($args->{kernelparms} =~ m/autoyast=/) { # sles - # if site.managedaddressmode=static is set, it will put several of these kernel parms on there for us. Do not duplicate in that case. - if ($args->{kernelparms} !~ m/ hostip=/) { $args->{kernelparms} .= " hostip=$ip"; } - if ($args->{kernelparms} !~ m/ netmask=/) { $args->{kernelparms} .= " netmask=$netmask"; } - if ($args->{kernelparms} !~ m/ gateway=/) { $args->{kernelparms} .= " gateway=$gateway"; } - if ($args->{kernelparms} !~ m/ hostname=/) { $args->{kernelparms} .= " hostname=$nodename"; } - if ($args->{kernelparms} !~ m/ dns=/) { $args->{kernelparms} .= " dns=$mnip"; } - # If they set installnic=mac (recommended), the netdevice will already be set to the mac. - # If they explicitly set installnic=, then ksdevice will be set to that and we will not disturb it here. - # Otherwise add netdevice set to the nic we calculated it should be. - if ($args->{kernelparms} !~ m/ netdevice=/) { $args->{kernelparms} .= " netdevice=$nic"; } - $args->{kernelparms} .= " netwait=$WAITTIME textmode=1"; - # print Dumper($args->{kernelparms}) - } - elsif ($args->{kernelparms} =~ m/ks=/) { # rhel/centos - # See https://www.centos.org/docs/5/html/Installation_Guide-en-US/s1-kickstart2-startinginstall.html - # and http://fedoraproject.org/wiki/Anaconda/NetworkIssues for description of kickstart kernel parms - # if site.managedaddressmode=static is set, it will put several of these kernel parms on there for us. Do not duplicate in that case. - if ($args->{kernelparms} !~ m/ ip=/) { $args->{kernelparms} .= " ip=$ip"; } - if ($args->{kernelparms} !~ m/ netmask=/) { $args->{kernelparms} .= " netmask=$netmask"; } - if ($args->{kernelparms} !~ m/ gateway=/) { $args->{kernelparms} .= " gateway=$gateway"; } - if ($args->{kernelparms} !~ m/ hostname=/) { $args->{kernelparms} .= " hostname=$nodename"; } - if ($args->{kernelparms} !~ m/ dns=/) { $args->{kernelparms} .= " dns=$mnip"; } - # If they set installnic=mac (recommended), the ksdevice will already be set to the mac. - # If they explicitly set installnic=, then ksdevice will be set to that and we will not disturb it here. - # Otherwise ksdevice will be set to bootif, and we change it to the nic we calculated it should be. - if ($args->{kernelparms} =~ m/ ksdevice=bootif/) { $args->{kernelparms} =~ s/ ksdevice=bootif/ ksdevice=$nic/; } - elsif ($args->{kernelparms} !~ m/ ksdevice=/) { $args->{kernelparms} .= " ksdevice=$nic"; } - $args->{kernelparms} .= " nicdelay=$WAITTIME linksleep=$WAITTIME textmode=1"; - # print Dumper($args->{kernelparms}) - } - else { die "Error: for scripted installs, only support SLES or RHEL/CentOS as the target OS.\n"; } - } + # get node ip and add it to the kernel parms + my ($nic, $ip, $netmask, $network, $broadcast, $gateway, $mac) = getNodeIpInfo($args); + if (!$ip) { die "Error: could not find the NIC that would connect to the xCAT mgmt node's IP (" . $args->{mnip} . ").\n"; } + + #if (defined($PROVMETHOD) && $PROVMETHOD eq 'sysclone') { + if ($args->{kernelpath} =~ m/genesis\.kernel\.x86_64/) { + + # genesis case, add additional parms for sysclone or nodeset shell + my $bootif = $mac; + $bootif =~ s/:/-/g; + $bootif = "BOOTIF=01-$bootif"; + + # DEVICE=eth0 IPADDR=10.0.0.99 NETMASK=255.255.255.0 NETWORK=10.0.0.0 BROADCAST=10.0.0.255 GATEWAY=10.0.0.1 GATEWAYDEV=eth0 + #todo: should we also add ETHER_SLEEP=$WAITTIME textmode=1 dns=$mnip ? + $args->{kernelparms} .= " $bootif IPADDR=$ip NETMASK=$netmask NETWORK=$network BROADCAST=$broadcast GATEWAY=$gateway HOSTNAME=$nodename DEVICE=$nic GATEWAYDEV=$nic"; + } + else { # scripted install (kickstart or autoyast) + if ($args->{kernelparms} =~ m/autoyast=/) { # sles + # if site.managedaddressmode=static is set, it will put several of these kernel parms on there for us. Do not duplicate in that case. + if ($args->{kernelparms} !~ m/ hostip=/) { $args->{kernelparms} .= " hostip=$ip"; } + if ($args->{kernelparms} !~ m/ netmask=/) { $args->{kernelparms} .= " netmask=$netmask"; } + if ($args->{kernelparms} !~ m/ gateway=/) { $args->{kernelparms} .= " gateway=$gateway"; } + if ($args->{kernelparms} !~ m/ hostname=/) { $args->{kernelparms} .= " hostname=$nodename"; } + if ($args->{kernelparms} !~ m/ dns=/) { $args->{kernelparms} .= " dns=$mnip"; } + + # If they set installnic=mac (recommended), the netdevice will already be set to the mac. + # If they explicitly set installnic=, then ksdevice will be set to that and we will not disturb it here. + # Otherwise add netdevice set to the nic we calculated it should be. + if ($args->{kernelparms} !~ m/ netdevice=/) { $args->{kernelparms} .= " netdevice=$nic"; } + $args->{kernelparms} .= " netwait=$WAITTIME textmode=1"; + + # print Dumper($args->{kernelparms}) + } + elsif ($args->{kernelparms} =~ m/ks=/) { # rhel/centos + # See https://www.centos.org/docs/5/html/Installation_Guide-en-US/s1-kickstart2-startinginstall.html + # and http://fedoraproject.org/wiki/Anaconda/NetworkIssues for description of kickstart kernel parms + # if site.managedaddressmode=static is set, it will put several of these kernel parms on there for us. Do not duplicate in that case. + if ($args->{kernelparms} !~ m/ ip=/) { $args->{kernelparms} .= " ip=$ip"; } + if ($args->{kernelparms} !~ m/ netmask=/) { $args->{kernelparms} .= " netmask=$netmask"; } + if ($args->{kernelparms} !~ m/ gateway=/) { $args->{kernelparms} .= " gateway=$gateway"; } + if ($args->{kernelparms} !~ m/ hostname=/) { $args->{kernelparms} .= " hostname=$nodename"; } + if ($args->{kernelparms} !~ m/ dns=/) { $args->{kernelparms} .= " dns=$mnip"; } + + # If they set installnic=mac (recommended), the ksdevice will already be set to the mac. + # If they explicitly set installnic=, then ksdevice will be set to that and we will not disturb it here. + # Otherwise ksdevice will be set to bootif, and we change it to the nic we calculated it should be. + if ($args->{kernelparms} =~ m/ ksdevice=bootif/) { $args->{kernelparms} =~ s/ ksdevice=bootif/ ksdevice=$nic/; } + elsif ($args->{kernelparms} !~ m/ ksdevice=/) { $args->{kernelparms} .= " ksdevice=$nic"; } + $args->{kernelparms} .= " nicdelay=$WAITTIME linksleep=$WAITTIME textmode=1"; + + # print Dumper($args->{kernelparms}) + } + else { die "Error: for scripted installs, only support SLES or RHEL/CentOS as the target OS.\n"; } + } } # get this nodes nic, ip, netmask, gateway, and mac. Returns them in a 5 element array. sub getNodeIpInfo { - my $args = shift @_; - my ($ipprefix) = $args->{mnip}=~m/^(\d+)\./; #todo: this is a hack, just using the 1st octet of the mn ip addr - verbose("using IP prefix $ipprefix"); + my $args = shift @_; + my ($ipprefix) = $args->{mnip} =~ m/^(\d+)\./; #todo: this is a hack, just using the 1st octet of the mn ip addr + verbose("using IP prefix $ipprefix"); - # parse ip addr show output, looking for ipprefix, to determine nic, ip, mac - my @output = runcmd("/sbin/ip addr show"); - my ($nic, $mac, $ipandmask); - foreach my $line (@output) { - my ($nictmp, $mactmp, $iptmp); - if (($nictmp) = $line=~m/^\d+:\s+(\S+): /) { $nic = $nictmp; } # new stanza, remember it - if (($mactmp) = $line=~m|^\s+link/ether\s+(\S+) |) { $mac = $mactmp; } # got mac, remember it - if (($iptmp) = $line=~m/^\s+inet\s+($ipprefix\S+) /) { $ipandmask = $iptmp; last; } # got ip, we are done - } - if (!defined($ipandmask)) { die "Error: can't find a NIC with a prefix $ipprefix that communicates with".$args->{mnip}.".\n"; } - my ($ip, $netmask, $network, $broadcast) = convertIpAndMask($ipandmask); + # parse ip addr show output, looking for ipprefix, to determine nic, ip, mac + my @output = runcmd("/sbin/ip addr show"); + my ($nic, $mac, $ipandmask); + foreach my $line (@output) { + my ($nictmp, $mactmp, $iptmp); + if (($nictmp) = $line =~ m/^\d+:\s+(\S+): /) { $nic = $nictmp; } # new stanza, remember it + if (($mactmp) = $line =~ m|^\s+link/ether\s+(\S+) |) { $mac = $mactmp; } # got mac, remember it + if (($iptmp) = $line =~ m/^\s+inet\s+($ipprefix\S+) /) { $ipandmask = $iptmp; last; } # got ip, we are done + } + if (!defined($ipandmask)) { die "Error: can't find a NIC with a prefix $ipprefix that communicates with" . $args->{mnip} . ".\n"; } + my ($ip, $netmask, $network, $broadcast) = convertIpAndMask($ipandmask); - # if the nic is a bonded nic (common on sl), then find the 1st real nic that is up that is part of it. - # also find that real nics real mac - my $realnic; - if ($nic =~ /^bond/) { - my @nics = grep(m/\s+master\s+$nic\s+/, @output); - if (!scalar(@nics)) { die "Error: can't find the NICs that are part of $nic.\n"; } - foreach my $line (@nics) { - my ($nictmp, $state) = $line=~m/^\d+:\s+(\S+): .* state\s+(\S+)/; - if (defined($nictmp) && defined($state) && $state eq 'UP') { $realnic = $nictmp; last; } # got ip, we are done - } - if (!defined($realnic)) { die "Error: can't find a physical NIC that is up and part of $nic.\n"; } + # if the nic is a bonded nic (common on sl), then find the 1st real nic that is up that is part of it. + # also find that real nics real mac + my $realnic; + if ($nic =~ /^bond/) { + my @nics = grep(m/\s+master\s+$nic\s+/, @output); + if (!scalar(@nics)) { die "Error: can't find the NICs that are part of $nic.\n"; } + foreach my $line (@nics) { + my ($nictmp, $state) = $line =~ m/^\d+:\s+(\S+): .* state\s+(\S+)/; + if (defined($nictmp) && defined($state) && $state eq 'UP') { $realnic = $nictmp; last; } # got ip, we are done + } + if (!defined($realnic)) { die "Error: can't find a physical NIC that is up and part of $nic.\n"; } - # now get the real mac of this real nic (when 2 nics are bonded, ip addr show displays one of the nics - # macs for both nics and the bond). So we have to depend on /proc/net/bonding/$bond instead. - my @bondout = runcmd("cat /proc/net/bonding/$nic"); - my $foundnic; - foreach my $line (@bondout) { - my $mactmp; - if ($line=~m/^Slave Interface:\s+$realnic/) { $foundnic = 1; } # found the stanza for this nic, remember it - if ($foundnic && (($mactmp) = $line=~m/^Permanent HW addr:\s+(\S+)/)) { $mac = $mactmp; last; } - } - } - else { $realnic = $nic; } + # now get the real mac of this real nic (when 2 nics are bonded, ip addr show displays one of the nics + # macs for both nics and the bond). So we have to depend on /proc/net/bonding/$bond instead. + my @bondout = runcmd("cat /proc/net/bonding/$nic"); + my $foundnic; + foreach my $line (@bondout) { + my $mactmp; + if ($line =~ m/^Slave Interface:\s+$realnic/) { $foundnic = 1; } # found the stanza for this nic, remember it + if ($foundnic && (($mactmp) = $line =~ m/^Permanent HW addr:\s+(\S+)/)) { $mac = $mactmp; last; } + } + } + else { $realnic = $nic; } - # centos/redhat seems to name the nic in a different order than sles on some svrs. - # sles seems to name them in the same order as 'ip addr show' displays them, centos does not. - # so if we are on centos right now, we need to count down to determine the number that sles - # will give the nic that we have selected, because it is the sles naming that we care about, - # because that is the initrd that will be running in the scripted install case. - # This works similarly (at least in some case) when rhel is the target OS. - # The preferred way is for the user to set installnic=mac, then we do not need to run this code. - # For the sysclone case, genesis doxcat uses the mac to find the nic. - if (isRedhat() && $args->{kernelparms} !~ m/ ksdevice=\S*:/ && $args->{kernelparms} !~ m/ netdevice=\S*:/) { - my @nics = grep(m/^\d+:\s+eth/, @output); - my $i = 0; - foreach my $line (@nics) { - my ($nictmp) = $line=~m/^\d+:\s+(\S+):/; - if (defined($nictmp) && $nictmp eq $realnic) { $realnic = "eth$i"; last; } # got ip, we are done - $i++; - } - print "Determined that SLES/RHEL will call the install NIC $realnic (it has mac $mac)\n"; - } + # centos/redhat seems to name the nic in a different order than sles on some svrs. + # sles seems to name them in the same order as 'ip addr show' displays them, centos does not. + # so if we are on centos right now, we need to count down to determine the number that sles + # will give the nic that we have selected, because it is the sles naming that we care about, + # because that is the initrd that will be running in the scripted install case. + # This works similarly (at least in some case) when rhel is the target OS. + # The preferred way is for the user to set installnic=mac, then we do not need to run this code. + # For the sysclone case, genesis doxcat uses the mac to find the nic. + if (isRedhat() && $args->{kernelparms} !~ m/ ksdevice=\S*:/ && $args->{kernelparms} !~ m/ netdevice=\S*:/) { + my @nics = grep(m/^\d+:\s+eth/, @output); + my $i = 0; + foreach my $line (@nics) { + my ($nictmp) = $line =~ m/^\d+:\s+(\S+):/; + if (defined($nictmp) && $nictmp eq $realnic) { $realnic = "eth$i"; last; } # got ip, we are done + $i++; + } + print "Determined that SLES/RHEL will call the install NIC $realnic (it has mac $mac)\n"; + } - # finally, find the gateway - my $gateway; - my @output = runcmd("/sbin/ip route"); - # we are looking for a line like: 10.0.0.0/8 via 10.54.51.1 dev bond0 - my @networks = grep(m/ via .* $nic\s*$/, @output); - if (scalar(@networks)) { ($gateway) = $networks[0]=~m/ via\s+(\S+)/; } - else { - # use the mn ip as a fall back - $gateway = $args->{mnip}; - verbose("using xCAT mgmt node IP as the fall back gateway."); - } + # finally, find the gateway + my $gateway; + my @output = runcmd("/sbin/ip route"); - verbose("IP info: realnic=$realnic, ip=$ip, netmask=$netmask, gateway=$gateway, mac=$mac"); - return ($realnic, $ip, $netmask, $network, $broadcast, $gateway, $mac); + # we are looking for a line like: 10.0.0.0/8 via 10.54.51.1 dev bond0 + my @networks = grep(m/ via .* $nic\s*$/, @output); + if (scalar(@networks)) { ($gateway) = $networks[0] =~ m/ via\s+(\S+)/; } + else { + # use the mn ip as a fall back + $gateway = $args->{mnip}; + verbose("using xCAT mgmt node IP as the fall back gateway."); + } + + verbose("IP info: realnic=$realnic, ip=$ip, netmask=$netmask, gateway=$gateway, mac=$mac"); + return ($realnic, $ip, $netmask, $network, $broadcast, $gateway, $mac); } # Convert an ip/mask in slash notation (like 10.1.1.1/26) to separate ip, netmask, network, and broadcast values, # like: 10.1.1.1, 255.255.255.192, 10.1.1.0, 10.1.1.63 sub convertIpAndMask { - my $ipandmask = shift @_; - my ($ip, $masknum) = split('/', $ipandmask); + my $ipandmask = shift @_; + my ($ip, $masknum) = split('/', $ipandmask); - # build the netmask - my $nmbin = oct("0b" . '1' x $masknum . '0' x (32-$masknum)); # create a str like '1111100', then convert to binary - my @nmarr=unpack('C4',pack('N',$nmbin)); # separate into the 4 octets - my $netmask=join('.',@nmarr); # put them together into the normal looking netmask + # build the netmask + my $nmbin = oct("0b" . '1' x $masknum . '0' x (32 - $masknum)); # create a str like '1111100', then convert to binary + my @nmarr = unpack('C4', pack('N', $nmbin)); # separate into the 4 octets + my $netmask = join('.', @nmarr); # put them together into the normal looking netmask - # create binary form of ip - my @iparr=split(/\./,$ip); - my ( $ipbin ) = unpack('N', pack('C4',@iparr ) ); + # create binary form of ip + my @iparr = split(/\./, $ip); + my ($ipbin) = unpack('N', pack('C4', @iparr)); - # Calculate network address by logical AND operation of ip & netmask and convert network address to IP address format - my $netbin = ( $ipbin & $nmbin ); - my @netarr=unpack('C4', pack('N',$netbin ) ); - my $network=join(".",@netarr); + # Calculate network address by logical AND operation of ip & netmask and convert network address to IP address format + my $netbin = ($ipbin & $nmbin); + my @netarr = unpack('C4', pack('N', $netbin)); + my $network = join(".", @netarr); - # Calculate broadcast address by inverting the netmask and adding it to the network address - my $bcbin = ( $ipbin & $nmbin ) + ( ~ $nmbin ); - my @bcarr=unpack('C4', pack('N',$bcbin ) ) ; - my $broadcast=join(".",@bcarr); + # Calculate broadcast address by inverting the netmask and adding it to the network address + my $bcbin = ($ipbin & $nmbin) + (~$nmbin); + my @bcarr = unpack('C4', pack('N', $bcbin)); + my $broadcast = join(".", @bcarr); - return ($ip, $netmask, $network, $broadcast); + return ($ip, $netmask, $network, $broadcast); } # not used - resolve the hostname to an ip addr sub getipaddr { - my $hostname = shift @_; - my $packed_ip; + my $hostname = shift @_; + my $packed_ip; $packed_ip = inet_aton($hostname); if (!$packed_ip) { return undef; } return inet_ntoa($packed_ip); @@ -246,102 +255,106 @@ sub getipaddr { # Update the grub config file with a new stanza for booting our kernel and initrd sub updateGrub { - my $args = shift @_; + my $args = shift @_; - # how we specify the path for the kernel and initrd is different on redhat and suse - my $fileprefix; - if (isRedhat()) { $fileprefix = '/'; } - elsif (isSuse()) { $fileprefix = '/boot/'; } - else { die "Error: currently only support red hat or suse distros.\n"; } + # how we specify the path for the kernel and initrd is different on redhat and suse + my $fileprefix; + if (isRedhat()) { $fileprefix = '/'; } + elsif (isSuse()) { $fileprefix = '/boot/'; } + else { die "Error: currently only support red hat or suse distros.\n"; } - # open the grub file and see if it is in there or if we have to add it - my $grubfile = findGrubPath(); - verbose("reading $grubfile"); - open(FILE, $grubfile) || die "Error: can not open config file $grubfile for reading: $!\n"; - my @lines = ; - close FILE; + # open the grub file and see if it is in there or if we have to add it + my $grubfile = findGrubPath(); + verbose("reading $grubfile"); + open(FILE, $grubfile) || die "Error: can not open config file $grubfile for reading: $!\n"; + my @lines = ; + close FILE; - # this is the entry we want in the grub file - my @rootlines = grep(/^\s+root\s+/, @lines); # copy one of the existing root lines - if (!scalar(@rootlines)) { die "Error: can't find an existing line for 'root' in the grub config file\n"; } - my ($rootline) = $rootlines[0] =~ m/^\s*(.*?)\s*$/; - my @entry = ( - "title $XCATNETBOOTTITLE\n", - "\t$rootline\n", - "\tkernel " . $fileprefix . $args->{kernelpath} . ' ' . $args->{kernelparms} . "\n", - "\tinitrd " . $fileprefix . $args->{initrdpath} . "\n", - ); - if ($DRYRUN) { - print "Dry run: would add this stanza to $grubfile:\n"; - foreach my $l (@entry) { print $l; } - return; - } + # this is the entry we want in the grub file + my @rootlines = grep(/^\s+root\s+/, @lines); # copy one of the existing root lines + if (!scalar(@rootlines)) { die "Error: can't find an existing line for 'root' in the grub config file\n"; } + my ($rootline) = $rootlines[0] =~ m/^\s*(.*?)\s*$/; + my @entry = ( + "title $XCATNETBOOTTITLE\n", + "\t$rootline\n", +"\tkernel " . $fileprefix . $args->{kernelpath} . ' ' . $args->{kernelparms} . "\n", + "\tinitrd " . $fileprefix . $args->{initrdpath} . "\n", + ); + if ($DRYRUN) { + print "Dry run: would add this stanza to $grubfile:\n"; + foreach my $l (@entry) { print $l; } + return; + } - my $needtowritefile = 1; - if (grep(/^title\s+$XCATNETBOOTTITLE/, @lines)) { $needtowritefile = updateGrubEntry(\@lines, \@entry); } # there is already an entry in there - else { addGrubEntry (\@lines, \@entry); } + my $needtowritefile = 1; + if (grep(/^title\s+$XCATNETBOOTTITLE/, @lines)) { $needtowritefile = updateGrubEntry(\@lines, \@entry); } # there is already an entry in there + else { addGrubEntry(\@lines, \@entry); } - # write the file with the new/updated xcat entry - if ($needtowritefile) { - verbose("updating $grubfile"); - open(FILE, '>', $grubfile) || die "Error: can not open config file $grubfile for writing: $!\n"; - print FILE @lines; - close FILE; - } - else { print "Info: $grubfile did not need modifying. It was already up to date.\n"; } + # write the file with the new/updated xcat entry + if ($needtowritefile) { + verbose("updating $grubfile"); + open(FILE, '>', $grubfile) || die "Error: can not open config file $grubfile for writing: $!\n"; + print FILE @lines; + close FILE; + } + else { print "Info: $grubfile did not need modifying. It was already up to date.\n"; } } # add our entry as the 1st one in the grub file sub addGrubEntry { - my ($lines, $entry) = @_; - # find the index of the 1st stanza (it starts with 'title') - my $i; - for ($i=0; $i[$i] =~ m/^title\s+/) { verbose('adding xcat entry before:'.$lines->[$i]); last; } # found it - } - - # splice the entry right before the i-th line (which may also be 1 past the end) - splice(@$lines, $i, 0, @$entry); + my ($lines, $entry) = @_; + + # find the index of the 1st stanza (it starts with 'title') + my $i; + for ($i = 0 ; $i < scalar(@$lines) ; $i++) { + if ($lines->[$i] =~ m/^title\s+/) { verbose('adding xcat entry before:' . $lines->[$i]); last; } # found it + } + + # splice the entry right before the i-th line (which may also be 1 past the end) + splice(@$lines, $i, 0, @$entry); } # check the xcat entry in the grub file and see if it needs to be updated. Return 1 if it does. sub updateGrubEntry { - my ($lines, $entry) = @_; - #print Dumper($lines), Dumper($entry); - # find the index of the xcat stanza - my $i; - for ($i=0; $i[$i] =~ m/^title\s+$XCATNETBOOTTITLE/) { last; } # found it - } + my ($lines, $entry) = @_; - # compare the next few lines with the corresponding line in @$entries and replace if different - my $replaced = 0; - for (my $j=0; $j[$i+$j], "\n ", $entry->[$j], "\n"; - if ($lines->[$i+$j] ne $entry->[$j]) { # this line was different - $lines->[$i+$j] = $entry->[$j]; - $replaced = 1; - } - } - - return $replaced; + #print Dumper($lines), Dumper($entry); + # find the index of the xcat stanza + my $i; + for ($i = 0 ; $i < scalar(@$lines) ; $i++) { + if ($lines->[$i] =~ m/^title\s+$XCATNETBOOTTITLE/) { last; } # found it + } + + # compare the next few lines with the corresponding line in @$entries and replace if different + my $replaced = 0; + for (my $j = 0 ; $j < scalar(@$entry) ; $j++) { + + #print "comparing:\n ", $lines->[$i+$j], "\n ", $entry->[$j], "\n"; + if ($lines->[ $i + $j ] ne $entry->[$j]) { # this line was different + $lines->[ $i + $j ] = $entry->[$j]; + $replaced = 1; + } + } + + return $replaced; } # depending on the distro, find the correct grub file and return its path sub findGrubPath { - # for rhel/centos it is /boot/grub/grub.conf, for sles it is /boot/grub/menu.lst - my @paths = qw(/boot/grub/grub.conf /boot/grub/menu.lst); - foreach my $p (@paths) { - if (-f $p) { return $p; } - } - - die "Error: Can't find grub config file.\n"; - #todo: support ubuntu: you add an executable file in /etc/grub.d named 06_xcatnetboot that prints out the - # entry to add. Then run grub-mkconfig. + # for rhel/centos it is /boot/grub/grub.conf, for sles it is /boot/grub/menu.lst + my @paths = qw(/boot/grub/grub.conf /boot/grub/menu.lst); + foreach my $p (@paths) { + if (-f $p) { return $p; } + } + + die "Error: Can't find grub config file.\n"; + + #todo: support ubuntu: you add an executable file in /etc/grub.d named 06_xcatnetboot that prints out the + # entry to add. Then run grub-mkconfig. } @@ -350,7 +363,7 @@ sub verbose { if ($VERBOSE) { print shift, "\n"; } } # Check the distro we are running on sub isSuse { return (-e '/etc/SuSE-release'); } -sub isRedhat { return (-e '/etc/redhat-release' || -e '/etc/centos-release' || -e '/etc/fedora-release'); } # add chk for fedora +sub isRedhat { return (-e '/etc/redhat-release' || -e '/etc/centos-release' || -e '/etc/fedora-release'); } # add chk for fedora @@ -362,23 +375,23 @@ sub runcmd my ($cmd) = @_; my $rc; - $cmd .= ' 2>&1' ; + $cmd .= ' 2>&1'; verbose($cmd); - my @output; - if (wantarray) { - @output = `$cmd`; - $rc = $?; - } - else { - system($cmd); - $rc = $?; - } + my @output; + if (wantarray) { + @output = `$cmd`; + $rc = $?; + } + else { + system($cmd); + $rc = $?; + } if ($rc) { $rc = $rc >> 8; - if ($rc > 0) { die "Error: rc $rc return from cmd: $cmd\n"; } - else { die "Error: system error returned from cmd: $cmd\n"; } + if ($rc > 0) { die "Error: rc $rc return from cmd: $cmd\n"; } + else { die "Error: system error returned from cmd: $cmd\n"; } } elsif (wantarray) { return @output; } } diff --git a/xCAT-SoftLayer/bin/pushinitrd b/xCAT-SoftLayer/bin/pushinitrd index 79041473f..0df2251d9 100755 --- a/xCAT-SoftLayer/bin/pushinitrd +++ b/xCAT-SoftLayer/bin/pushinitrd @@ -18,30 +18,31 @@ my $WAITTIME; my $NOAUTOINST; my $usage = sub { - my $exitcode = shift @_; - print "Usage: pushinitrd [-?|-h|--help] [-v|--verbose] [--dryrun] [-w ] [--noautoinst] \n\n"; - if (!$exitcode) { - print "Copy the initrd, kernel, params, and static IP info to nodes, so they can net install\n"; - print "even across vlans (w/o setting up pxe/dhcp broadcast relay). This assumes a working\n"; - print "OS is on the node, that you've run nodeset for these nodes, and that all of the nodes\n"; - print "in this noderange are using the same osimage.\n"; - } - exit $exitcode; + my $exitcode = shift @_; + print "Usage: pushinitrd [-?|-h|--help] [-v|--verbose] [--dryrun] [-w ] [--noautoinst] \n\n"; + if (!$exitcode) { + print "Copy the initrd, kernel, params, and static IP info to nodes, so they can net install\n"; + print "even across vlans (w/o setting up pxe/dhcp broadcast relay). This assumes a working\n"; + print "OS is on the node, that you've run nodeset for these nodes, and that all of the nodes\n"; + print "in this noderange are using the same osimage.\n"; + } + exit $exitcode; }; # Process the cmd line args Getopt::Long::Configure("bundling"); + # Getopt::Long::Configure("pass_through"); Getopt::Long::Configure("no_pass_through"); -if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE, 'dryrun' => \$DRYRUN, 'w|waittime=s' => \$WAITTIME, 'a|noautoinst' => \$NOAUTOINST)) { $usage->(1); } +if (!GetOptions('h|?|help' => \$HELP, 'v|verbose' => \$VERBOSE, 'dryrun' => \$DRYRUN, 'w|waittime=s' => \$WAITTIME, 'a|noautoinst' => \$NOAUTOINST)) { $usage->(1); } if ($HELP) { $usage->(0); } if (scalar(@ARGV) != 1) { $usage->(1); } -if (!defined($WAITTIME)) { $WAITTIME = 75; } # seconds to wait after configuring the nic (to let the switch handle the state change) +if (!defined($WAITTIME)) { $WAITTIME = 75; } # seconds to wait after configuring the nic (to let the switch handle the state change) my $noderange = $ARGV[0]; # -# Run some Node verification before starting pushinitrd +# Run some Node verification before starting pushinitrd # verifyNodeConfiguration($noderange); @@ -51,7 +52,7 @@ updateGrubOnNodes($noderange, \%bootparms); if ($DRYRUN) { exit(0); } -if ($bootparms{osimageprovmethod} eq 'install' && $bootparms{osimageosvers}=~ m/^sles/ && !$NOAUTOINST) { modifyAutoinstFiles($noderange, \%bootparms); } +if ($bootparms{osimageprovmethod} eq 'install' && $bootparms{osimageosvers} =~ m/^sles/ && !$NOAUTOINST) { modifyAutoinstFiles($noderange, \%bootparms); } if ($bootparms{osimageprovmethod} eq 'sysclone') { copySyscloneFiles(); } @@ -59,307 +60,321 @@ exit(0); # Query the db for the kernel, initrd, and kcmdline attributes of the 1st node in the noderange sub getBootParms { - my $nr = shift @_; - my %bootparms; - my @output = runcmd("nodels $nr bootparams.kernel bootparams.initrd bootparams.kcmdline nodetype.provmethod"); + my $nr = shift @_; + my %bootparms; + my @output = runcmd("nodels $nr bootparams.kernel bootparams.initrd bootparams.kcmdline nodetype.provmethod"); - # the attributes can be displayed in a different order than requested, so need to grep for them - foreach my $attr (qw(bootparams.kernel bootparams.initrd bootparams.kcmdline nodetype.provmethod)) { - my ($a) = $attr =~ m/\.(.*)$/; - my @gresults = grep(/^\S+:\s+$attr:/, @output); - if (!scalar(@gresults)) { die "Error: attribute $attr not defined for the noderange. Did you run 'nodeset osimage=' ?\n"; } - # for now just pick the 1st one. They should all be the same, except for the node name in kcmdline - chomp($gresults[0]); - $gresults[0] =~ s/^\S+:\s+$attr:\s*//; - #print "gresults='$gresults[0]'\n"; - if ($gresults[0] !~ m/\S/) { die "Error: attribute $attr not defined for the noderange. Did you run 'nodeset osimage=' ?\n"; } - $bootparms{$a} = $gresults[0]; - } - $bootparms{kcmdline} =~ s|/install/autoinst/\S+|/install/autoinst/|; + # the attributes can be displayed in a different order than requested, so need to grep for them + foreach my $attr (qw(bootparams.kernel bootparams.initrd bootparams.kcmdline nodetype.provmethod)) { + my ($a) = $attr =~ m/\.(.*)$/; + my @gresults = grep(/^\S+:\s+$attr:/, @output); + if (!scalar(@gresults)) { die "Error: attribute $attr not defined for the noderange. Did you run 'nodeset osimage=' ?\n"; } - # from the nodes provmethod, get the osimage provmethod, so we know the type of install - @output = runcmd("lsdef -t osimage $bootparms{provmethod} -ci provmethod,osvers"); - foreach my $line (@output) { - chomp($line); - if ($line =~ m/^Could not find/) { die "Error: provmethod $bootparms{provmethod} is set for the node, but there is no osimage definition by that name."; } - if ($line =~ m/ provmethod=/) { - my ($junk, $provmethod) = split(/=/, $line); - $bootparms{osimageprovmethod} = $provmethod; - } - if ($line =~ m/ osvers=/) { - my ($junk, $osvers) = split(/=/, $line); - $bootparms{osimageosvers} = $osvers; - } - } - #print "provmethod=$bootparms{osimageprovmethod}, osvers=$bootparms{osimageosvers}\n"; exit; + # for now just pick the 1st one. They should all be the same, except for the node name in kcmdline + chomp($gresults[0]); + $gresults[0] =~ s/^\S+:\s+$attr:\s*//; - # get the mgmt node cluster-facing ip addr - @output = runcmd('lsdef -t site -ci master'); - chomp($output[0]); - my ($junk, $ip) = split(/=/, $output[0]); - $bootparms{mnip} = $ip; + #print "gresults='$gresults[0]'\n"; + if ($gresults[0] !~ m/\S/) { die "Error: attribute $attr not defined for the noderange. Did you run 'nodeset osimage=' ?\n"; } + $bootparms{$a} = $gresults[0]; + } + $bootparms{kcmdline} =~ s|/install/autoinst/\S+|/install/autoinst/|; - verbose(Dumper(\%bootparms)); - return %bootparms; + # from the nodes provmethod, get the osimage provmethod, so we know the type of install + @output = runcmd("lsdef -t osimage $bootparms{provmethod} -ci provmethod,osvers"); + foreach my $line (@output) { + chomp($line); + if ($line =~ m/^Could not find/) { die "Error: provmethod $bootparms{provmethod} is set for the node, but there is no osimage definition by that name."; } + if ($line =~ m/ provmethod=/) { + my ($junk, $provmethod) = split(/=/, $line); + $bootparms{osimageprovmethod} = $provmethod; + } + if ($line =~ m/ osvers=/) { + my ($junk, $osvers) = split(/=/, $line); + $bootparms{osimageosvers} = $osvers; + } + } + + #print "provmethod=$bootparms{osimageprovmethod}, osvers=$bootparms{osimageosvers}\n"; exit; + + # get the mgmt node cluster-facing ip addr + @output = runcmd('lsdef -t site -ci master'); + chomp($output[0]); + my ($junk, $ip) = split(/=/, $output[0]); + $bootparms{mnip} = $ip; + + verbose(Dumper(\%bootparms)); + return %bootparms; } # Copy the kernel and initrd to the nodes # Args: noderange, reference to the bootparms hash sub copyFilesToNodes { - my $nr = shift @_; - my $bootparms = shift @_; - foreach my $a (qw(kernel initrd)) { - my $file = $bootparms->{$a}; - my $localfile = "/tftpboot/$file"; - # for the - my $remotefile = '/boot/' . remoteFilename($file); - my $cmd = "xdcp $nr -p $localfile $remotefile"; - if ($DRYRUN) { - print "Dry run: Copying $localfile to $nr:$remotefile\n"; - print "Dry run: $cmd\n"; - } - else { - print "Copying $localfile to $nr:$remotefile\n"; - runcmd($cmd); - } - } + my $nr = shift @_; + my $bootparms = shift @_; + foreach my $a (qw(kernel initrd)) { + my $file = $bootparms->{$a}; + my $localfile = "/tftpboot/$file"; + + # for the + my $remotefile = '/boot/' . remoteFilename($file); + my $cmd = "xdcp $nr -p $localfile $remotefile"; + if ($DRYRUN) { + print "Dry run: Copying $localfile to $nr:$remotefile\n"; + print "Dry run: $cmd\n"; + } + else { + print "Copying $localfile to $nr:$remotefile\n"; + runcmd($cmd); + } + } } # Form the remote file name, using the last 2 parts of the path, separated by "-" sub remoteFilename { - my $f = shift @_; - $f =~ s|^.*?([^/]+)/([^/]+)$|$1-$2|; - return $f; + my $f = shift @_; + $f =~ s|^.*?([^/]+)/([^/]+)$|$1-$2|; + return $f; } # Run the modifygrub script on the nodes to update the grub config file # Args: noderange, reference to the bootparms hash sub updateGrubOnNodes { - my $nr = shift @_; - my $bootparms = shift @_; - my $vtxt = ($VERBOSE ? '-v' : ''); - my $dtxt = ($DRYRUN ? '--dryrun' : ''); - my @output = runcmd('which modifygrub'); - my $modifygrub = $output[0]; - chomp($modifygrub); - my $euser ="root"; - my $cmd = "xdsh $nr -l $euser -e $modifygrub $vtxt $dtxt -w $WAITTIME -p " . $bootparms->{osimageprovmethod} . ' ' . remoteFilename($bootparms->{kernel}) . ' ' . remoteFilename($bootparms->{initrd}) . ' '; - # we need to quote the kernel parms, both here when passing it to xdsh, and on the node - # when xdsh is passing it to modifygrub. The way to get single quotes inside single quotes - # is to quote each of the outer single quotes with double quotes. - $cmd .= q("'"') . $bootparms->{kcmdline} . q('"'"); - $cmd .= ' ' . $bootparms->{mnip}; - print "Running modifygrub on $nr to update the grub configuration.\n"; - runcmd($cmd); + my $nr = shift @_; + my $bootparms = shift @_; + my $vtxt = ($VERBOSE ? '-v' : ''); + my $dtxt = ($DRYRUN ? '--dryrun' : ''); + my @output = runcmd('which modifygrub'); + my $modifygrub = $output[0]; + chomp($modifygrub); + my $euser = "root"; + my $cmd = "xdsh $nr -l $euser -e $modifygrub $vtxt $dtxt -w $WAITTIME -p " . $bootparms->{osimageprovmethod} . ' ' . remoteFilename($bootparms->{kernel}) . ' ' . remoteFilename($bootparms->{initrd}) . ' '; + + # we need to quote the kernel parms, both here when passing it to xdsh, and on the node + # when xdsh is passing it to modifygrub. The way to get single quotes inside single quotes + # is to quote each of the outer single quotes with double quotes. + $cmd .= q("'"') . $bootparms->{kcmdline} . q('"'"); + $cmd .= ' ' . $bootparms->{mnip}; + print "Running modifygrub on $nr to update the grub configuration.\n"; + runcmd($cmd); } # Hack the autoinst files to overcome the nic coming up delay. #todo: this has only been tested with SLES nodes sub modifyAutoinstFiles { - my $nr = shift @_; - my $bootparms = shift @_; + my $nr = shift @_; + my $bootparms = shift @_; - # expand the noderange into a list of nodes - my @nodes = runcmd("nodels $nr"); - chomp(@nodes); + # expand the noderange into a list of nodes + my @nodes = runcmd("nodels $nr"); + chomp(@nodes); - # Modify chroot.sles to insert a wait in the /etc/init.d/network of each node. This is - # necessary because even tho compute.sles11.softlayer.tmpl configures bonding, when autoyast - # reboots the node after installing the rpms, it does not bring up the network in the normal way - # at first and seems to skip any bonding and the if-up.d scripts. So we are left doing this. - # (After autoyast is done with all of its post-configuration, it brings up the network in the - # normal way, so bonding gets done then, which is good at least.) + # Modify chroot.sles to insert a wait in the /etc/init.d/network of each node. This is + # necessary because even tho compute.sles11.softlayer.tmpl configures bonding, when autoyast + # reboots the node after installing the rpms, it does not bring up the network in the normal way + # at first and seems to skip any bonding and the if-up.d scripts. So we are left doing this. + # (After autoyast is done with all of its post-configuration, it brings up the network in the + # normal way, so bonding gets done then, which is good at least.) - # Edit each file to have chroot.sles insert a wait at the end of /etc/init.d/network - # this finds the end of boot.sh script (which is chroot.sles) - my $search = '\n\]\]>\s*\s*\s*'; - # hack the /etc/init.d/network script to put a wait in it - my $file = '/mnt/etc/init.d/network'; # at this point in the installation, the permanent file system is just mounted - # this is the string to insert in the nodes /etc/init.d/network script. It is a while loop pinging the mn, but some of the chars need to be escaped for sed - my $waitstring = 'echo -n Waiting to reach xCAT mgmt node ' . $bootparms->{mnip} . '.;xcatretries=60;while \[ \$\(\(xcati+=1\)\) -le \$xcatretries \] \&\& ! ping -c2 -w3 ' . $bootparms->{mnip} .' \>\/dev\/null 2\>\&1; do echo -n .; done; if \[ \$xcati -le \$xcatretries \]; then echo success; else echo failed; fi'; - # this crazy sed string is from google. It gathers up the whole file into the hold buffer, and then the substitution is done on the whole file - my $sedstring = q|sed -n '1h;1!H;${;g;s/\(\t\treload_firewall\n\)\n/\1\t\t| . $waitstring . q(\n\n/g;p;}') . " $file > $file.new"; - # finally create the perl replace string that will be used to modify the autoinst file - my $replace = "$sedstring\nchmod 755 $file.new; mv -f $file.new $file"; + # Edit each file to have chroot.sles insert a wait at the end of /etc/init.d/network + # this finds the end of boot.sh script (which is chroot.sles) + my $search = '\n\]\]>\s*\s*\s*'; - # Add a script that gets invoked by the OS after the nic is brought up - # Note: this does not work, because midway thru the autoyast process, the if-up.d scripts do not seem to get invoked - # so autoyast fails to get the media - # these are specific to SLES - #my $netdir = '/etc/sysconfig/network'; - #my $filename = '/etc/sysconfig/network/if-up.d/xcat-sl-wait'; - #my $mnip = $bootparms->{mnip}; - #todo: to support rhel, use these values instead - #my $netdir='/etc/sysconfig/network-scripts'; - #my $filename='/sbin/ifup-local'; - #my $replace = qq( - #FILENAME=$filename - #NETDIR=$netdir - #MNIP=$mnip - #); -# $replace .= q( -#cat >$FILENAME << EOF1 -#MNIP=$MNIP -#NETDIR=$NETDIR -#EOF1 -# -# this part of the file we do NOT want to expand the variables in the content -#cat >>$FILENAME << 'EOF2' -#NIC="$1" -# look in this ifcfg script to get the nics ip to see if this is the one we should be waiting on -#NICIP=`awk -F= '/^IPADDR/ {print $2}' $NETDIR/ifcfg-$NIC | tr -d \' ` -#if [ "${NICIP%.*.*}" != "${MNIP%.*.*}" ]; then exit; fi # hack: compare the 1st 2 octets -#echo -n Waiting to reach xCAT mgmt node $MNIP. -#xcatretries=60 -#while [ $((xcati+=1)) -le $xcatretries ] && ! ping -c2 -w3 $MNIP >/dev/null 2>&1; do echo -n .; done -#if [ $xcati -le $xcatretries ]; then echo " success"; else echo " failed"; fi -#sleep 3 -#EOF2 -# -#chmod +x $FILENAME -#); + # hack the /etc/init.d/network script to put a wait in it + my $file = '/mnt/etc/init.d/network'; # at this point in the installation, the permanent file system is just mounted + # this is the string to insert in the nodes /etc/init.d/network script. It is a while loop pinging the mn, but some of the chars need to be escaped for sed + my $waitstring = 'echo -n Waiting to reach xCAT mgmt node ' . $bootparms->{mnip} . '.;xcatretries=60;while \[ \$\(\(xcati+=1\)\) -le \$xcatretries \] \&\& ! ping -c2 -w3 ' . $bootparms->{mnip} . ' \>\/dev\/null 2\>\&1; do echo -n .; done; if \[ \$xcati -le \$xcatretries \]; then echo success; else echo failed; fi'; - # The compute.sles11.softlayer.tmpl file contains 2 variables (node ip and netmask) that are - # not replaced by Template.pm. Substitute those in the autoinst files now. - # Also use our own multiline sed to put the network script hack in. - print "Updating /install/autoinst files.\n"; - foreach my $n (@nodes) { - my $f = "/install/autoinst/$n"; - my ($ip, $netmask, $gateway) = getNodeIpInfo($n); - runcmd("sudo sed -i 's/#NODEIPADDR#/$ip/;s/#NODENETMASK#/$netmask/;s/#NODEGATEWAY#/$gateway/' $f"); - my $matches = sed($f, $search, $replace, mode=>'insertbefore'); - if (!$matches) { die "Error: could not find the right place in $f to insert the sed of the network wait.\n"; } - } + # this crazy sed string is from google. It gathers up the whole file into the hold buffer, and then the substitution is done on the whole file + my $sedstring = q|sed -n '1h;1!H;${;g;s/\(\t\treload_firewall\n\)\n/\1\t\t| . $waitstring . q(\n\n/g;p;}') . " $file > $file.new"; + + # finally create the perl replace string that will be used to modify the autoinst file + my $replace = "$sedstring\nchmod 755 $file.new; mv -f $file.new $file"; + + # Add a script that gets invoked by the OS after the nic is brought up + # Note: this does not work, because midway thru the autoyast process, the if-up.d scripts do not seem to get invoked + # so autoyast fails to get the media + # these are specific to SLES + #my $netdir = '/etc/sysconfig/network'; + #my $filename = '/etc/sysconfig/network/if-up.d/xcat-sl-wait'; + #my $mnip = $bootparms->{mnip}; + #todo: to support rhel, use these values instead + #my $netdir='/etc/sysconfig/network-scripts'; + #my $filename='/sbin/ifup-local'; + #my $replace = qq( + #FILENAME=$filename + #NETDIR=$netdir + #MNIP=$mnip + #); + # $replace .= q( + #cat >$FILENAME << EOF1 + #MNIP=$MNIP + #NETDIR=$NETDIR + #EOF1 + # + # this part of the file we do NOT want to expand the variables in the content + #cat >>$FILENAME << 'EOF2' + #NIC="$1" + # look in this ifcfg script to get the nics ip to see if this is the one we should be waiting on + #NICIP=`awk -F= '/^IPADDR/ {print $2}' $NETDIR/ifcfg-$NIC | tr -d \' ` + #if [ "${NICIP%.*.*}" != "${MNIP%.*.*}" ]; then exit; fi # hack: compare the 1st 2 octets + #echo -n Waiting to reach xCAT mgmt node $MNIP. + #xcatretries=60 + #while [ $((xcati+=1)) -le $xcatretries ] && ! ping -c2 -w3 $MNIP >/dev/null 2>&1; do echo -n .; done + #if [ $xcati -le $xcatretries ]; then echo " success"; else echo " failed"; fi + #sleep 3 + #EOF2 + # + #chmod +x $FILENAME + #); + + # The compute.sles11.softlayer.tmpl file contains 2 variables (node ip and netmask) that are + # not replaced by Template.pm. Substitute those in the autoinst files now. + # Also use our own multiline sed to put the network script hack in. + print "Updating /install/autoinst files.\n"; + foreach my $n (@nodes) { + my $f = "/install/autoinst/$n"; + my ($ip, $netmask, $gateway) = getNodeIpInfo($n); + runcmd("sudo sed -i 's/#NODEIPADDR#/$ip/;s/#NODENETMASK#/$netmask/;s/#NODEGATEWAY#/$gateway/' $f"); + my $matches = sed($f, $search, $replace, mode => 'insertbefore'); + if (!$matches) { die "Error: could not find the right place in $f to insert the sed of the network wait.\n"; } + } } -sub verifyNodeConfiguration { - my $nr = shift @_; +sub verifyNodeConfiguration { + my $nr = shift @_; - my @nodes = runcmd("nodels $nr"); - chomp(@nodes); + my @nodes = runcmd("nodels $nr"); + chomp(@nodes); - foreach my $n (@nodes) { - # Verify the IP is set for the node - my @output = runcmd("nodels $n hosts.ip"); - chomp($output[0]); - my ($junk, $ip) = split(/\s+/, $output[0]); - #todo: also support getting the ip from name resolution - if (!$ip) { - die "Error: The ip attribute must be set for $n.\n"; - } - } + foreach my $n (@nodes) { + + # Verify the IP is set for the node + my @output = runcmd("nodels $n hosts.ip"); + chomp($output[0]); + my ($junk, $ip) = split(/\s+/, $output[0]); + + #todo: also support getting the ip from name resolution + if (!$ip) { + die "Error: The ip attribute must be set for $n.\n"; + } + } } # Copy softlayer specific systemimager post-install scripts to the systemimager location. # These cause si to use static ip and insert a wait into the bring up of the network. sub copySyscloneFiles { - my $cmd = "cp -f /opt/xcat/share/xcat/sysclone/post-install/* /install/sysclone/scripts/post-install"; - print "Copying SoftLayer-specific post scripts to the SystemImager post-install directory.\n"; - runcmd($cmd); + my $cmd = "cp -f /opt/xcat/share/xcat/sysclone/post-install/* /install/sysclone/scripts/post-install"; + print "Copying SoftLayer-specific post scripts to the SystemImager post-install directory.\n"; + runcmd($cmd); } # Get IP and network of a node sub getNodeIpInfo { - my $node = shift; + my $node = shift; - # get ip for the node - my @output = runcmd("nodels $node hosts.ip"); - chomp($output[0]); - my ($junk, $ip) = split(/\s+/, $output[0]); - #todo: also support getting the ip from name resolution + # get ip for the node + my @output = runcmd("nodels $node hosts.ip"); + chomp($output[0]); + my ($junk, $ip) = split(/\s+/, $output[0]); - # find relevant network in the networks table - # first get the networks in a hash - my %networks; - @output = runcmd("lsdef -t network -ci net,mask,gateway"); - foreach my $line (@output) { - chomp($line); - my ($netname, $attr, $val) = $line =~ m/^(.+):\s+(.+?)=(.+)$/; - $networks{$netname}->{$attr} = $val; - } - # now go thru the networks looking for the correct one - my ($netmask, $gateway); - foreach my $key (keys %networks) { - if (isIPinNet($ip, $networks{$key}->{net}, $networks{$key}->{mask})) { # found it - $netmask = $networks{$key}->{mask}; - $gateway = $networks{$key}->{gateway}; - last; - } - } - if (!$netmask) { die "Error: could not find a network in the networks table that $node $ip is part of.\n"; } - if (!$gateway) { die "Error: gateway not specified in the networks table for the network that $node $ip is part of.\n"; } + #todo: also support getting the ip from name resolution - verbose("IP info for $node: ip=$ip, netmask=$netmask, gateway=$gateway"); - return ($ip, $netmask, $gateway); + # find relevant network in the networks table + # first get the networks in a hash + my %networks; + @output = runcmd("lsdef -t network -ci net,mask,gateway"); + foreach my $line (@output) { + chomp($line); + my ($netname, $attr, $val) = $line =~ m/^(.+):\s+(.+?)=(.+)$/; + $networks{$netname}->{$attr} = $val; + } + + # now go thru the networks looking for the correct one + my ($netmask, $gateway); + foreach my $key (keys %networks) { + if (isIPinNet($ip, $networks{$key}->{net}, $networks{$key}->{mask})) { # found it + $netmask = $networks{$key}->{mask}; + $gateway = $networks{$key}->{gateway}; + last; + } + } + if (!$netmask) { die "Error: could not find a network in the networks table that $node $ip is part of.\n"; } + if (!$gateway) { die "Error: gateway not specified in the networks table for the network that $node $ip is part of.\n"; } + + verbose("IP info for $node: ip=$ip, netmask=$netmask, gateway=$gateway"); + return ($ip, $netmask, $gateway); } # Is the IP in the network/netmask combo sub isIPinNet { - my ($ip, $net, $mask) = @_; - my $ipbin = convert2bin($ip); - my $netbin = convert2bin($net); - my $maskbin = convert2bin($mask); + my ($ip, $net, $mask) = @_; + my $ipbin = convert2bin($ip); + my $netbin = convert2bin($net); + my $maskbin = convert2bin($mask); $ipbin &= $maskbin; - if ($ipbin && $netbin && ($ipbin == $netbin)) { return 1; } - else { return 0; } + if ($ipbin && $netbin && ($ipbin == $netbin)) { return 1; } + else { return 0; } } # Convert dotted decimal format (1.2.3.4) to a binary number sub convert2bin { - my @arr=split(/\./, shift); - my ($bin) = unpack('N', pack('C4',@arr ) ); - return $bin; + my @arr = split(/\./, shift); + my ($bin) = unpack('N', pack('C4', @arr)); + return $bin; } # this is like multi-line sed replace function # Args: filename, search-string, replace-string, options (mode=>{insertbefore,insertafter,replace}) sub sed { - my ($file, $search, $replace, %options) = @_; - #my $opts = 's'; - #if ($options{global}) { $opts .= 'g'; } + my ($file, $search, $replace, %options) = @_; - # open the file for reading - verbose("reading $file"); - open(FILE, $file) || die "Error: can not open file $file for reading: $!\n"; - my $lines; - while () { $lines .= $_; } - #verbose('file length is '.length($lines)); - close FILE; + #my $opts = 's'; + #if ($options{global}) { $opts .= 'g'; } - # we also need to look for this string 1st - my $replacecopy = $replace; # a search string can't have special chars in it - $replacecopy =~ s/(\W)/\\$1/g; # so escape all of the meta characters - #print "replacecopy=$replacecopy\n"; - # check to see if the replace string is already in the file - if ($lines =~ m/$replacecopy/s) { - print "$file did not need updating.\n"; - return 1; - } + # open the file for reading + verbose("reading $file"); + open(FILE, $file) || die "Error: can not open file $file for reading: $!\n"; + my $lines; + while () { $lines .= $_; } - # search/replace and see if there were any matches - my $matches; - if ($options{mode} eq 'insertbefore') { $matches = $lines =~ s/($search)/\n$replace\n$1/s; } - elsif ($options{mode} eq 'insertafter') { $matches = $lines =~ s/($search)/$1\n$replace\n/s; } - elsif ($options{mode} eq 'replace') { $matches = $lines =~ s/$search/$replace/s; } - else { die "Internal error: don't suppor sed mode of $options{mode}.\n"; } + #verbose('file length is '.length($lines)); + close FILE; + + # we also need to look for this string 1st + my $replacecopy = $replace; # a search string can't have special chars in it + $replacecopy =~ s/(\W)/\\$1/g; # so escape all of the meta characters + #print "replacecopy=$replacecopy\n"; + # check to see if the replace string is already in the file + if ($lines =~ m/$replacecopy/s) { + print "$file did not need updating.\n"; + return 1; + } + + # search/replace and see if there were any matches + my $matches; + if ($options{mode} eq 'insertbefore') { $matches = $lines =~ s/($search)/\n$replace\n$1/s; } + elsif ($options{mode} eq 'insertafter') { $matches = $lines =~ s/($search)/$1\n$replace\n/s; } + elsif ($options{mode} eq 'replace') { $matches = $lines =~ s/$search/$replace/s; } + else { die "Internal error: don't suppor sed mode of $options{mode}.\n"; } - # write file if necessary - if ($matches) { - verbose("updating $file"); - open(FILE, '>', $file) || die "Error: can not open file $file for writing: $!\n"; - print FILE $lines; - close FILE; - } - return $matches; + # write file if necessary + if ($matches) { + verbose("updating $file"); + open(FILE, '>', $file) || die "Error: can not open file $file for writing: $!\n"; + print FILE $lines; + close FILE; + } + return $matches; } @@ -376,23 +391,23 @@ sub runcmd my ($cmd) = @_; my $rc; - $cmd .= ' 2>&1' ; + $cmd .= ' 2>&1'; verbose($cmd); - my @output; - if (wantarray) { - @output = `$cmd`; - $rc = $?; - } - else { - system($cmd); - $rc = $?; - } + my @output; + if (wantarray) { + @output = `$cmd`; + $rc = $?; + } + else { + system($cmd); + $rc = $?; + } if ($rc) { $rc = $rc >> 8; - if ($rc > 0) { die "Error: rc $rc return from cmd: $cmd\n"; } - else { die "Error: system error returned from cmd: $cmd\n"; } + if ($rc > 0) { die "Error: rc $rc return from cmd: $cmd\n"; } + else { die "Error: system error returned from cmd: $cmd\n"; } } elsif (wantarray) { return @output; } } diff --git a/xCAT-SoftLayer/xpod2man b/xCAT-SoftLayer/xpod2man index 1ae1f36c3..d867fd448 100755 --- a/xCAT-SoftLayer/xpod2man +++ b/xCAT-SoftLayer/xpod2man @@ -8,17 +8,19 @@ # done relative to that. use strict; + #use lib '.'; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = "$ENV{'HOME'}/tmp"; if (system("mkdir -p $cachedir")) { die "Error: could not create $cachedir.\n"; } my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the cmd overview page. @@ -29,12 +31,12 @@ my @pods = getPodList($poddir); print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } @@ -43,15 +45,17 @@ my @dummyPods = createDummyPods($poddir, \@pods); # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + #print "$podfile, $htmlfile, $poddir, $htmldir\n"; convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -68,73 +72,78 @@ exit; # if that pod does not exist, create an empty one that will satisfy pod2html # keep track of all dummy pods created, so they can be removed later sub createDummyPods { - my ($poddir, $pods) = @_; - my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; - #print "Running cmd: ", $cmd, "\n"; - my @lines = `$cmd`; - if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } - #my @lines; - #system($cmd); - my @dummyPods; - foreach my $l (@lines) { - #print "$l\n"; - my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line - # The above line should create the array with every other entry being the man page name - # and every other entry is the section # (5 or 7) - my $cmd; - while ($cmd=shift @matches) { - #foreach my $m (@matches) { - my $section = shift @matches; - my $filename = "$poddir/man$section/$cmd.$section.pod"; - #print "$filename\n"; - if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } - } - } - - - # Create these empty files - print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; - mkdir "$poddir/man7"; - foreach my $d (@dummyPods) { - if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } - else { close TMP; } - } - - return @dummyPods; + my ($poddir, $pods) = @_; + my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; + + #print "Running cmd: ", $cmd, "\n"; + my @lines = `$cmd`; + if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } + + #my @lines; + #system($cmd); + my @dummyPods; + foreach my $l (@lines) { + + #print "$l\n"; + my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line + # The above line should create the array with every other entry being the man page name + # and every other entry is the section # (5 or 7) + my $cmd; + while ($cmd = shift @matches) { + + #foreach my $m (@matches) { + my $section = shift @matches; + my $filename = "$poddir/man$section/$cmd.$section.pod"; + + #print "$filename\n"; + if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } + } + } + + + # Create these empty files + print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; + mkdir "$poddir/man7"; + foreach my $d (@dummyPods) { + if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } + else { close TMP; } + } + + return @dummyPods; } # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the xcat man page that gives a summary description of each xcat cmd. # Not used. sub writesummarypage { - my $file = shift; # relative path file name of the man page - # the rest of @_ contains the pod files that describe each cmd + my $file = shift; # relative path file name of the man page + # the rest of @_ contains the pod files that describe each cmd - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME B - extreme Cluster Administration Tool. @@ -160,56 +169,58 @@ i.e. all the commands in section 1, then the commands in section 3, etc. =over 12 EOS1 -# extract the summary for each cmd from its man page -foreach my $manpage (@_) { - my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; - # Suck in the whole file, then we will parse it. - open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; - my @contents = ; - my $wholemanpage = join('', @contents); - close(MANPAGE); - # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline - my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; - if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } - if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } - $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off - $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off - print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n".$description."\n"; -} + # extract the summary for each cmd from its man page + foreach my $manpage (@_) { + my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; -# Artificially add the xcattest cmd, because the xCAT-test rpm will add this -print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + # Suck in the whole file, then we will parse it. + open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; + my @contents = ; + my $wholemanpage = join('', @contents); + close(MANPAGE); - print FILE <<"EOS3"; + # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline + my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; + if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } + if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } + $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off + $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off + print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n" . $description . "\n"; + } + + # Artificially add the xcattest cmd, because the xCAT-test rpm will add this + print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + + print FILE <<"EOS3"; =back EOS3 - close FILE; + close FILE; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man1", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man1", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } diff --git a/xCAT-buildkit/bin/buildkit b/xCAT-buildkit/bin/buildkit index 8944b1f49..34521cfaf 100755 --- a/xCAT-buildkit/bin/buildkit +++ b/xCAT-buildkit/bin/buildkit @@ -17,12 +17,12 @@ BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; $::XCATDIR = $ENV{'XCATDIR'} ? $ENV{'XCATDIR'} : '/etc/xcat'; - $::XCATSHARE = $::XCATROOT.'/share/xcat'; + $::XCATSHARE = $::XCATROOT . '/share/xcat'; } if ($^O =~ /^aix/i) { - print "ERROR - the buildkit command is not supported on AIX \n"; - exit 1; + print "ERROR - the buildkit command is not supported on AIX \n"; + exit 1; } use lib "$::XCATROOT/lib/perl"; @@ -37,272 +37,272 @@ use File::Basename; #----------------------------------------------------------------------------- # Main -$::progname = "buildkit"; +$::progname = "buildkit"; $::buildkit_conf = "buildkit.conf"; -$::kit_conf = "kit.conf"; -$::current_dir = cwd(); +$::kit_conf = "kit.conf"; +$::current_dir = cwd(); # this code will build a kit using framework 1. -$::KITFRAMEWORK ="2"; +$::KITFRAMEWORK = "2"; # this code is compatible with other kits that are at framework 0 or 1. $::COMPATIBLE_KITFRAMEWORKS = "0,1,2"; -%::buildkit_def = ( - kit => { basename => { - description=>'The kit base name (e.g., kit-lsf)', - value_desc=>'Must be: Generic Name String', - mandatory=>1, - cp_to_kitconfig=>1}, - description => { - description=>'The kit description', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - version => { - description=>'The kit version (e.g., 9.0)', - value_desc=>'Must be: Generic Name String', - mandatory=>1, - cp_to_kitconfig=>1}, - release => { - description=>'The kit release (e.g., 1)', - value_desc=>'Must be: Generic Name String', - mandatory=>0, - cp_to_kitconfig=>1}, - ostype => { - description=>'The kit OS type (e.g., Linux)', - value_desc=>'Must be: OS Type String', - mandatory=>1, - cp_to_kitconfig=>1}, - osbasename => { - description=>'The kit OS basename', - value_desc=>'Must be: Generic Name String', - mandatory=>0, - cp_to_kitconfig=>0}, - osmajorversion => { - description=>'The kit OS majorversion', - value_desc=>'Must be: Generic Name String', - mandatory=>0, - cp_to_kitconfig=>0}, - osminorversion => { - description=>'The kit OS minorversion', - value_desc=>'Must be: Generic Name String', - mandatory=>0, - cp_to_kitconfig=>0}, - osarch => { - description=>'The kit OS architecture', - value_desc=>'Must be: Generic Name String', - mandatory=>0, - cp_to_kitconfig=>0}, - isinternal=> { - description=>'Flag to say if this Kit is used for internal use only. It is only used for information purposes.', - value_desc=>'Must be: empty string or boolean string', - mandatory=>0, - cp_to_kitconfig=>1}, - kitdeployparams=> { - description=>'The path to the Kit Deployment Parameters file.', - value_desc=>'Must be: empty string or relative path string', - mandatory=>0, - base_dir=>'other_files', - cp_to_kitconfig=>2}, # 2 = rename with KIT_KITNAME_ on cp - kitlicense=> { - description=>'The Kit license string to be built into all kitcomponent packages.', - value_desc=>'any string', - mandatory=>1, - cp_to_kitconfig=>0}, - kittarfilename=> { - description=>'The filename to use for the generated kit.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - vendor=> { - description=>'The Vendor value to use when building the rpms.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - packager=> { - description=>'The Packager value to use when building the rpms.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - url=> { - description=>'The URL value to use when building the rpms.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}}, - kitrepo => {kitrepoid => { - description=>'The Kit Package Repository ID. (e.g., rhels-6.2-x86_64)', - value_desc=>'Must be: Generic Name String, unique in kit', - mandatory=>1, - cp_to_kitconfig=>0}, - osbasename => { - description=>'The OS distro base name (e.g., rhels)', - value_desc=>'Must be OS Name String', - mandatory=>1, - cp_to_kitconfig=>1}, - osmajorversion => { - description=>'The OS distro major version (e.g., 6)', - value_desc=>'Must be Generic Number String', - mandatory=>1, - cp_to_kitconfig=>1}, - osminorversion => { - description=>'The OS distro minor version (e.g., 3)', - value_desc=>'Must be Generic Number String', - mandatory=>0, - cp_to_kitconfig=>1}, - osarch => { - description=>'The OS distro architecture (e.g., x86_64)', - value_desc=>'Must be OS Arch String', - mandatory=>1, - cp_to_kitconfig=>1}, - compat_osbasenames => { - description=>'Comma-separated list of compatible OS base names. ', - value_desc=>'Must be Empty String or list of OS Name Strings', - mandatory=>0, - cp_to_kitconfig=>1} }, - kitcomponent => {basename => { - description=>'The component name. It is used as the meta-package name.', - value_desc=>'any string', - mandatory=>1, - cp_to_kitconfig=>1}, - description => { - description=>'The component description. The description is added to the meta-package.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - version => { - description=>'The component version (e.g., 9.0). It is used as the meta-package version.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - release => { - description=>'The component release number (e.g., 1). It is used as the meta-package release number.', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - serverroles => { - description=>'tbd', - value_desc=>'any string', - mandatory=>1, - cp_to_kitconfig=>1}, - kitrepoid => { - description=>'tbd', - value_desc=>'any string', - mandatory=>1, - cp_to_kitconfig=>0}, - kitcompdeps => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - ospkgdeps => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - kitpkgdeps => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - non_native_pkgs => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - driverpacks => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>1}, - exlist => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - base_dir=>'other_files', - cp_to_kitconfig=>2}, - preinstall => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - postinstall => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - preuninstall => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - postuninstall => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - preupgrade => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - postupgrade => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - postbootscripts => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - base_dir=>'scripts', - cp_to_kitconfig=>2}, - genimage_postinstall => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - base_dir=>'scripts', - cp_to_kitconfig=>2} }, - kitpackage => {filename => { - description=>'tbd', - value_desc=>'any string', - mandatory=>1, - cp_to_kitconfig=>0}, - kitrepoid => { - description=>'tbd', - value_desc=>'any string', - mandatory=>1, - cp_to_kitconfig=>0}, - rpm_spec => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - rpm_srcdir => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - rpm_srctarball => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - rpm_srpm => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - rpm_prebuiltdir => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}, - isexternalpkg => { - description=>'tbd', - value_desc=>'any string', - mandatory=>0, - cp_to_kitconfig=>0}} +%::buildkit_def = ( + kit => { basename => { + description => 'The kit base name (e.g., kit-lsf)', + value_desc => 'Must be: Generic Name String', + mandatory => 1, + cp_to_kitconfig => 1 }, + description => { + description => 'The kit description', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + version => { + description => 'The kit version (e.g., 9.0)', + value_desc => 'Must be: Generic Name String', + mandatory => 1, + cp_to_kitconfig => 1 }, + release => { + description => 'The kit release (e.g., 1)', + value_desc => 'Must be: Generic Name String', + mandatory => 0, + cp_to_kitconfig => 1 }, + ostype => { + description => 'The kit OS type (e.g., Linux)', + value_desc => 'Must be: OS Type String', + mandatory => 1, + cp_to_kitconfig => 1 }, + osbasename => { + description => 'The kit OS basename', + value_desc => 'Must be: Generic Name String', + mandatory => 0, + cp_to_kitconfig => 0 }, + osmajorversion => { + description => 'The kit OS majorversion', + value_desc => 'Must be: Generic Name String', + mandatory => 0, + cp_to_kitconfig => 0 }, + osminorversion => { + description => 'The kit OS minorversion', + value_desc => 'Must be: Generic Name String', + mandatory => 0, + cp_to_kitconfig => 0 }, + osarch => { + description => 'The kit OS architecture', + value_desc => 'Must be: Generic Name String', + mandatory => 0, + cp_to_kitconfig => 0 }, + isinternal => { + description => 'Flag to say if this Kit is used for internal use only. It is only used for information purposes.', + value_desc => 'Must be: empty string or boolean string', + mandatory => 0, + cp_to_kitconfig => 1 }, + kitdeployparams => { + description => 'The path to the Kit Deployment Parameters file.', + value_desc => 'Must be: empty string or relative path string', + mandatory => 0, + base_dir => 'other_files', + cp_to_kitconfig => 2 }, # 2 = rename with KIT_KITNAME_ on cp + kitlicense => { + description => 'The Kit license string to be built into all kitcomponent packages.', + value_desc => 'any string', + mandatory => 1, + cp_to_kitconfig => 0 }, + kittarfilename => { + description => 'The filename to use for the generated kit.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + vendor => { + description => 'The Vendor value to use when building the rpms.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + packager => { + description => 'The Packager value to use when building the rpms.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + url => { + description => 'The URL value to use when building the rpms.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 } }, + kitrepo => { kitrepoid => { + description => 'The Kit Package Repository ID. (e.g., rhels-6.2-x86_64)', + value_desc => 'Must be: Generic Name String, unique in kit', + mandatory => 1, + cp_to_kitconfig => 0 }, + osbasename => { + description => 'The OS distro base name (e.g., rhels)', + value_desc => 'Must be OS Name String', + mandatory => 1, + cp_to_kitconfig => 1 }, + osmajorversion => { + description => 'The OS distro major version (e.g., 6)', + value_desc => 'Must be Generic Number String', + mandatory => 1, + cp_to_kitconfig => 1 }, + osminorversion => { + description => 'The OS distro minor version (e.g., 3)', + value_desc => 'Must be Generic Number String', + mandatory => 0, + cp_to_kitconfig => 1 }, + osarch => { + description => 'The OS distro architecture (e.g., x86_64)', + value_desc => 'Must be OS Arch String', + mandatory => 1, + cp_to_kitconfig => 1 }, + compat_osbasenames => { + description => 'Comma-separated list of compatible OS base names. ', + value_desc => 'Must be Empty String or list of OS Name Strings', + mandatory => 0, + cp_to_kitconfig => 1 } }, + kitcomponent => { basename => { + description => 'The component name. It is used as the meta-package name.', + value_desc => 'any string', + mandatory => 1, + cp_to_kitconfig => 1 }, + description => { + description => 'The component description. The description is added to the meta-package.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + version => { + description => 'The component version (e.g., 9.0). It is used as the meta-package version.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + release => { + description => 'The component release number (e.g., 1). It is used as the meta-package release number.', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + serverroles => { + description => 'tbd', + value_desc => 'any string', + mandatory => 1, + cp_to_kitconfig => 1 }, + kitrepoid => { + description => 'tbd', + value_desc => 'any string', + mandatory => 1, + cp_to_kitconfig => 0 }, + kitcompdeps => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + ospkgdeps => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + kitpkgdeps => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + non_native_pkgs => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + driverpacks => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 1 }, + exlist => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + base_dir => 'other_files', + cp_to_kitconfig => 2 }, + preinstall => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + postinstall => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + preuninstall => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + postuninstall => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + preupgrade => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + postupgrade => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + postbootscripts => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + base_dir => 'scripts', + cp_to_kitconfig => 2 }, + genimage_postinstall => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + base_dir => 'scripts', + cp_to_kitconfig => 2 } }, + kitpackage => { filename => { + description => 'tbd', + value_desc => 'any string', + mandatory => 1, + cp_to_kitconfig => 0 }, + kitrepoid => { + description => 'tbd', + value_desc => 'any string', + mandatory => 1, + cp_to_kitconfig => 0 }, + rpm_spec => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + rpm_srcdir => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + rpm_srctarball => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + rpm_srpm => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + rpm_prebuiltdir => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 }, + isexternalpkg => { + description => 'tbd', + value_desc => 'any string', + mandatory => 0, + cp_to_kitconfig => 0 } } ); @@ -314,15 +314,15 @@ $Getopt::Long::ignorecase = 0; # parse the options if ( !GetOptions( - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, - 'V|verbose' => \$::VERBOSE, - 'n|noprerequisite' => \$::PREREQUISITE, - 'p|pkgdir=s' => \$::PKGDIR, - 'k|kitversion=s' => \$::KITVERSION, - 'r|kitrelease=s' => \$::KITRELEASE, - 'l|kitloc=s' => \$::KITLOC, - 'for=s' => \$::FOROSVERSARCH, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, + 'V|verbose' => \$::VERBOSE, + 'n|noprerequisite' => \$::PREREQUISITE, + 'p|pkgdir=s' => \$::PKGDIR, + 'k|kitversion=s' => \$::KITVERSION, + 'r|kitrelease=s' => \$::KITRELEASE, + 'l|kitloc=s' => \$::KITLOC, + 'for=s' => \$::FOROSVERSARCH, ) ) { @@ -338,9 +338,9 @@ if ($::HELP) } my $debianflag = 0; -my $dpkg_flag = '-uc -us'; +my $dpkg_flag = '-uc -us'; my $tempstring = xCAT::BuildKitUtils->osver(); -if ( $tempstring =~ /debian/ || $tempstring =~ /ubuntu/ ){ +if ($tempstring =~ /debian/ || $tempstring =~ /ubuntu/) { $debianflag = 1; } @@ -352,10 +352,10 @@ if ( $tempstring =~ /debian/ || $tempstring =~ /ubuntu/ ){ # buildkit --for ubuntu buildrepo # buildkit --for ubuntu buildtar if ($::FOROSVERSARCH) { - if ( $::FOROSVERSARCH =~ /debian/ || $::FOROSVERSARCH =~ /ubuntu/ ) { - $debianflag=1; - $dpkg_flag .= ' -A -d'; - } + if ($::FOROSVERSARCH =~ /debian/ || $::FOROSVERSARCH =~ /ubuntu/) { + $debianflag = 1; + $dpkg_flag .= ' -A -d'; + } } # display the version statement if -v or --version is specified @@ -363,16 +363,18 @@ if ($::VERSION) { my $versioncmd = "rpm -q --qf \"%{NAME}: %{VERSION}-%{RELEASE} \n\" xCAT-buildkit"; my $message = "Error quering xCAT-buildkit rpm. Version info is not available. \n"; - if ( $debianflag ){ + if ($debianflag) { $versioncmd = "dpkg-query --show -f='\${binary:Package}: \${Version}\n' xcat-buildkit"; $message = "Error quering xcat-buildkit package. Version info is not available. \n"; } - if ( system($versioncmd) ) { + if (system($versioncmd)) { + # non-zero return from system call print $message; exit 1; - } + } + # add framework info to output print "\tkitframework = $::KITFRAMEWORK\n"; print "\tcompatible_frameworks = $::COMPATIBLE_KITFRAMEWORKS\n"; @@ -380,111 +382,111 @@ if ($::VERSION) exit 0; } -my $arg=shift(@ARGV); -if ( ! $arg ) { - &usage; - exit (0); +my $arg = shift(@ARGV); +if (!$arg) { + &usage; + exit(0); } # set kit location if ($::KITLOC) { - $::workdir = $::KITLOC; - $::current_dir = $::workdir; + $::workdir = $::KITLOC; + $::current_dir = $::workdir; } else { - $::workdir = $::current_dir; + $::workdir = $::current_dir; } -$::full_buildkit_conf = $::workdir."/".$::buildkit_conf; -$::build_dir = $::workdir."/build"; -$::deploy_dir = $::build_dir; #kitname appended by validate_bldkitconf routine -$::base_repodir = $::build_dir."/kit_repodir"; +$::full_buildkit_conf = $::workdir . "/" . $::buildkit_conf; +$::build_dir = $::workdir . "/build"; +$::deploy_dir = $::build_dir; #kitname appended by validate_bldkitconf routine +$::base_repodir = $::build_dir . "/kit_repodir"; while ($arg) { my $command = $arg; - $command =~ tr/A-Z/a-z/; # convert to lowercase - if ( $command eq 'create' ) { - $::KIT_CREATE=shift(@ARGV); + $command =~ tr/A-Z/a-z/; # convert to lowercase + if ($command eq 'create') { + $::KIT_CREATE = shift(@ARGV); if ($::KITLOC) { - $::workdir = dirname($::KITLOC); + $::workdir = dirname($::KITLOC); $::current_dir = $::workdir; } - if ( ! $::KIT_CREATE ) { - print "The Kit basename was not specified for the buildkit create command.\n"; - &usage; - exit 1; + if (!$::KIT_CREATE) { + print "The Kit basename was not specified for the buildkit create command.\n"; + &usage; + exit 1; } - } elsif ( $command eq 'chkconfig' ) { - $::KIT_CHKCONFIG=1; - } elsif ( $command eq 'buildrepo' ) { - $::KIT_BUILDREPO=shift(@ARGV); - if ( ! $::KIT_BUILDREPO ) { - print "The Kit package repository name was not specified for buildkit buildrepo command.\n"; - &usage; - exit 1; + } elsif ($command eq 'chkconfig') { + $::KIT_CHKCONFIG = 1; + } elsif ($command eq 'buildrepo') { + $::KIT_BUILDREPO = shift(@ARGV); + if (!$::KIT_BUILDREPO) { + print "The Kit package repository name was not specified for buildkit buildrepo command.\n"; + &usage; + exit 1; } - } elsif ( $command eq 'listrepo' ) { - $::KIT_LISTREPO=1; - } elsif ( $command eq 'cleanrepo' ) { - $::KIT_CLEANREPO=shift(@ARGV); - if ( ! $::KIT_CLEANREPO ) { - print "kit package repository name not specified for buildkit cleanrepo command \n"; - &usage; - exit 1; + } elsif ($command eq 'listrepo') { + $::KIT_LISTREPO = 1; + } elsif ($command eq 'cleanrepo') { + $::KIT_CLEANREPO = shift(@ARGV); + if (!$::KIT_CLEANREPO) { + print "kit package repository name not specified for buildkit cleanrepo command \n"; + &usage; + exit 1; } - } elsif ( $command eq 'buildtar' ) { - $::KIT_BUILDTAR=1; - } elsif ( $command eq 'cleantar' ) { - $::KIT_CLEANTAR=1; - } elsif ( $command eq 'cleanall' ) { - $::KIT_CLEANALL=1; - } elsif ( $command eq 'addpkgs' ) { - $::KIT_ADDPKGS=shift(@ARGV); - if (!($::KIT_ADDPKGS)){ + } elsif ($command eq 'buildtar') { + $::KIT_BUILDTAR = 1; + } elsif ($command eq 'cleantar') { + $::KIT_CLEANTAR = 1; + } elsif ($command eq 'cleanall') { + $::KIT_CLEANALL = 1; + } elsif ($command eq 'addpkgs') { + $::KIT_ADDPKGS = shift(@ARGV); + if (!($::KIT_ADDPKGS)) { print "Missing parameter: the name must be specified when using the \'buildkit addpkgs\' command.\n"; &usage; - exit (1); + exit(1); } - if (!($::PKGDIR)){ + if (!($::PKGDIR)) { print "Missing option: the -p option must be specified with \'buildkit addpkgs\' command. \n"; &usage; - exit (1); + exit(1); } } else { print "The buildkit command $arg is not recognized.\n"; &usage; - exit (1); - } - $arg=shift(@ARGV); + exit(1); + } + $arg = shift(@ARGV); } my $rc = 0; -if ( $::KIT_CREATE ) { - $rc = &kit_create; +if ($::KIT_CREATE) { + $rc = &kit_create; } -if ( $::KIT_CHKCONFIG ) { - unless ($rc = &kit_chkconfig) { - print "No errors were found in Kit Build File $::full_buildkit_conf. \n"; - } +if ($::KIT_CHKCONFIG) { + unless ($rc = &kit_chkconfig) { + print "No errors were found in Kit Build File $::full_buildkit_conf. \n"; + } } -if ( $::KIT_LISTREPO ) { - unless ($rc = &kit_chkconfig) { $rc = &kit_listrepo; } +if ($::KIT_LISTREPO) { + unless ($rc = &kit_chkconfig) { $rc = &kit_listrepo; } } -if ( $::KIT_BUILDREPO ) { - unless ($rc = &kit_chkconfig) { $rc = &kit_buildrepo; } +if ($::KIT_BUILDREPO) { + unless ($rc = &kit_chkconfig) { $rc = &kit_buildrepo; } } -if ( $::KIT_CLEANREPO ) { - unless ($rc = &kit_chkconfig) { $rc = &kit_cleanrepo; } +if ($::KIT_CLEANREPO) { + unless ($rc = &kit_chkconfig) { $rc = &kit_cleanrepo; } } -if ( $::KIT_BUILDTAR ) { - unless ($rc = &kit_chkconfig) { $rc = &kit_buildtar; } +if ($::KIT_BUILDTAR) { + unless ($rc = &kit_chkconfig) { $rc = &kit_buildtar; } } -if ( $::KIT_CLEANTAR ) { - unless ($rc = &kit_chkconfig) { $rc = &kit_cleantar; } +if ($::KIT_CLEANTAR) { + unless ($rc = &kit_chkconfig) { $rc = &kit_cleantar; } } -if ( $::KIT_CLEANALL ) { - unless ($rc = &kit_chkconfig) { $rc = &kit_cleanall; } +if ($::KIT_CLEANALL) { + unless ($rc = &kit_chkconfig) { $rc = &kit_cleanall; } } -if ( $::KIT_ADDPKGS ) { $rc = &kit_addpkgs; } +if ($::KIT_ADDPKGS) { $rc = &kit_addpkgs; } exit $rc; @@ -503,7 +505,7 @@ exit $rc; #----------------------------------------------------------------------------- sub usage { - print "Usage: + print "Usage: buildkit [-?│-h│--help] [-v│--version] To build a new Kit @@ -564,32 +566,33 @@ sub kit_create { # create Kit directory in pwd - my $kitname=$::KIT_CREATE; + my $kitname = $::KIT_CREATE; my $kitdir; - if ($::KITLOC ) { - $kitdir=$::KITLOC; + if ($::KITLOC) { + $kitdir = $::KITLOC; } else { - $kitdir=$::workdir."/$kitname"; + $kitdir = $::workdir . "/$kitname"; } - if ( -d $kitdir ) { + if (-d $kitdir) { print "Another directory already exists with the name $kitdir. Not able to create new Kit. \n"; exit 1; } - if ( ! mkdir($kitdir) ) { - print "Error creating Kit directory $kitdir. Verify that the current user has privileges to create the directory. \n"; - exit 1; + if (!mkdir($kitdir)) { + print "Error creating Kit directory $kitdir. Verify that the current user has privileges to create the directory. \n"; + exit 1; } # Recursive copy the shipped template directory to the Kit directory - if ( system("cp -fRp $::XCATSHARE/kits/kit_template/* $kitdir") ) { + if (system("cp -fRp $::XCATSHARE/kits/kit_template/* $kitdir")) { + # non-zero return from system call print "Error copying sample Kit template files from $::XCAT_SHARE/kits/kit_template to $kitdir \n"; exit 1; - } + } - if (&edit_bldkitconf($kitdir."/".$::buildkit_conf,$kitname)) { - exit 1; + if (&edit_bldkitconf($kitdir . "/" . $::buildkit_conf, $kitname)) { + exit 1; } print "Kit template for $kitname created in $kitdir directory \n"; @@ -609,16 +612,16 @@ sub kit_create sub kit_chkconfig { - if ( $::CHKCONFIG_DONE ) { return 0; } + if ($::CHKCONFIG_DONE) { return 0; } my $bldkitconf = $::full_buildkit_conf; my $chkrc = &load_bldkitconf($bldkitconf); - if ( $chkrc != 0 ) { return 1; }; + if ($chkrc != 0) { return 1; } $chkrc = &validate_bldkitconf(); - if ( $chkrc != 0 ) { return 1; }; + if ($chkrc != 0) { return 1; } - $::CHKCONFIG_DONE=1; + $::CHKCONFIG_DONE = 1; return 0; } @@ -634,26 +637,27 @@ sub kit_chkconfig sub kit_buildrepo { - my $rc = 0; + my $rc = 0; my $repoid = $::KIT_BUILDREPO; - if ( !$debianflag ){ + if (!$debianflag) { + # Check if createrepo exists or not. Fail at the beginning. #- don't use specific path - may not be correct in build env - my $rcmd = "createrepo -h > /dev/null"; - if ( system( $rcmd ) ) { + my $rcmd = "createrepo -h > /dev/null"; + if (system($rcmd )) { print "Error: the createrepo command does not seem to be installed. Make sure createrepo is installed before running the buildkit command. \n"; return 1; } } $repoid =~ s/\s+//g; - $repoid =~ tr/A-Z/a-z/; # convert to lowercase - if ( $repoid ne 'all' ) { - return &kit_buildrepo1($::KIT_BUILDREPO); + $repoid =~ tr/A-Z/a-z/; # convert to lowercase + if ($repoid ne 'all') { + return &kit_buildrepo1($::KIT_BUILDREPO); } else { - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ( &kit_buildrepo1($kr->{kitrepoid}) ) { return 1; } + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if (&kit_buildrepo1($kr->{kitrepoid})) { return 1; } } } return $rc; @@ -670,59 +674,60 @@ sub kit_buildrepo #----------------------------------------------------------------------------- sub kit_buildrepo1 { - my $rc = 0; + my $rc = 0; my $repoid = shift; $repoid =~ s/\s+//g; my $repodir = $::base_repodir; - my $srcdir = $::workdir."/source_packages/"; + my $srcdir = $::workdir . "/source_packages/"; my $basedir = $repodir; my $repo; - + # find the repo my $found = 0; - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ( $kr->{kitrepoid} eq $repoid ) { + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if ($kr->{kitrepoid} eq $repoid) { $found = 1; - $repo = $kr; - if ( &validate_os($kr)) { + $repo = $kr; + if (&validate_os($kr)) { print "The buildrepo operation will continue, but errors may occur. You may need to run this command on a host with the same OS.\n"; } $repodir .= "/$kr->{kitreponame}"; last; } } - if (! $found) { + if (!$found) { print "The specified Kit Package Repository \"$repoid\" does not exist in the Kit Build File. \n"; return 1; } # Create repo build directory - if ( (! -d $repodir) && (! mkpath($repodir)) ) { - print "Error creating build repository directory $repodir.\n"; - return 1; - } + if ((!-d $repodir) && (!mkpath($repodir))) { + print "Error creating build repository directory $repodir.\n"; + return 1; + } # Build kitpackages first my $kitrepohash; - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - $kitrepohash->{$kr->{kitrepoid}} = $kr->{kitreponame}; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + $kitrepohash->{ $kr->{kitrepoid} } = $kr->{kitreponame}; } - foreach my $kp (@{$::bldkit_config->{kitpackage}{entries}}) { + foreach my $kp (@{ $::bldkit_config->{kitpackage}{entries} }) { + # For this kitrepo? my $found = 0; foreach my $kprid (split(/,/, $kp->{kitrepoid})) { - $kprid =~ s/\s+//g; - if ($repoid eq $kprid) { - $found = 1; - last; - } + $kprid =~ s/\s+//g; + if ($repoid eq $kprid) { + $found = 1; + last; + } } if (!$found) { next; } # is this package already built? my $rpm = "$repodir/$kp->{filename}"; - if ( -r $rpm) { next; } + if (-r $rpm) { next; } my $kprid; my $rpm_built; @@ -730,48 +735,54 @@ sub kit_buildrepo1 if ($repoid eq $kprid) { next; } - if ( (-d "$basedir/$kitrepohash->{$kprid}") and (-f "$basedir/$kitrepohash->{$kprid}/$kp->{filename}") ) { + if ((-d "$basedir/$kitrepohash->{$kprid}") and (-f "$basedir/$kitrepohash->{$kprid}/$kp->{filename}")) { $rpm_built = $kitrepohash->{$kprid}; last; } } - + # determine build method if ($kp->{isexternalpkg} eq 'yes') { - if ($::VERBOSE) { print "skipping build of external kitpackage $kp->{filename} \n";} - next; + if ($::VERBOSE) { print "skipping build of external kitpackage $kp->{filename} \n"; } + next; } else { - if ($::VERBOSE) { print "building kitpackage $kp->{filename} \n";} + if ($::VERBOSE) { print "building kitpackage $kp->{filename} \n"; } } if (defined($kp->{rpm_prebuiltdir})) { - # simply copy the file to the build directory - my $full_prebuiltrpm = $srcdir.$kp->{rpm_prebuiltdir}."/".$kp->{filename}; - if ( $rpm_built ) { + # simply copy the file to the build directory + my $full_prebuiltrpm = $srcdir . $kp->{rpm_prebuiltdir} . "/" . $kp->{filename}; + + if ($rpm_built) { if (system("cd $repodir;ln -sf ../$rpm_built/$kp->{filename} $kp->{filename}")) { + # non-zero return from system call print "Error create symlink for prebuilt rpm $kp->{filename} to Kit Build directory. \n"; return; } } else { if (system("cp -fp $full_prebuiltrpm $repodir")) { + # non-zero return from system call print "Error copying prebuilt rpm $kp->{filename} to Kit Build directory. \n"; return 1; } } } elsif (defined($kp->{rpm_srpm})) { + # run rpmbuild --rebuild on the source rpm print "SKIPPING BUILD FOR KIT PACKAGE $kp->{filename} \n"; print "TBD - only buildrepo for prebuilt rpms is available at this time \n\n"; - } elsif (defined($kp->{rpm_srctarball}) && - defined($kp->{rpm_spec}) ) { + } elsif (defined($kp->{rpm_srctarball}) && + defined($kp->{rpm_spec})) { + # run rpmbuild print "SKIPPING BUILD FOR KIT PACKAGE $kp->{filename} \n"; print "TBD - only buildrepo for prebuilt rpms is available at this time \n\n"; - } elsif (defined($kp->{rpm_srcdir}) && - defined($kp->{rpm_spec}) ) { + } elsif (defined($kp->{rpm_srcdir}) && + defined($kp->{rpm_spec})) { + # build tarfile and run rpmbuild print "SKIPPING BUILD FOR KIT PACKAGE $kp->{filename} \n"; print "TBD - only buildrepo for prebuilt rpms is available at this time \n\n"; @@ -780,37 +791,38 @@ sub kit_buildrepo1 return 1; } } - + # Build kitcomponent preppackages and metapackages - if ( $debianflag ){ - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { + if ($debianflag) { + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { if ($repoid ne $kc->{kitrepoid}) { next; } - my $debname = "$repodir/".&comppkgname($kc); + my $debname = "$repodir/" . &comppkgname($kc); if (-r $debname) { next; } - if ($::VERBOSE) { print "building kitcomponent package for $kc->{basename} \n";} + if ($::VERBOSE) { print "building kitcomponent package for $kc->{basename} \n"; } if (&build_kitcomp_debian($kc)) { print "Error building kitcomponent metapackage for $kc->{basename} \n"; return 1; } } - - if ( system("cd $repodir;dpkg-scanpackages . > Packages") ) { - print "Error building the repository meta-data with the dpkg-scanpackages command \n"; + + if (system("cd $repodir;dpkg-scanpackages . > Packages")) { + print "Error building the repository meta-data with the dpkg-scanpackages command \n"; return 1; } } - else{ - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { - # Check if this kitcomponent is in the requested repo + else { + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + + # Check if this kitcomponent is in the requested repo if ($repoid ne $kc->{kitrepoid}) { next; } - + # Check if already built - my $rpm = "$repodir/".&comppkgname($kc); + my $rpm = "$repodir/" . &comppkgname($kc); if (-r $rpm) { next; } # Build it - if ($::VERBOSE) { print "building kitcomponent metapackage for $kc->{basename} \n";} - if (&build_kitcomp($kc)) { + if ($::VERBOSE) { print "building kitcomponent metapackage for $kc->{basename} \n"; } + if (&build_kitcomp($kc)) { print "Error building kitcomponent metapackage for $kc->{basename} \n"; return 1; } @@ -818,11 +830,11 @@ sub kit_buildrepo1 # run createrepo my $cr_opts = ''; - if (( $repo->{osbasename} =~ m/rh|RH|centos|CentOS/ ) && - ( $repo->{osmajorversion} eq '5') ) { + if (($repo->{osbasename} =~ m/rh|RH|centos|CentOS/) && + ($repo->{osmajorversion} eq '5')) { $cr_opts = '-s md5'; } - if ( system("createrepo $cr_opts $repodir") ) { + if (system("createrepo $cr_opts $repodir")) { print "Error building the repository meta-data with the createrepo command \n"; return 1; } @@ -842,14 +854,14 @@ sub kit_buildrepo1 sub kit_listrepo { # print "Kit Repository: Status \n"; - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - my $rc = 0; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + my $rc = 0; my $status = "NOT DONE"; - unless ($rc = &validate_repo($kr)) {$status = "DONE";} + unless ($rc = &validate_repo($kr)) { $status = "DONE"; } print "$kr->{kitrepoid}: $status \n"; } - return 0; + return 0; } #----------------------------------------------------------------------------- @@ -863,49 +875,49 @@ sub kit_listrepo #----------------------------------------------------------------------------- sub kit_cleanrepo { - my $repoid = $::KIT_CLEANREPO; + my $repoid = $::KIT_CLEANREPO; my $tmp_repoid = $repoid; - $tmp_repoid =~ tr/A-Z/a-z/; # convert to lowercase + $tmp_repoid =~ tr/A-Z/a-z/; # convert to lowercase if (($tmp_repoid eq 'all') && - -d $::base_repodir ) { - if ( system("rm -Rf $::base_repodir ") ) { - print "Error removing contents of $::base_repodir \n"; - return 1; - } else { - print "Contents of $::base_repodir has been successfully removed. \n"; - } + -d $::base_repodir) { + if (system("rm -Rf $::base_repodir ")) { + print "Error removing contents of $::base_repodir \n"; + return 1; + } else { + print "Contents of $::base_repodir has been successfully removed. \n"; + } } else { my $got_one = 0; - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ($repoid eq $kr->{kitrepoid}) { - my $repodir = $::base_repodir.'/'.$kr->{kitreponame}; - if ( -d $repodir ){ - if ( system("rm -Rf $repodir ") ) { - print "Error removing directory $repodir \n"; - return 1; - } else { - print "Kit repository $kr->{kitrepoid} has been removed. \n"; - } - } else { - print "Kit repository $kr->{kitrepoid} directory $repodir does not exist. Nothing to remove for this repository. \n"; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if ($repoid eq $kr->{kitrepoid}) { + my $repodir = $::base_repodir . '/' . $kr->{kitreponame}; + if (-d $repodir) { + if (system("rm -Rf $repodir ")) { + print "Error removing directory $repodir \n"; + return 1; + } else { + print "Kit repository $kr->{kitrepoid} has been removed. \n"; + } + } else { + print "Kit repository $kr->{kitrepoid} directory $repodir does not exist. Nothing to remove for this repository. \n"; + } + $got_one = 1; + last; } - $got_one = 1; - last; - } } - if ( !$got_one ) { + if (!$got_one) { print "Kit repository $repoid does not exist.\n"; return 1; } } - if ( -d "$::workdir/rpmbuild" ) { - system("rm -Rf $::workdir/rpmbuild "); + if (-d "$::workdir/rpmbuild") { + system("rm -Rf $::workdir/rpmbuild "); } - if ( -d "$::workdir/tmp" ) { + if (-d "$::workdir/tmp") { system("rm -Rf $::workdir/tmp "); } - if ( -d "$::workdir/debbuild" ){ + if (-d "$::workdir/debbuild") { system("rm -Rf $::workdir/debbuild"); } @@ -923,7 +935,7 @@ sub kit_cleanrepo #----------------------------------------------------------------------------- sub kit_buildtar { - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { if (&validate_repo($kr)) { print "Kit Repository $kr->{kitrepoid} not built. Run: \n"; print " buildkit buildrepo $kr->{kitrepoid} \n"; @@ -936,7 +948,7 @@ sub kit_buildtar return 1; } - if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { + if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { if (&create_PARTIAL_builddir) { print "Error creating PARTIAL kit build directory contents \n"; return 1; @@ -948,86 +960,88 @@ sub kit_buildtar } } - if (! -d "$::deploy_dir/repos") { - symlink "$::build_dir/kit_repodir","$::deploy_dir/repos"; + if (!-d "$::deploy_dir/repos") { + symlink "$::build_dir/kit_repodir", "$::deploy_dir/repos"; } # build the tarfile my $extpkgs = ''; - if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { - $extpkgs = '.NEED_PRODUCT_PKGS'; + if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { + $extpkgs = '.NEED_PRODUCT_PKGS'; } - my $kitname = $::bldkit_config->{kit}{entries}[0]->{kitname}; + my $kitname = $::bldkit_config->{kit}{entries}[0]->{kitname}; my $kitfilename = $kitname; - if ( defined($::bldkit_config->{kit}{entries}[0]->{kittarfilename}) ) { + if (defined($::bldkit_config->{kit}{entries}[0]->{kittarfilename})) { $kitfilename = $::bldkit_config->{kit}{entries}[0]->{kittarfilename}; $kitfilename =~ s/tar\.bz2\s*$//; } - $kitfilename = $kitfilename.$extpkgs.".tar.bz2"; + $kitfilename = $kitfilename . $extpkgs . ".tar.bz2"; - my $tarfile = $::deploy_dir."/".$kitfilename; + my $tarfile = $::deploy_dir . "/" . $kitfilename; - my $dir = dirname($::deploy_dir); - my $bidir = "$dir/build_input"; + my $dir = dirname($::deploy_dir); + my $bidir = "$dir/build_input"; #It is for partial kit. if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { - if ( -d "$bidir") { - if ( system("cd $::deploy_dir; cd ..; cp -r build_input $kitname" ) ) { - print "Error: Could not copy building tarfile $tarfile \n"; - return 1; + if (-d "$bidir") { + if (system("cd $::deploy_dir; cd ..; cp -r build_input $kitname")) { + print "Error: Could not copy building tarfile $tarfile \n"; + return 1; } } } else { - #If it is complete kit and there is build_input directory in deploy_dir - #If there is tmp rpmbuild source_packages - #delete them from complete kit build_input - if ( -d "$bidir") { - if (system("cd $::deploy_dir; cd ..; rm -fr build_input/tmp" )){ - print "Error:Could not delete build_input/tmp \n"; - } - if (system("cd $::deploy_dir; cd ..; rm -fr build_input/rpmbuild" )){ - print "Error:Could not delete build_input/tmp \n"; - } - if (system("cd $::deploy_dir; cd ..; rm -fr build_input/source_packages" )){ - print "Error:Could not delete build_input/source_packages \n"; - } - if (system("cd $::deploy_dir; cd ..; cp -fr build_input $kitname")){ - print "Error: Could not copy building tarfile $tarfile \n"; - return 1; - } - } else{ - #If kit build dir is new created - #partial kit is never created before - #make sure there is build_input dir in complete kit dir - if (system("cd $::deploy_dir; mkdir -p build_input" )){ - print "Error creating kit build directory contents \n"; - return 1; - } - if (system("cd $::deploy_dir; cp -fp $::workdir/buildkit.conf build_input" )){ - print "Error creating kit build directory contents \n"; - return 1; - } - if (system("cd $::deploy_dir; cp -frp $::workdir/other_files build_input" )){ - print "Error creating kit build directory contents \n"; - return 1; - } - if (system("cd $::deploy_dir; cp -frp $::workdir/plugins build_input" )){ - print "Error creating kit build directory contents \n"; - return 1; - } - if (system("cd $::deploy_dir; cp -frp $::workdir/scripts build_input" )){ - print "Error creating kit build directory contents \n"; - return 1; - } - } + + #If it is complete kit and there is build_input directory in deploy_dir + #If there is tmp rpmbuild source_packages + #delete them from complete kit build_input + if (-d "$bidir") { + if (system("cd $::deploy_dir; cd ..; rm -fr build_input/tmp")) { + print "Error:Could not delete build_input/tmp \n"; + } + if (system("cd $::deploy_dir; cd ..; rm -fr build_input/rpmbuild")) { + print "Error:Could not delete build_input/tmp \n"; + } + if (system("cd $::deploy_dir; cd ..; rm -fr build_input/source_packages")) { + print "Error:Could not delete build_input/source_packages \n"; + } + if (system("cd $::deploy_dir; cd ..; cp -fr build_input $kitname")) { + print "Error: Could not copy building tarfile $tarfile \n"; + return 1; + } + } else { + + #If kit build dir is new created + #partial kit is never created before + #make sure there is build_input dir in complete kit dir + if (system("cd $::deploy_dir; mkdir -p build_input")) { + print "Error creating kit build directory contents \n"; + return 1; + } + if (system("cd $::deploy_dir; cp -fp $::workdir/buildkit.conf build_input")) { + print "Error creating kit build directory contents \n"; + return 1; + } + if (system("cd $::deploy_dir; cp -frp $::workdir/other_files build_input")) { + print "Error creating kit build directory contents \n"; + return 1; + } + if (system("cd $::deploy_dir; cp -frp $::workdir/plugins build_input")) { + print "Error creating kit build directory contents \n"; + return 1; + } + if (system("cd $::deploy_dir; cp -frp $::workdir/scripts build_input")) { + print "Error creating kit build directory contents \n"; + return 1; + } + } } print "Creating tar file $::current_dir/$kitfilename.\n"; - if ( system("cd $::deploy_dir; cd ..; tar -cjhf $tarfile $kitname/*") ) { - print "Error building tarfile $tarfile \n"; - return 1; + if (system("cd $::deploy_dir; cd ..; tar -cjhf $tarfile $kitname/*")) { + print "Error building tarfile $tarfile \n"; + return 1; } system("mv $tarfile $::current_dir"); @@ -1053,47 +1067,50 @@ sub kit_buildtar sub kit_cleantar { my $basename = $::bldkit_config->{kit}{entries}[0]->{basename}; - my $rmfiles = "$basename\*tar.bz2"; + my $rmfiles = "$basename\*tar.bz2"; my $tarfile = "$::workdir/$rmfiles"; - if ( $rmfiles ) { - if ( system("rm -f $tarfile ") ) { + if ($rmfiles) { + if (system("rm -f $tarfile ")) { print "Error removing kit tar files in $::workdir.\n"; } else { print "Kit tar files have been successfully removed from $::workdir.\n"; } } - if ( -d $::deploy_dir ) { - if ( system("rm -Rf $::deploy_dir ") ) { + if (-d $::deploy_dir) { + if (system("rm -Rf $::deploy_dir ")) { print "Error removing contents of $::deploy_dir \n"; } else { print "Removed $::deploy_dir.\n"; } } - if ( -d "$::workdir/rpmbuild" ) { - if ( system("rm -Rf $::workdir/rpmbuild ")) { - # print "Error removing $::workdir/rpmbuild\n"; + if (-d "$::workdir/rpmbuild") { + if (system("rm -Rf $::workdir/rpmbuild ")) { + + # print "Error removing $::workdir/rpmbuild\n"; } else { print "Removed $::workdir/rpmbuild\n"; } } - if ( -d "$::workdir/tmp" ) { - if ( system("rm -Rf $::workdir/tmp ") ) { - # print "Error removing $::workdir/tmp \n"; + if (-d "$::workdir/tmp") { + if (system("rm -Rf $::workdir/tmp ")) { + + # print "Error removing $::workdir/tmp \n"; } else { print "Removed $::workdir/tmp \n"; } } - if ( -d "$::workdir/debbuild" ){ - if ( system("rm -Rf $::workdir/debbuild")) { - # print "Error removing $::workdir/debbuild.\n"; + if (-d "$::workdir/debbuild") { + if (system("rm -Rf $::workdir/debbuild")) { + + # print "Error removing $::workdir/debbuild.\n"; } else { print "Removed $::workdir/debbuild\n"; } } - return 0; + return 0; } #----------------------------------------------------------------------------- @@ -1111,20 +1128,20 @@ sub kit_cleanall &kit_cleantar; - if ( -d $::build_dir ) { - if ( system("rm -Rf $::build_dir/* ") ) { + if (-d $::build_dir) { + if (system("rm -Rf $::build_dir/* ")) { print "Error removing contents of $::build_dir \n"; } else { print "All $::build_dir contents have been successfully removed \n"; } } - if ( -d "$::workdir/rpmbuild" ) { + if (-d "$::workdir/rpmbuild") { system("rm -Rf $::workdir/rpmbuild "); } - if ( -d "$::workdir/tmp" ) { + if (-d "$::workdir/tmp") { system("rm -Rf $::workdir/tmp "); } - if ( -d "$::workdir/debbuild" ){ + if (-d "$::workdir/debbuild") { system("rm -Rf $::workdir/debbuild"); } @@ -1143,12 +1160,12 @@ sub kit_cleanall sub edit_bldkitconf { my $bldkitconf = shift; - my $kitname = shift; + my $kitname = shift; # read in the buildkit.conf file my $CF; - unless ( open( $CF, "<", $bldkitconf ) ) { - print "The Kit build file $bldkitconf does not exist. \n"; + unless (open($CF, "<", $bldkitconf)) { + print "The Kit build file $bldkitconf does not exist. \n"; return 1; } if ($::VERBOSE) { @@ -1157,20 +1174,20 @@ sub edit_bldkitconf my @lines = <$CF>; close $CF; - my $osinfo = xCAT::BuildKitUtils->osver(); + my $osinfo = xCAT::BuildKitUtils->osver(); my $kitrepoid = $osinfo; $kitrepoid =~ s/\,//; - my ($osbasename,$osmore) = split(/\,/, $osinfo); - my ($osmajorversion,$osminorversion) = split(/\./, $osmore); - my $osarch=`uname -p`; - chomp($osarch); - my $kitcomponent_basename = $kitname."_compute"; + my ($osbasename, $osmore) = split(/\,/, $osinfo); + my ($osmajorversion, $osminorversion) = split(/\./, $osmore); + my $osarch = `uname -p`; + chomp($osarch); + my $kitcomponent_basename = $kitname . "_compute"; - if ($debianflag==1) { - if($osarch eq "ppc64le"){ - $osarch="ppc64el"; - } - $kitcomponent_basename = $kitname."-compute"; + if ($debianflag == 1) { + if ($osarch eq "ppc64le") { + $osarch = "ppc64el"; + } + $kitcomponent_basename = $kitname . "-compute"; } for (@lines) { @@ -1181,17 +1198,17 @@ sub edit_bldkitconf s/<<>>/$osminorversion/; s/<<>>/$osarch/; s/<<>>/$kitcomponent_basename/; - if ($debianflag){ + if ($debianflag) { s/(filename=.*?)\-(.*)\.noarch\.rpm/$1_$2_all.deb/; } - if ($osbasename =~ /rh/){ + if ($osbasename =~ /rh/) { s/.*<<>>/ compat_osbasenames=centos/; } } # Write the buildkit.conf back out my $NCF; - unless ( open( $NCF, ">$bldkitconf" ) ) { + unless (open($NCF, ">$bldkitconf")) { return 1; } if ($::VERBOSE) { @@ -1199,7 +1216,7 @@ sub edit_bldkitconf } print $NCF @lines; close($NCF); - + return 0; } @@ -1216,11 +1233,11 @@ sub edit_bldkitconf sub load_bldkitconf { my $bldkitconf = shift; - + # read in the buildkit.conf file my $CF; - unless ( open( $CF, "<", $bldkitconf ) ) { - print "The Kit build file $bldkitconf does not exist in the current directory. \n"; + unless (open($CF, "<", $bldkitconf)) { + print "The Kit build file $bldkitconf does not exist in the current directory. \n"; return 1; } if ($::VERBOSE) { @@ -1232,73 +1249,74 @@ sub load_bldkitconf my $current_section = 'no section'; my %current_entry; my $syntax_error = ''; - my $bad_line = ''; - my $line_number = 0; + my $bad_line = ''; + my $line_number = 0; foreach my $l (@lines) { $line_number++; + # skip blank and comment lines - next if ( $l =~ /^\s*$/ || $l =~ /^\s*#/ ); + next if ($l =~ /^\s*$/ || $l =~ /^\s*#/); # process a real line # new section? - if ( $l =~ /^\s*(\w+)\s*:/ ) { - my $section = $1; - if ( defined( $::buildkit_def{$section} ) ) { - if (($section eq 'kit') && - ($::bldkit_config->{$section}{'exists'})) { - $syntax_error = "More than one \"$section:\" section exists "; - $bad_line = $l; - last; - } - $::bldkit_config->{$section}{'exists'} = 1; - push ( @{ $::bldkit_config->{$current_section}{'entries'} }, {%current_entry}); - $current_section = $section; - undef %current_entry; - next; - } + if ($l =~ /^\s*(\w+)\s*:/) { + my $section = $1; + if (defined($::buildkit_def{$section})) { + if (($section eq 'kit') && + ($::bldkit_config->{$section}{'exists'})) { + $syntax_error = "More than one \"$section:\" section exists "; + $bad_line = $l; + last; + } + $::bldkit_config->{$section}{'exists'} = 1; + push(@{ $::bldkit_config->{$current_section}{'entries'} }, {%current_entry}); + $current_section = $section; + undef %current_entry; + next; + } } - if ( $l =~ /^\s*(\w+)\s*=\s*(.*)\s*/ ) { - my $attr = $1; - my $val = $2; + if ($l =~ /^\s*(\w+)\s*=\s*(.*)\s*/) { + my $attr = $1; + my $val = $2; my $orig_attr = $attr; my $orig_val = $val; $attr =~ s/^\s*//; # Remove any leading whitespace $attr =~ s/\s*$//; # Remove any trailing whitespace $attr =~ tr/A-Z/a-z/; # Convert to lowercase - $val =~ s/^\s*//; - $val =~ s/\s*$//; + $val =~ s/^\s*//; + $val =~ s/\s*$//; - if ( defined( $::buildkit_def{$current_section}{$attr} ) ) { - if ( $val ne '') { $current_entry{$attr} = $val; } + if (defined($::buildkit_def{$current_section}{$attr})) { + if ($val ne '') { $current_entry{$attr} = $val; } } else { - if ( $current_section eq 'no section' ) { - $syntax_error = "No section specified for attribute $attr."; + if ($current_section eq 'no section') { + $syntax_error = "No section specified for attribute $attr."; } else { - my $valid_attrs = join (', ', (keys (%{$::buildkit_def{$current_section}}))); + my $valid_attrs = join(', ', (keys(%{ $::buildkit_def{$current_section} }))); $syntax_error = "Attribute \"$attr\" is not valid for section \"$current_section\". Valid attributes are: $valid_attrs.\n"; } $bad_line = $l; last; - } + } } else { $syntax_error = "Invalid line format"; - $bad_line = $l; + $bad_line = $l; last; - + } } # Need at least one kit and one kitrepo section - if (! $syntax_error) { - if ( !($::bldkit_config->{'kit'}{'exists'})) { + if (!$syntax_error) { + if (!($::bldkit_config->{'kit'}{'exists'})) { $syntax_error = "No \"kit:\" section found. At least one section required. "; $bad_line = ''; - } elsif ( !($::bldkit_config->{'kitrepo'}{'exists'})) { + } elsif (!($::bldkit_config->{'kitrepo'}{'exists'})) { $syntax_error = "No \"kitrepo:\" section found. At least one section required. "; $bad_line = ''; } else { - push ( @{ $::bldkit_config->{$current_section}{'entries'} }, {%current_entry}); + push(@{ $::bldkit_config->{$current_section}{'entries'} }, {%current_entry}); } } @@ -1325,20 +1343,20 @@ sub load_bldkitconf # Check for mandatory attributes foreach my $s (keys %{$::bldkit_config}) { - if (! defined($::buildkit_def{$s}) ) { next;} - foreach my $se (@{$::bldkit_config->{$s}{entries}}) { - foreach my $a (keys %{$::buildkit_def{$s}}) { - if (( $::buildkit_def{$s}{$a}->{mandatory} ) && - ( ! defined ($se->{$a}) ) ) { - print "The \"$a\" mandatory attribute must be defined in the \"$s\" section of the Kit build file \n"; - return 1; - } + if (!defined($::buildkit_def{$s})) { next; } + foreach my $se (@{ $::bldkit_config->{$s}{entries} }) { + foreach my $a (keys %{ $::buildkit_def{$s} }) { + if (($::buildkit_def{$s}{$a}->{mandatory}) && + (!defined($se->{$a}))) { + print "The \"$a\" mandatory attribute must be defined in the \"$s\" section of the Kit build file \n"; + return 1; + } + } } - } } -#use Data::Dumper; -#print Dumper($::bldkit_config); + #use Data::Dumper; + #print Dumper($::bldkit_config); return 0; } @@ -1354,86 +1372,86 @@ sub load_bldkitconf #----------------------------------------------------------------------------- sub validate_bldkitconf { - my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; + my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; my $full_kitname = $kitname; - $full_kitname .= '-'.$::bldkit_config->{kit}{entries}[0]->{version}; + $full_kitname .= '-' . $::bldkit_config->{kit}{entries}[0]->{version}; if (defined($::bldkit_config->{kit}{entries}[0]->{release})) { - $full_kitname .= '-'.$::bldkit_config->{kit}{entries}[0]->{release}; + $full_kitname .= '-' . $::bldkit_config->{kit}{entries}[0]->{release}; } my $short_kitname = $full_kitname; if (defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) { - $full_kitname .= '-'.$::bldkit_config->{kit}{entries}[0]->{osbasename}; + $full_kitname .= '-' . $::bldkit_config->{kit}{entries}[0]->{osbasename}; } if (defined($::bldkit_config->{kit}{entries}[0]->{osmajorversion})) { - if ( ! defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) { - print "Error: Kit osmajorversion attribute was specified but Kit osbasename was not set. \n"; - return 1; - } - $full_kitname .= '-'.$::bldkit_config->{kit}{entries}[0]->{osmajorversion}; + if (!defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) { + print "Error: Kit osmajorversion attribute was specified but Kit osbasename was not set. \n"; + return 1; + } + $full_kitname .= '-' . $::bldkit_config->{kit}{entries}[0]->{osmajorversion}; } if (defined($::bldkit_config->{kit}{entries}[0]->{osminorversion})) { - if ( ( ! defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) || - ( ! defined($::bldkit_config->{kit}{entries}[0]->{osmajorversion}))) { - print "Error: Kit osminorversion attribute was specified but either Kit osbasename or Kit osmajorversion were not set. \n"; - return 1; - } - $full_kitname .= '-'.$::bldkit_config->{kit}{entries}[0]->{osminorversion}; + if ((!defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) || + (!defined($::bldkit_config->{kit}{entries}[0]->{osmajorversion}))) { + print "Error: Kit osminorversion attribute was specified but either Kit osbasename or Kit osmajorversion were not set. \n"; + return 1; + } + $full_kitname .= '-' . $::bldkit_config->{kit}{entries}[0]->{osminorversion}; } if (defined($::bldkit_config->{kit}{entries}[0]->{osarch})) { - $full_kitname .= '-'.$::bldkit_config->{kit}{entries}[0]->{osarch}; + $full_kitname .= '-' . $::bldkit_config->{kit}{entries}[0]->{osarch}; } $::bldkit_config->{kit}{entries}[0]->{kitname} = $full_kitname; - $::deploy_dir .= "/".$full_kitname; + $::deploy_dir .= "/" . $full_kitname; # Make sure each kit kitdeployparams file exists - if (defined($::bldkit_config->{kit}{entries}[0]->{kitdeployparams})){ - my $kd_file = $::workdir."/other_files/".$::bldkit_config->{kit}{entries}[0]->{kitdeployparams}; - if (! -r $kd_file ) { - print "Kit Deployment Parameters file $kd_file does not exist or is not readable\n"; - return 1; - } - if (&edit_deployparams($kd_file,1)) { return 1;} + if (defined($::bldkit_config->{kit}{entries}[0]->{kitdeployparams})) { + my $kd_file = $::workdir . "/other_files/" . $::bldkit_config->{kit}{entries}[0]->{kitdeployparams}; + if (!-r $kd_file) { + print "Kit Deployment Parameters file $kd_file does not exist or is not readable\n"; + return 1; + } + if (&edit_deployparams($kd_file, 1)) { return 1; } } - + # Make sure each kitrepo has unique distro info - my $kr_count = scalar @{$::bldkit_config->{kitrepo}{entries}}; + my $kr_count = scalar @{ $::bldkit_config->{kitrepo}{entries} }; if ($kr_count > 1) { - foreach my $kri (0..$kr_count-2) { - foreach my $kri2 ($kri+1..$kr_count-1) { - my $kr = $::bldkit_config->{kitrepo}{entries}[$kri]; - my $kr2 = $::bldkit_config->{kitrepo}{entries}[$kri2]; - if ( $kr->{kitrepoid} eq $kr2->{kitrepoid} ) { - print "There are two or more kitrepo sections with the same kitrepoid \"$kr->{kitrepoid}\". \n"; - return 1; - } - if ( ($kr->{osbasename} eq $kr2->{osbasename}) && - ($kr->{osmajorversion} eq $kr2->{osmajorversion}) && - ($kr->{osarch} eq $kr2->{osarch}) ) { - if( ( defined ($kr->{osminorversion}) && - defined ($kr2->{osminorversion}) && - ($kr->{osminorversion} eq $kr2->{osminorversion}) ) || - ( ! defined ($kr->{osminorversion}) && - ! defined ($kr2->{osminorversion}) ) ) { - print "There are two or more kitrepo sections which are defined with the same OS name, major/minor version, and architecture. \n"; + foreach my $kri (0 .. $kr_count - 2) { + foreach my $kri2 ($kri + 1 .. $kr_count - 1) { + my $kr = $::bldkit_config->{kitrepo}{entries}[$kri]; + my $kr2 = $::bldkit_config->{kitrepo}{entries}[$kri2]; + if ($kr->{kitrepoid} eq $kr2->{kitrepoid}) { + print "There are two or more kitrepo sections with the same kitrepoid \"$kr->{kitrepoid}\". \n"; return 1; - } + } + if (($kr->{osbasename} eq $kr2->{osbasename}) && + ($kr->{osmajorversion} eq $kr2->{osmajorversion}) && + ($kr->{osarch} eq $kr2->{osarch})) { + if ((defined($kr->{osminorversion}) && + defined($kr2->{osminorversion}) && + ($kr->{osminorversion} eq $kr2->{osminorversion})) || + (!defined($kr->{osminorversion}) && + !defined($kr2->{osminorversion}))) { + print "There are two or more kitrepo sections which are defined with the same OS name, major/minor version, and architecture. \n"; + return 1; + } + } } - } } } - - # Kitcomponent version/release are now optional - + + # Kitcomponent version/release are now optional - # default to kit version/release - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { - if (! defined($kc->{version})) { - $kc->{version} = $::bldkit_config->{kit}{entries}[0]->{version}; + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + if (!defined($kc->{version})) { + $kc->{version} = $::bldkit_config->{kit}{entries}[0]->{version}; } - if (! defined($kc->{release})) { - if (! defined($::bldkit_config->{kit}{entries}[0]->{release})) { + if (!defined($kc->{release})) { + if (!defined($::bldkit_config->{kit}{entries}[0]->{release})) { print "Kitcomponent $kc->{basename} does not have a release specified and there is no Kit release value set to use as a default. \n"; return 1; } else { - $kc->{release} = $::bldkit_config->{kit}{entries}[0]->{release}; + $kc->{release} = $::bldkit_config->{kit}{entries}[0]->{release}; } } @@ -1441,350 +1459,360 @@ sub validate_bldkitconf # Make sure each kitcomponent has unique basename/repoid # If same basename, make sure version/release are same, too - my $kc_count = scalar @{$::bldkit_config->{kitcomponent}{entries}}; + my $kc_count = scalar @{ $::bldkit_config->{kitcomponent}{entries} }; if ($kc_count > 1) { - foreach my $kci (0..$kc_count-2) { - foreach my $kci2 ($kci+1..$kc_count-1) { - if ( $::bldkit_config->{kitcomponent}{entries}[$kci]->{basename} - eq $::bldkit_config->{kitcomponent}{entries}[$kci2]->{basename} ) { - if ( $::bldkit_config->{kitcomponent}{entries}[$kci]->{kitrepoid} - eq $::bldkit_config->{kitcomponent}{entries}[$kci2]->{kitrepoid} ) { + foreach my $kci (0 .. $kc_count - 2) { + foreach my $kci2 ($kci + 1 .. $kc_count - 1) { + if ($::bldkit_config->{kitcomponent}{entries}[$kci]->{basename} + eq $::bldkit_config->{kitcomponent}{entries}[$kci2]->{basename}) { + if ($::bldkit_config->{kitcomponent}{entries}[$kci]->{kitrepoid} + eq $::bldkit_config->{kitcomponent}{entries}[$kci2]->{kitrepoid}) { - print "Two or more kitcomponents are defined with the same basename \"$::bldkit_config->{kitcomponent}{entries}[$kci]->{basename}\" and the same repoid \"$::bldkit_config->{kitcomponent}{entries}[$kci]->{kitrepoid}\". \n"; - return 1; - } - if ( ($::bldkit_config->{kitcomponent}{entries}[$kci]->{version} - ne $::bldkit_config->{kitcomponent}{entries}[$kci2]->{version}) || - ($::bldkit_config->{kitcomponent}{entries}[$kci]->{release} - ne $::bldkit_config->{kitcomponent}{entries}[$kci2]->{release}) - ) { - print "Two or more kitcomponents are defined with the same basename \"$::bldkit_config->{kitcomponent}{entries}[$kci]->{basename}\" but with different version or release. \n"; - return 1; - } + print "Two or more kitcomponents are defined with the same basename \"$::bldkit_config->{kitcomponent}{entries}[$kci]->{basename}\" and the same repoid \"$::bldkit_config->{kitcomponent}{entries}[$kci]->{kitrepoid}\". \n"; + return 1; + } + if (($::bldkit_config->{kitcomponent}{entries}[$kci]->{version} + ne $::bldkit_config->{kitcomponent}{entries}[$kci2]->{version}) || + ($::bldkit_config->{kitcomponent}{entries}[$kci]->{release} + ne $::bldkit_config->{kitcomponent}{entries}[$kci2]->{release}) + ) { + print "Two or more kitcomponents are defined with the same basename \"$::bldkit_config->{kitcomponent}{entries}[$kci]->{basename}\" but with different version or release. \n"; + return 1; + } + } } - } } } - + # Kitrepo checks - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { my $reponame = $short_kitname; - if ((defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) && + if ((defined($::bldkit_config->{kit}{entries}[0]->{osbasename})) && ($::bldkit_config->{kit}{entries}[0]->{osbasename} ne - $kr->{osbasename} ) ) { + $kr->{osbasename})) { print "Warning: Kit osbasename is set to \"$::bldkit_config->{kit}{entries}[0]->{osbasename}\", but this does not match kitrepo $kr->{kitrepoid} osbasename \"$kr->{osbasename}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; } - $reponame .= '-'.$kr->{osbasename}; - if ( (defined($::bldkit_config->{kit}{entries}[0]->{osmajorversion})) && - ($::bldkit_config->{kit}{entries}[0]->{osmajorversion} ne - $kr->{osmajorversion} ) ) { - print "Warning: Kit osmajorversion is set to \"$::bldkit_config->{kit}{entries}[0]->{osmajorversion}\", but this does not match kitrepo $kr->{kitrepoid} osmajorversion \"$kr->{osmajorversion}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; - } - $reponame .= '-'.$kr->{osmajorversion}; - if (defined($kr->{osminorversion})){ - if ( (defined($::bldkit_config->{kit}{entries}[0]->{osminorversion})) && - ($::bldkit_config->{kit}{entries}[0]->{osminorversion} ne - $kr->{osminorversion} ) ) { - print "Warning: Kit osminorversion is set to \"$::bldkit_config->{kit}{entries}[0]->{osminorversion}\", but this does not match kitrepo $kr->{kitrepoid} osminorversion \"$kr->{osminorversion}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; - } - $reponame .= '.'.$kr->{osminorversion}; + $reponame .= '-' . $kr->{osbasename}; + if ((defined($::bldkit_config->{kit}{entries}[0]->{osmajorversion})) && + ($::bldkit_config->{kit}{entries}[0]->{osmajorversion} ne + $kr->{osmajorversion})) { + print "Warning: Kit osmajorversion is set to \"$::bldkit_config->{kit}{entries}[0]->{osmajorversion}\", but this does not match kitrepo $kr->{kitrepoid} osmajorversion \"$kr->{osmajorversion}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; } - if ( (defined($::bldkit_config->{kit}{entries}[0]->{osarch})) && - ($::bldkit_config->{kit}{entries}[0]->{osarch} ne - $kr->{osarch} ) ) { - print "Warning: Kit osarch is set to \"$::bldkit_config->{kit}{entries}[0]->{osarch}\", but this does not match kitrepo $kr->{kitrepoid} osarch \"$kr->{osarch}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; + $reponame .= '-' . $kr->{osmajorversion}; + if (defined($kr->{osminorversion})) { + if ((defined($::bldkit_config->{kit}{entries}[0]->{osminorversion})) && + ($::bldkit_config->{kit}{entries}[0]->{osminorversion} ne + $kr->{osminorversion})) { + print "Warning: Kit osminorversion is set to \"$::bldkit_config->{kit}{entries}[0]->{osminorversion}\", but this does not match kitrepo $kr->{kitrepoid} osminorversion \"$kr->{osminorversion}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; + } + $reponame .= '.' . $kr->{osminorversion}; } - $reponame .= '-'.$kr->{osarch}; + if ((defined($::bldkit_config->{kit}{entries}[0]->{osarch})) && + ($::bldkit_config->{kit}{entries}[0]->{osarch} ne + $kr->{osarch})) { + print "Warning: Kit osarch is set to \"$::bldkit_config->{kit}{entries}[0]->{osarch}\", but this does not match kitrepo $kr->{kitrepoid} osarch \"$kr->{osarch}\". Processing will continue, but verify that you do not have an error in your buildkit configuration file. \n"; + } + $reponame .= '-' . $kr->{osarch}; $kr->{kitreponame} = $reponame; } - + # Kitcomponent checks - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + # Make sure all kitcomponent kitrepoids are defined my $found = 0; my %repo; - if ($debianflag){ - if ($kc->{basename} =~ /_/){ + if ($debianflag) { + if ($kc->{basename} =~ /_/) { print "Kit Component basename can not contain underscore.\n"; return 1; } } - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ($kc->{kitrepoid} eq $kr->{kitrepoid}) { - $found = 1; - %repo = %{$kr}; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if ($kc->{kitrepoid} eq $kr->{kitrepoid}) { + $found = 1; + %repo = %{$kr}; $kc->{kitreponame} = $kr->{kitreponame}; - push (@{$kr->{packages}}, &comppkgname($kc,$kr)); - last; + push(@{ $kr->{packages} }, &comppkgname($kc, $kr)); + last; } } - if ( ! $found ) { + if (!$found) { print "Kit Repository \"$kc->{kitrepoid}\" required by the Kit Component \"$kc->{basename}\" not defined in the Kit Build file.\n"; return 1; } + # Create full kitcomponent name my $compname = $kc->{basename}; - $compname .= '-'.$kc->{version}; - $compname .= '-'.$kc->{release}; - $compname .= '-'.$repo{osbasename}; - $compname .= '-'.$repo{osmajorversion}; - if ( defined($repo{osminorversion}) ) { - $compname .= '.'.$repo{osminorversion}; + $compname .= '-' . $kc->{version}; + $compname .= '-' . $kc->{release}; + $compname .= '-' . $repo{osbasename}; + $compname .= '-' . $repo{osmajorversion}; + if (defined($repo{osminorversion})) { + $compname .= '.' . $repo{osminorversion}; } - $compname .= '-'.$repo{osarch}; + $compname .= '-' . $repo{osarch}; $kc->{kitcompname} = $compname; + # Make sure all kitcomponent kitpkgdeps are defined if (defined($kc->{kitpkgdeps})) { - foreach my $d (split(/,/, $kc->{kitpkgdeps})) { - $d =~ s/\s+//g; - $d =~ s/^([\w\.\-]+)[<>=]*.*$/$1/; - my $found = 0; - foreach my $kp (@{$::bldkit_config->{kitpackage}{entries}}) { - if ( $kp->{filename} =~ /^$d[\.\-]?/ ) { - foreach my $kprid (split(/,/, $kp->{kitrepoid})) { - $kprid =~ s/\s+//g; - if ($kc->{kitrepoid} eq $kprid) { - $found = 1; - last; - } + foreach my $d (split(/,/, $kc->{kitpkgdeps})) { + $d =~ s/\s+//g; + $d =~ s/^([\w\.\-]+)[<>=]*.*$/$1/; + my $found = 0; + foreach my $kp (@{ $::bldkit_config->{kitpackage}{entries} }) { + if ($kp->{filename} =~ /^$d[\.\-]?/) { + foreach my $kprid (split(/,/, $kp->{kitrepoid})) { + $kprid =~ s/\s+//g; + if ($kc->{kitrepoid} eq $kprid) { + $found = 1; + last; + } + } + } + if ($found) { last; } + } + if (!$found) { + print "Kit Package \"$d\" required by the Kit Component \"$kc->{basename}\" was not found in the Kit Component\'s repository \"$kc->{kitrepoid}\".\n"; + return 1; } - } - if ($found) { last; } } - if ( !$found ) { - print "Kit Package \"$d\" required by the Kit Component \"$kc->{basename}\" was not found in the Kit Component\'s repository \"$kc->{kitrepoid}\".\n"; - return 1; - } - } } + # Make sure all kitcomponent driverpacks are defined if (defined($kc->{driverpacks})) { - my @drvs = split(/,/, $kc->{driverpacks}); - foreach my $d (@drvs) { - $d =~ s/\s+//g; - my $found = 0; - foreach my $kp (@{$::bldkit_config->{kitpackage}{entries}}) { - if ( $kp->{filename} eq $d ) { - foreach my $kprid (split(/,/, $kp->{kitrepoid})) { - $kprid =~ s/\s+//g; - if ($kc->{kitrepoid} eq $kprid) { - $found = 1; - last; - } + my @drvs = split(/,/, $kc->{driverpacks}); + foreach my $d (@drvs) { + $d =~ s/\s+//g; + my $found = 0; + foreach my $kp (@{ $::bldkit_config->{kitpackage}{entries} }) { + if ($kp->{filename} eq $d) { + foreach my $kprid (split(/,/, $kp->{kitrepoid})) { + $kprid =~ s/\s+//g; + if ($kc->{kitrepoid} eq $kprid) { + $found = 1; + last; + } + } + } + if ($found) { last; } + } + if (!$found) { + print "Driver package \"$d\" required by the Kit Component \"$kc->{basename}\" was not found in the Kit Component\'s repository \"$kc->{kitrepoid}\".\n"; + return 1; } - } - if ($found) { last; } } - if ( !$found ) { - print "Driver package \"$d\" required by the Kit Component \"$kc->{basename}\" was not found in the Kit Component\'s repository \"$kc->{kitrepoid}\".\n"; + } + + # Make sure files exist + if (defined($kc->{exlist})) { + my $ck_file = $::workdir . "/other_files/" . $kc->{exlist}; + if (!-r $ck_file) { + print "Exclude List file $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; return 1; - } + } } - } - # Make sure files exist - if (defined($kc->{exlist})){ - my $ck_file = $::workdir."/other_files/".$kc->{exlist}; - if (! -r $ck_file ) { - print "Exclude List file $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{preinstall})) { + my $ck_file = $::workdir . "/scripts/" . $kc->{preinstall}; + if (!-r $ck_file) { + print "Pre-Install script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } } - } - if (defined($kc->{preinstall})){ - my $ck_file = $::workdir."/scripts/".$kc->{preinstall}; - if (! -r $ck_file ) { - print "Pre-Install script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{postinstall})) { + my $ck_file = $::workdir . "/scripts/" . $kc->{postinstall}; + if (!-r $ck_file) { + print "Post-Install script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } } - } - if (defined($kc->{postinstall})){ - my $ck_file = $::workdir."/scripts/".$kc->{postinstall}; - if (! -r $ck_file ) { - print "Post-Install script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{preuninstall})) { + my $ck_file = $::workdir . "/scripts/" . $kc->{preuninstall}; + if (!-r $ck_file) { + print "Pre-Uninstall script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } } - } - if (defined($kc->{preuninstall})){ - my $ck_file = $::workdir."/scripts/".$kc->{preuninstall}; - if (! -r $ck_file ) { - print "Pre-Uninstall script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{postuninstall})) { + my $ck_file = $::workdir . "/scripts/" . $kc->{postuninstall}; + if (!-r $ck_file) { + print "Post-Uninstall script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } } - } - if (defined($kc->{postuninstall})){ - my $ck_file = $::workdir."/scripts/".$kc->{postuninstall}; - if (! -r $ck_file ) { - print "Post-Uninstall script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{preupgrade})) { + my $ck_file = $::workdir . "/scripts/" . $kc->{preupgrade}; + if (!-r $ck_file) { + print "Pre-Upgrade script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } } - } - if (defined($kc->{preupgrade})){ - my $ck_file = $::workdir."/scripts/".$kc->{preupgrade}; - if (! -r $ck_file ) { - print "Pre-Upgrade script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{postupgrade})) { + my $ck_file = $::workdir . "/scripts/" . $kc->{postupgrade}; + if (!-r $ck_file) { + print "Post-Upgrade script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } } - } - if (defined($kc->{postupgrade})){ - my $ck_file = $::workdir."/scripts/".$kc->{postupgrade}; - if (! -r $ck_file ) { - print "Post-Upgrade script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; + if (defined($kc->{genimage_postinstall})) { + foreach my $script (split(/\,/, $kc->{genimage_postinstall})) { + $script =~ s/\s+//g; + my $ck_file = $::workdir . "/scripts/" . $script; + if (!-r $ck_file) { + print "genimage_postinstall script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } + } } - } - if (defined($kc->{genimage_postinstall})){ - foreach my $script (split(/\,/, $kc->{genimage_postinstall})){ - $script =~ s/\s+//g; - my $ck_file = $::workdir."/scripts/".$script; - if (! -r $ck_file ) { - print "genimage_postinstall script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; - } - } - } - if (defined($kc->{postbootscripts})){ - foreach my $script (split(/\,/, $kc->{postbootscripts})){ - $script =~ s/\s+//g; - my $ck_file = $::workdir."/scripts/".$script; - if (! -r $ck_file ) { - print "Postboot script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; - return 1; - } + if (defined($kc->{postbootscripts})) { + foreach my $script (split(/\,/, $kc->{postbootscripts})) { + $script =~ s/\s+//g; + my $ck_file = $::workdir . "/scripts/" . $script; + if (!-r $ck_file) { + print "Postboot script $ck_file defined in Kit Componenet \"$kc->{basename}\" does not exist or is not readable\n"; + return 1; + } + } + } + if (defined($kc->{non_native_pkgs})) { + if ($kc->{non_native_pkgs} =~ /EXTERNALPKGS/) { + $::NON_NATIVE_PKGS->{ $kc->{kitcompname} } = 1; + $::HAVE_NON_NATIVE_PKGS = 1; + } } - } - if (defined($kc->{non_native_pkgs})){ - if ($kc->{non_native_pkgs} =~ /EXTERNALPKGS/) { - $::NON_NATIVE_PKGS->{$kc->{kitcompname}} = 1; - $::HAVE_NON_NATIVE_PKGS = 1; - } - } } - + # Kitpackage checks - foreach my $kp (@{$::bldkit_config->{kitpackage}{entries}}) { - # determine if valid build method - if ( (defined($kp->{isexternalpkg})) || - (defined($kp->{rpm_prebuiltdir})) ) { - if ((defined($kp->{rpm_srpm})) || - (defined($kp->{rpm_srctarball})) || - (defined($kp->{rpm_spec})) || - (defined($kp->{rpm_srcdir})) ) { - print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; - return 1; - } - if ( !(defined($kp->{isexternalpkg})) ) { $kp->{isexternalpkg} = 'no'; } - my $orig_isext = $kp->{isexternalpkg}; - $kp->{isexternalpkg} =~ s/\s+//g; - $kp->{isexternalpkg} =~ tr/A-Z/a-z/; # convert to lowercase - if ( $kp->{isexternalpkg} eq '0' ) { $kp->{isexternalpkg} = 'no'; } - if ( $kp->{isexternalpkg} eq '1' ) { $kp->{isexternalpkg} = 'yes'; } - if ( ( $kp->{isexternalpkg} ne 'yes' ) && - ( $kp->{isexternalpkg} ne 'no' ) ) { - print "Error in definition for Kit Package $kp->{filename}. Invalid attribute value \'isexternalpkg=$orig_isext\'. Valid values are \'no\'|\'0\' or \'yes\'|\'1\'.\n"; - return 1; - } - if ( ( $kp->{isexternalpkg} eq 'yes' ) ) { - $::HAVE_EXTERNAL_PKG=1; - } - if ( ( $kp->{isexternalpkg} eq 'yes' ) && - (defined($kp->{rpm_prebuiltdir})) ) { - print "Error in definition for Kit Package $kp->{filename}. Do not specify \'isexternalpkg=$orig_isext\' with 'rpm_prebuiltdir'.\n"; - return 1; - } - } elsif (defined($kp->{rpm_srpm})) { - if ((defined($kp->{rpm_prebuiltdir})) || - (defined($kp->{rpm_srctarball})) || - (defined($kp->{rpm_spec})) || - (defined($kp->{rpm_srcdir})) ) { - print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; - return 1; - } - } elsif (defined($kp->{rpm_srctarball}) && - defined($kp->{rpm_spec}) ) { - if ((defined($kp->{rpm_prebuiltdir})) || - (defined($kp->{rpm_srpm})) || - (defined($kp->{rpm_srcdir})) ) { - print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; - return 1; - } - } elsif (defined($kp->{rpm_srcdir}) && - defined($kp->{rpm_spec}) ) { - if ((defined($kp->{rpm_prebuiltdir})) || - (defined($kp->{rpm_srpm})) || - (defined($kp->{rpm_srctarball})) ) { - print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; - return 1; - } - } else { - print "Cannot determine build method for Kit Package $kp->{filename}. Verify that your Kit Build File is correct. \n"; - return 1; - } - # Make sure all kitpackage kitrepoids are defined - foreach my $kprid (split(/,/, $kp->{kitrepoid})) { - my $found = 0; - $kprid =~ s/\s+//g; - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ($kprid eq $kr->{kitrepoid}) { - $found = 1; - $kp->{kitreponame}.=",".$kr->{kitreponame}; - if ( !( $kp->{isexternalpkg} eq 'yes' ) ) { - push (@{$kr->{packages}}, $kp->{filename}); - } - last; + foreach my $kp (@{ $::bldkit_config->{kitpackage}{entries} }) { + + # determine if valid build method + if ((defined($kp->{isexternalpkg})) || + (defined($kp->{rpm_prebuiltdir}))) { + if ((defined($kp->{rpm_srpm})) || + (defined($kp->{rpm_srctarball})) || + (defined($kp->{rpm_spec})) || + (defined($kp->{rpm_srcdir}))) { + print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; + return 1; } - } - if ( ! $found ) { - print "Kit Repository \"$kprid\" required by the Kit Package \"$kp->{filename}\" is not defined in the Kit Build file.\n"; + if (!(defined($kp->{isexternalpkg}))) { $kp->{isexternalpkg} = 'no'; } + my $orig_isext = $kp->{isexternalpkg}; + $kp->{isexternalpkg} =~ s/\s+//g; + $kp->{isexternalpkg} =~ tr/A-Z/a-z/; # convert to lowercase + if ($kp->{isexternalpkg} eq '0') { $kp->{isexternalpkg} = 'no'; } + if ($kp->{isexternalpkg} eq '1') { $kp->{isexternalpkg} = 'yes'; } + if (($kp->{isexternalpkg} ne 'yes') && + ($kp->{isexternalpkg} ne 'no')) { + print "Error in definition for Kit Package $kp->{filename}. Invalid attribute value \'isexternalpkg=$orig_isext\'. Valid values are \'no\'|\'0\' or \'yes\'|\'1\'.\n"; + return 1; + } + if (($kp->{isexternalpkg} eq 'yes')) { + $::HAVE_EXTERNAL_PKG = 1; + } + if (($kp->{isexternalpkg} eq 'yes') && + (defined($kp->{rpm_prebuiltdir}))) { + print "Error in definition for Kit Package $kp->{filename}. Do not specify \'isexternalpkg=$orig_isext\' with 'rpm_prebuiltdir'.\n"; + return 1; + } + } elsif (defined($kp->{rpm_srpm})) { + if ((defined($kp->{rpm_prebuiltdir})) || + (defined($kp->{rpm_srctarball})) || + (defined($kp->{rpm_spec})) || + (defined($kp->{rpm_srcdir}))) { + print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; + return 1; + } + } elsif (defined($kp->{rpm_srctarball}) && + defined($kp->{rpm_spec})) { + if ((defined($kp->{rpm_prebuiltdir})) || + (defined($kp->{rpm_srpm})) || + (defined($kp->{rpm_srcdir}))) { + print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; + return 1; + } + } elsif (defined($kp->{rpm_srcdir}) && + defined($kp->{rpm_spec})) { + if ((defined($kp->{rpm_prebuiltdir})) || + (defined($kp->{rpm_srpm})) || + (defined($kp->{rpm_srctarball}))) { + print "Cannot determine build method for Kit Package $kp->{filename}. Conflicting attributes were specified.\n"; + return 1; + } + } else { + print "Cannot determine build method for Kit Package $kp->{filename}. Verify that your Kit Build File is correct. \n"; return 1; - } - } - $kp->{kitreponame} =~ s/^,//; - if (!$::NEW_PARTIAL_KIT) { - # Make sure files exist - if (defined($kp->{rpm_spec})){ - my $ck_file = $::workdir."/source_packages/".$kp->{rpm_spec}; - if (! -r $ck_file ) { - print "RPM spec file $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; - return 1; + } + + # Make sure all kitpackage kitrepoids are defined + foreach my $kprid (split(/,/, $kp->{kitrepoid})) { + my $found = 0; + $kprid =~ s/\s+//g; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if ($kprid eq $kr->{kitrepoid}) { + $found = 1; + $kp->{kitreponame} .= "," . $kr->{kitreponame}; + if (!($kp->{isexternalpkg} eq 'yes')) { + push(@{ $kr->{packages} }, $kp->{filename}); + } + last; + } } - } - if (defined($kp->{rpm_srcdir})){ - my $ck_dir = $::workdir."/source_packages/".$kp->{rpm_srcdir}; - if (! -d $ck_dir ) { - print "RPM source directory $ck_dir defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; - return 1; - } - } - if (defined($kp->{rpm_srctarball})){ - my $ck_file = $::workdir."/source_packages/".$kp->{rpm_srctarball}; - if (! -r $ck_file ) { - print "RPM source tarfile $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; - return 1; - } - } - if (defined($kp->{rpm_srpm})){ - my $ck_file = $::workdir."/source_packages/".$kp->{rpm_srpm}; - if (! -r $ck_file ) { - print "Source RPM $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; - return 1; - } - } - if (defined($kp->{rpm_prebuiltdir})){ - my $ck_dir = $::workdir."/source_packages/".$kp->{rpm_prebuiltdir}; - if (! -d $ck_dir ) { - print "Pre-built RPM directory $ck_dir defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + if (!$found) { + print "Kit Repository \"$kprid\" required by the Kit Package \"$kp->{filename}\" is not defined in the Kit Build file.\n"; return 1; } - my $ck_file = $ck_dir."/".$kp->{filename}; - if ( system("ls $ck_file > /dev/null") ) { -# if (! -r $ck_file ) { - print "Pre-built rpm $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; - return 1; + } + $kp->{kitreponame} =~ s/^,//; + if (!$::NEW_PARTIAL_KIT) { + + # Make sure files exist + if (defined($kp->{rpm_spec})) { + my $ck_file = $::workdir . "/source_packages/" . $kp->{rpm_spec}; + if (!-r $ck_file) { + print "RPM spec file $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + return 1; + } + } + if (defined($kp->{rpm_srcdir})) { + my $ck_dir = $::workdir . "/source_packages/" . $kp->{rpm_srcdir}; + if (!-d $ck_dir) { + print "RPM source directory $ck_dir defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + return 1; + } + } + if (defined($kp->{rpm_srctarball})) { + my $ck_file = $::workdir . "/source_packages/" . $kp->{rpm_srctarball}; + if (!-r $ck_file) { + print "RPM source tarfile $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + return 1; + } + } + if (defined($kp->{rpm_srpm})) { + my $ck_file = $::workdir . "/source_packages/" . $kp->{rpm_srpm}; + if (!-r $ck_file) { + print "Source RPM $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + return 1; + } + } + if (defined($kp->{rpm_prebuiltdir})) { + my $ck_dir = $::workdir . "/source_packages/" . $kp->{rpm_prebuiltdir}; + if (!-d $ck_dir) { + print "Pre-built RPM directory $ck_dir defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + return 1; + } + my $ck_file = $ck_dir . "/" . $kp->{filename}; + if (system("ls $ck_file > /dev/null")) { + + # if (! -r $ck_file ) { + print "Pre-built rpm $ck_file defined in Kit Package \"$kp->{filename}\" does not exist or is not readable\n"; + return 1; + } } - } } } -#use Data::Dumper; -#print Dumper($::bldkit_config->{kitrepo}); + + #use Data::Dumper; + #print Dumper($::bldkit_config->{kitrepo}); return 0; } @@ -1805,13 +1833,13 @@ sub comppkgname my $pkgname = $comp->{basename}; if ($debianflag) { - $pkgname .= '_'.$comp->{version}; - $pkgname .= '-'.$comp->{release}; + $pkgname .= '_' . $comp->{version}; + $pkgname .= '-' . $comp->{release}; $pkgname .= '_all.deb'; } - else{ - $pkgname .= '-'.$comp->{version}; - $pkgname .= '-'.$comp->{release}; + else { + $pkgname .= '-' . $comp->{version}; + $pkgname .= '-' . $comp->{release}; $pkgname .= '.noarch.rpm'; } return $pkgname; @@ -1835,32 +1863,33 @@ sub validate_repo { my $repo = shift; - my $repodir = $::base_repodir."/".$repo->{kitreponame}; - if ( ! -d $repodir ) { + my $repodir = $::base_repodir . "/" . $repo->{kitreponame}; + if (!-d $repodir) { if ($::VERBOSE) { print "\n$repodir does not exist. No rpms have been built for this kitrepo. \n"; } return 1; } - + # Make sure each repo pkg exists - foreach my $pkg (@{$repo->{packages}}){ + foreach my $pkg (@{ $repo->{packages} }) { + # skip check for kit component meta rpm if it includes # external non-native pkgs my $skip_check = 0; - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { if ($repo->{kitrepoid} eq $kc->{kitrepoid}) { my $kitpkgname = comppkgname($kc); - if (($kitpkgname eq $pkg) && - ($::NON_NATIVE_PKGS->{$kc->{kitcompname}}) ) { - $skip_check = 1; - last; + if (($kitpkgname eq $pkg) && + ($::NON_NATIVE_PKGS->{ $kc->{kitcompname} })) { + $skip_check = 1; + last; } } } - if ( ! $skip_check ) { - my $pkg_filename = $repodir.'/'.$pkg; - if ( system("ls $pkg_filename > /dev/null") ) { + if (!$skip_check) { + my $pkg_filename = $repodir . '/' . $pkg; + if (system("ls $pkg_filename > /dev/null")) { if ($::VERBOSE) { print "\nFile $pkg in directory $repodir does not exist or is not readable. \n"; } @@ -1890,31 +1919,31 @@ sub validate_os my $repo = shift; my $osinfo = xCAT::BuildKitUtils->osver(); - my ($osbasename,$osmore) = split(/\,/, $osinfo); - my ($osmajorversion,$osminorversion) = split(/\./, $osmore); - my $osarch=`uname -p`; + my ($osbasename, $osmore) = split(/\,/, $osinfo); + my ($osmajorversion, $osminorversion) = split(/\./, $osmore); + my $osarch = `uname -p`; chomp($osarch); - if ($debianflag==1) { - if($osarch eq "ppc64le"){ - $osarch="ppc64el"; - } + if ($debianflag == 1) { + if ($osarch eq "ppc64le") { + $osarch = "ppc64el"; + } } $osinfo =~ s/\,//; my $repo_osinfo = "$repo->{osbasename}$repo->{osmajorversion}"; - if (defined($repo->{osminorversion})){ + if (defined($repo->{osminorversion})) { $repo_osinfo .= ".$repo->{osminorversion}"; } $repo_osinfo .= "-$repo->{osarch} "; my $mismatch_msg = "The local host is running $osinfo-$osarch. This does not match the Kit Repository \"$repo->{kitrepoid}\" data: $repo_osinfo"; - if (defined($repo->{compat_osbasenames})){ + if (defined($repo->{compat_osbasenames})) { $mismatch_msg .= " or the compatible OS distros: $repo->{compat_osbasenames} "; } my $compat_match = 0; if ($repo->{osbasename} ne $osbasename) { - if (defined($repo->{compat_osbasenames})){ + if (defined($repo->{compat_osbasenames})) { foreach my $cos (split(/,/, $repo->{compat_osbasenames})) { if ($cos eq $osbasename) { $compat_match = 1; @@ -1930,8 +1959,8 @@ sub validate_os return 1; } } - if ( ($repo->{osmajorversion} ne $osmajorversion) && - (!$compat_match) ) { + if (($repo->{osmajorversion} ne $osmajorversion) && + (!$compat_match)) { print "$mismatch_msg \n"; if ($::VERBOSE) { print "\n Local OS major version $osmajorversion does not match repository.\n"; @@ -1939,8 +1968,8 @@ sub validate_os return 1; } if (defined($repo->{osminorversion})) { - if ( ($repo->{osminorversion} ne $osminorversion) && - (!$compat_match) ) { + if (($repo->{osminorversion} ne $osminorversion) && + (!$compat_match)) { print "$mismatch_msg \n"; if ($::VERBOSE) { print "\n Local OS minor version $osminorversion does not match repository.\n"; @@ -1972,115 +2001,117 @@ sub build_kitcomp { my $comp = shift; my %repo; - my $rpmbuild_dir = $::workdir."/rpmbuild"; - my $tmpdir = $::workdir."/tmp/$comp->{kitcompname}"; - my $kcmetaname = comppkgname($comp); + my $rpmbuild_dir = $::workdir . "/rpmbuild"; + my $tmpdir = $::workdir . "/tmp/$comp->{kitcompname}"; + my $kcmetaname = comppkgname($comp); - # If this kitcomponent has external non-native pkgs, + # If this kitcomponent has external non-native pkgs, # skip the meta rpm build - if ( defined($::NON_NATIVE_PKGS) && - defined($::NON_NATIVE_PKGS->{$comp->{kitcompname}}) && - $::NON_NATIVE_PKGS->{$comp->{kitcompname}} ) { + if (defined($::NON_NATIVE_PKGS) && + defined($::NON_NATIVE_PKGS->{ $comp->{kitcompname} }) && + $::NON_NATIVE_PKGS->{ $comp->{kitcompname} }) { if ($::VERBOSE) { - print "Kit component $comp->{kitcompname} has external non-native packages. Skipping rpm build for $kcmetaname. \n"; + print "Kit component $comp->{kitcompname} has external non-native packages. Skipping rpm build for $kcmetaname. \n"; } return 0; } # find the kitrepo hash for this component - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ($comp->{kitrepoid} eq $kr->{kitrepoid}) { - %repo = %{$kr}; - last; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if ($comp->{kitrepoid} eq $kr->{kitrepoid}) { + %repo = %{$kr}; + last; } } - my $repodir = $::base_repodir."/".$repo{kitreponame}; + my $repodir = $::base_repodir . "/" . $repo{kitreponame}; # Fix the kitpkgdeps value for this kitcomponent # For any kitpkgdep that has an rpm file in the repo, # specifically reference it's version-release - if ( &update_kitcomp_kitpkgdeps($comp,$repodir) ) { return 1; } + if (&update_kitcomp_kitpkgdeps($comp, $repodir)) { return 1; } $::VALID_PRER_COMPONENT = 0; - if ( !$::PREREQUISITE ) { - if ( $comp->{ospkgdeps} || $comp->{preinstall} || $comp->{preupgrade} ) { - if ( &gen_kitcomp_spec($comp,\%repo, 'PREREQUISITE') ) { return 1; } - + if (!$::PREREQUISITE) { + if ($comp->{ospkgdeps} || $comp->{preinstall} || $comp->{preupgrade}) { + if (&gen_kitcomp_spec($comp, \%repo, 'PREREQUISITE')) { return 1; } + # run the rpmbuild command my $curdir = $::workdir; - my $cmd = "rm -Rf $curdir/rpmbuild"; + my $cmd = "rm -Rf $curdir/rpmbuild"; system($cmd); - my $avoiderr = $rpmbuild_dir."/BUILDROOT/prep_".$comp->{basename}; + my $avoiderr = $rpmbuild_dir . "/BUILDROOT/prep_" . $comp->{basename}; $avoiderr .= "-$comp->{version}-$comp->{release}.$repo{osarch}"; mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/BUILD/"; + $avoiderr = $rpmbuild_dir . "/BUILD/"; mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/SRPMS/"; + $avoiderr = $rpmbuild_dir . "/SRPMS/"; mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/RPMS/noarch/"; + $avoiderr = $rpmbuild_dir . "/RPMS/noarch/"; mkpath($avoiderr); # Read the kit component prerequisite rpm name - my $specfile = $::workdir."/tmp/$comp->{kitcompname}-prep.spec"; + my $specfile = $::workdir . "/tmp/$comp->{kitcompname}-prep.spec"; my $rpmbuild_cmd = "rpmbuild --define \"_topdir $rpmbuild_dir\" -ba $specfile"; - # don't want debug info - 3845 -# if (!$::VERBOSE) { - $rpmbuild_cmd .= ' --quiet '; -# } - if ( system($rpmbuild_cmd) ) { + # don't want debug info - 3845 + # if (!$::VERBOSE) { + $rpmbuild_cmd .= ' --quiet '; + + # } + if (system($rpmbuild_cmd)) { print "Error running rpmbuild command for kit component $comp->{kitcompname} meta package\n"; return 1; } my @built_rpms = `find $rpmbuild_dir/RPMS -name "*.rpm"`; foreach my $rpm (@built_rpms) { chomp($rpm); - if ( system ("cp -fp $rpm $repodir") ) { + if (system("cp -fp $rpm $repodir")) { print "Error copying rpm $rpm to build repo directory $repodir \n"; return 1; } } - + $::VALID_PRER_COMPONENT = 1; } - if ( &gen_kitcomp_spec($comp,\%repo, 'METARPM') ) { return 1; } + if (&gen_kitcomp_spec($comp, \%repo, 'METARPM')) { return 1; } } else { + # Create spec file for this kit component - if ( &gen_kitcomp_spec($comp,\%repo, 'ALL') ) { return 1; } + if (&gen_kitcomp_spec($comp, \%repo, 'ALL')) { return 1; } } # run the rpmbuild command my $curdir = $::workdir; - my $cmd = "rm -Rf $curdir/rpmbuild"; + my $cmd = "rm -Rf $curdir/rpmbuild"; system($cmd); - my $avoiderr = $rpmbuild_dir."/BUILDROOT/".$comp->{basename}; + my $avoiderr = $rpmbuild_dir . "/BUILDROOT/" . $comp->{basename}; $avoiderr .= "-$comp->{version}-$comp->{release}.$repo{osarch}"; mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/BUILD/"; + $avoiderr = $rpmbuild_dir . "/BUILD/"; mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/SRPMS/"; + $avoiderr = $rpmbuild_dir . "/SRPMS/"; mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/RPMS/noarch/"; + $avoiderr = $rpmbuild_dir . "/RPMS/noarch/"; mkpath($avoiderr); # Read the kit component meta rpm name - - my $specfile = $::workdir."/tmp/$comp->{kitcompname}.spec"; + + my $specfile = $::workdir . "/tmp/$comp->{kitcompname}.spec"; my $rpmbuild_cmd = "rpmbuild --define \"_topdir $rpmbuild_dir\" -ba $specfile"; # Copy in any non-native packages - if (defined($comp->{non_native_pkgs}) ) { + if (defined($comp->{non_native_pkgs})) { mkpath($tmpdir); mkpath("$rpmbuild_dir/SOURCES"); - my $sourcedir = $::workdir."/source_packages"; + my $sourcedir = $::workdir . "/source_packages"; foreach my $pkgfile (split(/,/, $comp->{non_native_pkgs})) { my $pkg_file; - my ($key,$value) = split /:/,$pkgfile; + my ($key, $value) = split /:/, $pkgfile; if ("$key" =~ /EXTERNALPKGS/) { $pkg_file = $value; } else { @@ -2088,31 +2119,32 @@ sub build_kitcomp } $cmd = "cp -p $sourcedir/$pkg_file $tmpdir"; - if ( system($cmd) ) { + if (system($cmd)) { print "Error copying non-native package file $sourcedir/$pkg_file to $tmpdir\n"; return 1; } } - $cmd = "cd $tmpdir/..;mv $comp->{kitcompname} $comp->{basename}; tar -czf $rpmbuild_dir/SOURCES/$comp->{basename}.tar.gz $comp->{basename};mv $comp->{basename} $comp->{kitcompname}"; - if ( system($cmd) ) { + $cmd = "cd $tmpdir/..;mv $comp->{kitcompname} $comp->{basename}; tar -czf $rpmbuild_dir/SOURCES/$comp->{basename}.tar.gz $comp->{basename};mv $comp->{basename} $comp->{kitcompname}"; + if (system($cmd)) { print "Error creating tarfile $rpmbuild_dir/SOURCES/$comp->{kitreponame}-$comp->{kitcompname}.tar from $sourcedir/*"; return 1; } } # - don't want debug info - 3845 -# if (!$::VERBOSE) { - $rpmbuild_cmd .= ' --quiet '; -# } + # if (!$::VERBOSE) { + $rpmbuild_cmd .= ' --quiet '; - if ( system($rpmbuild_cmd) ) { + # } + + if (system($rpmbuild_cmd)) { print "Error running rpmbuild command for kit component $comp->{kitcompname} meta package\n"; return 1; } my @built_rpms = `find $rpmbuild_dir/RPMS -name "*.rpm"`; foreach my $rpm (@built_rpms) { chomp($rpm); - if ( system ("cp -fp $rpm $repodir") ) { + if (system("cp -fp $rpm $repodir")) { print "Error copying rpm $rpm to build repo directory $repodir \n"; return 1; } @@ -2142,31 +2174,34 @@ sub build_kitcomp #----------------------------------------------------------------------------- sub update_kitcomp_kitpkgdeps { - my $comp = shift; + my $comp = shift; my $repodir = shift; if (defined($comp->{kitpkgdeps})) { + # we have some rpms listed in buildkit.conf file my $new_kitpkgdeps = ''; foreach my $d (split(/,/, $comp->{kitpkgdeps})) { $d =~ s/\s+//g; my $d_short = $d; + # strip off everything after ">=" $d_short =~ s/^([\w\.\-]+)[<>=]*.*$/$1/; # if they are the same then there was no v/r info provided - if ( $d_short eq $d ) { + if ($d_short eq $d) { + # no version-release comparisons specified for this kitpkgdep # do we have this rpm file? # get a list of any matches my $lscmd = "cd $repodir; /bin/ls $d-\[0-9\]\*.rpm 2>/dev/null"; my @rpmlist = `$lscmd`; - if ( scalar(@rpmlist) == 0) { + if (scalar(@rpmlist) == 0) { next; - } + } - # get the newest version there is + # get the newest version there is my $newestrpm = xCAT::BuildKitUtils->get_latest_version($repodir, \@rpmlist); if (!$newestrpm) { @@ -2174,10 +2209,10 @@ sub update_kitcomp_kitpkgdeps next; } - # get the Version and release values for this rpm + # get the Version and release values for this rpm my $cmd = "rpm -q --qf \"%{NAME} >= %{VERSION}-%{RELEASE}\" -p $repodir/$newestrpm 2>/dev/null"; if ($::VERBOSE) { - print "running rpm query to get version-release info: \n $cmd \n"; + print "running rpm query to get version-release info: \n $cmd \n"; } my $new_d = `$cmd`; @@ -2190,13 +2225,13 @@ sub update_kitcomp_kitpkgdeps if ($::VERBOSE) { print "output: \n \'$new_d\' \n"; } - if ( $new_d ne '' ) { - $new_kitpkgdeps .= "$new_d,"; + if ($new_d ne '') { + $new_kitpkgdeps .= "$new_d,"; } else { - $new_kitpkgdeps .= "$d,"; + $new_kitpkgdeps .= "$d,"; } } else { - $new_kitpkgdeps .= "$d,"; + $new_kitpkgdeps .= "$d,"; } } @@ -2220,17 +2255,17 @@ sub update_kitcomp_kitpkgdeps #----------------------------------------------------------------------------- sub gen_kitcomp_spec { - my $comp = shift; - my $repo = shift; - my $level = shift; - my $scriptdir = $::workdir."/scripts/"; - my $tmpdir = $::workdir."/tmp/"; + my $comp = shift; + my $repo = shift; + my $level = shift; + my $scriptdir = $::workdir . "/scripts/"; + my $tmpdir = $::workdir . "/tmp/"; # read in the template spec file - my $spec_template = $::XCATSHARE."/kits/kitcomponent.spec.template"; + my $spec_template = $::XCATSHARE . "/kits/kitcomponent.spec.template"; my $SF; - unless ( open( $SF, "<", $spec_template ) ) { - print "Error attempting to open the xCAT Kit Component template file $spec_template. \n"; + unless (open($SF, "<", $spec_template)) { + print "Error attempting to open the xCAT Kit Component template file $spec_template. \n"; return 1; } if ($::VERBOSE) { @@ -2239,27 +2274,27 @@ sub gen_kitcomp_spec my @lines = <$SF>; close $SF; - my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; + my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; my $kitcompname = $comp->{kitcompname}; - my ($prescript,$postscript,$preupscript,$postupscript,$preunscript,$postunscript,$nonnativepkgs,$sourcetar,$setup,$files) = ' '; - if ( $level eq 'PREREQUISITE' || $level eq 'ALL' ) { + my ($prescript, $postscript, $preupscript, $postupscript, $preunscript, $postunscript, $nonnativepkgs, $sourcetar, $setup, $files) = ' '; + if ($level eq 'PREREQUISITE' || $level eq 'ALL') { if (defined($comp->{preinstall})) { - $prescript = &load_script("$scriptdir$comp->{preinstall}"); - $prescript = "if [ \"\$1\" = \"1\" ] ; then\n" . $prescript . "\nfi";} + $prescript = &load_script("$scriptdir$comp->{preinstall}"); + $prescript = "if [ \"\$1\" = \"1\" ] ; then\n" . $prescript . "\nfi"; } if (defined($comp->{preupgrade})) { $preupscript = &load_script("$scriptdir$comp->{preupgrade}"); - $preupscript = "if [ \"\$1\" = \"2\" ] ; then\n" . $preupscript . "\nfi";} + $preupscript = "if [ \"\$1\" = \"2\" ] ; then\n" . $preupscript . "\nfi"; } } - if ( $level eq 'METARPM' || $level eq 'ALL' ) { + if ($level eq 'METARPM' || $level eq 'ALL') { if (defined($comp->{preuninstall})) { $preunscript = &load_script("$scriptdir$comp->{preuninstall}"); } if (defined($comp->{postinstall})) { - $postscript = &load_script("$scriptdir$comp->{postinstall}"); + $postscript = &load_script("$scriptdir$comp->{postinstall}"); $postscript = "if [ \"\$1\" = \"1\" ] ; then\n" . $postscript . "\nfi"; } if (defined($comp->{postupgrade})) { $postupscript = &load_script("$scriptdir$comp->{postupgrade}"); - $postupscript = "if [ \"\$1\" = \"2\" ] ; then\n" . $postupscript . "\nfi";} + $postupscript = "if [ \"\$1\" = \"2\" ] ; then\n" . $postupscript . "\nfi"; } if (defined($comp->{postuninstall})) { $postunscript = &load_script("$scriptdir$comp->{postuninstall}"); } if (defined($comp->{non_native_pkgs})) { @@ -2267,25 +2302,26 @@ sub gen_kitcomp_spec $nonnativepkgs .= "mkdir -p \$RPM_BUILD_ROOT/opt/xcat/kits/$kitname/$kitcompname \n"; $nonnativepkgs .= "cp -a * \$RPM_BUILD_ROOT/opt/xcat/kits/$kitname/$kitcompname \n"; $sourcetar = "Source: $comp->{basename}.tar.gz"; - $setup = "\%setup -q -n $comp->{basename}"; - $files = "/opt/xcat/kits"; + $setup = "\%setup -q -n $comp->{basename}"; + $files = "/opt/xcat/kits"; } } # remove lines that correspond to optional tags that have no values - # in this instance. Adding lines to the spec file that have + # in this instance. Adding lines to the spec file that have # no values will cause a build error. my @newlines; foreach my $l (@lines) { chomp; + # don't add vendor,packager,url to spec file unless we have a value if ($l =~ /INSERT_vendor_HERE/) { - if (!$::bldkit_config->{kit}{entries}[0]->{vendor} ) { + if (!$::bldkit_config->{kit}{entries}[0]->{vendor}) { next; } } if ($l =~ /INSERT_packager_HERE/) { - if (!$::bldkit_config->{kit}{entries}[0]->{packager} ) { + if (!$::bldkit_config->{kit}{entries}[0]->{packager}) { next; } } @@ -2294,20 +2330,20 @@ sub gen_kitcomp_spec next; } } - push @newlines, $l; + push @newlines, $l; } - @lines=@newlines; + @lines = @newlines; - if ( $level eq 'ALL' ) { + if ($level eq 'ALL') { for (@lines) { chomp; s/<<>>/$kitname/; s/<<>>/$comp->{basename}/; s/<<>>/$comp->{version}/; s/<<>>/$comp->{release}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitlicense}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{vendor}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{packager}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitlicense}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{vendor}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{packager}/; s/<<>>/$::bldkit_config->{kit}{entries}[0]->{url}/; s/<<>>/$comp->{ospkgdeps}/; s/<<>>/$comp->{kitpkgdeps}/; @@ -2322,18 +2358,18 @@ sub gen_kitcomp_spec s/<<>>/$preupscript/; s/<<>>/$postupscript/; s/<<>>/$preunscript/; - s/<<>>/$postunscript/; +s/<<>>/$postunscript/; } - } elsif ( $level eq 'PREREQUISITE' ) { + } elsif ($level eq 'PREREQUISITE') { for (@lines) { chomp; s/<<>>/$kitname/; s/<<>>/prep_$comp->{basename}/; s/<<>>/$comp->{version}/; s/<<>>/$comp->{release}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitlicense}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{vendor}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{packager}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitlicense}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{vendor}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{packager}/; s/<<>>/$::bldkit_config->{kit}{entries}[0]->{url}/; s/<<>>/$comp->{ospkgdeps}/; s/<<>>//; @@ -2351,24 +2387,25 @@ sub gen_kitcomp_spec s/<<>>//; } - } elsif ( $level eq 'METARPM' ) { + } elsif ($level eq 'METARPM') { for (@lines) { chomp; s/<<>>/$kitname/; s/<<>>/$comp->{basename}/; s/<<>>/$comp->{version}/; s/<<>>/$comp->{release}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitlicense}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{vendor}/; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{packager}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitlicense}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{vendor}/; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{packager}/; s/<<>>/$::bldkit_config->{kit}{entries}[0]->{url}/; s/<<>>//; s/<<>>/$comp->{kitpkgdeps}/; + #Update kitcompdeps for prep_ - if ( $::VALID_PRER_COMPONENT ) { - s/<<>>/$comp->{kitcompdeps},prep_$comp->{basename}/; + if ($::VALID_PRER_COMPONENT) { +s/<<>>/$comp->{kitcompdeps},prep_$comp->{basename}/; } else { - s/<<>>/$comp->{kitcompdeps}/; +s/<<>>/$comp->{kitcompdeps}/; } s/<<>>/$comp->{description}/; s/<<>>/$nonnativepkgs/; @@ -2380,21 +2417,21 @@ sub gen_kitcomp_spec s/<<>>//; s/<<>>/$postupscript/; s/<<>>/$preunscript/; - s/<<>>/$postunscript/; +s/<<>>/$postunscript/; } } - # Write the generated spec file + # Write the generated spec file mkpath($tmpdir); - + my $fn; my $NSF; - if ( $level eq 'PREREQUISITE' ) { - $fn = $comp->{kitcompname}."-prep.spec" + if ($level eq 'PREREQUISITE') { + $fn = $comp->{kitcompname} . "-prep.spec" } else { - $fn = $comp->{kitcompname}.".spec" + $fn = $comp->{kitcompname} . ".spec" } - unless ( open( $NSF, ">$tmpdir$fn" ) ) { + unless (open($NSF, ">$tmpdir$fn")) { return 1; } if ($::VERBOSE) { @@ -2402,7 +2439,7 @@ sub gen_kitcomp_spec } foreach my $line (@lines) { - print $NSF $line,"\n"; + print $NSF $line, "\n"; } close($NSF); @@ -2418,76 +2455,80 @@ sub gen_kitcomp_spec =cut #----------------------------------------------------------------------------- -sub build_kitcomp_debian{ +sub build_kitcomp_debian { my $comp = shift; my %repo; - my $debbuilddir = $::workdir."/debbuild/".$comp->{kitcompname}; - my $kcmetaname = comppkgname($comp); - - #If this kitcomponent has external non-native pkgs, + my $debbuilddir = $::workdir . "/debbuild/" . $comp->{kitcompname}; + my $kcmetaname = comppkgname($comp); + + #If this kitcomponent has external non-native pkgs, #skip the meta package build - if ( defined($::NON_NATIVE_PKGS) && - defined($::NON_NATIVE_PKGS->{$comp->{kitcompname}}) && - $::NON_NATIVE_PKGS->{$comp->{kitcompname}} ) { + if (defined($::NON_NATIVE_PKGS) && + defined($::NON_NATIVE_PKGS->{ $comp->{kitcompname} }) && + $::NON_NATIVE_PKGS->{ $comp->{kitcompname} }) { if ($::VERBOSE) { - print "Kit component $comp->{kitcompname} has external non-native packages. Skipping rpm build for $kcmetaname. \n"; + print "Kit component $comp->{kitcompname} has external non-native packages. Skipping rpm build for $kcmetaname. \n"; } return 0; } + # find the kitrepo hash for this component - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { - if ($comp->{kitrepoid} eq $kr->{kitrepoid}) { - %repo = %{$kr}; - last; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { + if ($comp->{kitrepoid} eq $kr->{kitrepoid}) { + %repo = %{$kr}; + last; } } #run the dpkg-buildpackage command my $curdir = $::workdir; - my $cmd = "rm -Rf $debbuilddir"; + my $cmd = "rm -Rf $debbuilddir"; system($cmd); mkpath($debbuilddir); $::VALID_PREP_COMPONENT = 0; - if ( !$::PREREQUISITE ) { - if ( $comp->{ospkgdeps} || $comp->{preinstall} || $comp->{preupgrade} || $comp->{preuninstall} ) { - + if (!$::PREREQUISITE) { + if ($comp->{ospkgdeps} || $comp->{preinstall} || $comp->{preupgrade} || $comp->{preuninstall}) { + #Create debian directory for this kit component preppackage - if ( &gen_kitcomp_debdir_prep($comp,\%repo) ) { return 1; } + if (&gen_kitcomp_debdir_prep($comp, \%repo)) { return 1; } $::VALID_PREP_COMPONENT = 1; + # build prep deb my $prep_compversion = $comp->{version} . "-" . $comp->{release}; my $prep_buildstring = "Prep Kit component build package."; - my $prep_debbuilddir = $::workdir."/debbuild/"."prep-".$comp->{kitcompname}; + my $prep_debbuilddir = $::workdir . "/debbuild/" . "prep-" . $comp->{kitcompname}; my $prep_debianbuildcmd = "cd $prep_debbuilddir;debchange -v $prep_compversion -b -c debian/changelog $prep_buildstring;dpkg-buildpackage $dpkg_flag"; - if ( system($prep_debianbuildcmd) ) { + if (system($prep_debianbuildcmd)) { print "Error running \"dpkg-buildpackage $dpkg_flag\" command for kit component prep-$comp->{kitcompname} meta package\n"; return 1; } } + #Create debian directory for this kit component metapackage - if ( &gen_kitcomp_debdir($comp,\%repo,'METADEB') ) { return 1; } + if (&gen_kitcomp_debdir($comp, \%repo, 'METADEB')) { return 1; } } else { + #Create debian directory for this kit component - if ( &gen_kitcomp_debdir($comp,\%repo,'ALL') ) { return 1; } + if (&gen_kitcomp_debdir($comp, \%repo, 'ALL')) { return 1; } } - if (defined($comp->{non_native_pkgs}) ) { - my $sourcedir = $::workdir."/source_packages"; + if (defined($comp->{non_native_pkgs})) { + my $sourcedir = $::workdir . "/source_packages"; foreach my $pkgfile (split(/,/, $comp->{non_native_pkgs})) { my $pkg_file; - my ($key,$value) = split /:/,$pkgfile; + my ($key, $value) = split /:/, $pkgfile; if ("$key" =~ /EXTERNALPKGS/) { $pkg_file = $value; } else { @@ -2495,7 +2536,7 @@ sub build_kitcomp_debian{ } $cmd = "cp -p $sourcedir/$pkg_file $debbuilddir"; - if ( system($cmd) ) { + if (system($cmd)) { print "Error copying non-native package file $sourcedir/$pkg_file to debbuilddir\n"; return 1; } @@ -2504,16 +2545,16 @@ sub build_kitcomp_debian{ my $compversion = $comp->{version} . "-" . $comp->{release}; my $buildstring = "\'Kit component build package.\'"; my $debianbuildcmd = "cd $debbuilddir;debchange -v $compversion -b -c debian/changelog $buildstring;dpkg-buildpackage $dpkg_flag"; - if ( !$::NON_NATIVE_PKGS->{$comp->{kitcompname}} ) { - if ( system($debianbuildcmd) ) { + if (!$::NON_NATIVE_PKGS->{ $comp->{kitcompname} }) { + if (system($debianbuildcmd)) { print "Error running \"dpkg-buildpackage $dpkg_flag\" command for kit component $comp->{kitcompname} meta package\n"; return 1; } - my $repodir = $::base_repodir."/".$repo{kitreponame}; + my $repodir = $::base_repodir . "/" . $repo{kitreponame}; my @builtdebs = `find $::workdir/debbuild -maxdepth 1 -name "*.deb"`; foreach my $deb (@builtdebs) { chomp($deb); - if ( system ("cp -fp $deb $repodir") ) { + if (system("cp -fp $deb $repodir")) { print "Error copying package $deb to build repo directory $repodir \n"; return 1; } @@ -2532,22 +2573,22 @@ sub build_kitcomp_debian{ =cut #----------------------------------------------------------------------------- -sub gen_kitcomp_debdir_prep{ - my $comp = shift; - my $repo = shift; - my $scriptdir = $::workdir."/scripts/"; - my $combuilddir = $::workdir."/debbuild/"."prep-".$comp->{kitcompname}; +sub gen_kitcomp_debdir_prep { + my $comp = shift; + my $repo = shift; + my $scriptdir = $::workdir . "/scripts/"; + my $combuilddir = $::workdir . "/debbuild/" . "prep-" . $comp->{kitcompname}; #copy the debian dir template to the build path mkpath("$combuilddir/debian"); my $cmd = "cp -Rf " . $::XCATSHARE . "/kits/debian_template/* $combuilddir/debian/"; system($cmd); - my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; - my $kitcompname = "prep-".$comp->{kitcompname}; - my $upgradeflag = "pre-".$comp->{basename} . ".tmp"; + my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; + my $kitcompname = "prep-" . $comp->{kitcompname}; + my $upgradeflag = "pre-" . $comp->{basename} . ".tmp"; - my ($prescript,$postscript,$preupscript,$postupscript,$preunscript,$postunscript,$nonnativepkgs) = ''; + my ($prescript, $postscript, $preupscript, $postupscript, $preunscript, $postunscript, $nonnativepkgs) = ''; if (defined($comp->{preinstall})) { $prescript = &load_script("$scriptdir$comp->{preinstall}"); } @@ -2559,30 +2600,30 @@ sub gen_kitcomp_debdir_prep{ } #replace all special sub string in all files under debian - unless (opendir(DH, "${combuilddir}/debian/")){ + unless (opendir(DH, "${combuilddir}/debian/")) { print "Can not open the xCAT Kit Component debian dir: ${combuilddir}/debian/"; return 1; } - foreach (readdir(DH)){ + foreach (readdir(DH)) { my $file = "${combuilddir}/debian/$_"; - if ( -d $file){ + if (-d $file) { next; } - unless ( open ( FH, "<", $file )){ + unless (open(FH, "<", $file)) { print "Error attempting to open the xCAT Kit Component ${kitcompname}'s debian template file $file.\n"; close(DH); return 1; } - if ($::VERBOSE){ + if ($::VERBOSE) { print "Reading the xCAT Kit Component ${kitcompname}'s debian template file $file. \n"; } my @lines = ; close(FH); - my $prep_comp_name="prep-".$comp->{basename}; - for(@lines) { + my $prep_comp_name = "prep-" . $comp->{basename}; + for (@lines) { chomp; s/<<>>/$prep_comp_name/; s/<<>>/$comp->{ospkgdeps}/; @@ -2599,10 +2640,10 @@ sub gen_kitcomp_debdir_prep{ } my $joined_lines = join("\n", @lines); - @lines = split(/\\n/,$joined_lines); + @lines = split(/\\n/, $joined_lines); - open (FH, ">", $file); - if ($::VERBOSE){ + open(FH, ">", $file); + if ($::VERBOSE) { print "Created kitcomponent ${kitcompname}'s build file under debian dir $file"; } print FH @lines; @@ -2624,28 +2665,28 @@ sub gen_kitcomp_debdir_prep{ =cut #----------------------------------------------------------------------------- -sub gen_kitcomp_debdir{ - my $comp = shift; - my $repo = shift; - my $level = shift; - my $scriptdir = $::workdir."/scripts/"; - my $combuilddir = $::workdir."/debbuild/".$comp->{kitcompname}; +sub gen_kitcomp_debdir { + my $comp = shift; + my $repo = shift; + my $level = shift; + my $scriptdir = $::workdir . "/scripts/"; + my $combuilddir = $::workdir . "/debbuild/" . $comp->{kitcompname}; #copy the debian dir template to the build path mkpath("$combuilddir/debian"); my $cmd = "cp -Rf " . $::XCATSHARE . "/kits/debian_template/* $combuilddir/debian/"; system($cmd); - my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; + my $kitname = $::bldkit_config->{kit}{entries}[0]->{basename}; my $kitcompname = $comp->{kitcompname}; my $upgradeflag = $comp->{basename} . ".tmp"; - my ($prescript,$postscript,$preupscript,$postupscript,$preunscript,$postunscript,$nonnativepkgs) = ''; + my ($prescript, $postscript, $preupscript, $postupscript, $preunscript, $postunscript, $nonnativepkgs) = ''; if ($level eq 'METADEB' || $level eq 'ALL') { if (defined($comp->{postinstall})) { - $postscript = &load_script("$scriptdir$comp->{postinstall}"); + $postscript = &load_script("$scriptdir$comp->{postinstall}"); } if (defined($comp->{postupgrade})) { @@ -2663,7 +2704,7 @@ sub gen_kitcomp_debdir{ if ($level eq 'ALL') { if (defined($comp->{preinstall})) { - $prescript = &load_script("$scriptdir$comp->{preinstall}"); + $prescript = &load_script("$scriptdir$comp->{preinstall}"); } if (defined($comp->{preupgrade})) { $preupscript = &load_script("$scriptdir$comp->{preupgrade}"); @@ -2671,44 +2712,44 @@ sub gen_kitcomp_debdir{ if (defined($comp->{preuninstall})) { $preunscript = &load_script("$scriptdir$comp->{preuninstall}"); } - } + } #replace all special sub string in all files under debian - unless (opendir(DH, "${combuilddir}/debian/")){ + unless (opendir(DH, "${combuilddir}/debian/")) { print "Can not open the xCAT Kit Component debian dir: ${combuilddir}/debian/"; return 1; } - - foreach (readdir(DH)){ + + foreach (readdir(DH)) { my $file = "${combuilddir}/debian/$_"; - if ( -d $file){ + if (-d $file) { next; } - unless ( open ( FH, "<", $file )){ + unless (open(FH, "<", $file)) { print "Error attempting to open the xCAT Kit Component ${kitcompname}'s debian template file $file.\n"; close(DH); return 1; } - if ($::VERBOSE){ + if ($::VERBOSE) { print "Reading the xCAT Kit Component ${kitcompname}'s debian template file $file. \n"; } my @lines = ; close(FH); - my $prepcomp="prep-".$comp->{basename}; - for(@lines) { + my $prepcomp = "prep-" . $comp->{basename}; + for (@lines) { chomp; s/<<>>/$comp->{basename}/; s/<<>>/$comp->{ospkgdeps}/; s/<<>>/$comp->{kitpkgdeps}/; - if ( $::VALID_PREP_COMPONENT ) { - s/<<>>/$comp->{kitcompdeps},$prepcomp/; + if ($::VALID_PREP_COMPONENT) { +s/<<>>/$comp->{kitcompdeps},$prepcomp/; } else { - s/<<>>/$comp->{kitcompdeps}/; +s/<<>>/$comp->{kitcompdeps}/; } s/<<>>/$comp->{description}/; @@ -2718,13 +2759,13 @@ sub gen_kitcomp_debdir{ s/<<>>/$preupscript/; s/<<>>/$postupscript/; s/<<>>/$preunscript/; - s/<<>>/$postunscript/; +s/<<>>/$postunscript/; } my $joined_lines = join("\n", @lines); - @lines = split(/\\n/,$joined_lines); - - open (FH, ">", $file); - if ($::VERBOSE){ + @lines = split(/\\n/, $joined_lines); + + open(FH, ">", $file); + if ($::VERBOSE) { print "Created kitcomponent ${kitcompname}'s build file under debian dir $file"; } print FH @lines; @@ -2733,20 +2774,20 @@ sub gen_kitcomp_debdir{ closedir(DH); if (defined($comp->{non_native_pkgs})) { - unless (open (FH, ">", "${combuilddir}/debian/dir")) { + unless (open(FH, ">", "${combuilddir}/debian/dir")) { print "Error attempting to open the xCAT Kit Component ${kitcompname}'s debian file dir.\n"; return 1; } print FH "opt/xcat/kits/$kitname/$kitcompname/"; - close (FH); + close(FH); - unless ( open (FH, ">", "${combuilddir}/debian/install") ){ + unless (open(FH, ">", "${combuilddir}/debian/install")) { print "Error attempting to open the xCAT Kit Component ${kitcompname}'s debian file dir.\n"; return 1; } foreach my $pkgfile (split(/,/, $comp->{non_native_pkgs})) { my $pkgname = ''; - my ($key,$value) = split /:/,$pkgfile; + my ($key, $value) = split /:/, $pkgfile; if ("$key" =~ /EXTERNALPKGS/) { $pkgname = $value; } else { @@ -2774,8 +2815,8 @@ sub load_script { my $scriptname = shift; my $SF; - unless ( open( $SF, "<", $scriptname ) ) { - print "Error attempting to open the file $scriptname. \n"; + unless (open($SF, "<", $scriptname)) { + print "Error attempting to open the file $scriptname. \n"; return; } if ($::VERBOSE) { @@ -2802,144 +2843,147 @@ sub create_kitconf # Build kit config file entries from buildkit config input my $kitname = $::bldkit_config->{kit}{entries}[0]->{kitname}; foreach my $s (keys %{$::bldkit_config}) { - if (! defined($::buildkit_def{$s}) ) { next;} - if ( $s eq 'kitpackage' ) { next; } - my $li = 0; - foreach my $se (@{$::bldkit_config->{$s}{entries}}) { - $::kit_config->{$s}{entries}[$li]->{kitname} = $kitname; - # copy all defined attrs over - foreach my $a (keys %{$::buildkit_def{$s}}) { - if (( $::buildkit_def{$s}{$a}->{cp_to_kitconfig} eq '1' ) && - ( defined ($se->{$a}) ) ) { - if ( $s eq 'kitcomponent' ) { - if ($a eq 'kitpkgdeps') { - my $value; - foreach my $d (split(/,/, $se->{$a})) { - $d =~ s/\s+//g; - $d =~ s/^([\w\.\-]+)[<>=]*.*$/$1/; - $value .= "$d,"; + if (!defined($::buildkit_def{$s})) { next; } + if ($s eq 'kitpackage') { next; } + my $li = 0; + foreach my $se (@{ $::bldkit_config->{$s}{entries} }) { + $::kit_config->{$s}{entries}[$li]->{kitname} = $kitname; + + # copy all defined attrs over + foreach my $a (keys %{ $::buildkit_def{$s} }) { + if (($::buildkit_def{$s}{$a}->{cp_to_kitconfig} eq '1') && + (defined($se->{$a}))) { + if ($s eq 'kitcomponent') { + if ($a eq 'kitpkgdeps') { + my $value; + foreach my $d (split(/,/, $se->{$a})) { + $d =~ s/\s+//g; + $d =~ s/^([\w\.\-]+)[<>=]*.*$/$1/; + $value .= "$d,"; + } + $value =~ s/(\,)*$//; + $se->{$a} = $value; + } + } + $::kit_config->{$s}{entries}[$li]->{$a} = $se->{$a}; + } + + # cp_to_kitconfig=2 means copy the file to the new kit + # but only do the copy if this is a final kit build + if (($::buildkit_def{$s}{$a}->{cp_to_kitconfig} eq '2') && + (defined($se->{$a})) && + !$::HAVE_EXTERNAL_PKG && !$::HAVE_NON_NATIVE_PKGS) { + my $prefix = "$kitname"; + if ($s eq 'kitcomponent') { + $prefix = "$::bldkit_config->{$s}{entries}[$li]->{kitcompname}"; + if (($a eq 'postbootscripts') || + ($a eq 'genimage_postinstall')) { + $prefix = "KIT_" . $prefix; + } + if (!($::kit_config->{$s}{entries}[$li]->{$a} = + &cp_to_builddir($a, $se->{$a}, $::workdir . '/' . $::buildkit_def{$s}{$a}->{base_dir}, $prefix, $::bldkit_config->{$s}{entries}[$li]))) { + return 1; + } + } else { + if (!($::kit_config->{$s}{entries}[$li]->{$a} = + &cp_to_builddir($a, $se->{$a}, $::workdir . '/' . $::buildkit_def{$s}{$a}->{base_dir}, $prefix))) { + return 1; + } } - $value =~ s/(\,)*$//; - $se->{$a} = $value; } } - $::kit_config->{$s}{entries}[$li]->{$a} = $se->{$a}; - } - # cp_to_kitconfig=2 means copy the file to the new kit - # but only do the copy if this is a final kit build - if (( $::buildkit_def{$s}{$a}->{cp_to_kitconfig} eq '2' ) && - ( defined ($se->{$a}) ) && - !$::HAVE_EXTERNAL_PKG && !$::HAVE_NON_NATIVE_PKGS ) { - my $prefix = "$kitname"; - if ( $s eq 'kitcomponent' ) { - $prefix = "$::bldkit_config->{$s}{entries}[$li]->{kitcompname}"; - if (($a eq 'postbootscripts') || - ($a eq 'genimage_postinstall')) { - $prefix = "KIT_".$prefix; - } - if ( !($::kit_config->{$s}{entries}[$li]->{$a} = - &cp_to_builddir($a,$se->{$a},$::workdir.'/'.$::buildkit_def{$s}{$a}->{base_dir},$prefix, $::bldkit_config->{$s}{entries}[$li])) ) { - return 1; - } - } else { - if ( !($::kit_config->{$s}{entries}[$li]->{$a} = - &cp_to_builddir($a,$se->{$a},$::workdir.'/'.$::buildkit_def{$s}{$a}->{base_dir},$prefix)) ) { - return 1; + + # Handle special attrs, these 3 attributes did not defined in the buildkit.conf, special cases. + if ($s eq 'kitrepo') { + $::kit_config->{$s}{entries}[$li]->{kitreponame} = + $se->{kitreponame}; + } elsif ($s eq 'kitcomponent') { + $::kit_config->{$s}{entries}[$li]->{kitcompname} = + $se->{kitcompname}; + $::kit_config->{$s}{entries}[$li]->{kitreponame} = + $se->{kitreponame}; + if (!$::PREREQUISITE and ($se->{ospkgdeps} || $se->{preinstall} || $se->{preupgrade} || $se->{preuninstall})) { + if ($debianflag) { + $::kit_config->{$s}{entries}[$li]->{prerequisite} = + "prep-" . $se->{basename}; + } else { + $::kit_config->{$s}{entries}[$li]->{prerequisite} = + "prep_" . $se->{basename}; + } } } - } + $li++; } - # Handle special attrs, these 3 attributes did not defined in the buildkit.conf, special cases. - if ( $s eq 'kitrepo' ) { - $::kit_config->{$s}{entries}[$li]->{kitreponame} = - $se->{kitreponame}; - } elsif ( $s eq 'kitcomponent' ) { - $::kit_config->{$s}{entries}[$li]->{kitcompname} = - $se->{kitcompname}; - $::kit_config->{$s}{entries}[$li]->{kitreponame} = - $se->{kitreponame}; - if ( !$::PREREQUISITE and ($se->{ospkgdeps} || $se->{preinstall} || $se->{preupgrade} || $se->{preuninstall}) ) { - if ( $debianflag ){ - $::kit_config->{$s}{entries}[$li]->{prerequisite} = - "prep-" . $se->{basename}; - }else{ - $::kit_config->{$s}{entries}[$li]->{prerequisite} = - "prep_" . $se->{basename}; - } - } - } - $li++; - } } # Handle external packages if ($::HAVE_EXTERNAL_PKG) { - foreach my $kp (@{$::bldkit_config->{kitpackage}{entries}}) { - if ($kp->{isexternalpkg} eq 'yes') { - my %current_entry; - $current_entry{filename} = $kp->{filename}; - $current_entry{kitreponame} = $kp->{kitreponame}; - push ( @{ $::kit_config->{EXTERNALPKG}{'entries'} }, {%current_entry}); + foreach my $kp (@{ $::bldkit_config->{kitpackage}{entries} }) { + if ($kp->{isexternalpkg} eq 'yes') { + my %current_entry; + $current_entry{filename} = $kp->{filename}; + $current_entry{kitreponame} = $kp->{kitreponame}; + push(@{ $::kit_config->{EXTERNALPKG}{'entries'} }, {%current_entry}); + } } - } } # Handle non_native_pkgs - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { - if ($::NON_NATIVE_PKGS->{$kc->{kitcompname}}) { - my @nativefiles; - foreach my $pkgfile (split(/,/, $kc->{non_native_pkgs})) { - my ($key,$value) = split /:/,$pkgfile; - if ("$key" =~ /EXTERNALPKGS/) { - push (@nativefiles, $value); - } + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + if ($::NON_NATIVE_PKGS->{ $kc->{kitcompname} }) { + my @nativefiles; + foreach my $pkgfile (split(/,/, $kc->{non_native_pkgs})) { + my ($key, $value) = split /:/, $pkgfile; + if ("$key" =~ /EXTERNALPKGS/) { + push(@nativefiles, $value); + } + } + + my %current_entry; + $current_entry{filename} = join ',', @nativefiles; + $current_entry{kitcompname} = $kc->{kitcompname}; + $current_entry{basename} = $kc->{basename}; + $current_entry{kitreponame} = $kc->{kitreponame}; + push(@{ $::kit_config->{NONNATIVEPKGS}{'entries'} }, {%current_entry}); } - - my %current_entry; - $current_entry{filename} = join ',', @nativefiles; - $current_entry{kitcompname} = $kc->{kitcompname}; - $current_entry{basename} = $kc->{basename}; - $current_entry{kitreponame} = $kc->{kitreponame}; - push ( @{ $::kit_config->{NONNATIVEPKGS}{'entries'} }, {%current_entry}); - } } # Write Kit Config File my @lines; - my $li=0; - $lines[$li++] = "# Kit Configuration File for $kitname generated by buildkit\n"; - $lines[$li++] = "kitbuildinfo: \n"; + my $li = 0; + $lines[ $li++ ] = "# Kit Configuration File for $kitname generated by buildkit\n"; + $lines[ $li++ ] = "kitbuildinfo: \n"; my $xCAT_buildkit_version = ''; - if ( $debianflag ){ + if ($debianflag) { $xCAT_buildkit_version = `dpkg-query --show -f='\${Version}' xcat-buildkit`; } - else{ + else { $xCAT_buildkit_version = `rpm -q --qf \"%{VERSION}-%{RELEASE}\" xCAT-buildkit`; } - $lines[$li++] = " xCAT_version = $xCAT_buildkit_version \n"; - $lines[$li++] = " build_date = ".localtime()."\n"; - $lines[$li++] = " kitframework = $::KITFRAMEWORK \n"; - $lines[$li++] = " compatible_kitframeworks = $::COMPATIBLE_KITFRAMEWORKS \n"; + $lines[ $li++ ] = " xCAT_version = $xCAT_buildkit_version \n"; + $lines[ $li++ ] = " build_date = " . localtime() . "\n"; + $lines[ $li++ ] = " kitframework = $::KITFRAMEWORK \n"; + $lines[ $li++ ] = " compatible_kitframeworks = $::COMPATIBLE_KITFRAMEWORKS \n"; - foreach my $s ('kit','kitrepo','kitcomponent','EXTERNALPKG', 'NONNATIVEPKGS') { - foreach my $se (@{$::kit_config->{$s}{entries}}) { - $lines[$li++] = "$s: \n"; - foreach my $a (keys %{$se}) { - $lines[$li++] = " $a = $se->{$a} \n"; + foreach my $s ('kit', 'kitrepo', 'kitcomponent', 'EXTERNALPKG', 'NONNATIVEPKGS') { + foreach my $se (@{ $::kit_config->{$s}{entries} }) { + $lines[ $li++ ] = "$s: \n"; + foreach my $a (keys %{$se}) { + $lines[ $li++ ] = " $a = $se->{$a} \n"; + } } - } } - if ( (! -d $::deploy_dir) && (! mkpath($::deploy_dir)) ) { + if ((!-d $::deploy_dir) && (!mkpath($::deploy_dir))) { print "Error creating build directory $::deploy_dir.\n"; return; } - my $full_kit_conf = $::deploy_dir."/".$::kit_conf; + my $full_kit_conf = $::deploy_dir . "/" . $::kit_conf; my $NCF; - unless ( open( $NCF, ">$full_kit_conf" ) ) { + unless (open($NCF, ">$full_kit_conf")) { return 1; } if ($::VERBOSE) { @@ -2963,47 +3007,48 @@ sub create_kitconf #----------------------------------------------------------------------------- sub cp_to_builddir { - my $type = shift; - my $files = shift; + my $type = shift; + my $files = shift; my $from_dir = shift; - my $prefix = shift; - my $kitcomp = shift; + my $prefix = shift; + my $kitcomp = shift; my $copied_files; - my $other_files = $::deploy_dir."/other_files"; - if ( (! -d $other_files) && (! mkpath($other_files)) ) { + my $other_files = $::deploy_dir . "/other_files"; + if ((!-d $other_files) && (!mkpath($other_files))) { print "Error creating build directory $other_files.\n"; return; } foreach my $file (split(/\,/, $files)) { $file =~ s/\s+//g; - my $from_file = $from_dir."/".$file; - my $from_file_base = basename($file); - my $to_file_base = $prefix."_".$from_file_base; - my $to_file = $other_files."/".$to_file_base; + my $from_file = $from_dir . "/" . $file; + my $from_file_base = basename($file); + my $to_file_base = $prefix . "_" . $from_file_base; + my $to_file = $other_files . "/" . $to_file_base; # Read in the file my $FF; - unless ( open( $FF, "<", $from_file ) ) { - print "The Kit file $from_file could not be read. \n"; + unless (open($FF, "<", $from_file)) { + print "The Kit file $from_file could not be read. \n"; return 1; } my @lines = <$FF>; for (@lines) { - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitname}/g; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{basename}/g; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{version}/g; - s/<<>>/$::bldkit_config->{kit}{entries}[0]->{release}/g; - if ( defined ($kitcomp) ) { - s/<<>>/$kitcomp->{kitcompname}/g; - s/<<>>/$kitcomp->{basename}/g; - s/<<>>/$kitcomp->{version}/g; - s/<<>>/$kitcomp->{release}/g; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{kitname}/g; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{basename}/g; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{version}/g; +s/<<>>/$::bldkit_config->{kit}{entries}[0]->{release}/g; + if (defined($kitcomp)) { +s/<<>>/$kitcomp->{kitcompname}/g; +s/<<>>/$kitcomp->{basename}/g; +s/<<>>/$kitcomp->{version}/g; +s/<<>>/$kitcomp->{release}/g; } } + # Write the file back out my $TF; - unless ( open( $TF, ">$to_file" ) ) { + unless (open($TF, ">$to_file")) { print "Error copying file $from_file to build directory $other_files \n"; return 1; } @@ -3014,8 +3059,8 @@ sub cp_to_builddir close($TF); $copied_files .= ",$to_file_base"; - - if (($type eq 'postbootscripts') || + + if (($type eq 'postbootscripts') || ($type eq 'genimage_postinstall')) { system("chmod 755 $to_file"); } @@ -3044,67 +3089,71 @@ sub create_builddir # - exlists, postbootscripts, and deployparams already copied # copy plugins to build dir and edit to insert correct plugin and kit names - my $plugin_dir = $::deploy_dir."/plugins"; - if ( -d "$::workdir/plugins" ) { - if ( (! -d $plugin_dir) && (! mkpath($plugin_dir)) ) { + my $plugin_dir = $::deploy_dir . "/plugins"; + if (-d "$::workdir/plugins") { + if ((!-d $plugin_dir) && (!mkpath($plugin_dir))) { print "Error creating build directory $plugin_dir.\n"; return 1; } - - foreach my $plugin (<$::workdir/plugins/*.pm>){ + + foreach my $plugin (<$::workdir/plugins/*.pm>) { my $plugin_base = basename($plugin); my $mod_kitname = $kitname; $mod_kitname =~ s/\-/\_/g; $mod_kitname =~ s/\./\_/g; - my $to_plugin = $plugin_dir."/".$mod_kitname."_".$plugin_base; + my $to_plugin = $plugin_dir . "/" . $mod_kitname . "_" . $plugin_base; + + if (system("cp -fp $plugin $to_plugin")) { - if ( system("cp -fp $plugin $to_plugin") ) { # non-zero return from system call print "Error copying plugin file $plugin to build directory $plugin_dir \n"; return 1; } - if (&edit_plugin($to_plugin)) { return 1;} + if (&edit_plugin($to_plugin)) { return 1; } } - } + } # copy docs to build dir - if ( -d "$::workdir/docs" ) { - if ( system("cp -fRp $::workdir/docs $::deploy_dir") ) { + if (-d "$::workdir/docs") { + if (system("cp -fRp $::workdir/docs $::deploy_dir")) { + # non-zero return from system call print "Error copying doc files $::workdir/docs to build directory $::deploy_dir \n"; return 1; } - } - - # Edit deploy params file to make sure correct format for xCAT - if (defined($::kit_config->{kit}{entries}[0]->{kitdeployparams})){ - my $kd_file = $::deploy_dir."/other_files/".$::kit_config->{kit}{entries}[0]->{kitdeployparams}; - if (&edit_deployparams($kd_file)) { return 1;} } - if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { + # Edit deploy params file to make sure correct format for xCAT + if (defined($::kit_config->{kit}{entries}[0]->{kitdeployparams})) { + my $kd_file = $::deploy_dir . "/other_files/" . $::kit_config->{kit}{entries}[0]->{kitdeployparams}; + if (&edit_deployparams($kd_file)) { return 1; } + } + + if ($::HAVE_EXTERNAL_PKG or $::HAVE_NON_NATIVE_PKGS) { + # Copy the kitcomponent meta rpm spec if there is external non_native_pkgs. - if ( $debianflag ) { + if ($debianflag) { foreach my $comp (keys %{$::NON_NATIVE_PKGS}) { my $kitrepo; - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { if ($comp eq $kc->{kitcompname}) { - $kitrepo = $kc->{kitreponame} + $kitrepo = $kc->{kitreponame} } } mkpath("$::deploy_dir/tmp/"); my $cmd = "cp -fRP $::workdir/debbuild/$comp $::deploy_dir/tmp/$comp"; - if ( system("$cmd") ) { + if (system("$cmd")) { print "Error copying kitcomponent meta debian build file $::workdir/debbuild/$comp to build directory $::deploy_dir \n"; return 1; } } } - + # Copy over the original buildkit.conf file and input files # to help make addpkgs processing easier later mkpath("$::deploy_dir/build_input/"); - if ( system("cp -fp $::full_buildkit_conf $::deploy_dir/build_input") ) { + if (system("cp -fp $::full_buildkit_conf $::deploy_dir/build_input")) { + # non-zero return from system call print "Error copying buildkit config file $::full_buildkit_conf to build directory $::deploy_dir/build_input \n"; return 1; @@ -3135,52 +3184,58 @@ sub create_PARTIAL_builddir # - exlists, postbootscripts, and deployparams already copied # copy docs to build dir - if ( -d "$::workdir/docs" ) { - if ( system("cp -fRp $::workdir/docs $::deploy_dir") ) { + if (-d "$::workdir/docs") { + if (system("cp -fRp $::workdir/docs $::deploy_dir")) { + # non-zero return from system call print "Error copying doc files $::workdir/docs to build directory $::deploy_dir \n"; return 1; } - } - + } + # Copy over the original buildkit.conf file and input files # to help make addpkgs processing easier later mkpath("$::deploy_dir/build_input/"); - if ( system("cp -fp $::full_buildkit_conf $::deploy_dir/build_input") ) { + if (system("cp -fp $::full_buildkit_conf $::deploy_dir/build_input")) { + # non-zero return from system call print "Error copying buildkit config file $::full_buildkit_conf to build directory $::deploy_dir/build_input \n"; return 1; } - if ( -d "$::workdir/other_files" ) { - if ( system("cp -fpR $::workdir/other_files $::deploy_dir/build_input") ) { + if (-d "$::workdir/other_files") { + if (system("cp -fpR $::workdir/other_files $::deploy_dir/build_input")) { + # non-zero return from system call print "Error copying $::workdir/otherfiles to build directory $::deploy_dir/build_input \n"; return 1; } } - if ( -d "$::workdir/plugins" ) { - if ( system("cp -fpR $::workdir/plugins $::deploy_dir/build_input") ) { + if (-d "$::workdir/plugins") { + if (system("cp -fpR $::workdir/plugins $::deploy_dir/build_input")) { + # non-zero return from system call print "Error copying $::workdir/plugins to build directory $::deploy_dir/build_input \n"; return 1; } } - if ( -d "$::workdir/scripts" ) { - if ( system("cp -fpR $::workdir/scripts $::deploy_dir/build_input") ) { + if (-d "$::workdir/scripts") { + if (system("cp -fpR $::workdir/scripts $::deploy_dir/build_input")) { + # non-zero return from system call print "Error copying $::workdir/scripts to build directory $::deploy_dir/build_input \n"; return 1; } } + # Copy over any provided non-native packages my $to_source_dir = "$::deploy_dir/build_input/source_packages"; mkpath("$to_source_dir"); - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { - if (defined($kc->{non_native_pkgs}) ) { - my $sourcedir = $::workdir."/source_packages"; + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + if (defined($kc->{non_native_pkgs})) { + my $sourcedir = $::workdir . "/source_packages"; foreach my $pkgfile (split(/,/, $kc->{non_native_pkgs})) { my $pkg_file; - my ($key,$value) = split /:/,$pkgfile; + my ($key, $value) = split /:/, $pkgfile; if ("$key" =~ /EXTERNALPKGS/) { next; } else { @@ -3188,7 +3243,7 @@ sub create_PARTIAL_builddir } my $cmd = "cp -p $sourcedir/$pkg_file $to_source_dir"; - if ( system($cmd) ) { + if (system($cmd)) { print "Error copying non-native package file $sourcedir/$pkg_file to $to_source_dir \n"; return 1; } @@ -3212,13 +3267,13 @@ sub create_PARTIAL_builddir #----------------------------------------------------------------------------- sub edit_deployparams { - my $file = shift; + my $file = shift; my $validate_only = shift; # read in the file my $DF; - unless ( open( $DF, "<", $file ) ) { - print "The Kit deployment parameters file $file could not be read. \n"; + unless (open($DF, "<", $file)) { + print "The Kit deployment parameters file $file could not be read. \n"; return 1; } my @lines = <$DF>; @@ -3230,36 +3285,41 @@ sub edit_deployparams my $ln = 0; foreach my $l (@lines) { $ln++; + # skip blank lines - if ( $l =~ /^\s*$/ ) { - push (@new_lines, $l); + if ($l =~ /^\s*$/) { + push(@new_lines, $l); next; - } + } + # #ENV lines - $l =~ s/^\s+//; # compress leading blanks - if ( $l =~ /^\#ENV\:/ ) { - if ( !($l =~ /\#\s*$/) ) { - chomp $l; - $l .= "#\n"; - $changed = 1; + $l =~ s/^\s+//; # compress leading blanks + if ($l =~ /^\#ENV\:/) { + if (!($l =~ /\#\s*$/)) { + chomp $l; + $l .= "#\n"; + $changed = 1; } - push (@new_lines, $l); + push(@new_lines, $l); next; } + # skip all other comments - if ( $l =~ /^\s*#/ ) { - push (@new_lines, $l); - next; - } - # Add #ENV if not specified - if ( $l =~ /^\w*\s*\=/ ) { - chomp $l; - $l = "#ENV: $l #"; - $changed = 1; - push (@new_lines, $l); + if ($l =~ /^\s*#/) { + push(@new_lines, $l); next; } - # Syntax error + + # Add #ENV if not specified + if ($l =~ /^\w*\s*\=/) { + chomp $l; + $l = "#ENV: $l #"; + $changed = 1; + push(@new_lines, $l); + next; + } + + # Syntax error print "Syntax error in kit deployment parameters file $file \n"; print "line $ln: \n"; print "$l \n"; @@ -3269,7 +3329,7 @@ sub edit_deployparams # Write the file back out if ($changed && !$validate_only) { my $NDF; - unless ( open( $NDF, ">$file" ) ) { + unless (open($NDF, ">$file")) { return 1; } if ($::VERBOSE) { @@ -3293,8 +3353,9 @@ sub edit_deployparams #----------------------------------------------------------------------------- sub edit_plugin { - my $file = shift; + my $file = shift; my $kitname = $::bldkit_config->{kit}{entries}[0]->{kitname}; + # convert dashes to underscore since the kitname is used as perl pkg names # in the plugin and this causes perl syntax errors my $mod_kitname = $kitname; @@ -3303,8 +3364,8 @@ sub edit_plugin # read in the file my $PF; - unless ( open( $PF, "<", $file ) ) { - print "The Kit plugin file $file could not be read. \n"; + unless (open($PF, "<", $file)) { + print "The Kit plugin file $file could not be read. \n"; return 1; } my @lines = <$PF>; @@ -3317,7 +3378,7 @@ sub edit_plugin # Write the plugin back out my $NPF; - unless ( open( $NPF, ">$file" ) ) { + unless (open($NPF, ">$file")) { return 1; } if ($::VERBOSE) { @@ -3340,9 +3401,9 @@ sub edit_plugin #----------------------------------------------------------------------------- sub kit_addpkgs { - # add RPM pkgs to an existing kit tarfile - my $kittarfile=$::KIT_ADDPKGS; - my $kitbfname = basename($kittarfile); + # add RPM pkgs to an existing kit tarfile + my $kittarfile = $::KIT_ADDPKGS; + my $kitbfname = basename($kittarfile); $kitbfname =~ s/.tar.bz2$//; $kitbfname =~ s/.NEED_PRODUCT_PKGS$//; my $tmpdir_base = "/tmp/$kitbfname"; @@ -3352,37 +3413,38 @@ sub kit_addpkgs # Cleanup - should have been removed when last command ran # - but just in case - system ("rm -Rf $tmpdir_base"); + system("rm -Rf $tmpdir_base"); # the tar file may not be in the current dir $kittarfile = "$::workdir/$kittarfile"; - if ( !(-r $kittarfile) ) { - print "The Kit tar file $kittarfile could not be read. \n"; + if (!(-r $kittarfile)) { + print "The Kit tar file $kittarfile could not be read. \n"; return 1; } $kittarfile = abs_path($kittarfile); foreach my $rpmdir (@pkgdirlist) { - if ( !(-d $rpmdir) ) { - print "The package directory $rpmdir could not be read. \n"; + if (!(-d $rpmdir)) { + print "The package directory $rpmdir could not be read. \n"; return 1; } } # Create work directory - if ( (! -d $tmpdir_base) && (! mkpath($tmpdir_base)) ) { - print "Error creating temporary work directory $tmpdir_base\n"; - return 1; - } + if ((!-d $tmpdir_base) && (!mkpath($tmpdir_base))) { + print "Error creating temporary work directory $tmpdir_base\n"; + return 1; + } print "Extracting tar file $kittarfile. Please wait.\n"; - if ( system("cd $tmpdir_base; tar -jxf $kittarfile ") ) { - print "Error extracting tarfile $kittarfile \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; + if (system("cd $tmpdir_base; tar -jxf $kittarfile ")) { + print "Error extracting tarfile $kittarfile \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; } my $tmp_kit_conf = `find $tmpdir_base -name kit.conf`; @@ -3391,10 +3453,11 @@ sub kit_addpkgs # read in the file my $CKF; - unless ( open( $CKF, "<", $tmp_kit_conf ) ) { - print "The Kit configuration file $tmp_kit_conf could not be read or was not included in the kit tar file. \n"; + unless (open($CKF, "<", $tmp_kit_conf)) { + print "The Kit configuration file $tmp_kit_conf could not be read or was not included in the kit tar file. \n"; + # Cleanup - system ("rm -Rf $tmpdir_base"); + system("rm -Rf $tmpdir_base"); return 1; } my @lines = <$CKF>; @@ -3402,11 +3465,12 @@ sub kit_addpkgs $::PREREQUISITE = 1; foreach my $l (@lines) { + # skip blank and comment lines - if ( $l =~ /^\s*$/ || $l =~ /^\s*#/ ) { + if ($l =~ /^\s*$/ || $l =~ /^\s*#/) { next; } - if ($l =~ /prerequisite/ ) { + if ($l =~ /prerequisite/) { $::PREREQUISITE = 0; } } @@ -3421,15 +3485,15 @@ sub kit_addpkgs # if this in not a partial kit then the framework must be 2 or greater my $kit_name = basename($kittarfile); - if ( (!($kit_name =~ /NEED_PRODUCT_PKGS/)) && ($::kitframework < 2) ) { + if ((!($kit_name =~ /NEED_PRODUCT_PKGS/)) && ($::kitframework < 2)) { print "This kit cannot be updated. To update a complete kit the kit framework\n value must be greater than or equal to 2. You can use the\n\t\'lskit -F \' \ncommand to check the framework value of the kit.\n"; - return 1; + return 1; } ### Check if this is a new partial kit built with xCAT 2.8.1 or newer if (-d "$tmpdir/build_input") { - system ("mv $tmpdir/build_input $tmpdir_base"); - return &NEW_kit_addpkgs($tmpdir_base,$tmpdir); + system("mv $tmpdir/build_input $tmpdir_base"); + return &NEW_kit_addpkgs($tmpdir_base, $tmpdir); } ### OLD KITS BUILT PRIOR TO xCAT 2.8.1 @@ -3440,267 +3504,281 @@ sub kit_addpkgs exit 1; } - my $rpmdir=$::PKGDIR; + my $rpmdir = $::PKGDIR; - my $ext_filename = ''; - my $ext_reponames = ''; - my $non_native_filename = ''; + my $ext_filename = ''; + my $ext_reponames = ''; + my $non_native_filename = ''; my $non_native_kitcompname = ''; - my $non_native_basename = ''; + my $non_native_basename = ''; my $non_native_kitreponame = ''; my %create_repodata_list; my @new_lines; - my $section = ''; - my $kitname = ''; + my $section = ''; + my $kitname = ''; my $kitbasename = ''; - my $kitversion = ''; - my $kitostype = ''; + my $kitversion = ''; + my $kitostype = ''; + foreach my $l (@lines) { + # skip blank and comment lines - if ( $l =~ /^\s*$/ || $l =~ /^\s*#/ ) { + if ($l =~ /^\s*$/ || $l =~ /^\s*#/) { push(@new_lines, $l); next; } + # new section? - if ( $l =~ /^\s*(\w+)\s*:/ ) { - $section = $1; - if ($section eq 'EXTERNALPKG') { - $ext_filename = ''; - $ext_reponames = ''; - next; - } - if ($section eq 'NONNATIVEPKGS') { - $non_native_filename = ''; - $non_native_kitcompname = ''; - $non_native_basename = ''; - $non_native_kitreponame = ''; - next; - } - push(@new_lines, $l); - next; + if ($l =~ /^\s*(\w+)\s*:/) { + $section = $1; + if ($section eq 'EXTERNALPKG') { + $ext_filename = ''; + $ext_reponames = ''; + next; + } + if ($section eq 'NONNATIVEPKGS') { + $non_native_filename = ''; + $non_native_kitcompname = ''; + $non_native_basename = ''; + $non_native_kitreponame = ''; + next; + } + push(@new_lines, $l); + next; } - if ( $l =~ /^\s*(\w+)\s*=\s*(.*)\s*/ ) { - my $attr = $1; - my $val = $2; - my $orig_attr = $attr; - my $orig_val = $val; - $attr =~ s/^\s*//; # Remove any leading whitespace - $attr =~ s/\s*$//; # Remove any trailing whitespace - $attr =~ tr/A-Z/a-z/; # Convert to lowercase - $val =~ s/^\s*//; - $val =~ s/\s*$//; + if ($l =~ /^\s*(\w+)\s*=\s*(.*)\s*/) { + my $attr = $1; + my $val = $2; + my $orig_attr = $attr; + my $orig_val = $val; + $attr =~ s/^\s*//; # Remove any leading whitespace + $attr =~ s/\s*$//; # Remove any trailing whitespace + $attr =~ tr/A-Z/a-z/; # Convert to lowercase + $val =~ s/^\s*//; + $val =~ s/\s*$//; - if ($section eq 'kit') { - if ( $attr eq 'basename' ) { $kitbasename = $val; } - if ( $attr eq 'version' ) { $kitversion = $val; } - if ( $attr eq 'ostype' ) { $kitostype = $val; } - if ( ($kitbasename ne '') && ($kitversion ne '') && - ($kitostype ne '') ) { - $kitname = "$kitbasename-$kitversion-$kitostype"; - } + if ($section eq 'kit') { + if ($attr eq 'basename') { $kitbasename = $val; } + if ($attr eq 'version') { $kitversion = $val; } + if ($attr eq 'ostype') { $kitostype = $val; } + if (($kitbasename ne '') && ($kitversion ne '') && + ($kitostype ne '')) { + $kitname = "$kitbasename-$kitversion-$kitostype"; + } } - if ($section eq 'EXTERNALPKG') { - if ($attr eq 'filename') { - $ext_filename = $val; - } elsif ($attr eq 'kitreponame') { - $ext_reponames = $val; - } else { - next; - } - if ( ($ext_filename ne '') && ($ext_reponames ne '') ){ - my $fromfile = $rpmdir."/".$ext_filename; - if ( system("ls $fromfile > /dev/null") ){ - print "The product package file $ext_filename could not be read from the package directory $rpmdir. \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } - foreach my $repo (split(/,/, $ext_reponames)) { - my $repodir = $tmpdir."/repos/".$repo; - if ( ! -d ($repodir) && (! mkpath($repodir)) ) { - print "Error creating repository directory $repodir\n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } - if (system("cp -fp $fromfile $repodir")) { - print "Error copying package file $fromfile to $repodir \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } - $create_repodata_list{$repodir}=1; - } - } - next; - } - - if ($section eq 'NONNATIVEPKGS') { - if ( $attr eq 'filename' ) { - $non_native_filename = $val; - } elsif ($attr eq 'kitcompname') { - $non_native_kitcompname = $val; - } elsif ($attr eq 'basename') { - $non_native_basename = $val; - } elsif ($attr eq 'kitreponame') { - $non_native_kitreponame = $val; - } else { - next; - } - if ( ($non_native_filename ne '') - && ($non_native_kitcompname ne '') - && ($non_native_basename ne '') - && ($non_native_kitreponame ne '')) { - #find out the useful dir - my $tdir = $tmpdir."/tmp/"; - my $source_dir = "$tdir/$non_native_kitcompname"; - my $spec = "$tdir/$non_native_kitcompname.spec"; - if (!-d "$tdir" or !-d "$source_dir") { - print "Error open kitcomponent rpm build direcotry $tdir or $tdir/$non_native_kitcompname \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; + if ($section eq 'EXTERNALPKG') { + if ($attr eq 'filename') { + $ext_filename = $val; + } elsif ($attr eq 'kitreponame') { + $ext_reponames = $val; + } else { + next; } + if (($ext_filename ne '') && ($ext_reponames ne '')) { + my $fromfile = $rpmdir . "/" . $ext_filename; + if (system("ls $fromfile > /dev/null")) { + print "The product package file $ext_filename could not be read from the package directory $rpmdir. \n"; - #copy the nan_native_pkgs to the source dir - foreach my $tepmfilename (split(/,/, $non_native_filename)){ - #the $non_native_filename may contain several pkgs, can check and copy at the same time - my $fromfile = $rpmdir."/".$tepmfilename; - if ( system("ls $fromfile > /dev/null") ){ - print "The product package file $non_native_filename could not be read from the package directory $rpmdir. \n"; - system ("rm -Rf $tmpdir_base"); - return 1; - } - if (system("cp -fp $fromfile $tdir/$non_native_kitcompname")) { - print "Error copying package file $fromfile to $tdir/$non_native_kitcompname \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } - } - #for debian/ubuntu - my $repodir = $tmpdir . "/repos/".$non_native_kitreponame; - if ( $debianflag ){ - my $debbuildcmd = "cd $source_dir;dpkg-buildpackage $dpkg_flag"; - if ( system($debbuildcmd) ){ - print "error running debian build cmd for kit component $non_native_basename meta package.\n"; + # Cleanup + system("rm -Rf $tmpdir_base"); return 1; } - my @debs = `find $tdir -maxdepth 1 -name "*.deb"`; - foreach my $debname (@debs){ - chomp($debname); - if ( system("mv -f $debname $repodir") ){ - print "Error copying package $debname to build repo directory $repodir. \n"; + foreach my $repo (split(/,/, $ext_reponames)) { + my $repodir = $tmpdir . "/repos/" . $repo; + if (!-d ($repodir) && (!mkpath($repodir))) { + print "Error creating repository directory $repodir\n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } + if (system("cp -fp $fromfile $repodir")) { + print "Error copying package file $fromfile to $repodir \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } + $create_repodata_list{$repodir} = 1; + } + } + next; + } + + if ($section eq 'NONNATIVEPKGS') { + if ($attr eq 'filename') { + $non_native_filename = $val; + } elsif ($attr eq 'kitcompname') { + $non_native_kitcompname = $val; + } elsif ($attr eq 'basename') { + $non_native_basename = $val; + } elsif ($attr eq 'kitreponame') { + $non_native_kitreponame = $val; + } else { + next; + } + if (($non_native_filename ne '') + && ($non_native_kitcompname ne '') + && ($non_native_basename ne '') + && ($non_native_kitreponame ne '')) { + + #find out the useful dir + my $tdir = $tmpdir . "/tmp/"; + my $source_dir = "$tdir/$non_native_kitcompname"; + my $spec = "$tdir/$non_native_kitcompname.spec"; + if (!-d "$tdir" or !-d "$source_dir") { + print "Error open kitcomponent rpm build direcotry $tdir or $tdir/$non_native_kitcompname \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } + + #copy the nan_native_pkgs to the source dir + foreach my $tepmfilename (split(/,/, $non_native_filename)) { + + #the $non_native_filename may contain several pkgs, can check and copy at the same time + my $fromfile = $rpmdir . "/" . $tepmfilename; + if (system("ls $fromfile > /dev/null")) { + print "The product package file $non_native_filename could not be read from the package directory $rpmdir. \n"; + system("rm -Rf $tmpdir_base"); + return 1; + } + if (system("cp -fp $fromfile $tdir/$non_native_kitcompname")) { + print "Error copying package file $fromfile to $tdir/$non_native_kitcompname \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); return 1; } } + + #for debian/ubuntu + my $repodir = $tmpdir . "/repos/" . $non_native_kitreponame; + if ($debianflag) { + my $debbuildcmd = "cd $source_dir;dpkg-buildpackage $dpkg_flag"; + if (system($debbuildcmd)) { + print "error running debian build cmd for kit component $non_native_basename meta package.\n"; + return 1; + } + my @debs = `find $tdir -maxdepth 1 -name "*.deb"`; + foreach my $debname (@debs) { + chomp($debname); + if (system("mv -f $debname $repodir")) { + print "Error copying package $debname to build repo directory $repodir. \n"; + return 1; + } + } + } + else { + if (!-r "$spec") { + print "Error open kitcomponent rpm build spec $tdir/$non_native_kitcompname.spec \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } + my $rpmbuild_dir = $tmpdir . "/rpmbuild"; + my $cmd = "rm -Rf $rpmbuild_dir"; + system($cmd); + + my $avoiderr = $rpmbuild_dir . "/BUILDROOT/"; + mkpath($avoiderr); + $avoiderr = $rpmbuild_dir . "/BUILD/"; + mkpath($avoiderr); + $avoiderr = $rpmbuild_dir . "/SRPMS/"; + mkpath($avoiderr); + $avoiderr = $rpmbuild_dir . "/RPMS/noarch/"; + mkpath($avoiderr); + + unless (open(SF, "<", $spec)) { + print "Error attempting to open spec $spec of kitcomponent $non_native_basename. \n"; + return 1; + } + + mkpath("$rpmbuild_dir/SOURCES"); + $cmd = "cd $source_dir/..;mv $non_native_kitcompname $non_native_basename; tar -czf $rpmbuild_dir/SOURCES/$non_native_basename.tar.gz $non_native_basename;mv $non_native_basename $non_native_kitcompname;"; + if (system($cmd)) { + print "Error creating tarfile $rpmbuild_dir/SOURCES/$non_native_basename.tar from $source_dir/*"; + return 1; + } + my $rpmbuild_cmd = "rpmbuild --define \"_topdir $rpmbuild_dir\" -ba $spec"; + if (!$::VERBOSE) { + $rpmbuild_cmd .= ' --quiet '; + } + if (system($rpmbuild_cmd)) { + print "Error running rpmbuild command for kit component $non_native_basename meta package\n"; + return 1; + } + + # Copy the built meta rpm to repo + my @built_rpms = `find $rpmbuild_dir/RPMS -name "*.rpm"`; + foreach my $rpm (@built_rpms) { + chomp($rpm); + if (system("cp -fp $rpm $repodir")) { + print "Error copying rpm $rpm to build repo directory $repodir \n"; + return 1; + } + } + } + $create_repodata_list{$repodir} = 1; } - else{ - if (!-r "$spec") { - print "Error open kitcomponent rpm build spec $tdir/$non_native_kitcompname.spec \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } - my $rpmbuild_dir = $tmpdir."/rpmbuild"; - my $cmd = "rm -Rf $rpmbuild_dir"; - system($cmd); - - my $avoiderr = $rpmbuild_dir."/BUILDROOT/"; - mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/BUILD/"; - mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/SRPMS/"; - mkpath($avoiderr); - $avoiderr = $rpmbuild_dir."/RPMS/noarch/"; - mkpath($avoiderr); - - unless ( open( SF, "<", $spec ) ) { - print "Error attempting to open spec $spec of kitcomponent $non_native_basename. \n"; - return 1; - } - - mkpath("$rpmbuild_dir/SOURCES"); - $cmd = "cd $source_dir/..;mv $non_native_kitcompname $non_native_basename; tar -czf $rpmbuild_dir/SOURCES/$non_native_basename.tar.gz $non_native_basename;mv $non_native_basename $non_native_kitcompname;"; - if ( system($cmd) ) { - print "Error creating tarfile $rpmbuild_dir/SOURCES/$non_native_basename.tar from $source_dir/*"; - return 1; - } - my $rpmbuild_cmd = "rpmbuild --define \"_topdir $rpmbuild_dir\" -ba $spec"; - if (!$::VERBOSE) { - $rpmbuild_cmd .= ' --quiet '; - } - if ( system($rpmbuild_cmd) ) { - print "Error running rpmbuild command for kit component $non_native_basename meta package\n"; - return 1; - } - - # Copy the built meta rpm to repo - my @built_rpms = `find $rpmbuild_dir/RPMS -name "*.rpm"`; - foreach my $rpm (@built_rpms) { - chomp($rpm); - if ( system ("cp -fp $rpm $repodir") ) { - print "Error copying rpm $rpm to build repo directory $repodir \n"; - return 1; - } - } - } - $create_repodata_list{$repodir}=1; - } - next; + next; } - + push(@new_lines, $l); } } # Re-write kit.conf with EXTERNALPKG and NONNATIVEPKGS sections removed my $NCF; - unless ( open( $NCF, ">$tmp_kit_conf" ) ) { + unless (open($NCF, ">$tmp_kit_conf")) { return 1; } print $NCF @new_lines; close($NCF); - + # Clean up RPMBUILD and tmp in kit directory my $cmd = "rm -Rf $tmpdir/tmp"; system("$cmd"); - unless ( $debianflag ){ + unless ($debianflag) { $cmd = "rm -Rf $tmpdir/rpmbuild"; system("$cmd"); } # Run createrepo for each updated directory foreach my $repo (keys(%create_repodata_list)) { - my $createrepocmd = ''; - if ( $debianflag ){ - $createrepocmd = "cd $repo;dpkg-scanpackages . > Packages"; - } - else{ - $createrepocmd = "createrepo $repo"; - } - if (system( $createrepocmd )) { - print "Error running $createrepocmd. \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } + my $createrepocmd = ''; + if ($debianflag) { + $createrepocmd = "cd $repo;dpkg-scanpackages . > Packages"; + } + else { + $createrepocmd = "createrepo $repo"; + } + if (system($createrepocmd )) { + print "Error running $createrepocmd. \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } } # Create new tar file in current directory - my $new_tarfile = $::workdir.'/'.$kitbfname.'.tar.bz2'; - if ( system("cd $tmpdir; cd ..; tar -cjhf $new_tarfile $kitname/*") ) { - print "Error building tarfile $new_tarfile \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; + my $new_tarfile = $::workdir . '/' . $kitbfname . '.tar.bz2'; + if (system("cd $tmpdir; cd ..; tar -cjhf $new_tarfile $kitname/*")) { + print "Error building tarfile $new_tarfile \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; } print "Kit tar file $new_tarfile successfully built \n"; - + # Cleanup - system ("rm -Rf $tmpdir_base"); + system("rm -Rf $tmpdir_base"); return 0; } @@ -3715,16 +3793,16 @@ sub kit_addpkgs #----------------------------------------------------------------------------- sub NEW_kit_addpkgs { - # add RPM pkgs to an existing kit tarfile + # add RPM pkgs to an existing kit tarfile my $tmpdir_base = shift; - my $tmpdir = shift; + my $tmpdir = shift; # - could be list of pkgdir dirs my @pkgdirlist = split(",", $::PKGDIR); - $::NEW_PARTIAL_KIT = 1; - $::workdir = "$tmpdir_base/build_input"; - $::full_buildkit_conf = $::workdir."/".$::buildkit_conf; + $::NEW_PARTIAL_KIT = 1; + $::workdir = "$tmpdir_base/build_input"; + $::full_buildkit_conf = $::workdir . "/" . $::buildkit_conf; $::deploy_dir = $tmpdir_base; #kitname appended by validate_bldkitconf routine my $tmp_buildkit_conf = `find $tmpdir_base -name $::buildkit_conf`; @@ -3735,79 +3813,82 @@ sub NEW_kit_addpkgs } my $loadrc = &load_bldkitconf($tmp_buildkit_conf); - if ( $loadrc != 0 ) { + if ($loadrc != 0) { print "Error reading buildkit config file $tmp_buildkit_conf \n"; - return 1; + return 1; } - - if ( defined($::KITVERSION) ) { + + if (defined($::KITVERSION)) { $::bldkit_config->{kit}{entries}[0]->{version} = $::KITVERSION; } - if ( defined($::KITRELEASE) ) { + if (defined($::KITRELEASE)) { $::bldkit_config->{kit}{entries}[0]->{release} = $::KITRELEASE; } my $chkrc = &validate_bldkitconf(); - if ( $chkrc != 0 ) { + if ($chkrc != 0) { print "Error validating buildkit config file $tmp_buildkit_conf \n"; - return 1; + return 1; } if ($tmpdir ne $::deploy_dir) { - if (system ("mv $tmpdir $::deploy_dir ") ) { + if (system("mv $tmpdir $::deploy_dir ")) { print "Error moving $tmpdir to $::deploy_dir \n"; return 1; } } - $::build_dir = $::deploy_dir; + $::build_dir = $::deploy_dir; $::base_repodir = "$::deploy_dir/repos"; my $kitname = $::bldkit_config->{kit}{entries}[0]->{kitname}; # Handle external packages if ($::HAVE_EXTERNAL_PKG) { - foreach my $kp (@{$::bldkit_config->{kitpackage}{entries}}) { - if ($kp->{isexternalpkg} eq 'yes') { - my $ext_filename = $kp->{filename}; - my $ext_reponames = $kp->{kitreponame}; - my $files; - if($debianflag){ - $files = xCAT::BuildKitUtils->find_latest_pkg_deb(\@pkgdirlist, $ext_filename); - } - else { - $files = xCAT::BuildKitUtils->find_latest_pkg(\@pkgdirlist, $ext_filename); - } - if (!defined($files) ) { - print "Error: The product package file $ext_filename was not found in the package directory(s) @pkgdirlist.\n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } + foreach my $kp (@{ $::bldkit_config->{kitpackage}{entries} }) { + if ($kp->{isexternalpkg} eq 'yes') { + my $ext_filename = $kp->{filename}; + my $ext_reponames = $kp->{kitreponame}; + my $files; + if ($debianflag) { + $files = xCAT::BuildKitUtils->find_latest_pkg_deb(\@pkgdirlist, $ext_filename); + } + else { + $files = xCAT::BuildKitUtils->find_latest_pkg(\@pkgdirlist, $ext_filename); + } + if (!defined($files)) { + print "Error: The product package file $ext_filename was not found in the package directory(s) @pkgdirlist.\n"; - my @fromfiles=@$files; + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } - foreach my $repo (split(/,/, $ext_reponames)) { - my $repodir = $::base_repodir."/".$repo; - if ( ! -d ($repodir) && (! mkpath($repodir)) ) { - print "Error creating repository directory $repodir\n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } + my @fromfiles = @$files; - foreach my $fromfile (@fromfiles) { - if (system("cp -fp $fromfile $repodir")) { - print "Error copying package file $fromfile to $repodir \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - return 1; - } - } - if ($::VERBOSE) { - print "Copied @fromfiles\n to $repodir\n"; - } - } + foreach my $repo (split(/,/, $ext_reponames)) { + my $repodir = $::base_repodir . "/" . $repo; + if (!-d ($repodir) && (!mkpath($repodir))) { + print "Error creating repository directory $repodir\n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } + + foreach my $fromfile (@fromfiles) { + if (system("cp -fp $fromfile $repodir")) { + print "Error copying package file $fromfile to $repodir \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + return 1; + } + } + if ($::VERBOSE) { + print "Copied @fromfiles\n to $repodir\n"; + } + } + } } - } } # Handle non_native_pkgs @@ -3817,121 +3898,123 @@ sub NEW_kit_addpkgs # these are not RPMs! my $to_source_dir = "$::workdir/source_packages"; mkpath("$to_source_dir"); - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { - if ($::NON_NATIVE_PKGS->{$kc->{kitcompname}}) { - my @nativefiles; - foreach my $pkgfile (split(/,/, $kc->{non_native_pkgs})) { - my ($key,$value) = split /:/,$pkgfile; - if ("$key" =~ /EXTERNALPKGS/) { - #the $non_native_filename may contain several pkgs, can check and copy at the same time - foreach my $nnpkg (split(/,/, $value)){ - my $found=0; - foreach my $pdir (@pkgdirlist) { - my $fromfile = $pdir."/".$nnpkg; - if ( system("ls $fromfile > /dev/null") ){ - next; - } else { - $found++; - if (system("cp -fp $fromfile $to_source_dir")) { - print "Error copying package file $fromfile to $to_source_dir \n"; - # Cleanup - system ("rm -Rf $tmpdir_base"); - next; - } else { - if ($::VERBOSE) { - print "Copied $fromfile to $to_source_dir\n"; + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + if ($::NON_NATIVE_PKGS->{ $kc->{kitcompname} }) { + my @nativefiles; + foreach my $pkgfile (split(/,/, $kc->{non_native_pkgs})) { + my ($key, $value) = split /:/, $pkgfile; + if ("$key" =~ /EXTERNALPKGS/) { + + #the $non_native_filename may contain several pkgs, can check and copy at the same time + foreach my $nnpkg (split(/,/, $value)) { + my $found = 0; + foreach my $pdir (@pkgdirlist) { + my $fromfile = $pdir . "/" . $nnpkg; + if (system("ls $fromfile > /dev/null")) { + next; + } else { + $found++; + if (system("cp -fp $fromfile $to_source_dir")) { + print "Error copying package file $fromfile to $to_source_dir \n"; + + # Cleanup + system("rm -Rf $tmpdir_base"); + next; + } else { + if ($::VERBOSE) { + print "Copied $fromfile to $to_source_dir\n"; + } + } } } + if (!$found) { + print "Could not find $nnpkg.\n"; + } } } - if (!$found) { - print "Could not find $nnpkg.\n"; - } } - } } - } } # Turn off external pkg flags and build the kit component meta pkgs - $::HAVE_EXTERNAL_PKG = ''; + $::HAVE_EXTERNAL_PKG = ''; $::HAVE_NON_NATIVE_PKGS = ''; - $::NON_NATIVE_PKGS = {}; + $::NON_NATIVE_PKGS = {}; - foreach my $kc (@{$::bldkit_config->{kitcomponent}{entries}}) { - my $rc=0; - if ( $debianflag ){ + foreach my $kc (@{ $::bldkit_config->{kitcomponent}{entries} }) { + my $rc = 0; + if ($debianflag) { $rc = &build_kitcomp_debian($kc); } - else{ + else { $rc = &build_kitcomp($kc); } - if ( $rc ) { + if ($rc) { print "Error building kitcomponent metapackage for $kc->{basename} \n"; return 1; } } # run createrepo - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) { + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) { my $repodir = "$::base_repodir/$kr->{kitreponame}"; - if ( -d $repodir ) { - my $cr_opts = ''; - if (( $kr->{osbasename} =~ m/rh|RH|centos|CentOS/ ) && - ( $kr->{osmajorversion} eq '5') ) { - $cr_opts = '-s md5'; - } - my $repocmd = ""; - if ( $debianflag ){ - $repocmd = "cd $repodir;dpkg-scanpackages . > Packages"; - } - else{ - $repocmd = "createrepo $cr_opts $repodir"; - } - if ( system( $repocmd ) ) { - print "Error building the repository meta-data with the createrepo command \n"; - return 1; - } + if (-d $repodir) { + my $cr_opts = ''; + if (($kr->{osbasename} =~ m/rh|RH|centos|CentOS/) && + ($kr->{osmajorversion} eq '5')) { + $cr_opts = '-s md5'; + } + my $repocmd = ""; + if ($debianflag) { + $repocmd = "cd $repodir;dpkg-scanpackages . > Packages"; + } + else { + $repocmd = "createrepo $cr_opts $repodir"; + } + if (system($repocmd )) { + print "Error building the repository meta-data with the createrepo command \n"; + return 1; + } } } #When using -k -r, there are useless repodir #delete useless repo dir - my $kitrepodirby=$::base_repodir; - my $cmdby = "/bin/ls $kitrepodirby 2>/dev/null"; - my $outputby = `$cmdby`; - my @allrepolist = split(/\n/, $outputby); + my $kitrepodirby = $::base_repodir; + my $cmdby = "/bin/ls $kitrepodirby 2>/dev/null"; + my $outputby = `$cmdby`; + my @allrepolist = split(/\n/, $outputby); my @dellist; - + foreach my $reponame (@allrepolist) { - my $match=0; - foreach my $kr (@{$::bldkit_config->{kitrepo}{entries}}) - { - my $repodirname = "$kr->{kitreponame}"; + my $match = 0; + foreach my $kr (@{ $::bldkit_config->{kitrepo}{entries} }) + { + my $repodirname = "$kr->{kitreponame}"; - if ( ${repodirname} eq ${reponame} ) - { + if (${repodirname} eq ${reponame}) + { ${match}++; - } - } - if ( ${match} == 0 ) - { - push(@dellist,$reponame); - } + } + } + if (${match} == 0) + { + push(@dellist, $reponame); + } } foreach my $del (@dellist) { - my $delrepodir=$::base_repodir."/".$del ; - if ( -d $delrepodir ) + my $delrepodir = $::base_repodir . "/" . $del; + if (-d $delrepodir) { - my $delcmd="rm -Rf $delrepodir"; - if ( system($delcmd) ) - { - print "Failed to delete useless repo directory \n"; - } + my $delcmd = "rm -Rf $delrepodir"; + if (system($delcmd)) + { + print "Failed to delete useless repo directory \n"; + } } } @@ -3940,7 +4023,7 @@ sub NEW_kit_addpkgs my $buildtar_rc = &kit_buildtar; # clean out the tmp dir - system ("rm -Rf $tmpdir_base"); + system("rm -Rf $tmpdir_base"); if ($buildtar_rc) { print "Error building full kit tarfile \n"; @@ -3983,46 +4066,47 @@ sub check_framework my $kitframework; my $section = ''; foreach my $l (@kitconflines) { + # skip blank and comment lines - if ( $l =~ /^\s*$/ || $l =~ /^\s*#/ ) { + if ($l =~ /^\s*$/ || $l =~ /^\s*#/) { next; } - if ( $l =~ /^\s*(\w+)\s*:/ ) { - $section = $1; - next; + if ($l =~ /^\s*(\w+)\s*:/) { + $section = $1; + next; } - if ( $l =~ /^\s*(\w+)\s*=\s*(.*)\s*/ ) { + if ($l =~ /^\s*(\w+)\s*=\s*(.*)\s*/) { my $attr = $1; my $val = $2; $attr =~ s/^\s*//; # Remove any leading whitespace $attr =~ s/\s*$//; # Remove any trailing whitespace $attr =~ tr/A-Z/a-z/; # Convert to lowercase - $val =~ s/^\s*//; - $val =~ s/\s*$//; + $val =~ s/^\s*//; + $val =~ s/\s*$//; if ($section eq 'kitbuildinfo') { - if ( $attr eq 'compatible_kitframeworks' ) { + if ($attr eq 'compatible_kitframeworks') { $kitcompat = $val; } - if ( $attr eq 'kitframework' ) { + if ($attr eq 'kitframework') { $kitframework = $val; } } if ($section eq 'kit') { - if ( $attr eq 'basename' ) { $kitbasename = $val; } + if ($attr eq 'basename') { $kitbasename = $val; } } } } if (!$kitcompat) { - print "Warning: Could not determine the kit compatible framework values for \'$kitbasename\' from the kit.conf file. Continuing for now.\n"; + print "Warning: Could not determine the kit compatible framework values for \'$kitbasename\' from the kit.conf file. Continuing for now.\n"; return 0; } - my @kit_compat_list = split (',', $kitcompat); - my @my_compat_list = split (',', $::COMPATIBLE_KITFRAMEWORKS); + my @kit_compat_list = split(',', $kitcompat); + my @my_compat_list = split(',', $::COMPATIBLE_KITFRAMEWORKS); foreach my $myfw (@my_compat_list) { chomp $myfw; @@ -4032,7 +4116,7 @@ sub check_framework if ($myfw eq $kitfw) { return $kitframework; } - } + } } print "Error: The kit named \'$kitbasename\' is not compatible with this version of the buildkit command. \'$kitbasename\' is compatible with \'$kitcompat\' and the buildkit command is compatible with \'$::COMPATIBLE_KITFRAMEWORKS\'\n"; return undef; diff --git a/xCAT-client/bin/copycds-cdrom b/xCAT-client/bin/copycds-cdrom index f572bd9fd..b7d7ad2f7 100755 --- a/xCAT-client/bin/copycds-cdrom +++ b/xCAT-client/bin/copycds-cdrom @@ -1,27 +1,28 @@ #!/usr/bin/env perl -my $go=1; +my $go = 1; my $file; my $opts = ""; $file = pop @ARGV; if (!$file) { - print "No device given, assuming /dev/cdrom.\n"; - $file = "/dev/cdrom"; -} + print "No device given, assuming /dev/cdrom.\n"; + $file = "/dev/cdrom"; +} while ($go) { - $go = 0; - #print "copycds $opts $file"; - system("copycds $opts $file"); - print "Would you like to copy another CD (y/N)? "; - if ( =~ /^y/i) { - $go = 1; - system("eject"); - print "Replace the CD and press enter."; - ; - } + $go = 0; + + #print "copycds $opts $file"; + system("copycds $opts $file"); + print "Would you like to copy another CD (y/N)? "; + if ( =~ /^y/i) { + $go = 1; + system("eject"); + print "Replace the CD and press enter."; + ; + } } # vim: set ts=2 sts=2 sw=2 et ai : diff --git a/xCAT-client/bin/db2sqlsetup b/xCAT-client/bin/db2sqlsetup index d0123ecd9..bb84dfd18 100755 --- a/xCAT-client/bin/db2sqlsetup +++ b/xCAT-client/bin/db2sqlsetup @@ -50,7 +50,7 @@ BEGIN # TODO: Remove during FVT should not need because DBD is compiled with # 5.8.8 and we require 61J or later which runs with 5.8.8 Perl. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -73,19 +73,20 @@ my $args = join ' ', @ARGV; $::command = "$0 $args"; Getopt::Long::Configure("bundling"); $Getopt::Long::ignorecase = 0; + # parse the options if ( !GetOptions( - 'i|init' => \$::INIT, - 'S|Server' => \$::SERVER, - 'C|Client' => \$::CLIENT, - 'N|nostart' => \$::NOSTART, - 'o|odbc' => \$::SETUPODBC, - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, - 'V|verbose' => \$::VERBOSE, - 'p|passwd' => \$::PASSWD, - 'r|rm' => \$::RM, + 'i|init' => \$::INIT, + 'S|Server' => \$::SERVER, + 'C|Client' => \$::CLIENT, + 'N|nostart' => \$::NOSTART, + 'o|odbc' => \$::SETUPODBC, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, + 'V|verbose' => \$::VERBOSE, + 'p|passwd' => \$::PASSWD, + 'r|rm' => \$::RM, ) ) { @@ -143,9 +144,9 @@ else if ($::RM) { - #&remove; - xCAT::MsgUtils->message("I", "Remove is not currently supported"); - exit(0); + #&remove; + xCAT::MsgUtils->message("I", "Remove is not currently supported"); + exit(0); } @@ -173,7 +174,7 @@ if (($::PASSWD) && ($::VERBOSE)) &usage; exit(1); } -if ((!($::SERVER)) && (!($::CLIENT))&& (!($::PASSWD))) +if ((!($::SERVER)) && (!($::CLIENT)) && (!($::PASSWD))) { xCAT::MsgUtils->message("I", "Either -S, -C, or -p flag must be chosen"); &usage; @@ -189,7 +190,7 @@ if (($::SERVER) && ($::CLIENT)) if ((!($::SERVER)) && (!($::CLIENT)) && ($::SETUPODBC)) { xCAT::MsgUtils->message("I", - "Either -S or -C flag must be chosen with the -o flag."); + "Either -S or -C flag must be chosen with the -o flag."); &usage; exit(1); } @@ -209,91 +210,93 @@ if ((!($::INIT)) && ($::SETUPODBC)) if (!(-e ($::installdb2dir))) { my $message = - "\nDB2 is not installed. It should be first obtained and installed into $::installdb2dir."; +"\nDB2 is not installed. It should be first obtained and installed into $::installdb2dir."; xCAT::MsgUtils->message("SE", "$message"); exit(1); } -# check to see if the perl DBD for DB2 is installed +# check to see if the perl DBD for DB2 is installed # my $cmd = "rpm -qa | grep perl-DBD-DB2"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - my $message = - "\perl-DBD-DB2 is not installed. It should be first obtained from the xcat dependency tarballs and installed before we can setup DB2"; - xCAT::MsgUtils->message("E", " $cmd failed. $message"); - exit(1); + my $message = +"\perl-DBD-DB2 is not installed. It should be first obtained from the xcat dependency tarballs and installed before we can setup DB2"; + xCAT::MsgUtils->message("E", " $cmd failed. $message"); + exit(1); } # If setting up the Server, check to see if DB2 is running $::db2running = 0; -$::xcatrunningdb2 = 0; +$::xcatrunningdb2 = 0; # determine the location of the xcatdb instance # -$::databaseloc = "/var/lib/db2"; # database location default -$::databaselocdir = "/var/lib"; # database path +$::databaseloc = "/var/lib/db2"; # database location default +$::databaselocdir = "/var/lib"; # database path + # if database location environment variable is set, use it -if ($ENV{'DATABASELOC'}) # input where xcatdb is located +if ($ENV{'DATABASELOC'}) # input where xcatdb is located { - $::databaseloc = $ENV{'DATABASELOC'}; + $::databaseloc = $ENV{'DATABASELOC'}; $::databaselocdir = $ENV{'DATABASELOC'}; - $::databaseloc .="\/db2"; -} else { # use site.databaseloc if set - if (!($::NOSTART)) { - my $cmd = " XCATBYPASS=1 tabdump site | grep databaseloc"; - my @output = xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) # if there - { - (my $attr, my $db) = split(",", $output[0]); - (my $q, $::databaseloc) = split("\"", $db); - $::databaselocdir = $::databaseloc; - $::databaseloc .="\/db2"; - + $::databaseloc .= "\/db2"; +} else { # use site.databaseloc if set + if (!($::NOSTART)) { + my $cmd = " XCATBYPASS=1 tabdump site | grep databaseloc"; + my @output = xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC == 0) # if there + { + (my $attr, my $db) = split(",", $output[0]); + (my $q, $::databaseloc) = split("\"", $db); + $::databaselocdir = $::databaseloc; + $::databaseloc .= "\/db2"; + + } } - } } -# If not NOSTART where we are setting up DB2 before xCAT is installed. -# check that they have not defined the databaseloc under the site.installoc +# If not NOSTART where we are setting up DB2 before xCAT is installed. +# check that they have not defined the databaseloc under the site.installoc # directory, default /install. This is invalid because this directory # is usually mounted on the Service Nodes. Error out if they do -# this is really the attribute in installdir which I will check. -if (!($::NOSTART)){ - my @installlocdir; - my $cmd = " XCATBYPASS=1 tabdump site | grep installdir"; - my @installlocation = xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) - { - (my $attr, my $installoc) = split(",", $installlocation[0]); - (my $q,my $installpt) = split("\"", $installoc); # remove quotes - @installlocdir = split '/', $installpt; # get the base directory +# this is really the attribute in installdir which I will check. +if (!($::NOSTART)) { + my @installlocdir; + my $cmd = " XCATBYPASS=1 tabdump site | grep installdir"; + my @installlocation = xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC == 0) + { + (my $attr, my $installoc) = split(",", $installlocation[0]); + (my $q, my $installpt) = split("\"", $installoc); # remove quotes + @installlocdir = split '/', $installpt; # get the base directory - } else { - $installlocdir[1] = "install"; # default - } - - # is it the same as the first directory in databaseloc - my @dblocdir = split '/', $::databaselocdir; # get the base directory - $installlocdir[1] =~ s/\s*//g; #remove blanks - $dblocdir[1] =~ s/\s*//g; #remove blanks - if ($installlocdir[1] eq $dblocdir[1] ) { # if they match,error - xCAT::MsgUtils->message("E", "The site databaseloc attribute is set to the directory or a sub-directory of the site table installloc or installdir attribute or the default of /install. This is not a supported configuration."); - exit(1); - } + } else { + $installlocdir[1] = "install"; # default + } + + # is it the same as the first directory in databaseloc + my @dblocdir = split '/', $::databaselocdir; # get the base directory + $installlocdir[1] =~ s/\s*//g; #remove blanks + $dblocdir[1] =~ s/\s*//g; #remove blanks + if ($installlocdir[1] eq $dblocdir[1]) { # if they match,error + xCAT::MsgUtils->message("E", "The site databaseloc attribute is set to the directory or a sub-directory of the site table installloc or installdir attribute or the default of /install. This is not a supported configuration."); + exit(1); + } } -if (!(-e $::databaselocdir)){ # if it does not exist, create it - my $cmd = "mkdir -p $::databaselocdir"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); - } +if (!(-e $::databaselocdir)) { # if it does not exist, create it + my $cmd = "mkdir -p $::databaselocdir"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); + } } -# if we are on the MN ( db2 server) + +# if we are on the MN ( db2 server) if ($::SERVER) { my $cmd = "ps -ef | grep db2"; @@ -307,7 +310,7 @@ if ($::SERVER) if ($::INIT) { my $message = - "DB2 is running. Database initialization will not take place."; +"DB2 is running. Database initialization will not take place."; xCAT::MsgUtils->message("I", "$message"); } $::db2running = 1; @@ -322,7 +325,7 @@ if ($::SERVER) if ($::INIT) { my $message = - "The /etc/xcat/cfgloc file is already configured for DB2. xCAT appears to be already running on DB2. xcat database configuration will not take place."; +"The /etc/xcat/cfgloc file is already configured for DB2. xCAT appears to be already running on DB2. xcat database configuration will not take place."; xCAT::MsgUtils->message("I", "$message"); } $::xcatrunningdb2 = 1; @@ -331,7 +334,7 @@ if ($::SERVER) } # if not just odbc update and xcat MN is not already running on DB2 -# or if we are setting up the Client and not just the ODBC +# or if we are setting up the Client and not just the ODBC # or change password # then Get instance password # @@ -354,10 +357,11 @@ if ((($odbconly == 0) && ($::xcatrunningdb2 == 0)) || (($::CLIENT) && ($odbconly `stty -echo`; chop(my $adminpwd2 = ); `stty echo`; - if ($::adminpassword ne $adminpwd2) { # no match + + if ($::adminpassword ne $adminpwd2) { # no match $msg = "Sorry, passwords do not match. "; - xCAT::MsgUtils->message('I', "$msg"); - exit 1; + xCAT::MsgUtils->message('I', "$msg"); + exit 1; } } } @@ -365,18 +369,18 @@ if ((($odbconly == 0) && ($::xcatrunningdb2 == 0)) || (($::CLIENT) && ($odbconly # if we are just changing the password for the instance # do it and exit if ($::PASSWD) { - my $rc=0; - $rc=&updatepasswd; - exit $rc; + my $rc = 0; + $rc = &updatepasswd; + exit $rc; } # initial setup request and not already running db2 if (($::INIT) && ($::xcatrunningdb2 == 0)) { - if (($::SERVER) && (!($::NOSTART))) - { # setting up db2 server on the MN and not nostart option + if (($::SERVER) && (!($::NOSTART))) + { # setting up db2 server on the MN and not nostart option - # makesure the daemon is running + # makesure the daemon is running &startxcatd; # # Backup current database @@ -393,7 +397,8 @@ if (($::INIT) && ($::xcatrunningdb2 == 0)) } &backupxcatdb; - # shutdown the xcatd daemon while migrating + + # shutdown the xcatd daemon while migrating &shutdownxcatd; # @@ -425,7 +430,7 @@ if (($::INIT) && ($::xcatrunningdb2 == 0)) else { xCAT::MsgUtils->message("E", - "Hostname resolution for $hname failed."); + "Hostname resolution for $hname failed."); &startxcatd; exit(1); } @@ -456,10 +461,10 @@ if (($::INIT) && ($::xcatrunningdb2 == 0)) { &db2start; - # - # Setup DB2 to restart on reboot - # - &db2reboot; + # + # Setup DB2 to restart on reboot + # + &db2reboot; } } @@ -468,7 +473,7 @@ if (($::INIT) && ($::xcatrunningdb2 == 0)) if (($::SERVER) && ($::xcatrunningdb2 == 0)) { # - # update DBM config + # update DBM config # &updateDBM; @@ -490,6 +495,7 @@ if (($::INIT) && ($::xcatrunningdb2 == 0)) &catalogServer; &createcfgloc; } + # add paths to db2 code to roots path. Need this for LL, but it is # convenient &adddb2paths; @@ -499,25 +505,26 @@ if (($::INIT) && ($::xcatrunningdb2 == 0)) # if ($::SERVER) { - if ($::xcatrunningdb2 == 0) # if not already running on db2 - { - if (!($::NOSTART)){ - &restorexcatdb; + if ($::xcatrunningdb2 == 0) # if not already running on db2 + { + if (!($::NOSTART)) { + &restorexcatdb; + } } - } if ($::NOSTART) { - xCAT::MsgUtils->message("I", - "xCAT DB2 database is setup.\n"); + xCAT::MsgUtils->message("I", + "xCAT DB2 database is setup.\n"); } else { - xCAT::MsgUtils->message("I", - "xCAT is running on the DB2 database.\n"); + xCAT::MsgUtils->message("I", + "xCAT is running on the DB2 database.\n"); } - # add cron entry for table reorg - &updatecrontab; + + # add cron entry for table reorg + &updatecrontab; } - else # client + else # client { # # start the daemon @@ -562,13 +569,14 @@ sub usage { xCAT::MsgUtils->message( 'I', - "Usage:\ndb2sqlsetup - Performs the setup of IBM DB2 for xCAT to use as its database. See man db2sqlsetup for more information." - ); - my $msg= - "db2sqlsetup <-h|--help>\n <-v|--version>\n <-i|--init> <-S|-C> [-N|--nostart] [-o|--setupODBC] [-V|--verbose]\n <-o|--setupODBC> <-S|-C> [-V|--verbose]\n <-p|--passwd> [-S|-C]\n "; +"Usage:\ndb2sqlsetup - Performs the setup of IBM DB2 for xCAT to use as its database. See man db2sqlsetup for more information." + ); + my $msg = +"db2sqlsetup <-h|--help>\n <-v|--version>\n <-i|--init> <-S|-C> [-N|--nostart] [-o|--setupODBC] [-V|--verbose]\n <-o|--setupODBC> <-S|-C> [-V|--verbose]\n <-p|--passwd> [-S|-C]\n "; xCAT::MsgUtils->message('I', "$msg"); } + #----------------------------------------------------------------------------- =head3 startxcatd @@ -579,26 +587,26 @@ sub usage #----------------------------------------------------------------------------- -sub startxcatd +sub startxcatd { - my $xcmd; - if ($::osname eq 'AIX') - { - if ($ENV{'XCATDB2QUIET'} == 1){ # don't show errors - $xcmd = "$::XCATROOT/sbin/restartxcatd >/dev/null 2>&1"; - } else { - $xcmd = "$::XCATROOT/sbin/restartxcatd"; - } - system($xcmd); + my $xcmd; + if ($::osname eq 'AIX') + { + if ($ENV{'XCATDB2QUIET'} == 1) { # don't show errors + $xcmd = "$::XCATROOT/sbin/restartxcatd >/dev/null 2>&1"; + } else { + $xcmd = "$::XCATROOT/sbin/restartxcatd"; + } + system($xcmd); - } - else - { - #$xcmd = "service xcatd restart"; - my $ret=xCAT::Utils->restartservice("xcatd"); - return $ret; - } + } + else + { + #$xcmd = "service xcatd restart"; + my $ret = xCAT::Utils->restartservice("xcatd"); + return $ret; + } } @@ -627,7 +635,7 @@ sub shutdownxcatd else { #$xcmd = "service xcatd stop"; - my $ret=xCAT::Utils->stopservice("xcatd"); + my $ret = xCAT::Utils->stopservice("xcatd"); return $ret; } @@ -648,40 +656,40 @@ sub backupxcatdb { - xCAT::MsgUtils->message( - "I", - "Backing up xCAT Database to $::backupdir.\nThis could take several minutes." - ); - if (!(-e $::backupdir)) - { # does not exist, make it - my $cmd = "mkdir -p $::backupdir"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); - } - } - else - { # remove contents - - my $cmd = "rm -rf $::backupdir/*"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); - } - } - - # back it up - my $cmd = " dumpxCATdb -p $::backupdir"; + xCAT::MsgUtils->message( + "I", +"Backing up xCAT Database to $::backupdir.\nThis could take several minutes." + ); + if (!(-e $::backupdir)) + { # does not exist, make it + my $cmd = "mkdir -p $::backupdir"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message("E", " $cmd failed."); exit(1); } + } + else + { # remove contents + + my $cmd = "rm -rf $::backupdir/*"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); + } + } + + # back it up + my $cmd = " dumpxCATdb -p $::backupdir"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); + } } @@ -709,37 +717,37 @@ sub mkdb2user xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - $makeuser =1; # user does not exist - } else { # user exists but check to see if home directory exist + $makeuser = 1; # user does not exist + } else { # user exists but check to see if home directory exist my $homedir = xCAT::Utils->getHomeDir("xcatdb"); - if (!(-e $homedir)) { # if it does not exist - $cmd = "rmuser xcatdb"; # we need to remake the user - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("SE", " $cmd failed."); - exit(1); - } - $makeuser =1; - - } else { # user ok , home dir ok - $makeuser =0; + if (!(-e $homedir)) { # if it does not exist + $cmd = "rmuser xcatdb"; # we need to remake the user + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("SE", " $cmd failed."); + exit(1); + } + $makeuser = 1; + + } else { # user ok , home dir ok + $makeuser = 0; } } - if ($makeuser ==1) { - $cmd = "lsgroup xcatdb"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) - { + if ($makeuser == 1) { + $cmd = "lsgroup xcatdb"; + xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC != 0) + { - #group does not exist, need to make it - $cmd = "mkgroup xcatdb"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("SE", " $cmd failed."); - exit(1); - } + #group does not exist, need to make it + $cmd = "mkgroup xcatdb"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("SE", " $cmd failed."); + exit(1); + } } $cmd = "mkuser pgrp=xcatdb home=$::databaseloc shell=/bin/ksh xcatdb"; xCAT::Utils->runcmd($cmd, 0); @@ -748,6 +756,7 @@ sub mkdb2user xCAT::MsgUtils->message("SE", " $cmd failed."); exit(1); } + # touch .profile to makesure it stays owned by xcatd $cmd = "touch $::databaseloc/.profile"; xCAT::Utils->runcmd($cmd, 0); @@ -767,10 +776,10 @@ sub mkdb2user } # set xcatdb id password - my $verboseflg=0; - if ($::VERBOSE) { # do not show commands with password - $verboseflg=1; - $::VERBOSE=undef; + my $verboseflg = 0; + if ($::VERBOSE) { # do not show commands with password + $verboseflg = 1; + $::VERBOSE = undef; } $cmd = qq~echo "xcatdb:$::adminpassword" | /bin/chpasswd -c~; xCAT::Utils->runcmd($cmd, 0); @@ -781,7 +790,7 @@ sub mkdb2user exit(1); } if ($verboseflg == 1) { - $::VERBOSE=1; + $::VERBOSE = 1; } } else @@ -791,40 +800,40 @@ sub mkdb2user xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - $makeuser =1; # user does not exist - } else { # user exists but check to see if home directory exist + $makeuser = 1; # user does not exist + } else { # user exists but check to see if home directory exist my $homedir = xCAT::Utils->getHomeDir("xcatdb"); - if (!(-e $homedir)) { # if it does not exist - $cmd = "userdel xcatdb"; # we need to remake the user - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("SE", " $cmd failed."); - exit(1); - } - $makeuser =1; # user does not exist - - } else { # user ok , home dir ok - $makeuser =0; + if (!(-e $homedir)) { # if it does not exist + $cmd = "userdel xcatdb"; # we need to remake the user + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("SE", " $cmd failed."); + exit(1); + } + $makeuser = 1; # user does not exist + + } else { # user ok , home dir ok + $makeuser = 0; } } - if ($makeuser ==1) { - $cmd = "egrep -i \"^xcatdb:\" /etc/group"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) - { - - #group does not exist, need to make it - $cmd = "groupadd xcatdb"; - xCAT::Utils->runcmd($cmd, 0); + if ($makeuser == 1) { + $cmd = "egrep -i \"^xcatdb:\" /etc/group"; + xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("SE", " $cmd failed."); - exit(1); - } - } - #user does not exist, need to make it + #group does not exist, need to make it + $cmd = "groupadd xcatdb"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("SE", " $cmd failed."); + exit(1); + } + } + + #user does not exist, need to make it $cmd = "useradd -d $::databaseloc -g xcatdb -m -s /bin/bash xcatdb"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) @@ -836,10 +845,10 @@ sub mkdb2user } # set xcatdb id password - my $verboseflg=0; - if ($::VERBOSE) { # do not show commands with password - $verboseflg=1; - $::VERBOSE=undef; + my $verboseflg = 0; + if ($::VERBOSE) { # do not show commands with password + $verboseflg = 1; + $::VERBOSE = undef; } $cmd = qq~echo $::adminpassword | passwd xcatdb --stdin~; xCAT::Utils->runcmd($cmd, 0); @@ -850,7 +859,7 @@ sub mkdb2user exit(1); } if ($verboseflg == 1) { - $::VERBOSE=1; + $::VERBOSE = 1; } } @@ -934,10 +943,11 @@ sub setupinstance if ($::RUNCMD_RC != 0) { # if error exit xCAT::MsgUtils->message("E", " $cmd failed."); + # start the daemon &startxcatd; exit(1); - + } # setup instance @@ -967,13 +977,13 @@ sub setupinstance } $cmd = "echo \"EXTSHM=ON\" >> $::databaseloc/sqllib/db2profile "; - xCAT::Utils->runcmd($cmd,0); + xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message("I", " $cmd warning."); } $cmd = "echo \"export EXTSHM\" >> $::databaseloc/sqllib/db2profile "; - xCAT::Utils->runcmd($cmd,0); + xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message("I", " $cmd warning."); @@ -1004,21 +1014,22 @@ sub setupinstance } } + # for either client or server update # su to xcatdb and run more setup $cmd = "export EXTSHM=ON "; $rc = &rundb2cmd($cmd); if ($rc != 0) { - xCAT::MsgUtils->message("SI", " $cmd warning."); + xCAT::MsgUtils->message("SI", " $cmd warning."); } $cmd = "db2set DB2ENVLIST=EXTSHM "; $rc = &rundb2cmd($cmd); if ($rc != 0) { - xCAT::MsgUtils->message("SI", " $cmd warning."); + xCAT::MsgUtils->message("SI", " $cmd warning."); } - + } #----------------------------------------------------------------------------- @@ -1102,16 +1113,17 @@ sub setupdb2env xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("SE", " $cmd failed."); + xCAT::MsgUtils->message("SE", " $cmd failed."); } $cmd = "chmod 755 /etc/profile.d/xcatdb2.csh"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("SE", " $cmd failed."); + xCAT::MsgUtils->message("SE", " $cmd failed."); } my $path = $::installdb2dir; - $path .="\/lib64"; + $path .= "\/lib64"; + # add path of db2 libraries to ld.so.conf my $cmd = "egrep -i \"V9.7\" /etc/ld.so.conf"; xCAT::Utils->runcmd($cmd, -1); @@ -1150,7 +1162,7 @@ sub db2start my $db2check = "db2sysc"; # see if really running if (grep(/$db2check/, @output)) { - return; + return; } } xCAT::MsgUtils->message("I", "Starting the DB2 Server"); @@ -1166,9 +1178,9 @@ sub db2start sleep 20; $rc = &rundb2cmd($cmd); if ($rc != 0) { - xCAT::MsgUtils->message("W", " $cmd failed."); - &startxcatd; - exit(1); + xCAT::MsgUtils->message("W", " $cmd failed."); + &startxcatd; + exit(1); } } @@ -1196,7 +1208,7 @@ sub catalogServer else { my $msg = - "Input the hostname or ip address of the Management Node as known by this Service node. Should be the same as the site.master attribute: "; +"Input the hostname or ip address of the Management Node as known by this Service node. Should be the same as the site.master attribute: "; xCAT::MsgUtils->message('I', "$msg"); chop($MN = ); @@ -1215,6 +1227,7 @@ sub catalogServer $rc = &rundb2cmd($cmd); } + #----------------------------------------------------------------------------- =head3 updateDBM @@ -1226,14 +1239,14 @@ sub catalogServer #----------------------------------------------------------------------------- -sub updateDBM +sub updateDBM { xCAT::MsgUtils->message("I", - "Updating the DBM."); + "Updating the DBM."); my $cmd; my $rc = 0; - # su to xcatdb to update the DBM + # su to xcatdb to update the DBM $cmd = "db2 -tvf /opt/xcat/share/xcat/scripts/updateDBM.sql "; $rc = &rundb2cmd($cmd); if ($rc != 0) @@ -1258,10 +1271,11 @@ sub updateDBM sub createxcatdb { xCAT::MsgUtils->message("I", - "Creating the xCAT database. This can take several minutes."); + "Creating the xCAT database. This can take several minutes."); my $cmd; my $rc = 0; - # need to make sure the createdb.sql script if pointing to the + + # need to make sure the createdb.sql script if pointing to the # correct databaseloc, the default is /var/lib/db2 in the shipped # script but this may have been changed by the admin # two lines are affected @@ -1269,56 +1283,59 @@ sub createxcatdb #('/var/lib/db2 /ts16') BUFFERPOOL BP16K; #Create tablespace xcattbs32k pagesize 32k managed by system using # ('/var/lib/db2 /ts32') BUFFERPOOL BP32K; - my $createdb = "/opt/xcat/share/xcat/scripts/createdb.sql"; + my $createdb = "/opt/xcat/share/xcat/scripts/createdb.sql"; my $createdborg = "/opt/xcat/share/xcat/scripts/createdb.sql.org"; my $createdbtmp = "/opt/xcat/share/xcat/scripts/createdb.sql.tmp"; my $cmd; my $message; if (!(-e $createdborg)) { - $cmd = "cp $createdb $createdborg"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { + $cmd = "cp $createdb $createdborg"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { xCAT::MsgUtils->message("E", " $cmd failed."); exit 1; - } + } } + # rm tmp file - $cmd = "rm $createdbtmp"; # rm tmp file, ignore errors + $cmd = "rm $createdbtmp"; # rm tmp file, ignore errors xCAT::Utils->runcmd($cmd, -1); $cmd = "touch $createdbtmp"; - xCAT::Utils->runcmd($cmd,0 ); + xCAT::Utils->runcmd($cmd, 0); + # now read the orginal file and build the tmp file with the correct info - open (CREATEDB," < $createdb"); - foreach my $line () + open(CREATEDB, " < $createdb"); + foreach my $line () { - chop $line; - if ($line =~ /^Create tablespace/i) { # line to change - my $newline; - if ($line =~ /xcattbs16k/i) { - $newline="Create tablespace xcattbs16k pagesize 16k managed by system using('$::databaseloc/ts16') BUFFERPOOL BP16K;"; - $cmd="echo \"$newline\" >> $createdbtmp" - } else { - $newline="Create tablespace xcattbs32k pagesize 32k managed by system using('$::databaseloc/ts32') BUFFERPOOL BP32K;"; - $cmd="echo \"$newline\" >> $createdbtmp" - } - } else { # just put line in new file - $cmd="echo \"$line\" >> $createdbtmp" - } - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed. Could not build createdb.sql"); - exit 1; - } + chop $line; + if ($line =~ /^Create tablespace/i) { # line to change + my $newline; + if ($line =~ /xcattbs16k/i) { + $newline = "Create tablespace xcattbs16k pagesize 16k managed by system using('$::databaseloc/ts16') BUFFERPOOL BP16K;"; + $cmd = "echo \"$newline\" >> $createdbtmp" + } else { + $newline = "Create tablespace xcattbs32k pagesize 32k managed by system using('$::databaseloc/ts32') BUFFERPOOL BP32K;"; + $cmd = "echo \"$newline\" >> $createdbtmp" + } + } else { # just put line in new file + $cmd = "echo \"$line\" >> $createdbtmp" + } + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) { + xCAT::MsgUtils->message("E", " $cmd failed. Could not build createdb.sql"); + exit 1; + } } close CREATEDB; + # copy tmp back to createdb.sql $cmd = "cp $createdbtmp $createdb"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit 1; + xCAT::MsgUtils->message("E", " $cmd failed."); + exit 1; } @@ -1332,7 +1349,7 @@ sub createxcatdb # restart the instance to apply the change xCAT::MsgUtils->message("I", - "Database created. Restarting the instance to apply the change. "); + "Database created. Restarting the instance to apply the change. "); $cmd = "db2 connect reset "; $rc = &rundb2cmd($cmd); if ($rc != 0) @@ -1378,7 +1395,7 @@ sub db2reboot xCAT::MsgUtils->message("I", "Setting up DB2 to start on reboot"); my $cmd; - # su to xcatdb + # su to xcatdb $cmd = "db2iauto -on xcatdb "; my $rc = &rundb2cmd($cmd); if ($rc != 0) @@ -1386,79 +1403,83 @@ sub db2reboot xCAT::MsgUtils->message("W", " $cmd failed."); } + # root needs to run the command also $cmd = $::installdb2dir; $cmd .= "\/bin\/db2iauto -on xcatdb "; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) - { # if error exit - xCAT::MsgUtils->message("W", " $cmd failed."); - + { # if error exit + xCAT::MsgUtils->message("W", " $cmd failed."); + } + # For redhat 6 need to setup upstart for reboot until DB2 does # DB2 will shipped this with 9.7 later PTF # check to see DB2 has not already implemented a script in /etc/init - my $osver=xCAT::Utils->osver; + my $osver = xCAT::Utils->osver; if ($osver eq 'rhserver6') { - # see if left over /etc/init.d/db2xcat then remove it. This was put in - # by xcat db2sqlsetup script in the past - if (-e("/etc/init.d/db2xcat")) { - $cmd = "chkconfig --del db2xcat"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - } - $cmd = "rm /etc/init.d/db2xcat"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); + # see if left over /etc/init.d/db2xcat then remove it. This was put in + # by xcat db2sqlsetup script in the past + if (-e ("/etc/init.d/db2xcat")) { + $cmd = "chkconfig --del db2xcat"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); - } - - } - $cmd = " fgrep db2fmcd /etc/init/*"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) { - my $message = "DB2 /etc/init reboot file already setup"; - xCAT::MsgUtils->message("I", "$message"); - } else { - $cmd = "cp /opt/xcat/share/xcat/scripts/xcatfmcd.conf /etc/init/xcatfmcd.conf"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed. DB2 will not automatical + } + $cmd = "rm /etc/init.d/db2xcat"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + + } + + } + $cmd = " fgrep db2fmcd /etc/init/*"; + xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC == 0) { + my $message = "DB2 /etc/init reboot file already setup"; + xCAT::MsgUtils->message("I", "$message"); + } else { + $cmd = "cp /opt/xcat/share/xcat/scripts/xcatfmcd.conf /etc/init/xcatfmcd.conf"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed. DB2 will not automatical ly restart on reboot."); - } - } - } # end Redhat6 + } + } + } # end Redhat6 - # setup for any Linux shmmax attribute + # setup for any Linux shmmax attribute if ($::osname eq 'Linux') { - # add setup required for DB2 reboot - $cmd = " fgrep \"kernel.shmmax = 268435456\" /etc/sysctl.conf"; - xCAT::Utils->runcmd($cmd, -1); # entry not there - if ($::RUNCMD_RC != 0) { - $cmd = "echo \"#xcat setup\" >> /etc/sysctl.conf "; - xCAT::Utils->runcmd($cmd,0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("I", " $cmd failed."); - } - $cmd = "echo \"kernel.shmmax = 268435456\" >> /etc/sysctl.conf "; - xCAT::Utils->runcmd($cmd,0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("I", " $cmd failed. DB2 will not automatically restart on reboot."); - } - } - } - - - + + # add setup required for DB2 reboot + $cmd = " fgrep \"kernel.shmmax = 268435456\" /etc/sysctl.conf"; + xCAT::Utils->runcmd($cmd, -1); # entry not there + if ($::RUNCMD_RC != 0) { + $cmd = "echo \"#xcat setup\" >> /etc/sysctl.conf "; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("I", " $cmd failed."); + } + $cmd = "echo \"kernel.shmmax = 268435456\" >> /etc/sysctl.conf "; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("I", " $cmd failed. DB2 will not automatically restart on reboot."); + } + } + } + + + } #----------------------------------------------------------------------------- @@ -1485,77 +1506,83 @@ sub setupODBC if ($::RUNCMD_RC != 0) { my $message = - "\nunixODBC is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before we can setup the ODBC. If on Linux, install from the OS CDs. If Redhat and ppc is being used then both unixODBC.*.ppc64 and unixODBC.*.ppc should be installed. "; +"\nunixODBC is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before we can setup the ODBC. If on Linux, install from the OS CDs. If Redhat and ppc is being used then both unixODBC.*.ppc64 and unixODBC.*.ppc should be installed. "; xCAT::MsgUtils->message("E", " $cmd failed. $message"); exit(1); } - # For CNM you must have the 32 bit version on Unix ODBC, Pam, + + # For CNM you must have the 32 bit version on Unix ODBC, Pam, # and openssl installed on Redhat. Put out a warning. if ($::linuxos =~ /rh.*/) { - $cmd = "rpm -qa | grep unixODBC"; - my @output=xCAT::Utils->runcmd($cmd, 0); - # check for two lines one ppc and one ppc64 - my $foundppc64 =0; - my $foundppc =0; - foreach my $line (@output) { - if ($line =~ /\.ppc$/i) { - $foundppc=1; + $cmd = "rpm -qa | grep unixODBC"; + my @output = xCAT::Utils->runcmd($cmd, 0); + + # check for two lines one ppc and one ppc64 + my $foundppc64 = 0; + my $foundppc = 0; + foreach my $line (@output) { + if ($line =~ /\.ppc$/i) { + $foundppc = 1; + } + if ($line =~ /\.ppc64$/i) { + $foundppc64 = 1; + } } - if ($line =~ /\.ppc64$/i) { - $foundppc64=1; + if (($foundppc64 != 1) || ($foundppc != 1)) + { + my $message = +"If Redhat on power is being used then both unixODBC.*.ppc64 and unixODBC.*.ppc rpms must be installed. "; + xCAT::MsgUtils->message("I", "$message"); + } - } - if (($foundppc64 !=1) || ($foundppc != 1)) - { - my $message = - "If Redhat on power is being used then both unixODBC.*.ppc64 and unixODBC.*.ppc rpms must be installed. "; - xCAT::MsgUtils->message("I", "$message"); - - } - # check pam 32 and 64 bit installed - @output=(); - $cmd = "rpm -qa | grep \^pam-"; - @output=xCAT::Utils->runcmd($cmd, 0); - # check for two lines one ppc and one ppc64 - $foundppc64 =0; - $foundppc =0; - foreach my $line (@output) { - if ($line =~ /\.ppc$/i) { - $foundppc=1; + + # check pam 32 and 64 bit installed + @output = (); + $cmd = "rpm -qa | grep \^pam-"; + @output = xCAT::Utils->runcmd($cmd, 0); + + # check for two lines one ppc and one ppc64 + $foundppc64 = 0; + $foundppc = 0; + foreach my $line (@output) { + if ($line =~ /\.ppc$/i) { + $foundppc = 1; + } + if ($line =~ /\.ppc64$/i) { + $foundppc64 = 1; + } } - if ($line =~ /\.ppc64$/i) { - $foundppc64=1; + if (($foundppc64 != 1) || ($foundppc != 1)) + { + my $message = +"If Redhat on power is being used then both pam-*.ppc64 and pam-*.ppc rpms must be installed. "; + xCAT::MsgUtils->message("I", "$message"); + } - } - if (($foundppc64 !=1) || ($foundppc != 1)) - { - my $message = - "If Redhat on power is being used then both pam-*.ppc64 and pam-*.ppc rpms must be installed. "; - xCAT::MsgUtils->message("I", "$message"); - - } - # check openssl 32 and 64 bit installed - @output=(); - $cmd = "rpm -qa | grep \^openssl-"; - @output=xCAT::Utils->runcmd($cmd, 0); - # check for two lines one ppc and one ppc64 - $foundppc64 =0; - $foundppc =0; - foreach my $line (@output) { - if ($line =~ /\.ppc$/i) { - $foundppc=1; + + # check openssl 32 and 64 bit installed + @output = (); + $cmd = "rpm -qa | grep \^openssl-"; + @output = xCAT::Utils->runcmd($cmd, 0); + + # check for two lines one ppc and one ppc64 + $foundppc64 = 0; + $foundppc = 0; + foreach my $line (@output) { + if ($line =~ /\.ppc$/i) { + $foundppc = 1; + } + if ($line =~ /\.ppc64$/i) { + $foundppc64 = 1; + } } - if ($line =~ /\.ppc64$/i) { - $foundppc64=1; + if (($foundppc64 != 1) || ($foundppc != 1)) + { + my $message = +"If Redhat on power is being used then both openssl*.ppc64 and openssl*.ppc rpms must be installed. "; + xCAT::MsgUtils->message("I", "$message"); + } - } - if (($foundppc64 !=1) || ($foundppc != 1)) - { - my $message = - "If Redhat on power is being used then both openssl*.ppc64 and openssl*.ppc rpms must be installed. "; - xCAT::MsgUtils->message("I", "$message"); - - } } @@ -1572,7 +1599,7 @@ sub setupODBC if (!(-e ($xcatconfig)) && (!(-e ($xcatconfigbackup)))) { $message = - "The $xcatconfig and $xcatconfigbackup files are missing. You need to configure xCAT for DB2 before setting up the ODBC."; +"The $xcatconfig and $xcatconfigbackup files are missing. You need to configure xCAT for DB2 before setting up the ODBC."; xCAT::MsgUtils->message("E", "$message"); exit(1); @@ -1587,7 +1614,7 @@ sub setupODBC if ($::RUNCMD_RC != 0) # then try backup { $message = - "Cannot find DB2 info in the cfgloc or cfgloc.db2 file. Configuration of ODBC cannot continue."; +"Cannot find DB2 info in the cfgloc or cfgloc.db2 file. Configuration of ODBC cannot continue."; xCAT::MsgUtils->message("E", " $cmd failed. $message"); exit(1); } @@ -1599,11 +1626,11 @@ sub setupODBC # The unixODBC Driver Manager loads the DB2 Driver dynamically # so the shared object must be extracted from the driver - if ($::osname eq 'AIX') + if ($::osname eq 'AIX') { if (!(-e "$::databaseloc/sqllib/lib/libdb2.so")) { - $cmd = "touch db2sql.test"; # see if this is a writable directory + $cmd = "touch db2sql.test"; # see if this is a writable directory xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { @@ -1650,8 +1677,8 @@ sub setupODBC if ($::osname eq 'AIX') { $sharedlibaix = "$::databaseloc/sqllib/lib/libdb2.so"; } else { - $sharedlib32="$::databaseloc/sqllib/lib32/libdb2.so"; - $sharedlib64="$::databaseloc/sqllib/lib/libdb2o.so"; + $sharedlib32 = "$::databaseloc/sqllib/lib32/libdb2.so"; + $sharedlib64 = "$::databaseloc/sqllib/lib/libdb2o.so"; } $cmd = "fgrep -i DB2 $odbcinstfile "; xCAT::Utils->runcmd($cmd, -1); @@ -1659,27 +1686,27 @@ sub setupODBC { my $entry; if ($::osname eq 'AIX') { - $entry = - "[DB2]\nDescription = DB2 Driver\nDriver = $sharedlibaix"; - $cmd = "echo \"$entry\" >> $odbcinstfile"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - $message = "$cmd failed. Could not setup ODBC."; - xCAT::MsgUtils->message("E", "$message"); - exit(1); - } - } else { #RHEL - $entry = - "[DB2]\nDescription = DB2 Driver\nDriver = $sharedlib32\nDriver64 = $sharedlib64"; - $cmd = "echo \"$entry\" >> $odbcinstfile"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - $message = "$cmd failed. Could not setup ODBC."; - xCAT::MsgUtils->message("E", "$message"); - exit(1); - } + $entry = + "[DB2]\nDescription = DB2 Driver\nDriver = $sharedlibaix"; + $cmd = "echo \"$entry\" >> $odbcinstfile"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + $message = "$cmd failed. Could not setup ODBC."; + xCAT::MsgUtils->message("E", "$message"); + exit(1); + } + } else { #RHEL + $entry = +"[DB2]\nDescription = DB2 Driver\nDriver = $sharedlib32\nDriver64 = $sharedlib64"; + $cmd = "echo \"$entry\" >> $odbcinstfile"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + $message = "$cmd failed. Could not setup ODBC."; + xCAT::MsgUtils->message("E", "$message"); + exit(1); + } } $entry = "FileUsage = 1"; $cmd = "echo \"$entry\" >> $odbcinstfile"; @@ -1742,18 +1769,18 @@ sub setupODBC # when accessing through ODBC # setup $::databaseloc/sqllib/cfg/db2cli.ini - my $db2clifile = "$::databaseloc/sqllib/cfg/db2cli.ini"; - $cmd = "db2 update cli cfg for section $instance using uid $instance"; - my $rc = &rundb2cmd($cmd); + my $db2clifile = "$::databaseloc/sqllib/cfg/db2cli.ini"; + $cmd = "db2 update cli cfg for section $instance using uid $instance"; + my $rc = &rundb2cmd($cmd); if ($rc != 0) { - xCAT::MsgUtils->message("SI", " $cmd warning."); + xCAT::MsgUtils->message("SI", " $cmd warning."); } - $cmd = "db2 update cli cfg for section $instance using pwd $passwd"; + $cmd = "db2 update cli cfg for section $instance using pwd $passwd"; $rc = &rundb2cmd($cmd); if ($rc != 0) { - xCAT::MsgUtils->message("SI", " $cmd warning."); + xCAT::MsgUtils->message("SI", " $cmd warning."); } $cmd = "chown xcatdb $db2clifile"; xCAT::Utils->runcmd($cmd, 0); @@ -1765,29 +1792,29 @@ sub setupODBC xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed."); + xCAT::MsgUtils->message("E", " $cmd failed."); } - my $path= $homedir .= "\/db2cli.ini"; # copy to roots home directory + my $path = $homedir .= "\/db2cli.ini"; # copy to roots home directory $cmd = "cp $db2clifile $path "; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed."); + xCAT::MsgUtils->message("E", " $cmd failed."); } $cmd = "chmod 0600 $path"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed."); + xCAT::MsgUtils->message("E", " $cmd failed."); } - if ($::SERVER) { # if on the DB2 Server - # set authorization to client so LoadL id can connect - $cmd = "db2 update dbm cfg using authentication client immediate"; - $rc = &rundb2cmd($cmd); - if ($rc != 0) - { - xCAT::MsgUtils->message("SI", " $cmd warning."); - } + if ($::SERVER) { # if on the DB2 Server + # set authorization to client so LoadL id can connect + $cmd = "db2 update dbm cfg using authentication client immediate"; + $rc = &rundb2cmd($cmd); + if ($rc != 0) + { + xCAT::MsgUtils->message("SI", " $cmd warning."); + } } } @@ -1806,18 +1833,18 @@ sub createcfgloc { my $cfgloc = "/etc/xcat/cfgloc"; - my $dir = "/etc/xcat"; + my $dir = "/etc/xcat"; my $cfglocbackup = "/etc/xcat/cfgloc.xcat.backup"; my $cmd; my $message; - if (!(-e $dir)){ # if it does not exist, create it - $cmd = "mkdir -p $dir"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed. Cannot create the cfgloc file"); - return 1; - } + if (!(-e $dir)) { # if it does not exist, create it + $cmd = "mkdir -p $dir"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed. Cannot create the cfgloc file"); + return 1; + } } # if they had an old cfgloc , save it @@ -1830,10 +1857,10 @@ sub createcfgloc xCAT::MsgUtils->message("E", " $cmd failed."); } } - my $verboseflg=0; - if ($::VERBOSE) { # do not show commands with password - $verboseflg=1; - $::VERBOSE=undef; + my $verboseflg = 0; + if ($::VERBOSE) { # do not show commands with password + $verboseflg = 1; + $::VERBOSE = undef; } my $db2entry = "DB2:xcatdb|xcatdb|$::adminpassword"; $cmd = "echo \"$db2entry\" > $cfgloc"; @@ -1846,7 +1873,7 @@ sub createcfgloc } if ($verboseflg == 1) { - $::VERBOSE=1; + $::VERBOSE = 1; } # allow readonly by root @@ -1870,7 +1897,7 @@ sub restorexcatdb # set the env variable for Table.pm for the new database my $xcatcfg; my $cfgl; - open($cfgl,"<","/etc/xcat/cfgloc"); + open($cfgl, "<", "/etc/xcat/cfgloc"); $xcatcfg = <$cfgl>; close($cfgl); chomp($xcatcfg); @@ -1878,17 +1905,18 @@ sub restorexcatdb # restore the database xCAT::MsgUtils->message( "I", - "Restoring the xCAT Database with $::backupdir to DB2 database.\nThis could take several minutes." - ); +"Restoring the xCAT Database with $::backupdir to DB2 database.\nThis could take several minutes." + ); if (!(-d $::backupdir)) { # does not exist, error xCAT::MsgUtils->message("E", - " $::backupdir is missing. Cannot retore the database."); + " $::backupdir is missing. Cannot retore the database."); exit(1); } # restore it my $cmd = "XCATBYPASS=1 XCATCFG=\"$xcatcfg\" restorexCATdb -p $::backupdir"; + # secure passwords in verbose mode my $tmpv = $::VERBOSE; $::VERBOSE = 0; @@ -1905,6 +1933,7 @@ sub restorexcatdb # &startxcatd; } + #----------------------------------------------------------------------------- =head3 updatecrontab @@ -1916,17 +1945,18 @@ sub restorexcatdb #----------------------------------------------------------------------------- -sub updatecrontab +sub updatecrontab { - my $cmd="/opt/xcat/share/xcat/tools/reorgtbls"; - my $entry="0 0 * * 0 $cmd"; - my ($code, $msg)=xCAT::Utils::add_cron_job($entry); - if ($code==0) { + my $cmd = "/opt/xcat/share/xcat/tools/reorgtbls"; + my $entry = "0 0 * * 0 $cmd"; + my ($code, $msg) = xCAT::Utils::add_cron_job($entry); + if ($code == 0) { xCAT::MsgUtils->message("I", "A crontab entry has been added to run DB2 table reorg once a week on Sunday 12am.\nIf you would like to change this time, use crontab -e to modify the entry for reorgtbls execution.\nYou may also limit the tables to reorg by using the -t parameter on reorgtbls.\nRun reorgtbls -h."); - } else { + } else { xCAT::MsgUtils->message("W", " Failed to add crontab entry for Table reorg."); - } + } } + #----------------------------------------------------------------------------- =head3 adddb2paths @@ -1940,12 +1970,12 @@ sub updatecrontab sub adddb2paths { - my $cmd; - if ($::osname eq 'AIX') - { + my $cmd; + if ($::osname eq 'AIX') + { my $profname = "/etc/profile"; - my $cmd = qq~cat $profname | grep "xCAT DB2 setup"~; - my $outref = xCAT::Utils->runcmd("$cmd", -1); + my $cmd = qq~cat $profname | grep "xCAT DB2 setup"~; + my $outref = xCAT::Utils->runcmd("$cmd", -1); if ($::RUNCMD_RC != 0) { @@ -1958,51 +1988,51 @@ sub adddb2paths } # add DB2 paths - my $db2paths="$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; + my $db2paths = "$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; my $eccmd = - qq~echo '# xCAT DB2 setup\nPATH=\$PATH:$db2paths\nexport PATH\n' >>$profname~; +qq~echo '# xCAT DB2 setup\nPATH=\$PATH:$db2paths\nexport PATH\n' >>$profname~; $outref = xCAT::Utils->runcmd("$eccmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', "Could not update $profname."); } - } + } my $homedir = xCAT::Utils->getHomeDir(); $profname = "$homedir/.profile"; - if (-e ("$profname")) { # if .profile exists - $cmd = qq~cat $profname | grep "xCAT DB2 setup"~; - $outref = xCAT::Utils->runcmd("$cmd", -1); - if ($::RUNCMD_RC != 0) - { - - # make back up file - my $cpcmd = qq~/bin/cp -p $profname $profname.orig1~; - my $outref = xCAT::Utils->runcmd("$cpcmd", 0); + if (-e ("$profname")) { # if .profile exists + $cmd = qq~cat $profname | grep "xCAT DB2 setup"~; + $outref = xCAT::Utils->runcmd("$cmd", -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E', "Could not copy $profname."); + + # make back up file + my $cpcmd = qq~/bin/cp -p $profname $profname.orig1~; + my $outref = xCAT::Utils->runcmd("$cpcmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not copy $profname."); + } + + # add DB2 paths + my $db2paths = "$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; + + my $eccmd = +qq~echo '# xCAT DB2 setup\nPATH=\$PATH:$db2paths\nexport PATH\n' >>$profname~; + $outref = xCAT::Utils->runcmd("$eccmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not update $profname."); + } } + } - # add DB2 paths - my $db2paths="$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; - - my $eccmd = - qq~echo '# xCAT DB2 setup\nPATH=\$PATH:$db2paths\nexport PATH\n' >>$profname~; - $outref = xCAT::Utils->runcmd("$eccmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not update $profname."); - } - } - } - - } - else #Linux - { + } + else #Linux + { my $profname = "/etc/profile.d/xcatdb2.sh"; - my $cmd = qq~cat $profname | grep "db2"~; - my $outref = xCAT::Utils->runcmd("$cmd", -1); + my $cmd = qq~cat $profname | grep "db2"~; + my $outref = xCAT::Utils->runcmd("$cmd", -1); if ($::RUNCMD_RC != 0) { @@ -2015,22 +2045,22 @@ sub adddb2paths } # add DB2 paths - my $db2paths="$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; + my $db2paths = "$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; my $eccmd = - qq~echo 'PATH=\$PATH:$db2paths\nexport PATH\n' >>$profname~; + qq~echo 'PATH=\$PATH:$db2paths\nexport PATH\n' >>$profname~; $outref = xCAT::Utils->runcmd("$eccmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', "Could not update $profname."); } - } + } my $profname = "/etc/profile.d/xcatdb2.csh"; - my $cmd = qq~cat $profname | grep "db2"~; - my $outref = xCAT::Utils->runcmd("$cmd", -1); + my $cmd = qq~cat $profname | grep "db2"~; + my $outref = xCAT::Utils->runcmd("$cmd", -1); if ($::RUNCMD_RC != 0) { - + # make back up file my $cpcmd = qq~/bin/cp -p $profname $profname.orig1~; my $outref = xCAT::Utils->runcmd("$cpcmd", 0); @@ -2040,15 +2070,16 @@ sub adddb2paths } # add DB2 paths - my $db2paths="$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; + my $db2paths = "$::databaseloc/sqllib/bin:$::databaseloc/sqllib/adm:$::databaseloc/sqllib/misc:$::databaseloc/sqllib/db2tss/bin"; my $eccmd = - qq~echo 'setenv PATH \${PATH}:$db2paths\n' >>$profname~; + qq~echo 'setenv PATH \${PATH}:$db2paths\n' >>$profname~; $outref = xCAT::Utils->runcmd("$eccmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', "Could not update $profname."); } + # set correct permissions $cmd = "chmod 755 /etc/profile.d/xcatdb2.sh"; xCAT::Utils->runcmd($cmd, 0); @@ -2062,9 +2093,10 @@ sub adddb2paths { xCAT::MsgUtils->message("SE", " $cmd failed."); } - } - } + } + } } + #----------------------------------------------------------------------------- =head3 remove @@ -2079,10 +2111,11 @@ sub adddb2paths #----------------------------------------------------------------------------- sub remove { - my $cmd; + my $cmd; my @output; - my $error = 0; - my $retcode=0; + my $error = 0; + my $retcode = 0; + #see if DB2 is installed if (!(-e ($::installdb2dir))) { @@ -2091,9 +2124,9 @@ sub remove xCAT::MsgUtils->message("E", "$message"); exit(1); } - + #see if xcat is using DB2 - my $backupdic = "/xcatbackdb2"; + my $backupdic = "/xcatbackdb2"; my $xcatconfig = "/etc/xcat/cfgloc"; if (-e ($xcatconfig)) { @@ -2101,242 +2134,251 @@ sub remove my $cmd = "egrep -i \"^DB2:\" /etc/xcat/cfgloc"; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC == 0) - { + { #if it is management node, need to backup database if ($::SERVER) { - xCAT::MsgUtils->message("I","Begin to backup database, this would take a while"); - - $cmd = "mkdir -p $backupdic"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) - { - my $message = "can't make a directory $backupdic, try again"; - $error += 1; - xCAT::MsgUtils->message("E", "$message"); - $backupdic = "/xCATbackupDB"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) - { - my $message = "fail again, can not make a direcorty $backupdic"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - exit(1); - } - } - - my $cmd = "ps -elf|grep xcatd"; + xCAT::MsgUtils->message("I", "Begin to backup database, this would take a while"); + + $cmd = "mkdir -p $backupdic"; + xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC != 0) + { + my $message = "can't make a directory $backupdic, try again"; + $error += 1; + xCAT::MsgUtils->message("E", "$message"); + $backupdic = "/xCATbackupDB"; + xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC != 0) + { + my $message = "fail again, can not make a direcorty $backupdic"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + exit(1); + } + } + + my $cmd = "ps -elf|grep xcatd"; my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC == 0) - { + { if ($::osname eq 'AIX') { - my $cmd = "startsrc -s xcatd"; + my $cmd = "startsrc -s xcatd"; xCAT::Utils->runcmd($cmd, -1); - $retcode=$::RUNCMD_RC; + $retcode = $::RUNCMD_RC; } else - { - #my $cmd = "service xcatd start"; - $retcode=xCAT::Utils->startservice("xcatd"); + { + #my $cmd = "service xcatd start"; + $retcode = xCAT::Utils->startservice("xcatd"); } + #xCAT::Utils->runcmd($cmd, -1); - #if ($::RUNCMD_RC !=0) - if($retcode!=0) - { - my $message = "can't start xcatd"; - $error += 1; - xCAT::MsgUtils->message("E", "$message"); - exit(1); - } - } - - - $cmd = "dumpxCATdb -p $backupdic"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) - { - my $message = "can't dump xcatdb"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - exit(1); - } + #if ($::RUNCMD_RC !=0) + if ($retcode != 0) + { + my $message = "can't start xcatd"; + $error += 1; + xCAT::MsgUtils->message("E", "$message"); + exit(1); + } + } + + + $cmd = "dumpxCATdb -p $backupdic"; + xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC != 0) + { + my $message = "can't dump xcatdb"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + exit(1); + } } - + if ($::osname eq 'AIX') { - my $cmd = "stopsrc -s xcatd"; + my $cmd = "stopsrc -s xcatd"; xCAT::Utils->runcmd($cmd, -1); - $retcode=$::RUNCMD_RC; + $retcode = $::RUNCMD_RC; } else - { - #my $cmd = "service xcatd stop"; - $retcode=xCAT::Utils->stopservice("xcatd"); + { + #my $cmd = "service xcatd stop"; + $retcode = xCAT::Utils->stopservice("xcatd"); } + #xCAT::Utils->runcmd($cmd, -1); #if ($::RUNCMD_RC !=0) - if($retcode!=0) + if ($retcode != 0) { - my $message = "can't stop xcatd"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - exit(1); + my $message = "can't stop xcatd"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + exit(1); } - - + + my $cmd = "rm -rf /etc/xcat/cfgloc"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) + if ($::RUNCMD_RC != 0) { - my $message = "can't remove cfgloc file"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - exit(1); + my $message = "can't remove cfgloc file"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + exit(1); } - + if ($::SERVER) - { + { my $cmd = "XCATBYPASS=1 restorexCATdb -p $backupdic"; - xCAT::Utils->runcmd($cmd, -1); + xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) - { - my $message = "can't restore xcat database"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - exit(1); + { + my $message = "can't restore xcat database"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + exit(1); } - + } - - + + if ($::osname eq 'AIX') { - my $cmd = "startsrc -s xcatd"; + my $cmd = "startsrc -s xcatd"; xCAT::Utils->runcmd($cmd, -1); - $retcode=$::RUNCMD_RC; + $retcode = $::RUNCMD_RC; } else - { - #my $cmd = "service xcatd start"; - $retcode=xCAT::Utils->startservice("xcatd"); + { + #my $cmd = "service xcatd start"; + $retcode = xCAT::Utils->startservice("xcatd"); } + #xCAT::Utils->runcmd($cmd, -1); #if ($::RUNCMD_RC !=0) - if($retcode!=0) + if ($retcode != 0) { - my $message = "can't start xcatd"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; + my $message = "can't start xcatd"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; } - xCAT::MsgUtils->message("I", "Have remove DB2 from xCAT. \n"); + xCAT::MsgUtils->message("I", "Have remove DB2 from xCAT. \n"); } } - - xCAT::MsgUtils->message("I", "Begin to remove DB2 \n"); + + xCAT::MsgUtils->message("I", "Begin to remove DB2 \n"); if ($::SERVER) - { + { #remove database my $cmd = "db2 force application all"; - my $rc = &rundb2cmd($cmd); + my $rc = &rundb2cmd($cmd); if ($rc != 0) { xCAT::MsgUtils->message("W", " $cmd failed. \n"); $error += 1; + #exit(1); } - + $cmd = "db2 drop database xcatdb"; - $rc = &rundb2cmd($cmd); + $rc = &rundb2cmd($cmd); if ($rc != 0) { xCAT::MsgUtils->message("W", " $cmd failed.\n"); $error += 1; + #exit(1); } else { xCAT::MsgUtils->message("W", "db2 stop \n."); } - + $cmd = "db2stop"; - $rc = &rundb2cmd($cmd); + $rc = &rundb2cmd($cmd); if ($rc != 0) { xCAT::MsgUtils->message("W", " $cmd failed. \n"); $error += 1; + #exit(1); - } - + } + } + #remove instance $cmd = $::installdb2dir; - $cmd = $cmd."/instance/db2idrop xcatdb"; + $cmd = $cmd . "/instance/db2idrop xcatdb"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) + if ($::RUNCMD_RC != 0) { - my $message = "can't drop DB2 instance \n"; - xCAT::MsgUtils->message("E", "$message"); - exit(1); + my $message = "can't drop DB2 instance \n"; + xCAT::MsgUtils->message("E", "$message"); + exit(1); } - + #check if all the instances have been removed $cmd = $::installdb2dir; - $cmd = $cmd."/instance/db2ilist"; + $cmd = $cmd . "/instance/db2ilist"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) + if ($::RUNCMD_RC != 0) { - my $message = "there is still instance, can't uninstall DB2\n"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - } + my $message = "there is still instance, can't uninstall DB2\n"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + } else { #uninstall DB2 $cmd = $::installdb2dir; - $cmd = $cmd."/install/db2_deinstall -a"; + $cmd = $cmd . "/install/db2_deinstall -a"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) + if ($::RUNCMD_RC != 0) { - my $message = "can't uninstall DB2 \n"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - #exit(1); - } + my $message = "can't uninstall DB2 \n"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + + #exit(1); + } xCAT::MsgUtils->message("I", "Remove DB2 successfully, begin to cleanup the enviroment. \n"); - } - - + } + + #unconfig enviroment $cmd = "egrep -i \"^db2c_xcatdb\" /etc/services"; xCAT::Utils->runcmd($cmd, -1); my $file1 = "/etc/services"; if ($::RUNCMD_RC == 0) - { - open(FH,"+<$file1") or die "cannot open file $file1 \n"; + { + open(FH, "+<$file1") or die "cannot open file $file1 \n"; $cmd = "touch /etc/services.back"; xCAT::Utils->runcmd($cmd, -1); - open(DH,"+) { - my $line = $_; - if($line !~ /xcatdb/) + my $line = $_; + if ($line !~ /xcatdb/) { - print DH $line; - } + print DH $line; + } } close(FH); close(DH); $cmd = "mv /etc/services.back $file1"; - xCAT::Utils->runcmd($cmd, -1); + xCAT::Utils->runcmd($cmd, -1); + #$cmd = "cat $file1 | sed s/.*xcatdb.*// > $file1"; - #xCAT::Utils->runcmd($cmd, -1); + #xCAT::Utils->runcmd($cmd, -1); } - - + + if ($::osname eq 'AIX') { $cmd = "rmuser xcatdb"; @@ -2348,10 +2390,10 @@ sub remove xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - my $message = "can't remove user xcatdb \n"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - } + my $message = "can't remove user xcatdb \n"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + } if ($::osname eq 'AIX') { @@ -2359,110 +2401,111 @@ sub remove xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - my $message = "can't remove group xcatdb \n"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; - } + my $message = "can't remove group xcatdb \n"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; + } } - - + + $cmd = "rm -rf "; - $cmd = $cmd.$::installdb2dir; + $cmd = $cmd . $::installdb2dir; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - my $message = "can't remove the directory $::installdb2dir /db2/V9.7 \n"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; + my $message = "can't remove the directory $::installdb2dir /db2/V9.7 \n"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; } - - $cmd = "rm -rf $::databaseloc/"; + + $cmd = "rm -rf $::databaseloc/"; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - my $message = "can't remove the directory $::databaseloc \n*"; - xCAT::MsgUtils->message("E", "$message"); - $error += 1; + my $message = "can't remove the directory $::databaseloc \n*"; + xCAT::MsgUtils->message("E", "$message"); + $error += 1; } - + my $file2; if ($::osname eq 'AIX') { - $file2 = "/etc/profile"; - open(FH,"+<$file2") or die "cannot open file $file2 \n"; + $file2 = "/etc/profile"; + open(FH, "+<$file2") or die "cannot open file $file2 \n"; $cmd = "touch /etc/tmp.back"; xCAT::Utils->runcmd($cmd, -1); - open(DH,"+) { - my $line = $_; - if(($line !~ /xcatdb/) and ($line !~ /EXTSHM/)) + my $line = $_; + if (($line !~ /xcatdb/) and ($line !~ /EXTSHM/)) { print DH $line; - } + } } close(FH); close(DH); $cmd = "mv /etc/tmp.back $file2"; - xCAT::Utils->runcmd($cmd, -1); + xCAT::Utils->runcmd($cmd, -1); } else - { - $file2 = "/etc/profile.d/xcat.sh"; - $cmd = "egrep -i \"DB2INSTANCE\" /etc/profile.d/xcat.sh"; + { + $file2 = "/etc/profile.d/xcat.sh"; + $cmd = "egrep -i \"DB2INSTANCE\" /etc/profile.d/xcat.sh"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) - { - open(FH,"+<$file2") or die "cannot open file $file2 \n"; + if ($::RUNCMD_RC == 0) + { + open(FH, "+<$file2") or die "cannot open file $file2 \n"; $cmd = "touch /etc/tmp.back"; xCAT::Utils->runcmd($cmd, -1); - open(DH,"+) { - my $line = $_; - if(($line !~ /xcatdb/) and ($line !~ /EXTSHM/)) + my $line = $_; + if (($line !~ /xcatdb/) and ($line !~ /EXTSHM/)) { print DH $line; - } + } } close(FH); close(DH); $cmd = "mv /etc/tmp.back $file2"; - xCAT::Utils->runcmd($cmd, -1); - } - - $file2 = "/etc/profile.d/xcat.csh"; - $cmd = "egrep -i \"DB2INSTANCE\" /etc/profile.d/xcat.csh"; + xCAT::Utils->runcmd($cmd, -1); + } + + $file2 = "/etc/profile.d/xcat.csh"; + $cmd = "egrep -i \"DB2INSTANCE\" /etc/profile.d/xcat.csh"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) - { - open(FH,"+<$file2") or die "cannot open file $file2 \n"; + if ($::RUNCMD_RC == 0) + { + open(FH, "+<$file2") or die "cannot open file $file2 \n"; $cmd = "touch /etc/tmp.back"; xCAT::Utils->runcmd($cmd, -1); - open(DH,"+) { - my $line = $_; - if(($line !~ /xcatdb/) and ($line !~ /EXTSHM/)) + my $line = $_; + if (($line !~ /xcatdb/) and ($line !~ /EXTSHM/)) { print DH $line; - } + } } close(FH); close(DH); $cmd = "mv /etc/tmp.back $file2"; - xCAT::Utils->runcmd($cmd, -1); - } - } - + xCAT::Utils->runcmd($cmd, -1); + } + } + #$cmd = "cat $file2 | sed s/.*xcatdb.*// > $file2"; #xCAT::Utils->runcmd($cmd, -1); - #$cmd = "cat $file2 | sed s/.*EXTSHM.*// > $file2"; + #$cmd = "cat $file2 | sed s/.*EXTSHM.*// > $file2"; #xCAT::Utils->runcmd($cmd, -1); - - xCAT::MsgUtils->message("I", "Cleanup completely finished. $error errors have got. \n"); - + + xCAT::MsgUtils->message("I", "Cleanup completely finished. $error errors have got. \n"); + } + #----------------------------------------------------------------------------- =head3 updatepasswd @@ -2475,76 +2518,80 @@ sub remove #----------------------------------------------------------------------------- -sub updatepasswd +sub updatepasswd { - my $rc=0; - $ENV{'XCATDB2QUIET'} = 1; - my $updateclient=0; - my $updateserver=0; - if ($::SERVER) { # going to update the server MN - $updateserver=1; - } + my $rc = 0; + $ENV{'XCATDB2QUIET'} = 1; + my $updateclient = 0; + my $updateserver = 0; + if ($::SERVER) { # going to update the server MN + $updateserver = 1; + } - if ($::CLIENT) { # going to update the clients (SNs) - $updateclient=1; - } - if ((!($::CLIENT)) && (!($::SERVER))) { # update both MN and SNs - $updateserver=1; - $updateclient=1; - } - my $snlist; - # must read the database before we change the password on the MN - # to get the list of Service Nodes - if ($updateclient==1) { - if (xCAT::Utils->isMN()) { # if on Management Node - my @allSN=xCAT::Utils->getAllSN; - foreach my $nodes (@allSN) { - $snlist.=$nodes; - $snlist.="\,"; - } - chop $snlist; - } - } - # change password on the MN - if ($updateserver==1) { # we will change the MN - # then shutdown xcatd - # First change xcatd password - # change /etc/xcat/cfgloc - # then restart xcatd - # change odbc password, if it exists - &shutdownxcatd; - &mkdb2user; - &createcfgloc; - &startxcatd; - &setupODBC; - } - # change password on the Service Nodes - # note this routine will be run on the SN's also from xdsh - if ($updateclient==1) { # Update the clients - if (xCAT::Utils->isMN()) { # if on Management Node - # xdsh -v /opt/xcat/bin/db2sqlsetup -C -p - my $cmd="xdsh $snlist -v DATABASELOC=$::databaselocdir XCATDB2PW=$::adminpassword \/opt\/xcat\/bin\/db2sqlsetup -C -p"; - # secure passwords in verbose mode - my $tmpv = $::VERBOSE; - $::VERBOSE = 0; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - my $cmd2="xdsh $snlist -v DATABASELOC=$::databaselocdir XCATDB2PW=XXXXXX \/opt\/xcat\/bin\/db2sqlsetup -C -p"; - my $message = - "$cmd2 failed. Could not change password on all the Service Nodes"; - xCAT::MsgUtils->message("E", "$message"); - } - $::VERBOSE = $tmpv; - } else { # on the SN - &shutdownxcatd; - &mkdb2user; - &createcfgloc; - &startxcatd; - &setupODBC; - } - } - - return $::RUNCMD_RC; + if ($::CLIENT) { # going to update the clients (SNs) + $updateclient = 1; + } + if ((!($::CLIENT)) && (!($::SERVER))) { # update both MN and SNs + $updateserver = 1; + $updateclient = 1; + } + my $snlist; + + # must read the database before we change the password on the MN + # to get the list of Service Nodes + if ($updateclient == 1) { + if (xCAT::Utils->isMN()) { # if on Management Node + my @allSN = xCAT::Utils->getAllSN; + foreach my $nodes (@allSN) { + $snlist .= $nodes; + $snlist .= "\,"; + } + chop $snlist; + } + } + + # change password on the MN + if ($updateserver == 1) { # we will change the MN + # then shutdown xcatd + # First change xcatd password + # change /etc/xcat/cfgloc + # then restart xcatd + # change odbc password, if it exists + &shutdownxcatd; + &mkdb2user; + &createcfgloc; + &startxcatd; + &setupODBC; + } + + # change password on the Service Nodes + # note this routine will be run on the SN's also from xdsh + if ($updateclient == 1) { # Update the clients + if (xCAT::Utils->isMN()) { # if on Management Node + # xdsh -v /opt/xcat/bin/db2sqlsetup -C -p + my $cmd = "xdsh $snlist -v DATABASELOC=$::databaselocdir XCATDB2PW=$::adminpassword \/opt\/xcat\/bin\/db2sqlsetup -C -p"; + + # secure passwords in verbose mode + my $tmpv = $::VERBOSE; + $::VERBOSE = 0; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + my $cmd2 = "xdsh $snlist -v DATABASELOC=$::databaselocdir XCATDB2PW=XXXXXX \/opt\/xcat\/bin\/db2sqlsetup -C -p"; + my $message = +"$cmd2 failed. Could not change password on all the Service Nodes"; + xCAT::MsgUtils->message("E", "$message"); + } + $::VERBOSE = $tmpv; + } else { # on the SN + &shutdownxcatd; + &mkdb2user; + &createcfgloc; + &startxcatd; + &setupODBC; + } + } + + return $::RUNCMD_RC; } diff --git a/xCAT-client/bin/genimage b/xCAT-client/bin/genimage index aa61089b9..4693a56e2 100755 --- a/xCAT-client/bin/genimage +++ b/xCAT-client/bin/genimage @@ -2,9 +2,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -19,16 +19,16 @@ use xCAT::TableUtils; use File::Basename; $::XCATROOT = "/opt/xcat"; -my $os = ""; -my $profile = ""; +my $os = ""; +my $profile = ""; my $interface = ""; my $version; -my $drivers = ""; +my $drivers = ""; my $otherInterfaces = ""; -my $kernel = ""; -my @oses; # available OSes. -my @profiles; # available profiles -my $profDir; # root where you do ./genimage from +my $kernel = ""; +my @oses; # available OSes. +my @profiles; # available profiles +my $profDir; # root where you do ./genimage from my $help; my $match = 0; my $imagename; @@ -44,6 +44,7 @@ my $onlyinitrd; my $dryrun; my $ignorekernelchk; my $noupdate; + #----------------------------------------------------------------------------- =head3 print_usage - usage message @@ -56,7 +57,7 @@ sub print_usage print "Usage:\n"; print " genimage\n\n"; print " genimage --dryrun\n\n"; - print ' genimage [-o ] [-a ] [-p ] [-i ] [-n ] [--onlyinitrd] [-r ] [-k ] [-g ] [-m statelite] [-l rootlimitsize] [-t tmplimitsize] [--permission ] [--interactive] [--dryrun] [--noupdate] '."\n\n"; + print ' genimage [-o ] [-a ] [-p ] [-i ] [-n ] [--onlyinitrd] [-r ] [-k ] [-g ] [-m statelite] [-l rootlimitsize] [-t tmplimitsize] [--permission ] [--interactive] [--dryrun] [--noupdate] ' . "\n\n"; print " --permission is used for statelite only\n"; print " -g is used for SLES only\n\n"; print " -m is used for urbuntu, debian and fedora12 only\n\n"; @@ -68,152 +69,156 @@ sub print_usage } if (!GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$os, - 'n=s' => \$drivers, - 'i=s' => \$interface, - 'r=s' => \$otherInterfaces, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernel, - 'g=s' => \$krpmver, - 'm=s' => \$mode, - 'permission=s' => \$permission, - 'kerneldir=s' => \$kerneldir, - 'interactive' => \$interactive, - 'onlyinitrd' => \$onlyinitrd, - 'dryrun' => \$dryrun, - 'ignorekernelchk' => \$ignorekernelchk, - 'noupdate' => \$noupdate, - 'h|help' => \$help, - 'v|version' => \$version, -)) { - &print_usage; - exit 1; + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$os, + 'n=s' => \$drivers, + 'i=s' => \$interface, + 'r=s' => \$otherInterfaces, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernel, + 'g=s' => \$krpmver, + 'm=s' => \$mode, + 'permission=s' => \$permission, + 'kerneldir=s' => \$kerneldir, + 'interactive' => \$interactive, + 'onlyinitrd' => \$onlyinitrd, + 'dryrun' => \$dryrun, + 'ignorekernelchk' => \$ignorekernelchk, + 'noupdate' => \$noupdate, + 'h|help' => \$help, + 'v|version' => \$version, + )) { + &print_usage; + exit 1; } -if($help){ +if ($help) { &print_usage; exit 0; } -if ($version){ +if ($version) { my $version = xCAT::Utils->Version(); xCAT::MsgUtils->message("N", $version); exit 0; } if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } if ((!$imagename) && (!$profile) && (!$os) && (!$arch)) { - my $tmpimgs=`lsdef -t osimage -w provmethod=~'/statelite|netboot/' |cut -d' ' -f1`; + my $tmpimgs = `lsdef -t osimage -w provmethod=~'/statelite|netboot/' |cut -d' ' -f1`; if ($? == 0) { - if (($tmpimgs) && ($tmpimgs !~ /^Could/)) { #Could is returned when the osimage table is empty - my @images=split('\n', $tmpimgs); - print "Do you want to re-generate an existing image from the osimage table? "; - print "[y/n] "; - my $conf = ; - chomp($conf); - if($conf ne "" && $conf !~/N|n|[Nn][Oo]/) { - $match = 0; - while(1){ - print "Available images: \n"; - foreach(sort @images){ - print " $_\n"; - } - # default is the first image - print "Which image do you want to re-generate? ["; - print $images[0]; - print "] "; - - my $img = ; - chomp($img); - if($img eq ""){ - $imagename = $images[0]; - last; - } - foreach(@images){ - if($img eq $_){ - $imagename=$img; - $match = 1; - } - } - if ($match) { - last; - } else { - print "$img is not found in the osimage table.\n"; - } - } - } - } + if (($tmpimgs) && ($tmpimgs !~ /^Could/)) { #Could is returned when the osimage table is empty + my @images = split('\n', $tmpimgs); + print "Do you want to re-generate an existing image from the osimage table? "; + print "[y/n] "; + my $conf = ; + chomp($conf); + if ($conf ne "" && $conf !~ /N|n|[Nn][Oo]/) { + $match = 0; + while (1) { + print "Available images: \n"; + foreach (sort @images) { + print " $_\n"; + } + + # default is the first image + print "Which image do you want to re-generate? ["; + print $images[0]; + print "] "; + + my $img = ; + chomp($img); + if ($img eq "") { + $imagename = $images[0]; + last; + } + foreach (@images) { + if ($img eq $_) { + $imagename = $img; + $match = 1; + } + } + if ($match) { + last; + } else { + print "$img is not found in the osimage table.\n"; + } + } + } + } } } # get the install directory -my @entries = xCAT::TableUtils->get_site_attribute("installdir"); +my @entries = xCAT::TableUtils->get_site_attribute("installdir"); my $installdir = $entries[0]; chomp($installdir); + # lots of error checking to make sure it exists. -if($installdir eq ''){ +if ($installdir eq '') { print "Could not get install directory from site table. Assuming your OSes are stored in '/install'\n"; $installdir = "/install"; } - -unless(-d $installdir){ + +unless (-d $installdir) { print "The directory where your OS distributions resides: $installdir does not exist. Please check site table\n"; - exit 1; + exit 1; } -if ((!$imagename) && (!$os)){ +if ((!$imagename) && (!$os)) { my @dircontents = `ls $installdir`; chomp(@dircontents); foreach (@dircontents) { - # SL matches Scientific Linux, sl matches sles amd sled - if($_ =~ /(rhel|fedora|SL|centos|sl|suse)/){ - push @oses,$_; - } - } - - if($#oses eq -1){ - print "There are no OS repositories in $installdir. Please run copycds for the OS first.\n"; - exit 1; + + # SL matches Scientific Linux, sl matches sles amd sled + if ($_ =~ /(rhel|fedora|SL|centos|sl|suse)/) { + push @oses, $_; + } } - + + if ($#oses eq -1) { + print "There are no OS repositories in $installdir. Please run copycds for the OS first.\n"; + exit 1; + } + # now they have the OSes, make sure they select one that is available $match = 0; - while(1){ - print "Available OSes: \n"; - foreach(@oses){ - print " $_\n"; - } - # default is the first OS cause in many cases, they'll only have 1. - print "Which OS do you want to build a image for? ["; - print $oses[0] ; - print "] "; - - $os = ; - chomp($os); - if($os eq ""){ - $os = $oses[0]; - last; - } - foreach(@oses){ - if($os eq $_){ - $match = 1; - } - } - - if($match){ - last; - }else{ - print "$os is not found in '$installdir'\n"; - } + while (1) { + print "Available OSes: \n"; + foreach (@oses) { + print " $_\n"; + } + + # default is the first OS cause in many cases, they'll only have 1. + print "Which OS do you want to build a image for? ["; + print $oses[0]; + print "] "; + + $os = ; + chomp($os); + if ($os eq "") { + $os = $oses[0]; + last; + } + foreach (@oses) { + if ($os eq $_) { + $match = 1; + } + } + + if ($match) { + last; + } else { + print "$os is not found in '$installdir'\n"; + } } - + chomp($os); } if ($os) { print " OS: $os\n"; } @@ -222,10 +227,10 @@ if ($os) { print " OS: $os\n"; } ### Get the Profile #### my $osfamily = $os; -$osfamily =~ s/\d+//g; -$osfamily =~ s/\.//g; -if($osfamily =~ /rh/){ - $osfamily = "rh"; +$osfamily =~ s/\d+//g; +$osfamily =~ s/\.//g; +if ($osfamily =~ /rh/) { + $osfamily = "rh"; } # OS version on s390x can contain 'sp', e.g. sles11sp1 @@ -236,86 +241,87 @@ if ($osfamily =~ /sles/ && $osfamily =~ /sp/) { #print "OSfamily: $osfamily\n"; $profDir = "$::XCATROOT/share/xcat/netboot/$osfamily"; -unless(-d $profDir){ +unless (-d $profDir) { print "Unable to find genimage script in $profDir\n"; exit 1; } -if ((!$imagename) && (!$profile)){ +if ((!$imagename) && (!$profile)) { my $profDir2 = "$installdir/custom/netboot/$osfamily"; - my @proList = `ls $profDir/*.pkglist`; + my @proList = `ls $profDir/*.pkglist`; if (-d $profDir2) { - @proList = (@proList, `ls $profDir2/*.pkglist`); + @proList = (@proList, `ls $profDir2/*.pkglist`); } my %seen = (); foreach (@proList) { - my $f = basename($_); - $f =~ s/([^\.]*).*/$1/; - chomp($f); - $seen{$f}++; - } + my $f = basename($_); + $f =~ s/([^\.]*).*/$1/; + chomp($f); + $seen{$f}++; + } @profiles = sort keys %seen; - if($#profiles eq -1){ - print "There are no profiles in $::XCATROOT/share/xcat/netboot/$osfamily.\n"; - exit 1; + if ($#profiles eq -1) { + print "There are no profiles in $::XCATROOT/share/xcat/netboot/$osfamily.\n"; + exit 1; } $match = 0; - while(1){ - print "Available Profiles for $os: \n"; - foreach(@profiles){ - print " $_\n"; - } - # default is the first OS cause in many cases, they'll only have 1. - print "Which profile do you want to use for $os? ["; - print "$profiles[0] "; - print "] "; - - $profile = ; - chomp($profile); - if($profile eq ""){ - $profile = $profiles[0]; - last; - } - foreach(@profiles){ - if($profile eq $_){ - $match = 1; - } - } - if($match eq 1){ - last; - } + while (1) { + print "Available Profiles for $os: \n"; + foreach (@profiles) { + print " $_\n"; + } + + # default is the first OS cause in many cases, they'll only have 1. + print "Which profile do you want to use for $os? ["; + print "$profiles[0] "; + print "] "; + + $profile = ; + chomp($profile); + if ($profile eq "") { + $profile = $profiles[0]; + last; + } + foreach (@profiles) { + if ($profile eq $_) { + $match = 1; + } + } + if ($match eq 1) { + last; + } } } -if ($profile) { print " Profile: $profile\n"; } +if ($profile) { print " Profile: $profile\n"; } # get the interface -if ((!$imagename) && (!$interface)){ - while(1){ - print "OPTIONAL: Which specific network interface will the image boot from? []"; - $interface = ; - chomp($interface); - if($interface eq ""){ - last; - }else{ - print "You want your stateless machines to boot off of "; - print "$interface"; - print "? "; - print "[Y/n] "; - my $conf = ; - chomp($conf); - if($conf eq ""){ - last; - } - if($conf =~ /Y|y|[Yy][Ee][Ss]/){ - last; - } - } +if ((!$imagename) && (!$interface)) { + while (1) { + print "OPTIONAL: Which specific network interface will the image boot from? []"; + $interface = ; + chomp($interface); + if ($interface eq "") { + last; + } else { + print "You want your stateless machines to boot off of "; + print "$interface"; + print "? "; + print "[Y/n] "; + my $conf = ; + chomp($conf); + if ($conf eq "") { + last; + } + if ($conf =~ /Y|y|[Yy][Ee][Ss]/) { + last; + } + } } if ($interface) { print " Interface: $interface\n"; } - else { print " No interface specified. The interface will be determined at network boot time.\n"; } + else { print " No interface specified. The interface will be determined at network boot time.\n"; } } - + print "Generating image: \n"; my @arg; @@ -349,7 +355,7 @@ if ($kernel) { push @arg, "$kernel"; } -if($otherInterfaces){ +if ($otherInterfaces) { push @arg, "-r"; push @arg, "$otherInterfaces"; } @@ -364,7 +370,7 @@ if ($rootlimit) { push @arg, "$rootlimit"; } -if($tmplimit) { +if ($tmplimit) { push @arg, "-t"; push @arg, "$tmplimit"; } @@ -384,8 +390,8 @@ if ($kerneldir) { push @arg, "$kerneldir"; } -my $tempfile="/tmp/xcat_genimage.$$"; -push @arg, "--tempfile"; #this is the file that contains the output +my $tempfile = "/tmp/xcat_genimage.$$"; +push @arg, "--tempfile"; #this is the file that contains the output push @arg, "$tempfile"; if ($interactive) { @@ -410,45 +416,47 @@ if ($noupdate) { } my $cmdref; -push (@{$cmdref->{arg}}, @arg); -$cmdref->{command}->[0] = "genimage"; +push(@{ $cmdref->{arg} }, @arg); +$cmdref->{command}->[0] = "genimage"; if (!$interactive) { xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; } else { if ($dryrun) { exit 0; } - #when in interactive mode, first call genimage.pm get info from DB, + + #when in interactive mode, first call genimage.pm get info from DB, xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); #then call the specific genimage under /opt/xcat/share... if (-f $tempfile) { - my $cmdname; - #read the command name - open(FILE1, "<$tempfile"); - my @output = ; - if (@output >0) { - $cmdname=$output[0]; - } else { - close FILE1; - return 1; - } - close FILE1; + my $cmdname; - # run the specific genimage command - #print "cmdname=$cmdname\n"; - system("$cmdname"); + #read the command name + open(FILE1, "<$tempfile"); + my @output = ; + if (@output > 0) { + $cmdname = $output[0]; + } else { + close FILE1; + return 1; + } + close FILE1; - #then call genimage.pm to save the DB - my @arg1; - push @arg1, $tempfile; - my $request; - push (@{$request->{arg}}, @arg1); - $request->{command}->[0] = "saveimgdata"; - xCAT::Client::submit_request($request, \&xCAT::Client::handle_response); - exit $xCAT::Client::EXITCODE; + # run the specific genimage command + #print "cmdname=$cmdname\n"; + system("$cmdname"); + + #then call genimage.pm to save the DB + my @arg1; + push @arg1, $tempfile; + my $request; + push(@{ $request->{arg} }, @arg1); + $request->{command}->[0] = "saveimgdata"; + xCAT::Client::submit_request($request, \&xCAT::Client::handle_response); + exit $xCAT::Client::EXITCODE; } else { - exit 1; + exit 1; } } - + diff --git a/xCAT-client/bin/mysqlsetup b/xCAT-client/bin/mysqlsetup index 408580e11..5a4ccbf8c 100755 --- a/xCAT-client/bin/mysqlsetup +++ b/xCAT-client/bin/mysqlsetup @@ -29,7 +29,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -52,21 +52,21 @@ $::command = "$0 $args"; Getopt::Long::Configure("bundling"); $Getopt::Long::ignorecase = 0; $::installdir = "/usr/local/mysql"; # current release of xcat-mysql -$::debianflag = 0; +$::debianflag = 0; #$::installdir="/opt/xcat/mysql"; # next release of xcat-mysql # parse the options if ( !GetOptions( - 'i|init' => \$::INIT, - 'u|update' => \$::UPDATE, - 'f|hostfile=s' => \$::HOSTFILE, - 'o|odbc' => \$::SETUPODBC, - 'L|LL' => \$::SETUPLL, - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, - 'V|verbose' => \$::VERBOSE, + 'i|init' => \$::INIT, + 'u|update' => \$::UPDATE, + 'f|hostfile=s' => \$::HOSTFILE, + 'o|odbc' => \$::SETUPODBC, + 'L|LL' => \$::SETUPLL, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, + 'V|verbose' => \$::VERBOSE, ) ) { @@ -88,7 +88,7 @@ if ($::VERSION) xCAT::MsgUtils->message("I", $version); exit 0; } -if ((!($::INIT)) && (!($::UPDATE)) && (!($::SETUPODBC))&& (!($::SETUPLL))) +if ((!($::INIT)) && (!($::UPDATE)) && (!($::SETUPODBC)) && (!($::SETUPLL))) { xCAT::MsgUtils->message("I", "Either -i or -u or -o flag must be chosen"); &usage; @@ -97,7 +97,7 @@ if ((!($::INIT)) && (!($::UPDATE)) && (!($::SETUPODBC))&& (!($::SETUPLL))) # check to see if only odbc update, no passwords needed my $odbconly = 0; -if ((!($::INIT)) && (!($::UPDATE)) && (!($::SETUPLL)) && ($::SETUPODBC)) +if ((!($::INIT)) && (!($::UPDATE)) && (!($::SETUPLL)) && ($::SETUPODBC)) { $odbconly = 1; @@ -110,14 +110,14 @@ if ((!($::HOSTFILE)) && ($::UPDATE) && ($::SETUPODBC)) if (($::INIT) && ($::UPDATE)) { my $warning = - " The -i and -u flags may not be input to the command. Use one or the other. \n "; +" The -i and -u flags may not be input to the command. Use one or the other. \n "; xCAT::MsgUtils->message("E", $warning); exit 1; } if (($::UPDATE) && ((!($::HOSTFILE)) && (!($::SETUPODBC)))) { my $warning = - " The -u flag requires the -o flag or the -f flag pointing to a file that contains the list of hosts that you would like to add to database access."; +" The -u flag requires the -o flag or the -f flag pointing to a file that contains the list of hosts that you would like to add to database access."; xCAT::MsgUtils->message("E", $warning); exit 1; } @@ -141,54 +141,61 @@ else $::osname = 'Linux'; } -if ( -e "/etc/debian_version" ){ +if (-e "/etc/debian_version") { $::debianflag = 1; } + # determine whether redhat or sles $::linuxos = xCAT::Utils->osver(); # SLES SP 1 my $sp1flag; + # if linuxos==sles12 -if ( $::linuxos == "sles12" ){ +if ($::linuxos == "sles12") { + # open /etc/os-release my @lines; my $relfile; $sp1flag = 0; - open($relfile,"<","/etc/os-release"); + open($relfile, "<", "/etc/os-release"); + # parse lines @lines = <$relfile>; close($relfile); chomp(@lines); + # if == 12.1 - if (grep /VERSION_ID="12.1"/, @lines){ + if (grep /VERSION_ID="12.1"/, @lines) { + #$::linuxos == "sles12.1"; $sp1flag = 1; } } + # set flag # SLES SP 1 # is this MariaDB or MySQL -$::MariaDB=0; +$::MariaDB = 0; my $cmd; -if ( $::debianflag ){ +if ($::debianflag) { $cmd = "dpkg -l | grep mariadb"; } else { - $cmd = "rpm -qa | grep -i mariadb"; # check this is MariaDB not MySQL + $cmd = "rpm -qa | grep -i mariadb"; # check this is MariaDB not MySQL } xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC == 0) { - $::MariaDB=1; + $::MariaDB = 1; } # # check to see if mysql is installed - # +# $cmd = "rpm -qa | grep -i perl-DBD-mysql"; my $msg = "\nMySQL perl DBD "; -if ( $::debianflag ){ - if ( $::MariaDB ){ +if ($::debianflag) { + if ($::MariaDB) { $cmd = "dpkg -l | grep -i mariadb-server"; $msg = "\nmariadb-server "; } else { @@ -200,16 +207,17 @@ xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { my $message = - "\n$msg is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; +"\n$msg is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; xCAT::MsgUtils->message("E", " $cmd failed. $message"); exit(1); } + # check to see if MySQL is running $::mysqlrunning = 0; $::xcatrunningmysql = 0; my $cmd = "ps -ef | grep mysqld"; my @output = xCAT::Utils->runcmd($cmd, 0); -my $mysqlcheck = "mysql.sock"; # see if really running +my $mysqlcheck = "mysql.sock"; # see if really running if (grep(/$mysqlcheck/, @output)) { @@ -224,14 +232,14 @@ if (grep(/$mysqlcheck/, @output)) #for ubuntu 14, after install mysql/maria server, the mysql will running #need to stop mysql in order to setup init xcat mysql -if ( $::debianflag or $sp1flag ){ +if ($::debianflag or $sp1flag) { $cmd = "pidof mysqld"; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC == 0) { if ($::INIT) { - my $ret=xCAT::Utils->stopservice("mysql"); + my $ret = xCAT::Utils->stopservice("mysql"); if ($ret != 0) { xCAT::MsgUtils->message("E", " failed to stop mysql/mariadb."); @@ -253,7 +261,7 @@ if (-e ("/etc/xcat/cfgloc")) # check to see if xcat is using mysql if ($::INIT) { my $message = - "The /etc/xcat/cfgloc file is already configured for MySQL and xCAT is using mysql as it's database. No xCAT setup is required."; +"The /etc/xcat/cfgloc file is already configured for MySQL and xCAT is using mysql as it's database. No xCAT setup is required."; xCAT::MsgUtils->message("I", "$message"); } $::xcatrunningmysql = 1; @@ -271,22 +279,22 @@ if ($::osname eq 'AIX') # if not just odbc update and not already running mysql or mysqlsetup -u or -L # Get root and admin passwords # -if ((($odbconly == 0) && ( $::xcatrunningmysql == 0)) || $::UPDATE || $::SETUPLL ) +if ((($odbconly == 0) && ($::xcatrunningmysql == 0)) || $::UPDATE || $::SETUPLL) { # not just updating the odbc if ($ENV{'XCATMYSQLADMIN_PW'}) # input env sets the password { - my $pw= $ENV{'XCATMYSQLADMIN_PW'}; - if ($pw =~ m/[^a-zA-Z0-9]/){ # if not alpha-numerid - my $warning = - " The password in the env variable XCATMYSQLADMIN_PW is not alpha-numeric."; - xCAT::MsgUtils->message("E", $warning); - exit 1; + my $pw = $ENV{'XCATMYSQLADMIN_PW'}; + if ($pw =~ m/[^a-zA-Z0-9]/) { # if not alpha-numerid + my $warning = +" The password in the env variable XCATMYSQLADMIN_PW is not alpha-numeric."; + xCAT::MsgUtils->message("E", $warning); + exit 1; } $::adminpassword = $ENV{'XCATMYSQLADMIN_PW'}; } - else # prompt for password + else # prompt for password { my $msg = "Input the alpha-numberic password for xcatadmin in the MySQL database: "; xCAT::MsgUtils->message('I', "$msg"); @@ -294,19 +302,19 @@ if ((($odbconly == 0) && ( $::xcatrunningmysql == 0)) || $::UPDATE || $::SETUPLL chop($::adminpassword = ); `stty echo`; - if ($::adminpassword =~ m/[^a-zA-Z0-9]/){ # if not alpha-numerid - my $warning = - "The input password is not alpha-numeric. Rerun the command an input an alpha-numeric password."; + if ($::adminpassword =~ m/[^a-zA-Z0-9]/) { # if not alpha-numerid + my $warning = +"The input password is not alpha-numeric. Rerun the command an input an alpha-numeric password."; xCAT::MsgUtils->message("E", $warning); exit 1; - } + } } - if ($ENV{'XCATMYSQLROOT_PW'}) # input env sets the password + if ($ENV{'XCATMYSQLROOT_PW'}) # input env sets the password { - my $pw= $ENV{'XCATMYSQLROOT_PW'}; - if ($pw =~ m/[^a-zA-Z0-9]/){ # if not alpha-numerid - my $warning = - " The password in the env variable XCATMYSQLROOT_PW is not alpha-numeric."; + my $pw = $ENV{'XCATMYSQLROOT_PW'}; + if ($pw =~ m/[^a-zA-Z0-9]/) { # if not alpha-numerid + my $warning = +" The password in the env variable XCATMYSQLROOT_PW is not alpha-numeric."; xCAT::MsgUtils->message("E", $warning); exit 1; } @@ -314,7 +322,7 @@ if ((($odbconly == 0) && ( $::xcatrunningmysql == 0)) || $::UPDATE || $::SETUPLL $::rootpassword = $ENV{'XCATMYSQLROOT_PW'}; } - else # prompt for password + else # prompt for password { my $msg = "Input the password for root in the MySQL database: "; @@ -322,13 +330,13 @@ if ((($odbconly == 0) && ( $::xcatrunningmysql == 0)) || $::UPDATE || $::SETUPLL `stty -echo`; chop($::rootpassword = ); `stty echo`; - - if ($::rootpassword =~ m/[^a-zA-Z0-9]/){ # if not alpha-numerid - my $warning = - "The input password is not alpha-numeric. Rerun the command an input an alpha-numeric password."; + + if ($::rootpassword =~ m/[^a-zA-Z0-9]/) { # if not alpha-numerid + my $warning = +"The input password is not alpha-numeric. Rerun the command an input an alpha-numeric password."; xCAT::MsgUtils->message("E", $warning); exit 1; - } + } } } @@ -384,6 +392,7 @@ if (($::INIT) && ($::xcatrunningmysql == 0)) } &backupxcatdb; + # shutdown the xcatd daemon while migrating &shutdownxcatd; @@ -408,6 +417,7 @@ if (($::INIT) && ($::xcatrunningmysql == 0)) chomp $hname; } + #my ($name, $aliases, $addrtype, $length, @addrs) = gethostbyname($hname); my $ipaddr = xCAT::NetworkUtils->getipaddr($hname); if ($ipaddr) @@ -443,10 +453,10 @@ if (($::INIT) && ($::xcatrunningmysql == 0)) if ($::osname eq 'AIX') { - xCAT::MsgUtils->message("I", "xCAT is now running on the MySQL database.\nYou should log out and back in, so that the new ulimit settings will take affect."); + xCAT::MsgUtils->message("I", "xCAT is now running on the MySQL database.\nYou should log out and back in, so that the new ulimit settings will take affect."); } else { - xCAT::MsgUtils->message("I", "xCAT is now running on the MySQL database."); - } + xCAT::MsgUtils->message("I", "xCAT is now running on the MySQL database."); + } } } # end initialization @@ -499,10 +509,10 @@ sub usage { xCAT::MsgUtils->message( 'I', - "Usage:\nmysqlsetup - Performs the setup of MySQL or MariaDB for xCAT to use as its database. See man mysqlsetup for more information." - ); +"Usage:\nmysqlsetup - Performs the setup of MySQL or MariaDB for xCAT to use as its database. See man mysqlsetup for more information." + ); my $msg = - "mysqlsetup <-h|--help>\n <-v|--version>\n <-i|--init> [-f|hostfile] [-o|--odbc] [-L|--LL] [-V|--verbose]\n <-u|--update> <-f|hostfile> [-o|--odbc] [-L|--LL] [-V|--verbose]\n <-o|--odbc> [-V|--verbose]\n <-L|--LL> [-V|--verbose]"; +"mysqlsetup <-h|--help>\n <-v|--version>\n <-i|--init> [-f|hostfile] [-o|--odbc] [-L|--LL] [-V|--verbose]\n <-u|--update> <-f|hostfile> [-o|--odbc] [-L|--LL] [-V|--verbose]\n <-o|--odbc> [-V|--verbose]\n <-L|--LL> [-V|--verbose]"; xCAT::MsgUtils->message('I', "$msg"); } @@ -612,8 +622,8 @@ sub backupxcatdb { xCAT::MsgUtils->message( "I", - "Backing up xCAT Database to $::backupdir.\nThis could take several minutes." - ); +"Backing up xCAT Database to $::backupdir.\nThis could take several minutes." + ); if (!(-e $::backupdir)) { # does not exist, make it my $cmd = "mkdir -p $::backupdir"; @@ -647,6 +657,7 @@ sub backupxcatdb } } + #----------------------------------------------------------------------------- =head3 shutdownxcatd @@ -672,8 +683,8 @@ sub shutdownxcatd else { #$xcmd = "service xcatd stop"; - my $ret=xCAT::Utils->stopservice("xcatd"); - return $ret; + my $ret = xCAT::Utils->stopservice("xcatd"); + return $ret; } } @@ -734,8 +745,8 @@ sub fixinstalldir # xCAT::MsgUtils->message( 'I', - "Fixing install directory permissions.\nThis may take a few minutes." - ); +"Fixing install directory permissions.\nThis may take a few minutes." + ); my $mysqldir = $::installdir; $mysqldir .= "\/*"; $cmd = "chown -R mysql $mysqldir"; @@ -797,7 +808,7 @@ sub initmysqldb { $cmd = - "awk '{gsub(\"\\\\[mysqld]\",\"\\[mysqld]\\ndatadir=/var/lib/mysql \"); print}' /etc/my.cnf > /etc/my.cnf.xcat"; +"awk '{gsub(\"\\\\[mysqld]\",\"\\[mysqld]\\ndatadir=/var/lib/mysql \"); print}' /etc/my.cnf > /etc/my.cnf.xcat"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { @@ -875,7 +886,7 @@ sub initmysqldb #on debian/ubuntu should comment the bind-adress line in my.cnf #on Ubuntu16.04, the bind-address line is in the mariadb.conf.d/50-server.cnf - if ( $::debianflag ){ + if ($::debianflag) { my $bind_file; if (-e "/etc/mysql/mariadb.conf.d/50-server.cnf") { @@ -895,12 +906,12 @@ sub initmysqldb # Create the MySQL data directory and initialize the grant tables # if not already setup my $cmd2 = - "ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; +"ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; if ($::osname eq 'AIX') { $cmd = $cmd2; $cmd .= - "$::installdir/scripts/mysql_install_db --user=mysql --basedir=$::installdir"; +"$::installdir/scripts/mysql_install_db --user=mysql --basedir=$::installdir"; } else { @@ -931,7 +942,7 @@ sub initmysqldb sub mysqlstart { my $cmd; - my $ret=0; + my $ret = 0; if ($::osname eq 'AIX') { my $hostname = `hostname`; @@ -939,34 +950,34 @@ sub mysqlstart #$cmd = "$::installdir/bin/mysqld_safe --user=mysql &"; #doesnot return my $cmd2 = - "ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; +"ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; $cmd = $cmd2; $cmd .= - "$::installdir/bin/mysqld --user=mysql --basedir=$::installdir --datadir=/var/lib/mysql --user=mysql --log-error=/var/lib/mysql/$hostname.err --pid-file=/var/lib/mysql/$hostname.pid --socket=/tmp/mysql.sock --port=3306 &"; - $ret=xCAT::Utils->runcmd($cmd, 0); - - +"$::installdir/bin/mysqld --user=mysql --basedir=$::installdir --datadir=/var/lib/mysql --user=mysql --log-error=/var/lib/mysql/$hostname.err --pid-file=/var/lib/mysql/$hostname.pid --socket=/tmp/mysql.sock --port=3306 &"; + $ret = xCAT::Utils->runcmd($cmd, 0); + + } else { - if ($::MariaDB==1) { # running MariaDB - if ($::linuxos =~ /rh.*/) { - $ret=xCAT::Utils->startservice("mariadb"); - } else { # sles - $ret=xCAT::Utils->startservice("mysql"); - } - - } else { # it is mysql + if ($::MariaDB == 1) { # running MariaDB + if ($::linuxos =~ /rh.*/) { + $ret = xCAT::Utils->startservice("mariadb"); + } else { # sles + $ret = xCAT::Utils->startservice("mysql"); + } - if ($::linuxos =~ /rh.*/) - { - $ret=xCAT::Utils->startservice("mysqld"); - } - else - { # sles - $ret=xCAT::Utils->startservice("mysql"); - } - } + } else { # it is mysql + + if ($::linuxos =~ /rh.*/) + { + $ret = xCAT::Utils->startservice("mysqld"); + } + else + { # sles + $ret = xCAT::Utils->startservice("mysql"); + } + } } if ($ret != 0) { @@ -981,21 +992,21 @@ sub mysqlstart { my @output = xCAT::Utils->runcmd($cmd, 0); my $mysqlcheck = "--datadir"; # see if really running - if ( $::debianflag or $sp1flag ){ + if ($::debianflag or $sp1flag) { $mysqlcheck = "mysqld"; } if (grep(/$mysqlcheck/, @output)) { - sleep 10; # give a few extra seconds to be sure + sleep 10; # give a few extra seconds to be sure return; } else { - sleep 10; # wait for daemon + sleep 10; # wait for daemon } } xCAT::MsgUtils->message("E", - " Could not start the mysql daemon, in time allocated ( 2minutes)"); + " Could not start the mysql daemon, in time allocated ( 2minutes)"); exit(1); } @@ -1032,13 +1043,13 @@ sub mysqlreboot { xCAT::MsgUtils->message("E", - " $cmd failed. Could not backup inittab."); + " $cmd failed. Could not backup inittab."); exit(1); } } $cmd = - "awk '{gsub(\"xcatd:2:once:/opt/xcat/sbin/restartxcatd > /dev/console 2>&1\",\"mysql:2:once:/usr/local/mysql/bin/mysqld_safe --user=mysql \\& \\nxcatd:2:once:/opt/xcat/sbin/restartxcatd > /dev/console 2>\\&1\"); print}' /etc/inittab > /etc/inittab.xcat"; +"awk '{gsub(\"xcatd:2:once:/opt/xcat/sbin/restartxcatd > /dev/console 2>&1\",\"mysql:2:once:/usr/local/mysql/bin/mysqld_safe --user=mysql \\& \\nxcatd:2:once:/opt/xcat/sbin/restartxcatd > /dev/console 2>\\&1\"); print}' /etc/inittab > /etc/inittab.xcat"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) @@ -1055,41 +1066,41 @@ sub mysqlreboot { xCAT::MsgUtils->message("E", - " $cmd failed. MySQL will not restart on reboot."); + " $cmd failed. MySQL will not restart on reboot."); } } } else # linux { - if ($::MariaDB==1 ) { # MariaDB not MySQL - - if ($::linuxos =~ /rh.*/) { - $cmd = "chkconfig mariadb on"; - } else { #sles - $cmd = "chkconfig mysql on"; - if ( $::debianflag ){ - $cmd = "update-rc.d mysql defaults"; - } + if ($::MariaDB == 1) { # MariaDB not MySQL - } - } else { # mysql - if ($::linuxos =~ /rh.*/) - { - $cmd = "chkconfig mysqld on"; - } - else - { # sles - $cmd = "chkconfig mysql on"; - if ( $::debianflag ){ - $cmd = "update-rc.d mysql defaults"; - } - } + if ($::linuxos =~ /rh.*/) { + $cmd = "chkconfig mariadb on"; + } else { #sles + $cmd = "chkconfig mysql on"; + if ($::debianflag) { + $cmd = "update-rc.d mysql defaults"; + } + + } + } else { # mysql + if ($::linuxos =~ /rh.*/) + { + $cmd = "chkconfig mysqld on"; + } + else + { # sles + $cmd = "chkconfig mysql on"; + if ($::debianflag) { + $cmd = "update-rc.d mysql defaults"; + } + } } xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message("E", - " $cmd failed. MySQL will not restart on reboot."); + " $cmd failed. MySQL will not restart on reboot."); } } @@ -1101,7 +1112,7 @@ sub verifymysqlroot if ($::osname eq 'AIX') { my $cmd2 = - "ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; +"ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; $cmd = $cmd2; $cmd .= "$::installdir/bin/mysqladmin -u root -p$::rootpassword version"; } @@ -1116,15 +1127,15 @@ sub verifymysqlroot $::VERBOSE = $tmpv; if ($::RUNCMD_RC == 0) { - # User has input an correct root passwd. That is fine. Do nothing and go head. - return + # User has input an correct root passwd. That is fine. Do nothing and go head. + return } # The password is wrong, warn the user and die. xCAT::MsgUtils->message( - "E", - "Wrong MySQL root password." - ); + "E", + "Wrong MySQL root password." + ); exit 1; } @@ -1148,7 +1159,7 @@ sub setupmysqlroot if ($::osname eq 'AIX') { my $cmd2 = - "ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; +"ulimit -n unlimited; ulimit -m unlimited; ulimit -d unlimited;ulimit -f unlimited; ulimit -s unlimited;"; $cmd = $cmd2; $cmd .= "$::installdir/bin/mysqladmin -u root password $::rootpassword"; } @@ -1166,8 +1177,8 @@ sub setupmysqlroot { xCAT::MsgUtils->message( "I", - "Warning, mysqladmin -u root password command failed, trying to set root password in MySQL. If root id has been defined in MySQL, and has a password then this message can be ignored." - ); +"Warning, mysqladmin -u root password command failed, trying to set root password in MySQL. If root id has been defined in MySQL, and has a password then this message can be ignored." + ); } @@ -1191,15 +1202,16 @@ sub setupxcatdb my $mysql; my $timeout = 10; # sets Expect default timeout, 0 accepts immediately my $pwd_sent = 0; - my $pwd_prompt = 'Enter password: '; + my $pwd_prompt = 'Enter password: '; my $mysql_prompt; - if ($::MariaDB == 1) { # setup MariaDB - $mysql_prompt = 'MariaDB \[\(none\)\]> '; + if ($::MariaDB == 1) { # setup MariaDB + $mysql_prompt = 'MariaDB \[\(none\)\]> '; } else { - $mysql_prompt = 'mysql> '; + $mysql_prompt = 'mysql> '; } - my $expect_log = undef; - my $debug = 0; + my $expect_log = undef; + my $debug = 0; + #if ($::VERBOSE) #{ # $debug = 1; @@ -1215,7 +1227,7 @@ sub setupxcatdb $grantall .= " IDENTIFIED BY \'$::adminpassword\';\r"; #GRAND user xcatadmin to localhost account - my $grantall_localhost= ""; + my $grantall_localhost = ""; $grantall_localhost = "GRANT ALL on xcatdb.* TO xcatadmin@"; $grantall_localhost .= "\'"; $grantall_localhost .= "localhost"; @@ -1259,7 +1271,7 @@ sub setupxcatdb unless ($mysql->spawn($spawncmd)) { xCAT::MsgUtils->message("E", - "Unable to run $spawncmd to create database and add MN."); + "Unable to run $spawncmd to create database and add MN."); return; } @@ -1271,30 +1283,30 @@ sub setupxcatdb my @result = $mysql->expect( $timeout, [ - $pwd_prompt, - sub { - $mysql->send("$::rootpassword\r"); - $mysql->clear_accum(); - $mysql->exp_continue(); - } + $pwd_prompt, + sub { + $mysql->send("$::rootpassword\r"); + $mysql->clear_accum(); + $mysql->exp_continue(); + } ], [ - $mysql_prompt, - sub { + $mysql_prompt, + sub { - $mysql->send("CREATE DATABASE xcatdb;ALTER DATABASE xcatdb DEFAULT CHARACTER SET latin1;\r"); - $mysql->clear_accum(); - $mysql->send("$createuser"); - $mysql->clear_accum(); - $mysql->send("$grantall"); - $mysql->clear_accum(); - $mysql->send("$grantall_localhost"); - $mysql->clear_accum(); - $mysql->send("exit;\r"); + $mysql->send("CREATE DATABASE xcatdb;ALTER DATABASE xcatdb DEFAULT CHARACTER SET latin1;\r"); + $mysql->clear_accum(); + $mysql->send("$createuser"); + $mysql->clear_accum(); + $mysql->send("$grantall"); + $mysql->clear_accum(); + $mysql->send("$grantall_localhost"); + $mysql->clear_accum(); + $mysql->send("exit;\r"); - } + } ] - ); + ); ########################################## # Expect error - report and quit ########################################## @@ -1303,13 +1315,14 @@ sub setupxcatdb my $errmsg = $result[1]; $mysql->soft_close(); xCAT::MsgUtils->message("E", - "Failed creating database. $errmsg"); + "Failed creating database. $errmsg"); exit(1); } $mysql->soft_close(); } + #----------------------------------------------------------------------------- =head3 setupLL @@ -1326,15 +1339,16 @@ sub setupLL my $mysql; my $timeout = 10; # sets Expect default timeout, 0 accepts immediately my $pwd_sent = 0; - my $pwd_prompt = 'Enter password: '; + my $pwd_prompt = 'Enter password: '; my $mysql_prompt; - if ($::MariaDB == 1) { # setup MariaDB - $mysql_prompt = 'MariaDB \[\(none\)\]> '; + if ($::MariaDB == 1) { # setup MariaDB + $mysql_prompt = 'MariaDB \[\(none\)\]> '; } else { - $mysql_prompt = 'mysql> '; + $mysql_prompt = 'mysql> '; } - my $expect_log = undef; - my $debug = 0; + my $expect_log = undef; + my $debug = 0; + #if ($::VERBOSE) #{ # $debug = 1; @@ -1380,7 +1394,7 @@ sub setupLL unless ($mysql->spawn($spawncmd)) { xCAT::MsgUtils->message("E", - "Unable to run $spawncmd to add LL setup."); + "Unable to run $spawncmd to add LL setup."); return; } @@ -1392,24 +1406,24 @@ sub setupLL my @result = $mysql->expect( $timeout, [ - $pwd_prompt, - sub { - $mysql->send("$::rootpassword\r"); - $mysql->clear_accum(); - $mysql->exp_continue(); - } + $pwd_prompt, + sub { + $mysql->send("$::rootpassword\r"); + $mysql->clear_accum(); + $mysql->exp_continue(); + } ], [ - $mysql_prompt, - sub { + $mysql_prompt, + sub { - $mysql->send("$setLLfunction"); - $mysql->clear_accum(); - $mysql->send("exit;\r"); + $mysql->send("$setLLfunction"); + $mysql->clear_accum(); + $mysql->send("exit;\r"); - } + } ] - ); + ); ########################################## # Expect error - report and quit ########################################## @@ -1418,7 +1432,7 @@ sub setupLL my $errmsg = $result[1]; $mysql->soft_close(); xCAT::MsgUtils->message("E", - "Failed LoadLeveler setup. $errmsg"); + "Failed LoadLeveler setup. $errmsg"); exit(1); } @@ -1444,6 +1458,7 @@ sub addhosts { my @hosts; my $debug = 0; + #if ($::VERBOSE) #{ # $debug = 1; @@ -1461,14 +1476,14 @@ sub addhosts my $mysql; my $timeout = 10; # sets Expect default timeout, 0 accepts immediately my $pwd_sent = 0; - my $pwd_prompt = 'Enter password: '; + my $pwd_prompt = 'Enter password: '; my $mysql_prompt; - if ($::MariaDB == 1) { # setup MariaDB - $mysql_prompt = 'MariaDB \[\(none\)\]> '; + if ($::MariaDB == 1) { # setup MariaDB + $mysql_prompt = 'MariaDB \[\(none\)\]> '; } else { - $mysql_prompt = 'mysql> '; + $mysql_prompt = 'mysql> '; } - my $expect_log = undef; + my $expect_log = undef; foreach my $host (@hosts) { @@ -1518,7 +1533,7 @@ sub addhosts xCAT::MsgUtils->message( "E", "Unable to run $spawncmd to grant host access to the database." - ); + ); return; } @@ -1530,24 +1545,24 @@ sub addhosts my @result = $mysql->expect( $timeout, [ - $pwd_prompt, - sub { - $mysql->send("$::rootpassword\r"); - $mysql->clear_accum(); - $mysql->exp_continue(); - } + $pwd_prompt, + sub { + $mysql->send("$::rootpassword\r"); + $mysql->clear_accum(); + $mysql->exp_continue(); + } ], [ - $mysql_prompt, - sub { + $mysql_prompt, + sub { - $mysql->send("$grantall"); - $mysql->clear_accum(); - $mysql->send("exit;\r"); + $mysql->send("$grantall"); + $mysql->clear_accum(); + $mysql->send("exit;\r"); - } + } ] - ); + ); ########################################## # Expect error - report and quit ########################################## @@ -1556,7 +1571,7 @@ sub addhosts my $errmsg = $result[1]; $mysql->soft_close(); xCAT::MsgUtils->message("E", - "Failed adding hosts. $errmsg"); + "Failed adding hosts. $errmsg"); exit(1); } @@ -1584,14 +1599,14 @@ sub setupODBC # # for all OS need unixODBC rpm my $cmd = "rpm -qa | grep unixODBC"; - if ( $::debianflag ){ + if ($::debianflag) { $cmd = "dpkg -l | grep unixodbc"; } xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { my $message = - "unixODBC is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before we can setup the ODBC. If on Linux, install from the OS CDs."; +"unixODBC is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before we can setup the ODBC. If on Linux, install from the OS CDs."; xCAT::MsgUtils->message("E", " $message"); exit(1); } @@ -1604,12 +1619,12 @@ sub setupODBC if ($::RUNCMD_RC != 0) { my $message = - "xcat-connector-odbc is not installed. It should be first obtained from the xcat dependency tarballs and installed before running this command. If on Linux, install from the OS CDs."; +"xcat-connector-odbc is not installed. It should be first obtained from the xcat dependency tarballs and installed before running this command. If on Linux, install from the OS CDs."; xCAT::MsgUtils->message("E", "$message"); exit(1); } } - elsif ( $::debianflag ){ + elsif ($::debianflag) { $cmd = "dpkg -l | grep libmyodbc"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) @@ -1626,7 +1641,7 @@ sub setupODBC if ($::RUNCMD_RC != 0) { my $message = - "mysql-client is not installed. It should be first installed from the SLES CDs."; +"mysql-client is not installed. It should be first installed from the SLES CDs."; xCAT::MsgUtils->message("E", "$message"); exit(1); } @@ -1635,7 +1650,7 @@ sub setupODBC if ($::RUNCMD_RC != 0) { my $message = - "libmysqlclient is not installed. It should be first installed from the SLES CDs."; +"libmysqlclient is not installed. It should be first installed from the SLES CDs."; xCAT::MsgUtils->message("E", "$message"); exit(1); } @@ -1644,7 +1659,7 @@ sub setupODBC if ($::RUNCMD_RC != 0) { my $message = - "MyODBC-unixODBC is not installed. It should be first installed from the SLES CDs."; +"MyODBC-unixODBC is not installed. It should be first installed from the SLES CDs."; xCAT::MsgUtils->message("E", "$message"); exit(1); } @@ -1660,7 +1675,7 @@ sub setupODBC if (!(-e ($xcatconfig)) && (!(-e ($xcatconfigbackup)))) { $message = - "The $xcatconfig and $xcatconfigbackup files are missing. You need to configure xCAT for MySQL before setting up the ODBC."; +"The $xcatconfig and $xcatconfigbackup files are missing. You need to configure xCAT for MySQL before setting up the ODBC."; xCAT::MsgUtils->message("E", "$message"); exit(1); @@ -1675,7 +1690,7 @@ sub setupODBC if ($::RUNCMD_RC != 0) # then try backup { $message = - "Cannot find host info in the cfgloc or cfgloc.mysql file. Configuration of ODBC cannot continue."; +"Cannot find host info in the cfgloc or cfgloc.mysql file. Configuration of ODBC cannot continue."; xCAT::MsgUtils->message("E", "$message"); exit(1); } @@ -1692,7 +1707,7 @@ sub setupODBC $cmd = "rpm -ql mysql-connector-odbc | grep libmyodbc..so"; @rpmoutput = xCAT::Utils->runcmd($cmd, 0); } - elsif ( $::debianflag ){ + elsif ($::debianflag) { $odbcinstfile = "/etc/odbcinst.ini"; $odbcfile = "/etc/odbc.ini"; $cmd = "dpkg -L libmyodbc | grep libmyodbc.so"; @@ -1741,7 +1756,7 @@ sub setupODBC if ($::RUNCMD_RC != 0) # then xcat entry not there { my $entry = - "[xCATDB]\nDriver = MySQL\nSERVER = $server\nPORT = 3306\nDATABASE = xcatdb"; +"[xCATDB]\nDriver = MySQL\nSERVER = $server\nPORT = 3306\nDATABASE = xcatdb"; $cmd = "echo \"$entry\" >> $odbcfile"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) @@ -1778,11 +1793,12 @@ sub setupODBC if ($::RUNCMD_RC != 0) # then xcat entry not there { my $entry = - "[xCATDB]\nSERVER =$server\nDATABASE = xcatdb\nUSER = $adminid\nPASSWORD = $passwd"; +"[xCATDB]\nSERVER =$server\nDATABASE = xcatdb\nUSER = $adminid\nPASSWORD = $passwd"; $cmd = "echo \"$entry\" >> $rootodbcfile"; + # secure passwd in verbose mode my $tmpv = $::VERBOSE; - $::VERBOSE = 0; + $::VERBOSE = 0; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { @@ -1840,7 +1856,7 @@ sub createcfgloc # secure passwd in verbose mode my $tmpv = $::VERBOSE; - $::VERBOSE = 0; + $::VERBOSE = 0; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { @@ -1877,12 +1893,12 @@ sub restorexcatdb # if they had an old cfgloc on another database, save it if ((-e ("/etc/xcat/cfgloc")) && (!(-e ("/etc/xcat/cfgloc.olddb")))) { - $cmd = "cp /etc/xcat/cfgloc /etc/xcat/cfgloc.olddb"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - } + $cmd = "cp /etc/xcat/cfgloc /etc/xcat/cfgloc.olddb"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + } } # put in place cfgloc for mysql @@ -1890,17 +1906,17 @@ sub restorexcatdb xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); } # allow readonly by root chmod 0600, "/etc/xcat/cfgloc"; - # set the env variable for Table.pm for the new database + # set the env variable for Table.pm for the new database my $xcatcfg; my $cfgl; - open($cfgl,"<","/etc/xcat/cfgloc"); + open($cfgl, "<", "/etc/xcat/cfgloc"); $xcatcfg = <$cfgl>; close($cfgl); chomp($xcatcfg); @@ -1908,17 +1924,18 @@ sub restorexcatdb # restore the database xCAT::MsgUtils->message( "I", - "Restoring the xCAT Database with $::backupdir to MySQL database.\nThis could take several minutes." - ); +"Restoring the xCAT Database with $::backupdir to MySQL database.\nThis could take several minutes." + ); if (!(-d $::backupdir)) { # does not exist, error xCAT::MsgUtils->message("E", - " $::backupdir is missing. Cannot retore the database."); + " $::backupdir is missing. Cannot retore the database."); exit(1); } # restore it my $cmd = "XCATBYPASS=y XCATCFG=\"$xcatcfg\" restorexCATdb -p $::backupdir"; + # not display passwords in verbose mode my $tmpv = $::VERBOSE; $::VERBOSE = 0; @@ -1942,7 +1959,7 @@ sub restorexcatdb else { #$xcmd = "service xcatd restart"; - my $ret=xCAT::Utils->restartservice("xcatd"); + my $ret = xCAT::Utils->restartservice("xcatd"); return $ret; } diff --git a/xCAT-client/bin/pasu b/xCAT-client/bin/pasu index c04d9b59f..4139f00de 100755 --- a/xCAT-client/bin/pasu +++ b/xCAT-client/bin/pasu @@ -5,16 +5,16 @@ # Run asu64 or iflash64 utility out of band to multiple nodes, either sequentially or in parallel BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } my $iam = $0; use strict; close(STDIN); -open(STDIN,"<","/dev/null"); +open(STDIN, "<", "/dev/null"); use lib "$::XCATROOT/lib/perl"; use IO::Socket::SSL; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; use Data::Dumper; use IO::Handle; use IO::Select; @@ -22,13 +22,14 @@ use xCAT::Utils; use Getopt::Long; use POSIX qw(:signal_h :errno_h :sys_wait_h); use Thread qw(yield); + if ($iam =~ /pasu/) { - $::utilcmd = '/opt/lenovo/toolscenter/asu/asu64'; - if (! -x $::utilcmd) { - $::utilcmd = '/opt/ibm/toolscenter/asu/asu64'; - } + $::utilcmd = '/opt/lenovo/toolscenter/asu/asu64'; + if (!-x $::utilcmd) { + $::utilcmd = '/opt/ibm/toolscenter/asu/asu64'; + } } elsif ($iam =~ /piflash/) { - $::utilcmd = '/opt/xcat/sbin/iflash64 --unattended'; + $::utilcmd = '/opt/xcat/sbin/iflash64 --unattended'; } my $interface; my $username; @@ -39,64 +40,67 @@ my $help; Getopt::Long::Configure("require_order"); Getopt::Long::Configure("bundling"); Getopt::Long::Configure("no_pass_through"); + if (!GetOptions( - "i|interface=s" => \$interface, - "p|passwd=s" => \$passwd, - 'l|loginname=s' => \$username, - 'f|fanout=i' => \$fanout, - 'b|batch=s' => \$batchfile, - 'r|retry' => \$::RETRY, - 'd|donotfilter' => \$::DONOTFILTER, - "V|verbose" => \$::VERBOSE, - 'h|help' => \$help, - ) || $help || ($batchfile && scalar(@ARGV)!=1) || (!$batchfile && scalar(@ARGV)<2) ) { - print "Usage: $iam [-V] [-d] [-i ] [-l ] [-p ] [-f ] \n"; - print " $iam [-V] [-d] [-i ] [-l ] [-p ] [-f ] -b \n"; - exit; + "i|interface=s" => \$interface, + "p|passwd=s" => \$passwd, + 'l|loginname=s' => \$username, + 'f|fanout=i' => \$fanout, + 'b|batch=s' => \$batchfile, + 'r|retry' => \$::RETRY, + 'd|donotfilter' => \$::DONOTFILTER, + "V|verbose" => \$::VERBOSE, + 'h|help' => \$help, + ) || $help || ($batchfile && scalar(@ARGV) != 1) || (!$batchfile && scalar(@ARGV) < 2)) { + print "Usage: $iam [-V] [-d] [-i ] [-l ] [-p ] [-f ] \n"; + print " $iam [-V] [-d] [-i ] [-l ] [-p ] [-f ] -b \n"; + exit; } my %nodehdl; -my $xcathost='localhost:3001'; -my $pasumaxp = 64; +my $xcathost = 'localhost:3001'; +my $pasumaxp = 64; if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; + $xcathost = $ENV{XCATHOST}; } -if ($ENV{XCATPSHFANOUT}) { - $pasumaxp=$ENV{XCATPSHFANOUT}; +if ($ENV{XCATPSHFANOUT}) { + $pasumaxp = $ENV{XCATPSHFANOUT}; } -if ($fanout) { # see if they overroad the fanout from the command line - $pasumaxp=$fanout; +if ($fanout) { # see if they overroad the fanout from the command line + $pasumaxp = $fanout; } my $noderange = shift @ARGV; -my @nodes=(); +my @nodes = (); #print "fanout=$fanout, username=$username, noderange=$noderange\n"; my $nodeattrs; - # do not need to do this call, because getting the ipmi atts will also give us a list of nodes - #@nodes = expandnoderange($noderange); - # this is reference to a hash, each key is the nodename and the value is a reference to a hash of attr values - $nodeattrs = getipmiattrs($noderange); - #print Dumper($nodeattrs); - #foreach my $k (keys(%$nodeattrs)) { - # print "$k:\n"; - # my $subhash = $nodeattrs->{$k}; - # foreach my $k2 (keys(%$subhash)) { print " $k2=", $subhash->{$k2}, "\n"; } - #} - #exit; - @nodes = keys(%$nodeattrs); +# do not need to do this call, because getting the ipmi atts will also give us a list of nodes +#@nodes = expandnoderange($noderange); + +# this is reference to a hash, each key is the nodename and the value is a reference to a hash of attr values +$nodeattrs = getipmiattrs($noderange); + +#print Dumper($nodeattrs); +#foreach my $k (keys(%$nodeattrs)) { +# print "$k:\n"; +# my $subhash = $nodeattrs->{$k}; +# foreach my $k2 (keys(%$subhash)) { print " $k2=", $subhash->{$k2}, "\n"; } +#} +#exit; +@nodes = keys(%$nodeattrs); my $children = 0; -my $inputs = new IO::Select; -my %pids; # pid => node -my %exitcodes; # Keep a list of children with known exit codes +my $inputs = new IO::Select; +my %pids; # pid => node +my %exitcodes; # Keep a list of children with known exit codes my %foundcodes; my @retries; # the nodes that fail with connection error if ($interface) { - foreach (@nodes) { - s/$/-$interface/; - } + foreach (@nodes) { + s/$/-$interface/; + } } # Fork the processes for running utility for each node @@ -105,60 +109,61 @@ if ($interface) { # logic in just in case. @retries = @nodes; while (scalar(@retries)) { - @nodes = @retries; - @retries = (); - foreach (@nodes) { - my $node=$_; - my $ipmiattrs = $nodeattrs->{$node}; - my $bmc = $ipmiattrs->{bmcaddr}; - if (!defined($bmc)) { - print "$node: the ipmi.bmc attribute is not defined, skipping.\n"; - next; + @nodes = @retries; + @retries = (); + foreach (@nodes) { + my $node = $_; + my $ipmiattrs = $nodeattrs->{$node}; + my $bmc = $ipmiattrs->{bmcaddr}; + if (!defined($bmc)) { + print "$node: the ipmi.bmc attribute is not defined, skipping.\n"; + next; + } + + # if we have already forked the max # of simultaneous processes, wait till 1 finishes + while ($children > $pasumaxp) { processoutput($inputs); } + + # fork anothe process + my $child; + $children++; + + # precedence on the username and password is: cli option, ipmi table, passwd table + my ($user, $pw); + if (defined($username)) { $user = $username; } # cli option + elsif (defined($ipmiattrs->{bmcuser})) { $user = $ipmiattrs->{bmcuser}; } + if (defined($passwd)) { $pw = $passwd; } # cli option + elsif (defined($ipmiattrs->{bmcpass})) { $pw = $ipmiattrs->{bmcpass}; } + if ($::VERBOSE) { print "For node $node using bmc=$bmc, user=$user, pw=$pw\n"; } + utilnode(\$child, $node, $bmc, $user, $pw, $batchfile, @ARGV); # child is the fd of the child process + $inputs->add($child); + $nodehdl{$child} = $node; } - # if we have already forked the max # of simultaneous processes, wait till 1 finishes - while ($children > $pasumaxp) { processoutput($inputs); } - - # fork anothe process - my $child; - $children++; - # precedence on the username and password is: cli option, ipmi table, passwd table - my ($user, $pw); - if (defined($username)) { $user = $username; } # cli option - elsif (defined($ipmiattrs->{bmcuser})) { $user = $ipmiattrs->{bmcuser}; } - if (defined($passwd)) { $pw = $passwd; } # cli option - elsif (defined($ipmiattrs->{bmcpass})) { $pw = $ipmiattrs->{bmcpass}; } - if ($::VERBOSE) { print "For node $node using bmc=$bmc, user=$user, pw=$pw\n"; } - utilnode(\$child,$node,$bmc,$user,$pw,$batchfile,@ARGV); # child is the fd of the child process - $inputs->add($child); - $nodehdl{$child} = $node; - } - - # quiesce everything - while ($inputs->count) { - processoutput($inputs); - } - while (processoutput($inputs)) {}; - while (wait != -1) { - yield; - } + # quiesce everything + while ($inputs->count) { + processoutput($inputs); + } + while (processoutput($inputs)) { } + while (wait != -1) { + yield; + } } -my $exitcode=0; +my $exitcode = 0; foreach (values %pids) { - my $possible_codes = join ",",keys %foundcodes; + my $possible_codes = join ",", keys %foundcodes; unless (defined $exitcodes{$_}) { print stderr "$_: *** $iam missed exit code, probably one of the following: $possible_codes\n"; } } foreach (keys %exitcodes) { if ($exitcodes{$_}) { - print stderr "$_: *** $::utilcmd exited with error code ".$exitcodes{$_}.".\n"; + print stderr "$_: *** $::utilcmd exited with error code " . $exitcodes{$_} . ".\n"; $exitcode++; } } -if ($exitcode) { #Exit code reflects number of failed nodes - $exitcode=$exitcode%256; #keep from overflowing valid values +if ($exitcode) { #Exit code reflects number of failed nodes + $exitcode = $exitcode % 256; #keep from overflowing valid values unless ($exitcode) { #if number of failed nodes happened to be evenly divisible by 256, make it non-zero again $exitcode++; } @@ -166,177 +171,183 @@ if ($exitcode) { #Exit code reflects number of failed nodes exit($exitcode); # Process output on the select stmt from the forked cmds -sub processoutput { #This way, one arbiter handles output, no interrupting - my $inputs = shift; # the select object that contains all the file descriptors - my @readyins = $inputs->can_read(1); # child fds with some output available - my $rc = @readyins; - my $readyh; - foreach $readyh (@readyins) { - my $cursel = new IO::Select; # need to do non-blocking reads on this fd - $cursel->add($readyh); - while ($cursel->can_read(0)) { - my $line = <$readyh>; - unless ($line) { - $inputs->remove($readyh); - close($readyh); - $exitcodes{$nodehdl{$readyh}} = $? >> 8; - $children--; - next; - } - chomp($line); - if ($::RETRY && ($line =~ /Connection link error/i) ) { - if ($::VERBOSE) { print "Need to retry $nodehdl{$readyh}\n"; } - push @retries, $nodehdl{$readyh}; - } elsif ($::DONOTFILTER || ($line!~/IBM Advanced Settings Utility version/i && - $line!~/Lenovo Advanced Settings Utility version/i && - $line!~/Licensed Materials - Property of IBM/i && - $line!~/Licensed Materials - Property of Lenovo/i && - $line!~/\(C\) Copyright IBM Corp. \d+-\d+ All Rights Reserved/i && - $line!~/\(C\) Copyright Lenovo Corp. \d+-\d+ All Rights Reserved/i && - $line!~/Connected to IMM at IP address/i )) { - print $nodehdl{$readyh}.": ".$line."\n"; - } +sub processoutput { #This way, one arbiter handles output, no interrupting + my $inputs = shift; # the select object that contains all the file descriptors + my @readyins = $inputs->can_read(1); # child fds with some output available + my $rc = @readyins; + my $readyh; + foreach $readyh (@readyins) { + my $cursel = new IO::Select; # need to do non-blocking reads on this fd + $cursel->add($readyh); + while ($cursel->can_read(0)) { + my $line = <$readyh>; + unless ($line) { + $inputs->remove($readyh); + close($readyh); + $exitcodes{ $nodehdl{$readyh} } = $? >> 8; + $children--; + next; + } + chomp($line); + if ($::RETRY && ($line =~ /Connection link error/i)) { + if ($::VERBOSE) { print "Need to retry $nodehdl{$readyh}\n"; } + push @retries, $nodehdl{$readyh}; + } elsif ($::DONOTFILTER || ($line !~ /IBM Advanced Settings Utility version/i && + $line !~ /Lenovo Advanced Settings Utility version/i && + $line !~ /Licensed Materials - Property of IBM/i && + $line !~ /Licensed Materials - Property of Lenovo/i && + $line !~ /\(C\) Copyright IBM Corp. \d+-\d+ All Rights Reserved/i && + $line !~ /\(C\) Copyright Lenovo Corp. \d+-\d+ All Rights Reserved/i && + $line !~ /Connected to IMM at IP address/i)) { + print $nodehdl{$readyh} . ": " . $line . "\n"; + } + } } - } - no strict 'subs'; - IO::Handle::flush(stdout); - use strict 'subs'; - yield; #Explicitly give all children a chance to refill any buffers - return $rc; + no strict 'subs'; + IO::Handle::flush(stdout); + use strict 'subs'; + yield; #Explicitly give all children a chance to refill any buffers + return $rc; } sub utilnode { - my $out = shift; # this is a reference to the child file descriptor - my $node = shift; - my $bmc = shift; - my $username = shift; - my $passwd = shift; - my $batchfile = shift; - my $args; - $bmc =~ s/,.*//; - if ($batchfile) { - $args = "batch $batchfile"; - } else { - foreach my $a (@_) { $args .= ' ' . xCAT::Utils->quote($a); } - } - my $cmd = "$::utilcmd $args --host '$bmc' --user '$username' --password '$passwd' 2>&1 |"; - if ($::VERBOSE) { print "forking $cmd\n"; } - my $pid = open($$out, $cmd); - $pids{$pid} = $node; + my $out = shift; # this is a reference to the child file descriptor + my $node = shift; + my $bmc = shift; + my $username = shift; + my $passwd = shift; + my $batchfile = shift; + my $args; + $bmc =~ s/,.*//; + + if ($batchfile) { + $args = "batch $batchfile"; + } else { + foreach my $a (@_) { $args .= ' ' . xCAT::Utils->quote($a); } + } + my $cmd = "$::utilcmd $args --host '$bmc' --user '$username' --password '$passwd' 2>&1 |"; + if ($::VERBOSE) { print "forking $cmd\n"; } + my $pid = open($$out, $cmd); + $pids{$pid} = $node; } # Contact xcatd to expand the noderange into a list of nodes sub expandnoderange { - my $noderange = shift @_; - my @nodes; - my @user = getpwuid($>); - my $homedir=$user[7]; - my %sslargs; - if (defined($ENV{'XCATSSLVER'})) { - $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; - } - - my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=>$homedir."/.xcat/client-cred.pem", - SSL_cert_file=>$homedir."/.xcat/client-cred.pem", - SSL_ca_file => $homedir."/.xcat/ca.pem", - SSL_use_cert => 1, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - %sslargs, - ); - die "Connection failure: $!\n" unless ($client); - #todo: get the bmc attr for each node, not the node name itself - my %cmdref = (command => 'noderange', noderange => $noderange); - $SIG{ALRM} = sub { die "No response getting noderange" }; - alarm(15); - my $msg = XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); - if ($ENV{XCATXMLTRACE}) { print $msg; } - print $client $msg; - alarm(15); - my $response=""; - while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - if ($ENV{XCATXMLTRACE}) { print $response; } - my $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; - } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - @nodes=@{$rsp->{node}}; - } - if ($rsp->{serverdone}) { - last; - } + my $noderange = shift @_; + my @nodes; + my @user = getpwuid($>); + my $homedir = $user[7]; + my %sslargs; + if (defined($ENV{'XCATSSLVER'})) { + $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; } - } - close($client); - if ($::VERBOSE) { print 'Nodes:', join(',',@nodes), "\n"; } - return @nodes; + + my $client = IO::Socket::SSL->new( + PeerAddr => $xcathost, + SSL_key_file => $homedir . "/.xcat/client-cred.pem", + SSL_cert_file => $homedir . "/.xcat/client-cred.pem", + SSL_ca_file => $homedir . "/.xcat/ca.pem", + SSL_use_cert => 1, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + %sslargs, + ); + die "Connection failure: $!\n" unless ($client); + + #todo: get the bmc attr for each node, not the node name itself + my %cmdref = (command => 'noderange', noderange => $noderange); + $SIG{ALRM} = sub { die "No response getting noderange" }; + alarm(15); + my $msg = XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); + if ($ENV{XCATXMLTRACE}) { print $msg; } + print $client $msg; + alarm(15); + my $response = ""; + + while (<$client>) { + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + if ($ENV{XCATXMLTRACE}) { print $response; } + my $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + @nodes = @{ $rsp->{node} }; + } + if ($rsp->{serverdone}) { + last; + } + } + } + close($client); + if ($::VERBOSE) { print 'Nodes:', join(',', @nodes), "\n"; } + return @nodes; } # Contact xcatd to get from the ipmi table for this list of nodes: bmc, username, password sub getipmiattrs { - my $noderange = shift @_; - my $nodeattrs = {}; # this will be a reference to a hash - my @user = getpwuid($>); - my $homedir=$user[7]; - my %sslargs; - if (defined($ENV{'XCATSSLVER'})) { - $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; - } - - my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=>$homedir."/.xcat/client-cred.pem", - SSL_cert_file=>$homedir."/.xcat/client-cred.pem", - SSL_ca_file => $homedir."/.xcat/ca.pem", - SSL_use_cert => 1, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - %sslargs, - ); - die "Connection failure: $!\n" unless ($client); - my %cmdref = (command => 'getipmicons', noderange => $noderange); - $SIG{ALRM} = sub { die "No response getting ipmi attributes" }; - alarm(15); - my $msg = XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); - if ($ENV{XCATXMLTRACE}) { print $msg; } - print $client $msg; - alarm(15); - my $response=""; - while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - if ($ENV{XCATXMLTRACE}) { print $response; } - my $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; - } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - #print Dumper($rsp->{node}); - foreach (keys %{$rsp->{node}}) { - $nodeattrs->{$_} = $rsp->{node}->{$_}; # this is reference to a hash, each key is the nodename and the value is a reference to a hash of attr values - } - } - if ($rsp->{serverdone}) { - last; - } + my $noderange = shift @_; + my $nodeattrs = {}; # this will be a reference to a hash + my @user = getpwuid($>); + my $homedir = $user[7]; + my %sslargs; + if (defined($ENV{'XCATSSLVER'})) { + $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; } - } - close($client); - #if ($::VERBOSE) { print 'Nodes:', join(',',$nodeattrs), "\n"; } - return $nodeattrs; + + my $client = IO::Socket::SSL->new( + PeerAddr => $xcathost, + SSL_key_file => $homedir . "/.xcat/client-cred.pem", + SSL_cert_file => $homedir . "/.xcat/client-cred.pem", + SSL_ca_file => $homedir . "/.xcat/ca.pem", + SSL_use_cert => 1, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + %sslargs, + ); + die "Connection failure: $!\n" unless ($client); + my %cmdref = (command => 'getipmicons', noderange => $noderange); + $SIG{ALRM} = sub { die "No response getting ipmi attributes" }; + alarm(15); + my $msg = XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); + if ($ENV{XCATXMLTRACE}) { print $msg; } + print $client $msg; + alarm(15); + my $response = ""; + + while (<$client>) { + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + if ($ENV{XCATXMLTRACE}) { print $response; } + my $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + + #print Dumper($rsp->{node}); + foreach (keys %{ $rsp->{node} }) { + $nodeattrs->{$_} = $rsp->{node}->{$_}; # this is reference to a hash, each key is the nodename and the value is a reference to a hash of attr values + } + } + if ($rsp->{serverdone}) { + last; + } + } + } + close($client); + + #if ($::VERBOSE) { print 'Nodes:', join(',',$nodeattrs), "\n"; } + return $nodeattrs; } diff --git a/xCAT-client/bin/pgsqlsetup b/xCAT-client/bin/pgsqlsetup index adcd7b8dd..2f97f50b3 100755 --- a/xCAT-client/bin/pgsqlsetup +++ b/xCAT-client/bin/pgsqlsetup @@ -41,7 +41,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -64,11 +64,12 @@ my $args = join ' ', @ARGV; $::command = "$0 $args"; Getopt::Long::Configure("bundling"); $Getopt::Long::ignorecase = 0; + # Default install location for all but version 9.0 -$::installdir = "/var/lib/pgsql"; # install location -$::installdatadir = "/var/lib/pgsql/data"; # install location -$::pgcmddir = "/usr/bin"; # pg cmds location -$::debiancfgdir = "/etc/postgresql/9.1/main"; +$::installdir = "/var/lib/pgsql"; # install location +$::installdatadir = "/var/lib/pgsql/data"; # install location +$::pgcmddir = "/usr/bin"; # pg cmds location +$::debiancfgdir = "/etc/postgresql/9.1/main"; my $INIT; my $SETUPODBC; my $NOSTART; @@ -76,16 +77,17 @@ my $SETUPPCM; my $HELP; my $VERSION; my $debianflag = 0; + # parse the options if ( !GetOptions( - 'i|init' => \$INIT, - 'o|odbc' => \$SETUPODBC, - 'N|nostart' => \$NOSTART, - 'P|PCM' => \$SETUPPCM, - 'h|help' => \$HELP, - 'v|version' => \$VERSION, - 'V|verbose' => \$::VERBOSE, + 'i|init' => \$INIT, + 'o|odbc' => \$SETUPODBC, + 'N|nostart' => \$NOSTART, + 'P|PCM' => \$SETUPPCM, + 'h|help' => \$HELP, + 'v|version' => \$VERSION, + 'V|verbose' => \$::VERBOSE, ) ) { @@ -107,8 +109,9 @@ if ($VERSION) xCAT::MsgUtils->message("I", $version); exit 0; } -# Database name xcatdb -$::dbname="xcatdb"; + +# Database name xcatdb +$::dbname = "xcatdb"; if ((!($INIT)) && (!($SETUPODBC))) { @@ -135,9 +138,10 @@ if (xCAT::Utils->isAIX()) else { $::osname = 'Linux'; + # determine whether redhat or sles $::linuxos = xCAT::Utils->osver(); - if ( -e "/etc/debian_version" ){ + if (-e "/etc/debian_version") { $debianflag = 1; } } @@ -147,15 +151,15 @@ else # check to see if perl-DBD-Pg is installed # my $cmd = "rpm -qa | grep perl-DBD-Pg"; -if ($debianflag){ +if ($debianflag) { $cmd = "dpkg -l | grep libdbd-pg-perl"; } -my @output=xCAT::Utils->runcmd($cmd, 0); +my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { my $message = - "\nperl-DBD-Pg is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; - if ($debianflag){ +"\nperl-DBD-Pg is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; + if ($debianflag) { $message = "\nlibdb-pg-perl is not installed. Use apt-get to install it."; } xCAT::MsgUtils->message("E", " $cmd failed. $message"); @@ -165,15 +169,15 @@ if ($::RUNCMD_RC != 0) # check to see if postgresql is installed # my $cmd = "rpm -qa | grep postgresql | grep server"; -if ($debianflag){ +if ($debianflag) { $cmd = "dpkg -l | grep postgresql | awk '{print \$2}'"; } -my @output=xCAT::Utils->runcmd($cmd, 0); +my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { my $message = - "\nPostgreSQL is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; - if ($debianflag){ +"\nPostgreSQL is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; + if ($debianflag) { $message = "\npostgresql is not installed. Use apt-get to install it."; } xCAT::MsgUtils->message("E", " $cmd failed. $message"); @@ -183,46 +187,47 @@ if ($::RUNCMD_RC != 0) # check if 9.X release not built by us is installed, setup different # SLES used default dir -if ( (grep(/postgresql9/, @output)) && ($::linuxos !~ /sles/) ){ # postgresql 9.x - # figure out which 9.x release and build path - my @parseout= split(/\-/, $output[0]); - my @ptflevel= split ("postgresql9",$parseout[0]); - $::postgres9=@ptflevel[1]; # set it to the PTF level - $::installdir = "/var/lib/pgsql/9.$::postgres9"; # override default - $::installdatadir = "/var/lib/pgsql/9.$::postgres9/data"; # override default - $::pgcmddir = "/usr/pgsql-9.$::postgres9/bin"; # pg cmds location +if ((grep(/postgresql9/, @output)) && ($::linuxos !~ /sles/)) { # postgresql 9.x + # figure out which 9.x release and build path + my @parseout = split(/\-/, $output[0]); + my @ptflevel = split("postgresql9", $parseout[0]); + $::postgres9 = @ptflevel[1]; # set it to the PTF level + $::installdir = "/var/lib/pgsql/9.$::postgres9"; # override default + $::installdatadir = "/var/lib/pgsql/9.$::postgres9/data"; # override default + $::pgcmddir = "/usr/pgsql-9.$::postgres9/bin"; # pg cmds location } -if ($debianflag){ +if ($debianflag) { undef $::postgres9; $::installdatadir = "/var/lib/postgresql/9.1/main"; - $::pgcmddir = "/usr/lib/postgresql/9.1/bin"; - for my $line (@output){ - if ($line =~ /postgresql\-9/){ + $::pgcmddir = "/usr/lib/postgresql/9.1/bin"; + for my $line (@output) { + if ($line =~ /postgresql\-9/) { my $pgsqlver = substr $line, 11; - $::pgcmddir = "/usr/lib/postgresql/${pgsqlver}/bin"; + $::pgcmddir = "/usr/lib/postgresql/${pgsqlver}/bin"; $::installdatadir = "/var/lib/postgresql/${pgsqlver}/main"; - $::debiancfgdir = "/etc/postgresql/${pgsqlver}/main"; + $::debiancfgdir = "/etc/postgresql/${pgsqlver}/main"; last; } } } + # check to see if PostgreSQL is running my $pgsqlrunning = 0; my $xcatrunningpgsql = 0; -my $cmd = "ps -ef | grep postgres"; -my @output = xCAT::Utils->runcmd($cmd, 0); +my $cmd = "ps -ef | grep postgres"; +my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC == 0) # already running { my $pgsqlcheck = "postgres:"; # see if really running if (grep(/$pgsqlcheck/, @output)) { - $pgsqlrunning = 1; + $pgsqlrunning = 1; } } -if (-e ("/etc/xcat/cfgloc")) # check to see if xcat is using pgsql -{ # cfgloc exists +if (-e ("/etc/xcat/cfgloc")) # check to see if xcat is using pgsql +{ # cfgloc exists $cmd = "fgrep Pg /etc/xcat/cfgloc"; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC == 0) @@ -230,7 +235,7 @@ if (-e ("/etc/xcat/cfgloc")) # check to see if xcat is using pgsql if ($INIT) { my $message = - "The /etc/xcat/cfgloc file is already configured for PostgreSQL. xcat database initialization will not take place."; +"The /etc/xcat/cfgloc file is already configured for PostgreSQL. xcat database initialization will not take place."; xCAT::MsgUtils->message("I", "$message"); } $xcatrunningpgsql = 1; @@ -240,151 +245,151 @@ if (-e ("/etc/xcat/cfgloc")) # check to see if xcat is using pgsql # if not just odbc update # Get admin password or use the env variable # -if (($odbconly == 0) && ($xcatrunningpgsql == 0)) +if (($odbconly == 0) && ($xcatrunningpgsql == 0)) { # not just updating the odbc and xcat not already running on pg if ($ENV{'XCATPGPW'}) # passwd supplied { - my $pw=$ENV{'XCATPGPW'}; - if ($pw =~ m/[^a-zA-Z0-9]/){ # if not alpha-numerid - my $warning = - "The password in the env variable XCATPGPW is not alpha-numeric."; - xCAT::MsgUtils->message("E", $warning); - exit 1; - } - $::adminpassword = $ENV{'XCATPGPW'}; - } else { - - my $msg = "Input the password for xcatadm id: "; - xCAT::MsgUtils->message('I', "$msg"); - `stty -echo`; - chop($::adminpassword = ); - `stty echo`; - if ($::adminpassword =~ m/[^a-zA-Z0-9]/){ # if not alpha-numerid + my $pw = $ENV{'XCATPGPW'}; + if ($pw =~ m/[^a-zA-Z0-9]/) { # if not alpha-numerid my $warning = - "The input password is not alpha-numeric. Rerun the command an input an alpha-numeric password."; + "The password in the env variable XCATPGPW is not alpha-numeric."; xCAT::MsgUtils->message("E", $warning); exit 1; - } - - } + } + $::adminpassword = $ENV{'XCATPGPW'}; + } else { + + my $msg = "Input the password for xcatadm id: "; + xCAT::MsgUtils->message('I', "$msg"); + `stty -echo`; + chop($::adminpassword = ); + `stty echo`; + if ($::adminpassword =~ m/[^a-zA-Z0-9]/) { # if not alpha-numerid + my $warning = +"The input password is not alpha-numeric. Rerun the command an input an alpha-numeric password."; + xCAT::MsgUtils->message("E", $warning); + exit 1; + } + + } } # initial setup request and not already running pgsql if (($INIT) && ($xcatrunningpgsql == 0)) { - if (!($NOSTART)) { # if not just setting up the database - # - # Backup current database - # - my $homedir = xCAT::Utils->getHomeDir(); - $::backupdir = $homedir; - if ($::osname eq 'AIX') + if (!($NOSTART)) { # if not just setting up the database + # + # Backup current database + # + my $homedir = xCAT::Utils->getHomeDir(); + $::backupdir = $homedir; + if ($::osname eq 'AIX') + { + $::backupdir .= "xcat-dbback"; + } + else + { + $::backupdir .= "/xcat-dbback"; + } + + &backupxcatdb; + + # shutdown the xcatd daemon + &shutdownxcatd; + } + my $hname; + $hname = `hostname`; + chomp $hname; + if (!($NOSTART)) { # if not just setting up the database + # + # Get MN name from site.master in backed up database + # if that does not exist use resolved hostname + # double check site.master for resolution + my $sitefile = "$::backupdir/site.csv"; + my $cmd = "grep master $sitefile"; + my @output = xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC == 0) # entry in site table + { + (my $attr, my $master) = split(",", $output[0]); + (my $q, $hname) = split("\"", $master); + chomp $hname; + } + } + + + my $ipaddr = xCAT::NetworkUtils->getipaddr($hname); + if ($ipaddr) { - $::backupdir .= "xcat-dbback"; + $::MN = $ipaddr; } else { - $::backupdir .= "/xcat-dbback"; - } - - &backupxcatdb; - - # shutdown the xcatd daemon - &shutdownxcatd; - } - my $hname; - $hname = `hostname`; - chomp $hname; - if (!($NOSTART)) { # if not just setting up the database - # - # Get MN name from site.master in backed up database - # if that does not exist use resolved hostname - # double check site.master for resolution - my $sitefile = "$::backupdir/site.csv"; - my $cmd = "grep master $sitefile"; - my @output = xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) # entry in site table - { - (my $attr, my $master) = split(",", $output[0]); - (my $q, $hname) = split("\"", $master); - chomp $hname; - } - } - - - my $ipaddr = xCAT::NetworkUtils->getipaddr($hname); - if ($ipaddr) - { - $::MN = $ipaddr; - } - else - { xCAT::MsgUtils->message("E", "Hostname resolution for $hname failed."); exit(1); - } + } - # Add postgres user and group and xcatadm for AIX - # create the /var/lib/pgsql data directory and set permissions. - # All this is done on Linux install automatically: - # postgres is created on Linux and xcatadm does not need to be a - # real userid on Linux. Also directory permissions are correct on Linux - # - if ($::osname eq 'AIX') - { + # Add postgres user and group and xcatadm for AIX + # create the /var/lib/pgsql data directory and set permissions. + # All this is done on Linux install automatically: + # postgres is created on Linux and xcatadm does not need to be a + # real userid on Linux. Also directory permissions are correct on Linux + # + if ($::osname eq 'AIX') + { &mkpgusers; - } + } - # - # Init Pg database and setup pg_hba.conf and postgresql.conf - # - &initpgdb; + # + # Init Pg database and setup pg_hba.conf and postgresql.conf + # + &initpgdb; - # - # Start Postgresql server - # - if ($pgsqlrunning == 0) # if not already running - { - &pgstart(0); - } + # + # Start Postgresql server + # + if ($pgsqlrunning == 0) # if not already running + { + &pgstart(0); + } - # - # Setup Postgresql to restart on reboot - # - &pgreboot; + # + # Setup Postgresql to restart on reboot + # + &pgreboot; - # if xcat not already configured to run Postgresql add xCAT database - if ($xcatrunningpgsql == 0) - { + # if xcat not already configured to run Postgresql add xCAT database + if ($xcatrunningpgsql == 0) + { - # - # Create xcatd database - # Create xcatadm in the database - # - &setupxcatdb; - - # - # create cfgloc file - # - &createcfgloc; - - if (!($NOSTART)) { # if not just setting up the database # - # Restore backed up database into PostgreSQL + # Create xcatd database + # Create xcatadm in the database # - &restorexcatdb; - } - } - - if (!($NOSTART)) { # if not just setting up the database - xCAT::MsgUtils->message("I", - "xCAT is running on the PostgreSQL database.\n"); - } else { - xCAT::MsgUtils->message("I", - "xCAT PostgreSQL database is setup.\n"); - } + &setupxcatdb; + + # + # create cfgloc file + # + &createcfgloc; + + if (!($NOSTART)) { # if not just setting up the database + # + # Restore backed up database into PostgreSQL + # + &restorexcatdb; + } + } + + if (!($NOSTART)) { # if not just setting up the database + xCAT::MsgUtils->message("I", + "xCAT is running on the PostgreSQL database.\n"); + } else { + xCAT::MsgUtils->message("I", + "xCAT PostgreSQL database is setup.\n"); + } } # end initialization @@ -420,10 +425,10 @@ sub usage { xCAT::MsgUtils->message( 'I', - "Usage:\npgsqlsetup - Performs the setup of PostgreSQL for xCAT to use as its database. See man pgsqlsetup for more information." - ); +"Usage:\npgsqlsetup - Performs the setup of PostgreSQL for xCAT to use as its database. See man pgsqlsetup for more information." + ); my $msg = - "pgsqlsetup <-h|--help>\n <-v|--version>\n <-i|--init> [-N|--nostart] [-P|--PCM] [-o|--odbc] [-V|--verbose]\n <-o|--odbc> [-V|--verbose]"; +"pgsqlsetup <-h|--help>\n <-v|--version>\n <-i|--init> [-N|--nostart] [-P|--PCM] [-o|--odbc] [-V|--verbose]\n <-o|--odbc> [-V|--verbose]"; xCAT::MsgUtils->message('I', "$msg"); } @@ -452,9 +457,9 @@ sub shutdownxcatd } else { - # $xcmd = "service xcatd stop"; - my $ret=xCAT::Utils->stopservice("xcatd"); - return $ret; + # $xcmd = "service xcatd stop"; + my $ret = xCAT::Utils->stopservice("xcatd"); + return $ret; } } @@ -475,29 +480,29 @@ sub backupxcatdb xCAT::MsgUtils->message( - "I", - "Backing up xCAT Database to $::backupdir.\nThis could take several minutes." - ); + "I", +"Backing up xCAT Database to $::backupdir.\nThis could take several minutes." + ); if (!(-e $::backupdir)) { # does not exist, make it - my $cmd = "mkdir -p $::backupdir"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); - } + my $cmd = "mkdir -p $::backupdir"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); + } } else { # remove contents - my $cmd = "rm -f $::backupdir/*"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); - } + my $cmd = "rm -f $::backupdir/*"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); + } } # back it up @@ -505,8 +510,8 @@ sub backupxcatdb xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", " $cmd failed."); - exit(1); + xCAT::MsgUtils->message("E", " $cmd failed."); + exit(1); } } @@ -580,7 +585,7 @@ sub mkpgusers # secure passwd in verbose mode my $tmpv = $::VERBOSE; - $::VERBOSE = 0; + $::VERBOSE = 0; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { @@ -638,14 +643,15 @@ sub mkpgusers sub runpostgrescmd { my $orgcmd = shift; - my $cmd = "\'"; + my $cmd = "\'"; $cmd .= $orgcmd; $cmd .= ' 2>&1'; - $cmd .= "\'"; + $cmd .= "\'"; system("su - postgres -c $cmd"); } + #----------------------------------------------------------------------------- =head3 runpgcmd_chkoutput @@ -662,34 +668,34 @@ sub runpostgrescmd sub runpgcmd_chkoutput { my $orgcmd = shift; - my $rc =0; - my $cmd = "\'"; + my $rc = 0; + my $cmd = "\'"; $cmd .= $orgcmd; $cmd .= ' 2>&1'; - $cmd .= "\'"; - - my $retries=0; + $cmd .= "\'"; + + my $retries = 0; my @output; while ($retries < 6) { - $retries++; - @output =`su - postgres -c $cmd`; - if (grep(/could not connect to database postgres/, @output)) { - sleep 5; - $rc=1 - } else { - $rc=0; - foreach my $line (@output) { - print "$line \n"; - } - last; - } + $retries++; + @output = `su - postgres -c $cmd`; + if (grep(/could not connect to database postgres/, @output)) { + sleep 5; + $rc = 1 + } else { + $rc = 0; + foreach my $line (@output) { + print "$line \n"; + } + last; + } } - if ($rc == 1) { # print out the postgresql connect failure - foreach my $line (@output) { - print "$line \n"; - } + if ($rc == 1) { # print out the postgresql connect failure + foreach my $line (@output) { + print "$line \n"; + } } - return $rc; + return $rc; } @@ -711,12 +717,12 @@ sub initpgdb my $dbrestart = 0; # init the database, must su to postgres - + if ($::osname eq 'AIX') { - $cmd = "$::installdir/bin/initdb -D $::installdatadir "; + $cmd = "$::installdir/bin/initdb -D $::installdatadir "; } else { - $cmd = "$::pgcmddir/initdb -D $::installdatadir "; + $cmd = "$::pgcmddir/initdb -D $::installdatadir "; } &runpostgrescmd($cmd); @@ -726,21 +732,22 @@ sub initpgdb my $hbafile = $::installdatadir; $hbafile .= "\/pg_hba.conf"; - if ($debianflag){ + if ($debianflag) { $hbafile = $::debiancfgdir . "/pg_hba.conf"; } $cmd = "fgrep $::MN $hbafile"; xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) # not already there + if ($::RUNCMD_RC != 0) # not already there { - $cmd = "cp $hbafile $hbafile.org"; # backup the original + $cmd = "cp $hbafile $hbafile.org"; # backup the original xCAT::Utils->runcmd($cmd, -1); my $insertstr = "host all all "; $insertstr .= $::MN; $insertstr .= "\/32 md5 "; $cmd = - "awk '{gsub(\"\IPv4 local connections:\",\"\IPv4 local connections:\\n$insertstr \"); print}' $hbafile > $hbafile.xcat"; +"awk '{gsub(\"\IPv4 local connections:\",\"\IPv4 local connections:\\n$insertstr \"); print}' $hbafile > $hbafile.xcat"; xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) { @@ -769,7 +776,7 @@ sub initpgdb # setup the postgresql.conf file my $pgconf = $::installdatadir; $pgconf .= "\/postgresql.conf"; - if ($debianflag){ + if ($debianflag) { $pgconf = $::debiancfgdir . "/postgresql.conf"; } my $str = "\"setup by xCAT\""; @@ -807,25 +814,26 @@ sub initpgdb } $dbrestart = 1; } + # make sure everything in /var/lib/pgsql/data is owned by postgres - if ($::installdatadir) { # for protection - $cmd = "chown postgres $::installdatadir/*"; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { + if ($::installdatadir) { # for protection + $cmd = "chown postgres $::installdatadir/*"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { - xCAT::MsgUtils->message("E", " $cmd failed."); - } - $cmd = "chgrp postgres $::installdatadir/* "; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { + xCAT::MsgUtils->message("E", " $cmd failed."); + } + $cmd = "chgrp postgres $::installdatadir/* "; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { - xCAT::MsgUtils->message("E", " $cmd failed."); - } + xCAT::MsgUtils->message("E", " $cmd failed."); + } } - if ($dbrestart){ + if ($dbrestart) { &pgstart(1); } @@ -850,7 +858,7 @@ sub pgstart { my $startflg = shift; my $cmd; - my $ret=0; + my $ret = 0; xCAT::MsgUtils->message("I", "Starting the PosgreSQL Server"); if ($::osname eq 'AIX') { @@ -861,25 +869,28 @@ sub pgstart } else # linux { - if (defined($::postgres9)) { # set to the PTF level of postgresql 9.X - #$cmd = "service postgresql-9.$::postgres9 start"; - $cmd = "postgresql-9.$::postgres9"; + if (defined($::postgres9)) { # set to the PTF level of postgresql 9.X + #$cmd = "service postgresql-9.$::postgres9 start"; + $cmd = "postgresql-9.$::postgres9"; } else { - #$cmd = "service postgresql start"; - $cmd = "postgresql"; + + #$cmd = "service postgresql start"; + $cmd = "postgresql"; } - if ($startflg == 0) { - $ret=xCAT::Utils->startservice($cmd); + if ($startflg == 0) { + $ret = xCAT::Utils->startservice($cmd); } else { - $ret=xCAT::Utils->restartservice($cmd); + $ret = xCAT::Utils->restartservice($cmd); } if ($ret != 0) { xCAT::MsgUtils->message("E", " failed to start $cmd."); exit(1); } + # check to see if running before continuing - my $retries =0; - my $pgstarted =0; + my $retries = 0; + my $pgstarted = 0; + #if (defined($::postgres9)) { # set to the PTF level of postgresql 9.X # #$cmd = "service postgresql-9.$::postgres9 status"; # $ret=xCAT::Utils->checkservicestatus("postgresql-9.$::postgres9"); @@ -888,22 +899,23 @@ sub pgstart # $ret=xCAT::Utils->checkservicestatus("postgresql"); #} while ($retries < 30) { - $retries++; - #my @status=xCAT::Utils->runcmd($cmd, -1); - #if (grep(/[r|R]unning/, @status)) { - $ret=xCAT::Utils->checkservicestatus($cmd); - if($ret == 0){ - $pgstarted=1; - last; - } - sleep 1; + $retries++; + + #my @status=xCAT::Utils->runcmd($cmd, -1); + #if (grep(/[r|R]unning/, @status)) { + $ret = xCAT::Utils->checkservicestatus($cmd); + if ($ret == 0) { + $pgstarted = 1; + last; + } + sleep 1; } - if ($pgstarted ==0) { # failed to started - xCAT::MsgUtils->message("E", " service postgresql start failed."); - exit(1); - - } - } # end linux + if ($pgstarted == 0) { # failed to started + xCAT::MsgUtils->message("E", " service postgresql start failed."); + exit(1); + + } + } # end linux } @@ -926,28 +938,30 @@ sub pgreboot xCAT::MsgUtils->message( "I", " Autosetup on AIX to start Postgresql on reboot not supported yet." - ); + ); } else # linux { - if (defined($::postgres9)) { # set to the postgresql ptf level - # $cmd = "chkconfig postgresql-9.$::postgres9 on"; + if (defined($::postgres9)) { # set to the postgresql ptf level + # $cmd = "chkconfig postgresql-9.$::postgres9 on"; $cmd = "postgresql-9.$::postgres9"; } else { + #$cmd = "chkconfig postgresql on"; $cmd = "postgresql"; } + #if ($debianflag){ - #$cmd = "update-rc.d postgresql defaults"; + #$cmd = "update-rc.d postgresql defaults"; #} #xCAT::Utils->runcmd($cmd, 0); #if ($::RUNCMD_RC != 0) - my $ret=xCAT::Utils->enableservice($cmd); - if($cmd !=0 ) + my $ret = xCAT::Utils->enableservice($cmd); + if ($cmd != 0) { xCAT::MsgUtils->message("E", - "enable service $cmd failed. PostgreSQL will not restart on reboot."); +"enable service $cmd failed. PostgreSQL will not restart on reboot."); } } @@ -968,42 +982,44 @@ sub setupxcatdb { my $cmd; + # create the database if ($::osname eq 'AIX') { - $cmd = "$::installdir/bin/createdb $::dbname "; - } else { #Linux - $cmd = "$::pgcmddir/createdb $::dbname "; + $cmd = "$::installdir/bin/createdb $::dbname "; + } else { #Linux + $cmd = "$::pgcmddir/createdb $::dbname "; } + # We need to check the output, because sometimes # postmaster daemon is not ready at this point to create the database my $rc = &runpgcmd_chkoutput($cmd); if ($rc > 0) { xCAT::MsgUtils->message("E", - "Failed creating the $::dbname database"); + "Failed creating the $::dbname database"); exit(1); } if ($::osname eq 'AIX') { - $cmd = "/var/lib/pgsql/bin/psql -d $::dbname -U postgres"; - } else { # Linux - $cmd = "$::pgcmddir/psql -d $::dbname -U postgres"; - if ( ($debianflag) || ($::linuxos =~ /sles/) ){ - $cmd = "su - postgres -c '$::pgcmddir/psql -d $::dbname -U postgres'"; - } + $cmd = "/var/lib/pgsql/bin/psql -d $::dbname -U postgres"; + } else { # Linux + $cmd = "$::pgcmddir/psql -d $::dbname -U postgres"; + if (($debianflag) || ($::linuxos =~ /sles/)) { + $cmd = "su - postgres -c '$::pgcmddir/psql -d $::dbname -U postgres'"; + } } my $pgsql; my $timeout = 10; # sets Expect default timeout, 0 accepts immediately my $pwd_sent = 0; - my $pg_prompt = "$::dbname=# "; - my $expect_log = undef; - my $debug = 0; + my $pg_prompt = "$::dbname=# "; + my $expect_log = undef; + my $debug = 0; $pgsql = new Expect; # # -re $pg_prompt - # For example xcatdb=# + # For example xcatdb=# # # @@ -1023,28 +1039,28 @@ sub setupxcatdb #$pgsql->log_stdout(1); $pgsql->log_stdout($debug); - my $createuser="CREATE USER xcatadm WITH PASSWORD \'$::adminpassword\';\r"; + my $createuser = "CREATE USER xcatadm WITH PASSWORD \'$::adminpassword\';\r"; my $spawncmd; - $spawncmd = $cmd; + $spawncmd = $cmd; unless ($pgsql->spawn($spawncmd)) { xCAT::MsgUtils->message("E", - "Unable to run $spawncmd to add xcat admin user."); + "Unable to run $spawncmd to add xcat admin user."); return; } my @result = $pgsql->expect( $timeout, [ - $pg_prompt, - sub { - $pgsql->send("$createuser"); - $pgsql->clear_accum(); - $pgsql->exp_continue(); - $pgsql->send("\q;\r"); - } + $pg_prompt, + sub { + $pgsql->send("$createuser"); + $pgsql->clear_accum(); + $pgsql->exp_continue(); + $pgsql->send("\q;\r"); + } ] - ); + ); ###################################### # Expect error - report and quit ########################################## @@ -1053,7 +1069,7 @@ sub setupxcatdb my $errmsg = $result[1]; $pgsql->soft_close(); xCAT::MsgUtils->message("E", - "Failed creating xcatadm id."); + "Failed creating xcatadm id."); exit(1); } @@ -1064,7 +1080,7 @@ sub setupxcatdb # # -re $pg_prompt - # For example xcatdb=# + # For example xcatdb=# # # @@ -1084,28 +1100,28 @@ sub setupxcatdb #$pgsql->log_stdout(1); $pgsql->log_stdout($debug); - $createuser="CREATE USER root WITH PASSWORD \'$::adminpassword\';\r"; + $createuser = "CREATE USER root WITH PASSWORD \'$::adminpassword\';\r"; $spawncmd; - $spawncmd = $cmd; + $spawncmd = $cmd; unless ($pgsql->spawn($spawncmd)) { xCAT::MsgUtils->message("E", - "Unable to run $spawncmd to add xcat root user."); + "Unable to run $spawncmd to add xcat root user."); return; } my @result = $pgsql->expect( $timeout, [ - $pg_prompt, - sub { - $pgsql->send("$createuser"); - $pgsql->clear_accum(); - $pgsql->exp_continue(); - $pgsql->send("\q;\r"); - } + $pg_prompt, + sub { + $pgsql->send("$createuser"); + $pgsql->clear_accum(); + $pgsql->exp_continue(); + $pgsql->send("\q;\r"); + } ] - ); + ); ###################################### # Expect error - report and quit ########################################## @@ -1114,7 +1130,7 @@ sub setupxcatdb my $errmsg = $result[1]; $pgsql->soft_close(); xCAT::MsgUtils->message("E", - "Failed creating root id. $errmsg"); + "Failed creating root id. $errmsg"); exit(1); } @@ -1149,22 +1165,22 @@ sub setupODBC # for all OS need unixODBC rpm my $message; my $cmd = "rpm -qa | grep unixODBC"; - if ($debianflag){ + if ($debianflag) { $cmd = "dpkg -l | grep unixodbc"; } xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { $message = - "unixODBC rpm is not installed. Install from the OS CDs."; - if ($debianflag){ + "unixODBC rpm is not installed. Install from the OS CDs."; + if ($debianflag) { $message = "unixodbc is not installed. Install it first."; } xCAT::MsgUtils->message("E", "$message"); exit(1); } $cmd = "rpm -qa | grep postgresql-odbc"; - if ($debianflag){ + if ($debianflag) { $cmd = "dpkg -l | grep odbc-postgresql"; } xCAT::Utils->runcmd($cmd, -1); @@ -1172,17 +1188,17 @@ sub setupODBC { $message = "postgresql-odbc rpm is not installed. Install from the OS CDs."; - if ($debianflag){ + if ($debianflag) { $message = "odbc-postgresql is not installed. Install it first."; } xCAT::MsgUtils->message("E", " $message"); exit(1); } - my $xcatconfig = "/etc/xcat/cfgloc"; + my $xcatconfig = "/etc/xcat/cfgloc"; if (!(-e $xcatconfig)) { $message = - "The $xcatconfig file is missing. You need to configure xCAT for PostgreSQL before setting up the ODBC."; +"The $xcatconfig file is missing. You need to configure xCAT for PostgreSQL before setting up the ODBC."; xCAT::MsgUtils->message("E", "$message"); exit(1); @@ -1190,36 +1206,39 @@ sub setupODBC $cmd = "fgrep -i host $xcatconfig"; my @output; @output = xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) # cannot get the necessary hostname or ip + if ($::RUNCMD_RC != 0) # cannot get the necessary hostname or ip { - $message = - "Cannot find host info in the /etc/xcat/cfgloc file. Configuration of ODBC cannot continue."; - xCAT::MsgUtils->message("E", "$message"); - exit(1); + $message = +"Cannot find host info in the /etc/xcat/cfgloc file. Configuration of ODBC cannot continue."; + xCAT::MsgUtils->message("E", "$message"); + exit(1); } + # get host and password database from cfgloc - my( $connstring, $adminid, $passwd) = split(/\|/, $output[0]); - my ($hdr, $id, $server) = split(/=/, $connstring); - my ($database,$footer) = split(/;/, $id); - # the odbcinst.ini file should have been created during install of the + my ($connstring, $adminid, $passwd) = split(/\|/, $output[0]); + my ($hdr, $id, $server) = split(/=/, $connstring); + my ($database, $footer) = split(/;/, $id); + + # the odbcinst.ini file should have been created during install of the # unixODBC and postgresql-ODBC rpms my $odbcfile = "/etc/odbc.ini"; my $odbcinstfile = "/etc/odbcinst.ini"; - if (!( -e $odbcinstfile)) { - $message = - "Cannot find $odbcinstfile. Configuration of ODBC cannot continue."; - xCAT::MsgUtils->message("E", "$message"); - exit(1); + if (!(-e $odbcinstfile)) { + $message = + "Cannot find $odbcinstfile. Configuration of ODBC cannot continue."; + xCAT::MsgUtils->message("E", "$message"); + exit(1); } + # setup the DSN odbc.ini file $cmd = "fgrep -i xcatdb $odbcfile"; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) # then xcat entry not there { my $entry = - "[xCATDB]\nDriver = PostgreSQL\nSERVER = $server\nPORT = 3306\nDATABASE = $database"; +"[xCATDB]\nDriver = PostgreSQL\nSERVER = $server\nPORT = 3306\nDATABASE = $database"; $cmd = "echo \"$entry\" >> $odbcfile"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) @@ -1231,24 +1250,27 @@ sub setupODBC } } else - { # entry already there + { # entry already there $message = "$odbcfile already configured, will not change."; xCAT::MsgUtils->message("I", "$message"); } + # setup $roothome/.odbc.ini so root will not have to specify password # when accessing through ODBC my $homedir = xCAT::Utils->getHomeDir(); my $rootodbcfile = $homedir; $rootodbcfile .= "/.odbc.ini"; + # setup the DSN odbc.ini file $cmd = "fgrep -i XCATDB $rootodbcfile"; xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) # then xcat entry not there { my $entry = - "[xCATDB]\nSERVER =$server\nDATABASE = $database\nUSER = $adminid\nPASSWORD = $passwd"; +"[xCATDB]\nSERVER =$server\nDATABASE = $database\nUSER = $adminid\nPASSWORD = $passwd"; $cmd = "echo \"$entry\" >> $rootodbcfile"; + # secure passwd in verbose mode my $tmpv = $::VERBOSE; $::VERBOSE = 0; @@ -1264,7 +1286,7 @@ sub setupODBC } else { # entry already there - $message = "$rootodbcfile already configured, will not change. Make sure the userid and password are correct for PostgreSQL"; + $message = "$rootodbcfile already configured, will not change. Make sure the userid and password are correct for PostgreSQL"; xCAT::MsgUtils->message("I", "$message"); } @@ -1308,7 +1330,7 @@ sub createcfgloc # secure passwd in verbose mode my $tmpv = $::VERBOSE; - $::VERBOSE = 0; + $::VERBOSE = 0; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { @@ -1340,27 +1362,28 @@ sub restorexcatdb # set the env variable for Table.pm for the new database my $xcatcfg; my $cfgl; - open($cfgl,"<","/etc/xcat/cfgloc"); + open($cfgl, "<", "/etc/xcat/cfgloc"); $xcatcfg = <$cfgl>; close($cfgl); chomp($xcatcfg); - + # restore the database xCAT::MsgUtils->message( "I", - "Restoring the xCAT Database with $::backupdir to PostgreSQL database.\nThis could take several minutes." - ); +"Restoring the xCAT Database with $::backupdir to PostgreSQL database.\nThis could take several minutes." + ); if (!(-d $::backupdir)) { # does not exist, error xCAT::MsgUtils->message("E", - " $::backupdir is missing. Cannot retore the database."); + " $::backupdir is missing. Cannot retore the database."); exit(1); } my $tmpv = $::VERBOSE; - $::VERBOSE = 0; + $::VERBOSE = 0; # restore it my $cmd = "XCATBYPASS=1 XCATCFG=\"$xcatcfg\" restorexCATdb -p $::backupdir"; + # secure passwords in verbose mode my $tmpv = $::VERBOSE; $::VERBOSE = 0; @@ -1386,7 +1409,7 @@ sub restorexcatdb else { #$xcmd = "service xcatd start"; - my $ret=xCAT::Utils->startservice("xcatd"); + my $ret = xCAT::Utils->startservice("xcatd"); return $ret; } diff --git a/xCAT-client/bin/pping b/xCAT-client/bin/pping index 5193acd0e..09bf8cdba 100755 --- a/xCAT-client/bin/pping +++ b/xCAT-client/bin/pping @@ -2,7 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html #Note, this pping still frontends fping. I think it would be possible to write a perl equivalent, but #I've not had the time. Net::Ping shows perl code I could see being adapted for a somewhat -#asynchronous ICMP ping (the tcp syn is interesting, but far too limited, and that is currently the only async +#asynchronous ICMP ping (the tcp syn is interesting, but far too limited, and that is currently the only async #method Net::Ping provides. BEGIN { @@ -16,36 +16,38 @@ use xCAT::TableUtils; use POSIX qw(:signal_h :errno_h :sys_wait_h); use IO::Socket::SSL; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; + #use Data::Dumper; use IO::Handle; use IO::Select; use Getopt::Long; -my $USAGE="Usage: pping [-i|--interface interfaces][-f|--use_fping] noderange +my $USAGE = "Usage: pping [-i|--interface interfaces][-f|--use_fping] noderange pping -h|--help - pping -v|--version\n"; + pping -v|--version\n"; my $interface; + # Parse the options require Getopt::Long; -Getopt::Long::Configure ("bundling"); -if(!GetOptions( - 'f|use_fping' => \$::USE_FPING, - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, - 'X|noexpand' => \$::NOEXPAND, - 'i|interface=s' => \$interface)) - { - print "$USAGE"; - exit 1; - } +Getopt::Long::Configure("bundling"); +if (!GetOptions( + 'f|use_fping' => \$::USE_FPING, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, + 'X|noexpand' => \$::NOEXPAND, + 'i|interface=s' => \$interface)) +{ + print "$USAGE"; + exit 1; +} -if ($::HELP) { print "$USAGE"; exit 0} -if ($::VERSION) {print xCAT::Utils->Version() . "\n"; exit 0} -my $xcathost='localhost:3001'; +if ($::HELP) { print "$USAGE"; exit 0 } +if ($::VERSION) { print xCAT::Utils->Version() . "\n"; exit 0 } +my $xcathost = 'localhost:3001'; if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; + $xcathost = $ENV{XCATHOST}; } unless (@ARGV) { @@ -53,60 +55,61 @@ unless (@ARGV) { exit(1); } my $noderange = $ARGV[0]; -my @nodes=(); -my $cmd="id -u"; -my $userid = xCAT::Utils->runcmd("$cmd", -1); +my @nodes = (); +my $cmd = "id -u"; +my $userid = xCAT::Utils->runcmd("$cmd", -1); -if ($::NOEXPAND) { # this is when ppping is calling us and has already expanded the noderange - @nodes = split(/,/, $noderange); +if ($::NOEXPAND) { # this is when ppping is calling us and has already expanded the noderange + @nodes = split(/,/, $noderange); } -else { # the normal case of the user running the cmd - expand the noderange using xcatd +else { # the normal case of the user running the cmd - expand the noderange using xcatd my %sslargs; if (defined($ENV{'XCATSSLVER'})) { $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; } - my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=> xCAT::Utils->getHomeDir()."/.xcat/client-cred.pem", - SSL_cert_file=> xCAT::Utils->getHomeDir()."/.xcat/client-cred.pem", - SSL_ca_file => xCAT::Utils->getHomeDir()."/.xcat/ca.pem", - SSL_use_cert => 1, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - %sslargs, - ); - die "Connection failure: $!\n" unless ($client); - my %cmdref = (command => 'noderange', noderange => $noderange); - $SIG{ALRM} = sub { die "No response getting noderange" }; - alarm(15); - print $client XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); - alarm(15); - my $response=""; - while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - my $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; - } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - @nodes=@{$rsp->{node}}; - } - if ($rsp->{serverdone}) { - last; - } - } - } - close($client); -} # end of else that expands the noderange using xcatd + my $client = IO::Socket::SSL->new( + PeerAddr => $xcathost, + SSL_key_file => xCAT::Utils->getHomeDir() . "/.xcat/client-cred.pem", + SSL_cert_file => xCAT::Utils->getHomeDir() . "/.xcat/client-cred.pem", + SSL_ca_file => xCAT::Utils->getHomeDir() . "/.xcat/ca.pem", + SSL_use_cert => 1, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + %sslargs, + ); + die "Connection failure: $!\n" unless ($client); + my %cmdref = (command => 'noderange', noderange => $noderange); + $SIG{ALRM} = sub { die "No response getting noderange" }; + alarm(15); + print $client XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); + alarm(15); + my $response = ""; + + while (<$client>) { + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + my $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + @nodes = @{ $rsp->{node} }; + } + if ($rsp->{serverdone}) { + last; + } + } + } + close($client); +} # end of else that expands the noderange using xcatd unless (scalar(@nodes)) { - exit 1; + exit 1; } # I think this was only needed when we forked ping ourselves @@ -115,61 +118,62 @@ unless (scalar(@nodes)) { #$SIG{CHLD} = sub { while (waitpid(-1,WNOHANG) > 0) { $children--; } }; my $usenmap = (-x '/usr/bin/nmap' or -x '/usr/local/bin/nmap'); -if ($::USE_FPING) { # Use fping instead of nmap - $usenmap = 0; +if ($::USE_FPING) { # Use fping instead of nmap + $usenmap = 0; } my @interfaces; if ($interface) { @interfaces = split(/,/, $interface); } -else { $interfaces[0] = ''; } +else { $interfaces[0] = ''; } # Do the pings to the nodes for each interface in sequence. We could consider doing all the interfaces # in parallel, but then the output would get all mixed up and be confusing for the user. foreach my $interf (@interfaces) { - my $noderef; - if ($interf) { - # make a copy of the node list and add the interface on - $noderef = [ @nodes ]; - foreach (@$noderef) { - s/-hf\d$//; - s/$/-$interf/; - } - } - else { - $noderef = \@nodes; # use the original node list - } - - if ($usenmap) { nmap_pping($noderef); } - else { fping_pping($noderef); } + my $noderef; + if ($interf) { + + # make a copy of the node list and add the interface on + $noderef = [@nodes]; + foreach (@$noderef) { + s/-hf\d$//; + s/$/-$interf/; + } + } + else { + $noderef = \@nodes; # use the original node list + } + + if ($usenmap) { nmap_pping($noderef); } + else { fping_pping($noderef); } } sub fping_pping { - my $nodes = shift; - my $master = xCAT::TableUtils->get_site_Master(); - my $masterip = xCAT::NetworkUtils->getipaddr($master); - if ($masterip =~ /:/) #IPv6, needs fping6 support + my $nodes = shift; + my $master = xCAT::TableUtils->get_site_Master(); + my $masterip = xCAT::NetworkUtils->getipaddr($master); + if ($masterip =~ /:/) #IPv6, needs fping6 support + { + if (!-x '/usr/bin/fping6') { - if (!-x '/usr/bin/fping6') - { - print "fping6 is not availabe for IPv6 ping.\n"; - exit 1; - } - open (FPING, "fping6 ".join(' ',@$nodes). " 2>&1 |") or die("Cannot open fping pipe: $!"); + print "fping6 is not availabe for IPv6 ping.\n"; + exit 1; } - else - { - open (FPING, "fping ".join(' ',@$nodes). " 2>&1 |") or die("Cannot open fping pipe: $!"); + open(FPING, "fping6 " . join(' ', @$nodes) . " 2>&1 |") or die("Cannot open fping pipe: $!"); + } + else + { + open(FPING, "fping " . join(' ', @$nodes) . " 2>&1 |") or die("Cannot open fping pipe: $!"); + } + while () { + if ($_ =~ /is unreachable/) { + s/ is unreachable/: noping/; + } elsif ($_ =~ /is alive/) { + s/ is alive/: ping/; + } elsif ($_ =~ /address not found/) { + s/ address not found/: noping/; } - while () { - if ($_ =~ /is unreachable/) { - s/ is unreachable/: noping/; - } elsif ($_ =~ /is alive/) { - s/ is alive/: ping/; - } elsif ($_ =~ /address not found/) { - s/ address not found/: noping/; - } - print $_; - } + print $_; + } } sub nmap_pping { @@ -179,45 +183,46 @@ sub nmap_pping { my $more_options; my $tcmd; foreach (@$nodes) { - $deadnodes{$_}=1; + $deadnodes{$_} = 1; } - if ( $userid != 0 ) { - $tcmd ="tabdump site|grep nmapoptions|awk -F, '{print $2}'|sed -e 's/\"//g'|awk -F, '{print $1}'"; - $more_options = xCAT::Utils->runcmd($tcmd, -1); + if ($userid != 0) { + $tcmd = "tabdump site|grep nmapoptions|awk -F, '{print $2}'|sed -e 's/\"//g'|awk -F, '{print $1}'"; + $more_options = xCAT::Utils->runcmd($tcmd, -1); } else { + # get additional options from site table @nmap_options = xCAT::TableUtils->get_site_attribute("nmapoptions"); $more_options = $nmap_options[0]; - } - open (FPING, "nmap -PE --system-dns --send-ip -sP $more_options ".join(' ',@$nodes). " 2> /dev/null|") or die("Cannot open nmap pipe: $!"); + } + open(FPING, "nmap -PE --system-dns --send-ip -sP $more_options " . join(' ', @$nodes) . " 2> /dev/null|") or die("Cannot open nmap pipe: $!"); my $node; while () { - if (/Host (.*) \(.*\) appears to be up/) { - $node=$1; - unless ($deadnodes{$node}) { - foreach (keys %deadnodes) { - if ($node =~ /^$_\./) { - $node = $_; - last; - } - } - } - delete $deadnodes{$node}; - print "$node: ping\n" if ($node); - } elsif (/Nmap scan report for ([^ ]*) /) { - $node=$1; - } elsif (/Host is up./) { - unless ($deadnodes{$node}) { - foreach (keys %deadnodes) { - if ($node =~ /^$_\./) { - $node = $_; - last; - } - } - } - delete $deadnodes{$node}; - print "$node: ping\n" if ($node); - } + if (/Host (.*) \(.*\) appears to be up/) { + $node = $1; + unless ($deadnodes{$node}) { + foreach (keys %deadnodes) { + if ($node =~ /^$_\./) { + $node = $_; + last; + } + } + } + delete $deadnodes{$node}; + print "$node: ping\n" if ($node); + } elsif (/Nmap scan report for ([^ ]*) /) { + $node = $1; + } elsif (/Host is up./) { + unless ($deadnodes{$node}) { + foreach (keys %deadnodes) { + if ($node =~ /^$_\./) { + $node = $_; + last; + } + } + } + delete $deadnodes{$node}; + print "$node: ping\n" if ($node); + } } foreach (sort keys %deadnodes) { print "$_: noping\n"; diff --git a/xCAT-client/bin/ppping b/xCAT-client/bin/ppping index 4ad7b21f2..535a9022f 100755 --- a/xCAT-client/bin/ppping +++ b/xCAT-client/bin/ppping @@ -2,7 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html #Note, this ppping still frontends fping. I think it would be possible to write a perl equivalent, but #I've not had the time. Net::Ping shows perl code I could see being adapted for a somewhat -#asynchronous ICMP ping (the tcp syn is interesting, but far too limited, and that is currently the only async +#asynchronous ICMP ping (the tcp syn is interesting, but far too limited, and that is currently the only async #method Net::Ping provides. # This script starts with a noderange from the user, expands it using the @@ -11,8 +11,8 @@ # obtained from the user. It then prints out the result and exits. BEGIN { - # XCATROOT must be set for this script to work - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + # XCATROOT must be set for this script to work + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use strict; use lib "$::XCATROOT/lib/perl"; @@ -22,60 +22,61 @@ use POSIX qw(:signal_h :errno_h :sys_wait_h); use IO::Socket::SSL; use XML::Simple; if ($^O =~ /^linux/i) { - $XML::Simple::PREFERRED_PARSER='XML::Parser'; + $XML::Simple::PREFERRED_PARSER = 'XML::Parser'; } + #use Data::Dumper; use IO::Handle; use IO::Select; use Getopt::Long; my $interface; -my $USAGE="Usage: ppping [-i|--interface interfaces] [-d|--debug] [-V|--verbose] [-q|--quiet] [-s|--serial] noderange +my $USAGE = "Usage: ppping [-i|--interface interfaces] [-d|--debug] [-V|--verbose] [-q|--quiet] [-s|--serial] noderange ppping -h|--help - ppping -v|--version\n"; + ppping -v|--version\n"; # Parse the options require Getopt::Long; -Getopt::Long::Configure ("bundling"); -if(!GetOptions( - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, - 's|serial' => \$::SERIAL, - 'd|debug' => \$::DEBUG, - 'V|verbose' => \$::VERBOSE, - 'H|hierarchical' => \$::HIERARCHY, - 'q|quiet' => \$::QUIET, - 'i|interface=s' => \$interface)) +Getopt::Long::Configure("bundling"); +if (!GetOptions( + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, + 's|serial' => \$::SERIAL, + 'd|debug' => \$::DEBUG, + 'V|verbose' => \$::VERBOSE, + 'H|hierarchical' => \$::HIERARCHY, + 'q|quiet' => \$::QUIET, + 'i|interface=s' => \$interface)) { - print "$USAGE"; - exit 1; + print "$USAGE"; + exit 1; } -if ($::HELP) { print "$USAGE"; exit 0} -if ($::VERSION) {print xCAT::Utils->Version() . "\n"; exit 0} +if ($::HELP) { print "$USAGE"; exit 0 } +if ($::VERSION) { print xCAT::Utils->Version() . "\n"; exit 0 } # A method to prefix and print debug information only if it is wanted. sub debug { - my $debug_text = shift; - if($::DEBUG){ - print("---$debug_text"); - } + my $debug_text = shift; + if ($::DEBUG) { + print("---$debug_text"); + } } -my $xcathost='localhost:3001'; +my $xcathost = 'localhost:3001'; if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; + $xcathost = $ENV{XCATHOST}; } unless (@ARGV) { - print "$USAGE"; - exit 1; + print "$USAGE"; + exit 1; } ## Connect to xcatd to expand a noderange my $noderange = $ARGV[0]; -my @user = getpwuid($>); -my $homedir=$user[7]; +my @user = getpwuid($>); +my $homedir = $user[7]; my %sslargs; if (defined($ENV{'XCATSSLVER'})) { @@ -83,86 +84,89 @@ if (defined($ENV{'XCATSSLVER'})) { } my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=>$homedir."/.xcat/client-cred.pem", - SSL_cert_file=>$homedir."/.xcat/client-cred.pem", - SSL_ca_file => $homedir."/.xcat/ca.pem", - SSL_use_cert => 1, - %sslargs, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - ); + PeerAddr => $xcathost, + SSL_key_file => $homedir . "/.xcat/client-cred.pem", + SSL_cert_file => $homedir . "/.xcat/client-cred.pem", + SSL_ca_file => $homedir . "/.xcat/ca.pem", + SSL_use_cert => 1, + %sslargs, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", +); die "Connection failure: $!\n" unless ($client); my %cmdref = (command => 'noderange', noderange => $noderange); + # Request nodes from xcatd debug("[start] - request nodes from xcatd\n"); $SIG{ALRM} = sub { die "No response getting noderange" }; alarm(15); -print $client XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); +print $client XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); alarm(15); debug("[stop] - request nodes from xcatd\n"); ## Recieve nodes from xcatd and place them in @nodes -my $response=""; -my @nodes=(); +my $response = ""; +my @nodes = (); debug("[start] - recieve nodes from xcatd\n"); while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - my $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + my $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + @nodes = @{ $rsp->{node} }; + } + if ($rsp->{serverdone}) { + last; + } } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - @nodes=@{$rsp->{node}}; - } - if ($rsp->{serverdone}) { - last; - } - } } close($client); debug("[stop] - recieve nodes from xcatd\n"); debug("\@nodes LENGTH:" . scalar @nodes . "\n"); unless (scalar(@nodes)) { - exit 1; + exit 1; } my $children = 0; -my $inputs = new IO::Select; -$SIG{CHLD} = sub { while (waitpid(-1,WNOHANG) > 0) { $children--; } }; +my $inputs = new IO::Select; +$SIG{CHLD} = sub { while (waitpid(-1, WNOHANG) > 0) { $children--; } }; ## Use pping to determine which nodes are reachable -my @reachable_nodes=(); -my @unreachable_nodes=(); +my @reachable_nodes = (); +my @unreachable_nodes = (); debug("[start] - find unreachable nodes\n"); -my $cmd = "$::XCATROOT/bin/pping ".join(',',@nodes). " --noexpand 2>&1"; +my $cmd = "$::XCATROOT/bin/pping " . join(',', @nodes) . " --noexpand 2>&1"; debug("Running '$cmd'\n"); -open (PPING, "$cmd |") or die("Cannot open ppinginternal pipe: $!"); +open(PPING, "$cmd |") or die("Cannot open ppinginternal pipe: $!"); while () { - if ($_ =~ / ping/) { - my @a_tmp=split(':', $_); - push(@reachable_nodes, $a_tmp[0]); - } - elsif ($_ =~ /noping/) { - my @a_tmp=split(':', $_); - push(@unreachable_nodes, $a_tmp[0]); - } - else { print $_; } # probably an error msg, so just echo it + + if ($_ =~ / ping/) { + my @a_tmp = split(':', $_); + push(@reachable_nodes, $a_tmp[0]); + } + elsif ($_ =~ /noping/) { + my @a_tmp = split(':', $_); + push(@unreachable_nodes, $a_tmp[0]); + } + else { print $_; } # probably an error msg, so just echo it } close(PPING); + # this next line seems to always have a non-zero $?, even if pping succeeded... #if ($?) { die "Error in the pping command used to first test the nodes (exit code=" . ($?>>8) . ").\n"; } debug("[stop] - find unreachable nodes\n"); ## Dispose of the unreachable nodes now -foreach(@unreachable_nodes) { - print "$_: noping\n"; +foreach (@unreachable_nodes) { + print "$_: noping\n"; } ## If there are nodes in @reachable nodes, use xdsh to make each reachable @@ -172,57 +176,60 @@ debug("REACHABLE_NODES:@reachable_nodes\n"); if (@reachable_nodes == 0) { exit 1; } -my $allnodes=join(',', @nodes); +my $allnodes = join(',', @nodes); # Note: even if verbose is not set, we still do not want to set the quiet flag because we want # to count the pings that come back, unless they request fully quiet mode. my $quiet = ""; -if($::QUIET) { $quiet = "-q "; } +if ($::QUIET) { $quiet = "-q "; } + # bypass mode for xdsh is not used any more, because it doesn't give any advantage my $bypass = ""; my @interfaces; if ($interface) { @interfaces = split(/,/, $interface); } -else { $interfaces[0] = ''; } +else { $interfaces[0] = ''; } # Possible todo: this loop runs xdsh pping2 for each interface. An optimization could be to send all # the interfaces to pping2 at once. But this would mix up all the ping responses and making it # harder to tell what is going on. foreach my $interf (@interfaces) { - my $i_string = $interf ? "-i $interf " : ''; + my $i_string = $interf ? "-i $interf " : ''; - ## If the serial option was set, pping2 one reachable node at a time. - if ($::SERIAL) { - debug("SERIAL:$::SERIAL\n"); - debug("[start] - xdsh to each reachable node\n"); - foreach(@reachable_nodes) { - my $command = "$::XCATROOT/bin/xdsh $_ $bypass -s -e $::XCATROOT/sbin/pping2 \"$i_string$quiet$allnodes\" 2>&1"; - debug("Running '$command'\n"); - open (PPING2, "$command |") or die("Cannot open xdsh internal pipe: $!"); - # Print out the result - my %numpings; - while () { - output($_, \%numpings, $interf); - } - close(PPING2); + ## If the serial option was set, pping2 one reachable node at a time. + if ($::SERIAL) { + debug("SERIAL:$::SERIAL\n"); + debug("[start] - xdsh to each reachable node\n"); + foreach (@reachable_nodes) { + my $command = "$::XCATROOT/bin/xdsh $_ $bypass -s -e $::XCATROOT/sbin/pping2 \"$i_string$quiet$allnodes\" 2>&1"; + debug("Running '$command'\n"); + open(PPING2, "$command |") or die("Cannot open xdsh internal pipe: $!"); + + # Print out the result + my %numpings; + while () { + output($_, \%numpings, $interf); + } + close(PPING2); + } + debug("[stop] - xdsh to each reachable node\n"); } - debug("[stop] - xdsh to each reachable node\n"); - } - - ## If the serial option was not set, pping2 all the reachable nodes simultaneously. - else { - debug("SERIAL not set.\n"); - my $node_string=join(',', @reachable_nodes); - my $command = "$::XCATROOT/bin/xdsh $node_string $bypass -s -e $::XCATROOT/sbin/pping2 \"$i_string$quiet$allnodes\" 2>&1"; - debug("Running '$command'\n"); - open (PPING2, "$command |") or die("Cannot open xdsh internal pipe: $!"); - # Print out the result - my %numpings; - while () { - output($_, \%numpings, $interf); + + ## If the serial option was not set, pping2 all the reachable nodes simultaneously. + else { + debug("SERIAL not set.\n"); + my $node_string = join(',', @reachable_nodes); + my $command = "$::XCATROOT/bin/xdsh $node_string $bypass -s -e $::XCATROOT/sbin/pping2 \"$i_string$quiet$allnodes\" 2>&1"; + debug("Running '$command'\n"); + open(PPING2, "$command |") or die("Cannot open xdsh internal pipe: $!"); + + # Print out the result + my %numpings; + while () { + output($_, \%numpings, $interf); + } + close(PPING2); } - close(PPING2); - } } debug("[stop] - deal with reachable nodes\n"); @@ -230,30 +237,31 @@ exit 0; # Process the output if the xdsh pping2 commands sub output { - my $line = shift; - my $numpings = shift; - my $interface = shift; - if ($line =~ /^\s*$/) { return; } # xdsh had a habit of adding an extra blank line in streaming mode - # In verbose mode we just echo everything. In quiet mode, the only thing that will come back - # from pping2 are the nopings, so we echo everything in that case too. - if ($::VERBOSE || $::QUIET) { print "$line"; return; } - - # This is the default case in which pping2 will return both pings and nopings. - # We want to count the pings and display the nopings. - my $node; - if ( ($node) = $line =~ /^(\S+):.+:\s+ping$/) { - if (!($numpings->{$node}==-1)) { - $numpings->{$node}++; - # If we got pings for all the nodes then print success - if ($numpings->{$node} >= scalar(@nodes)) { - my $istr = $interface ? " on interface $interface" : ''; - print "$node: pinged all nodes successfully$istr\n"; - $numpings->{$node} = -1; - } - } - } - else { - print "$line"; - if ( ($node) = $line =~ /^(\S+?):/) { $numpings->{$node} = -1; } # something beside ping, stop counting - } + my $line = shift; + my $numpings = shift; + my $interface = shift; + if ($line =~ /^\s*$/) { return; } # xdsh had a habit of adding an extra blank line in streaming mode + # In verbose mode we just echo everything. In quiet mode, the only thing that will come back + # from pping2 are the nopings, so we echo everything in that case too. + if ($::VERBOSE || $::QUIET) { print "$line"; return; } + + # This is the default case in which pping2 will return both pings and nopings. + # We want to count the pings and display the nopings. + my $node; + if (($node) = $line =~ /^(\S+):.+:\s+ping$/) { + if (!($numpings->{$node} == -1)) { + $numpings->{$node}++; + + # If we got pings for all the nodes then print success + if ($numpings->{$node} >= scalar(@nodes)) { + my $istr = $interface ? " on interface $interface" : ''; + print "$node: pinged all nodes successfully$istr\n"; + $numpings->{$node} = -1; + } + } + } + else { + print "$line"; + if (($node) = $line =~ /^(\S+?):/) { $numpings->{$node} = -1; } # something beside ping, stop counting + } } diff --git a/xCAT-client/bin/prsync b/xCAT-client/bin/prsync index 049de4b7e..ab0c1a898 100755 --- a/xCAT-client/bin/prsync +++ b/xCAT-client/bin/prsync @@ -7,7 +7,8 @@ BEGIN use lib "$::XCATROOT/lib/perl"; use IO::Socket::SSL; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; + #use Data::Dumper; use IO::Handle; use IO::Select; @@ -23,25 +24,25 @@ Getopt::Long::Configure("no_gnu_compat"); Getopt::Long::Configure("bundling"); my %nodehdl; -my $xcathost='localhost:3001'; +my $xcathost = 'localhost:3001'; if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; + $xcathost = $ENV{XCATHOST}; } if (!(@ARGV)) { - &usage; - exit(1); - + &usage; + exit(1); + } if (!GetOptions( - 'h|help' => \$help, - 'v|version' => \$version, - 'o|options=s' => \$opts, - 'f|fanout=s' => \$fanout, - 'i|interface=s' => \$interface)) + 'h|help' => \$help, + 'v|version' => \$version, + 'o|options=s' => \$opts, + 'f|fanout=s' => \$fanout, + 'i|interface=s' => \$interface)) { - &usage; - exit(1); + &usage; + exit(1); } if ($help) { &usage; @@ -52,125 +53,132 @@ if ($version) { print "$version \n"; exit(0); } -my $pshmaxp = 64; +my $pshmaxp = 64; + # determine fanout -if ($ENV{XCATPSHFANOUT}) { - $pshmaxp=$ENV{XCATPSHFANOUT}; +if ($ENV{XCATPSHFANOUT}) { + $pshmaxp = $ENV{XCATPSHFANOUT}; } -if ($fanout) { # see if they overroad the fanout from the command line - $pshmaxp=$fanout; +if ($fanout) { # see if they overroad the fanout from the command line + $pshmaxp = $fanout; } -(my $noderange,my $destloc) = split(/:/,$ARGV[1]); -my @user = getpwuid($>); -my $homedir=$user[7]; +(my $noderange, my $destloc) = split(/:/, $ARGV[1]); +my @user = getpwuid($>); +my $homedir = $user[7]; my %sslargs; if (defined($ENV{'XCATSSLVER'})) { $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; } my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=>$homedir."/.xcat/client-cred.pem", - SSL_cert_file=>$homedir."/.xcat/client-cred.pem", - SSL_ca_file => $homedir."/.xcat/ca.pem", - SSL_use_cert => 1, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - %sslargs, - ); + PeerAddr => $xcathost, + SSL_key_file => $homedir . "/.xcat/client-cred.pem", + SSL_cert_file => $homedir . "/.xcat/client-cred.pem", + SSL_ca_file => $homedir . "/.xcat/ca.pem", + SSL_use_cert => 1, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + %sslargs, +); die "Connection failure: $!\n" unless ($client); my %cmdref = (command => 'noderange', noderange => $noderange); $SIG{ALRM} = sub { die "No response getting noderange" }; alarm(15); -print $client XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); +print $client XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); alarm(15); -my $response=""; -my @nodes=(); +my $response = ""; +my @nodes = (); + while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + @nodes = @{ $rsp->{node} }; + } + if ($rsp->{serverdone}) { + last; + } } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - @nodes=@{$rsp->{node}}; - } - if ($rsp->{serverdone}) { - last; - } - } } close($client); my $children = 0; -my $inputs = new IO::Select; +my $inputs = new IO::Select; $SIG{CHLD} = \&reaper; + sub reaper { - while (($pid = waitpid(-1,WNOHANG)) > 0) { - $children--; - } - if ($children and $pid == -1) { #for whatever reason, rsync processes slip by frequently - $children = 0; - } - $SIG{CHLD} = \&reaper; + while (($pid = waitpid(-1, WNOHANG)) > 0) { + $children--; + } + if ($children and $pid == -1) { #for whatever reason, rsync processes slip by frequently + $children = 0; + } + $SIG{CHLD} = \&reaper; } if ($interface) { - foreach (@nodes) { - s/$/-$interface/; - } + foreach (@nodes) { + s/$/-$interface/; + } } foreach (@nodes) { - my $node=$_; - while ($children > $pshmaxp) { processoutput($inputs); } - my $child; - $children++; - scpnode(\$child,$node,@ARGV[0],$destloc,$opts); - $inputs->add($child); - $nodehdl{$child} = $node; + my $node = $_; + while ($children > $pshmaxp) { processoutput($inputs); } + my $child; + $children++; + scpnode(\$child, $node, @ARGV[0], $destloc, $opts); + $inputs->add($child); + $nodehdl{$child} = $node; } while ($inputs->count and $children) { - processoutput($inputs); + processoutput($inputs); } -while (processoutput($inputs)) {}; +while (processoutput($inputs)) { } wait; exit(0); -sub processoutput { #This way, one arbiter handles output, no interrupting - my $inputs = shift; - my @readyins = $inputs->can_read(1); - my $rc = @readyins; - my $readyh; - foreach $readyh (@readyins) { - my $line = <$readyh>; - unless ($line) { - $inputs->remove($readyh); - print $nodehdl{$readyh}.": done\n"; - close($readyh); - next; +sub processoutput { #This way, one arbiter handles output, no interrupting + my $inputs = shift; + my @readyins = $inputs->can_read(1); + my $rc = @readyins; + my $readyh; + foreach $readyh (@readyins) { + my $line = <$readyh>; + unless ($line) { + $inputs->remove($readyh); + print $nodehdl{$readyh} . ": done\n"; + close($readyh); + next; + } + chomp($line); + print $nodehdl{$readyh} . ": " . $line . "\n"; } - chomp($line); - print $nodehdl{$readyh}.": ".$line."\n"; - } - #yield; - return $rc; + + #yield; + return $rc; } + sub scpnode { - my $out = shift; - my $node = shift; - my $in; - #my $args = join(" ",@_); - my $file = shift; - my $dest = shift; - my $opts = shift; - my $cmd="rsync -az$opts $file $node:$dest 2>&1 |"; - open($$out,"rsync -az$opts $file $node:$dest 2>&1 |"); + my $out = shift; + my $node = shift; + my $in; + + #my $args = join(" ",@_); + my $file = shift; + my $dest = shift; + my $opts = shift; + my $cmd = "rsync -az$opts $file $node:$dest 2>&1 |"; + open($$out, "rsync -az$opts $file $node:$dest 2>&1 |"); } + sub usage { print "Usage: prsync filename [filename ...] noderange:destinationdirectory\n"; print " prsync [-f fanout] [-o rsync options] [filename filename ...] [directory directory ...]"; diff --git a/xCAT-client/bin/pscp b/xCAT-client/bin/pscp index 60b33fa2e..245f9598b 100755 --- a/xCAT-client/bin/pscp +++ b/xCAT-client/bin/pscp @@ -8,7 +8,8 @@ use lib "$::XCATROOT/lib/perl"; use xCAT::Utils; use IO::Socket::SSL; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; + #use Data::Dumper; use IO::Handle; use IO::Select; @@ -17,31 +18,31 @@ use Getopt::Long qw(:config pass_through require_order); use POSIX qw(:signal_h :errno_h :sys_wait_h); my $interface; GetOptions( - "interface=s" => \$interface, - "f|fanout=s" => \$fanout, - "h|help" => \$usage, - "v|version" => \$::VERSION, - ); + "interface=s" => \$interface, + "f|fanout=s" => \$fanout, + "h|help" => \$usage, + "v|version" => \$::VERSION, +); my %nodehdl; -my $xcathost='localhost:3001'; -if ($::VERSION) {print xCAT::Utils->Version() . "\n"; exit 0} +my $xcathost = 'localhost:3001'; +if ($::VERSION) { print xCAT::Utils->Version() . "\n"; exit 0 } if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; + $xcathost = $ENV{XCATHOST}; } sub usage { - print $_[0]; - print "Usage: pscp [ -f fanout] [-i ] [SCP OPTIONS...] FILE... :\n"; - exit 1; + print $_[0]; + print "Usage: pscp [ -f fanout] [-i ] [SCP OPTIONS...] FILE... :\n"; + exit 1; } -my $pshmaxp = 64; -if ($ENV{XCATPSHFANOUT}) { - $pshmaxp=$ENV{XCATPSHFANOUT}; +my $pshmaxp = 64; +if ($ENV{XCATPSHFANOUT}) { + $pshmaxp = $ENV{XCATPSHFANOUT}; } -if ($fanout) { # see if they overroad the fanout from the command line - $pshmaxp=$fanout; +if ($fanout) { # see if they overroad the fanout from the command line + $pshmaxp = $fanout; } @@ -51,113 +52,118 @@ my $dest = shift; my @scpargs; while (@ARGV) { - push @scpargs, $dest; - $dest = shift; + push @scpargs, $dest; + $dest = shift; } my $noderange, $destloc; if ($dest =~ /:/) { ($noderange, $destloc) = split(/:/, $dest); } -else { usage("No node range specified\n\n"); } +else { usage("No node range specified\n\n"); } -my @user = getpwuid($>); -my $homedir=$user[7]; +my @user = getpwuid($>); +my $homedir = $user[7]; my %sslargs; if (defined($ENV{'XCATSSLVER'})) { $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; } my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=>$homedir."/.xcat/client-cred.pem", - SSL_cert_file=>$homedir."/.xcat/client-cred.pem", - SSL_ca_file => $homedir."/.xcat/ca.pem", - SSL_use_cert => 1, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - %sslargs, - ); + PeerAddr => $xcathost, + SSL_key_file => $homedir . "/.xcat/client-cred.pem", + SSL_cert_file => $homedir . "/.xcat/client-cred.pem", + SSL_ca_file => $homedir . "/.xcat/ca.pem", + SSL_use_cert => 1, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + %sslargs, +); die "Connection failure: $!\n" unless ($client); my %cmdref = (command => 'noderange', noderange => $noderange); $SIG{ALRM} = sub { die "No response getting noderange" }; alarm(15); -print $client XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); +print $client XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); alarm(15); -my $response=""; -my @nodes=(); +my $response = ""; +my @nodes = (); + while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + @nodes = @{ $rsp->{node} }; + } + if ($rsp->{serverdone}) { + last; + } } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - @nodes=@{$rsp->{node}}; - } - if ($rsp->{serverdone}) { - last; - } - } } close($client); my $children = 0; -my $inputs = new IO::Select; -$SIG{CHLD} = sub { while (waitpid(-1,WNOHANG) > 0) { $children--; } }; +my $inputs = new IO::Select; +$SIG{CHLD} = sub { while (waitpid(-1, WNOHANG) > 0) { $children--; } }; if ($interface) { - foreach (@nodes) { - s/$/-$interface/; - } + foreach (@nodes) { + s/$/-$interface/; + } } foreach (@nodes) { - my $node=$_; - while ($children > $pshmaxp) { processoutput($inputs); } - $children++; - #scpnode(\$child,$node,@ARGV[0],$destloc); - scpnode($inputs,\%nodehdl,$node,\@scpargs,$destloc); + my $node = $_; + while ($children > $pshmaxp) { processoutput($inputs); } + $children++; + + #scpnode(\$child,$node,@ARGV[0],$destloc); + scpnode($inputs, \%nodehdl, $node, \@scpargs, $destloc); } while ($inputs->count and $children) { - processoutput($inputs); + processoutput($inputs); } -while (processoutput($inputs)) {}; +while (processoutput($inputs)) { } wait; exit(0); -sub processoutput { #This way, one arbiter handles output, no interrupting - my $inputs = shift; - my @readyins = $inputs->can_read(1); - my $rc = @readyins; - my $readyh; - foreach $readyh (@readyins) { - my $line = <$readyh>; - unless ($line) { - $inputs->remove($readyh); - print $nodehdl{$readyh}.": done\n"; - close($readyh); - next; +sub processoutput { #This way, one arbiter handles output, no interrupting + my $inputs = shift; + my @readyins = $inputs->can_read(1); + my $rc = @readyins; + my $readyh; + foreach $readyh (@readyins) { + my $line = <$readyh>; + unless ($line) { + $inputs->remove($readyh); + print $nodehdl{$readyh} . ": done\n"; + close($readyh); + next; + } + chomp($line); + print $nodehdl{$readyh} . ": " . $line . "\n"; } - chomp($line); - print $nodehdl{$readyh}.": ".$line."\n"; - } - #yield; - return $rc; + + #yield; + return $rc; } + sub scpnode { - my $inputs = shift; - my $nodehdl = shift; - my $node = shift; - my $in; - #my $args = join(" ",@_); - #my $file = shift; - my $scpargsr = shift; - my @scpargs = @{$scpargsr}; - my $dest = shift; - my $child; - open($child, "scp -o BatchMode=yes @scpargs $node:$dest 2>&1 |"); - $inputs->add($child); - $nodehdl->{$child} = $node; + my $inputs = shift; + my $nodehdl = shift; + my $node = shift; + my $in; + + #my $args = join(" ",@_); + #my $file = shift; + my $scpargsr = shift; + my @scpargs = @{$scpargsr}; + my $dest = shift; + my $child; + open($child, "scp -o BatchMode=yes @scpargs $node:$dest 2>&1 |"); + $inputs->add($child); + $nodehdl->{$child} = $node; } # vim: set et sw=2 ts=2 sts=2: diff --git a/xCAT-client/bin/psh b/xCAT-client/bin/psh index 03f53a7e2..2290c625e 100755 --- a/xCAT-client/bin/psh +++ b/xCAT-client/bin/psh @@ -3,14 +3,15 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } close(STDIN); -open(STDIN,"<","/dev/null"); +open(STDIN, "<", "/dev/null"); use lib "$::XCATROOT/lib/perl"; use IO::Socket::SSL; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; + #use Data::Dumper; use xCAT::Utils; use IO::Handle; @@ -21,198 +22,202 @@ use Thread qw(yield); my $interface; my $username; my $help; -my $timeout=0; +my $timeout = 0; Getopt::Long::Configure("require_order"); Getopt::Long::Configure("no_pass_through"); + if (!GetOptions( - "i|interface=s" => \$interface, - 'l|loginname=s' => \$username, - 't|timeout=s' => \$timeout, - 'f|fanout=s' => \$fanout, - "nonodecheck" => \$::NONODECHECK, #does not check the noderange, in this case, noderange need to be a list of nodes. - 'h|help' => \$help, - "v|version" => \$::VERSION, - ) || scalar(@ARGV)<2 ) { - if ($::VERSION) {print xCAT::Utils->Version() . "\n"; exit 0} - if ($help) { - print "Usage: psh [-i ] [-l ] [-f ] [--nonodecheck] [-t ] \n"; - exit; - } + "i|interface=s" => \$interface, + 'l|loginname=s' => \$username, + 't|timeout=s' => \$timeout, + 'f|fanout=s' => \$fanout, + "nonodecheck" => \$::NONODECHECK, #does not check the noderange, in this case, noderange need to be a list of nodes. + 'h|help' => \$help, + "v|version" => \$::VERSION, + ) || scalar(@ARGV) < 2) { + if ($::VERSION) { print xCAT::Utils->Version() . "\n"; exit 0 } + if ($help) { + print "Usage: psh [-i ] [-l ] [-f ] [--nonodecheck] [-t ] \n"; + exit; + } } my %nodehdl; -my $xcathost='localhost:3001'; -my $pshmaxp = 64; +my $xcathost = 'localhost:3001'; +my $pshmaxp = 64; if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; + $xcathost = $ENV{XCATHOST}; } -if ($ENV{XCATPSHFANOUT}) { - $pshmaxp=$ENV{XCATPSHFANOUT}; +if ($ENV{XCATPSHFANOUT}) { + $pshmaxp = $ENV{XCATPSHFANOUT}; } -if ($fanout) { # see if they overroad the fanout from the command line - $pshmaxp=$fanout; +if ($fanout) { # see if they overroad the fanout from the command line + $pshmaxp = $fanout; } my $noderange = $ARGV[0]; -my @nodes=(); +my @nodes = (); if ($::NONODECHECK) { - @nodes=split(/,/, $noderange); + @nodes = split(/,/, $noderange); } else { - my @user = getpwuid($>); - my $homedir=$user[7]; - my %sslargs; - if (defined($ENV{'XCATSSLVER'})) { - $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; - } - - my $client = IO::Socket::SSL->new( - PeerAddr=>$xcathost, - SSL_key_file=>$homedir."/.xcat/client-cred.pem", - SSL_cert_file=>$homedir."/.xcat/client-cred.pem", - SSL_ca_file => $homedir."/.xcat/ca.pem", - SSL_use_cert => 1, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_verifycn_scheme => "none", - %sslargs, - ); - die "Connection failure: $!\n" unless ($client); - my %cmdref = (command => 'noderange', noderange => $noderange); - $SIG{ALRM} = sub { die "No response getting noderange" }; - alarm(15); - print $client XMLout(\%cmdref,RootName=>'xcatrequest', NoAttr=>1, KeyAttr => []); - alarm(15); - my $response=""; - while (<$client>) { - alarm(0); - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - $rsp=XMLin($response, ForceArray => ['node']); - $response=''; - if ($rsp->{warning}) { - printf "Warning: ".$rsp->{warning}."\n"; - } - if ($rsp->{error}) { - die ("ERROR: ".$rsp->{error}."\n"); - } elsif ($rsp->{node}) { - @nodes=@{$rsp->{node}}; - } - if ($rsp->{serverdone}) { - last; - } + my @user = getpwuid($>); + my $homedir = $user[7]; + my %sslargs; + if (defined($ENV{'XCATSSLVER'})) { + $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; } - } - close($client); + + my $client = IO::Socket::SSL->new( + PeerAddr => $xcathost, + SSL_key_file => $homedir . "/.xcat/client-cred.pem", + SSL_cert_file => $homedir . "/.xcat/client-cred.pem", + SSL_ca_file => $homedir . "/.xcat/ca.pem", + SSL_use_cert => 1, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + %sslargs, + ); + die "Connection failure: $!\n" unless ($client); + my %cmdref = (command => 'noderange', noderange => $noderange); + $SIG{ALRM} = sub { die "No response getting noderange" }; + alarm(15); + print $client XMLout(\%cmdref, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); + alarm(15); + my $response = ""; + + while (<$client>) { + alarm(0); + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + $rsp = XMLin($response, ForceArray => ['node']); + $response = ''; + if ($rsp->{warning}) { + printf "Warning: " . $rsp->{warning} . "\n"; + } + if ($rsp->{error}) { + die("ERROR: " . $rsp->{error} . "\n"); + } elsif ($rsp->{node}) { + @nodes = @{ $rsp->{node} }; + } + if ($rsp->{serverdone}) { + last; + } + } + } + close($client); } my $children = 0; -my $inputs = new IO::Select; -my %pids; # pid => node -my %exitcodes; # Keep a list of children with known exit codes +my $inputs = new IO::Select; +my %pids; # pid => node +my %exitcodes; # Keep a list of children with known exit codes my %foundcodes; if ($interface) { - foreach (@nodes) { - s/$/-$interface/; - } -} -local $SIG{ALRM}= sub { - my @proclist = `ps -ef`; - my %ownedpids; - foreach (@proclist) { - m/\S+\s+(\S+)\s+(\S+)/; - $ownedpids{$2}=$1; #only recall one child per parent - } - foreach my $pid (keys %pids) { - my $node = $pids{$pid}; - unless (defined $exitcodes{$node}) { - print stderr "$node: timeout exceeded\n"; - if ($ownedpids{$pid}) { - kill 15,$ownedpids{$pid}; - } else { - kill 15,$pid; - } + foreach (@nodes) { + s/$/-$interface/; + } +} +local $SIG{ALRM} = sub { + my @proclist = `ps -ef`; + my %ownedpids; + foreach (@proclist) { + m/\S+\s+(\S+)\s+(\S+)/; + $ownedpids{$2} = $1; #only recall one child per parent + } + foreach my $pid (keys %pids) { + my $node = $pids{$pid}; + unless (defined $exitcodes{$node}) { + print stderr "$node: timeout exceeded\n"; + if ($ownedpids{$pid}) { + kill 15, $ownedpids{$pid}; + } else { + kill 15, $pid; + } + } } - } }; if ($timeout) { alarm($timeout); } foreach (@nodes) { - my $node=$_; - while ($children >= $pshmaxp) { processoutput($inputs); } - $children++; - sshnode($inputs,\%nodehdl,$node,$username,@ARGV[1 .. $#ARGV]); + my $node = $_; + while ($children >= $pshmaxp) { processoutput($inputs); } + $children++; + sshnode($inputs, \%nodehdl, $node, $username, @ARGV[ 1 .. $#ARGV ]); } while ($inputs->count) { - processoutput($inputs); + processoutput($inputs); } -while (processoutput($inputs)) {}; +while (processoutput($inputs)) { } while (wait != -1) { - yield; + yield; } -my $exitcode=0; +my $exitcode = 0; foreach (values %pids) { - my $possible_codes = join ",",keys %foundcodes; + my $possible_codes = join ",", keys %foundcodes; unless (defined $exitcodes{$_}) { print stderr "$_: *** psh missed exit code, probably one of the following: $possible_codes\n"; } } foreach (keys %exitcodes) { if ($exitcodes{$_}) { - print stderr "$_: *** ssh exited with error code ".$exitcodes{$_}.".\n"; + print stderr "$_: *** ssh exited with error code " . $exitcodes{$_} . ".\n"; $exitcode++; } } -if ($exitcode) { #Exit code reflects number of failed nodes - $exitcode=$exitcode%256; #keep from overflowing valid values +if ($exitcode) { #Exit code reflects number of failed nodes + $exitcode = $exitcode % 256; #keep from overflowing valid values unless ($exitcode) { #if number of failed nodes happened to be evenly divisible by 256, make it non-zero again $exitcode++; } } exit($exitcode); -sub processoutput { #This way, one arbiter handles output, no interrupting - my $inputs = shift; - my @readyins = $inputs->can_read(1); - my $rc = @readyins; - my $readyh; - foreach $readyh (@readyins) { - my $cursel = new IO::Select; - $cursel->add($readyh); - while ($cursel->can_read(0)) { - my $line = <$readyh>; - unless ($line) { - $inputs->remove($readyh); - close($readyh); - $exitcodes{$nodehdl{$readyh}} = $? >> 8; - $children--; - next; - } - chomp($line); - print $nodehdl{$readyh}.": ".$line."\n"; +sub processoutput { #This way, one arbiter handles output, no interrupting + my $inputs = shift; + my @readyins = $inputs->can_read(1); + my $rc = @readyins; + my $readyh; + foreach $readyh (@readyins) { + my $cursel = new IO::Select; + $cursel->add($readyh); + while ($cursel->can_read(0)) { + my $line = <$readyh>; + unless ($line) { + $inputs->remove($readyh); + close($readyh); + $exitcodes{ $nodehdl{$readyh} } = $? >> 8; + $children--; + next; + } + chomp($line); + print $nodehdl{$readyh} . ": " . $line . "\n"; + } } - } - IO::Handle::flush(stdout); - yield; #Explicitly give all children a chance to refill any buffers - return $rc; + IO::Handle::flush(stdout); + yield; #Explicitly give all children a chance to refill any buffers + return $rc; } + sub sshnode { - my $inputs = shift; - my $nodehdl = shift; - my $node = shift; - my $username = shift; - my $out; - if (length($username)) { $username = "-l $username"; } - my $in; - my $args = join(" ",@_); - #print "ssh -o BatchMode=yes $username $node " . "e($args) . " 2>&1 |\n"; - my $pid = open($out,"ssh -o BatchMode=yes $username $node " . "e($args) . " 2>&1 |"); - $inputs->add($out); - $nodehdl->{$out} = $node; - $pids{$pid} = $node; + my $inputs = shift; + my $nodehdl = shift; + my $node = shift; + my $username = shift; + my $out; + if (length($username)) { $username = "-l $username"; } + my $in; + my $args = join(" ", @_); + + #print "ssh -o BatchMode=yes $username $node " . "e($args) . " 2>&1 |\n"; + my $pid = open($out, "ssh -o BatchMode=yes $username $node " . "e($args) . " 2>&1 |"); + $inputs->add($out); + $nodehdl->{$out} = $node; + $pids{$pid} = $node; } sub quote { - my $str = shift; + my $str = shift; # if the value has imbedded double quotes, use single quotes. If it also has # single quotes, escape the double quotes. diff --git a/xCAT-client/bin/rinstall b/xCAT-client/bin/rinstall index 48ce9b1a1..9d989a2e7 100755 --- a/xCAT-client/bin/rinstall +++ b/xCAT-client/bin/rinstall @@ -1,7 +1,7 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html -# Used as a convience command combined of [nodech]-nodeset-rsetboot-rpower-[rcons/wcons] +# Used as a convience command combined of [nodech]-nodeset-rsetboot-rpower-[rcons/wcons] # to make ease of node OS provision # This is the client front-end to rinstall/winstall commands @@ -10,9 +10,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; @@ -28,60 +28,65 @@ use strict; my $bname = basename($0); my $cmdref; $cmdref->{command}->[0] = $bname; -$cmdref->{cwd}->[0] = cwd(); +$cmdref->{cwd}->[0] = cwd(); + # allows our plugins to get the stdin of the cmd that invoked the plugin my $data; -if ( (($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}) ) +if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'})) { - my $rin=""; + my $rin = ""; my $rout; - vec($rin,fileno(STDIN),1)=1; - my $nfound=select($rout=$rin,"","",1); + vec($rin, fileno(STDIN), 1) = 1; + my $nfound = select($rout = $rin, "", "", 1); if ($nfound) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } else { if (-p STDIN) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } my $arg; my @tmpargv = @ARGV; + # first -$arg=shift(@ARGV); +$arg = shift(@ARGV); + # first 1st non-hyphen arg is the noderange while ($arg =~ /^-/) { - push (@{$cmdref->{arg}}, $arg); - $arg=shift(@ARGV); + push(@{ $cmdref->{arg} }, $arg); + $arg = shift(@ARGV); } -$cmdref->{noderange}->[0]=$arg; -push (@{$cmdref->{arg}}, @ARGV); +$cmdref->{noderange}->[0] = $arg; +push(@{ $cmdref->{arg} }, @ARGV); -my $noderange=$cmdref->{noderange}->[0]; # save the noderange +my $noderange = $cmdref->{noderange}->[0]; # save the noderange # ok call Client to run the plugin rinstall.pm -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); -if ($xCAT::Client::EXITCODE == 0) # no errors +if ($xCAT::Client::EXITCODE == 0) # no errors { - my $startconsole=$cmdref->{startconsole}->[0]; - # if startconsole requested ( -c flag) for rinstall always for winstall - # This is set in the rinstall plugin - if ($startconsole == 1) { - if (basename($0) =~ /rinstall/) { + my $startconsole = $cmdref->{startconsole}->[0]; - exec("rcons $noderange"); - } - elsif (basename($0) =~ /winstall/) { - # winstall can commence a wcons command to the noderange for monitoring the provision cycle + # if startconsole requested ( -c flag) for rinstall always for winstall + # This is set in the rinstall plugin + if ($startconsole == 1) { + if (basename($0) =~ /rinstall/) { - exec("wcons $noderange"); + exec("rcons $noderange"); + } + elsif (basename($0) =~ /winstall/) { + + # winstall can commence a wcons command to the noderange for monitoring the provision cycle + + exec("wcons $noderange"); + } } - } } exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/bin/updatenode b/xCAT-client/bin/updatenode index 5ce3fbe83..17e52db8e 100755 --- a/xCAT-client/bin/updatenode +++ b/xCAT-client/bin/updatenode @@ -22,26 +22,27 @@ sub updatenode_usage my $bname = basename($0); my $cmdref; $cmdref->{command}->[0] = $bname; -$cmdref->{cwd}->[0] = cwd(); +$cmdref->{cwd}->[0] = cwd(); my $data; + # allows our plugins to get the stdin of the cmd that invoked the plugin -if ( (($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}) ) +if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'})) { - my $rin=""; + my $rin = ""; my $rout; - vec($rin,fileno(STDIN),1)=1; - my $nfound=select($rout=$rin,"","",1); + vec($rin, fileno(STDIN), 1) = 1; + my $nfound = select($rout = $rin, "", "", 1); if ($nfound) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } else { if (-p STDIN) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } @@ -50,56 +51,58 @@ Getopt::Long::Configure("posix_default"); Getopt::Long::Configure("no_gnu_compat"); Getopt::Long::Configure("bundling"); -my $tmp=" ".join(' ', @ARGV); +my $tmp = " " . join(' ', @ARGV); if (!($tmp =~ / (--help|-h|-v|--version)/)) { - my $arg=shift(@ARGV); - # Set the noderange - if ($arg !~ /^-/) { - my @tempnr = (); - foreach my $nr (split(/,/, $arg)) { - if ($nr =~ /^\^(.*)$/) { - my $nrf = $1; - if ($nrf !~ /^\//) { #relative path - $nrf = Cwd::abs_path($nrf); + my $arg = shift(@ARGV); + + # Set the noderange + if ($arg !~ /^-/) { + my @tempnr = (); + foreach my $nr (split(/,/, $arg)) { + if ($nr =~ /^\^(.*)$/) { + my $nrf = $1; + if ($nrf !~ /^\//) { #relative path + $nrf = Cwd::abs_path($nrf); + } + $nrf = "\^" . $nrf; + push @tempnr, $nrf; + } else { + push @tempnr, $nr; + } } - $nrf = "\^" . $nrf; - push @tempnr, $nrf; - } else { - push @tempnr, $nr; - } + $arg = join(',', @tempnr); + $cmdref->{noderange}->[0] = $arg; + } else { + &updatenode_usage(); + print "The noderange should be the first argument.\n"; + exit 1; } - $arg = join(',',@tempnr); - $cmdref->{noderange}->[0]=$arg; - } else { - &updatenode_usage(); - print "The noderange should be the first argument.\n"; - exit 1; - } } -push (@{$cmdref->{arg}}, @ARGV); +push(@{ $cmdref->{arg} }, @ARGV); + # check the syntax -my ($ALLSW,$CMDLINE,$ALTSRC,$HELP,$VERSION,$VERBOSE,$FILESYNC,$GENMYPOST,$USER,$SNFILESYNC,$SWMAINTENANCE,$SETSERVER,$RERUNPS,$SECURITY,$OS,$fanout,$timeout,$NOVERIFY); +my ($ALLSW, $CMDLINE, $ALTSRC, $HELP, $VERSION, $VERBOSE, $FILESYNC, $GENMYPOST, $USER, $SNFILESYNC, $SWMAINTENANCE, $SETSERVER, $RERUNPS, $SECURITY, $OS, $fanout, $timeout, $NOVERIFY); if ( !GetOptions( - 'A|updateallsw' => \$ALLSW, - 'c|cmdlineonly' => \$CMDLINE, - 'd=s' => \$ALTSRC, - 'h|help' => \$HELP, - 'v|version' => \$VERSION, - 'V|verbose' => \$VERBOSE, - 'F|sync' => \$FILESYNC, - 'g|genmypost' => \$GENMYPOST, - 'f|snsync' => \$SNFILESYNC, - 'l|user=s' => \$USER, - 'S|sw' => \$SWMAINTENANCE, - 's|sn' => \$SETSERVER, - 'P|scripts:s' => \$RERUNPS, - 'k|security' => \$SECURITY, - 'o|os=s' => \$OS, - 'fanout=i' => \$fanout, - 't|timetout=i' => \$timeout, - 'n|noverify' => \$NOVERIFY, + 'A|updateallsw' => \$ALLSW, + 'c|cmdlineonly' => \$CMDLINE, + 'd=s' => \$ALTSRC, + 'h|help' => \$HELP, + 'v|version' => \$VERSION, + 'V|verbose' => \$VERBOSE, + 'F|sync' => \$FILESYNC, + 'g|genmypost' => \$GENMYPOST, + 'f|snsync' => \$SNFILESYNC, + 'l|user=s' => \$USER, + 'S|sw' => \$SWMAINTENANCE, + 's|sn' => \$SETSERVER, + 'P|scripts:s' => \$RERUNPS, + 'k|security' => \$SECURITY, + 'o|os=s' => \$OS, + 'fanout=i' => \$fanout, + 't|timetout=i' => \$timeout, + 'n|noverify' => \$NOVERIFY, ) ) { &updatenode_usage(); @@ -131,29 +134,29 @@ if ($VERSION) print "$version\n"; exit 0; } -if (($FILESYNC) && ($SNFILESYNC)){ # only one +if (($FILESYNC) && ($SNFILESYNC)) { # only one my $msg = "Choose either -f to sync the service nodes, or -F to sync the nodes not both."; xCAT::MsgUtils->message("E", $msg); exit 1; -} -if (($SECURITY) && (($SWMAINTENANCE) || defined($RERUNPS) || ($FILESYNC) || ($SNFILESYNC))){ +} +if (($SECURITY) && (($SWMAINTENANCE) || defined($RERUNPS) || ($FILESYNC) || ($SNFILESYNC))) { my $msg = "If you use the -k flag, you cannot specify the -S,-P,-f or -F flags."; xCAT::MsgUtils->message("E", $msg); exit 1; } -if ($SNFILESYNC && ($SWMAINTENANCE || defined($RERUNPS) || $SECURITY || $FILESYNC)){ +if ($SNFILESYNC && ($SWMAINTENANCE || defined($RERUNPS) || $SECURITY || $FILESYNC)) { my $msg = "If you specify the -f flag you must not specify either the -S or -k or -P or -F flags"; xCAT::MsgUtils->message("E", $msg); exit 1; } -# determine who is running the command on the client and who we will run as +# determine who is running the command on the client and who we will run as # on the node my $current_userid = getpwuid($>); $ENV{DSH_FROM_USERID} = $current_userid; my $to_userid; -if ($USER) # entered -l +if ($USER) # entered -l { $to_userid = $USER; } @@ -167,11 +170,11 @@ $ENV{DSH_TO_USERID} = $to_userid; if ($SECURITY) { my $msg; if (!($ENV{'DSH_REMOTE_PASSWORD'})) - { # if not already set - # prompt for the password for the userid on the node that will be setup + { # if not already set + # prompt for the password for the userid on the node that will be setup my $userpw; $msg = - "The ssh keys will be updated for '$to_userid' on the node(s).\nPassword:"; +"The ssh keys will be updated for '$to_userid' on the node(s).\nPassword:"; xCAT::MsgUtils->message("I", $msg); system("stty -echo"); # turn off keyboard chop($userpw = ); @@ -193,9 +196,9 @@ if ($SECURITY) { foreach (keys %ENV) { if (/^DSH_/ || /^XCAT/) { - push @{$cmdref->{environment}}, "$_=$ENV{$_}"; + push @{ $cmdref->{environment} }, "$_=$ENV{$_}"; } } -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/bin/wcons b/xCAT-client/bin/wcons index 79e959817..321e87634 100755 --- a/xCAT-client/bin/wcons +++ b/xCAT-client/bin/wcons @@ -7,63 +7,67 @@ use IO::Socket::UNIX; use Time::HiRes qw/sleep/; use lib "$::XCATROOT/lib/perl"; use xCAT::Client; + #use Data::Dumper; use strict; unless ($ENV{DISPLAY}) { - print '$DISPLAY not set'; - exit 1; + print '$DISPLAY not set'; + exit 1; } my $mydir = dirname($0); my $sb; my $tilefact; -my $xrm="-xrm xterm.mainMenu.*.font:fixed -xrm xterm.vtMenu.*.font:fixed -xrm xterm.fontMenu.*.font:fixed -xrm xterm -xrm xterm.vt100.font6:grvga.737"; +my $xrm = "-xrm xterm.mainMenu.*.font:fixed -xrm xterm.vtMenu.*.font:fixed -xrm xterm.fontMenu.*.font:fixed -xrm xterm -xrm xterm.vt100.font6:grvga.737"; my $font = "5x7"; my $sizegeometry; GetOptions( - #'sb' => \$sb, - 'tile|t:i' => \$tilefact, - 'geometry|g:s' => \$sizegeometry, - #'font|f=s' => \$font + + #'sb' => \$sb, + 'tile|t:i' => \$tilefact, + 'geometry|g:s' => \$sizegeometry, + + #'font|f=s' => \$font ); my $noderange = $ARGV[$#ARGV]; my %conserverref = (command => 'nodels', noderange => $noderange, arg => ['nodehm.conserver']); my @nodes; my %conservers; + sub getconserver { - my $rsp = shift; - foreach (@{$rsp->{node}}) { - my $node = $_->{name}; - if (ref $node) { $node = $node->[0]; } - push @nodes,$node; - if ($_->{data}->[0]->{contents}) { - $conservers{$node}=$_->{data}->[0]->{contents}; - if (ref $conservers{$node}) { $conservers{$node} = $conservers{$node}->[0] }; - } - } + my $rsp = shift; + foreach (@{ $rsp->{node} }) { + my $node = $_->{name}; + if (ref $node) { $node = $node->[0]; } + push @nodes, $node; + if ($_->{data}->[0]->{contents}) { + $conservers{$node} = $_->{data}->[0]->{contents}; + if (ref $conservers{$node}) { $conservers{$node} = $conservers{$node}->[0] } + } + } } -xCAT::Client::submit_request(\%conserverref,\&getconserver); +xCAT::Client::submit_request(\%conserverref, \&getconserver); unless ($ARGV[$#ARGV]) { - print "Usage: wcons \n"; - exit 1; + print "Usage: wcons \n"; + exit 1; } pop @ARGV; foreach (@nodes) { - if ($conservers{$_}) { - next; - } - if ($ENV{XCATHOST}) { - $conservers{$_} = $ENV{XCATHOST}; - $conservers{$_} =~ s/:.*//; - next; - } + if ($conservers{$_}) { + next; + } + if ($ENV{XCATHOST}) { + $conservers{$_} = $ENV{XCATHOST}; + $conservers{$_} =~ s/:.*//; + next; + } } - + my $firstnode = shift @nodes; unless ($firstnode) { - exit 1; + exit 1; } my $currx; my $curry; @@ -74,118 +78,120 @@ my $screenwidth; my $screenheight; my $window_width; my $window_height; -my $panel_pad=0; +my $panel_pad = 0; my $top_pad; + if (defined($tilefact)) { - my $rootinf = `xwininfo -root`; - foreach (split /\n/,$rootinf) { - if (/.*Width:\s+([0-9]*).*/) { - $screenwidth=$1; - } elsif (/.*Height:\s+([0-9]*).*/) { - $screenheight=$1; - } - } - $rootinf = `xwininfo -name "Top Panel" 2> /dev/null`; - foreach (split /\n/,$rootinf) { - if (/-geometry\s+([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+)/) { - if ($1 > 640 and $2 < 480 and $3 == 0 and $4 == 0) { - $panel_pad=$2; - } - } - } - if ($panel_pad == 0) { - $rootinf = `xwininfo -name "Top Expanded Edge Panel" 2> /dev/null`; - foreach (split /\n/,$rootinf) { - if (/-geometry\s+([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+)/) { - if ($1 > 640 and $2 < 480 and $3 == 0 and $4 == 0) { - $panel_pad=$2; - } - } - } - } + my $rootinf = `xwininfo -root`; + foreach (split /\n/, $rootinf) { + if (/.*Width:\s+([0-9]*).*/) { + $screenwidth = $1; + } elsif (/.*Height:\s+([0-9]*).*/) { + $screenheight = $1; + } + } + $rootinf = `xwininfo -name "Top Panel" 2> /dev/null`; + foreach (split /\n/, $rootinf) { + if (/-geometry\s+([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+)/) { + if ($1 > 640 and $2 < 480 and $3 == 0 and $4 == 0) { + $panel_pad = $2; + } + } + } + if ($panel_pad == 0) { + $rootinf = `xwininfo -name "Top Expanded Edge Panel" 2> /dev/null`; + foreach (split /\n/, $rootinf) { + if (/-geometry\s+([0-9]+)x([0-9]+)\+([0-9]+)\+([0-9]+)/) { + if ($1 > 640 and $2 < 480 and $3 == 0 and $4 == 0) { + $panel_pad = $2; + } + } + } + } - $ENV{CONSCONTROLPATH} = "/tmp/wconscontrol.$firstnode.$$"; - system("xterm $xrm -bg black -fg white -title $firstnode -n $firstnode -geometry $sizegeometry+0+0 ".join(" ",@ARGV)." -e /bin/bash -c \"/bin/true ".$ENV{DISPLAY}." $firstnode $firstnode & let SDATE=`date +%s`+5; $mydir/rcons $firstnode ".$conservers{$firstnode}."; if [ \\\$SDATE -gt \\`date +%s\\` ]; then echo Press enter to close; read SDATE; fi \" &"); - $ENV{CONSCONTROLPATH} = ""; - my $remainwait = 2; - if (-x "/opt/confluent/bin/confetty" or -x "/usr/bin/confetty" or -x "/usr/local/bin/confetty" ) { - $remainwait = 10; - } - while (not -S "/tmp/wconscontrol.$firstnode.$$" and $remainwait > 0) { - sleep(0.1); - $remainwait -= 0.1; - } - my $xinfo; - if (-S "/tmp/wconscontrol.$firstnode.$$") { # confluent mode - my $controlchannel = IO::Socket::UNIX->new(Type=>SOCK_STREAM(), Peer => "/tmp/wconscontrol.$firstnode.$$"); + $ENV{CONSCONTROLPATH} = "/tmp/wconscontrol.$firstnode.$$"; + system("xterm $xrm -bg black -fg white -title $firstnode -n $firstnode -geometry $sizegeometry+0+0 " . join(" ", @ARGV) . " -e /bin/bash -c \"/bin/true " . $ENV{DISPLAY} . " $firstnode $firstnode & let SDATE=`date +%s`+5; $mydir/rcons $firstnode " . $conservers{$firstnode} . "; if [ \\\$SDATE -gt \\`date +%s\\` ]; then echo Press enter to close; read SDATE; fi \" &"); + $ENV{CONSCONTROLPATH} = ""; + my $remainwait = 2; + if (-x "/opt/confluent/bin/confetty" or -x "/usr/bin/confetty" or -x "/usr/local/bin/confetty") { + $remainwait = 10; + } + while (not -S "/tmp/wconscontrol.$firstnode.$$" and $remainwait > 0) { + sleep(0.1); + $remainwait -= 0.1; + } + my $xinfo; + if (-S "/tmp/wconscontrol.$firstnode.$$") { # confluent mode + my $controlchannel = IO::Socket::UNIX->new(Type => SOCK_STREAM(), Peer => "/tmp/wconscontrol.$firstnode.$$"); print $controlchannel "GETWINID\n"; my $winid = <$controlchannel>; $winid = <$controlchannel>; - $xinfo = `xwininfo -id $winid`; - } else { - $xinfo = `xwininfo -name $firstnode`; - } + $xinfo = `xwininfo -id $winid`; + } else { + $xinfo = `xwininfo -name $firstnode`; + } - my @xinfl = split(/\n/,$xinfo); - my $side_pad; - my $wmxo; - my $wmyo; - foreach (@xinfl) { - if (/.*Absolute upper-left X:\s*([0-9]*).*/) { - $side_pad = $1; - } elsif (/.*Absolute upper-left Y:\s*([0-9]*).*/) { - $top_pad = $1-$panel_pad; - } elsif (/.*Width:\s*([0-9]*).*/) { - $window_width = $1; - } elsif (/.*Height:\s*([0-9]*).*/) { - $window_height = $1; - } elsif (/.*-gemotery \d+x\d+\+(\d+)(\d+)/) { - $wmxo=$1; - $wmyo=$2; - } - } - $window_width += $side_pad*2; #add the side border, assuming symmetric left and right borders - $window_height += $side_pad+$top_pad; #Add the titlebar and bottom border, which is guessed to probably be equal to the sides, doesn't hold true in all cases, i.e. window maker, but it's the currently best approximation - $screenwidth-=$wmxo; #Subtract a factor that 1.3 did, not sure why precisely - $screenheight-=$wmyo; - $currx=$window_width; - $curry=$panel_pad; #+$top_pad; - my $maxcol = int($screenwidth/$window_width); - unless ($tilefact or $tilefact > $maxcol) { - $tilefact=$maxcol; - } - if ($tilefact==1) { - $curry+=$window_height; - $currx=0; - } + my @xinfl = split(/\n/, $xinfo); + my $side_pad; + my $wmxo; + my $wmyo; + foreach (@xinfl) { + if (/.*Absolute upper-left X:\s*([0-9]*).*/) { + $side_pad = $1; + } elsif (/.*Absolute upper-left Y:\s*([0-9]*).*/) { + $top_pad = $1 - $panel_pad; + } elsif (/.*Width:\s*([0-9]*).*/) { + $window_width = $1; + } elsif (/.*Height:\s*([0-9]*).*/) { + $window_height = $1; + } elsif (/.*-gemotery \d+x\d+\+(\d+)(\d+)/) { + $wmxo = $1; + $wmyo = $2; + } + } + $window_width += $side_pad * 2; #add the side border, assuming symmetric left and right borders + $window_height += $side_pad + $top_pad; #Add the titlebar and bottom border, which is guessed to probably be equal to the sides, doesn't hold true in all cases, i.e. window maker, but it's the currently best approximation + $screenwidth -= $wmxo; #Subtract a factor that 1.3 did, not sure why precisely + $screenheight -= $wmyo; + $currx = $window_width; + $curry = $panel_pad; #+$top_pad; + my $maxcol = int($screenwidth / $window_width); + + unless ($tilefact or $tilefact > $maxcol) { + $tilefact = $maxcol; + } + if ($tilefact == 1) { + $curry += $window_height; + $currx = 0; + } } else { - my $geo; - if ($sizegeometry) { - $geo = "-g $sizegeometry "; - } - system("xterm $xrm $geo-bg black -fg white -title $firstnode -n $firstnode ".join(" ",@ARGV)." -e /bin/bash -c \"$mydir/xtcd.pl ".$ENV{DISPLAY}." $firstnode $firstnode & let SDATE=`date +%s`+5; $mydir/rcons $firstnode ".$conservers{$firstnode}."; if [ \\\$SDATE -gt \\`date +%s\\` ]; then echo Press enter to close; read SDATE; fi\" &"); + my $geo; + if ($sizegeometry) { + $geo = "-g $sizegeometry "; + } + system("xterm $xrm $geo-bg black -fg white -title $firstnode -n $firstnode " . join(" ", @ARGV) . " -e /bin/bash -c \"$mydir/xtcd.pl " . $ENV{DISPLAY} . " $firstnode $firstnode & let SDATE=`date +%s`+5; $mydir/rcons $firstnode " . $conservers{$firstnode} . "; if [ \\\$SDATE -gt \\`date +%s\\` ]; then echo Press enter to close; read SDATE; fi\" &"); } -my $geometry=""; +my $geometry = ""; foreach (@nodes) { - if ($tilefact) { - my $corrected_x=$currx+$wmxo; - my $corrected_y=$curry+$wmyo; - $geometry="-geometry $sizegeometry+$corrected_x+$corrected_y"; - $currx+=$window_width; - if ($currx >= ($tilefact * $window_width)) { - $currx=0; - $curry+=$window_height; - if (($curry+$window_height) > $screenheight) { - $curry = $panel_pad; #+$top_pad; - } - } - } elsif ($sizegeometry) { - $geometry = "-geometry $sizegeometry"; - } + if ($tilefact) { + my $corrected_x = $currx + $wmxo; + my $corrected_y = $curry + $wmyo; + $geometry = "-geometry $sizegeometry+$corrected_x+$corrected_y"; + $currx += $window_width; + if ($currx >= ($tilefact * $window_width)) { + $currx = 0; + $curry += $window_height; + if (($curry + $window_height) > $screenheight) { + $curry = $panel_pad; #+$top_pad; + } + } + } elsif ($sizegeometry) { + $geometry = "-geometry $sizegeometry"; + } - system("xterm $xrm -bg black -fg white ".join(" ",@ARGV)." -title $_ -n $_ $geometry -e /bin/bash -c \"$mydir/xtcd.pl .".$ENV{DISPLAY}." $_ $_ & let SDATE=`date +%s`+5; $mydir/rcons $_ ".$conservers{$_}."; if [ \\\$SDATE -gt \\`date +%s\\` ]; then echo Press enter to close; read SDATE; fi\" &"); + system("xterm $xrm -bg black -fg white " . join(" ", @ARGV) . " -title $_ -n $_ $geometry -e /bin/bash -c \"$mydir/xtcd.pl ." . $ENV{DISPLAY} . " $_ $_ & let SDATE=`date +%s`+5; $mydir/rcons $_ " . $conservers{$_} . "; if [ \\\$SDATE -gt \\`date +%s\\` ]; then echo Press enter to close; read SDATE; fi\" &"); } diff --git a/xCAT-client/bin/wvid b/xCAT-client/bin/wvid index cbffb04a4..a46db2c8f 100755 --- a/xCAT-client/bin/wvid +++ b/xCAT-client/bin/wvid @@ -4,6 +4,7 @@ BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } use lib "$::XCATROOT/lib/perl"; use Cwd; + #use IO::Socket::SSL; #use IO::Socket::INET; my %rvidhash; @@ -13,16 +14,17 @@ unless ($xcatroot) { } use File::Basename; use xCAT::Client; + #use Data::Dumper; sub process_response { my $resp = shift; - foreach my $rst (\@{$resp->{node}}) { + foreach my $rst (\@{ $resp->{node} }) { foreach my $rsp (@$rst) { - if ($rsp->{errorcode} and (not ref $rsp->{errorcode} or $rsp->{errorcode}->[0])) { - print $rsp->{name}->[0].": Error: ".$rsp->{error}->[0]."\n"; - } else { - $rvidhash{$rsp->{name}->[0]}->{$rsp->{data}->[0]->{desc}->[0]} = $rsp->{data}->[0]->{contents}->[0]; - } + if ($rsp->{errorcode} and (not ref $rsp->{errorcode} or $rsp->{errorcode}->[0])) { + print $rsp->{name}->[0] . ": Error: " . $rsp->{error}->[0] . "\n"; + } else { + $rvidhash{ $rsp->{name}->[0] }->{ $rsp->{data}->[0]->{desc}->[0] } = $rsp->{data}->[0]->{contents}->[0]; + } } } } @@ -31,23 +33,23 @@ my $cmdref; $cmdref->{command}->[0] = 'getrvidparms'; # Consider the 1st non-hyphen arg to be the noderange. All others (before and after) go on the arg list. -my $arg=shift(@ARGV); +my $arg = shift(@ARGV); while ($arg =~ /^-/) { - push (@{$cmdref->{arg}}, $arg); - $arg=shift(@ARGV); + push(@{ $cmdref->{arg} }, $arg); + $arg = shift(@ARGV); } if ($arg ne "NO_NODE_RANGE") { - $cmdref->{noderange}->[0]=$arg; + $cmdref->{noderange}->[0] = $arg; } -push (@{$cmdref->{arg}}, @ARGV); +push(@{ $cmdref->{arg} }, @ARGV); -xCAT::Client::submit_request($cmdref,\&process_response); -my %CLEANENV=%ENV; +xCAT::Client::submit_request($cmdref, \&process_response); +my %CLEANENV = %ENV; foreach my $node (keys %rvidhash) { - %ENV=%CLEANENV; - foreach my $var (keys %{$rvidhash{$node}}) { - $ENV{"rvid_$var"}=$rvidhash{$node}->{$var}; + %ENV = %CLEANENV; + foreach my $var (keys %{ $rvidhash{$node} }) { + $ENV{"rvid_$var"} = $rvidhash{$node}->{$var}; } - system("$xcatroot/share/xcat/rvid/rvid.".$ENV{"rvid_method"}." &"); + system("$xcatroot/share/xcat/rvid/rvid." . $ENV{"rvid_method"} . " &"); } exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/bin/xcatDBcmds b/xCAT-client/bin/xcatDBcmds index 5b063d074..e646932b3 100755 --- a/xCAT-client/bin/xcatDBcmds +++ b/xCAT-client/bin/xcatDBcmds @@ -52,32 +52,34 @@ else } $cmdref->{cwd}->[0] = cwd(); + # get info from files piped in as stdin my $data; -if ( (($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}) ) +if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'})) { my $rout; - my $rin=""; - vec($rin,fileno(STDIN),1)=1; - my $nfound=select($rout=$rin,"","",1); + my $rin = ""; + vec($rin, fileno(STDIN), 1) = 1; + my $nfound = select($rout = $rin, "", "", 1); if ($nfound) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } else { if (-p STDIN) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } + # The noderange can be specified through a noderange file # the noderange file can be a relative path, # convert the relative path to a full path. my @tmpargv = (); -my @tmpv = @ARGV; +my @tmpv = @ARGV; foreach my $a (@tmpv) { if (!($a =~ /=/) && !($a =~ /^-/)) { @@ -85,17 +87,17 @@ foreach my $a (@tmpv) foreach my $nr (split(/,/, $a)) { if ($nr =~ /^\^(.*)$/) { my $nrf = $1; - if ($nrf !~ /^\//) { #relative path - $nrf = Cwd::abs_path($nrf); - } + if ($nrf !~ /^\//) { #relative path + $nrf = Cwd::abs_path($nrf); + } $nrf = "\^" . $nrf; push @tempnr, $nrf; } else { push @tempnr, $nr; } } - $a = join(',',@tempnr); - } + $a = join(',', @tempnr); + } push @tmpargv, $a; } @ARGV = @tmpargv; @@ -103,25 +105,27 @@ foreach my $a (@tmpv) # add all the cmd line args to the hash - to pass to the plugin subroutine foreach my $a (@ARGV) { - push(@{$cmdref->{arg}}, $a); + push(@{ $cmdref->{arg} }, $a); } # For some commands we need to set the noderange value # - don't want to depend on the order of args so need to pick # the operand that doesn't have an "=" sign ( ie. attr=val format) my @checkcmds = ("nimnodeset", "mkdsklsnode", "rmdsklsnode", "xcat2nim", "nimnodecust"); -if (grep(/^$bname$/, @checkcmds) ) { - # strip off all options - # use getopt instead of getopts to let long options pass through - getopt('ismot'); - # check the operands for a noderange - while (my $a = shift(@ARGV)) { - if (!($a =~ /=/) && !($a =~ /^-/)) { - $cmdref->{noderange}->[0]=$a; - last; - } - } +if (grep(/^$bname$/, @checkcmds)) { + + # strip off all options + # use getopt instead of getopts to let long options pass through + getopt('ismot'); + + # check the operands for a noderange + while (my $a = shift(@ARGV)) { + if (!($a =~ /=/) && !($a =~ /^-/)) { + $cmdref->{noderange}->[0] = $a; + last; + } + } } -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/bin/xcatclient b/xCAT-client/bin/xcatclient index d721a8cb1..83a918941 100755 --- a/xCAT-client/bin/xcatclient +++ b/xCAT-client/bin/xcatclient @@ -11,37 +11,40 @@ BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } use lib "$::XCATROOT/lib/perl"; use Cwd; + #use IO::Socket::SSL; #use IO::Socket::INET; use File::Basename; + #use Data::Dumper; use xCAT::Client; use strict; my $bname = basename($0); my $cmdref; -if ($bname =~ /xcatclient/) { $cmdref->{command}->[0]=shift @ARGV; } # xcatclient was invoked directly and the 1st arg is cmd name that is used to locate the plugin -else { $cmdref->{command}->[0] = $bname; } # the cmd was sym linked to xcatclient +if ($bname =~ /xcatclient/) { $cmdref->{command}->[0] = shift @ARGV; } # xcatclient was invoked directly and the 1st arg is cmd name that is used to locate the plugin +else { $cmdref->{command}->[0] = $bname; } # the cmd was sym linked to xcatclient $cmdref->{cwd}->[0] = cwd(); my $data; + # allows our plugins to get the stdin of the cmd that invoked the plugin -if ( (($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}) ) +if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'})) { - my $rin=""; + my $rin = ""; my $rout; - vec($rin,fileno(STDIN),1)=1; - my $nfound=select($rout=$rin,"","",1); + vec($rin, fileno(STDIN), 1) = 1; + my $nfound = select($rout = $rin, "", "", 1); if ($nfound) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } else { if (-p STDIN) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } @@ -57,40 +60,41 @@ if (($bname =~ /lslite/) && $str =~ /-i/) $arg = "NO_NODE_RANGE"; } else -{ # Consider the 1st non-hyphen arg to be the noderange. All others (before and after) go on the arg list. - $arg=shift(@ARGV); +{ # Consider the 1st non-hyphen arg to be the noderange. All others (before and after) go on the arg list. + $arg = shift(@ARGV); while ($arg =~ /^-/) { - push (@{$cmdref->{arg}}, $arg); - $arg=shift(@ARGV); + push(@{ $cmdref->{arg} }, $arg); + $arg = shift(@ARGV); } } if ($arg ne "NO_NODE_RANGE") { - # The noderange can be specified through a noderange file, - # the noderange file can be a relative path, - # convert the relative path to a full path. - # an ideal way is converting the relative path in xCAT::Noderange::noderange, - # but the existing xCAT::Noderange::noderange can not get the cwd(), - # needs to change all the callers to pass the cwd(), - # there are more than 100 callers. - my @tempnr = (); - foreach my $nr (split(/,/, $arg)) { - if ($nr =~ /^\^(.*)$/) { - my $nrf = $1; - if ($nrf !~ /^\//) { #relative path - $nrf = Cwd::abs_path($nrf); - } - $nrf = "\^" . $nrf; - push @tempnr, $nrf; - } else { - push @tempnr, $nr; + + # The noderange can be specified through a noderange file, + # the noderange file can be a relative path, + # convert the relative path to a full path. + # an ideal way is converting the relative path in xCAT::Noderange::noderange, + # but the existing xCAT::Noderange::noderange can not get the cwd(), + # needs to change all the callers to pass the cwd(), + # there are more than 100 callers. + my @tempnr = (); + foreach my $nr (split(/,/, $arg)) { + if ($nr =~ /^\^(.*)$/) { + my $nrf = $1; + if ($nrf !~ /^\//) { #relative path + $nrf = Cwd::abs_path($nrf); + } + $nrf = "\^" . $nrf; + push @tempnr, $nrf; + } else { + push @tempnr, $nr; + } } - } - $arg = join(',',@tempnr); - $cmdref->{noderange}->[0]=$arg; + $arg = join(',', @tempnr); + $cmdref->{noderange}->[0] = $arg; } if (@ARGV) { - push (@{$cmdref->{arg}}, @ARGV); + push(@{ $cmdref->{arg} }, @ARGV); } foreach (keys %ENV) { if (/^XCAT_/) { @@ -98,5 +102,5 @@ foreach (keys %ENV) { } } -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/bin/xcatclientnnr b/xCAT-client/bin/xcatclientnnr index c2a136c14..e33b80408 100755 --- a/xCAT-client/bin/xcatclientnnr +++ b/xCAT-client/bin/xcatclientnnr @@ -15,34 +15,35 @@ use strict; my $bname = basename($0); my $cmdref; -if ($bname =~ /xcatclientnnr/) { $cmdref->{command}->[0]=shift @ARGV; } # xcatclientnnr was invoked directly and the 1st arg is cmd name that is used to locate the plugin -else { $cmdref->{command}->[0] = $bname; } # the cmd was sym linked to xcatclientnnr +if ($bname =~ /xcatclientnnr/) { $cmdref->{command}->[0] = shift @ARGV; } # xcatclientnnr was invoked directly and the 1st arg is cmd name that is used to locate the plugin +else { $cmdref->{command}->[0] = $bname; } # the cmd was sym linked to xcatclientnnr $cmdref->{cwd}->[0] = cwd(); my $data; + # allows our plugins to get the stdin of the cmd that invoked the plugin -if ( (($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'}) ) +if ((($^O =~ /^linux/i) && ($ENV{'SHELL'} =~ /\/ksh$/)) || !defined($ENV{'TERM'})) { my $rout; - my $rin=""; - vec($rin,fileno(STDIN),1)=1; - my $nfound=select($rout=$rin,"","",1); + my $rin = ""; + vec($rin, fileno(STDIN), 1) = 1; + my $nfound = select($rout = $rin, "", "", 1); if ($nfound) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } else { if (-p STDIN) { - while ( ) { $data.=$_; } - $cmdref->{stdin}->[0]=$data; + while () { $data .= $_; } + $cmdref->{stdin}->[0] = $data; } } if (@ARGV) { - push (@{$cmdref->{arg}}, @ARGV); + push(@{ $cmdref->{arg} }, @ARGV); } foreach (keys %ENV) { if (/^XCAT_/) { @@ -50,7 +51,7 @@ foreach (keys %ENV) { } } -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/bin/xcoll b/xCAT-client/bin/xcoll index 4169edd06..03a14a0ef 100755 --- a/xCAT-client/bin/xcoll +++ b/xCAT-client/bin/xcoll @@ -2,6 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } use lib "$::XCATROOT/lib/perl"; + #use Data::Dumper; use xCAT::Client; use Getopt::Long; @@ -12,30 +13,31 @@ my $option; my $printcount; my $individual; -GetOptions("n"=>\$option, - "i"=>\$individual, - "c"=>\$printcount); +GetOptions("n" => \$option, + "i" => \$individual, + "c" => \$printcount); while () { my $node; my $output; if (/:/) { - ($node,$output) = split /:/,$_,2; + ($node, $output) = split /:/, $_, 2; } else { - $node= "UNKNOWN"; + $node = "UNKNOWN"; $output = $_; } $output =~ s/^ //; - $output{$node}.=$output; + $output{$node} .= $output; } my %collated; unless ($individual) { foreach (keys %output) { - $collated{$output{$_}}->{$_}=1; + $collated{ $output{$_} }->{$_} = 1; } } my $nodes; + sub fillerup { my $response = shift; if ($response->{data}->[0]) { @@ -53,20 +55,20 @@ if ($individual) { exit(0); } foreach my $output (keys %collated) { - $nodes = join(',',sort (keys %{$collated{$output}})); + $nodes = join(',', sort (keys %{ $collated{$output} })); my $cmdref = { noderange => [$nodes], - command => ['rnoderange'], + command => ['rnoderange'], }; unless ($option) { - xCAT::Client::submit_request($cmdref,\&fillerup); + xCAT::Client::submit_request($cmdref, \&fillerup); } print "====================================\n"; print "$nodes\n"; print "====================================\n"; if ($printcount) { - print "Node count = ".scalar( keys %{$collated{$output}})." \n"; - print "====================================\n"; + print "Node count = " . scalar(keys %{ $collated{$output} }) . " \n"; + print "====================================\n"; } print $output; print "\n"; diff --git a/xCAT-client/bin/xcsv b/xCAT-client/bin/xcsv index d8d0f01b6..375dad9f6 100755 --- a/xCAT-client/bin/xcsv +++ b/xCAT-client/bin/xcsv @@ -2,6 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } use lib "$::XCATROOT/lib/perl"; + #use Data::Dumper; use xCAT::Client; my %columns; @@ -11,30 +12,31 @@ while () { my $node; my $output; if (/:/) { - ($node,$output) = split /:/,$_,2; + ($node, $output) = split /:/, $_, 2; } else { - $node= "UNKNOWN"; + $node = "UNKNOWN"; $output = $_; } my $colname; - if ($output =~ /:/) { - ($colname,$output) = split /:/,$output,2; + if ($output =~ /:/) { + ($colname, $output) = split /:/, $output, 2; } else { - $colname = "UNKNOWN"; + $colname = "UNKNOWN"; } - $colname =~ s/^ *//; + $colname =~ s/^ *//; $output =~ s/^ //; $output =~ s/\n//; - $output{$node}->{$colname}.=$output; - $columns{$colname}=1; + $output{$node}->{$colname} .= $output; + $columns{$colname} = 1; } my @columns; -foreach (keys %columns) { #create,preserv ordered list of columns - push @columns, $_; +foreach (keys %columns) { #create,preserv ordered list of columns + push @columns, $_; } -print join(',',"node",@columns)."\n"; +print join(',', "node", @columns) . "\n"; my $nodes; + sub fillerup { my $response = shift; if ($response->{data}->[0]) { @@ -42,9 +44,9 @@ sub fillerup { } } foreach my $node (keys %output) { - my @output=($node); + my @output = ($node); foreach (@columns) { - push @output,$output{$node}->{$_}; + push @output, $output{$node}->{$_}; } - print join(",",@output)."\n"; + print join(",", @output) . "\n"; } diff --git a/xCAT-client/bin/xdsh b/xCAT-client/bin/xdsh index 7c1d5e98f..1d06e74a9 100644 --- a/xCAT-client/bin/xdsh +++ b/xCAT-client/bin/xdsh @@ -3,9 +3,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -73,7 +73,7 @@ if ($arg =~ /^-/) # no noderange if ($::ROOTIMG != 1) { # if not running against rootimg then noderange required xCAT::MsgUtils->message("I", - "Node range not specified, see $bname man page for syntax.\n"); + "Node range not specified, see $bname man page for syntax.\n"); exit 1; } } @@ -84,7 +84,7 @@ else if (!($cmdref->{noderange}->[0])) { xCAT::MsgUtils->message("I", - "Node range not specified, see man page for syntax.\n"); + "Node range not specified, see man page for syntax.\n"); exit 1; } @ARGV = @SaveARGV; # noderange removed for parsing @@ -100,7 +100,7 @@ else foreach my $sarg (@SaveARGV) { - push(@{$cmdref->{arg}}, $sarg); + push(@{ $cmdref->{arg} }, $sarg); } # add environment variables, if they have not already been assigned with @@ -109,7 +109,7 @@ if (!($::NODE_RSH)) { if ($ENV{'DSH_NODE_RSH'}) { - push(@{$cmdref->{env}}, "DSH_NODE_RSH=$ENV{'DSH_NODE_RSH'}"); + push(@{ $cmdref->{env} }, "DSH_NODE_RSH=$ENV{'DSH_NODE_RSH'}"); } } @@ -117,7 +117,7 @@ if (!($::NODE_RCP)) { if ($ENV{'DSH_NODE_RCP'}) { - push(@{$cmdref->{env}}, "DSH_NODE_RCP=$ENV{'DSH_NODE_RCP'}"); + push(@{ $cmdref->{env} }, "DSH_NODE_RCP=$ENV{'DSH_NODE_RCP'}"); } } @@ -125,7 +125,7 @@ if (!($::NODE_OPTS)) { if ($ENV{'DSH_NODE_OPTS'}) { - push(@{$cmdref->{env}}, "DSH_NODE_OPTS=$ENV{'DSH_NODE_OPTS'}"); + push(@{ $cmdref->{env} }, "DSH_NODE_OPTS=$ENV{'DSH_NODE_OPTS'}"); } } @@ -133,7 +133,7 @@ if (!($::FANOUT)) { if ($ENV{'DSH_FANOUT'}) { - push(@{$cmdref->{env}}, "DSH_FANOUT=$ENV{'DSH_FANOUT'}"); + push(@{ $cmdref->{env} }, "DSH_FANOUT=$ENV{'DSH_FANOUT'}"); } } @@ -141,53 +141,53 @@ if (!($::TIMEOUT)) { if ($ENV{'DSH_TIMEOUT'}) { - push(@{$cmdref->{env}}, "DSH_TIMEOUT=$ENV{'DSH_TIMEOUT'}"); + push(@{ $cmdref->{env} }, "DSH_TIMEOUT=$ENV{'DSH_TIMEOUT'}"); } } if ($ENV{'DSH_REMOTE_PASSWORD'}) { - push(@{$cmdref->{env}}, "DSH_REMOTE_PASSWORD=$ENV{'DSH_REMOTE_PASSWORD'}"); + push(@{ $cmdref->{env} }, "DSH_REMOTE_PASSWORD=$ENV{'DSH_REMOTE_PASSWORD'}"); } if ($ENV{'DSH_FROM_USERID'}) { - push(@{$cmdref->{env}}, "DSH_FROM_USERID=$ENV{'DSH_FROM_USERID'}"); + push(@{ $cmdref->{env} }, "DSH_FROM_USERID=$ENV{'DSH_FROM_USERID'}"); } if ($ENV{'DSH_TO_USERID'}) { - push(@{$cmdref->{env}}, "DSH_TO_USERID=$ENV{'DSH_TO_USERID'}"); + push(@{ $cmdref->{env} }, "DSH_TO_USERID=$ENV{'DSH_TO_USERID'}"); } if ($ENV{'DEVICETYPE'}) { - push(@{$cmdref->{env}}, "DEVICETYPE=$ENV{'DEVICETYPE'}"); + push(@{ $cmdref->{env} }, "DEVICETYPE=$ENV{'DEVICETYPE'}"); } if ($ENV{'DSH_RSYNC_FILE'}) { - push(@{$cmdref->{env}}, "DSH_RSYNC_FILE=$ENV{'DSH_RSYNC_FILE'}"); + push(@{ $cmdref->{env} }, "DSH_RSYNC_FILE=$ENV{'DSH_RSYNC_FILE'}"); } if ($ENV{'RSYNCSN'}) { - push(@{$cmdref->{env}}, "RSYNCSN=$ENV{'RSYNCSN'}"); + push(@{ $cmdref->{env} }, "RSYNCSN=$ENV{'RSYNCSN'}"); } if ($ENV{'RSYNCSNONLY'}) { - push(@{$cmdref->{env}}, "RSYNCSNONLY=$ENV{'RSYNCSNONLY'}"); + push(@{ $cmdref->{env} }, "RSYNCSNONLY=$ENV{'RSYNCSNONLY'}"); } if ($ENV{'DCP_PULL'}) { - push(@{$cmdref->{env}}, "DCP_PULL=$ENV{'DCP_PULL'}"); + push(@{ $cmdref->{env} }, "DCP_PULL=$ENV{'DCP_PULL'}"); } if ($ENV{'DSHEXECUTE'}) { - push(@{$cmdref->{env}}, "DSHEXECUTE=$ENV{'DSHEXECUTE'}"); + push(@{ $cmdref->{env} }, "DSHEXECUTE=$ENV{'DSHEXECUTE'}"); } if ($ENV{'DSH_ENVIRONMENT'}) { - push(@{$cmdref->{env}}, "DSH_ENVIRONMENT=$ENV{'DSH_ENVIRONMENT'}"); + push(@{ $cmdref->{env} }, "DSH_ENVIRONMENT=$ENV{'DSH_ENVIRONMENT'}"); } xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); @@ -208,10 +208,11 @@ exit $xCAT::Client::EXITCODE; sub parse_args_xdsh { my $snodes = shift; + # test to see if any parameters were entered - my $arraysize=@ARGV; - if ($arraysize ==0) { - my $msg= "No parameters were supplied on the xdsh command. Run xdsh -h"; + my $arraysize = @ARGV; + if ($arraysize == 0) { + my $msg = "No parameters were supplied on the xdsh command. Run xdsh -h"; xCAT::MsgUtils->message("E", $msg); exit 1; } @@ -247,8 +248,8 @@ sub parse_args_xdsh 'V|version' => \$options{'version'}, 'devicetype=s' => \$options{'devicetype'}, - 'nodestatus|nodestatus' => \$options{'nodestatus'}, - 'sudo|sudo' => \$options{'sudo'}, + 'nodestatus|nodestatus' => \$options{'nodestatus'}, + 'sudo|sudo' => \$options{'sudo'}, 'command-name|commandName=s' => \$options{'command-name'}, 'command-description|commandDescription=s' => \$options{'command-description'}, @@ -281,7 +282,7 @@ sub parse_args_xdsh # get the directories on the servicenode to put the files in my $defaultsyndir = "/var/xcat/syncfiles"; - my @syndir = xCAT::TableUtils->get_site_attribute("SNsyncfiledir"); + my @syndir = xCAT::TableUtils->get_site_attribute("SNsyncfiledir"); my $synfiledir; if ($syndir[0]) { @@ -291,9 +292,10 @@ sub parse_args_xdsh { $synfiledir = "/var/xcat/syncfiles"; # default } + # for append function my $defaultnodesyndir = "/var/xcat/node/syncfiles"; - my @syndir2 = xCAT::TableUtils->get_site_attribute("nodesyncfiledir"); + my @syndir2 = xCAT::TableUtils->get_site_attribute("nodesyncfiledir"); my $synfiledir2; if ($syndir2[0]) { @@ -307,12 +309,13 @@ sub parse_args_xdsh { my $answer; my $msg = - "Do you wish to erase $synfiledir,$synfiledir2 and all subdirectories?\n Enter Y or N."; +"Do you wish to erase $synfiledir,$synfiledir2 and all subdirectories?\n Enter Y or N."; xCAT::MsgUtils->message('I', "$msg"); `stty -echo`; chop($answer = ); `stty echo`; - $answer =~ tr/a-z/A-Z/; # convert to upper + $answer =~ tr/a-z/A-Z/; # convert to upper + if ($answer ne "Y") { exit 0; @@ -321,7 +324,7 @@ sub parse_args_xdsh my $cmd = "xdsh $snodes -v rm -rf $synfiledir/*;xdsh $snodes -v rm -rf $synfiledir2"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) - { # error + { # error my $msg = "Error from $cmd: to cleanup servicenodes"; xCAT::MsgUtils->message("E", $msg); exit 1; @@ -331,7 +334,7 @@ sub parse_args_xdsh } if ($options{'bypass'}) { - $ENV{XCATBYPASS} = "yes"; # bypass xcatd + $ENV{XCATBYPASS} = "yes"; # bypass xcatd } if ($options{'show-config'}) { @@ -339,24 +342,27 @@ sub parse_args_xdsh exit 0; } my $executescript; + #check for full path to file if ($options{execute}) - { + { # this can be a file + parameters $executescript = join ' ', @ARGV; if ($executescript !~ /^\//) { - #relative path - $executescript = xCAT::Utils->full_path($executescript); + + #relative path + $executescript = xCAT::Utils->full_path($executescript); } - $ENV{'DSHEXECUTE'} = $executescript; # execute script + $ENV{'DSHEXECUTE'} = $executescript; # execute script } + # -E option if not already exported - + if ($options{environment}) - { - if (!($ENV{'DSH_ENVIRONMENT'})) { # env variable first - $ENV{'DSH_ENVIRONMENT'} = $options{environment}; # env file - } + { + if (!($ENV{'DSH_ENVIRONMENT'})) { # env variable first + $ENV{'DSH_ENVIRONMENT'} = $options{environment}; # env file + } } @@ -384,12 +390,13 @@ sub parse_args_xdsh $devicepath =~ s/::/\//g; if (($options{'ssh-setup'}) && ($devicepath =~ /Mellanox/i)) { my $msg = - "You do not use xdsh -K to setup the Mellanox switch ssh keys. Use rspconfig. See man page for rspconfig option sshcfg={enable|disable}."; +"You do not use xdsh -K to setup the Mellanox switch ssh keys. Use rspconfig. See man page for rspconfig option sshcfg={enable|disable}."; xCAT::MsgUtils->message("E", $msg); exit 2; } + # only allow -K with -l if --devicetype defined - if ( (($options{'user'}) && ($options{'ssh-setup'})) + if ((($options{'user'}) && ($options{'ssh-setup'})) && (!($options{'devicetype'}))) { my $msg = @@ -405,7 +412,7 @@ sub parse_args_xdsh # prompt for the password for the userid on the node that will be setup my $userpw; $msg = - "The ssh keys will be updated for '$to_userid' on the node(s).\nPassword:"; +"The ssh keys will be updated for '$to_userid' on the node(s).\nPassword:"; xCAT::MsgUtils->message("I", $msg); system("stty -echo"); # turn off keyboard chop($userpw = ); @@ -433,49 +440,49 @@ sub parse_args_xdsh my $sshdir = "$home/.ssh"; if (!-d $sshdir) { - my $cmd = "/bin/mkdir -m 700 -p $sshdir"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not create $sshdir directory."); - exit 1; - } + my $cmd = "/bin/mkdir -m 700 -p $sshdir"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not create $sshdir directory."); + exit 1; + } } - # add config file with strict host checking no, if not already there - my $configinfo = "StrictHostKeyChecking no"; - my $configfile= "$home/.ssh/config"; - if (-e $configfile) - { - my $cmd = "grep StrictHostKeyChecking $configfile"; - xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) - { # not there - $cmd = "echo $configinfo >> $configfile"; - my @output = xCAT::Utils->runcmd($cmd, 0); + # add config file with strict host checking no, if not already there + my $configinfo = "StrictHostKeyChecking no"; + my $configfile = "$home/.ssh/config"; + if (-e $configfile) + { + my $cmd = "grep StrictHostKeyChecking $configfile"; + xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) - { # error - xCAT::MsgUtils->message("E", "Error on $cmd, @output"); - return 1; - } + { # not there + $cmd = "echo $configinfo >> $configfile"; + my @output = xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { # error + xCAT::MsgUtils->message("E", "Error on $cmd, @output"); + return 1; + } - } + } } else # file does not exist { - my $cmd = "echo $configinfo >> $configfile"; - my @output = xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { # error - xCAT::MsgUtils->message("E", "Error on $cmd, @output"); - return 1; - } - else - { - chmod 0600, $configfile; + my $cmd = "echo $configinfo >> $configfile"; + my @output = xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { # error + xCAT::MsgUtils->message("E", "Error on $cmd, @output"); + return 1; + } + else + { + chmod 0600, $configfile; - } + } } @@ -484,15 +491,16 @@ sub parse_args_xdsh # if ($current_userid ne "root") { - $::REMOTE_SHELL = "/usr/bin/ssh"; - my $callback = \&xCAT::Client::handle_response; - # generates new keys for non-root id, if they do not already exist - my $rc= - xCAT::RemoteShellExp->remoteshellexp("k",$callback,$::REMOTE_SHELL); - if ($rc != 0) { - $msg = "remoteshellexp failed generating keys."; - xCAT::MsgUtils->message("E", $msg); - } + $::REMOTE_SHELL = "/usr/bin/ssh"; + my $callback = \&xCAT::Client::handle_response; + + # generates new keys for non-root id, if they do not already exist + my $rc = + xCAT::RemoteShellExp->remoteshellexp("k", $callback, $::REMOTE_SHELL); + if ($rc != 0) { + $msg = "remoteshellexp failed generating keys."; + xCAT::MsgUtils->message("E", $msg); + } } @@ -547,10 +555,11 @@ sub parse_args_xdcp { my %options = (); + # test to see if any parameters were entered - my $arraysize=@ARGV; - if ($arraysize ==0) { - my $msg= "No parameters were supplied on the xdcp command. Run xdcp -h"; + my $arraysize = @ARGV; + if ($arraysize == 0) { + my $msg = "No parameters were supplied on the xdcp command. Run xdcp -h"; xCAT::MsgUtils->message("E", $msg); exit 1; } @@ -560,28 +569,28 @@ sub parse_args_xdcp if ( !GetOptions( - 'f|fanout=i' => \$options{'fanout'}, - 'F|File=s' => \$options{'File'}, - 'h|help' => \$options{'help'}, - 'i|rootimg=s' => \$options{'rootimg'}, - 'l|user=s' => \$options{'user'}, - 'm|monitor' => \$options{'monitor'}, - 'o|node-options=s' => \$options{'node-options'}, - 'q|show-config' => \$options{'show-config'}, - 'p|preserve' => \$options{'preserve'}, - 'r|c|node-rcp=s' => \$options{'node-rcp'}, - 's' => \$options{'rsyncSN'}, - 't|timeout=i' => \$options{'timeout'}, - 'v|verify' => \$options{'verify'}, - 'B|bypass' => \$options{'bypass'}, - 'Q|silent' => \$options{'silent'}, - 'P|pull' => \$options{'pull'}, - 'R|recursive' => \$options{'recursive'}, - 'T|trace' => \$options{'trace'}, - 'V|version' => \$options{'version'}, - 'nodestatus|nodestatus' => \$options{'nodestatus'}, - 'sudo|sudo' => \$options{'sudo'}, - 'X:s' => \$options{'ignore_env'} + 'f|fanout=i' => \$options{'fanout'}, + 'F|File=s' => \$options{'File'}, + 'h|help' => \$options{'help'}, + 'i|rootimg=s' => \$options{'rootimg'}, + 'l|user=s' => \$options{'user'}, + 'm|monitor' => \$options{'monitor'}, + 'o|node-options=s' => \$options{'node-options'}, + 'q|show-config' => \$options{'show-config'}, + 'p|preserve' => \$options{'preserve'}, + 'r|c|node-rcp=s' => \$options{'node-rcp'}, + 's' => \$options{'rsyncSN'}, + 't|timeout=i' => \$options{'timeout'}, + 'v|verify' => \$options{'verify'}, + 'B|bypass' => \$options{'bypass'}, + 'Q|silent' => \$options{'silent'}, + 'P|pull' => \$options{'pull'}, + 'R|recursive' => \$options{'recursive'}, + 'T|trace' => \$options{'trace'}, + 'V|version' => \$options{'version'}, + 'nodestatus|nodestatus' => \$options{'nodestatus'}, + 'sudo|sudo' => \$options{'sudo'}, + 'X:s' => \$options{'ignore_env'} ) ) { @@ -645,7 +654,7 @@ sub parse_args_xdcp if (($options{'rootimg'}) && (!($options{'File'}))) { xCAT::MsgUtils->message("E", - "To use -i flag you must supply the -F flag\n."); + "To use -i flag you must supply the -F flag\n."); exit 1; } if ($options{'node-rcp'}) # if set on command line, use it @@ -680,64 +689,64 @@ sub check_invalid_exports if ($ENV{'DSH_CONTEXT'}) { xCAT::MsgUtils->message("I", - "DSH_CONTEXT is set but is not supported. It will be ignored.\n"); + "DSH_CONTEXT is set but is not supported. It will be ignored.\n"); } if ($ENV{'DSH_LIST'}) # if file of nodes input { xCAT::MsgUtils->message("I", - "DSH_LIST is set but is not supported. It will be ignored.\n"); + "DSH_LIST is set but is not supported. It will be ignored.\n"); } if ($ENV{'DSH_NODE_LIST'}) { xCAT::MsgUtils->message( - "I", - "DSH_NODE_LIST is set but is not supported. It will be ignored.\n" - ); + "I", + "DSH_NODE_LIST is set but is not supported. It will be ignored.\n" + ); } if ($ENV{'DSH_DEVICE_LIST'}) { xCAT::MsgUtils->message( "I", "DSH_DEVICE_LIST is set but is not supported. It will be ignored.\n" - ); + ); } if ($ENV{'DSH_DEVICE_OPTS'}) { xCAT::MsgUtils->message( "I", "DSH_DEVICE_OPTS is set but is not supported. It will be ignored.\n" - ); + ); } if ($ENV{'DSH_DEVICE_RCP'}) { xCAT::MsgUtils->message( - "I", - "DSH_DEVICE_RCP is set but is not supported. It will be ignored.\n" - ); + "I", + "DSH_DEVICE_RCP is set but is not supported. It will be ignored.\n" + ); } if ($ENV{'DSH_DEVICE_RSH'}) { xCAT::MsgUtils->message( - "I", - "DSH_DEVICE_RSH is set but is not supported. It will be ignored.\n" - ); + "I", + "DSH_DEVICE_RSH is set but is not supported. It will be ignored.\n" + ); } if ($ENV{'DSH_NODEGROUP_PATH'}) { xCAT::MsgUtils->message( "I", - "DSH_NODEGROUP_PATH is set but is not supported. It will be ignored.\n" - ); +"DSH_NODEGROUP_PATH is set but is not supported. It will be ignored.\n" + ); } if ($ENV{'RSYNC_RSH'}) { xCAT::MsgUtils->message("I", - " RSYNC_RSH is set but is not supported. It will be ignored.\n"); + " RSYNC_RSH is set but is not supported. It will be ignored.\n"); } if ($ENV{'DSH_REPORT'}) { xCAT::MsgUtils->message("I", - " DSH_REPORT is set but is not supported. It will be ignored.\n"); + " DSH_REPORT is set but is not supported. It will be ignored.\n"); } } diff --git a/xCAT-client/bin/xdshbak b/xCAT-client/bin/xdshbak index e38442481..66bc59ff3 100644 --- a/xCAT-client/bin/xdshbak +++ b/xCAT-client/bin/xdshbak @@ -24,7 +24,7 @@ use Getopt::Std; # -c : list distinct output only once # # -h : usage # # -x : omit extra header output for each node. # -# Can not be used with -c. # +# Can not be used with -c. # # -q : quiet mode # # # # Ouputs: # @@ -110,8 +110,8 @@ while () # $num_lines++; if (!($quiet)) { - if ($::opt_x) { $num_lines % 100 == 0 && print STDOUT "."; } - else { $num_lines % 1000 == 0 && print STDOUT "."; } + if ($::opt_x) { $num_lines % 100 == 0 && print STDOUT "."; } + else { $num_lines % 1000 == 0 && print STDOUT "."; } } if (/: /) { @@ -204,7 +204,7 @@ sub d_syntax "-c : compresses the output by listing unique output only once.\n"; my $usage3 = "-h : help \n"; my $usage4 = - "-x : omit extra header output for each node. Can not be used with -c. \n"; +"-x : omit extra header output for each node. Can not be used with -c. \n"; my $usage5 = "-q : quiet mode.\n"; my $usage = $usage1 .= $usage2 .= $usage3 .= $usage4 .= $usage5; xCAT::MsgUtils->message("I", $usage); @@ -302,10 +302,10 @@ sub print_tree xCAT::MsgUtils->message("I", "HOSTS:"); print - "-------------------------------------------------------------------------\n"; +"-------------------------------------------------------------------------\n"; &display_wc; print - "-------------------------------------------------------------------------------\n"; +"-------------------------------------------------------------------------------\n"; print $str{$index}; } } diff --git a/xCAT-client/podchecker b/xCAT-client/podchecker index 9bd3cd2da..1b5fb6d29 100755 --- a/xCAT-client/podchecker +++ b/xCAT-client/podchecker @@ -1,6 +1,6 @@ #!/usr/bin/perl - eval 'exec perl -S $0 "$@"' - if 0; +eval 'exec perl -S $0 "$@"' + if 0; ############################################################################# # podchecker -- command to invoke the podchecker function in Pod::Checker # @@ -11,6 +11,7 @@ ############################################################################# use strict; + #use diagnostics; =head1 NAME @@ -98,15 +99,15 @@ use Getopt::Long; my %options; ## Parse options -GetOptions(\%options, qw(help man warnings+ nowarnings)) || pod2usage(2); -pod2usage(1) if ($options{help}); -pod2usage(-verbose => 2) if ($options{man}); +GetOptions(\%options, qw(help man warnings+ nowarnings)) || pod2usage(2); +pod2usage(1) if ($options{help}); +pod2usage(-verbose => 2) if ($options{man}); -if($options{nowarnings}) { - $options{warnings} = 0; +if ($options{nowarnings}) { + $options{warnings} = 0; } -elsif(!defined $options{warnings}) { - $options{warnings} = 1; # default is warnings on +elsif (!defined $options{warnings}) { + $options{warnings} = 1; # default is warnings on } ## Dont default to STDIN if connected to a terminal @@ -114,27 +115,29 @@ pod2usage(2) if ((@ARGV == 0) && (-t STDIN)); ## Invoke podchecker() my $status = 0; -@ARGV = qw(-) unless(@ARGV); +@ARGV = qw(-) unless (@ARGV); for my $podfile (@ARGV) { - if($podfile eq '-') { - $podfile = '<&STDIN'; + if ($podfile eq '-') { + $podfile = '<&STDIN'; } - elsif(-d $podfile) { - warn "podchecker: Warning: Ignoring directory '$podfile'\n"; - next; + elsif (-d $podfile) { + warn "podchecker: Warning: Ignoring directory '$podfile'\n"; + next; } my $errors = podchecker($podfile, undef, '-warnings' => $options{warnings}); - if($errors > 0) { + if ($errors > 0) { + # errors occurred $status = 1; printf STDERR ("%s has %d pod syntax %s.\n", - $podfile, $errors, - ($errors == 1) ? 'error' : 'errors'); + $podfile, $errors, + ($errors == 1) ? 'error' : 'errors'); } - elsif($errors < 0) { + elsif ($errors < 0) { + # no pod found - $status = 2 unless($status); + $status = 2 unless ($status); print STDERR "$podfile does not contain any pod commands.\n"; } else { diff --git a/xCAT-client/sbin/dumpxCATdb b/xCAT-client/sbin/dumpxCATdb index 63aae579b..9bf6527a9 100644 --- a/xCAT-client/sbin/dumpxCATdb +++ b/xCAT-client/sbin/dumpxCATdb @@ -7,9 +7,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use Getopt::Long; @@ -33,31 +33,31 @@ use strict; my $rc = 0; my $cmd; &parse_args; -if ($::BINARY) { # not using xCAT to dump, using the database utility - my $DBname = xCAT::Utils->get_DBName; - if ($DBname eq "DB2") { - $rc=&DB2_bindump; - if ($rc == 0) { - xCAT::MsgUtils->message("I", "Backup Complete."); - } else { - xCAT::MsgUtils->message("I", "Backup Failed."); - } - exit $rc; - } else { - if ($DBname eq "PG") { - $rc=&PG_bindump; - if ($rc == 0) { - xCAT::MsgUtils->message("I", "Backup Complete."); - } else { - xCAT::MsgUtils->message("I", "Backup Failed."); - } - exit $rc; - } else { - xCAT::MsgUtils->message("E", - "Binary dump (-b) is not supported for $DBname"); - exit 1; - } - } +if ($::BINARY) { # not using xCAT to dump, using the database utility + my $DBname = xCAT::Utils->get_DBName; + if ($DBname eq "DB2") { + $rc = &DB2_bindump; + if ($rc == 0) { + xCAT::MsgUtils->message("I", "Backup Complete."); + } else { + xCAT::MsgUtils->message("I", "Backup Failed."); + } + exit $rc; + } else { + if ($DBname eq "PG") { + $rc = &PG_bindump; + if ($rc == 0) { + xCAT::MsgUtils->message("I", "Backup Complete."); + } else { + xCAT::MsgUtils->message("I", "Backup Failed."); + } + exit $rc; + } else { + xCAT::MsgUtils->message("E", + "Binary dump (-b) is not supported for $DBname"); + exit 1; + } + } } @@ -66,50 +66,55 @@ my @output = xCAT::Utils->runcmd("tabdump", 0); if ($::RUNCMD_RC != 0) { # error xCAT::MsgUtils->message("E", - "Error running tabdump to get list of tables"); + "Error running tabdump to get list of tables"); exit 1; } + # Determine which table to skip my @output2; if ($ENV{'XCAT_SKIPTABLES'}) { - @output2=$ENV{'XCAT_SKIPTABLES'}; + @output2 = $ENV{'XCAT_SKIPTABLES'}; } else { - # read tables to skip from site.skiptables attribute - @output2=xCAT::TableUtils->get_site_attribute('skiptables'); + + # read tables to skip from site.skiptables attribute + @output2 = xCAT::TableUtils->get_site_attribute('skiptables'); } my @skiptbls; if (@output2) { - @skiptbls = split (/\,/,$output2[0]); + @skiptbls = split(/\,/, $output2[0]); } foreach my $table (@output) { # if not -a request , skip eventlog and auditlog - if ( (!$::ALL) && (($table =~ /^eventlog/) || ($table =~ /^auditlog/))) { - if ($::DUMPVERBOSE) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + if ((!$::ALL) && (($table =~ /^eventlog/) || ($table =~ /^auditlog/))) { + if ($::DUMPVERBOSE) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } - # skip teal tables - if ( $table =~ /^x_teal/ ) { - if ($::DUMPVERBOSE) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + + # skip teal tables + if ($table =~ /^x_teal/) { + if ($::DUMPVERBOSE) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } - # skip ISNM tables except isnm_config - if ( $table =~ /^isnm_perf/ ) { - if ($::DUMPVERBOSE) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + + # skip ISNM tables except isnm_config + if ($table =~ /^isnm_perf/) { + if ($::DUMPVERBOSE) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } + # skip any table in the site.skiptables attribute - if (grep(/^$table$/, @skiptbls)) { - if ($::DUMPVERBOSE) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + if (grep(/^$table$/, @skiptbls)) { + if ($::DUMPVERBOSE) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } $cmd = "tabdump -f $::PATH/$table.csv $table"; @@ -118,9 +123,9 @@ foreach my $table (@output) { # error xCAT::MsgUtils->message("E", "Error running $cmd, @errout"); } else { - if ($::DUMPVERBOSE) { - xCAT::MsgUtils->message("I", "Dumping $table"); - } + if ($::DUMPVERBOSE) { + xCAT::MsgUtils->message("I", "Dumping $table"); + } } } @@ -139,18 +144,18 @@ exit $rc; sub parse_args { my $msg; - my $usagemsg = - " dumpxCATdb -h \n dumpxCATdb -v \n dumpxCATdb [-a] [-V] <-p> [path to backup directory] \n dumpxCATdb -b [-V] <-p> [path to backup directory]"; + my $usagemsg = +" dumpxCATdb -h \n dumpxCATdb -v \n dumpxCATdb [-a] [-V] <-p> [path to backup directory] \n dumpxCATdb -b [-V] <-p> [path to backup directory]"; Getopt::Long::Configure("posix_default"); Getopt::Long::Configure("no_gnu_compat"); Getopt::Long::Configure("bundling"); if ( !GetOptions( - 'a|all' => \$::ALL, - 'b|bin' => \$::BINARY, + 'a|all' => \$::ALL, + 'b|bin' => \$::BINARY, 'p|path=s' => \$::PATH, 'h|help' => \$::HELP, - 'V|verbose' => \$::DUMPVERBOSE, + 'V|verbose' => \$::DUMPVERBOSE, 'v|version' => \$::VERSION ) @@ -176,16 +181,16 @@ sub parse_args xCAT::MsgUtils->message("E", $msg); exit 1; } - if (!( -e $::PATH)) { - my $msg = " Creating $::PATH for database dump"; - xCAT::MsgUtils->message("I", $msg); - my @output = xCAT::Utils->runcmd("mkdir -p $::PATH", 0); - if ($::RUNCMD_RC != 0) - { # error - xCAT::MsgUtils->message("E", - "Error running mkdir -p $::PATH"); - exit 1; - } + if (!(-e $::PATH)) { + my $msg = " Creating $::PATH for database dump"; + xCAT::MsgUtils->message("I", $msg); + my @output = xCAT::Utils->runcmd("mkdir -p $::PATH", 0); + if ($::RUNCMD_RC != 0) + { # error + xCAT::MsgUtils->message("E", + "Error running mkdir -p $::PATH"); + exit 1; + } } } @@ -199,69 +204,71 @@ sub parse_args =cut #----------------------------------------------------------------------------- -sub DB2_bindump +sub DB2_bindump { my $msg; - my $rc=0; + my $rc = 0; + # check to see if they are setup to do an online dump # Database has to have defined logretain RECOVERY and there - # must already been taken an offline backup. - my $cmd="db2 get database configuration for xcatdb > /tmp/db2output"; - $rc = &rundb2cmd($cmd); # must su to xcatdb + # must already been taken an offline backup. + my $cmd = "db2 get database configuration for xcatdb > /tmp/db2output"; + $rc = &rundb2cmd($cmd); # must su to xcatdb if ($rc != 0) { - xCAT::MsgUtils->message("E", " $cmd error."); - return 1; + xCAT::MsgUtils->message("E", " $cmd error."); + return 1; } # check to see if they setup log recover $cmd = " egrep -i \"Log retain for recovery enabled\" /tmp/db2output"; - my @output=xCAT::Utils->runcmd($cmd, -1); + my @output = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "Log retain for recovery enabled (LOGRETAIN) = RECOVERY must be set to perform ONLINE Backups and one ONLINE backup must have been taken. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); - return 1; - } else { # check to see if LOGRETAIN is ON - if (!grep(/ = RECOVERY/, @output)) { - xCAT::MsgUtils->message("E", "Log retain for recovery enabled (LOGRETAIN) = RECOVERY must be set to perform ONLINE Backups and one ONLINE backup must have been taken. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); - return 1; - } + xCAT::MsgUtils->message("E", "Log retain for recovery enabled (LOGRETAIN) = RECOVERY must be set to perform ONLINE Backups and one ONLINE backup must have been taken. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); + return 1; + } else { # check to see if LOGRETAIN is ON + if (!grep(/ = RECOVERY/, @output)) { + xCAT::MsgUtils->message("E", "Log retain for recovery enabled (LOGRETAIN) = RECOVERY must be set to perform ONLINE Backups and one ONLINE backup must have been taken. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); + return 1; + } } - - # check to see if they have one backup - $cmd = " ls $::PATH"; - @output=xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "One ONLINE backup must have been taken and exist in $::PATH. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); - return 1; - } else { # check to see if LOGRETAIN is ON - if (!grep(/XCATDB/, @output)) { - xCAT::MsgUtils->message("E", "One ONLINE backup must have been taken and exist in $::PATH. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); - return 1; - } - } - - # finally all checks ok, can take an ONLINE backup - # get password from cfgloc - - my $cmd="cat /etc/xcat/cfgloc"; - my $info=xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); - return 1; - } - chomp($info); - my ($db,$inst,$pw) = split(/\|/, $info); - my $cmd=" db2 backup db xcatdb user xcatdb using $pw ONLINE to $::PATH"; - $rc = &rundb2cmd($cmd); # must su to xcatdb + # check to see if they have one backup + $cmd = " ls $::PATH"; + @output = xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC != 0) { + xCAT::MsgUtils->message("E", "One ONLINE backup must have been taken and exist in $::PATH. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); + return 1; + } else { # check to see if LOGRETAIN is ON + if (!grep(/XCATDB/, @output)) { + xCAT::MsgUtils->message("E", "One ONLINE backup must have been taken and exist in $::PATH. See xCAT DB2 documentation. The section - Backup/Restore the database with DB2 Commands."); + return 1; + } + } + + # finally all checks ok, can take an ONLINE backup + # get password from cfgloc + + my $cmd = "cat /etc/xcat/cfgloc"; + my $info = xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC != 0) { + xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); + return 1; + } + chomp($info); + my ($db, $inst, $pw) = split(/\|/, $info); + + my $cmd = " db2 backup db xcatdb user xcatdb using $pw ONLINE to $::PATH"; + $rc = &rundb2cmd($cmd); # must su to xcatdb if ($rc != 0) { - xCAT::MsgUtils->message("E", " $cmd error."); - return 1; + xCAT::MsgUtils->message("E", " $cmd error."); + return 1; } return 0; - + } + #----------------------------------------------------------------------------- =head3 PG_bindump @@ -271,53 +278,57 @@ sub DB2_bindump =cut #----------------------------------------------------------------------------- -sub PG_bindump +sub PG_bindump { my $msg; - my $rc=0; - my $pgcmddir = "/usr/bin"; + my $rc = 0; + my $pgcmddir = "/usr/bin"; + # get path to Postgresql commands if running 9.X version my $cmd = "rpm -qa | grep postgresql"; - my @output=xCAT::Utils->runcmd($cmd, 0); + my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - my $message = - "\nPostgreSQL is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; - xCAT::MsgUtils->message("E", " $cmd failed. $message"); - exit(1); + my $message = +"\nPostgreSQL is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; + xCAT::MsgUtils->message("E", " $cmd failed. $message"); + exit(1); } + # check if 9.X release, setup different - if (grep(/postgresql9/, @output)) { # postgresql 9.x - # figure out which 9.x release and build path - # for example 9.x release /usr/pgsql-9.x/bin - my @parseout= split(/\-/, $output[0]); - my @ptflevel= split ("postgresql9",$parseout[0]); - my $postgres9=@ptflevel[1]; # set it to the PTF level - $pgcmddir = "/usr/pgsql-9.$postgres9/bin"; # pg cmds location + if (grep(/postgresql9/, @output)) { # postgresql 9.x + # figure out which 9.x release and build path + # for example 9.x release /usr/pgsql-9.x/bin + my @parseout = split(/\-/, $output[0]); + my @ptflevel = split("postgresql9", $parseout[0]); + my $postgres9 = @ptflevel[1]; # set it to the PTF level + $pgcmddir = "/usr/pgsql-9.$postgres9/bin"; # pg cmds location } + # Get database, admin from cfgloc file - my $cmd="cat /etc/xcat/cfgloc"; - my $info=xCAT::Utils->runcmd($cmd, -1); + my $cmd = "cat /etc/xcat/cfgloc"; + my $info = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); - return 1; + xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); + return 1; } - chomp($info); - my ($db,$admin,$pw) = split(/\|/, $info); - my ($info1,$info2) = split(/=/,$db); - my ($dbname,$host) = split(/;/,$info2); - + chomp($info); + my ($db, $admin, $pw) = split(/\|/, $info); + my ($info1, $info2) = split(/=/, $db); + my ($dbname, $host) = split(/;/, $info2); + # create backup file name - my $backupfile="$::PATH/pgbackup.$$"; - my $cmd="$pgcmddir/pg_dump $dbname -f $backupfile -U postgres -F custom"; - my $info=xCAT::Utils->runcmd($cmd, -1); + my $backupfile = "$::PATH/pgbackup.$$"; + my $cmd = "$pgcmddir/pg_dump $dbname -f $backupfile -U postgres -F custom"; + my $info = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "$cmd failed"); - return 1; + xCAT::MsgUtils->message("E", "$cmd failed"); + return 1; } return 0; - + } + #----------------------------------------------------------------------------- =head3 rundb2cmd @@ -327,6 +338,7 @@ sub PG_bindump Input: command =cut + #----------------------------------------------------------------------------- sub rundb2cmd { diff --git a/xCAT-client/sbin/restorexCATdb b/xCAT-client/sbin/restorexCATdb index b40346a48..894ab8eb5 100644 --- a/xCAT-client/sbin/restorexCATdb +++ b/xCAT-client/sbin/restorexCATdb @@ -7,9 +7,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use Getopt::Long; @@ -34,32 +34,33 @@ use strict; my $rc = 0; &parse_args; -if ($::BINARY) { # not using xCAT to dump, using the database utility - my $DBname = xCAT::Utils->get_DBName; - if ($DBname eq "DB2") { - $rc=&DB2_binrestore; - if ($rc == 0) { - xCAT::MsgUtils->message("I", "Restore Complete. You can now restart the daemons."); - } else { - xCAT::MsgUtils->message("E", "Restore Failed."); - } - exit $rc; - } else { - if ($DBname eq "PG") { - $rc=&PG_binrestore; - if ($rc == 0) { - xCAT::MsgUtils->message("I", "Restore Complete."); - } else { - xCAT::MsgUtils->message("I", "Restore Failed."); - } - exit $rc; - } else { - xCAT::MsgUtils->message("E", - "Binary dump (-b) is not supported for $DBname"); - exit 1; - } - } +if ($::BINARY) { # not using xCAT to dump, using the database utility + my $DBname = xCAT::Utils->get_DBName; + if ($DBname eq "DB2") { + $rc = &DB2_binrestore; + if ($rc == 0) { + xCAT::MsgUtils->message("I", "Restore Complete. You can now restart the daemons."); + } else { + xCAT::MsgUtils->message("E", "Restore Failed."); + } + exit $rc; + } else { + if ($DBname eq "PG") { + $rc = &PG_binrestore; + if ($rc == 0) { + xCAT::MsgUtils->message("I", "Restore Complete."); + } else { + xCAT::MsgUtils->message("I", "Restore Failed."); + } + exit $rc; + } else { + xCAT::MsgUtils->message("E", + "Binary dump (-b) is not supported for $DBname"); + exit 1; + } + } } + # read all the *.csv files from the input directory and restore the database opendir DIRPATH, $::PATH; if ($? != 0) @@ -68,11 +69,12 @@ if ($? != 0) xCAT::MsgUtils->message("E", $msg); exit 1; } + # read tables to skip during restore from site.skiptables attribute -my @output2=xCAT::TableUtils->get_site_attribute('skiptables'); +my @output2 = xCAT::TableUtils->get_site_attribute('skiptables'); my @skiptbls; if (@output2) { - @skiptbls = split (/\,/,$output2[0]); + @skiptbls = split(/\,/, $output2[0]); } my @files = readdir(DIRPATH); @@ -83,38 +85,40 @@ foreach my $table (@files) my $tablename = $::PATH; $tablename .= "/"; $tablename .= $table; - if ( (!$::ALL) && (($table =~ /^eventlog/) || ($table =~ /^auditlog/))) { - - if ($::VERBOSEREST) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + if ((!$::ALL) && (($table =~ /^eventlog/) || ($table =~ /^auditlog/))) { + + if ($::VERBOSEREST) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } + # skip teal tables - if ( $table =~ /^x_teal/ ) { - if ($::VERBOSEREST) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + if ($table =~ /^x_teal/) { + if ($::VERBOSEREST) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } + # skip ISNM tables except isnm_config - if ( $table =~ /^isnm_perf/ ) { - if ($::DUMPVERBOSE) { - xCAT::MsgUtils->message("I", "Skipping $table\n"); - } - next; + if ($table =~ /^isnm_perf/) { + if ($::DUMPVERBOSE) { + xCAT::MsgUtils->message("I", "Skipping $table\n"); + } + next; } # skip and table in the site.skiptables attribute if (@skiptbls) { - my ($tmptable,$suffix) = split(/\./,$table); - chomp $tmptable; - if (grep(/^$tmptable$/, @skiptbls)) { - if ($::VERBOSEREST) { - xCAT::MsgUtils->message("I", "Skipping $tmptable\n"); + my ($tmptable, $suffix) = split(/\./, $table); + chomp $tmptable; + if (grep(/^$tmptable$/, @skiptbls)) { + if ($::VERBOSEREST) { + xCAT::MsgUtils->message("I", "Skipping $tmptable\n"); + } + next; } - next; - } } my $cmd = "tabrestore $tablename"; @@ -123,9 +127,9 @@ foreach my $table (@files) { # error xCAT::MsgUtils->message("E", "Error running $cmd, @errout\n"); } else { - if ($::VERBOSEREST) { - xCAT::MsgUtils->message("I", "Restoring $table.\n"); - } + if ($::VERBOSEREST) { + xCAT::MsgUtils->message("I", "Restoring $table.\n"); + } } } } @@ -145,20 +149,20 @@ exit $rc; sub parse_args { my $msg; - my $usagemsg = - " restorexCATdb -h \n restorexCATdb -v \n restorexCATdb [-a] [-V] <-p> [path to restore .csv files]\n restorexCATdb -b [-V] <-t> [timestamp on restore backup file] <-p> [path to restore backup file]"; + my $usagemsg = +" restorexCATdb -h \n restorexCATdb -v \n restorexCATdb [-a] [-V] <-p> [path to restore .csv files]\n restorexCATdb -b [-V] <-t> [timestamp on restore backup file] <-p> [path to restore backup file]"; Getopt::Long::Configure("posix_default"); Getopt::Long::Configure("no_gnu_compat"); Getopt::Long::Configure("bundling"); if ( !GetOptions( - 'a|all' => \$::ALL, - 'b|binary' => \$::BINARY, - 'p|path=s' => \$::PATH, - 't|timestamp=s' => \$::TIMESTAMP, - 'h|help' => \$::HELP, - 'V|verbose' => \$::VERBOSEREST, - 'v|version' => \$::VERSION + 'a|all' => \$::ALL, + 'b|binary' => \$::BINARY, + 'p|path=s' => \$::PATH, + 't|timestamp=s' => \$::TIMESTAMP, + 'h|help' => \$::HELP, + 'V|verbose' => \$::VERBOSEREST, + 'v|version' => \$::VERSION ) ) @@ -192,6 +196,7 @@ sub parse_args } } + #----------------------------------------------------------------------------- =head3 DB2_binrestore @@ -204,50 +209,54 @@ sub parse_args sub DB2_binrestore { my $msg; - my $rc=0; - if (!($::TIMESTAMP)){ - xCAT::MsgUtils->message("E", "To restore from a binary backup, the timestamp of the backup must be provided with the -t option."); - return 1; + my $rc = 0; + if (!($::TIMESTAMP)) { + xCAT::MsgUtils->message("E", "To restore from a binary backup, the timestamp of the backup must be provided with the -t option."); + return 1; } + # check to see if xcatd running. Cannot restore if it is my $cmd = "ps -ef | grep xcatd"; - my @output=xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC == 0) { # found something - if (grep(/xcatd: SSL listener/, @output)) { # xcatd running - xCAT::MsgUtils->message("E", "xcatd is still accessing the database. All applications accessing the DB2 database must be stopped before you can restore."); - return 1; + my @output = xCAT::Utils->runcmd($cmd, -1); + if ($::RUNCMD_RC == 0) { # found something + if (grep(/xcatd: SSL listener/, @output)) { # xcatd running + xCAT::MsgUtils->message("E", "xcatd is still accessing the database. All applications accessing the DB2 database must be stopped before you can restore."); + return 1; - } + } } + # get password from cfgloc - my $cmd="cat /etc/xcat/cfgloc"; - my $info=xCAT::Utils->runcmd($cmd, -1); + my $cmd = "cat /etc/xcat/cfgloc"; + my $info = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); - return 1; + xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); + return 1; } chomp($info); - my ($db,$inst,$pw) = split(/\|/, $info); + my ($db, $inst, $pw) = split(/\|/, $info); # Hopefully nothing else is accessing the database, so try restore - $cmd="db2 restore db xcatdb user xcatdb using $pw from $::PATH taken at $::TIMESTAMP"; - $rc = &rundb2cmd($cmd); # must su to xcatdb + $cmd = "db2 restore db xcatdb user xcatdb using $pw from $::PATH taken at $::TIMESTAMP"; + $rc = &rundb2cmd($cmd); # must su to xcatdb if ($rc != 0) { - xCAT::MsgUtils->message("E", " $cmd error."); - return 1; + xCAT::MsgUtils->message("E", " $cmd error."); + return 1; } + # Now roll forward any tranactions since the backup - $cmd="db2 rollforward database xcatdb to end of logs and complete"; - $rc = &rundb2cmd($cmd); # must su to xcatdb + $cmd = "db2 rollforward database xcatdb to end of logs and complete"; + $rc = &rundb2cmd($cmd); # must su to xcatdb if ($rc != 0) { - xCAT::MsgUtils->message("E", " $cmd error."); - return 1; + xCAT::MsgUtils->message("E", " $cmd error."); + return 1; } return 0; } + #----------------------------------------------------------------------------- =head3 PG_binrestore @@ -257,52 +266,56 @@ sub DB2_binrestore =cut #----------------------------------------------------------------------------- -sub PG_binrestore +sub PG_binrestore { my $msg; - my $rc=0; - my $pgcmddir = "/usr/bin"; + my $rc = 0; + my $pgcmddir = "/usr/bin"; + # get path to Postgresql commands if running 9.X version my $cmd = "rpm -qa | grep postgresql"; - my @output=xCAT::Utils->runcmd($cmd, 0); + my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - my $message = - "\nPostgreSQL is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; - xCAT::MsgUtils->message("E", " $cmd failed. $message"); - exit(1); + my $message = +"\nPostgreSQL is not installed. If on AIX, it should be first obtained from the xcat dependency tarballs and installed before running this command.\n If on Linux, install from the OS CDs."; + xCAT::MsgUtils->message("E", " $cmd failed. $message"); + exit(1); } + # check if 9.X release, setup different - if (grep(/postgresql9/, @output)) { # postgresql 9.x - # figure out which 9.x release and build path - # for example 9.x release /usr/pgsql-9.x/bin - my @parseout= split(/\-/, $output[0]); - my @ptflevel= split ("postgresql9",$parseout[0]); - my $postgres9=@ptflevel[1]; # set it to the PTF level - $pgcmddir = "/usr/pgsql-9.$postgres9/bin"; # pg cmds location + if (grep(/postgresql9/, @output)) { # postgresql 9.x + # figure out which 9.x release and build path + # for example 9.x release /usr/pgsql-9.x/bin + my @parseout = split(/\-/, $output[0]); + my @ptflevel = split("postgresql9", $parseout[0]); + my $postgres9 = @ptflevel[1]; # set it to the PTF level + $pgcmddir = "/usr/pgsql-9.$postgres9/bin"; # pg cmds location } + # Get database, admin from cfgloc file - my $cmd="cat /etc/xcat/cfgloc"; - my $info=xCAT::Utils->runcmd($cmd, -1); + my $cmd = "cat /etc/xcat/cfgloc"; + my $info = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); - return 1; + xCAT::MsgUtils->message("E", "Cannot read /etc/xcat/cfgloc."); + return 1; } - chomp($info); - my ($db,$admin,$pw) = split(/\|/, $info); - my ($info1,$info2) = split(/=/,$db); - my ($dbname,$host) = split(/;/,$info2); - + chomp($info); + my ($db, $admin, $pw) = split(/\|/, $info); + my ($info1, $info2) = split(/=/, $db); + my ($dbname, $host) = split(/;/, $info2); + # restore from backup file - my $cmd="$pgcmddir/pg_restore $::PATH -U postgres -d $dbname -c "; - my $info=xCAT::Utils->runcmd($cmd, -1); + my $cmd = "$pgcmddir/pg_restore $::PATH -U postgres -d $dbname -c "; + my $info = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message("E", "$cmd failed"); - return 1; + xCAT::MsgUtils->message("E", "$cmd failed"); + return 1; } return 0; - + } + #----------------------------------------------------------------------------- =head3 rundb2cmd @@ -312,6 +325,7 @@ sub PG_binrestore Input: command =cut + #----------------------------------------------------------------------------- sub rundb2cmd { diff --git a/xCAT-client/sbin/tabrestore b/xCAT-client/sbin/tabrestore index c0f5a7422..9d115a047 100755 --- a/xCAT-client/sbin/tabrestore +++ b/xCAT-client/sbin/tabrestore @@ -12,11 +12,11 @@ use xCAT::Utils; use Getopt::Long; sub usage { - print "Usage: tabrestore .csv\n"; - print " tabrestore -a .csv\n"; - print " tabrestore [-?|-h|--help]\n"; - print " tabrestore [-v|--version]\n"; - exit $_[0]; + print "Usage: tabrestore .csv\n"; + print " tabrestore -a .csv\n"; + print " tabrestore [-?|-h|--help]\n"; + print " tabrestore [-v|--version]\n"; + exit $_[0]; } #my $bname = basename($0); @@ -26,48 +26,48 @@ $cmdref->{command}->[0] = "tabrestore"; # Get the options my $HELP; if ( - !GetOptions( - 'h|?|help' => \$HELP, - 'v|version' => \$VERSION, - 'a|addrows' => \$ADDROWS, - ) -) + !GetOptions( + 'h|?|help' => \$HELP, + 'v|version' => \$VERSION, + 'a|addrows' => \$ADDROWS, + ) + ) { usage(1); } -my $arg=shift(@ARGV); +my $arg = shift(@ARGV); while ($arg =~ /^-/) { - push (@{$cmdref->{arg}}, $arg); - $arg=shift(@ARGV); + push(@{ $cmdref->{arg} }, $arg); + $arg = shift(@ARGV); } if ($VERSION) { - my $version = xCAT::Utils->Version(); - print "$version\n"; - exit 0; + my $version = xCAT::Utils->Version(); + print "$version\n"; + exit 0; } if ($HELP) { - usage; + usage; } if ($ADDROWS) { - $cmdref->{addrows}->[0] = "yes"; + $cmdref->{addrows}->[0] = "yes"; } -unless ($arg) { usage(2); } # no filename specified +unless ($arg) { usage(2); } # no filename specified # Open the specified table file and put its contents in the data key my $filename = $arg; -my $tabname = basename($filename); +my $tabname = basename($filename); $tabname =~ s/\..*//; $cmdref->{table}->[0] = $tabname; my $fh; -unless (open($fh,$filename)) { print "Error: Unable to open $arg for reading.\n"; exit 3; } +unless (open($fh, $filename)) { print "Error: Unable to open $arg for reading.\n"; exit 3; } while (<$fh>) { - push @{$cmdref->{data}},$_; + push @{ $cmdref->{data} }, $_; } -xCAT::Client::submit_request($cmdref,\&xCAT::Client::handle_response); +xCAT::Client::submit_request($cmdref, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-client/sbin/xdshcoll b/xCAT-client/sbin/xdshcoll index 53e6650d1..f7359eae7 100755 --- a/xCAT-client/sbin/xdshcoll +++ b/xCAT-client/sbin/xdshcoll @@ -6,20 +6,20 @@ while () { my $node; my $output; if (/:/) { - ($node,$output) = split /:/,$_,2; + ($node, $output) = split /:/, $_, 2; } else { - $node= "UNKNOWN"; + $node = "UNKNOWN"; $output = $_; } $output =~ s/^ //; - $output{$node}.=$output; + $output{$node} .= $output; } my %collated; foreach (keys %output) { - $collated{$output{$_}}->{$_}=1; + $collated{ $output{$_} }->{$_} = 1; } foreach (keys %collated) { - my $nodes = join(',',sort (keys %{$collated{$_}})); + my $nodes = join(',', sort (keys %{ $collated{$_} })); print "====================================\n"; print "$nodes\n"; print "====================================\n"; diff --git a/xCAT-client/share/xcat/tools/groupfiles4dsh b/xCAT-client/share/xcat/tools/groupfiles4dsh index 2e103b436..41e5f95ae 100755 --- a/xCAT-client/share/xcat/tools/groupfiles4dsh +++ b/xCAT-client/share/xcat/tools/groupfiles4dsh @@ -6,9 +6,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use Getopt::Long; @@ -79,7 +79,7 @@ sub parse_args my $msg; my $usagemsg; $usagemsg = - "groupfiles4dsh -h \ngroupfiles4dsh -v \ngroupfiles4dsh [-p] [path to group files directory]"; +"groupfiles4dsh -h \ngroupfiles4dsh -v \ngroupfiles4dsh [-p] [path to group files directory]"; Getopt::Long::Configure("posix_default"); Getopt::Long::Configure("no_gnu_compat"); Getopt::Long::Configure("bundling"); diff --git a/xCAT-client/xpod2man b/xCAT-client/xpod2man index 6888b5c0e..d7ee05ea9 100755 --- a/xCAT-client/xpod2man +++ b/xCAT-client/xpod2man @@ -8,17 +8,19 @@ # done relative to that. use strict; + #use lib '.'; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = "$ENV{'HOME'}/tmp"; if (system("mkdir -p $cachedir")) { die "Error: could not create $cachedir.\n"; } my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the cmd overview page. @@ -30,12 +32,12 @@ push @pods, "$poddir/man1/xcat.1.pod"; print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } @@ -44,15 +46,17 @@ my @dummyPods = createDummyPods($poddir, \@pods); # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + #print "$podfile, $htmlfile, $poddir, $htmldir\n"; convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -69,75 +73,80 @@ exit; # if that pod does not exist, create an empty one that will satisfy pod2html # keep track of all dummy pods created, so they can be removed later sub createDummyPods { - my ($poddir, $pods) = @_; - my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; - #print "Running cmd: ", $cmd, "\n"; - my @lines = `$cmd`; - if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } - #my @lines; - #system($cmd); - my @dummyPods; - foreach my $l (@lines) { - #print "$l\n"; - my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line - # The above line should create the array with every other entry being the man page name - # and every other entry is the section # (5 or 7) - my $cmd; - while ($cmd=shift @matches) { - #foreach my $m (@matches) { - my $section = shift @matches; - my $filename = "$poddir/man$section/$cmd.$section.pod"; - #print "$filename\n"; - if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } - } - } - - # Also add xcattest.1.pod and buildkit.1.pod, because the xcat.1.pod summary page refers to it - push @dummyPods, "$poddir/man1/xcattest.1.pod"; - push @dummyPods, "$poddir/man1/buildkit.1.pod"; - - # Create these empty files - print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; - mkdir "$poddir/man7"; - foreach my $d (@dummyPods) { - if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } - else { close TMP; } - } - - return @dummyPods; + my ($poddir, $pods) = @_; + my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; + + #print "Running cmd: ", $cmd, "\n"; + my @lines = `$cmd`; + if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } + + #my @lines; + #system($cmd); + my @dummyPods; + foreach my $l (@lines) { + + #print "$l\n"; + my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line + # The above line should create the array with every other entry being the man page name + # and every other entry is the section # (5 or 7) + my $cmd; + while ($cmd = shift @matches) { + + #foreach my $m (@matches) { + my $section = shift @matches; + my $filename = "$poddir/man$section/$cmd.$section.pod"; + + #print "$filename\n"; + if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } + } + } + + # Also add xcattest.1.pod and buildkit.1.pod, because the xcat.1.pod summary page refers to it + push @dummyPods, "$poddir/man1/xcattest.1.pod"; + push @dummyPods, "$poddir/man1/buildkit.1.pod"; + + # Create these empty files + print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; + mkdir "$poddir/man7"; + foreach my $d (@dummyPods) { + if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } + else { close TMP; } + } + + return @dummyPods; } # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the xcat man page that gives a summary description of each xcat cmd. sub writesummarypage { - my $file = shift; # relative path file name of the man page - # the rest of @_ contains the pod files that describe each cmd + my $file = shift; # relative path file name of the man page + # the rest of @_ contains the pod files that describe each cmd - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME B - extreme Cluster Administration Tool. @@ -168,56 +177,58 @@ i.e. all the commands in section 1, then the commands in section 3, etc. =over 12 EOS1 -# extract the summary for each cmd from its man page -foreach my $manpage (@_) { - my ($cmd, $sectionnum) = $manpage =~ /([^\/]+)\.(\d+)\.pod$/; - # Suck in the whole file, then we will parse it. - open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; - my @contents = ; - my $wholemanpage = join('', @contents); - close(MANPAGE); - # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline - my ($description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+\S+\s+(.+?)\n/si; - if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } - $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off - print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n".$description."\n"; -} + # extract the summary for each cmd from its man page + foreach my $manpage (@_) { + my ($cmd, $sectionnum) = $manpage =~ /([^\/]+)\.(\d+)\.pod$/; -# Artificially add the xcattest and buildkit cmds, -# because the xCAT-test and xCAT-buildkit rpms will add these -print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; -print FILE "\n=item L\n\nBuild product software kits to be installed in an xCAT cluster.\n"; + # Suck in the whole file, then we will parse it. + open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; + my @contents = ; + my $wholemanpage = join('', @contents); + close(MANPAGE); - print FILE <<"EOS3"; + # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline + my ($description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+\S+\s+(.+?)\n/si; + if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } + $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off + print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n" . $description . "\n"; + } + + # Artificially add the xcattest and buildkit cmds, + # because the xCAT-test and xCAT-buildkit rpms will add these + print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + print FILE "\n=item L\n\nBuild product software kits to be installed in an xCAT cluster.\n"; + + print FILE <<"EOS3"; =back EOS3 - close FILE; + close FILE; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man1:man3:man5:man7:man8", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man1:man3:man5:man7:man8", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } diff --git a/xCAT-confluent/xpod2man b/xCAT-confluent/xpod2man index 851a1853f..d49af7443 100755 --- a/xCAT-confluent/xpod2man +++ b/xCAT-confluent/xpod2man @@ -8,16 +8,18 @@ # done relative to that. use strict; + #use lib '.'; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = '/tmp'; my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the cmd overview page. @@ -28,12 +30,12 @@ my @pods = getPodList($poddir); print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } @@ -42,15 +44,17 @@ my @dummyPods = createDummyPods($poddir, \@pods); # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + #print "$podfile, $htmlfile, $poddir, $htmldir\n"; convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -67,72 +71,77 @@ exit; # if that pod does not exist, create an empty one that will satisfy pod2html # keep track of all dummy pods created, so they can be removed later sub createDummyPods { - my ($poddir, $pods) = @_; - my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; - #print "Running cmd: ", $cmd, "\n"; - my @lines = `$cmd`; - if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } - #my @lines; - #system($cmd); - my @dummyPods; - foreach my $l (@lines) { - #print "$l\n"; - my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line - # The above line should create the array with every other entry being the man page name - # and every other entry is the section # (5 or 7) - my $cmd; - while ($cmd=shift @matches) { - #foreach my $m (@matches) { - my $section = shift @matches; - my $filename = "$poddir/man$section/$cmd.$section.pod"; - #print "$filename\n"; - if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } - } - } - - - # Create these empty files - print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; - mkdir "$poddir/man7"; - foreach my $d (@dummyPods) { - if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } - else { close TMP; } - } - - return @dummyPods; + my ($poddir, $pods) = @_; + my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; + + #print "Running cmd: ", $cmd, "\n"; + my @lines = `$cmd`; + if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } + + #my @lines; + #system($cmd); + my @dummyPods; + foreach my $l (@lines) { + + #print "$l\n"; + my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line + # The above line should create the array with every other entry being the man page name + # and every other entry is the section # (5 or 7) + my $cmd; + while ($cmd = shift @matches) { + + #foreach my $m (@matches) { + my $section = shift @matches; + my $filename = "$poddir/man$section/$cmd.$section.pod"; + + #print "$filename\n"; + if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } + } + } + + + # Create these empty files + print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; + mkdir "$poddir/man7"; + foreach my $d (@dummyPods) { + if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } + else { close TMP; } + } + + return @dummyPods; } # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the xcat man page that gives a summary description of each xcat cmd. sub writesummarypage { - my $file = shift; # relative path file name of the man page - # the rest of @_ contains the pod files that describe each cmd + my $file = shift; # relative path file name of the man page + # the rest of @_ contains the pod files that describe each cmd - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME B - extreme Cluster Administration Tool. @@ -158,56 +167,58 @@ i.e. all the commands in section 1, then the commands in section 3, etc. =over 12 EOS1 -# extract the summary for each cmd from its man page -foreach my $manpage (@_) { - my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; - # Suck in the whole file, then we will parse it. - open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; - my @contents = ; - my $wholemanpage = join('', @contents); - close(MANPAGE); - # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline - my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; - if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } - if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } - $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off - $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off - print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n".$description."\n"; -} + # extract the summary for each cmd from its man page + foreach my $manpage (@_) { + my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; -# Artificially add the xcattest cmd, because the xCAT-test rpm will add this -print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + # Suck in the whole file, then we will parse it. + open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; + my @contents = ; + my $wholemanpage = join('', @contents); + close(MANPAGE); - print FILE <<"EOS3"; + # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline + my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; + if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } + if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } + $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off + $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off + print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n" . $description . "\n"; + } + + # Artificially add the xcattest cmd, because the xCAT-test rpm will add this + print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + + print FILE <<"EOS3"; =back EOS3 - close FILE; + close FILE; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man1", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man1", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } diff --git a/xCAT-genesis-builder/findmcprpms b/xCAT-genesis-builder/findmcprpms index 837a93568..31bd405b0 100755 --- a/xCAT-genesis-builder/findmcprpms +++ b/xCAT-genesis-builder/findmcprpms @@ -7,19 +7,19 @@ my $genesisrpm = shift @ARGV; my %rpms; my @files = `rpm -qlp $genesisrpm`; my $total = scalar(@files); -my $i = 0; +my $i = 0; foreach my $f (@files) { - $i++; - print "$i/$total\r"; - chomp($f); - if ($f !~ m|/opt/xcat/share/xcat/netboot/genesis/x86_64/fs|) { next; } - $f =~ s|^/opt/xcat/share/xcat/netboot/genesis/x86_64/fs||; - if (!$f || !(-e $f)) { next; } # there are files dracut creates that are not part of an rpm - my $rpm = `rpm -q --whatprovides $f`; - if ($?) { next; } # there are files dracut creates that are not part of an rpm - #print '.'; # show progress - chomp($rpm); - $rpms{$rpm} = 1; + $i++; + print "$i/$total\r"; + chomp($f); + if ($f !~ m|/opt/xcat/share/xcat/netboot/genesis/x86_64/fs|) { next; } + $f =~ s|^/opt/xcat/share/xcat/netboot/genesis/x86_64/fs||; + if (!$f || !(-e $f)) { next; } # there are files dracut creates that are not part of an rpm + my $rpm = `rpm -q --whatprovides $f`; + if ($?) { next; } # there are files dracut creates that are not part of an rpm + #print '.'; # show progress + chomp($rpm); + $rpms{$rpm} = 1; } print "\n"; foreach my $r (sort keys %rpms) { print "$r\n"; } diff --git a/xCAT-probe/subcmds/discovery b/xCAT-probe/subcmds/discovery index 38359562b..a89626981 100755 --- a/xCAT-probe/subcmds/discovery +++ b/xCAT-probe/subcmds/discovery @@ -293,7 +293,7 @@ sub get_node_ip { } foreach my $node (keys %nodecheckrst) { - probe_utils->send_msg("$output", "d", "$node : $nodecheckrst{$node}{error}") if(exists($nodecheckrst{$node}{error})); + probe_utils->send_msg("$output", "d", "$node : $nodecheckrst{$node}{error}") if (exists($nodecheckrst{$node}{error})); } return %nodeip; @@ -379,7 +379,7 @@ sub dhcp_dynamic_range_check { } else { push @dynamic_range, "$2-$1"; } - + } } @@ -413,16 +413,16 @@ sub dhcp_dynamic_range_check { probe_utils->send_msg("$output", "d", "Dynamic range for net $net is @{$subnet_hash{$net}}.") if ($verbose); if (%node_ip) { - foreach my $node (keys %node_ip) { - foreach my $dr (@{$subnet_hash{$net}}) { - my @dr_ip = split(/-/, $dr); + foreach my $node (keys %node_ip) { + foreach my $dr (@{ $subnet_hash{$net} }) { + my @dr_ip = split(/-/, $dr); - if (compare_ip_value($dr_ip[0], $node_ip{$node}) and compare_ip_value($node_ip{$node}, $dr_ip[1])) { - probe_utils->send_msg("$output", "d", "$node ip $node_ip{$node} is conflicting with dynamic range.") if ($verbose); - $rst = 1; - } - } - } + if (compare_ip_value($dr_ip[0], $node_ip{$node}) and compare_ip_value($node_ip{$node}, $dr_ip[1])) { + probe_utils->send_msg("$output", "d", "$node ip $node_ip{$node} is conflicting with dynamic range.") if ($verbose); + $rst = 1; + } + } + } } } else { probe_utils->send_msg("$output", "d", "Dynamic range for net $net did not be configured.") if ($verbose); @@ -1015,17 +1015,17 @@ sub do_monitor { my $computerpid; my $varlogpid; my $rst = 0; - { #important to hold a block - if(! -e "$varlogmsg"){ + { #important to hold a block + if (!-e "$varlogmsg") { probe_utils->send_msg("$output", "w", "$varlogmsg doesn't exist"); } - if(! -e "$clusterlog"){ + if (!-e "$clusterlog") { probe_utils->send_msg("$output", "w", "$clusterlog doesn't exist"); } - if(! -e "$computelog"){ + if (!-e "$computelog") { probe_utils->send_msg("$output", "w", "$computelog doesn't exist"); } - if(! -e "$httplog"){ + if (!-e "$httplog") { probe_utils->send_msg("$output", "w", "$httplog doesn't exist"); } @@ -1092,7 +1092,7 @@ sub do_monitor { probe_utils->send_msg("$output", "o", "All nodes need to monitor have finished discovery process"); } last; - } + } sleep 0.01; } &dump_history; diff --git a/xCAT-probe/subcmds/image b/xCAT-probe/subcmds/image index 68316ba74..2dc104ab9 100755 --- a/xCAT-probe/subcmds/image +++ b/xCAT-probe/subcmds/image @@ -8,6 +8,7 @@ use probe_utils; use File::Basename; use Net::Ping; use Getopt::Long qw(:config no_ignore_case); + #use Data::Dumper; use warnings; @@ -74,7 +75,8 @@ unless (defined($CONSISTENCY_CHECK) || defined($DEFINITION_CHECK)) { } if (scalar(@ARGV) >= 1) { - # After processing all the expected flags and arguments, + + # After processing all the expected flags and arguments, # there is still left over stuff on the command line probe_utils->send_msg("$output", "f", "Invalid flag or parameter: @ARGV"); probe_utils->send_msg("$output", "d", "$::USAGE"); @@ -90,20 +92,22 @@ my %node_defined_image_uuid_hash; my %node_defined_image_name_hash; my %osimage_defined_provmethod_hash; -my $all_nodes_provmethod = `lsdef -i provmethod -c $noderange`; +my $all_nodes_provmethod = `lsdef -i provmethod -c $noderange`; my $all_osimage_provmethod = `lsdef -t osimage -i provmethod,rootimgdir -c`; chomp($all_nodes_provmethod); -my @all_nodes_provmethod_lines = split("[\n\r]", $all_nodes_provmethod); +my @all_nodes_provmethod_lines = split("[\n\r]", $all_nodes_provmethod); my @all_osimage_provmethod_lines = split("[\n\r]", $all_osimage_provmethod); if ($all_nodes_provmethod =~ /Usage:/) { + # lsdef command displayed a Usage message. Must be some noderange formatting problem. # Issue a warning and exit. probe_utils->send_msg("$output", "w", "Can not get a list of nodes from specified noderange."); exit 1; } -if (scalar(@all_nodes_provmethod_lines) <=0) { +if (scalar(@all_nodes_provmethod_lines) <= 0) { + # There were no nodes matching the noderange. Issue a warning and exit. probe_utils->send_msg("$output", "w", "No nodes matching the noderange were found."); exit 1; @@ -117,22 +121,25 @@ foreach (@all_osimage_provmethod_lines) { # First, extract diskless nodes foreach (@all_nodes_provmethod_lines) { + # Get osimage name for the node my ($node_name, $junk, $node_osimage_name) = split "[:=]", $_; chomp($node_osimage_name); - + if (length($node_osimage_name) > 0) { + # Get provmethod and rootimgdir for the osimage - my $osimage_provmethod_type = $osimage_defined_provmethod_hash{$node_osimage_name . ": provmethod"}; - my $rootimagedir= $osimage_defined_provmethod_hash{$node_osimage_name . ": rootimgdir"}; + my $osimage_provmethod_type = $osimage_defined_provmethod_hash{ $node_osimage_name . ": provmethod" }; + my $rootimagedir = $osimage_defined_provmethod_hash{ $node_osimage_name . ": rootimgdir" }; chomp($osimage_provmethod_type) if ($osimage_provmethod_type); - chomp($rootimagedir) if ($rootimagedir); + chomp($rootimagedir) if ($rootimagedir); # Check if it is netboot, meaning diskless if ($osimage_provmethod_type && $osimage_provmethod_type eq 'netboot') { push(@diskless_nodes, $node_name); probe_utils->send_msg("$output", "o", "$node_name is diskless") if ($VERBOSE); if (length($rootimagedir) > 0) { + # For this diskless node, get UUID from rootimg directory xcatinfo file of the provmethod osimage my $xcatinfo_file = $rootimagedir . "/rootimg/opt/xcat/xcatinfo"; if (-r $xcatinfo_file) { @@ -149,27 +156,29 @@ foreach (@all_nodes_provmethod_lines) { } else { probe_utils->send_msg("$output", "w", "$node_name is not diskless. No image consistency verification will be performed."); - } + } } else { probe_utils->send_msg("$output", "w", "$node_name has no provision method defined. No image consistency verification will be performed."); } } -if (scalar(@diskless_nodes) <=0) { +if (scalar(@diskless_nodes) <= 0) { + # There were no diskless nodes found. Issue a warning and exit. probe_utils->send_msg("$output", "w", "No diskless compute nodes were found."); exit 1; } -if (scalar(@diskless_nodes) <=0) { +if (scalar(@diskless_nodes) <= 0) { + # There were no diskless nodes found. Issue a warning and exit. probe_utils->send_msg("$output", "w", "No diskless compute nodes were found"); exit 1; } # Next, check if all diskless nodes are pingable -my $ping_hosts = join ",",@diskless_nodes; +my $ping_hosts = join ",", @diskless_nodes; my $pping_output = `pping $ping_hosts`; chomp($pping_output); my @pping_lines = split("[\n\r]", $pping_output); @@ -186,13 +195,15 @@ foreach (@pping_lines) { } } -if (scalar(@pingable_nodes) <=0) { +if (scalar(@pingable_nodes) <= 0) { + # There were no pingable, diskless nodes found. Issue a warning and exit. probe_utils->send_msg("$output", "w", "No diskless, pingable compute nodes were found"); exit 1; } if ((scalar(@pingable_nodes) == 1) && ($CONSISTENCY_CHECK)) { + # There was only one node in noderange and comparison check was requested. # Nothing to compare the single node to. probe_utils->send_msg("$output", "w", "Comparison check for a single diskless pingable node will not be performed. Minimum of 2 nodes are needed for that."); @@ -229,9 +240,9 @@ foreach (@xdsh_UUID_lines) { # It is possible that some older version xCAT compute nodes will not have an IMAGEUUID line in # the xcatinfo file, for those nodes insert $na as the running UUID value foreach (@pingable_nodes) { - unless (exists($node_running_image_uuid_hash{$_})) { + unless (exists($node_running_image_uuid_hash{$_})) { $node_running_image_uuid_hash{$_} = $na; - } + } } # Build a hash of key="hostname", value="running OS image name" @@ -277,6 +288,7 @@ if ($DEFINITION_CHECK) { probe_utils->send_msg("$output", "f", "$msg"); } if (scalar(@pingable_nodes) eq $success_nodes) { + # All pingable nodes were tested with success probe_utils->send_msg("$output", "o", "OS image installed on each diskless compute node matches the image defined for it on management node"); } diff --git a/xCAT-probe/subcmds/osdeploy b/xCAT-probe/subcmds/osdeploy index 3040efa22..dabbd16fe 100755 --- a/xCAT-probe/subcmds/osdeploy +++ b/xCAT-probe/subcmds/osdeploy @@ -41,6 +41,7 @@ Options: "; #------------------------------------------ + =head3 Description: Check if all nodes are valid @@ -70,6 +71,7 @@ sub check_noderange { $nodecheckrst{$currentnode}{"error"} = "Could not find node definition"; $rst = 1; } elsif ($_ =~ /^\s*Object name: (\w+)/i) { + # 'rst' is used to check whether the node process finished, 1 is finished. $monitor_nodes{$1}{"rst"} = 0; $currentnode = $1; @@ -312,7 +314,8 @@ sub handle_cluster_msg { probe_utils->send_msg("$output", "f", "Node $node has finished it's os provision process"); push(@{ $rawdata{$node}{"history"} }, "Node $node os provision failed"); } elsif (exists($rawdata{$node}) and ($status eq "installing")) { - # record 'installing' status, to check when receive 'booted' status + + # record 'installing' status, to check when receive 'booted' status $monitor_nodes{$node}{"status"} = "installing"; } } diff --git a/xCAT-probe/subcmds/switch-macmap b/xCAT-probe/subcmds/switch-macmap index 5fe02e147..a92b0e886 100755 --- a/xCAT-probe/subcmds/switch-macmap +++ b/xCAT-probe/subcmds/switch-macmap @@ -31,12 +31,12 @@ Options: my $help; my $test; my $check; -my @nodes = (); +my @nodes = (); my $verbose = ''; -if (!GetOptions("help|h" => \$help, - "T" => \$test, - "c" => \$check, - "V" => \$verbose)) { +if (!GetOptions("help|h" => \$help, + "T" => \$test, + "c" => \$check, + "V" => \$verbose)) { probe_utils->send_msg("$output", "f", "Option not support"); probe_utils->send_msg("$output", "d", $::USAGE); exit 1; @@ -54,10 +54,10 @@ if ($help) { exit 0; } -if (! -d "$currdir/bin") { - mkpath("$currdir/bin/"); +if (!-d "$currdir/bin") { + mkpath("$currdir/bin/"); } -if (! -e "$currdir/bin/switchprobe") { +if (!-e "$currdir/bin/switchprobe") { link("$::XCATROOT/bin/xcatclient", "$currdir/bin/switchprobe"); } @@ -74,9 +74,9 @@ if ($test) { if ($verbose) { $verbose = "-V"; } -my $noderange = join(',',@nodes); +my $noderange = join(',', @nodes); my $normal_file = "/tmp/result_normal"; -my $error_file = "/tmp/result_error"; +my $error_file = "/tmp/result_error"; if (-f $normal_file) { unlink($normal_file); } @@ -84,7 +84,7 @@ if (-f $error_file) { unlink($error_file); } if ($check) { - `$currdir/bin/switchprobe $noderange -c $verbose >$normal_file 2>$error_file`; +`$currdir/bin/switchprobe $noderange -c $verbose >$normal_file 2>$error_file`; } else { `$currdir/bin/switchprobe $noderange $verbose >$normal_file 2>$error_file`; @@ -95,6 +95,7 @@ if (-f $error_file) { my $fd; open($fd, "<", "$normal_file"); my @fails = (); + # There is 2 kinds of error message: # 1. Error: The nodetype is not 'switch' for nodes: switch1 # Error: No switch configuration info find for switch-10-5-23-1 @@ -107,7 +108,7 @@ foreach (<$fd>) { } elsif (/^Error:\s*(.*)/) { push @fails, $1; } else { - push @fails, $_; + push @fails, $_; } } elsif (/^(\S*):\s*PASS/) { @@ -117,7 +118,7 @@ foreach (<$fd>) { probe_utils->send_msg("$output", "d", $_); } } -close ($fd); +close($fd); if (-f $normal_file) { unlink($normal_file); } diff --git a/xCAT-probe/subcmds/xcatmn b/xCAT-probe/subcmds/xcatmn index 0bfd233db..ed88011f8 100755 --- a/xCAT-probe/subcmds/xcatmn +++ b/xCAT-probe/subcmds/xcatmn @@ -75,7 +75,7 @@ if (!defined($installnic)) { exit 1; } -my $msg = "NIC $installnic exists on current server"; +my $msg = "NIC $installnic exists on current server"; my $nics = `ip addr show $installnic >/dev/null 2>&1`; if ($?) { probe_utils->send_msg("$output", "f", "$msg"); diff --git a/xCAT-probe/xcatprobe b/xCAT-probe/xcatprobe index de624515e..0ded99666 100755 --- a/xCAT-probe/xcatprobe +++ b/xCAT-probe/xcatprobe @@ -61,7 +61,7 @@ sub loadsubcmds { next; } else { my $desc = $2; - unless ($1 =~ /^ok$/) { + unless ($1 =~ /^ok$/) { print "skip $_ for doing '$_ -T' failed, invalid flag\n" if ($verbose); next; } @@ -233,7 +233,7 @@ my $pluginname; my $optnum = 0; foreach my $attr (@tmpargv) { if ($attr =~ /^-/) { - unless (grep(/^$attr$/, @supportopt)){ + unless (grep(/^$attr$/, @supportopt)) { print "Unsupported attribute: $attr\n"; print $::USAGE; exit 1; diff --git a/xCAT-rmc/scripts/check_ftpd b/xCAT-rmc/scripts/check_ftpd index d96ae8729..88c8a30b7 100755 --- a/xCAT-rmc/scripts/check_ftpd +++ b/xCAT-rmc/scripts/check_ftpd @@ -2,16 +2,17 @@ # IBM(c) 2010 EPL license http://www.eclipse.org/legal/epl-v10.html use strict; use locale; + BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use Getopt::Std; use IPC::SysV qw(IPC_STAT S_IRWXU IPC_PRIVATE IPC_CREAT S_IRUSR S_IWUSR ); use IPC::Msg; -my $rc=`lssrc -l -s inetd |grep " ftpd"|grep active 2>&1`; +my $rc = `lssrc -l -s inetd |grep " ftpd"|grep active 2>&1`; if ($? == 0) { print "ftpd is active"; } else { diff --git a/xCAT-rmc/scripts/check_xcatd b/xCAT-rmc/scripts/check_xcatd index 3de9036f9..b83b667cd 100755 --- a/xCAT-rmc/scripts/check_xcatd +++ b/xCAT-rmc/scripts/check_xcatd @@ -2,16 +2,17 @@ # IBM(c) 2010 EPL license http://www.eclipse.org/legal/epl-v10.html use strict; use locale; + BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use Getopt::Std; use IPC::SysV qw(IPC_STAT S_IRWXU IPC_PRIVATE IPC_CREAT S_IRUSR S_IWUSR ); use IPC::Msg; -my $rc=`$::XCATROOT/bin/lsxcatd -a 2>&1`; +my $rc = `$::XCATROOT/bin/lsxcatd -a 2>&1`; if ($?) { print "$rc"; } else { diff --git a/xCAT-rmc/scripts/email-hierarchical-batch-event b/xCAT-rmc/scripts/email-hierarchical-batch-event index 3733555da..eab151d1b 100755 --- a/xCAT-rmc/scripts/email-hierarchical-batch-event +++ b/xCAT-rmc/scripts/email-hierarchical-batch-event @@ -5,7 +5,7 @@ # Condition that is watching another Condition in a hierarchical cluster environment. # The condition that is being watched is a batch event. This script will go th the # node that has the watched condition, get the event batch file. And parse the file -# and then send email to a user with the detailed info of the events in the batch file. +# and then send email to a user with the detailed info of the events in the batch file. # The batch file will be then deleted if -d flag is set. # To use this script, create a Response that invokes this script with email address as the input. @@ -30,40 +30,40 @@ use POSIX qw(strftime); use File::Basename; use File::Path; -my $user=shift; -my $delete=shift; +my $user = shift; +my $delete = shift; if (($delete) && ($delete eq '-d')) { - $delete=1; + $delete = 1; } else { - $delete=0; + $delete = 0; } # Convert Severity and Type environment variables from integers to strings my @COND_SEVERITY = qw(Informational Warning Critical); -my @TYPE = ('event', 'rearm event'); -my $severity=$COND_SEVERITY[$ENV{ERRM_COND_SEVERITYID}]; -my $type=$TYPE[$ENV{ERRM_TYPEID }]; +my @TYPE = ('event', 'rearm event'); +my $severity = $COND_SEVERITY[ $ENV{ERRM_COND_SEVERITYID} ]; +my $type = $TYPE[ $ENV{ERRM_TYPEID} ]; # Parse the ERRM_VALUE attribute, which will contain the EventOccurred structured data variable from the Condition class # The fields in this structured data variable are documented below where we parse them out. my $event = $ENV{ERRM_VALUE}; -$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them +$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them # This parse the LastEvent -my ( # split the SD into the following fields: - $Saved, # batch file has been saved - $filename, # location of the batch file - $Size, # The size of the batch file - ) = split(/,/, $event); +my ( # split the SD into the following fields: + $Saved, # batch file has been saved + $filename, # location of the batch file + $Size, # The size of the batch file +) = split(/,/, $event); -my $sn_condname=$ENV{ERRM_RSRC_NAME}; -my $sn_name=$ENV{ERRM_NODE_NAME}; +my $sn_condname = $ENV{ERRM_RSRC_NAME}; +my $sn_name = $ENV{ERRM_NODE_NAME}; -my ( - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - ) = split(/,/, $ENV{ERRM_TIME}); +my ( + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime +) = split(/,/, $ENV{ERRM_TIME}); my $msg; $msg .= "The following $type occurred:\n"; @@ -71,69 +71,70 @@ $msg .= " Event Time: " . convertTime($EventTime) . "\n"; $msg .= " Condition name: $ENV{ERRM_COND_NAME}\n"; $msg .= " Severiry: $severity\n"; $msg .= " Condition being monitored: $sn_condname\n"; -$msg .= " Node where the condition was monitored: $sn_name\n"; # do we have to use $ERRM_NODE_NAMELIST here? +$msg .= " Node where the condition was monitored: $sn_name\n"; # do we have to use $ERRM_NODE_NAMELIST here? $msg .= " SN batch files name: $filename\n"; #copy the batch file from sn to mn $filename =~ s/"//g; -my $bn=basename($filename); +my $bn = basename($filename); #printf stderr "ful path :$filename\n"; #printf stderr "base name:$bn\n"; -my $dirname="/tmp/batch_process/"; -if (! -d $dirname) { +my $dirname = "/tmp/batch_process/"; +if (!-d $dirname) { mkdir($dirname); } my $cmd; -my $isHMC=0; +my $isHMC = 0; if ($filename =~ /\/home\/hscroot\/tmp/) { - $isHMC=1; - $cmd="scp hscroot\@$sn_name:$filename $dirname/$bn"; + $isHMC = 1; + $cmd = "scp hscroot\@$sn_name:$filename $dirname/$bn"; } else { - $cmd="scp $sn_name:$filename $dirname/$bn"; + $cmd = "scp $sn_name:$filename $dirname/$bn"; } -my $rc=`$cmd 2>&1`; +my $rc = `$cmd 2>&1`; if ($? != 0) { $msg .= "$rc\n"; } #now process the batch file open(FILE1, "<$dirname/$bn"); -readline(FILE1);#skip first 2 lines +readline(FILE1); #skip first 2 lines readline(FILE1); -my $line1=readline(FILE1); -my @aTemp=split(/=/, $line1); -my $num_events=$aTemp[1]; +my $line1 = readline(FILE1); +my @aTemp = split(/=/, $line1); +my $num_events = $aTemp[1]; close(FILE1); my $count; -for ($count = 1; $count <= $num_events; $count++) { - my $content=`sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $dirname/$bn`; - - my @content_array=split(/\n/, $content); - pop(@content_array); #get rid of last line - shift(@content_array); #get rid of firt line - - my %content_hash=(); - foreach(@content_array) { - /([^\=]+)\=(.*)/; - $content_hash{$1}=$2; - } - +for ($count = 1 ; $count <= $num_events ; $count++) { + my $content = `sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $dirname/$bn`; + + my @content_array = split(/\n/, $content); + pop(@content_array); #get rid of last line + shift(@content_array); #get rid of firt line + + my %content_hash = (); + foreach (@content_array) { + /([^\=]+)\=(.*)/; + $content_hash{$1} = $2; + } + my $event = "Event count: $count\n"; + #$event .= " Event time: " . $content_hash{ERRM_TIME} . "\n"; $event .= " Node where the event occurred: " . $content_hash{ERRM_NODE_NAMELIST} . "\n"; $event .= " Resource class: " . $content_hash{ERRM_RSRC_CLASS_PNAME} . "\n"; $event .= " Resource name: " . $content_hash{ERRM_RSRC_NAME} . "\n"; $event .= " Attribute name: " . $content_hash{ERRM_ATTR_PNAME} . "\n"; $event .= " Attribute value: " . $content_hash{ERRM_VALUE} . "\n\n"; - + $msg .= $event; -} - +} + #send the mail out `echo "$msg"| mail -s "xxx$severity $type: $ENV{ERRM_COND_NAME}" $user`; @@ -143,9 +144,9 @@ for ($count = 1; $count <= $num_events; $count++) { #remove the batch file on the sn if needed if ($delete) { if ($isHMC) { - `ssh -l hscroot $sn_name "rm $filename"`; + `ssh -l hscroot $sn_name "rm $filename"`; } else { - `ssh -l root $sn_name "rm $filename"`; + `ssh -l root $sn_name "rm $filename"`; } } @@ -154,6 +155,6 @@ exit; # convert time string sub convertTime { - my ($seconds, $micro) = split(/\./, $_[0]); - return strftime("%A %D %T", localtime($seconds)); + my ($seconds, $micro) = split(/\./, $_[0]); + return strftime("%A %D %T", localtime($seconds)); } diff --git a/xCAT-rmc/scripts/email-hierarchical-event b/xCAT-rmc/scripts/email-hierarchical-event index 0a4fbe1a2..9304fa775 100755 --- a/xCAT-rmc/scripts/email-hierarchical-event +++ b/xCAT-rmc/scripts/email-hierarchical-event @@ -28,65 +28,66 @@ use strict; use Getopt::Std; use POSIX qw(strftime); -my $user=shift; +my $user = shift; # Convert Severity and Type environment variables from integers to strings my @COND_SEVERITY = qw(Informational Warning Critical); -my @TYPE = ('event', 'rearm event'); -my $severity=$COND_SEVERITY[$ENV{ERRM_COND_SEVERITYID}]; -my $type=$TYPE[$ENV{ERRM_TYPEID }]; +my @TYPE = ('event', 'rearm event'); +my $severity = $COND_SEVERITY[ $ENV{ERRM_COND_SEVERITYID} ]; +my $type = $TYPE[ $ENV{ERRM_TYPEID} ]; # Parse the ERRM_VALUE attribute, which will contain the EventOccurred structured data variable from the Condition class # The fields in this structured data variable are documented below where we parse them out. my $event = $ENV{ERRM_VALUE}; -$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them +$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them # This parse the LastEvent -my ( # split the SD into the following fields: - $Occurred, # One if the condition has been triggered - $ErrNum, # Non-zero if there was in error in the event registration - $ErrMsg, # The string msg related to ErrNum - $EventFlags, # Bit mask giving some additional info about the event - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered - $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), - # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), - # this will be the FMS. - $NumAttrs, # Number of attr values from the resource returned in this event - $NumAttrsInExpr, # How many of the above were attributes in the event expression - $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added - # to LastEvent, this will be the element right after this one. - $AttrArray # This list of attribute names, types, and values - ) = split(/,/, $event, 12); +my ( # split the SD into the following fields: + $Occurred, # One if the condition has been triggered + $ErrNum, # Non-zero if there was in error in the event registration + $ErrMsg, # The string msg related to ErrNum + $EventFlags, # Bit mask giving some additional info about the event + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime + $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered + $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), + # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), + # this will be the FMS. + $NumAttrs, # Number of attr values from the resource returned in this event + $NumAttrsInExpr, # How many of the above were attributes in the event expression + $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added + # to LastEvent, this will be the element right after this one. + $AttrArray # This list of attribute names, types, and values +) = split(/,/, $event, 12); -my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list +my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list my ($ResourceName, $valuesMsg); -my $j = 0; # index into attrArray -for (my $i=0; $i<$NumAttrs; $i++) { - my $attrName = $attrArray[$j++]; - my $attrType = $attrArray[$j++]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. - my $attrValue = $attrArray[$j++]; - if ($attrName eq '"Name"') { $ResourceName = $attrValue; } - $valuesMsg .= " Attribute Value $i: $attrName = $attrValue\n"; +my $j = 0; # index into attrArray +for (my $i = 0 ; $i < $NumAttrs ; $i++) { + my $attrName = $attrArray[ $j++ ]; + my $attrType = $attrArray[ $j++ ]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. + my $attrValue = $attrArray[ $j++ ]; + if ($attrName eq '"Name"') { $ResourceName = $attrValue; } + $valuesMsg .= " Attribute Value $i: $attrName = $attrValue\n"; } if (!length($ResourceName)) { $ResourceName = '(unknown)'; } my $msg; $msg .= "The following $TYPE[$ENV{ERRM_TYPEID}] occurred:\n"; $msg .= " MN Condition: $ENV{ERRM_COND_NAME}\n"; -$msg .= " SN: $ENV{ERRM_NODE_NAME}\n"; # do we have to use $ERRM_NODE_NAMELIST here? +$msg .= " SN: $ENV{ERRM_NODE_NAME}\n"; # do we have to use $ERRM_NODE_NAMELIST here? $msg .= " SN Condition: $ENV{ERRM_RSRC_NAME}\n"; $msg .= " Node: $NodeName\n"; $msg .= " Resource Name: $ResourceName\n"; $msg .= " Event Time: " . convertTime($EventTime) . "\n"; if (length($valuesMsg)) { - $msg .= " Attributes that came in the event for condition $ENV{ERRM_RSRC_NAME} from node $NodeName for resource $ResourceName:\n"; - $msg .= $valuesMsg; + $msg .= " Attributes that came in the event for condition $ENV{ERRM_RSRC_NAME} from node $NodeName for resource $ResourceName:\n"; + $msg .= $valuesMsg; } + # Skipped the following: $ERRM_EXPR $ERRM_RSRC_CLASS_PNAME $ERRM_DATA_TYPE $ERRM_NODE_NAMELIST $ERRM_RSRC_TYPE `echo "$msg"| mail -s "$severity $type: $ENV{ERRM_COND_NAME}" $user`; @@ -95,6 +96,6 @@ exit; # convert time string sub convertTime { - my ($seconds, $micro) = split(/\./, $_[0]); - return strftime("%A %D %T", localtime($seconds)); + my ($seconds, $micro) = split(/\./, $_[0]); + return strftime("%A %D %T", localtime($seconds)); } diff --git a/xCAT-rmc/scripts/errmsgque b/xCAT-rmc/scripts/errmsgque index 358c148fe..eaf8b44d8 100755 --- a/xCAT-rmc/scripts/errmsgque +++ b/xCAT-rmc/scripts/errmsgque @@ -16,34 +16,35 @@ my $key = IPC::SysV::ftok("/var/adm/ras/errlog", $m); # my $message = join " ", @ARGV; # $msg->snd(1, "$message"); -my $message = join " ", @ARGV; +my $message = join " ", @ARGV; runcmd("/usr/bin/refsensor ErrorLogSensor String=\"$message\" 1>/dev/null 2>/dev/null", 0); -if($::RUNCMD_RC != 0){ - my $msg = new IPC::Msg($key, IPC_CREAT|S_IRUSR|S_IWUSR ); - my $stat = $msg->stat; - my $qcurrentlen = $$stat[5]; - if ($qcurrentlen >= 10000) - { - if (!-d "/var/opt/xcat_err_mon/") - { - my $cmd = "mkdir -p \"/var/opt/xcat_err_mon\""; - runcmd($cmd, -1); - } - open(FILE, ">>/var/opt/xcat_err_mon/errmsgqueerr.log"); - my $sdate = `/bin/date`; - chomp $sdate; - print FILE "$sdate:\n"; - print FILE "Can not write the message to queue because the queue is almost full, the message content is: $message\n\n\n"; - close FILE; - exit 0; - } - $msg->snd(1, "$message"); +if ($::RUNCMD_RC != 0) { + my $msg = new IPC::Msg($key, IPC_CREAT | S_IRUSR | S_IWUSR); + my $stat = $msg->stat; + my $qcurrentlen = $$stat[5]; + if ($qcurrentlen >= 10000) + { + if (!-d "/var/opt/xcat_err_mon/") + { + my $cmd = "mkdir -p \"/var/opt/xcat_err_mon\""; + runcmd($cmd, -1); + } + open(FILE, ">>/var/opt/xcat_err_mon/errmsgqueerr.log"); + my $sdate = `/bin/date`; + chomp $sdate; + print FILE "$sdate:\n"; + print FILE "Can not write the message to queue because the queue is almost full, the message content is: $message\n\n\n"; + close FILE; + exit 0; + } + $msg->snd(1, "$message"); } exit 0; #-------------------------------------------------------------------------------- + =head3 runcmd Run the given cmd and return the output in an array (already chopped). Alternatively, if this function is used in a scalar context, the output is joined into a single string @@ -69,72 +70,74 @@ exit 0; If refoutput is true, then the output will be returned as a reference to an array for efficiency. =cut + #-------------------------------------------------------------------------------- sub runcmd { - my ($cmd, $exitcode, $refoutput) = @_; - $::RUNCMD_RC = 0; - if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } - - my $outref = []; - @$outref = `$cmd`; - if ($?) - { - $::RUNCMD_RC = $? >> 8; - my $displayerror = 1; - my $rc; - if (defined($exitcode) && length($exitcode) && $exitcode != -2) + my ($cmd, $exitcode, $refoutput) = @_; + $::RUNCMD_RC = 0; + if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } + + my $outref = []; + @$outref = `$cmd`; + if ($?) { - if ($exitcode > 0) - { - $rc = $exitcode; - } # if not zero, exit with specified code - elsif ($exitcode <= 0) - { - $rc = ''; # if zero or negative, do not exit - if ($exitcode < 0) { $displayerror = 0; } - } + $::RUNCMD_RC = $? >> 8; + my $displayerror = 1; + my $rc; + if (defined($exitcode) && length($exitcode) && $exitcode != -2) + { + if ($exitcode > 0) + { + $rc = $exitcode; + } # if not zero, exit with specified code + elsif ($exitcode <= 0) + { + $rc = ''; # if zero or negative, do not exit + if ($exitcode < 0) { $displayerror = 0; } + } + } + else + { + $rc = $::RUNCMD_RC; + } # if exitcode not specified, use cmd exit code + if ($displayerror) + { + my $errmsg = ''; + if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) + { + $errmsg = "Segmentation fault $errmsg"; + } + else + { + # The error msgs from the -api cmds are pretty messy. Clean them up a little. + filterRmcApiOutput($cmd, $outref); + $errmsg = join('', @$outref); + chomp $errmsg; + } + print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + } + } + if ($refoutput) + { + chomp(@$outref); + return $outref; + } + elsif (wantarray) + { + chomp(@$outref); + return @$outref; } else { - $rc = $::RUNCMD_RC; - } # if exitcode not specified, use cmd exit code - if ($displayerror) - { - my $errmsg = ''; - if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) - { - $errmsg = "Segmentation fault $errmsg"; - } - else - { - # The error msgs from the -api cmds are pretty messy. Clean them up a little. - filterRmcApiOutput($cmd, $outref); - $errmsg = join('', @$outref); - chomp $errmsg; - } - print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + my $line = join('', @$outref); + chomp $line; + return $line; } - } - if ($refoutput) - { - chomp(@$outref); - return $outref; - } - elsif (wantarray) - { - chomp(@$outref); - return @$outref; - } - else - { - my $line = join('', @$outref); - chomp $line; - return $line; - } } #-------------------------------------------------------------------------------- + =head3 filterRmcApiOutput filter RMC Api Output Arguments: @@ -152,25 +155,26 @@ sub runcmd The error msgs from the RPM -api cmds are pretty messy. This routine cleans them up a little bit. =cut + #-------------------------------------------------------------------------------- sub filterRmcApiOutput { - my ($cmd, $outref) = @_; - if (!($cmd =~ m|^/usr/bin/\S+-api |)) { - return; - } # give as much info as possible, if verbose + my ($cmd, $outref) = @_; + if (!($cmd =~ m|^/usr/bin/\S+-api |)) { + return; + } # give as much info as possible, if verbose - # Figure out the output delimiter - my ($d) = $cmd =~ / -D\s+(\S+)/; - if (length($d)) { - $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes - # escape any chars perl pattern matching would intepret as special chars - $d =~ s/([\|\^\*\+\?\.])/\\$1/g; - } - else - { - $d = '::'; - } # this is the default output delimiter for the -api cmds - $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; + # Figure out the output delimiter + my ($d) = $cmd =~ / -D\s+(\S+)/; + if (length($d)) { + $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes + # escape any chars perl pattern matching would intepret as special chars + $d =~ s/([\|\^\*\+\?\.])/\\$1/g; + } + else + { + $d = '::'; + } # this is the default output delimiter for the -api cmds + $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; } diff --git a/xCAT-rmc/scripts/log-hierarchical-batch-event b/xCAT-rmc/scripts/log-hierarchical-batch-event index f4ed01a5b..8bf79ec91 100755 --- a/xCAT-rmc/scripts/log-hierarchical-batch-event +++ b/xCAT-rmc/scripts/log-hierarchical-batch-event @@ -5,7 +5,7 @@ # Condition that is watching another Condition in a hierarchical cluster environment. # The condition that is being watched is a batch event. This script will go th the # node that has the watched condition, get the event batch file. And parse the file -# and then send email to a user with the detailed info of the events in the batch file. +# and then send email to a user with the detailed info of the events in the batch file. # The batch file will be then deleted if -d flag is set. # To use this script, create a Response that invokes this script with user id as the input. @@ -31,123 +31,125 @@ use File::Basename; use File::Path; my $logfn = join(' ', @ARGV); -my $delete=0; +my $delete = 0; if ($logfn =~ /-d/) { - $delete=1; + $delete = 1; } -$logfn =~ s/-d//; #remove -d +$logfn =~ s/-d//; #remove -d # Convert Severity and Type environment variables from integers to strings my @COND_SEVERITY = qw(Informational Warning Critical); -my @TYPE = ('event', 'rearm event'); -my $severity=$COND_SEVERITY[$ENV{ERRM_COND_SEVERITYID}]; -my $type=$TYPE[$ENV{ERRM_TYPEID }]; +my @TYPE = ('event', 'rearm event'); +my $severity = $COND_SEVERITY[ $ENV{ERRM_COND_SEVERITYID} ]; +my $type = $TYPE[ $ENV{ERRM_TYPEID} ]; # Parse the ERRM_VALUE attribute, which will contain the EventOccurred structured data variable from the Condition class # The fields in this structured data variable are documented below where we parse them out. my $event = $ENV{ERRM_VALUE}; -$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them +$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them # This parse the LastEvent -my ( # split the SD into the following fields: - $Saved, # batch file has been saved - $filename, # location of the batch file - $Size, # The size of the batch file - ) = split(/,/, $event); +my ( # split the SD into the following fields: + $Saved, # batch file has been saved + $filename, # location of the batch file + $Size, # The size of the batch file +) = split(/,/, $event); -my $sn_condname=$ENV{ERRM_RSRC_NAME}; -my $sn_name=$ENV{ERRM_NODE_NAME}; +my $sn_condname = $ENV{ERRM_RSRC_NAME}; +my $sn_name = $ENV{ERRM_NODE_NAME}; -my ( - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - ) = split(/,/, $ENV{ERRM_TIME}); +my ( + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime +) = split(/,/, $ENV{ERRM_TIME}); -my $msg="===================================================================\n";; +my $msg = "===================================================================\n"; $msg .= " Event Time: " . convertTime($EventTime) . "\n"; $msg .= " Condition name: $ENV{ERRM_COND_NAME}\n"; $msg .= " Event Type: $type\n"; $msg .= " Severiry: $severity\n"; $msg .= " Condition being monitored: $sn_condname\n"; -$msg .= " Node where the condition was monitored: $sn_name\n"; # do we have to use $ERRM_NODE_NAMELIST here? +$msg .= " Node where the condition was monitored: $sn_name\n"; # do we have to use $ERRM_NODE_NAMELIST here? $msg .= " SN batch files name: $filename\n"; #copy the batch file from sn to mn $filename =~ s/"//g; -my $bn=basename($filename); +my $bn = basename($filename); #printf stderr "ful path :$filename\n"; #printf stderr "base name:$bn\n"; -my $dirname="/tmp/batch_process/"; -if (! -d $dirname) { +my $dirname = "/tmp/batch_process/"; +if (!-d $dirname) { mkdir($dirname); } my $cmd; -my $isHMC=0; +my $isHMC = 0; if ($filename =~ /\/home\/hscroot\/tmp/) { - $isHMC=1; - $cmd="scp hscroot\@$sn_name:$filename $dirname/$bn"; + $isHMC = 1; + $cmd = "scp hscroot\@$sn_name:$filename $dirname/$bn"; } else { - $cmd="scp $sn_name:$filename $dirname/$bn"; + $cmd = "scp $sn_name:$filename $dirname/$bn"; } -my $rc=`$cmd 2>&1`; +my $rc = `$cmd 2>&1`; if ($? != 0) { $msg .= "$rc\n"; } #now process the batch file open(FILE1, "<$dirname/$bn"); -readline(FILE1);#skip first 2 lines +readline(FILE1); #skip first 2 lines readline(FILE1); -my $line1=readline(FILE1); -my @aTemp=split(/=/, $line1); -my $num_events=$aTemp[1]; +my $line1 = readline(FILE1); +my @aTemp = split(/=/, $line1); +my $num_events = $aTemp[1]; close(FILE1); my $count; -for ($count = 1; $count <= $num_events; $count++) { - my $content=`sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $dirname/$bn`; - - my @content_array=split(/\n/, $content); - pop(@content_array); #get rid of last line - shift(@content_array); #get rid of firt line - - my %content_hash=(); - foreach(@content_array) { - /([^\=]+)\=(.*)/; - $content_hash{$1}=$2; - } - +for ($count = 1 ; $count <= $num_events ; $count++) { + my $content = `sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $dirname/$bn`; + + my @content_array = split(/\n/, $content); + pop(@content_array); #get rid of last line + shift(@content_array); #get rid of firt line + + my %content_hash = (); + foreach (@content_array) { + /([^\=]+)\=(.*)/; + $content_hash{$1} = $2; + } + my $event = "Event count: $count\n"; + #$event .= " Event time: " . $content_hash{ERRM_TIME} . "\n"; $event .= " Node where the event occurred: " . $content_hash{ERRM_NODE_NAMELIST} . "\n"; $event .= " Resource class: " . $content_hash{ERRM_RSRC_CLASS_PNAME} . "\n"; $event .= " Resource name: " . $content_hash{ERRM_RSRC_NAME} . "\n"; $event .= " Attribute name: " . $content_hash{ERRM_ATTR_PNAME} . "\n"; $event .= " Attribute value: " . $content_hash{ERRM_VALUE} . "\n\n"; - + $msg .= $event; -} - +} + #log the events -if (open (FILE, ">>$logfn")) { +if (open(FILE, ">>$logfn")) { print FILE "$msg\n"; - close (FILE); -} + close(FILE); +} + #delete the batch file on the mn `rm $dirname/$bn`; #remove the batch file on the sn if needed if ($delete) { if ($isHMC) { - `ssh -l hscroot $sn_name "rm $filename"`; + `ssh -l hscroot $sn_name "rm $filename"`; } else { - `ssh -l root $sn_name "rm $filename"`; + `ssh -l root $sn_name "rm $filename"`; } } @@ -156,6 +158,6 @@ exit; # convert time string sub convertTime { - my ($seconds, $micro) = split(/\./, $_[0]); - return strftime("%A %D %T", localtime($seconds)); + my ($seconds, $micro) = split(/\./, $_[0]); + return strftime("%A %D %T", localtime($seconds)); } diff --git a/xCAT-rmc/scripts/log-hierarchical-event b/xCAT-rmc/scripts/log-hierarchical-event index d7183fdcb..06a3bca0b 100755 --- a/xCAT-rmc/scripts/log-hierarchical-event +++ b/xCAT-rmc/scripts/log-hierarchical-event @@ -32,77 +32,77 @@ use File::Path; # Convert Severity and Type environment variables from integers to strings my @COND_SEVERITY = qw(Informational Warning Critical); -my @TYPE = ('Event', 'Rearm event'); -my $severity=$COND_SEVERITY[$ENV{ERRM_COND_SEVERITYID}]; -my $type=$TYPE[$ENV{ERRM_TYPEID }]; +my @TYPE = ('Event', 'Rearm event'); +my $severity = $COND_SEVERITY[ $ENV{ERRM_COND_SEVERITYID} ]; +my $type = $TYPE[ $ENV{ERRM_TYPEID} ]; my $filename = shift; # Parse the ERRM_VALUE attribute, which will contain the EventOccurred structured data variable from the Condition class # The fields in this structured data variable are documented below where we parse them out. my $event = $ENV{ERRM_VALUE}; -$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them +$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them # This parse the LastEvent -my ( # split the SD into the following fields: - $Occurred, # One if the condition has been triggered - $ErrNum, # Non-zero if there was in error in the event registration - $ErrMsg, # The string msg related to ErrNum - $EventFlags, # Bit mask giving some additional info about the event - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered - $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), - # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), - # this will be the FMS. - $NumAttrs, # Number of attr values from the resource returned in this event - $NumAttrsInExpr, # How many of the above were attributes in the event expression - $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added - # to LastEvent, this will be the element right after this one. - $AttrArray # This list of attribute names, types, and values - ) = split(/,/, $event, 12); +my ( # split the SD into the following fields: + $Occurred, # One if the condition has been triggered + $ErrNum, # Non-zero if there was in error in the event registration + $ErrMsg, # The string msg related to ErrNum + $EventFlags, # Bit mask giving some additional info about the event + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime + $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered + $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), + # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), + # this will be the FMS. + $NumAttrs, # Number of attr values from the resource returned in this event + $NumAttrsInExpr, # How many of the above were attributes in the event expression + $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added + # to LastEvent, this will be the element right after this one. + $AttrArray # This list of attribute names, types, and values +) = split(/,/, $event, 12); -my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list +my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list my ($ResourceName, $valuesMsg); -my $j = 0; # index into attrArray -for (my $i=0; $i<$NumAttrs; $i++) { - my $attrName = $attrArray[$j++]; - my $attrType = $attrArray[$j++]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. - my $attrValue = $attrArray[$j++]; - if ($attrName eq '"Name"') { $ResourceName = $attrValue; } - $valuesMsg .= " Attribute Value $i: $attrName = $attrValue\n"; +my $j = 0; # index into attrArray +for (my $i = 0 ; $i < $NumAttrs ; $i++) { + my $attrName = $attrArray[ $j++ ]; + my $attrType = $attrArray[ $j++ ]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. + my $attrValue = $attrArray[ $j++ ]; + if ($attrName eq '"Name"') { $ResourceName = $attrValue; } + $valuesMsg .= " Attribute Value $i: $attrName = $attrValue\n"; } if (!length($ResourceName)) { $ResourceName = '(unknown)'; } -my $msg="=============================================================================\n"; +my $msg = "=============================================================================\n"; $msg .= " Time: " . convertTime($EventTime) . " \n"; $msg .= " MN Condition: $ENV{ERRM_COND_NAME}\n"; $msg .= " Severity: $severity\n"; $msg .= " Event Type: $type\n"; $msg .= " SN Condition: $ENV{ERRM_RSRC_NAME}\n"; -$msg .= " SN: $ENV{ERRM_NODE_NAME}\n"; # do we have to use $ERRM_NODE_NAMELIST here? +$msg .= " SN: $ENV{ERRM_NODE_NAME}\n"; # do we have to use $ERRM_NODE_NAMELIST here? $msg .= " Node: $NodeName\n"; $msg .= " Resource Name: $ResourceName\n"; if (length($valuesMsg)) { - $msg .= " Attributes:\n"; - $msg .= $valuesMsg; + $msg .= " Attributes:\n"; + $msg .= $valuesMsg; } # Skipped the following: $ERRM_EXPR $ERRM_RSRC_CLASS_PNAME $ERRM_DATA_TYPE $ERRM_NODE_NAMELIST $ERRM_RSRC_TYPE #$str = escape_chars($str); -if (open (FILE, ">>$filename")) { +if (open(FILE, ">>$filename")) { print FILE "$msg\n"; - close (FILE); -} - + close(FILE); +} + exit; # convert time string sub convertTime { - my ($seconds, $micro) = split(/\./, $_[0]); - return strftime("%A %D %T", localtime($seconds)); + my ($seconds, $micro) = split(/\./, $_[0]); + return strftime("%A %D %T", localtime($seconds)); } diff --git a/xCAT-rmc/scripts/logevent_simple b/xCAT-rmc/scripts/logevent_simple index 705219af6..fa3d228df 100755 --- a/xCAT-rmc/scripts/logevent_simple +++ b/xCAT-rmc/scripts/logevent_simple @@ -1,39 +1,40 @@ #!/usr/bin/env perl BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; -open(FILE, ">>/var/log/logevent_simple.log") or dir ("cannot open the file\n"); -($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); -printf FILE "\n-----------%2d-%02d-%04d %02d:%02d:%02d-----------\n", $mon+1,$mday,$year+1900,$hour,$min,$sec; +open(FILE, ">>/var/log/logevent_simple.log") or dir("cannot open the file\n"); +($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time); +printf FILE "\n-----------%2d-%02d-%04d %02d:%02d:%02d-----------\n", $mon + 1, $mday, $year + 1900, $hour, $min, $sec; -my $respname=$ENV{ERRM_ER_NAME}; -my $cond_name=$ENV{ERRM_COND_NAME}; -my $batch=0; -if (exists($ENV{ERRM_COND_BATCH})) { $batch=$ENV{ERRM_COND_BATCH}; } +my $respname = $ENV{ERRM_ER_NAME}; +my $cond_name = $ENV{ERRM_COND_NAME}; +my $batch = 0; +if (exists($ENV{ERRM_COND_BATCH})) { $batch = $ENV{ERRM_COND_BATCH}; } if ($batch) { if ($ENV{ERRM_COND_BATCH_NUM} > 0) { - #check if event detail file exist - if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})){ - xCAT::MsgUtils->message('S', "logeventtoxcat: no event detail file specified in the response $respname for condition $cond_name.\n"); - exit (1); - } - my $filename=$ENV{ERRM_EVENT_DETAIL_FILE}; - if (! -f $filename) { - xCAT::MsgUtils->message('S', "logeventtoxcat: cannot find event detail file $filename in response $respname for condition $cond_name.\n"); - exit (1); - } - open(FILE1, "<$filename"); - my $line1=readline(FILE1); - my @aTemp=split(/=/, $line1); - my $num_events=$aTemp[1]; - close(FILE1); - print FILE "Total events=$num_events\n\n"; + #check if event detail file exist + if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})) { + xCAT::MsgUtils->message('S', "logeventtoxcat: no event detail file specified in the response $respname for condition $cond_name.\n"); + exit(1); + } + + my $filename = $ENV{ERRM_EVENT_DETAIL_FILE}; + if (!-f $filename) { + xCAT::MsgUtils->message('S', "logeventtoxcat: cannot find event detail file $filename in response $respname for condition $cond_name.\n"); + exit(1); + } + open(FILE1, "<$filename"); + my $line1 = readline(FILE1); + my @aTemp = split(/=/, $line1); + my $num_events = $aTemp[1]; + close(FILE1); + print FILE "Total events=$num_events\n\n"; } -} +} close(FILE); return 0; - + diff --git a/xCAT-rmc/scripts/logeventtoteal b/xCAT-rmc/scripts/logeventtoteal index d95755b96..98eb60caf 100755 --- a/xCAT-rmc/scripts/logeventtoteal +++ b/xCAT-rmc/scripts/logeventtoteal @@ -1,12 +1,12 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html -# This script is used by LogEventToTealEventLog response to put RMC events into -# the TEAL's x_tealeventlog table. It handles both batch and non-batching events. +# This script is used by LogEventToTealEventLog response to put RMC events into +# the TEAL's x_tealeventlog table. It handles both batch and non-batching events. BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -19,91 +19,92 @@ use IO::File; use TEAL::Semaphore; use TEAL::event_id; -my $batch=0; -if (exists($ENV{ERRM_COND_BATCH})) { $batch=$ENV{ERRM_COND_BATCH}; } -my @a=(); -my $condname=$ENV{ERRM_COND_NAME}; -my $respname=$ENV{ERRM_ER_NAME}; -my $eventid = $TEAL::event_id::tabeventid{$condname}; +my $batch = 0; +if (exists($ENV{ERRM_COND_BATCH})) { $batch = $ENV{ERRM_COND_BATCH}; } +my @a = (); +my $condname = $ENV{ERRM_COND_NAME}; +my $respname = $ENV{ERRM_ER_NAME}; +my $eventid = $TEAL::event_id::tabeventid{$condname}; -if (!$batch) { #handle single event - my $time=$ENV{ERRM_TIME}; - my $nodenamelist=$ENV{ERRM_NODE_NAMELIST}; +if (!$batch) { #handle single event + my $time = $ENV{ERRM_TIME}; + my $nodenamelist = $ENV{ERRM_NODE_NAMELIST}; $nodenamelist =~ s/\{(.*)\}/$1/; - - my $event={ - event_id => $eventid, - time_occurred => convertTime($time), - src_comp => $ENV{ERRM_RSRC_CLASS_PNAME}, - src_loc_type => "A", - src_loc => "$nodenamelist##" . $ENV{ERRM_RSRC_NAME}, - rpt_comp => 'IBM.Condition', - rpt_loc_type =>"A", - rpt_loc => $ENV{ERRM_NODE_NAME} . "##" . $ENV{ERRM_COND_NAME}, - raw_data_fmt =>"0", - raw_data => $ENV{ERRM_ATTR_PNAME} . "=" . $ENV{ERRM_VALUE}, - }; - + + my $event = { + event_id => $eventid, + time_occurred => convertTime($time), + src_comp => $ENV{ERRM_RSRC_CLASS_PNAME}, + src_loc_type => "A", + src_loc => "$nodenamelist##" . $ENV{ERRM_RSRC_NAME}, + rpt_comp => 'IBM.Condition', + rpt_loc_type => "A", + rpt_loc => $ENV{ERRM_NODE_NAME} . "##" . $ENV{ERRM_COND_NAME}, + raw_data_fmt => "0", + raw_data => $ENV{ERRM_ATTR_PNAME} . "=" . $ENV{ERRM_VALUE}, + }; + push(@a, $event); -} else { #handle event batching +} else { #handle event batching if ($ENV{ERRM_COND_BATCH_NUM} > 0) { + #check if event detail file exist - if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})){ - xCAT::MsgUtils->message('S', "logeventtoteal: no event detail file specified in the response $respname for condition $condname.\n"); - exit (1); - } - - my $filename=$ENV{ERRM_EVENT_DETAIL_FILE}; - if (! -f $filename) { - xCAT::MsgUtils->message('S', "logeventtoteal: cannot find event detail file $filename in response $respname for condition $condname.\n"); - exit (1); - } + if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})) { + xCAT::MsgUtils->message('S', "logeventtoteal: no event detail file specified in the response $respname for condition $condname.\n"); + exit(1); + } - open(FILE1, "<$filename"); - readline(FILE1);#skip first 2 lines + my $filename = $ENV{ERRM_EVENT_DETAIL_FILE}; + if (!-f $filename) { + xCAT::MsgUtils->message('S', "logeventtoteal: cannot find event detail file $filename in response $respname for condition $condname.\n"); + exit(1); + } + + open(FILE1, "<$filename"); + readline(FILE1); #skip first 2 lines readline(FILE1); - my $line1=readline(FILE1); - my @aTemp=split(/=/, $line1); - my $num_events=$aTemp[1]; - close(FILE1); + my $line1 = readline(FILE1); + my @aTemp = split(/=/, $line1); + my $num_events = $aTemp[1]; + close(FILE1); - my $count; - for ($count = 1; $count <= $num_events; $count++) { - my $content=`sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $filename`; - - my @content_array=split(/\n/, $content); - pop(@content_array); #get rid of last line - shift(@content_array); #get rid of firt line - - my %content_hash=(); - foreach(@content_array) { + my $count; + for ($count = 1 ; $count <= $num_events ; $count++) { + my $content = `sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $filename`; + + my @content_array = split(/\n/, $content); + pop(@content_array); #get rid of last line + shift(@content_array); #get rid of firt line + + my %content_hash = (); + foreach (@content_array) { /([^\=]+)\=(.*)/; - $content_hash{$1}=$2; - } + $content_hash{$1} = $2; + } - my $time=$content_hash{ERRM_TIME}; - my $nodenamelist=$content_hash{ERRM_NODE_NAMELIST}; - $nodenamelist =~ s/\{(.*)\}/$1/; - my $event={ - event_id => $eventid, - time_occurred => convertTime($time), - src_comp => $content_hash{ERRM_RSRC_CLASS_PNAME}, - src_loc_type => "A", - src_loc => $nodenamelist . "##" . $content_hash{ERRM_RSRC_NAME}, - rpt_comp => "IBM.Condition", - rpt_loc_type =>"A", - rpt_loc => $content_hash{ERRM_NODE_NAME} . "##" . $content_hash{ERRM_COND_NAME}, + my $time = $content_hash{ERRM_TIME}; + my $nodenamelist = $content_hash{ERRM_NODE_NAMELIST}; + $nodenamelist =~ s/\{(.*)\}/$1/; + my $event = { + event_id => $eventid, + time_occurred => convertTime($time), + src_comp => $content_hash{ERRM_RSRC_CLASS_PNAME}, + src_loc_type => "A", + src_loc => $nodenamelist . "##" . $content_hash{ERRM_RSRC_NAME}, + rpt_comp => "IBM.Condition", + rpt_loc_type => "A", + rpt_loc => $content_hash{ERRM_NODE_NAME} . "##" . $content_hash{ERRM_COND_NAME}, raw_data_fmt => "0", - raw_data => $content_hash{ERRM_ATTR_PNAME} . "=" . $content_hash{ERRM_VALUE}, - }; - push(@a, $event); - } + raw_data => $content_hash{ERRM_ATTR_PNAME} . "=" . $content_hash{ERRM_VALUE}, + }; + push(@a, $event); + } } -} +} -my ($rc, $msg)=xCAT::TableUtils->logEventsToTealDatabase(\@a); +my ($rc, $msg) = xCAT::TableUtils->logEventsToTealDatabase(\@a); if ($rc) { - xCAT::MsgUtils->message('S', "logeventtoteal:$msg. The condition is $condname. The response is $respname.\n"); + xCAT::MsgUtils->message('S', "logeventtoteal:$msg. The condition is $condname. The response is $respname.\n"); } else { my $s = TEAL::Semaphore->new(); $s->post() @@ -111,11 +112,12 @@ if ($rc) { # convert time string that can be used for timestamp datatype for db sub convertTime { - my ($seconds, $micro) = split(/\,/, $_[0]); - #return strftime("%A %D %T", localtime($seconds)); - my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($seconds); - my $result=sprintf("%4d-%02d-%02d %02d:%02d:%02d.%06d", $year+1900,$mon+1,$mday,$hour,$min,$sec,$micro); - return $result; + my ($seconds, $micro) = split(/\,/, $_[0]); + + #return strftime("%A %D %T", localtime($seconds)); + my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime($seconds); + my $result = sprintf("%4d-%02d-%02d %02d:%02d:%02d.%06d", $year + 1900, $mon + 1, $mday, $hour, $min, $sec, $micro); + return $result; } diff --git a/xCAT-rmc/scripts/logeventtoxcat b/xCAT-rmc/scripts/logeventtoxcat index 592119f14..9016043b2 100755 --- a/xCAT-rmc/scripts/logeventtoxcat +++ b/xCAT-rmc/scripts/logeventtoxcat @@ -1,12 +1,12 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html -# This script is used by LogEventToxCATDatabase event response to put RMC events into +# This script is used by LogEventToxCATDatabase event response to put RMC events into # the xCAT evnetlog table. It handles both batch and non-batching events. BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -17,90 +17,91 @@ use xCAT::TableUtils; use xCAT::MsgUtils; use IO::File; -my $batch=0; -if (exists($ENV{ERRM_COND_BATCH})) { $batch=$ENV{ERRM_COND_BATCH}; } -my @a=(); -my $condname=$ENV{ERRM_COND_NAME}; -my $respname=$ENV{ERRM_ER_NAME}; +my $batch = 0; +if (exists($ENV{ERRM_COND_BATCH})) { $batch = $ENV{ERRM_COND_BATCH}; } +my @a = (); +my $condname = $ENV{ERRM_COND_NAME}; +my $respname = $ENV{ERRM_ER_NAME}; -if (!$batch) { #handle single event - my $time=$ENV{ERRM_TIME}; - my $nodenamelist=$ENV{ERRM_NODE_NAMELIST}; +if (!$batch) { #handle single event + my $time = $ENV{ERRM_TIME}; + my $nodenamelist = $ENV{ERRM_NODE_NAMELIST}; $nodenamelist =~ s/\{(.*)\}/$1/; - - my $event={ - eventtype => $ENV{ERRM_TYPE}, - monitor => $ENV{ERRM_COND_NAME}, - monnode => $ENV{ERRM_NODE_NAME}, - node => $nodenamelist, - application => 'RMC', - component => $ENV{ERRM_RSRC_CLASS_PNAME}, - id => $ENV{ERRM_RSRC_NAME} . "," . $ENV{ERRM_ATTR_PNAME}, - severity => $ENV{ERRM_COND_SEVERITY}, - message => '', - rawdata => $ENV{ERRM_ATTR_PNAME} . "=" . $ENV{ERRM_VALUE}, - }; - + + my $event = { + eventtype => $ENV{ERRM_TYPE}, + monitor => $ENV{ERRM_COND_NAME}, + monnode => $ENV{ERRM_NODE_NAME}, + node => $nodenamelist, + application => 'RMC', + component => $ENV{ERRM_RSRC_CLASS_PNAME}, + id => $ENV{ERRM_RSRC_NAME} . "," . $ENV{ERRM_ATTR_PNAME}, + severity => $ENV{ERRM_COND_SEVERITY}, + message => '', + rawdata => $ENV{ERRM_ATTR_PNAME} . "=" . $ENV{ERRM_VALUE}, + }; + push(@a, $event); -} else { #handle event batching +} else { #handle event batching if ($ENV{ERRM_COND_BATCH_NUM} > 0) { + #check if event detail file exist - if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})){ - xCAT::MsgUtils->message('S', "logeventtoxcat: no event detail file specified in the response $respname for condition $condname.\n"); - exit (1); - } - - my $filename=$ENV{ERRM_EVENT_DETAIL_FILE}; - if (! -f $filename) { - xCAT::MsgUtils->message('S', "logeventtoxcat: cannot find event detail file $filename in response $respname for condition $condname.\n"); - exit (1); - } + if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})) { + xCAT::MsgUtils->message('S', "logeventtoxcat: no event detail file specified in the response $respname for condition $condname.\n"); + exit(1); + } - open(FILE1, "<$filename"); - readline(FILE1);#skip first 2 lines + my $filename = $ENV{ERRM_EVENT_DETAIL_FILE}; + if (!-f $filename) { + xCAT::MsgUtils->message('S', "logeventtoxcat: cannot find event detail file $filename in response $respname for condition $condname.\n"); + exit(1); + } + + open(FILE1, "<$filename"); + readline(FILE1); #skip first 2 lines readline(FILE1); - my $line1=readline(FILE1); - my @aTemp=split(/=/, $line1); - my $num_events=$aTemp[1]; - close(FILE1); + my $line1 = readline(FILE1); + my @aTemp = split(/=/, $line1); + my $num_events = $aTemp[1]; + close(FILE1); - my $count; - for ($count = 1; $count <= $num_events; $count++) { - my $content=`sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $filename`; - - my @content_array=split(/\n/, $content); - pop(@content_array); #get rid of last line - shift(@content_array); #get rid of firt line - - my %content_hash=(); - foreach(@content_array) { + my $count; + for ($count = 1 ; $count <= $num_events ; $count++) { + my $content = `sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $filename`; + + my @content_array = split(/\n/, $content); + pop(@content_array); #get rid of last line + shift(@content_array); #get rid of firt line + + my %content_hash = (); + foreach (@content_array) { /([^\=]+)\=(.*)/; - $content_hash{$1}=$2; - } + $content_hash{$1} = $2; + } - my $time=$content_hash{ERRM_TIME}; - my $nodenamelist=$content_hash{ERRM_NODE_NAMELIST}; - $nodenamelist =~ s/\{(.*)\}/$1/; - my $event={ - eventtype => $content_hash{ERRM_TYPE}, - monitor => $content_hash{ERRM_COND_NAME}, - monnode => $content_hash{ERRM_NODE_NAME}, - node => $nodenamelist, - application => 'RMC', - component => $content_hash{ERRM_RSRC_CLASS_PNAME}, - id => $content_hash{ERRM_RSRC_NAME} . "," . $content_hash{ERRM_ATTR_PNAME}, - severity => $content_hash{ERRM_COND_SEVERITY}, - message => '', - rawdata => $content_hash{ERRM_ATTR_PNAME} . "=" . $content_hash{ERRM_VALUE}, - }; - push(@a, $event); - } + my $time = $content_hash{ERRM_TIME}; + my $nodenamelist = $content_hash{ERRM_NODE_NAMELIST}; + $nodenamelist =~ s/\{(.*)\}/$1/; + my $event = { + eventtype => $content_hash{ERRM_TYPE}, + monitor => $content_hash{ERRM_COND_NAME}, + monnode => $content_hash{ERRM_NODE_NAME}, + node => $nodenamelist, + application => 'RMC', + component => $content_hash{ERRM_RSRC_CLASS_PNAME}, + id => $content_hash{ERRM_RSRC_NAME} . "," . $content_hash{ERRM_ATTR_PNAME}, + severity => $content_hash{ERRM_COND_SEVERITY}, + message => '', + rawdata => $content_hash{ERRM_ATTR_PNAME} . "=" . $content_hash{ERRM_VALUE}, + }; + push(@a, $event); + } } -} +} -my ($rc, $msg)=xCAT::TableUtils->logEventsToDatabase(\@a); +my ($rc, $msg) = xCAT::TableUtils->logEventsToDatabase(\@a); if ($rc) { - xCAT::MsgUtils->message('S', "logeventtoxcat:$msg. The condition is $condname. The response is $respname.\n"); + xCAT::MsgUtils->message('S', "logeventtoxcat:$msg. The condition is $condname. The response is $respname.\n"); } exit $rc; diff --git a/xCAT-rmc/scripts/mkrmcresources b/xCAT-rmc/scripts/mkrmcresources index 8ff6a27ea..261b67cd6 100755 --- a/xCAT-rmc/scripts/mkrmcresources +++ b/xCAT-rmc/scripts/mkrmcresources @@ -2,6 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html #------------------------------------------------------------------------------- + =head1 mkrmcresources =head2 mkrmcresources is used to predefine RMC conditions, responses, associations, sensors (and can be extended to support any RSCT resource @@ -15,15 +16,17 @@ This command should be called by the post install scripts of packaging files, script run after install or from the command line. =cut + #------------------------------------------------------------------------------- use Getopt::Long; $Getopt::Long::ignorecase = 0; #Checks case in GetOptions -Getopt::Long::Configure("bundling"); #allows short command line options to be grouped (e.g. -av) +Getopt::Long::Configure("bundling"); #allows short command line options to be grouped (e.g. -av) #-------------------------------------------------------------------------------- + =head3 quote Quote a string, taking into account embedded quotes. This function is most useful when passing string through the shell to another cmd. It handles one @@ -40,36 +43,38 @@ Getopt::Long::Configure("bundling"); #allows short command line options to be Comments: none =cut + #-------------------------------------------------------------------------------- sub quote { - my ($str) = @_; + my ($str) = @_; - # if the value has imbedded double quotes, use single quotes. If it also has - # single quotes, escape the double quotes. - if (!($str =~ /\"/)) # no embedded double quotes - { - $str =~ s/\$/\\\$/sg; # escape the dollar signs - $str =~ s/\`/\\\`/sg; - $str = qq("$str"); - } - elsif (!($str =~ /\'/)) - { - $str = qq('$str'); - } # no embedded single quotes - else # has both embedded double and single quotes - { - # Escape the double quotes. (Escaping single quotes does not seem to work - # in the shells.) - $str =~ s/\"/\\\"/sg; #" this comment helps formating - $str =~ s/\$/\\\$/sg; # escape the dollar signs - $str =~ s/\`/\\\`/sg; - $str = qq("$str"); - } + # if the value has imbedded double quotes, use single quotes. If it also has + # single quotes, escape the double quotes. + if (!($str =~ /\"/)) # no embedded double quotes + { + $str =~ s/\$/\\\$/sg; # escape the dollar signs + $str =~ s/\`/\\\`/sg; + $str = qq("$str"); + } + elsif (!($str =~ /\'/)) + { + $str = qq('$str'); + } # no embedded single quotes + else # has both embedded double and single quotes + { + # Escape the double quotes. (Escaping single quotes does not seem to work + # in the shells.) + $str =~ s/\"/\\\"/sg; #" this comment helps formating + $str =~ s/\$/\\\$/sg; # escape the dollar signs + $str =~ s/\`/\\\`/sg; + $str = qq("$str"); + } } #-------------------------------------------------------------------------------- + =head3 filterRmcApiOutput filter RMC Api Output Arguments: @@ -87,36 +92,38 @@ sub quote The error msgs from the RPM -api cmds are pretty messy. This routine cleans them up a little bit. =cut + #-------------------------------------------------------------------------------- sub filterRmcApiOutput { - my ($cmd, $outref) = @_; - if ($::VERBOSE || !($cmd =~ m|^/usr/bin/\S+-api |)) { - return; - } # give as much info as possible, if verbose + my ($cmd, $outref) = @_; + if ($::VERBOSE || !($cmd =~ m|^/usr/bin/\S+-api |)) { + return; + } # give as much info as possible, if verbose - # Figure out the output delimiter - my ($d) = $cmd =~ / -D\s+(\S+)/; - if (length($d)) { - $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes - # escape any chars perl pattern matching would intepret as special chars - $d =~ s/([\|\^\*\+\?\.])/\\$1/g; - } - else - { - $d = '::'; - } # this is the default output delimiter for the -api cmds - $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; + # Figure out the output delimiter + my ($d) = $cmd =~ / -D\s+(\S+)/; + if (length($d)) { + $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes + # escape any chars perl pattern matching would intepret as special chars + $d =~ s/([\|\^\*\+\?\.])/\\$1/g; + } + else + { + $d = '::'; + } # this is the default output delimiter for the -api cmds + $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; } sub isHMC { - my $hmcfile = "/opt/hsc/data/hmcType.properties"; - if (-e $hmcfile) { return 1; } - else { return 0; } + my $hmcfile = "/opt/hsc/data/hmcType.properties"; + if (-e $hmcfile) { return 1; } + else { return 0; } } #-------------------------------------------------------------------------------- + =head3 runcmd Run the given cmd and return the output in an array (already chopped). Alternatively, if this function is used in a scalar context, the output is joined into a single string @@ -142,73 +149,75 @@ sub isHMC If refoutput is true, then the output will be returned as a reference to an array for efficiency. =cut + #-------------------------------------------------------------------------------- sub runcmd { - my ($cmd, $exitcode, $refoutput) = @_; - $::RUNCMD_RC = 0; - if (!$::NO_STDERR_REDIRECT) { - if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } - } - my $outref = []; - @$outref = `$cmd`; - if ($?) - { - $::RUNCMD_RC = $? >> 8; - my $displayerror = 1; - my $rc; - if (defined($exitcode) && length($exitcode) && $exitcode != -2) + my ($cmd, $exitcode, $refoutput) = @_; + $::RUNCMD_RC = 0; + if (!$::NO_STDERR_REDIRECT) { + if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } + } + my $outref = []; + @$outref = `$cmd`; + if ($?) { - if ($exitcode > 0) - { - $rc = $exitcode; - } # if not zero, exit with specified code - elsif ($exitcode <= 0) - { - $rc = ''; # if zero or negative, do not exit - if ($exitcode < 0) { $displayerror = 0; } - } + $::RUNCMD_RC = $? >> 8; + my $displayerror = 1; + my $rc; + if (defined($exitcode) && length($exitcode) && $exitcode != -2) + { + if ($exitcode > 0) + { + $rc = $exitcode; + } # if not zero, exit with specified code + elsif ($exitcode <= 0) + { + $rc = ''; # if zero or negative, do not exit + if ($exitcode < 0) { $displayerror = 0; } + } + } + else + { + $rc = $::RUNCMD_RC; + } # if exitcode not specified, use cmd exit code + if ($displayerror) + { + my $errmsg = ''; + if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) + { + $errmsg = "Segmentation fault $errmsg"; + } + else + { + # The error msgs from the -api cmds are pretty messy. Clean them up a little. + filterRmcApiOutput($cmd, $outref); + $errmsg = join('', @$outref); + chomp $errmsg; + } + print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + } + } + if ($refoutput) + { + chomp(@$outref); + return $outref; + } + elsif (wantarray) + { + chomp(@$outref); + return @$outref; } else { - $rc = $::RUNCMD_RC; - } # if exitcode not specified, use cmd exit code - if ($displayerror) - { - my $errmsg = ''; - if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) - { - $errmsg = "Segmentation fault $errmsg"; - } - else - { - # The error msgs from the -api cmds are pretty messy. Clean them up a little. - filterRmcApiOutput($cmd, $outref); - $errmsg = join('', @$outref); - chomp $errmsg; - } - print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + my $line = join('', @$outref); + chomp $line; + return $line; } - } - if ($refoutput) - { - chomp(@$outref); - return $outref; - } - elsif (wantarray) - { - chomp(@$outref); - return @$outref; - } - else - { - my $line = join('', @$outref); - chomp $line; - return $line; - } } #-------------------------------------------------------------------------------- + =head3 runrmccmd Runs an RMC commmand Arguments: @@ -225,541 +234,566 @@ sub runcmd and run RMC commands seperately for each slice. Otherwise just run RMC commands with the arguments passed in. =cut + #-------------------------------------------------------------------------------- sub runrmccmd { - my ($rmccmd, $options, $select, $exitcode, $nodelist_ref) = @_; + my ($rmccmd, $options, $select, $exitcode, $nodelist_ref) = @_; - my @nodelist; - my $return_ref = []; + my @nodelist; + my $return_ref = []; - if (!defined($exitcode)) - { - $exitcode = -2; - } - - if(! grep /usr\/bin/, $rmccmd) - { - # add absolute path - $rmccmd = "/usr/bin/$rmccmd"; - } - - if ($nodelist_ref) - { - # check whether to break up nodelist for better scalability. - @nodelist = @$nodelist_ref; - my $divide = 500; # max number of nodes for each division - my @sublist; - my @newarray; - my ($start_index, $end_index, $nodestring); - - my $count = 0; - my $times = int(scalar(@nodelist) / $divide); - while ($count <= $times) + if (!defined($exitcode)) { - $start_index = $count * $divide; - $end_index = - ((scalar(@nodelist) - 1) < (($count + 1) * $divide - 1)) - ? (scalar(@nodelist) - 1) - : (($count + 1) * $divide - 1); - @sublist = @nodelist[$start_index .. $end_index]; - @newarray = (); - foreach my $node (@sublist) - { - my @vals = split ',|\s', $node; - push @newarray, @vals; - } - $nodestring = join("','", @newarray); - - # replace the pattern in select string with the broken up node string - my $select_new = $select; - $select_new =~ s/XXX/$nodestring/; - my $cmd = "$rmccmd $options $select_new"; - my $outref = runcmd($cmd, $exitcode, 1); - push @$return_ref, @$outref; - $count++; + $exitcode = -2; } - } - else - { - my $cmd = "$rmccmd $options $select"; - $return_ref = runcmd($cmd, $exitcode, 1); - } - # returns a reference to the output array - return $return_ref; + if (!grep /usr\/bin/, $rmccmd) + { + # add absolute path + $rmccmd = "/usr/bin/$rmccmd"; + } + + if ($nodelist_ref) + { + # check whether to break up nodelist for better scalability. + @nodelist = @$nodelist_ref; + my $divide = 500; # max number of nodes for each division + my @sublist; + my @newarray; + my ($start_index, $end_index, $nodestring); + + my $count = 0; + my $times = int(scalar(@nodelist) / $divide); + while ($count <= $times) + { + $start_index = $count * $divide; + $end_index = + ((scalar(@nodelist) - 1) < (($count + 1) * $divide - 1)) + ? (scalar(@nodelist) - 1) + : (($count + 1) * $divide - 1); + @sublist = @nodelist[ $start_index .. $end_index ]; + @newarray = (); + foreach my $node (@sublist) + { + my @vals = split ',|\s', $node; + push @newarray, @vals; + } + $nodestring = join("','", @newarray); + + # replace the pattern in select string with the broken up node string + my $select_new = $select; + $select_new =~ s/XXX/$nodestring/; + my $cmd = "$rmccmd $options $select_new"; + my $outref = runcmd($cmd, $exitcode, 1); + push @$return_ref, @$outref; + $count++; + } + } + else + { + my $cmd = "$rmccmd $options $select"; + $return_ref = runcmd($cmd, $exitcode, 1); + } + + # returns a reference to the output array + return $return_ref; } #-------------------------------------------------------------------------------- + =head3 queryResources Queries all resources of a given class or classes. Places results into a global hash for each resource class. Arguments: a list of RSCT resource classes Globals: %::EXISTS::{$resource} =cut + #-------------------------------------------------------------------------------- sub queryResources { - my @resources = @_; + my @resources = @_; - my $where = ""; - foreach my $res (@resources) - { - if ($res eq "IBM.Association") + my $where = ""; + foreach my $res (@resources) { - #special case: run lscondresp because Associations do not have names - #cant run lsrsrc because Assoctation also does not store names of resources (just handles) - my @condresp = runcmd("LANG=C /usr/bin/lscondresp"); - my $class = $res; - $class =~ s/^IBM\.//; - splice @condresp, 0, - 2; #delete first two lines -- they are just comments - foreach my $line (@condresp) - { - my ($condition, $response, $node, $state) = split ' ', $line; - $condition = &removeQuotes($condition); - $response = &removeQuotes($response); - my $key = "${condition}:_:${response}"; - my $ActiveFlag = 0; #assume offline - if ($state =~ m/Active/) + if ($res eq "IBM.Association") { - $ActiveFlag = 1; + #special case: run lscondresp because Associations do not have names + #cant run lsrsrc because Assoctation also does not store names of resources (just handles) + my @condresp = runcmd("LANG=C /usr/bin/lscondresp"); + my $class = $res; + $class =~ s/^IBM\.//; + splice @condresp, 0, + 2; #delete first two lines -- they are just comments + foreach my $line (@condresp) + { + my ($condition, $response, $node, $state) = split ' ', $line; + $condition = &removeQuotes($condition); + $response = &removeQuotes($response); + my $key = "${condition}:_:${response}"; + my $ActiveFlag = 0; #assume offline + if ($state =~ m/Active/) + { + $ActiveFlag = 1; + } + + #currently does not checked for locked + # This \%{typeglob} syntax auto-vivifies + # the hash table for us, and gives us a reference. + my $ref = \%{ $::EXISTS::{$class} }; + $ref->{$key} = { ActiveFlag => $ActiveFlag, }; + } } - #currently does not checked for locked + else + { + $where .= " -s ${res}::::'*p0x0020'"; + } + } + + my $output = runrmccmd("lsrsrc-api", "-i -m -n -D ':|:'", $where); + foreach my $line (@$output) + { + my @array = split(/:\|:/, $line); + my $class = shift @array; #the -m flag puts the class name in front + $class =~ s/^IBM\.//; + my %attrs = @array; + # This \%{typeglob} syntax auto-vivifies # the hash table for us, and gives us a reference. - my $ref = \%{$::EXISTS::{$class}}; - $ref->{$key} = {ActiveFlag => $ActiveFlag,}; - } + my $ref = \%{ $::EXISTS::{$class} }; + my $key = $attrs{'Name'}; + $ref->{$key} = {%attrs}; #sets the EXISTS array with the info } - else - { - $where .= " -s ${res}::::'*p0x0020'"; - } - } - - my $output = runrmccmd("lsrsrc-api", "-i -m -n -D ':|:'", $where); - foreach my $line (@$output) - { - my @array = split(/:\|:/, $line); - my $class = shift @array; #the -m flag puts the class name in front - $class =~ s/^IBM\.//; - my %attrs = @array; - # This \%{typeglob} syntax auto-vivifies - # the hash table for us, and gives us a reference. - my $ref = \%{$::EXISTS::{$class}}; - my $key = $attrs{'Name'}; - $ref->{$key} = {%attrs}; #sets the EXISTS array with the info - } } #-------------------------------------------------------------------------------- + =head3 traverseDirectories Calls readFiles on each sub-directory of the given path. Creates a global array with all target resource classes. Arguments: A directory Globals: @::DIRECTORIES (will hold all resource classes) =cut + #-------------------------------------------------------------------------------- sub traverseDirectories { - my ($dir) = @_; - my ($dir_fh, $file); + my ($dir) = @_; + my ($dir_fh, $file); - opendir($dir_fh, $dir) - or die "Can not open directory $dir\n"; - while ($file = readdir($dir_fh)) - { - if ($file ne '.' and $file ne '..') + opendir($dir_fh, $dir) + or die "Can not open directory $dir\n"; + while ($file = readdir($dir_fh)) { - my $subdir = "$dir/$file"; - if (-d $subdir) - { #only look at directories - &readFiles($subdir); - push @::DIRECTORIES, $file; #file=just the filename - } + if ($file ne '.' and $file ne '..') + { + my $subdir = "$dir/$file"; + if (-d $subdir) + { #only look at directories + &readFiles($subdir); + push @::DIRECTORIES, $file; #file=just the filename + } + } } - } - closedir($dir_fh) - or die "Can not close directory $dir\n"; + closedir($dir_fh) + or die "Can not close directory $dir\n"; } #-------------------------------------------------------------------------------- + =head3 readFiles Calls require on all .pm files in a given directory Arguments: A directory =cut + #-------------------------------------------------------------------------------- sub readFiles { - my ($dir) = @_; - my ($dir_fh, $file); - opendir($dir_fh, $dir) + my ($dir) = @_; + my ($dir_fh, $file); + opendir($dir_fh, $dir) or die "Can not open directory $dir\n"; - while ($file = readdir($dir_fh)) - { - if ($file ne '.' and $file ne '..') + while ($file = readdir($dir_fh)) { - $file = "$dir/$file"; - if ($file =~ m/\.pm$/) - { - #its a perl module - require $file; - } + if ($file ne '.' and $file ne '..') + { + $file = "$dir/$file"; + if ($file =~ m/\.pm$/) + { + #its a perl module + require $file; + } + } } - } - closedir($dir_fh) - or die "Can not close directory $dir\n"; + closedir($dir_fh) + or die "Can not close directory $dir\n"; } #-------------------------------------------------------------------------------- + =head3 compareResources Compares existing resources to those requiring definition. Globals: uses %::EXISTS and %::RES and makes %::CHANGE and %::CREATE =cut + #-------------------------------------------------------------------------------- sub compareResources { - foreach my $class (@::DIRECTORIES) - { #this has all subdirectory names - $class =~ s/^IBM\.//; #the IBM prefix is not used in the hash name - local *exi = $::EXISTS::{$class}; #defined on system - local *res = $::RES::{$class}; #defined in file - foreach my $resource (keys %res) - { - if (defined $exi{$resource}) - { #exists on the system - if (defined $res{$resource}{'Locked'} - && $res{$resource}{'Locked'} == 1) + foreach my $class (@::DIRECTORIES) + { #this has all subdirectory names + $class =~ s/^IBM\.//; #the IBM prefix is not used in the hash name + local *exi = $::EXISTS::{$class}; #defined on system + local *res = $::RES::{$class}; #defined in file + foreach my $resource (keys %res) { - #only change the resource if it is supposed to be locked - foreach my $attr (keys %{$res{$resource}}) - { - if ($exi{$resource}{$attr} ne $res{$resource}{$attr}) - { - if (!($class eq "Association" && $attr eq "Locked")) - { # association locked attrs are not stored - # something has changed - if ($::VERBOSE) + if (defined $exi{$resource}) + { #exists on the system + if (defined $res{$resource}{'Locked'} + && $res{$resource}{'Locked'} == 1) { - print "Differs: Class=$class\tExists=$exi{$resource}{$attr}\tDefined=$res{$resource}{$attr}\n"; + #only change the resource if it is supposed to be locked + foreach my $attr (keys %{ $res{$resource} }) + { + if ($exi{$resource}{$attr} ne $res{$resource}{$attr}) + { + if (!($class eq "Association" && $attr eq "Locked")) + { # association locked attrs are not stored + # something has changed + if ($::VERBOSE) + { + print "Differs: Class=$class\tExists=$exi{$resource}{$attr}\tDefined=$res{$resource}{$attr}\n"; + } + $::CHANGE::{$class}{$resource} = $res{$resource}; + last; + } + } + } } - $::CHANGE::{$class}{$resource} = $res{$resource}; - last; - } } - } + else + { #resource is not defined on the system + $::CREATE::{$class}{$resource} = $res{$resource}; + } } - } - else - { #resource is not defined on the system - $::CREATE::{$class}{$resource} = $res{$resource}; - } } - } } #-------------------------------------------------------------------------------- + =head3 removeQuotes removes starting and ending quotes that are in the output of lsrsrc Arguments: string Returns: string with no leading or trailing quotes =cut + #-------------------------------------------------------------------------------- sub removeQuotes { - my ($string) = @_; - $string =~ s/^\"|^\'//; - $string =~ s/\"$|\'$//; - return $string; + my ($string) = @_; + $string =~ s/^\"|^\'//; + $string =~ s/\"$|\'$//; + return $string; } #-------------------------------------------------------------------------------- + =head3 createResources Calls mkrsrc-api on all resources in the %::CREATE hash Globals: %::CREATE =cut + #-------------------------------------------------------------------------------- sub createResources { - my $string; - my $counter = 0; - my @assoc_cmds; - my $sensorflg = 0; - foreach my $class (@::DIRECTORIES) - { #all the class names - local *cre = $::CREATE::{$class}; - if ($class eq "Sensor") - { - $sensorflg = 1; - } - else - { - $sensorflg = 0; - } - foreach my $resource (keys %cre) - { - if ($class eq "Association") - { #special case - my ($cond, $resp) = split ":_:", $resource; - if ($cre{$resource}{'ActiveFlag'} == 1) + my $string; + my $counter = 0; + my @assoc_cmds; + my $sensorflg = 0; + foreach my $class (@::DIRECTORIES) + { #all the class names + local *cre = $::CREATE::{$class}; + if ($class eq "Sensor") { - push @assoc_cmds, "/usr/bin/startcondresp $cond $resp"; - if ($cre{$resource}{'Locked'} == 1) - { - push @assoc_cmds, "/usr/bin/startcondresp -L $cond $resp"; - } + $sensorflg = 1; } else - { #not active - push @assoc_cmds, "/usr/bin/mkcondresp $cond $resp"; - #no need to lock stopped associations - } - } - else - { - $string .= " IBM.${class}::"; - foreach my $attr (keys %{$cre{$resource}}) { - my $value = $cre{$resource}{$attr}; - $string .= "${attr}::" . quote($value) . "::"; + $sensorflg = 0; } - if (($sensorflg == 1) && ($::INSTALL)) + foreach my $resource (keys %cre) { - # make the Sensor with no userid check - $string .= "::Options::1"; + if ($class eq "Association") + { #special case + my ($cond, $resp) = split ":_:", $resource; + if ($cre{$resource}{'ActiveFlag'} == 1) + { + push @assoc_cmds, "/usr/bin/startcondresp $cond $resp"; + if ($cre{$resource}{'Locked'} == 1) + { + push @assoc_cmds, "/usr/bin/startcondresp -L $cond $resp"; + } + } + else + { #not active + push @assoc_cmds, "/usr/bin/mkcondresp $cond $resp"; + + #no need to lock stopped associations + } + } + else + { + $string .= " IBM.${class}::"; + foreach my $attr (keys %{ $cre{$resource} }) + { + my $value = $cre{$resource}{$attr}; + $string .= "${attr}::" . quote($value) . "::"; + } + if (($sensorflg == 1) && ($::INSTALL)) + { + # make the Sensor with no userid check + $string .= "::Options::1"; + } + # + # Only build up to 10 resources at a pass + # to avoid command line limit + # + $counter = $counter + 1; + if ($counter > 10) + { + if ($string =~ m/\w+/) + { + #my $cmd = "/usr/bin/mkrsrc-api $string"; + #print "running $cmd\n"; + #system($cmd); + runrmccmd("mkrsrc-api", "", $string); + $string = ""; + $counter = 0; + } + } + } } - # - # Only build up to 10 resources at a pass - # to avoid command line limit - # - $counter = $counter + 1; - if ($counter > 10) - { - if ($string =~ m/\w+/) - { - #my $cmd = "/usr/bin/mkrsrc-api $string"; - #print "running $cmd\n"; - #system($cmd); - runrmccmd("mkrsrc-api", "", $string); - $string = ""; - $counter = 0; - } - } - } } - } - if ($string =~ m/\w+/) # for any remaining resources - { - #my $cmd = "/usr/bin/mkrsrc-api $string"; - #print "running $cmd\n"; - #system($cmd); - runrmccmd("mkrsrc-api", "", $string); - } - foreach my $cmd (@assoc_cmds) - { - #need to make associations after conds and resps have been made - runcmd("$cmd"); - } + if ($string =~ m/\w+/) # for any remaining resources + { + #my $cmd = "/usr/bin/mkrsrc-api $string"; + #print "running $cmd\n"; + #system($cmd); + runrmccmd("mkrsrc-api", "", $string); + } + foreach my $cmd (@assoc_cmds) + { + #need to make associations after conds and resps have been made + runcmd("$cmd"); + } } #-------------------------------------------------------------------------------- + =head3 changeResources Calls chrsrc-api on all resources in the %::CHANGE hash Globals: %::CHANGE =cut + #-------------------------------------------------------------------------------- sub changeResources { - my $string; - my $ustring; #unlock - my @unlock; #unlock each class - my $where; #unlock each class - foreach my $class (@::DIRECTORIES) - { #all the class names - local *cha = $::CHANGE::{$class}; - foreach my $resource (keys %cha) - { - if ($class eq "Association") - { #special case - #code here is identical to createResource - my ($cond, $resp) = split ":_:", $resource; - if ($cre{$resource}{'ActiveFlag'} == 1) + my $string; + my $ustring; #unlock + my @unlock; #unlock each class + my $where; #unlock each class + foreach my $class (@::DIRECTORIES) + { #all the class names + local *cha = $::CHANGE::{$class}; + foreach my $resource (keys %cha) { - runcmd("/usr/bin/startcondresp $cond $resp"); - if ($cre{$resource}{'Locked'} == 1) - { - runcmd( "/usr/bin/startcondresp -L $cond $resp"); - } - } - else - { #not active - runcmd("/usr/bin/mkcondresp $cond $resp"); - #no need to lock stopped associations - } - } - else # not class association - { - $where = qq/"Name IN ('XXX')"/; - $string .= " -s IBM.${class}::${where}::"; - push @unlock, $cha{$resource}{'Name'}; - delete $cha{$resource}{'Name'}; - foreach my $attr (keys %{$cha{$resource}}) - { - my $value = $cha{$resource}{$attr}; - $string .= "${attr}::" . quote($value) . "::"; - } - } - if (@unlock) - { - $where = qq/"Name IN ('XXX')"/; - $ustring .= " -s IBM.${class}::${where}::Locked::'0'"; - } - } # foreach resource - } # foreach key - # - # although @unlock contains the resource and not the node name - # this is a hack to use runrmccmd and the node_ref must - # be provided even though we are not really dealing with nodes - # here + if ($class eq "Association") + { #special case + #code here is identical to createResource + my ($cond, $resp) = split ":_:", $resource; + if ($cre{$resource}{'ActiveFlag'} == 1) + { + runcmd("/usr/bin/startcondresp $cond $resp"); + if ($cre{$resource}{'Locked'} == 1) + { + runcmd("/usr/bin/startcondresp -L $cond $resp"); + } + } + else + { #not active + runcmd("/usr/bin/mkcondresp $cond $resp"); - if ($ustring =~ m/\w+/) { - runrmccmd("chrsrc-api", "", $ustring, undef, \@unlock); - } - if ($string =~ m/\w+/) { - runrmccmd("chrsrc-api", "", $string, undef, \@unlock); - } + #no need to lock stopped associations + } + } + else # not class association + { + $where = qq/"Name IN ('XXX')"/; + $string .= " -s IBM.${class}::${where}::"; + push @unlock, $cha{$resource}{'Name'}; + delete $cha{$resource}{'Name'}; + foreach my $attr (keys %{ $cha{$resource} }) + { + my $value = $cha{$resource}{$attr}; + $string .= "${attr}::" . quote($value) . "::"; + } + } + if (@unlock) + { + $where = qq/"Name IN ('XXX')"/; + $ustring .= " -s IBM.${class}::${where}::Locked::'0'"; + } + } # foreach resource + } # foreach key + # + # although @unlock contains the resource and not the node name + # this is a hack to use runrmccmd and the node_ref must + # be provided even though we are not really dealing with nodes + # here + + if ($ustring =~ m/\w+/) { + runrmccmd("chrsrc-api", "", $ustring, undef, \@unlock); + } + if ($string =~ m/\w+/) { + runrmccmd("chrsrc-api", "", $string, undef, \@unlock); + } } #-------------------------------------------------------------------------------- + =head3 writeAllFiles creates all files for the given resources classes Arguments: a array ref of class names, basedir =cut + #-------------------------------------------------------------------------------- sub writeAllFiles { - my @classes = @{shift()}; - my $basedir = shift; - print "classes=@classes, basedir=$basedir"; - foreach my $class (@classes) - { - my $output = runrmccmd("lsrsrc-api", "-i", "-s ${class}::::Name"); - foreach my $line (@$output) + my @classes = @{ shift() }; + my $basedir = shift; + print "classes=@classes, basedir=$basedir"; + foreach my $class (@classes) { - &writeFile("${class}::$line", $basedir); + my $output = runrmccmd("lsrsrc-api", "-i", "-s ${class}::::Name"); + foreach my $line (@$output) + { + &writeFile("${class}::$line", $basedir); + } } - } } #-------------------------------------------------------------------------------- + =head3 writeFile creates a file with the resource info in $basedir/ Arguments: class::resource_name, basedir =cut + #-------------------------------------------------------------------------------- sub writeFile { - my $input = shift; - my $basedir= shift; - print "input=$input, basedir=$basedir\n"; + my $input = shift; + my $basedir = shift; + print "input=$input, basedir=$basedir\n"; - my ($class, $resourcefilename) = split "::", $input; - if (!$resourcefilename) { - print 'mkrmcresource --mkfile requires as input.\n'; - exit 1; - } - my $resource; - push(@$resource, $resourcefilename); + my ($class, $resourcefilename) = split "::", $input; + if (!$resourcefilename) { + print 'mkrmcresource --mkfile requires as input.\n'; + exit 1; + } + my $resource; + push(@$resource, $resourcefilename); - if (!-e "$basedir/$class") { - `mkdir -p "$basedir/$class"`; - } - my $file = "$basedir/$class/$resourcefilename.pm"; - my $where = qq/"Name IN ('XXX')"/; - my $string = " -s ${class}::${where}::*p0x0002"; - my $output = runrmccmd("lsrsrc-api", "-i -n -D ':|:'", - $string, undef, $resource); - $string = " -s ${class}::${where}::*p0x0008"; - my $optional = runrmccmd("lsrsrc-api", "-i -n -D ':|:'", - $string, undef, $resource); + if (!-e "$basedir/$class") { + `mkdir -p "$basedir/$class"`; + } + my $file = "$basedir/$class/$resourcefilename.pm"; + my $where = qq/"Name IN ('XXX')"/; + my $string = " -s ${class}::${where}::*p0x0002"; + my $output = runrmccmd("lsrsrc-api", "-i -n -D ':|:'", + $string, undef, $resource); + $string = " -s ${class}::${where}::*p0x0008"; + my $optional = runrmccmd("lsrsrc-api", "-i -n -D ':|:'", + $string, undef, $resource); - #my @output = runcmd("/usr/bin/lsrsrc -s $where $class"); - #uses lsrsrc instead of lsrsrc-api because format is almost right (just needs a few mods) + #my @output = runcmd("/usr/bin/lsrsrc -s $where $class"); + #uses lsrsrc instead of lsrsrc-api because format is almost right (just needs a few mods) - my $fh; - open($fh, ">$file") - or die "Can not open this file for writing $file.\n"; - print $fh "#!/usr/bin/perl\n\n"; - $class =~ s/IBM\.//; + my $fh; + open($fh, ">$file") + or die "Can not open this file for writing $file.\n"; + print $fh "#!/usr/bin/perl\n\n"; + $class =~ s/IBM\.//; - print $fh '$RES::' . $class . "{" . "'" + print $fh '$RES::' . $class . "{" . "'" . $resourcefilename . "'" . "} = {\n"; - foreach my $line (@$output) - { - my %attrs = split /:\|:/, - $line; #can't go straight into a hash because -p creates extra fields - foreach my $attr (keys %attrs) + foreach my $line (@$output) { - if ( $attr !~ m/ActivePeerDomain/ - && $attr !~ m/NodeNameList/ - && $attr !~ m/NodeIDs/) - { - my $value = $attrs{$attr}; - if ($value =~ m/\w/ || $value =~ m/\d/) + my %attrs = split /:\|:/, + $line; #can't go straight into a hash because -p creates extra fields + foreach my $attr (keys %attrs) { - # print "value = |$value|\n"; - #$value = &removeQuotes($value); #quotes are not needed becaues of q() - #print "value = |$value|\n"; - my $line = "\t$attr => q($value),"; - print $fh "$line\n"; + if ($attr !~ m/ActivePeerDomain/ + && $attr !~ m/NodeNameList/ + && $attr !~ m/NodeIDs/) + { + my $value = $attrs{$attr}; + if ($value =~ m/\w/ || $value =~ m/\d/) + { + # print "value = |$value|\n"; + #$value = &removeQuotes($value); #quotes are not needed becaues of q() + #print "value = |$value|\n"; + my $line = "\t$attr => q($value),"; + print $fh "$line\n"; + } + } } - } } - } - foreach my $line (@$optional) - { - my %attrs = split /:\|:/, - $line; #can't go straight into a hash because -p creates extra fields - foreach my $attr (keys %attrs) + foreach my $line (@$optional) { - if ( $attr !~ m/ActivePeerDomain/ - && $attr !~ m/NodeNameList/ - && $attr !~ m/NodeIDs/) - { - my $value = $attrs{$attr}; - if ($value =~ m/\w/ || $value =~ m/\d/) + my %attrs = split /:\|:/, + $line; #can't go straight into a hash because -p creates extra fields + foreach my $attr (keys %attrs) { - # print "value = |$value|\n"; - #$value = &removeQuotes($value); #quotes are not needed becaues of q() - #print "value = |$value|\n"; - my $line = "\t$attr => q($value),"; - print $fh "$line\n"; + if ($attr !~ m/ActivePeerDomain/ + && $attr !~ m/NodeNameList/ + && $attr !~ m/NodeIDs/) + { + my $value = $attrs{$attr}; + if ($value =~ m/\w/ || $value =~ m/\d/) + { + # print "value = |$value|\n"; + #$value = &removeQuotes($value); #quotes are not needed becaues of q() + #print "value = |$value|\n"; + my $line = "\t$attr => q($value),"; + print $fh "$line\n"; + } + } } - } } - } - print $fh "};"; - print $fh "\n"; - print $fh "1;"; - print $fh "\n"; - close($fh) - or die "cabbit close file $file\n"; + print $fh "};"; + print $fh "\n"; + print $fh "1;"; + print $fh "\n"; + close($fh) + or die "cabbit close file $file\n"; } #-------------------------------------------------------------------------------- + =head3 usage Prints the command usage statement =cut + #-------------------------------------------------------------------------------- sub usage { - print "Usage: + print "Usage: mkrmcresources [--install|--mkfile classname::rsrcname|--mkall] \ [-V|--verbose] directory\n\ mkrmcresources -h|--help\n\ @@ -778,41 +812,41 @@ sub usage # get arguments if ( - !GetOptions( - 'h|help' => \$::HELP, - 'V|verbose' => \$::VERBOSE, - 'install' => \$::INSTALL, - 'mkfile=s' => \$::MKFILE, - 'mkall' => \$::MKALL, + !GetOptions( + 'h|help' => \$::HELP, + 'V|verbose' => \$::VERBOSE, + 'install' => \$::INSTALL, + 'mkfile=s' => \$::MKFILE, + 'mkall' => \$::MKALL, ) ) { - &usage; - exit 1; + &usage; + exit 1; } if ($::HELP) { &usage; exit; } if (isHMC() && ($ENV{'DC_ENVIRONMENT'} ne 1)) { - print "mkresources is not supported on HMC.\n"; + print "mkresources is not supported on HMC.\n"; } # any function requested if (@ARGV < 1) { - &usage; - exit 1; + &usage; + exit 1; } my $basedir = $ARGV[0]; if ($::MKFILE) { - &writeFile($::MKFILE, $basedir); - exit; + &writeFile($::MKFILE, $basedir); + exit; } if ($::MKALL) { - @rsrc_classes=('IBM.Condition', 'IBM.EventResponse', 'IBM.Sensor'); - &writeAllFiles(\@rsrc_classes, $basedir); - exit; + @rsrc_classes = ('IBM.Condition', 'IBM.EventResponse', 'IBM.Sensor'); + &writeAllFiles(\@rsrc_classes, $basedir); + exit; } diff --git a/xCAT-rmc/scripts/monaixsyslog b/xCAT-rmc/scripts/monaixsyslog index 7346c217c..adb19801b 100755 --- a/xCAT-rmc/scripts/monaixsyslog +++ b/xCAT-rmc/scripts/monaixsyslog @@ -1,19 +1,21 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html #------------------------------------------------------------------------------ + =head1 monaixsyslog =head2 =cut + #------------------------------------------------------------------------------ use locale; use Getopt::Long; my $dirname = "xcat_aix_syslog"; -my $vardir = "/var/opt/$dirname"; +my $vardir = "/var/opt/$dirname"; my $default_runfile = "$vardir/.monaixsyslog_run"; -my $default_file = "$vardir/syslog.out"; -my $default_pri = "*.warn"; +my $default_file = "$vardir/syslog.out"; +my $default_pri = "*.warn"; $::MAX_SENSOR_STRING = 65535; my ($facility_priority, $logfile, $runfile) = &getArgs(); @@ -21,35 +23,35 @@ my ($facility_priority, $logfile, $runfile) = &getArgs(); my ($syslogconf, $embedinfo); $syslogconf = "/etc/syslog.conf"; -$embedinfo = "$facility_priority $logfile rotate size 4m files 1"; +$embedinfo = "$facility_priority $logfile rotate size 4m files 1"; if (!-d $vardir) { mkdir($vardir); } #check to see if this is the first time this script has been run if (!-e $runfile) -{ #first time - if ($^O =~ /^aix/i) - { - runcmd("grep \"$embedinfo\" $syslogconf", -1); - if ($::RUNCMD_RC == 1) - { #grep did not find embedinfo - #update syslog.conf - if (!-d $vardir) { mkdir($vardir); } - if (!-e $logfile) - { - touchFile($logfile); - } - runcmd("echo \"$embedinfo\" >> $syslogconf"); - my $cmd = "refresh -s syslogd"; - runcmd($cmd); - } - touchFile($runfile); - } - else - { - print "non-AIX platform, this scripts should not be ran.\n"; - exit 1; - } +{ #first time + if ($^O =~ /^aix/i) + { + runcmd("grep \"$embedinfo\" $syslogconf", -1); + if ($::RUNCMD_RC == 1) + { #grep did not find embedinfo + #update syslog.conf + if (!-d $vardir) { mkdir($vardir); } + if (!-e $logfile) + { + touchFile($logfile); + } + runcmd("echo \"$embedinfo\" >> $syslogconf"); + my $cmd = "refresh -s syslogd"; + runcmd($cmd); + } + touchFile($runfile); + } + else + { + print "non-AIX platform, this scripts should not be ran.\n"; + exit 1; + } } #Check for errors @@ -58,14 +60,15 @@ if ($^O =~ /^aix/i) { unless (open(RUNFILE, "<$runfile")) { - print "Cannot open file $runfile\n"; + print "Cannot open file $runfile\n"; exit 1; } - + my $marker = ; close(RUNFILE); my ($new_number, $new_content, $to_rfile); + # If the $runfile is empty, then we should read the $logfile from the beginning. if (!$marker) { @@ -75,9 +78,9 @@ if ($^O =~ /^aix/i) { my @info = split ':::', $marker; my ($last_modified_time, $line_number, $mark_content) = @info; - + my @stats = stat($logfile); - my $time = $stats[9]; + my $time = $stats[9]; if ($time == $last_modified_time) { # The log file has not been updated since last modified. @@ -97,9 +100,9 @@ if ($^O =~ /^aix/i) ($new_number, $new_content, $to_rfile) = &refreshSensorFromLogfile($logfile, 0, undef); } } - + # Get the last modified time for this log file - my @stats = stat($logfile); + my @stats = stat($logfile); my $new_time = $stats[9]; &updateRunfile($new_time, $new_number, $new_content, $runfile); @@ -107,7 +110,7 @@ if ($^O =~ /^aix/i) else { print "non-AIX platform, this scripts should not be ran.\n"; - exit 1; + exit 1; } exit 0; @@ -131,7 +134,7 @@ sub getArgs() print "ENTERING: $routine\n" if $::DEBUG; my @command_line = (); - @command_line = @ARGV; + @command_line = @ARGV; # Checks case in GetOptions $Getopt::Long::ignorecase = 0; @@ -140,8 +143,8 @@ sub getArgs() if ( !GetOptions( - 'p=s' => \$facility_priority, - 'f=s' => \$file, + 'p=s' => \$facility_priority, + 'f=s' => \$file, ) ) { @@ -154,7 +157,7 @@ sub getArgs() { my @para = split '/', $file; my $newpara = join '-', @para; - $runfile = "$vardir/.monaixsyslog_run" . "-$facility_priority". "-$newpara"; + $runfile = "$vardir/.monaixsyslog_run" . "-$facility_priority" . "-$newpara"; } else { @@ -163,14 +166,14 @@ sub getArgs() if (!$file) { - $file = $default_file; + $file = $default_file; } if (!$facility_priority) { $facility_priority = $default_pri; } - + return ($facility_priority, $file, $runfile); } @@ -202,10 +205,10 @@ sub refreshSensorFromLogfile() # The file may be opened by syslogd. exit 0; } - - my $i = 0; + + my $i = 0; my $matchflag = 0; - my $to_rfile = 0; + my $to_rfile = 0; my $mark_content; my $allinfo = ""; while (my $line = ) @@ -215,8 +218,8 @@ sub refreshSensorFromLogfile() # Start reading the file from this line and push it to the sensor # and update the mark file $allinfo .= $line; - $i = $i + 1; - $mark_content = $line; + $i = $i + 1; + $mark_content = $line; } else { @@ -229,7 +232,7 @@ sub refreshSensorFromLogfile() if ($line eq $bgncontent) { $matchflag = 1; - $i = $i + 1; + $i = $i + 1; next; } else @@ -244,6 +247,7 @@ sub refreshSensorFromLogfile() if ($allinfo) { my $strlen = length($allinfo); + # The condition/response can not handle # the long sensor String very well, # use file to pass messages. @@ -270,7 +274,7 @@ sub refreshSensorFromLogfile() } else { - print $allinfo; + print $allinfo; } } close(FILE); @@ -300,13 +304,14 @@ sub refreshSensorFromLogfile() sub updateRunfile() { my ($time, $line, $content, $file) = @_; - + # the marker line is something like "last_modified_time:::line_number:::mark_content" my $new_marker = join(":::", $time, $line, $content); runcmd("echo \"$new_marker\" > $file"); } #-------------------------------------------------------------------------------- + =head3 runcmd Run the given cmd and return the output in an array (already chopped). Alternatively, if this function is used in a scalar context, the output is joined into a single string @@ -332,72 +337,74 @@ sub updateRunfile() If refoutput is true, then the output will be returned as a reference to an array for efficiency. =cut + #-------------------------------------------------------------------------------- sub runcmd { - my ($cmd, $exitcode, $refoutput) = @_; - $::RUNCMD_RC = 0; - if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } - - my $outref = []; - @$outref = `$cmd`; - if ($?) - { - $::RUNCMD_RC = $? >> 8; - my $displayerror = 1; - my $rc; - if (defined($exitcode) && length($exitcode) && $exitcode != -2) + my ($cmd, $exitcode, $refoutput) = @_; + $::RUNCMD_RC = 0; + if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } + + my $outref = []; + @$outref = `$cmd`; + if ($?) { - if ($exitcode > 0) - { - $rc = $exitcode; - } # if not zero, exit with specified code - elsif ($exitcode <= 0) - { - $rc = ''; # if zero or negative, do not exit - if ($exitcode < 0) { $displayerror = 0; } - } + $::RUNCMD_RC = $? >> 8; + my $displayerror = 1; + my $rc; + if (defined($exitcode) && length($exitcode) && $exitcode != -2) + { + if ($exitcode > 0) + { + $rc = $exitcode; + } # if not zero, exit with specified code + elsif ($exitcode <= 0) + { + $rc = ''; # if zero or negative, do not exit + if ($exitcode < 0) { $displayerror = 0; } + } + } + else + { + $rc = $::RUNCMD_RC; + } # if exitcode not specified, use cmd exit code + if ($displayerror) + { + my $errmsg = ''; + if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) + { + $errmsg = "Segmentation fault $errmsg"; + } + else + { + # The error msgs from the -api cmds are pretty messy. Clean them up a little. + filterRmcApiOutput($cmd, $outref); + $errmsg = join('', @$outref); + chomp $errmsg; + } + print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + } + } + if ($refoutput) + { + chomp(@$outref); + return $outref; + } + elsif (wantarray) + { + chomp(@$outref); + return @$outref; } else { - $rc = $::RUNCMD_RC; - } # if exitcode not specified, use cmd exit code - if ($displayerror) - { - my $errmsg = ''; - if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) - { - $errmsg = "Segmentation fault $errmsg"; - } - else - { - # The error msgs from the -api cmds are pretty messy. Clean them up a little. - filterRmcApiOutput($cmd, $outref); - $errmsg = join('', @$outref); - chomp $errmsg; - } - print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + my $line = join('', @$outref); + chomp $line; + return $line; } - } - if ($refoutput) - { - chomp(@$outref); - return $outref; - } - elsif (wantarray) - { - chomp(@$outref); - return @$outref; - } - else - { - my $line = join('', @$outref); - chomp $line; - return $line; - } } #-------------------------------------------------------------------------------- + =head3 filterRmcApiOutput filter RMC Api Output Arguments: @@ -415,26 +422,27 @@ sub runcmd The error msgs from the RPM -api cmds are pretty messy. This routine cleans them up a little bit. =cut + #-------------------------------------------------------------------------------- sub filterRmcApiOutput { - my ($cmd, $outref) = @_; - if (!($cmd =~ m|^/usr/bin/\S+-api |)) { - return; - } # give as much info as possible, if verbose + my ($cmd, $outref) = @_; + if (!($cmd =~ m|^/usr/bin/\S+-api |)) { + return; + } # give as much info as possible, if verbose - # Figure out the output delimiter - my ($d) = $cmd =~ / -D\s+(\S+)/; - if (length($d)) { - $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes - # escape any chars perl pattern matching would intepret as special chars - $d =~ s/([\|\^\*\+\?\.])/\\$1/g; - } - else - { - $d = '::'; - } # this is the default output delimiter for the -api cmds - $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; + # Figure out the output delimiter + my ($d) = $cmd =~ / -D\s+(\S+)/; + if (length($d)) { + $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes + # escape any chars perl pattern matching would intepret as special chars + $d =~ s/([\|\^\*\+\?\.])/\\$1/g; + } + else + { + $d = '::'; + } # this is the default output delimiter for the -api cmds + $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; } #-------------------------------------------------------------------------------- @@ -448,28 +456,29 @@ sub filterRmcApiOutput #-------------------------------------------------------------------------------- sub touchFile { - my ($filename, $donotExit) = @_; - my $fh; - my $rc = 0; - if (!-e $filename) { - #if the file doesn't exist we need to open and close it - open($fh, ">>$filename") or $rc++; - if ($rc > 0 && !$donotExit) { - print "Touch of file $filename failed with: $!\n"; - return $rc; + my ($filename, $donotExit) = @_; + my $fh; + my $rc = 0; + if (!-e $filename) { + + #if the file doesn't exist we need to open and close it + open($fh, ">>$filename") or $rc++; + if ($rc > 0 && !$donotExit) { + print "Touch of file $filename failed with: $!\n"; + return $rc; + } + close($fh) or $rc++; } - close($fh) or $rc++; - } - else { - #if the file does exist we can just utime it (see the perlfunc man page entry on utime) - my $now = time; - utime($now, $now, $filename); - } - if ($rc > 0 && !$donotExit) { - print "Touch of file $filename failed with: $!\n"; - return $rc; - } - return 0; + else { + #if the file does exist we can just utime it (see the perlfunc man page entry on utime) + my $now = time; + utime($now, $now, $filename); + } + if ($rc > 0 && !$donotExit) { + print "Touch of file $filename failed with: $!\n"; + return $rc; + } + return 0; } @@ -496,12 +505,12 @@ sub touchFile sub createRandomName { - my $name=shift; + my $name = shift; my $nI; for ($nI = 0 ; $nI < 8 ; $nI++) { - my $char = ('a' .. 'z', 'A' .. 'Z')[int(rand(52)) + 1]; + my $char = ('a' .. 'z', 'A' .. 'Z')[ int(rand(52)) + 1 ]; $name .= $char; } $name; diff --git a/xCAT-rmc/scripts/monerrorlog b/xCAT-rmc/scripts/monerrorlog index d0908d720..717e5b78f 100755 --- a/xCAT-rmc/scripts/monerrorlog +++ b/xCAT-rmc/scripts/monerrorlog @@ -1,6 +1,7 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html #------------------------------------------------------------------------------ + =head1 monaixsyslog =head2 When first run (by the sensor) this script adds an entry to the AIX ODM @@ -9,10 +10,11 @@ it checks for any logged errors. On all subsequent runs this script just checks for errors. =cut + #------------------------------------------------------------------------------# BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -24,15 +26,15 @@ use xCAT::Utils; BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } my $dirname = "xcat_err_mon"; -my $vardir = "/var/opt/$dirname"; +my $vardir = "/var/opt/$dirname"; my $default_runfile = "$vardir/.monerrorlog_run"; -my $default_fifo = "$vardir/syslog_fifo"; -my $default_pri = "*.warn"; +my $default_fifo = "$vardir/syslog_fifo"; +my $default_pri = "*.warn"; $::MAX_SENSOR_STRING = 65535; my ($facility_priority, $fifo, $runfile) = &getArgs(); @@ -43,20 +45,20 @@ if (isNg()) $syslogconf = "/etc/syslog-ng/syslog-ng.conf"; if (($facility_priority eq $default_pri) && ($fifo eq $default_fifo)) { - $embedinfo = "destination warn_fifo { pipe(\\\"$fifo\\\" group(root) perm(0644)); };\nlog { source(src); filter(f_warn); destination(warn_fifo); };"; + $embedinfo = "destination warn_fifo { pipe(\\\"$fifo\\\" group(root) perm(0644)); };\nlog { source(src); filter(f_warn); destination(warn_fifo); };"; } else { my $tmp_dest = createRandomName("fifo"); - $embedinfo = "destination $tmp_dest { pipe(\\\"$fifo\\\" group(root) perm(0644)); };\nlog { source(src); filter($facility_priority); destination($tmp_dest); };"; + $embedinfo = "destination $tmp_dest { pipe(\\\"$fifo\\\" group(root) perm(0644)); };\nlog { source(src); filter($facility_priority); destination($tmp_dest); };"; } } else { - $syslogconf = "/etc/syslog.conf"; - $embedinfo = "$facility_priority |$fifo"; + $syslogconf = "/etc/syslog.conf"; + $embedinfo = "$facility_priority |$fifo"; } -my $odmstanza = "$vardir/odmstanza"; +my $odmstanza = "$vardir/odmstanza"; if (!-d $vardir) { mkdir($vardir); } @@ -79,170 +81,173 @@ Returns: #-------------------------------------------------------------------------------- sub first_time_run() { - if($^O =~ /^aix/i) - { - my $output = runcmd("/bin/odmget -q \"en_name=xcat_errlog_sen\" errnotify", -1); - if (!$output) - { - return 1; - } - return 0; - } - else - { - if (!-e $runfile) - { - return 1; - } - return 0; - } + if ($^O =~ /^aix/i) + { + my $output = runcmd("/bin/odmget -q \"en_name=xcat_errlog_sen\" errnotify", -1); + if (!$output) + { + return 1; + } + return 0; + } + else + { + if (!-e $runfile) + { + return 1; + } + return 0; + } } #check to see if this is the first time this script has been run if (&first_time_run) -{ #first time - if ($^O =~ /^linux/i) - { - runcmd("grep \"$embedinfo\" $syslogconf", -1); - if ($::RUNCMD_RC == 1) - { #grep did not find dirname - #update syslog.conf - if (!-d $vardir) { mkdir($vardir); } - if (!-e $fifo) - { - runcmd("/usr/bin/mkfifo $fifo"); - } - runcmd("echo \"$embedinfo\" >> $syslogconf"); - #my $cmd = service("syslog", "restart"); - #runcmd($cmd); - xCAT::Utils->restartservice("syslog"); - } - touchFile($runfile); - } - elsif ($^O =~ /^aix/i) - { - open(ODM, ">$odmstanza") or die $!; - print ODM ' +{ #first time + if ($^O =~ /^linux/i) + { + runcmd("grep \"$embedinfo\" $syslogconf", -1); + if ($::RUNCMD_RC == 1) + { #grep did not find dirname + #update syslog.conf + if (!-d $vardir) { mkdir($vardir); } + if (!-e $fifo) + { + runcmd("/usr/bin/mkfifo $fifo"); + } + runcmd("echo \"$embedinfo\" >> $syslogconf"); + + #my $cmd = service("syslog", "restart"); + #runcmd($cmd); + xCAT::Utils->restartservice("syslog"); + } + touchFile($runfile); + } + elsif ($^O =~ /^aix/i) + { + open(ODM, ">$odmstanza") or die $!; + print ODM ' errnotify: en_pid = 0 en_name = "xcat_errlog_sen" en_persistenceflg = 1 en_method = "' . "$::XCATROOT/sbin/rmcmon/errmsgque" . ' sequence = $1 error_id = $2 class = $3 type = $4 alert_flags = $5 res_name = $6 res_type = $7 res_class = $8 label = $9" '; - close ODM or die $!; - runcmd("/usr/bin/odmadd $odmstanza"); - } - else - { - print "unknown platform\n"; - exit 1; - } + close ODM or die $!; + runcmd("/usr/bin/odmadd $odmstanza"); + } + else + { + print "unknown platform\n"; + exit 1; + } } #Check for errors if ($^O =~ /^linux/i) { - local $SIG{ALRM} = sub { die "alarm\n" }; - eval { - alarm 4; - open(PIPE, $fifo) or die - print "cannot open file$fifo"; - alarm 0; - }; - if ($@ =~ /alarm/) { close PIPE; exit 0; } + local $SIG{ALRM} = sub { die "alarm\n" }; + eval { + alarm 4; + open(PIPE, $fifo) or die + print "cannot open file$fifo"; + alarm 0; + }; + if ($@ =~ /alarm/) { close PIPE; exit 0; } - my $allinfo = ""; - while (1) - { - my $line; - eval { - alarm 2; - $line = ; - alarm 0; - }; - if ($@ =~ /alarm/) { - close PIPE; - # send the messages to sensor - if ($allinfo) - { - my $strlen = length($allinfo); - # The condition/response can not handle - # the long sensor String very well, - # use file to pass messages. - # file name: /var/opt/xcat_err_mon/tmplogmsg - if ($strlen > $::MAX_SENSOR_STRING) - { - srand(time | $$); - my $filename = "$vardir/tmplogmsg_$$"; - while (-e $filename) - { - $filename = createRandomName($filename); - } - if (open(TMPLOG, ">$filename")) - { - print TMPLOG $allinfo; - close TMPLOG; - print "XCAT_MONERRORLOG_FILE:$filename"; - } - else - { - #open failed, why? - print "OPEN_FILE_FAILED: $filename"; - } - } - else - { - print $allinfo; - } - } + my $allinfo = ""; + while (1) + { + my $line; + eval { + alarm 2; + $line = ; + alarm 0; + }; + if ($@ =~ /alarm/) { + close PIPE; - exit 0; - } - $allinfo .= $line; - } - close PIPE; + # send the messages to sensor + if ($allinfo) + { + my $strlen = length($allinfo); + + # The condition/response can not handle + # the long sensor String very well, + # use file to pass messages. + # file name: /var/opt/xcat_err_mon/tmplogmsg + if ($strlen > $::MAX_SENSOR_STRING) + { + srand(time | $$); + my $filename = "$vardir/tmplogmsg_$$"; + while (-e $filename) + { + $filename = createRandomName($filename); + } + if (open(TMPLOG, ">$filename")) + { + print TMPLOG $allinfo; + close TMPLOG; + print "XCAT_MONERRORLOG_FILE:$filename"; + } + else + { + #open failed, why? + print "OPEN_FILE_FAILED: $filename"; + } + } + else + { + print $allinfo; + } + } + + exit 0; + } + $allinfo .= $line; + } + close PIPE; } elsif ($^O =~ /^aix/i) { - # the monitoring is stopped - if ($ENV{'SENSOR_MonitorStatus'} eq '2') - { - # stopsrc -s IBM.SensorRM will also - # set $ENV{'SENSOR_MonitorStatus'} to 2 - # should not do clean up when IBM.SensorRM is stopped - if (isRMrunning("IBM.SensorRM")) - { - runcmd("/bin/odmdelete -o errnotify -q \" en_name=xcat_errlog_sen\"", -1); - if (-e $runfile) - { - unlink($runfile); - } - } - exit 0; - } + # the monitoring is stopped + if ($ENV{'SENSOR_MonitorStatus'} eq '2') + { + # stopsrc -s IBM.SensorRM will also + # set $ENV{'SENSOR_MonitorStatus'} to 2 + # should not do clean up when IBM.SensorRM is stopped + if (isRMrunning("IBM.SensorRM")) + { + runcmd("/bin/odmdelete -o errnotify -q \" en_name=xcat_errlog_sen\"", -1); + if (-e $runfile) + { + unlink($runfile); + } + } + exit 0; + } - my $m = ord('xcat'); - my $key = IPC::SysV::ftok("/var/adm/ras/errlog", $m); - my $buf; - my $msg = new IPC::Msg($key, IPC_CREAT | S_IRUSR | S_IWUSR); - local $SIG{ALRM} = sub { die "alarm\n" }; - while (1) - { - eval { - alarm 2; - my $rectype = $msg->rcv($buf, 256); - alarm 0; - }; - if ($@ =~ /alarm/) { close PIPE; exit 0; } - runcmd( - "echo \"/usr/bin/refsensor ErrorLogSensor String=\'$buf\' 1>/dev/null 2>/dev/null\" | at now", - 0 - ); - } + my $m = ord('xcat'); + my $key = IPC::SysV::ftok("/var/adm/ras/errlog", $m); + my $buf; + my $msg = new IPC::Msg($key, IPC_CREAT | S_IRUSR | S_IWUSR); + local $SIG{ALRM} = sub { die "alarm\n" }; + while (1) + { + eval { + alarm 2; + my $rectype = $msg->rcv($buf, 256); + alarm 0; + }; + if ($@ =~ /alarm/) { close PIPE; exit 0; } + runcmd( +"echo \"/usr/bin/refsensor ErrorLogSensor String=\'$buf\' 1>/dev/null 2>/dev/null\" | at now", + 0 + ); + } - exit 0; + exit 0; } exit 0; @@ -266,7 +271,7 @@ sub getArgs() print "ENTERING: $routine\n" if $::DEBUG; my @command_line = (); - @command_line = @ARGV; + @command_line = @ARGV; # Checks case in GetOptions $Getopt::Long::ignorecase = 0; @@ -275,8 +280,8 @@ sub getArgs() if ( !GetOptions( - 'p=s' => \$facility_priority, - 'f=s' => \$fifo, + 'p=s' => \$facility_priority, + 'f=s' => \$fifo, ) ) { @@ -289,7 +294,7 @@ sub getArgs() { my @para = split '/', $fifo; my $newpara = join '-', @para; - $runfile = "$vardir/.monerrorlog_run" . "-$facility_priority". "-$newpara"; + $runfile = "$vardir/.monerrorlog_run" . "-$facility_priority" . "-$newpara"; } else { @@ -298,19 +303,20 @@ sub getArgs() if (!$fifo) { - $fifo = $default_fifo; + $fifo = $default_fifo; } if (!$facility_priority) { $facility_priority = $default_pri; } - + return ($facility_priority, $fifo, $runfile); } #-------------------------------------------------------------------------------- + =head3 runcmd Run the given cmd and return the output in an array (already chopped). Alternatively, if this function is used in a scalar context, the output is joined into a single string @@ -336,72 +342,74 @@ sub getArgs() If refoutput is true, then the output will be returned as a reference to an array for efficiency. =cut + #-------------------------------------------------------------------------------- sub runcmd { - my ($cmd, $exitcode, $refoutput) = @_; - $::RUNCMD_RC = 0; - if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } - - my $outref = []; - @$outref = `$cmd`; - if ($?) - { - $::RUNCMD_RC = $? >> 8; - my $displayerror = 1; - my $rc; - if (defined($exitcode) && length($exitcode) && $exitcode != -2) + my ($cmd, $exitcode, $refoutput) = @_; + $::RUNCMD_RC = 0; + if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } + + my $outref = []; + @$outref = `$cmd`; + if ($?) { - if ($exitcode > 0) - { - $rc = $exitcode; - } # if not zero, exit with specified code - elsif ($exitcode <= 0) - { - $rc = ''; # if zero or negative, do not exit - if ($exitcode < 0) { $displayerror = 0; } - } + $::RUNCMD_RC = $? >> 8; + my $displayerror = 1; + my $rc; + if (defined($exitcode) && length($exitcode) && $exitcode != -2) + { + if ($exitcode > 0) + { + $rc = $exitcode; + } # if not zero, exit with specified code + elsif ($exitcode <= 0) + { + $rc = ''; # if zero or negative, do not exit + if ($exitcode < 0) { $displayerror = 0; } + } + } + else + { + $rc = $::RUNCMD_RC; + } # if exitcode not specified, use cmd exit code + if ($displayerror) + { + my $errmsg = ''; + if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) + { + $errmsg = "Segmentation fault $errmsg"; + } + else + { + # The error msgs from the -api cmds are pretty messy. Clean them up a little. + filterRmcApiOutput($cmd, $outref); + $errmsg = join('', @$outref); + chomp $errmsg; + } + print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + } + } + if ($refoutput) + { + chomp(@$outref); + return $outref; + } + elsif (wantarray) + { + chomp(@$outref); + return @$outref; } else { - $rc = $::RUNCMD_RC; - } # if exitcode not specified, use cmd exit code - if ($displayerror) - { - my $errmsg = ''; - if (($^O =~ /^linux/i) && $::RUNCMD_RC == 139) - { - $errmsg = "Segmentation fault $errmsg"; - } - else - { - # The error msgs from the -api cmds are pretty messy. Clean them up a little. - filterRmcApiOutput($cmd, $outref); - $errmsg = join('', @$outref); - chomp $errmsg; - } - print "Exit code $::RUNCMD_RC from command: $cmd\nError message from cmd: $errmsg\n" + my $line = join('', @$outref); + chomp $line; + return $line; } - } - if ($refoutput) - { - chomp(@$outref); - return $outref; - } - elsif (wantarray) - { - chomp(@$outref); - return @$outref; - } - else - { - my $line = join('', @$outref); - chomp $line; - return $line; - } } #-------------------------------------------------------------------------------- + =head3 filterRmcApiOutput filter RMC Api Output Arguments: @@ -419,26 +427,27 @@ sub runcmd The error msgs from the RPM -api cmds are pretty messy. This routine cleans them up a little bit. =cut + #-------------------------------------------------------------------------------- sub filterRmcApiOutput { - my ($cmd, $outref) = @_; - if (!($cmd =~ m|^/usr/bin/\S+-api |)) { - return; - } # give as much info as possible, if verbose + my ($cmd, $outref) = @_; + if (!($cmd =~ m|^/usr/bin/\S+-api |)) { + return; + } # give as much info as possible, if verbose - # Figure out the output delimiter - my ($d) = $cmd =~ / -D\s+(\S+)/; - if (length($d)) { - $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes - # escape any chars perl pattern matching would intepret as special chars - $d =~ s/([\|\^\*\+\?\.])/\\$1/g; - } - else - { - $d = '::'; - } # this is the default output delimiter for the -api cmds - $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; + # Figure out the output delimiter + my ($d) = $cmd =~ / -D\s+(\S+)/; + if (length($d)) { + $d =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes + # escape any chars perl pattern matching would intepret as special chars + $d =~ s/([\|\^\*\+\?\.])/\\$1/g; + } + else + { + $d = '::'; + } # this is the default output delimiter for the -api cmds + $$outref[0] =~ s/^ERROR${d}.*${d}.*${d}.*${d}.*${d}//; } #-------------------------------------------------------------------------------- @@ -452,29 +461,31 @@ sub filterRmcApiOutput #-------------------------------------------------------------------------------- sub touchFile { - my ($filename, $donotExit) = @_; - my $fh; - my $rc = 0; - if (!-e $filename) { - #if the file doesn't exist we need to open and close it - open($fh, ">>$filename") or $rc++; - if ($rc > 0 && !$donotExit) { - print "Touch of file $filename failed with: $!\n"; - return $rc; + my ($filename, $donotExit) = @_; + my $fh; + my $rc = 0; + if (!-e $filename) { + + #if the file doesn't exist we need to open and close it + open($fh, ">>$filename") or $rc++; + if ($rc > 0 && !$donotExit) { + print "Touch of file $filename failed with: $!\n"; + return $rc; + } + close($fh) or $rc++; } - close($fh) or $rc++; - } - else { - #if the file does exist we can just utime it (see the perlfunc man page entry on utime) - my $now = time; - utime($now, $now, $filename); - } - if ($rc > 0 && !$donotExit) { - print "Touch of file $filename failed with: $!\n"; - return $rc; - } - return 0; + else { + #if the file does exist we can just utime it (see the perlfunc man page entry on utime) + my $now = time; + utime($now, $now, $filename); + } + if ($rc > 0 && !$donotExit) { + print "Touch of file $filename failed with: $!\n"; + return $rc; + } + return 0; } + #-------------------------------------------------------------------------------- =head3 createRandomName @@ -503,13 +514,14 @@ sub createRandomName my $nI; for ($nI = 0 ; $nI < 8 ; $nI++) { - my $char = ('a' .. 'z', 'A' .. 'Z')[int(rand(52)) + 1]; + my $char = ('a' .. 'z', 'A' .. 'Z')[ int(rand(52)) + 1 ]; $name .= $char; } $name; } #-------------------------------------------------------------------------------- + =head3 service Send a service request to an init script. Arguments: @@ -526,50 +538,51 @@ sub createRandomName #-------------------------------------------------------------------------------- sub service { - my ($service, $svcarg) = @_; - my $cmd; - my $SVCCLI = "/sbin/service"; - my $SVCDIR = "/etc/init.d"; + my ($service, $svcarg) = @_; + my $cmd; + my $SVCCLI = "/sbin/service"; + my $SVCDIR = "/etc/init.d"; - # On SLES, nfs server script is "nfsserver". - if (((-e "/etc/SuSE-release") || isHMC()) && $service eq "nfs") { - $service = "nfsserver"; - } - if (-f $SVCCLI) { - $cmd = "$SVCCLI $service $svcarg "; - } - else { - $cmd = "$SVCDIR/$service $svcarg"; - } - return $cmd; + # On SLES, nfs server script is "nfsserver". + if (((-e "/etc/SuSE-release") || isHMC()) && $service eq "nfs") { + $service = "nfsserver"; + } + if (-f $SVCCLI) { + $cmd = "$SVCCLI $service $svcarg "; + } + else { + $cmd = "$SVCDIR/$service $svcarg"; + } + return $cmd; } sub isHMC { - my $hmcfile = "/opt/hsc/data/hmcType.properties"; - if (-e $hmcfile) { return 1; } - else { return 0; } + my $hmcfile = "/opt/hsc/data/hmcType.properties"; + if (-e $hmcfile) { return 1; } + else { return 0; } } sub isNg { if (-f "/etc/SuSE-release") { - my $sysconfig="/etc/sysconfig/syslog"; - my $result=`grep "^SYSLOG_DAEMON=" $sysconfig 2>&1`; - if ($result =~ /syslog-ng/) { return 1; } + my $sysconfig = "/etc/sysconfig/syslog"; + my $result = `grep "^SYSLOG_DAEMON=" $sysconfig 2>&1`; + if ($result =~ /syslog-ng/) { return 1; } } return 0; } -sub isRMrunning{ - my $resMan = $_[0]; - my @output = runcmd("LANG=C /usr/bin/lssrc -s $resMan", -1); - if ($::RUNCMD_RC) { return 0; } # maybe we should try to catch real errors here - my ($subsys, $group, $pid, $status) = split(' ', $output[1]); - if (defined($status) && $status eq 'active') { - #now check to see if IBM.AuditRM is up - return 1; - } - return 0; +sub isRMrunning { + my $resMan = $_[0]; + my @output = runcmd("LANG=C /usr/bin/lssrc -s $resMan", -1); + if ($::RUNCMD_RC) { return 0; } # maybe we should try to catch real errors here + my ($subsys, $group, $pid, $status) = split(' ', $output[1]); + if (defined($status) && $status eq 'active') { + + #now check to see if IBM.AuditRM is up + return 1; + } + return 0; } diff --git a/xCAT-rmc/scripts/msg-hierarchical-batch-event b/xCAT-rmc/scripts/msg-hierarchical-batch-event index c06b23031..b65b7bebc 100755 --- a/xCAT-rmc/scripts/msg-hierarchical-batch-event +++ b/xCAT-rmc/scripts/msg-hierarchical-batch-event @@ -5,7 +5,7 @@ # Condition that is watching another Condition in a hierarchical cluster environment. # The condition that is being watched is a batch event. This script will go th the # node that has the watched condition, get the event batch file. And parse the file -# and then send email to a user with the detailed info of the events in the batch file. +# and then send email to a user with the detailed info of the events in the batch file. # The batch file will be then deleted if -d flag is set. # To use this script, create a Response that invokes this script with user id as the input. @@ -31,39 +31,39 @@ use File::Basename; use File::Path; my $where = join(' ', @ARGV); -my $delete=0; +my $delete = 0; if ($where =~ /-d/) { - $delete=1; + $delete = 1; } -$where =~ s/-d//; #remove -d +$where =~ s/-d//; #remove -d # Convert Severity and Type environment variables from integers to strings my @COND_SEVERITY = qw(Informational Warning Critical); -my @TYPE = ('event', 'rearm event'); -my $severity=$COND_SEVERITY[$ENV{ERRM_COND_SEVERITYID}]; -my $type=$TYPE[$ENV{ERRM_TYPEID }]; +my @TYPE = ('event', 'rearm event'); +my $severity = $COND_SEVERITY[ $ENV{ERRM_COND_SEVERITYID} ]; +my $type = $TYPE[ $ENV{ERRM_TYPEID} ]; # Parse the ERRM_VALUE attribute, which will contain the EventOccurred structured data variable from the Condition class # The fields in this structured data variable are documented below where we parse them out. my $event = $ENV{ERRM_VALUE}; -$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them +$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them # This parse the LastEvent -my ( # split the SD into the following fields: - $Saved, # batch file has been saved - $filename, # location of the batch file - $Size, # The size of the batch file - ) = split(/,/, $event); +my ( # split the SD into the following fields: + $Saved, # batch file has been saved + $filename, # location of the batch file + $Size, # The size of the batch file +) = split(/,/, $event); -my $sn_condname=$ENV{ERRM_RSRC_NAME}; -my $sn_name=$ENV{ERRM_NODE_NAME}; +my $sn_condname = $ENV{ERRM_RSRC_NAME}; +my $sn_name = $ENV{ERRM_NODE_NAME}; -my ( - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - ) = split(/,/, $ENV{ERRM_TIME}); +my ( + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime +) = split(/,/, $ENV{ERRM_TIME}); my $msg; $msg .= "The following $type occurred:\n"; @@ -71,69 +71,70 @@ $msg .= " Event Time: " . convertTime($EventTime) . "\n"; $msg .= " Condition name: $ENV{ERRM_COND_NAME}\n"; $msg .= " Severiry: $severity\n"; $msg .= " Condition being monitored: $sn_condname\n"; -$msg .= " Node where the condition was monitored: $sn_name\n"; # do we have to use $ERRM_NODE_NAMELIST here? +$msg .= " Node where the condition was monitored: $sn_name\n"; # do we have to use $ERRM_NODE_NAMELIST here? $msg .= " SN batch files name: $filename\n"; #copy the batch file from sn to mn $filename =~ s/"//g; -my $bn=basename($filename); +my $bn = basename($filename); #printf stderr "ful path :$filename\n"; #printf stderr "base name:$bn\n"; -my $dirname="/tmp/batch_process/"; -if (! -d $dirname) { +my $dirname = "/tmp/batch_process/"; +if (!-d $dirname) { mkdir($dirname); } my $cmd; -my $isHMC=0; +my $isHMC = 0; if ($filename =~ /\/home\/hscroot\/tmp/) { - $isHMC=1; - $cmd="scp hscroot\@$sn_name:$filename $dirname/$bn"; + $isHMC = 1; + $cmd = "scp hscroot\@$sn_name:$filename $dirname/$bn"; } else { - $cmd="scp $sn_name:$filename $dirname/$bn"; + $cmd = "scp $sn_name:$filename $dirname/$bn"; } -my $rc=`$cmd 2>&1`; +my $rc = `$cmd 2>&1`; if ($? != 0) { $msg .= "$rc\n"; } #now process the batch file open(FILE1, "<$dirname/$bn"); -readline(FILE1);#skip first 2 lines +readline(FILE1); #skip first 2 lines readline(FILE1); -my $line1=readline(FILE1); -my @aTemp=split(/=/, $line1); -my $num_events=$aTemp[1]; +my $line1 = readline(FILE1); +my @aTemp = split(/=/, $line1); +my $num_events = $aTemp[1]; close(FILE1); my $count; -for ($count = 1; $count <= $num_events; $count++) { - my $content=`sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $dirname/$bn`; - - my @content_array=split(/\n/, $content); - pop(@content_array); #get rid of last line - shift(@content_array); #get rid of firt line - - my %content_hash=(); - foreach(@content_array) { - /([^\=]+)\=(.*)/; - $content_hash{$1}=$2; - } - +for ($count = 1 ; $count <= $num_events ; $count++) { + my $content = `sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $dirname/$bn`; + + my @content_array = split(/\n/, $content); + pop(@content_array); #get rid of last line + shift(@content_array); #get rid of firt line + + my %content_hash = (); + foreach (@content_array) { + /([^\=]+)\=(.*)/; + $content_hash{$1} = $2; + } + my $event = "Event count: $count\n"; + #$event .= " Event time: " . $content_hash{ERRM_TIME} . "\n"; $event .= " Node where the event occurred: " . $content_hash{ERRM_NODE_NAMELIST} . "\n"; $event .= " Resource class: " . $content_hash{ERRM_RSRC_CLASS_PNAME} . "\n"; $event .= " Resource name: " . $content_hash{ERRM_RSRC_NAME} . "\n"; $event .= " Attribute name: " . $content_hash{ERRM_ATTR_PNAME} . "\n"; $event .= " Attribute value: " . $content_hash{ERRM_VALUE} . "\n\n"; - + $msg .= $event; -} - +} + #send the mail out my $rc = system(qq(echo "$msg" | write $where)) >> 8; @@ -143,9 +144,9 @@ my $rc = system(qq(echo "$msg" | write $where)) >> 8; #remove the batch file on the sn if needed if ($delete) { if ($isHMC) { - `ssh -l hscroot $sn_name "rm $filename"`; + `ssh -l hscroot $sn_name "rm $filename"`; } else { - `ssh -l root $sn_name "rm $filename"`; + `ssh -l root $sn_name "rm $filename"`; } } @@ -154,6 +155,6 @@ exit $rc; # convert time string sub convertTime { - my ($seconds, $micro) = split(/\./, $_[0]); - return strftime("%A %D %T", localtime($seconds)); + my ($seconds, $micro) = split(/\./, $_[0]); + return strftime("%A %D %T", localtime($seconds)); } diff --git a/xCAT-rmc/scripts/msg-hierarchical-event b/xCAT-rmc/scripts/msg-hierarchical-event index 98a141ed3..20d278868 100755 --- a/xCAT-rmc/scripts/msg-hierarchical-event +++ b/xCAT-rmc/scripts/msg-hierarchical-event @@ -30,46 +30,46 @@ use POSIX qw(strftime); # Convert Severity and Type environment variables from integers to strings my @COND_SEVERITY = qw(Informational Warning Critical); -my @TYPE = ('Event', 'Rearm event'); -my $severity=$COND_SEVERITY[$ENV{ERRM_COND_SEVERITYID}]; -my $type=$TYPE[$ENV{ERRM_TYPEID }]; +my @TYPE = ('Event', 'Rearm event'); +my $severity = $COND_SEVERITY[ $ENV{ERRM_COND_SEVERITYID} ]; +my $type = $TYPE[ $ENV{ERRM_TYPEID} ]; my $where = join(' ', @ARGV); # Parse the ERRM_VALUE attribute, which will contain the EventOccurred structured data variable from the Condition class # The fields in this structured data variable are documented below where we parse them out. my $event = $ENV{ERRM_VALUE}; -$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them +$event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them # This parse the LastEvent -my ( # split the SD into the following fields: - $Occurred, # One if the condition has been triggered - $ErrNum, # Non-zero if there was in error in the event registration - $ErrMsg, # The string msg related to ErrNum - $EventFlags, # Bit mask giving some additional info about the event - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered - $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), - # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), - # this will be the FMS. - $NumAttrs, # Number of attr values from the resource returned in this event - $NumAttrsInExpr, # How many of the above were attributes in the event expression - $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added - # to LastEvent, this will be the element right after this one. - $AttrArray # This list of attribute names, types, and values - ) = split(/,/, $event, 12); +my ( # split the SD into the following fields: + $Occurred, # One if the condition has been triggered + $ErrNum, # Non-zero if there was in error in the event registration + $ErrMsg, # The string msg related to ErrNum + $EventFlags, # Bit mask giving some additional info about the event + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime + $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered + $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), + # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), + # this will be the FMS. + $NumAttrs, # Number of attr values from the resource returned in this event + $NumAttrsInExpr, # How many of the above were attributes in the event expression + $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added + # to LastEvent, this will be the element right after this one. + $AttrArray # This list of attribute names, types, and values +) = split(/,/, $event, 12); -my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list +my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list my ($ResourceName, $valuesMsg); -my $j = 0; # index into attrArray -for (my $i=0; $i<$NumAttrs; $i++) { - my $attrName = $attrArray[$j++]; - my $attrType = $attrArray[$j++]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. - my $attrValue = $attrArray[$j++]; - if ($attrName eq '"Name"') { $ResourceName = $attrValue; } - $valuesMsg .= " Attribute Value $i: $attrName = $attrValue\n"; +my $j = 0; # index into attrArray +for (my $i = 0 ; $i < $NumAttrs ; $i++) { + my $attrName = $attrArray[ $j++ ]; + my $attrType = $attrArray[ $j++ ]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. + my $attrValue = $attrArray[ $j++ ]; + if ($attrName eq '"Name"') { $ResourceName = $attrValue; } + $valuesMsg .= " Attribute Value $i: $attrName = $attrValue\n"; } if (!length($ResourceName)) { $ResourceName = '(unknown)'; } @@ -77,13 +77,13 @@ my $msg; $msg .= "$severity $type occurred:\n"; $msg .= " MN Condition: $ENV{ERRM_COND_NAME}\n"; $msg .= " SN Condition: $ENV{ERRM_RSRC_NAME}\n"; -$msg .= " SN: $ENV{ERRM_NODE_NAME}\n"; # do we have to use $ERRM_NODE_NAMELIST here? +$msg .= " SN: $ENV{ERRM_NODE_NAME}\n"; # do we have to use $ERRM_NODE_NAMELIST here? $msg .= " Node: $NodeName\n"; $msg .= " Resource Name: $ResourceName\n"; $msg .= " Time: " . convertTime($EventTime) . " \n"; if (length($valuesMsg)) { - $msg .= " Attributes:\n"; - $msg .= $valuesMsg; + $msg .= " Attributes:\n"; + $msg .= $valuesMsg; } # Skipped the following: $ERRM_EXPR $ERRM_RSRC_CLASS_PNAME $ERRM_DATA_TYPE $ERRM_NODE_NAMELIST $ERRM_RSRC_TYPE @@ -100,8 +100,8 @@ exit $rc; # convert time string sub convertTime { - my ($seconds, $micro) = split(/\./, $_[0]); - return strftime("%A %D %T", localtime($seconds)); + my ($seconds, $micro) = split(/\./, $_[0]); + return strftime("%A %D %T", localtime($seconds)); } diff --git a/xCAT-rmc/scripts/mtime b/xCAT-rmc/scripts/mtime index 784689257..4981d994a 100755 --- a/xCAT-rmc/scripts/mtime +++ b/xCAT-rmc/scripts/mtime @@ -14,14 +14,14 @@ $mtime = 0; $startdir = @ARGV[0]; chomp($startdir); -if (-d $startdir) { #directory - &directory("/", *mtime); +if (-d $startdir) { #directory + &directory("/", *mtime); } -elsif (-f $startdir) { #file - my ($dv, $in, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($startdir); - $mtime = $mtime1; +elsif (-f $startdir) { #file + my ($dv, $in, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($startdir); + $mtime = $mtime1; } -else { exit 1; } #not a recognized format +else { exit 1; } #not a recognized format print $mtime; exit 0; @@ -34,75 +34,75 @@ exit 0; # sub directory { - local ($dir, *mtime, $nlink) = @_; - local ($dev, $ino, $mode, $subcount, $dirtry, $namedirtry, $name1, $name, - $dir1, $mtime1, $dv, $in, $m, $nl, $u, $g, $rd, $siz, $at); + local ($dir, *mtime, $nlink) = @_; + local ($dev, $ino, $mode, $subcount, $dirtry, $namedirtry, $name1, $name, + $dir1, $mtime1, $dv, $in, $m, $nl, $u, $g, $rd, $siz, $at); - ($dev, $ino, $nlink) = stat($dir) unless $nlink; + ($dev, $ino, $nlink) = stat($dir) unless $nlink; - $dirtry = $startdir; - $dirtry .= $dir; + $dirtry = $startdir; + $dirtry .= $dir; - $dir1 = substr($dir, 1); + $dir1 = substr($dir, 1); - opendir(DIR, $dirtry); + opendir(DIR, $dirtry); - local (@filenames) = readdir(DIR); + local (@filenames) = readdir(DIR); - if ($nlink == 2) { - for (@filenames) { - next if $_ eq '.'; - next if $_ eq '..'; - # - # Check to see if the mtime of this file is later than the current mtime - # - $name = "$dir/$_"; - $name1 = "$dir1/$_"; - $name2 = "/$startdir/$name1"; + if ($nlink == 2) { + for (@filenames) { + next if $_ eq '.'; + next if $_ eq '..'; + # + # Check to see if the mtime of this file is later than the current mtime + # + $name = "$dir/$_"; + $name1 = "$dir1/$_"; + $name2 = "/$startdir/$name1"; - ($dv, $in, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($name2); + ($dv, $in, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($name2); - if ($mtime1 > $mtime) { - $mtime = $mtime1; - } + if ($mtime1 > $mtime) { + $mtime = $mtime1; + } + } } - } - else { - $subcount = $nlink - 2; - for (@filenames) { - next if $_ eq '.'; - next if $_ eq '..'; + else { + $subcount = $nlink - 2; + for (@filenames) { + next if $_ eq '.'; + next if $_ eq '..'; - # - # Check to see if the mtime of this file is later than the current mtime - # + # + # Check to see if the mtime of this file is later than the current mtime + # - $name = "$dir/$_"; - $name1 = "$dir1/$_"; - $name2 = "/$startdir/$name1"; + $name = "$dir/$_"; + $name1 = "$dir1/$_"; + $name2 = "/$startdir/$name1"; - ($dev, $ino, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($name2); + ($dev, $ino, $m, $nl, $u, $g, $rd, $siz, $at, $mtime1) = stat($name2); - if ($mtime1 > $mtime && !(-d $name2)) { - $mtime = $mtime1; - } + if ($mtime1 > $mtime && !(-d $name2)) { + $mtime = $mtime1; + } - next if $subcount == 0; + next if $subcount == 0; - # - # Recurse into next lower subdirectory - # + # + # Recurse into next lower subdirectory + # - $namedirtry = "/$startdir/"; - $namedirtry .= $name; + $namedirtry = "/$startdir/"; + $namedirtry .= $name; - ($dev, $ino, $mode, $nlink) = lstat($namedirtry); + ($dev, $ino, $mode, $nlink) = lstat($namedirtry); - #next unless -d _; - next unless { $nlink > 1 } - &directory($name, *mtime, $nlink); + #next unless -d _; + next unless { $nlink > 1 } + &directory($name, *mtime, $nlink); - --$subcount; + --$subcount; + } } - } } diff --git a/xCAT-rmc/scripts/rmcmetrixmon b/xCAT-rmc/scripts/rmcmetrixmon index 6561f20b1..64a5ec0c8 100755 --- a/xCAT-rmc/scripts/rmcmetrixmon +++ b/xCAT-rmc/scripts/rmcmetrixmon @@ -1,9 +1,11 @@ #!/usr/bin/env perl use Getopt::Long; + BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } + #Modules to use use lib "$::XCATROOT/lib/perl"; use xCAT::Utils; @@ -20,11 +22,11 @@ use xCAT_monitoring::rmcmetrix; ############################################################## sub err_handle { - my ($c, $m) = @_; - if($c != 0){ - print "ERROR: $m\n"; - exit($c); - } + my ($c, $m) = @_; + if ($c != 0) { + print "ERROR: $m\n"; + exit($c); + } } ############################################################### #sub getcrontime @@ -35,57 +37,57 @@ sub err_handle ############################################################## sub getcrontime { - my $minute = shift @_; - my ($min, $hour, $day, $month); - my $temp = undef; - my $temp1 = undef; - $temp = $minute % 60 ; - if($temp < 2){ - $min = '*'; - } else { - $temp1 = $temp; - $min = '0'; - while($temp1 < 60){ - $min = $min.",$temp1"; - $temp1 = $temp1 + $temp; - } - } - $minute = int $minute/60; - $temp = $minute % 24; - if($temp < 2){ - $hour = '*'; - } else { - $temp1 = $temp; - $hour = '0'; - while($temp1 < 24){ - $hour = $hour.",$temp1"; - $temp1 = $temp1 + $temp; - } - } - $minute = int $minute/24; - $temp = $minute % 31; - if($temp < 2){ - $day = '*'; - } else { - $temp1 = $temp; - $day = '0'; - while($day < 31){ - $day = $day.",$temp1"; - $temp1 = $temp1 + $temp; - } - } - $minute = int $minute/31; - $temp = $minute % 12; - if($temp < 2){ - $month = '*'; - } else { - $month = '0'; - while($month < 12){ - $month = $month.",$temp1"; - $temp1 = $temp1 + $temp; - } - } - return "$min $hour $day $month *"; + my $minute = shift @_; + my ($min, $hour, $day, $month); + my $temp = undef; + my $temp1 = undef; + $temp = $minute % 60; + if ($temp < 2) { + $min = '*'; + } else { + $temp1 = $temp; + $min = '0'; + while ($temp1 < 60) { + $min = $min . ",$temp1"; + $temp1 = $temp1 + $temp; + } + } + $minute = int $minute / 60; + $temp = $minute % 24; + if ($temp < 2) { + $hour = '*'; + } else { + $temp1 = $temp; + $hour = '0'; + while ($temp1 < 24) { + $hour = $hour . ",$temp1"; + $temp1 = $temp1 + $temp; + } + } + $minute = int $minute / 24; + $temp = $minute % 31; + if ($temp < 2) { + $day = '*'; + } else { + $temp1 = $temp; + $day = '0'; + while ($day < 31) { + $day = $day . ",$temp1"; + $temp1 = $temp1 + $temp; + } + } + $minute = int $minute / 31; + $temp = $minute % 12; + if ($temp < 2) { + $month = '*'; + } else { + $month = '0'; + while ($month < 12) { + $month = $month . ",$temp1"; + $temp1 = $temp1 + $temp; + } + } + return "$min $hour $day $month *"; } ################################################################ @@ -97,61 +99,61 @@ sub getcrontime # 3. To start a data collector # ./rmcmetrixmon init resourceclass resoucename attr0, attr1, attr2, ... minute # 4. To stop all data collectors and data consolidators -# ./rmcmetrixmon clean -# 5. To work as a data collector +# ./rmcmetrixmon clean +# 5. To work as a data collector # ./rmcmetrixmon data resourceclass resourcename attr0, attr1, attr2, ... minute -# 6. To work as a data consolidator +# 6. To work as a data consolidator # ./rmcmetrixmon sum resourceclass attr0, attr1, attr2, ... minute -################################################################# +################################################################# -my $cmd = $ARGV[0]; -my @tabs = (); -my $entry = undef; -my $minute = undef; +my $cmd = $ARGV[0]; +my @tabs = (); +my $entry = undef; +my $minute = undef; my $crontime = undef; -my $code = 0; -my $msg = undef; -if($cmd eq 'init'){ - if ($ARGV[1] eq 'rrdserver'){ - $code = xCAT_monitoring::rrdutil::start_RRD_server('13900', "/var/rrd/"); - &err_handle($code, "can't start RRD server"); - exit 0; - } - $minute = $ARGV[4]; - $crontime = &getcrontime($minute); - ($code, $msg) = xCAT::Utils->add_cron_job("$crontime /opt/xcat/sbin/rmcmon/rmcmetrixmon data $ARGV[1] $ARGV[2] $ARGV[3] $ARGV[4] > /dev/null"); - &err_handle($code, $msg); - if(xCAT::Utils->isMN()){ - $minute = $minute * 5; - $crontime = &getcrontime($minute); - ($code, $msg) = xCAT::Utils->add_cron_job("$crontime /opt/xcat/sbin/rmcmon/rmcmetrixmon sum $ARGV[1] $ARGV[3] $ARGV[4] > /dev/null"); - &err_handle($code, $msg); - } -} elsif ($cmd eq 'clean'){ - if ($ARGV[1] eq 'rrdserver'){ - $code = xCAT_monitoring::rrdutil::stop_RRD_server(); - &err_handle($code, "can't stop RRD server"); - exit 0; - } +my $code = 0; +my $msg = undef; +if ($cmd eq 'init') { + if ($ARGV[1] eq 'rrdserver') { + $code = xCAT_monitoring::rrdutil::start_RRD_server('13900', "/var/rrd/"); + &err_handle($code, "can't start RRD server"); + exit 0; + } + $minute = $ARGV[4]; + $crontime = &getcrontime($minute); + ($code, $msg) = xCAT::Utils->add_cron_job("$crontime /opt/xcat/sbin/rmcmon/rmcmetrixmon data $ARGV[1] $ARGV[2] $ARGV[3] $ARGV[4] > /dev/null"); + &err_handle($code, $msg); + if (xCAT::Utils->isMN()) { + $minute = $minute * 5; + $crontime = &getcrontime($minute); + ($code, $msg) = xCAT::Utils->add_cron_job("$crontime /opt/xcat/sbin/rmcmon/rmcmetrixmon sum $ARGV[1] $ARGV[3] $ARGV[4] > /dev/null"); + &err_handle($code, $msg); + } +} elsif ($cmd eq 'clean') { + if ($ARGV[1] eq 'rrdserver') { + $code = xCAT_monitoring::rrdutil::stop_RRD_server(); + &err_handle($code, "can't stop RRD server"); + exit 0; + } - $msg = `rm -rf /var/rrd/*`; - &err_handle($?, $msg); - @tabs = `/usr/bin/crontab -l 2>/dev/null;`; - foreach $entry (@tabs){ - chomp($entry); - if($entry =~ /rmcmetrixmon/){ - ($code, $msg) = xCAT::Utils->remove_cron_job($entry); - &err_handle($code, $msg); - } - } -} elsif ($cmd eq 'data'){ - ($code, $msg) = &xCAT_monitoring::rmcmetrix::getmetrix($ARGV[1], $ARGV[2], $ARGV[3], $ARGV[4]); - &err_handle($code, $msg); -} elsif ($cmd eq 'sum'){ - ($code, $msg) = &xCAT_monitoring::rmcmetrix::get_sum_metrix($ARGV[2], $ARGV[3]); - &err_handle($code, $msg); + $msg = `rm -rf /var/rrd/*`; + &err_handle($?, $msg); + @tabs = `/usr/bin/crontab -l 2>/dev/null;`; + foreach $entry (@tabs) { + chomp($entry); + if ($entry =~ /rmcmetrixmon/) { + ($code, $msg) = xCAT::Utils->remove_cron_job($entry); + &err_handle($code, $msg); + } + } +} elsif ($cmd eq 'data') { + ($code, $msg) = &xCAT_monitoring::rmcmetrix::getmetrix($ARGV[1], $ARGV[2], $ARGV[3], $ARGV[4]); + &err_handle($code, $msg); +} elsif ($cmd eq 'sum') { + ($code, $msg) = &xCAT_monitoring::rmcmetrix::get_sum_metrix($ARGV[2], $ARGV[3]); + &err_handle($code, $msg); } else { - print "ERROR:Invalid parameter\n"; + print "ERROR:Invalid parameter\n"; } 1; diff --git a/xCAT-rmc/scripts/updatexcatnodestatus b/xCAT-rmc/scripts/updatexcatnodestatus index f25bcdaf2..3198698a8 100755 --- a/xCAT-rmc/scripts/updatexcatnodestatus +++ b/xCAT-rmc/scripts/updatexcatnodestatus @@ -6,180 +6,182 @@ BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use strict; use Getopt::Std; use POSIX qw(strftime); -my $respname=$ENV{ERRM_ER_NAME}; -my $cond_name=$ENV{ERRM_COND_NAME}; -my $batch=0; -if (exists($ENV{ERRM_COND_BATCH})) { $batch=$ENV{ERRM_COND_BATCH}; } +my $respname = $ENV{ERRM_ER_NAME}; +my $cond_name = $ENV{ERRM_COND_NAME}; +my $batch = 0; +if (exists($ENV{ERRM_COND_BATCH})) { $batch = $ENV{ERRM_COND_BATCH}; } my $currtime; if (!$batch) { my $node; my $status; if ($cond_name eq "NodeReachability") { - $node=$ENV{ERRM_RSRC_NAME}; - $status=$ENV{ERRM_VALUE}; - } elsif ($cond_name eq "NodeReachability_H") { - # Parse the ERRM_VALUE attribute, which will contain the - # LastEvent structured data variable from the Condition class - # The fields in this structured data variable are documented below where we parse them out. - my $event = $ENV{ERRM_VALUE}; - $event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them - - # This parse the LastEvent - my ( # split the SD into the following fields: - $Occurred, # One if the condition has been triggered - $ErrNum, # Non-zero if there was in error in the event registration - $ErrMsg, # The string msg related to ErrNum - $EventFlags, # Bit mask giving some additional info about the event - $EventTime, # Time of event expressed in seconds since 1/1/1970 - $EventTimeMicros, # Number of microseconds past EventTime - $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered - $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), - # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), - # this will be the FMS. - $NumAttrs, # Number of attr values from the resource returned in this event - $NumAttrsInExpr, # How many of the above were attributes in the event expression - $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added - # to LastEvent, this will be the element right after this one. - $AttrArray # This list of attribute names, types, and values - ) = split(/,/, $event, 12); - - my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list - - my $j = 0; # index into attrArray - for (my $i=0; $i<$NumAttrs; $i++) { - my $attrName = $attrArray[$j++]; - my $attrType = $attrArray[$j++]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. - my $attrValue = $attrArray[$j++]; - if ($attrName eq '"Name"') { $node = $attrValue; } - if ($attrName eq '"Status"') { $status = $attrValue; } - } - } else { - `logger -t xcat -p local4.err "[mon]: updatexcatnodestatus: This script does not handle condition $cond_name"`; - exit 1; + $node = $ENV{ERRM_RSRC_NAME}; + $status = $ENV{ERRM_VALUE}; + } elsif ($cond_name eq "NodeReachability_H") { + + # Parse the ERRM_VALUE attribute, which will contain the + # LastEvent structured data variable from the Condition class + # The fields in this structured data variable are documented below where we parse them out. + my $event = $ENV{ERRM_VALUE}; + $event =~ s/^\[(.*)\]$/$1/; # SD variables have square brackets around them + + # This parse the LastEvent + my ( # split the SD into the following fields: + $Occurred, # One if the condition has been triggered + $ErrNum, # Non-zero if there was in error in the event registration + $ErrMsg, # The string msg related to ErrNum + $EventFlags, # Bit mask giving some additional info about the event + $EventTime, # Time of event expressed in seconds since 1/1/1970 + $EventTimeMicros, # Number of microseconds past EventTime + $ResourceHandle, # Binary address of the RMC resource that caused the condition to be triggered + $NodeName, # The node on which the event occurred. For conditions that use the management domain scope (4), + # this will be the leaf node. For conditions that use the local scope (e.g. NodeReachability), + # this will be the FMS. + $NumAttrs, # Number of attr values from the resource returned in this event + $NumAttrsInExpr, # How many of the above were attributes in the event expression + $IndexForAttrs, # The starting index of the array of values. Until new fixed fields are added + # to LastEvent, this will be the element right after this one. + $AttrArray # This list of attribute names, types, and values + ) = split(/,/, $event, 12); + + my @attrArray = split(/,/, $AttrArray); # Note: parsing this way does not support SDs or SD Arrays that may be in this list + + my $j = 0; # index into attrArray + for (my $i = 0 ; $i < $NumAttrs ; $i++) { + my $attrName = $attrArray[ $j++ ]; + my $attrType = $attrArray[ $j++ ]; # Types <= 8 are "simple" types. Types > 8 are SDs and arrays. + my $attrValue = $attrArray[ $j++ ]; + if ($attrName eq '"Name"') { $node = $attrValue; } + if ($attrName eq '"Status"') { $status = $attrValue; } + } + } else { +`logger -t xcat -p local4.err "[mon]: updatexcatnodestatus: This script does not handle condition $cond_name"`; + exit 1; } my $status_string; - if ($status == 1) { $status_string="alive"; } - else { $status_string="unreachable"; } - + if ($status == 1) { $status_string = "alive"; } + else { $status_string = "unreachable"; } + if (!$currtime) { - my ( - $sec, $min, $hour, $mday, $mon, - $year, $wday, $yday, $isdst - ) - = localtime(time); - $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", - $mon + 1, $mday, $year + 1900, - $hour, $min, $sec); + my ( + $sec, $min, $hour, $mday, $mon, + $year, $wday, $yday, $isdst + ) + = localtime(time); + $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", + $mon + 1, $mday, $year + 1900, + $hour, $min, $sec); } - my $result=`$::XCATROOT/sbin/chtab node=$node nodelist.status=$status_string nodelist.statustime="$currtime" 2>&1`; - my $code=$?; + my $result = `$::XCATROOT/sbin/chtab node=$node nodelist.status=$status_string nodelist.statustime="$currtime" 2>&1`; + my $code = $?; if ($code) { - `logger -t xcat -p local4.err "[mon]: Error saving node status ($node,$status_string) to xCAT:$result"`; - exit $code; +`logger -t xcat -p local4.err "[mon]: Error saving node status ($node,$status_string) to xCAT:$result"`; + exit $code; } -} else { #batch event +} else { #batch event if ($cond_name ne "NodeReachability_Batch") { - `logger -t xcat -p local4.err "[mon]: updatexcatnodestatus: This script does not handle condition $cond_name"`; - exit 1; +`logger -t xcat -p local4.err "[mon]: updatexcatnodestatus: This script does not handle condition $cond_name"`; + exit 1; } if ($ENV{ERRM_COND_BATCH_NUM} > 0) { + #check if event detail file exist - if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})){ - xCAT::MsgUtils->message('S', "logeventtoxcat: no event detail file specified in the response $respname for condition $cond_name.\n"); - exit (1); - } - - my $filename=$ENV{ERRM_EVENT_DETAIL_FILE}; - if (! -f $filename) { - xCAT::MsgUtils->message('S', "logeventtoxcat: cannot find event detail file $filename in response $respname for condition $cond_name.\n"); - exit (1); - } + if (!exists($ENV{ERRM_EVENT_DETAIL_FILE})) { + xCAT::MsgUtils->message('S', "logeventtoxcat: no event detail file specified in the response $respname for condition $cond_name.\n"); + exit(1); + } - open(FILE1, "<$filename"); - readline(FILE1);#skip first 2 lines + my $filename = $ENV{ERRM_EVENT_DETAIL_FILE}; + if (!-f $filename) { + xCAT::MsgUtils->message('S', "logeventtoxcat: cannot find event detail file $filename in response $respname for condition $cond_name.\n"); + exit(1); + } + + open(FILE1, "<$filename"); + readline(FILE1); #skip first 2 lines readline(FILE1); - my $line1=readline(FILE1); - my @aTemp=split(/=/, $line1); - my $num_events=$aTemp[1]; - close(FILE1); + my $line1 = readline(FILE1); + my @aTemp = split(/=/, $line1); + my $num_events = $aTemp[1]; + close(FILE1); - my $count; - my @active=(); - my @inactive=(); - my %new_value=(); - for ($count = 1; $count <= $num_events; $count++) { - my $content=`sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $filename`; - - my @content_array=split(/\n/, $content); - pop(@content_array); #get rid of last line - shift(@content_array); #get rid of firt line - - my %content_hash=(); - foreach(@content_array) { + my $count; + my @active = (); + my @inactive = (); + my %new_value = (); + for ($count = 1 ; $count <= $num_events ; $count++) { + my $content = `sed -n "/Event $count:/,/ERRM_COND_BATCH/ p" $filename`; + + my @content_array = split(/\n/, $content); + pop(@content_array); #get rid of last line + shift(@content_array); #get rid of firt line + + my %content_hash = (); + foreach (@content_array) { /([^\=]+)\=(.*)/; - $content_hash{$1}=$2; - } + $content_hash{$1} = $2; + } - my $node; - my $status; - my $status_string; - $node=$content_hash{ERRM_RSRC_NAME}; - $status=$content_hash{ERRM_VALUE}; + my $node; + my $status; + my $status_string; + $node = $content_hash{ERRM_RSRC_NAME}; + $status = $content_hash{ERRM_VALUE}; - if ($status == 1) { $new_value{$node}=1; } - else { $new_value{$node}=0; } - } #end for + if ($status == 1) { $new_value{$node} = 1; } + else { $new_value{$node} = 0; } + } #end for foreach my $node (keys %new_value) { - if ($new_value{$node} == 1) { push(@active, $node);} - else { push(@inactive, $node);} - } #end foreach + if ($new_value{$node} == 1) { push(@active, $node); } + else { push(@inactive, $node); } + } #end foreach - if (@active > 0) { - if (!$currtime) { - my ( - $sec, $min, $hour, $mday, $mon, - $year, $wday, $yday, $isdst - ) - = localtime(time); - $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", - $mon + 1, $mday, $year + 1900, - $hour, $min, $sec); - } - my $node_string=join(',',@active); - my $result=`XCATBYPASS=Y $::XCATROOT/bin/nodech $node_string nodelist.status=active nodelist.statustime="$currtime" 2>&1`; - my $code=$?; - if ($code) { - `logger -t xcat -p local4.warning "[mon]: Error saving node status ($node_string,active) to xCAT:$result"`; - } - } + if (@active > 0) { + if (!$currtime) { + my ( + $sec, $min, $hour, $mday, $mon, + $year, $wday, $yday, $isdst + ) + = localtime(time); + $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", + $mon + 1, $mday, $year + 1900, + $hour, $min, $sec); + } + my $node_string = join(',', @active); + my $result = `XCATBYPASS=Y $::XCATROOT/bin/nodech $node_string nodelist.status=active nodelist.statustime="$currtime" 2>&1`; + my $code = $?; + if ($code) { +`logger -t xcat -p local4.warning "[mon]: Error saving node status ($node_string,active) to xCAT:$result"`; + } + } if (@inactive > 0) { - if (!$currtime) { - my ( - $sec, $min, $hour, $mday, $mon, - $year, $wday, $yday, $isdst - ) - = localtime(time); - $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", - $mon + 1, $mday, $year + 1900, - $hour, $min, $sec); - } - my $node_string=join(',',@inactive); - my $result=`XCATBYPASS=Y $::XCATROOT/bin/nodech $node_string nodelist.status=inactive nodelist.statustime="$currtime" 2>&1`; + if (!$currtime) { + my ( + $sec, $min, $hour, $mday, $mon, + $year, $wday, $yday, $isdst + ) + = localtime(time); + $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", + $mon + 1, $mday, $year + 1900, + $hour, $min, $sec); + } + my $node_string = join(',', @inactive); + my $result = `XCATBYPASS=Y $::XCATROOT/bin/nodech $node_string nodelist.status=inactive nodelist.statustime="$currtime" 2>&1`; - my $code=$?; - if ($code) { - `logger -t xcat -p local4.warning "[mon]: Error saving node status ($node_string,inactive) to xCAT:$result"`; - } - } - } + my $code = $?; + if ($code) { +`logger -t xcat -p local4.warning "[mon]: Error saving node status ($node_string,inactive) to xCAT:$result"`; + } + } + } } exit 0 diff --git a/xCAT-server/bin/replaycons b/xCAT-server/bin/replaycons index 0cb54bfc9..043d972c0 100755 --- a/xCAT-server/bin/replaycons +++ b/xCAT-server/bin/replaycons @@ -3,7 +3,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; @@ -15,8 +15,8 @@ use xCAT::NetworkUtils; use xCAT::MsgUtils; use Getopt::Long; -my $usage_string= -"Usage: +my $usage_string = + "Usage: replaycons node [bps] [tail] replaycons -h|--help replaycons -v|--version @@ -27,93 +27,95 @@ my $usage_string= -h|--help Display this usage statement. -v|--version Display the version number."; -my $version_string="Version 2.0"; +my $version_string = "Version 2.0"; -$Getopt::Long::ignorecase=0; - if(!GetOptions( - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION)) { +$Getopt::Long::ignorecase = 0; +if (!GetOptions( + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION)) { exit(1); - } - if ($::HELP) { +} +if ($::HELP) { print "$usage_string\n"; exit(0); - } - if ($::VERSION) { +} +if ($::VERSION) { print "$version_string\n"; exit(0); - } +} -if (@ARGV<1) { - print "Please specify a node name.\n"; - exit(1); +if (@ARGV < 1) { + print "Please specify a node name.\n"; + exit(1); } - + my $node = @ARGV[0]; -my $bps = 19200; -if (@ARGV>1) { - $bps=@ARGV[1]; - if ($bps==0) {$bps = 19200;} +my $bps = 19200; +if (@ARGV > 1) { + $bps = @ARGV[1]; + if ($bps == 0) { $bps = 19200; } } -my $tail=0; -if (@ARGV>2) { $tail=@ARGV[2];} +my $tail = 0; +if (@ARGV > 2) { $tail = @ARGV[2]; } print "node=$node, bps=$bps, tail=$tail\n"; # get the conserver for the node my $conserver; my $hmtab = xCAT::Table->new('nodehm'); if ($hmtab) { - my $ent=$hmtab->getNodeAttribs($node,['node', 'conserver']); - if ($ent->{conserver}) {$conserver=$ent->{conserver};} + my $ent = $hmtab->getNodeAttribs($node, [ 'node', 'conserver' ]); + if ($ent->{conserver}) { $conserver = $ent->{conserver}; } } else { - print "nodehm table cannot be opened\n"; - exit(1); + print "nodehm table cannot be opened\n"; + exit(1); } my $file = "/var/log/consoles/$node"; + #use confluent if it is there if ((-x "/opt/confluent/bin/confetty") || (-x "/usr/bin/confetty")) { - $file = "/var/log/confluent/consoles/$node"; + $file = "/var/log/confluent/consoles/$node"; } + #print "file=$file\n"; #if has conserver, goto conserver the execute replaycons command -my @hostinfo=xCAT::NetworkUtils->determinehostname(); -my %iphash=(); -foreach(@hostinfo) {$iphash{$_}=1;} +my @hostinfo = xCAT::NetworkUtils->determinehostname(); +my %iphash = (); +foreach (@hostinfo) { $iphash{$_} = 1; } if (($conserver) && ($iphash{$conserver} != 1)) { - system("ssh -o BatchMode=yes $conserver $::XCATROOT/bin/replaycons $node $bps $tail 2>&1"); - exit(0); + system("ssh -o BatchMode=yes $conserver $::XCATROOT/bin/replaycons $node $bps $tail 2>&1"); + exit(0); } - -my $cps = $bps / 8; -my $ms = 1 / $cps; -my $msc = 0; + +my $cps = $bps / 8; +my $ms = 1 / $cps; +my $msc = 0; my $debug = 0; my @c; select(STDOUT); $| = 1; -if(!open(FILE,$file)) { - print "replaycons: cannot open $file\n"; - exit(1); +if (!open(FILE, $file)) { + print "replaycons: cannot open $file\n"; + exit(1); } -if($tail > 0) { - seek(FILE,-$tail,2); +if ($tail > 0) { + seek(FILE, -$tail, 2); } -while() { - @c = split(//); - foreach(@c) { - print $_; - $msc += $ms; - if($msc > .1) { - select(undef, undef, undef, $msc); - $msc = 0; +while () { + @c = split(//); + foreach (@c) { + print $_; + $msc += $ms; + if ($msc > .1) { + select(undef, undef, undef, $msc); + $msc = 0; + } } - } } close(FILE); diff --git a/xCAT-server/build-readme b/xCAT-server/build-readme index 3a7b86ade..459b380f1 100755 --- a/xCAT-server/build-readme +++ b/xCAT-server/build-readme @@ -6,14 +6,17 @@ # html version). use strict; + #use lib '.'; -my $toolsdir = 'share/xcat/tools'; +my $toolsdir = 'share/xcat/tools'; my $textreadme = "$toolsdir/README.txt"; my $htmlreadme = "$toolsdir/README.html"; + #my $cachedir = '/tmp'; my @tools = getToolList($toolsdir); + #foreach (@tools) { print "$_\n"; } # Put the intro text in the readme files @@ -24,14 +27,14 @@ writeintro(\*TXT, \*HTML, @tools); # Run each tool with --help flag foreach my $toolfile (@tools) { - my $cmd = "./$toolsdir/$toolfile --help"; + my $cmd = "./$toolsdir/$toolfile --help"; my $output = `$cmd`; - if ($?) { - my $err = "Error: execution of '$cmd' failed with rc=" . ($?>>8) . ".\n"; - print $err; - $output .= $err; - } - writetoolhelp(\*TXT, \*HTML, $toolfile, $output); + if ($?) { + my $err = "Error: execution of '$cmd' failed with rc=" . ($? >> 8) . ".\n"; + print $err; + $output .= $err; + } + writetoolhelp(\*TXT, \*HTML, $toolfile, $output); } # close files @@ -44,50 +47,51 @@ exit; # get the list of tool script files. sub getToolList { - my $toolsdir = shift; + my $toolsdir = shift; - # 1st get toplevel dir listing - opendir(DIR, $toolsdir) or die "Error: could not read $toolsdir.\n"; - my @files = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $toolsdir) or die "Error: could not read $toolsdir.\n"; + my @files = grep !/^\./, readdir(DIR); # / + close(DIR); - # remove files that are not regular files (not dirs) and executable - my @newlist; - foreach my $f (@files) { - my $file = "$toolsdir/$f"; - if ((-f $file) && (-x $file)) { push @newlist, $f; } - } - #foreach (@files) { print "$_\n"; } - #foreach (@newlist) { print "$_\n"; } + # remove files that are not regular files (not dirs) and executable + my @newlist; + foreach my $f (@files) { + my $file = "$toolsdir/$f"; + if ((-f $file) && (-x $file)) { push @newlist, $f; } + } - return sort @newlist; + #foreach (@files) { print "$_\n"; } + #foreach (@newlist) { print "$_\n"; } + + return sort @newlist; } # print some text to both readmes sub printtoboth { - my $txt = shift; - my $html = shift; - my $str = shift; - print $txt $str; - print $html $str; + my $txt = shift; + my $html = shift; + my $str = shift; + print $txt $str; + print $html $str; } # write the up front stuff of the readme sub writeintro { - my $txt = shift; # the file handle to the txt readme file - my $html = shift; # the file handle to the html readme file - # the rest of @_ contains the tool files in the dir + my $txt = shift; # the file handle to the txt readme file + my $html = shift; # the file handle to the html readme file + # the rest of @_ contains the tool files in the dir - # write title part of readmes - print $txt <<'TXTEOS1'; + # write title part of readmes + print $txt <<'TXTEOS1'; xCAT TOOL DESCRIPTIONS ---------------------- TXTEOS1 - print $html <<'HTMLEOS1'; + print $html <<'HTMLEOS1'; xCAT Tool Descriptions @@ -96,17 +100,17 @@ TXTEOS1

xCAT Tool Descriptions

HTMLEOS1 - # write the table of contents for the html readme - print $html "
  • Introduction\n"; - foreach my $tool (@_) { - print $html "
  • $tool\n"; - } - print $html "
\n"; + # write the table of contents for the html readme + print $html "
  • Introduction\n"; + foreach my $tool (@_) { + print $html "
  • $tool\n"; + } + print $html "
\n"; - # write the intro - print $html "

Introduction

\n"; + # write the intro + print $html "

Introduction

\n"; - printtoboth $txt, $html, <<'EOS1'; + printtoboth $txt, $html, <<'EOS1'; This is a list of additional tools that are provided by xCAT. They are located in /opt/xcat/share/xcat/tools/, but should also be in your path. Many of these tools have been contributed by xCAT users that are not part of the core xCAT @@ -116,20 +120,20 @@ risk. If you have problems with a tool, post to the xCAT mailing list and the author will try to help you. EOS1 - print $html "

\n"; + print $html "

\n"; } # write the help for one tool sub writetoolhelp { - my $txt = shift; # the file handle to the txt readme file - my $html = shift; # the file handle to the html readme file - my $toolname = shift; # the script name of the tool - my $toolhelp = shift; # the --help output from the tool + my $txt = shift; # the file handle to the txt readme file + my $html = shift; # the file handle to the html readme file + my $toolname = shift; # the script name of the tool + my $toolhelp = shift; # the --help output from the tool - # write the heading for this tool - print $txt <<"TXTEOS2"; + # write the heading for this tool + print $txt <<"TXTEOS2"; $toolname @@ -137,28 +141,29 @@ $toolname TXTEOS2 - print $html <<"HTMLEOS2"; + print $html <<"HTMLEOS2";

$toolname

 HTMLEOS2
 
-	# write the actual contents of the tool help
-	printtoboth $txt, $html, $toolhelp;
+    # write the actual contents of the tool help
+    printtoboth $txt, $html, $toolhelp;
 
-	# finish up
-	print $html <<"HTMLEOS3";
+    # finish up
+    print $html <<"HTMLEOS3";
 
HTMLEOS3 } sub writeending { - my $html = shift; - # finish up the html readme - print $html <<'HTMLEOS4'; + my $html = shift; + + # finish up the html readme + print $html <<'HTMLEOS4'; HTMLEOS4 -} \ No newline at end of file +} diff --git a/xCAT-server/sbin/chtab b/xCAT-server/sbin/chtab index ae2a447ff..816174c61 100755 --- a/xCAT-server/sbin/chtab +++ b/xCAT-server/sbin/chtab @@ -10,157 +10,161 @@ use xCAT::NodeRange; use Getopt::Long; use strict; + #This or something like this must always be available and not depend on server #Otherwise, can't set things to let server run in the first place # sub usage { - print "Usage:\n"; - print " To add or update rows for tables: + print "Usage:\n"; + print " To add or update rows for tables: chtab [keycolname=keyvalue[,keycolname=keyvalue...]] [tablename.colname=newvalue] [tablename.colname=newvalue]...\n"; - print " To delete rows from tables: + print " To delete rows from tables: chtab -d|--delete keycolname=keyvalue[,keycolname=keyvalue...] tablename [tablename]...\n"; - print " To display usage and other information: + print " To display usage and other information: chtab [-h|--help|-v|--Version]\n\n"; - print " -d|--delete Delete the rows from a list of tables. + print " -d|--delete Delete the rows from a list of tables. -v|--version Display the version of this command. -h|--help Display this usage information. keycolname=keyvalue a column name-and-value pair that identifies the rows in a table to be changed. tablename.colname=newvalue the new value for the specified row and column of the table.\n"; -} +} my %tables; # options can be bundled up like -vV -Getopt::Long::Configure("bundling") ; -$Getopt::Long::ignorecase=0; +Getopt::Long::Configure("bundling"); +$Getopt::Long::ignorecase = 0; # parse the options -if(!GetOptions( - 'd|delete' => \$::DELETE, - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION,)) +if (!GetOptions( + 'd|delete' => \$::DELETE, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION,)) { - &usage; - exit(1); + &usage; + exit(1); } # display the usage if -h or --help is specified -if ($::HELP) { &usage; exit(0);} +if ($::HELP) { &usage; exit(0); } # display the version statement if -v or --verison is specified if ($::VERSION) { - my $version = xCAT::Utils->Version(); - print "chtab $version\n"; - exit(0); + my $version = xCAT::Utils->Version(); + print "chtab $version\n"; + exit(0); } my $target = shift @ARGV; unless ($target) { - usage; - exit(1); + usage; + exit(1); } -my %keyhash=(); -my @keypairs=split(/,/,$target); +my %keyhash = (); +my @keypairs = split(/,/, $target); if ($keypairs[0] !~ /([^\.\=]+)\.([^\.\=]+)\=(.+)/) { - foreach (@keypairs) { - m/(.*)=(.*)/; - my $key=$1; - my $val=$2; - if (!defined($key) || !defined($val)) { - print "Incorrect argument \"$_\".\n"; - usage; - exit(1); + foreach (@keypairs) { + m/(.*)=(.*)/; + my $key = $1; + my $val = $2; + if (!defined($key) || !defined($val)) { + print "Incorrect argument \"$_\".\n"; + usage; + exit(1); + } + $keyhash{$key} = $val; } - $keyhash{$key}=$val; - } } else { unshift(@ARGV, $target); } if ($::DELETE) { - #delete option is specified - my @tables_to_del=@ARGV; - if(@tables_to_del == 0) { + + #delete option is specified + my @tables_to_del = @ARGV; + if (@tables_to_del == 0) { print "Missing table name.\n"; usage; exit(1); - } - for (@tables_to_del) { - $tables{$_} = xCAT::Table->new($_,-create => 1,-autocommit => 0); - $tables{$_}->delEntries(\%keyhash); - $tables{$_}->commit; - } + } + for (@tables_to_del) { + $tables{$_} = xCAT::Table->new($_, -create => 1, -autocommit => 0); + $tables{$_}->delEntries(\%keyhash); + $tables{$_}->commit; + } } else { - #update or create option - my %tableupdates; - for (@ARGV) { - my $temp; - my $table; - my $column; - my $value; + #update or create option + my %tableupdates; + for (@ARGV) { + my $temp; + my $table; + my $column; + my $value; - ($table,$temp) = split('\.',$_,2); + ($table, $temp) = split('\.', $_, 2); - #try to create the entry if it doesn't exist - unless ($tables{$table}) { - my $tab = xCAT::Table->new($table,-create => 1,-autocommit => 0); - if ($tab) { - $tables{$table}=$tab; - } else { - print "Table $table does not exist.\n"; - exit(1); - } + #try to create the entry if it doesn't exist + unless ($tables{$table}) { + my $tab = xCAT::Table->new($table, -create => 1, -autocommit => 0); + if ($tab) { + $tables{$table} = $tab; + } else { + print "Table $table does not exist.\n"; + exit(1); + } } #splice assignment - if(grep /\+=/, $temp) { - ($column,$value) = split('\+=',$temp,2); + if (grep /\+=/, $temp) { + ($column, $value) = split('\+=', $temp, 2); #grab the current values to check against my ($attrHash) = $tables{$table}->getAttribs(\%keyhash, $column); - my @existing = split(",",$attrHash->{$column}); + my @existing = split(",", $attrHash->{$column}); #if it has values, merge the new and old ones together so no dupes if (@existing) { - my @values = split(",",$value); - my %seen = (); - my @uniq = (); + my @values = split(",", $value); + my %seen = (); + my @uniq = (); my $item; - foreach $item (@existing,@values) { + foreach $item (@existing, @values) { unless ($seen{$item}) { + # if we get here, we have not seen it before $seen{$item} = 1; push(@uniq, $item); } } - $value = join(",",@uniq); + $value = join(",", @uniq); } } + #normal non-splicing assignment - else { - ($column,$value) = split("=",$temp,2); + else { + ($column, $value) = split("=", $temp, 2); } - $tableupdates{$table}{$column}=$value; - } - - #commit all the changes - foreach (keys %tables) { - if (exists($tableupdates{$_})) { - my $rc = $tables{$_}->setAttribs(\%keyhash,\%{$tableupdates{$_}}); - if ($rc) { - $::exitcode = 1; - } + $tableupdates{$table}{$column} = $value; + } + + #commit all the changes + foreach (keys %tables) { + if (exists($tableupdates{$_})) { + my $rc = $tables{$_}->setAttribs(\%keyhash, \%{ $tableupdates{$_} }); + if ($rc) { + $::exitcode = 1; + } + } + $tables{$_}->commit; } - $tables{$_}->commit; - } } if ($::exitcode) { - exit $::exitcode; + exit $::exitcode; } diff --git a/xCAT-server/sbin/configmic b/xCAT-server/sbin/configmic index 5a3b62d49..d9fc8a703 100755 --- a/xCAT-server/sbin/configmic +++ b/xCAT-server/sbin/configmic @@ -1,9 +1,9 @@ #!/usr/bin/env perl -# This script is used to configure the mics on the host. -# This script is run by xdsh from MN/SN to the host +# This script is used to configure the mics on the host. +# This script is run by xdsh from MN/SN to the host # parameters -# -m xcatmaster +# -m xcatmaster # -p the path of the mic configuration file. Generally, it's /tftpboot/xcat/miccfg/miccfg.hostname use strict; @@ -20,16 +20,17 @@ $| = 1; my $tmppath = "/tmp/mictmp"; my $logpath = "/var/log/xcat/"; my $logfile = "$logpath/configmic.log"; -my $micmnt = "/var/mpss/mnt"; +my $micmnt = "/var/mpss/mnt"; mkpath $tmppath; mkpath $micmnt; + #open the log file -open (LOG, ">>$logfile") or die "Error: cannot open $logfile\n"; -print LOG "\n\n====================================================\nStart mic configuratoin: ".`date`."\n"; +open(LOG, ">>$logfile") or die "Error: cannot open $logfile\n"; +print LOG "\n\n====================================================\nStart mic configuratoin: " . `date` . "\n"; my ($master, $cfgpath); -GetOptions ('m=s'=>\$master, 'p=s'=>\$cfgpath); +GetOptions('m=s' => \$master, 'p=s' => \$cfgpath); unless ($master && $cfgpath) { outputmsg("Error: the -m master and -p path arguments must be specified for configmic.\n", 1); } @@ -41,7 +42,7 @@ if ($masterip) { chomp($masterip); my $myip = `ip route get $masterip| head -n 1 | sed 's/^.*src//g' | awk {'print \$1'}`; if ($myip) { - my $myipinfo =`getent hosts $myip`; + my $myipinfo = `getent hosts $myip`; if ($myipinfo && $myipinfo =~ /([^\s]+)\s+([^\s]+)\s+([^\s]+)/) { my $n1 = $2; @@ -67,22 +68,23 @@ unless ($nodename_short) { # download the mic configuration file from master my $cmd = "wget -N --waitretry=10 --random-wait -T 60 http://$master/$cfgpath/miccfg.$nodename_short -P $tmppath"; -my ($rc, $output) = runsyscmd ($cmd); +my ($rc, $output) = runsyscmd($cmd); if ($rc) { $cmd = "wget -N --waitretry=10 --random-wait -T 60 http://$master/$cfgpath/miccfg.$nodename -P $tmppath"; - runsyscmd ($cmd, "Error: failed to download mic configuration file from $master\n", 3); + runsyscmd($cmd, "Error: failed to download mic configuration file from $master\n", 3); } else { + # use the correct short hotname in $nodename_short - $nodename=$nodename_short; + $nodename = $nodename_short; } unless (-r "$tmppath/miccfg.$nodename") { - runsyscmd ("Error: cannot get the mic configuration file from http://$master/$cfgpath/miccfg.$nodename\n", 4); + runsyscmd("Error: cannot get the mic configuration file from http://$master/$cfgpath/miccfg.$nodename\n", 4); } -# parse the configuration file -unless (open (CFGFILE, "<$tmppath/miccfg.$nodename")) { - runsyscmd ("Error: cannot open $tmppath/miccfg.$nodename\n", 5); +# parse the configuration file +unless (open(CFGFILE, "<$tmppath/miccfg.$nodename")) { + runsyscmd("Error: cannot open $tmppath/miccfg.$nodename\n", 5); } # the configureation file should have the following format @@ -99,11 +101,12 @@ my $brgname; my $brgip; my $brgtype; while () { + if (/(\d+):(.*)/) { my $deviceid = $1; - my @params = split (/\|/, $2); + my @params = split(/\|/, $2); foreach (@params) { - my ($n, $v) = split (/=/, $_, 2); + my ($n, $v) = split(/=/, $_, 2); $miccfg{$deviceid}{$n} = $v; if ($n eq 'br') { $brgname = $v; @@ -125,36 +128,39 @@ while () { } } } -close (CFGFILE); +close(CFGFILE); $miclist =~ s/,/ /g; # add the mount entry for mounting of root fs from master to /etc/fstab # e.g. mount $master:/install/mpss3 /var/mpss/mnt $cmd = "grep \'$master:$ospath \' $micmnt /etc/fstab "; -($rc, $output) = runsyscmd ($cmd); +($rc, $output) = runsyscmd($cmd); if ($rc) { + # not found the exact mount entry $cmd = "grep $micmnt /etc/fstab"; - ($rc, $output) = runsyscmd ($cmd); + ($rc, $output) = runsyscmd($cmd); if (!$rc) { + # found the mount to $micmnt with another master or directory, remove the entry and umount it my $trans = $micmnt; $trans =~ s/\//\\\//g; $cmd = "sed \"/$trans/d\" /etc/fstab > $tmppath/fstab.tmp"; - runsyscmd ($cmd, "Error: failed to configure fstab.\n", 6); - copy ("$tmppath/fstab.tmp", "/etc/fstab"); + runsyscmd($cmd, "Error: failed to configure fstab.\n", 6); + copy("$tmppath/fstab.tmp", "/etc/fstab"); $cmd = "umount -l -f $micmnt"; - runsyscmd ($cmd, "Error: failed to run umount -l -f $micmnt\n", 7); + runsyscmd($cmd, "Error: failed to run umount -l -f $micmnt\n", 7); } $cmd = "echo \"$master:$ospath $micmnt nfs timeo=14,intr 1 2\" >>/etc/fstab"; - runsyscmd ($cmd); + runsyscmd($cmd); $cmd = "mount -a"; - runsyscmd ($cmd); + runsyscmd($cmd); } else { + # run mount -a anyway $cmd = "mount -a"; - runsyscmd ($cmd); + runsyscmd($cmd); } # the dir structure in mount opint 'mnt' @@ -175,27 +181,27 @@ if ($rc) { # | |--xx.filelist # | `--xx -# make sure the remote files are accessable +# make sure the remote files are accessable unless (-r "$micmnt/common.filelist") { outputmsg("Error: cannot access the $micmnt/common.filelist\n", 8); } # initialize mic card if it has not been -if (! -f "/etc/mpss/default.conf") { +if (!-f "/etc/mpss/default.conf") { $cmd = "micctrl --initdefaults"; - runsyscmd ($cmd, "Error: failed to initiate the mic configuration file.\n", 200) + runsyscmd($cmd, "Error: failed to initiate the mic configuration file.\n", 200) } # start to configure the mic # stop the mpss service first $cmd = "service mpss stop"; -runsyscmd ($cmd, "Error: failed to stop mpss service.\n", 100); +runsyscmd($cmd, "Error: failed to stop mpss service.\n", 100); # make sute the mpss has been stopped my $i = 5; while ($i > 0) { - $cmd = "service mpss status"; - ($rc, $output) = runsyscmd ($cmd); + $cmd = "service mpss status"; + ($rc, $output) = runsyscmd($cmd); if (grep /mpss is stopped/, @$output) { last; } @@ -204,16 +210,16 @@ while ($i > 0) { } # remove the mic configuration files and source files for ramfs, them will be recreated base on setting -unlink ("/etc/mpss/default.conf"); -foreach my $mic (split (/ /, $miclist)) { - unlink ("/etc/mpss/$mic.conf"); - unlink ("/var/mpss/$mic.filelist"); - rmtree ("/var/mpss/$mic"); +unlink("/etc/mpss/default.conf"); +foreach my $mic (split(/ /, $miclist)) { + unlink("/etc/mpss/$mic.conf"); + unlink("/var/mpss/$mic.filelist"); + rmtree("/var/mpss/$mic"); } # reset the configuration to default $cmd = "micctrl --initdefaults $miclist"; -runsyscmd ($cmd, "Error: failed to initiate the mic devices.\n", 200); +runsyscmd($cmd, "Error: failed to initiate the mic devices.\n", 200); # configure the base dir #$cmd = "micctrl --basedir=/opt/intel/mic/mnt/opt/intel/mic/filesystem/base --list=/opt/intel/mic/mnt/opt/intel/mic/filesystem/base.filelist $miclist"; @@ -221,16 +227,16 @@ runsyscmd ($cmd, "Error: failed to initiate the mic devices.\n", 200); # configure the commondir $cmd = "micctrl --commondir=$micmnt/common --list=$micmnt/common.filelist $miclist"; -runsyscmd ($cmd, "Error: failed to set the common dir for mic file system.\n", 102); +runsyscmd($cmd, "Error: failed to set the common dir for mic file system.\n", 102); # configure the overlay file system -my @ols = split (/,/, $overlay); +my @ols = split(/,/, $overlay); foreach (@ols) { if (/^filelist:(.+)/) { $cmd = "micctrl --overlay=Filelist --source=$micmnt/overlay/$1/ --target=$micmnt/overlay/$1.filelist --state=on $miclist"; - } elsif (/^ofilelist:(.+)/) { # for 2.8.4 and later + } elsif (/^ofilelist:(.+)/) { # for 2.8.4 and later $cmd = "micctrl --overlay=Filelist --source=$micmnt/overlay/rootimg/ --target=$micmnt/overlay/rootimg/opt/mic/$1.filelist --state=on $miclist"; - } elsif (/^pfilelist:(.+)/) { # only for 2.8.3 + } elsif (/^pfilelist:(.+)/) { # only for 2.8.3 $cmd = "micctrl --overlay=Filelist --source=$micmnt/overlay/package/ --target=$micmnt/overlay/package/opt/mic/$1.filelist --state=on $miclist"; } elsif (/^rpm:(.+)/) { $cmd = "micctrl --overlay=RPM --source=$micmnt/overlay/rpm/ --state=on $miclist"; @@ -238,26 +244,27 @@ foreach (@ols) { $cmd = "micctrl --overlay=Simple --source=$micmnt/overlay/simple/$1 --target=$2 --state=on $miclist"; } - runsyscmd ($cmd, "Error: failed to set the overlay dir for mic file system.\n", 103); + runsyscmd($cmd, "Error: failed to set the overlay dir for mic file system.\n", 103); } # configure bridge for mic my ($netbit, $brc, $mtu); if ($brgtype && $brgtype =~ /Internal/i) { $cmd = "micctrl --addbridge=$brgname --type=Internal --ip=$brgip"; - runsyscmd ($cmd, "Error: failed to add bridge for mic.\n", 111); + runsyscmd($cmd, "Error: failed to add bridge for mic.\n", 111); } else { + # for External bridge, it must has been set up correctly # get the ip of the bridge $cmd = "ip -4 addr show"; - ($rc, $output) = runsyscmd ($cmd); + ($rc, $output) = runsyscmd($cmd); $cmd = "ip -4 route show"; - my ($rc2, $output2) = runsyscmd ($cmd); + my ($rc2, $output2) = runsyscmd($cmd); foreach (@$output) { if (/inet\s+([\d\.]+)\/(\d+)\s+brd\s+([\d\.]+) scope global $brgname/) { - $brgip = $1; + $brgip = $1; $netbit = $2; - $brc = $3; + $brc = $3; last; } elsif (/\d+:\s+$brgname:.*mtu\s+(\d+)/) { $mtu = $1; @@ -274,16 +281,18 @@ if ($brgtype && $brgtype =~ /Internal/i) { #$cmd = "echo \"Bridge $brg External $brip $netbit $mtu\" >> /etc/sysconfig/mic/default.conf"; #runsyscmd ($cmd); $cmd = "micctrl --addbridge=$brgname --type=external --ip=$brgip --netbits=$netbit --mtu=$mtu"; - runsyscmd ($cmd, "Error: failed to add bridge for mic.\n", 111); + runsyscmd($cmd, "Error: failed to add bridge for mic.\n", 111); } # do the mic specific configuration foreach my $micid (keys %miccfg) { if ($micid !~ /^\d*$/) { + # not mic specific, return next; } my $micname = $miccfg{$micid}{'name'}; + # set the boot device to be staticramfs so that the osimage don't need to generated for every boot #$cmd = "micctrl --rootdev=StaticRamFS --target=/opt/intel/mic/filesystem/$micname.image mic$micid"; #runsyscmd ($cmd, "Error: failed to set root image for mic.\n", 104); @@ -295,71 +304,73 @@ foreach my $micid (keys %miccfg) { # set the autoboot if ($miccfg{$micid}{'onboot'} =~ /no/i) { $cmd = "micctrl --autoboot=no mic$micid"; - runsyscmd ($cmd, "Error: failed to set the autoboot for mic.\n", 106); - } elsif($miccfg{$micid}{'onboot'} =~ /yes/i) { + runsyscmd($cmd, "Error: failed to set the autoboot for mic.\n", 106); + } elsif ($miccfg{$micid}{'onboot'} =~ /yes/i) { $cmd = "micctrl --autoboot=yes mic$micid"; - runsyscmd ($cmd, "Error: failed to set the autoboot for mic.\n", 106); + runsyscmd($cmd, "Error: failed to set the autoboot for mic.\n", 106); } # set the hostname $cmd = "sed \"s/Hostname .*/Hostname \"$micname\"/\" /etc/mpss/mic$micid.conf > $tmppath/mic$micid.conf"; - runsyscmd ($cmd, "Error: failed to set hostname for mic.\n", 107); - copy ("$tmppath/mic$micid.conf", "/etc/mpss/mic$micid.conf"); + runsyscmd($cmd, "Error: failed to set hostname for mic.\n", 107); + copy("$tmppath/mic$micid.conf", "/etc/mpss/mic$micid.conf"); # configure the Verbose log if ($miccfg{$micid}{'vlog'} =~ /yes/i) { $cmd = "sed \"s/VerboseLogging .*/VerboseLogging \"Enabled\"/\" /etc/mpss/mic$micid.conf > $tmppath/mic$micid.conf"; - runsyscmd ($cmd, "Error: failed to set Verbose log for mic.\n", 108); - copy ("$tmppath/mic$micid.conf", "/etc/mpss/mic$micid.conf"); + runsyscmd($cmd, "Error: failed to set Verbose log for mic.\n", 108); + copy("$tmppath/mic$micid.conf", "/etc/mpss/mic$micid.conf"); } # configure the power management - if (defined ($miccfg{$micid}{'powermgt'})) { + if (defined($miccfg{$micid}{'powermgt'})) { $cmd = "micctrl --pm=set "; - foreach my $item (split (/!/, $miccfg{$micid}{'powermgt'})) { + foreach my $item (split(/!/, $miccfg{$micid}{'powermgt'})) { $cmd .= " --$item "; } $cmd .= " mic$micid"; - runsyscmd ($cmd, "Error: failed to set power management for mic.\n", 109); + runsyscmd($cmd, "Error: failed to set power management for mic.\n", 109); } # configure network for each mic - $cmd = "micctrl --network=static --bridge=".$miccfg{$micid}{br}." --ip=".$miccfg{$micid}{ip}." mic$micid"; - runsyscmd ($cmd, "Error: failed to generate IP configuration for mic.\n", 104); + $cmd = "micctrl --network=static --bridge=" . $miccfg{$micid}{br} . " --ip=" . $miccfg{$micid}{ip} . " mic$micid"; + runsyscmd($cmd, "Error: failed to generate IP configuration for mic.\n", 104); # configure nfs mount for each mic - foreach my $msrc (keys %{$miccfg{'micmount'}}) { + foreach my $msrc (keys %{ $miccfg{'micmount'} }) { my $mntsrc; if (defined $miccfg{$micid}{'statemnt'}) { if ($miccfg{$micid}{'statemnt'} =~ /:/) { + # for 'statemnt' is a nfs server plus dir like 192.168.1:/nfs - $mntsrc = $miccfg{$micid}{'statemnt'}."/$msrc"; + $mntsrc = $miccfg{$micid}{'statemnt'} . "/$msrc"; } else { + # for 'statemnt' is a nfs server ip 192.168.0.1 - $mntsrc = $miccfg{$micid}{'statemnt'}.":/$msrc"; + $mntsrc = $miccfg{$micid}{'statemnt'} . ":/$msrc"; } } else { $mntsrc = "$brgip:/$msrc"; } $cmd = "micctrl --addnfs=$mntsrc --dir=$miccfg{micmount}{$msrc} mic$micid"; - runsyscmd ($cmd, "Error: failed to add nfs mount for mic.\n", 104); + runsyscmd($cmd, "Error: failed to add nfs mount for mic.\n", 104); # since there's a bug that nfsserver cannot be set, just manully change it if ($mntsrc =~ /^(.+):/) { if ($1 ne $brgip) { $cmd = "sed -i \'s/$brgip/$1/g\' /var/mpss/mic$micid/etc/fstab"; - runsyscmd ($cmd, "Error: failed to hack nfs mount for mic.\n", 104); + runsyscmd($cmd, "Error: failed to hack nfs mount for mic.\n", 104); } } } # take the configuration to effect $cmd = "micctrl --resetconfig mic$micid"; - runsyscmd ($cmd, "Error: failed to spread the configuration.\n", 201); + runsyscmd($cmd, "Error: failed to spread the configuration.\n", 201); # back up the /etc/passwd and /etc/shadow which generated by 'micctrl --initdefaults' - system ("/bin/cp -rf /var/mpss/mic$micid/etc/passwd /tmp/mictmp/passwd"); - system ("/bin/cp -rf /var/mpss/mic$micid/etc/shadow /tmp/mictmp/shadow"); + system("/bin/cp -rf /var/mpss/mic$micid/etc/passwd /tmp/mictmp/passwd"); + system("/bin/cp -rf /var/mpss/mic$micid/etc/shadow /tmp/mictmp/shadow"); # copy the system files which generated by genimage to the micdir # e.g. /etc/hosts /etc/passwd ... @@ -367,15 +378,15 @@ foreach my $micid (keys %miccfg) { my $dst = "/var/mpss/mic$micid"; $cmd = "/bin/cp -rf $src $dst"; - runsyscmd ($cmd, "Error: failed to copy the overlay dir.\n", 300); + runsyscmd($cmd, "Error: failed to copy the overlay dir.\n", 300); # append /etc/passwd and /etc/shadow which generated by 'micctrl --initdefaults' - system ("/bin/grep micuser /tmp/mictmp/passwd >> /var/mpss/mic$micid/etc/passwd"); - system ("/bin/grep micuser /tmp/mictmp/shadow >> /var/mpss/mic$micid/etc/shadow"); + system("/bin/grep micuser /tmp/mictmp/passwd >> /var/mpss/mic$micid/etc/passwd"); + system("/bin/grep micuser /tmp/mictmp/shadow >> /var/mpss/mic$micid/etc/shadow"); # generate the static root file system in ramdisk format $cmd = "micctrl --updateramfs mic$micid"; - runsyscmd ($cmd, "Error: failed to generate the static ramfs.\n", 301); + runsyscmd($cmd, "Error: failed to generate the static ramfs.\n", 301); } # start the mpss service after the configuration @@ -384,8 +395,8 @@ system($cmd); $i = 5; while ($i > 0) { - $cmd = "service mpss status"; - ($rc, $output) = runsyscmd ($cmd, "Error: failed to get the status of mpss.\n", 100); + $cmd = "service mpss status"; + ($rc, $output) = runsyscmd($cmd, "Error: failed to get the status of mpss.\n", 100); if (grep /mpss is running/, @$output) { last; } @@ -396,29 +407,30 @@ while ($i > 0) { # notice nodeset command, the configuratoin has been done foreach my $micid (keys %miccfg) { if ($micid !~ /^\d*$/) { + # not mic specific, return next; } - outputmsg ("MICMSG:$miccfg{$micid}{'name'}: Done\n"); + outputmsg("MICMSG:$miccfg{$micid}{'name'}: Done\n"); } print LOG "mpss has been started\n"; -print LOG "\nFinish the mic configuratoin: ".`date`."====================================================\n"; +print LOG "\nFinish the mic configuratoin: " . `date` . "====================================================\n"; -close (LOG); +close(LOG); exit 0; # run command sub runsyscmd { - my $cmd = shift; + my $cmd = shift; my $errmsg = shift; - my $rc = shift; + my $rc = shift; print LOG "---------------------------------------------\n"; print LOG "Run command: $cmd\n"; - if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } + if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } my @output = `$cmd`; my $errcode = 0; @@ -439,9 +451,9 @@ sub runsyscmd { } # display the output message -sub outputmsg{ +sub outputmsg { my $msg = shift; - my $rc =shift; + my $rc = shift; print LOG $msg; print $msg; if ($rc) { diff --git a/xCAT-server/sbin/flashmic b/xCAT-server/sbin/flashmic index 108af6c7e..0a92fd94d 100755 --- a/xCAT-server/sbin/flashmic +++ b/xCAT-server/sbin/flashmic @@ -1,9 +1,9 @@ #!/usr/bin/env perl -# This script is used to flash the mics on the host. -# This script is run by xdsh from MN/SN to the host +# This script is used to flash the mics on the host. +# This script is run by xdsh from MN/SN to the host # parameters -# -m xcatmaster +# -m xcatmaster # -p the path of the mic configuration file. Generally, it's /tftpboot/xcat/miccfg/micflash.hostname use strict; @@ -17,24 +17,25 @@ use Getopt::Long; select STDOUT; $| = 1; -my $tmppath = "/tmp/mictmp"; -my $logpath = "/var/log/xcat/"; -my $logfile = "$logpath/flash.log"; -my $micmnt = "/var/mpss/mnt"; +my $tmppath = "/tmp/mictmp"; +my $logpath = "/var/log/xcat/"; +my $logfile = "$logpath/flash.log"; +my $micmnt = "/var/mpss/mnt"; my $flashpath = "$micmnt/usr/share/mpss/flash"; -if (! -d "$flashpath") { +if (!-d "$flashpath") { $flashpath = "/usr/share/mpss/flash"; } mkpath $tmppath; mkpath $micmnt; + #open the log file -open (LOG, ">>$logfile") or die "Error: cannot open $logfile\n"; -print LOG "\n\n====================================================\nStart mic flashing: ".`date`."\n"; +open(LOG, ">>$logfile") or die "Error: cannot open $logfile\n"; +print LOG "\n\n====================================================\nStart mic flashing: " . `date` . "\n"; my ($master, $cfgpath); -GetOptions ('m=s'=>\$master, 'p=s'=>\$cfgpath); +GetOptions('m=s' => \$master, 'p=s' => \$cfgpath); unless ($master && $cfgpath) { outputmsg("Error: the -m master and -p path arguments must be specified for configmic.\n", 1); } @@ -46,7 +47,7 @@ if ($masterip) { chomp($masterip); my $myip = `ip route get $masterip| head -n 1 | sed 's/^.*src//g' | awk {'print \$1'}`; if ($myip) { - my $myipinfo =`getent hosts $myip`; + my $myipinfo = `getent hosts $myip`; if ($myipinfo && $myipinfo =~ /([^\s]+)\s+([^\s]+)\s+([^\s]+)/) { my $n1 = $2; @@ -72,19 +73,19 @@ unless ($nodename_short) { # download the mic configuration file from master my $cmd = "wget -N --waitretry=10 --random-wait -T 60 http://$master/$cfgpath/micflash.$nodename_short -P $tmppath"; -my ($rc, $output) = runsyscmd ($cmd); +my ($rc, $output) = runsyscmd($cmd); if ($rc) { $cmd = "wget -N --waitretry=10 --random-wait -T 60 http://$master/$cfgpath/micflash.$nodename -P $tmppath"; - runsyscmd ($cmd, "Error: failed to download mic configuration file from $master\n", 3); + runsyscmd($cmd, "Error: failed to download mic configuration file from $master\n", 3); } unless (-r "$tmppath/micflash.$nodename") { - runsyscmd ("Error: cannot get the mic configuration file from http://$master/$cfgpath/micflash.$nodename\n", 4); + runsyscmd("Error: cannot get the mic configuration file from http://$master/$cfgpath/micflash.$nodename\n", 4); } -# parse the configuration file -unless (open (CFGFILE, "<$tmppath/micflash.$nodename")) { - runsyscmd ("Error: cannot open $tmppath/micflash.$nodename\n", 5); +# parse the configuration file +unless (open(CFGFILE, "<$tmppath/micflash.$nodename")) { + runsyscmd("Error: cannot open $tmppath/micflash.$nodename\n", 5); } # the configureation file should have the following format @@ -98,43 +99,45 @@ my $ospath; while () { if (/(\d+):(.*)/) { my $deviceid = $1; - my @params = split (/\|/, $2); + my @params = split(/\|/, $2); foreach (@params) { - my ($n, $v) = split (/=/, $_); + my ($n, $v) = split(/=/, $_); $miccfg{$deviceid}{$n} = $v; } } elsif (/^miclist=(.*)/) { $miclist = $1; } elsif (/^imgpath=(.*)/) { - $ospath= $1; + $ospath = $1; } } -close (CFGFILE); +close(CFGFILE); $miclist =~ s/,/ /g; # add the mount entry for mounting of root fs from master to /etc/fstab # e.g. mount $master:/install/mpss3 /var/mpss/mnt $cmd = "grep \'$master:$ospath \' $micmnt /etc/fstab "; -($rc, $output) = runsyscmd ($cmd); +($rc, $output) = runsyscmd($cmd); if ($rc) { + # not found the exact mount entry $cmd = "grep $micmnt /etc/fstab"; - ($rc, $output) = runsyscmd ($cmd); + ($rc, $output) = runsyscmd($cmd); if (!$rc) { + # found the mount to $micmnt with another master or directory, remove the entry and umount it my $trans = $micmnt; $trans =~ s/\//\\\//g; $cmd = "sed \"/$trans/d\" /etc/fstab > $tmppath/fstab.tmp"; - runsyscmd ($cmd, "Error: failed to configure fstab.\n", 6); - copy ("$tmppath/fstab.tmp", "/etc/fstab"); + runsyscmd($cmd, "Error: failed to configure fstab.\n", 6); + copy("$tmppath/fstab.tmp", "/etc/fstab"); $cmd = "umount -l -f $micmnt"; - runsyscmd ($cmd, "Error: failed to run umount -l -f $micmnt\n", 7); + runsyscmd($cmd, "Error: failed to run umount -l -f $micmnt\n", 7); } $cmd = "echo \"$master:$ospath $micmnt nfs timeo=14,intr 1 2\" >>/etc/fstab"; - runsyscmd ($cmd); + runsyscmd($cmd); $cmd = "mount -a"; - runsyscmd ($cmd); + runsyscmd($cmd); } # make sure the remote flash directory is accessable @@ -146,7 +149,7 @@ unless (-d "$flashpath") { # # # # reset the mic to ready stat $cmd = "micctrl -r -w $miclist"; -($rc, $output) = runsyscmd ($cmd, "Error: failed to reset mic.\n", 100); +($rc, $output) = runsyscmd($cmd, "Error: failed to reset mic.\n", 100); my $micidlist; foreach my $micid (keys %miccfg) { @@ -160,34 +163,34 @@ $micidlist =~ s/^,//; # do the flash $cmd = "micflash -update $flashpath -device $micidlist"; -($rc, $output) = runsyscmd ($cmd); +($rc, $output) = runsyscmd($cmd); # generate the output messages foreach (@$output) { foreach my $line (split /\n/, $_) { - if ($line =~ /^mic(\d+):/) { - $line =~ s/^mic(\d+):/MICMSG:$miccfg{$1}{'name'}:/; - } - print $line."\n"; + if ($line =~ /^mic(\d+):/) { + $line =~ s/^mic(\d+):/MICMSG:$miccfg{$1}{'name'}:/; + } + print $line. "\n"; } } -print LOG "\nFinish the mic flashing: ".`date`."====================================================\n"; +print LOG "\nFinish the mic flashing: " . `date` . "====================================================\n"; -close (LOG); +close(LOG); exit 0; # run command sub runsyscmd { - my $cmd = shift; + my $cmd = shift; my $errmsg = shift; - my $rc = shift; + my $rc = shift; print LOG "---------------------------------------------\n"; print LOG "Run command: $cmd\n"; - if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } + if (!($cmd =~ /2>&1$/)) { $cmd .= ' 2>&1'; } my @output = `$cmd`; my $errcode = 0; @@ -208,9 +211,9 @@ sub runsyscmd { } # display the output message -sub outputmsg{ +sub outputmsg { my $msg = shift; - my $rc =shift; + my $rc = shift; print LOG $msg; print $msg; if ($rc) { diff --git a/xCAT-server/sbin/pcp_collect b/xCAT-server/sbin/pcp_collect index b443148c3..d64ebc2be 100755 --- a/xCAT-server/sbin/pcp_collect +++ b/xCAT-server/sbin/pcp_collect @@ -3,7 +3,7 @@ #package xCAT_monitoring::performance; BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; use xCAT::NodeRange; @@ -20,178 +20,205 @@ use strict; use warnings; 1; performance(); -sub performance - { #opening subroutine - - my $noderef=xCAT_monitoring::monitorctrl->getMonHierarchy(); - #identification of this node - my @hostinfo=xCAT::NetworkUtils->determinehostname(); - #print "hosT:@hostinfo\n"; - my $isSV=xCAT::Utils->isServiceNode(); - #print "is sv is:$isSV \n"; - my %iphash=(); - foreach(@hostinfo) {$iphash{$_}=1;} - if (!$isSV) { $iphash{'noservicenode'}=1;} - my @children; - my $str; - - foreach my $key (keys (%$noderef)) - { #opening foreach1 - #print "opening foreach1 \n"; - #print "key is: $key \n"; - my @key_a=split(':', $key); - if (! $iphash{$key_a[0]}) { next;} - my $mon_nodes=$noderef->{$key}; +sub performance +{ #opening subroutine - foreach(@$mon_nodes) - { #opening foreach2 - my $node=$_->[0]; - my $nodetype=$_->[1]; - #print "node=$node, nodetype=$nodetype\n"; - if (($nodetype) && ($nodetype =~ /$::NODETYPE_OSI/)) - { - push(@children,$node); - } - } #closing foreach2 - } #closing foreach1 - - #print "children:@children\n"; - my $count_child=@children; - if($count_child > 0) - { #opening if count_child 1 - #print "number of children is $count_child \n"; - no strict; - no warnings; - #my $i=0; - my @inactive_children; - for ($i = 0;$i < $count_child;$i++) - { #opening if count_child 2 - $str=`pmdumptext -c $::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config -d§ -s1 -h$children[$i] -f%D:%H:%M:%S 2>&1`; - #print "before split is $str \n"; - #if ($str =~ /\s*No\s*route\s*to\s*host/) - if ($str =~ /pmdumptext:\s*Error:\s*host\s*"\w*":/) - { - #print "host unreachable \n"; - @inactive_children=$children[$i]; - #print "inactive children is @inactive_children \n"; - } - - else - { - #print "into elso loop \n"; - $str =~ s/\n//g; - #print "before split_1 is $str \n"; - my @spl1=split(/§/,$str); - #print "splitted and #printing \n"; - #print @spl1; - my $count_spl1=@spl1; - #print "the array has $count_spl1 elements \n"; - #print "@spl1[0] \n"; - #print "@spl1[1] \n"; - #my $count3= `cat $::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config | wc -l`; - #print "the number of lines in the file is count3:$count3 \n"; - #`tr "\n" "§" <$::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config> $::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config.tr`; - my $fname; - if (-e "/var/log/pcpmon.config") - { - #print "config under /var/log \n"; - $fname="/var/log/pcpmon.config"; - } - else - { - #print "config not under /var/log \n"; - $fname = "$::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config"; - } - print "config file is in $fname \n"; - unless ( open( CONF, $fname )) - { - return(0); - } - my @raw_data = ; - close( CONF ); - #print "before chopping @raw_data \n"; - chop(@raw_data); - #print "raw data after chopping is @raw_data \n"; - my $raw_data = join('§', @raw_data); - #print "the contents of the config file are $raw_data \n"; - my @spl2=split(/§/,$raw_data); - #print "splitted and #printing \n"; - #print @spl2; - my $count_spl2=@spl2; - #print "the array has $count_spl2 elements \n"; - #print @spl2[0] ; - #print @spl2[1] ; - #print "updating table \n"; - my $table1=xCAT::Table->new("performance", -create => 1,-autocommit => 1); - #print "table created \n"; - my $j; - #my $k; - my $l=$j+1; - #print "l is $l \n"; - my %setting_hash=(); - for ($j=0;$j<$count_spl2 ;$j++) - { - - #print "inside j loop \n"; - #print "spl1[0] is $spl1[0] \n"; - my %key_col1 = (timestamp=>$spl1[0]); - #print "time stamp updated \n"; - #print "node is $children[$i] \n"; - $key_col1{node}=$children[$i]; - #print "children updatesd \n"; - #print "spl2 is $spl2[$j] \n"; - $key_col1{attrname} = $spl2[$j]; - #$setting_hash{attrname}=$spl2[$j]; - #print "spl1 is $spl1[$j+1] \n"; - $setting_hash{attrvalue}=$spl1[$j+1]; - $table1->setAttribs(\%key_col1, \%setting_hash); - } - $table1->close(); - } - } #closing if count_child 2 + my $noderef = xCAT_monitoring::monitorctrl->getMonHierarchy(); + + #identification of this node + my @hostinfo = xCAT::NetworkUtils->determinehostname(); + + #print "hosT:@hostinfo\n"; + my $isSV = xCAT::Utils->isServiceNode(); + + #print "is sv is:$isSV \n"; + my %iphash = (); + foreach (@hostinfo) { $iphash{$_} = 1; } + if (!$isSV) { $iphash{'noservicenode'} = 1; } + + my @children; + my $str; + + foreach my $key (keys(%$noderef)) + { #opening foreach1 + #print "opening foreach1 \n"; + #print "key is: $key \n"; + my @key_a = split(':', $key); + if (!$iphash{ $key_a[0] }) { next; } + my $mon_nodes = $noderef->{$key}; + + foreach (@$mon_nodes) + { #opening foreach2 + my $node = $_->[0]; + my $nodetype = $_->[1]; + + #print "node=$node, nodetype=$nodetype\n"; + if (($nodetype) && ($nodetype =~ /$::NODETYPE_OSI/)) + { + push(@children, $node); + } + } #closing foreach2 + } #closing foreach1 + + #print "children:@children\n"; + my $count_child = @children; + if ($count_child > 0) + { #opening if count_child 1 + #print "number of children is $count_child \n"; + no strict; + no warnings; + + #my $i=0; + my @inactive_children; + for ($i = 0 ; $i < $count_child ; $i++) + { #opening if count_child 2 + $str = `pmdumptext -c $::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config -d§ -s1 -h$children[$i] -f%D:%H:%M:%S 2>&1`; + + #print "before split is $str \n"; + #if ($str =~ /\s*No\s*route\s*to\s*host/) + if ($str =~ /pmdumptext:\s*Error:\s*host\s*"\w*":/) + { + #print "host unreachable \n"; + @inactive_children = $children[$i]; + + #print "inactive children is @inactive_children \n"; + } + + else + { + #print "into elso loop \n"; + $str =~ s/\n//g; + + #print "before split_1 is $str \n"; + my @spl1 = split(/§/, $str); + + #print "splitted and #printing \n"; + #print @spl1; + my $count_spl1 = @spl1; + + #print "the array has $count_spl1 elements \n"; + #print "@spl1[0] \n"; + #print "@spl1[1] \n"; + #my $count3= `cat $::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config | wc -l`; + #print "the number of lines in the file is count3:$count3 \n"; + #`tr "\n" "§" <$::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config> $::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config.tr`; + my $fname; + if (-e "/var/log/pcpmon.config") + { + #print "config under /var/log \n"; + $fname = "/var/log/pcpmon.config"; + } + else + { + #print "config not under /var/log \n"; + $fname = "$::XCATROOT/lib/perl/xCAT_monitoring/pcp/pcpmon.config"; + } + print "config file is in $fname \n"; + unless (open(CONF, $fname)) + { + return (0); + } + my @raw_data = ; + close(CONF); + + #print "before chopping @raw_data \n"; + chop(@raw_data); + + #print "raw data after chopping is @raw_data \n"; + my $raw_data = join('§', @raw_data); + + #print "the contents of the config file are $raw_data \n"; + my @spl2 = split(/§/, $raw_data); + + #print "splitted and #printing \n"; + #print @spl2; + my $count_spl2 = @spl2; + + #print "the array has $count_spl2 elements \n"; + #print @spl2[0] ; + #print @spl2[1] ; + #print "updating table \n"; + my $table1 = xCAT::Table->new("performance", -create => 1, -autocommit => 1); + + #print "table created \n"; + my $j; + + #my $k; + my $l = $j + 1; + + #print "l is $l \n"; + my %setting_hash = (); + for ($j = 0 ; $j < $count_spl2 ; $j++) + { + + #print "inside j loop \n"; + #print "spl1[0] is $spl1[0] \n"; + my %key_col1 = (timestamp => $spl1[0]); + + #print "time stamp updated \n"; + #print "node is $children[$i] \n"; + $key_col1{node} = $children[$i]; + + #print "children updatesd \n"; + #print "spl2 is $spl2[$j] \n"; + $key_col1{attrname} = $spl2[$j]; + + #$setting_hash{attrname}=$spl2[$j]; + #print "spl1 is $spl1[$j+1] \n"; + $setting_hash{attrvalue} = $spl1[ $j + 1 ]; + $table1->setAttribs(\%key_col1, \%setting_hash); + } + $table1->close(); + } + } #closing if count_child 2 - my $table2=xCAT::Table->new("monitoring", -create =>1); - if (!$table2) - { - my $rsp={}; - $rsp->{data}->[0]="Cannot open the monitoring table.\n"; - $callback->($rsp); - return 1; - } + my $table2 = xCAT::Table->new("monitoring", -create => 1); + if (!$table2) + { + my $rsp = {}; + $rsp->{data}->[0] = "Cannot open the monitoring table.\n"; + $callback->($rsp); + return 1; + } - my $ref = $table2->getAttribs({'name' => 'pcpmon'}, 'nodestatmon'); - #print "array is $ref \n"; - my $node_stat=$ref->{nodestatmon}; - #print "nodestatmon is $node_stat \n"; - if ($node_stat ='Y') - { #opening ifnodestatusmon - #print "inside nodestatus mon $node_stat \n"; - my %node_status=(); - #print "2nd set is @inactive_children \n"; - my $count_inactive=@inactive_children; - if ($count_inactive>0) - { - #print "more than 0 inactive children \n"; - #print "3rd set is @inactive_children \n"; - $node_status{$::STATUS_INACTIVE}=\@inactive_children; - my $changed1=$nodes_status{$::STATUS_INACTIVE}; - #print "the changed1 is $changed1 \n"; - my @final_inactive=@$changed1; - #print "final inactive is @final_inactive \n"; - } + my $ref = $table2->getAttribs({ 'name' => 'pcpmon' }, 'nodestatmon'); + + #print "array is $ref \n"; + my $node_stat = $ref->{nodestatmon}; + + #print "nodestatmon is $node_stat \n"; + if ($node_stat = 'Y') + { #opening ifnodestatusmon + #print "inside nodestatus mon $node_stat \n"; + my %node_status = (); + + #print "2nd set is @inactive_children \n"; + my $count_inactive = @inactive_children; + if ($count_inactive > 0) + { + #print "more than 0 inactive children \n"; + #print "3rd set is @inactive_children \n"; + $node_status{$::STATUS_INACTIVE} = \@inactive_children; + my $changed1 = $nodes_status{$::STATUS_INACTIVE}; + + #print "the changed1 is $changed1 \n"; + my @final_inactive = @$changed1; + + #print "final inactive is @final_inactive \n"; + } - #only set the node status for the changed ones - if (keys(%node_status) > 0) - { - #print %node_status, "\n"; - #print "updating nodelist table \n"; - xCAT_monitoring::xcatmon::setNodeStatusAttributes(\%node_status); - } + #only set the node status for the changed ones + if (keys(%node_status) > 0) + { + #print %node_status, "\n"; + #print "updating nodelist table \n"; + xCAT_monitoring::xcatmon::setNodeStatusAttributes(\%node_status); + } - } #closing if nodestatusmon - } #closing if count_child 1 - - } # closing subroutine + } #closing if nodestatusmon + } #closing if count_child 1 + +} # closing subroutine diff --git a/xCAT-server/sbin/proxydhcp-xcat b/xCAT-server/sbin/proxydhcp-xcat index 91fae26fa..8fba00534 100755 --- a/xCAT-server/sbin/proxydhcp-xcat +++ b/xCAT-server/sbin/proxydhcp-xcat @@ -7,7 +7,7 @@ use IO::Socket::INET; use IO::Select; use Getopt::Long; -my $quit = 0; +my $quit = 0; my $doreload = 0; my %nodecfg; my $bootpmagic = pack("C*", 0x63, 0x82, 0x53, 0x63); @@ -33,14 +33,14 @@ if ($tobedaemon) { daemonize(); } -# open syslog +# open syslog openlog("xcat", "nofatal", "local4"); my $socket; my $retry = 5; -while ($retry > 0) { +while ($retry > 0) { $socket = IO::Socket::INET->new(LocalPort => 4011, - Proto => 'udp', + Proto => 'udp', Domain => AF_INET); if ($socket) { last; @@ -50,18 +50,18 @@ while ($retry > 0) { $retry--; } unless ($socket) { - syslog ("info", "Unable to open socket on port 4011."); - closelog(); + syslog("info", "Unable to open socket on port 4011."); + closelog(); exit; } # regist my pid to /var/run/xcat/proxydhcp.pid -if (open (PIDF, ">/var/run/xcat/proxydhcp-xcat.pid")) { +if (open(PIDF, ">/var/run/xcat/proxydhcp-xcat.pid")) { print PIDF $$; close(PIDF); } else { - syslog ("info", "Cannot open /var/run/xcat/proxydhcp.pid."); - closelog(); + syslog("info", "Cannot open /var/run/xcat/proxydhcp.pid."); + closelog(); exit; } @@ -69,32 +69,32 @@ if (open (PIDF, ">/var/run/xcat/proxydhcp-xcat.pid")) { my $select = new IO::Select; $select->add($socket); load_cfg(); -until ($quit) { - until ($select->can_read(5)) { #Wait for data +until ($quit) { + until ($select->can_read(5)) { #Wait for data if ($doreload) { load_cfg(); - syslog ("info", "Reload configuration file in select."); + syslog("info", "Reload configuration file in select."); } - if ($quit) { last; }; - yield; + if ($quit) { last; } + yield; } if ($doreload) { load_cfg(); - syslog ("info", "Reload configuration file before recv."); + syslog("info", "Reload configuration file before recv."); } my $data; - my $caddr = $socket->recv($data,1500); + my $caddr = $socket->recv($data, 1500); my ($cport, $cnip) = sockaddr_in($caddr); my $snip = my_ip_facing($cnip); unless ($snip) { - syslog ("info", "Cannot find the server ip of proxydhcp daemon"); + syslog("info", "Cannot find the server ip of proxydhcp daemon"); next; } - if (length ($data) < 320) { + if (length($data) < 320) { next; } @@ -103,51 +103,52 @@ until ($quit) { if (pack("C*", $package[0xec], $package[0xed], $package[0xee], $package[0xef]) != $bootpmagic) { next; - } + } # get the node name of client my $nodename = gethostbyaddr($cnip, AF_INET); - + # get the winpepath my $winpepath = ""; if ($nodename) { if (defined $nodecfg{$nodename}) { $winpepath = $nodecfg{$nodename}; - if ($verbose) {syslog ("info", "Find configure for $nodename= $nodecfg{$nodename} in configuration file")}; + if ($verbose) { syslog("info", "Find configure for $nodename= $nodecfg{$nodename} in configuration file") } } else { $nodename =~ s/\..*//; if (defined $nodecfg{$nodename}) { $winpepath = $nodecfg{$nodename}; - if ($verbose) {syslog ("info", "Find configure for $nodename= $nodecfg{$nodename} in configuration file")}; + if ($verbose) { syslog("info", "Find configure for $nodename= $nodecfg{$nodename} in configuration file") } } } } # get the Vendor class identifier - my $strp = 0xf0; + my $strp = 0xf0; my $archp = 0; while ($strp < $#package) { if ($package[$strp] eq 60) { $archp = $strp + 0x11; last; } else { - $strp += $package[$strp+1] + 2; + $strp += $package[ $strp + 1 ] + 2; } } - # get the winpe boot loader path - my $winboot = $winpepath."Boot/pxeboot.0"; + # get the winpe boot loader path + my $winboot = $winpepath . "Boot/pxeboot.0"; if ($archp) { my $clienttype = substr($data, $archp, 5); if ($clienttype eq "00000") { - #if ("$package[$archp]$package[$archp+1]$package[$archp+2]$package[$archp+3]$package[$archp+4]" == "00000") { - $winboot = $winpepath."Boot/pxeboot.0"; + + #if ("$package[$archp]$package[$archp+1]$package[$archp+2]$package[$archp+3]$package[$archp+4]" == "00000") { + $winboot = $winpepath . "Boot/pxeboot.0"; } elsif ($clienttype eq "00007") { - $winboot = $winpepath."Boot/bootmgfw.efi"; + $winboot = $winpepath . "Boot/bootmgfw.efi"; } } - syslog ("info", "The boot loader path for node $nodename is $winboot"); + syslog("info", "The boot loader path for node $nodename is $winboot"); # set message type $replypkg[0] = 2; @@ -162,7 +163,7 @@ until ($quit) { $replypkg[3] = $package[3]; # set the transaction ID - @replypkg = (@replypkg, @package[4 .. 7]); + @replypkg = (@replypkg, @package[ 4 .. 7 ]); # set elapsed time $replypkg[8] = 0; @@ -173,7 +174,7 @@ until ($quit) { $replypkg[0xb] = 0; # set client ip - @replypkg = (@replypkg, @package[0xc .. 0xf]); + @replypkg = (@replypkg, @package[ 0xc .. 0xf ]); # set Your (client IP) @replypkg = (@replypkg, 0, 0, 0, 0); @@ -185,7 +186,7 @@ until ($quit) { @replypkg = (@replypkg, 0, 0, 0, 0); # set client hardware address - @replypkg = (@replypkg, @package[0x1c .. 0x2b]); + @replypkg = (@replypkg, @package[ 0x1c .. 0x2b ]); # set server host name foreach (0x2c .. 0x6b) { @@ -194,7 +195,7 @@ until ($quit) { # set the boot file name @replypkg = (@replypkg, unpack("C*", $winboot)); - my $lenth = length ($winboot); + my $lenth = length($winboot); foreach (0x6c + $lenth .. 0xeb) { $replypkg[$_] = 0; } @@ -205,50 +206,50 @@ until ($quit) { @replypkg = (@replypkg, unpack("C*", $bootpmagic)); # set dhcp msg type - $replypkg[0xf0] = 0x35; # option number - $replypkg[0xf1] = 0x1; # msg length - $replypkg[0xf2] = 0x5; # dhcp ack + $replypkg[0xf0] = 0x35; # option number + $replypkg[0xf1] = 0x1; # msg length + $replypkg[0xf2] = 0x5; # dhcp ack # set dhcp server identifer - $replypkg[0xf3] = 0x36; # option number - $replypkg[0xf4] = 0x4; # msg length + $replypkg[0xf3] = 0x36; # option number + $replypkg[0xf4] = 0x4; # msg length @replypkg = (@replypkg, unpack("C*", $snip)); # set the bcd path - my $winbcd = $winpepath."Boot/BCD"; - $replypkg[0xf9] = 0xfc; # option number - $replypkg[0xfa] = length($winbcd) + 1; # msg length + my $winbcd = $winpepath . "Boot/BCD"; + $replypkg[0xf9] = 0xfc; # option number + $replypkg[0xfa] = length($winbcd) + 1; # msg length @replypkg = (@replypkg, unpack("C*", $winbcd)); - $replypkg[0xfa + length($winbcd) + 1] = 0; - $replypkg[0xfa + length($winbcd) + 2] = 0xff; - + $replypkg[ 0xfa + length($winbcd) + 1 ] = 0; + $replypkg[ 0xfa + length($winbcd) + 2 ] = 0xff; + $socket->send(pack("C*", @replypkg), 0, $caddr); - syslog ("info", "The BCD path for node $nodename is $winbcd"); + syslog("info", "The BCD path for node $nodename is $winbcd"); # debug package detail if (0) { - my $msg; - my $firstline = 1; - my $num = 0; - foreach (@replypkg) { - my $v = sprintf("%2x ", $_); - $msg .= $v; - if (($num - 5)%8 eq 0) { - $msg .= " "; + my $msg; + my $firstline = 1; + my $num = 0; + foreach (@replypkg) { + my $v = sprintf("%2x ", $_); + $msg .= $v; + if (($num - 5) % 8 eq 0) { + $msg .= " "; + } + if (($num - 5) % 16 eq 0) { + syslog("info", $msg); + print $msg. "\n"; + $msg = ""; + } + $num++; } - if (($num - 5)%16 eq 0) { - syslog ("info", $msg); - print $msg."\n"; - $msg = ""; - } - $num++; + print $msg. "\n"; } - print $msg."\n"; - } } -closelog(); +closelog(); # daemonize the service sub daemonize @@ -262,7 +263,7 @@ sub daemonize } open STDOUT, '>/dev/null'; open STDERR, '>/dev/null'; - $0='proxydhcp-xcat'; + $0 = 'proxydhcp-xcat'; $progname = \$0; } @@ -270,12 +271,12 @@ sub daemonize sub load_cfg { $doreload = 0; - if (! -r "/var/lib/xcat/proxydhcp.cfg") { + if (!-r "/var/lib/xcat/proxydhcp.cfg") { return; } - if (! open (CFG, "); -my $rsp = {}; -my $host=`hostname`; -$host=~ s/\s*//g; # remove blanks +my $rsp = {}; +my $host = `hostname`; +$host =~ s/\s*//g; # remove blanks + # check the arguments &parse_args($cmd); -$rsp->{syslogdata}->[0] ="restartxcatd invoked by $current_userid.\n"; -$rsp->{userid} ->[0] = $current_userid; -$rsp->{clientname} -> [0] = $host; -$rsp->{clienttype} -> [0]= "cli"; -$rsp->{command} -> [0] = $cmd; -$rsp->{status} -> [0] = "allowed"; -xCAT::MsgUtils->message("SA",$rsp); # syslog and auditlog +$rsp->{syslogdata}->[0] = "restartxcatd invoked by $current_userid.\n"; +$rsp->{userid}->[0] = $current_userid; +$rsp->{clientname}->[0] = $host; +$rsp->{clienttype}->[0] = "cli"; +$rsp->{command}->[0] = $cmd; +$rsp->{status}->[0] = "allowed"; +xCAT::MsgUtils->message("SA", $rsp); # syslog and auditlog # for Linux specific if (xCAT::Utils->isLinux()) -{ +{ print "Restarting xCATd "; if (-r "/etc/profile.d/xcat.sh") { $cmd = "source /etc/profile.d/xcat.sh;"; @@ -73,11 +77,11 @@ if (xCAT::Utils->isLinux()) xCAT::Utils->runcmd("$cmd", -1); if ($::RUNCMD_RC == 0) { print "[ OK ]\n"; - system ("logger -p local4.info -t xcat Restart xcatd: [ OK ]."); + system("logger -p local4.info -t xcat Restart xcatd: [ OK ]."); exit 0; } else { print "[ FAILED ]\n"; - system ("logger -p local4.info -t xcat Restart xcatd: [ FAILED ]."); + system("logger -p local4.info -t xcat Restart xcatd: [ FAILED ]."); exit 1; } } elsif (!(xCAT::Utils->isAIX())) { @@ -87,7 +91,7 @@ if (xCAT::Utils->isLinux()) # Following code is for AIX only -$::RE_CHECK_NUM = 10; # the times to check the result of command, the checking interval is 1 second +$::RE_CHECK_NUM = 10; # the times to check the result of command, the checking interval is 1 second my $rc; my @output; @@ -95,9 +99,10 @@ my $inoperative = 0; my $check_num; # Check whether the xcatd subsystem has been created -$cmd = "/usr/bin/lssrc -s xcatd | grep \"xcatd Subsystem is not on file\""; +$cmd = "/usr/bin/lssrc -s xcatd | grep \"xcatd Subsystem is not on file\""; @output = `$cmd`; if (scalar(@output)) { + # create the subsystem if it does not exist $cmd = "mkssys -p $::XCATROOT/sbin/xcatd -s xcatd -u 0 -S -n 15 -f 15 -a \"-f\""; $rc = system($cmd); @@ -108,7 +113,7 @@ if (scalar(@output)) { } # Check the current status of xcatd subsystem -$cmd = "lssrc -s xcatd | grep 'xcatd' | grep 'inoperative'"; +$cmd = "lssrc -s xcatd | grep 'xcatd' | grep 'inoperative'"; @output = `$cmd`; if (scalar(@output)) { if ($::VERBOSE) { @@ -117,10 +122,10 @@ if (scalar(@output)) { $inoperative = 1; } -if (! $inoperative) { # active - # Stop the xcatd subsystem +if (!$inoperative) { # active + # Stop the xcatd subsystem $cmd = "/usr/bin/stopsrc -s xcatd"; - $rc = system($cmd); + $rc = system($cmd); if ($rc >> 8) { xCAT::MsgUtils->message("E", "Error: Cannot run stopsrc command correctly.\n"); exit 1; @@ -129,7 +134,7 @@ if (! $inoperative) { # active # Wait for end of the xcatd subsystem $check_num = $::RE_CHECK_NUM; while ($check_num > 0) { - $cmd = "lssrc -s xcatd | grep 'xcatd' | grep 'inoperative'"; + $cmd = "lssrc -s xcatd | grep 'xcatd' | grep 'inoperative'"; @output = `$cmd`; if (scalar(@output) == 0) { sleep 1; @@ -150,10 +155,10 @@ if (! $inoperative) { # active } # Kill xcatd manually if needed -$cmd = "ps -ef | grep xcatd: | grep -v grep"; +$cmd = "ps -ef | grep xcatd: | grep -v grep"; @output = `$cmd`; if (scalar(@output)) { - $cmd = "ps -ef | grep xcatd | grep 'SSL listener'"; + $cmd = "ps -ef | grep xcatd | grep 'SSL listener'"; @output = `$cmd`; foreach my $ps (@output) { $ps =~ s/^\s+//; # strip any leading spaces @@ -161,8 +166,9 @@ if (scalar(@output)) { my $cmd = "/usr/bin/kill -15 -$pid >/dev/null 2>&1"; `$cmd`; } + # Kill the xcatd by force if it still there - $cmd = "ps -ef | grep xcatd: | grep -v grep"; + $cmd = "ps -ef | grep xcatd: | grep -v grep"; @output = `$cmd`; foreach my $ps (@output) { $ps =~ s/^\s+//; # strip any leading spaces @@ -172,7 +178,7 @@ if (scalar(@output)) { } $check_num = $::RE_CHECK_NUM; while ($check_num > 0) { - $cmd = "ps -ef | grep xcatd: | grep -v grep"; + $cmd = "ps -ef | grep xcatd: | grep -v grep"; @output = `$cmd`; if (scalar(@output)) { sleep 1; @@ -208,6 +214,7 @@ if ($rc >> 8) { xCAT::MsgUtils->message("E", "Error: Cannot run startsrc command correctly.\n"); exit 1; } + # Sleep a while to make sure the startsrc has completed it's work sleep 3; @@ -232,15 +239,15 @@ if ($check_num <= 0) { # now see if we can really talk to the database, up to a minute $wait = 60; while ($wait > 0) { - sleep 10; - $wait = $wait -10; - xCAT::Utils->runcmd("$::XCATROOT/sbin/tabdump site",-1); - if ($::RUNCMD_RC == 0) { - $wait=0; - } + sleep 10; + $wait = $wait - 10; + xCAT::Utils->runcmd("$::XCATROOT/sbin/tabdump site", -1); + if ($::RUNCMD_RC == 0) { + $wait = 0; + } } if ($::VERBOSE) { - xCAT::MsgUtils->message("I", "Started the xcatd subsystem.\n"); + xCAT::MsgUtils->message("I", "Started the xcatd subsystem.\n"); } exit 0; @@ -282,12 +289,12 @@ sub parse_args } if ($::RELOAD) { - $ENV{XCATRELOAD} = "yes"; + $ENV{XCATRELOAD} = "yes"; } if ($::VERSION) { my $version = xCAT::Utils->Version(); - $version .="\n"; + $version .= "\n"; xCAT::MsgUtils->message("I", $version); exit 0; } diff --git a/xCAT-server/sbin/rshell_api b/xCAT-server/sbin/rshell_api index ef2f42f9f..aa04a7864 100755 --- a/xCAT-server/sbin/rshell_api +++ b/xCAT-server/sbin/rshell_api @@ -20,24 +20,24 @@ my $help; my $verbose; if (!GetOptions( - 'l|loginname=s' => \$username, - 'p|password=s' => \$passwd, - 't|telnet' => \$telnet, #use telnet, otherwise ssh - 'h|help' => \$help, - 'v|verbose'=> \$verbose, - ) || $help || scalar(@ARGV)<2 ) { - print "Usage: rshell_api [-v] [-t] [-l ] [-p ] \n"; - exit; + 'l|loginname=s' => \$username, + 'p|password=s' => \$passwd, + 't|telnet' => \$telnet, #use telnet, otherwise ssh + 'h|help' => \$help, + 'v|verbose' => \$verbose, + ) || $help || scalar(@ARGV) < 2) { + print "Usage: rshell_api [-v] [-t] [-l ] [-p ] \n"; + exit; } my $node = $ARGV[0]; -my $output =xCAT::RShellAPI::run_remote_shell_api($node, $username, $passwd, $telnet, $verbose, @ARGV[1 .. $#ARGV]); -my $rc=0; +my $output = xCAT::RShellAPI::run_remote_shell_api($node, $username, $passwd, $telnet, $verbose, @ARGV[ 1 .. $#ARGV ]); +my $rc = 0; my $data; if ($output && (@$output > 1)) { - $rc=$output->[0]; - $data=$output->[1]; + $rc = $output->[0]; + $data = $output->[1]; } print "$data"; diff --git a/xCAT-server/sbin/runsqlcmd b/xCAT-server/sbin/runsqlcmd index b0a30a1dc..4247a4e4d 100755 --- a/xCAT-server/sbin/runsqlcmd +++ b/xCAT-server/sbin/runsqlcmd @@ -37,25 +37,26 @@ use strict; $::progname = "runsqlcmd"; Getopt::Long::Configure("bundling"); $Getopt::Long::ignorecase = 0; -my ($directory, $help, $version,$verbose, $filelist); +my ($directory, $help, $version, $verbose, $filelist); # parse the options if ( !GetOptions( - 'd|dir=s' => \$directory, - 'f|files=s' => \$filelist, - 'h|help' => \$help, - 'v|version' => \$version, - 'V|verbose' => \$verbose, + 'd|dir=s' => \$directory, + 'f|files=s' => \$filelist, + 'h|help' => \$help, + 'v|version' => \$version, + 'V|verbose' => \$verbose, ) ) { &usage; exit(1); } + # see if they entered a command my $args = join ' ', @ARGV; -my $command = $args; +my $command = $args; # display the usage if -h or --help is specified if ($help) @@ -63,6 +64,7 @@ if ($help) &usage; exit(0); } + # display the version statement if -v or --version is specified if ($version) { @@ -72,39 +74,40 @@ if ($version) } if (($filelist) && ($directory)) { - xCAT::MsgUtils->message("E","Cannot enter both the -f and -d flags."); + xCAT::MsgUtils->message("E", "Cannot enter both the -f and -d flags."); exit 1; } if (($command) && (($directory) || ($filelist))) { - xCAT::MsgUtils->message("E","Cannot enter both a command and the -d or -f flag."); + xCAT::MsgUtils->message("E", "Cannot enter both a command and the -d or -f flag."); exit 1; } my $tempfile; -if ($command) { # command on command line - $tempfile="/tmp/runcmdfile.$$"; - my $cmd = "echo \"$command\" > $tempfile"; - xCAT::Utils->runcmd($cmd,0); - if ($::RUNCMD_RC != 0) - { # error - xCAT::MsgUtils->message("E", "$cmd failed"); - exit 1; +if ($command) { # command on command line + $tempfile = "/tmp/runcmdfile.$$"; + my $cmd = "echo \"$command\" > $tempfile"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { # error + xCAT::MsgUtils->message("E", "$cmd failed"); + exit 1; - } - # put on filelist - $filelist=$tempfile; -} else { # commands in a file + } - if (!($filelist)) { # if no file list and no directory set default - if (!($directory)) { - $directory = "$::XCATROOT/lib/perl/xCAT_schema"; - } - } + # put on filelist + $filelist = $tempfile; +} else { # commands in a file + + if (!($filelist)) { # if no file list and no directory set default + if (!($directory)) { + $directory = "$::XCATROOT/lib/perl/xCAT_schema"; + } + } } my @filearray; if ($filelist) -{ # use filelist +{ # use filelist $directory = ""; #Get rid of the default @filearray = &process_file_list($filelist); } @@ -114,55 +117,56 @@ else if (!(-e $directory)) { xCAT::MsgUtils->message("E", - "The $directory directory does not exist."); + "The $directory directory does not exist."); exit 1; } } my @sqlfilelist = xCAT::Table->get_filelist($directory, \@filearray, "sql"); -if (@sqlfilelist) { # if anything to do - #determine database - my $xcatcfg = xCAT::Table->get_xcatcfg(); - foreach my $file (@sqlfilelist) - { - if ($xcatcfg =~ /^DB2:/) +if (@sqlfilelist) { # if anything to do + #determine database + my $xcatcfg = xCAT::Table->get_xcatcfg(); + foreach my $file (@sqlfilelist) { - &rundb2cmd($file); - } - if ($xcatcfg =~ /^mysql:/) - { - &runmysqlcmd($file, $xcatcfg); - } - if ($xcatcfg =~ /^Pg:/) - { - &runpgsqlcmd($file, $xcatcfg); - } - if ($xcatcfg =~ /^SQLite:/) - { - # not supported but will leave routine in case we change our mind - if ($verbose) { - xCAT::MsgUtils->message("SE", "The runsqlcmd does not support the SQLite database."); + if ($xcatcfg =~ /^DB2:/) + { + &rundb2cmd($file); } - #&runsqlitecmd($file,$xcatcfg); - exit 1; - } + if ($xcatcfg =~ /^mysql:/) + { + &runmysqlcmd($file, $xcatcfg); + } + if ($xcatcfg =~ /^Pg:/) + { + &runpgsqlcmd($file, $xcatcfg); + } + if ($xcatcfg =~ /^SQLite:/) + { + # not supported but will leave routine in case we change our mind + if ($verbose) { + xCAT::MsgUtils->message("SE", "The runsqlcmd does not support the SQLite database."); + } - } + #&runsqlitecmd($file,$xcatcfg); + exit 1; + } + + } } else { - if ($verbose) { + if ($verbose) { xCAT::MsgUtils->message("SI", "The runsqlcmd has no files to process in $directory ."); - } + } } if ($tempfile) { - my $cmd = "rm $tempfile"; - xCAT::Utils->runcmd($cmd,0); - if ($::RUNCMD_RC != 0) - { # error - xCAT::MsgUtils->message("E", "$cmd failed"); - exit 1; + my $cmd = "rm $tempfile"; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { # error + xCAT::MsgUtils->message("E", "$cmd failed"); + exit 1; - } -} + } +} exit 0; ##################################### @@ -183,10 +187,10 @@ sub usage { xCAT::MsgUtils->message( 'I', - "Usage:\nRuns the sql commands in files located in /opt/xcat/lib/perl/xCAT_schema by default, or the directory input with -d, or the list of files input with the -f flag, or the command input on the command line. Supports DB2,PostgreSQL,MySQL." - ); +"Usage:\nRuns the sql commands in files located in /opt/xcat/lib/perl/xCAT_schema by default, or the directory input with -d, or the list of files input with the -f flag, or the command input on the command line. Supports DB2,PostgreSQL,MySQL." + ); my $msg = - "runsqlcmd <-h|--help>\n <-v|--version>\n <-V|--verbose>\n <-d|--dir>\n <-f|--files> \n "; +"runsqlcmd <-h|--help>\n <-v|--version>\n <-V|--verbose>\n <-d|--dir>\n <-f|--files> \n "; xCAT::MsgUtils->message('I', "$msg"); } @@ -205,9 +209,9 @@ sub usage sub rundb2cmd { use File::Basename; - my $file = shift; - my $rc = 0; - if (!(-e $file)) { # file does not exist + my $file = shift; + my $rc = 0; + if (!(-e $file)) { # file does not exist xCAT::MsgUtils->message("SE", "The file:$file does not exist. "); return; @@ -245,7 +249,7 @@ sub rundb2cmd { $rc = $? >> 8; xCAT::MsgUtils->message("SE", - "The command $cmd had errors. Return=$rc"); + "The command $cmd had errors. Return=$rc"); } $cmd = "rm $tmpfile"; @output = xCAT::Utils->runcmd($cmd, 0); @@ -276,32 +280,35 @@ sub runmysqlcmd my ($prefix, $dbname) = split('=', $front); my ($host, $admin, $passwd) = split('\|', $back); my ($hostind, $hostname) = split('=', $host); - - my $rc = 0; - if (!(-e $file)) { # file does not exist + + my $rc = 0; + if (!(-e $file)) { # file does not exist xCAT::MsgUtils->message("SE", "The file:$file does not exist. "); return; } + # set correct path to the mysql cmd my $mysql; if (xCAT::Utils->isAIX()) { - $mysql="/usr/local/mysql/bin/mysql"; + $mysql = "/usr/local/mysql/bin/mysql"; } else { - $mysql="/usr/bin/mysql"; + $mysql = "/usr/bin/mysql"; } my $cmd = - "$mysql --user=$admin --password=$passwd --host=$hostname $dbname \< $file "; +"$mysql --user=$admin --password=$passwd --host=$hostname $dbname \< $file "; + #xCAT::MsgUtils->message("SI", "Running mysql --user=$admin --host=$hostname $dbname $file "); system("$cmd"); if ($? > 0) # error { $rc = $? >> 8; + # secure password $cmd = "$mysql --user=$admin --password=xxxxxx --host=$hostname $dbname \< $file "; xCAT::MsgUtils->message("SE", - "The command $cmd had errors. Return=$rc"); + "The command $cmd had errors. Return=$rc"); } return; } @@ -326,21 +333,23 @@ sub runpgsqlcmd my ($host, $admin, $passwd) = split('\|', $back); my ($hostind, $hostname) = split('=', $host); - my $rc = 0; - if (!(-e $file)) { # file does not exist + my $rc = 0; + if (!(-e $file)) { # file does not exist xCAT::MsgUtils->message("SE", "The file:$file does not exist. "); return; } + # set correct path to the psql cmd my $psql; if (xCAT::Utils->isAIX()) { - $psql="/var/lib/pgsql/bin/psql"; + $psql = "/var/lib/pgsql/bin/psql"; } else { - $psql="/usr/bin/psql"; + $psql = "/usr/bin/psql"; } my $cmd = "PGPASSWORD=$passwd $psql -d $dbname -h $hostname -U $admin -f $file "; + #xCAT::MsgUtils->message("SI", "Running psql -d $dbname -h $hostname -U $admin -f $file "); system("$cmd"); @@ -348,7 +357,7 @@ sub runpgsqlcmd { $rc = $? >> 8; xCAT::MsgUtils->message("SE", - "The command $cmd had errors. Return=$rc"); + "The command $cmd had errors. Return=$rc"); } return; } diff --git a/xCAT-server/sbin/stopstartxcatd b/xCAT-server/sbin/stopstartxcatd index 14c285db4..69c260d1b 100755 --- a/xCAT-server/sbin/stopstartxcatd +++ b/xCAT-server/sbin/stopstartxcatd @@ -7,9 +7,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use Getopt::Long; @@ -71,35 +71,35 @@ sub parse_args ) ) - { + { if ($cmd eq "xcatstart") { - $usagemsg = "$cmd [-h|-v|-r]\n"; - xCAT::MsgUtils->message("E", $usagemsg); - } else { #xcatstop - $usagemsg = "$cmd [-h|-v]\n"; - xCAT::MsgUtils->message("E", $usagemsg); - } + $usagemsg = "$cmd [-h|-v|-r]\n"; + xCAT::MsgUtils->message("E", $usagemsg); + } else { #xcatstop + $usagemsg = "$cmd [-h|-v]\n"; + xCAT::MsgUtils->message("E", $usagemsg); + } exit 1; } if ($::HELP) { if ($cmd eq "xcatstart") { - $usagemsg = "$cmd [-h|-v|-r]\n"; - xCAT::MsgUtils->message("I", $usagemsg); - } else { #xcatstop - $usagemsg = "$cmd [-h|-v]\n"; - xCAT::MsgUtils->message("I", $usagemsg); - } + $usagemsg = "$cmd [-h|-v|-r]\n"; + xCAT::MsgUtils->message("I", $usagemsg); + } else { #xcatstop + $usagemsg = "$cmd [-h|-v]\n"; + xCAT::MsgUtils->message("I", $usagemsg); + } exit 0; } if ($::RELOAD) { - $ENV{XCATRELOAD} = "yes"; + $ENV{XCATRELOAD} = "yes"; } if ($::VERSION) { my $version = xCAT::Utils->Version(); - $version .="\n"; + $version .= "\n"; xCAT::MsgUtils->message("I", $version); exit 0; } diff --git a/xCAT-server/sbin/updateSNimage b/xCAT-server/sbin/updateSNimage index 65142f015..67794d447 100644 --- a/xCAT-server/sbin/updateSNimage +++ b/xCAT-server/sbin/updateSNimage @@ -7,9 +7,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use File::Basename; @@ -77,7 +77,7 @@ else # if not make them if ($thostname eq "local") -{ # local host +{ # local host $cmd = "ls $path/etc/xcat/ca"; } else @@ -88,7 +88,7 @@ my @output = xCAT::Utils->runcmd($cmd, -1); if ($::RUNCMD_RC != 0) { if ($thostname eq "local") - { # local host + { # local host $cmd = "mkdir $path/etc/xcat/ca"; } else @@ -343,7 +343,7 @@ sub create_fstab { my ($path) = @_; my $cmd; - my $file = "$path/etc/fstab"; + my $file = "$path/etc/fstab"; my $file2 = "$path/etc/fstab.ORIG"; if (!(-e $file2)) { # if not already done diff --git a/xCAT-server/sbin/xcat_traphandler b/xCAT-server/sbin/xcat_traphandler index c5c9a3350..de041be67 100755 --- a/xCAT-server/sbin/xcat_traphandler +++ b/xCAT-server/sbin/xcat_traphandler @@ -2,7 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; use Sys::Syslog; @@ -14,20 +14,23 @@ use xCAT_plugin::ipmi; use xCAT_monitoring::monitorctrl; use Socket; use Data::Dumper; + #use strict; #------------------------------------------------------------------------------- + =head1 xcat_traphandler =head2 Description Script for SNMP trap handling. =cut + #------------------------------------------------------------------------------- # admin needs to create a mail aliase called alerts # put "alerts: emailadd,emailaddr.." to /etc/aliases file # then run newaliases command -my $MAILTO="alerts"; +my $MAILTO = "alerts"; my $message; my $briefmsg; @@ -41,316 +44,326 @@ my $message1; my $errsrc; #get settings -my $EMAIL=0; -my $LOG=0; -my $IGNORE=0; -my $DB=0; -my %hashI=(); -my %hashE=(); -my %hashL=(); -my %hashR=(); -my %hashD=(); -my %hashRUN=(); -my %settings=xCAT_monitoring::monitorctrl->getPluginSettings("snmpmon"); -my $i=$settings{'ignore'}; -if ($i) { %hashI =parseSettings($i); } -my $e=$settings{'email'}; -if ($e) { %hashE=parseSettings($e); } -my $l=$settings{'log'}; -if ($l) { %hashL=parseSettings($l); } -my $d=$settings{'db'}; -if ($d) { %hashD=parseSettings($d); } +my $EMAIL = 0; +my $LOG = 0; +my $IGNORE = 0; +my $DB = 0; +my %hashI = (); +my %hashE = (); +my %hashL = (); +my %hashR = (); +my %hashD = (); +my %hashRUN = (); +my %settings = xCAT_monitoring::monitorctrl->getPluginSettings("snmpmon"); +my $i = $settings{'ignore'}; +if ($i) { %hashI = parseSettings($i); } +my $e = $settings{'email'}; +if ($e) { %hashE = parseSettings($e); } +my $l = $settings{'log'}; +if ($l) { %hashL = parseSettings($l); } +my $d = $settings{'db'}; +if ($d) { %hashD = parseSettings($d); } foreach my $k (keys %settings) { - if ($k =~ /runcmd(\d*)/) { - my $r=$settings{$k}; - my %hashTemp=parseSettings($r); - $hashR{$k}=\%hashTemp; - $hashRUN{$k}=0; + if ($k =~ /runcmd(\d*)/) { + my $r = $settings{$k}; + my %hashTemp = parseSettings($r); + $hashR{$k} = \%hashTemp; + $hashRUN{$k} = 0; } } # read host name -my $host=; +my $host = ; chomp($host); # read the host ip -my $ip=; +my $ip = ; chomp($ip); # read uptime -my $uptimeline=; +my $uptimeline = ; chomp($uptimeline); -my @a=split(/ /, $uptimeline); -my $oid=shift @a; -my $value=join(' ', @a); +my @a = split(/ /, $uptimeline); +my $oid = shift @a; +my $value = join(' ', @a); $message .= " $oid=$value\n"; -# read trapid -my $trapidline=; +# read trapid +my $trapidline = ; chomp($trapidline); -@a=split(/ /, $trapidline); -$oid=shift @a; -$value=join(' ', @a); +@a = split(/ /, $trapidline); +$oid = shift @a; +$value = join(' ', @a); $message .= " $oid=$value\n"; checkWithOid($oid, $value); + #print "I=$IGNORE,E=$EMAIL, L=$LOG, R=$RUNCMD D=$DB\n"; -if ($IGNORE) { exit 0;} +if ($IGNORE) { exit 0; } #for ipmi traps, the values is: SNMPv2-SMI::enterprises.3183.1.1.0.x or # RFC1155-SMI::enterprises.3183.1.1.0.x, where x is the ipmi trap id. -my $trapid; -if ($value =~ /enterprises\.3183\.1\.1\.0\.(.*)/) { $trapid=$1; } +my $trapid; +if ($value =~ /enterprises\.3183\.1\.1\.0\.(.*)/) { $trapid = $1; } #print "trapid=$trapid\n"; my $holder; -my $begin=1; +my $begin = 1; my $pair; my $temp; -while ($temp=) { - chomp($temp); - my $temp1=$temp; #save the one with quotes - $temp1 =~ s/\"//g; - my $c1=length($temp); - my $c2=length($temp1); - - - if (($c1-$c2)%2 == 0) { - if ($begin==1) { # single line - $pair=$temp; - } - else { # middle multi-line - $pair .= " $temp"; - next; - } - } else { # multi line - if ($begin==1) { - $pair=$temp; #start of multi-line - $begin=0; - next; - } else { - $pair .= " $temp"; #end of multi-line - $begin=1; - } - } - - @a=split(/ /, $pair); - $oid=shift @a; - $value=join(' ', @a); - $value =~ s/^"//; - $value =~ s/"$//; - - #for BladeCenter MM traps and RSA II traps, creat a brief message - if ($oid =~ /BLADESPPALT-MIB::spTrapAppId|RSASPPALT-MIB::ibmSpTrapAppId/) { - $briefmsg .= " App ID: $value\n"; - $appname=$value; - } - elsif ($oid =~ /BLADESPPALT-MIB::spTrapAppType|RSASPPALT-MIB::ibmSpTrapAppType/) { - $briefmsg .= " App Alert Type: $value\n"; - $id=$value; - } - elsif ($oid =~ /BLADESPPALT-MIB::spTrapMsgText|RSASPPALT-MIB::ibmSpTrapMsgText/) { - $briefmsg .= " Message: $value\n"; - $message1=$value; - } - elsif ($oid =~ /BLADESPPALT-MIB::spTrapBladeName/) { - my $temp="$value"; - $temp =~ /^\"(.*)\"/; - if ($1) { - $briefmsg .= " Blade Name: $value\n"; - $node1=$1; - } - } - elsif (($oid =~ /BLADESPPALT-MIB::spTrapSourceId/)) { - $briefmsg .= " Error Source=$value\n"; - $errsrc=$value; - } - elsif ($oid =~ /BLADESPPALT-MIB::spTrapPriority|RSASPPALT-MIB::ibmSpTrapPriority/) { - # Critical Alert(0), Major(1), Non-Critical Alert(2), System Alert(4), - # Recovery Alert(8), Informational Only Alert(255) - if ($value==0) { - $severity="Critical Alert"; - $severity_type="Critical"; - } elsif ($value==1) { - $severity="Major Alert"; - $severity_type="Critical"; - } elsif ($value==2) { - $severity="Non-Critical Alert"; - $severity_type="Warning"; - } elsif ($value==4) { - $severity="System Alert"; - $severity_type="Warning"; - } elsif ($value==8) { - $severity="Recovery Alert"; - $severity_type="Informational"; - } elsif ($value==255) { - $severity="Informational Alert"; - $severity_type="Informational"; - } - } - elsif ($oid =~ /enterprises\.3183\.1\.1\.1/) { #IPMI PRTs (traps) - $node1=$host; - #$node1 =~ s/(-(eth|man)\d+)?(\..*)?$//; - - my $ip1=$ip; - $ip1 =~ /(\d+\.\d+\.\d+\.\d+)/; - $ip1=$1; - - # get the host name if it is unknown - if ($node1 =~//) { - my $name = xCAT::NetworkUtils->gethostname($ip1); - if ($name) { - $node1=$name; - $host=$name; - my @shorthost = split(/\./, $node1); - $node1=$shorthost[0]; - } - } - - #print "node1=$node1\n"; - #node1 is the bmc name, we need the node that bmc connects to to call xCAT - my $realnode; - my $ipmitab = xCAT::Table->new('ipmi'); - if (defined($ipmitab)) { - my @tmp1=$ipmitab->getAllNodeAttribs(['node','bmc']); - if (@tmp1 && (@tmp1 > 0)) { - foreach(@tmp1) { - if ($_->{bmc} eq $node1) { $realnode=$_->{node}; last;} - } - } - $ipmitab->close(); - } - if ($realnode) {$node1=$realnode;} - #print "node1=$node1\n"; +while ($temp = ) { + chomp($temp); + my $temp1 = $temp; #save the one with quotes + $temp1 =~ s/\"//g; + my $c1 = length($temp); + my $c2 = length($temp1); - # make the vlaue into a hex array for decoding + if (($c1 - $c2) % 2 == 0) { + if ($begin == 1) { # single line + $pair = $temp; + } + else { # middle multi-line + $pair .= " $temp"; + next; + } + } else { # multi line + if ($begin == 1) { + $pair = $temp; #start of multi-line + $begin = 0; + next; + } else { + $pair .= " $temp"; #end of multi-line + $begin = 1; + } + } + + @a = split(/ /, $pair); + $oid = shift @a; + $value = join(' ', @a); + $value =~ s/^"//; + $value =~ s/"$//; + + #for BladeCenter MM traps and RSA II traps, creat a brief message + if ($oid =~ /BLADESPPALT-MIB::spTrapAppId|RSASPPALT-MIB::ibmSpTrapAppId/) { + $briefmsg .= " App ID: $value\n"; + $appname = $value; + } + elsif ($oid =~ /BLADESPPALT-MIB::spTrapAppType|RSASPPALT-MIB::ibmSpTrapAppType/) { + $briefmsg .= " App Alert Type: $value\n"; + $id = $value; + } + elsif ($oid =~ /BLADESPPALT-MIB::spTrapMsgText|RSASPPALT-MIB::ibmSpTrapMsgText/) { + $briefmsg .= " Message: $value\n"; + $message1 = $value; + } + elsif ($oid =~ /BLADESPPALT-MIB::spTrapBladeName/) { + my $temp = "$value"; + $temp =~ /^\"(.*)\"/; + if ($1) { + $briefmsg .= " Blade Name: $value\n"; + $node1 = $1; + } + } + elsif (($oid =~ /BLADESPPALT-MIB::spTrapSourceId/)) { + $briefmsg .= " Error Source=$value\n"; + $errsrc = $value; + } + elsif ($oid =~ /BLADESPPALT-MIB::spTrapPriority|RSASPPALT-MIB::ibmSpTrapPriority/) { + + # Critical Alert(0), Major(1), Non-Critical Alert(2), System Alert(4), + # Recovery Alert(8), Informational Only Alert(255) + if ($value == 0) { + $severity = "Critical Alert"; + $severity_type = "Critical"; + } elsif ($value == 1) { + $severity = "Major Alert"; + $severity_type = "Critical"; + } elsif ($value == 2) { + $severity = "Non-Critical Alert"; + $severity_type = "Warning"; + } elsif ($value == 4) { + $severity = "System Alert"; + $severity_type = "Warning"; + } elsif ($value == 8) { + $severity = "Recovery Alert"; + $severity_type = "Informational"; + } elsif ($value == 255) { + $severity = "Informational Alert"; + $severity_type = "Informational"; + } + } + elsif ($oid =~ /enterprises\.3183\.1\.1\.1/) { #IPMI PRTs (traps) + $node1 = $host; + + #$node1 =~ s/(-(eth|man)\d+)?(\..*)?$//; + + my $ip1 = $ip; + $ip1 =~ /(\d+\.\d+\.\d+\.\d+)/; + $ip1 = $1; + + # get the host name if it is unknown + if ($node1 =~ //) { + my $name = xCAT::NetworkUtils->gethostname($ip1); + if ($name) { + $node1 = $name; + $host = $name; + my @shorthost = split(/\./, $node1); + $node1 = $shorthost[0]; + } + } + + #print "node1=$node1\n"; + #node1 is the bmc name, we need the node that bmc connects to to call xCAT + my $realnode; + my $ipmitab = xCAT::Table->new('ipmi'); + if (defined($ipmitab)) { + my @tmp1 = $ipmitab->getAllNodeAttribs([ 'node', 'bmc' ]); + if (@tmp1 && (@tmp1 > 0)) { + foreach (@tmp1) { + if ($_->{bmc} eq $node1) { $realnode = $_->{node}; last; } + } + } + $ipmitab->close(); + } + if ($realnode) { $node1 = $realnode; } + + #print "node1=$node1\n"; + + + # make the vlaue into a hex array for decoding + $value =~ s/\"//g; + my @varray = split(/\s+/, $value); + + #print "varray=@varray\n"; + foreach (@varray) { $_ = hex($_); } + my $error = xCAT_plugin::ipmi->decodealert($trapid, $node1, @varray); + $briefmsg .= $error; + $message .= " decodedipmialert=$error\n"; + + #severity value from decodealert are: + #LOG,INFORMATION,OK,CRITICAL,NON-RECOVERABLE,MONITOR and UNKNOWN-SEVERITY + $severity_type = "Warning"; + if ($error) { + my @tempArray = split(/\:/, $error); + $severity = $tempArray[0]; + if ($severity eq "LOG") { #in fact this is called "unspecifiled" + $severity_type = "Warning"; + } + elsif ($severity eq "INFORMATION") { + $severity_type = "Informational"; + } + elsif ($severity eq "OK") { + $severity_type = "Informational"; + } + elsif ($severity eq "CRITICAL") { + $severity_type = "Critical"; + } + elsif ($severity eq "NON-RECOVERABLE") { + $severity_type = "Critical"; + } + } + } + + + $message .= " $oid=$value\n"; + + #check agains the settings $value =~ s/\"//g; - my @varray=split(/\s+/, $value); - #print "varray=@varray\n"; - foreach (@varray) { $_=hex($_); } - my $error = xCAT_plugin::ipmi->decodealert($trapid, $node1, @varray); - $briefmsg .= $error; - $message .= " decodedipmialert=$error\n"; + checkWithOid($oid, $value); - #severity value from decodealert are: - #LOG,INFORMATION,OK,CRITICAL,NON-RECOVERABLE,MONITOR and UNKNOWN-SEVERITY - $severity_type="Warning"; - if ($error) { - my @tempArray=split(/\:/, $error); - $severity=$tempArray[0]; - if ($severity eq "LOG") {#in fact this is called "unspecifiled" - $severity_type="Warning"; - } - elsif($severity eq "INFORMATION") { - $severity_type="Informational"; - } - elsif($severity eq "OK") { - $severity_type="Informational"; - } - elsif($severity eq "CRITICAL") { - $severity_type="Critical"; - } - elsif($severity eq "NON-RECOVERABLE") { - $severity_type="Critical"; - } - } - } - - - $message .= " $oid=$value\n"; - - #check agains the settings - $value =~ s/\"//g; - checkWithOid($oid, $value); - #print "I=$IGNORE,E=$EMAIL, L=$LOG, R=$RUNCMD, D=$DB\n"; - if ($IGNORE) { exit 0;} + #print "I=$IGNORE,E=$EMAIL, L=$LOG, R=$RUNCMD, D=$DB\n"; + if ($IGNORE) { exit 0; } } -if (!$severity_type) { $severity_type="Warning"; } -if ((!$IGNORE) && exists($hashI{$severity_type})) { - #print "ignore, exit\n"; - exit 0; +if (!$severity_type) { $severity_type = "Warning"; } +if ((!$IGNORE) && exists($hashI{$severity_type})) { + + #print "ignore, exit\n"; + exit 0; } -if ((!$EMAIL) && exists($hashE{$severity_type})) { $EMAIL=1; } -if ((!$LOG) && exists($hashL{$severity_type})) { $LOG=1; } -if ((!$DB) && exists($hashD{$severity_type})) { $DB=1; } +if ((!$EMAIL) && exists($hashE{$severity_type})) { $EMAIL = 1; } +if ((!$LOG) && exists($hashL{$severity_type})) { $LOG = 1; } +if ((!$DB) && exists($hashD{$severity_type})) { $DB = 1; } foreach my $k (keys %hashRUN) { if (($hashRUN{$k} == 0) && exists($hashR{$k}->{$severity_type})) { $hashRUN{$k} = 1; } } + #print "I=$IGNORE,E=$EMAIL, L=$LOG, R=$RUNCMD, D=$DB\n"; #email 'alerts' aliase -if ($EMAIL || ((keys(%hashE)==0) && ($severity_type =~/Critical|Warning/))) { - #($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); - #$datetime=sprintf "%2d-%02d-%04d %02d:%02d:%02d", $mon+1,$mday,$year+1900,$hour,$min,$sec; - #my $head="SNMP $severity received from $host($ip) on $datetime\n$briefmsg\n"; - my $head="SNMP $severity received from $host($ip)\n$briefmsg\n"; - if ($node1) { $info= getMoreInfo($node1);} - my $middle="Trap details:\n$message\n"; +if ($EMAIL || ((keys(%hashE) == 0) && ($severity_type =~ /Critical|Warning/))) { - #email the full message to the alerts aliase - my $cmd="echo \'$info$head\n$middle\' \| mail -s \"$severity_type: Cluster SNMP Alert\!\" $MAILTO"; - $ENV{'XCATCFG'}=""; - `$cmd`; + #($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); + #$datetime=sprintf "%2d-%02d-%04d %02d:%02d:%02d", $mon+1,$mday,$year+1900,$hour,$min,$sec; + #my $head="SNMP $severity received from $host($ip) on $datetime\n$briefmsg\n"; + my $head = "SNMP $severity received from $host($ip)\n$briefmsg\n"; + if ($node1) { $info = getMoreInfo($node1); } + my $middle = "Trap details:\n$message\n"; + + #email the full message to the alerts aliase + my $cmd = "echo \'$info$head\n$middle\' \| mail -s \"$severity_type: Cluster SNMP Alert\!\" $MAILTO"; + $ENV{'XCATCFG'} = ""; + `$cmd`; } #log to syslog if needed. default is log all -$ENV{'XCATCFG'}=""; -if ($LOG || (keys(%hashL)==0)) { - my $head="SNMP $severity received from $host($ip)."; - my $body; - if ($briefmsg) { $body=$briefmsg;} - else { $body=$message; } +$ENV{'XCATCFG'} = ""; +if ($LOG || (keys(%hashL) == 0)) { + my $head = "SNMP $severity received from $host($ip)."; + my $body; + if ($briefmsg) { $body = $briefmsg; } + else { $body = $message; } - openlog("xcat","","local4"); - if ($severity_type eq "Informational") { - syslog("local4|info", "$head\n$body\n"); - } else { - syslog("local4|err", "$head\n$body\n"); - } - closelog(); + openlog("xcat", "", "local4"); + if ($severity_type eq "Informational") { + syslog("local4|info", "$head\n$body\n"); + } else { + syslog("local4|err", "$head\n$body\n"); + } + closelog(); } #save to eventlog table in xCAT database if ($DB) { - my $head="SNMP $severity received from $host($ip)\n$briefmsg\n"; - if (($node1)&& (!$info)) { $info= getMoreInfo($node1);} - my $middle="Trap details:\n$message\n"; - my $event={ - eventtype => 'event', - monitor => 'snmpmon', - monnode => $host, - node => $node1? $node1:"", + my $head = "SNMP $severity received from $host($ip)\n$briefmsg\n"; + if (($node1) && (!$info)) { $info = getMoreInfo($node1); } + my $middle = "Trap details:\n$message\n"; + my $event = { + eventtype => 'event', + monitor => 'snmpmon', + monnode => $host, + node => $node1 ? $node1 : "", application => $appname, - component => $errsrc , - id =>$id, - severity => $severity_type, - message => $message1, - rawdata => "$info$head\n$middle", + component => $errsrc, + id => $id, + severity => $severity_type, + message => $message1, + rawdata => "$info$head\n$middle", }; - my @a=(); - push(@a, $event); - xCAT::TableUtils->logEventsToDatabase(\@a); + my @a = (); + push(@a, $event); + xCAT::TableUtils->logEventsToDatabase(\@a); } #run user defined commands if needed. foreach my $k (keys %hashRUN) { if ($hashRUN{$k} == 1) { - $k =~ /runcmd(\d*)/; - my $scripts=$settings{"cmds$1"}; - while ($scripts =~ s/^([^,]+)(,)*//) { - my $cmd="echo \'host=$host\nip=$ip\n$message\n\' \| $1"; - `$cmd`; - } + $k =~ /runcmd(\d*)/; + my $scripts = $settings{"cmds$1"}; + while ($scripts =~ s/^([^,]+)(,)*//) { + my $cmd = "echo \'host=$host\nip=$ip\n$message\n\' \| $1"; + `$cmd`; + } } } #-------------------------------------------------------------------------------- + =head3 getMoreInfo This function returns the node module/type, serial number, position etc. Arguments: @@ -358,71 +371,73 @@ foreach my $k (keys %hashRUN) { Returns: A string with node info ready to display. =cut + #-------------------------------------------------------------------------------- sub getMoreInfo { - my $node=shift; - my $pos; - my $vpd; - - # get module name and serial number from the xCAT DB. - my $ref; - my $table=xCAT::Table->new("vpd", -create =>1); - if ($table) { - my $ref = $table->getNodeAttribs($node, ['serial', 'mtm']); - if ($ref) { - $vpd .= " Type/Mudule: "; - if ($ref->{mtm}) { $vpd .= $ref->{mtm};} - $vpd .= "\n"; - $vpd .= " Serial Number: "; - if ($ref->{serial}) { $vpd .= $ref->{serial};} - $vpd .= "\n"; - } - $table->close(); - } + my $node = shift; + my $pos; + my $vpd; - # get the info from rinv command if nothing in the vpd table - if (!$vpd) { - my $result=`XCATBYPASS=Y $::XCATROOT/bin/rinv $node all 2>&1 | egrep -i '(model|serial)' | grep -v Univ`; - if ($? == 0) {#success - chomp($result); - my @b=split(/\n/, $result); - foreach (@b) { - s/^(.*)\:(.*)\:(.*)$/$2: $3/; - $vpd .= " $_\n"; + # get module name and serial number from the xCAT DB. + my $ref; + my $table = xCAT::Table->new("vpd", -create => 1); + if ($table) { + my $ref = $table->getNodeAttribs($node, [ 'serial', 'mtm' ]); + if ($ref) { + $vpd .= " Type/Mudule: "; + if ($ref->{mtm}) { $vpd .= $ref->{mtm}; } + $vpd .= "\n"; + $vpd .= " Serial Number: "; + if ($ref->{serial}) { $vpd .= $ref->{serial}; } + $vpd .= "\n"; } - } - } - if (!$vpd) { - $vpd .= " Type/Mudule: \n"; - $vpd .= " Serial Number: \n"; - } - + $table->close(); + } - #get the position - my $table1=xCAT::Table->new("nodepos", -create =>1); - if ($table1) { - my $ref1 = $table1->getNodeAttribs($node, ['rack', 'u', 'chassis', 'slot', 'room', 'comments']); - if (($ref1) && ($ref1->{room})) { $pos .= " Room: " . $ref1->{room}. "\n"; } - if(($ref1) && ($ref1->{rack})) { $pos .= " Rack: ". $ref1->{rack}. "\n";} - if(($ref1) && ($ref1->{u})) { $pos .= " Unit: " . $ref1->{u} . "\n"; } - if(($ref1) && ($ref1->{chassis})) { $pos .= " Chassis: " . $ref1->{chassis} . "\n";} - if(($ref1) && ($ref1->{slot})) { $pos .= " Slot: " . $ref1->{slot} . "\n";} - if(($ref1) && ($ref1->{comments})) { $pos .= " Comments: " . $ref1->{comments} . "\n";} + # get the info from rinv command if nothing in the vpd table + if (!$vpd) { + my $result = `XCATBYPASS=Y $::XCATROOT/bin/rinv $node all 2>&1 | egrep -i '(model|serial)' | grep -v Univ`; + if ($? == 0) { #success + chomp($result); + my @b = split(/\n/, $result); + foreach (@b) { + s/^(.*)\:(.*)\:(.*)$/$2: $3/; + $vpd .= " $_\n"; + } + } + } + if (!$vpd) { + $vpd .= " Type/Mudule: \n"; + $vpd .= " Serial Number: \n"; + } - $pos .= "\n"; - $table1->close(); - } + #get the position + my $table1 = xCAT::Table->new("nodepos", -create => 1); + if ($table1) { + my $ref1 = $table1->getNodeAttribs($node, [ 'rack', 'u', 'chassis', 'slot', 'room', 'comments' ]); + if (($ref1) && ($ref1->{room})) { $pos .= " Room: " . $ref1->{room} . "\n"; } + if (($ref1) && ($ref1->{rack})) { $pos .= " Rack: " . $ref1->{rack} . "\n"; } + if (($ref1) && ($ref1->{u})) { $pos .= " Unit: " . $ref1->{u} . "\n"; } + if (($ref1) && ($ref1->{chassis})) { $pos .= " Chassis: " . $ref1->{chassis} . "\n"; } + if (($ref1) && ($ref1->{slot})) { $pos .= " Slot: " . $ref1->{slot} . "\n"; } + if (($ref1) && ($ref1->{comments})) { $pos .= " Comments: " . $ref1->{comments} . "\n"; } - if (($pos) || ($vpd)) { - return " Node: $node\n$vpd$pos\n"; - } - - return ""; + $pos .= "\n"; + + $table1->close(); + } + + if (($pos) || ($vpd)) { + return " Node: $node\n$vpd$pos\n"; + } + + return ""; } #-------------------------------------------------------------------------------- + =head3 parseSettings This function takes a setting string which looks like "key1=value1,key2=value2..." and returns a hash (key1=>value1, key2=>value2...). @@ -431,31 +446,33 @@ sub getMoreInfo { Returns: A hash. =cut + #-------------------------------------------------------------------------------- sub parseSettings { - my $settings=shift; - my %ret=(); - while (($settings =~ s/^(Informational|Warning|Critical|All|None)()()(,)*//) || - ($settings =~ s/^([^\=]+)(=~)(\"[^\"]+\")(,)*//) || - ($settings =~ s/^([^\=]+)(=~)([^\"\,]+)(,)*//) || - ($settings =~ s/^([^\=]+)(=)(\"[^\"]+\")(,)*//) || - ($settings =~ s/^([^\=]+)(=)([^\"\,]+)(,)*//)) { - my $val='eq'; - if ($2 eq "=~") { $val='=~';} - if (exists($ret{$1}{$val})) { - my $pa=$ret{$1}{$val}; - push(@$pa, $3); + my $settings = shift; + my %ret = (); + while (($settings =~ s/^(Informational|Warning|Critical|All|None)()()(,)*//) || + ($settings =~ s/^([^\=]+)(=~)(\"[^\"]+\")(,)*//) || + ($settings =~ s/^([^\=]+)(=~)([^\"\,]+)(,)*//) || + ($settings =~ s/^([^\=]+)(=)(\"[^\"]+\")(,)*//) || + ($settings =~ s/^([^\=]+)(=)([^\"\,]+)(,)*//)) { + my $val = 'eq'; + if ($2 eq "=~") { $val = '=~'; } + if (exists($ret{$1}{$val})) { + my $pa = $ret{$1}{$val}; + push(@$pa, $3); + } + else { + $ret{$1}{$val} = [$3]; + } } - else { - $ret{$1}{$val}=[$3]; - } - } - #print Dumper(%ret); - return %ret; + #print Dumper(%ret); + return %ret; } #-------------------------------------------------------------------------------- + =head3 checkWithOid This function checks the input strings with the setting to see what actions need to be done for this event. @@ -465,77 +482,79 @@ sub parseSettings { Returns: none. The variables $EMAIL, $LOG, $IGNORE and $RUNCMD may be changed. =cut + #-------------------------------------------------------------------------------- sub checkWithOid { - my $o=shift; - my $v=shift; + my $o = shift; + my $v = shift; - sub checking { - my $hashX=shift; - my $o=shift; - my $v=shift; - - if (exists($hashX->{'All'})) { return 1; } - if (exists($hashX->{'None'})) { return 0; } - - my @a_oid=split('::', $o); - my $new_o=$o; - if (@a_oid == 2) { $new_o=$a_oid[1]; } - #print "o=$o, new_o=$new_o v=$v\n"; + sub checking { + my $hashX = shift; + my $o = shift; + my $v = shift; - #check for 'contains' - if (exists($hashX->{$o})) { - my $pa= $hashX->{$o}{'=~'}; - foreach(@$pa) { - if ($v =~ /$_/) {return 1; } - } - } - if (exists($hashX->{$new_o})) { - my $pa= $hashX->{$new_o}{'=~'}; - foreach(@$pa) { - if ($v =~ /$_/) {return 1; } - } + if (exists($hashX->{'All'})) { return 1; } + if (exists($hashX->{'None'})) { return 0; } + + my @a_oid = split('::', $o); + my $new_o = $o; + if (@a_oid == 2) { $new_o = $a_oid[1]; } + + #print "o=$o, new_o=$new_o v=$v\n"; + + #check for 'contains' + if (exists($hashX->{$o})) { + my $pa = $hashX->{$o}{'=~'}; + foreach (@$pa) { + if ($v =~ /$_/) { return 1; } + } + } + if (exists($hashX->{$new_o})) { + my $pa = $hashX->{$new_o}{'=~'}; + foreach (@$pa) { + if ($v =~ /$_/) { return 1; } + } + } + + #check for 'equals' + if (exists($hashX->{$o})) { + my $pa = $hashX->{$o}{'eq'}; + foreach (@$pa) { + if ($_ eq $v) { return 1; } + } + } + if (exists($hashX->{$new_o})) { + my $pa = $hashX->{$new_o}{'eq'}; + foreach (@$pa) { + if ($_ eq $v) { return 1; } + } + } + + + return 0; } - #check for 'equals' - if (exists($hashX->{$o})) { - my $pa= $hashX->{$o}{'eq'}; - foreach(@$pa) { - if ($_ eq $v) { return 1; } - } - } - if (exists($hashX->{$new_o})) { - my $pa= $hashX->{$new_o}{'eq'}; - foreach(@$pa) { - if ($_ eq $v) { return 1; } - } + if ((!$IGNORE) && (keys(%hashI) > 0)) { + $IGNORE = checking(\%hashI, $o, $v); + if ($IGNORE) { return; } } - - return 0; - } - - if ((!$IGNORE) && (keys(%hashI)>0)) { - $IGNORE=checking(\%hashI, $o, $v); - if ($IGNORE) { return;} - } + if ((!$EMAIL) && (keys(%hashE) > 0)) { + $EMAIL = checking(\%hashE, $o, $v); + } - if ((!$EMAIL) && (keys(%hashE)>0)) { - $EMAIL=checking(\%hashE, $o, $v); - } + if ((!$LOG) && (keys(%hashL) > 0)) { + $LOG = checking(\%hashL, $o, $v); + } - if ((!$LOG) && (keys(%hashL)>0)) { - $LOG=checking(\%hashL, $o, $v); - } + if ((!$DB) && (keys(%hashD) > 0)) { + $DB = checking(\%hashD, $o, $v); + } - if ((!$DB) && (keys(%hashD)>0)) { - $DB=checking(\%hashD, $o, $v); - } + foreach my $k (keys %hashRUN) { + if ($hashRUN{$k} == 0) { $hashRUN{$k} = checking($hashR{$k}, $o, $v); } + } - foreach my $k (keys %hashRUN) { - if ($hashRUN{$k} == 0) { $hashRUN{$k} = checking($hashR{$k}, $o, $v); } - } - } diff --git a/xCAT-server/sbin/xcatconfig b/xCAT-server/sbin/xcatconfig index ac57971a6..b58f14797 100755 --- a/xCAT-server/sbin/xcatconfig +++ b/xCAT-server/sbin/xcatconfig @@ -43,12 +43,12 @@ $::INSTALLDIR = "/install"; # Default TFTP dir location $::TFTPDIR = "/tftpboot"; - my $arraysize=@ARGV; - if ($arraysize ==0) { - my $msg= "No parameters were supplied on the xcatconfig command. Run xcatconfig -h" ; - xCAT::MsgUtils->message("E", $msg); - exit 1; - } +my $arraysize = @ARGV; +if ($arraysize == 0) { + my $msg = "No parameters were supplied on the xcatconfig command. Run xcatconfig -h"; + xCAT::MsgUtils->message("E", $msg); + exit 1; +} Getopt::Long::Configure("posix_default"); Getopt::Long::Configure("no_gnu_compat"); @@ -57,20 +57,20 @@ Getopt::Long::Configure("bundling"); # parse the options if ( !GetOptions( - 'f|force' => \$::FORCE, - 'i|initinstall' => \$::INITIALINSTALL, - 'u|updateinstall' => \$::UPDATEINSTALL, - 'k|sshkeys' => \$::genSSHRootKeys, - 'm|mgtnode' => \$::setupMNinDB, - 's|sshnodehostkeys' => \$::genSSHNodeHostKeys, - 't|tunables' => \$::settunables, - 'c|credentials' => \$::genCredentials, - 'd|database' => \$::initDB, - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, - 'V|verbose' => \$::VERBOSE, - 'installdir=s' => \$::INSTALLDIR, - 'tftpdir=s' => \$::TFTPDIR, + 'f|force' => \$::FORCE, + 'i|initinstall' => \$::INITIALINSTALL, + 'u|updateinstall' => \$::UPDATEINSTALL, + 'k|sshkeys' => \$::genSSHRootKeys, + 'm|mgtnode' => \$::setupMNinDB, + 's|sshnodehostkeys' => \$::genSSHNodeHostKeys, + 't|tunables' => \$::settunables, + 'c|credentials' => \$::genCredentials, + 'd|database' => \$::initDB, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, + 'V|verbose' => \$::VERBOSE, + 'installdir=s' => \$::INSTALLDIR, + 'tftpdir=s' => \$::TFTPDIR, ) ) { @@ -96,7 +96,7 @@ if ($::VERSION) } if ($::FORCE) { - if ( $::INITIALINSTALL + if ($::INITIALINSTALL || $::UPDATEINSTALL || $::genSSHRootKeys || $::genSSHNodeHostKey @@ -105,7 +105,7 @@ if ($::FORCE) || $::initDB) { my $warning = - " The -f flag includes the function for the -i, -u, -k, -s, -c, -d flags. Do not combine with other flags.\n "; +" The -f flag includes the function for the -i, -u, -k, -s, -c, -d flags. Do not combine with other flags.\n "; xCAT::MsgUtils->message("I", $warning); exit 1; } @@ -113,7 +113,7 @@ if ($::FORCE) if (($::INITIALINSTALL) && ($::UPDATEINSTALL)) { my $warning = - " The -i and -u flags may not be input to the command. Use one or the other. \n "; +" The -i and -u flags may not be input to the command. Use one or the other. \n "; xCAT::MsgUtils->message("I", $warning); exit 1; } @@ -134,15 +134,15 @@ else # if on rhel6, check to see if perl-IO-Compress-Zlib* is installed if (($::INITIALINSTALL) || ($::UPDATEINSTALL)) { - my $os = xCAT::Utils->osver(); - my $arch = `uname -p`; - if (($os =~ /^rh.*6$/) && ($arch =~ /^x86_64/)) { - if (!(-e "/usr/lib64/perl5/IO/Uncompress/Gunzip.pm")) { + my $os = xCAT::Utils->osver(); + my $arch = `uname -p`; + if (($os =~ /^rh.*6$/) && ($arch =~ /^x86_64/)) { + if (!(-e "/usr/lib64/perl5/IO/Uncompress/Gunzip.pm")) { xCAT::MsgUtils->message('I', "perl-IO-Compress-Zlib* is not installed. If you try and use genesis discovery, you will have fatal errors in the xcat daemon.\n Install perl-IO-Compress-Zlib,perl-IO-Compress-Base rpms."); - - } - } + } + + } } @@ -174,8 +174,9 @@ if ($::INITIALINSTALL || $::FORCE) } } } + # To support AIX INUCLIENTS, to support the scenario where the user needs to install xCAT rpms -# into the INUCLIENT=1 environment, such as AIX diskless node(installing xCAT in AIX NIM SPOT), +# into the INUCLIENT=1 environment, such as AIX diskless node(installing xCAT in AIX NIM SPOT), # or alternative disk installation. # @@ -183,7 +184,7 @@ if (($::osname eq 'AIX') && ($ENV{'INUCLIENTS'} == 1)) { # INUCLIENTS is configured, add xcatconfig to /etc/inittab my $cmd = "/usr/sbin/lsitab xcatconfig > /dev/null 2>&1"; - my $rc = system("$cmd") >>8; + my $rc = system("$cmd") >> 8; if ($rc != 0) { # add new entry @@ -202,7 +203,7 @@ if (($::osname eq 'AIX') && ($ENV{'INUCLIENTS'} == 1)) { $flag = "-d"; } - + my $mkcmd = qq~/usr/sbin/mkitab "xcatconfig:2:once:$::XCATROOT/sbin/xcatconfig $flag > /dev/console 2>&1"~; system("$mkcmd"); } @@ -212,6 +213,7 @@ if (($::osname eq 'AIX') && ($ENV{'INUCLIENTS'} == 1)) if ($::osname eq 'AIX') { $::arch = `uname -p`; + #$::root = ""; $::root = xCAT::Utils->getHomeDir(); } @@ -228,7 +230,7 @@ if ($::INITIALINSTALL || $::FORCE || $::UPDATEINSTALL) # Ubuntu uses upstart to manage dhcp server, # xCAT does not support upstart for now, # disable dhcp server in upstart and let xCAT totally manage dhcp server - if ( -e "/etc/debian_version" ) + if (-e "/etc/debian_version") { # Try to stop isc-dhcp-server started by upstart my $cmd = "stop isc-dhcp-server"; @@ -244,26 +246,26 @@ if ($::INITIALINSTALL || $::FORCE || $::UPDATEINSTALL) # # if (xCAT::Utils->isMN()) { - if ($::FORCE || $::genSSHNodeHostKeys || $::INITIALINSTALL ) - { - &genSSHNodeHostKey; - } + if ($::FORCE || $::genSSHNodeHostKeys || $::INITIALINSTALL) + { + &genSSHNodeHostKey; + } } # -# Set tunables +# Set tunables # # -if (($::settunables) && ( $::osname eq 'AIX')) { # not supported on AIX - xCAT::MsgUtils->message('E', "Setting tunables (-t) is not supported on AIX."); - exit 1; +if (($::settunables) && ($::osname eq 'AIX')) { # not supported on AIX + xCAT::MsgUtils->message('E', "Setting tunables (-t) is not supported on AIX."); + exit 1; } -if ($::FORCE || $::settunables || $::INITIALINSTALL ) +if ($::FORCE || $::settunables || $::INITIALINSTALL) { - if ($::osname eq 'Linux') { - &settunables; - } + if ($::osname eq 'Linux') { + &settunables; + } } # # gen root's ssh keys, if needed and copy to appropriate directories to @@ -277,14 +279,14 @@ if ($::INITIALINSTALL || $::FORCE || $::genSSHRootKeys) # # Update /etc/profile on AIX # -if (($::INITIALINSTALL) ||($::UPDATEINSTALL)) +if (($::INITIALINSTALL) || ($::UPDATEINSTALL)) { my $profname = "/etc/profile"; if ($::osname eq 'AIX') { my $cmd = qq~cat $profname | grep "XCATROOT"~; my $outref = xCAT::Utils->runcmd("$cmd", -1); - if ($::RUNCMD_RC != 0) # no xcat paths in the /etc/profile + if ($::RUNCMD_RC != 0) # no xcat paths in the /etc/profile { # make back up file @@ -297,25 +299,25 @@ if (($::INITIALINSTALL) ||($::UPDATEINSTALL)) # add xCAT paths my $eccmd = - qq~echo '# xCAT setup\nXCATROOT=$::XCATROOT\nPATH=\$XCATROOT/bin:\$XCATROOT/sbin:\$XCATROOT/share/xcat/tools:\$PATH\nMANPATH=\$XCATROOT/share/man:\$MANPATH\nexport XCATROOT PATH MANPATH' >>$profname~; +qq~echo '# xCAT setup\nXCATROOT=$::XCATROOT\nPATH=\$XCATROOT/bin:\$XCATROOT/sbin:\$XCATROOT/share/xcat/tools:\$PATH\nMANPATH=\$XCATROOT/share/man:\$MANPATH\nexport XCATROOT PATH MANPATH' >>$profname~; $outref = xCAT::Utils->runcmd("$eccmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', "Could not update $profname."); } - } else { # xcat path is there, maybe need to add /share/xcat/tools - my $cmd = qq~cat $profname | grep "/share/xcat/tools"~; - my $outref = xCAT::Utils->runcmd("$cmd", -1); - if ($::RUNCMD_RC != 0) # no tools paths in the /etc/profile - { - my $eccmd = - qq~echo 'PATH=\$XCATROOT/share/xcat/tools:\$PATH\nexport MANPATH' >>$profname~; - $outref = xCAT::Utils->runcmd("$eccmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not update $profname."); - } - } + } else { # xcat path is there, maybe need to add /share/xcat/tools + my $cmd = qq~cat $profname | grep "/share/xcat/tools"~; + my $outref = xCAT::Utils->runcmd("$cmd", -1); + if ($::RUNCMD_RC != 0) # no tools paths in the /etc/profile + { + my $eccmd = +qq~echo 'PATH=\$XCATROOT/share/xcat/tools:\$PATH\nexport MANPATH' >>$profname~; + $outref = xCAT::Utils->runcmd("$eccmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not update $profname."); + } + } } } } @@ -334,7 +336,7 @@ if ($::INITIALINSTALL || $::FORCE || $::UPDATEINSTALL) if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not create /var/log/consoles directory."); + "Could not create /var/log/consoles directory."); } else { @@ -344,34 +346,35 @@ if ($::INITIALINSTALL || $::FORCE || $::UPDATEINSTALL) if ($::osname eq 'AIX') { - if ($::INITIALINSTALL) { # do only on install - xCAT::Utils->setupAIXconserver($::VERBOSE); + if ($::INITIALINSTALL) { # do only on install + xCAT::Utils->setupAIXconserver($::VERBOSE); } &setupAIXIPMITool; # Add the xcatd subsystem to the AIX no strict 'refs'; my $mkssys_cmd = - "mkssys -p $::XCATROOT/sbin/xcatd -s xcatd -u 0 -S -n 15 -f 15 -a \"-f\""; +"mkssys -p $::XCATROOT/sbin/xcatd -s xcatd -u 0 -S -n 15 -f 15 -a \"-f\""; system($mkssys_cmd); use strict; # if not Update, add to inittab # breaks HAMS to add on update - if (! $::UPDATEINSTALL) { - # for AIX systems add xcatd to the /etc/inittab file - # add xcatd entry if one does not exist - my $rcmd = "/bin/cat /etc/inittab | grep 'xcatd'"; - my $outref = xCAT::Utils->runcmd("$rcmd", -1); - if ($::RUNCMD_RC != 0) { - my $mkitab_cmd = - "mkitab \"xcatd:2:once:$::XCATROOT/sbin/restartxcatd > /dev/console 2>&1\" > /dev/null 2>&1"; - xCAT::Utils->runcmd("$mkitab_cmd", 0); - if ($::RUNCMD_RC != 0) { + if (!$::UPDATEINSTALL) { + + # for AIX systems add xcatd to the /etc/inittab file + # add xcatd entry if one does not exist + my $rcmd = "/bin/cat /etc/inittab | grep 'xcatd'"; + my $outref = xCAT::Utils->runcmd("$rcmd", -1); + if ($::RUNCMD_RC != 0) { + my $mkitab_cmd = +"mkitab \"xcatd:2:once:$::XCATROOT/sbin/restartxcatd > /dev/console 2>&1\" > /dev/null 2>&1"; + xCAT::Utils->runcmd("$mkitab_cmd", 0); + if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', "Could not set up inittab."); - } - } - } + } + } + } # add AIX needed exports &setupAIXexports; @@ -418,11 +421,12 @@ if ($::INITIALINSTALL || $::FORCE || $::UPDATEINSTALL) verbose("syslog has been set up."); } } + # The systemd only has LANG and PATH as default environmental variables, # TERM is needed for KVM consoles(actually screen command needs TERM) # import the TERM into systemd -if ( -d "/usr/lib/systemd/system" ) { - my $term=$ENV{'TERM'}; +if (-d "/usr/lib/systemd/system") { + my $term = $ENV{'TERM'}; if (!$term) { $term = "vt100"; } @@ -460,125 +464,130 @@ if ($::INITIALINSTALL || $::FORCE) &startnamedonboot; my $cmd; if ($::osname eq 'Linux') { - #Zap the almost certainly wrong pxelinux.cfg file - if (-f "$::TFTPDIR/pxelinux.cfg/default") - { - $cmd = "/bin/rm $::TFTPDIR/pxelinux.cfg/default"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) + + #Zap the almost certainly wrong pxelinux.cfg file + if (-f "$::TFTPDIR/pxelinux.cfg/default") { - xCAT::MsgUtils->message('E', - "Could not remove $::TFTPDIR/pxelinux.cfg/default"); + $cmd = "/bin/rm $::TFTPDIR/pxelinux.cfg/default"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', + "Could not remove $::TFTPDIR/pxelinux.cfg/default"); + } + else + { + verbose("Removed $::TFTPDIR/pxelinux.cfg/default."); + } } - else + + # makenetworks and setup http + &makenetworks; + &setuphttp; + + # chkconfig dhcpd on + #system("chkconfig dhcpd on"); + xCAT::Utils->enableservice("dhcp"); + + # Turn off selinux on RedHat + if (-f "/etc/redhat-release") { - verbose("Removed $::TFTPDIR/pxelinux.cfg/default."); - } - } + my $rc = xCAT::Utils->isSELINUX(); - # makenetworks and setup http - &makenetworks; - &setuphttp; + # rc 0 means SELinux is enabled + # rc 1 means SELinux is not enabled + if ($rc == 0) + { + xCAT::MsgUtils->message('W', "SELINUX is not disabled, disabling it now..."); - # chkconfig dhcpd on - #system("chkconfig dhcpd on"); - xCAT::Utils->enableservice("dhcp"); + # set selinux be in permissive mode for running system, + # if the user forgot to disable selinux, + # try to not hurt xcat too much + my $enforcefile; + if (-f "/selinux/enforce") + { + $enforcefile = "/selinux/enforce"; + } elsif (-f "/sys/fs/selinux/enforce") { + $enforcefile = "/sys/fs/selinux/enforce"; + } + if ($enforcefile) + { + my $cmd = "echo 0 > $enforcefile"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Failed to disable SELINUX."); + } + } - # Turn off selinux on RedHat - if (-f "/etc/redhat-release") - { - my $rc=xCAT::Utils->isSELINUX(); - # rc 0 means SELinux is enabled - # rc 1 means SELinux is not enabled - if ($rc == 0) - { - xCAT::MsgUtils->message('W', "SELINUX is not disabled, disabling it now..."); - # set selinux be in permissive mode for running system, - # if the user forgot to disable selinux, - # try to not hurt xcat too much - my $enforcefile; - if ( -f "/selinux/enforce") - { - $enforcefile = "/selinux/enforce"; - } elsif ( -f "/sys/fs/selinux/enforce" ) { - $enforcefile = "/sys/fs/selinux/enforce"; - } - if ($enforcefile) - { - my $cmd = "echo 0 > $enforcefile"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { + # Disable selinux through reboots + my $cmd = "sed -i 's/^SELINUX=.*\$/SELINUX=disabled/' /etc/selinux/config"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { xCAT::MsgUtils->message('E', "Failed to disable SELINUX."); - } - } - # Disable selinux through reboots - my $cmd = "sed -i 's/^SELINUX=.*\$/SELINUX=disabled/' /etc/selinux/config"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Failed to disable SELINUX."); - } - } - } + } + } + } - my $ret=xCAT::Utils->stopservice("firewall"); - if($ret!=0) + my $ret = xCAT::Utils->stopservice("firewall"); + if ($ret != 0) { xCAT::MsgUtils->message('E', "Failed to stop firewall"); } - $ret=xCAT::Utils->disableservice("firewall"); - if($ret!=0) + $ret = xCAT::Utils->disableservice("firewall"); + if ($ret != 0) { xCAT::MsgUtils->message('E', "Failed to disable firewall on boot"); } - #} - # Enable ip forwarding. In most cases, - # the MN itself will act as the default gateway for the compute nodes, - # ip forwarding is required for a network gateway - xCAT::NetworkUtils->setup_ip_forwarding(1); + #} - # Enable ipv6 forwarding, - # only if there are IPv6 networks in the networks table - my $ipv6net = 0; - my $ntab = xCAT::Table->new('networks'); - if ($ntab) - { - foreach my $enet (@{$ntab->getAllEntries()}) - { - if ($enet->{'net'} =~ /:/) - { - $ipv6net = 1; - } - } - $ntab->close(); - } - if ($ipv6net) - { - xCAT::NetworkUtils->setup_ipv6_forwarding(1); - } + # Enable ip forwarding. In most cases, + # the MN itself will act as the default gateway for the compute nodes, + # ip forwarding is required for a network gateway + xCAT::NetworkUtils->setup_ip_forwarding(1); + + # Enable ipv6 forwarding, + # only if there are IPv6 networks in the networks table + my $ipv6net = 0; + my $ntab = xCAT::Table->new('networks'); + if ($ntab) + { + foreach my $enet (@{ $ntab->getAllEntries() }) + { + if ($enet->{'net'} =~ /:/) + { + $ipv6net = 1; + } + } + $ntab->close(); + } + if ($ipv6net) + { + xCAT::NetworkUtils->setup_ipv6_forwarding(1); + } - my $linux_note = - "xCAT is now running, it is recommended to tabedit networks \nand set a dynamic ip address range on any networks where nodes \nare to be discovered. Then, run makedhcp -n to create a new dhcpd \nconfiguration file, and \/etc\/init.d\/dhcpd restart. Either examine sample \nconfiguration templates, or write your own, or specify a value per \nnode with nodeadd or tabedit."; - xCAT::MsgUtils->message('I', $linux_note); + my $linux_note = +"xCAT is now running, it is recommended to tabedit networks \nand set a dynamic ip address range on any networks where nodes \nare to be discovered. Then, run makedhcp -n to create a new dhcpd \nconfiguration file, and \/etc\/init.d\/dhcpd restart. Either examine sample \nconfiguration templates, or write your own, or specify a value per \nnode with nodeadd or tabedit."; + xCAT::MsgUtils->message('I', $linux_note); - } else { #AIX - # makenetworks - &makenetworks; + } else { #AIX + # makenetworks + &makenetworks; - my $AIX_note = - "xCAT is now running."; - xCAT::MsgUtils->message('I', $AIX_note); - } + my $AIX_note = + "xCAT is now running."; + xCAT::MsgUtils->message('I', $AIX_note); + } } #End - more - Linux-only config # Run mknb to put xCAT-genesis-scripts-x86_64 and xCAT-genesis-base-x86_64 together and in /tftpboot if (($::INITIALINSTALL || $::UPDATEINSTALL) && $::osname eq 'Linux') { - &mknb; + &mknb; } END @@ -588,17 +597,18 @@ END if (($::osname eq 'AIX') && ($ENV{'INUCLIENTS'} != 1)) { my $cmd = "/usr/sbin/lsitab xcatconfig > /dev/null 2>&1"; - my $rc = system("$cmd") >>8; + my $rc = system("$cmd") >> 8; if ($rc == 0) { my $rmcmd = '/usr/sbin/rmitab xcatconfig'; system("$rmcmd"); - } + } } } + # if xcatconfig -m request to setup the management node in the database if ($::setupMNinDB) { - &setupMNinDB; + &setupMNinDB; } exit; @@ -620,12 +630,12 @@ sub usage { xCAT::MsgUtils->message( 'I', - "Usage:\nxcatconfig - Performs basic xCAT setup operations on an xCAT management node. Only the -t option should be used on a Service Node.\n" - ); +"Usage:\nxcatconfig - Performs basic xCAT setup operations on an xCAT management node. Only the -t option should be used on a Service Node.\n" + ); xCAT::MsgUtils->message( 'I', - "xcatconfig [-h|--help]\nxcatconfig [-v|--version]\nxcatconfig [-f|--force] [-V|--verbose]\nxcatconfig [-i|--initinstall] [-V|--verbose]\nxcatconfig [-u|--updateinstall] [-V|--verbose]\nxcatconfig [-k|--sshkeys] [-s|--sshnodehostkeys] [-c|--credentials] [-d|database] [-m|mgtnode] [-t|tunables] [-V|--verbose]" - ); +"xcatconfig [-h|--help]\nxcatconfig [-v|--version]\nxcatconfig [-f|--force] [-V|--verbose]\nxcatconfig [-i|--initinstall] [-V|--verbose]\nxcatconfig [-u|--updateinstall] [-V|--verbose]\nxcatconfig [-k|--sshkeys] [-s|--sshnodehostkeys] [-c|--credentials] [-d|database] [-m|mgtnode] [-t|tunables] [-V|--verbose]" + ); } sub verbose @@ -682,25 +692,25 @@ sub genSSHRootKeys # ok - then add this entry my $cmd = - "/bin/echo StrictHostKeyChecking no >> $cfgfile; chmod 600 $cfgfile"; +"/bin/echo StrictHostKeyChecking no >> $cfgfile; chmod 600 $cfgfile"; my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not update the $cfgfile file."); + "Could not update the $cfgfile file."); } else { xCAT::MsgUtils->message('I', - "Added updates to the $cfgfile file."); + "Added updates to the $cfgfile file."); } } - if ( -e "/etc/debian_version" ){ + if (-e "/etc/debian_version") { my $out = `/bin/cat $cfgfile | grep 'HashKnownHosts'`; - if ( $out ){ - `/bin/sed -e 's/.*HashKnownHosts.*/HashKnownHosts no/' $cfgfile > tempcfg;mv -f tempcfg $cfgfile`; + if ($out) { +`/bin/sed -e 's/.*HashKnownHosts.*/HashKnownHosts no/' $cfgfile > tempcfg;mv -f tempcfg $cfgfile`; } - else{ + else { `/bin/echo HashKnownHosts no >> $cfgfile`; } `chmod 600 $cfgfile`; @@ -721,10 +731,11 @@ sub genSSHRootKeys { xCAT::MsgUtils->message('I', "Added updates to the $cfgfile file."); } + #debian or ubuntu, the HashKnownHosts default is yes, change it - if ( -e "/etc/debian_version" ){ - $cmd = "/bin/echo HashKnownHosts no >> $cfgfile"; - xCAT::Utils->runcmd("$cmd", 0); + if (-e "/etc/debian_version") { + $cmd = "/bin/echo HashKnownHosts no >> $cfgfile"; + xCAT::Utils->runcmd("$cmd", 0); } } @@ -738,7 +749,7 @@ sub genSSHRootKeys if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not create $::INSTALLDIR/postscripts/_ssh directory."); + "Could not create $::INSTALLDIR/postscripts/_ssh directory."); } else { @@ -760,12 +771,12 @@ sub genSSHRootKeys if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not remove id_rsa files from $::root/.ssh directory."); + "Could not remove id_rsa files from $::root/.ssh directory."); } else { xCAT::MsgUtils->message('I', - "Removed id_rsa files from $::root/.ssh directory."); + "Removed id_rsa files from $::root/.ssh directory."); } } @@ -795,25 +806,26 @@ sub genSSHRootKeys { xCAT::MsgUtils->message( 'E', - "Could not copy $pubfile to $::INSTALLDIR/postscripts/_ssh/authorized_keys." - ); +"Could not copy $pubfile to $::INSTALLDIR/postscripts/_ssh/authorized_keys." + ); } else { xCAT::MsgUtils->message( - 'I', - "Copied $pubfile to $::INSTALLDIR/postscripts/_ssh/authorized_keys." - ); + 'I', +"Copied $pubfile to $::INSTALLDIR/postscripts/_ssh/authorized_keys." + ); } } else { xCAT::MsgUtils->message( 'E', - "Could not copy $pubfile to $::INSTALLDIR/postscripts/_ssh/authorized_keys,because $pubfile does not exist." - ); +"Could not copy $pubfile to $::INSTALLDIR/postscripts/_ssh/authorized_keys,because $pubfile does not exist." + ); } } + #----------------------------------------------------------------------------- =head3 settunables @@ -824,50 +836,53 @@ sub genSSHRootKeys #----------------------------------------------------------------------------- -sub settunables +sub settunables { - # tuning ARP on Linux - # set for right now - - my $ECHO=xCAT::Utils->fullpathbin("echo"); - my $cmd = "$ECHO '1024' >/proc/sys/net/ipv4/neigh/default/gc_thresh1"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( 'E', "Could not run $cmd."); - } - $cmd = "$ECHO '4096' >/proc/sys/net/ipv4/neigh/default/gc_thresh2"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( 'E', "Could not run $cmd."); - } - $cmd = "$ECHO '8192' >/proc/sys/net/ipv4/neigh/default/gc_thresh3"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( 'E', "Could not run $cmd."); - } - # set for after reboot - if (!( -f "/etc/sysctl.conf.xcatbackup")){ # not already backed up - $cmd = "cp /etc/sysctl.conf /etc/sysctl.conf.xcatbackup"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( 'E', "Could not backup /etc/sysctl.conf."); - exit 1; - } - } - #delete all occurance of the attribute and then add xCAT settings - `sed -i '/net.ipv4.neigh.default.gc_thresh1 /'d /etc/sysctl.conf`; - `echo "net.ipv4.neigh.default.gc_thresh1 = 1024" >>/etc/sysctl.conf`; - `sed -i '/net.ipv4.neigh.default.gc_thresh2 /'d /etc/sysctl.conf`; - `echo "net.ipv4.neigh.default.gc_thresh2 = 4096" >>/etc/sysctl.conf`; - `sed -i '/net.ipv4.neigh.default.gc_thresh3 /'d /etc/sysctl.conf`; - `echo "net.ipv4.neigh.default.gc_thresh3 = 8192" >>/etc/sysctl.conf`; - + # tuning ARP on Linux + # set for right now + + my $ECHO = xCAT::Utils->fullpathbin("echo"); + my $cmd = "$ECHO '1024' >/proc/sys/net/ipv4/neigh/default/gc_thresh1"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not run $cmd."); + } + $cmd = "$ECHO '4096' >/proc/sys/net/ipv4/neigh/default/gc_thresh2"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not run $cmd."); + } + $cmd = "$ECHO '8192' >/proc/sys/net/ipv4/neigh/default/gc_thresh3"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not run $cmd."); + } + + # set for after reboot + if (!(-f "/etc/sysctl.conf.xcatbackup")) { # not already backed up + $cmd = "cp /etc/sysctl.conf /etc/sysctl.conf.xcatbackup"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not backup /etc/sysctl.conf."); + exit 1; + } + } + + #delete all occurance of the attribute and then add xCAT settings + `sed -i '/net.ipv4.neigh.default.gc_thresh1 /'d /etc/sysctl.conf`; + `echo "net.ipv4.neigh.default.gc_thresh1 = 1024" >>/etc/sysctl.conf`; + `sed -i '/net.ipv4.neigh.default.gc_thresh2 /'d /etc/sysctl.conf`; + `echo "net.ipv4.neigh.default.gc_thresh2 = 4096" >>/etc/sysctl.conf`; + `sed -i '/net.ipv4.neigh.default.gc_thresh3 /'d /etc/sysctl.conf`; + `echo "net.ipv4.neigh.default.gc_thresh3 = 8192" >>/etc/sysctl.conf`; + } + #----------------------------------------------------------------------------- =head3 genSSHNodeHostKey @@ -894,55 +909,55 @@ sub genSSHNodeHostKey my $hostkey2 = "/etc/xcat/hostkeys/ssh_host_rsa_key"; #create directories /etc/xcat/hostkeys and /install/postscripts/hostkeys - if (!-d "$::INSTALLDIR/postscripts/hostkeys") # dir for public keys + if (!-d "$::INSTALLDIR/postscripts/hostkeys") # dir for public keys { - my $cmd = "/bin/mkdir -m 755 -p $::INSTALLDIR/postscripts/hostkeys"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( - 'E', - "Could not create $::INSTALLDIR/postscripts/hostkeys directory." - ); - } + my $cmd = "/bin/mkdir -m 755 -p $::INSTALLDIR/postscripts/hostkeys"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message( + 'E', + "Could not create $::INSTALLDIR/postscripts/hostkeys directory." + ); + } } if (!-d "/etc/xcat/hostkeys") # directory for public/private keys { - my $cmd = "/bin/mkdir -p /etc/xcat/hostkeys"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', - "Could not create /etc/xcat/hostkeys directory."); - } + my $cmd = "/bin/mkdir -p /etc/xcat/hostkeys"; + my $outref = xCAT::Utils->runcmd("$cmd", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', + "Could not create /etc/xcat/hostkeys directory."); + } } # remove the old keys from the /intall/postscripts/hostkeys directroy if (-r $hostkey) { - my $cmd = "/bin/rm $::INSTALLDIR/postscripts/hostkeys/ssh_host*"; - my $outref = xCAT::Utils->runcmd("$cmd", -1); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( - 'I', - "Could not remove ssh keys from $::INSTALLDIR/postscripts/hostkeys directory. They may not exist." - ); - } + my $cmd = "/bin/rm $::INSTALLDIR/postscripts/hostkeys/ssh_host*"; + my $outref = xCAT::Utils->runcmd("$cmd", -1); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message( + 'I', +"Could not remove ssh keys from $::INSTALLDIR/postscripts/hostkeys directory. They may not exist." + ); + } } # remove the old keys from the /etc/xcat/hostkeys directory if (-r $hostkey2) { - my $cmd = "/bin/rm /etc/xcat/hostkeys/ssh_host*"; - my $outref = xCAT::Utils->runcmd("$cmd", -1); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message( - 'I', - "Could not remove ssh keys from /etc/xcat/hostkeys directory. They may not exist." - ); - } + my $cmd = "/bin/rm /etc/xcat/hostkeys/ssh_host*"; + my $outref = xCAT::Utils->runcmd("$cmd", -1); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message( + 'I', +"Could not remove ssh keys from /etc/xcat/hostkeys directory. They may not exist." + ); + } } # @@ -951,56 +966,57 @@ sub genSSHNodeHostKey xCAT::MsgUtils->message('I', "Generating new node hostkeys..."); xCAT::MsgUtils->message('I', "Generating SSH2 RSA Key..."); my $cmd = - "/usr/bin/ssh-keygen -t rsa -f /etc/xcat/hostkeys/ssh_host_rsa_key -C '' -N ''"; +"/usr/bin/ssh-keygen -t rsa -f /etc/xcat/hostkeys/ssh_host_rsa_key -C '' -N ''"; my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E', "Could not generate SSH2 RSA key."); + xCAT::MsgUtils->message('E', "Could not generate SSH2 RSA key."); } xCAT::MsgUtils->message('I', "Generating SSH2 DSA Key..."); $cmd = - "/usr/bin/ssh-keygen -t dsa -f /etc/xcat/hostkeys/ssh_host_dsa_key -C '' -N ''"; - $outref = xCAT::Utils->runcmd("$cmd", 0); +"/usr/bin/ssh-keygen -t dsa -f /etc/xcat/hostkeys/ssh_host_dsa_key -C '' -N ''"; + $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E', "Could not generate SSH2 DSA key."); + xCAT::MsgUtils->message('E', "Could not generate SSH2 DSA key."); } + # see if this system supports the ecdsa if (-e "/etc/ssh/ssh_host_ecdsa_key") { - xCAT::MsgUtils->message('I', "Generating SSH2 ECDSA Key..."); - $cmd = - "/usr/bin/ssh-keygen -t ecdsa -f /etc/xcat/hostkeys/ssh_host_ecdsa_key -C '' -N ''"; + xCAT::MsgUtils->message('I', "Generating SSH2 ECDSA Key..."); + $cmd = +"/usr/bin/ssh-keygen -t ecdsa -f /etc/xcat/hostkeys/ssh_host_ecdsa_key -C '' -N ''"; $outref = xCAT::Utils->runcmd("$cmd", 0); - if ($::RUNCMD_RC != 0) - { + if ($::RUNCMD_RC != 0) + { xCAT::MsgUtils->message('E', "Could not generate SSH2 ECDSA key."); - } + } } # copy the public keys to install directory $cmd = - "/bin/cp /etc/xcat/hostkeys/*.pub $::INSTALLDIR/postscripts/hostkeys/."; + "/bin/cp /etc/xcat/hostkeys/*.pub $::INSTALLDIR/postscripts/hostkeys/."; $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E', "$cmd not successful."); + xCAT::MsgUtils->message('E', "$cmd not successful."); } else { - verbose("$cmd is successful"); + verbose("$cmd is successful"); } } sub is_redhat6sp4 { - if( -e "/etc/redhat-release" ){ + if (-e "/etc/redhat-release") { open(my $relfile, "<", "/etc/redhat-release"); my $line = <$relfile>; close($relfile); - if ( $line =~ /Red Hat Enterprise Linux Server release 6.[4-5]/i ){ + if ($line =~ /Red Hat Enterprise Linux Server release 6.[4-5]/i) { return 1; } } @@ -1033,48 +1049,50 @@ sub initDB my $tftpdir = "$::TFTPDIR"; my $installdir = "$::INSTALLDIR"; my $master; - $master = xCAT::NetworkUtils->getipaddr($hname); + $master = xCAT::NetworkUtils->getipaddr($hname); if (!$master) { xCAT::MsgUtils->message("E", "Hostname resolution for $hname failed, setting the site.master to NORESOLUTION for now, after the xCAT installation is finished, fix this hostname resolution problem, change the site.master to the correct value and then resart xcatd."); $master = "NORESOLUTION"; } + # get forwarders which are the nameserver entries in /etc/resolv.conf # don't use if the address is this machine (Management Node) my $forwarders; + # find out the names for the Management Node my @MNnodeinfo = xCAT::NetworkUtils->determinehostname; - my $MNnodename = pop @MNnodeinfo; # hostname - my @MNnodeipaddr = @MNnodeinfo; # ipaddresses + my $MNnodename = pop @MNnodeinfo; # hostname + my @MNnodeipaddr = @MNnodeinfo; # ipaddresses - my @names; + my @names; my @tmpnames = - xCAT::Utils->runcmd( - "/bin/grep ^[^#]*nameserver /etc/resolv.conf | awk '{print \$2}'", -1); + xCAT::Utils->runcmd( + "/bin/grep ^[^#]*nameserver /etc/resolv.conf | awk '{print \$2}'", -1); foreach my $ip (@tmpnames) { - if (!grep(/^$ip$/, @MNnodeipaddr)) - { # if not the MN - push @names,$ip; # add it as a forwarder - } + if (!grep(/^$ip$/, @MNnodeipaddr)) + { # if not the MN + push @names, $ip; # add it as a forwarder + } } if (@names) { - $forwarders = join(',', @names); + $forwarders = join(',', @names); } - + # for policy table # get hostname from the /etc/xcat/cert/server-cert.pem my $MNname; - if ( -e ("/etc/xcat/cert/server-cert.pem")) { - my $cmd ="grep Subject /etc/xcat/cert/server-cert.pem"; - my $result = xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("E", "Error from $cmd.\n MN policy not created."); - - } - (my $subject,my $mname) = split /CN=/ , $result; - ($MNname, my $endstuff) = split /Subject/, $mname; - $MNname =~ s/\s*//g; + if (-e ("/etc/xcat/cert/server-cert.pem")) { + my $cmd = "grep Subject /etc/xcat/cert/server-cert.pem"; + my $result = xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("E", "Error from $cmd.\n MN policy not created."); + + } + (my $subject, my $mname) = split /CN=/, $result; + ($MNname, my $endstuff) = split /Subject/, $mname; + $MNname =~ s/\s*//g; } # set value based on OS @@ -1103,19 +1121,20 @@ sub initDB chomp $domain; # create basic site definition, if they do not exist reset request - if ( ((!-r "/etc/xcat/site.sqlite") && (!-r "/etc/xcat/cfgloc")) + if (((!-r "/etc/xcat/site.sqlite") && (!-r "/etc/xcat/cfgloc")) || $::FORCE || $::initDB) { my $chtabcmds; - my $confdir = "/etc/xcat"; - my $syncdir = "/var/xcat/syncfiles"; + my $confdir = "/etc/xcat"; + my $syncdir = "/var/xcat/syncfiles"; my $nodesyncdir = "/var/xcat/node/syncfiles"; $chtabcmds = "$::XCATROOT/sbin/chtab key=blademaxp site.value=64;"; $chtabcmds .= "$::XCATROOT/sbin/chtab key=domain site.value=$domain;"; $chtabcmds .= "$::XCATROOT/sbin/chtab key=fsptimeout site.value=0;"; $chtabcmds .= "$::XCATROOT/sbin/chtab key=installdir site.value=$installdir;"; + if ($::osname eq 'Linux') { $chtabcmds .= "$::XCATROOT/sbin/chtab key=ipmimaxp site.value=64;"; @@ -1128,7 +1147,7 @@ sub initDB } $chtabcmds .= "$::XCATROOT/sbin/chtab key=master site.value=$master;"; if ($forwarders) { - $chtabcmds .= "$::XCATROOT/sbin/chtab key=forwarders site.value=$forwarders;"; + $chtabcmds .= "$::XCATROOT/sbin/chtab key=forwarders site.value=$forwarders;"; } $chtabcmds .= "$::XCATROOT/sbin/chtab key=nameservers site.value=$master;"; $chtabcmds .= "$::XCATROOT/sbin/chtab key=maxssh site.value=8;"; @@ -1164,6 +1183,7 @@ sub initDB $chtabcmds .= "$::XCATROOT/sbin/chtab key=auditnosyslog site.value=0;"; $chtabcmds .= "$::XCATROOT/sbin/chtab key=xcatsslversion site.value=TLSv1;"; $chtabcmds .= "$::XCATROOT/sbin/chtab key=auditskipcmds site.value=ALL;"; + #$chtabcmds .= "$::XCATROOT/sbin/chtab key=useflowcontrol site.value=yes;"; # need to fix 4031 if ($::osname eq 'AIX') @@ -1190,54 +1210,57 @@ sub initDB # create default postscript list in postscripts table # if it does not exist, or request reset - if ( ((!-r "/etc/xcat/postscripts.sqlite") && (!-r "/etc/xcat/cfgloc")) + if (((!-r "/etc/xcat/postscripts.sqlite") && (!-r "/etc/xcat/cfgloc")) || $::FORCE || $::initDB) { # For Linux check to see if otherpkgs in the postscripts table # if it is do not change it, otherwise put in postbootscripts - my $chtabcmds = ""; + my $chtabcmds = ""; my $otherpkgsprocessed = 0; my $otherpkgsexist; if ($::osname eq 'Linux') { - $otherpkgsexist = &checkotherpkgs; - # 0 = does not exist - # 1 = exists in postscripts - # 2 = exists in postbootscripts - - # if otherpkgs does not exist or we are initializing the DB - # put in postbootscripts - if (($otherpkgsexist == 0) || ($::initDB)) - { - $chtabcmds = - "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postbootscripts='otherpkgs';"; - $otherpkgsprocessed = 1; - } - # if already processed otherpkgs or it is in postbootscripts attr - # then don't put otherpkgs in the postscripts attribute - # else it was in postscripts attribute so leave it there. - if (($otherpkgsprocessed == 1) || ($otherpkgsexist == 2)) - { - $chtabcmds .= - "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts='syslog,remoteshell,syncfiles';"; - } - else - { # put otherpkgs in postscripts attr - $chtabcmds .= - "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts='syslog,remoteshell,otherpkgs,syncfiles';"; - } - # add servicenode default - $chtabcmds .= - "$::XCATROOT/sbin/chtab node=service postscripts.postscripts='servicenode'"; + $otherpkgsexist = &checkotherpkgs; - } - if ($::osname eq 'AIX') { # we don't use otherpkgs on AIX + # 0 = does not exist + # 1 = exists in postscripts + # 2 = exists in postbootscripts - $chtabcmds .= - "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts='syslog,remoteshell,syncfiles';"; - $chtabcmds .= - "$::XCATROOT/sbin/chtab node=service postscripts.postscripts='servicenode'"; + # if otherpkgs does not exist or we are initializing the DB + # put in postbootscripts + if (($otherpkgsexist == 0) || ($::initDB)) + { + $chtabcmds = +"$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postbootscripts='otherpkgs';"; + $otherpkgsprocessed = 1; + } + + # if already processed otherpkgs or it is in postbootscripts attr + # then don't put otherpkgs in the postscripts attribute + # else it was in postscripts attribute so leave it there. + if (($otherpkgsprocessed == 1) || ($otherpkgsexist == 2)) + { + $chtabcmds .= +"$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts='syslog,remoteshell,syncfiles';"; + } + else + { # put otherpkgs in postscripts attr + $chtabcmds .= +"$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts='syslog,remoteshell,otherpkgs,syncfiles';"; + } + + # add servicenode default + $chtabcmds .= +"$::XCATROOT/sbin/chtab node=service postscripts.postscripts='servicenode'"; + + } + if ($::osname eq 'AIX') { # we don't use otherpkgs on AIX + + $chtabcmds .= +"$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts='syslog,remoteshell,syncfiles';"; + $chtabcmds .= +"$::XCATROOT/sbin/chtab node=service postscripts.postscripts='servicenode'"; } @@ -1245,7 +1268,7 @@ sub initDB if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not create postscripts definition."); + "Could not create postscripts definition."); } else { @@ -1254,7 +1277,7 @@ sub initDB } # create or reset basic policy table definitions - if ( ((!-r "/etc/xcat/policy.sqlite") && (!-r "/etc/xcat/cfgloc")) + if (((!-r "/etc/xcat/policy.sqlite") && (!-r "/etc/xcat/cfgloc")) || $::FORCE || $::initDB) { @@ -1262,50 +1285,50 @@ sub initDB if ($::osname eq 'AIX') { $chtabcmds = - "$::XCATROOT/sbin/chtab priority=1 policy.name=root policy.rule=allow;"; - if (defined($MNname)){ - $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=1.2 policy.name=$MNname policy.rule=trusted;"; - } +"$::XCATROOT/sbin/chtab priority=1 policy.name=root policy.rule=allow;"; + if (defined($MNname)) { + $chtabcmds .= +"$::XCATROOT/sbin/chtab priority=1.2 policy.name=$MNname policy.rule=trusted;"; + } $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.4 policy.commands=getpostscript policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.4 policy.commands=getpostscript policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.5 policy.commands=getcredentials policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.5 policy.commands=getcredentials policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.6 policy.commands=syncfiles policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.6 policy.commands=syncfiles policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=2.3 policy.commands=lsxcatd policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=2.3 policy.commands=lsxcatd policy.rule=allow;"; } else # linux { $chtabcmds = - "$::XCATROOT/sbin/chtab priority=1 policy.name=root policy.rule=allow;"; - if (defined($MNname)){ - $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=1.2 policy.name=$MNname policy.rule=trusted;"; +"$::XCATROOT/sbin/chtab priority=1 policy.name=root policy.rule=allow;"; + if (defined($MNname)) { + $chtabcmds .= +"$::XCATROOT/sbin/chtab priority=1.2 policy.name=$MNname policy.rule=trusted;"; } $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=2 policy.commands=getbmcconfig policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=2 policy.commands=getbmcconfig policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=2.1 policy.commands=remoteimmsetup policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=2.1 policy.commands=remoteimmsetup policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=2.3 policy.commands=lsxcatd policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=2.3 policy.commands=lsxcatd policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=3 policy.commands=nextdestiny policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=3 policy.commands=nextdestiny policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4 policy.commands=getdestiny policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4 policy.commands=getdestiny policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.4 policy.commands=getpostscript policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.4 policy.commands=getpostscript policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.5 policy.commands=getcredentials policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.5 policy.commands=getcredentials policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.6 policy.commands=syncfiles policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.6 policy.commands=syncfiles policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.7 policy.commands=litefile policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.7 policy.commands=litefile policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.8 policy.commands=litetree policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.8 policy.commands=litetree policy.rule=allow;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.9 policy.commands=getadapter policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=4.9 policy.commands=getadapter policy.rule=allow;"; } my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); if ($::RUNCMD_RC != 0) @@ -1324,36 +1347,38 @@ sub initDB # setup Management Node policy to trusted my $chtabcmds; $chtabcmds = - "$::XCATROOT/sbin/chtab priority=1.2 policy.name=$MNname policy.rule=trusted;"; +"$::XCATROOT/sbin/chtab priority=1.2 policy.name=$MNname policy.rule=trusted;"; $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=2.3 policy.commands=lsxcatd policy.rule=allow;"; - $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=2.1 policy.commands=remoteimmsetup policy.rule=allow;"; +"$::XCATROOT/sbin/chtab priority=2.3 policy.commands=lsxcatd policy.rule=allow;"; + $chtabcmds .= +"$::XCATROOT/sbin/chtab priority=2.1 policy.commands=remoteimmsetup policy.rule=allow;"; my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); + if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not update policy.name=$hname rule."); + "Could not update policy.name=$hname rule."); } else { verbose("Updated policy definition for MN."); } - # add statelite policies on update for Linux + + # add statelite policies on update for Linux if ($::osname eq 'Linux') { - $chtabcmds = - "$::XCATROOT/sbin/chtab priority=4.7 policy.commands=litefile policy.rule=allow;"; - $chtabcmds .= - "$::XCATROOT/sbin/chtab priority=4.8 policy.commands=litetree policy.rule=allow;"; - my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not create statelite policy."); - } - else - { - verbose("Created statelite policy definition."); - } + $chtabcmds = +"$::XCATROOT/sbin/chtab priority=4.7 policy.commands=litefile policy.rule=allow;"; + $chtabcmds .= +"$::XCATROOT/sbin/chtab priority=4.8 policy.commands=litetree policy.rule=allow;"; + my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not create statelite policy."); + } + else + { + verbose("Created statelite policy definition."); + } } # For Linux check to see if otherpkgs is in the postscripts table @@ -1362,20 +1387,21 @@ sub initDB # 1 = exists in postscripts # 2 = exists in postbootscripts my $otherpkgsexist; - $chtabcmds =""; + $chtabcmds = ""; if ($::osname eq 'Linux') { - $otherpkgsexist = &checkotherpkgs; - if (($otherpkgsexist == 1) || ($otherpkgsexist == 2)) { - # otherpkgs already in postscripts or in postbootscripts - # just add syncfiles - $chtabcmds = "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts+='syncfiles'"; - } - else - { # otherpkgs does not exist - # put in postbootscripts - $chtabcmds = "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postbootscripts+='otherpkgs';"; - } - } else { # AIX , no otherpkgs just add syncfiles + $otherpkgsexist = &checkotherpkgs; + if (($otherpkgsexist == 1) || ($otherpkgsexist == 2)) { + + # otherpkgs already in postscripts or in postbootscripts + # just add syncfiles + $chtabcmds = "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts+='syncfiles'"; + } + else + { # otherpkgs does not exist + # put in postbootscripts + $chtabcmds = "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postbootscripts+='otherpkgs';"; + } + } else { # AIX , no otherpkgs just add syncfiles $chtabcmds = "$::XCATROOT/sbin/chtab node=xcatdefaults postscripts.postscripts+='syncfiles'"; } @@ -1384,7 +1410,7 @@ sub initDB if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not update postscripts definition."); + "Could not update postscripts definition."); } else { @@ -1394,11 +1420,11 @@ sub initDB # remove any xcatdefaults node in nodelist # leave to cleanup from previous bug - my $rmdefault="$::XCATROOT/sbin/chtab -d node=xcatdefaults nodelist"; + my $rmdefault = "$::XCATROOT/sbin/chtab -d node=xcatdefaults nodelist"; $outref = xCAT::Utils->runcmd("$rmdefault", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E',"Could not remove xcatdefaults."); + xCAT::MsgUtils->message('E', "Could not remove xcatdefaults."); } else { @@ -1416,7 +1442,7 @@ sub initDB $outref = xCAT::Utils->runcmd("$cmds", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E',"Could not set ddns as dnshandler."); + xCAT::MsgUtils->message('E', "Could not set ddns as dnshandler."); } } @@ -1424,18 +1450,20 @@ sub initDB $cmds = "XCATBYPASS=Y $::XCATROOT/sbin/tabdump site 2>/dev/null |grep xcatsslversion"; xCAT::Utils->runcmd("$cmds", -1); if ($::RUNCMD_RC != 0) { + # if site.xcatsslversion was not set, then set the default value TLSv1 $cmds = "$::XCATROOT/sbin/chtab key=xcatsslversion site.value=TLSv1;"; xCAT::Utils->runcmd("$cmds", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E',"Could not add default value for site.xcatsslversion."); + xCAT::MsgUtils->message('E', "Could not add default value for site.xcatsslversion."); } } - } - # remove xcatserver,xcatclient - # from the postscripts. They are now called by servicenode - &cleanupPSTable; - + } + + # remove xcatserver,xcatclient + # from the postscripts. They are now called by servicenode + &cleanupPSTable; + } # end initial DB install setup #----------------------------------------------------------------------------- @@ -1457,12 +1485,12 @@ sub initDB sub checkotherpkgs { my $otherpkgsexist = 0; - my $postscriptstab = xCAT::Table->new('postscripts'); - my $attr = "xcatdefaults"; + my $postscriptstab = xCAT::Table->new('postscripts'); + my $attr = "xcatdefaults"; my @values; if ($postscriptstab) { - my $ref = $postscriptstab->getAttribs({node => $attr}, 'postscripts'); + my $ref = $postscriptstab->getAttribs({ node => $attr }, 'postscripts'); if ($ref) { @values = $ref->{postscripts}; @@ -1475,7 +1503,7 @@ sub checkotherpkgs { # check postbootscripts - my $ref = $postscriptstab->getAttribs({node => $attr}, 'postbootscripts'); + my $ref = $postscriptstab->getAttribs({ node => $attr }, 'postbootscripts'); if ($ref) { @values = $ref->{postscripts}; @@ -1510,7 +1538,7 @@ sub genCredentials $cmd = "groupadd $user"; $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E',"$cmd failed"); + xCAT::MsgUtils->message('E', "$cmd failed"); return; } } @@ -1519,8 +1547,8 @@ sub genCredentials $cmd = "useradd -g $user -s /bin/bash -d /home/$user -m $user"; $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { - xCAT::MsgUtils->message('E',"$cmd failed"); - return; + xCAT::MsgUtils->message('E', "$cmd failed"); + return; } } }; @@ -1531,16 +1559,16 @@ sub genCredentials { xCAT::MsgUtils->message( 'I', - "\nSetting up basic certificates. Respond with a \'y\' when prompted.\n" - ); +"\nSetting up basic certificates. Respond with a \'y\' when prompted.\n" + ); my $cmd = - "echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-xcat-ca.sh 'xCAT CA'"; +"echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-xcat-ca.sh 'xCAT CA'"; verbose("Running $cmd"); my $rc = system($cmd); if ($rc >> 8) { xCAT::MsgUtils->message('E', - "Could not create xCAT certificate in /etc/xcat/ca."); + "Could not create xCAT certificate in /etc/xcat/ca."); } else { @@ -1549,14 +1577,14 @@ sub genCredentials } # copy to postscript directory just non-sensitive files - my $cmd = "/bin/rm -rf $::INSTALLDIR/postscripts/ca >/dev/null 2>&1"; + my $cmd = "/bin/rm -rf $::INSTALLDIR/postscripts/ca >/dev/null 2>&1"; my $outref = xCAT::Utils->runcmd("$cmd", 0); - $cmd = "/bin/mkdir -m 755 -p $::INSTALLDIR/postscripts/ca"; + $cmd = "/bin/mkdir -m 755 -p $::INSTALLDIR/postscripts/ca"; $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not create $::INSTALLDIR/postscripts/ca directory."); + "Could not create $::INSTALLDIR/postscripts/ca directory."); } $cmd = "/bin/cp -p /etc/xcat/ca/ca-cert.pem $::INSTALLDIR/postscripts/ca/ca-cert.pem"; @@ -1566,65 +1594,65 @@ sub genCredentials xCAT::MsgUtils->message( 'E', "$cmd failed" - ); + ); } else { - verbose "$cmd succeeded."; + verbose "$cmd succeeded."; } if ((!-d "/etc/xcat/cert") || $::FORCE || $::genCredentials) { my $cmd = - "echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-server-cert.sh $hname"; +"echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-server-cert.sh $hname"; verbose("Running $cmd"); my $rc = system($cmd); if ($rc >> 8) { xCAT::MsgUtils->message('E', - "Could not create xCAT certificate in /etc/xcat/cert."); + "Could not create xCAT certificate in /etc/xcat/cert."); } else { - if ($::genCredentials) { # if just generating new credentials - xCAT::MsgUtils->message('I', "Created xCAT certificate."); - my $chtabcmds = - "$::XCATROOT/sbin/chtab priority=1.2 policy.name=$hname policy.rule=trusted;"; - my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not create policy definition.$chtabcmds."); + if ($::genCredentials) { # if just generating new credentials + xCAT::MsgUtils->message('I', "Created xCAT certificate."); + my $chtabcmds = +"$::XCATROOT/sbin/chtab priority=1.2 policy.name=$hname policy.rule=trusted;"; + my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not create policy definition.$chtabcmds."); + } } - } } } - if ((! -d "/etc/xcatdockerca/cert") || $::FORCE || $::genCredentials) { + if ((!-d "/etc/xcatdockerca/cert") || $::FORCE || $::genCredentials) { my $cmd = "echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-dockerhost-cert.sh"; verbose("Running $cmd"); my $rc = system($cmd); if ($rc >> 8) { xCAT::MsgUtils->message('E', - "Could not create xCAT dockerhost certificate in /etc/xcatdockerca/cert."); +"Could not create xCAT dockerhost certificate in /etc/xcatdockerca/cert."); } else { verbose("Create xCAT dockerhost certificate in /etc/xcatdockerca/cert directory."); } } # copy to postscript directory, no longer use cert directory - $cmd = "/bin/rm -rf $::INSTALLDIR/postscripts/cert >/dev/null 2>&1"; + $cmd = "/bin/rm -rf $::INSTALLDIR/postscripts/cert >/dev/null 2>&1"; $outref = xCAT::Utils->runcmd("$cmd", 0); if ((!-r "$::root/.xcat/client-key.pem") || $::FORCE || $::genCredentials) { my $cmd = - "echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-local-client.sh root"; +"echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-local-client.sh root"; verbose("Running $cmd"); my $rc = system($cmd); if ($rc >> 8) { xCAT::MsgUtils->message('E', - "Could not create xCAT certificate in /.xcat/client-key.pem."); + "Could not create xCAT certificate in /.xcat/client-key.pem."); } else { @@ -1636,13 +1664,13 @@ sub genCredentials { $add_user_func->('conserver'); my $cmd = - "echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-local-client.sh conserver"; +"echo 'y\ny\ny\ny' |$::XCATROOT/share/xcat/scripts/setup-local-client.sh conserver"; verbose("Running $cmd"); my $rc = system($cmd); if ($rc >> 8) { xCAT::MsgUtils->message('E', - "Could not create xCAT certificate in /home/conserver/.xcat/client-key.pem."); +"Could not create xCAT certificate in /home/conserver/.xcat/client-key.pem."); } else { @@ -1658,7 +1686,7 @@ sub genCredentials if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not create $::INSTALLDIR/postscripts/_xcat directory."); + "Could not create $::INSTALLDIR/postscripts/_xcat directory."); } else { @@ -1670,12 +1698,12 @@ sub genCredentials { xCAT::MsgUtils->message( 'E', - "Could not copy $::root/.xcat/ca.pem to $::INSTALLDIR/postscripts/_xcat directory." - ); +"Could not copy $::root/.xcat/ca.pem to $::INSTALLDIR/postscripts/_xcat directory." + ); } else { - verbose "Copied $::root/.xcat/ca.pem to $::INSTALLDIR/postscripts/_xcat directory."; + verbose "Copied $::root/.xcat/ca.pem to $::INSTALLDIR/postscripts/_xcat directory."; } } @@ -1695,13 +1723,13 @@ sub setupAIXIPMITool if (!-f "/usr/bin/ipmitool") { my $cmd = "ln -sf /opt/freeware/bin/ipmitool /usr/bin/ipmitool"; - my $outref = xCAT::Utils->runcmd("$cmd", 0); + my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message( 'E', "Could not ln -sf /opt/freeware/bin/ipmitool /usr/bin/ipmitool." - ); + ); } else { @@ -1743,7 +1771,7 @@ sub setupAIXexports if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not export directory $::INSTALLDIR/postscripts."); + "Could not export directory $::INSTALLDIR/postscripts."); } } } @@ -1774,13 +1802,13 @@ sub setupLinuxexports # ok - then add this entry #SECURITY: this has potential for sharing private host/user keys my $cmd = - "/bin/echo '$::TFTPDIR *(rw,no_root_squash,sync,no_subtree_check)' >> /etc/exports"; +"/bin/echo '$::TFTPDIR *(rw,no_root_squash,sync,no_subtree_check)' >> /etc/exports"; my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not update the /etc/exports file."); + "Could not update the /etc/exports file."); } else { @@ -1801,12 +1829,12 @@ sub setupLinuxexports # ok - then add this entry #SECURITY: this has potential for sharing private host/user keys my $cmd = - "/bin/echo '$::INSTALLDIR *(rw,no_root_squash,sync,no_subtree_check)' >> /etc/exports"; +"/bin/echo '$::INSTALLDIR *(rw,no_root_squash,sync,no_subtree_check)' >> /etc/exports"; my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { xCAT::MsgUtils->message('E', - "Could not update the /etc/exports file."); + "Could not update the /etc/exports file."); } else { @@ -1819,18 +1847,18 @@ sub setupLinuxexports { # restart nfs - # my $cmd; - # my $os = xCAT::Utils->osver(); - # my $SERVICE = xCAT::Utils->fullpathbin("service"); - # if ($os =~ /sles/) { - # $cmd = "$SERVICE nfsserver restart"; - # } else { - # $cmd = "$SERVICE nfs restart"; - # } - # my $outref = xCAT::Utils->runcmd("$cmd", 0); - # if ($::RUNCMD_RC != 0) - my $ret=xCAT::Utils->restartservice("nfs"); - if($ret!=0) + # my $cmd; + # my $os = xCAT::Utils->osver(); + # my $SERVICE = xCAT::Utils->fullpathbin("service"); + # if ($os =~ /sles/) { + # $cmd = "$SERVICE nfsserver restart"; + # } else { + # $cmd = "$SERVICE nfs restart"; + # } + # my $outref = xCAT::Utils->runcmd("$cmd", 0); + # if ($::RUNCMD_RC != 0) + my $ret = xCAT::Utils->restartservice("nfs"); + if ($ret != 0) { xCAT::MsgUtils->message('E', "Could not restart NFS."); } @@ -1844,13 +1872,13 @@ sub setupLinuxexports # $cmd = "$CHKCONFIG nfsserver on"; #} else { # $cmd = "$CHKCONFIG nfs on"; - #} + #} #$outref = xCAT::Utils->runcmd("$cmd", 0); #if ($::RUNCMD_RC != 0) - $ret=xCAT::Utils->enableservice("nfs"); - if($ret!=0) + $ret = xCAT::Utils->enableservice("nfs"); + if ($ret != 0) { xCAT::MsgUtils->message('E', "Could not enable NFS."); } @@ -1884,14 +1912,15 @@ sub setupLinuxexports sub mknb { # The xCAT-genesis-scripts.spec file touches /etc/xcat/genesis-scripts-updated or - # the xCAT-genesis-base.spec file touches /etc/xcat/genesis-base-updated, + # the xCAT-genesis-base.spec file touches /etc/xcat/genesis-base-updated, # so we know to run mknb here. my $cmd; if ($::arch =~ /ppc/) { $::arch = "ppc64"; } - if ((($::arch eq "x86_64") ||($::arch =~ /ppc/)) && (-f '/etc/xcat/genesis-scripts-updated') ) { + if ((($::arch eq "x86_64") || ($::arch =~ /ppc/)) && (-f '/etc/xcat/genesis-scripts-updated')) { unlink '/etc/xcat/genesis-scripts-updated'; + # Do not print messages or run command twice if (-f '/etc/xcat/genesis-base-updated') { unlink '/etc/xcat/genesis-base-updated'; @@ -1899,11 +1928,12 @@ sub mknb $cmd = "$::XCATROOT/sbin/mknb $::arch"; xCAT::MsgUtils->message('I', "Running '$cmd', triggered by the installation/update of xCAT-genesis-scripts-$::arch ..."); } - if ((($::arch eq "x86_64") ||($::arch =~ /ppc/)) && (-f '/etc/xcat/genesis-base-updated')) { + if ((($::arch eq "x86_64") || ($::arch =~ /ppc/)) && (-f '/etc/xcat/genesis-base-updated')) { unlink '/etc/xcat/genesis-base-updated'; $cmd = "$::XCATROOT/sbin/mknb $::arch"; xCAT::MsgUtils->message('I', "Running '$cmd', triggered by the installation/update of xCAT-genesis-base-$::arch ..."); } + # my $outref = xCAT::Utils->runcmd("$cmd", 0); if ($cmd) { system($cmd); @@ -1943,6 +1973,7 @@ sub makenetworks } + #----------------------------------------------------------------------------- =head3 setuphttp @@ -1952,29 +1983,29 @@ sub makenetworks =cut #----------------------------------------------------------------------------- -sub setuphttp +sub setuphttp { -# my $cmd; -# my $distro = xCAT::Utils->osver(); -# # restart httpd -# if (-e "/etc/init.d/apache2") -# { #for sles/ubuntu -# $cmd = "/etc/init.d/apache2 stop; /etc/init.d/apache2 start"; -# } -# elsif (-e "/etc/init.d/httpd") -# { -# $cmd = "/etc/init.d/httpd stop; /etc/init.d/httpd start"; -# } -# else -# { -# $cmd = "service httpd stop; service httpd start"; -# } + # my $cmd; + # my $distro = xCAT::Utils->osver(); + # # restart httpd + # if (-e "/etc/init.d/apache2") + # { #for sles/ubuntu + # $cmd = "/etc/init.d/apache2 stop; /etc/init.d/apache2 start"; + # } + # elsif (-e "/etc/init.d/httpd") + # { + # $cmd = "/etc/init.d/httpd stop; /etc/init.d/httpd start"; + # } + # else + # { + # $cmd = "service httpd stop; service httpd start"; + # } -# my $outref = xCAT::Utils->runcmd("$cmd", 0); -# if ($::RUNCMD_RC != 0) - my $ret=xCAT::Utils->restartservice("http"); - if($ret!=0) + # my $outref = xCAT::Utils->runcmd("$cmd", 0); + # if ($::RUNCMD_RC != 0) + my $ret = xCAT::Utils->restartservice("http"); + if ($ret != 0) { xCAT::MsgUtils->message('E', "Could not restart httpd."); } @@ -1999,13 +2030,13 @@ sub setuphttp # my $CHKCONFIG = xCAT::Utils->fullpathbin("chkconfig"); # $cmd = "$CHKCONFIG httpd on"; #} - + #$outref = xCAT::Utils->runcmd("$cmd", 0); #if ($::RUNCMD_RC != 0) - $ret=xCAT::Utils->enableservice("http"); - if($ret!=0) + $ret = xCAT::Utils->enableservice("http"); + if ($ret != 0) { xCAT::MsgUtils->message('E', "Could not enable httpd."); } @@ -2014,6 +2045,7 @@ sub setuphttp verbose("httpd has been enabled."); } } + #----------------------------------------------------------------------------- =head3 cleanupPSTable @@ -2039,88 +2071,93 @@ sub setuphttp =cut #----------------------------------------------------------------------------- -sub cleanupPSTable +sub cleanupPSTable { - my $rc=0; - my $tab; - if ($tab = xCAT::Table->new("postscripts")) { - my @tableentries = $tab->getAllAttribs('node','postscripts'); - foreach my $entry (@tableentries) { - my $changeit=0; - my $node=$entry->{'node'}; - my $pslist=$entry->{'postscripts'}; # get list of postscripts on the line - if ($pslist) { - my $servicenode=0; - my $aixremoteshell=0; - my $remoteshell=0; - my $newpslist ="\'"; - my @ps= split(",", $pslist); - # now check is servicenode and xcatclient and/or xcatserver on the line - foreach my $pscript (@ps) { - # check for aixremoteshell, need to replace with remoteshell - if ($pscript =~ /(^|\|)aixremoteshell($|\|)/i) { - $aixremoteshell=1; - } - if ($pscript =~ /(^|\|)remoteshell($|\|)/i) { - $remoteshell=1; - } - if ($pscript =~ /(^|\|)servicenode($|\|)/i) { # found servicenode ps - $newpslist .=$pscript; - $newpslist .=","; - $servicenode=1; - } else{ # process rest of ps list - # if servicenode and aixremoteshell not found on the line go - # to the next line - if (($servicenode == 0) && ($aixremoteshell ==0)) { - $newpslist .=$pscript; - $newpslist .=","; - - } else { - # servicenode found, do not keep xcatserver/xcatclient or - # aixremoteshell, and no remoteshell replace with remoteshell - if (($aixremoteshell == 1) && ($remoteshell == 0)) { - $newpslist .="remoteshell,"; - $changeit=1; # had to replace aixremoteshell - next; - } - # if already put in remoteshell, then skip any more - # occurances of remoteshell on the line - if (($aixremoteshell == 1) && ($remoteshell == 1)) { - next; - } - if (($pscript =~ /(^|\|)xcatserver($|\|)/i) ||($pscript =~ /(^|\|)xcatclient($|\|)/i)) { - $changeit=1; # had to remove xcatserver/xcatclient - next; - } else { - $newpslist .=$pscript; - $newpslist .=","; - } - } # end servicenode processing - } - } - chop $newpslist; - $newpslist .="\'"; - if ($changeit == 1) { # we had to modify the line - my $chtabcmds .= - "$::XCATROOT/sbin/chtab node=$node postscripts.postscripts=$newpslist;"; - my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', - "Could not modify postscripts definition for $node."); - } - } - } - } - } - else - { - xCAT::MsgUtils->message("E", " Could not open the postscripts table\n"); - return 1; - } + my $rc = 0; + my $tab; + if ($tab = xCAT::Table->new("postscripts")) { + my @tableentries = $tab->getAllAttribs('node', 'postscripts'); + foreach my $entry (@tableentries) { + my $changeit = 0; + my $node = $entry->{'node'}; + my $pslist = $entry->{'postscripts'}; # get list of postscripts on the line + if ($pslist) { + my $servicenode = 0; + my $aixremoteshell = 0; + my $remoteshell = 0; + my $newpslist = "\'"; + my @ps = split(",", $pslist); - return $rc + # now check is servicenode and xcatclient and/or xcatserver on the line + foreach my $pscript (@ps) { + + # check for aixremoteshell, need to replace with remoteshell + if ($pscript =~ /(^|\|)aixremoteshell($|\|)/i) { + $aixremoteshell = 1; + } + if ($pscript =~ /(^|\|)remoteshell($|\|)/i) { + $remoteshell = 1; + } + if ($pscript =~ /(^|\|)servicenode($|\|)/i) { # found servicenode ps + $newpslist .= $pscript; + $newpslist .= ","; + $servicenode = 1; + } else { # process rest of ps list + # if servicenode and aixremoteshell not found on the line go + # to the next line + if (($servicenode == 0) && ($aixremoteshell == 0)) { + $newpslist .= $pscript; + $newpslist .= ","; + + } else { + + # servicenode found, do not keep xcatserver/xcatclient or + # aixremoteshell, and no remoteshell replace with remoteshell + if (($aixremoteshell == 1) && ($remoteshell == 0)) { + $newpslist .= "remoteshell,"; + $changeit = 1; # had to replace aixremoteshell + next; + } + + # if already put in remoteshell, then skip any more + # occurances of remoteshell on the line + if (($aixremoteshell == 1) && ($remoteshell == 1)) { + next; + } + if (($pscript =~ /(^|\|)xcatserver($|\|)/i) || ($pscript =~ /(^|\|)xcatclient($|\|)/i)) { + $changeit = 1; # had to remove xcatserver/xcatclient + next; + } else { + $newpslist .= $pscript; + $newpslist .= ","; + } + } # end servicenode processing + } + } + chop $newpslist; + $newpslist .= "\'"; + if ($changeit == 1) { # we had to modify the line + my $chtabcmds .= +"$::XCATROOT/sbin/chtab node=$node postscripts.postscripts=$newpslist;"; + my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', +"Could not modify postscripts definition for $node."); + } + } + } + } + } + else + { + xCAT::MsgUtils->message("E", " Could not open the postscripts table\n"); + return 1; + } + + return $rc } + #----------------------------------------------------------------------------- =head3 setupMNinDB @@ -2134,88 +2171,94 @@ sub cleanupPSTable #----------------------------------------------------------------------------- sub setupMNinDB { - my $mnname = `hostname`; - chomp $mnname; - $mnname && $mnname =~ s/\..*//; # strip off domain + my $mnname = `hostname`; + chomp $mnname; + $mnname && $mnname =~ s/\..*//; # strip off domain - # check to see if MN already defined in the nodelist + # check to see if MN already defined in the nodelist - my $defined = 0; - my $cmds="XCATBYPASS=Y $::XCATROOT/sbin/tabdump nodelist | grep __mgmtnode"; - my @output = xCAT::Utils->runcmd("$cmds", -1); - - if ($::RUNCMD_RC == 0) # found nodes in __mgmtnode - { - my $chtabcmds; - # Look through the MN list and see if this MN is defined - foreach my $line (@output) { - my @mn = split(",", $line); - $mn[0]=~ s/"//g; # remove the quotes - if ($mn[0] eq $mnname) { # already in the database - verbose("$mnname already defined in the the nodelist table."); - $defined=1; - last; + my $defined = 0; + my $cmds = "XCATBYPASS=Y $::XCATROOT/sbin/tabdump nodelist | grep __mgmtnode"; + my @output = xCAT::Utils->runcmd("$cmds", -1); + + if ($::RUNCMD_RC == 0) # found nodes in __mgmtnode + { + my $chtabcmds; + + # Look through the MN list and see if this MN is defined + foreach my $line (@output) { + my @mn = split(",", $line); + $mn[0] =~ s/"//g; # remove the quotes + if ($mn[0] eq $mnname) { # already in the database + verbose("$mnname already defined in the the nodelist table."); + $defined = 1; + last; + } } - } } + # now add with the new name , if not already there - if ($defined ==0) { - my $chtabcmds = "$::XCATROOT/sbin/chtab node=$mnname nodelist.groups=__mgmtnode;"; - my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not add $mnname to the noderes table."); - } - else - { - verbose("Added $mnname to the noderes table."); - } - - } - # now add to the servicenode table with default settings - # check to see if MN already defined in the servicenode table - my $cmds="XCATBYPASS=Y $::XCATROOT/sbin/tabdump servicenode | grep __mgmtnode"; - my $output = xCAT::Utils->runcmd("$cmds", -1); - if ($::RUNCMD_RC != 0) # no management node defined - { - # add to the servicenode table - my $chtabcmds; - if (xCAT::Utils->isLinux()) { - # always setup tftp - $chtabcmds= - "$::XCATROOT/sbin/chtab node=__mgmtnode servicenode.tftpserver=yes "; - # check setting of site.vsftp to see if we want to setup ftp - $cmds="XCATBYPASS=Y $::XCATROOT/sbin/tabdump site | grep vsftp"; - $output = xCAT::Utils->runcmd("$cmds", -1); - if ($::RUNCMD_RC == 0){ # vsftp defined - # check the setting to see if we want ftp - my @vals = split(',', $output); - if ($vals[1] && ($vals[1] !~ /0|NO|No|no|N|n/ )) { # setup ftp - $chtabcmds .= " servicenode.ftpserver=yes "; - } - } - } else { # AIX, don't define any services just add the MN node - $chtabcmds = - "$::XCATROOT/sbin/chtab node=__mgmtnode servicenode.ftpserver=no;"; - } - - my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message('E', "Could not add $mnname to the servicenode table."); - } - else - { - verbose("Added $mnname to the servicenode table table."); - } - - } else { # it was already defined in the servicenode table - verbose("$mnname already defined in the the servicenode table."); - - } - xCAT::MsgUtils->message('I', "Management Node defined in the database."); - return; + if ($defined == 0) { + my $chtabcmds = "$::XCATROOT/sbin/chtab node=$mnname nodelist.groups=__mgmtnode;"; + my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not add $mnname to the noderes table."); + } + else + { + verbose("Added $mnname to the noderes table."); + } + + } + + # now add to the servicenode table with default settings + # check to see if MN already defined in the servicenode table + my $cmds = "XCATBYPASS=Y $::XCATROOT/sbin/tabdump servicenode | grep __mgmtnode"; + my $output = xCAT::Utils->runcmd("$cmds", -1); + if ($::RUNCMD_RC != 0) # no management node defined + { + # add to the servicenode table + my $chtabcmds; + if (xCAT::Utils->isLinux()) { + + # always setup tftp + $chtabcmds = +"$::XCATROOT/sbin/chtab node=__mgmtnode servicenode.tftpserver=yes "; + + # check setting of site.vsftp to see if we want to setup ftp + $cmds = "XCATBYPASS=Y $::XCATROOT/sbin/tabdump site | grep vsftp"; + $output = xCAT::Utils->runcmd("$cmds", -1); + if ($::RUNCMD_RC == 0) { # vsftp defined + # check the setting to see if we want ftp + my @vals = split(',', $output); + if ($vals[1] && ($vals[1] !~ /0|NO|No|no|N|n/)) { # setup ftp + $chtabcmds .= " servicenode.ftpserver=yes "; + } + } + } else { # AIX, don't define any services just add the MN node + $chtabcmds = +"$::XCATROOT/sbin/chtab node=__mgmtnode servicenode.ftpserver=no;"; + } + + my $outref = xCAT::Utils->runcmd("$chtabcmds", 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message('E', "Could not add $mnname to the servicenode table."); + } + else + { + verbose("Added $mnname to the servicenode table table."); + } + + } else { # it was already defined in the servicenode table + verbose("$mnname already defined in the the servicenode table."); + + } + xCAT::MsgUtils->message('I', "Management Node defined in the database."); + return; } + #----------------------------------------------------------------------------- =head3 startnamedonboot @@ -2228,12 +2271,12 @@ sub setupMNinDB sub startnamedonboot { # start named on boot - my $distro = xCAT::Utils->osver(); + my $distro = xCAT::Utils->osver(); if (xCAT::Utils->isAIX()) { #/etc/inittab my $cmd = "/usr/sbin/lsitab named > /dev/null 2>&1"; - my $rc = system("$cmd") >>8; + my $rc = system("$cmd") >> 8; if ($rc != 0) { #add new entry @@ -2255,14 +2298,14 @@ sub startnamedonboot #"service named start" is very slowly,sometimes hang in rhels6.4 after installation #a work around is to generate /etc/rndc-key during xCAT installation - if( is_redhat6sp4() ){ - system("rndc-confgen -a -r /dev/urandom"); + if (is_redhat6sp4()) { + system("rndc-confgen -a -r /dev/urandom"); } #my $outref = xCAT::Utils->runcmd("$cmd", 0); #if ($::RUNCMD_RC != 0) - my $ret=xCAT::Utils->enableservice("named"); - if($ret!=0) + my $ret = xCAT::Utils->enableservice("named"); + if ($ret != 0) { xCAT::MsgUtils->message("E", "Could not enable dns server."); } diff --git a/xCAT-server/sbin/xcatd b/xCAT-server/sbin/xcatd index 4781e0a2d..8e9271509 100644 --- a/xCAT-server/sbin/xcatd +++ b/xCAT-server/sbin/xcatd @@ -3,12 +3,14 @@ use strict; use warnings; use Carp qw(cluck confess); + BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + # Required when using DB2 as the xCAT database: $ENV{'DB2INSTANCE'} = 'xcatdb'; - $ENV{'EXTSHM'} = 'ON'; + $ENV{'EXTSHM'} = 'ON'; if (defined $ENV{ENABLE_TRACE_CODE}) { use lib "$ENV{'XCATROOT'}/lib/perl"; @@ -18,9 +20,9 @@ BEGIN } } -my $globalencode = "xml"; +my $globalencode = "xml"; my %supported_encodes = ( - "xml" => 1, + "xml" => 1, "storable" => 1, ); my $sslctl; @@ -30,6 +32,7 @@ my $pid_MON; # ----used for command log start--------- my $cmdlog_svrpid; + # ----used for command log end--------- # if AIX - make sure we include perl 5.8.2 in INC path. @@ -45,11 +48,12 @@ use xCAT::NetworkUtils; use xCAT::MsgUtils; use xCAT::xcatd; use xCAT::State; -my $os = xCAT::Utils->osver(); +my $os = xCAT::Utils->osver(); my $arch = `uname -p`; + # These do not have the IO::Uncompress rpm available -unless (($^O =~ /^aix/i) || ($os =~ /^sle[sc]10/) || (($os =~ /^rh.*5$/) && ($arch =~ /ppc64/))){ - eval {require IO::Uncompress::Gunzip;} +unless (($^O =~ /^aix/i) || ($os =~ /^sle[sc]10/) || (($os =~ /^rh.*5$/) && ($arch =~ /ppc64/))) { + eval { require IO::Uncompress::Gunzip; } } use File::Basename; use File::Path; @@ -57,12 +61,12 @@ use Time::HiRes qw(sleep); use Thread qw(yield); use Fcntl qw/:DEFAULT :flock/; use xCAT::Client qw(submit_request); -my $clientselect = new IO::Select; -my $sslclients = 0; # THROTTLE -my $maxsslclients = 64; # default -my $batchclients = 50; -my @deferredmsgargs; # hold argumentlist for MsgUtils call until after fork - # parallelizing logging overhead with real work +my $clientselect = new IO::Select; +my $sslclients = 0; # THROTTLE +my $maxsslclients = 64; # default +my $batchclients = 50; +my @deferredmsgargs; # hold argumentlist for MsgUtils call until after fork + # parallelizing logging overhead with real work sub xexit { while (wait() > 0) { @@ -70,18 +74,18 @@ sub xexit { } exit @_; } -my $dispatch_children=0; -my %dispatched_children=(); -my $plugin_numchildren=0; +my $dispatch_children = 0; +my %dispatched_children = (); +my $plugin_numchildren = 0; my %plugin_children; my $inet6support; -my @CALLBACK_COMMAND =('getadapter'); +my @CALLBACK_COMMAND = ('getadapter'); -if ($^O =~ /^aix/i) { # disable AIX IPV6 TODO +if ($^O =~ /^aix/i) { # disable AIX IPV6 TODO $inet6support = 0; } else { - $inet6support=eval { require Socket6 }; + $inet6support = eval { require Socket6 }; } if ($inet6support) { $inet6support = eval { require IO::Socket::INET6 }; @@ -91,6 +95,7 @@ if ($inet6support) { } if ($^O =~ /^linux/i) { + # Is IPv6 enabled on the MN or SN at all? my $ipv6enabled = `ip addr | grep inet6`; if (!$ipv6enabled) { @@ -104,23 +109,24 @@ unless ($inet6support) { eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet4'); }; } -my $dispatch_requests = 1; # govern whether commands are dispatchable +my $dispatch_requests = 1; # govern whether commands are dispatchable use IO::Socket; use IO::Handle; use IO::Select; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; use xCAT::Table; my $dbmaster; use xCAT::ExtTab; use Data::Dumper; use Getopt::Long; use Sys::Syslog qw(:DEFAULT setlogsock); -openlog("xcat","local4"); +openlog("xcat", "local4"); + # turn off warnings for call to setlogsock. puts out warning message if # syslog tcp port not defined in /etc/services. this can safely be ignored. no warnings; -setlogsock(["tcp","unix","stream"]); +setlogsock([ "tcp", "unix", "stream" ]); use warnings; use xCAT::NotifHandler; @@ -135,7 +141,7 @@ use POSIX qw(WNOHANG setsid :errno_h); my $pidfile; my $foreground; GetOptions( - 'pidfile|p=s' => \$pidfile, + 'pidfile|p=s' => \$pidfile, 'foreground|f' => \$foreground ); @@ -145,18 +151,18 @@ unless ($pidfile) { # start syslog if it is not up if (xCAT::Utils->isLinux()) { - my $init_file="/etc/init.d/syslog"; + my $init_file = "/etc/init.d/syslog"; if ((-f "/etc/fedora-release") || (-f "/etc/redhat-release") || (-f "/etc/lsb-release")) { - $init_file="/etc/init.d/rsyslog"; + $init_file = "/etc/init.d/rsyslog"; } - if ( -x $init_file ) { - my $result=`$init_file status 2>&1`; + if (-x $init_file) { + my $result = `$init_file status 2>&1`; if ($result !~ /running/i) { `$init_file start`; } } } else { - my $result=`lssrc -s syslogd 2>&1`; + my $result = `lssrc -s syslogd 2>&1`; if ($result !~ /active/i) { `startsrc -s syslogd`; } @@ -169,47 +175,49 @@ my $domain; my $xcatdir; my $sitetab; my $retries = 0; + # The database initialization may take some time in the system boot scenario # wait for a while for the database initialization -while (!($sitetab=xCAT::Table->new('site')) && $retries < 200) +while (!($sitetab = xCAT::Table->new('site')) && $retries < 200) { - print ("Can not open basic site table for configuration, waiting the database to be initialized.\n"); + print("Can not open basic site table for configuration, waiting the database to be initialized.\n"); sleep 1; $retries++; } unless ($sitetab) { - xCAT::MsgUtils->message("S","ERROR: Unable to open basic site table for configuration"); + xCAT::MsgUtils->message("S", "ERROR: Unable to open basic site table for configuration"); die; } -my ($tmp) = $sitetab->getAttribs({'key'=>'xcatdport'},'value'); +my ($tmp) = $sitetab->getAttribs({ 'key' => 'xcatdport' }, 'value'); unless ($tmp) { - xCAT::MsgUtils->message("S","ERROR:Need xcatdport defined in site table, try chtab key=xcatdport site.value=3001"); + xCAT::MsgUtils->message("S", "ERROR:Need xcatdport defined in site table, try chtab key=xcatdport site.value=3001"); die; } $port = $tmp->{value}; -($tmp) = $sitetab->getAttribs({'key'=>'xcatiport'},'value'); +($tmp) = $sitetab->getAttribs({ 'key' => 'xcatiport' }, 'value'); if ($tmp) { $sport = $tmp->{value}; } -($tmp) = $sitetab->getAttribs({'key'=>'xcatmaxconnections'},'value'); +($tmp) = $sitetab->getAttribs({ 'key' => 'xcatmaxconnections' }, 'value'); if ($tmp and $tmp->{value}) { $maxsslclients = $tmp->{value}; } -($tmp) = $sitetab->getAttribs({'key'=>'xcatmaxbatchconnections'},'value'); +($tmp) = $sitetab->getAttribs({ 'key' => 'xcatmaxbatchconnections' }, 'value'); if ($tmp and $tmp->{value}) { $batchclients = $tmp->{value}; } -my $plugins_dir=$::XCATROOT.'/lib/perl/xCAT_plugin'; -($tmp) = $sitetab->getAttribs({'key'=>'xcatconfdir'},'value'); +my $plugins_dir = $::XCATROOT . '/lib/perl/xCAT_plugin'; +($tmp) = $sitetab->getAttribs({ 'key' => 'xcatconfdir' }, 'value'); $xcatdir = (($tmp and $tmp->{value}) ? $tmp->{value} : "/etc/xcat"); # ----used for command log start------- -my $cmdlog_logfile="/var/log/xcat/commands.log"; -my $cmdlog_port=3003; -($tmp) = $sitetab->getAttribs({'key'=>'xcatlport'},'value'); +my $cmdlog_logfile = "/var/log/xcat/commands.log"; +my $cmdlog_port = 3003; +($tmp) = $sitetab->getAttribs({ 'key' => 'xcatlport' }, 'value'); if ($tmp) { $cmdlog_port = $tmp->{value}; } -my $cmdlog_alllog="====================================================\n"; +my $cmdlog_alllog = "====================================================\n"; + # ----used for command log end--------- $sitetab->close; @@ -229,29 +237,33 @@ $progname = \$0; # /opt/xcat/lib/perl/xCAT_schema if (xCAT::Utils->isMN()) { + # update schema for xCAT tables my @table; - push @table,xCAT::Table->getTableList(); - foreach my $tablename (@table) { - my $tablelisttab=xCAT::Table->new($tablename,-create=>1); - my $rc= $tablelisttab->updateschema(); + push @table, xCAT::Table->getTableList(); + foreach my $tablename (@table) { + my $tablelisttab = xCAT::Table->new($tablename, -create => 1); + my $rc = $tablelisttab->updateschema(); $tablelisttab->close; } + # update schema for user tables xCAT::ExtTab->updateTables(); + # run any sql commands `$::XCATROOT/sbin/runsqlcmd`; } my $startupchild; my $startupparent; + sub daemonize { chdir('/'); umask 0022; my $pid; - socketpair($startupparent,$startupchild,AF_UNIX,SOCK_STREAM,PF_UNSPEC); - if (! defined($pid = xCAT::Utils->xfork)) { - xCAT::MsgUtils->message("S","Can't fork: $!"); + socketpair($startupparent, $startupchild, AF_UNIX, SOCK_STREAM, PF_UNSPEC); + if (!defined($pid = xCAT::Utils->xfork)) { + xCAT::MsgUtils->message("S", "Can't fork: $!"); die; } if ($pid) { @@ -259,30 +271,30 @@ sub daemonize { if ($pidfile) { open(PFILE, '>', $pidfile); print PFILE $pid; - close (PFILE); + close(PFILE); } else { - xCAT::MsgUtils->message("S","xcatd starting as PID $pid"); + xCAT::MsgUtils->message("S", "xcatd starting as PID $pid"); } - my $result=<$startupchild>; + my $result = <$startupchild>; chomp($result); - unless ($result) { exit (1); } + unless ($result) { exit(1); } if ($result ne "SUCCESS") { - xCAT::MsgUtils->message("S","xcatd failed to start: $result"); + xCAT::MsgUtils->message("S", "xcatd failed to start: $result"); exit(1); } exit; } - close($startupchild); # only want child to report up to parent... - if (! open STDIN, '/dev/null') { + close($startupchild); # only want child to report up to parent... + if (!open STDIN, '/dev/null') { print $startupparent "Can't read /dev/null: $!\n"; die; } open STDOUT, '>/dev/null'; open STDERR, '>/dev/null'; - $0='xcatd'; + $0 = 'xcatd'; $progname = \$0; - if (! setsid) { - xCAT::MsgUtils->message("S","Can't start new session"); + if (!setsid) { + xCAT::MsgUtils->message("S", "Can't start new session"); print $startupparent "Can't start new session\n"; die; } @@ -293,66 +305,69 @@ my $rescanreadpipe; my $rescanwritepipe; my $rescanrselect; my $rescanrequest = "rescanplugins"; + sub do_installm_service { unless ($sport) { return; } + # This function servers as a handler for messages from installing nodes my $socket; my $installpidfile; - my $retry=1; + my $retry = 1; $SIG{USR2} = sub { if ($socket) { # do not mess with pid file except when we still have the socket. - unlink("/var/run/xcat/installservice.pid"); close($socket); $quit=1; - $udpctl=0; - xCAT::MsgUtils->message("S","xcatd install monitor $$ quiescing"); + unlink("/var/run/xcat/installservice.pid"); close($socket); $quit = 1; + $udpctl = 0; + xCAT::MsgUtils->message("S", "xcatd install monitor $$ quiescing"); } }; if ($inet6support) { - $socket = IO::Socket::INET6->new(LocalPort=>$sport, - Proto => 'tcp', - ReuseAddr => 1, - Listen => 8192); + $socket = IO::Socket::INET6->new(LocalPort => $sport, + Proto => 'tcp', + ReuseAddr => 1, + Listen => 8192); } else { - $socket = IO::Socket::INET->new(LocalPort=>$sport, - Proto => 'tcp', - ReuseAddr => 1, - Listen => 8192); + $socket = IO::Socket::INET->new(LocalPort => $sport, + Proto => 'tcp', + ReuseAddr => 1, + Listen => 8192); } - if (not $socket and open($installpidfile,"<","/var/run/xcat/installservice.pid")) { # if we couldn't get the socket, go to pid to figure out current owner - # TODO: lsof or similar may be a more accurate measure + if (not $socket and open($installpidfile, "<", "/var/run/xcat/installservice.pid")) { # if we couldn't get the socket, go to pid to figure out current owner + # TODO: lsof or similar may be a more accurate measure my $pid = <$installpidfile>; if ($pid) { - $retry=100; # grace period for old instance to get out of the way, 5 seconds - kill 'USR2',$pid; - yield(); # let peer have a shot at closure + $retry = 100; # grace period for old instance to get out of the way, 5 seconds + kill 'USR2', $pid; + yield(); # let peer have a shot at closure } close($installpidfile); } while (not $socket and $retry) { $retry--; if ($inet6support) { - $socket = IO::Socket::INET6->new(LocalPort=>$sport, - Proto => 'tcp', - ReuseAddr => 1, - Listen => 8192); + $socket = IO::Socket::INET6->new(LocalPort => $sport, + Proto => 'tcp', + ReuseAddr => 1, + Listen => 8192); } else { - $socket = IO::Socket::INET->new(LocalPort=>$sport, - Proto => 'tcp', - ReuseAddr => 1, - Listen => 8192); + $socket = IO::Socket::INET->new(LocalPort => $sport, + Proto => 'tcp', + ReuseAddr => 1, + Listen => 8192); } - sleep 0.05; # up to 50 ms outage possible + sleep 0.05; # up to 50 ms outage possible } unless ($socket) { - xCAT::MsgUtils->message("S","xcatd unable to open install monitor services on $sport"); + xCAT::MsgUtils->message("S", "xcatd unable to open install monitor services on $sport"); die; } + # we have the socket, now we claim the pid file as our own - open($installpidfile,">","/var/run/xcat/installservice.pid"); # if here, everyone else has unlinked installservicepid or doesn't care + open($installpidfile, ">", "/var/run/xcat/installservice.pid"); # if here, everyone else has unlinked installservicepid or doesn't care print $installpidfile $$; close($installpidfile); until ($quit) { - $SIG{ALRM} = sub { xCAT::MsgUtils->message("S","XCATTIMEOUT"); die; }; + $SIG{ALRM} = sub { xCAT::MsgUtils->message("S", "XCATTIMEOUT"); die; }; my $conn; next unless $conn = $socket->accept; @@ -362,7 +377,7 @@ sub do_installm_service { foreach my $rrequest (@rescans) { my $rescan_request = fd_retrieve($rrequest); if ($$rescan_request =~ /rescanplugins/) { - scan_plugins('','1'); + scan_plugins('', '1'); } else { print "ignoring unrecognized pipe request received by install monitor from ssl listener: $rescan_request \n"; } @@ -373,29 +388,29 @@ sub do_installm_service { my $client_aliases; my @clients; if ($inet6support) { - ($client_name,$client_aliases) = gethostbyaddr($conn->peeraddr,AF_INET6); - unless ($client_name) { ($client_name,$client_aliases) = gethostbyaddr($conn->peeraddr,AF_INET); } + ($client_name, $client_aliases) = gethostbyaddr($conn->peeraddr, AF_INET6); + unless ($client_name) { ($client_name, $client_aliases) = gethostbyaddr($conn->peeraddr, AF_INET); } } else { - ($client_name,$client_aliases) = gethostbyaddr($conn->peeraddr,AF_INET); + ($client_name, $client_aliases) = gethostbyaddr($conn->peeraddr, AF_INET); } unless ($client_name) { my $myaddr = inet_ntoa($conn->peeraddr); - xCAT::MsgUtils->message("S","xcatd received a connection request from unknown host with ip address $myaddr, please check whether the reverse name resolution works correctly. The connection request will be ignored"); + xCAT::MsgUtils->message("S", "xcatd received a connection request from unknown host with ip address $myaddr, please check whether the reverse name resolution works correctly. The connection request will be ignored"); print "xcatd received a connection request from unknown host with ip address $myaddr, please check whether the reverse name resolution works correctly. The connection request will be ignored\n"; } $clients[0] = $client_name; if ($client_aliases) { - push @clients, split(/\s+/,$client_aliases); + push @clients, split(/\s+/, $client_aliases); } - my $validclient=0; + my $validclient = 0; my $node; my $domain; foreach my $client (@clients) { - my @ndn = ($client); - my $nd = xCAT::NetworkUtils->getNodeDomains(\@ndn); + my @ndn = ($client); + my $nd = xCAT::NetworkUtils->getNodeDomains(\@ndn); my %nodedomains = %{$nd}; $domain = $nodedomains{$client}; $client =~ s/\..*//; @@ -404,16 +419,17 @@ sub do_installm_service { } else { $client =~ s/\..*//; } + # ensure this is coming from a node IP at least ($node) = noderange($client); - if ($node) { # Means the source isn't valid - $validclient=1; + if ($node) { # Means the source isn't valid + $validclient = 1; last; } else { - xCAT::MsgUtils->message("S","xcatd received a connection request from $client, which can not be found in xCAT nodelist table. The connection request will be ignored"); + xCAT::MsgUtils->message("S", "xcatd received a connection request from $client, which can not be found in xCAT nodelist table. The connection request will be ignored"); print "xcatd received a connection request from $client, which can not be found in xCAT nodelist table. The connection request will be ignored\n"; } - + } unless ($validclient) { @@ -430,51 +446,55 @@ sub do_installm_service { $text =~ s/\r//g; if ($text =~ /next/) { my %request = ( - command => [ 'nodeset' ], - node => [ $node ], - arg => [ 'next' ], - ); + command => ['nodeset'], + node => [$node], + arg => ['next'], + ); + # node should be blocked, race condition may occur otherwise #my $pid=xCAT::Utils->xfork(); #unless ($pid) { # fork off the nodeset and potential slowness - plugin_command(\%request,undef,\&build_response); + plugin_command(\%request, undef, \&build_response); + #exit(0); #} close($conn); } elsif ($text =~ /installstatus/) { - my @tmpa=split(' ', $text); - for (my $i = 1; $i <= @tmpa-1; $i++) { - my $newstat=$tmpa[$i]; + my @tmpa = split(' ', $text); + for (my $i = 1 ; $i <= @tmpa - 1 ; $i++) { + my $newstat = $tmpa[$i]; my %request = ( - command => [ 'updatenodestat' ], - node => [ $node ], - arg => [ "$newstat" ], - ); + command => ['updatenodestat'], + node => [$node], + arg => ["$newstat"], + ); + # node should be blocked, race condition may occur otherwise #my $pid=xCAT::Utils->xfork(); #unless ($pid) { # fork off the nodeset and potential slowness - plugin_command(\%request,undef,\&build_response); + plugin_command(\%request, undef, \&build_response); + #exit(0); #} } close($conn); } elsif ($text =~ /^unlocktftpdir/) { # TODO: only nodes in install state should be allowed mkpath("$tftpdir/xcat/$node"); - chmod 01777,"$tftpdir/xcat/$node"; - chmod 0666,glob("$tftpdir/xcat/$node/*"); + chmod 01777, "$tftpdir/xcat/$node"; + chmod 0666, glob("$tftpdir/xcat/$node/*"); close($conn); } elsif ($text =~ /locktftpdir/) { - chmod 0755,"$tftpdir/xcat/$node"; - chmod 0644,glob("$tftpdir/xcat/$node/*"); + chmod 0755, "$tftpdir/xcat/$node"; + chmod 0644, glob("$tftpdir/xcat/$node/*"); } elsif ($text =~ /^getpostscript/) { - my $reply =plugin_command({command=>['getpostscript'],_xcat_clienthost=>[$node]},undef,\&build_response); - foreach (@{$reply->{data}}) { + my $reply = plugin_command({ command => ['getpostscript'], _xcat_clienthost => [$node] }, undef, \&build_response); + foreach (@{ $reply->{data} }) { print $conn $_; } print $conn "#END OF SCRIPT\n"; close($conn); } elsif ($text =~ /^syncfiles/) { - plugin_command({command=>['syncfiles'],_xcat_clienthost=>[$node]},undef,\&build_response); + plugin_command({ command => ['syncfiles'], _xcat_clienthost => [$node] }, undef, \&build_response); print $conn "syncfiles done\n"; close($conn); } elsif ($text =~ /^setiscsiparms/) { @@ -482,46 +502,47 @@ sub do_installm_service { my $kname; my $iname; my $kcmdline; - ($kname,$iname,$kcmdline) = split(/\s+/,$text,3); + ($kname, $iname, $kcmdline) = split(/\s+/, $text, 3); chomp($kcmdline); - my $bptab = xCAT::Table->new('bootparams',-create=>1); - $bptab->setNodeAttribs($node,{kernel=>"xcat/$node/$kname",initrd=>"xcat/$node/$iname",kcmdline=>$kcmdline}); - my $iscsitab = xCAT::Table->new('iscsi',-create=>1); - $iscsitab->setNodeAttribs($node,{kernel=>"xcat/$node/$kname",initrd=>"xcat/$node/$iname",kcmdline=>$kcmdline}); - my $chaintab = xCAT::Table->new('chain',-create=>1); - $chaintab->setNodeAttribs($node,{currstate=>'iscsiboot',currchain=>'netboot'}); + my $bptab = xCAT::Table->new('bootparams', -create => 1); + $bptab->setNodeAttribs($node, { kernel => "xcat/$node/$kname", initrd => "xcat/$node/$iname", kcmdline => $kcmdline }); + my $iscsitab = xCAT::Table->new('iscsi', -create => 1); + $iscsitab->setNodeAttribs($node, { kernel => "xcat/$node/$kname", initrd => "xcat/$node/$iname", kcmdline => $kcmdline }); + my $chaintab = xCAT::Table->new('chain', -create => 1); + $chaintab->setNodeAttribs($node, { currstate => 'iscsiboot', currchain => 'netboot' }); $bptab->close; $chaintab->close; undef $bptab; undef $chaintab; my %request = ( - command => [ 'nodeset' ], - node => [ $node ], - arg => [ 'enact' ], - ); - my $pid=xCAT::Utils->xfork(); + command => ['nodeset'], + node => [$node], + arg => ['enact'], + ); + my $pid = xCAT::Utils->xfork(); unless ($pid) { # fork off the nodeset and potential slowness - plugin_command(\%request,undef,\&build_response); + plugin_command(\%request, undef, \&build_response); xexit(0); } } elsif ($text =~ /hpcbootstatus/) { $text =~ s/hpcbootstatus //; chomp $text; my %request = ( - command => [ 'updatenodeappstat' ], - node => [ $node ], - arg => [ "$text" ], - ); + command => ['updatenodeappstat'], + node => [$node], + arg => ["$text"], + ); - plugin_command(\%request,undef,\&build_response); + plugin_command(\%request, undef, \&build_response); close($conn); } elsif ($text =~ /basecustremv/) { $text =~ s/basecustremv //; chomp $text; + # remove the BASECUST_REMOVAL line from /tftpboot/hostname.info file my $myfile = "/tftpboot/$text" . ".info"; - `/usr/bin/cat $myfile | /usr/bin/sed "/BASECUST_REMOVAL/d">/tmp/$text.nimtmp`; +`/usr/bin/cat $myfile | /usr/bin/sed "/BASECUST_REMOVAL/d">/tmp/$text.nimtmp`; `/usr/bin/mv /tmp/$text.nimtmp $myfile`; close($conn); } @@ -531,13 +552,13 @@ sub do_installm_service { }; if ($@) { if ($@ =~ /XCATTIMEOUT/) { - xCAT::MsgUtils->message("S","xcatd installmonitor timed out talking to $node"); + xCAT::MsgUtils->message("S", "xcatd installmonitor timed out talking to $node"); } else { - xCAT::MsgUtils->message("S","xcatd: possible BUG encountered by xCAT install monitor service: ".$@); + xCAT::MsgUtils->message("S", "xcatd: possible BUG encountered by xCAT install monitor service: " . $@); } } } - if (open($installpidfile,"<","/var/run/xcat/installservice.pid")) { + if (open($installpidfile, "<", "/var/run/xcat/installservice.pid")) { my $pid = <$installpidfile>; if ($pid == $$) { # if our pid, unlink the file, otherwise, we managed to see the pid after someone else created it unlink("/var/run/xcat/installservice.pid"); @@ -548,50 +569,52 @@ sub do_installm_service { sub grant_tcrequests { - my $requestors = shift; - my $udpcontext = shift; + my $requestors = shift; + my $udpcontext = shift; my $availableslots = $batchclients; if (not keys %{$requestors}) { return; } # skip the interaction with SSL if - # no requests are actually pending - my $oldtime = time()-180; # drop requests older than three minutes if still around + # no requests are actually pending + my $oldtime = time() - 180; # drop requests older than three minutes if still around my $msg; - eval { store_fd({'req'=>'get_client_count'}, $sslctl); $msg = fd_retrieve($sslctl); }; - if (not $msg) { + eval { store_fd({ 'req' => 'get_client_count' }, $sslctl); $msg = fd_retrieve($sslctl); }; + + if (not $msg) { return; } - $availableslots -= $msg->{clientfudge}; # value that forecasts the pressure + $availableslots -= $msg->{clientfudge}; # value that forecasts the pressure $availableslots -= $msg->{sslclientcount}; # subtract all currently really active sessions my $fudgefactor = $msg->{clientfudge}; foreach my $rkey (keys %{$requestors}) { if ($requestors->{$rkey}->{timestamp} < $oldtime) { delete $requestors->{$rkey}; next; } unless ($availableslots > 0) { next; } # no slots, ignore requests for now - $fudgefactor += 1; # adjust forecast for being busy - $availableslots-=1; - $udpcontext->{socket}->send("resourcerequest: ok\n",0,$requestors->{$rkey}->{sockaddr}); - delete ($requestors->{$rkey}); # we acknoweldged, assume consumer got it, they'll do retry if they failed + $fudgefactor += 1; # adjust forecast for being busy + $availableslots -= 1; + $udpcontext->{socket}->send("resourcerequest: ok\n", 0, $requestors->{$rkey}->{sockaddr}); + delete($requestors->{$rkey}); # we acknoweldged, assume consumer got it, they'll do retry if they failed } - eval { store_fd({'req'=>'set_fudge_factor', 'fudge'=>$fudgefactor}, $sslctl); $msg = fd_retrieve($sslctl); }; + eval { store_fd({ 'req' => 'set_fudge_factor', 'fudge' => $fudgefactor }, $sslctl); $msg = fd_retrieve($sslctl); }; } sub do_discovery_process { $SIG{TERM} = 'DEFAULT'; - $SIG{INT} = 'DEFAULT'; - my %args =@_; - my $broker = $args{broker}; - my $quit=0; + $SIG{INT} = 'DEFAULT'; + my %args = @_; + my $broker = $args{broker}; + my $quit = 0; my $vintage = time(); - $dispatch_requests=0; + $dispatch_requests = 0; populate_site_hash(); populate_vpd_hash(); populate_mp_hash(); + while (not $quit) { my $msg = fd_retrieve($broker); - if ((time()-$vintage)> 15) { + if ((time() - $vintage) > 15) { populate_site_hash(); populate_vpd_hash(); populate_mp_hash(); $vintage = time(); - } # site table reread every 15 second + } # site table reread every 15 second my $data; my $client; my $clientn; @@ -599,8 +622,8 @@ sub do_discovery_process { if (ref $msg eq 'HASH') { $data = $msg->{data}; } else { die "incorrect code to disco"; } my $saddr = $msg->{sockaddr}; if ($inet6support) { - ($client,$sport) = Socket6::getnameinfo($saddr); - ($clientip,$sport) = Socket6::getnameinfo($saddr,Socket6::NI_NUMERICHOST()); + ($client, $sport) = Socket6::getnameinfo($saddr); + ($clientip, $sport) = Socket6::getnameinfo($saddr, Socket6::NI_NUMERICHOST()); if ($clientip =~ /::ffff:.*\..*\./) { $clientip =~ s/^::ffff://; } @@ -608,77 +631,82 @@ sub do_discovery_process { $client =~ s/^::ffff://; } } else { - ($sport,$clientn) = sockaddr_in($saddr); + ($sport, $clientn) = sockaddr_in($saddr); $clientip = inet_ntoa($clientn); - $client=gethostbyaddr($clientn,AF_INET); + $client = gethostbyaddr($clientn, AF_INET); } - if ($data =~ /^\037\213/) { # per rfc 1952, these two bytes are gzip, and they are invalid for - # xcatrequest xml, so go ahead and decompress it + if ($data =~ /^\037\213/) { # per rfc 1952, these two bytes are gzip, and they are invalid for + # xcatrequest xml, so go ahead and decompress it my $bigdata; - IO::Uncompress::Gunzip::gunzip(\$data,\$bigdata); + IO::Uncompress::Gunzip::gunzip(\$data, \$bigdata); $data = $bigdata; } - my $req = eval { XMLin($data, SuppressEmpty=>undef,ForceArray=>1) }; + my $req = eval { XMLin($data, SuppressEmpty => undef, ForceArray => 1) }; if ($req and $req->{command} and ($req->{command}->[0] eq "findme" and $sport < 1000)) { # only consider priveleged port requests to start with - $req->{'_xcat_clienthost'}=$client; - $req->{'_xcat_clientip'}=$clientip; - $req->{'_xcat_clientport'}=$sport; + $req->{'_xcat_clienthost'} = $client; + $req->{'_xcat_clientip'} = $clientip; + $req->{'_xcat_clientport'} = $sport; if (defined($cmd_handlers{"findme"}) and xCAT::NetworkUtils->nodeonmynet($clientip)) { # only discover from ips that appear to be on a managed network - xCAT::MsgUtils->message("S","xcatd: Processing discovery request from ".$req->{'_xcat_clientip'}); + xCAT::MsgUtils->message("S", "xcatd: Processing discovery request from " . $req->{'_xcat_clientip'}); + # Using cacheonly will cause the discovery processing running 2 times, cacheonly seems useless for switch.pm, so remove it #$req->{cacheonly}->[0] = 1; #plugin_command($req,undef,\&build_response); #if ($req->{cacheonly}->[0]) { #delete $req->{cacheonly}; - plugin_command($req,undef,\&build_response); + plugin_command($req, undef, \&build_response); + #} } else { - xCAT::MsgUtils->message("S","xcatd: Skipping discovery from ".$client." because we either have no discovery plugins or the client address does not match an IP network that xCAT is managing"); + xCAT::MsgUtils->message("S", "xcatd: Skipping discovery from " . $client . " because we either have no discovery plugins or the client address does not match an IP network that xCAT is managing"); } } } } -sub do_udp_service { # This function opens up a UDP port - # It will do similar to the standard service, except: - # -Obviously, unencrypted and messages are not guaranteed - # -For that reason, more often than not plugins designed with - # -this method will not expect to have a callback - # Also, this throttles to handle one message at a time, so no forking either - # Explicitly, to handle whatever operations nodes periodically send during discover state - # Could be used for heartbeating and such as desired - my %args=@_; + +sub do_udp_service { # This function opens up a UDP port + # It will do similar to the standard service, except: + # -Obviously, unencrypted and messages are not guaranteed + # -For that reason, more often than not plugins designed with + # -this method will not expect to have a callback + # Also, this throttles to handle one message at a time, so no forking either + # Explicitly, to handle whatever operations nodes periodically send during discover state + # Could be used for heartbeating and such as desired + my %args = @_; my $discoctl = $args{discoctl}; - $dispatch_requests=0; + $dispatch_requests = 0; my $udpcontext; - $udpcontext->{sslclientcount}=0; + $udpcontext->{sslclientcount} = 0; my $udppidfile; - my $retry=1; + my $retry = 1; my $socket; my $discopid = $args{discopid}; $SIG{USR2} = sub { + if ($socket) { + # only clear out pid file when we still have socket. - unlink("/var/run/xcat/udpservice.pid"); close($socket); $quit=1; $socket=0; - $udpctl=0; - xCAT::MsgUtils->message("S","xcatd udp service $$ quiescing"); + unlink("/var/run/xcat/udpservice.pid"); close($socket); $quit = 1; $socket = 0; + $udpctl = 0; + xCAT::MsgUtils->message("S", "xcatd udp service $$ quiescing"); } - kill('TERM',$discopid); + kill('TERM', $discopid); }; if ($inet6support) { $socket = IO::Socket::INET6->new(LocalPort => $port, - Proto => 'udp', - ); + Proto => 'udp', + ); } else { $socket = IO::Socket::INET->new(LocalPort => $port, - Proto => 'udp', + Proto => 'udp', Domain => AF_INET); } - if (not $socket and open($udppidfile,"<","/var/run/xcat/udpservice.pid")) { + if (not $socket and open($udppidfile, "<", "/var/run/xcat/udpservice.pid")) { my $pid = <$udppidfile>; if ($pid) { - $retry=100; # grace period for old instance to get out of the way, 5 seconds - kill 'USR2',$pid; - yield(); # let peer have a shot at closure + $retry = 100; # grace period for old instance to get out of the way, 5 seconds + kill 'USR2', $pid; + yield(); # let peer have a shot at closure } close($udppidfile); } @@ -687,24 +715,25 @@ sub do_udp_service { # This function opens up a UDP port $retry--; if ($inet6support) { $socket = IO::Socket::INET6->new(LocalPort => $port, - Proto => 'udp', - ); + Proto => 'udp', + ); } else { $socket = IO::Socket::INET->new(LocalPort => $port, - Proto => 'udp', + Proto => 'udp', Domain => AF_INET); } sleep 0.05; } - openlog("xcat",'','local4'); + openlog("xcat", '', 'local4'); unless ($socket) { - xCAT::MsgUtils->message("S","xCAT UDP service unable to open port $port: $!"); + xCAT::MsgUtils->message("S", "xCAT UDP service unable to open port $port: $!"); closelog(); die "Unable to start UDP on $port"; } + # only take udp pid if we get the socket - open($udppidfile,">","/var/run/xcat/udpservice.pid"); # if here, everyone else has unlinked udpservicepid or doesn't care + open($udppidfile, ">", "/var/run/xcat/udpservice.pid"); # if here, everyone else has unlinked udpservicepid or doesn't care print $udppidfile $$; close($udppidfile); $select->add($socket); @@ -717,17 +746,18 @@ sub do_udp_service { # This function opens up a UDP port my $client; my $peerhost; my %packets; - my $actualpid=$$; + my $actualpid = $$; + until ($quit) { eval { - my $tcclients; # hash reference to store traffic control requests + my $tcclients; # hash reference to store traffic control requests while (1) { unless ($actualpid == $$) { # This really should be impossible now... - xCAT::MsgUtils->message("S","xcatd: Something absolutely ludicrous happpened, xCAT developers think this message is impossible to see, post if you see it, fork bomb averted"); + xCAT::MsgUtils->message("S", "xcatd: Something absolutely ludicrous happpened, xCAT developers think this message is impossible to see, post if you see it, fork bomb averted"); exit(1); } - until ($select->can_read(5)) { # Wait for data - if ($quit) { last; }; + until ($select->can_read(5)) { # Wait for data + if ($quit) { last; } populate_site_hash(); yield; } @@ -736,12 +766,13 @@ sub do_udp_service { # This function opens up a UDP port my $hdl; foreach $hdl (@hdls) { if ($hdl == $socket) { - $part = $socket->recv($data,2000); - $packets{$part} = [$part,$data]; + $part = $socket->recv($data, 2000); + $packets{$part} = [ $part, $data ]; } elsif ($hdl == $sslctl) { next; + #update_udpcontext_from_sslctl(udpcontext=>$udpcontext,select=>$select); - } elsif ($hdl == $discoctl) { # got a discovery response.... + } elsif ($hdl == $discoctl) { # got a discovery response.... } else { print "Something is wrong in udp process (search xcatd for this string)\n"; } @@ -749,44 +780,46 @@ sub do_udp_service { # This function opens up a UDP port } foreach my $pkey (keys %packets) { my $saddr = $packets{$pkey}->[0]; - $data=$packets{$pkey}->[1]; - if ($data =~ /^\037\213/) { # per rfc 1952, these two bytes are gzip, and they are invalid for - store_fd({data=>$data,sockaddr=>$saddr},$discoctl); # for now, punt the gunzip to the worker process - } elsif ($data =~ /^$data,sockaddr=>$saddr},$discoctl); - } else { # for *now*, we'll do a tiny YAML subset + $data = $packets{$pkey}->[1]; + if ($data =~ /^\037\213/) { # per rfc 1952, these two bytes are gzip, and they are invalid for + store_fd({ data => $data, sockaddr => $saddr }, $discoctl); # for now, punt the gunzip to the worker process + } elsif ($data =~ /^ $data, sockaddr => $saddr }, $discoctl); + } else { # for *now*, we'll do a tiny YAML subset if ($data =~ /^resourcerequest: xcatd$/) { - $socket->send("ackresourcerequest\n",0,$packets{$pkey}->[0]); - $tcclients->{$pkey}={ sockaddr=>$packets{$pkey}->[0], timestamp=>time() } + $socket->send("ackresourcerequest\n", 0, $packets{$pkey}->[0]); + $tcclients->{$pkey} = { sockaddr => $packets{$pkey}->[0], timestamp => time() } } - } # JSON maybe one day if important + } # JSON maybe one day if important if ($quit) { last; } while (@hdls = $select->can_read(0)) { # grab any incoming requests during run foreach my $hdl (@hdls) { if ($hdl == $socket) { - $part = $socket->recv($data,1500); - $packets{$part} = [$part,$data]; + $part = $socket->recv($data, 1500); + $packets{$part} = [ $part, $data ]; + #} elsif ($hdl == $sslctl) { # update_udpcontext_from_sslctl(udpcontext=>$udpcontext,select=>$select); } } } + # Some of those 'future' packets might be stale dupes of this packet, so... delete $packets{$pkey}; # Delete any duplicates of current packet } if ($quit) { last; } - grant_tcrequests($tcclients,$udpcontext); + grant_tcrequests($tcclients, $udpcontext); } }; if ($@) { - xCAT::MsgUtils->message("S","xcatd: possible BUG encountered by xCAT UDP service: ".$@); + xCAT::MsgUtils->message("S", "xcatd: possible BUG encountered by xCAT UDP service: " . $@); } unless ($actualpid == $$) { # We should absolutely never be here, exponential growth from a plugin crash. - xCAT::MsgUtils->message("S","xcatd: Something ludicrous happpened, bailing to avoid fork bomb, double check perl XS modules like 'net-snmp-perl'"); + xCAT::MsgUtils->message("S", "xcatd: Something ludicrous happpened, bailing to avoid fork bomb, double check perl XS modules like 'net-snmp-perl'"); exit 1; } } - if (open($udppidfile,"<","/var/run/xcat/udpservice.pid")) { + if (open($udppidfile, "<", "/var/run/xcat/udpservice.pid")) { my $pid = <$udppidfile>; if ($pid == $$) { # if our pid, unlink the file, otherwise, we managed to see the pid after someone else created it unlink("/var/run/xcat/udpservice.pid"); @@ -799,69 +832,70 @@ sub do_udp_service { # This function opens up a UDP port sub scan_plugins { my $serialdest = shift; - my $rescan = shift; - %cmd_handlers=(); - my @plugins=glob($plugins_dir."/*.pm"); + my $rescan = shift; + %cmd_handlers = (); + my @plugins = glob($plugins_dir . "/*.pm"); foreach (@plugins) { /.*\/([^\/]*).pm$/; my $modname = $1; - unless ( eval { require "$_" }) { - xCAT::MsgUtils->message("S","Error loading module ".$_." ...skipping"); + unless (eval { require "$_" }) { + xCAT::MsgUtils->message("S", "Error loading module " . $_ . " ...skipping"); next; } no strict 'refs'; my $cmd_adds; eval { - $cmd_adds=${"xCAT_plugin::".$modname."::"}{handled_commands}->(); + $cmd_adds = ${ "xCAT_plugin::" . $modname . "::" }{handled_commands}->(); }; if ($@) { - xCAT::MsgUtils->message("S","Error registering module ".$_." ...skipping"); + xCAT::MsgUtils->message("S", "Error registering module " . $_ . " ...skipping"); next; } foreach (keys %$cmd_adds) { my $value = $_; my @modulehandlerinfos; if (ref $cmd_adds->{$_}) { - @modulehandlerinfos=@{$cmd_adds->{$value}}; + @modulehandlerinfos = @{ $cmd_adds->{$value} }; } else { - @modulehandlerinfos=($cmd_adds->{$value}); + @modulehandlerinfos = ($cmd_adds->{$value}); } unless (defined($cmd_handlers{$value})) { - $cmd_handlers{$value} = [ ]; + $cmd_handlers{$value} = []; } + # Add every plugin registration to cmd_handlers foreach (@modulehandlerinfos) { - push @{$cmd_handlers{$value}},[$modname,$_]; + push @{ $cmd_handlers{$value} }, [ $modname, $_ ]; } } } - if ( ! $rescan ) { + if (!$rescan) { foreach (@plugins) { no strict 'refs'; /.*\/([^\/]*).pm$/; my $modname = $1; - unless (defined(${"xCAT_plugin::".$modname."::"}{init_plugin})) { + unless (defined(${ "xCAT_plugin::" . $modname . "::" }{init_plugin})) { next; } - ${"xCAT_plugin::".$modname."::"}{init_plugin}->(\&do_request); + ${ "xCAT_plugin::" . $modname . "::" }{init_plugin}->(\&do_request); } } - if ($serialdest) { store_fd(\%cmd_handlers,$serialdest); }; #print $serialdest freeze(\%cmd_handlers); }; + if ($serialdest) { store_fd(\%cmd_handlers, $serialdest); }; #print $serialdest freeze(\%cmd_handlers); }; } my $pid_init; my $readpipe; my $writepipe; -if (socketpair($readpipe, $writepipe,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) { +if (socketpair($readpipe, $writepipe, AF_UNIX, SOCK_STREAM, PF_UNSPEC)) { $pid_init = xCAT::Utils->xfork; } else { xCAT::MsgUtils->message("S", "socketpair failed: $!"); } if (defined $pid_init) { - if ($pid_init) { # parent, just sit and wait.. + if ($pid_init) { # parent, just sit and wait.. close($writepipe); - %cmd_handlers = %{fd_retrieve($readpipe)}; + %cmd_handlers = %{ fd_retrieve($readpipe) }; } else { $$progname = "xcatd: plugin initialization"; scan_plugins($writepipe); @@ -873,9 +907,9 @@ if (defined $pid_init) { } -unless (xCAT::Utils->isLinux()) { # messes up the output of the service cmd on linux +unless (xCAT::Utils->isLinux()) { # messes up the output of the service cmd on linux eval { - xCAT::MsgUtils->message("S","xcatd: service starting"); + xCAT::MsgUtils->message("S", "xcatd: service starting"); }; } if ($@) { @@ -886,17 +920,20 @@ unless ($foreground) { daemonize; } -$dbmaster=xCAT::Table::init_dbworker; +$dbmaster = xCAT::Table::init_dbworker; + # Make sure DB process is ready. wait_db_process(); -my $CHILDPID=0; # Global for reapers +my $CHILDPID = 0; # Global for reapers my %immediatechildren; + sub generic_reaper { - local($!); - while (($CHILDPID=waitpid(-1,WNOHANG)) > 0) { + local ($!); + while (($CHILDPID = waitpid(-1, WNOHANG)) > 0) { if (($CHILDPID == $pid_UDP) && ($udpctl)) { + # got here because UDP child is gone - close($udpctl); $udpctl=0; + close($udpctl); $udpctl = 0; } yield; } @@ -904,17 +941,18 @@ sub generic_reaper { } sub ssl_reaper { - local($!); + local ($!); my $numdone = 0; - while (($CHILDPID=waitpid(-1,WNOHANG)) > 0) { + while (($CHILDPID = waitpid(-1, WNOHANG)) > 0) { if ($immediatechildren{$CHILDPID}) { delete $immediatechildren{$CHILDPID}; $sslclients--; $numdone--; } if (($CHILDPID == $pid_UDP) && ($udpctl)) { + # got here because UDP child is gone - close($udpctl); $udpctl=0; + close($udpctl); $udpctl = 0; $pid_UDP = 0; } if ($CHILDPID == $cmdlog_svrpid) { @@ -928,30 +966,32 @@ sub ssl_reaper { } sub dispatch_reaper { - local($!); - while (($CHILDPID =waitpid(-1, WNOHANG)) > 0) { + local ($!); + while (($CHILDPID = waitpid(-1, WNOHANG)) > 0) { if ($dispatched_children{$CHILDPID}) { delete $dispatched_children{$CHILDPID}; $dispatch_children--; } if (($CHILDPID == $pid_UDP) && ($udpctl)) { + # got here because UDP child is gone - close($udpctl); $udpctl=0; + close($udpctl); $udpctl = 0; } } $SIG{CHLD} = \&dispatch_reaper; } sub plugin_reaper { - local($!); + local ($!); while (($CHILDPID = waitpid(-1, WNOHANG)) > 0) { if ($plugin_children{$CHILDPID}) { delete $plugin_children{$CHILDPID}; $plugin_numchildren--; } if (($CHILDPID == $pid_UDP) && ($udpctl)) { + # got here because UDP child is gone - close($udpctl); $udpctl=0; + close($udpctl); $udpctl = 0; } } $SIG{CHLD} = \&plugin_reaper; @@ -960,6 +1000,7 @@ sub plugin_reaper { $SIG{CHLD} = \&generic_reaper; $SIG{TERM} = $SIG{INT} = sub { + #printf("Asked to quit...\n"); $quit++; foreach (keys %dispatched_children) { @@ -975,42 +1016,45 @@ $SIG{TERM} = $SIG{INT} = sub { kill 'USR2', $pid_MON; } xCAT::Table::shut_dbworker; + # ----used for command log start--------- - if ($cmdlog_svrpid){ + if ($cmdlog_svrpid) { kill 'INT', $cmdlog_svrpid; } + # ----used for command log end--------- }; -socketpair($sslctl, $udpctl,AF_UNIX,SOCK_STREAM,PF_UNSPEC); +socketpair($sslctl, $udpctl, AF_UNIX, SOCK_STREAM, PF_UNSPEC); my $prevfh = select($udpctl); -$|=1; +$| = 1; select($sslctl); -$|=1; +$| = 1; select($prevfh); $pid_UDP = xCAT::Utils->xfork; -if (! defined $pid_UDP) { +if (!defined $pid_UDP) { xCAT::MsgUtils->message("S", "Unable to fork for UDP/TCP"); die; } unless ($pid_UDP) { - close($udpctl); $udpctl=0; - $$progname="xcatd: UDP listener"; + close($udpctl); $udpctl = 0; + $$progname = "xcatd: UDP listener"; my $pid_disco; my $discoctl; my $udpbroker; - socketpair($discoctl,$udpbroker,AF_UNIX,SOCK_STREAM,PF_UNSPEC); + socketpair($discoctl, $udpbroker, AF_UNIX, SOCK_STREAM, PF_UNSPEC); $udpbroker->autoflush(1); $discoctl->autoflush(1); $pid_disco = xCAT::Utils->xfork; + if (!defined $pid_disco) { xCAT::MsgUtils->message("S", "Unable to fork for UDP/TCP"); die; } unless ($pid_disco) { # this is the child, therefore the discovery process.. close($discoctl); - $$progname="xcatd: Discovery worker"; - do_discovery_process(broker=>$udpbroker); + $$progname = "xcatd: Discovery worker"; + do_discovery_process(broker => $udpbroker); xexit(0); } close($udpbroker); @@ -1023,66 +1067,66 @@ unless ($pid_UDP) { alarm(2); }; - do_udp_service(discoctl=>$discoctl,discopid=>$pid_disco); + do_udp_service(discoctl => $discoctl, discopid => $pid_disco); xexit(0); } close($sslctl); # Set up communication pipe to have ssl listener tell install monitor to # rescanplugins -if ( !(socketpair($rescanreadpipe, $rescanwritepipe,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) ) { +if (!(socketpair($rescanreadpipe, $rescanwritepipe, AF_UNIX, SOCK_STREAM, PF_UNSPEC))) { xCAT::MsgUtils->message("S", "socketpair failed: $!"); } $rescanrselect = new IO::Select; $rescanrselect->add($rescanreadpipe); $pid_MON = xCAT::Utils->xfork; -if (! defined $pid_MON) { +if (!defined $pid_MON) { xCAT::MsgUtils->message("S", "Unable to fork installmonitor"); die; } unless ($pid_MON) { - $$progname="xcatd: install monitor"; - close($udpctl); $udpctl=0; + $$progname = "xcatd: install monitor"; + close($udpctl); $udpctl = 0; do_installm_service; xexit(0); } # ----used for command log start--------- $cmdlog_svrpid = xCAT::Utils->xfork; -if (! defined $cmdlog_svrpid) { +if (!defined $cmdlog_svrpid) { print "xCAT command log sever unable to fork"; - xCAT::MsgUtils->message("S","xCAT command log sever unable to fork"); + xCAT::MsgUtils->message("S", "xCAT command log sever unable to fork"); } -unless ($cmdlog_svrpid){ - $$progname="xcatd: Command log writer"; +unless ($cmdlog_svrpid) { + $$progname = "xcatd: Command log writer"; my $clientsock; my @waittowritepro; my $cmdlogsvrlistener; my $cmdlogfile; my $cmdlogpidfile; - my $retry=200; - my $writing=0; - my $cmdlogfileswitch=0; - my $cmdlogservicefile="/var/run/xcat/cmdlogservice.pid"; + my $retry = 200; + my $writing = 0; + my $cmdlogfileswitch = 0; + my $cmdlogservicefile = "/var/run/xcat/cmdlogservice.pid"; my $cmdlog_logfile_umask; $SIG{USR2} = sub { - while($writing){sleep(0.01);} - if($cmdlogfile){close($cmdlogfile);} - if($clientsock){close($clientsock);} - if( -e $cmdlogservicefile){ unlink("$cmdlogservicefile");} - if($cmdlogsvrlistener){close($cmdlogsvrlistener);} - xCAT::MsgUtils->message("S","INFO xcatd: 'Command log writer' process $$ is terminated by USR2 signal"); + while ($writing) { sleep(0.01); } + if ($cmdlogfile) { close($cmdlogfile); } + if ($clientsock) { close($clientsock); } + if (-e $cmdlogservicefile) { unlink("$cmdlogservicefile"); } + if ($cmdlogsvrlistener) { close($cmdlogsvrlistener); } + xCAT::MsgUtils->message("S", "INFO xcatd: 'Command log writer' process $$ is terminated by USR2 signal"); exit(0); }; $SIG{TERM} = $SIG{INT} = sub { - while($writing){sleep(0.01);} - if($cmdlogfile){close($cmdlogfile);} - if($clientsock){close($clientsock);} - if( -e $cmdlogservicefile){ unlink("$cmdlogservicefile");} - if($cmdlogsvrlistener){close($cmdlogsvrlistener);} - xCAT::MsgUtils->message("S","INFO xcatd: 'Command log writer' process $$ is terminated by TERM or INT signal"); + while ($writing) { sleep(0.01); } + if ($cmdlogfile) { close($cmdlogfile); } + if ($clientsock) { close($clientsock); } + if (-e $cmdlogservicefile) { unlink("$cmdlogservicefile"); } + if ($cmdlogsvrlistener) { close($cmdlogsvrlistener); } + xCAT::MsgUtils->message("S", "INFO xcatd: 'Command log writer' process $$ is terminated by TERM or INT signal"); exit(0); }; @@ -1090,37 +1134,37 @@ unless ($cmdlog_svrpid){ # when it changes the commands.log name, it will send HUP signal to 'command log writer' process. # so when 'command log writer' process receives the HUP siganl, it should reopen the commands.log to make log writing correctly. $SIG{HUP} = sub { - my $trytime=200; - while($writing){sleep(0.01);} - $cmdlogfileswitch=0; - if($cmdlogfile){close($cmdlogfile);} - while(!$cmdlogfileswitch and $trytime){ - unless (open ($cmdlogfile, ">>$cmdlog_logfile")) { + my $trytime = 200; + while ($writing) { sleep(0.01); } + $cmdlogfileswitch = 0; + if ($cmdlogfile) { close($cmdlogfile); } + while (!$cmdlogfileswitch and $trytime) { + unless (open($cmdlogfile, ">>$cmdlog_logfile")) { $trytime--; - xCAT::MsgUtils->trace(0,"E","xcatd: Can't open xcat command log file $cmdlog_logfile."); + xCAT::MsgUtils->trace(0, "E", "xcatd: Can't open xcat command log file $cmdlog_logfile."); sleep(0.05); next; } select($cmdlogfile); - $|=1; - $cmdlogfileswitch=1; + $| = 1; + $cmdlogfileswitch = 1; } - if(!$trytime){ - xCAT::MsgUtils->message("S","INFO xcatd: 'Command log writer' process $$ get HUP signal, reopen commands.log file failed, send TERM signal to kill itself"); + if (!$trytime) { + xCAT::MsgUtils->message("S", "INFO xcatd: 'Command log writer' process $$ get HUP signal, reopen commands.log file failed, send TERM signal to kill itself"); kill 'INT', $$; - }else{ - xCAT::MsgUtils->message("S","INFO xcatd: 'Command log writer' process $$ get HUP signal, reopen commands.log file"); + } else { + xCAT::MsgUtils->message("S", "INFO xcatd: 'Command log writer' process $$ get HUP signal, reopen commands.log file"); } }; $cmdlogsvrlistener = IO::Socket::INET->new(LocalPort => $cmdlog_port, LocalAddr => "127.0.0.1", - Type => SOCK_STREAM, - Reuse => 1, - Listen => 8192); + Type => SOCK_STREAM, + Reuse => 1, + Listen => 8192); - if(not $cmdlogsvrlistener and open($cmdlogpidfile,"<","$cmdlogservicefile")) { - xCAT::MsgUtils->message("S","INFO xcatd: 'Command log writer' process $$ is trying to get port $cmdlog_port"); + if (not $cmdlogsvrlistener and open($cmdlogpidfile, "<", "$cmdlogservicefile")) { + xCAT::MsgUtils->message("S", "INFO xcatd: 'Command log writer' process $$ is trying to get port $cmdlog_port"); my $pid = <$cmdlogpidfile>; if ($pid) { kill 'USR2', $pid; @@ -1131,33 +1175,33 @@ unless ($cmdlog_svrpid){ $retry--; $cmdlogsvrlistener = IO::Socket::INET->new(LocalPort => $cmdlog_port, LocalAddr => "127.0.0.1", - Type => SOCK_STREAM, - Reuse => 1, - Listen => 8192); + Type => SOCK_STREAM, + Reuse => 1, + Listen => 8192); sleep(0.05); } unless ($cmdlogsvrlistener) { - xCAT::MsgUtils->trace(0,"E","xcatd: Can't open command log service on port $cmdlog_port,command log process $$ stop."); + xCAT::MsgUtils->trace(0, "E", "xcatd: Can't open command log service on port $cmdlog_port,command log process $$ stop."); exit(0); } - open($cmdlogpidfile,">$cmdlogservicefile"); + open($cmdlogpidfile, ">$cmdlogservicefile"); print $cmdlogpidfile $$; close($cmdlogpidfile); - xCAT::MsgUtils->trace(0,"I","xcatd: command log process $$ start"); + xCAT::MsgUtils->trace(0, "I", "xcatd: command log process $$ start"); - my $cmdlog_logfile_path=dirname($cmdlog_logfile); - mkpath("$cmdlog_logfile_path") unless(-d "$cmdlog_logfile_path"); + my $cmdlog_logfile_path = dirname($cmdlog_logfile); + mkpath("$cmdlog_logfile_path") unless (-d "$cmdlog_logfile_path"); $cmdlog_logfile_umask = umask(0077); - unless (open ($cmdlogfile, ">>$cmdlog_logfile")) { - xCAT::MsgUtils->trace(0,"E","xcatd: Can't open xcat command log file $cmdlog_logfile,command log process $$ stop."); + unless (open($cmdlogfile, ">>$cmdlog_logfile")) { + xCAT::MsgUtils->trace(0, "E", "xcatd: Can't open xcat command log file $cmdlog_logfile,command log process $$ stop."); exit(1); } umask($cmdlog_logfile_umask); select($cmdlogfile); - $|=1; - $cmdlogfileswitch=1; + $| = 1; + $cmdlogfileswitch = 1; while (1) { @@ -1166,38 +1210,39 @@ unless ($cmdlog_svrpid){ my $log = ""; my $bytesread; do { - $bytesread=sysread($clientsock,$log,65536,length($log)) - } while ($bytesread); + $bytesread = sysread($clientsock, $log, 65536, length($log)) + } while ($bytesread); close($clientsock); - until($cmdlogfileswitch){ + until ($cmdlogfileswitch) { sleep(0.05); } - $writing=1; + $writing = 1; print $cmdlogfile $log; - $writing=0; + $writing = 0; } - if($cmdlogfile){close($cmdlogfile);} - if($cmdlogsvrlistener){close($cmdlogsvrlistener);} - xCAT::MsgUtils->message("S","INFO xcatd: 'Command log writer' process $$ stop"); + if ($cmdlogfile) { close($cmdlogfile); } + if ($cmdlogsvrlistener) { close($cmdlogsvrlistener); } + xCAT::MsgUtils->message("S", "INFO xcatd: 'Command log writer' process $$ stop"); } + # ----used for command log end--------- -$$progname="xcatd: SSL listener"; +$$progname = "xcatd: SSL listener"; # Enable the signals for the subroutine calling trace $SIG{TRAP} = sub { if (-f "/tmp/xcatcallingtrace.flag") { - if (open (TRACEFLAG, "; - if($traceflag == 1) { + if ($traceflag == 1) { &enable_callingtrace; print "enabled calling trace\n"; } else { &disable_callingtrace; print "dislabled calling trace\n"; } - close (TRACEFLAG); + close(TRACEFLAG); } } }; @@ -1212,7 +1257,7 @@ xCAT_monitoring::monitorctrl::start($$); # cmd_handlers hash and pass it back to this parent when rescanplugins requested my $chreadpipe; my $chwritepipe; -if ( !(socketpair($chreadpipe, $chwritepipe,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) ) { +if (!(socketpair($chreadpipe, $chwritepipe, AF_UNIX, SOCK_STREAM, PF_UNSPEC))) { xCAT::MsgUtils->message("S", "socketpair failed: $!"); } my $chrselect = new IO::Select; @@ -1221,36 +1266,36 @@ $chrselect->add($chreadpipe); my $peername; my $ssltimeout; -my $retry=1; -openlog("xcat","","local4"); +my $retry = 1; +openlog("xcat", "", "local4"); my $listener; my $mainpidfile; $SIG{USR2} = sub { if ($listener) { - unlink("/var/run/xcat/mainservice.pid"); close($listener); $quit=1; $listener=0; - $udpctl=0; - xCAT::MsgUtils->message("S","xcatd main service $$ quiescing"); + unlink("/var/run/xcat/mainservice.pid"); close($listener); $quit = 1; $listener = 0; + $udpctl = 0; + xCAT::MsgUtils->message("S", "xcatd main service $$ quiescing"); } }; if ($inet6support) { $listener = IO::Socket::INET6->new( LocalPort => $port, - Listen => 8192, - Reuse => 1, - ); + Listen => 8192, + Reuse => 1, + ); } else { $listener = IO::Socket::INET->new( LocalPort => $port, - Listen => 8192, - Reuse => 1, - ); + Listen => 8192, + Reuse => 1, + ); } -if (not $listener and open($mainpidfile,"<","/var/run/xcat/mainservice.pid")) { +if (not $listener and open($mainpidfile, "<", "/var/run/xcat/mainservice.pid")) { my $pid = <$mainpidfile>; if ($pid) { - $retry=100; # grace period for old instance to get out of the way, 5 seconds - kill 'USR2',$pid; - yield(); # let peer have a shot at closure + $retry = 100; # grace period for old instance to get out of the way, 5 seconds + kill 'USR2', $pid; + yield(); # let peer have a shot at closure } close($mainpidfile); } @@ -1259,21 +1304,21 @@ while (not $listener and $retry) { if ($inet6support) { $listener = IO::Socket::INET6->new( LocalPort => $port, - Listen => 8192, - Reuse => 1, - ); + Listen => 8192, + Reuse => 1, + ); } else { $listener = IO::Socket::INET->new( LocalPort => $port, - Listen => 8192, - Reuse => 1, - ); + Listen => 8192, + Reuse => 1, + ); } sleep(0.05); } my $listenwatcher = IO::Select->new($listener); -my $udpwatcher = IO::Select->new($udpctl); -my $bothwatcher = IO::Select->new($udpctl, $listener); +my $udpwatcher = IO::Select->new($udpctl); +my $bothwatcher = IO::Select->new($udpctl, $listener); unless ($listener) { kill 'INT', $pid_UDP; @@ -1282,7 +1327,7 @@ unless ($listener) { if ($dbmaster) { kill 'INT', $dbmaster; } - xCAT::MsgUtils->message("S","xCAT service unable to open SSL services on $port: $!"); + xCAT::MsgUtils->message("S", "xCAT service unable to open SSL services on $port: $!"); closelog(); if ($startupparent) { print $startupparent "Unable to perform socket takeover from existing xCAT instance\n"; @@ -1295,25 +1340,25 @@ if ($startupparent) { } # only write to pid file if we have listener, listener ownership serves as lock to protect integrity -open($mainpidfile,">","/var/run/xcat/mainservice.pid"); # if here, everyone else has unlinked mainservicepid or doesn't care +open($mainpidfile, ">", "/var/run/xcat/mainservice.pid"); # if here, everyone else has unlinked mainservicepid or doesn't care print $mainpidfile $$; close($mainpidfile); closelog(); my @pendingconnections; my $tconn; my $sslfudgefactor = 0; -my $udpalive = 1; +my $udpalive = 1; until ($quit) { $SIG{CHLD} = \&ssl_reaper; # set here to ensure that signal handler is not corrupted during loop - while ($udpalive and $udpwatcher->can_read(0)) { # take an intermission to broker some state requests from udp traffic control + while ($udpalive and $udpwatcher->can_read(0)) { # take an intermission to broker some state requests from udp traffic control eval { my $msg = fd_retrieve($udpctl); if ($msg->{req} eq 'get_client_count') { - store_fd({'clientfudge'=>$sslfudgefactor, 'sslclientcount' => $sslclients}, $udpctl); + store_fd({ 'clientfudge' => $sslfudgefactor, 'sslclientcount' => $sslclients }, $udpctl); } elsif ($msg->{req} eq 'set_fudge_factor') { $sslfudgefactor = $msg->{fudge}; - store_fd({'clientfudge'=>$sslfudgefactor, 'sslclientcount' => $sslclients}, $udpctl); + store_fd({ 'clientfudge' => $sslfudgefactor, 'sslclientcount' => $sslclients }, $udpctl); } }; if ($@) { @@ -1325,61 +1370,67 @@ until ($quit) { while ($listenwatcher->can_read(0)) { # grab everything we can, but don't spend any time waiting for more $tconn = $listener->accept; unless ($tconn) { next; } - push @pendingconnections,$tconn; + push @pendingconnections, $tconn; } } else { + # if select returned with no ready fds, there might be udpctl broken. if (not $bothwatcher->can_read(30)) { + # if the errno is 'bad fd', check the health of the udpctl if ($! == EBADF) { $udpwatcher->can_read(0); if ($! == EBADF) { + # if udpctl cannot be read and said 'bad fd', remove it from $bothwatcher - $udpalive = 0;$bothwatcher = IO::Select->new($listener); + $udpalive = 0; $bothwatcher = IO::Select->new($listener); } } } - if (not $listenwatcher->can_read(0)) { # check for udpctl messages since - # we have no listen to hear + if (not $listenwatcher->can_read(0)) { # check for udpctl messages since + # we have no listen to hear next; } $tconn = $listener->accept; # we have no connections pending, no rush, just wait until the next connection attempt comes in unless ($tconn) { next; } # sometimes we get 'undef', in which case carry on with our lives... - push @pendingconnections,$tconn; + push @pendingconnections, $tconn; } unless (scalar @pendingconnections) { next; } # if for some reason we landed here without any accepted connections, carry on.. if ($sslclients > $maxsslclients) { # we have enough children, wait for some to exit before spawning more $bothwatcher->can_read(0.1); # when next connection tries to come in or a tenth of a second, whichever comes first - next; # just keep pulling things off listen queue onto our own + next; # just keep pulling things off listen queue onto our own } + # before we fork, check to see if rescanplugins was previously processed and # we now have a new cmd_handlers hash to refresh my @chdata; if (@chdata = $chrselect->can_read(0)) { foreach my $chd (@chdata) { - %cmd_handlers = %{fd_retrieve($chd)}; + %cmd_handlers = %{ fd_retrieve($chd) }; } } + # we have a pending connection and we are under the threshold, grab one from the list and process it... - my $cnnection=shift @pendingconnections; + my $cnnection = shift @pendingconnections; + #my $previous = select ($cnnection); # assure that perl buffering is not in play at the low level #$|=1; #select ($previous); my $connection; my $child = xCAT::Utils->xfork(); # Yes we fork, IO::Socket::SSL is not threadsafe.. if ($child) { - $immediatechildren{$child}=1; + $immediatechildren{$child} = 1; } unless (defined $child) { - xCAT::MsgUtils->message("S","xcatd cannot fork"); + xCAT::MsgUtils->message("S", "xcatd cannot fork"); die; } if ($child == 0) { - close($udpctl); $udpctl=0; + close($udpctl); $udpctl = 0; $SIG{TERM} = $SIG{INT} = 'DEFAULT'; - $SIG{CHLD} = \&generic_reaper; # THROTTLE + $SIG{CHLD} = \&generic_reaper; # THROTTLE $listener->close; populate_site_hash(); @@ -1392,59 +1443,62 @@ until ($quit) { eval { alarm(10); $connection = IO::Socket::SSL->start_SSL($cnnection, - SSL_key_file=>$xcatdir."/cert/server-cred.pem", - SSL_cert_file=>$xcatdir."/cert/server-cred.pem", - SSL_ca_file=>$xcatdir."/cert/ca.pem", - SSL_server=>1, - SSL_verify_mode=> 1, + SSL_key_file => $xcatdir . "/cert/server-cred.pem", + SSL_cert_file => $xcatdir . "/cert/server-cred.pem", + SSL_ca_file => $xcatdir . "/cert/ca.pem", + SSL_server => 1, + SSL_verify_mode => 1, %extrasslargs, - ); + ); alarm(0); }; - $SIG{ALRM}='DEFAULT'; - if ($@) { # SSL failure + $SIG{ALRM} = 'DEFAULT'; + if ($@) { # SSL failure close($cnnection); xexit 0; } unless ($connection) { xexit 0; } + #$previous=select($connection); # also assure buffering not in play at SSL socket, which seems to be possibly independent of lower socket #$|=1; #select($previous); $clientselect->add($connection); - my $peerhost=undef; - my $peerfqdn=undef; - my $peer=$connection->peer_certificate("owner"); + my $peerhost = undef; + my $peerfqdn = undef; + my $peer = $connection->peer_certificate("owner"); if ($peer) { $peer =~ m/CN=([^\/]*)/; $peername = $1; } else { - $peername=undef; + $peername = undef; } if ($inet6support) { - $peerhost = gethostbyaddr($connection->peeraddr,AF_INET6); + $peerhost = gethostbyaddr($connection->peeraddr, AF_INET6); } else { - $peerhost = gethostbyaddr($connection->peeraddr,AF_INET); + $peerhost = gethostbyaddr($connection->peeraddr, AF_INET); } - unless ($peerhost) { $peerhost = gethostbyaddr($connection->peeraddr,AF_INET); } - $peerfqdn=$peerhost; - my $peerhostorg=$peerhost; # save original with domain for validation + unless ($peerhost) { $peerhost = gethostbyaddr($connection->peeraddr, AF_INET); } + $peerfqdn = $peerhost; + my $peerhostorg = $peerhost; # save original with domain for validation if ($peerhost) { my @hosts; - push (@hosts, $peerhost); - my $nd = xCAT::NetworkUtils->getNodeDomains(\@hosts); + push(@hosts, $peerhost); + my $nd = xCAT::NetworkUtils->getNodeDomains(\@hosts); my %nodedomains = %$nd; $domain = $nodedomains{$peerhost}; } if ($domain) { + # strip off domain if set $peerhost && $peerhost =~ s/\.$domain\.*$//; } else { + # otherwise just strip off whatever comes after the first dot $peerhost && $peerhost =~ s/\..*//; } @@ -1452,23 +1506,24 @@ until ($quit) { $peerhost && $peerhost =~ s/-eth\d*$//; $peerhost && $peerhost =~ s/-myri\d*$//; $peerhost && $peerhost =~ s/-ib\d*$//; + #printf('info'.": xcatd: connection from ".($peername ? $peername . "@" . $peerhost : $peerhost)."\n"); - my $debugmsg = "xcatd: connection from ".($peername ? $peername . "@" . $peerhost : $peerhost)."\n"; - xCAT::MsgUtils->trace(0,"D","$debugmsg"); + my $debugmsg = "xcatd: connection from " . ($peername ? $peername . "@" . $peerhost : $peerhost) . "\n"; + xCAT::MsgUtils->trace(0, "D", "$debugmsg"); - $$progname="xcatd SSL: Instance for ".($peername ? $peername ."@".$peerhost : $peerhost) if $peerhost; - service_connection($connection,$peername,$peerhost,$peerfqdn,$peerhostorg); + $$progname = "xcatd SSL: Instance for " . ($peername ? $peername . "@" . $peerhost : $peerhost) if $peerhost; + service_connection($connection, $peername, $peerhost, $peerfqdn, $peerhostorg); - $debugmsg = "xcatd: close connection with ".($peername ? $peername . "@" . $peerhost : $peerhost)."\n"; - xCAT::MsgUtils->trace(0,"D","$debugmsg"); + $debugmsg = "xcatd: close connection with " . ($peername ? $peername . "@" . $peerhost : $peerhost) . "\n"; + xCAT::MsgUtils->trace(0, "D", "$debugmsg"); xexit(0); } if ($sslfudgefactor) { $sslfudgefactor -= 1; } - $sslclients++; # THROTTLE + $sslclients++; # THROTTLE $cnnection->close(); } -if (open($mainpidfile,"<","/var/run/xcat/mainservice.pid")) { +if (open($mainpidfile, "<", "/var/run/xcat/mainservice.pid")) { my $pid = <$mainpidfile>; if ($pid == $$) { # if our pid, unlink the file, otherwise, we managed to see the pid after someone else created it unlink("/var/run/xcat/mainservice.pid"); @@ -1478,7 +1533,7 @@ if (open($mainpidfile,"<","/var/run/xcat/mainservice.pid")) { if ($listener) { $listener->close; } my $lastpid; while (keys %immediatechildren || $pid_UDP || $cmdlog_svrpid || $pid_MON) { - $lastpid=wait(); + $lastpid = wait(); if ($immediatechildren{$lastpid}) { delete $immediatechildren{$lastpid}; } elsif ($lastpid == $pid_UDP) { @@ -1501,25 +1556,26 @@ my $parent_fd; my %resps; sub plugin_command { - my $req = shift; - my $sock = shift; + my $req = shift; + my $sock = shift; my $callback = shift; my %handler_hash; my $usesiteglobal = 0; use xCAT::NodeRange qw/extnoderange nodesmissed noderange/; - $Main::resps={}; + $Main::resps = {}; my @nodes; @ARGV = (); + if ($req->{node}) { - @nodes = @{$req->{node}}; + @nodes = @{ $req->{node} }; } elsif ($req->{noderange} and $req->{noderange}->[0]) { xCAT::NodeRange::retain_cache(0); # if the request has a 'noderange' element, take the performance hit for the sake of freshness @nodes = noderange($req->{noderange}->[0]); if (nodesmissed) { - my $rsp = {errorcode=>['1'],error=>["Invalid nodes and/or groups in noderange: ".join(',',nodesmissed)]}; - $rsp->{serverdone} = [ undef ]; + my $rsp = { errorcode => ['1'], error => [ "Invalid nodes and/or groups in noderange: " . join(',', nodesmissed) ] }; + $rsp->{serverdone} = [undef]; if ($sock) { - send_response($rsp,$sock); + send_response($rsp, $sock); } return ($rsp); } @@ -1531,44 +1587,45 @@ sub plugin_command { if (@nodes) { $req->{node} = \@nodes; } my %unhandled_nodes; foreach (@nodes) { - $unhandled_nodes{$_}=1; + $unhandled_nodes{$_} = 1; } - my $useunhandled=0; - if (defined($cmd_handlers{$req->{command}->[0]})) { + my $useunhandled = 0; + if (defined($cmd_handlers{ $req->{command}->[0] })) { my $hdlspec; - my @globalhandlers=(); - my $useglobals=1; # If it stays 1, then use globals normally, if 0, use only for 'unhandled_nodes, if -1, don't do at all + my @globalhandlers = (); + my $useglobals = 1; # If it stays 1, then use globals normally, if 0, use only for 'unhandled_nodes, if -1, don't do at all my %hdlrcaches; - foreach (@{$cmd_handlers{$req->{command}->[0]}}) { - $hdlspec =$_->[1]; + foreach (@{ $cmd_handlers{ $req->{command}->[0] } }) { + $hdlspec = $_->[1]; my $ownmod = $_->[0]; - if ($hdlspec =~ /^site:/) { # A site entry specifies a plugin + if ($hdlspec =~ /^site:/) { # A site entry specifies a plugin my $sitekey = $hdlspec; $sitekey =~ s/^site://; - if ($::XCATSITEVALS{$sitekey}) {# A site style plugin specification is just like - # a static global, it grabs all nodes rather than some + if ($::XCATSITEVALS{$sitekey}) { # A site style plugin specification is just like + # a static global, it grabs all nodes rather than some $useglobals = -1; # If they tried to specify anything, don't use the default global handlers at all unless (@nodes) { - $handler_hash{$::XCATSITEVALS{$sitekey}} = 1; + $handler_hash{ $::XCATSITEVALS{$sitekey} } = 1; $usesiteglobal = 1; } foreach (@nodes) { # Specified a specific plugin, not a table lookup - $handler_hash{$::XCATSITEVALS{$sitekey}}->{$_} = 1; + $handler_hash{ $::XCATSITEVALS{$sitekey} }->{$_} = 1; } } } elsif ($hdlspec =~ /:/) { # Specificed a table lookup path for plugin name - if (@nodes) { # only use table lookup plugin if nodelist exists - # Usage will be handled in common AAAhelp plugin + if (@nodes) { # only use table lookup plugin if nodelist exists + # Usage will be handled in common AAAhelp plugin $useglobals = 0; # Only contemplate nodes that aren't caught through searching below in the global handler - $useunhandled=1; + $useunhandled = 1; my $table; my $cols; - ($table,$cols) = split(/:/,$hdlspec); - my @colmns=split(/,/,$cols); + ($table, $cols) = split(/:/, $hdlspec); + my @colmns = split(/,/, $cols); my @columns; - my $hdlrtable=0; + my $hdlrtable = 0; + unless ($hdlrcaches{$hdlspec}) { - $hdlrtable=xCAT::Table->new($table,-create=>0); + $hdlrtable = xCAT::Table->new($table, -create => 0); unless ($hdlrtable) { next; } @@ -1578,11 +1635,11 @@ sub plugin_command { foreach my $colu (@colmns) { if ($colu =~ /=/) { # a value redirect to a pattern/specific name my $coln; my $colv; - ($coln,$colv) = split(/=/,$colu,2); + ($coln, $colv) = split(/=/, $colu, 2); $colvals->{$coln} = $colv; - push (@columns,$coln); + push(@columns, $coln); } else { - push (@columns,$colu); + push(@columns, $colu); } } @@ -1592,14 +1649,14 @@ sub plugin_command { $useglobals = 1; } if ($hdlrtable) { - $hdlrcaches{$hdlspec} = $hdlrtable->getNodesAttribs(\@nodes,\@columns); + $hdlrcaches{$hdlspec} = $hdlrtable->getNodesAttribs(\@nodes, \@columns); } foreach $node (@nodes) { unless ($hdlrcaches{$hdlspec}) { next; } my $attribs = $hdlrcaches{$hdlspec}->{$node}->[0]; #$hdlrtable->getNodeAttribs($node,\@columns); unless (defined($attribs)) { next; } foreach (@columns) { - my $col=$_; + my $col = $_; if (defined($attribs->{$col})) { if ($colvals->{$col}) { # A pattern match style request. if ($attribs->{$col} =~ /$colvals->{$col}/) { @@ -1608,9 +1665,10 @@ sub plugin_command { last; } } else { + # call the plugin that matches the table value for that node if ($attribs->{$col} =~ /$ownmod/) { - $handler_hash{$attribs->{$col}}->{$node} = 1; + $handler_hash{ $attribs->{$col} }->{$node} = 1; delete $unhandled_nodes{$node}; last; } @@ -1619,10 +1677,10 @@ sub plugin_command { } } $hdlrtable->close if $hdlrtable; - } # end if (@nodes) + } # end if (@nodes) } else { - push @globalhandlers,$hdlspec; + push @globalhandlers, $hdlspec; } } if ($useglobals == 1) { # Behavior when globals have not been overriden @@ -1639,7 +1697,7 @@ sub plugin_command { unless (@nodes or $usesiteglobal) { # if something like 'makedhcp -n', foreach (keys %handler_hash) { if ($handler_hash{$_} == 1) { - delete ($handler_hash{$_}) + delete($handler_hash{$_}) } } } @@ -1651,13 +1709,13 @@ sub plugin_command { $handler_hash{$hdlspec}->{$_} = 1; } } - } # Otherwise, global handler is implicitly disabled + } # Otherwise, global handler is implicitly disabled } else { - return 1; # TODO: error back that request has no known plugin for it + return 1; # TODO: error back that request has no known plugin for it } if ($useunhandled) { - my $queuelist=''; - foreach (@{$cmd_handlers{$req->{command}->[0]}}) { + my $queuelist = ''; + foreach (@{ $cmd_handlers{ $req->{command}->[0] } }) { my $queueitem = $_->[1]; if (($queueitem =~ /:/) and !($queuelist =~ /($queueitem)/)) { $queuelist .= "$_->[1];"; @@ -1668,20 +1726,21 @@ sub plugin_command { if ($sock) { my $xcatresponse = { xcatresponse => [] }; foreach (keys %unhandled_nodes) { - push @{$xcatresponse->{xcatresponse}},{node=>[{name=>[$_],error=>["Unable to identify plugin for this command, check relevant tables: $queuelist"],errorcode=>[1]}]}; + push @{ $xcatresponse->{xcatresponse} }, { node => [ { name => [$_], error => ["Unable to identify plugin for this command, check relevant tables: $queuelist"], errorcode => [1] } ] }; } - send_response($xcatresponse,$sock); + send_response($xcatresponse, $sock); } else { foreach (keys %unhandled_nodes) { my $tabdesc = $queuelist; $tabdesc =~ s/=.*$//; - $callback->({node=>[{name=>[$_],error=>['Unable to identify plugin for this command, check relevant tables: '.$tabdesc],errorcode=>[1]}]}); + $callback->({ node => [ { name => [$_], error => [ 'Unable to identify plugin for this command, check relevant tables: ' . $tabdesc ], errorcode => [1] } ] }); } } } - my %xcatresponses = ( xcatresponse => [] ); - $plugin_numchildren=0; - %plugin_children=(); + my %xcatresponses = (xcatresponse => []); + $plugin_numchildren = 0; + %plugin_children = (); + # save the old signal my $old_sig_chld = $SIG{CHLD}; $SIG{CHLD} = \&plugin_reaper; #sub {my $plugpid; while (($plugpid = waitpid(-1, WNOHANG)) > 0) { if ($plugin_children{$plugpid}) { delete $plugin_children{$plugpid}; $plugin_numchildren--; } } }; @@ -1691,7 +1750,7 @@ sub plugin_command { foreach (keys %plugin_children) { kill 'INT', $_; } - $SIG{ALRM} = sub { xexit 0; }; # wait 1s for grace exit + $SIG{ALRM} = sub { xexit 0; }; # wait 1s for grace exit alarm(1); }; @@ -1699,89 +1758,95 @@ sub plugin_command { if ($sock) { $check_fds = new IO::Select; } + # Multiple plugins for one command # $req->{sequential} is 0 by default if (defined($req->{sequential}) && $req->{sequential}->[0]) { + # PCM case, executing plugins sequentially in alphabetic order my $old_parent_fd = $parent_fd; $parent_fd = 0; foreach (sort(keys %handler_hash)) { my $modname = $_; - $Main::resps={}; - if (-r $plugins_dir."/".$modname.".pm") { - require $plugins_dir."/".$modname.".pm"; + $Main::resps = {}; + if (-r $plugins_dir . "/" . $modname . ".pm") { + require $plugins_dir . "/" . $modname . ".pm"; $plugin_numchildren++; - my $oldprogname=$$progname; - $$progname=$oldprogname.": $modname instance"; + my $oldprogname = $$progname; + $$progname = $oldprogname . ": $modname instance"; unless ($handler_hash{$_} == 1) { + # ok, if nodes have numbers, this sorts them numerically... roughly.. # if node doesn't, then it sorts out alphabetically. - my @nodes = sort {($a =~ /(\d+)/ ? $1 : -1)[0] <=> ($b =~ /(\d+)/ ? $1 : -1)[0] || $a cmp $b } (keys %{$handler_hash{$_}}); - $req->{node}=\@nodes; + my @nodes = sort { ($a =~ /(\d+)/ ? $1 : -1)[0] <=> ($b =~ /(\d+)/ ? $1 : -1)[0] || $a cmp $b } (keys %{ $handler_hash{$_} }); + $req->{node} = \@nodes; } - no strict "refs"; - eval { # REMOVEEVALFORDEBUG + no strict "refs"; + eval { # REMOVEEVALFORDEBUG if ($dispatch_requests) { - dispatch_request($req,$callback,$modname); + dispatch_request($req, $callback, $modname); } else { - $SIG{CHLD}='DEFAULT'; + $SIG{CHLD} = 'DEFAULT'; + # Call the plugin to process the command request # rescanplugins request gets handled directly here in xcatd if ($req->{command}->[0] eq 'rescanplugins') { - scan_plugins($chwritepipe,'1'); + scan_plugins($chwritepipe, '1'); if ($rescanwritepipe) { - store_fd(\$rescanrequest,$rescanwritepipe); + store_fd(\$rescanrequest, $rescanwritepipe); } } else { - my $debuglog= "xcatd: call plugin <$modname> to handle command <$req->{command}->[0]>"; - xCAT::MsgUtils->trace(0,"D","$debuglog"); + my $debuglog = "xcatd: call plugin <$modname> to handle command <$req->{command}->[0]>"; + xCAT::MsgUtils->trace(0, "D", "$debuglog"); - ${"xCAT_plugin::".$modname."::"}{process_request}->($req,$callback,\&do_request); + ${ "xCAT_plugin::" . $modname . "::" }{process_request}->($req, $callback, \&do_request); } } - $$progname=$oldprogname; - }; # REMOVEEVALFORDEBUG + $$progname = $oldprogname; + }; # REMOVEEVALFORDEBUG if ($@) { # We are still alive, should be alive, but yet we have an error. This means we are in the case of 'do_request' or something similar. Forward up the death since our communication channel is intact.. xCAT::MsgUtils->message("S", "$@"); die $@; } } else { - my $pm_name = $plugins_dir."/".$modname.".pm"; + my $pm_name = $plugins_dir . "/" . $modname . ".pm"; if (ref $handler_hash{$_}) { - foreach my $node (keys %{$handler_hash{$_}}) { + foreach my $node (keys %{ $handler_hash{$_} }) { if ($sock) { - send_response({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]},$sock); + send_response({ node => [ { name => [$node], data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] } ] }, $sock); } else { - $callback->({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]}); + $callback->({ node => [ { name => [$node], data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] } ] }); } } } else { if ($sock) { - send_response({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]},$sock); + send_response({ data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] }, $sock); } else { - $callback->({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}); + $callback->({ data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] }); } } } - push @{$xcatresponses{xcatresponse}}, $Main::resps; + push @{ $xcatresponses{xcatresponse} }, $Main::resps; } $parent_fd = $old_parent_fd; } else { my $req_back = undef; - my $command = $req->{'command'}->[0]; + my $command = $req->{'command'}->[0]; + # executing plugins parallel foreach (keys %handler_hash) { - my $modname = $_; - my $shouldbealivepid=$$; - if (-r $plugins_dir."/".$modname.".pm") { - require $plugins_dir."/".$modname.".pm"; + my $modname = $_; + my $shouldbealivepid = $$; + if (-r $plugins_dir . "/" . $modname . ".pm") { + require $plugins_dir . "/" . $modname . ".pm"; $plugin_numchildren++; + # build the request queue for the callback command if (grep (/^$command$/, @CALLBACK_COMMAND)) { - no strict "refs"; - if (defined(${"xCAT_plugin::".$modname."::"}{route_request})) { - my $ret = ${"xCAT_plugin::".$modname."::"}{route_request} - ($req,$callback,\&do_request); + no strict "refs"; + if (defined(${ "xCAT_plugin::" . $modname . "::" }{route_request})) { + my $ret = ${ "xCAT_plugin::" . $modname . "::" }{route_request} + ($req, $callback, \&do_request); if ($ret == xCAT::State->REQUEST_ERROR) { xCAT::MsgUtils->message("S", "Request failed: $!"); next; @@ -1790,22 +1855,23 @@ sub plugin_command { } } } - my $pfd; # will be referenced for inter-process messaging. + my $pfd; # will be referenced for inter-process messaging. my $parfd; # not causing a problem that I discern yet, but theoretically my $child; - if ($sock) { # If $sock not passed in, don't fork.. - if (! socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) { + if ($sock) { # If $sock not passed in, don't fork.. + if (!socketpair($pfd, $parfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC)) { xCAT::MsgUtils->message("S", "socketpair failed: $!"); die; } + #pipe($pfd,$cfd); my $oldfh = select $parfd; - $|=1; + $| = 1; select $pfd; - $|=1; + $| = 1; select $oldfh; - binmode($parfd,':utf8'); - binmode($pfd,':utf8'); + binmode($parfd, ':utf8'); + binmode($pfd, ':utf8'); $child = xCAT::Utils->xfork; } else { if ($req_back) { @@ -1820,127 +1886,131 @@ sub plugin_command { die; } if ($child == 0) { - if ($parfd) { # If xCAT is doing multiple requests in same communication PID, things would get unfortunate otherwise + if ($parfd) { # If xCAT is doing multiple requests in same communication PID, things would get unfortunate otherwise $parent_fd = $parfd; } my $org_parent_fd = $parent_fd; - my $oldprogname=$$progname; - $$progname=$oldprogname.": $modname instance"; + my $oldprogname = $$progname; + $$progname = $oldprogname . ": $modname instance"; if ($sock) { close $pfd; } unless ($handler_hash{$_} == 1) { + # ok, if nodes have numbers, this sorts them numerically... roughly.. # if node doesn't, then it sorts out alphabetically. - my @nodes = sort {($a =~ /(\d+)/ ? $1 : -1)[0] <=> ($b =~ /(\d+)/ ? $1 : -1)[0] || $a cmp $b } (keys %{$handler_hash{$_}}); - $req->{node}=\@nodes; + my @nodes = sort { ($a =~ /(\d+)/ ? $1 : -1)[0] <=> ($b =~ /(\d+)/ ? $1 : -1)[0] || $a cmp $b } (keys %{ $handler_hash{$_} }); + $req->{node} = \@nodes; } - no strict "refs"; - eval { # REMOVEEVALFORDEBUG + no strict "refs"; + eval { # REMOVEEVALFORDEBUG if ($dispatch_requests) { - dispatch_request($req,$callback,$modname); + dispatch_request($req, $callback, $modname); } else { - $SIG{CHLD}='DEFAULT'; + $SIG{CHLD} = 'DEFAULT'; + # Call the plugin to process the command request # rescanplugins request gets handled directly here in xcatd if ($req->{command}->[0] eq 'rescanplugins') { - scan_plugins($chwritepipe,'1'); + scan_plugins($chwritepipe, '1'); if ($rescanwritepipe) { - store_fd(\$rescanrequest,$rescanwritepipe); + store_fd(\$rescanrequest, $rescanwritepipe); } } else { - ${"xCAT_plugin::".$modname."::"}{process_request}->($req,$callback,\&do_request); + ${ "xCAT_plugin::" . $modname . "::" }{process_request}->($req, $callback, \&do_request); } } - $$progname=$oldprogname; + $$progname = $oldprogname; $parent_fd = $org_parent_fd; if ($sock) { close($parent_fd); xexit(0); } - $@=""; # sometimes a child 'eval' doesn't clean up $@, if we make it this far, no non-eval bug bombed out - }; # REMOVEEVALFORDEBUG + $@ = ""; # sometimes a child 'eval' doesn't clean up $@, if we make it this far, no non-eval bug bombed out + }; # REMOVEEVALFORDEBUG if ($sock or $shouldbealivepid != $$) { # We shouldn't still be alive, try to send as much detail to parent as possible as to why - my $error= "$modname plugin bug, pid $$, process description: '$$progname'"; + my $error = "$modname plugin bug, pid $$, process description: '$$progname'"; if ($@) { $error .= " with error '$@'"; } else { # Sys::Virt and perhaps Net::SNMP sometimes crashes in a way $@ won't catch.. $error .= " with missing eval error, probably due to special manipulation of $@ or strange circumstances in an XS library, remove evals in xcatd marked 'REMOVEEVALFORDEBUG and run xcatd -f for more info"; } - if (scalar (@nodes)) { # Don't know which of the nodes, so one error message warning about the possibliity.. - $error .= " while trying to fulfill request for the following nodes: ".join(",",@nodes); + if (scalar(@nodes)) { # Don't know which of the nodes, so one error message warning about the possibliity.. + $error .= " while trying to fulfill request for the following nodes: " . join(",", @nodes); } - xCAT::MsgUtils->message("S","xcatd: $error"); - $callback->({error=>[$error],errorcode=>[1]}); - xexit(0); # Die like we should have done + xCAT::MsgUtils->message("S", "xcatd: $error"); + $callback->({ error => [$error], errorcode => [1] }); + xexit(0); # Die like we should have done } elsif ($@) { # We are still alive, should be alive, but yet we have an error. This means we are in the case of 'do_request' or something similar. Forward up the death since our communication channel is intact.. xCAT::MsgUtils->message("S", "$@"); die $@; } } else { - $plugin_children{$child}=1; + $plugin_children{$child} = 1; close $parfd; $check_fds->add($pfd); } } else { - my $pm_name = $plugins_dir."/".$modname.".pm"; + my $pm_name = $plugins_dir . "/" . $modname . ".pm"; if (ref $handler_hash{$_}) { - foreach my $node (keys %{$handler_hash{$_}}) { + foreach my $node (keys %{ $handler_hash{$_} }) { if ($sock) { - send_response({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]},$sock); + send_response({ node => [ { name => [$node], data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] } ] }, $sock); } else { - $callback->({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]}); + $callback->({ node => [ { name => [$node], data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] } ] }); } } } else { if ($sock) { - send_response({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]},$sock); + send_response({ data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] }, $sock); } else { - $callback->({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}); + $callback->({ data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] }); } } } } } unless ($sock) { + # restore the old signal $SIG{CHLD} = $old_sig_chld; return $Main::resps } - if (@deferredmsgargs) { xCAT::MsgUtils->message(@deferredmsgargs) }; - @deferredmsgargs=(); - my $nextxmittime = time()+1; + if (@deferredmsgargs) { xCAT::MsgUtils->message(@deferredmsgargs) } + @deferredmsgargs = (); + my $nextxmittime = time() + 1; while (($plugin_numchildren > 0) and ($check_fds->count > 0)) { # this tracks end of useful data from children much more closely - relay_fds($check_fds,$xcatresponses{xcatresponse}); + relay_fds($check_fds, $xcatresponses{xcatresponse}); if (time() > $nextxmittime) { - $nextxmittime = time()+1; - send_response(\%xcatresponses,$sock); - $xcatresponses{xcatresponse}=[]; + $nextxmittime = time() + 1; + send_response(\%xcatresponses, $sock); + $xcatresponses{xcatresponse} = []; } } if ($check_fds->count > 0) { - relay_fds($check_fds,$xcatresponses{xcatresponse}); + relay_fds($check_fds, $xcatresponses{xcatresponse}); } - if (scalar(@{$xcatresponses{xcatresponse}})) { - send_response(\%xcatresponses,$sock); - $xcatresponses{xcatresponse}=[]; + if (scalar(@{ $xcatresponses{xcatresponse} })) { + send_response(\%xcatresponses, $sock); + $xcatresponses{xcatresponse} = []; } + #while (relay_fds($check_fds,$sock)) {} # restore the old signal $SIG{CHLD} = $old_sig_chld; my %done; - $done{serverdone} = [ undef ]; + $done{serverdone} = [undef]; if ($req->{transid}) { - $done{transid}=$req->{transid}->[0]; + $done{transid} = $req->{transid}->[0]; } if ($sock) { my $clientpresence = new IO::Select; # The client may have gone away without confirmation, don't PIPE over this trivial thing $clientpresence->add($sock); - my $deadline = time()+5; + my $deadline = time() + 5; while ($deadline > time()) { # sometimes can_write exits prematurely without waiting the whole time..... if ($clientpresence->can_write(5)) { - send_response(\%done,$sock); + send_response(\%done, $sock); last; } } @@ -1948,24 +2018,26 @@ sub plugin_command { } my $dispatch_parentfd; + sub dispatch_callback { my $rspo = shift; unless ($rspo) { return; } - my $rsp = {%$rspo}; # deep copy + my $rsp = {%$rspo}; # deep copy delete $rsp->{serverdone}; unless (%$rsp) { return; } - store_fd($rsp,$dispatch_parentfd); - yield; # This has to happen before next line could possibly work anyway + store_fd($rsp, $dispatch_parentfd); + yield; # This has to happen before next line could possibly work anyway my $parselect = new IO::Select; $parselect->add($dispatch_parentfd); my $selbits = $parselect->bits; - while (defined($selbits) && ($rsp = select($selbits,undef,undef,5))) { # block for up to 5 seconds before continuing - if ($quit) { # termination requested by a clean shutdown facility + + while (defined($selbits) && ($rsp = select($selbits, undef, undef, 5))) { # block for up to 5 seconds before continuing + if ($quit) { # termination requested by a clean shutdown facility xexit 0; } - if ($rsp == 0) { # The select call failed to find any ready items + if ($rsp == 0) { # The select call failed to find any ready items last; } if ($rsp < 0) { # A child exited or other signal event that made select skip out before suggesting succes @@ -1986,7 +2058,7 @@ sub dispatch_callback { } sub relay_dispatch { - my $fds = shift; + my $fds = shift; my $dispatch_cb = shift; my @ready_ins; eval { @@ -2012,33 +2084,34 @@ sub relay_dispatch { } sub dispatch_request { - %dispatched_children=(); - my $req = shift; + %dispatched_children = (); + my $req = shift; my $dispatch_cb = shift; - my $modname = shift; - my $reqs = []; + my $modname = shift; + my $reqs = []; my $child_fdset = new IO::Select; - no strict "refs"; + no strict "refs"; # save the old signal my $old_sig_chld = $SIG{CHLD}; # ----used for trace start--------- - my $str_cmd=$req->{command}->[0]." "; - if(exists($req->{noderange})){ - foreach my $n (@{$req->{noderange}}) { - $str_cmd .= $n.","; + my $str_cmd = $req->{command}->[0] . " "; + if (exists($req->{noderange})) { + foreach my $n (@{ $req->{noderange} }) { + $str_cmd .= $n . ","; } $str_cmd =~ s/(.+),$/$1 /g; } - if(exists($req->{arg})){ - foreach my $arg (@{$req->{arg}}) { - $str_cmd .= $arg." "; + if (exists($req->{arg})) { + foreach my $arg (@{ $req->{arg} }) { + $str_cmd .= $arg . " "; } $str_cmd =~ s/(.+) $/$1/g; } - xCAT::MsgUtils->trace(0,"D","xcatd: dispatch request '$str_cmd' to plugin '$modname'"); + xCAT::MsgUtils->trace(0, "D", "xcatd: dispatch request '$str_cmd' to plugin '$modname'"); + # ----used for trace end--------- # Hierarchy support. Originally, the default scope for noderange commands was @@ -2049,26 +2122,27 @@ sub dispatch_request { # Since plugins may commonly experience this, a preprocess_request implementation # will for now be required for a command to be scaled through service nodes # If the plugin offers a preprocess method, use it to set the request array - if ((not (defined $req->{_xcatpreprocessed}->[0] and $req->{_xcatpreprocessed}->[0] == 1)) and (defined(${"xCAT_plugin::".$modname."::"}{preprocess_request}))) { - $SIG{CHLD}='DEFAULT'; - xCAT::MsgUtils->trace(0,"D","xcatd: handle request '$req->{command}->[0]' by plugin '$modname''s preprocess_request"); - $reqs = ${"xCAT_plugin::".$modname."::"}{preprocess_request}->($req,$dispatch_cb,\&do_request); - } else { # otherwise, pass it in without hierarchy support + if ((not(defined $req->{_xcatpreprocessed}->[0] and $req->{_xcatpreprocessed}->[0] == 1)) and (defined(${ "xCAT_plugin::" . $modname . "::" }{preprocess_request}))) { + $SIG{CHLD} = 'DEFAULT'; + xCAT::MsgUtils->trace(0, "D", "xcatd: handle request '$req->{command}->[0]' by plugin '$modname''s preprocess_request"); + $reqs = ${ "xCAT_plugin::" . $modname . "::" }{preprocess_request}->($req, $dispatch_cb, \&do_request); + } else { # otherwise, pass it in without hierarchy support $reqs = [$req]; } - $dispatch_children=0; + $dispatch_children = 0; $SIG{CHLD} = \&dispatch_reaper; #sub {my $cpid; while (($cpid =waitpid(-1, WNOHANG)) > 0) { if ($dispatched_children{$cpid}) { delete $dispatched_children{$cpid}; $dispatch_children--; } } }; $SIG{TERM} = $SIG{INT} = sub { foreach (keys %dispatched_children) { kill 'INT', $_; } - $SIG{ALRM} = sub { xexit 0; }; # wait 1s for grace exit + $SIG{ALRM} = sub { xexit 0; }; # wait 1s for grace exit alarm(1); }; + # this is used to filter out the incorrect module that xcat command came into # Mainly useful for hierarchical environment on SN - if (defined $req->{'_modname'} ) { + if (defined $req->{'_modname'}) { my $in_modname = undef; if (ref $req->{'_modname'} eq 'ARRAY') { $in_modname = $req->{'_modname'}->[0]; @@ -2080,9 +2154,9 @@ sub dispatch_request { } } - my $onlyone=0; + my $onlyone = 0; if (defined $reqs and (scalar(@{$reqs}) == 1)) { - $onlyone=1; + $onlyone = 1; } foreach (@{$reqs}) { @@ -2091,139 +2165,146 @@ sub dispatch_request { my $child; delete $_->{noderange}; if (ref $_->{'_xcatdest'} and (ref $_->{'_xcatdest'}) eq 'ARRAY') { - _->{'_xcatdest'} = $_->{'_xcatdest'}->[0]; + _->{'_xcatdest'} = $_->{'_xcatdest'}->[0]; } - if ($onlyone and not ($_->{'_xcatdest'} and xCAT::NetworkUtils->thishostisnot($_->{'_xcatdest'}))) { - $SIG{CHLD}='DEFAULT'; + if ($onlyone and not($_->{'_xcatdest'} and xCAT::NetworkUtils->thishostisnot($_->{'_xcatdest'}))) { + $SIG{CHLD} = 'DEFAULT'; # make the plugin process exit directly instead of wait(), this is useful # for the plugin process to exit successfully when it opened some shell subprocesses. $SIG{TERM} = $SIG{INT} = 'DEFAULT'; - "" =~ m/()/; # clear $1 that we may have sitting around + "" =~ m/()/; # clear $1 that we may have sitting around if ($_->{'_xcatdelay'} and not ref $_->{'_xcatdelay'}) { sleep $_->{'_xcatdelay'}; } + # Call the plugin to process the command request # rescanplugins request gets handled directly here in xcatd if ($_->{command}->[0] eq 'rescanplugins') { - scan_plugins($chwritepipe,'1'); + scan_plugins($chwritepipe, '1'); if ($rescanwritepipe) { - store_fd(\$rescanrequest,$rescanwritepipe); + store_fd(\$rescanrequest, $rescanwritepipe); } } else { - xCAT::MsgUtils->trace(0,"D","xcatd: handle request '$_->{command}->[0]' by plugin '$modname''s process_request"); - ${"xCAT_plugin::".$modname."::"}{process_request}->($_,$dispatch_cb,\&do_request); + xCAT::MsgUtils->trace(0, "D", "xcatd: handle request '$_->{command}->[0]' by plugin '$modname''s process_request"); + ${ "xCAT_plugin::" . $modname . "::" }{process_request}->($_, $dispatch_cb, \&do_request); } return; } - if (! socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) { + if (!socketpair($pfd, $parfd, AF_UNIX, SOCK_STREAM, PF_UNSPEC)) { xCAT::MsgUtils->message("S", "ERROR: socketpair: $!"); die; } my $oldfh = select $parfd; - $|=1; + $| = 1; select $pfd; - $|=1; + $| = 1; select $oldfh; - binmode($parfd,':utf8'); - binmode($pfd,':utf8'); + binmode($parfd, ':utf8'); + binmode($pfd, ':utf8'); $child = xCAT::Utils->xfork; + if ($child) { $dispatch_children++; - $dispatched_children{$child}=1; + $dispatched_children{$child} = 1; $child_fdset->add($pfd); close($parfd); next; } unless (defined $child) { - $dispatch_cb->({error=>['Fork failure dispatching request'],errorcode=>[1]}); + $dispatch_cb->({ error => ['Fork failure dispatching request'], errorcode => [1] }); } close($pfd); - $SIG{CHLD}='DEFAULT'; + $SIG{CHLD} = 'DEFAULT'; $dispatch_parentfd = $parfd; - my @prexcatdests=(); - my @xcatdests=(); + my @prexcatdests = (); + my @xcatdests = (); if ($_->{'_xcatdelay'} and not ref $_->{'_xcatdelay'}) { sleep $_->{'_xcatdelay'}; } if (ref($_->{'_xcatdest'}) eq 'ARRAY') { # If array, consider it an 'anycast' operation, broadcast done through dupe - # requests, or an alternative join '&' maybe? - @prexcatdests=@{$_->{'_xcatdest'}}; + # requests, or an alternative join '&' maybe? + @prexcatdests = @{ $_->{'_xcatdest'} }; } else { - @prexcatdests=($_->{'_xcatdest'}); + @prexcatdests = ($_->{'_xcatdest'}); } foreach (@prexcatdests) { if ($_ and /,/) { - push @xcatdests,split /,/,$_; + push @xcatdests, split /,/, $_; } else { - push @xcatdests,$_; + push @xcatdests, $_; } } my $xcatdest; - my $numdests=scalar(@xcatdests); - my $request_satisfied=0; + my $numdests = scalar(@xcatdests); + my $request_satisfied = 0; foreach $xcatdest (@xcatdests) { my $dlock; if ($xcatdest and xCAT::NetworkUtils->thishostisnot($xcatdest)) { + #mkpath("/var/lock/xcat/"); # For now, limit intra-xCAT requests to one at a time, to mitigate DB handle usage #open($dlock,">","/var/lock/xcat/dispatchto_$xcatdest"); #flock($dlock,LOCK_EX); - $ENV{XCATHOST} = ($xcatdest =~ /:/ ? $xcatdest : $xcatdest.":3001" ); - $$progname.=": connection to ".$ENV{XCATHOST}; + $ENV{XCATHOST} = ($xcatdest =~ /:/ ? $xcatdest : $xcatdest . ":3001"); + $$progname .= ": connection to " . $ENV{XCATHOST}; my $errstr; eval { undef $_->{'_xcatdest'}; + # mainly used by SN to filter out the incorrect module that xcat command came into $_->{'_modname'} = $modname; - xCAT::MsgUtils->trace(0,"D","dispatch hierarchical sub-command $_->{command}->[0] to $ENV{XCATHOST}"); - xCAT::Client::submit_request($_,\&dispatch_callback,$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/ca.pem"); + xCAT::MsgUtils->trace(0, "D", "dispatch hierarchical sub-command $_->{command}->[0] to $ENV{XCATHOST}"); + xCAT::Client::submit_request($_, \&dispatch_callback, $xcatdir . "/cert/server-cred.pem", $xcatdir . "/cert/server-cred.pem", $xcatdir . "/cert/ca.pem"); }; if ($@) { - $errstr=$@; + $errstr = $@; } + #unlink("/var/lock/xcat/dispatchto_$xcatdest"); #flock($dlock,LOCK_UN); if ($errstr) { if ($numdests == 1) { - dispatch_callback({error=>["Unable to dispatch hierarchical sub-command to ".$ENV{XCATHOST}.". Error: $errstr. "],errorcode=>[1]}); - xCAT::MsgUtils->message("S","Error dispatching request to ".$ENV{XCATHOST}.": ".$errstr); + dispatch_callback({ error => [ "Unable to dispatch hierarchical sub-command to " . $ENV{XCATHOST} . ". Error: $errstr. " ], errorcode => [1] }); + xCAT::MsgUtils->message("S", "Error dispatching request to " . $ENV{XCATHOST} . ": " . $errstr); } else { - xCAT::MsgUtils->message("S","Error dispatching request to ".$ENV{XCATHOST}.", trying other service nodes: ".$errstr); + xCAT::MsgUtils->message("S", "Error dispatching request to " . $ENV{XCATHOST} . ", trying other service nodes: " . $errstr); } next; } else { - $request_satisfied=1; + $request_satisfied = 1; last; } } else { - $$progname.=": locally executing"; - $SIG{CHLD}='DEFAULT'; + $$progname .= ": locally executing"; + $SIG{CHLD} = 'DEFAULT'; + # make the plugin process exit directly instead of wait(), this is useful # for the plugin process to exit successfully when it opened some shell subprocesses. $SIG{TERM} = $SIG{INT} = 'DEFAULT'; + # Call the plugin to process the command request # rescanplugins request gets handled directly here in xcatd if ($_->{command}->[0] eq 'rescanplugins') { - scan_plugins($chwritepipe,'1'); + scan_plugins($chwritepipe, '1'); if ($rescanwritepipe) { - store_fd(\$rescanrequest,$rescanwritepipe); + store_fd(\$rescanrequest, $rescanwritepipe); } } else { - xCAT::MsgUtils->trace(0,"D","handle command $_->{command}->[0] by plugin $modname 's process_request"); - ${"xCAT_plugin::".$modname."::"}{process_request}->($_,\&dispatch_callback,\&do_request); + xCAT::MsgUtils->trace(0, "D", "handle command $_->{command}->[0] by plugin $modname 's process_request"); + ${ "xCAT_plugin::" . $modname . "::" }{process_request}->($_, \&dispatch_callback, \&do_request); } last; } } - if (!(xCAT::Utils->isServiceNode())) { # not on a service node + if (!(xCAT::Utils->isServiceNode())) { # not on a service node if ($numdests > 1 and not $request_satisfied) { - xCAT::MsgUtils->message("S","Error dispatching a request to all possible service nodes for request"); - dispatch_callback({error=>["Failed to dispatch command to any of the following service nodes: ".join(",",@xcatdests)],errorcode=>[1]}); + xCAT::MsgUtils->message("S", "Error dispatching a request to all possible service nodes for request"); + dispatch_callback({ error => [ "Failed to dispatch command to any of the following service nodes: " . join(",", @xcatdests) ], errorcode => [1] }); } } xexit; } - while (($dispatch_children > 0) and ($child_fdset->count > 0)) { relay_dispatch($child_fdset,$dispatch_cb) } - while (relay_dispatch($child_fdset,$dispatch_cb)) { } # Potentially useless drain. + while (($dispatch_children > 0) and ($child_fdset->count > 0)) { relay_dispatch($child_fdset, $dispatch_cb) } + while (relay_dispatch($child_fdset, $dispatch_cb)) { } # Potentially useless drain. # restore the old signal $SIG{CHLD} = $old_sig_chld; @@ -2231,10 +2312,10 @@ sub dispatch_request { sub do_request { - my $req = shift; - my $second = shift; + my $req = shift; + my $second = shift; my $rsphandler = \&build_response; - my $sock = undef; + my $sock = undef; if ($second) { if (ref($second) eq "CODE") { $rsphandler = $second; @@ -2245,32 +2326,32 @@ sub do_request { #my $sock = shift; # If no sock, will return a response hash - if ($cmd_handlers{$req->{command}->[0]}) { - return plugin_command($req,$sock,$rsphandler); + if ($cmd_handlers{ $req->{command}->[0] }) { + return plugin_command($req, $sock, $rsphandler); } elsif ($req->{command}->[0] eq "noderange" and $req->{noderange}) { my @nodes = noderange($req->{noderange}->[0]); my %resp; if (nodesmissed) { - $resp{warning}="Invalid nodes in noderange:".join ',',nodesmissed; + $resp{warning} = "Invalid nodes in noderange:" . join ',', nodesmissed; } - $resp{serverdone} = [ undef ]; - @{$resp{node}}=@nodes; + $resp{serverdone} = [undef]; + @{ $resp{node} } = @nodes; if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; + $resp{transid} = $req->{transid}->[0]; } if ($sock) { - send_response(\%resp,$sock); + send_response(\%resp, $sock); } else { return (\%resp); } } else { - my %resp=(error=>"Unsupported request"); - $resp{serverdone} = [ undef ]; + my %resp = (error => "Unsupported request"); + $resp{serverdone} = [undef]; if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; + $resp{transid} = $req->{transid}->[0]; } if ($sock) { - send_response(\%resp,$sock); + send_response(\%resp, $sock); } else { return (\%resp); } @@ -2278,7 +2359,8 @@ sub do_request { } sub convey_response { - my $resp=shift; + my $resp = shift; + # TODO: This is where the following will/may happen: # -Track transaction id # -Save output for deferred commands @@ -2287,27 +2369,30 @@ sub convey_response { return; } unless ($resp) { return; } - $pipeexpected=1; + $pipeexpected = 1; + #$resp = XMLout($resp,KeyAttr=>[], NoAttr=>1,RootName=>'xcatresponse'); # sanitize the response, to avoid being killed by non-printable bytes #$resp =~ tr/\011-\177/?/c; # seeing if using utf-8 offloads potential issues to client terminal, it didn't - store_fd($resp,$parent_fd); + store_fd($resp, $parent_fd); yield; # parent must get timeslice anyway before an ack could possibly return my $parsel = new IO::Select; $parsel->add($parent_fd); my $selbits = $parsel->bits; my $rsp; while ($selbits && ($rsp = select($selbits, undef, undef, 5))) { # block up to five seconds - if ($quit) { # Obey quit flag + + if ($quit) { # Obey quit flag xexit 0; } - if ($rsp == 0) { # This means the filedescriptor was removed + if ($rsp == 0) { # This means the filedescriptor was removed last; } - if ($rsp < 0) { # A signal caused select to skip out, do-over + if ($rsp < 0) { # A signal caused select to skip out, do-over next; } + # At this point, the only possibility is a positive return, meaning parent_fd requires attention of some sort $rsp = <$parent_fd>; if ($rsp) { # If data actually came in, last, otherwise, remove it from the IO::Select, but both should amount to the same thing @@ -2322,6 +2407,7 @@ sub convey_response { } sub build_response { + # Handle responses from do_request calls made directly from a plugin # Merge this response into the full response hash. We'll collect all # the responses and ship it back on the return to the plugin. @@ -2332,34 +2418,36 @@ sub build_response { foreach (keys %$resp) { my $subresp = dclone($resp->{$_}); if (ref $subresp eq 'ARRAY') { - push (@{$Main::resps->{$_}}, @{$subresp}); + push(@{ $Main::resps->{$_} }, @{$subresp}); } else { - push (@{$Main::resps->{$_}}, $subresp); + push(@{ $Main::resps->{$_} }, $subresp); } } } sub becomeuser { + # if username and password match, return the new username # otherwise, return undef # TODO PAM? my $passtab = xCAT::Table->new('passwd'); - my $id=shift; - my $pass=shift; + my $id = shift; + my $pass = shift; unless (defined $id and defined $pass) { return undef; } - my $passent=$passtab->getAttribs({key=>'xcat',username=>$id},['password']); + my $passent = $passtab->getAttribs({ key => 'xcat', username => $id }, ['password']); unless ($passent) { return undef; } - $passent=$passent->{password}; - my $encryptedpass = crypt($pass,$passent); + $passent = $passent->{password}; + my $encryptedpass = crypt($pass, $passent); if ($encryptedpass eq $passent) { return $id; - }elsif ($pass eq $passent) { + } elsif ($pass eq $passent) { return $id; } + #if ($passent =~ /^\$(2a|1)\$.*\$/) { # MD5 or Blowfish hash, calculate before comparison #$pass = crypt($pass,$passent); #} # Not bothering with old DES method, for now assume plaintext if not set @@ -2374,129 +2462,139 @@ sub becomeuser { sub wait_db_process { my $retry = 100; my $ready = 0; + # Make sure DB process is ready, so that no direct access - while($retry) { + while ($retry) { if (!xCAT::Utils::is_process_exists($dbmaster)) { sleep 0.1; } else { $ready = 1; last; } - $retry --; + $retry--; } if (!$ready) { - xCAT::MsgUtils->message("S","Error: xcat db process has not been started in 10 seconds."); + xCAT::MsgUtils->message("S", "Error: xcat db process has not been started in 10 seconds."); return -1; } + # use '-create=>1' to make sure nodelist and site object cached. - my $tmptab = xCAT::Table->new('site',-create=>1); - if(!$tmptab) { - xCAT::MsgUtils->message("S","Error: Failed to access site table when monitoring DB process."); + my $tmptab = xCAT::Table->new('site', -create => 1); + if (!$tmptab) { + xCAT::MsgUtils->message("S", "Error: Failed to access site table when monitoring DB process."); return -1; } return 0; } sub populate_site_hash { - %::XCATSITEVALS=(); - my $sitetab = xCAT::Table->new('site',-create=>0); + %::XCATSITEVALS = (); + my $sitetab = xCAT::Table->new('site', -create => 0); unless ($sitetab) { return; } my @records = $sitetab->getAllAttribs(qw/key value/); foreach (@records) { - $::XCATSITEVALS{$_->{key}}=$_->{value}; + $::XCATSITEVALS{ $_->{key} } = $_->{value}; } } sub populate_vpd_hash { - %::XCATVPDHASH=(); - my $vpdtab = xCAT::Table->new('vpd',-create=>0); - unless ($vpdtab) {return;} + %::XCATVPDHASH = (); + my $vpdtab = xCAT::Table->new('vpd', -create => 0); + unless ($vpdtab) { return; } my @entries = $vpdtab->getAllAttribs(qw/node serial mtm/); foreach (@entries) { - unless ($_->{mtm} and $_->{serial}) {next;} - my $mtms = $_->{mtm}."*".$_->{serial}; - push @{$::XCATVPDHASH{$mtms}}, $_->{node}; + unless ($_->{mtm} and $_->{serial}) { next; } + my $mtms = $_->{mtm} . "*" . $_->{serial}; + push @{ $::XCATVPDHASH{$mtms} }, $_->{node}; } } + sub populate_mp_hash { - %::XCATMPHASH=(); - my $mptab = xCAT::Table->new('mp',-create=>0); - unless ($mptab) {return;} + %::XCATMPHASH = (); + my $mptab = xCAT::Table->new('mp', -create => 0); + unless ($mptab) { return; } my @entries = $mptab->getAllAttribs(qw/node nodetype/); foreach (@entries) { if ($_->{nodetype} and $_->{nodetype} eq 'bmc') { - $::XCATMPHASH{$_->{node}}=$_->{nodetype}; + $::XCATMPHASH{ $_->{node} } = $_->{nodetype}; } } } sub send_response { my $response = shift; - my $sock = shift; - my $encode = shift; + my $sock = shift; + my $encode = shift; unless ($encode) { $encode = $globalencode; } if ($encode eq "xml") { my $xml; - if ($response->{xcatresponse}) { # it's an aggregate, keeproot - $xml = XMLout($response,KeyAttr=>[], NoAttr=>1,KeepRoot=>1); + if ($response->{xcatresponse}) { # it's an aggregate, keeproot + $xml = XMLout($response, KeyAttr => [], NoAttr => 1, KeepRoot => 1); } else { - $xml = XMLout($response,RootName => 'xcatresponse',NoAttr=>1); + $xml = XMLout($response, RootName => 'xcatresponse', NoAttr => 1); } $xml =~ tr/\011-\177/?/c; + # ----used for command log start------- my $tmp_xml = $xml; + # ----used for command log end -------- eval { my $rsplen = length($xml); - my $blocks = int($rsplen/4096)-1; - if ($rsplen%4096) { + my $blocks = int($rsplen / 4096) - 1; + if ($rsplen % 4096) { $blocks += 1; } - foreach (0..$blocks) { + foreach (0 .. $blocks) { do { - syswrite($sock,$xml,4096,$_*4096); - } while (($! == EAGAIN) or ($! == ECHILD)); + syswrite($sock, $xml, 4096, $_ * 4096); + } while (($! == EAGAIN) or ($! == ECHILD)); } }; # ----used for command log start------- - my $cmdlog_xml=""; + my $cmdlog_xml = ""; $tmp_xml =~ s/\e/xxxxESCxxxx/g; - $cmdlog_xml .= $tmp_xml.""; - my $cmdlog_rsp = XMLin($cmdlog_xml,SuppressEmpty=>undef,ForceArray=>1); + $cmdlog_xml .= $tmp_xml . ""; + my $cmdlog_rsp = XMLin($cmdlog_xml, SuppressEmpty => undef, ForceArray => 1); cmdlog_collectlog($cmdlog_rsp); + # ----used for command log end -------- } elsif ($encode eq "storable") { if ($response->{xcatresponse}) { $response = $response->{xcatresponse}; } - nstore_fd($response,$sock); + nstore_fd($response, $sock); $sock->flush(); # otherwise, the response might actually get deferred until after the close_notify, crazy huh? } } + sub get_request { - my $sock = shift; - my $encode = shift; + my $sock = shift; + my $encode = shift; my $request = shift; if ($encode eq "xml") { my $readtry = 0; while ((!$request) || ($request !~ m/<\/xcatrequest>/)) { if ($readtry > 10) { + # if retry too much, sleep for a while and try again # otherwise it will use too much cpu sleep 1; $readtry = 0; } - my $flags=fcntl($sock,F_GETFL,0); + my $flags = fcntl($sock, F_GETFL, 0); $flags |= O_NONBLOCK; # we want sysread to bail on us, select seems to be evil to us still.. - fcntl($sock,F_SETFL,$flags); + fcntl($sock, F_SETFL, $flags); my $bytesread; my $line = ''; - do { $bytesread=sysread($sock,$line,65536,length($line)) } while ($bytesread); - if (length($line)==0) { + do { $bytesread = sysread($sock, $line, 65536, length($line)) } while ($bytesread); + if (length($line) == 0) { + if (not defined $bytesread and ($! == EAGAIN or $! == ECHILD)) { + # retry when an error happens # ECHILD makes no sense, but some platform does it $readtry++; @@ -2504,9 +2602,9 @@ sub get_request { } return undef; } - $flags=fcntl($sock,F_GETFL,0); - $flags &= ~O_NONBLOCK; # now we want *print* to be blocking IO - fcntl($sock,F_SETFL,$flags); + $flags = fcntl($sock, F_GETFL, 0); + $flags &= ~O_NONBLOCK; # now we want *print* to be blocking IO + fcntl($sock, F_SETFL, $flags); $request .= $line; # check the validity of the request message @@ -2515,22 +2613,23 @@ sub get_request { return undef; } } - return eval { XMLin($request, SuppressEmpty=>undef,ForceArray=>1) }; + return eval { XMLin($request, SuppressEmpty => undef, ForceArray => 1) }; } elsif ($encode eq "storable") { - my $return = eval { fd_retrieve($sock); }; # suppres end of stream err + my $return = eval { fd_retrieve($sock); }; # suppres end of stream err return $return; } } sub service_connection { - my $sock = shift; - my $peername = shift; - my $peerhost = shift; - my $peerfqdn = shift; + my $sock = shift; + my $peername = shift; + my $peerhost = shift; + my $peerfqdn = shift; my $peerhostorg = shift; - my $peerport = $sock->peerport; - my %tables=(); + my $peerport = $sock->peerport; + my %tables = (); + # some paranoid measures could reduce a third party abusing stage3 image to attempting to get USER/PASS for BMCs: # -Well, minimally, ignore requests if requesting node is not in spconfig mode (stage3) # -Option to generate a random password per 'getipmi' request. This reduces the exposure to a D.O.S. hopefully @@ -2539,75 +2638,76 @@ sub service_connection { $SIG{ALRM} = sub { $timedout = 1; die; }; my $evalpid = $$; - eval { # REMOVEEVALFORDEBUG + eval { # REMOVEEVALFORDEBUG my $request; - my $req=undef; + my $req = undef; my $line; my $clientsel = new IO::Select; $clientsel->add($sock); while (1) { unless ($clientsel->can_read(15)) { last; } # don't let an unresponsive client hold us up - my $line = <$sock>; # grab one line, check for mode... - # Commenting out, could be a remote exceution path - # consider sereal one day - #if ($line and $line =~ /^xcatencoding: (.*)/) { - #unless ($supported_encodes{$1}) { - #print $sock "Unsupported encoding $1\n"; - #last; - #} - #print $sock "Encoding accepted\n"; - #$globalencode=$1; - #$line = ""; - #} - $req = get_request($sock,$globalencode,$line); + my $line = <$sock>; # grab one line, check for mode... + # Commenting out, could be a remote exceution path + # consider sereal one day + #if ($line and $line =~ /^xcatencoding: (.*)/) { + #unless ($supported_encodes{$1}) { + #print $sock "Unsupported encoding $1\n"; + #last; + #} + #print $sock "Encoding accepted\n"; + #$globalencode=$1; + #$line = ""; + #} + $req = get_request($sock, $globalencode, $line); unless ($req) { last; } # ----used for command log start---------- - my ($sec,$min,$hour,$mday,$mon,$year) = localtime(time()); + my ($sec, $min, $hour, $mday, $mon, $year) = localtime(time()); $year += 1900; - $mon += 1; - my $strmon = ($mon>9? $mon:"0".$mon); - my $strmday = ($mday>9? $mday:"0".$mday); - my $strhour = ($hour>9? $hour:"0".$hour); - my $strmin = ($min>9? $min:"0".$min); - my $strsec = ($sec>9? $sec:"0".$sec); + $mon += 1; + my $strmon = ($mon > 9 ? $mon : "0" . $mon); + my $strmday = ($mday > 9 ? $mday : "0" . $mday); + my $strhour = ($hour > 9 ? $hour : "0" . $hour); + my $strmin = ($min > 9 ? $min : "0" . $min); + my $strsec = ($sec > 9 ? $sec : "0" . $sec); $cmdlog_alllog .= "[Date] $year-$strmon-$strmday $strhour:$strmin:$strsec\n"; #print ">>>>>>>cmdlog request dumper>>>>>>>>\n"; #print Dumper $req; - $cmdlog_alllog .= "[ClientType] ".$req->{clienttype}->[0]." \n"; - $cmdlog_alllog .= "[Request] ".$req->{command}->[0]." "; - if(exists($req->{noderange})){ - foreach my $node (@{$req->{noderange}}) { - $cmdlog_alllog .= $node.","; + $cmdlog_alllog .= "[ClientType] " . $req->{clienttype}->[0] . " \n"; + $cmdlog_alllog .= "[Request] " . $req->{command}->[0] . " "; + if (exists($req->{noderange})) { + foreach my $node (@{ $req->{noderange} }) { + $cmdlog_alllog .= $node . ","; } $cmdlog_alllog =~ s/(.+),$/$1 /g; } - if(exists($req->{arg})){ - foreach my $arg (@{$req->{arg}}) { - if($arg =~ /[^A-Za-z0-9.-]/){ + if (exists($req->{arg})) { + foreach my $arg (@{ $req->{arg} }) { + if ($arg =~ /[^A-Za-z0-9.-]/) { my $tmparg = $arg; $tmparg =~ s/'/'\\''/g; - $cmdlog_alllog .= "'".$tmparg."' "; - }else{ - $cmdlog_alllog .= $arg." "; + $cmdlog_alllog .= "'" . $tmparg . "' "; + } else { + $cmdlog_alllog .= $arg . " "; } } } $cmdlog_alllog .= "\n[Response]\n"; + # ----used for command log end---------- - { # TODO: find closing brace.. - # first change peername on 'becomeuser' tag if present and valid + { # TODO: find closing brace.. + # first change peername on 'becomeuser' tag if present and valid if (defined $req->{becomeuser}) { - $peername=becomeuser($req->{becomeuser}->[0]->{username}->[0], + $peername = becomeuser($req->{becomeuser}->[0]->{username}->[0], $req->{becomeuser}->[0]->{password}->[0]); unless (defined $peername) { - my $resp={error=>["Authentication failure"],errorcode=>[1]}; - $resp->{serverdone}=[ undef ] ; - send_response($resp,$sock); + my $resp = { error => ["Authentication failure"], errorcode => [1] }; + $resp->{serverdone} = [undef]; + send_response($resp, $sock); return; } delete($req->{becomeuser}); # Remove it to keep it from view @@ -2615,34 +2715,37 @@ sub service_connection { # If the request is to aquire a token for a specific account if (defined $req->{gettoken}) { + # authencitate the username:password - $peername=becomeuser($req->{gettoken}->[0]->{username}->[0], + $peername = becomeuser($req->{gettoken}->[0]->{username}->[0], $req->{gettoken}->[0]->{password}->[0]); my $resp; if ($peername) { + # for a valid account, get a token my ($tokenid, $exptime) = xCAT::xcatd->gettoken($req); - my ($sec,$min,$hour,$mday,$mon,$year) = localtime($exptime); + my ($sec, $min, $hour, $mday, $mon, $year) = localtime($exptime); $year += 1900; - $mon += 1; + $mon += 1; my $htime = "$year-$mon-$mday $hour:$min:$sec"; - $resp = {data=>[{token => [{id => $tokenid, expire => $htime}]}]}; + $resp = { data => [ { token => [ { id => $tokenid, expire => $htime } ] } ] }; } else { - $resp={error=>["Authentication failure"],errorcode=>[1]}; + $resp = { error => ["Authentication failure"], errorcode => [1] }; } - $resp->{serverdone}=[ undef ] ; - send_response($resp,$sock); + $resp->{serverdone} = [undef]; + send_response($resp, $sock); return; } # If user trying to use 'token' to authenticate if (defined $req->{tokens}) { + # get the valid user name by the token id $peername = xCAT::xcatd->verifytoken($req); unless (defined $peername) { - my $resp={error=>["Authentication failure"],errorcode=>[1]}; - $resp->{serverdone}=[ undef ] ; - send_response($resp,$sock); + my $resp = { error => ["Authentication failure"], errorcode => [1] }; + $resp->{serverdone} = [undef]; + send_response($resp, $sock); return; } delete($req->{tokenid}); @@ -2650,134 +2753,136 @@ sub service_connection { # we have a full request.. #printf $request."\n"; - $request=""; - if (xCAT::xcatd->validate($peername,$peerhost,$req,$peerhostorg,\@deferredmsgargs)) { - $req->{'_xcat_authname'} = [$peername]; + $request = ""; + if (xCAT::xcatd->validate($peername, $peerhost, $req, $peerhostorg, \@deferredmsgargs)) { + $req->{'_xcat_authname'} = [$peername]; $req->{'_xcat_clienthost'} = [$peerhost]; $req->{'_xcat_clientfqdn'} = [$peerfqdn]; - $req->{'_xcat_clientport'}= [$peerport]; - $$progname="xcatd SSL: ".$req->{command}->[0]; + $req->{'_xcat_clientport'} = [$peerport]; + $$progname = "xcatd SSL: " . $req->{command}->[0]; if ($req->{noderange} && defined($req->{noderange}->[0])) { - $$progname .= " to ".$req->{noderange}->[0]; + $$progname .= " to " . $req->{noderange}->[0]; } - if($peerhost){ - $$progname .= " for ".($peername ? $peername ."@".$peerhost : $peerhost); + if ($peerhost) { + $$progname .= " for " . ($peername ? $peername . "@" . $peerhost : $peerhost); } - my $debuglog= "xcatd: open new process : $$progname"; - xCAT::MsgUtils->trace(0,"D","$debuglog"); + my $debuglog = "xcatd: open new process : $$progname"; + xCAT::MsgUtils->trace(0, "D", "$debuglog"); if ($req->{command}->[0] eq "authcheck") { # provide a method for UI to verify a user without actually requesting action my $resp; if ($peername or $peername eq "0") { - $resp->{username}=[$peername]; - $resp->{data}=["Authenticated"]; + $resp->{username} = [$peername]; + $resp->{data} = ["Authenticated"]; } else { - $resp->{data}=["Unauthenticated"]; + $resp->{data} = ["Unauthenticated"]; } - $resp->{serverdone}=[ undef ]; - send_response($resp,$sock); - } elsif ($cmd_handlers{$req->{command}->[0]}) { - plugin_command($req,$sock,\&convey_response); + $resp->{serverdone} = [undef]; + send_response($resp, $sock); + } elsif ($cmd_handlers{ $req->{command}->[0] }) { + plugin_command($req, $sock, \&convey_response); } elsif ($req->{command}->[0] eq "noderange" and $req->{noderange}) { xCAT::NodeRange::retain_cache(0); # if the request has a 'noderange' element, take the performance hit for the sake of freshness my @nodes = noderange($req->{noderange}->[0]); my %resp; if (nodesmissed) { - $resp{warning}="Invalid nodes in noderange:".join ',',nodesmissed; + $resp{warning} = "Invalid nodes in noderange:" . join ',', nodesmissed; } - $resp{serverdone} = [ undef ]; - @{$resp{node}}=@nodes; + $resp{serverdone} = [undef]; + @{ $resp{node} } = @nodes; if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; + $resp{transid} = $req->{transid}->[0]; } - send_response(\%resp,$sock); + send_response(\%resp, $sock); next; - } elsif ($req->{command}->[0] eq "extnoderange" and $req->{noderange}) { # This is intended for the UIs to build trees - # as this would be part of a highly dynamic construct, it has a shortcut here to minimize server load - my $subgroups=0; - if ($req->{arg} and grep /subgroups/,@{$req->{arg}}) { - $subgroups=1; + } elsif ($req->{command}->[0] eq "extnoderange" and $req->{noderange}) { # This is intended for the UIs to build trees + # as this would be part of a highly dynamic construct, it has a shortcut here to minimize server load + my $subgroups = 0; + if ($req->{arg} and grep /subgroups/, @{ $req->{arg} }) { + $subgroups = 1; } - my %resp=%{extnoderange($req->{noderange}->[0],{intersectinggroups=>$subgroups})}; - $resp{serverdone}=[ undef ]; - send_response(\%resp,$sock); + my %resp = %{ extnoderange($req->{noderange}->[0], { intersectinggroups => $subgroups }) }; + $resp{serverdone} = [undef]; + send_response(\%resp, $sock); next; } else { - my %resp=(error=>"Unsupported request"); - $resp{serverdone} = [ undef ]; + my %resp = (error => "Unsupported request"); + $resp{serverdone} = [undef]; if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; + $resp{transid} = $req->{transid}->[0]; } - xCAT::MsgUtils->message("S","Unsupported request: peername=$peername, peerhost=$peerhost,peerfqdn=$peerfqdn,peerport=$peerport, command=".$req->{command}->[0]); - send_response(\%resp,$sock); + xCAT::MsgUtils->message("S", "Unsupported request: peername=$peername, peerhost=$peerhost,peerfqdn=$peerfqdn,peerport=$peerport, command=" . $req->{command}->[0]); + send_response(\%resp, $sock); next; } } else { - my %resp=(error=>"Permission denied for request"); - $resp{serverdone} = [ undef ]; + my %resp = (error => "Permission denied for request"); + $resp{serverdone} = [undef]; if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; + $resp{transid} = $req->{transid}->[0]; } - xCAT::MsgUtils->message("S","Permission denied for request: peername=$peername, peerhost=$peerhost,peerfqdn=$peerfqdn,peerport=$peerport command= ".$req->{command}->[0]); - send_response(\%resp,$sock); + xCAT::MsgUtils->message("S", "Permission denied for request: peername=$peername, peerhost=$peerhost,peerfqdn=$peerfqdn,peerport=$peerport command= " . $req->{command}->[0]); + send_response(\%resp, $sock); next; } } } - }; # REMOVEEVALFORDEBUG - if ($@) { # The eval statement caught a program bug.. + }; # REMOVEEVALFORDEBUG + if ($@) { # The eval statement caught a program bug.. if ($@ =~ /^SIGPIPE/) { - xCAT::MsgUtils->message("S","xcatd: Unexpected client disconnect"); + xCAT::MsgUtils->message("S", "xcatd: Unexpected client disconnect"); if ($sock) { eval { - send_response({error=>"Generic PIPE error occurred. $@"},$sock); + send_response({ error => "Generic PIPE error occurred. $@" }, $sock); }; } } elsif ($@ =~ /Client abort requested/) { } else { - my $errstr="A fatal error was encountered, the following information may help identify a bug: $@"; + my $errstr = "A fatal error was encountered, the following information may help identify a bug: $@"; chomp($errstr); - xCAT::MsgUtils->message("S","xcatd: possible BUG encountered by xCAT TCP service: ".$@); + xCAT::MsgUtils->message("S", "xcatd: possible BUG encountered by xCAT TCP service: " . $@); if ($sock) { eval { - send_response({error=>$errstr},$sock); + send_response({ error => $errstr }, $sock); }; } } } elsif ($evalpid ne $$) { - xCAT::MsgUtils->message("S","A child jumped to where it should never ever be, this shouldn't be possible, please report this bug"); + xCAT::MsgUtils->message("S", "A child jumped to where it should never ever be, this shouldn't be possible, please report this bug"); + # The folowing corrupts the SSL state preventing any further output by the parent. # A bug triggering this absolutely # needs to fixed. With the current code layout it is either trash valid data that could have been or # risk user missing data # without knowing it. It's likely possible to rearchitect to change that, but as it stands it really # should be no longer possible to hit this condition. - send_response({error=>"A child jumped to where it should never ever be, this shouldn't be possible, please report this bug"},$sock); + send_response({ error => "A child jumped to where it should never ever be, this shouldn't be possible, please report this bug" }, $sock); } # ----used for command log start------- cmdlog_submitlog(); + # ----used for command log end--------- - $SIG{ALRM}= sub { xCAT::MsgUtils->message("S","$$ failed shutting down"); die;}; + $SIG{ALRM} = sub { xCAT::MsgUtils->message("S", "$$ failed shutting down"); die; }; alarm(10); foreach (keys %tables) { $tables{$_}->commit; } - $sock->close(SSL_fast_shutdown=>1); + $sock->close(SSL_fast_shutdown => 1); if ($timedout == 1) { - printf ("Client timeout"); + printf("Client timeout"); } } sub relay_fds { # Relays file descriptors from pipes to children to the SSL socket - my $fds = shift; - my $replyqueue=shift; - my $goneclient=0; - my $collate = ( scalar @_ > 0 ? shift : 0); - my @readyset = $fds->can_read(1); + my $fds = shift; + my $replyqueue = shift; + my $goneclient = 0; + my $collate = (scalar @_ > 0 ? shift : 0); + my @readyset = $fds->can_read(1); my $rfh; my $rc = @readyset; my $text; @@ -2785,7 +2890,7 @@ sub relay_fds { # Relays file descriptors from pipes to children to the SSL sock # A PIPE signal might be received when run fd_retrieve from the plugin sub processors # This mostly happens when there are multiple plugins are called for certain command # So spkit the pipe error handle - $pipeexpected=1; + $pipeexpected = 1; foreach $rfh (@readyset) { # go through each child, extract a complete, atomic message my $line; my $resp; @@ -2796,7 +2901,7 @@ sub relay_fds { # Relays file descriptors from pipes to children to the SSL sock $fds->remove($rfh); close($rfh); } else { - push @$replyqueue,$resp; + push @$replyqueue, $resp; print $rfh "nfin\n"; } } @@ -2804,16 +2909,16 @@ sub relay_fds { # Relays file descriptors from pipes to children to the SSL sock my $subselect = new IO::Select; $subselect->add($rin); my $subdata; - my $clientintr = get_request($rin,$globalencode,""); + my $clientintr = get_request($rin, $globalencode, ""); unless ($clientintr) { next; } if ($clientintr->{abortcommand}->[0]) { - $pipeexpected=1; + $pipeexpected = 1; print "Aborting..."; foreach (keys %plugin_children) { print "Sending INT to $_\n"; - kill 'INT', $_; + kill 'INT', $_; kill 'TERM', $_; } foreach my $cin ($fds->handles) { @@ -2826,6 +2931,7 @@ sub relay_fds { # Relays file descriptors from pipes to children to the SSL sock # ----used for command log start------- $cmdlog_alllog .= "Client abort requested\n"; cmdlog_submitlog(); + # ----used for command log end--------- exit(0); @@ -2841,16 +2947,16 @@ sub relay_fds { # Relays file descriptors from pipes to children to the SSL sock # Enable the trace of subroutine calling. # Replace the original subroutine with a trace added subroutine to output more debug trace -sub enable_callingtrace{ - my $enableall = 0; # if $enableall=1, enable trace for all the functions of xcat - my @pluginfuncs = (); # function list that will be enabled for plugins - my @xcatdfuncs = (); # function list that will be enabled for xcatd +sub enable_callingtrace { + my $enableall = 0; # if $enableall=1, enable trace for all the functions of xcat + my @pluginfuncs = (); # function list that will be enabled for plugins + my @xcatdfuncs = (); # function list that will be enabled for xcatd # call the subroutine scan_plugins to fill the symbol table #scan_plugins(); # Backup the trace log - my ($sec,$min,$hour,$mday,$mon,$year) = localtime(); + my ($sec, $min, $hour, $mday, $mon, $year) = localtime(); $year -= 100; $mon += 1; my $time = sprintf "%02s%02s%02s%02s%02s%02s", $year, $mon, $mday, $hour, $min, $sec; @@ -2863,7 +2969,7 @@ sub enable_callingtrace{ # Read the subroutine list from the configuration file if (-f "/tmp/xcatcallingtrace.cfg") { - if (! open (FUNLIST, "message("SL", "Enable subroutine calling trace failed: cannot open /tmp/xcatcallingtrace.cfg"); xCAT::MsgUtils->stop_logging(); return 1; @@ -2871,18 +2977,19 @@ sub enable_callingtrace{ my $cfg = ; chomp($cfg); my @funlist; - if (-f $cfg) { # Specified a configuration file - if (! open (CFG, "<$cfg")) { + if (-f $cfg) { # Specified a configuration file + if (!open(CFG, "<$cfg")) { xCAT::MsgUtils->message("SL", "Enable subroutine calling trace failed: cannot open $cfg"); xCAT::MsgUtils->stop_logging(); return 1; - } else { # read the configuration file + } else { # read the configuration file while () { push @funlist, $_; } - close (CFG); + close(CFG); } } else { + # Specified the function list # The format of the function list should be package(func1,func2,...),package(func1,func2,...) push @funlist, split /\|/, $cfg; @@ -2890,13 +2997,13 @@ sub enable_callingtrace{ # Parse the function list foreach (@funlist) { - if (/(.*::.*)\((.*)\)/) { # if the format is xCAT::plugin(f1,f2) + if (/(.*::.*)\((.*)\)/) { # if the format is xCAT::plugin(f1,f2) my $pkg = $1; my @funcs = split /,/, $2; foreach (@funcs) { chomp; s/^\s*//; - push @pluginfuncs, "\*".$pkg."::".$_; + push @pluginfuncs, "\*" . $pkg . "::" . $_; } } else { # if the format is f1,f2, only for the functions in the xcatd s/^\s*\(//; @@ -2905,11 +3012,11 @@ sub enable_callingtrace{ foreach (@funcs) { chomp; s/^\s*//; - push @xcatdfuncs, "\*main::".$_; + push @xcatdfuncs, "\*main::" . $_; } } } - close (FUNLIST); + close(FUNLIST); } else { $enableall = 1; } @@ -2917,26 +3024,29 @@ sub enable_callingtrace{ no strict 'refs'; my @debugfuns = (); + # Get the functions of xcatd - my $xcatdpath = $::XCATROOT."/sbin/xcatd"; - if (! open (XCATDLINES, "<$xcatdpath")) { + my $xcatdpath = $::XCATROOT . "/sbin/xcatd"; + if (!open(XCATDLINES, "<$xcatdpath")) { xCAT::MsgUtils->message("SL", "Enable subroutine calling trace failed: cannot open $xcatdpath"); } else { my @sub_in_xcatd; + # Get all the name of subroutines except the xxx_callingtrace while () { if (/^\s*sub\s+([^\s]*)/) { - if (! /enable_callingtrace|disable_callingtrace|add_callingtrace/) { + if (!/enable_callingtrace|disable_callingtrace|add_callingtrace/) { push @sub_in_xcatd, $1; } } } close(XCATDLINES); + # Get all the symbols from the %main:: space foreach my $fun (keys %main::) { my $symfun = $main::{$fun}; - if (($symfun =~ /^\*/) # must be a symbol - && *{$symfun}{CODE} # must be a subroutine + if (($symfun =~ /^\*/) # must be a symbol + && *{$symfun}{CODE} # must be a subroutine && grep (/\Q$fun\E/, @sub_in_xcatd) # must be defined in the xcatd && ($enableall || grep (/\Q$symfun\E/, @xcatdfuncs))) { # all or configured in the configuration file push @debugfuns, $symfun; @@ -2946,41 +3056,46 @@ sub enable_callingtrace{ # Get the functions of xCAT plugins foreach my $plugin (\%xCAT::, \%xCAT_plugin::) { + # Get the path of the plugins my $path = ""; foreach (keys %$plugin) { my $glob = $plugin->{$_}; if ($glob =~ /\*([^:]*)::/) { - $path = $::XCATROOT."/lib/perl/$1/"; + $path = $::XCATROOT . "/lib/perl/$1/"; last; } } + # For each plugin moduel, search the matched functions foreach my $xcatplugin (keys %$plugin) { if ($xcatplugin =~ /[^\*].*::$/) { + # get the subroutines in the plugin file my $pluginfile = $xcatplugin; $pluginfile =~ s/:://; + # Ignore to enable the trace for the subroutines in the MsgUtils if ($pluginfile eq "MsgUtils") { next; } - my $module_file = $path.$pluginfile.".pm"; - my @sub_in_pm = (); + my $module_file = $path . $pluginfile . ".pm"; + my @sub_in_pm = (); if (-r $module_file) { - open (LINES, "<$module_file") or last; + open(LINES, "<$module_file") or last; while () { if (/^\s*sub\s+([^\s]*)/) { push @sub_in_pm, $1; } } - close (LINES); + close(LINES); } + # Search the symbol from the space of plugin - foreach my $fun (keys %{$plugin->{$xcatplugin}}) { + foreach my $fun (keys %{ $plugin->{$xcatplugin} }) { my $symfun = $plugin->{$xcatplugin}{$fun}; - if ($symfun =~ /^\*/ # must be a symbol - && *{$symfun}{CODE} # must be a subroutine + if ($symfun =~ /^\*/ # must be a symbol + && *{$symfun}{CODE} # must be a subroutine && grep (/\Q$fun\E/, @sub_in_pm) # must be defined in the plugin modules && ($enableall || grep (/\Q$symfun\E/, @pluginfuncs))) { # all or configured in the configuration file push @debugfuns, $symfun; @@ -2996,12 +3111,13 @@ sub enable_callingtrace{ my ($funname, $orig) = @_; sub { my $args = Dumper(@_); + #$args =~ s{\A\$VAR\d+\s*=\s*}{}; my $callstack = Carp::longmess; # write the trace log to the trace file print $::LOG_FILE_HANDLE "\n***************Calling of subroutine $funname***************\n"; - print $::LOG_FILE_HANDLE localtime()."\n"; + print $::LOG_FILE_HANDLE localtime() . "\n"; print $::LOG_FILE_HANDLE "Arguments: \n$args\n"; print $::LOG_FILE_HANDLE "Calling stack: \n $callstack\n"; &$orig; @@ -3012,18 +3128,23 @@ sub enable_callingtrace{ print $::LOG_FILE_HANDLE "##########Enabled the calling trace for: ###########\n"; foreach my $debugfun (@debugfuns) { print $::LOG_FILE_HANDLE " $debugfun\n"; - if (defined ($::DEBUG_FUN{"$debugfun"}{'debug'})) { + if (defined($::DEBUG_FUN{"$debugfun"}{'debug'})) { + # if the trace added subroutine has been defined *{"$debugfun"} = $::DEBUG_FUN{"$debugfun"}{'debug'}; + #print " => $::DEBUG_FUN{$debugfun}{debug}\n"; } else { my $oldfun = *{$debugfun}{CODE}; + # Bakcup the original subroutine $::DEBUG_FUN{"$debugfun"}{'orig'} = $oldfun; + #print "$debugfun".": $::DEBUG_FUN{$debugfun}{orig}"; # otherise creating a trace added subroutine from scratch *{"$debugfun"} = add_callingtrace($debugfun, $oldfun); $::DEBUG_FUN{"$debugfun"}{'debug'} = *{"$debugfun"}{CODE}; + #print " => $::DEBUG_FUN{$debugfun}{debug}\n"; } } @@ -3058,19 +3179,19 @@ sub disable_callingtrace { =cut # -------------------------------------------------------------------------------- -sub cmdlog_collectlog(){ - my $rsponse= shift; - my $rsp_log=""; +sub cmdlog_collectlog() { + my $rsponse = shift; + my $rsp_log = ""; - if((exists($rsponse->{xcatresponse}->[0]->{serverdone})) && (! exists($rsponse->{xcatresponse}->[0]->{error}))){return 0;} + if ((exists($rsponse->{xcatresponse}->[0]->{serverdone})) && (!exists($rsponse->{xcatresponse}->[0]->{error}))) { return 0; } my $rsp; - if(exists($rsponse->{xcatresponse})){ + if (exists($rsponse->{xcatresponse})) { $rsp = $rsponse->{xcatresponse}; - }else{ + } else { push @{$rsp}, $rsponse; } - if (ref($rsp) ne 'ARRAY') {return 0;} - if (scalar(@$rsp) == 0) {return 0;} + if (ref($rsp) ne 'ARRAY') { return 0; } + if (scalar(@$rsp) == 0) { return 0; } foreach my $tmprsp (@{$rsp}) { $rsp = $tmprsp; @@ -3079,12 +3200,12 @@ sub cmdlog_collectlog(){ # Handle errors if ($rsp->{error}) { if (ref($rsp->{error}) eq 'ARRAY') { - foreach my $text (@{$rsp->{error}}) { + foreach my $text (@{ $rsp->{error} }) { if (defined($text)) { if ($rsp->{NoErrorPrefix}) { - $rsp_log.=$text; + $rsp_log .= $text; } else { - $rsp_log.="Error: $text\n"; + $rsp_log .= "Error: $text\n"; } } } @@ -3092,9 +3213,9 @@ sub cmdlog_collectlog(){ else { if (defined($rsp->{error})) { if ($rsp->{NoErrorPrefix}) { - $rsp_log.= $rsp->{error}."\n"; + $rsp_log .= $rsp->{error} . "\n"; } else { - $rsp_log.= "Error: ".$rsp->{error}."\n"; + $rsp_log .= "Error: " . $rsp->{error} . "\n"; } } } @@ -3102,22 +3223,22 @@ sub cmdlog_collectlog(){ if ($rsp->{warning}) { if (ref($rsp->{warning}) eq 'ARRAY') { - foreach my $text (@{$rsp->{warning}}) { - if (defined ($text)) { + foreach my $text (@{ $rsp->{warning} }) { + if (defined($text)) { if ($rsp->{NoWarnPrefix}) { - $rsp_log.= "$text\n"; + $rsp_log .= "$text\n"; } else { - $rsp_log.= "Warning: $text\n"; + $rsp_log .= "Warning: $text\n"; } } } } else { - if (defined ($rsp->{warning})) { + if (defined($rsp->{warning})) { if ($rsp->{NoWarnPrefix}) { - $rsp_log.= $rsp->{warning}."\n"; + $rsp_log .= $rsp->{warning} . "\n"; } else { - $rsp_log.= "Warning: ".$rsp->{warning}."\n"; + $rsp_log .= "Warning: " . $rsp->{warning} . "\n"; } } } @@ -3125,35 +3246,35 @@ sub cmdlog_collectlog(){ if ($rsp->{info}) { if (ref($rsp->{info}) eq 'ARRAY') { - foreach my $text (@{$rsp->{info}}) { + foreach my $text (@{ $rsp->{info} }) { if (defined($text)) { - $rsp_log.= "$text\n"; + $rsp_log .= "$text\n"; } } - }else{ - if (defined ($rsp->{info})) { - $rsp_log.= $rsp->{info}."\n"; + } else { + if (defined($rsp->{info})) { + $rsp_log .= $rsp->{info} . "\n"; } } } if ($rsp->{sinfo}) { if (ref($rsp->{sinfo}) eq 'ARRAY') { - foreach my $text (@{$rsp->{sinfo}}) { + foreach my $text (@{ $rsp->{sinfo} }) { if (defined($text)) { - $rsp_log.= "$text "; + $rsp_log .= "$text "; } } - }else{ + } else { if (defined($rsp->{sinfo})) { - $rsp_log.= $rsp->{sinfo}." "; + $rsp_log .= $rsp->{sinfo} . " "; } } } # Handle {node} structure - my $errflg=0; - my $nodes=($rsp->{node}); + my $errflg = 0; + my $nodes = ($rsp->{node}); unless (ref $nodes eq 'ARRAY') { $nodes = [$nodes]; } @@ -3162,108 +3283,108 @@ sub cmdlog_collectlog(){ foreach $node (@$nodes) { my $desc; if (ref($node->{name}) eq 'ARRAY') { - $desc=$node->{name}->[0]; + $desc = $node->{name}->[0]; } else { - $desc=$node->{name}; + $desc = $node->{name}; } if ($node->{error}) { if (defined($node->{error}->[0])) { - $desc.=": Error: ".$node->{error}->[0]; - $errflg=1; + $desc .= ": Error: " . $node->{error}->[0]; + $errflg = 1; } } if ($node->{warning}) { if (defined($node->{warning}->[0])) { - $desc.=": Warning: ".$node->{warning}->[0]; - $errflg=1; + $desc .= ": Warning: " . $node->{warning}->[0]; + $errflg = 1; } } if ($node->{data}) { if (ref(\($node->{data})) eq 'SCALAR') { if (defined($node->{data})) { - $desc=$desc.": ".$node->{data}; + $desc = $desc . ": " . $node->{data}; } } elsif (ref($node->{data}) eq 'HASH') { if ($node->{data}->{desc}) { if (ref($node->{data}->{desc}) eq 'ARRAY') { if (defined($node->{data}->{desc}->[0])) { - $desc=$desc.": ".$node->{data}->{desc}->[0]; + $desc = $desc . ": " . $node->{data}->{desc}->[0]; } } else { if (defined($node->{data}->{desc})) { - $desc=$desc.": ".$node->{data}->{desc}; + $desc = $desc . ": " . $node->{data}->{desc}; } } } if ($node->{data}->{contents}) { if (ref($node->{data}->{contents}) eq 'ARRAY') { if (defined($node->{data}->{contents}->[0])) { - $desc="$desc: ".$node->{data}->{contents}->[0]; + $desc = "$desc: " . $node->{data}->{contents}->[0]; } - }else{ + } else { if (defined($node->{data}->{contents})) { - $desc="$desc: ".$node->{data}->{contents}; + $desc = "$desc: " . $node->{data}->{contents}; } } } - }elsif (ref(\($node->{data}->[0])) eq 'SCALAR') { + } elsif (ref(\($node->{data}->[0])) eq 'SCALAR') { if (defined($node->{data}->[0])) { - $desc=$desc.": ".$node->{data}->[0]; + $desc = $desc . ": " . $node->{data}->[0]; } - }else{ + } else { if ($node->{data}->[0]->{desc}) { if (defined($node->{data}->[0]->{desc}->[0])) { - $desc=$desc.": ".$node->{data}->[0]->{desc}->[0]; + $desc = $desc . ": " . $node->{data}->[0]->{desc}->[0]; } } if ($node->{data}->[0]->{contents}) { if (defined($node->{data}->[0]->{contents}->[0])) { - $desc="$desc: ".$node->{data}->[0]->{contents}->[0]; + $desc = "$desc: " . $node->{data}->[0]->{contents}->[0]; } } } } if ($desc) { if ($errflg == 1) { - $rsp_log.= "$desc\n"; - }else{ - $rsp_log.= "$desc\n"; + $rsp_log .= "$desc\n"; + } else { + $rsp_log .= "$desc\n"; } } } } # Handle {data} structure with no nodes - foreach my $mykey ( keys %{$rsp} ) { - if ($mykey ne "data") {next;} + foreach my $mykey (keys %{$rsp}) { + if ($mykey ne "data") { next; } if ($rsp->{data}) { if (ref($rsp->{data}) eq 'ARRAY') { - my $data=($rsp->{data}); + my $data = ($rsp->{data}); my $data_entry; foreach $data_entry (@$data) { my $desc; if (ref(\($data_entry)) eq 'SCALAR') { - $desc=$data_entry; + $desc = $data_entry; } else { if ($data_entry->{desc}) { - $desc=$data_entry->{desc}->[0]; + $desc = $data_entry->{desc}->[0]; } if ($data_entry->{contents}) { if ($desc) { if (defined($data_entry->{contents}->[0])) { - $desc="$desc: ".$data_entry->{contents}->[0]; + $desc = "$desc: " . $data_entry->{contents}->[0]; } } else { - $desc=$data_entry->{contents}->[0]; + $desc = $data_entry->{contents}->[0]; } } } if ($desc) { - $rsp_log.= "$desc\n"; + $rsp_log .= "$desc\n"; } } - }else{ - $rsp_log.= $rsp->{data}."\n"; + } else { + $rsp_log .= $rsp->{data} . "\n"; } } } @@ -3301,39 +3422,39 @@ sub cmdlog_collectlog(){ sub cmdlog_submitlog() { my $tmpreq; my $mysocket; - my $trytime=3; - my @tmplog=split(/\n/, $cmdlog_alllog); + my $trytime = 3; + my @tmplog = split(/\n/, $cmdlog_alllog); foreach my $item (@tmplog) { - if($item =~ /\[Request\]/){ + if ($item =~ /\[Request\]/) { $tmpreq = $item; } } $tmpreq =~ s/\[Request\]\s+(.+)/$1/g; - if ($tmpreq =~ /getipmicons/) {return 1;} - if ($tmpreq =~ /getcons/) {return 1;} + if ($tmpreq =~ /getipmicons/) { return 1; } + if ($tmpreq =~ /getcons/) { return 1; } - if( $cmdlog_alllog !~ /\n$/) { + if ($cmdlog_alllog !~ /\n$/) { $cmdlog_alllog .= "\n"; } - while ($trytime>0){ + while ($trytime > 0) { $mysocket = IO::Socket::INET->new(PeerAddr => "127.0.0.1", PeerPort => $cmdlog_port, - Proto => "tcp"); - if($mysocket) { + Proto => "tcp"); + if ($mysocket) { last; - }else{ + } else { $trytime--; sleep(0.05); } } - if($mysocket){ + if ($mysocket) { print $mysocket $cmdlog_alllog; - close ($mysocket); + close($mysocket); return 0; - }else{ - xCAT::MsgUtils->trace(0,"I","xcatd: Drop request '$tmpreq' output due to connection with 'Command log writer' process failed"); + } else { + xCAT::MsgUtils->trace(0, "I", "xcatd: Drop request '$tmpreq' output due to connection with 'Command log writer' process failed"); return 1; } } diff --git a/xCAT-server/sbin/xcatdebug b/xCAT-server/sbin/xcatdebug index f6abf482f..6144a37b1 100755 --- a/xCAT-server/sbin/xcatdebug +++ b/xCAT-server/sbin/xcatdebug @@ -1,7 +1,7 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html -# This command can be used to +# This command can be used to # 1. Enable/Disbale the subroutine calling trace. # 2. Enable the commented trace log inside a subroutine. @@ -12,7 +12,7 @@ # xCAT::Utils(isMN,Version) # xCAT_plugin::DBobjectdefs(defls,process_request) # -# Following three lines need to be added to enable the capability of commented trace +# Following three lines need to be added to enable the capability of commented trace #if (defined $ENV{ENABLE_TRACE_CODE}) { # use xCAT::Enabletrace qw(loadtrace filter); # loadtrace(); @@ -41,77 +41,79 @@ my $usage = "xcatdebug { [-f enable|disable [-c configuration file | subroutine Getopt::Long::Configure("bundling"); Getopt::Long::Configure("no_pass_through"); if ( - !GetOptions( - 'f=s' => \$::FUNC, - 'c=s' => \$::CONFIG, - 'd=s' => \$::DEBUG,)) { + !GetOptions( + 'f=s' => \$::FUNC, + 'c=s' => \$::CONFIG, + 'd=s' => \$::DEBUG,)) { print "$usage"; exit 1; } if ($^O !~ /^linux/i) { - print "xcatdebug command only supports Linux Operating System.\n"; - exit 1; + print "xcatdebug command only supports Linux Operating System.\n"; + exit 1; } if (!($::FUNC || $::DEBUG)) { - print "$usage"; - exit 1; + print "$usage"; + exit 1; } # The action that enable the commented debug log should be done firstly # In this case the xcatd need to be restart if (defined($::DEBUG)) { - if ($::DEBUG eq "enable") { - `XCATRELOAD=yes ENABLE_TRACE_CODE=1 xcatd -p /var/run/xcatd.pid`; - print "Enabled the commented trace log.\n"; - } elsif ($::DEBUG eq "disable") { - `XCATRELOAD=yes xcatd -p /var/run/xcatd.pid`; - print "Disabled the commented trace log.\n"; - } else { - print "$usage"; - exit 1; - } + if ($::DEBUG eq "enable") { + `XCATRELOAD=yes ENABLE_TRACE_CODE=1 xcatd -p /var/run/xcatd.pid`; + print "Enabled the commented trace log.\n"; + } elsif ($::DEBUG eq "disable") { + `XCATRELOAD=yes xcatd -p /var/run/xcatd.pid`; + print "Disabled the commented trace log.\n"; + } else { + print "$usage"; + exit 1; + } } if (defined($::FUNC)) { - # Get the pid of xcatd - my $pid; - if (-e "/var/run/xcatd.pid") { - open (PID, "; - close (PID); - } elsif ($pid = `ps -ef | grep 'xcatd: SSL listener' | grep -v 'grep' | awk '{print \$2}'`) { - } else { - die "Cannot find the pid in the /var/run/xcatd.pid\n"; - } - if ($::FUNC eq "enable") { - # Enable the function trace - if (defined $::CONFIG) { - open(CFG, ">/tmp/xcatcallingtrace.cfg") or die "Cannot open /tmp/xcatcallingtrace.cfg\n"; - print CFG $::CONFIG; - close (CFG); + + # Get the pid of xcatd + my $pid; + if (-e "/var/run/xcatd.pid") { + open(PID, "; + close(PID); + } elsif ($pid = `ps -ef | grep 'xcatd: SSL listener' | grep -v 'grep' | awk '{print \$2}'`) { } else { - unlink "/tmp/xcatcallingtrace.cfg"; + die "Cannot find the pid in the /var/run/xcatd.pid\n"; } - open(TRACEFLAG, ">/tmp/xcatcallingtrace.flag") or die "Cannot open file to write in /tmp\n"; - print TRACEFLAG 1; - close (TRACEFLAG); - kill SIGTRAP, $pid; - print "Enabled the subroutine calling trace.\n"; - } elsif ($::FUNC eq "disable") { - open(TRACEFLAG, ">/tmp/xcatcallingtrace.flag") or die "Cannot open file to write in /tmp\n"; - print TRACEFLAG 0; - close (TRACEFLAG); - kill SIGTRAP, $pid; - unlink "/tmp/xcatcallingtrace.cfg"; - print "Disabled the subroutine calling trace.\n"; - } else { - print "$usage"; - exit 1; - } - print " Get the trace log from the /var/log/xcat/subcallingtrace\n"; + if ($::FUNC eq "enable") { + + # Enable the function trace + if (defined $::CONFIG) { + open(CFG, ">/tmp/xcatcallingtrace.cfg") or die "Cannot open /tmp/xcatcallingtrace.cfg\n"; + print CFG $::CONFIG; + close(CFG); + } else { + unlink "/tmp/xcatcallingtrace.cfg"; + } + open(TRACEFLAG, ">/tmp/xcatcallingtrace.flag") or die "Cannot open file to write in /tmp\n"; + print TRACEFLAG 1; + close(TRACEFLAG); + kill SIGTRAP, $pid; + print "Enabled the subroutine calling trace.\n"; + } elsif ($::FUNC eq "disable") { + open(TRACEFLAG, ">/tmp/xcatcallingtrace.flag") or die "Cannot open file to write in /tmp\n"; + print TRACEFLAG 0; + close(TRACEFLAG); + kill SIGTRAP, $pid; + unlink "/tmp/xcatcallingtrace.cfg"; + print "Disabled the subroutine calling trace.\n"; + } else { + print "$usage"; + exit 1; + } + print " Get the trace log from the /var/log/xcat/subcallingtrace\n"; } diff --git a/xCAT-server/sbin/xcatnodemon b/xCAT-server/sbin/xcatnodemon index 4055e0df3..deac4418a 100755 --- a/xCAT-server/sbin/xcatnodemon +++ b/xCAT-server/sbin/xcatnodemon @@ -13,53 +13,55 @@ use xCAT_monitoring::xcatmon; # This script is used as a cron job by the xCAT monitoring plug-in # to monitor the node status. To activate it, simply do # chtab pname=xCAT monitoring.nodestatmon=Y -################################################################## +################################################################## #($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); #printf "%2d-%02d-%04d %02d:%02d:%02d: xcatnodemon started.\n", $mon+1,$mday,$year+1900,$hour,$min,$sec; -#get saved node status from the nodelist table -my %nodes_status_old=xCAT_monitoring::xcatmon::getMonNodesStatus(); +#get saved node status from the nodelist table +my %nodes_status_old = xCAT_monitoring::xcatmon::getMonNodesStatus(); #get a list of nodes -my $tmp_node_active=$nodes_status_old{$::STATUS_ACTIVE}; -my $tmp_node_inactive=$nodes_status_old{$::STATUS_INACTIVE}; -my $tmp_node_unknown=$nodes_status_old{unknown}; +my $tmp_node_active = $nodes_status_old{$::STATUS_ACTIVE}; +my $tmp_node_inactive = $nodes_status_old{$::STATUS_INACTIVE}; +my $tmp_node_unknown = $nodes_status_old{unknown}; + #print "active nodes: @$tmp_node_active\n"; #print "inactive nodes: @$tmp_node_inactive\n"; #print "unknown nodes: @$tmp_node_unknown\n"; #get current node status -my %nodes_status_new1=(); -if ($tmp_node_active) { %nodes_status_new1=xCAT::NetworkUtils->pingNodeStatus(@$tmp_node_active);} -my %nodes_status_new2=(); -if ($tmp_node_inactive) {%nodes_status_new2=xCAT::NetworkUtils->pingNodeStatus(@$tmp_node_inactive);} -my %nodes_status_new3=(); -if ($tmp_node_unknown) { %nodes_status_new3=xCAT::NetworkUtils->pingNodeStatus(@$tmp_node_unknown);} +my %nodes_status_new1 = (); +if ($tmp_node_active) { %nodes_status_new1 = xCAT::NetworkUtils->pingNodeStatus(@$tmp_node_active); } +my %nodes_status_new2 = (); +if ($tmp_node_inactive) { %nodes_status_new2 = xCAT::NetworkUtils->pingNodeStatus(@$tmp_node_inactive); } +my %nodes_status_new3 = (); +if ($tmp_node_unknown) { %nodes_status_new3 = xCAT::NetworkUtils->pingNodeStatus(@$tmp_node_unknown); } -my $changed1=$nodes_status_new1{$::STATUS_INACTIVE}; -my $changed2=$nodes_status_new2{$::STATUS_ACTIVE}; -my $changed3=$nodes_status_new3{$::STATUS_INACTIVE}; -my $changed4=$nodes_status_new3{$::STATUS_ACTIVE}; -my @changed_active=(@$changed2, @$changed4); -my @changed_inactive=(@$changed1, @$changed3); +my $changed1 = $nodes_status_new1{$::STATUS_INACTIVE}; +my $changed2 = $nodes_status_new2{$::STATUS_ACTIVE}; +my $changed3 = $nodes_status_new3{$::STATUS_INACTIVE}; +my $changed4 = $nodes_status_new3{$::STATUS_ACTIVE}; +my @changed_active = (@$changed2, @$changed4); +my @changed_inactive = (@$changed1, @$changed3); #print " switch to active: @changed_active\n"; #print " switch to inactive: @changed_inactive\n"; -my %node_status=(); -if (@changed_active>0) { - $node_status{$::STATUS_ACTIVE}=\@changed_active; -} -if (@changed_inactive>0) { - $node_status{$::STATUS_INACTIVE}=\@changed_inactive; +my %node_status = (); +if (@changed_active > 0) { + $node_status{$::STATUS_ACTIVE} = \@changed_active; +} +if (@changed_inactive > 0) { + $node_status{$::STATUS_INACTIVE} = \@changed_inactive; } #only set the node status for the changed ones if (keys(%node_status) > 0) { - #the second parameter means ignore checking. This is because the check is - #done getMonNodesStatus() call - xCAT_monitoring::xcatmon::setNodeStatusAttributes(\%node_status, 1); + + #the second parameter means ignore checking. This is because the check is + #done getMonNodesStatus() call + xCAT_monitoring::xcatmon::setNodeStatusAttributes(\%node_status, 1); } #($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time); diff --git a/xCAT-server/sbin/xcatsnap b/xCAT-server/sbin/xcatsnap index 0723c28b1..ea5c7871e 100755 --- a/xCAT-server/sbin/xcatsnap +++ b/xCAT-server/sbin/xcatsnap @@ -42,9 +42,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use File::Spec; @@ -56,7 +56,7 @@ my @Commands_array; my $Command_name; my $Command; my $currentDirectory; -my $logDirectory="/tmp/xcatsnap"; +my $logDirectory = "/tmp/xcatsnap"; my $output_dir; my @files_array; my @file_list; @@ -82,7 +82,7 @@ sub usage { sub valid_dir { $logDirectory = File::Spec->rel2abs($logDirectory); my $Dir_last_char = substr $logDirectory, -1, 1; - if ( $Dir_last_char eq "/" ) { + if ($Dir_last_char eq "/") { chop($logDirectory); } @@ -92,12 +92,12 @@ sub valid_dir { sub run_cmd { my @output; - $Command_name = $Command;#Constructing the output file name from the command + $Command_name = $Command; #Constructing the output file name from the command $Command_name =~ s/ /_/g; $Command_name =~ s/-//g; $Command_name =~ s/tabdump_//g; $Command_name =~ s/\//_/g; - + print "$Command -> $Command_name.out"; print "\n\tExecuting: $Command \n"; eval { @@ -110,33 +110,33 @@ sub run_cmd { print "\t$Command timed out.\n"; @output = "$Command timed out.\n"; } - - print "\tExecution Complete :$Command.\n"; #Writing command output into a file - my $outfile = $output_dir . $Command_name . ".out"; - open( MYFILE, ">", $outfile ); - print MYFILE @output; - close(MYFILE); - + + print "\tExecution Complete :$Command.\n"; #Writing command output into a file + my $outfile = $output_dir . $Command_name . ".out"; + open(MYFILE, ">", $outfile); + print MYFILE @output; + close(MYFILE); + } ######################## Tar it: Tars files and folders ############################# sub Tar_it { - my $file= shift; + my $file = shift; print "\n Processing $file ..\n"; my $last = substr $file, -1, 1; - if ( $last eq "*" ) { + if ($last eq "*") { @file_list = `ls $file 2>/dev/null`; foreach my $i (@file_list) { print "\tProcessing $i"; } } - if ( -l $file ) { + if (-l $file) { check_symbolic_link($file); # Checking Symbolic links } - if ( $circular != 1 ) { - if ( -e $TarFile ) { + if ($circular != 1) { + if (-e $TarFile) { `cd /; tar -uf $TarFile .$file 2>/dev/null`; } else { @@ -151,14 +151,14 @@ sub Tar_it { sub check_symbolic_link { - my $file= shift; + my $file = shift; my $max_link_count = 32; my $i = 0; - while ( defined( my $link = readlink $file ) && $i <= $max_link_count ) { + while (defined(my $link = readlink $file) && $i <= $max_link_count) { $file = $link; $i++; } - if ( $i >= $max_link_count ) { + if ($i >= $max_link_count) { $circular = 1; print "Either the link is circular or the symbolic link count exceeds max_link_count"; @@ -168,7 +168,7 @@ sub check_symbolic_link { ############## make_output_dir: Creates output directory ####################### sub make_output_dir { - if ( -d $output_dir ) { + if (-d $output_dir) { `rm -rf $output_dir`; } `mkdir $output_dir`; @@ -178,67 +178,68 @@ sub make_output_dir { sub snap_it { print "Collecting files ...\n"; - chop( $INSTALLDIR = - `tabdump site | grep installdir | cut -f2 -d ,` ); + chop($INSTALLDIR = + `tabdump site | grep installdir | cut -f2 -d ,`); $INSTALLDIR =~ s/"//g; + # make a list of all files in /tftpboot # need to limit what we get due to size `ls -lR /tftpboot > /tftpboot/tftpboot.list`; - if ( $OSname eq "AIX" ) { - + if ($OSname eq "AIX") { + @files_array = ( - "/etc/xcat/*","$::ROOTHOME/.xcat/*", "$INSTALLDIR/autoinst/*", + "/etc/xcat/*", "$::ROOTHOME/.xcat/*", "$INSTALLDIR/autoinst/*", "$INSTALLDIR/postscripts/*", "$INSTALLDIR/prescripts/*", "/tftpboot/*", "/var/log/consoles/*", "/tmp/spot.out.*", "/var/lib/dhcpd/dhcpd.leases", "/etc/hosts", "/etc/conserver.cf", "/var/log/conserver", "/etc/db_file.cr", "/etc/dhcpsd.cnf", "/var/adm/ras/nimlog", - "/etc/resolv.conf", "/etc/named.conf", "/var/log/messages", "/var/log/xcat/*"); +"/etc/resolv.conf", "/etc/named.conf", "/var/log/messages", "/var/log/xcat/*"); } - elsif ( $OSname eq "Linux" ) { - + elsif ($OSname eq "Linux") { + @files_array = ( - "/etc/xcat/*","$::ROOTHOME/.xcat/*", "$INSTALLDIR/autoinst/*", - "$INSTALLDIR/postscripts/*", "$INSTALLDIR/prescripts/*", "$INSTALLDIR/custom/*", - "/tftpboot/*", "/var/log/consoles/*", - "/etc/*-release", "/etc/dhcpd.conf", + "/etc/xcat/*", "$::ROOTHOME/.xcat/*", "$INSTALLDIR/autoinst/*", +"$INSTALLDIR/postscripts/*", "$INSTALLDIR/prescripts/*", "$INSTALLDIR/custom/*", + "/tftpboot/*", "/var/log/consoles/*", + "/etc/*-release", "/etc/dhcpd.conf", "/var/lib/dhcpd/dhcpd.leases", "/etc/hosts", "/etc/resolv.conf", - "/etc/named.conf", "/etc/conserver.cf", "/var/log/conserver", - "/etc/nsswitch.conf", "/var/log/messages", "/var/log/xcat/*"); + "/etc/named.conf", "/etc/conserver.cf", "/var/log/conserver", + "/etc/nsswitch.conf", "/var/log/messages", "/var/log/xcat/*"); print("@files_array \n"); } - foreach my $item (@files_array) { - my $file = $item; - Tar_it($file); - } + foreach my $item (@files_array) { + my $file = $item; + Tar_it($file); + } print "Done collecting files ...\n\n"; print "Gathering system configuration...\n\n"; $output_dir = "$logDirectory/commands_output/"; - my $xcatroot=$ENV{'XCATROOT'}; + my $xcatroot = $ENV{'XCATROOT'}; my $installdir; - chop( $installdir = - `tabdump site | grep installdir | cut -f2 -d ,` ); + chop($installdir = + `tabdump site | grep installdir | cut -f2 -d ,`); make_output_dir(); - if ( $OSname eq "AIX" ) { + if ($OSname eq "AIX") { @Commands_array = ( - "uname -a","ifconfig -a","netstat -in","netstat -rn","env", - "reventlog -a","lsmod","/sbin/lspci","lssrc -a","rpm -qa", - "ls $installdir","/bin/crontab -l", - "find /tftpboot -size -32k","ls -lR $xcatroot", - "arp -a","ps -edlf","ps -aux","ulimit -a","df -k","oslevel", - "netstat -A","errpt -a","/usr/sbin/instfix -i", - "/usr/sbin/lsnim -l","lssrc -l -s dhcpsd","lslpp -hac","lsxcatd -a"); + "uname -a", "ifconfig -a", "netstat -in", "netstat -rn", "env", + "reventlog -a", "lsmod", "/sbin/lspci", "lssrc -a", "rpm -qa", + "ls $installdir", "/bin/crontab -l", + "find /tftpboot -size -32k", "ls -lR $xcatroot", + "arp -a", "ps -edlf", "ps -aux", "ulimit -a", "df -k", "oslevel", + "netstat -A", "errpt -a", "/usr/sbin/instfix -i", +"/usr/sbin/lsnim -l", "lssrc -l -s dhcpsd", "lslpp -hac", "lsxcatd -a"); } - elsif ( $OSname eq "Linux" ) { + elsif ($OSname eq "Linux") { @Commands_array = ( - "uname -a","ifconfig -a","netstat -in","netstat -rn","env", - "reventlog -a","lsmod","/sbin/lspci","lssrc -a","rpm -qa", - "ls $installdir","/usr/bin/crontab -l", - "find /tftpboot -size -32k","ls -lR $xcatroot", - "arp -a","ps -edlf","ps -aux","ulimit -a","df -k", - "cat /etc/issue","lsxcatd -a","cat /proc/meminfo", "cat /proc/cpuinfo"); + "uname -a", "ifconfig -a", "netstat -in", "netstat -rn", "env", + "reventlog -a", "lsmod", "/sbin/lspci", "lssrc -a", "rpm -qa", + "ls $installdir", "/usr/bin/crontab -l", + "find /tftpboot -size -32k", "ls -lR $xcatroot", + "arp -a", "ps -edlf", "ps -aux", "ulimit -a", "df -k", +"cat /etc/issue", "lsxcatd -a", "cat /proc/meminfo", "cat /proc/cpuinfo"); } foreach my $item (@Commands_array) { $Command = $item; @@ -246,13 +247,13 @@ sub snap_it { } print "Done gathering system configuration...\n\n"; - if ( -d "/opt/xcat/" ) { + if (-d "/opt/xcat/") { print "Capturing xCAT specific information...\n\n"; print "Gathering management node configurations...\n"; @Commands_array = ( - "lsdef -t site -l","lsdef -t group -l","lsdef -t osimage -l", - "nodels","lsdef -t node -l","rpower all stat","nodestat all", - "nodels all groups","monls -a","lsvm all","rinv all all", + "lsdef -t site -l", "lsdef -t group -l", "lsdef -t osimage -l", + "nodels", "lsdef -t node -l", "rpower all stat", "nodestat all", + "nodels all groups", "monls -a", "lsvm all", "rinv all all", "rvitals all all"); foreach my $item (@Commands_array) { $Command = $item; @@ -262,24 +263,29 @@ sub snap_it { print "Retrieving xCAT database...\n"; $output_dir = "$logDirectory/xcat-database/"; make_output_dir(); + # do not snap the ISNM tables, too big my $cmd; - $cmd="XCAT_SKIPTABLES=isnm_perf,isnm_perf_dlink,isnm_perf_dlink_sum,isnm_perf_hfi,isnm_perf_hfi_sum,isnm_perf_isr,isnm_perf_isr_sum,isnm_perf_lllink,isnm_perf_lllink_sum,isnm_perf_lrlink,isnm_perf_lrlink_sum,isnm_perf_sum"; - $cmd .= " dumpxCATdb -p $output_dir"; + $cmd = "XCAT_SKIPTABLES=isnm_perf,isnm_perf_dlink,isnm_perf_dlink_sum,isnm_perf_hfi,isnm_perf_hfi_sum,isnm_perf_isr,isnm_perf_isr_sum,isnm_perf_lllink,isnm_perf_lllink_sum,isnm_perf_lrlink,isnm_perf_lrlink_sum,isnm_perf_sum"; + $cmd .= " dumpxCATdb -p $output_dir"; `$cmd`; + # now get auditlog and eventlog, last two days - # get number of seconds in the day count - my $numberdays=2; - my $numbersecs=($numberdays * 86400); + # get number of seconds in the day count + my $numberdays = 2; + my $numbersecs = ($numberdays * 86400); + # get time now - my $timenow=time; - my $secsdaysago=$timenow - $numbersecs; - # Format like the database table timestamp record + my $timenow = time; + my $secsdaysago = $timenow - $numbersecs; + + # Format like the database table timestamp record my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = - localtime($secsdaysago); - my $daysago = sprintf("%04d-%02d-%02d %02d:%02d:%02d", - $year + 1900, $mon + 1, $mday, - $hour, $min, $sec); + localtime($secsdaysago); + my $daysago = sprintf("%04d-%02d-%02d %02d:%02d:%02d", + $year + 1900, $mon + 1, $mday, + $hour, $min, $sec); + # now tabdump days gt 2 days ago $cmd = "tabdump -w \"audittime>$daysago\" auditlog > $output_dir/auditlog.csv"; @@ -287,34 +293,34 @@ sub snap_it { $cmd = "tabdump -w \"eventtime>$daysago\" eventlog > $output_dir/eventlog.csv"; `$cmd`; - + print "xCAT database retrieved.\n"; } - `rm /tftpboot/tftpboot.list`; # remove temp list -} + `rm /tftpboot/tftpboot.list`; # remove temp list +} ##################### getHomeDirectory ########################### # input userid output homedir ##################################################################### sub getHomeDir { - my @user; - my $homedir; - @user = getpwuid($>); - my $username=$user[0]; + my @user; + my $homedir; + @user = getpwuid($>); + my $username = $user[0]; - if ($user[7]) { # if homedir - $homedir= $user[7]; - } else { # no home - $homedir=`su - $username -c pwd`; - chop $homedir; - } - return $homedir; + if ($user[7]) { # if homedir + $homedir = $user[7]; + } else { # no home + $homedir = `su - $username -c pwd`; + chop $homedir; + } + return $homedir; } ############################# Main Section #################################### -my $userid = `id -ru`; #Checking if the user is root -if ( $userid != 0 ) { +my $userid = `id -ru`; #Checking if the user is root +if ($userid != 0) { print "You must be root to run the xcatsnap tool"; exit 1; } @@ -325,68 +331,69 @@ if ( $userid != 0 ) { if ( !GetOptions( - 'd|dir=s' => \$::DIRECTORY, - 'B|bypass' => \$::BYPASS, - 'h|help' => \$::HELP, - 'v|version' => \$::VERSION, + 'd|dir=s' => \$::DIRECTORY, + 'B|bypass' => \$::BYPASS, + 'h|help' => \$::HELP, + 'v|version' => \$::VERSION, ) ) { &usage; exit(1); } -if ($::HELP ) { +if ($::HELP) { usage(); exit 0; } if ($::VERSION) { - my $version = xCAT::Utils->Version(); - $version .= "\n"; - xCAT::MsgUtils->message("N", $version); - exit 0; + my $version = xCAT::Utils->Version(); + $version .= "\n"; + xCAT::MsgUtils->message("N", $version); + exit 0; exit 0; } if ($::BYPASS) { - $ENV{XCATBYPASS} = "yes"; # bypass xcatd + $ENV{XCATBYPASS} = "yes"; # bypass xcatd } if (!($::DIRECTORY)) { print " Log Directory will be /tmp/xcatsnap/\n"; } -else { - $logDirectory = $::DIRECTORY ; +else { + $logDirectory = $::DIRECTORY; valid_dir(); } -unless ( -d $logDirectory ) { #Create the output directory if it doesn't exist +unless (-d $logDirectory) { #Create the output directory if it doesn't exist `mkdir -p $logDirectory`; - if ($?!=0) { - print " Could not create $logDirectory\n"; - exit 1; - } - + if ($? != 0) { + print " Could not create $logDirectory\n"; + exit 1; + } + valid_dir(); } my $hostname; -chop( $OSname = `uname` ); -chop( $hostname = `hostname -s` ); -my ( $sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst ) = +chop($OSname = `uname`); +chop($hostname = `hostname -s`); +my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time); $mon = $mon + 1; -my @date_array = ( $mon, $mday, $hour, $min ); +my @date_array = ($mon, $mday, $hour, $min); + foreach my $item (@date_array) { $item = - sprintf( "%2d", $item ); #Formatting the date for dispaly in file name + sprintf("%2d", $item); #Formatting the date for dispaly in file name $item =~ tr/ /0/; } my $logdate = $date_array[0] . $date_array[1] . $date_array[2] . $date_array[3]; $LogFile = $logDirectory . "/xcatsnap." . $hostname . "." . $logdate . ".log"; $TarFile = $logDirectory . "/xcatsnap." . $hostname . "." . $logdate . ".tar"; -open( STDOUT, "| tee $LogFile" ); +open(STDOUT, "| tee $LogFile"); print "Time Stamp:" . `date`; print "Log Directory: $logDirectory \n"; print "Preparation Complete...\n"; @@ -401,32 +408,32 @@ print "Compiling Information...\n"; print "Information compiled...\n"; `chmod 400 $LogFile`; # Processing the log file print "Send $LogFile to IBM Support.\n"; -my $donotdelete=0; -if ( `which gunzip` == 0 ) { # Compressing the tar file +my $donotdelete = 0; +if (`which gunzip` == 0) { # Compressing the tar file `gzip -f $TarFile`; } -elsif ( `which compress` == 0 ) { +elsif (`which compress` == 0) { `compress -f $TarFile`; } else { print "gzip and compress are not available. The tar file $TarFile will not be compressed"; -$donotdelete=1; + $donotdelete = 1; } -if (-e $TarFile && $donotdelete == 0){ # Don't remove if only file to send +if (-e $TarFile && $donotdelete == 0) { # Don't remove if only file to send `rm $TarFile`; } -if ( -e $TarFile . ".gz" ) { +if (-e $TarFile . ".gz") { `chmod 400 $TarFile".gz"`; print "Send $TarFile.gz to IBM Support.\n"; } -elsif ( -e $TarFile . ".z" ) { +elsif (-e $TarFile . ".z") { `chmod 400 $TarFile".z"`; print "Send $TarFile.z to IBM Support.\n"; } -elsif ( -e $TarFile ) { +elsif (-e $TarFile) { `chmod 400 $TarFile`; print "Send $TarFile to IBM Support.\n"; } diff --git a/xCAT-server/share/xcat/cons/blade b/xCAT-server/share/xcat/cons/blade index 92c70fd5f..66e50dfbc 100755 --- a/xCAT-server/share/xcat/cons/blade +++ b/xCAT-server/share/xcat/cons/blade @@ -1,20 +1,21 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Error trying to secure a startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Error trying to secure a startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } BEGIN @@ -25,17 +26,18 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } -my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd +my $sleepint = int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd use lib "$::XCATROOT/lib/perl"; require xCAT::Client; @@ -47,16 +49,17 @@ my $scriptname = $0; #$mptab = xCAT::Table->new('mp'); #unless ($mptab) { - #sleep 5; #Try not to overwhelm logfiles... +#sleep 5; #Try not to overwhelm logfiles... # die "mp table must be configured"; #} #$mpatab = xCAT::Table->new('mpa'); #$passtab = xCAT::Table->new('passwd'); -my $username = "USERID"; +my $username = "USERID"; my $passsword = "PASSW0RD"; my $mm; my $slot; + #my $dba; #if ($passtab) { # ($dba) = $passtab->getAttribs({key=>blade},qw(username password)); @@ -81,41 +84,42 @@ my $slot; #xCAT::Utils::close_all_dbhs; #sleep 5; #Slow start, I know, but with exec, can't return sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { - $mm = $rsp->{node}->[0]->{mm}->[0]; + $mm = $rsp->{node}->[0]->{mm}->[0]; $username = $rsp->{node}->[0]->{username}->[0]; - $slot = $rsp->{node}->[0]->{slot}->[0]; - $slot =~ s/-.*//; #remove range info if multi-wide blade + $slot = $rsp->{node}->[0]->{slot}->[0]; + $slot =~ s/-.*//; #remove range info if multi-wide blade } } -my $cmdref={ - command=>["getbladecons"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["getbladecons"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($mm and $username and $slot) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen print "Console not ready, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip delay)\n"; sleep $sleepint; get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } -release_lock(); #done with xcatd, can run with near impunity -my $solchkcmd = "ssh -t $username"."@"."$mm sol -T blade[$slot]"; +release_lock(); #done with xcatd, can run with near impunity +my $solchkcmd = "ssh -t $username" . "@" . "$mm sol -T blade[$slot]"; my $solstatus = `$solchkcmd`; while ($solstatus !~ /SOL Session: Ready/ and $solstatus !~ /SOL Session: Active/) { - $sleepint=60+int(rand(30)); #Stagger sleep to take it easy on AMM/hosting server + $sleepint = 60 + int(rand(30)); #Stagger sleep to take it easy on AMM/hosting server print "SOL unavailable, retrying in $sleepint seconds (hit Ctrl-E,c,o to skip)\n"; sleep $sleepint; $solstatus = `$solchkcmd`; } -exec "ssh -t $username"."@"."$mm console -o -T blade[$slot]"; +exec "ssh -t $username" . "@" . "$mm console -o -T blade[$slot]"; + #my $pathtochild= dirname($scriptname). "/"; #exec $pathtochild."blade.expect $mm $slot $username $password"; - + #SECURITY: In this case, the authentication is expected to be done using the script user's ssh keys. As such, #this script does not receive any particularly sensitive data from the xCAT server. diff --git a/xCAT-server/share/xcat/cons/fsp b/xCAT-server/share/xcat/cons/fsp index 0876c01ce..b2030b127 100755 --- a/xCAT-server/share/xcat/cons/fsp +++ b/xCAT-server/share/xcat/cons/fsp @@ -1,20 +1,21 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Error trying to secure a startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Error trying to secure a startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } BEGIN @@ -25,25 +26,28 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } -my $sleepint=int(rand(10)); +my $sleepint = int(rand(10)); use lib "$::XCATROOT/lib/perl"; require xCAT::Client; require xCAT::Utils; use strict; + #use Getopt::Long; #use xCAT::Table; #use xCAT::PPCdb; use Expect; + #use xCAT::DBobjUtils; #use Data::Dumper; require File::Basename; @@ -89,7 +93,7 @@ my $hwtype; # if ( defined( $_[0] )) { # print STDERR "$_[0]\n"; # } -# my @msg = ( +# my @msg = ( # "$cmd -h|--help\n", # "$cmd -v|--version\n", # "$cmd singlenode [-V|-Verbose]\n" ); @@ -162,12 +166,12 @@ my $hwtype; ########################################################################## -# Open remote console +# Open remote console ########################################################################## sub invoke_cmd { - my $node = shift; - my $fsp_ip = shift; - my $id = shift; + my $node = shift; + my $fsp_ip = shift; + my $id = shift; my $hwtype = shift; my $machine; if ($hwtype eq 'blade') { @@ -190,7 +194,7 @@ sub invoke_cmd { # } #} ################################## - # Get node power type + # Get node power type ################################## #my $hwtype = __FILE__; #$hwtype =~ s/.*([\w]{3})$/$1/; @@ -236,24 +240,26 @@ sub invoke_cmd { # #my $fsp_name = $att->{hcp}; #my $id = $att->{id}; - - #use xcatd to get the attribute $fsp_name and $id of the node. + + #use xcatd to get the attribute $fsp_name and $id of the node. #my $fsp_api ="/opt/xcat/sbin/fsp-api"; - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; my $action = "console"; - my $type = "0"; + my $type = "0"; + #my $fsp_ip = (); my $Rc = 0; - + #$fsp_ip = xCAT::NetworkUtils::getNodeIPaddress( $fsp_name ); #if(!defined($fsp_ip)) { # return "Failed to get the $fsp_name\'s ip"; #} - my $power_state_cmd = "$fsp_api -a cec_state -t $type:$fsp_ip:$id:$node: 2>&1"; + my $power_state_cmd = "$fsp_api -a cec_state -t $type:$fsp_ip:$id:$node: 2>&1"; my $res; - my $index = 0; + my $index = 0; my $pre_state = undef; + #my $wait_interval =20; my $ipl_num = 0; while (1) { @@ -292,13 +298,14 @@ sub invoke_cmd { } } elsif ($res =~ /(IPL-in-process)$/) { if (!$pre_state) { - $pre_state =$1; + $pre_state = $1; sleep 10; next; } elsif ($pre_state and ($pre_state eq $1) and !$index) { print "\nDestination $machine is POWERING ON, please wait."; $index++; } else { + #print "\r\n====>pre_state=$pre_state\n"; $ipl_num++; $pre_state = $1; @@ -310,115 +317,118 @@ sub invoke_cmd { sleep 5; } else { $pre_state = $res; + #print "."; sleep 20; } + #$wait_interval =20+int(rand(20)); #sleep $wait_interval; } - + my $cmd = "$fsp_api -a $action -t $type:$fsp_ip:$id:$node:\r"; + #print "cmd: $cmd\n"; my $running_failed_code = "Reason code: 0x1000000"; - my $fsp_standby_msg = "Reason code: 0x1300"; - my $fsp_lock_msg = "Reason code: 0x1f00"; - my $timeout = 30; - my $failed = 0; - my $exp = new Expect; - $exp->log_stdout( 1 ); - $exp->spawn( $cmd ) or die "Can't spawn $cmd\r\n"; - - my @result = $exp->expect( $timeout, - [ "$running_failed_code", - sub { - $failed = 1; - } ], - [ "$fsp_standby_msg", - sub { - $failed = 2; - - }], - ["$fsp_lock_msg", - sub { - $failed = 3; - }] - ); - if($failed == 1) { - $exp->hard_close(); - return("Virtual terminal is already connected"); - - } - if($failed == 2) { - $exp->hard_close(); - return("Failed to open the console. Please check the related FSP's status"); - - } - if ($failed == 3) { - my $link_cmd = "$fsp_api -a fsp_reconnect -t $type:$fsp_ip:$id:$node: 2>&1"; - xCAT::Utils->runcmd($link_cmd, -1); - print "The connection is resetting, please wait."; - my $link_state = ""; - my $rs_num = 0; - while (!$link_state or $link_state !~ /state=LINE UP/i) { - sleep 2; - $rs_num++; - $link_cmd = "$fsp_api -a query_connection -t $type:$fsp_ip:$id:$node: 2>&1"; - $link_state = xCAT::Utils->runcmd($link_cmd, -1); - if ($rs_num == 5) { - print "."; - $rs_num = 0; - } - } - print "\n"; - $exp->hard_close(); - return (0); - } - + my $fsp_standby_msg = "Reason code: 0x1300"; + my $fsp_lock_msg = "Reason code: 0x1f00"; + my $timeout = 30; + my $failed = 0; + my $exp = new Expect; + $exp->log_stdout(1); + $exp->spawn($cmd) or die "Can't spawn $cmd\r\n"; + + my @result = $exp->expect($timeout, + [ "$running_failed_code", + sub { + $failed = 1; + } ], + [ "$fsp_standby_msg", + sub { + $failed = 2; + + } ], + [ "$fsp_lock_msg", + sub { + $failed = 3; + } ] + ); + if ($failed == 1) { + $exp->hard_close(); + return ("Virtual terminal is already connected"); + + } + if ($failed == 2) { + $exp->hard_close(); + return ("Failed to open the console. Please check the related FSP's status"); + + } + if ($failed == 3) { + my $link_cmd = "$fsp_api -a fsp_reconnect -t $type:$fsp_ip:$id:$node: 2>&1"; + xCAT::Utils->runcmd($link_cmd, -1); + print "The connection is resetting, please wait."; + my $link_state = ""; + my $rs_num = 0; + while (!$link_state or $link_state !~ /state=LINE UP/i) { + sleep 2; + $rs_num++; + $link_cmd = "$fsp_api -a query_connection -t $type:$fsp_ip:$id:$node: 2>&1"; + $link_state = xCAT::Utils->runcmd($link_cmd, -1); + if ($rs_num == 5) { + print "."; + $rs_num = 0; + } + } + print "\n"; + $exp->hard_close(); + return (0); + } + my $escape = "\030"; - $exp->send( "\r" ); - $exp->interact( \*STDIN, $escape ); - - $exp->hard_close(); - - return(0); + $exp->send("\r"); + $exp->interact(\*STDIN, $escape); + + $exp->hard_close(); + + return (0); } ############################################## -# Start main body of code +# Start main body of code ############################################## #if ( parse_args() ) { # exit(1); #} sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { - $ips = $rsp->{node}->[0]->{fsp_ip}->[0]; - $id = $rsp->{node}->[0]->{id}->[0]; + $ips = $rsp->{node}->[0]->{fsp_ip}->[0]; + $id = $rsp->{node}->[0]->{id}->[0]; $hwtype = $rsp->{node}->[0]->{type}->[0]; } } -my $cmdref={ - command=>["getfspcon"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["getfspcon"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($ips and $id) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen print "Console not ready, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip delay)\n"; sleep $sleepint; get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } -release_lock(); #done with xcatd, can run with near impunity +release_lock(); #done with xcatd, can run with near impunity $node = $ARGV[0]; - + my $result = invoke_cmd($node, $ips, $id, $hwtype); -if ( $result ne "0" ) { +if ($result ne "0") { print STDERR "$node: $result\n"; exit(1); } diff --git a/xCAT-server/share/xcat/cons/hmc b/xCAT-server/share/xcat/cons/hmc index 2673cf4af..b956f4f0f 100644 --- a/xCAT-server/share/xcat/cons/hmc +++ b/xCAT-server/share/xcat/cons/hmc @@ -1,21 +1,23 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Error trying to secure a startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Error trying to secure a startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } + BEGIN { use Time::HiRes qw(sleep); @@ -24,20 +26,22 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } -my $sleepint=int(rand(10)); +my $sleepint = int(rand(10)); use lib "$::XCATROOT/lib/perl"; require xCAT::Client; use strict; + #use Getopt::Long; #use xCAT::Table; #use xCAT::PPCdb; @@ -88,7 +92,7 @@ my $credencial; # if ( defined( $_[0] )) { # print STDERR "$_[0]\n"; # } -# my @msg = ( +# my @msg = ( # "$cmd -h|--help\n", # "$cmd -v|--version\n", # "$cmd singlenode [-V|-Verbose]\n" ); @@ -161,7 +165,7 @@ my $credencial; ########################################################################## -# Open remote console +# Open remote console ########################################################################## sub invoke_cmd { @@ -179,7 +183,7 @@ sub invoke_cmd { # } #} ################################### - ## Get node power type + ## Get node power type ################################### #my $hwtype = __FILE__; #$hwtype =~ s/.*([\w]{3})$/$1/; @@ -243,15 +247,15 @@ sub invoke_cmd { #my $host = $att->{hcp}; #my $lparid = $att->{id}; #$type = "lpar"; - - my $type = "lpar"; - my $hwtype = "hmc"; + + my $type = "lpar"; + my $hwtype = "hmc"; my %request = ( ppcretry => 1, verbose => $verbose ); ################################# - # Get userid and password + # Get userid and password ################################# #my @cred = xCAT::PPCdb::credentials( $host, $hwtype ); @cred = split(/,/, $credencial); @@ -259,57 +263,57 @@ sub invoke_cmd { ################################# # Connect to the remote server ################################# - my @exp = xCAT::PPCcli::connect( \%request, $hwtype, $host ); - if ( ref($exp[0]) ne "Expect" ) { - return( $exp[0] ); + my @exp = xCAT::PPCcli::connect(\%request, $hwtype, $host); + if (ref($exp[0]) ne "Expect") { + return ($exp[0]); } ################################# - # Open console connection + # Open console connection ################################# - my $result = xCAT::PPCcli::mkvterm( \@exp, $type, $lparid, $mtms ); + my $result = xCAT::PPCcli::mkvterm(\@exp, $type, $lparid, $mtms); my $Rc = shift(@$result); - if ( $Rc != SUCCESS ) { - return( @$result[0] ); + if ($Rc != SUCCESS) { + return (@$result[0]); } - return(0); + return (0); } ############################################## -# Start main body of code +# Start main body of code ############################################## #if ( parse_args() ) { # exit(1); #} sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { - $host = $rsp->{node}->[0]->{host}->[0]; - $lparid = $rsp->{node}->[0]->{lparid}->[0]; - $mtms = $rsp->{node}->[0]->{mtms}->[0]; - $credencial = $rsp->{node}->[0]->{cred}->[0]; + $host = $rsp->{node}->[0]->{host}->[0]; + $lparid = $rsp->{node}->[0]->{lparid}->[0]; + $mtms = $rsp->{node}->[0]->{mtms}->[0]; + $credencial = $rsp->{node}->[0]->{cred}->[0]; } } -my $cmdref={ - command=>["gethmccon"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["gethmccon"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($lparid and $host and $mtms) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen print "Console not ready, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip delay)\n"; sleep $sleepint; get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } -release_lock(); #done with xcatd, can run with near impunity +release_lock(); #done with xcatd, can run with near impunity $node = $ARGV[0]; - + my $result = invoke_cmd($host, $lparid, $mtms); -if ( $result ne "0" ) { +if ($result ne "0") { print STDERR "$node: $result\n"; exit(1); } diff --git a/xCAT-server/share/xcat/cons/hpblade b/xCAT-server/share/xcat/cons/hpblade index 2bb0efd34..2fe780c51 100755 --- a/xCAT-server/share/xcat/cons/hpblade +++ b/xCAT-server/share/xcat/cons/hpblade @@ -1,5 +1,5 @@ #!/usr/bin/env perl -# +# # © Copyright 2009 Hewlett-Packard Development Company, L.P. # EPL license http://www.eclipse.org/legal/epl-v10.html # @@ -7,20 +7,21 @@ # August, 2009 blade adapted to generate hpblade # use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Error trying to secure a startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Error trying to secure a startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } BEGIN @@ -31,19 +32,20 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } -my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd +my $sleepint = int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd use lib "$::XCATROOT/lib/perl"; -$ENV{HOME}='/root/'; +$ENV{HOME} = '/root/'; require xCAT::Client; require File::Basename; @@ -52,16 +54,17 @@ my $scriptname = $0; #$mptab = xCAT::Table->new('mp'); #unless ($mptab) { - #sleep 5; #Try not to overwhelm logfiles... +#sleep 5; #Try not to overwhelm logfiles... # die "mp table must be configured"; #} #$mpatab = xCAT::Table->new('mpa'); #$passtab = xCAT::Table->new('passwd'); -my $username = "admin"; +my $username = "admin"; my $passsword = "PASSW0RD"; my $mm; my $slot; + #my $dba; #if ($passtab) { # ($dba) = $passtab->getAttribs({key=>blade},qw(username password)); @@ -86,33 +89,34 @@ my $slot; #xCAT::Utils::close_all_dbhs; #sleep 5; #Slow start, I know, but with exec, can't return sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { - $mm = $rsp->{node}->[0]->{mm}->[0]; + $mm = $rsp->{node}->[0]->{mm}->[0]; $username = $rsp->{node}->[0]->{username}->[0]; - $slot = $rsp->{node}->[0]->{slot}->[0]; + $slot = $rsp->{node}->[0]->{slot}->[0]; } } -my $cmdref={ - command=>"gethpbladecons", - arg=>"text", - noderange=>$ARGV[0] +my $cmdref = { + command => "gethpbladecons", + arg => "text", + noderange => $ARGV[0] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($mm and $username and $slot) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen print "Console not ready, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip delay)\n"; sleep $sleepint; get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } -release_lock(); #done with xcatd, can run with near impunity -$sleepint=10+int(rand(30)); #Stagger sleep to take it easy on AMM/hosting server -exec "ssh -t $username"."@"."$mm vsp"; -my $pathtochild= dirname($scriptname). "/"; +release_lock(); #done with xcatd, can run with near impunity +$sleepint = 10 + int(rand(30)); #Stagger sleep to take it easy on AMM/hosting server +exec "ssh -t $username" . "@" . "$mm vsp"; +my $pathtochild = dirname($scriptname) . "/"; + #exec $pathtochild."hpblade.expect"; - + #SECURITY: In this case, the authentication is expected to be done using the script user's ssh keys. As such, #this script does not receive any particularly sensitive data from the xCAT server. diff --git a/xCAT-server/share/xcat/cons/ipmi b/xCAT-server/share/xcat/cons/ipmi index 26bf99b3d..875fa11ba 100755 --- a/xCAT-server/share/xcat/cons/ipmi +++ b/xCAT-server/share/xcat/cons/ipmi @@ -1,21 +1,23 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Fatal Error securing startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Fatal Error securing startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } + BEGIN { use Time::HiRes qw(sleep); @@ -24,53 +26,55 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { print "Unable to open lock file"; exec("sleep 15"); exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } -my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd +my $sleepint = int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; use lib "$::XCATROOT/lib/perl"; require xCAT::Client; my $username = 'USERID'; my $password = 'PASSW0RD'; -my $node = $ARGV[0]; +my $node = $ARGV[0]; my $bmc; + sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { - $bmc = $rsp->{node}->[0]->{bmcaddr}->[0]; + $bmc = $rsp->{node}->[0]->{bmcaddr}->[0]; $username = $rsp->{node}->[0]->{bmcuser}->[0]; $password = $rsp->{node}->[0]->{bmcpass}->[0]; if (exists $rsp->{node}->[0]->{error}) { - my $error = $rsp->{node}->[0]->{error}->[0]; - print $error."\n"; + my $error = $rsp->{node}->[0]->{error}->[0]; + print $error. "\n"; } } } -my $cmdref={ - command=>["getipmicons"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["getipmicons"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until (($username or $password) and $bmc) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); print "Console not ready, retrying in $sleepint seconds (Ctrl-e,c,o to skip delay) \n"; exec("sleep $sleepint"); get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } release_lock(); -my ($user,$pass); +my ($user, $pass); if ($username) { $user = "-U '$username'"; } else { @@ -81,6 +85,7 @@ if ($password) { } else { $pass = ''; } + #require xCAT::Table; #require xCAT::Utils; #my $dba; @@ -103,48 +108,49 @@ if ($password) { #} #xCAT::Utils::close_all_dbhs; #my $isintel = system "ipmitool -I lanplus -U $username -P $password -H $bmc chassis status > /dev/null 2>&1"; -my $isintel=0; +my $isintel = 0; my $sleepint; my $rc; my $ipmitool = "ipmitool"; if (-x "$XCATROOT/bin/ipmitool-xcat") { $ipmitool = "$XCATROOT/bin/ipmitool-xcat"; } -my @mcinfo=`$ipmitool -I lanplus $user $pass -H $bmc mc info`;#| grep 'Manufacturer ID : 343' > /dev/null 2>&1"; +my @mcinfo = `$ipmitool -I lanplus $user $pass -H $bmc mc info`; #| grep 'Manufacturer ID : 343' > /dev/null 2>&1"; $rc = $?; if ($rc) { #some shoddy vendors ignore the IPMI 2.0 requirement to support IPMI 1.5 formats for BMC capability determination, attempt IPMI 2.0 even without the ability to confirm IPMI 2.0 support. Though SOL was not baked in prior IPMI 2.0, this script supports pre-2.0 'ISOL' on older devices, hence why we are checking for 1.5/2.0 before proceeding normally - @mcinfo=`$ipmitool -I lan $user $pass -H $bmc mc info`; - $rc = $?; + @mcinfo = `$ipmitool -I lan $user $pass -H $bmc mc info`; + $rc = $?; } while ($rc != 0) { - $sleepint = 10+int(rand(20)); - print "Failure to reach IPMI device, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip)\n"; - exec("sleep $sleepint"); - #sleep $sleepint; - @mcinfo=`$ipmitool -I lanplus $user $pass -H $bmc mc info`;#| grep 'Manufacturer ID : 343' > /dev/null 2>&1"; - $rc = $?; - if ($rc) { #repeat workaround for shoddy vendors - @mcinfo=`$ipmitool -I lan $user $pass -H $bmc mc info`; - $rc = $?; + $sleepint = 10 + int(rand(20)); + print "Failure to reach IPMI device, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip)\n"; + exec("sleep $sleepint"); + + #sleep $sleepint; + @mcinfo = `$ipmitool -I lanplus $user $pass -H $bmc mc info`; #| grep 'Manufacturer ID : 343' > /dev/null 2>&1"; + $rc = $?; + if ($rc) { #repeat workaround for shoddy vendors + @mcinfo = `$ipmitool -I lan $user $pass -H $bmc mc info`; + $rc = $?; } } -my $solcom="sol"; -my $iface="lanplus"; -if (grep /IPMI Version : 1.5/,@mcinfo) { - $solcom="isol"; - $iface="lan"; -} elsif (grep /Manufacturer ID : 343/,@mcinfo) { - $isintel=1; +my $solcom = "sol"; +my $iface = "lanplus"; +if (grep /IPMI Version : 1.5/, @mcinfo) { + $solcom = "isol"; + $iface = "lan"; +} elsif (grep /Manufacturer ID : 343/, @mcinfo) { + $isintel = 1; } -my $inteloption=""; +my $inteloption = ""; if ($isintel) { - $inteloption=" -o intelplus"; + $inteloption = " -o intelplus"; } if ($iface eq "lanplus") { system "$ipmitool -I lanplus $inteloption $user $pass -H $bmc $solcom deactivate"; #Stop any active session } exec "$ipmitool -I $iface $inteloption $user $pass -H $bmc $solcom activate"; - + diff --git a/xCAT-server/share/xcat/cons/ivm b/xCAT-server/share/xcat/cons/ivm index d5c2aa63c..40e847b52 100755 --- a/xCAT-server/share/xcat/cons/ivm +++ b/xCAT-server/share/xcat/cons/ivm @@ -2,21 +2,23 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); use strict; + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Error trying to secure a startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Error trying to secure a startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } + BEGIN { use Time::HiRes qw(sleep); @@ -25,20 +27,21 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); - my $sleepint=int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd - print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; + my $sleepint = int(rand(10)); #Stagger start to avoid overwhelming conserver/xCATd + print "Opening console in " . (2 + (0.5 * $sleepint)) . " seconds...\n"; sleep $sleepint; } -my $sleepint=int(rand(10)); +my $sleepint = int(rand(10)); use lib "$::XCATROOT/lib/perl"; require xCAT::Client; use strict; + #use Getopt::Long; #use xCAT::Table; #use xCAT::PPCdb; @@ -89,7 +92,7 @@ my $credencial; # if ( defined( $_[0] )) { # print STDERR "$_[0]\n"; # } -# my @msg = ( +# my @msg = ( # "$cmd -h|--help\n", # "$cmd -v|--version\n", # "$cmd singlenode [-V|-Verbose]\n" ); @@ -162,7 +165,7 @@ my $credencial; ########################################################################## -# Open remote console +# Open remote console ########################################################################## sub invoke_cmd { @@ -180,7 +183,7 @@ sub invoke_cmd { # } #} ################################### - ## Get node power type + ## Get node power type ################################### #my $hwtype = __FILE__; #$hwtype =~ s/.*([\w]{3})$/$1/; @@ -244,15 +247,15 @@ sub invoke_cmd { #my $host = $att->{hcp}; #my $lparid = $att->{id}; #$type = "lpar"; - - my $type = "lpar"; - my $hwtype = "ivm"; + + my $type = "lpar"; + my $hwtype = "ivm"; my %request = ( ppcretry => 1, verbose => $verbose ); ################################# - # Get userid and password + # Get userid and password ################################# #my @cred = xCAT::PPCdb::credentials( $host, $hwtype ); @cred = split(/,/, $credencial); @@ -260,61 +263,61 @@ sub invoke_cmd { ################################# # Connect to the remote server ################################# - my @exp = xCAT::PPCcli::connect( \%request, $hwtype, $host ); - if ( ref($exp[0]) ne "Expect" ) { - return( $exp[0] ); + my @exp = xCAT::PPCcli::connect(\%request, $hwtype, $host); + if (ref($exp[0]) ne "Expect") { + return ($exp[0]); } ################################# - # Open console connection + # Open console connection ################################# - my $result = xCAT::PPCcli::mkvterm( \@exp, $type, $lparid, $mtms ); + my $result = xCAT::PPCcli::mkvterm(\@exp, $type, $lparid, $mtms); my $Rc = shift(@$result); - if ( $Rc != SUCCESS ) { - return( @$result[0] ); + if ($Rc != SUCCESS) { + return (@$result[0]); } - return(0); + return (0); } ############################################## -# Start main body of code +# Start main body of code ############################################## #if ( parse_args() ) { # exit(1); #} sub getans { - my $rsp = shift; - + my $rsp = shift; + if ($rsp->{node}) { - $host = $rsp->{node}->[0]->{host}->[0]; - $lparid = $rsp->{node}->[0]->{lparid}->[0]; - $mtms = $rsp->{node}->[0]->{mtms}->[0]; - $credencial = $rsp->{node}->[0]->{cred}->[0]; - + $host = $rsp->{node}->[0]->{host}->[0]; + $lparid = $rsp->{node}->[0]->{lparid}->[0]; + $mtms = $rsp->{node}->[0]->{mtms}->[0]; + $credencial = $rsp->{node}->[0]->{cred}->[0]; + } } -my $cmdref={ - command=>["gethmccon"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["gethmccon"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($lparid and $host and $mtms) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen print "Console not ready, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip delay)\n"; sleep $sleepint; get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } -release_lock(); #done with xcatd, can run with near impunity +release_lock(); #done with xcatd, can run with near impunity $node = $ARGV[0]; - + my $result = invoke_cmd($host, $lparid, $mtms); -if ( $result ne "0" ) { +if ($result ne "0") { print STDERR "$node: $result\n"; exit(1); } diff --git a/xCAT-server/share/xcat/cons/kvm b/xCAT-server/share/xcat/cons/kvm index 7d95cd3e4..c122799ad 100755 --- a/xCAT-server/share/xcat/cons/kvm +++ b/xCAT-server/share/xcat/cons/kvm @@ -1,21 +1,23 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Fatal error securing startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Fatal error securing startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } + BEGIN { use Time::HiRes qw(sleep); @@ -24,16 +26,18 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } + #BEGIN #{ # use Time::HiRes qw(sleep); @@ -50,43 +54,45 @@ require File::Basename; import File::Basename; my $scriptname = $0; -my $cmdref={ - command=>["getcons"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["getcons"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; use Data::Dumper; my $dsthost; my $dstty; my $speed; + sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { $dsthost = $rsp->{node}->[0]->{sshhost}->[0]; - $dstty = $rsp->{node}->[0]->{psuedotty}->[0]; - $speed = $rsp->{node}->[0]->{baudrate}->[0]; + $dstty = $rsp->{node}->[0]->{psuedotty}->[0]; + $speed = $rsp->{node}->[0]->{baudrate}->[0]; } } -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($dsthost and $speed and $dstty) { release_lock(); - $sleepint=int(rand(30))+60; + $sleepint = int(rand(30)) + 60; print "Console not ready, retrying in $sleepint seconds (Ctrl-C to skip delay)\n"; exec "sleep $sleepint"; } release_lock(); + # The screen command needs the TERM env var, # TERM might be empty for some unknown reasons, # for example, on SLES 12 and on PowerKVM if (!$ENV{'TERM'}) { - $ENV{'TERM'}="vt100"; + $ENV{'TERM'} = "vt100"; } -exec "ssh -t $dsthost screen -U -a -O -e ^]a -d -R -S serial-".$ARGV[0]."-cons -A $dstty $speed"; +exec "ssh -t $dsthost screen -U -a -O -e ^]a -d -R -S serial-" . $ARGV[0] . "-cons -A $dstty $speed"; #my $pathtochild= dirname($scriptname). "/"; #exec $pathtochild."blade.expect $mm $slot $username $password"; - + diff --git a/xCAT-server/share/xcat/cons/multiple b/xCAT-server/share/xcat/cons/multiple index 99aeb3f20..ff0feccf6 100755 --- a/xCAT-server/share/xcat/cons/multiple +++ b/xCAT-server/share/xcat/cons/multiple @@ -1,21 +1,23 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Error trying to secure a startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Error trying to secure a startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } + BEGIN { use Time::HiRes qw(sleep); @@ -24,14 +26,14 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); } -my $sleepint=int(rand(10)); +my $sleepint = int(rand(10)); use lib "$::XCATROOT/lib/perl"; require xCAT::Client; use strict; @@ -53,87 +55,88 @@ my $credencial; my $fsp_ip; my $id; my $hcps; -my $result; +my $result; ########################################################################## # Open remote console thourgh fsp ########################################################################## sub invoke_fsp { - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; my $action = "console"; - my $type = "0"; - my $Rc = 0; - - if( !(-e $fsp_api) && !(-x $fsp_api) ) { + my $type = "0"; + my $Rc = 0; + + if (!(-e $fsp_api) && !(-x $fsp_api)) { return "please check the $fsp_api"; } - + my $cmd = "$fsp_api -a $action -t $type:$fsp_ip:$id:$node:\r"; + #print "cmd: $cmd\n"; my $running_failed_code = "Reason code: 0x1000000"; - my $fsp_standby_msg = "Reason code: 0x1300"; - my $timeout = 30; - my $failed = 0; - my $exp = new Expect; - $exp->log_stdout( 1 ); - $exp->spawn( $cmd ) or die "Can't spawn $cmd\r\n"; - - my @result = $exp->expect( $timeout, - [ "$running_failed_code", - sub { - $failed = 1; - } ], - [ "$fsp_standby_msg", - sub { - $failed = 2; - - }], - [ "Session closed, back from open_vterm", - sub { - $failed = 3; - - }] - ); - if($failed == 1) { - $exp->hard_close(); - return("Virtual terminal is already connected"); - - } - if($failed == 2) { - $exp->hard_close(); - return("Failed to open the console. Please check the related FSP's status"); - - } - if($failed == 3) { - $exp->hard_close(); - return("Failed to open the console. Please check the related FSP's IP"); - - } - - + my $fsp_standby_msg = "Reason code: 0x1300"; + my $timeout = 30; + my $failed = 0; + my $exp = new Expect; + $exp->log_stdout(1); + $exp->spawn($cmd) or die "Can't spawn $cmd\r\n"; + + my @result = $exp->expect($timeout, + [ "$running_failed_code", + sub { + $failed = 1; + } ], + [ "$fsp_standby_msg", + sub { + $failed = 2; + + } ], + [ "Session closed, back from open_vterm", + sub { + $failed = 3; + + } ] + ); + if ($failed == 1) { + $exp->hard_close(); + return ("Virtual terminal is already connected"); + + } + if ($failed == 2) { + $exp->hard_close(); + return ("Failed to open the console. Please check the related FSP's status"); + + } + if ($failed == 3) { + $exp->hard_close(); + return ("Failed to open the console. Please check the related FSP's IP"); + + } + + my $escape = "\030"; - $exp->send( "\r" ); - $exp->interact( \*STDIN, $escape ); - - $exp->hard_close(); - - return(0); + $exp->send("\r"); + $exp->interact(\*STDIN, $escape); + + $exp->hard_close(); + + return (0); } ########################################################################## -# Open remote console through hmc +# Open remote console through hmc ########################################################################## sub invoke_hmc { - my $type = "lpar"; - my $hwtype = "hmc"; + my $type = "lpar"; + my $hwtype = "hmc"; my %request = ( ppcretry => 1, verbose => $verbose ); ################################# - # Get userid and password + # Get userid and password ################################# #my @cred = xCAT::PPCdb::credentials( $host, $hwtype ); @cred = split(/,/, $credencial); @@ -141,85 +144,85 @@ sub invoke_hmc { ################################# # Connect to the remote server ################################# - my @exp = xCAT::PPCcli::connect( \%request, $hwtype, $host ); - if ( ref($exp[0]) ne "Expect" ) { - return( $exp[0] ); + my @exp = xCAT::PPCcli::connect(\%request, $hwtype, $host); + if (ref($exp[0]) ne "Expect") { + return ($exp[0]); } ################################# - # Open console connection + # Open console connection ################################# - my $result = xCAT::PPCcli::mkvterm( \@exp, $type, $lparid, $mtms ); + my $result = xCAT::PPCcli::mkvterm(\@exp, $type, $lparid, $mtms); my $Rc = shift(@$result); - if ( $Rc != SUCCESS ) { - return( @$result[0] ); + if ($Rc != SUCCESS) { + return (@$result[0]); } - return(0); + return (0); } ############################################## -# Start main body of code +# Start main body of code ############################################## sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { $hcps = $rsp->{node}->[0]->{hcp}; - if ( $rsp->{node}->[0]->{errorcode} ) { + if ($rsp->{node}->[0]->{errorcode}) { print STDERR "$rsp->{node}->[0]->{error}"; } } } -my $cmdref={ - command=>["getmulcon"], - arg=>["text"], - noderange=>[$ARGV[0]] +my $cmdref = { + command => ["getmulcon"], + arg => ["text"], + noderange => [ $ARGV[0] ] }; -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($hcps) { - release_lock(); #Let other clients have a go - $sleepint=10+int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen + release_lock(); #Let other clients have a go + $sleepint = 10 + int(rand(20)); #Stagger to minimize lock collisions, but no big deal when it does happen print "Console not ready, retrying in $sleepint seconds (Hit Ctrl-E,c,o to skip delay)\n"; sleep $sleepint; get_lock(); - xCAT::Client::submit_request($cmdref,\&getans); + xCAT::Client::submit_request($cmdref, \&getans); } -release_lock(); #done with xcatd, can run with near impunity +release_lock(); #done with xcatd, can run with near impunity $node = $ARGV[0]; -my $c = scalar ( keys %{${$hcps}[0]}); -for my $thishcp (keys %{${$hcps}[0]}) { - my $nt = ${${${${${$hcps}[0]}{$thishcp}}[0]}{nodetype}}[0]; - if ( $nt =~ /^(fsp)$/ ) { - $fsp_ip = ${${${${${$hcps}[0]}{$thishcp}}[0]}{fsp_ip}}[0]; - $id = ${${${${${$hcps}[0]}{$thishcp}}[0]}{id}}[0]; - if ($fsp_ip and $id ) { - $result = invoke_fsp(); +my $c = scalar(keys %{ ${$hcps}[0] }); +for my $thishcp (keys %{ ${$hcps}[0] }) { + my $nt = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{nodetype} }[0]; + if ($nt =~ /^(fsp)$/) { + $fsp_ip = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{fsp_ip} }[0]; + $id = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{id} }[0]; + if ($fsp_ip and $id) { + $result = invoke_fsp(); } else { print STDERR "fsp_ip or id is not available\n"; } } - elsif ( $nt =~ /^(hmc)$/) { - $host = ${${${${${$hcps}[0]}{$thishcp}}[0]}{host}}[0]; - $lparid = ${${${${${$hcps}[0]}{$thishcp}}[0]}{lparid}}[0]; - $mtms = ${${${${${$hcps}[0]}{$thishcp}}[0]}{mtms}}[0]; - $credencial = ${${${${${$hcps}[0]}{$thishcp}}[0]}{credencial}}[0]; + elsif ($nt =~ /^(hmc)$/) { + $host = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{host} }[0]; + $lparid = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{lparid} }[0]; + $mtms = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{mtms} }[0]; + $credencial = ${ ${ ${ ${ ${$hcps}[0] }{$thishcp} }[0] }{credencial} }[0]; if ($host and $lparid and $mtms and $credencial) { $result = invoke_hmc(); } else { print STDERR "hcp or lparid or mtms or user/passwd is not available\n"; } } - - if($result eq 0) { + + if ($result eq 0) { last; - } + } ############## #Once every hcp is tried, if the $res!=0, it will return -1; - ############### + ############### $c--; - if($c == 0) { + if ($c == 0) { print STDERR "$node: $result\n"; exit(1) } diff --git a/xCAT-server/share/xcat/cons/xen b/xCAT-server/share/xcat/cons/xen index 0cd3bb1be..2cdf0b051 100755 --- a/xCAT-server/share/xcat/cons/xen +++ b/xCAT-server/share/xcat/cons/xen @@ -1,21 +1,23 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html use Fcntl qw(:DEFAULT :flock); + sub get_lock { - unless (flock(LOCKHANDLE,LOCK_EX|LOCK_NB)) { + unless (flock(LOCKHANDLE, LOCK_EX | LOCK_NB)) { $| = 1; print "Acquiring startup lock..."; - flock(LOCKHANDLE,LOCK_EX) or die "Fatal error securing startup lock"; + flock(LOCKHANDLE, LOCK_EX) or die "Fatal error securing startup lock"; print "done\n"; } - truncate(LOCKHANDLE,0); - print LOCKHANDLE $$."\n"; + truncate(LOCKHANDLE, 0); + print LOCKHANDLE $$ . "\n"; } sub release_lock { - truncate(LOCKHANDLE,0); - flock(LOCKHANDLE,LOCK_UN); + truncate(LOCKHANDLE, 0); + flock(LOCKHANDLE, LOCK_UN); } + BEGIN { use Time::HiRes qw(sleep); @@ -24,16 +26,18 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; umask 0077; mkpath("/tmp/xcat/"); - unless (sysopen(LOCKHANDLE,"/tmp/xcat/consolelock",O_WRONLY | O_CREAT)) { + unless (sysopen(LOCKHANDLE, "/tmp/xcat/consolelock", O_WRONLY | O_CREAT)) { sleep 15; print "Unable to open lock file"; exit 0; } get_lock(); + #my $sleepint=int(rand(10)); #print "Opening console in ".(2+(0.5*$sleepint))." seconds...\n"; #sleep $sleepint; } + #BEGIN #{ # use Time::HiRes qw(sleep); @@ -50,36 +54,37 @@ require File::Basename; import File::Basename; my $scriptname = $0; -my $cmdref={ - command=>"getxencons", - arg=>"text", - noderange=>$ARGV[0] +my $cmdref = { + command => "getxencons", + arg => "text", + noderange => $ARGV[0] }; use Data::Dumper; my $dsthost; my $dstty; my $speed; + sub getans { - my $rsp = shift; + my $rsp = shift; if ($rsp->{node}) { $dsthost = $rsp->{node}->[0]->{sshhost}->[0]; - $dstty = $rsp->{node}->[0]->{psuedotty}->[0]; - $speed = $rsp->{node}->[0]->{baudrate}->[0]; + $dstty = $rsp->{node}->[0]->{psuedotty}->[0]; + $speed = $rsp->{node}->[0]->{baudrate}->[0]; } } -xCAT::Client::submit_request($cmdref,\&getans); +xCAT::Client::submit_request($cmdref, \&getans); until ($dsthost and $speed and $dstty) { release_lock(); - $sleepint=int(rand(30))+60; + $sleepint = int(rand(30)) + 60; print "Console not ready, retrying in $sleepint seconds (Ctrl-C to skip delay)\n"; exec "sleep $sleepint"; } release_lock(); -exec "ssh -t $dsthost screen -U -a -O -e ^]a -d -R -S serial-".$ARGV[0]."-cons -A $dstty $speed"; +exec "ssh -t $dsthost screen -U -a -O -e ^]a -d -R -S serial-" . $ARGV[0] . "-cons -A $dstty $speed"; #my $pathtochild= dirname($scriptname). "/"; #exec $pathtochild."blade.expect $mm $slot $username $password"; - + diff --git a/xCAT-server/share/xcat/ib/scripts/annotatelog b/xCAT-server/share/xcat/ib/scripts/annotatelog index 814215598..f25212fea 100644 --- a/xCAT-server/share/xcat/ib/scripts/annotatelog +++ b/xCAT-server/share/xcat/ib/scripts/annotatelog @@ -6,12 +6,12 @@ # Command: annotatelog # # # #-------------------------------------------------------------------------# -# This xCAT script is used to parse the QLogic log entries in file -# /var/log/xcat/errorlog/[xCAT Management Nodes] on xCAT Management -# Node by subnet manager, IB node, chassis, FRU(Field-Replaceable Unit) or a +# This xCAT script is used to parse the QLogic log entries in file +# /var/log/xcat/errorlog/[xCAT Management Nodes] on xCAT Management +# Node by subnet manager, IB node, chassis, FRU(Field-Replaceable Unit) or a # particular node. This script is supported by both AIX and Linux MN. -# From xCAT's point of view, the log to analyze must be xCAT -# consolidated log, which means this log file must come from xCAT +# From xCAT's point of view, the log to analyze must be xCAT +# consolidated log, which means this log file must come from xCAT # syslog/errorlog monitoring mechanism, such as # /var/log/xcat/errorlog/[xCAT Management Nodes] file. Since the log format # is various, xCAT do not support other log files. @@ -27,17 +27,17 @@ # Must be xCAT consolidated log got from Qlogic HSM or ESM. # -s start_time # Specifies the start time for analysis, where the start_time -# variable has the format ddmmyyhh:mm:ss (day, month, year, +# variable has the format ddmmyyhh:mm:ss (day, month, year, # hour, minute, and second), 00:00:00 is valid. # -e end_time -# Specifies the end time for analysis, where the end_time -# variable has the format ddmmyyhh:mm:ss (day, month, year, +# Specifies the end time for analysis, where the end_time +# variable has the format ddmmyyhh:mm:ss (day, month, year, # hour, minute, and second), 00:00:00 is valid. # -l link_file # Specifies a link file fullpath name, which concatenates all # '/var/opt/iba/analysis/baseline/fabric*links' files from all fabric management nodes. # -g guid_file -# Specifies a guid file fullpath name, which has a list of +# Specifies a guid file fullpath name, which has a list of # GUIDs as obtained from the "getGuids" script. # -E Annotate with node ERRLOG_ON and ERRLOG_OFF information. This # can help determine if a disappearance was caused by a node @@ -60,17 +60,17 @@ use Time::Local; #Maps between HCA adapter and connector %::HCAMAP = ( - "iba0_lsw1" => "C65-T1 (HV=Cx-T1)", "iba0_lsw2" => "C65-T2 (HV=Cx-T2)", - "iba1_lsw1" => "C65-T3", "iba1_lsw2" => "C65-T4", - "iba2_lsw1" => "C66-T1", "iba2_lsw2" => "C66-T2", - "iba3_lsw1" => "C66-T3", "iba3_lsw2" => "C66-T4", - "ehca0_lsw1" => "C65-T1 (HV=Cx-T1)", "ehca0_lsw2" => "C65-T2 (HV=Cx-T2)", - "ehca1_lsw1" => "C65-T3", "ehca1_lsw2" => "C65-T4", - "ehca2_lsw1" => "C66-T1", "ehca2_lsw2" => "C66-T2", - "ehca3_lsw1" => "C66-T3", "ehca3_lsw2" => "C66-T4", + "iba0_lsw1" => "C65-T1 (HV=Cx-T1)", "iba0_lsw2" => "C65-T2 (HV=Cx-T2)", + "iba1_lsw1" => "C65-T3", "iba1_lsw2" => "C65-T4", + "iba2_lsw1" => "C66-T1", "iba2_lsw2" => "C66-T2", + "iba3_lsw1" => "C66-T3", "iba3_lsw2" => "C66-T4", + "ehca0_lsw1" => "C65-T1 (HV=Cx-T1)", "ehca0_lsw2" => "C65-T2 (HV=Cx-T2)", + "ehca1_lsw1" => "C65-T3", "ehca1_lsw2" => "C65-T4", + "ehca2_lsw1" => "C66-T1", "ehca2_lsw2" => "C66-T2", + "ehca3_lsw1" => "C66-T3", "ehca3_lsw2" => "C66-T4", ); -$::OK = 0; +$::OK = 0; $::NOK = 1; $::SHSEP = "###############################################################################"; $::DASEP = "-------------------------------------------------------------------------------"; @@ -82,18 +82,24 @@ $::DASEP = "-------------------------------------------------------------------- %::NODELOGS; %::NODELOGSBYNAME; %::OTHERLOGS; + #The start time and end time of logs that will be analyzed $::Start_Epoch; $::End_Epoch; -#Record the relationship between guid and it's information + +#Record the relationship between guid and it's information %::GUIDS; -#Record links between HCA and Switch and links between Switch and Swtich + +#Record links between HCA and Switch and links between Switch and Swtich %::HCALinks; + #ERRLOG_ON and ERRLOG_OFF information %::ELOGON; %::ELOGOFF; + #Information related with a node %::NodeInfo; + #List of nodes that their logs will be analyzed @::NodeList; @@ -116,78 +122,79 @@ sub getArgs() $Getopt::Long::ignorecase = 0; if ( !GetOptions( - 'h' => \$::HELP, - 'A' => \$::ALL, - 'f=s' => \$::LOG_FILE, - 's=s' => \$::START_TIME, - 'e=s' => \$::END_TIME, - 'g=s' => \$::GUIDS_FILE, - 'l=s' => \$::LINKS_FILE, - 'E' => \$::ERRLOG, - 'S' => \$::SM, - 'i' => \$::IBNODE, - 'c' => \$::CHASSIS, - 'u' => \$::FRU, - 'n=s' => \$::NODE_LIST - ) - ) + 'h' => \$::HELP, + 'A' => \$::ALL, + 'f=s' => \$::LOG_FILE, + 's=s' => \$::START_TIME, + 'e=s' => \$::END_TIME, + 'g=s' => \$::GUIDS_FILE, + 'l=s' => \$::LINKS_FILE, + 'E' => \$::ERRLOG, + 'S' => \$::SM, + 'i' => \$::IBNODE, + 'c' => \$::CHASSIS, + 'u' => \$::FRU, + 'n=s' => \$::NODE_LIST + ) + ) { usage(); - exit $::NOK; + exit $::NOK; } - if ( $::HELP == 1 ) + if ($::HELP == 1) { usage(); exit $::OK; } - if ( $::LOG_FILE eq "" ) + if ($::LOG_FILE eq "") { print "Please use \"-f\" to specify a log file."; usage(); - exit $::NOK; + exit $::NOK; } - if ( $::SM == 0 && $::IBNODE == 0 && $::CHASSIS == 0 && $::FRU == 0 && $::NODE_LIST eq "") + if ($::SM == 0 && $::IBNODE == 0 && $::CHASSIS == 0 && $::FRU == 0 && $::NODE_LIST eq "") { #If there is no flag specified, -A is default $::ALL = 1; } - - if ( $::ALL == 1 && ($::SM == 1 || $::IBNODE == 1 || $::CHASSIS == 1 || $::FRU == 1)) + + if ($::ALL == 1 && ($::SM == 1 || $::IBNODE == 1 || $::CHASSIS == 1 || $::FRU == 1)) { print "The flag -i, -S, -c or -u should not be used with -A."; usage(); - exit $::NOK; + exit $::NOK; } - if ( ($::ALL == 1 || $::IBNODE == 1) && ( $::GUIDS_FILE eq "" || $::LINKS_FILE eq "")) + if (($::ALL == 1 || $::IBNODE == 1) && ($::GUIDS_FILE eq "" || $::LINKS_FILE eq "")) { print "The -g flag and -l flag should be used with -a or -i flag.\n"; usage(); - exit $::NOK; + exit $::NOK; } - if ( $::ERRLOG == 1 && ( $::IBNODE == 0 && $::ALL == 0 && $::NODE_LIST eq "") ) + if ($::ERRLOG == 1 && ($::IBNODE == 0 && $::ALL == 0 && $::NODE_LIST eq "")) { print "The -E flag should be used with -n or -i or -a flag.\n"; usage(); - exit $::NOK; + exit $::NOK; } - - if ( $::NODE_LIST ne "" && $::GUIDS_FILE eq "" ) + + if ($::NODE_LIST ne "" && $::GUIDS_FILE eq "") { print "The -n flag should be used with -g flag.\n"; usage(); - exit $::NOK; + exit $::NOK; } - - if ( $::NODE_LIST ne "") + + if ($::NODE_LIST ne "") { @::NodeList = split /,/, $::NODE_LIST; + #List all nodes in Managed or MinManaged mode my @AllNodes = `nodels`; chomp @AllNodes; my @NotDefinedNodes; - foreach my $node (@::NodeList) + foreach my $node (@::NodeList) { #If there are IP addresses in NodeList, convert IP to hostname first if (isIpaddr($node)) # why? for xCAT, nodename can not be ip address... @@ -195,13 +202,14 @@ sub getArgs() my ($hostname, $ip) = getHost($node); $node = $hostname; } + #Check nodes in NodeList and find those that are not defined in xCAT database or not in Managed or MinManaged mode - if (!(grep {$_ =~ /$node/} @AllNodes)) + if (!(grep { $_ =~ /$node/ } @AllNodes)) { - push (@NotDefinedNodes, $node); + push(@NotDefinedNodes, $node); next; } - } + } if (scalar(@NotDefinedNodes)) { my $badnodes = join ",", @NotDefinedNodes; @@ -210,10 +218,10 @@ sub getArgs() } } - if ( $::GUIDS_FILE ne "" ) { %::GUIDS = getGUIDs($::GUIDS_FILE); } - if ( $::LINKS_FILE ne "" ) { %::HCALinks = getHCALinks($::LINKS_FILE); } + if ($::GUIDS_FILE ne "") { %::GUIDS = getGUIDs($::GUIDS_FILE); } + if ($::LINKS_FILE ne "") { %::HCALinks = getHCALinks($::LINKS_FILE); } - if ( $::START_TIME ne "" ) + if ($::START_TIME ne "") { $::Start_Epoch = epochTime($::START_TIME); } @@ -222,7 +230,7 @@ sub getArgs() $::Start_Epoch = 0; } - if ( $::END_TIME ne "" ) + if ($::END_TIME ne "") { $::End_Epoch = epochTime($::END_TIME); } @@ -260,8 +268,8 @@ sub isIpaddr { my ($class, $addr) = @_; - if ($addr =~ /:/) { #ipv6 - return 1; + if ($addr =~ /:/) { #ipv6 + return 1; } #print "addr=$addr\n"; @@ -314,7 +322,7 @@ sub getHost { $ipaddr = $arg; my $packedaddr = inet_aton($ipaddr); - $hostname = gethostbyaddr($packedaddr,AF_INET); + $hostname = gethostbyaddr($packedaddr, AF_INET); if (!$hostname) { $hostname = $ipaddr; @@ -326,14 +334,14 @@ sub getHost { $hostname = $arg; # this may be a short hostname my ($name, $aliases, $addrtype, $length, @addrs) = - gethostbyname($hostname); + gethostbyname($hostname); #print "name=$name, # of addrs=$#addrs.\n"; my $packedaddr = $addrs[0]; - $ipaddr = inet_ntoa($packedaddr); + $ipaddr = inet_ntoa($packedaddr); $hostname = - $name; # they may have specified a shorter or non-primary name - #print "ipaddr=$ipaddr, hostname=$hostname\n"; + $name; # they may have specified a shorter or non-primary name + #print "ipaddr=$ipaddr, hostname=$hostname\n"; } return ($hostname, $ipaddr); } @@ -359,192 +367,203 @@ sub getLogs print "Can't open '$logfile':\n\t$!"; exit $::NOK; } - + foreach my $line () { chomp $line; $tsepoch = 0; + # only work with local6 logs #if ( $line =~ /local6/ ) { # parse up log entries - if ($line =~ /SM:.*COND:#12/ and ($::ALL == 1 || $::SM == 1)) - { - my ($ts, $level, $sm, $cond, $node, $linkedto, $detail); - #Parse a line of logs - #The DETAIL is not always there - if ( $line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|LINKEDTO:(.*)\|DETAIL:(.*)/ ) - { - ($ts, $level, $sm, $cond, $node, $linkedto, $detail) = ($1, $2, $3, $4, $5, $6, $7); - } - elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|DETAIL:(.*)/) - { - ($ts, $level, $sm, $cond, $node, $detail) = ($1, $2, $3, $4, $5, $6); - } + if ($line =~ /SM:.*COND:#12/ and ($::ALL == 1 || $::SM == 1)) + { + my ($ts, $level, $sm, $cond, $node, $linkedto, $detail); - $tsepoch = epochTime($ts) if($ts); - #Check the time of this log is in the period specified - if ( $tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($ts && $tsepoch <= $::End_Epoch)) ) - { - $::SMLOGS{$sm} = "$::SMLOGS{$sm}\n$line"; - } - next; + #Parse a line of logs + #The DETAIL is not always there + if ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|LINKEDTO:(.*)\|DETAIL:(.*)/) + { + ($ts, $level, $sm, $cond, $node, $linkedto, $detail) = ($1, $2, $3, $4, $5, $6, $7); + } + elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|DETAIL:(.*)/) + { + ($ts, $level, $sm, $cond, $node, $detail) = ($1, $2, $3, $4, $5, $6); } - if ($line =~ /CHASSIS:/ and ($::ALL == 1 || $::CHASSIS == 1 || $::FRU == 1)) - { - my ($ts, $level, $chassis, $cond, $FRU, $pn, $details); - if ( $line =~ /(.........:..:..).*MSG:(\w*)\|CHASSIS:(.*)\|COND:(.*)\|FRU:(.*)\|PN:(.*)\|DETAIL:(.*)/ ) - { - ($ts, $level, $chassis, $cond, $FRU, $pn, $details) = ($1, $2, $3, $4, $5, $6, $7); - } - elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|CHASSIS:(.*)\|COND:(.*)\|FRU:(.*)\|PN:(.*)/) - { - ($ts, $level, $chassis, $cond, $FRU, $pn) = ($1, $2, $3, $4, $5, $6); - } + $tsepoch = epochTime($ts) if ($ts); - $tsepoch = epochTime($ts) if($ts); - if ( $tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($ts && $tsepoch <= $::End_Epoch)) ) - { - $FRU = "$chassis - $FRU"; - $::FRULOGS{$FRU} = "$::FRULOGS{$FRU}\n$line" if ($::ALL == 1 || $::FRU == 1); - $::CHASSISLOGS{$chassis} = "$::CHASSISLOGS{$chassis}\n$line" if ($::ALL == 1 || $::CHASSIS == 1); - } - next; + #Check the time of this log is in the period specified + if ($tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($ts && $tsepoch <= $::End_Epoch))) + { + $::SMLOGS{$sm} = "$::SMLOGS{$sm}\n$line"; + } + next; + } + + if ($line =~ /CHASSIS:/ and ($::ALL == 1 || $::CHASSIS == 1 || $::FRU == 1)) + { + my ($ts, $level, $chassis, $cond, $FRU, $pn, $details); + if ($line =~ /(.........:..:..).*MSG:(\w*)\|CHASSIS:(.*)\|COND:(.*)\|FRU:(.*)\|PN:(.*)\|DETAIL:(.*)/) + { + ($ts, $level, $chassis, $cond, $FRU, $pn, $details) = ($1, $2, $3, $4, $5, $6, $7); + } + elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|CHASSIS:(.*)\|COND:(.*)\|FRU:(.*)\|PN:(.*)/) + { + ($ts, $level, $chassis, $cond, $FRU, $pn) = ($1, $2, $3, $4, $5, $6); } - if ($line =~ /SM:/ && ($::ALL == 1 || $::SM == 1 || $::IBNODE == 1 || $::NODE_LIST ne "")) + $tsepoch = epochTime($ts) if ($ts); + if ($tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($ts && $tsepoch <= $::End_Epoch))) { - my $guid; - my $port; - my $guidref; - my $realguid; - my $lsw; - my $lswref; - my $hcaphys; - my $host; - my $elog_entry; - my ($ts, $level, $sm, $cond, $node, $linkedto, $detail); - if ( $line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|LINKEDTO:(.*)\|DETAIL:(.*)/) + $FRU = "$chassis - $FRU"; + $::FRULOGS{$FRU} = "$::FRULOGS{$FRU}\n$line" if ($::ALL == 1 || $::FRU == 1); + $::CHASSISLOGS{$chassis} = "$::CHASSISLOGS{$chassis}\n$line" if ($::ALL == 1 || $::CHASSIS == 1); + } + next; + } + + if ($line =~ /SM:/ && ($::ALL == 1 || $::SM == 1 || $::IBNODE == 1 || $::NODE_LIST ne "")) + { + my $guid; + my $port; + my $guidref; + my $realguid; + my $lsw; + my $lswref; + my $hcaphys; + my $host; + my $elog_entry; + my ($ts, $level, $sm, $cond, $node, $linkedto, $detail); + + if ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|LINKEDTO:(.*)\|DETAIL:(.*)/) + { + ($ts, $level, $sm, $cond, $node, $linkedto, $detail) = ($1, $2, $3, $4, $5, $6, $7); + } + elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|LINKEDTO:(.*)/) + { + ($ts, $level, $sm, $cond, $node, $linkedto) = ($1, $2, $3, $4, $5, $6); + } + elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|DETAIL:(.*)/) + { + ($ts, $level, $sm, $cond, $node, $detail) = ($1, $2, $3, $4, $5, $6); + } + elsif ($line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)/) + { + ($ts, $level, $sm, $cond, $node) = ($1, $2, $3, $4, $5); + } + if ($sm eq "") { $sm = "Other"; } + + $tsepoch = epochTime($ts) if ($ts); + if ($tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($ts && $tsepoch <= $::End_Epoch))) + { + if ($node =~ /IBM .*Logical/ && ($::ALL == 1 || $::IBNODE == 1 || $::NODE_LIST ne "")) { - ($ts, $level, $sm, $cond, $node, $linkedto, $detail) = ($1, $2, $3, $4, $5, $6, $7); - } - elsif ( $line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|LINKEDTO:(.*)/ ) - { - ($ts, $level, $sm, $cond, $node, $linkedto) = ($1, $2, $3, $4, $5, $6); - } - elsif ( $line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)\|DETAIL:(.*)/ ) - { - ($ts, $level, $sm, $cond, $node, $detail) = ($1, $2, $3, $4, $5, $6); - } - elsif ( $line =~ /(.........:..:..).*MSG:(\w*)\|SM:(.*)\|COND:(.*)\|NODE:(.*)/ ) - { - ($ts, $level, $sm, $cond, $node) = ($1, $2, $3, $4, $5); - } - if ( $sm eq "") { $sm = "Other"; } - - $tsepoch = epochTime($ts) if($ts); - if ( $tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($ts && $tsepoch <= $::End_Epoch)) ) - { - if ($node =~ /IBM .*Logical/ && ($::ALL == 1 || $::IBNODE == 1 || $::NODE_LIST ne "")) + $guid = $node; + $guid =~ s/.*:0x//; + $port = $node; + $port =~ s/.*port //; + $port =~ s/:.*//; + if ($node =~ /IBM .*Logical Switch/) { - $guid = $node; - $guid =~ s/.*:0x//; - $port = $node; - $port =~ s/.*port //; - $port =~ s/:.*//; - if ( $node =~ /IBM .*Logical Switch/ ) - { - #It's for Logical Switch - $realguid = $guid; - $guid =~ s/..$/00/; - $node =~ /.*Switch (\d):.*/; - $lsw = $1; - #The key for HCALinks to find the next link of this Logical Switch - $guidref = "$realguid:1"; - } - else - { - #It's for Logical HCA - $::GUIDS{$guid}{type} =~ /.*(\d+)/; - $lsw = $1; - #The key for HCALinks to find the linked Logical Switch of this Logical HCA - $guidref = "$guid:$port"; - $lswref = $::HCALinks{$guidref}; - $lswref =~ /.*GUID\s*0x(\w+).*/; - $lswref = $1; - #The key for HCALinks to find the next link of the Logical Switch - $lswref = "$lswref:1"; - } - my $hcadev = $::GUIDS{$guid}{dev}; - my $hcalu = "${hcadev}_lsw${lsw}"; - #Find the connector - $hcaphys = $::HCAMAP{$hcalu}; + #It's for Logical Switch + $realguid = $guid; + $guid =~ s/..$/00/; + $node =~ /.*Switch (\d):.*/; + $lsw = $1; - $host = $::GUIDS{$guid}{host}; - #If this it a log for HCA, the guid can be translated to a hostname using GUIDS map - $node = "$host :port $port:0x$guid" if($host); - if ( $::NODE_LIST ne "" ) + #The key for HCALinks to find the next link of this Logical Switch + $guidref = "$realguid:1"; + } + else + { + #It's for Logical HCA + $::GUIDS{$guid}{type} =~ /.*(\d+)/; + $lsw = $1; + + #The key for HCALinks to find the linked Logical Switch of this Logical HCA + $guidref = "$guid:$port"; + $lswref = $::HCALinks{$guidref}; + $lswref =~ /.*GUID\s*0x(\w+).*/; + $lswref = $1; + + #The key for HCALinks to find the next link of the Logical Switch + $lswref = "$lswref:1"; + } + my $hcadev = $::GUIDS{$guid}{dev}; + my $hcalu = "${hcadev}_lsw${lsw}"; + + #Find the connector + $hcaphys = $::HCAMAP{$hcalu}; + + $host = $::GUIDS{$guid}{host}; + + #If this it a log for HCA, the guid can be translated to a hostname using GUIDS map + $node = "$host :port $port:0x$guid" if ($host); + if ($::NODE_LIST ne "") + { + if (grep { $host =~ /$_/ || $_ =~ /$host/ } @::NodeList) { - if ( grep {$host =~ /$_/ || $_ =~ /$host/} @::NodeList ) - { - $::NODELOGSBYNAME{$host} = "$::NODELOGSBYNAME{$host}\n$line"; - } - } - #If -E is specified, get the ERRLOG_ON and ERRLOG_OFF information - if ( $::ERRLOG == 1 && $host && ($::ALL == 1 || $::IBNODE == 1 || ($::NODE_LIST ne "" && grep {$host =~ /$_/ || $_ =~ /$host/} @::NodeList))) - { - if ( ! exists $::ELOGON{$host}) - { - my $ret = getERRLOG($host); - ($::ELOGON{$host}, $::ELOGOFF{$host}) = split/[_]/, $ret; - } - $elog_entry = "\n# ERRLOG_ON: $::ELOGON{$host}\n# ERRLOG_OFF: $::ELOGOFF{$host}"; - } - if ($::ALL == 1 || $::IBNODE == 1) - { - $::HCALinks{$guidref} =~ /(.+)\s*port.*/; - my $swname = $1; - my $lswn = $::HCALinks{$guidref} ? $::HCALinks{$guidref} : "Not Found"; - my $swn = $::HCALinks{$lswref} ? $::HCALinks{$lswref} : "Not Found"; - - if ( (! exists $::NodeInfo{$node}) && $node) - { - if ( $node =~ /IBM .*Logical Switch/ ) - { - $::NodeInfo{$node} = "- <-> $lswn"; - } - else - { - $::NodeInfo{$node} = "- $::GUIDS{$guid}{dev} <-> $lswn\n" . - "- Connector is $hcaphys\n" . - "- $swname<-> $swn"; - if ( ($::ALL == 1 || $::IBNODE == 1) && $::ERRLOG == 1 ) - { - $::NodeInfo{$node} = $::NodeInfo{$node} . "\n$::DASEP\n# $host$elog_entry"; - } - } - } - } - if ($::ERRLOG == 1 && $host && $::NODE_LIST ne "" && (grep {$host =~ /$_/ || $_ =~ /$host/} @::NodeList)) - { - $::NodeInfo{$host} = "$elog_entry"; + $::NODELOGSBYNAME{$host} = "$::NODELOGSBYNAME{$host}\n$line"; } } - - $::SMLOGS{$sm} = "$::SMLOGS{$sm}\n$line" if ($::ALL == 1 || $::SM == 1); - $::NODELOGS{$node} = "$::NODELOGS{$node}\n$line" if ($::ALL == 1 || $::IBNODE == 1); + + #If -E is specified, get the ERRLOG_ON and ERRLOG_OFF information + if ($::ERRLOG == 1 && $host && ($::ALL == 1 || $::IBNODE == 1 || ($::NODE_LIST ne "" && grep { $host =~ /$_/ || $_ =~ /$host/ } @::NodeList))) + { + if (!exists $::ELOGON{$host}) + { + my $ret = getERRLOG($host); + ($::ELOGON{$host}, $::ELOGOFF{$host}) = split /[_]/, $ret; + } + $elog_entry = "\n# ERRLOG_ON: $::ELOGON{$host}\n# ERRLOG_OFF: $::ELOGOFF{$host}"; + } + if ($::ALL == 1 || $::IBNODE == 1) + { + $::HCALinks{$guidref} =~ /(.+)\s*port.*/; + my $swname = $1; + my $lswn = $::HCALinks{$guidref} ? $::HCALinks{$guidref} : "Not Found"; + my $swn = $::HCALinks{$lswref} ? $::HCALinks{$lswref} : "Not Found"; + + if ((!exists $::NodeInfo{$node}) && $node) + { + if ($node =~ /IBM .*Logical Switch/) + { + $::NodeInfo{$node} = "- <-> $lswn"; + } + else + { + $::NodeInfo{$node} = "- $::GUIDS{$guid}{dev} <-> $lswn\n" . + "- Connector is $hcaphys\n" . + "- $swname<-> $swn"; + if (($::ALL == 1 || $::IBNODE == 1) && $::ERRLOG == 1) + { + $::NodeInfo{$node} = $::NodeInfo{$node} . "\n$::DASEP\n# $host$elog_entry"; + } + } + } + } + if ($::ERRLOG == 1 && $host && $::NODE_LIST ne "" && (grep { $host =~ /$_/ || $_ =~ /$host/ } @::NodeList)) + { + $::NodeInfo{$host} = "$elog_entry"; + } } - next; + + $::SMLOGS{$sm} = "$::SMLOGS{$sm}\n$line" if ($::ALL == 1 || $::SM == 1); + $::NODELOGS{$node} = "$::NODELOGS{$node}\n$line" if ($::ALL == 1 || $::IBNODE == 1); } - if ($line =~ /.*/ and ($::ALL == 1)) + next; + } + if ($line =~ /.*/ and ($::ALL == 1)) + { + $line =~ /(.........:..:..).*/; + my $tsepoch = epochTime($1) if ($1); + if ($tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($1 && $tsepoch <= $::End_Epoch))) { - $line =~ /(.........:..:..).*/; - my $tsepoch = epochTime($1) if($1); - if ( $tsepoch >= $::Start_Epoch && (!defined($::End_Epoch) || ($1 && $tsepoch <= $::End_Epoch)) ) - { - $::OTHERLOGS{"others"} = "$::OTHERLOGS{\"others\"}\n$line"; - } - } + $::OTHERLOGS{"others"} = "$::OTHERLOGS{\"others\"}\n$line"; + } + } + #} } close LOGFILE; @@ -561,17 +580,17 @@ sub getLogs #-------------------------------------------------------------------------------- sub outputLogs { - my $SMLOGHDR = "Logs by Subnet Manager"; - my $SMLOGSECT = "Reported by subnet manager: "; - my $IBNODEHDR = "Logs by IB node"; - my $IBNODESECT = "Reported by IB node: "; + my $SMLOGHDR = "Logs by Subnet Manager"; + my $SMLOGSECT = "Reported by subnet manager: "; + my $IBNODEHDR = "Logs by IB node"; + my $IBNODESECT = "Reported by IB node: "; my $IBNODEHDRBYNAME = "Logs for special nodes"; - my $CHLOGHDR = "Logs by CHASSIS"; - my $CHLOGSECT = "Reported by chassis: "; - my $FRULOGHDR = "Logs by FRUS from CHASSIS"; - my $FRULOGSECT = "Associated with FRU: "; - my $OTLOGHDR = "Logs by Others"; - my $OTLOGSECT = ""; + my $CHLOGHDR = "Logs by CHASSIS"; + my $CHLOGSECT = "Reported by chassis: "; + my $FRULOGHDR = "Logs by FRUS from CHASSIS"; + my $FRULOGSECT = "Associated with FRU: "; + my $OTLOGHDR = "Logs by Others"; + my $OTLOGSECT = ""; print < 0, "Feb" => 1, "Mar" => 2, "Apr" => 3, "May" => 4, + my $ots = $timestring; + my $epoch = ""; + my $formaterror = 0; + my %themon = ("Jan" => 0, "Feb" => 1, "Mar" => 2, "Apr" => 3, "May" => 4, "Jun" => 5, "Jul" => 6, "Aug" => 7, "Sep" => 8, "Oct" => 9, "Nov" => 10, "Dec" => 11, ); - if ( length($timestring) > 1 ) + if (length($timestring) > 1) { #If the time string is not of ddmmyyhh:mm:ss format, it will be a time stamp of a log - if ( $timestring =~ /\S+\s+\d+\s+\d+:\d+:\d+/ ) + if ($timestring =~ /\S+\s+\d+\s+\d+:\d+:\d+/) { my $mont = substr $timestring, 0, 3; my $dayt = substr $timestring, 4, 2; @@ -737,52 +756,53 @@ sub epochTime my $year = substr $pyear, 2, 2; if ($dayt < 10) { $dayt =~ s/ /0/g; } if ($mont < 10) { $mont = "0$mont"; } + #Format the timestring to ddmmyyhh:mm:ss $timestring = "$dayt$mont$year$time"; } } - if ( ! ($timestring =~ /^\d+:\d+:\d+$/) ) + if (!($timestring =~ /^\d+:\d+:\d+$/)) { print "Invalid time '$ots'\n"; exit $::NOK; } - + my $day = substr $timestring, 0, 2; - if ( !($day =~ /^\d+$/) || $day < 1 || $day > 31 ) + if (!($day =~ /^\d+$/) || $day < 1 || $day > 31) { $formaterror = 1; } my $mon = substr $timestring, 2, 2; - if ( !($mon =~ /^\d+$/) || $mon < 1 || $mon > 12 ) + if (!($mon =~ /^\d+$/) || $mon < 1 || $mon > 12) { $formaterror = 1; } $mon = $mon - 1; my $year = substr $timestring, 4, 2; - if ( !($year =~ /^\d+$/) ) + if (!($year =~ /^\d+$/)) { $formaterror = 1; } $year = $year - 1900; - if ( $year < 0 ) { $year = $year + 2000 } - if ( $year > 138 ) { $formaterror = 1; } + if ($year < 0) { $year = $year + 2000 } + if ($year > 138) { $formaterror = 1; } my $hour = substr $timestring, 6, 2; - if ( !($hour =~ /^\d+$/) || $hour < 0 || $hour > 23 ) + if (!($hour =~ /^\d+$/) || $hour < 0 || $hour > 23) { $formaterror = 1; } my $min = substr $timestring, 9, 2; - if ( !($min =~ /^\d+$/) || $min < 0 || $min > 59 ) + if (!($min =~ /^\d+$/) || $min < 0 || $min > 59) { $formaterror = 1; } my $sec = substr $timestring, 12, 2; - if ( !($sec =~ /^\d+$/) || $sec < 0 || $sec > 59 ) + if (!($sec =~ /^\d+$/) || $sec < 0 || $sec > 59) { $formaterror = 1; } - if($formaterror) + if ($formaterror) { print "Invalid time '$ots'\n"; exit $::NOK; @@ -804,7 +824,7 @@ sub epochTime sub usage { - print <) { - if ( $getit == 1 ) + if ($getit == 1) { if ($line =~ /.*0x(\S*)\s+(\d+)\s+(\w+)\s+(.*)/) { @@ -1014,7 +1034,7 @@ sub getHCALinks my $port; ($hcaport, $port) = ($1, $2); $hcaport = "$hcaport:$port"; - $getit = 1; + $getit = 1; } } else @@ -1022,7 +1042,7 @@ sub getHCALinks $getit = 0; } } - + foreach my $key (keys %::HCALinks) { print "$key -> $hcalinks{$key}\n"; diff --git a/xCAT-server/share/xcat/ib/scripts/getGuids b/xCAT-server/share/xcat/ib/scripts/getGuids index ed557191e..d37c4fb9f 100644 --- a/xCAT-server/share/xcat/ib/scripts/getGuids +++ b/xCAT-server/share/xcat/ib/scripts/getGuids @@ -25,19 +25,19 @@ use strict; use Getopt::Long; # Log file -$::GUIDS_LOG = "/var/log/xcat/getGuids.log"; -$::DEFAULT_RESULT_FILE = "/var/opt/xcat/ib/Guids.xcat"; -$::GUIDS_LOG_PATH = "/var/log/xcat"; +$::GUIDS_LOG = "/var/log/xcat/getGuids.log"; +$::DEFAULT_RESULT_FILE = "/var/opt/xcat/ib/Guids.xcat"; +$::GUIDS_LOG_PATH = "/var/log/xcat"; $::DEFAULT_RESULT_FILE_PATH = "/var/opt/xcat/ib"; # variables and Commands -$::OK = 0; -$::NOK = 1; -$::logging = 0; +$::OK = 0; +$::NOK = 1; +$::logging = 0; $::GLOBAL_EXIT = 0; -$::NODEGRP = "/opt/xcat/bin/nodels"; -$::LinuxIBCmd = "/usr/bin/ibv_devinfo"; -$::AIXIBCmd = "/usr/bin/ibstat"; +$::NODEGRP = "/opt/xcat/bin/nodels"; +$::LinuxIBCmd = "/usr/bin/ibv_devinfo"; +$::AIXIBCmd = "/usr/bin/ibstat"; # MAIN Main main# &getArgs; @@ -51,16 +51,16 @@ local *FILE; unless (open(FILE, ">$::RESULT_FILE")) { print "Can't open file $::RESULT_FILE for writing.\n"; - print $::LOG_FILE_HANDLE + print $::LOG_FILE_HANDLE "Can't open file $::RESULT_FILE for writing.\n"; - + $::GLOBAL_EXIT = $::NOK; exit; } # get Linux nodes my @LnxNodes = `$::NODEGRP all nodetype.os | grep -E "sles|rhel"`; -print $::LOG_FILE_HANDLE "Running command: $::NODEGRP LinuxNodes\n"; +print $::LOG_FILE_HANDLE "Running command: $::NODEGRP LinuxNodes\n"; chomp @LnxNodes; my @ReachableLnxNodes; @@ -77,7 +77,7 @@ if ($num > 0) my $rest; ($node, $rest) = split(/:/, $node); my $rc = &checkxDshReachability($node); - if ($rc == 0) # xdsh is ok + if ($rc == 0) # xdsh is ok { push @ReachableLnxNodes, $node; } @@ -87,14 +87,14 @@ if ($num > 0) } } - if (scalar (@UnreachableLnxNodes)) + if (scalar(@UnreachableLnxNodes)) { - my $UnreachableLnxNodes = join (", ", @UnreachableLnxNodes); - print - "Warning: xdsh is unreachable for the node(s): $UnreachableLnxNodes.\n" . + my $UnreachableLnxNodes = join(", ", @UnreachableLnxNodes); + print +"Warning: xdsh is unreachable for the node(s): $UnreachableLnxNodes.\n" . "Please use xdsh -K command to configure it.\n"; print $::LOG_FILE_HANDLE - "Warning: xdsh is unreachable for the node(s): $UnreachableLnxNodes.\n" . +"Warning: xdsh is unreachable for the node(s): $UnreachableLnxNodes.\n" . "Please use xdsh -K command to configure it.\n"; } @@ -111,16 +111,16 @@ if ($num > 0) } } - if (scalar (@BadLnxNodes)) + if (scalar(@BadLnxNodes)) { - my $BadLnxNodes = join (", ", @BadLnxNodes); - print - "Warning: Command $::LinuxIBCmd is not available on the node(s): $BadLnxNodes.\nPlease ensure the libibverbs rpm is installed.\n"; + my $BadLnxNodes = join(", ", @BadLnxNodes); + print +"Warning: Command $::LinuxIBCmd is not available on the node(s): $BadLnxNodes.\nPlease ensure the libibverbs rpm is installed.\n"; print $::LOG_FILE_HANDLE - "Warning: Command $::LinuxIBCmd is not available on the node(s): $BadLnxNodes.\nPlease ensure the libibverbs rpm is installed.\n"; +"Warning: Command $::LinuxIBCmd is not available on the node(s): $BadLnxNodes.\nPlease ensure the libibverbs rpm is installed.\n"; } - if (scalar (@ValidLnxNodes)) + if (scalar(@ValidLnxNodes)) { my $rc = &getLinuxGUIDS(\@ValidLnxNodes); if ($rc) @@ -133,7 +133,7 @@ if ($num > 0) # get AIX nodes my @AIXNodes = `$::NODEGRP all nodetype.os | grep "AIX"`; -print $::LOG_FILE_HANDLE "Running command: $::NODEGRP\n"; +print $::LOG_FILE_HANDLE "Running command: $::NODEGRP\n"; chomp @AIXNodes; my @ReachableAIXNodes; @@ -143,15 +143,15 @@ my @BadAIXNodes; my $num = scalar(@AIXNodes); if ($num > 0) { - # Handle AIX Nodes + # Handle AIX Nodes # Check if xdsh is reachable foreach my $node (@AIXNodes) { my $rest; ($node, $rest) = split(/:/, $node); - + my $rc = &checkxDshReachability($node); - if ($rc == 0) # xdsh is ok + if ($rc == 0) # xdsh is ok { push @ReachableAIXNodes, $node; } @@ -161,14 +161,14 @@ if ($num > 0) } } - if (scalar (@UnreachableAIXNodes)) + if (scalar(@UnreachableAIXNodes)) { - my $UnreachableAIXNodes = join (", ", @UnreachableAIXNodes); - print - "Warning: The xdsh is unreachable for the node(s): $UnreachableAIXNodes.\n" . + my $UnreachableAIXNodes = join(", ", @UnreachableAIXNodes); + print +"Warning: The xdsh is unreachable for the node(s): $UnreachableAIXNodes.\n" . "Please use xdsh -K command to configure it.\n"; print $::LOG_FILE_HANDLE - "Warning: The xdsh is unreachable for the node(s): $UnreachableAIXNodes.\n" . +"Warning: The xdsh is unreachable for the node(s): $UnreachableAIXNodes.\n" . "Please use xdsh -K command to configure it.\n"; } @@ -185,16 +185,16 @@ if ($num > 0) } } - if (scalar (@BadAIXNodes)) + if (scalar(@BadAIXNodes)) { - my $BadAIXNodes = join (", ", @BadAIXNodes); - print - "Warning: Command $::AIXIBCmd is not available on the node(s): $BadAIXNodes.\nPlease ensure the devices.common.IBM.ib.rte fileset is installed.\n"; + my $BadAIXNodes = join(", ", @BadAIXNodes); + print +"Warning: Command $::AIXIBCmd is not available on the node(s): $BadAIXNodes.\nPlease ensure the devices.common.IBM.ib.rte fileset is installed.\n"; print $::LOG_FILE_HANDLE - "Warning: Command $::AIXIBCmd is not available on the node(s): $BadAIXNodes.\nPlease ensure the devices.common.IBM.ib.rte fileset is installed.\n"; +"Warning: Command $::AIXIBCmd is not available on the node(s): $BadAIXNodes.\nPlease ensure the devices.common.IBM.ib.rte fileset is installed.\n"; } - if (scalar (@ValidAIXNodes)) + if (scalar(@ValidAIXNodes)) { my $rc = &getAIXGUIDS(\@ValidAIXNodes); if ($rc) @@ -231,7 +231,7 @@ END } } -exit; # end of Main +exit; # end of Main #-------------------------------------------------------------------------------- @@ -244,8 +244,8 @@ exit; # end of Main sub getArgs() { GetOptions( - 'h' => \$::HELP, - 'f=s' => \$::RESULT_FILE + 'h' => \$::HELP, + 'f=s' => \$::RESULT_FILE ); if ($::HELP) { @@ -265,7 +265,7 @@ sub getArgs() exit; } } - } + } } #-------------------------------------------------------------------------------- @@ -279,11 +279,11 @@ sub getArgs() sub usage() { print - "Usage: getGuids [-h] [-f output_file] + "Usage: getGuids [-h] [-f output_file] -f output_file Specifies a file full path name that is used to save the GUIDs output. -h - Display usage information.\n"; + Display usage information.\n"; } #-------------------------------------------------------------------------------- @@ -308,7 +308,7 @@ sub checkxDshReachability() my ($node) = @_; my $output = `xdsh $node date 2>/dev/null`; - print $::LOG_FILE_HANDLE "Running command: xdsh $node date 2>/dev/null\n"; + print $::LOG_FILE_HANDLE "Running command: xdsh $node date 2>/dev/null\n"; if ($? == $::OK) { return $::OK; @@ -367,7 +367,7 @@ sub append_logging() { #my ($class, $logfile) = @_; my ($logfile) = @_; - my ($cmd, $rc); + my ($cmd, $rc); # # get log file ready @@ -402,10 +402,10 @@ sub append_logging() print "Output log is being written to \"$logfile\".\n"; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; print $::LOG_FILE_HANDLE "Logging started $sdate.\n"; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; return $::OK; } @@ -426,10 +426,10 @@ sub stop_logging() my $sdate = `/bin/date`; chomp $sdate; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; print $::LOG_FILE_HANDLE "Logging stopped $sdate.\n"; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; close($::LOG_FILE_HANDLE); $::LOG_FILE_HANDLE = undef; @@ -450,7 +450,7 @@ Arguments: sub getAIXGUIDS() { my ($refAIXNodes) = @_; - my $AIXNodes = join (",", @$refAIXNodes); + my $AIXNodes = join(",", @$refAIXNodes); print "Getting GUIDs from AIX nodes...\n"; print $::LOG_FILE_HANDLE "Getting GUIDs from AIX nodes...\n"; @@ -466,20 +466,20 @@ sub getAIXGUIDS() return $::NOK; } - my $oldhost = ""; - my $host = ""; - my $dev = ""; - my $guid = ""; - my $port = ""; - my $gid = ""; + my $oldhost = ""; + my $host = ""; + my $dev = ""; + my $guid = ""; + my $port = ""; + my $gid = ""; my $baseguid = ""; - my $lsw0 = ""; - my $lsw1 = ""; + my $lsw0 = ""; + my $lsw1 = ""; foreach my $line (@output) { chomp $line; - + # Get node hostname if ($line =~ /(\S*):.*/) { @@ -488,7 +488,7 @@ sub getAIXGUIDS() { print FILE "Node name is $host.\n"; print $::LOG_FILE_HANDLE "Node name is $host.\n"; - $oldhost=$host; + $oldhost = $host; } } @@ -502,23 +502,23 @@ sub getAIXGUIDS() if ($line =~ /.*\(GUID\):.*\s+(\S*)/) { $guid = $1; - $guid=~s/\.//g; - $baseguid=$guid; - $baseguid=~s/..$//; - $lsw0=$guid; - $lsw0=~s/..$/80/; - $lsw1=$guid; - $lsw1=~s/..$/81/; + $guid =~ s/\.//g; + $baseguid = $guid; + $baseguid =~ s/..$//; + $lsw0 = $guid; + $lsw0 =~ s/..$/80/; + $lsw1 = $guid; + $lsw1 =~ s/..$/81/; - print FILE "$host: $dev: baseguid: $baseguid\n"; - print FILE "$host: $dev: dev: $guid\n"; - print FILE "$host: $dev: lsw0: $lsw0\n"; - print FILE "$host: $dev: lsw1: $lsw1\n"; + print FILE "$host: $dev: baseguid: $baseguid\n"; + print FILE "$host: $dev: dev: $guid\n"; + print FILE "$host: $dev: lsw0: $lsw0\n"; + print FILE "$host: $dev: lsw1: $lsw1\n"; - print $::LOG_FILE_HANDLE "$host: $dev: baseguid: $baseguid\n"; - print $::LOG_FILE_HANDLE "$host: $dev: dev: $guid\n"; - print $::LOG_FILE_HANDLE "$host: $dev: lsw0: $lsw0\n"; - print $::LOG_FILE_HANDLE "$host: $dev: lsw1: $lsw1\n"; + print $::LOG_FILE_HANDLE "$host: $dev: baseguid: $baseguid\n"; + print $::LOG_FILE_HANDLE "$host: $dev: dev: $guid\n"; + print $::LOG_FILE_HANDLE "$host: $dev: lsw0: $lsw0\n"; + print $::LOG_FILE_HANDLE "$host: $dev: lsw1: $lsw1\n"; } # Get port number under device(iba) @@ -531,7 +531,7 @@ sub getAIXGUIDS() if ($line =~ /.*GUID\[.*\s+(\S*)/) { $gid = $1; - $gid=~s/\.//g; + $gid =~ s/\.//g; print FILE "$host: $dev: portGUID_$port: $gid\n"; print $::LOG_FILE_HANDLE "$host: $dev: portGUID_$port: $gid\n"; } @@ -553,9 +553,9 @@ Arguments: sub getLinuxGUIDS() { my ($refLnxNodes) = @_; - my $LnxNodes = join (",", @$refLnxNodes); + my $LnxNodes = join(",", @$refLnxNodes); - print + print "Getting GUIDs from Linux nodes...\n"; print $::LOG_FILE_HANDLE "Getting GUIDs from Linux nodes...\n"; @@ -566,26 +566,27 @@ sub getLinuxGUIDS() if ($?) { - print + print "Command failed: $getCmd.\n"; - print $::LOG_FILE_HANDLE + print $::LOG_FILE_HANDLE "Command failed: $getCmd.\n"; return $::NOK; } - my $oldhost = ""; - my $host =""; - my $dev = ""; - my $guid = ""; - my $port = ""; - my $gid = ""; + my $oldhost = ""; + my $host = ""; + my $dev = ""; + my $guid = ""; + my $port = ""; + my $gid = ""; my $baseguid = ""; - my $lsw0 = "" ; - my $lsw1 = ""; + my $lsw0 = ""; + my $lsw1 = ""; foreach my $line (@output) { chomp $line; + # Get node hostname if ($line =~ /(\S*):.*/) { @@ -594,27 +595,27 @@ sub getLinuxGUIDS() { print FILE "Node name is $host.\n"; print $::LOG_FILE_HANDLE "Node name is $host.\n"; - $oldhost=$host; + $oldhost = $host; } } # Get device name if ($line =~ /.*hca_id:\s(\S*).*/) { - $dev = $1; + $dev = $1; } # Get node_guid under hca_id if ($line =~ /.*node_guid:\s*(\S*)/) { $guid = $1; - $guid =~s/://g; + $guid =~ s/://g; $baseguid = $guid; - $baseguid =~s/..$//; + $baseguid =~ s/..$//; $lsw0 = $guid; - $lsw0 =~s/..$/80/; + $lsw0 =~ s/..$/80/; $lsw1 = $guid; - $lsw1 =~s/..$/81/; + $lsw1 =~ s/..$/81/; print FILE "$host: $dev: baseguid: $baseguid\n"; print FILE "$host: $dev: dev: $guid\n"; @@ -637,9 +638,9 @@ sub getLinuxGUIDS() if ($line =~ /.*GID.* *(\S*:\S*:\S*:\S*).*/) { $gid = $1; - $gid=~s/://g; - my $prefix = substr $baseguid, 0, 4; - $gid = $prefix . $gid; + $gid =~ s/://g; + my $prefix = substr $baseguid, 0, 4; + $gid = $prefix . $gid; print FILE "$host: $dev: portGUID_$port: $gid\n"; print $::LOG_FILE_HANDLE "$host: $dev: portGUID_$port: $gid\n"; } diff --git a/xCAT-server/share/xcat/ib/scripts/healthCheck b/xCAT-server/share/xcat/ib/scripts/healthCheck index e71975c1e..fb3dd451e 100644 --- a/xCAT-server/share/xcat/ib/scripts/healthCheck +++ b/xCAT-server/share/xcat/ib/scripts/healthCheck @@ -6,15 +6,15 @@ # Command: healthCheck # # # #-------------------------------------------------------------------------# -# This script is used to check the system health for both AIX and +# This script is used to check the system health for both AIX and # Linux Managed Nodes on Power6 platforms. It will use xdsh to access # the target nodes, and check the status for processor clock speed, # IB interfaces, memory, large page configuration and HCA status. -# If xdsh is unreachable, an error message will be given. +# If xdsh is unreachable, an error message will be given. # Command Syntax: # healthCheck { [-n node_list] [-M]} # {[-p min_clock_speed] [-i method] [-m min_memory] -# [-l min_freelp] [ -H [--speed speed --ignore interface_list --width width]]} +# [-l min_freelp] [ -H [--speed speed --ignore interface_list --width width]]} # [ -h ] # # -M Check status for all the Managed Nodes that are defined on this MN. @@ -23,7 +23,7 @@ # -p min_clock_speed # Specifies the minimal processor clock speed in MHz for processor monitor. # -i method -# Specifies the method to do Infiniband interface status check, the supported +# Specifies the method to do Infiniband interface status check, the supported # check methods are LL and RSCT. # -m min_memory # Specifies the minimal total memory in MB. @@ -33,7 +33,7 @@ # --speed speed # Specifies the physical port speed in G bps, it should be used with -H flag. # --ignore interface_list -# Specifies a comma-separated list of interface name to ignore from HCA status check, +# Specifies a comma-separated list of interface name to ignore from HCA status check, # such as ib0,ib1. It should be used with -H flag. # --width width # Specifies the physical port width, such as 4X or 12X. It should be used with -H flag. @@ -48,28 +48,29 @@ use Getopt::Long; # Log file $::HEALTHCHECK_PATH = "/var/log/xcat"; -$::HEALTHCHECK_LOG = "$::HEALTHCHECK_PATH/healthCheck.log"; +$::HEALTHCHECK_LOG = "$::HEALTHCHECK_PATH/healthCheck.log"; # variables and Commands -$::OK = 0; -$::NOK = 1; -$::logging = 0; -$::GLOBAL_EXIT = 0; -$::NODELS = "/opt/xcat/bin/nodels"; +$::OK = 0; +$::NOK = 1; +$::logging = 0; +$::GLOBAL_EXIT = 0; +$::NODELS = "/opt/xcat/bin/nodels"; $::LinuxProcCmd = "cat /proc/cpuinfo"; -$::AIXProcCmd = "/usr/pmapi/tools/pmcycles"; -$::IBifLLCmdL = "/opt/ibmll/LoadL/full/bin/llstatus"; -$::IBifLLCmdA = "/usr/lpp/LoadL/full/bin/llstatus"; -$::IBifRSCTCmd = "/usr/bin/lsrsrc"; -$::AIXMemCmd = "/usr/bin/vmstat"; -$::LinuxMemCmd = "cat /proc/meminfo"; -$::AIXHCACmd = "/usr/bin/ibstat"; -$::LinuxHCACmd = "/usr/bin/ibv_devinfo"; +$::AIXProcCmd = "/usr/pmapi/tools/pmcycles"; +$::IBifLLCmdL = "/opt/ibmll/LoadL/full/bin/llstatus"; +$::IBifLLCmdA = "/usr/lpp/LoadL/full/bin/llstatus"; +$::IBifRSCTCmd = "/usr/bin/lsrsrc"; +$::AIXMemCmd = "/usr/bin/vmstat"; +$::LinuxMemCmd = "cat /proc/meminfo"; +$::AIXHCACmd = "/usr/bin/ibstat"; +$::LinuxHCACmd = "/usr/bin/ibv_devinfo"; #Nodes to be checked my @NodeList; my @LnxNodeList; my @AIXNodeList; + #Ignored ib interfaces when checking HCA status my @IgnoreList; @@ -89,7 +90,7 @@ if (scalar(@NodeList) > 0) { my $rc = &checkDshReachability($node); if ($rc == 0) - { # xdsh is ok + { # xdsh is ok push @ReachableNodes, $node; } else @@ -98,9 +99,9 @@ if (scalar(@NodeList) > 0) } } - if (scalar (@UnreachableNodes)) + if (scalar(@UnreachableNodes)) { - my $UnreachableNodes = join (", ", @UnreachableNodes); + my $UnreachableNodes = join(", ", @UnreachableNodes); print "Warning: The xdsh is unreachable for the node(s): $UnreachableNodes. Run updatenode to configure xdsh for that node(s).\n"; print $::LOG_FILE_HANDLE "Warning: The xdsh is unreachable for the node(s): $UnreachableNodes. Run updatenode to configure xdsh for that node(s).\n"; } @@ -123,18 +124,18 @@ chomp @AllAIXNodes; foreach my $node (@ReachableNodes) { - if ( grep {$_ =~ /$node/} @AllLnxNodes ) + if (grep { $_ =~ /$node/ } @AllLnxNodes) { push @LnxNodeList, $node; } - if ( grep {$_ =~ /$node/} @AllAIXNodes ) + if (grep { $_ =~ /$node/ } @AllAIXNodes) { push @AIXNodeList, $node; } } #Do health check for Linux nodes and AIX nodes -if (scalar (@LnxNodeList)) +if (scalar(@LnxNodeList)) { my $rc = &healthCheckLinux(\@LnxNodeList); if ($rc) @@ -143,7 +144,7 @@ if (scalar (@LnxNodeList)) exit; } } -if (scalar (@AIXNodeList)) +if (scalar(@AIXNodeList)) { my $rc = &healthCheckAIX(\@AIXNodeList); if ($rc) @@ -156,17 +157,18 @@ if (scalar (@AIXNodeList)) # Finish up and exit END { - if ($::logging) + if ($::logging) { - &stop_logging(); - } - #Determine exit code - if ($::GLOBAL_EXIT > $?) + &stop_logging(); + } + + #Determine exit code + if ($::GLOBAL_EXIT > $?) { - $? = $::GLOBAL_EXIT; - } + $? = $::GLOBAL_EXIT; + } } -exit; # end of Main +exit; # end of Main #-------------------------------------------------------------------------------- @@ -198,7 +200,7 @@ sub getArgs() exit; } if (!$rc) - { #There are syntax errors in parameters + { #There are syntax errors in parameters &usage(); $::GLOBAL_EXIT = $::NOK; exit; @@ -213,25 +215,25 @@ sub getArgs() exit; } } - if(!defined($::MIN_CLOCK_SPEED) && !defined($::IF_CHECK_METHOD) && !defined($::MIN_MEMORY) && !defined($::MIN_FREELP) && !defined($::HCA)) + if (!defined($::MIN_CLOCK_SPEED) && !defined($::IF_CHECK_METHOD) && !defined($::MIN_MEMORY) && !defined($::MIN_FREELP) && !defined($::HCA)) { print "There is nothing to check. Please specify what you want to check.\n"; &usage(); $::GLOBAL_EXIT = $::NOK; exit; } - - if(!defined($::HCA) && (defined($::HCASPEED) || $::IGNORE_LIST ne "" || $::WIDTH ne "")) + + if (!defined($::HCA) && (defined($::HCASPEED) || $::IGNORE_LIST ne "" || $::WIDTH ne "")) { print "The flag --speed, --ignore or --width should be used with -H flag.\n"; &usage(); $::GLOBAL_EXIT = $::NOK; exit; } - - if($::WIDTH ne "") + + if ($::WIDTH ne "") { - if(!($::WIDTH =~ /^(\d+)X$/)) + if (!($::WIDTH =~ /^(\d+)X$/)) { print "The parameter of --width should be 4X, 12X, etc.\n"; &usage(); @@ -242,13 +244,13 @@ sub getArgs() #Parse the node list if ($::NODE_LIST) - { + { @NodeList = `$::NODELS $::NODE_LIST`; chomp @NodeList; if ($?) { - print $::LOG_FILE_HANDLE "Running command: $::NODELS $::NODE_LIST fail\n"; + print $::LOG_FILE_HANDLE "Running command: $::NODELS $::NODE_LIST fail\n"; exit; } else { - print $::LOG_FILE_HANDLE "Running command: $::NODELS $::NODE_LIST\n"; + print $::LOG_FILE_HANDLE "Running command: $::NODELS $::NODE_LIST\n"; } } @@ -257,7 +259,7 @@ sub getArgs() { my @templist = `$::NODELS`; chomp @templist; - print $::LOG_FILE_HANDLE "Running command: lsnode -w \"Mode='Managed' or Mode='MinManaged'\"\n"; + print $::LOG_FILE_HANDLE "Running command: lsnode -w \"Mode='Managed' or Mode='MinManaged'\"\n"; @NodeList = @templist; } if ($::IGNORE_LIST) @@ -277,7 +279,7 @@ sub getArgs() sub usage() { print -"Usage: healthCheck { [-n node_list] [-M]} + "Usage: healthCheck { [-n node_list] [-M]} {[-p min_clock_speed] [-i method] [-m min_memory] [-l min_freelp] [ -H [--speed speed --ignore interface_list --width width]]} [ -h ] @@ -303,7 +305,7 @@ sub usage() --width width Specifies the physical port width, such as 4X or 12X. It should be used with -H flag. -h Display usage information. -"; +"; } #-------------------------------------------------------------------------------- @@ -327,7 +329,7 @@ sub checkDshReachability() { my ($node) = @_; my $output = `xdsh $node date 2>/dev/null`; - print $::LOG_FILE_HANDLE "Running command: xdsh $node date 2>/dev/null\n"; + print $::LOG_FILE_HANDLE "Running command: xdsh $node date 2>/dev/null\n"; if ($? == $::OK) { return $::OK; @@ -356,7 +358,7 @@ sub checkCmdAvailability my @BadNodes; foreach my $node (@$refNodes) { - #Use xdsh to "ls" the command + #Use xdsh to "ls" the command `xdsh $node ls $cmd 2>/dev/null`; print $::LOG_FILE_HANDLE "Running command: xdsh $node ls $cmd 2>/dev/null\n"; if ($? == $::OK) @@ -369,9 +371,9 @@ sub checkCmdAvailability } } - if (scalar (@BadNodes)) + if (scalar(@BadNodes)) { - my $BadNodes = join (", ", @BadNodes); + my $BadNodes = join(", ", @BadNodes); print "Warning: The command $cmd is not available on the node(s): $BadNodes.\n"; print $::LOG_FILE_HANDLE "Warning: The command $cmd is not available on the node(s): $BadNodes.\n"; } @@ -390,12 +392,13 @@ sub checkCmdAvailability sub append_logging() { my ($logfile) = @_; - my ($cmd, $rc); + my ($cmd, $rc); # get log file ready if (!-e $logfile) { `mkdir -p $::HEALTHCHECK_PATH`; + # create the log file if not already there unless (open(LOGFILE, ">$logfile")) { @@ -422,10 +425,10 @@ sub append_logging() print "Output log is being written to \"$logfile\".\n"; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; print $::LOG_FILE_HANDLE "Logging started $sdate.\n"; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; return $::OK; } @@ -445,10 +448,10 @@ sub stop_logging() my $sdate = `/bin/date`; chomp $sdate; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; print $::LOG_FILE_HANDLE "Logging stopped $sdate.\n"; print $::LOG_FILE_HANDLE - "---------------------------------------------------------------------\n"; + "---------------------------------------------------------------------\n"; close($::LOG_FILE_HANDLE); $::LOG_FILE_HANDLE = undef; @@ -471,16 +474,16 @@ sub healthCheckLinux() my ($refLnxNodes) = @_; my $allnodes = join ", ", @$refLnxNodes; print "Checking health for Linux nodes: $allnodes...\n"; - print $::LOG_FILE_HANDLE "Checking health for Linux nodes: $allnodes...\n"; + print $::LOG_FILE_HANDLE "Checking health for Linux nodes: $allnodes...\n"; my $rc; - if ( defined($::MIN_CLOCK_SPEED) ) + if (defined($::MIN_CLOCK_SPEED)) { $rc = procsrCheckLinux($refLnxNodes); if ($rc != $::OK) { return $::NOK; } } - if ( defined($::MIN_MEMORY) || defined($::MIN_FREELP) ) + if (defined($::MIN_MEMORY) || defined($::MIN_FREELP)) { $rc = memCheckLinux($refLnxNodes); if ($rc != $::OK) @@ -488,7 +491,7 @@ sub healthCheckLinux() return $::NOK; } } - if ( $::IF_CHECK_METHOD ne "" ) + if ($::IF_CHECK_METHOD ne "") { $rc = ifCheck($refLnxNodes, 'Linux'); if ($rc != $::OK) @@ -496,7 +499,7 @@ sub healthCheckLinux() return $::NOK; } } - if ( defined($::HCA) ) + if (defined($::HCA)) { $rc = HCACheckLinux($refLnxNodes); if ($rc != $::OK) @@ -522,9 +525,9 @@ sub healthCheckAIX() my $allnodes = join ", ", @$refAIXNodes; print "Checking health for AIX nodes: $allnodes...\n"; print $::LOG_FILE_HANDLE "Checking health for AIX nodes: $allnodes...\n"; - + my $rc; - if ( defined($::MIN_CLOCK_SPEED) ) + if (defined($::MIN_CLOCK_SPEED)) { $rc = procsrCheckAIX($refAIXNodes); if ($rc != $::OK) @@ -532,7 +535,7 @@ sub healthCheckAIX() return $::NOK; } } - if ( defined($::MIN_MEMORY) || defined($::MIN_FREELP) ) + if (defined($::MIN_MEMORY) || defined($::MIN_FREELP)) { $rc = memCheckAIX($refAIXNodes); if ($rc != $::OK) @@ -540,7 +543,7 @@ sub healthCheckAIX() return $::NOK; } } - if ( $::IF_CHECK_METHOD ne "" ) + if ($::IF_CHECK_METHOD ne "") { $rc = ifCheck($refAIXNodes, 'AIX'); if ($rc != $::OK) @@ -548,7 +551,7 @@ sub healthCheckAIX() return $::NOK; } } - if ( defined($::HCA) ) + if (defined($::HCA)) { $rc = HCACheckAIX($refAIXNodes); if ($rc != $::OK) @@ -571,7 +574,7 @@ Arguments: sub procsrCheckLinux() { my ($refLnxNodes) = @_; - my $ValidLnxNodes = join (",", @$refLnxNodes); + my $ValidLnxNodes = join(",", @$refLnxNodes); print "\nChecking processor clock speed for nodes: $ValidLnxNodes...\n"; print $::LOG_FILE_HANDLE "Checking processor clock speed for nodes: $ValidLnxNodes...\n"; @@ -584,7 +587,7 @@ sub procsrCheckLinux() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + my $host; my $pcrnum; my $clspeed; @@ -592,6 +595,7 @@ sub procsrCheckLinux() foreach my $line (@output) { chomp $line; + # Get node hostname if ($line =~ /(\S*):.*/) { @@ -646,14 +650,14 @@ sub procsrCheckAIX() my $allnodes = join ", ", @$refAIXNodes; print "\nChecking processor clock speed for nodes: $allnodes...\n"; print $::LOG_FILE_HANDLE "Checking processor clock speed for nodes: $allnodes...\n"; - + @ValidAIXNodes = &checkCmdAvailability($refAIXNodes, $::AIXProcCmd); - if (!scalar (@ValidAIXNodes)) + if (!scalar(@ValidAIXNodes)) { return $::NOK; } - my $ValidAIXNodes = join (",", @ValidAIXNodes); + my $ValidAIXNodes = join(",", @ValidAIXNodes); my $checkCmd = "xdsh $ValidAIXNodes \"$::AIXProcCmd\" 2>/dev/null"; print $::LOG_FILE_HANDLE "Running command: $checkCmd.\n"; my @output = `$checkCmd`; @@ -662,13 +666,14 @@ sub procsrCheckAIX() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + my $host; my $pcrnum; my $clspeed; foreach my $line (@output) { chomp $line; + # Get node hostname if ($line =~ /(\S*):.*/) { @@ -686,7 +691,7 @@ sub procsrCheckAIX() } } } - if(!$abnormal) + if (!$abnormal) { print "The processor clock speed of all nodes is normal.\n"; print $::LOG_FILE_HANDLE "The processor clock speed of all nodes is normal.\n"; @@ -712,7 +717,7 @@ sub ifCheck() my $cmd; my $abnormal = 0; my $allnodes = join ", ", @$refNodes; - + if ($::IF_CHECK_METHOD eq "LL") { if ($os eq 'Linux') @@ -736,19 +741,19 @@ sub ifCheck() { return $::NOK; } - + print "\nChecking IB interface status using command $cmd for nodes: $allnodes...\n"; print $::LOG_FILE_HANDLE "Checking IB interface status using command $cmd for nodes: $allnodes...\n"; - + @ValidNodes = &checkCmdAvailability($refNodes, $cmd); - - if (!scalar (@ValidNodes)) + + if (!scalar(@ValidNodes)) { return $::NOK; } - - my $ValidNodes = join (",", @ValidNodes); - + + my $ValidNodes = join(",", @ValidNodes); + #Method is "LL" if ($::IF_CHECK_METHOD eq "LL") { @@ -761,67 +766,72 @@ sub ifCheck() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + #Record whether the next line is the beginning of a new section my $armed = 0; my $ibnum; my $host; + #Record abnormal ib interfaces of a node my @ib_array = (); foreach my $line (@output) { chomp $line; + #The text returned by llstatus is seperared into several sections by "==================" if ($line =~ /==================/) { #If there are abnormal interfaces found after check last section - if ( @ib_array ) + if (@ib_array) { print "$host IB interface(s) down: "; print $::LOG_FILE_HANDLE "$host IB interface(s) down: "; foreach (sort @ib_array) - { - print "ib$_ " ; - print $::LOG_FILE_HANDLE "ib$_ " ; + { + print "ib$_ "; + print $::LOG_FILE_HANDLE "ib$_ "; } print "\n"; print $::LOG_FILE_HANDLE "\n"; } @ib_array = (); - $armed = 1; + $armed = 1; } - elsif ( ( $armed ) && ($line =~ /\S+?:\s*(\S+)/) ) - { #The first line of a new section - #Get node hostname - $host = $1; + elsif (($armed) && ($line =~ /\S+?:\s*(\S+)/)) + { #The first line of a new section + #Get node hostname + $host = $1; $armed = 0; } - elsif ( $line =~ /\S+?:\s*ib(\d+).*/ ) + elsif ($line =~ /\S+?:\s*ib(\d+).*/) { #Get interface number $ibnum = $1; + #Check the status - if ( ! ($line =~ /READY/) ) + if (!($line =~ /READY/)) { - $abnormal = 1; + $abnormal = 1; push @ib_array, $ibnum; } } } + #If there are abnormal interfaces found after check the last section - if ( @ib_array ) + if (@ib_array) { print "$host IB interface(s) down: "; print $::LOG_FILE_HANDLE "$host IB interface(s) down: "; foreach (sort @ib_array) - { - print "ib$_ " ; - print $::LOG_FILE_HANDLE "ib$_ " ; + { + print "ib$_ "; + print $::LOG_FILE_HANDLE "ib$_ "; } print "\n"; print $::LOG_FILE_HANDLE "\n"; } } + #Method is "RSCT" elsif ($::IF_CHECK_METHOD eq "RSCT") { @@ -845,6 +855,7 @@ sub ifCheck() { #Get node hostname $host = $1; + #If the host is not equal prevhost, it indicates this is beginning of a section for another node. #If there are abnormal interfaces found after check last node, print them. if (($host ne $prevhost) && @ib_array) @@ -852,15 +863,15 @@ sub ifCheck() print "$prevhost IB interface(s) down: "; print $::LOG_FILE_HANDLE "$prevhost IB interface(s) down: "; foreach (sort @ib_array) - { - print "$_ " ; - print $::LOG_FILE_HANDLE "$_ " ; + { + print "$_ "; + print $::LOG_FILE_HANDLE "$_ "; } print "\n"; print $::LOG_FILE_HANDLE "\n"; @ib_array = (); } - $prevhost = $host; + $prevhost = $host; } if ($line =~ /\S*:\s*Name\s*=\s*\"(.*)\"/) { @@ -878,21 +889,22 @@ sub ifCheck() } } } + #If there are abnormal interfaces found after check the last node, print them. if (@ib_array) { print "$host IB interface(s) down: "; print $::LOG_FILE_HANDLE "$host IB interface(s) down: "; foreach (sort @ib_array) - { - print "$_ " ; - print $::LOG_FILE_HANDLE "$_ " ; + { + print "$_ "; + print $::LOG_FILE_HANDLE "$_ "; } print "\n"; print $::LOG_FILE_HANDLE "\n"; } } - if(!$abnormal) + if (!$abnormal) { print "IB interfaces of all nodes are normal.\n"; print $::LOG_FILE_HANDLE "IB interfaces of all nodes are normal.\n"; @@ -913,9 +925,9 @@ Arguments: sub memCheckLinux() { my ($refLnxNodes) = @_; - my $abnormalmem = 0; - my $abnormalflp = 0; - my $ValidLnxNodes = join (",", @$refLnxNodes); + my $abnormalmem = 0; + my $abnormalflp = 0; + my $ValidLnxNodes = join(",", @$refLnxNodes); print "\nChecking memory for nodes: $ValidLnxNodes...\n"; print $::LOG_FILE_HANDLE "Checking memory for nodes: $ValidLnxNodes...\n"; @@ -928,7 +940,7 @@ sub memCheckLinux() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + my $host; my $mem; my $freelp; @@ -939,7 +951,7 @@ sub memCheckLinux() { # Get node hostname and memory size $host = $1; - $mem = $2; + $mem = $2; if ($mem < ($::MIN_MEMORY * 1000)) { $abnormalmem = 1; @@ -951,7 +963,7 @@ sub memCheckLinux() if ($line =~ /(\S*): HugePages_Free:\s*(\d+)/ && defined($::MIN_FREELP)) { # Get node hostname and number of free large page - $host = $1; + $host = $1; $freelp = $2; if ($freelp < $::MIN_FREELP) { @@ -961,12 +973,12 @@ sub memCheckLinux() } } } - if(!$abnormalmem && defined($::MIN_MEMORY)) + if (!$abnormalmem && defined($::MIN_MEMORY)) { print "Memory size of all nodes are normal.\n"; print $::LOG_FILE_HANDLE "Memory size of all nodes are normal.\n" } - if(!$abnormalflp && defined($::MIN_FREELP)) + if (!$abnormalflp && defined($::MIN_FREELP)) { print "Free large page number of all nodes are normal.\n"; print $::LOG_FILE_HANDLE "Free large page number of all nodes are normal.\n"; @@ -987,20 +999,20 @@ Arguments: sub memCheckAIX() { my ($refAIXNodes) = @_; - my $abnormalmem = 0; - my $abnormalflp = 0; + my $abnormalmem = 0; + my $abnormalflp = 0; my @ValidAIXNodes; my $allnodes = join ", ", @$refAIXNodes; print "\nChecking memory for nodes $allnodes...\n"; print $::LOG_FILE_HANDLE "Checking memory for nodes $allnodes...\n"; - + @ValidAIXNodes = &checkCmdAvailability($refAIXNodes, $::AIXMemCmd); - - if (!scalar (@ValidAIXNodes)) + + if (!scalar(@ValidAIXNodes)) { return $::NOK; } - my $ValidAIXNodes = join (",", @ValidAIXNodes); + my $ValidAIXNodes = join(",", @ValidAIXNodes); my $checkCmd = "xdsh $ValidAIXNodes \"$::AIXMemCmd -l\" 2>/dev/null"; print $::LOG_FILE_HANDLE "Running command: $checkCmd.\n"; @@ -1010,18 +1022,18 @@ sub memCheckAIX() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + my $host; my $mem; my $freelp; foreach my $line (@output) { - chomp $line; + chomp $line; if ($line =~ /(\S*):\s+System Configuration: lcpu=(\d+)\s+mem=(\d+)\s*MB/ && defined($::MIN_MEMORY)) { # Get node hostname and memory size $host = $1; - $mem = $3; + $mem = $3; if ($mem < $::MIN_MEMORY) { $abnormalmem = 1; @@ -1032,7 +1044,7 @@ sub memCheckAIX() elsif ($line =~ /(\S*):\s*\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)/ && defined($::MIN_FREELP)) { # Get node hostname and number of free large page - $host = $1; + $host = $1; $freelp = $2; if ($freelp < $::MIN_FREELP) { @@ -1045,7 +1057,7 @@ sub memCheckAIX() { # Get node hostname and memory size $host = $1; - $mem = $3; + $mem = $3; if ($mem < $::MIN_MEMORY) { $abnormalmem = 1; @@ -1054,12 +1066,12 @@ sub memCheckAIX() } } } - if(!$abnormalmem && defined($::MIN_MEMORY)) + if (!$abnormalmem && defined($::MIN_MEMORY)) { print "Memory size of all nodes are normal.\n"; print $::LOG_FILE_HANDLE "Memory size of all nodes are normal.\n" } - if(!$abnormalflp && defined($::MIN_FREELP)) + if (!$abnormalflp && defined($::MIN_FREELP)) { print "Free large page number of all nodes is normal.\n"; print $::LOG_FILE_HANDLE "Free large page number of all nodes is normal.\n"; @@ -1085,14 +1097,14 @@ sub HCACheckAIX() my $allnodes = join ", ", @$refAIXNodes; print "\nChecking HCA status for nodes $allnodes...\n"; print $::LOG_FILE_HANDLE "Checking HCA status for nodes $allnodes...\n"; - + @ValidAIXNodes = &checkCmdAvailability($refAIXNodes, $::AIXHCACmd); - if (!scalar (@ValidAIXNodes)) + if (!scalar(@ValidAIXNodes)) { return $::NOK; } - my $ValidAIXNodes = join (",", @ValidAIXNodes); + my $ValidAIXNodes = join(",", @ValidAIXNodes); my $checkCmd = "xdsh $ValidAIXNodes \"$::AIXHCACmd -v | egrep 'IB PORT.*INFO|Port State:|Physical Port'\" 2>/dev/null"; print $::LOG_FILE_HANDLE "Running command: $checkCmd.\n"; my @output = `$checkCmd`; @@ -1101,7 +1113,7 @@ sub HCACheckAIX() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + my $host; my $hca_id; my $port; @@ -1110,20 +1122,24 @@ sub HCACheckAIX() foreach my $line (@output) { chomp $line; + #Get host name if ($line =~ /(\S*): (.*)/) { $host = $1; } + #Get HCA ID and port number if ($line =~ /\S*:\s*IB PORT (\d+) INFORMATION \(iba(\d+)\)/) { - $port = $1; + $port = $1; $hca_id = $2; + #Calculate interface number according to HCA ID and port number $if_id = $hca_id * 2 + $port - 1; + #If the interface is in ignore list - if ( grep {$_ eq "ib$if_id"} @IgnoreList ) + if (grep { $_ eq "ib$if_id" } @IgnoreList) { $ignore = 1; } @@ -1133,6 +1149,7 @@ sub HCACheckAIX() } next; } + #Check Logical Port State if ($line =~ /\S*:\s*Logical Port State:\s*(\w+)/ && $ignore == 0) { @@ -1149,6 +1166,7 @@ sub HCACheckAIX() } next; } + #Check Physical Port State if ($line =~ /\S*:\s*Physical Port State:\s*(\w+)/ && $ignore == 0) { @@ -1165,6 +1183,7 @@ sub HCACheckAIX() } next; } + #Check Physical Port Physical State if ($line =~ /\S*:\s*Physical Port Physical State:\s*(\.+)/ && $ignore == 0) { @@ -1181,6 +1200,7 @@ sub HCACheckAIX() } next; } + #Check speed if ($line =~ /\S*:\s*Physical Port Speed:\s*(.+)\s*G/ && $ignore == 0) { @@ -1202,6 +1222,7 @@ sub HCACheckAIX() } next; } + #Ckeck width if ($line =~ /\S*:\s*Physical Port Width:\s*(\w+)/ && $ignore == 0) { @@ -1224,8 +1245,9 @@ sub HCACheckAIX() next; } } + #All are normal - if(!$abnormal) + if (!$abnormal) { print "HCA status of all nodes is normal.\n"; print $::LOG_FILE_HANDLE "HCA status of all nodes is normal.\n"; @@ -1256,14 +1278,14 @@ sub HCACheckLinux() my $allnodes = join ", ", @$refLnxNodes; print "\nChecking HCA status for nodes: $allnodes...\n"; print $::LOG_FILE_HANDLE "Checking HCA status for nodes: $allnodes...\n"; - + @ValidLnxNodes = &checkCmdAvailability($refLnxNodes, $::LinuxHCACmd); - if (!scalar (@ValidLnxNodes)) + if (!scalar(@ValidLnxNodes)) { return $::NOK; } - my $ValidLnxNodes = join (",", @ValidLnxNodes); + my $ValidLnxNodes = join(",", @ValidLnxNodes); my $checkCmd = "xdsh $ValidLnxNodes \"$::LinuxHCACmd -v | egrep 'ehca|port:|state:|width:|speed:'\" 2>/dev/null"; print $::LOG_FILE_HANDLE "Running command: $checkCmd.\n"; my @output = `$checkCmd`; @@ -1272,7 +1294,7 @@ sub HCACheckLinux() print "Command failed: $checkCmd.\n"; print $::LOG_FILE_HANDLE "Command failed: $checkCmd.\n"; } - + my $host; my $hca_id; my $port; @@ -1281,25 +1303,29 @@ sub HCACheckLinux() foreach my $line (@output) { chomp $line; + #Get host name if ($line =~ /(\S*): (.*)/) { $host = $1; } + #Get HCA ID if ($line =~ /\S*:\s*hca_id:\s*ehca(\d+)/) { $hca_id = $1; next; } + #Get port number if ($line =~ /\S*:\s*port:\s*(\d+)/) { #Calculate interface number according to HCA ID and port number - $port = $1; + $port = $1; $if_id = $hca_id * 2 + $port - 1; + #If the interface is in ignore list - if ( grep {$_ eq "ib$if_id"} @IgnoreList ) + if (grep { $_ eq "ib$if_id" } @IgnoreList) { $ignore = 1; } @@ -1309,6 +1335,7 @@ sub HCACheckLinux() } next; } + #Check state if ($line =~ /\S*:\s*state:\s*(\w+)\s*\(.*/ && $ignore == 0) { @@ -1325,6 +1352,7 @@ sub HCACheckLinux() } next; } + #Check width if ($line =~ /\S*:\s*active_width:\s*(\w+)\s*\(.*/ && $ignore == 0) { @@ -1346,6 +1374,7 @@ sub HCACheckLinux() } next; } + #Check speed if ($line =~ /\S*:\s*active_speed:\s*(.+)\s*Gbps.*/ && $ignore == 0) { @@ -1367,6 +1396,7 @@ sub HCACheckLinux() } next; } + #Check Physical State if ($line =~ /\S*:\s*phys_state:\s*(\w+)\s*\(.*/ && $ignore == 0) { @@ -1384,8 +1414,9 @@ sub HCACheckLinux() next; } } + #All are normal - if(!$abnormal) + if (!$abnormal) { print "HCA status of all nodes is normal.\n"; print $::LOG_FILE_HANDLE "HCA status of all nodes is normal.\n"; diff --git a/xCAT-server/share/xcat/netboot/add-on/torque/pbsnodestat b/xCAT-server/share/xcat/netboot/add-on/torque/pbsnodestat index 51f7e62c5..580f7de6c 100755 --- a/xCAT-server/share/xcat/netboot/add-on/torque/pbsnodestat +++ b/xCAT-server/share/xcat/netboot/add-on/torque/pbsnodestat @@ -4,13 +4,13 @@ $/ = ''; -open(STAT,"pbsnodes -a |") || die "pbsnodes error\n"; -while() { - my $node = /^([a-zA-Z0-9\-]+)\b$/im ? $1 : ''; - my $state = / + state = (.*)$/im ? $1 : ''; - my $np = / + np = (.*)$/im ? $1 : ''; - my $jobs = / + jobs = (.*)$/im ? $1 : ''; - push @results, "$node: $state\t$jobs\n"; +open(STAT, "pbsnodes -a |") || die "pbsnodes error\n"; +while () { + my $node = /^([a-zA-Z0-9\-]+)\b$/im ? $1 : ''; + my $state = / + state = (.*)$/im ? $1 : ''; + my $np = / + np = (.*)$/im ? $1 : ''; + my $jobs = / + jobs = (.*)$/im ? $1 : ''; + push @results, "$node: $state\t$jobs\n"; } print @results; diff --git a/xCAT-server/share/xcat/netboot/debian/genimage b/xCAT-server/share/xcat/netboot/debian/genimage index 162355fbd..bd6a6b9d5 100755 --- a/xCAT-server/share/xcat/netboot/debian/genimage +++ b/xCAT-server/share/xcat/netboot/debian/genimage @@ -11,12 +11,13 @@ use File::Copy; use File::Find; use Getopt::Long; use Cwd qw(realpath); + #use strict; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -24,20 +25,21 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + #that this method of calling genimage is no longer used if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -47,9 +49,9 @@ my $srcdir_otherpkgs; my $otherpkglist; my $postinstall_filename; my $rootimg_dir; -my $rwfiles; # these files are used by statelite for tmpfs rw +my $rwfiles; # these files are used by statelite for tmpfs rw my $mode; -my $permission; # the permission works only for statelite mode currently +my $permission; # the permission works only for statelite mode currently my $tempfile; my $kerneldir; my $prompt; @@ -57,293 +59,302 @@ my $noupdate; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'm=s' => \$mode, - 'permission=s' => \$permission, - 'kerneldir=s' => \$kerneldir, - 'tempfile=s' =>\$tempfile, #internal flag - 'pkglist=s' => \$pkglist, #internal flag - 'srcdir=s' => \$srcdir, #internal flag - 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag - 'otherpkglist=s' => \$otherpkglist, #internal flag - 'postinstall=s' => \$postinstall_filename, #internal flag - 'rootimgdir=s' => \$destdir, #internal flag - 'interactive' =>\$prompt, - 'onlyinitrd' =>\$onlyinitrd, - 'noupdate' =>\$noupdate, + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'm=s' => \$mode, + 'permission=s' => \$permission, + 'kerneldir=s' => \$kerneldir, + 'tempfile=s' => \$tempfile, #internal flag + 'pkglist=s' => \$pkglist, #internal flag + 'srcdir=s' => \$srcdir, #internal flag + 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag + 'otherpkglist=s' => \$otherpkglist, #internal flag + 'postinstall=s' => \$postinstall_filename, #internal flag + 'rootimgdir=s' => \$destdir, #internal flag + 'interactive' => \$prompt, + 'onlyinitrd' => \$onlyinitrd, + 'noupdate' => \$noupdate, ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } -my %updates_os = (); # the hash for updating osimage table -my %updates = (); # the hash for updating linuximage table +my %updates_os = (); # the hash for updating osimage table +my %updates = (); # the hash for updating linuximage table if ($mode eq "statelite") { if (!$permission) { $permission = "755"; } - $updates{'permission'} = $permission if ( $tempfile ); + $updates{'permission'} = $permission if ($tempfile); } if (!$arch) { $arch = `uname -m`; chomp($arch); if ($arch =~ /i.86$/) { - $arch = "x86"; + $arch = "x86"; } } -if (!$srcdir) { - $srcdir="$installroot/$osver/$arch"; +if (!$srcdir) { + $srcdir = "$installroot/$osver/$arch"; } $updates{'pkgdir'} = $srcdir if ($tempfile); -if (!$srcdir_otherpkgs) { +if (!$srcdir_otherpkgs) { $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch"; } $updates{'otherpkgdir'} = $srcdir_otherpkgs if ($tempfile); if (!$destdir) { - $destdir="$installroot/netboot/$osver/$arch/$profile"; + $destdir = "$installroot/netboot/$osver/$arch/$profile"; } $updates{'rootimgdir'} = $destdir if ($tempfile); -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; unless ($osver and $profile and $netdriver and $prinic) { usage(); - exit 1; + exit 1; } if ($netdriver) { - if ( ($updates{'netdrivers'} ne $netdriver) and ($tempfile) ) { + if (($updates{'netdrivers'} ne $netdriver) and ($tempfile)) { $updates{'netdrivers'} = $netdriver; } } my @ndrivers; -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - if (/^$/) { - next; - } - push @ndrivers,$_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + if (/^$/) { + next; + } + push @ndrivers, $_; } -if($mode eq "statelite"){ - push @ndrivers,"fscache.ko"; - push @ndrivers,"sunrpc.ko"; - push @ndrivers,"lockd.ko"; - push @ndrivers,"nfs_acl.ko"; - push @ndrivers,"nfs.ko"; +if ($mode eq "statelite") { + push @ndrivers, "fscache.ko"; + push @ndrivers, "sunrpc.ko"; + push @ndrivers, "lockd.ko"; + push @ndrivers, "nfs_acl.ko"; + push @ndrivers, "nfs.ko"; } -my $uarch=$arch; +my $uarch = $arch; -if ( $arch eq x86_64 ) +if ($arch eq x86_64) { - $uarch="amd64"; + $uarch = "amd64"; } unless ($onlyinitrd) { - @aptdirs=(); - find(\&isaptdir, <$installroot/$osver/$arch/>); - unless (scalar(@aptdirs)) { - #unless ( -d $srcdir."/dists/stable/main/binary-$uarch/Packages.gz" ) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + @aptdirs = (); + find(\&isaptdir, <$installroot/$osver/$arch/>); + unless (scalar(@aptdirs)) { - my $aptconfig; - open($aptconfig,">","/tmp/genimage.$$.apt.list"); - my $repnum=0; - foreach $srcdir (@aptdirs) { - print $aptconfig "deb file://$srcdir main stable\n\n"; - $repnum += 1; - } - $repnum-=1; - close($aptconfig); - mkpath "$rootimg_dir/etc"; + #unless ( -d $srcdir."/dists/stable/main/binary-$uarch/Packages.gz" ) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } - my $non_interactive; - if (!$prompt) { $non_interactive="-y"; } + my $aptconfig; + open($aptconfig, ">", "/tmp/genimage.$$.apt.list"); + my $repnum = 0; + foreach $srcdir (@aptdirs) { + print $aptconfig "deb file://$srcdir main stable\n\n"; + $repnum += 1; + } + $repnum -= 1; + close($aptconfig); + mkpath "$rootimg_dir/etc"; - my $fd; - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); + my $non_interactive; + if (!$prompt) { $non_interactive = "-y"; } - + my $fd; + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); - my @line=split(" ",`ls -lh $installroot/$osver/$arch/dists/ | grep dr`); - #print "$line\n"; - #print "$index\n"; - my $dist = $line[@line-1]; - my $aptcmd1 = "debootstrap"; - my $aptcmd2 = "--arch $uarch $dist $rootimg_dir file://$installroot/$osver/$arch/"; - #foreach (0..$repnum) { - # $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - #} - - #yumcmd .= "install "; - #mkpath("$rootimg_dir/var/lib/yum"); - if (!$imagename) { - $pkglist= get_profile_def_filename($customdir,"pkglist"); - if (!$pkglist) { - $pkglist= get_profile_def_filename($pathtofiles, "pkglist"); - } - } + my @line = split(" ", `ls -lh $installroot/$osver/$arch/dists/ | grep dr`); - if ($pkglist) { - $updates{'pkglist'} = $pkglist if ($tempfile); - } else { - print "Unable to find package list for $profile!"; - exit 1; - } + #print "$line\n"; + #print "$index\n"; + my $dist = $line[ @line - 1 ]; - my %pkg_hash=get_package_names($pkglist); - my $index=1; - my $pass; - foreach $pass (sort (keys(%pkg_hash))) { - my $pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - my $pa=$pkg_hash{$pass}{$_}; - $pkgnames .= "" . join(',', @$pa); - } + my $aptcmd1 = "debootstrap"; + my $aptcmd2 = "--arch $uarch $dist $rootimg_dir file://$installroot/$osver/$arch/"; - print "$aptcmd1 --include=$pkgnames $aptcmd2\n"; - my $rc = system("$aptcmd1 --include=$pkgnames $aptcmd2"); - if ($rc) { - print "apt invocation failed\n"; - exit 1; - } - } + #foreach (0..$repnum) { + # $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + #} + + #yumcmd .= "install "; + #mkpath("$rootimg_dir/var/lib/yum"); - #Now let's handle extra packages if (!$imagename) { - $otherpkglist=get_profile_def_filename($customdir, "otherpkgs.pkglist"); - if (!$otherpkglist) { $otherpkglist=get_profile_def_filename($pathtofiles, "otherpkgs.pkglist"); } + $pkglist = get_profile_def_filename($customdir, "pkglist"); + if (!$pkglist) { + $pkglist = get_profile_def_filename($pathtofiles, "pkglist"); + } } - my %extra_hash=(); + + if ($pkglist) { + $updates{'pkglist'} = $pkglist if ($tempfile); + } else { + print "Unable to find package list for $profile!"; + exit 1; + } + + my %pkg_hash = get_package_names($pkglist); + my $index = 1; + my $pass; + foreach $pass (sort (keys(%pkg_hash))) { + my $pkgnames = ""; + foreach (keys(%{ $pkg_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + my $pa = $pkg_hash{$pass}{$_}; + $pkgnames .= "" . join(',', @$pa); + } + + print "$aptcmd1 --include=$pkgnames $aptcmd2\n"; + my $rc = system("$aptcmd1 --include=$pkgnames $aptcmd2"); + if ($rc) { + print "apt invocation failed\n"; + exit 1; + } + } + + #Now let's handle extra packages + if (!$imagename) { + $otherpkglist = get_profile_def_filename($customdir, "otherpkgs.pkglist"); + if (!$otherpkglist) { $otherpkglist = get_profile_def_filename($pathtofiles, "otherpkgs.pkglist"); } + } + my %extra_hash = (); if ($otherpkglist) { - $updates{'otherpkglist'} = $otherpkglist if ($tempfile); - %extra_hash=get_package_names($otherpkglist); + $updates{'otherpkglist'} = $otherpkglist if ($tempfile); + %extra_hash = get_package_names($otherpkglist); } - my %extrapkgnames; + my %extrapkgnames; if (keys(%extra_hash) > 0) { - open($yumconfig,">>","/tmp/genimage.$$.yum.conf"); - my $index=1; - foreach $pass (sort (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; - $index++; - my $pa=$extra_hash{$pass}{$_}; - $extrapkgnames{$pass} .= " " . join(' ', @$pa); + open($yumconfig, ">>", "/tmp/genimage.$$.yum.conf"); + my $index = 1; + foreach $pass (sort (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; + $index++; + my $pa = $extra_hash{$pass}{$_}; + $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } + } + close($yumconfig); + $index--; + $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } + for (1 .. $index) { + $yumcmd .= "--enablerepo=otherpkgs$_ "; } - } - close($yumconfig); - $index--; - $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - for (1..$index) { - $yumcmd .= "--enablerepo=otherpkgs$_ "; - } - foreach $pass (sort (keys(%extra_hash))) { - #remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "$yumcmd erase "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } + foreach $pass (sort (keys(%extra_hash))) { + + #remove the packages that are specified in the otherpkgs.list files with leading '-' + my $yumcmd_remove = "$yumcmd erase "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } - #install extra packages - my $yumcmd_base = $yumcmd; - $yumcmd .= "install "; - #append extra pkg names to yum command - if ($extrapkgnames{$pass}) { - $yumcmd .= " $extrapkgnames{$pass} "; - } - $yumcmd =~ s/ $/\n/; - - #debug - print "yumcmd=$yumcmd\n"; - #my $repo=`cat /tmp/genimage.$$.yum.conf`; - #print "repo=$repo"; - - my $rc = system($yumcmd); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - - #remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } - } - } + #install extra packages + my $yumcmd_base = $yumcmd; + $yumcmd .= "install "; - if (!$noupdate) { - # run yum update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update = $yumcmd_base . " update "; - $rc = system("$yumcmd_update"); - # ignore any return code - } + #append extra pkg names to yum command + if ($extrapkgnames{$pass}) { + $yumcmd .= " $extrapkgnames{$pass} "; + } + $yumcmd =~ s/ $/\n/; + + #debug + print "yumcmd=$yumcmd\n"; + + #my $repo=`cat /tmp/genimage.$$.yum.conf`; + #print "repo=$repo"; + + my $rc = system($yumcmd); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + + #remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } + } + } + + if (!$noupdate) { + + # run yum update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update = $yumcmd_base . " update "; + $rc = system("$yumcmd_update"); + + # ignore any return code + } - postscripts(); #run 'postscripts' + postscripts(); #run 'postscripts' } + #Default to the first kernel found in the install image if nothing specified explicitly. #A more accurate guess than whatever the image build server happens to be running #If specified, that takes precedence. #if image has one, that is used #if all else fails, resort to uname -r like this script did before -my @KVERS= <$rootimg_dir/boot/vmlinuz-*>; +my @KVERS = <$rootimg_dir/boot/vmlinuz-*>; foreach (@KVERS) { - s/vmlinuz-//; + s/vmlinuz-//; } unless (scalar(@KVERS)) { - @KVERS= <$rootimg_dir/lib/modules/*>; + @KVERS = <$rootimg_dir/lib/modules/*>; } if (scalar(@KVERS)) { $basekernelver = basename(pop @KVERS); @@ -352,28 +363,29 @@ unless ($basekernelver) { $basekernelver = `uname -r`; } unless ($kernelver) { - $kernelver=$basekernelver; + $kernelver = $basekernelver; } chomp($kernelver); + #$updates{'kernelver'} = $kernelver if ($tempfile); -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); print "Added $dep as an autodetected depedency\n"; } } @@ -384,23 +396,23 @@ unlink "/tmp/genimage.$$.yum.conf"; #-- run postinstall script if (!$imagename) { - $postinstall_filename= get_profile_def_filename($customdir, "postinstall"); + $postinstall_filename = get_profile_def_filename($customdir, "postinstall"); if (!$postinstall_filename) { - $postinstall_filename= get_profile_def_filename($pathtofiles, "postinstall"); + $postinstall_filename = get_profile_def_filename($pathtofiles, "postinstall"); } -} +} -if ( $postinstall_filename ) { +if ($postinstall_filename) { $updates{'postinstall'} = $postinstall_filename if ($tempfile); - foreach my $postinstall ( split /,/, $postinstall_filename ) { - if ( !-x $postinstall ) { + foreach my $postinstall (split /,/, $postinstall_filename) { + if (!-x $postinstall) { print "postinstall script $postinstall is not executable\n"; exit 1; } - my $rc = system($postinstall, $rootimg_dir,$osver,$arch,$profile); - if($rc) { + my $rc = system($postinstall, $rootimg_dir, $osver, $arch, $profile); + if ($rc) { print "postinstall script $postinstall failed\n"; exit 1; } @@ -411,27 +423,28 @@ if ( $postinstall_filename ) { # statelite .statelite directory added here. # this is where tmpfs will be created. -if($mode eq "statelite"){ - mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. - # this script will get the directories. - unless(-f "../add-on/statelite/rc.statelite"){ - print "Can't find ../add-on/statelite/rc.statelite!\n"; - exit; - } - system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - # also need to add this file: - # may have already been made into a symbolic link, if so ignore it +if ($mode eq "statelite") { + mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. + # this script will get the directories. + unless (-f "../add-on/statelite/rc.statelite") { + print "Can't find ../add-on/statelite/rc.statelite!\n"; + exit; + } + system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - unless(-l "$rootimg_dir/var/lib/dhclient" ){ - mkpath "$rootimg_dir/var/lib/dhclient/"; - system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); - } + # also need to add this file: + # may have already been made into a symbolic link, if so ignore it - unless(-l "$rootimg_dir/var/lib/dhcp" ){ - mkpath "$rootimg_dir/var/lib/dhcp/"; - system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); - } -} + unless (-l "$rootimg_dir/var/lib/dhclient") { + mkpath "$rootimg_dir/var/lib/dhclient/"; + system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); + } + + unless (-l "$rootimg_dir/var/lib/dhcp") { + mkpath "$rootimg_dir/var/lib/dhcp/"; + system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); + } +} # all the attributes have been gathered # now, update the linuximage and osimage tables @@ -440,106 +453,108 @@ if($mode eq "statelite"){ if ($tempfile) { open(FILE, ">>$tempfile"); if ($imagename) { - if (keys(%updates) > 0) { - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$imagename\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - } + if (keys(%updates) > 0) { + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$imagename\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + } } else { - $updates_os{'profile'} = $profile; - $updates_os{'imagetype'} = 'linux'; - if($mode eq "statelite") { - $updates_os{'provmethod'} = 'statelite'; - } else { - $updates_os{'provmethod'} = 'netboot'; - } - $updates_os{'osname'} = 'Linux'; - $updates_os{'osvers'} = $osver; - $updates_os{'osdistro'} = 'sles'; # not used currently - $updates_os{'osarch'} = $arch; - # update the imagename for stateless - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; + $updates_os{'profile'} = $profile; + $updates_os{'imagetype'} = 'linux'; + if ($mode eq "statelite") { + $updates_os{'provmethod'} = 'statelite'; + } else { + $updates_os{'provmethod'} = 'netboot'; + } + $updates_os{'osname'} = 'Linux'; + $updates_os{'osvers'} = $osver; + $updates_os{'osdistro'} = 'sles'; # not used currently + $updates_os{'osarch'} = $arch; + + # update the imagename for stateless + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; } close FILE; } + #END mkinitrd(); sub getlibs { - my $file = shift; - my $liblist = `chroot $rootimg_dir ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - next; - } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } - $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + my $file = shift; + my $liblist = `chroot $rootimg_dir ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + unless (/=>/) { + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; + } + $temp1 =~ s/^\///; + $libhash{$temp1} = 1; + } } sub mkinitrd { - mkpath("/tmp/xcatinitrd.$$/bin"); - if($basekernelver eq $kernelver) { - copy(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); - } - else { - if(-r "$rootimg_dir/boot/vmlinuz-$kernelver") { - copy("$rootimg_dir/boot/vmlinuz-$kernelver","$destdir/kernel"); - } elsif(-r "/boot/vmlinuz-$kernelver") { - copy("/boot/vmlinuz-$kernelver","$destdir/kernel"); - } - else { - xdie("Cannot read /boot/vmlinuz-$kernelver"); - } - } - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); - my $inifile; + mkpath("/tmp/xcatinitrd.$$/bin"); + if ($basekernelver eq $kernelver) { + copy(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); + } + else { + if (-r "$rootimg_dir/boot/vmlinuz-$kernelver") { + copy("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } elsif (-r "/boot/vmlinuz-$kernelver") { + copy("/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } + else { + xdie("Cannot read /boot/vmlinuz-$kernelver"); + } + } + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/bin"); + mkpath("/tmp/xcatinitrd.$$/usr/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/lib"); + mkpath("/tmp/xcatinitrd.$$/usr/lib64"); + mkpath("/tmp/xcatinitrd.$$/lib/firmware"); + mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); + mkpath("/tmp/xcatinitrd.$$/proc"); + mkpath("/tmp/xcatinitrd.$$/sys"); + mkpath("/tmp/xcatinitrd.$$/dev/mapper"); + mkpath("/tmp/xcatinitrd.$$/sysroot"); + mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); + mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); + my $inifile; -# start writing to the init script. - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/sbin/busybox.anaconda sh\n"; + # start writing to the init script. + open($inifile, ">", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/sbin/busybox.anaconda sh\n"; -# add some functions - print $inifile < /dev/null && export DEBUG=1 netstart @@ -919,29 +936,29 @@ elif [ -r /rootimg.sfs ]; then mount --move /ro /sysroot/ro mount --move /rw /sysroot/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile "echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o size=$rootlimit -t tmpfs rootfs /sysroot\n"; - } else { - print $inifile " mount -t tmpfs rootfs /sysroot\n"; - } - print $inifile " cd /sysroot\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " zcat /rootimg.gz |/bin/cpio -idum\n"; - print $inifile " else\n"; - print $inifile " zcat /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 1\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " echo\n"; - print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/sbin/nash\n"; - print $inifile "network --device $prinic --bootproto dhcp\n"; - close($inifile); - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - # add rsync for statelite - foreach ("bin/cpio","sbin/nash","sbin/busybox.anaconda","bin/bash", "usr/sbin/chroot", "sbin/rmmod","sbin/mount.nfs","/usr/bin/rsync") { - getlibs($_); - push @filestoadd,$_; - } - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libresolv.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - if($basekernelver ne $kernelver) { - system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); - unless (-d "$rootimg_dir/lib/modules/$kernelver") { - if(-d "/lib/modules/$kernelver") { - system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); - } - else { - xdie("Cannot read /lib/modules/$kernelver"); - } + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/sbin/nash\n"; + print $inifile "network --device $prinic --bootproto dhcp\n"; + close($inifile); + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + @filestoadd = (); + foreach (@ndrivers) { + + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; } - } - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + } - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$rootimg_dir/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$rootimg_dir/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + # add rsync for statelite + foreach ("bin/cpio", "sbin/nash", "sbin/busybox.anaconda", "bin/bash", "usr/sbin/chroot", "sbin/rmmod", "sbin/mount.nfs", "/usr/bin/rsync") { + getlibs($_); + push @filestoadd, $_; + } + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libresolv.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; + if ($basekernelver ne $kernelver) { + system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); + unless (-d "$rootimg_dir/lib/modules/$kernelver") { + if (-d "/lib/modules/$kernelver") { + system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); + } + else { + xdie("Cannot read /lib/modules/$kernelver"); + } + } + } + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + foreach (@filestoadd) { + if (ref($_)) { + + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$rootimg_dir/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$rootimg_dir/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isaptdir { - if ($File::Find::name =~ /\/Packages.gz$/) { - my $location = $File::Find::name; - $location =~ s/\/Packages.gz$//; - push @aptdirs,$location; - } + if ($File::Find::name =~ /\/Packages.gz$/) { + my $location = $File::Find::name; + $location =~ s/\/Packages.gz$//; + push @aptdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } -} - - - - - - - -sub postscripts { # TODO: customized postscripts - generic_post(); - - if ($mode eq "statelite") { - if( ! -d "$rootimg_dir/opt/xcat/") { - mkdir "$rootimg_dir/opt/xcat/"; + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; } - copy ("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); + } +} + + + + + + + +sub postscripts { # TODO: customized postscripts + generic_post(); + + if ($mode eq "statelite") { + if (!-d "$rootimg_dir/opt/xcat/") { + mkdir "$rootimg_dir/opt/xcat/"; + } + copy("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; } - if (-d "$installroot/postscripts/hostkeys") { - for my $key (<$installroot/postscripts/hostkeys/*key>) { - copy ($key,"$rootimg_dir/etc/ssh/"); - } - chmod 0600,; - } - if (-d "/$installroot/postscripts/.ssh") { - mkpath("/$rootimg_dir/root/.ssh"); - chmod(0700,"/$rootimg_dir/root/.ssh/"); - for my $file () { - copy ($file,"/$rootimg_dir/root/.ssh/"); - } - chmod(0600,); - } + if (-d "$installroot/postscripts/hostkeys") { + for my $key (<$installroot/postscripts/hostkeys/*key>) { + copy($key, "$rootimg_dir/etc/ssh/"); + } + chmod 0600, ; + } + if (-d "/$installroot/postscripts/.ssh") { + mkpath("/$rootimg_dir/root/.ssh"); + chmod(0700, "/$rootimg_dir/root/.ssh/"); + for my $file () { + copy($file, "/$rootimg_dir/root/.ssh/"); + } + chmod(0600, ); + } } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; - } - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); - # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no - # to skip the break of nfs-based boot - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - unless ( -r <$rootimg_dir/etc/rc3.d/S??network>) { - symlink "/etc/init.d/network","$rootimg_dir/etc/rc3.d/S10network"; - } - open($cfgfile,">","$rootimg_dir/etc/rc3.d/S60gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style - print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; - print $cfgfile " else\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - chmod(0755,"$rootimg_dir/etc/rc3.d/S60gettyset"); - #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; + } + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); + + # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no + # to skip the break of nfs-based boot + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + unless (-r <$rootimg_dir/etc/rc3.d/S??network>) { + symlink "/etc/init.d/network", "$rootimg_dir/etc/rc3.d/S10network"; + } + open($cfgfile, ">", "$rootimg_dir/etc/rc3.d/S60gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style + print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; + print $cfgfile " else\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + chmod(0755, "$rootimg_dir/etc/rc3.d/S60gettyset"); + + #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); #add postscript support for redhat - if($mode eq "statelite") { + if ($mode eq "statelite") { print $cfgfile "/opt/xcat/xcatdsklspost 4\n"; - } else { + } else { print $cfgfile "/opt/xcat/xcatdsklspost\n"; - } - close($cfgfile); - - copy(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); } + } + close($cfgfile); + + copy(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); } sub get_package_names { - my $plist_file_name=shift; - my %pkgnames=(); - my @tmp_array=(); + my $plist_file_name = shift; + my %pkgnames = (); + my @tmp_array = (); - if ($plist_file_name) { - my $pkgfile; - open($pkgfile,"<","$plist_file_name"); - while (<$pkgfile>) { - chomp; - s/\s+$//; #remove trailing white spaces - next if /^\s*$/; #-- skip empty lines - push(@tmp_array,$_); - } - close($pkgfile); + if ($plist_file_name) { + my $pkgfile; + open($pkgfile, "<", "$plist_file_name"); + while (<$pkgfile>) { + chomp; + s/\s+$//; #remove trailing white spaces + next if /^\s*$/; #-- skip empty lines + push(@tmp_array, $_); + } + close($pkgfile); - if ( @tmp_array > 0) { - my $pkgtext=join(',',@tmp_array); - - #handle the #INLCUDE# tag recursively - my $idir = dirname($plist_file_name); - my $doneincludes=0; - while (not $doneincludes) { - $doneincludes=1; - if ($pkgtext =~ /#INCLUDE:[^#^\n]+#/) { - $doneincludes=0; - $pkgtext =~ s/#INCLUDE:([^#^\n]+)#/include_file($1,$idir)/eg; - } - } - - #print "pkgtext=$pkgtext\n"; - my @tmp=split(',', $pkgtext); - my $pass=1; - foreach (@tmp) { - my $idir; - if (/^--/) { - $idir="POST_REMOVE"; #line starts with -- means the package should be removed after otherpkgs are installed - s/^--//; - } elsif (/^-/) { - $idir="PRE_REMOVE"; #line starts with single - means the package should be removed before otherpkgs are installed - s/^-//; - } elsif (/^#NEW_INSTALL_LIST#/) { - $pass++; - next; - } elsif (/^#/) { - # ignore all other comment lines - next; - } else { - $idir=dirname($_); - } - my $fn=basename($_); - if (exists($pkgnames{$pass}{$idir})) { - my $pa=$pkgnames{$pass}{$idir}; - push(@$pa, $fn); - } else { - $pkgnames{$pass}{$idir}=[$fn]; - } - } - } - } + if (@tmp_array > 0) { + my $pkgtext = join(',', @tmp_array); - return %pkgnames; + #handle the #INLCUDE# tag recursively + my $idir = dirname($plist_file_name); + my $doneincludes = 0; + while (not $doneincludes) { + $doneincludes = 1; + if ($pkgtext =~ /#INCLUDE:[^#^\n]+#/) { + $doneincludes = 0; + $pkgtext =~ s/#INCLUDE:([^#^\n]+)#/include_file($1,$idir)/eg; + } + } + + #print "pkgtext=$pkgtext\n"; + my @tmp = split(',', $pkgtext); + my $pass = 1; + foreach (@tmp) { + my $idir; + if (/^--/) { + $idir = "POST_REMOVE"; #line starts with -- means the package should be removed after otherpkgs are installed + s/^--//; + } elsif (/^-/) { + $idir = "PRE_REMOVE"; #line starts with single - means the package should be removed before otherpkgs are installed + s/^-//; + } elsif (/^#NEW_INSTALL_LIST#/) { + $pass++; + next; + } elsif (/^#/) { + + # ignore all other comment lines + next; + } else { + $idir = dirname($_); + } + my $fn = basename($_); + if (exists($pkgnames{$pass}{$idir})) { + my $pa = $pkgnames{$pass}{$idir}; + push(@$pa, $fn); + } else { + $pkgnames{$pass}{$idir} = [$fn]; + } + } + } + } + + return %pkgnames; } sub include_file { - my $file = shift; - my $idir = shift; - my @text = (); - unless ($file =~ /^\//) { - $file = $idir."/".$file; - } - - open(INCLUDE,$file) || \ - return "#INCLUDEBAD:cannot open $file#"; - - while() { - chomp($_); - s/\s+$//; #remove trailing spaces - next if /^\s*$/; #-- skip empty lines - push(@text, $_); - } - - close(INCLUDE); - - return join(',', @text); + my $file = shift; + my $idir = shift; + my @text = (); + unless ($file =~ /^\//) { + $file = $idir . "/" . $file; + } + + open(INCLUDE, $file) || \ + return "#INCLUDEBAD:cannot open $file#"; + + while () { + chomp($_); + s/\s+$//; #remove trailing spaces + next if /^\s*$/; #-- skip empty lines + push(@text, $_); + } + + close(INCLUDE); + + return join(',', @text); } sub get_profile_def_filename { - my $base=shift; - my $ext=shift; - my $dotpos = rindex($osver, "."); - my $osbase = substr($osver, 0, $dotpos); - if (-r "$base/$profile.$osver.$arch.$ext") { - return "$base/$profile.$osver.$arch.$ext"; - } elsif (-r "$base/$profile.$osbase.$arch.$ext") { - return "$base/$profile.$osbase.$arch.$ext"; - } elsif (-r "$base/$profile.$arch.$ext") { - return "$base/$profile.$arch.$ext"; - } elsif (-r "$base/$profile.$osver.$ext") { - return "$base/$profile.$osver.$ext"; - } elsif (-r "$base/$profile.$osbase.$ext") { - return "$base/$profile.$osbase.$ext"; - } elsif (-r "$base/$profile.$ext") { - return "$base/$profile.$ext"; - } + my $base = shift; + my $ext = shift; + my $dotpos = rindex($osver, "."); + my $osbase = substr($osver, 0, $dotpos); + if (-r "$base/$profile.$osver.$arch.$ext") { + return "$base/$profile.$osver.$arch.$ext"; + } elsif (-r "$base/$profile.$osbase.$arch.$ext") { + return "$base/$profile.$osbase.$arch.$ext"; + } elsif (-r "$base/$profile.$arch.$ext") { + return "$base/$profile.$arch.$ext"; + } elsif (-r "$base/$profile.$osver.$ext") { + return "$base/$profile.$osver.$ext"; + } elsif (-r "$base/$profile.$osbase.$ext") { + return "$base/$profile.$osbase.$ext"; + } elsif (-r "$base/$profile.$ext") { + return "$base/$profile.$ext"; + } - return ""; + return ""; } -sub usage { - print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]] [--interactive]'."\n"; - print " --permission only works when '-m statelite' is set\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; - return 0; +sub usage { + print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]] [--interactive]' . "\n"; + print " --permission only works when '-m statelite' is set\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; + return 0; } diff --git a/xCAT-server/share/xcat/netboot/fedora12/genimage b/xCAT-server/share/xcat/netboot/fedora12/genimage index d00151217..322cf8f7f 100755 --- a/xCAT-server/share/xcat/netboot/fedora12/genimage +++ b/xCAT-server/share/xcat/netboot/fedora12/genimage @@ -20,8 +20,8 @@ use imgutils; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -29,20 +29,21 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + #that this method of calling genimage is no longer used if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -53,7 +54,7 @@ my $otherpkglist; my $postinstall_filename; my $rootimg_dir; my $mode; -my $permission; # the permission works only for statelite mode currently +my $permission; # the permission works only for statelite mode currently my $tempfile; my $kerneldir; my $prompt; @@ -61,75 +62,75 @@ my $noupdate; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'm=s' => \$mode, - 'permission=s' => \$permission, - 'kerneldir=s' => \$kerneldir, - 'tempfile=s' =>\$tempfile, #internal flag - 'pkglist=s' => \$pkglist, #internal flag - 'srcdir=s' => \$srcdir, #internal flag - 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag - 'otherpkglist=s' => \$otherpkglist, #internal flag - 'postinstall=s' => \$postinstall_filename, #internal flag - 'rootimgdir=s' => \$destdir, #internal flag - 'interactive' =>\$prompt, - 'onlyinitrd' =>\$onlyinitrd, - 'noupdate' =>\$noupdate, + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'm=s' => \$mode, + 'permission=s' => \$permission, + 'kerneldir=s' => \$kerneldir, + 'tempfile=s' => \$tempfile, #internal flag + 'pkglist=s' => \$pkglist, #internal flag + 'srcdir=s' => \$srcdir, #internal flag + 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag + 'otherpkglist=s' => \$otherpkglist, #internal flag + 'postinstall=s' => \$postinstall_filename, #internal flag + 'rootimgdir=s' => \$destdir, #internal flag + 'interactive' => \$prompt, + 'onlyinitrd' => \$onlyinitrd, + 'noupdate' => \$noupdate, ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } -my %updates_os = (); # the hash for updating osimage table -my %updates = (); # the hash for updating linuximage table +my %updates_os = (); # the hash for updating osimage table +my %updates = (); # the hash for updating linuximage table if ($mode eq "statelite") { if (!$permission) { $permission = "755"; } - $updates{'permission'} = $permission if ( $tempfile ); + $updates{'permission'} = $permission if ($tempfile); } if (!$arch) { $arch = `uname -m`; chomp($arch); if ($arch =~ /i.86$/) { - $arch = "x86"; + $arch = "x86"; } } -if (!$srcdir) { - $srcdir="$installroot/$osver/$arch"; +if (!$srcdir) { + $srcdir = "$installroot/$osver/$arch"; } $updates{'pkgdir'} = $srcdir if ($tempfile); -if (!$srcdir_otherpkgs) { +if (!$srcdir_otherpkgs) { $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch"; } $updates{'otherpkgdir'} = $srcdir_otherpkgs if ($tempfile); if (!$destdir) { - $destdir="$installroot/netboot/$osver/$arch/$profile"; + $destdir = "$installroot/netboot/$osver/$arch/$profile"; } $updates{'rootimgdir'} = $destdir if ($tempfile); -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; unless ($osver and $profile and $netdriver and $prinic) { @@ -138,212 +139,219 @@ unless ($osver and $profile and $netdriver and $prinic) { } if ($netdriver) { - if ( ($updates{'netdrivers'} ne $netdriver) and ($tempfile) ) { + if (($updates{'netdrivers'} ne $netdriver) and ($tempfile)) { $updates{'netdrivers'} = $netdriver; } } my @ndrivers; -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - if (/^$/) { - next; - } - push @ndrivers,$_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + if (/^$/) { + next; + } + push @ndrivers, $_; } -if($mode eq "statelite"){ - push @ndrivers,"fscache.ko"; - push @ndrivers,"sunrpc.ko"; - push @ndrivers,"lockd.ko"; - push @ndrivers,"nfs_acl.ko"; - push @ndrivers,"nfs.ko"; +if ($mode eq "statelite") { + push @ndrivers, "fscache.ko"; + push @ndrivers, "sunrpc.ko"; + push @ndrivers, "lockd.ko"; + push @ndrivers, "nfs_acl.ko"; + push @ndrivers, "nfs.ko"; } unless ($onlyinitrd) { - @yumdirs=(); - find(\&isyumdir, <$installroot/$osver/$arch/>); - unless (scalar(@yumdirs)) { - #unless ( -d $srcdir."/repodata" ) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + @yumdirs = (); + find(\&isyumdir, <$installroot/$osver/$arch/>); + unless (scalar(@yumdirs)) { - my $yumconfig; - open($yumconfig,">","/tmp/genimage.$$.yum.conf"); - my $repnum=0; - foreach $srcdir (@yumdirs) { - print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; - $repnum += 1; - } - $repnum-=1; - close($yumconfig); - mkpath "$rootimg_dir/etc"; + #unless ( -d $srcdir."/repodata" ) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } + + my $yumconfig; + open($yumconfig, ">", "/tmp/genimage.$$.yum.conf"); + my $repnum = 0; + foreach $srcdir (@yumdirs) { + print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; + $repnum += 1; + } + $repnum -= 1; + close($yumconfig); + mkpath "$rootimg_dir/etc"; - my $fd; - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); + my $fd; + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); - my $non_interactive; - if (!$prompt) { $non_interactive="-y"; } + my $non_interactive; + if (!$prompt) { $non_interactive = "-y"; } - my $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - - $yumcmd .= "install "; - mkpath("$rootimg_dir/var/lib/yum"); + my $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } - if (!$imagename) { - $pkglist= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); - if (!$pkglist) { - $pkglist= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); - } - } + $yumcmd .= "install "; + mkpath("$rootimg_dir/var/lib/yum"); - if ($pkglist) { - $updates{'pkglist'} = $pkglist if ($tempfile); - } else { - print "Unable to find package list for $profile!"; - exit 1; - } - - my %pkg_hash=imgutils::get_package_names($pkglist); - my $index=1; - my $pass; - foreach $pass (sort (keys(%pkg_hash))) { - my $pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$pkg_hash{$pass}{INCLUDEBAD}}); - exit 1; - } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - my $pa=$pkg_hash{$pass}{$_}; - $pkgnames .= " " . join(' ', @$pa); - } - - print "$yumcmd $pkgnames\n"; - my $rc = system("$yumcmd $pkgnames"); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - } - - #Now let's handle extra packages if (!$imagename) { - $otherpkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "otherpkgs.pkglist"); - if (!$otherpkglist) { $otherpkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); + if (!$pkglist) { + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); + } } - my %extra_hash=(); + + if ($pkglist) { + $updates{'pkglist'} = $pkglist if ($tempfile); + } else { + print "Unable to find package list for $profile!"; + exit 1; + } + + my %pkg_hash = imgutils::get_package_names($pkglist); + my $index = 1; + my $pass; + foreach $pass (sort (keys(%pkg_hash))) { + my $pkgnames = ""; + foreach (keys(%{ $pkg_hash{$pass} })) { + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $pkg_hash{$pass}{INCLUDEBAD} }); + exit 1; + } + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + my $pa = $pkg_hash{$pass}{$_}; + $pkgnames .= " " . join(' ', @$pa); + } + + print "$yumcmd $pkgnames\n"; + my $rc = system("$yumcmd $pkgnames"); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + } + + #Now let's handle extra packages + if (!$imagename) { + $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "otherpkgs.pkglist"); + if (!$otherpkglist) { $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } + } + my %extra_hash = (); if ($otherpkglist) { - $updates{'otherpkglist'} = $otherpkglist if ($tempfile); - %extra_hash=imgutils::get_package_names($otherpkglist); + $updates{'otherpkglist'} = $otherpkglist if ($tempfile); + %extra_hash = imgutils::get_package_names($otherpkglist); } - my %extrapkgnames; + my %extrapkgnames; if (keys(%extra_hash) > 0) { - open($yumconfig,">>","/tmp/genimage.$$.yum.conf"); - my $index=1; - foreach $pass (sort (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { - - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$extra_hash{$pass}{INCLUDEBAD}}); - exit 1; - } + open($yumconfig, ">>", "/tmp/genimage.$$.yum.conf"); + my $index = 1; + foreach $pass (sort (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; - $index++; - my $pa=$extra_hash{$pass}{$_}; - $extrapkgnames{$pass} .= " " . join(' ', @$pa); + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $extra_hash{$pass}{INCLUDEBAD} }); + exit 1; + } + + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; + $index++; + my $pa = $extra_hash{$pass}{$_}; + $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } + } + close($yumconfig); + $index--; + $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } + for (1 .. $index) { + $yumcmd .= "--enablerepo=otherpkgs$_ "; } - } - close($yumconfig); - $index--; - $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - for (1..$index) { - $yumcmd .= "--enablerepo=otherpkgs$_ "; - } - foreach $pass (sort (keys(%extra_hash))) { - #remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "$yumcmd erase "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } + foreach $pass (sort (keys(%extra_hash))) { + + #remove the packages that are specified in the otherpkgs.list files with leading '-' + my $yumcmd_remove = "$yumcmd erase "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } - #install extra packages - my $yumcmd_base = $yumcmd; - $yumcmd .= "install "; - #append extra pkg names to yum command - if ($extrapkgnames{$pass}) { - $yumcmd .= " $extrapkgnames{$pass} "; - } - $yumcmd =~ s/ $/\n/; - - #debug - print "yumcmd=$yumcmd\n"; - #my $repo=`cat /tmp/genimage.$$.yum.conf`; - #print "repo=$repo"; - - my $rc = system($yumcmd); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - - #remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } - } - } + #install extra packages + my $yumcmd_base = $yumcmd; + $yumcmd .= "install "; - if (!$noupdate) { - # run yum update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update = $yumcmd_base . " update "; - $rc = system("$yumcmd_update"); - # ignore any return code - } + #append extra pkg names to yum command + if ($extrapkgnames{$pass}) { + $yumcmd .= " $extrapkgnames{$pass} "; + } + $yumcmd =~ s/ $/\n/; + + #debug + print "yumcmd=$yumcmd\n"; + + #my $repo=`cat /tmp/genimage.$$.yum.conf`; + #print "repo=$repo"; + + my $rc = system($yumcmd); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + + #remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } + } + } + + if (!$noupdate) { + + # run yum update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update = $yumcmd_base . " update "; + $rc = system("$yumcmd_update"); + + # ignore any return code + } - postscripts(); #run 'postscripts' + postscripts(); #run 'postscripts' } + #Default to the first kernel found in the install image if nothing specified explicitly. #A more accurate guess than whatever the image build server happens to be running #If specified, that takes precedence. #if image has one, that is used #if all else fails, resort to uname -r like this script did before -my @KVERS= <$rootimg_dir/boot/vmlinuz-*>; +my @KVERS = <$rootimg_dir/boot/vmlinuz-*>; foreach (@KVERS) { - s/vmlinuz-//; + s/vmlinuz-//; } unless (scalar(@KVERS)) { - @KVERS= <$rootimg_dir/lib/modules/*>; + @KVERS = <$rootimg_dir/lib/modules/*>; } if (scalar(@KVERS)) { $basekernelver = basename(pop @KVERS); @@ -352,29 +360,30 @@ unless ($basekernelver) { $basekernelver = `uname -r`; } unless ($kernelver) { - $kernelver=$basekernelver; + $kernelver = $basekernelver; } chomp($kernelver); + #$updates{'kernelver'} = $kernelver if ($tempfile); -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); print "Added $dep as an autodetected depedency\n"; } } @@ -385,23 +394,23 @@ unlink "/tmp/genimage.$$.yum.conf"; #-- run postinstall script if (!$imagename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); if (!$postinstall_filename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); } -} +} -if ( $postinstall_filename ) { +if ($postinstall_filename) { $updates{'postinstall'} = $postinstall_filename if ($tempfile); - foreach my $postinstall ( split /,/, $postinstall_filename ) { - if ( !-x $postinstall ) { + foreach my $postinstall (split /,/, $postinstall_filename) { + if (!-x $postinstall) { print "postinstall script $postinstall is not executable\n"; exit 1; } - my $rc = system($postinstall, $rootimg_dir,$osver,$arch,$profile); - if($rc) { + my $rc = system($postinstall, $rootimg_dir, $osver, $arch, $profile); + if ($rc) { print "postinstall script $postinstall failed\n"; exit 1; } @@ -411,27 +420,28 @@ if ( $postinstall_filename ) { # statelite .statelite directory added here. # this is where tmpfs will be created. -if($mode eq "statelite"){ - mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. - # this script will get the directories. - unless(-f "../add-on/statelite/rc.statelite"){ - print "Can't find ../add-on/statelite/rc.statelite!\n"; - exit; - } - system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - # also need to add this file: - # may have already been made into a symbolic link, if so ignore it +if ($mode eq "statelite") { + mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. + # this script will get the directories. + unless (-f "../add-on/statelite/rc.statelite") { + print "Can't find ../add-on/statelite/rc.statelite!\n"; + exit; + } + system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - unless(-l "$rootimg_dir/var/lib/dhclient" ){ - mkpath "$rootimg_dir/var/lib/dhclient/"; - system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); - } + # also need to add this file: + # may have already been made into a symbolic link, if so ignore it - unless(-l "$rootimg_dir/var/lib/dhcp" ){ - mkpath "$rootimg_dir/var/lib/dhcp/"; - system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); - } -} + unless (-l "$rootimg_dir/var/lib/dhclient") { + mkpath "$rootimg_dir/var/lib/dhclient/"; + system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); + } + + unless (-l "$rootimg_dir/var/lib/dhcp") { + mkpath "$rootimg_dir/var/lib/dhcp/"; + system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); + } +} # all the attributes have been gathered # now, update the linuximage and osimage tables @@ -440,106 +450,108 @@ if($mode eq "statelite"){ if ($tempfile) { open(FILE, ">>$tempfile"); if ($imagename) { - if (keys(%updates) > 0) { - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$imagename\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - } + if (keys(%updates) > 0) { + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$imagename\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + } } else { - $updates_os{'profile'} = $profile; - $updates_os{'imagetype'} = 'linux'; - if($mode eq "statelite") { - $updates_os{'provmethod'} = 'statelite'; - } else { - $updates_os{'provmethod'} = 'netboot'; - } - $updates_os{'osname'} = 'Linux'; - $updates_os{'osvers'} = $osver; - $updates_os{'osdistro'} = 'sles'; # not used currently - $updates_os{'osarch'} = $arch; - # update the imagename for stateless - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; + $updates_os{'profile'} = $profile; + $updates_os{'imagetype'} = 'linux'; + if ($mode eq "statelite") { + $updates_os{'provmethod'} = 'statelite'; + } else { + $updates_os{'provmethod'} = 'netboot'; + } + $updates_os{'osname'} = 'Linux'; + $updates_os{'osvers'} = $osver; + $updates_os{'osdistro'} = 'sles'; # not used currently + $updates_os{'osarch'} = $arch; + + # update the imagename for stateless + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; } close FILE; } + #END mkinitrd(); sub getlibs { - my $file = shift; - my $liblist = `chroot $rootimg_dir ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - next; - } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } - $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + my $file = shift; + my $liblist = `chroot $rootimg_dir ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + unless (/=>/) { + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; + } + $temp1 =~ s/^\///; + $libhash{$temp1} = 1; + } } sub mkinitrd { - mkpath("/tmp/xcatinitrd.$$/bin"); - if($basekernelver eq $kernelver) { - copy(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); - } - else { - if(-r "$rootimg_dir/boot/vmlinuz-$kernelver") { - copy("$rootimg_dir/boot/vmlinuz-$kernelver","$destdir/kernel"); - } elsif(-r "/boot/vmlinuz-$kernelver") { - copy("/boot/vmlinuz-$kernelver","$destdir/kernel"); - } - else { - xdie("Cannot read /boot/vmlinuz-$kernelver"); - } - } - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); - my $inifile; + mkpath("/tmp/xcatinitrd.$$/bin"); + if ($basekernelver eq $kernelver) { + copy(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); + } + else { + if (-r "$rootimg_dir/boot/vmlinuz-$kernelver") { + copy("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } elsif (-r "/boot/vmlinuz-$kernelver") { + copy("/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } + else { + xdie("Cannot read /boot/vmlinuz-$kernelver"); + } + } + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/bin"); + mkpath("/tmp/xcatinitrd.$$/usr/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/lib"); + mkpath("/tmp/xcatinitrd.$$/usr/lib64"); + mkpath("/tmp/xcatinitrd.$$/lib/firmware"); + mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); + mkpath("/tmp/xcatinitrd.$$/proc"); + mkpath("/tmp/xcatinitrd.$$/sys"); + mkpath("/tmp/xcatinitrd.$$/dev/mapper"); + mkpath("/tmp/xcatinitrd.$$/sysroot"); + mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); + mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); + my $inifile; -# start writing to the init script. - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/bin/dash\n"; + # start writing to the init script. + open($inifile, ">", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/bin/dash\n"; -# add some functions - print $inifile < /dev/null && export DEBUG=1 mkdir -p /var/run @@ -898,29 +911,29 @@ elif [ -r /rootimg.sfs ]; then mount --move /ro /sysroot/ro mount --move /rw /sysroot/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile "echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o size=$rootlimit mode=755 -t tmpfs rootfs /sysroot\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs /sysroot\n"; - } - print $inifile " cd /sysroot\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " zcat /rootimg.gz |/bin/cpio -idum\n"; - print $inifile " else\n"; - print $inifile " zcat /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 1\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " echo\n"; - print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/sbin/nash\n"; - print $inifile "network --device $prinic --bootproto dhcp\n"; - close($inifile); - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - # add rsync for statelite - foreach ("bin/cpio","bin/mkdir","sbin/insmod","sbin/nash","bin/sleep","sbin/ifconfig","bin/grep","sbin/dhclient","bin/dash","bin/mount","bin/mknod","usr/bin/wget","sbin/rmmod","sbin/mount.nfs","usr/bin/rsync", "usr/bin/wc") { - getlibs($_); - push @filestoadd,$_; - } - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libresolv.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - if($basekernelver ne $kernelver) { - system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); - unless (-d "$rootimg_dir/lib/modules/$kernelver") { - if(-d "/lib/modules/$kernelver") { - system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); - } - else { - xdie("Cannot read /lib/modules/$kernelver"); - } + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/sbin/nash\n"; + print $inifile "network --device $prinic --bootproto dhcp\n"; + close($inifile); + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + @filestoadd = (); + foreach (@ndrivers) { + + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; } - } - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + } - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$rootimg_dir/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$rootimg_dir/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + # add rsync for statelite + foreach ("bin/cpio", "bin/mkdir", "sbin/insmod", "sbin/nash", "bin/sleep", "sbin/ifconfig", "bin/grep", "sbin/dhclient", "bin/dash", "bin/mount", "bin/mknod", "usr/bin/wget", "sbin/rmmod", "sbin/mount.nfs", "usr/bin/rsync", "usr/bin/wc") { + getlibs($_); + push @filestoadd, $_; + } + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libresolv.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; + if ($basekernelver ne $kernelver) { + system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); + unless (-d "$rootimg_dir/lib/modules/$kernelver") { + if (-d "/lib/modules/$kernelver") { + system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); + } + else { + xdie("Cannot read /lib/modules/$kernelver"); + } + } + } + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + foreach (@filestoadd) { + if (ref($_)) { + + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$rootimg_dir/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$rootimg_dir/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + } + } } - -sub postscripts { # TODO: customized postscripts - generic_post(); - if (-d "$installroot/postscripts/hostkeys") { - for my $key (<$installroot/postscripts/hostkeys/*key>) { - copy ($key,"$rootimg_dir/etc/ssh/"); - } - chmod 0600,; - } - if (-d "/$installroot/postscripts/.ssh") { - mkpath("/$rootimg_dir/root/.ssh"); - chmod(0700,"/$rootimg_dir/root/.ssh/"); - for my $file () { - copy ($file,"/$rootimg_dir/root/.ssh/"); - } - chmod(0600,); - } + +sub postscripts { # TODO: customized postscripts + generic_post(); + if (-d "$installroot/postscripts/hostkeys") { + for my $key (<$installroot/postscripts/hostkeys/*key>) { + copy($key, "$rootimg_dir/etc/ssh/"); + } + chmod 0600, ; + } + if (-d "/$installroot/postscripts/.ssh") { + mkpath("/$rootimg_dir/root/.ssh"); + chmod(0700, "/$rootimg_dir/root/.ssh/"); + for my $file () { + copy($file, "/$rootimg_dir/root/.ssh/"); + } + chmod(0600, ); + } } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; - } - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - unless ( -r <$rootimg_dir/etc/rc3.d/S??network>) { - symlink "/etc/init.d/network","$rootimg_dir/etc/rc3.d/S10network"; - } - open($cfgfile,">","$rootimg_dir/etc/rc3.d/S60gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style - print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; - print $cfgfile " else\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - chmod(0755,"$rootimg_dir/etc/rc3.d/S60gettyset"); - #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; + } + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + unless (-r <$rootimg_dir/etc/rc3.d/S??network>) { + symlink "/etc/init.d/network", "$rootimg_dir/etc/rc3.d/S10network"; + } + open($cfgfile, ">", "$rootimg_dir/etc/rc3.d/S60gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style + print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; + print $cfgfile " else\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + chmod(0755, "$rootimg_dir/etc/rc3.d/S60gettyset"); + + #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); #add postscript support for redhat - if($mode eq "statelite") { + if ($mode eq "statelite") { print $cfgfile "/opt/xcat/xcatdsklspost 4\n"; - } else { + } else { print $cfgfile "/opt/xcat/xcatdsklspost\n"; - } - close($cfgfile); - - copy(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); } + } + close($cfgfile); + + copy(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); } -sub usage { - print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]] [--interactive]'."\n"; - print " --permission only works when '-m statelite' is set\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; - return 0; +sub usage { + print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]] [--interactive]' . "\n"; + print " --permission only works when '-m statelite' is set\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; + return 0; } diff --git a/xCAT-server/share/xcat/netboot/fedora12/geninitrd b/xCAT-server/share/xcat/netboot/fedora12/geninitrd index 2a75fe0c8..6eaa3fa92 100755 --- a/xCAT-server/share/xcat/netboot/fedora12/geninitrd +++ b/xCAT-server/share/xcat/netboot/fedora12/geninitrd @@ -11,12 +11,13 @@ use File::Copy; use File::Find; use Getopt::Long; use Cwd qw(realpath); + #use strict; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -24,19 +25,20 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -47,89 +49,90 @@ my $otherpkglist; my $postinstall_filename; my $rootimg_dir; my $mode; -my $permission; # the permission works only for statelite mode currently +my $permission; # the permission works only for statelite mode currently sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'm=s' => \$mode, - 'permission=s' => \$permission + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'm=s' => \$mode, + 'permission=s' => \$permission ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; if ($arch or $osver or $profile) { - print "-o, -p and -a options are not allowed when a image name is specified.\n"; + print "-o, -p and -a options are not allowed when a image name is specified.\n"; exit 1; } + #load the module in memory - eval {require("$::XCATROOT/lib/perl/xCAT/Table.pm")}; + eval { require("$::XCATROOT/lib/perl/xCAT/Table.pm") }; if ($@) { - print $@; - exit 1; - } - - #get the info from the osimage and linux - my $osimagetab=xCAT::Table->new('osimage', -create=>1); - if (!$osimagetab) { - print "The osimage table cannot be opened.\n"; - exit 1; - } - my $linuximagetab=xCAT::Table->new('linuximage', -create=>1); - if (!$linuximagetab) { - print "The linuximage table cannot be opened.\n"; - exit 1; - } - (my $ref) = $osimagetab->getAttribs({imagename => $imagename}, 'osvers', 'osarch', 'profile', 'provmethod'); - if (!$ref) { - print "Cannot find image \'$imagename\' from the osimage table.\n"; - exit 1; - } - (my $ref1) = $linuximagetab->getAttribs({imagename => $imagename}, 'pkglist', 'pkgdir', 'otherpkglist', 'otherpkgdir', 'postinstall', 'rootimgdir'); - if (!$ref1) { - print "Cannot find $imagename from the linuximage table\n"; - exit 1; + print $@; + exit 1; } - $osver=$ref->{'osvers'}; - $arch=$ref->{'osarch'}; - $profile=$ref->{'profile'}; - my $provmethod=$ref->{'provmethod'}; - + #get the info from the osimage and linux + my $osimagetab = xCAT::Table->new('osimage', -create => 1); + if (!$osimagetab) { + print "The osimage table cannot be opened.\n"; + exit 1; + } + my $linuximagetab = xCAT::Table->new('linuximage', -create => 1); + if (!$linuximagetab) { + print "The linuximage table cannot be opened.\n"; + exit 1; + } + (my $ref) = $osimagetab->getAttribs({ imagename => $imagename }, 'osvers', 'osarch', 'profile', 'provmethod'); + if (!$ref) { + print "Cannot find image \'$imagename\' from the osimage table.\n"; + exit 1; + } + (my $ref1) = $linuximagetab->getAttribs({ imagename => $imagename }, 'pkglist', 'pkgdir', 'otherpkglist', 'otherpkgdir', 'postinstall', 'rootimgdir'); + if (!$ref1) { + print "Cannot find $imagename from the linuximage table\n"; + exit 1; + } + + $osver = $ref->{'osvers'}; + $arch = $ref->{'osarch'}; + $profile = $ref->{'profile'}; + my $provmethod = $ref->{'provmethod'}; + unless ($osver and $arch and $profile and $provmethod) { - print"osimage.osvers, osimage.osarch, osimage.profile and osimage.provmethod must be specified for the image $imagename in the database.\n"; - exit 1; + print "osimage.osvers, osimage.osarch, osimage.profile and osimage.provmethod must be specified for the image $imagename in the database.\n"; + exit 1; } if ($provmethod ne 'netboot') { - print "\'$imagename\' cannot be used to build diskless image. Make sure osimage.provmethod is 'netboot'."; - exit 1; + print "\'$imagename\' cannot be used to build diskless image. Make sure osimage.provmethod is 'netboot'."; + exit 1; } - if (! $ref1->{'pkglist'}) { - print"A .pkglist file must be specified for image \'$imagename\' in the linuximage table.\n"; + if (!$ref1->{'pkglist'}) { + print "A .pkglist file must be specified for image \'$imagename\' in the linuximage table.\n"; exit 0; } - $pkglist =$ref1->{'pkglist'}; + $pkglist = $ref1->{'pkglist'}; - $srcdir=$ref1->{'pkgdir'}; - $srcdir_otherpkgs=$ref1->{'otherpkgdir'}; - $otherpkglist=$ref1->{'otherpkglist'}; - $postinstall_filename=$ref1->{'postinstall'}; - $destdir=$ref1->{'rootimgdir'}; + $srcdir = $ref1->{'pkgdir'}; + $srcdir_otherpkgs = $ref1->{'otherpkgdir'}; + $otherpkglist = $ref1->{'otherpkglist'}; + $postinstall_filename = $ref1->{'postinstall'}; + $destdir = $ref1->{'rootimgdir'}; } if ($mode eq "statelite") { @@ -142,220 +145,226 @@ if (!$arch) { $arch = `uname -m`; chomp($arch); if ($arch =~ /i.86$/) { - $arch = "x86"; + $arch = "x86"; } } -if (!$srcdir) { - $srcdir="$installroot/$osver/$arch"; +if (!$srcdir) { + $srcdir = "$installroot/$osver/$arch"; } -if (!$srcdir_otherpkgs) { +if (!$srcdir_otherpkgs) { $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch"; } if (!$destdir) { - $destdir="$installroot/netboot/$osver/$arch/$profile"; + $destdir = "$installroot/netboot/$osver/$arch/$profile"; } -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; unless ($osver and $profile and $netdriver and $prinic) { - print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]]'."\n"; - print ' genimage -i -n [-r ] -k '."\n"; - print " --permission only works when '-m statelite' is set\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; - print " genimage -i eth0 -n tg3 myimage\n"; - exit 1; + print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]]' . "\n"; + print ' genimage -i -n [-r ] -k ' . "\n"; + print " --permission only works when '-m statelite' is set\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; + print " genimage -i eth0 -n tg3 myimage\n"; + exit 1; } my @ndrivers; -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - if (/^$/) { - next; - } - push @ndrivers,$_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + if (/^$/) { + next; + } + push @ndrivers, $_; } -if($mode eq "statelite"){ - push @ndrivers,"fscache.ko"; - push @ndrivers,"sunrpc.ko"; - push @ndrivers,"lockd.ko"; - push @ndrivers,"nfs_acl.ko"; - push @ndrivers,"nfs.ko"; +if ($mode eq "statelite") { + push @ndrivers, "fscache.ko"; + push @ndrivers, "sunrpc.ko"; + push @ndrivers, "lockd.ko"; + push @ndrivers, "nfs_acl.ko"; + push @ndrivers, "nfs.ko"; } unless ($onlyinitrd) { - @yumdirs=(); - find(\&isyumdir, <$installroot/$osver/$arch/>); - unless (scalar(@yumdirs)) { - #unless ( -d $srcdir."/repodata" ) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + @yumdirs = (); + find(\&isyumdir, <$installroot/$osver/$arch/>); + unless (scalar(@yumdirs)) { - my $yumconfig; - open($yumconfig,">","/tmp/genimage.$$.yum.conf"); - my $repnum=0; - foreach $srcdir (@yumdirs) { - print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; - $repnum += 1; - } - $repnum-=1; - close($yumconfig); - mkpath "$rootimg_dir/etc"; + #unless ( -d $srcdir."/repodata" ) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } + + my $yumconfig; + open($yumconfig, ">", "/tmp/genimage.$$.yum.conf"); + my $repnum = 0; + foreach $srcdir (@yumdirs) { + print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; + $repnum += 1; + } + $repnum -= 1; + close($yumconfig); + mkpath "$rootimg_dir/etc"; - my $fd; - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); - my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - - $yumcmd .= "install "; - mkpath("$rootimg_dir/var/lib/yum"); + my $fd; + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); + my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } - if (!$imagename) { - $pkglist= get_profile_def_filename($customdir, "pkglist"); - if (!$pkglist) { - $pkglist= get_profile_def_filename($pathtofiles, "pkglist"); - } - } + $yumcmd .= "install "; + mkpath("$rootimg_dir/var/lib/yum"); - if (!$pkglist) { - print "Unable to find package list for $profile!"; - exit 1; - } - - my %pkg_hash=get_package_names($pkglist); - my $index=1; - my $pass; - foreach $pass (sort (keys(%pkg_hash))) { - my $pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - my $pa=$pkg_hash{$pass}{$_}; - $pkgnames .= " " . join(' ', @$pa); - } - - print "$yumcmd $pkgnames\n"; - my $rc = system("$yumcmd $pkgnames"); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - } - - #Now let's handle extra packages if (!$imagename) { - $otherpkglist=get_profile_def_filename($customdir, "otherpkgs.pkglist"); - if (!$otherpkglist) { $otherpkglist=get_profile_def_filename($pathtofiles, "otherpkgs.pkglist"); } + $pkglist = get_profile_def_filename($customdir, "pkglist"); + if (!$pkglist) { + $pkglist = get_profile_def_filename($pathtofiles, "pkglist"); + } } - my %extra_hash=(); + + if (!$pkglist) { + print "Unable to find package list for $profile!"; + exit 1; + } + + my %pkg_hash = get_package_names($pkglist); + my $index = 1; + my $pass; + foreach $pass (sort (keys(%pkg_hash))) { + my $pkgnames = ""; + foreach (keys(%{ $pkg_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + my $pa = $pkg_hash{$pass}{$_}; + $pkgnames .= " " . join(' ', @$pa); + } + + print "$yumcmd $pkgnames\n"; + my $rc = system("$yumcmd $pkgnames"); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + } + + #Now let's handle extra packages + if (!$imagename) { + $otherpkglist = get_profile_def_filename($customdir, "otherpkgs.pkglist"); + if (!$otherpkglist) { $otherpkglist = get_profile_def_filename($pathtofiles, "otherpkgs.pkglist"); } + } + my %extra_hash = (); if ($otherpkglist) { - %extra_hash=get_package_names($otherpkglist); + %extra_hash = get_package_names($otherpkglist); } - my %extrapkgnames; + my %extrapkgnames; if (keys(%extra_hash) > 0) { - open($yumconfig,">>","/tmp/genimage.$$.yum.conf"); - my $index=1; - foreach $pass (sort (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; - $index++; - my $pa=$extra_hash{$pass}{$_}; - $extrapkgnames{$pass} .= " " . join(' ', @$pa); + open($yumconfig, ">>", "/tmp/genimage.$$.yum.conf"); + my $index = 1; + foreach $pass (sort (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; + $index++; + my $pa = $extra_hash{$pass}{$_}; + $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } + } + close($yumconfig); + $index--; + $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } + for (1 .. $index) { + $yumcmd .= "--enablerepo=otherpkgs$_ "; } - } - close($yumconfig); - $index--; - $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - for (1..$index) { - $yumcmd .= "--enablerepo=otherpkgs$_ "; - } - foreach $pass (sort (keys(%extra_hash))) { - #remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "$yumcmd erase "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } + foreach $pass (sort (keys(%extra_hash))) { + + #remove the packages that are specified in the otherpkgs.list files with leading '-' + my $yumcmd_remove = "$yumcmd erase "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } - #install extra packages - my $yumcmd_base = $yumcmd; - $yumcmd .= "install "; - #append extra pkg names to yum command - if ($extrapkgnames{$pass}) { - $yumcmd .= " $extrapkgnames{$pass} "; - } - $yumcmd =~ s/ $/\n/; - - #debug - print "yumcmd=$yumcmd\n"; - #my $repo=`cat /tmp/genimage.$$.yum.conf`; - #print "repo=$repo"; - - my $rc = system($yumcmd); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - - #remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } - } - } + #install extra packages + my $yumcmd_base = $yumcmd; + $yumcmd .= "install "; - # run yum update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update = $yumcmd_base . " update "; - $rc = system("$yumcmd_update"); - # ignore any return code + #append extra pkg names to yum command + if ($extrapkgnames{$pass}) { + $yumcmd .= " $extrapkgnames{$pass} "; + } + $yumcmd =~ s/ $/\n/; + + #debug + print "yumcmd=$yumcmd\n"; + + #my $repo=`cat /tmp/genimage.$$.yum.conf`; + #print "repo=$repo"; + + my $rc = system($yumcmd); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + + #remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } + } + } + + # run yum update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update = $yumcmd_base . " update "; + $rc = system("$yumcmd_update"); + + # ignore any return code - postscripts(); #run 'postscripts' + postscripts(); #run 'postscripts' } + #Default to the first kernel found in the install image if nothing specified explicitly. #A more accurate guess than whatever the image build server happens to be running #If specified, that takes precedence. #if image has one, that is used #if all else fails, resort to uname -r like this script did before -my @KVERS= <$rootimg_dir/boot/vmlinuz-*>; +my @KVERS = <$rootimg_dir/boot/vmlinuz-*>; foreach (@KVERS) { - s/vmlinuz-//; + s/vmlinuz-//; } unless (scalar(@KVERS)) { - @KVERS= <$rootimg_dir/lib/modules/*>; + @KVERS = <$rootimg_dir/lib/modules/*>; } if (scalar(@KVERS)) { $basekernelver = basename(pop @KVERS); @@ -364,26 +373,26 @@ unless ($basekernelver) { $basekernelver = `uname -r`; } unless ($kernelver) { - $kernelver=$basekernelver; + $kernelver = $basekernelver; } chomp($kernelver); -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); print "Added $dep as an autodetected depedency\n"; } } @@ -394,15 +403,15 @@ unlink "/tmp/genimage.$$.yum.conf"; #-- run postinstall script if (!$imagename) { - $postinstall_filename= get_profile_def_filename($customdir, "postinstall"); + $postinstall_filename = get_profile_def_filename($customdir, "postinstall"); if (!$postinstall_filename) { - $postinstall_filename= get_profile_def_filename($pathtofiles, "postinstall"); + $postinstall_filename = get_profile_def_filename($pathtofiles, "postinstall"); } -} +} if (($postinstall_filename) && (-x $postinstall_filename)) { - my $rc = system($postinstall_filename, $rootimg_dir,$osver,$arch,$profile); - if($rc) { + my $rc = system($postinstall_filename, $rootimg_dir, $osver, $arch, $profile); + if ($rc) { print "postinstall script failed\n"; exit 1; } @@ -411,90 +420,91 @@ if (($postinstall_filename) && (-x $postinstall_filename)) { # statelite .statelite directory added here. # this is where tmpfs will be created. -if($mode eq "statelite"){ - mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. - # this script will get the directories. - unless(-f "../add-on/statelite/rc.statelite"){ - print "Can't find ../add-on/statelite/rc.statelite!\n"; - exit; - } - system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - # also need to add this file: - # may have already been made into a symbolic link, if so ignore it +if ($mode eq "statelite") { + mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. + # this script will get the directories. + unless (-f "../add-on/statelite/rc.statelite") { + print "Can't find ../add-on/statelite/rc.statelite!\n"; + exit; + } + system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - unless(-l "$rootimg_dir/var/lib/dhclient" ){ - mkpath "$rootimg_dir/var/lib/dhclient/"; - system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); - } + # also need to add this file: + # may have already been made into a symbolic link, if so ignore it - unless(-l "$rootimg_dir/var/lib/dhcp" ){ - mkpath "$rootimg_dir/var/lib/dhcp/"; - system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); - } -} + unless (-l "$rootimg_dir/var/lib/dhclient") { + mkpath "$rootimg_dir/var/lib/dhclient/"; + system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); + } + + unless (-l "$rootimg_dir/var/lib/dhcp") { + mkpath "$rootimg_dir/var/lib/dhcp/"; + system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); + } +} mkinitrd(); sub getlibs { - my $file = shift; - my $liblist = `chroot $rootimg_dir ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - next; - } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } - $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + my $file = shift; + my $liblist = `chroot $rootimg_dir ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + unless (/=>/) { + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; + } + $temp1 =~ s/^\///; + $libhash{$temp1} = 1; + } } sub mkinitrd { - mkpath("/tmp/xcatinitrd.$$/bin"); - if($basekernelver eq $kernelver) { - copy(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); - } - else { - if(-r "$rootimg_dir/boot/vmlinuz-$kernelver") { - copy("$rootimg_dir/boot/vmlinuz-$kernelver","$destdir/kernel"); - } elsif(-r "/boot/vmlinuz-$kernelver") { - copy("/boot/vmlinuz-$kernelver","$destdir/kernel"); - } - else { - xdie("Cannot read /boot/vmlinuz-$kernelver"); - } - } - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); - my $inifile; + mkpath("/tmp/xcatinitrd.$$/bin"); + if ($basekernelver eq $kernelver) { + copy(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); + } + else { + if (-r "$rootimg_dir/boot/vmlinuz-$kernelver") { + copy("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } elsif (-r "/boot/vmlinuz-$kernelver") { + copy("/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } + else { + xdie("Cannot read /boot/vmlinuz-$kernelver"); + } + } + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/bin"); + mkpath("/tmp/xcatinitrd.$$/usr/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/lib"); + mkpath("/tmp/xcatinitrd.$$/usr/lib64"); + mkpath("/tmp/xcatinitrd.$$/lib/firmware"); + mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); + mkpath("/tmp/xcatinitrd.$$/proc"); + mkpath("/tmp/xcatinitrd.$$/sys"); + mkpath("/tmp/xcatinitrd.$$/dev/mapper"); + mkpath("/tmp/xcatinitrd.$$/sysroot"); + mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); + mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); + my $inifile; -# start writing to the init script. - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/bin/dash\n"; + # start writing to the init script. + open($inifile, ">", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/bin/dash\n"; -# add some functions - print $inifile < /dev/null && export DEBUG=1 mkdir -p /var/run @@ -875,29 +886,29 @@ elif [ -r /rootimg.sfs ]; then mount --move /ro /sysroot/ro mount --move /rw /sysroot/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile "echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o size=$rootlimit -t tmpfs rootfs /sysroot\n"; - } else { - print $inifile " mount -t tmpfs rootfs /sysroot\n"; - } - print $inifile " cd /sysroot\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " gzip -cd /rootimg.gz |cpio -idum\n"; - print $inifile " else\n"; - print $inifile " gzip -cd /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 1\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " echo\n"; - print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/sbin/nash\n"; - print $inifile "network --device $prinic --bootproto dhcp\n"; - close($inifile); - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - # add rsync for statelite - foreach ("bin/cpio","bin/mkdir","sbin/insmod","bin/awk","sbin/nash","bin/sleep","sbin/ifconfig","bin/grep","sbin/dhclient","bin/cat","bin/cp","usr/bin/clear","bin/gzip","sbin/switch_root","bin/dash","bin/mount","bin/mknod","usr/bin/wget","sbin/rmmod","sbin/mount.nfs","/usr/bin/rsync") { - getlibs($_); - push @filestoadd,$_; - } - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libresolv.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - if($basekernelver ne $kernelver) { - system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); - unless (-d "$rootimg_dir/lib/modules/$kernelver") { - if(-d "/lib/modules/$kernelver") { - system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); - } - else { - xdie("Cannot read /lib/modules/$kernelver"); - } + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/sbin/nash\n"; + print $inifile "network --device $prinic --bootproto dhcp\n"; + close($inifile); + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + @filestoadd = (); + foreach (@ndrivers) { + + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; } - } - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + } - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$rootimg_dir/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$rootimg_dir/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + # add rsync for statelite + foreach ("bin/cpio", "bin/mkdir", "sbin/insmod", "bin/awk", "sbin/nash", "bin/sleep", "sbin/ifconfig", "bin/grep", "sbin/dhclient", "bin/cat", "bin/cp", "usr/bin/clear", "bin/gzip", "sbin/switch_root", "bin/dash", "bin/mount", "bin/mknod", "usr/bin/wget", "sbin/rmmod", "sbin/mount.nfs", "/usr/bin/rsync") { + getlibs($_); + push @filestoadd, $_; + } + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libresolv.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; + if ($basekernelver ne $kernelver) { + system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); + unless (-d "$rootimg_dir/lib/modules/$kernelver") { + if (-d "/lib/modules/$kernelver") { + system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); + } + else { + xdie("Cannot read /lib/modules/$kernelver"); + } + } + } + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + foreach (@filestoadd) { + if (ref($_)) { + + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$rootimg_dir/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$rootimg_dir/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + } + } } - -sub postscripts { # TODO: customized postscripts - generic_post(); - if (-d "$installroot/postscripts/hostkeys") { - for my $key (<$installroot/postscripts/hostkeys/*key>) { - copy ($key,"$rootimg_dir/etc/ssh/"); - } - chmod 0600,; - } - if (-d "/$installroot/postscripts/.ssh") { - mkpath("/$rootimg_dir/root/.ssh"); - chmod(0700,"/$rootimg_dir/root/.ssh/"); - for my $file () { - copy ($file,"/$rootimg_dir/root/.ssh/"); - } - chmod(0600,); - } + +sub postscripts { # TODO: customized postscripts + generic_post(); + if (-d "$installroot/postscripts/hostkeys") { + for my $key (<$installroot/postscripts/hostkeys/*key>) { + copy($key, "$rootimg_dir/etc/ssh/"); + } + chmod 0600, ; + } + if (-d "/$installroot/postscripts/.ssh") { + mkpath("/$rootimg_dir/root/.ssh"); + chmod(0700, "/$rootimg_dir/root/.ssh/"); + for my $file () { + copy($file, "/$rootimg_dir/root/.ssh/"); + } + chmod(0600, ); + } } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; - } - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - unless ( -r <$rootimg_dir/etc/rc3.d/S??network>) { - symlink "/etc/init.d/network","$rootimg_dir/etc/rc3.d/S10network"; - } - open($cfgfile,">","$rootimg_dir/etc/rc3.d/S60gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style - print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; - print $cfgfile " else\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - chmod(0755,"$rootimg_dir/etc/rc3.d/S60gettyset"); - #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; + } + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + unless (-r <$rootimg_dir/etc/rc3.d/S??network>) { + symlink "/etc/init.d/network", "$rootimg_dir/etc/rc3.d/S10network"; + } + open($cfgfile, ">", "$rootimg_dir/etc/rc3.d/S60gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style + print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; + print $cfgfile " else\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + chmod(0755, "$rootimg_dir/etc/rc3.d/S60gettyset"); + + #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); #add postscript support for redhat - if($mode eq "statelite") { + if ($mode eq "statelite") { print $cfgfile "/opt/xcat/xcatdsklspost 4\n"; - } else { + } else { print $cfgfile "/opt/xcat/xcatdsklspost\n"; - } - close($cfgfile); - - copy(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); } + } + close($cfgfile); + + copy(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); } sub get_package_names { - my $plist_file_name=shift; - my %pkgnames=(); - my @tmp_array=(); + my $plist_file_name = shift; + my %pkgnames = (); + my @tmp_array = (); - if ($plist_file_name) { - my $pkgfile; - open($pkgfile,"<","$plist_file_name"); - while (<$pkgfile>) { - chomp; - s/\s+$//; #remove trailing white spaces - next if /^\s*$/; #-- skip empty lines - push(@tmp_array,$_); - } - close($pkgfile); + if ($plist_file_name) { + my $pkgfile; + open($pkgfile, "<", "$plist_file_name"); + while (<$pkgfile>) { + chomp; + s/\s+$//; #remove trailing white spaces + next if /^\s*$/; #-- skip empty lines + push(@tmp_array, $_); + } + close($pkgfile); - if ( @tmp_array > 0) { - my $pkgtext=join(',',@tmp_array); - - #handle the #INLCUDE# tag recursively - my $idir = dirname($plist_file_name); - my $doneincludes=0; - while (not $doneincludes) { - $doneincludes=1; - if ($pkgtext =~ /#INCLUDE:[^#^\n]+#/) { - $doneincludes=0; - $pkgtext =~ s/#INCLUDE:([^#^\n]+)#/include_file($1,$idir)/eg; - } - } - - #print "pkgtext=$pkgtext\n"; - my @tmp=split(',', $pkgtext); - my $pass=1; - foreach (@tmp) { - my $idir; - if (/^--/) { - $idir="POST_REMOVE"; #line starts with -- means the package should be removed after otherpkgs are installed - s/^--//; - } elsif (/^-/) { - $idir="PRE_REMOVE"; #line starts with single - means the package should be removed before otherpkgs are installed - s/^-//; - } elsif (/^#NEW_INSTALL_LIST#/) { - $pass++; - next; - } elsif (/^#/) { - # ignore all other comment lines - next; - } else { - $idir=dirname($_); - } - my $fn=basename($_); - if (exists($pkgnames{$pass}{$idir})) { - my $pa=$pkgnames{$pass}{$idir}; - push(@$pa, $fn); - } else { - $pkgnames{$pass}{$idir}=[$fn]; - } - } - } - } + if (@tmp_array > 0) { + my $pkgtext = join(',', @tmp_array); - return %pkgnames; + #handle the #INLCUDE# tag recursively + my $idir = dirname($plist_file_name); + my $doneincludes = 0; + while (not $doneincludes) { + $doneincludes = 1; + if ($pkgtext =~ /#INCLUDE:[^#^\n]+#/) { + $doneincludes = 0; + $pkgtext =~ s/#INCLUDE:([^#^\n]+)#/include_file($1,$idir)/eg; + } + } + + #print "pkgtext=$pkgtext\n"; + my @tmp = split(',', $pkgtext); + my $pass = 1; + foreach (@tmp) { + my $idir; + if (/^--/) { + $idir = "POST_REMOVE"; #line starts with -- means the package should be removed after otherpkgs are installed + s/^--//; + } elsif (/^-/) { + $idir = "PRE_REMOVE"; #line starts with single - means the package should be removed before otherpkgs are installed + s/^-//; + } elsif (/^#NEW_INSTALL_LIST#/) { + $pass++; + next; + } elsif (/^#/) { + + # ignore all other comment lines + next; + } else { + $idir = dirname($_); + } + my $fn = basename($_); + if (exists($pkgnames{$pass}{$idir})) { + my $pa = $pkgnames{$pass}{$idir}; + push(@$pa, $fn); + } else { + $pkgnames{$pass}{$idir} = [$fn]; + } + } + } + } + + return %pkgnames; } sub include_file { - my $file = shift; - my $idir = shift; - my @text = (); - unless ($file =~ /^\//) { - $file = $idir."/".$file; - } - - open(INCLUDE,$file) || \ - return "#INCLUDEBAD:cannot open $file#"; - - while() { - chomp($_); - s/\s+$//; #remove trailing spaces - next if /^\s*$/; #-- skip empty lines - push(@text, $_); - } - - close(INCLUDE); - - return join(',', @text); + my $file = shift; + my $idir = shift; + my @text = (); + unless ($file =~ /^\//) { + $file = $idir . "/" . $file; + } + + open(INCLUDE, $file) || \ + return "#INCLUDEBAD:cannot open $file#"; + + while () { + chomp($_); + s/\s+$//; #remove trailing spaces + next if /^\s*$/; #-- skip empty lines + push(@text, $_); + } + + close(INCLUDE); + + return join(',', @text); } sub get_profile_def_filename { - my $base=shift; - my $ext=shift; - my $dotpos = rindex($osver, "."); - my $osbase = substr($osver, 0, $dotpos); - if (-r "$base/$profile.$osver.$arch.$ext") { - return "$base/$profile.$osver.$arch.$ext"; - } elsif (-r "$base/$profile.$osbase.$arch.$ext") { - return "$base/$profile.$osbase.$arch.$ext"; - } elsif (-r "$base/$profile.$arch.$ext") { - return "$base/$profile.$arch.$ext"; - } elsif (-r "$base/$profile.$osver.$ext") { - return "$base/$profile.$osver.$ext"; - } elsif (-r "$base/$profile.$osbase.$ext") { - return "$base/$profile.$osbase.$ext"; - } elsif (-r "$base/$profile.$ext") { - return "$base/$profile.$ext"; - } + my $base = shift; + my $ext = shift; + my $dotpos = rindex($osver, "."); + my $osbase = substr($osver, 0, $dotpos); + if (-r "$base/$profile.$osver.$arch.$ext") { + return "$base/$profile.$osver.$arch.$ext"; + } elsif (-r "$base/$profile.$osbase.$arch.$ext") { + return "$base/$profile.$osbase.$arch.$ext"; + } elsif (-r "$base/$profile.$arch.$ext") { + return "$base/$profile.$arch.$ext"; + } elsif (-r "$base/$profile.$osver.$ext") { + return "$base/$profile.$osver.$ext"; + } elsif (-r "$base/$profile.$osbase.$ext") { + return "$base/$profile.$osbase.$ext"; + } elsif (-r "$base/$profile.$ext") { + return "$base/$profile.$ext"; + } - return ""; + return ""; } - + diff --git a/xCAT-server/share/xcat/netboot/mic/genimage b/xCAT-server/share/xcat/netboot/mic/genimage index 205ea485c..3b5a49c0b 100755 --- a/xCAT-server/share/xcat/netboot/mic/genimage +++ b/xCAT-server/share/xcat/netboot/mic/genimage @@ -1,5 +1,5 @@ #!/usr/bin/env perl -# generate the image for mic +# generate the image for mic # Since the root file system for mic is generated on the host by # micctrl command, this script only help to generate the /etc/hosts, # /root/.ssh from the management node to the root file system. @@ -41,29 +41,29 @@ my $prompt; my $imagename; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'pkglist=s' => \$pkglist, - 'srcdir=s' => \$srcdir, - 'otherpkglist=s' => \$otherpkglist, - 'otherpkgdir=s' => \$srcdir_otherpkgs, - 'tempfile=s' => \$tempfile, - 'postinstall=s' => \$postinstall, - 'rootimgdir=s' => \$rootimgdir, - 'imagename=s' => \$imagename, - 'interactive' =>\$prompt, + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'pkglist=s' => \$pkglist, + 'srcdir=s' => \$srcdir, + 'otherpkglist=s' => \$otherpkglist, + 'otherpkgdir=s' => \$srcdir_otherpkgs, + 'tempfile=s' => \$tempfile, + 'postinstall=s' => \$postinstall, + 'rootimgdir=s' => \$rootimgdir, + 'imagename=s' => \$imagename, + 'interactive' => \$prompt, ); if ($rootimgdir) { - $rootimg_dir = $rootimgdir."/rootimg"; # for 2.8.4 and later + $rootimg_dir = $rootimgdir . "/rootimg"; # for 2.8.4 and later } else { - $rootimg_dir = "$srcdir/overlay/package"; # for 2.8.3 that rootimgdir was not set by default + $rootimg_dir = "$srcdir/overlay/package"; # for 2.8.3 that rootimgdir was not set by default } my @yumdirs; if (!$imagename && @ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } unless ($imagename) { print "Error: osimage name needs be specified.\n"; @@ -71,11 +71,11 @@ unless ($imagename) { } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } # creae default paths @@ -93,183 +93,186 @@ if ($otherpkglist) { print "Error: Cannot open table osimage.\n"; return 1; } + # generate the yum configuration file - + my $aiddistro; - my $oient = $oitab->getAttribs({'imagename'=>$imagename}, 'osdistroname'); + my $oient = $oitab->getAttribs({ 'imagename' => $imagename }, 'osdistroname'); if ($oient && $oient->{'osdistroname'}) { $aiddistro = $oient->{'osdistroname'}; } - + my $distrotab = xCAT::Table->new('osdistro'); unless ($distrotab) { print "Error: Cannot open table osdistro.\n"; return 1; } my $aiddistrodir; - my $distroent = $distrotab->getAttribs({'osdistroname'=>$aiddistro}, 'dirpaths'); + my $distroent = $distrotab->getAttribs({ 'osdistroname' => $aiddistro }, 'dirpaths'); if ($distroent && $distroent->{'dirpaths'}) { $aiddistrodir = $distroent->{'dirpaths'} } - - my @pkgdirs = split(",", $aiddistrodir); + + my @pkgdirs = split(",", $aiddistrodir); foreach my $dir (@pkgdirs) { - find(\&isyumdir, <$dir/>); - if (!grep /$dir/, @yumdirs) { - print "The repository for $dir should be created before running the genimge. Try to run [createrepo $dir].\n"; - } + find(\&isyumdir, <$dir/>); + if (!grep /$dir/, @yumdirs) { + print "The repository for $dir should be created before running the genimge. Try to run [createrepo $dir].\n"; + } } - + my $yumconfig; - open($yumconfig,">","/tmp/genimage.$$.yum.conf"); - my $repnum=0; + open($yumconfig, ">", "/tmp/genimage.$$.yum.conf"); + my $repnum = 0; foreach $srcdir (@yumdirs) { - print $yumconfig "[$aiddistro-$repnum]\nname=$aiddistro-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; - $repnum += 1; + print $yumconfig "[$aiddistro-$repnum]\nname=$aiddistro-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; + $repnum += 1; } - $repnum-=1; + $repnum -= 1; close($yumconfig); mkpath "$rootimg_dir/etc"; my %extra_hash = imgutils::get_package_names($otherpkglist); - my %extrapkgnames; + my %extrapkgnames; my %repohash; if (keys(%extra_hash) > 0) { - open($yumconfig,">>","/tmp/genimage.$$.yum.conf"); - my $index=1; - my $pass; - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$extra_hash{$pass}{INCLUDEBAD}}); - exit 1; + open($yumconfig, ">>", "/tmp/genimage.$$.yum.conf"); + my $index = 1; + my $pass; + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $extra_hash{$pass}{INCLUDEBAD} }); + exit 1; + } + + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; + $repohash{$pass}{$index} = 1; + $index++; + my $pa = $extra_hash{$pass}{$_}; + $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } + } + close($yumconfig); + $index--; + my $yumcmd_base = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd_base .= "--enablerepo=$aiddistro-$_ "; + } + + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { + my $yumcmd = $yumcmd_base; + foreach my $repo_index (keys %{ $repohash{$pass} }) { + $yumcmd .= "--enablerepo=otherpkgs$repo_index "; } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} - print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; - $repohash{$pass}{$index} = 1; - $index++; - my $pa=$extra_hash{$pass}{$_}; - $extrapkgnames{$pass} .= " " . join(' ', @$pa); + system("$yumcmd clean all"); + + my $envlist; + if (exists($extra_hash{$pass}{ENVLIST})) { + $envlist = join(' ', @{ $extra_hash{$pass}{ENVLIST} }); + } + + # remove the packages that are specified in the otherpkgs.list files with leading '-' + my $yumcmd_remove = "$yumcmd erase "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$envlist $yumcmd_remove $rm_packges\n"; + my $rc = system("$envlist $yumcmd_remove $rm_packges"); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + } + } + + # install extra packages + $yumcmd .= "install "; + + # append extra pkg names to yum command + if ($extrapkgnames{$pass}) { + $yumcmd .= " $extrapkgnames{$pass} "; + $yumcmd =~ s/ $/\n/; + + print "$envlist $yumcmd\n"; + my $rc = system("$envlist $yumcmd"); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + } else { + print "No Packages marked for install\n"; + } + + # remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$envlist $yumcmd_remove $rm_packges\n"; + my $rc = system("$envlist $yumcmd_remove $rm_packges"); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + } + } } - } - close($yumconfig); - $index--; - my $yumcmd_base = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd_base .= "--enablerepo=$aiddistro-$_ "; - } - - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { - my $yumcmd = $yumcmd_base; - foreach my $repo_index ( keys %{$repohash{$pass}} ) { - $yumcmd .= "--enablerepo=otherpkgs$repo_index "; - } - - system("$yumcmd clean all"); - - my $envlist; - if(exists($extra_hash{$pass}{ENVLIST})){ - $envlist = join(' ', @{$extra_hash{$pass}{ENVLIST}}); - } - # remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "$yumcmd erase "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$envlist $yumcmd_remove $rm_packges\n"; - my $rc = system("$envlist $yumcmd_remove $rm_packges"); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - } - } - - # install extra packages - $yumcmd .= "install "; - # append extra pkg names to yum command - if ($extrapkgnames{$pass}) { - $yumcmd .= " $extrapkgnames{$pass} "; - $yumcmd =~ s/ $/\n/; - - print "$envlist $yumcmd\n"; - my $rc = system("$envlist $yumcmd"); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - } else { - print "No Packages marked for install\n"; - } - - # remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$envlist $yumcmd_remove $rm_packges\n"; - my $rc = system("$envlist $yumcmd_remove $rm_packges"); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - } - } - } } } # run postinstall scripts -foreach my $post ( split /,/, $postinstall) { - if ( !-x $post) { +foreach my $post (split /,/, $postinstall) { + if (!-x $post) { print "postinstall script $post is not executable\n"; exit 1; } my $rc = system($postinstall, $rootimg_dir, $osver, $arch, $profile); - if($rc) { + if ($rc) { print "postinstall script $post failed\n"; exit 1; } } -my $fsdir = "$srcdir/"; +my $fsdir = "$srcdir/"; my $systemdir = "$fsdir/system"; -mkpath ($systemdir); +mkpath($systemdir); -# this is the file list which includes the files which should be copied +# this is the file list which includes the files which should be copied # from MN to the root file system my @sysfilelist = ( - "/etc/hosts", - "/etc/group", - "/etc/passwd", - "/etc/shadow", - "/etc/resolv.conf", - "/etc/nsswitch.conf", - "/etc/ssh/ssh_host_rsa_key", - "/etc/ssh/ssh_config", - "/etc/ssh/sshd_config", - "/etc/ssh/ssh_host_dsa_key", - "/root/.ssh/id_rsa", - "/root/.ssh/id_rsa.pub", - "/root/.ssh/authorized_keys",); + "/etc/hosts", + "/etc/group", + "/etc/passwd", + "/etc/shadow", + "/etc/resolv.conf", + "/etc/nsswitch.conf", + "/etc/ssh/ssh_host_rsa_key", + "/etc/ssh/ssh_config", + "/etc/ssh/sshd_config", + "/etc/ssh/ssh_host_dsa_key", + "/root/.ssh/id_rsa", + "/root/.ssh/id_rsa.pub", + "/root/.ssh/authorized_keys",); # do the copy foreach my $file (@sysfilelist) { my $dirname = dirname("$systemdir/$file"); unless (-d $dirname) { - mkpath ($dirname); + mkpath($dirname); } - copy ($file, "$systemdir/$file"); + copy($file, "$systemdir/$file"); } # Create emtpy common dir and common.filelist for later using -mkpath ("$fsdir/common"); -system ("touch $fsdir/common.filelist"); +mkpath("$fsdir/common"); +system("touch $fsdir/common.filelist"); print "Genimage for mic has been done.\n"; diff --git a/xCAT-server/share/xcat/netboot/rh/genimage b/xCAT-server/share/xcat/netboot/rh/genimage index af7224cde..0c42cb1f5 100755 --- a/xCAT-server/share/xcat/netboot/rh/genimage +++ b/xCAT-server/share/xcat/netboot/rh/genimage @@ -1,6 +1,6 @@ #!/usr/bin/env perl -# The possible files which getting from local OS that may affect he genimage cross distor level +# The possible files which getting from local OS that may affect he genimage cross distor level # /proc/self/oom_adj BEGIN @@ -24,10 +24,10 @@ use imgutils; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $dracutmode; #Indicate whether this is a dracut style initrd -my $dracutdir = "dracut"; # The default directory name of dracut -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $dracutmode; #Indicate whether this is a dracut style initrd +my $dracutdir = "dracut"; # The default directory name of dracut +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -35,22 +35,23 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + #that this method of calling genimage is no longer used if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; my $kerneldir; -my $kernelver = ""; #`uname -r`; +my $kernelver = ""; #`uname -r`; my $krpmver; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -60,7 +61,7 @@ my $srcdir_otherpkgs; my $otherpkglist; my $postinstall_filename; my $rootimg_dir; -my $permission; # the permission works only for statelite mode currently +my $permission; # the permission works only for statelite mode currently my $tempfile; my $prompt; my $ignorekernelchk; @@ -68,23 +69,23 @@ my $noupdate; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - umount_chroot($rootimage_dir); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + umount_chroot($rootimage_dir); + die @_; } -#helper subroutine to get the major release number +#helper subroutine to get the major release number #of a osver sub majversion { my $version = shift; my $majorrel; - if($osver =~ /^\D*(\d*)[.\d]*$/){ + if ($osver =~ /^\D*(\d*)[.\d]*$/) { $majorrel = $1; } - return $majorrel; + return $majorrel; } sub mount_chroot { @@ -94,15 +95,16 @@ sub mount_chroot { #For Redhat7 or above, mount /proc,/sys from host to avoid error messages #For Redhat7 or above, create /dev according to /dev on the host to avoid error messages #For Redhat6 or below, mount these directories might introduce error messages - if(majversion($osver) > 6){ - system("mkdir -p $rootimage_dir/proc"); - system("mount proc $rootimage_dir/proc -t proc"); - system("mkdir -p $rootimage_dir/sys"); - system("mount sysfs $rootimage_dir/sys -t sysfs"); - system("mkdir -p $rootimage_dir/dev"); - #system("mount devtmpfs $rootimage_dir/dev -t devtmpfs"); - system("cd /dev;find .|cpio -H newc -o >$rootimage_dir/dev/dev.archive;cd -"); - system("cd $rootimage_dir/dev;cpio -idum<./dev.archive;rm -f ./dev.archive;cd -"); + if (majversion($osver) > 6) { + system("mkdir -p $rootimage_dir/proc"); + system("mount proc $rootimage_dir/proc -t proc"); + system("mkdir -p $rootimage_dir/sys"); + system("mount sysfs $rootimage_dir/sys -t sysfs"); + system("mkdir -p $rootimage_dir/dev"); + + #system("mount devtmpfs $rootimage_dir/dev -t devtmpfs"); + system("cd /dev;find .|cpio -H newc -o >$rootimage_dir/dev/dev.archive;cd -"); + system("cd $rootimage_dir/dev;cpio -idum<./dev.archive;rm -f ./dev.archive;cd -"); } } @@ -111,85 +113,87 @@ sub mount_chroot { sub umount_chroot { my $rootimage_dir = shift; - if(majversion($osver) >6){ + if (majversion($osver) > 6) { system("umount -l $rootimage_dir/proc"); system("umount -l $rootimage_dir/sys"); + #system("umount -l $rootimage_dir/dev"); system("rm -rf $rootimage_dir/dev/*"); } } #check whether a dir is NFS mounted -sub isNFSdir{ - my $dir=shift; - my $out=qx(df -T -P $dir|tail -n 1|awk '{print \$2}'); +sub isNFSdir { + my $dir = shift; + my $out = qx(df -T -P $dir|tail -n 1|awk '{print \$2}'); - if($out =~ /nfs/i) - { + if ($out =~ /nfs/i) + { return 1; - } + } - return 0; + return 0; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'g=s' => \$krpmver, - 'permission=s' => \$permission, - 'kerneldir=s' => \$kerneldir, - 'tempfile=s' =>\$tempfile, #internal flag - 'pkglist=s' => \$pkglist, #internal flag - 'srcdir=s' => \$srcdir, #internal flag - 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag - 'otherpkglist=s' => \$otherpkglist, #internal flag - 'postinstall=s' => \$postinstall_filename, #internal flag - 'rootimgdir=s' => \$destdir, #internal flag - 'driverupdatesrc=s' => \$driverupdatesrc, #internal flag - 'interactive' =>\$prompt, - 'onlyinitrd' =>\$onlyinitrd, - 'ignorekernelchk' => \$ignorekernelchk, - 'noupdate' => \$noupdate, + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'g=s' => \$krpmver, + 'permission=s' => \$permission, + 'kerneldir=s' => \$kerneldir, + 'tempfile=s' => \$tempfile, #internal flag + 'pkglist=s' => \$pkglist, #internal flag + 'srcdir=s' => \$srcdir, #internal flag + 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag + 'otherpkglist=s' => \$otherpkglist, #internal flag + 'postinstall=s' => \$postinstall_filename, #internal flag + 'rootimgdir=s' => \$destdir, #internal flag + 'driverupdatesrc=s' => \$driverupdatesrc, #internal flag + 'interactive' => \$prompt, + 'onlyinitrd' => \$onlyinitrd, + 'ignorekernelchk' => \$ignorekernelchk, + 'noupdate' => \$noupdate, ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } -my %updates_os = (); # the hash for updating osimage table -my %updates = (); # the hash for updating linuximage table +my %updates_os = (); # the hash for updating osimage table +my %updates = (); # the hash for updating linuximage table $permission = "755" unless ($permission); -$updates{'permission'} = $permission if ( $tempfile ); +$updates{'permission'} = $permission if ($tempfile); unless ($arch) { $arch = `uname -m`; chomp($arch); - $arch = "x86" if ($arch =~ /i.86$/); + $arch = "x86" if ($arch =~ /i.86$/); } -$srcdir="$installroot/$osver/$arch" unless ($srcdir); +$srcdir = "$installroot/$osver/$arch" unless ($srcdir); $updates{'pkgdir'} = $srcdir if ($tempfile); $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch" unless ($srcdir_otherpkgs); $updates{'otherpkgdir'} = $srcdir_otherpkgs if ($tempfile); -$destdir="$installroot/netboot/$osver/$arch/$profile" unless ($destdir); +$destdir = "$installroot/netboot/$osver/$arch/$profile" unless ($destdir); $updates{'rootimgdir'} = $destdir if ($tempfile); -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; + +$kerneldir = "$installroot/kernels" unless ($kerneldir); # the default directory for 3rd-party kernel is "$installroot/kernels"; -$kerneldir = "$installroot/kernels" unless ($kerneldir); # the default directory for 3rd-party kernel is "$installroot/kernels"; #$updates{'kerneldir'} = $kerneldir if ($tempfile); # Get the subchannels of the given interface @@ -197,46 +201,47 @@ my $subchn; my $readChn; my @chn; if ($arch eq "s390x") { - $subchn = `cat /etc/sysconfig/network-scripts/ifcfg-$prinic | grep "SUBCHANNELS"`; - - if (!$subchn) { - print "SUBCHANNELS need to be given in /etc/sysconfig/network-scripts/ifcfg-$prinic"; - exit 1; - } else { - # Trim right - $subchn =~ s/\s*$//; + $subchn = `cat /etc/sysconfig/network-scripts/ifcfg-$prinic | grep "SUBCHANNELS"`; - # Trim left - $subchn =~ s/^\s*//; - - # Extract subchannels - $subchn =~ s/SUBCHANNELS=//g; - - # Extract read channel - @chn = split( ",", $subchn ); - $readChn = @chn[0]; - } + if (!$subchn) { + print "SUBCHANNELS need to be given in /etc/sysconfig/network-scripts/ifcfg-$prinic"; + exit 1; + } else { + + # Trim right + $subchn =~ s/\s*$//; + + # Trim left + $subchn =~ s/^\s*//; + + # Extract subchannels + $subchn =~ s/SUBCHANNELS=//g; + + # Extract read channel + @chn = split(",", $subchn); + $readChn = @chn[0]; + } } unless ($osver and $profile) { - usage(); - exit 1; + usage(); + exit 1; } my @ndrivers; if ($netdriver) { - foreach (split /,/,$netdriver) { + foreach (split /,/, $netdriver) { if (/^allupdate$/) { next; } - unless (/\.ko$/) { - s/$/.ko/; - } - next if (/^$/); - push @ndrivers, $_; + unless (/\.ko$/) { + s/$/.ko/; + } + next if (/^$/); + push @ndrivers, $_; } - - if ( ($updates{'netdrivers'} ne $netdriver) and ($tempfile) ) { + + if (($updates{'netdrivers'} ne $netdriver) and ($tempfile)) { $updates{'netdrivers'} = $netdriver; } } @@ -246,120 +251,121 @@ if ($arch eq 'x86' or $arch eq 'x86_64') { push @ndrivers, qw/tg3 bnx2 bnx2x e1000 e1000e igb mlx_en virtio_net be2net/; } elsif ($arch eq 'ppc64') { push @ndrivers, qw/e1000 e1000e igb ibmveth ehea/; -} elsif ($arch eq 's390x') { +} elsif ($arch eq 's390x') { push @ndrivers, qw/qdio ccwgroup/; } foreach (@ndrivers) { - unless (/\.ko$/) { - s/$/.ko/; - } + unless (/\.ko$/) { + s/$/.ko/; + } } unless ($onlyinitrd) { - @yumdirs=(); + @yumdirs = (); - my @pkgdirs = split(",", $srcdir); - my $dir; - foreach $dir (@pkgdirs) { - find(\&isyumdir, <$dir/>); - if (!grep /$dir/, @yumdirs) { - print "The repository for $dir should be created before running the genimge. Try to run [createrepo $dir].\n"; - } - } + my @pkgdirs = split(",", $srcdir); + my $dir; + foreach $dir (@pkgdirs) { + find(\&isyumdir, <$dir/>); + if (!grep /$dir/, @yumdirs) { + print "The repository for $dir should be created before running the genimge. Try to run [createrepo $dir].\n"; + } + } - # Add the dir for kernel rpm to be installed - if ($kernelver) { - find(\&isyumdir, <$kerneldir/>); - if (!grep /$kerneldir/, @yumdirs) { - print "The repository for $kerneldir should be created before running the genimge. Try to run [createrepo $kerneldir].\n"; - } - } - unless (scalar(@yumdirs)) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + # Add the dir for kernel rpm to be installed + if ($kernelver) { + find(\&isyumdir, <$kerneldir/>); + if (!grep /$kerneldir/, @yumdirs) { + print "The repository for $kerneldir should be created before running the genimge. Try to run [createrepo $kerneldir].\n"; + } + } + unless (scalar(@yumdirs)) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } - mkpath "$rootimg_dir"; - my $yumconfig; - open($yumconfig,">","/tmp/genimage.$$.yum.conf"); + mkpath "$rootimg_dir"; + my $yumconfig; + open($yumconfig, ">", "/tmp/genimage.$$.yum.conf"); - #yum/rpm/zypper has defect on calculating diskspace usage when installing rpm on a NFS mounted installroot - if(isNFSdir("$rootimg_dir")){ - print $yumconfig "[main]\ndiskspacecheck=0\n\n"; - } + #yum/rpm/zypper has defect on calculating diskspace usage when installing rpm on a NFS mounted installroot + if (isNFSdir("$rootimg_dir")) { + print $yumconfig "[main]\ndiskspacecheck=0\n\n"; + } - my $repnum=0; - foreach $srcdir (@yumdirs) { - print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; - $repnum += 1; - } - $repnum-=1; - close($yumconfig); - mkpath "$rootimg_dir/etc"; - + my $repnum = 0; + foreach $srcdir (@yumdirs) { + print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; + $repnum += 1; + } + $repnum -= 1; + close($yumconfig); + mkpath "$rootimg_dir/etc"; - my $fd; - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); - my $non_interactive; - if (!$prompt) { $non_interactive="-y"; } + my $fd; + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); - my $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + my $non_interactive; + if (!$prompt) { $non_interactive = "-y"; } - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - - mkpath("$rootimg_dir/var/lib/yum"); + my $yumcmd = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - unless ($imagename) { - $pkglist= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); - unless ($pkglist) { - $pkglist= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); - } - } + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } - if ($pkglist) { - $updates{'pkglist'} = $pkglist if ($tempfile); - } else { - print "Unable to find package list for $profile!"; - exit 1; - } + mkpath("$rootimg_dir/var/lib/yum"); - mount_chroot($rootimg_dir); + unless ($imagename) { + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); + unless ($pkglist) { + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); + } + } - my %pkg_hash=imgutils::get_package_names($pkglist); + if ($pkglist) { + $updates{'pkglist'} = $pkglist if ($tempfile); + } else { + print "Unable to find package list for $profile!"; + exit 1; + } - my $index=1; - my $pass; - foreach $pass (sort {$a <=> $b} (keys(%pkg_hash))) { + mount_chroot($rootimg_dir); + + my %pkg_hash = imgutils::get_package_names($pkglist); + + my $index = 1; + my $pass; + foreach $pass (sort { $a <=> $b } (keys(%pkg_hash))) { my $pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$pkg_hash{$pass}{INCLUDEBAD}}); - umount_chroot($rootimg_dir); - exit 1; + foreach (keys(%{ $pkg_hash{$pass} })) { + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $pkg_hash{$pass}{INCLUDEBAD} }); + umount_chroot($rootimg_dir); + exit 1; } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} - my $pa=$pkg_hash{$pass}{$_}; + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + my $pa = $pkg_hash{$pass}{$_}; my @npa = (); + # replace the kernel package with the name has the specific version foreach my $p (@$pa) { if ($p =~ /^kernel$/ && $kernelver) { my $kernelname; if ($krpmver) { - $kernelname = "kernel-".$krpmver; + $kernelname = "kernel-" . $krpmver; } else { - $kernelname = "kernel-".$kernelver; + $kernelname = "kernel-" . $kernelver; } my $searchkern = $yumcmd . " list $kernelname -q"; - my @kernpkgs = `$searchkern`; - my $found = 0; + my @kernpkgs = `$searchkern`; + my $found = 0; foreach my $k (@kernpkgs) { if ($k =~ /\s*kernel[^\s]*\s+([\w\.-]+)/) { my $version = $1; @@ -385,13 +391,13 @@ unless ($onlyinitrd) { $pkgnames .= " " . join(' ', @npa); } my $envlist; - if(exists $pkg_hash{$pass}{ENVLIST}){ - $envlist = join(' ', @{$pkg_hash{$pass}{ENVLIST}}); + if (exists $pkg_hash{$pass}{ENVLIST}) { + $envlist = join(' ', @{ $pkg_hash{$pass}{ENVLIST} }); } print "$envlist $yumcmd install $pkgnames\n"; my $rc = system("$envlist $yumcmd install $pkgnames"); - if ($rc) { + if ($rc) { print "yum invocation failed\n"; umount_chroot($rootimg_dir); exit 1; @@ -401,32 +407,32 @@ unless ($onlyinitrd) { #Now let's handle extra packages unless ($imagename) { $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "otherpkgs.pkglist"); - unless ($otherpkglist) { $otherpkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } + unless ($otherpkglist) { $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } } - my %extra_hash=(); + my %extra_hash = (); if ($otherpkglist) { $updates{'otherpkglist'} = $otherpkglist if ($tempfile); %extra_hash = imgutils::get_package_names($otherpkglist); } - my %extrapkgnames; + my %extrapkgnames; my %repohash; if (keys(%extra_hash) > 0) { - open($yumconfig,">>","/tmp/genimage.$$.yum.conf"); - my $index=1; - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { + open($yumconfig, ">>", "/tmp/genimage.$$.yum.conf"); + my $index = 1; + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$extra_hash{$pass}{INCLUDEBAD}}); + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $extra_hash{$pass}{INCLUDEBAD} }); umount_chroot($rootimg_dir); exit 1; } - - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} + + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; $repohash{$pass}{$index} = 1; $index++; - my $pa=$extra_hash{$pass}{$_}; + my $pa = $extra_hash{$pass}{$_}; $extrapkgnames{$pass} .= " " . join(' ', @$pa); } } @@ -435,57 +441,60 @@ unless ($onlyinitrd) { my $yumcmd_base = "yum $non_interactive -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; #yum/rpm/zypper has defect on calculating diskspace usage when installing rpm on a NFS mounted installroot - if(isNFSdir("$rootimg_dir")){ + if (isNFSdir("$rootimg_dir")) { $yumcmd_base .= "--setopt=diskspacecheck=0 "; } - foreach (0..$repnum) { + foreach (0 .. $repnum) { $yumcmd_base .= "--enablerepo=$osver-$arch-$_ "; } -# for (1..$index) { -# $yumcmd .= "--enablerepo=otherpkgs$_ "; -# } + + # for (1..$index) { + # $yumcmd .= "--enablerepo=otherpkgs$_ "; + # } # Hack uname when deal otherpkgs use_hackuname(); use_devnull(); - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { $yumcmd = $yumcmd_base; - foreach my $repo_index ( keys %{$repohash{$pass}} ) { + foreach my $repo_index (keys %{ $repohash{$pass} }) { $yumcmd .= "--enablerepo=otherpkgs$repo_index "; } system("$yumcmd clean all"); my $envlist; - if(exists($extra_hash{$pass}{ENVLIST})){ - $envlist = join(' ', @{$extra_hash{$pass}{ENVLIST}}); + if (exists($extra_hash{$pass}{ENVLIST})) { + $envlist = join(' ', @{ $extra_hash{$pass}{ENVLIST} }); } + # remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "$yumcmd erase "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); + my $yumcmd_remove = "$yumcmd erase "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); if ($rm_packges) { print "$envlist $yumcmd_remove $rm_packges\n"; $rc = system("$envlist $yumcmd_remove $rm_packges"); } } -# # mount /proc file system since several packages need it. -# print "mount /proc file system\nchroot $rootimg_dir /bin/mount -t proc proc /proc\n"; -# system("chroot $rootimg_dir /bin/mount -t proc proc /proc"); + # # mount /proc file system since several packages need it. + # print "mount /proc file system\nchroot $rootimg_dir /bin/mount -t proc proc /proc\n"; + # system("chroot $rootimg_dir /bin/mount -t proc proc /proc"); # install extra packages my $yumcmd_base = $yumcmd; $yumcmd .= "install "; + # append extra pkg names to yum command if ($extrapkgnames{$pass}) { $yumcmd .= " $extrapkgnames{$pass} "; $yumcmd =~ s/ $/\n/; - + # debug #print "yumcmd=$yumcmd\n"; #my $repo=`cat /tmp/genimage.$$.yum.conf`; @@ -495,6 +504,7 @@ unless ($onlyinitrd) { my $rc = system("$envlist $yumcmd"); if ($rc) { print "yum invocation failed\n"; + # remove the hacked uname file unuse_hackuname(); umount_chroot($rootimg_dir); @@ -504,14 +514,14 @@ unless ($onlyinitrd) { print "No Packages marked for install\n"; } -# # umount /proc file system that just mounted -# print "umount /proc file system\nchroot $rootimg_dir /bin/umount /proc\n"; -# system("chroot $rootimg_dir /bin/umount /proc"); - + # # umount /proc file system that just mounted + # print "umount /proc file system\nchroot $rootimg_dir /bin/umount /proc\n"; + # system("chroot $rootimg_dir /bin/umount /proc"); + # remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); if ($rm_packges) { print "$envlist $yumcmd_remove $rm_packges\n"; $rc = system("$envlist $yumcmd_remove $rm_packges"); @@ -520,41 +530,47 @@ unless ($onlyinitrd) { $yumcmd = $yumcmd_base; if (!$noupdate) { + # run yum update to update any installed rpms # needed when running genimage again after updating software in repositories my $yumcmd_update = $yumcmd_base . " update "; $rc = system("$yumcmd_update"); } } - + # use the original uname binary unuse_hackuname(); } umount_chroot($rootimg_dir); + # ignore any return code - postscripts(); #run 'postscripts' + postscripts(); #run 'postscripts' } #get the rpm version, if the rpm version is different then the db verison may change. my $mnrpmver = `rpm --version | awk '{print \$3}'`; my $cnrpmver = `chroot $rootimg_dir rpm --version | awk '{print \$3}'`; -if ( $mnrpmver ne $cnrpmver ){ +if ($mnrpmver ne $cnrpmver) { + #fine all db file witch should be rebuided my $filelist = `file $rootimg_dir/var/lib/rpm/* | grep 'Berkeley DB' | awk -F : '{print \$1}'`; my @files = split '\n', $filelist; system("rm -rf $rootimg_dir/var/lib/rpm/__db*"); - foreach my $file ( @files ){ + foreach my $file (@files) { my $filename = basename($file); + #dump the db file to a normal test file with the db_dump on the mn system("db_dump $file > $rootimg_dir/tmp/$filename.dbtmp9"); unlink("$rootimg_dir/var/lib/rpm/$filename"); + #chroot to the rootimage and run db_load system(" chroot $rootimg_dir db_load -f /tmp/$filename.dbtmp9 /var/lib/rpm/$filename"); } system("rm -rf $rootimg_dir/tmp/*.dbtmp9"); + #rebuild rpm db file in rootimage for cn system(" chroot $rootimg_dir rpm --rebuilddb"); } @@ -566,12 +582,12 @@ if ( $mnrpmver ne $cnrpmver ){ # if all else fails, resort to uname -r like this script did before # Kernel name for s390x should be the same: vmlinuz-2.6.18-164.el5 -my @KVERS= <$rootimg_dir/boot/vmlinuz-*>; +my @KVERS = <$rootimg_dir/boot/vmlinuz-*>; foreach (@KVERS) { s/vmlinuz-//; } -@KVERS= <$rootimg_dir/lib/modules/*> unless (scalar(@KVERS)); +@KVERS = <$rootimg_dir/lib/modules/*> unless (scalar(@KVERS)); $basekernelver = basename(pop @KVERS) if (scalar(@KVERS)); @@ -583,11 +599,11 @@ chomp($kernelver); #$updates{'kernelver'} = $kernelver if ($tempfile); # copy the kernel to $destdir -if ( -e "$rootimg_dir/boot/vmlinux-$kernelver") { +if (-e "$rootimg_dir/boot/vmlinux-$kernelver") { cp("$rootimg_dir/boot/vmlinux-$kernelver", "$destdir/kernel"); -} elsif ( -e "$rootimg_dir/boot/vmlinuz-$kernelver") { +} elsif (-e "$rootimg_dir/boot/vmlinuz-$kernelver") { cp("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); -} elsif ( -e "$rootimg_dir/boot/image-$kernelver") { +} elsif (-e "$rootimg_dir/boot/image-$kernelver") { cp("$rootimg_dir/boot/image-$kernelver", "$destdir/kernel"); } else { xdie("couldn't find the kernel file matched $kernelver in $rootimg_dir/boot"); @@ -599,7 +615,7 @@ my @dd_drivers = &load_dd(); # Push the drivers into the @ndrivers base on the order my @new_order = (); foreach my $dd (@dd_drivers) { - unless (grep { $_ eq $dd} @ndrivers) { + unless (grep { $_ eq $dd } @ndrivers) { push @new_order, $dd; } print "Added driver $dd from driver update disk or driver rpm\n"; @@ -610,29 +626,29 @@ if (@new_order) { } if (-f "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/net/ethernet/mellanox/mlx4/mlx4_en.ko") { - for (@ndrivers) { - s/mlx_en/mlx4_en/; - } + for (@ndrivers) { + s/mlx_en/mlx4_en/; + } } -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added print "Added $dep as an autodetected depedency\n"; } - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); } } } @@ -641,7 +657,7 @@ close($moddeps); #remove the duplicated drivers my @fulldrivers; foreach my $dn (@ndrivers) { - unless (grep {$_ eq $dn} @fulldrivers) { + unless (grep { $_ eq $dn } @fulldrivers) { push @fulldrivers, $dn; } } @@ -650,8 +666,9 @@ foreach my $dn (@ndrivers) { my $dracutver; unlink "/tmp/genimage.$$.yum.conf"; -if ( (-d "$rootimg_dir/usr/share/dracut") or (-d "$rootimg_dir/usr/lib/dracut") ) { +if ((-d "$rootimg_dir/usr/share/dracut") or (-d "$rootimg_dir/usr/lib/dracut")) { $dracutmode = 1; + # get dracut version $dracutver = `rpm --root $rootimg_dir -qi dracut | grep Version | awk -F' ' '{print \$3}'`; chomp($dracutver); @@ -659,7 +676,7 @@ if ( (-d "$rootimg_dir/usr/share/dracut") or (-d "$rootimg_dir/usr/lib/dracut") if ($dracutver >= "033") { $dracutdir = "dracut_033"; } else { - $dracutdir = "dracut"; # The default directory + $dracutdir = "dracut"; # The default directory } } print "Enter the dracut mode. Dracut version: $dracutver. Dracut directory: $dracutdir.\n"; @@ -667,31 +684,31 @@ if ( (-d "$rootimg_dir/usr/share/dracut") or (-d "$rootimg_dir/usr/lib/dracut") #-- for centos, disable the internet repository -if( -e "$rootimg_dir/etc/yum.repos.d/CentOS-Base.repo" ) { - my $repo_content=`sed -e '/enabled/d' $rootimg_dir/etc/yum.repos.d/CentOS-Base.repo | sed -e '/^gpgkey/i enabled=0'`; +if (-e "$rootimg_dir/etc/yum.repos.d/CentOS-Base.repo") { + my $repo_content = `sed -e '/enabled/d' $rootimg_dir/etc/yum.repos.d/CentOS-Base.repo | sed -e '/^gpgkey/i enabled=0'`; system("echo '$repo_content' > $rootimg_dir/etc/yum.repos.d/CentOS-Base.repo"); } # #-- run postinstall script unless ($imagename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); unless ($postinstall_filename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); } -} +} -if ( $postinstall_filename ) { +if ($postinstall_filename) { - #For Mellonax IB script. In diskless image, the uname -r not returning the rootimg level, + #For Mellonax IB script. In diskless image, the uname -r not returning the rootimg level, #because the "uname -r" only returns the version of the kernel in use - #create a temporary uname script. for every flag except for -r, it should just call the real + #create a temporary uname script. for every flag except for -r, it should just call the real #uname with the same flags and return that info. - if(!( -e "$rootimg_dir/bin/orig_uname")) { + if (!(-e "$rootimg_dir/bin/orig_uname")) { system("mv $rootimg_dir/bin/uname $rootimg_dir/bin/orig_uname"); } my $tmpuname; - open($tmpuname,">","$rootimg_dir/bin/uname"); + open($tmpuname, ">", "$rootimg_dir/bin/uname"); print $tmpuname <>$tempfile"); if ($imagename) { - if (keys(%updates) > 0) { - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$imagename\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - } + if (keys(%updates) > 0) { + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$imagename\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + } } else { - $updates_os{'profile'} = $profile; - $updates_os{'imagetype'} = 'linux'; - $updates_os{'provmethod'} = 'netboot'; - $updates_os{'osname'} = 'Linux'; - $updates_os{'osvers'} = $osver; - $updates_os{'osarch'} = $arch; - # update the imagename for stateless - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - # update the imagename for statelite - $updates_os{'provmethod'} = 'statelite'; - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-statelite-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-statelite-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; + $updates_os{'profile'} = $profile; + $updates_os{'imagetype'} = 'linux'; + $updates_os{'provmethod'} = 'netboot'; + $updates_os{'osname'} = 'Linux'; + $updates_os{'osvers'} = $osver; + $updates_os{'osarch'} = $arch; + + # update the imagename for stateless + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + # update the imagename for statelite + $updates_os{'provmethod'} = 'statelite'; + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-statelite-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-statelite-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; } close FILE; } + #END # statelite .statelite directory added here. # this is where tmpfs will be created. -mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. -mkpath "$rootimg_dir/.sllocal/localmnt"; # create place for localdisk mount -mkpath "$rootimg_dir/.sllocal/log"; # create place for localdisk log +mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. +mkpath "$rootimg_dir/.sllocal/localmnt"; # create place for localdisk mount +mkpath "$rootimg_dir/.sllocal/log"; # create place for localdisk log -# this script will get the directories. +# this script will get the directories. # TODO: the file is re-copied in liteimg.pm my $cwd = $FindBin::Bin; unless (-f "$cwd/../add-on/statelite/rc.statelite") { - print "Can't find $cwd/../add-on/statelite/rc.statelite!\n"; - exit 1; + print "Can't find $cwd/../add-on/statelite/rc.statelite!\n"; + exit 1; } system("cp $cwd/../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); system("cp $cwd/../add-on/statelite/rc.localdisk $rootimg_dir/etc/init.d/localdisk"); + # also need to add this file: # may have already been made into a symbolic link, if so ignore it -unless ($dracutmode) { #in dracut mode, we delegate all this activity - unless (-l "$rootimg_dir/var/lib/dhclient" ) { - mkpath "$rootimg_dir/var/lib/dhclient/"; - system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); +unless ($dracutmode) { #in dracut mode, we delegate all this activity + unless (-l "$rootimg_dir/var/lib/dhclient") { + mkpath "$rootimg_dir/var/lib/dhclient/"; + system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); } - - unless (-l "$rootimg_dir/var/lib/dhcp" ) { - mkpath "$rootimg_dir/var/lib/dhcp/"; - system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); + + unless (-l "$rootimg_dir/var/lib/dhcp") { + mkpath "$rootimg_dir/var/lib/dhcp/"; + system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); } } #if ($dracutmode) { - # modify etc/rc.sysinit, prevent remounting - # TODO: need to find one way to prevent remounting - if (-f "$rootimg_dir/etc/rc.sysinit") { - my $SYSINITFILE; - my $TMPSYSINITFILE; - # backup etc/rc.sysinit file before modifing it - system("cp -a $rootimg_dir/etc/rc.sysinit $rootimg_dir/etc/rc.sysinit.backup"); - open($SYSINITFILE, "$rootimg_dir/etc/rc.sysinit"); - open($TMPSYSINITFILE, '>', "/tmp/rc.sysinit.tmp"); - # find the following lines, - # if remount_needed ; then - # action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw / - # fi - # and change "if remount_needed ; then" to "if false; then" - while(<$SYSINITFILE>) { - if ($_ eq "if remount_needed ; then\n") { - $_ = "if false; then\n"; - } - print $TMPSYSINITFILE $_; +# modify etc/rc.sysinit, prevent remounting +# TODO: need to find one way to prevent remounting +if (-f "$rootimg_dir/etc/rc.sysinit") { + my $SYSINITFILE; + my $TMPSYSINITFILE; + + # backup etc/rc.sysinit file before modifing it + system("cp -a $rootimg_dir/etc/rc.sysinit $rootimg_dir/etc/rc.sysinit.backup"); + open($SYSINITFILE, "$rootimg_dir/etc/rc.sysinit"); + open($TMPSYSINITFILE, '>', "/tmp/rc.sysinit.tmp"); + + # find the following lines, + # if remount_needed ; then + # action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw / + # fi + # and change "if remount_needed ; then" to "if false; then" + while (<$SYSINITFILE>) { + if ($_ eq "if remount_needed ; then\n") { + $_ = "if false; then\n"; } - close($SYSINITFILE); - close($TMPSYSINITFILE); - cp("/tmp/rc.sysinit.tmp", "$rootimg_dir/etc/rc.sysinit"); + print $TMPSYSINITFILE $_; } + close($SYSINITFILE); + close($TMPSYSINITFILE); + cp("/tmp/rc.sysinit.tmp", "$rootimg_dir/etc/rc.sysinit"); +} + #} -# before mkinitrd, run depmod to generate modules.dep +# before mkinitrd, run depmod to generate modules.dep system("chroot $rootimg_dir depmod $kernelver"); # for the genimage-enchement, need to create two initial ramdisks, @@ -860,81 +884,83 @@ if ($dracutmode) { } sub getlibs { - my $file = shift; + my $file = shift; my $liblist = `chroot $rootimg_dir ldd $file`; if ($liblist =~ /not a dynamic executable/) { return; } - my @libs = split/\n/,$liblist; + my @libs = split /\n/, $liblist; my @return; foreach (@libs) { unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; $lib =~ s/^\///; - $libhash{$lib}=1; + $libhash{$lib} = 1; next; } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; unless ($temp1 =~ /\//) { next; } $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + $libhash{$temp1} = 1; + } } sub mkinitrd_dracut { - my ($mode) = @_; # the mode is for statelite or stateless + my ($mode) = @_; # the mode is for statelite or stateless - my $dracutmoduledir="$rootimg_dir/usr/share/dracut/modules.d/"; - if ( (! -d $dracutmoduledir) and (-d "$rootimg_dir/usr/lib/dracut/modules.d/")) + my $dracutmoduledir = "$rootimg_dir/usr/share/dracut/modules.d/"; + if ((!-d $dracutmoduledir) and (-d "$rootimg_dir/usr/lib/dracut/modules.d/")) { - $dracutmoduledir="$rootimg_dir/usr/lib/dracut/modules.d/"; + $dracutmoduledir = "$rootimg_dir/usr/lib/dracut/modules.d/"; } if ($dracutver >= "033") { my $perm = (stat("$fullpath/$dracutdir/patch/syslog/module-setup.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/module-setup.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."module-setup.sh"); + cp("$fullpath/$dracutdir/patch/syslog/module-setup.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "module-setup.sh"); $perm = (stat("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."rsyslogd-start.sh"); + cp("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "rsyslogd-start.sh"); $perm = (stat("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."syslog-genrules.sh"); + cp("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "syslog-genrules.sh"); } else { my $perm = (stat("$fullpath/$dracutdir/patch/syslog/check"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/check", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."check"); + cp("$fullpath/$dracutdir/patch/syslog/check", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "check"); $perm = (stat("$fullpath/$dracutdir/patch/syslog/install"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/install", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."install"); + cp("$fullpath/$dracutdir/patch/syslog/install", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "install"); $perm = (stat("$fullpath/$dracutdir/patch/syslog/parse-syslog-opts.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/parse-syslog-opts.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."parse-syslog-opts.sh"); + cp("$fullpath/$dracutdir/patch/syslog/parse-syslog-opts.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "parse-syslog-opts.sh"); } - my $dracutmpath = $dracutmoduledir."97xcat/"; + my $dracutmpath = $dracutmoduledir . "97xcat/"; mkpath($dracutmpath); my $perm = (stat("$fullpath/$dracutdir/check"))[2]; cp("$fullpath/$dracutdir/check", $dracutmpath); - chmod($perm&07777, "$dracutmpath/check"); + chmod($perm & 07777, "$dracutmpath/check"); foreach (@ndrivers) { s/\.ko$//; } + # Add drivers to support local disk push @ndrivers, "ext3"; push @ndrivers, "ext4"; + #remove the duplicated drivers my @fulldrivers; foreach my $dn (@ndrivers) { - unless (grep {$_ eq $dn} @fulldrivers) { + unless (grep { $_ eq $dn } @fulldrivers) { push @fulldrivers, $dn; } } @@ -945,65 +971,66 @@ sub mkinitrd_dracut { my $DRACUTCONF; if ($mode eq "statelite") { + # for statelite - cp("$fullpath/$dracutdir/install.statelite","$dracutmpath/install"); + cp("$fullpath/$dracutdir/install.statelite", "$dracutmpath/install"); $perm = (stat("$fullpath/$dracutdir/install.statelite"))[2]; - chmod($perm&07777, "$dracutmpath/install"); + chmod($perm & 07777, "$dracutmpath/install"); - cp("$installroot/postscripts/updateflag.awk","$dracutmpath/xcat-updateflag"); + cp("$installroot/postscripts/updateflag.awk", "$dracutmpath/xcat-updateflag"); $perm = (stat("$installroot/postscripts/updateflag.awk"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-updateflag"); + chmod($perm & 07777, "$dracutmpath/xcat-updateflag"); - cp("$fullpath/$dracutdir/xcat-prepivot.sh",$dracutmpath); + cp("$fullpath/$dracutdir/xcat-prepivot.sh", $dracutmpath); $perm = (stat("$fullpath/$dracutdir/xcat-prepivot.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-prepivot.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-prepivot.sh"); - cp("$fullpath/$dracutdir/xcat-premount.sh",$dracutmpath); + cp("$fullpath/$dracutdir/xcat-premount.sh", $dracutmpath); $perm = (stat("$fullpath/$dracutdir/xcat-premount.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-premount.sh"); - + chmod($perm & 07777, "$dracutmpath/xcat-premount.sh"); + #update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); - if (-d glob($dracutmoduledir."[0-9]*fadump")){ + if (-d glob($dracutmoduledir . "[0-9]*fadump")) { print $DRACUTCONF qq{dracutmodules+="xcat nfs base network kernel-modules syslog fadump"\n}; } - else{ + else { print $DRACUTCONF qq{dracutmodules+="xcat nfs base network kernel-modules syslog"\n}; } print $DRACUTCONF qq{add_drivers+="$add_drivers"\n}; print $DRACUTCONF qq{filesystems+="nfs"\n}; close $DRACUTCONF; } elsif ($mode eq "stateless") { - cp("$fullpath/$dracutdir/install.netboot","$dracutmpath/install"); + cp("$fullpath/$dracutdir/install.netboot", "$dracutmpath/install"); $perm = (stat("$fullpath/$dracutdir/install.netboot"))[2]; - chmod($perm&07777, "$dracutmpath/install"); + chmod($perm & 07777, "$dracutmpath/install"); - cp("$fullpath/$dracutdir/xcat-cmdline.sh","$dracutmpath/"); + cp("$fullpath/$dracutdir/xcat-cmdline.sh", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/xcat-cmdline.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-cmdline.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-cmdline.sh"); - cp("$installroot/postscripts/updateflag.awk","$dracutmpath/xcat-updateflag"); + cp("$installroot/postscripts/updateflag.awk", "$dracutmpath/xcat-updateflag"); $perm = (stat("$installroot/postscripts/updateflag.awk"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-updateflag"); + chmod($perm & 07777, "$dracutmpath/xcat-updateflag"); if ($prinic) { my $optspec; - open($optspec,'>>',"$dracutmpath/xcat-cmdline.sh"); + open($optspec, '>>', "$dracutmpath/xcat-cmdline.sh"); print $optspec "PRINIC=$prinic\n"; close $optspec; } - cp("$fullpath/$dracutdir/xcatroot","$dracutmpath/"); + cp("$fullpath/$dracutdir/xcatroot", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/xcatroot"))[2]; - chmod($perm&07777, "$dracutmpath/xcatroot"); + chmod($perm & 07777, "$dracutmpath/xcatroot"); cp("$fullpath/$dracutdir/installkernel", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/installkernel"))[2]; - chmod($perm&07777, "$dracutmpath/installkernel"); + chmod($perm & 07777, "$dracutmpath/installkernel"); - my $dracutmodulelist=" xcat nfs base network kernel-modules syslog "; - if (-d glob($dracutmoduledir."[0-9]*fadump")){ - $dracutmodulelist .=" fadump "; + my $dracutmodulelist = " xcat nfs base network kernel-modules syslog "; + if (-d glob($dracutmoduledir . "[0-9]*fadump")) { + $dracutmodulelist .= " fadump "; } @@ -1016,13 +1043,13 @@ sub mkinitrd_dracut { xdie "the mode: $mode is not supported by genimage"; } - my $additional_options=undef; - if($rootlimit) + my $additional_options = undef; + if ($rootlimit) { - open(my $ETC_CMDLINE,">","$rootimg_dir/tmp/cmdline"); - print $ETC_CMDLINE qq{rootlimit=$rootlimit\n}; - close $ETC_CMDLINE; - $additional_options= qq{--include /tmp/cmdline /etc/cmdline}; + open(my $ETC_CMDLINE, ">", "$rootimg_dir/tmp/cmdline"); + print $ETC_CMDLINE qq{rootlimit=$rootlimit\n}; + close $ETC_CMDLINE; + $additional_options = qq{--include /tmp/cmdline /etc/cmdline}; } # force the dracut run in non-hostonly mode for dracut higher than version 033 @@ -1031,80 +1058,82 @@ sub mkinitrd_dracut { } #if "pigz" is available in the rootimg, use "pigz" instead of "gzip" - my $compress=qx(chroot $rootimg_dir bash -c "type -p pigz"|tr -d "\n"); - if ($compress){ + my $compress = qx(chroot $rootimg_dir bash -c "type -p pigz"|tr -d "\n"); + if ($compress) { + #take the online cpu numerber as the pigz processes number - my $processnum=qx(lscpu -p=cpu --online|grep -v '#'|wc -l|tr -d "\n"); + my $processnum = qx(lscpu -p=cpu --online|grep -v '#'|wc -l|tr -d "\n"); $additional_options .= " --compress \"$compress -p $processnum \""; } print "\nchroot $rootimg_dir dracut $additional_options -f /tmp/initrd.$$.gz $kernelver\n"; !system("chroot $rootimg_dir dracut $additional_options -f /tmp/initrd.$$.gz $kernelver") - or die("Error: failed to generate the initial ramdisk for $mode.\n"); + or die("Error: failed to generate the initial ramdisk for $mode.\n"); print "the initial ramdisk for $mode is generated successfully.\n"; - move("$rootimg_dir/tmp/initrd.$$.gz", "$destdir/initrd-$mode.gz"); + move("$rootimg_dir/tmp/initrd.$$.gz", "$destdir/initrd-$mode.gz"); } sub mkinitrd { - my ($mode) = @_; # statelite or stateless + my ($mode) = @_; # statelite or stateless - if($mode eq "statelite") { + if ($mode eq "statelite") { push @ndrivers, "nfs.ko"; - open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); - my @moddeps = <$moddeps>; + open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); + my @moddeps = <$moddeps>; my @checkdeps = ("nfs.ko"); while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; unless (grep { $_ eq $dep } @ndrivers) { #only add if not added - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); print "Added $dep as an autodetected depedency\n"; } } } } - + # Additional modules needed on s390x if ($arch eq "s390x") { + # The network drivers need to be loaded in this order unshift @ndrivers, "ccwgroup.ko"; unshift @ndrivers, "qdio.ko"; } } - - mkpath("/tmp/xcatinitrd.$$/bin"); - - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); - my $inifile; -# start writing to the init script. - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/sbin/busybox.anaconda sh\n"; - -# add some functions - print $inifile <", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/sbin/busybox.anaconda sh\n"; + + # add some functions + print $inifile <> /etc/modprobe.conf echo `ifup $prinic` sleep 4 EOMS -} + } - print $inifile < /dev/null && export DEBUG=1 @@ -1568,40 +1597,41 @@ if [ -r /rootimg.sfs ]; then mount --move /ro \$NEWROOT/ro mount --move /rw \$NEWROOT/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile "echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o size=$rootlimit,mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } - print $inifile " cd \$NEWROOT\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " zcat /rootimg.gz |/bin/cpio -idum\n"; - print $inifile " else\n"; - print $inifile " zcat /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " echo Done\n"; - print $inifile "elif [ -r /rootimg.txz ]; then\n"; - print $inifile " echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o \"size=$rootlimit,mode=755\" -t tmpfs rootfs \$NEWROOT\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } - print $inifile " cd \$NEWROOT\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " tar -Jxvf /rootimg.txz\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 5\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " echo\n"; - print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/sbin/nash\n"; - close($inifile); + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/sbin/nash\n"; + close($inifile); - #/tmp/updateflag: a script to feedback node provision status to xcatd - system("mkdir -p /tmp/xcatinitrd.$$/tmp/"); - open($inifile, ">","/tmp/xcatinitrd.$$/tmp/updateflag"); + #/tmp/updateflag: a script to feedback node provision status to xcatd + system("mkdir -p /tmp/xcatinitrd.$$/tmp/"); + open($inifile, ">", "/tmp/xcatinitrd.$$/tmp/updateflag"); - print $inifile < /tmp/ncarg @@ -1654,138 +1684,141 @@ else fi EOMS - close($inifile); + close($inifile); + + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + chmod(0755, "/tmp/xcatinitrd.$$/tmp/updateflag"); + @filestoadd = (); + foreach (@ndrivers) { + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } + } + + # add rsync for statelite + foreach ("bin/cpio", "sbin/nash", "sbin/busybox.anaconda", "sbin/rmmod", "bin/bash", "usr/sbin/chroot", "sbin/mount.nfs", "usr/bin/rsync", "usr/bin/wc", "usr/bin/xz") { + getlibs($_); + push @filestoadd, $_; + } - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - chmod(0755,"/tmp/xcatinitrd.$$/tmp/updateflag"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - # add rsync for statelite - foreach ("bin/cpio","sbin/nash","sbin/busybox.anaconda","sbin/rmmod", "bin/bash", "usr/sbin/chroot", "sbin/mount.nfs", "usr/bin/rsync", "usr/bin/wc", "usr/bin/xz") { - getlibs($_); - push @filestoadd,$_; - } - # Additional binaries needed for udev on s390x if ($arch eq "s390x") { foreach ("sbin/udevsettle", "sbin/udevtrigger", "sbin/udevd", "sbin/depmod") { getlibs($_); - push @filestoadd,$_; + push @filestoadd, $_; } } - - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libresolv.so.2"; - } else { - push @filestoadd,"lib/libnss_dns.so.2"; - push @filestoadd,"lib/libresolv.so.2"; - } - push @filestoadd,keys %libhash; - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - my $pathonrootimage = "$rootimg_dir/tmpfiles"; - my $pathinrootimage = "/tmpfiles"; - mkpath($pathonrootimage); - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcfile = $_->[0]; - system("chroot $rootimg_dir cp $srcfile $pathinrootimage"); - my $srcpath = "$pathonrootimage/".basename($_->[0]); - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - system("chroot $rootimg_dir cp $_ $pathinrootimage"); - my $srcpath = "$pathonrootimage/".basename($_); - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } - rmtree($pathonrootimage); + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libresolv.so.2"; + } else { + push @filestoadd, "lib/libnss_dns.so.2"; + push @filestoadd, "lib/libresolv.so.2"; + } + push @filestoadd, keys %libhash; - # Copy udev and network scripts into initrd for s390x, which also works for other platforms - # udev - system("mkdir -p /tmp/xcatinitrd.$$/etc/udev"); - system("cp -r $rootimg_dir/etc/udev/* /tmp/xcatinitrd.$$/etc/udev"); - system("mkdir -p /tmp/xcatinitrd.$$/lib/udev"); - system("cp -r $rootimg_dir/lib/udev/* /tmp/xcatinitrd.$$/lib/udev"); - system("mkdir -p /tmp/xcatinitrd.$$/proc/self"); - system("cp -r /proc/self/oom_adj /tmp/xcatinitrd.$$/proc/self"); - - # Network related scripts - system("mkdir -p /tmp/xcatinitrd.$$/etc/sysconfig"); - system("cp -r $rootimg_dir/etc/sysconfig/* /tmp/xcatinitrd.$$/etc/sysconfig"); - system("mkdir -p /tmp/xcatinitrd.$$/sbin"); - system("cp -r $rootimg_dir/sbin/* /tmp/xcatinitrd.$$/sbin"); - system("mkdir -p /tmp/xcatinitrd.$$/lib/modules/$kernelver"); - system("cp -r $rootimg_dir/lib/modules/$kernelver/modules.dep /tmp/xcatinitrd.$$/lib/modules/$kernelver/modules.dep"); - system("mkdir -p /tmp/xcatinitrd.$$/etc/init.d"); - system("cp -r $rootimg_dir/etc/init.d/* /tmp/xcatinitrd.$$/etc/init.d"); - system("mkdir -p /tmp/xcatinitrd.$$/lib64"); - system("cp -r $rootimg_dir/lib64/* /tmp/xcatinitrd.$$/lib64"); - system("mkdir -p /tmp/xcatinitrd.$$/var/run/netreport"); - - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd-$mode.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + my $pathonrootimage = "$rootimg_dir/tmpfiles"; + my $pathinrootimage = "/tmpfiles"; + mkpath($pathonrootimage); + foreach (@filestoadd) { + if (ref($_)) { + + #print "$_->[0], $_->[1]\n"; + my $srcfile = $_->[0]; + system("chroot $rootimg_dir cp $srcfile $pathinrootimage"); + my $srcpath = "$pathonrootimage/" . basename($_->[0]); + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + system("chroot $rootimg_dir cp $_ $pathinrootimage"); + my $srcpath = "$pathonrootimage/" . basename($_); + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + rmtree($pathonrootimage); + + # Copy udev and network scripts into initrd for s390x, which also works for other platforms + # udev + system("mkdir -p /tmp/xcatinitrd.$$/etc/udev"); + system("cp -r $rootimg_dir/etc/udev/* /tmp/xcatinitrd.$$/etc/udev"); + system("mkdir -p /tmp/xcatinitrd.$$/lib/udev"); + system("cp -r $rootimg_dir/lib/udev/* /tmp/xcatinitrd.$$/lib/udev"); + system("mkdir -p /tmp/xcatinitrd.$$/proc/self"); + system("cp -r /proc/self/oom_adj /tmp/xcatinitrd.$$/proc/self"); + + # Network related scripts + system("mkdir -p /tmp/xcatinitrd.$$/etc/sysconfig"); + system("cp -r $rootimg_dir/etc/sysconfig/* /tmp/xcatinitrd.$$/etc/sysconfig"); + system("mkdir -p /tmp/xcatinitrd.$$/sbin"); + system("cp -r $rootimg_dir/sbin/* /tmp/xcatinitrd.$$/sbin"); + system("mkdir -p /tmp/xcatinitrd.$$/lib/modules/$kernelver"); + system("cp -r $rootimg_dir/lib/modules/$kernelver/modules.dep /tmp/xcatinitrd.$$/lib/modules/$kernelver/modules.dep"); + system("mkdir -p /tmp/xcatinitrd.$$/etc/init.d"); + system("cp -r $rootimg_dir/etc/init.d/* /tmp/xcatinitrd.$$/etc/init.d"); + system("mkdir -p /tmp/xcatinitrd.$$/lib64"); + system("cp -r $rootimg_dir/lib64/* /tmp/xcatinitrd.$$/lib64"); + system("mkdir -p /tmp/xcatinitrd.$$/var/run/netreport"); + + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd-$mode.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - print "Added driver $_ to initrd\n"; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + print "Added driver $_ to initrd\n"; + } + } } sub postscripts { - generic_post(); + generic_post(); - # TODO: workaround for kdump on RHEL6 - # add one fake command: fsck.nfs - unless ( -x "$rootimg_dir/sbin/fsck.nfs" ) { + # TODO: workaround for kdump on RHEL6 + # add one fake command: fsck.nfs + unless (-x "$rootimg_dir/sbin/fsck.nfs") { system("echo true > $rootimg_dir/sbin/fsck.nfs; chmod a+x $rootimg_dir/sbin/fsck.nfs"); - } - + } - if( ! -d "$rootimg_dir/opt/xcat/") { - mkdir "$rootimg_dir/opt/xcat/"; - } - copy ("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); - chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; + + if (!-d "$rootimg_dir/opt/xcat/") { + mkdir "$rootimg_dir/opt/xcat/"; + } + copy("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); + chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; } @@ -1795,16 +1828,16 @@ sub using_systemd { if ($1 >= 15) { return 1; } - }elsif ($os =~ /rhels(\d+)/) { + } elsif ($os =~ /rhels(\d+)/) { if ($1 >= 7) { return 1; } - }elsif ($os =~/centos(\d+)/){ - if($1 >= 7){ + } elsif ($os =~ /centos(\d+)/) { + if ($1 >= 7) { return 1; } - }elsif ($os =~/rhelhpc(\d+)/){ - if($1 >= 7){ + } elsif ($os =~ /rhelhpc(\d+)/) { + if ($1 >= 7) { return 1; } } @@ -1814,120 +1847,121 @@ sub using_systemd { sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if (!&using_systemd($osver)) { - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults,size=$tmplimit 0 2\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=$tmplimit 0 2\n"; - } else { - print $cfgfile "tmpfs /tmp tmpfs defaults,size=10m 0 2\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=10m 0 2\n"; - } - } + if (!&using_systemd($osver)) { + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults,size=$tmplimit 0 2\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=$tmplimit 0 2\n"; + } else { + print $cfgfile "tmpfs /tmp tmpfs defaults,size=10m 0 2\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=10m 0 2\n"; + } + } - my $rootfs_name=$profile."_".$arch; - print $cfgfile "$rootfs_name / tmpfs rw 0 1\n"; + my $rootfs_name = $profile . "_" . $arch; + print $cfgfile "$rootfs_name / tmpfs rw 0 1\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); - # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no - # to skip the break of nfs-based boot - if ($prinic) { - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - } - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - - # securetty not needed on s390x - if ($arch ne "s390x") { - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - } - - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - unless ( -r <$rootimg_dir/etc/rc3.d/S??network>) { - symlink "/etc/init.d/network","$rootimg_dir/etc/rc3.d/S10network"; - } - - # gettyset is not found on s390x - if ($arch ne "s390x") { - if (!&using_systemd($osver)) { - open($cfgfile,">","$rootimg_dir/etc/init.d/gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " if [ -x /sbin/initctl ]; then\n"; # Upstart style - # The syntax of next line is not correct, that means it does NOthing. (rh6 and higher) - # And it should NOT work for rh6 and higher, otherwise it will cauase multiple agetty for ttySx - print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; - print $cfgfile " else\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; + # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no + # to skip the break of nfs-based boot + if ($prinic) { + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + } + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } - close($cfgfile); + # securetty not needed on s390x + if ($arch ne "s390x") { + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + } - chmod(0755,"$rootimg_dir/etc/init.d/gettyset"); - system("cd $rootimg_dir/etc/rc3.d; ln -sf ../init.d/gettyset S60gettyset"); - } - - copy("$installroot/postscripts/xcatpostinit", "$rootimg_dir/etc/init.d/xcatpostinit"); - chmod(0755, "$rootimg_dir/etc/init.d/xcatpostinit"); - system("cd $rootimg_dir/etc/rc3.d; ln -sf ../init.d/xcatpostinit S61xcatpostinit"); - } -} + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + unless (-r <$rootimg_dir/etc/rc3.d/S??network>) { + symlink "/etc/init.d/network", "$rootimg_dir/etc/rc3.d/S10network"; + } + + # gettyset is not found on s390x + if ($arch ne "s390x") { + if (!&using_systemd($osver)) { + open($cfgfile, ">", "$rootimg_dir/etc/init.d/gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " if [ -x /sbin/initctl ]; then\n"; # Upstart style + # The syntax of next line is not correct, that means it does NOthing. (rh6 and higher) + # And it should NOT work for rh6 and higher, otherwise it will cauase multiple agetty for ttySx + print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; + print $cfgfile " else\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + + close($cfgfile); + + chmod(0755, "$rootimg_dir/etc/init.d/gettyset"); + system("cd $rootimg_dir/etc/rc3.d; ln -sf ../init.d/gettyset S60gettyset"); + } + + copy("$installroot/postscripts/xcatpostinit", "$rootimg_dir/etc/init.d/xcatpostinit"); + chmod(0755, "$rootimg_dir/etc/init.d/xcatpostinit"); + system("cd $rootimg_dir/etc/rc3.d; ln -sf ../init.d/xcatpostinit S61xcatpostinit"); + } +} my $driver_name; my $real_path; + sub get_path () { if ($File::Find::name =~ /\/$driver_name/) { @@ -1936,6 +1970,7 @@ sub get_path () } my @all_real_path; + sub get_all_path () { if ($File::Find::name =~ /\/$driver_name/) { @@ -1948,10 +1983,10 @@ sub get_all_path () # The valid value: dud:/install/dud/dd.img,rpm:/install/rpm/d.rpm, if missing the tag: 'dud'/'rpm' # the 'rpm' is default. # -# If cannot find the driver disk from osimage.driverupdatesrc, will try to search driver disk +# If cannot find the driver disk from osimage.driverupdatesrc, will try to search driver disk # from /install/driverdisk// # -# For driver rpm, the driver list will be gotten from osimage.netdrivers. If not set, copy all the drivers from driver +# For driver rpm, the driver list will be gotten from osimage.netdrivers. If not set, copy all the drivers from driver # rpm to the initrd. # # Return the driver names by loading order @@ -1978,7 +2013,8 @@ sub load_dd () } } } - if (! @dd_list) { + if (!@dd_list) { + # get Driver update disk from the default path if not specified in osimage # check the Driver Update Disk images, it can be .img or .iso if (-d "$installroot/driverdisk/$osver/$arch") { @@ -1986,7 +2022,7 @@ sub load_dd () } } - foreach (split /,/,$netdriver) { + foreach (split /,/, $netdriver) { if (/^allupdate$/) { $Injectalldriver = 1; next; @@ -2009,35 +2045,35 @@ sub load_dd () my $dd_dir = mkdtemp("/tmp/ddtmpXXXXXXX"); mkpath "$dd_dir/mnt"; mkpath "$dd_dir/mods"; - + my @dd_drivers = (); #driver name - + # Loading drivers from each Driver Disk foreach my $dd (@dd_list) { - my $rc = system ("mount -o loop $dd $dd_dir/mnt"); + my $rc = system("mount -o loop $dd $dd_dir/mnt"); if ($rc) { print "mount the Driver Disk $dd failed.\n"; next; } - - if (! (-f "$dd_dir/mnt/rhdd" || -f "$dd_dir/mnt/modinfo" + + if (!(-f "$dd_dir/mnt/rhdd" || -f "$dd_dir/mnt/modinfo" || -f "$dd_dir/mnt/modules.dep" || -f "$dd_dir/mnt/modules.cgz")) { print "The Driver Disk $dd has not correct format.\n"; - system ("umount -f $dd_dir/mnt"); + system("umount -f $dd_dir/mnt"); next; } - + # Load the modinfo open($modinfo, "<", "$dd_dir/mnt/modinfo"); my @modinfo_lines = <$modinfo>; - my $mod_ver = shift @modinfo_lines; + my $mod_ver = shift @modinfo_lines; chomp($mod_ver); if ($mod_ver !~ /^Version 0/) { print "The Driver Disk $dd has unknown version.\n"; - system ("umount -f $dd_dir/mnt"); + system("umount -f $dd_dir/mnt"); next; } - + foreach my $line (@modinfo_lines) { if ($line !~ /^Version/ && $line =~ /^(\w+)/) { chomp($line); @@ -2047,15 +2083,15 @@ sub load_dd () } } close($modinfo); - - # Copy the firmware + + # Copy the firmware if (-d "$dd_dir/mnt/firmware") { - system ("cp -rf $dd_dir/mnt/firmware $rootimg_dir/lib/firmware"); - } + system("cp -rf $dd_dir/mnt/firmware $rootimg_dir/lib/firmware"); + } # Load the modules.cgz - system ("cd $dd_dir/mods; gunzip -c $dd_dir/mnt/modules.cgz |cpio -id"); - if (! -d "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk") { + system("cd $dd_dir/mods; gunzip -c $dd_dir/mnt/modules.cgz |cpio -id"); + if (!-d "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk") { mkpath "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"; } @@ -2067,17 +2103,17 @@ sub load_dd () $driver_name = $d; $driver_name =~ s/.*\///; $real_path = ""; - find (\&get_path, <$rootimg_dir/lib/modules/$kernelver/*>); + find(\&get_path, <$rootimg_dir/lib/modules/$kernelver/*>); if ($real_path eq "") { - system ("cp $d $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); + system("cp $d $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); } else { - system ("cp $d $real_path"); + system("cp $d $real_path"); } } rmtree "$dd_dir/mods/*"; - - my $rc = system ("umount -f $dd_dir/mnt"); + + my $rc = system("umount -f $dd_dir/mnt"); if ($rc) { print "umount the directory $dd_dir/mnt failed\n"; exit 1; @@ -2086,11 +2122,12 @@ sub load_dd () # Loading the drivers from rpm packages if (@rpm_list && ($Injectalldriver || @driver_list)) { + # Extract the files from rpm to the tmp dir mkpath "$dd_dir/rpm"; foreach my $rpm (@rpm_list) { if (-r $rpm) { - if (system ("cd $dd_dir/rpm; rpm2cpio $rpm | cpio -idum")) { + if (system("cd $dd_dir/rpm; rpm2cpio $rpm | cpio -idum")) { print "Error: Cannot extract the files from the rpm $rpm.\n"; } } else { @@ -2100,13 +2137,13 @@ sub load_dd () # To skip the conflict of files that some rpm uses the xxx.ko.new as the name of the driver # Change it back to xxx.ko here - $driver_name = "\*ko.new"; + $driver_name = "\*ko.new"; @all_real_path = (); find(\&get_all_path, <$dd_dir/rpm/*>); foreach my $file (@all_real_path) { my $newname = $file; $newname =~ s/\.new$//; - if (system ("mv -f $file $newname")) { + if (system("mv -f $file $newname")) { print "Error: Could not rename $file\n"; } @@ -2114,7 +2151,7 @@ sub load_dd () # Copy the firmware to the rootimage if (-d "$dd_dir/rpm/lib/firmware") { - system ("cp -rf $dd_dir/rpm/lib/firmware $rootimg_dir/lib"); + system("cp -rf $dd_dir/rpm/lib/firmware $rootimg_dir/lib"); } # if $ignorekernelchk is specified, copy all driver files to target kernel dir @@ -2124,72 +2161,75 @@ sub load_dd () if ($path eq "$dd_dir/rpm/lib/modules/$kernelver") { next; } - + unless (-d "$dd_dir/rpm/lib/modules/$kernelver") { mkpath "$dd_dir/rpm/lib/modules/$kernelver"; } - system ("/bin/cp -rf $path/* $dd_dir/rpm/lib/modules/$kernelver"); + system("/bin/cp -rf $path/* $dd_dir/rpm/lib/modules/$kernelver"); } } # Copy the drivers to the rootimage if (-d "$dd_dir/rpm/lib/modules/$kernelver") { - if (@driver_list) { - foreach my $driver (@driver_list) { - $driver_name = $driver; - $real_path = ""; - find(\&get_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); - if ($real_path && $real_path =~ m!$dd_dir/rpm(/lib/modules/$kernelver/.*?)[^\/]*$!) { - # remove the old one if existing - @all_real_path = (); - find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); - foreach (@all_real_path) { - if (-r $_) { - unlink ($_); - } - } - - if (! -d "$rootimg_dir$1") { - mkpath "$rootimg_dir$1"; - } - system ("cp -rf $real_path $rootimg_dir$1"); - push @rpm_drivers, $driver; - } else { - print "Warning: cannot find the driver $driver from the driver rpms\n"; - } + if (@driver_list) { + foreach my $driver (@driver_list) { + $driver_name = $driver; + $real_path = ""; + find(\&get_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); + if ($real_path && $real_path =~ m!$dd_dir/rpm(/lib/modules/$kernelver/.*?)[^\/]*$!) { + + # remove the old one if existing + @all_real_path = (); + find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); + foreach (@all_real_path) { + if (-r $_) { + unlink($_); + } + } + + if (!-d "$rootimg_dir$1") { + mkpath "$rootimg_dir$1"; + } + system("cp -rf $real_path $rootimg_dir$1"); + push @rpm_drivers, $driver; + } else { + print "Warning: cannot find the driver $driver from the driver rpms\n"; + } + } + } elsif ($Injectalldriver) { + + # copy all the drviers to the rootimage + $driver_name = "\*\.ko"; + @all_real_path = (); + find(\&get_all_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); + my @all_drivers = @all_real_path; + foreach my $new_driver (@all_drivers) { + if (basename($new_driver) =~ /\.ko$/) { + + # remove the old one if existing + $driver_name = basename($new_driver); + @all_real_path = (); + find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); + foreach my $old_driver (@all_real_path) { + if (-r $old_driver) { + unlink($old_driver); + } + } + push @rpm_drivers, basename($new_driver); + } + } + + system("cp -rf $dd_dir/rpm/lib/modules/$kernelver $rootimg_dir/lib/modules/"); } - } elsif ($Injectalldriver) { - # copy all the drviers to the rootimage - $driver_name = "\*\.ko"; - @all_real_path = (); - find(\&get_all_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); - my @all_drivers = @all_real_path; - foreach my $new_driver (@all_drivers) { - if (basename($new_driver) =~ /\.ko$/) { - # remove the old one if existing - $driver_name = basename($new_driver); - @all_real_path = (); - find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); - foreach my $old_driver (@all_real_path) { - if (-r $old_driver) { - unlink ($old_driver); - } - } - push @rpm_drivers, basename($new_driver); - } - } - - system ("cp -rf $dd_dir/rpm/lib/modules/$kernelver $rootimg_dir/lib/modules/"); - } } else { - print "Warning: cannot find the kernel $kernelver from drvier rpms\n"; + print "Warning: cannot find the kernel $kernelver from drvier rpms\n"; } push @dd_drivers, @rpm_drivers; } # Generate the dependency relationship - system ("chroot '$rootimg_dir' depmod $kernelver"); + system("chroot '$rootimg_dir' depmod $kernelver"); # Clean the env rmtree "$dd_dir"; @@ -2198,22 +2238,22 @@ sub load_dd () } sub use_devnull { - if ( -e "$rootimg_dir/dev/null" and ! -c "$rootimg_dir/dev/null" ) { + if (-e "$rootimg_dir/dev/null" and !-c "$rootimg_dir/dev/null") { system("rm -f $rootimg_dir/dev/null"); } - if (! -e "$rootimg_dir/dev/null") { + if (!-e "$rootimg_dir/dev/null") { system("mknod $rootimg_dir/dev/null c 1 3"); } } #To hack the uname, same function with the one in ubuntu genimage sub use_hackuname { - unless ( -e "$rootimg_dir/bin/uname-binary") { - if ( -e -x "$rootimg_dir/bin/uname" ) { + unless (-e "$rootimg_dir/bin/uname-binary") { + if (-e -x "$rootimg_dir/bin/uname") { move("$rootimg_dir/bin/uname", "$rootimg_dir/bin/uname-binary"); } } - + my $unamefile; open($unamefile, ">", "$rootimg_dir/bin/uname"); print $unamefile < ] [ -n ] [-r ] -o -p -k [--permission ] [--interactive]'."\n"; - print " --permission only works with statelite mode\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute \n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot --permission 777\n"; + print 'Usage: genimage [ -i ] [ -n ] [-r ] -o -p -k [--permission ] [--interactive]' . "\n"; + print " --permission only works with statelite mode\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute \n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot --permission 777\n"; return 0; } diff --git a/xCAT-server/share/xcat/netboot/rh/genimage.rh4 b/xCAT-server/share/xcat/netboot/rh/genimage.rh4 index adcca5cba..7eb1d05fa 100755 --- a/xCAT-server/share/xcat/netboot/rh/genimage.rh4 +++ b/xCAT-server/share/xcat/netboot/rh/genimage.rh4 @@ -11,12 +11,13 @@ use File::Copy; use File::Find; use Getopt::Long; use Cwd qw(realpath); + #use strict; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -24,19 +25,20 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -47,89 +49,90 @@ my $otherpkglist; my $postinstall_filename; my $rootimg_dir; my $mode; -my $permission; # the permission works only for statelite mode currently +my $permission; # the permission works only for statelite mode currently sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'm=s' => \$mode, - 'permission=s' => \$permission + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'm=s' => \$mode, + 'permission=s' => \$permission ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; if ($arch or $osver or $profile) { - print "-o, -p and -a options are not allowed when a image name is specified.\n"; + print "-o, -p and -a options are not allowed when a image name is specified.\n"; exit 1; } + #load the module in memory - eval {require("$::XCATROOT/lib/perl/xCAT/Table.pm")}; + eval { require("$::XCATROOT/lib/perl/xCAT/Table.pm") }; if ($@) { - print $@; - exit 1; - } - - #get the info from the osimage and linux - my $osimagetab=xCAT::Table->new('osimage', -create=>1); - if (!$osimagetab) { - print "The osimage table cannot be opened.\n"; - exit 1; - } - my $linuximagetab=xCAT::Table->new('linuximage', -create=>1); - if (!$linuximagetab) { - print "The linuximage table cannot be opened.\n"; - exit 1; - } - (my $ref) = $osimagetab->getAttribs({imagename => $imagename}, 'osvers', 'osarch', 'profile', 'provmethod'); - if (!$ref) { - print "Cannot find image \'$imagename\' from the osimage table.\n"; - exit 1; - } - (my $ref1) = $linuximagetab->getAttribs({imagename => $imagename}, 'pkglist', 'pkgdir', 'otherpkglist', 'otherpkgdir', 'postinstall', 'rootimgdir'); - if (!$ref1) { - print "Cannot find $imagename from the linuximage table\n"; - exit 1; + print $@; + exit 1; } - $osver=$ref->{'osvers'}; - $arch=$ref->{'osarch'}; - $profile=$ref->{'profile'}; - my $provmethod=$ref->{'provmethod'}; - + #get the info from the osimage and linux + my $osimagetab = xCAT::Table->new('osimage', -create => 1); + if (!$osimagetab) { + print "The osimage table cannot be opened.\n"; + exit 1; + } + my $linuximagetab = xCAT::Table->new('linuximage', -create => 1); + if (!$linuximagetab) { + print "The linuximage table cannot be opened.\n"; + exit 1; + } + (my $ref) = $osimagetab->getAttribs({ imagename => $imagename }, 'osvers', 'osarch', 'profile', 'provmethod'); + if (!$ref) { + print "Cannot find image \'$imagename\' from the osimage table.\n"; + exit 1; + } + (my $ref1) = $linuximagetab->getAttribs({ imagename => $imagename }, 'pkglist', 'pkgdir', 'otherpkglist', 'otherpkgdir', 'postinstall', 'rootimgdir'); + if (!$ref1) { + print "Cannot find $imagename from the linuximage table\n"; + exit 1; + } + + $osver = $ref->{'osvers'}; + $arch = $ref->{'osarch'}; + $profile = $ref->{'profile'}; + my $provmethod = $ref->{'provmethod'}; + unless ($osver and $arch and $profile and $provmethod) { - print"osimage.osvers, osimage.osarch, osimage.profile and osimage.provmethod must be specified for the image $imagename in the database.\n"; - exit 1; + print "osimage.osvers, osimage.osarch, osimage.profile and osimage.provmethod must be specified for the image $imagename in the database.\n"; + exit 1; } if ($provmethod ne 'netboot') { - print "\'$imagename\' cannot be used to build diskless image. Make sure osimage.provmethod is 'netboot'."; - exit 1; + print "\'$imagename\' cannot be used to build diskless image. Make sure osimage.provmethod is 'netboot'."; + exit 1; } - if (! $ref1->{'pkglist'}) { - print"A .pkglist file must be specified for image \'$imagename\' in the linuximage table.\n"; + if (!$ref1->{'pkglist'}) { + print "A .pkglist file must be specified for image \'$imagename\' in the linuximage table.\n"; exit 0; } - $pkglist =$ref1->{'pkglist'}; + $pkglist = $ref1->{'pkglist'}; - $srcdir=$ref1->{'pkgdir'}; - $srcdir_otherpkgs=$ref1->{'otherpkgdir'}; - $otherpkglist=$ref1->{'otherpkglist'}; - $postinstall_filename=$ref1->{'postinstall'}; - $destdir=$ref1->{'rootimgdir'}; + $srcdir = $ref1->{'pkgdir'}; + $srcdir_otherpkgs = $ref1->{'otherpkgdir'}; + $otherpkglist = $ref1->{'otherpkglist'}; + $postinstall_filename = $ref1->{'postinstall'}; + $destdir = $ref1->{'rootimgdir'}; } if ($mode eq "statelite") { @@ -142,229 +145,236 @@ if (!$arch) { $arch = `uname -m`; chomp($arch); if ($arch =~ /i.86$/) { - $arch = "x86"; + $arch = "x86"; } } -if (!$srcdir) { - $srcdir="$installroot/$osver/$arch"; +if (!$srcdir) { + $srcdir = "$installroot/$osver/$arch"; } -if (!$srcdir_otherpkgs) { +if (!$srcdir_otherpkgs) { $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch"; } if (!$destdir) { - $destdir="$installroot/netboot/$osver/$arch/$profile"; + $destdir = "$installroot/netboot/$osver/$arch/$profile"; } -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; unless ($osver and $profile and $netdriver and $prinic) { - print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]]'."\n"; - print ' genimage -i -n [-r ] -k '."\n"; - print " --permission only works when '-m statelite' is set\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; - print " genimage -i eth0 -n tg3 myimage\n"; - exit 1; + print 'Usage: genimage -i -n [-r ] -o -p -k [-m [--permission ]]' . "\n"; + print ' genimage -i -n [-r ] -k ' . "\n"; + print " --permission only works when '-m statelite' is set\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot -m statelite --permission 777\n"; + print " genimage -i eth0 -n tg3 myimage\n"; + exit 1; } my @ndrivers; -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - if (/^$/) { - next; - } - push @ndrivers,$_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + if (/^$/) { + next; + } + push @ndrivers, $_; } -if($mode eq "statelite"){ - push @ndrivers,"fscache.ko"; - push @ndrivers,"sunrpc.ko"; - push @ndrivers,"lockd.ko"; - push @ndrivers,"nfs_acl.ko"; - push @ndrivers,"nfs.ko"; +if ($mode eq "statelite") { + push @ndrivers, "fscache.ko"; + push @ndrivers, "sunrpc.ko"; + push @ndrivers, "lockd.ko"; + push @ndrivers, "nfs_acl.ko"; + push @ndrivers, "nfs.ko"; } unless ($onlyinitrd) { - @yumdirs=(); - find(\&isyumdir, <$installroot/$osver/$arch/>); - unless (scalar(@yumdirs)) { - #unless ( -d $srcdir."/repodata" ) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + @yumdirs = (); + find(\&isyumdir, <$installroot/$osver/$arch/>); + unless (scalar(@yumdirs)) { - my $yumconfig; - open($yumconfig,">","/tmp/genimage.$$.yum.conf"); - my $repnum=0; - foreach $srcdir (@yumdirs) { - print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; - $repnum += 1; - } - $repnum-=1; - close($yumconfig); - mkpath "$rootimg_dir/etc"; - mkpath "$rootimg_dir/dev"; - if( ! -e "$rootimg_dir/dev/zero") { - system "mknod $rootimg_dir/dev/zero c 1 5"; - } - if( ! -e "$rootimg_dir/dev/null") { - system "mknod $rootimg_dir/dev/null c 1 3"; #that's neccessary for SLES11 - } + #unless ( -d $srcdir."/repodata" ) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } - my $fd; - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); - my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - - $yumcmd .= "install "; - mkpath("$rootimg_dir/var/lib/yum"); + my $yumconfig; + open($yumconfig, ">", "/tmp/genimage.$$.yum.conf"); + my $repnum = 0; + foreach $srcdir (@yumdirs) { + print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; + $repnum += 1; + } + $repnum -= 1; + close($yumconfig); + mkpath "$rootimg_dir/etc"; + mkpath "$rootimg_dir/dev"; + if (!-e "$rootimg_dir/dev/zero") { + system "mknod $rootimg_dir/dev/zero c 1 5"; + } + if (!-e "$rootimg_dir/dev/null") { + system "mknod $rootimg_dir/dev/null c 1 3"; #that's neccessary for SLES11 + } - if (!$imagename) { - $pkglist= get_profile_def_filename($customdir, "pkglist"); - if (!$pkglist) { - $pkglist= get_profile_def_filename($pathtofiles, "pkglist"); - } - } + my $fd; + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); + my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } - if (!$pkglist) { - print "Unable to find package list for $profile!"; - exit 1; - } + $yumcmd .= "install "; + mkpath("$rootimg_dir/var/lib/yum"); - my %pkg_hash=get_package_names($pkglist); - my $index=1; - my $pass; - foreach $pass (sort (keys(%pkg_hash))) { - my $pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - my $pa=$pkg_hash{$pass}{$_}; - $pkgnames .= " " . join(' ', @$pa); - } - - print "$yumcmd $pkgnames\n"; - my $rc = system("$yumcmd $pkgnames"); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - } - - #Now let's handle extra packages if (!$imagename) { - $otherpkglist=get_profile_def_filename($customdir, "otherpkgs.pkglist"); - if (!$otherpkglist) { $otherpkglist=get_profile_def_filename($pathtofiles, "otherpkgs.pkglist"); } + $pkglist = get_profile_def_filename($customdir, "pkglist"); + if (!$pkglist) { + $pkglist = get_profile_def_filename($pathtofiles, "pkglist"); + } } - my %extra_hash=(); + + if (!$pkglist) { + print "Unable to find package list for $profile!"; + exit 1; + } + + my %pkg_hash = get_package_names($pkglist); + my $index = 1; + my $pass; + foreach $pass (sort (keys(%pkg_hash))) { + my $pkgnames = ""; + foreach (keys(%{ $pkg_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + my $pa = $pkg_hash{$pass}{$_}; + $pkgnames .= " " . join(' ', @$pa); + } + + print "$yumcmd $pkgnames\n"; + my $rc = system("$yumcmd $pkgnames"); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + } + + #Now let's handle extra packages + if (!$imagename) { + $otherpkglist = get_profile_def_filename($customdir, "otherpkgs.pkglist"); + if (!$otherpkglist) { $otherpkglist = get_profile_def_filename($pathtofiles, "otherpkgs.pkglist"); } + } + my %extra_hash = (); if ($otherpkglist) { - %extra_hash=get_package_names($otherpkglist); + %extra_hash = get_package_names($otherpkglist); } - my %extrapkgnames; + my %extrapkgnames; if (keys(%extra_hash) > 0) { - open($yumconfig,">>","/tmp/genimage.$$.yum.conf"); - my $index=1; - foreach $pass (sort (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; - $index++; - my $pa=$extra_hash{$pass}{$_}; - $extrapkgnames{$pass} .= " " . join(' ', @$pa); + open($yumconfig, ">>", "/tmp/genimage.$$.yum.conf"); + my $index = 1; + foreach $pass (sort (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + print $yumconfig "[otherpkgs$index]\nname=otherpkgs$index\nbaseurl=file://$srcdir_otherpkgs/$_\ngpgpcheck=0\n\n"; + $index++; + my $pa = $extra_hash{$pass}{$_}; + $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } + } + close($yumconfig); + $index--; + $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; + foreach (0 .. $repnum) { + $yumcmd .= "--enablerepo=$osver-$arch-$_ "; + } + for (1 .. $index) { + $yumcmd .= "--enablerepo=otherpkgs$_ "; } - } - close($yumconfig); - $index--; - $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir/ --disablerepo=* "; - foreach (0..$repnum) { - $yumcmd .= "--enablerepo=$osver-$arch-$_ "; - } - for (1..$index) { - $yumcmd .= "--enablerepo=otherpkgs$_ "; - } - foreach $pass (sort (keys(%extra_hash))) { - #remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "$yumcmd erase "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } + foreach $pass (sort (keys(%extra_hash))) { + + #remove the packages that are specified in the otherpkgs.list files with leading '-' + my $yumcmd_remove = "$yumcmd erase "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } - #install extra packages - my $yumcmd_base = $yumcmd; - $yumcmd .= "install "; - #append extra pkg names to yum command - if ($extrapkgnames{$pass}) { - $yumcmd .= " $extrapkgnames{$pass} "; - } - $yumcmd =~ s/ $/\n/; - - #debug - print "yumcmd=$yumcmd\n"; - #my $repo=`cat /tmp/genimage.$$.yum.conf`; - #print "repo=$repo"; - - my $rc = system($yumcmd); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } - - #remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$yumcmd_remove $rm_packges\n"; - $rc = system("$yumcmd_remove $rm_packges"); - } - } - } - } + #install extra packages + my $yumcmd_base = $yumcmd; + $yumcmd .= "install "; - # run yum update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update = $yumcmd_base . " update "; - $rc = system("$yumcmd_update"); - # ignore any return code + #append extra pkg names to yum command + if ($extrapkgnames{$pass}) { + $yumcmd .= " $extrapkgnames{$pass} "; + } + $yumcmd =~ s/ $/\n/; + + #debug + print "yumcmd=$yumcmd\n"; + + #my $repo=`cat /tmp/genimage.$$.yum.conf`; + #print "repo=$repo"; + + my $rc = system($yumcmd); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + + #remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$yumcmd_remove $rm_packges\n"; + $rc = system("$yumcmd_remove $rm_packges"); + } + } + } + } + + # run yum update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update = $yumcmd_base . " update "; + $rc = system("$yumcmd_update"); + + # ignore any return code - postscripts(); #run 'postscripts' + postscripts(); #run 'postscripts' } + #Default to the first kernel found in the install image if nothing specified explicitly. #A more accurate guess than whatever the image build server happens to be running #If specified, that takes precedence. #if image has one, that is used #if all else fails, resort to uname -r like this script did before -my @KVERS= <$rootimg_dir/boot/vmlinuz-*>; +my @KVERS = <$rootimg_dir/boot/vmlinuz-*>; foreach (@KVERS) { - s/vmlinuz-//; + s/vmlinuz-//; } unless (scalar(@KVERS)) { - @KVERS= <$rootimg_dir/lib/modules/*>; + @KVERS = <$rootimg_dir/lib/modules/*>; } if (scalar(@KVERS)) { -# it doesn't works for RH4.x, at least for 4.8 + + # it doesn't works for RH4.x, at least for 4.8 #$basekernelver = basename(pop @KVERS); $basekernelver = basename(shift @KVERS); } @@ -372,26 +382,26 @@ unless ($basekernelver) { $basekernelver = `uname -r`; } unless ($kernelver) { - $kernelver=$basekernelver; + $kernelver = $basekernelver; } chomp($kernelver); -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); print "Added $dep as an autodetected depedency\n"; } } @@ -402,15 +412,15 @@ unlink "/tmp/genimage.$$.yum.conf"; #-- run postinstall script if (!$imagename) { - $postinstall_filename= get_profile_def_filename($customdir, "postinstall"); + $postinstall_filename = get_profile_def_filename($customdir, "postinstall"); if (!$postinstall_filename) { - $postinstall_filename= get_profile_def_filename($pathtofiles, "postinstall"); + $postinstall_filename = get_profile_def_filename($pathtofiles, "postinstall"); } -} +} if (($postinstall_filename) && (-x $postinstall_filename)) { - my $rc = system($postinstall_filename, $rootimg_dir,$osver,$arch,$profile); - if($rc) { + my $rc = system($postinstall_filename, $rootimg_dir, $osver, $arch, $profile); + if ($rc) { print "postinstall script failed\n"; exit 1; } @@ -419,92 +429,93 @@ if (($postinstall_filename) && (-x $postinstall_filename)) { # statelite .statelite directory added here. # this is where tmpfs will be created. -if($mode eq "statelite"){ - mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. - # this script will get the directories. - unless(-f "../add-on/statelite/rc.statelite"){ - print "Can't find ../add-on/statelite/rc.statelite!\n"; - exit; - } - system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - # also need to add this file: - # may have already been made into a symbolic link, if so ignore it +if ($mode eq "statelite") { + mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. + # this script will get the directories. + unless (-f "../add-on/statelite/rc.statelite") { + print "Can't find ../add-on/statelite/rc.statelite!\n"; + exit; + } + system("cp ../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); - unless(-l "$rootimg_dir/var/lib/dhclient" ){ - mkpath "$rootimg_dir/var/lib/dhclient/"; - system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); - } + # also need to add this file: + # may have already been made into a symbolic link, if so ignore it - unless(-l "$rootimg_dir/var/lib/dhcp" ){ - mkpath "$rootimg_dir/var/lib/dhcp/"; - system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); - } -} + unless (-l "$rootimg_dir/var/lib/dhclient") { + mkpath "$rootimg_dir/var/lib/dhclient/"; + system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); + } + + unless (-l "$rootimg_dir/var/lib/dhcp") { + mkpath "$rootimg_dir/var/lib/dhcp/"; + system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); + } +} mkinitrd(); sub getlibs { - my $file = shift; - my $liblist = `chroot $rootimg_dir ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - next; - } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } - $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + my $file = shift; + my $liblist = `chroot $rootimg_dir ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + unless (/=>/) { + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; + } + $temp1 =~ s/^\///; + $libhash{$temp1} = 1; + } } sub mkinitrd { - mkpath("/tmp/xcatinitrd.$$/bin"); - if($basekernelver eq $kernelver) { - rename(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); - } - else { - if(-r "$rootimg_dir/boot/vmlinuz-$kernelver") { - copy("$rootimg_dir/boot/vmlinuz-$kernelver","$destdir/kernel"); - } elsif(-r "/boot/vmlinuz-$kernelver") { - copy("/boot/vmlinuz-$kernelver","$destdir/kernel"); - } - else { - xdie("Cannot read /boot/vmlinuz-$kernelver"); - } - } - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); + mkpath("/tmp/xcatinitrd.$$/bin"); + if ($basekernelver eq $kernelver) { + rename(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); + } + else { + if (-r "$rootimg_dir/boot/vmlinuz-$kernelver") { + copy("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } elsif (-r "/boot/vmlinuz-$kernelver") { + copy("/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } + else { + xdie("Cannot read /boot/vmlinuz-$kernelver"); + } + } + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/bin"); + mkpath("/tmp/xcatinitrd.$$/usr/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/lib"); + mkpath("/tmp/xcatinitrd.$$/usr/lib64"); + mkpath("/tmp/xcatinitrd.$$/lib/firmware"); + mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); + mkpath("/tmp/xcatinitrd.$$/proc"); + mkpath("/tmp/xcatinitrd.$$/sys"); + mkpath("/tmp/xcatinitrd.$$/dev/mapper"); + mkpath("/tmp/xcatinitrd.$$/sysroot"); + mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); + mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); mkpath("/tmp/xcatinitrd.$$/var/lib/dhcp/"); - my $inifile; + my $inifile; -# start writing to the init script. - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/bin/bash\n"; + # start writing to the init script. + open($inifile, ">", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/bin/bash\n"; print $inifile "ln -sf /bin/bash /bin/sh\n"; -# add some functions - print $inifile < /dev/null && export DEBUG=1 @@ -859,29 +871,29 @@ elif [ -r /rootimg.sfs ]; then mount --move /ro /sysroot/ro mount --move /rw /sysroot/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile "echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o size=$rootlimit -t tmpfs rootfs /sysroot\n"; - } else { - print $inifile " mount -t tmpfs rootfs /sysroot\n"; - } - print $inifile " cd /sysroot\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " zcat /rootimg.gz |/bin/cpio -idum\n"; - print $inifile " else\n"; - print $inifile " zcat /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 1\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " echo\n"; - print $inifile </dev/console 2>&1\n"; - #print $inifile "exec /sbin/switch_root -c /dev/console /sysroot /sbin/init\n"; - close($inifile); + print $inifile " exit\n"; + print $inifile "fi\n"; + print $inifile "cd /\n"; + print $inifile "shell\n"; + print $inifile "cp /var/lib/dhcp/dhclient.leases /sysroot/dev/.dhclient-$prinic.leases\n"; + print $inifile "cp /var/lib/dhcp/dhclient.leases /sysroot/var/lib/dhcp/dhclient-$prinic.leases\n"; + print $inifile "mknod /sysroot/dev/console c 5 1\n"; + print $inifile "mknod /dev/initctl p;\n"; -chmod(0755,"/tmp/xcatinitrd.$$/init"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } + #print $inifile "chmod 600 /dev/initctl\n"; + print $inifile "mount -n --bind /dev /sysroot/dev\n"; + + #print $inifile "/bin/bash\n"; + print $inifile "umount /sys\n"; + print $inifile "umount /proc\n"; + print $inifile "cd /sysroot; mount --move . /;\n"; + print $inifile "exec /usr/sbin/chroot . /sbin/init 3 /dev/console 2>&1\n"; + + #print $inifile "exec /sbin/switch_root -c /dev/console /sysroot /sbin/init\n"; + close($inifile); + + chmod(0755, "/tmp/xcatinitrd.$$/init"); + @filestoadd = (); + foreach (@ndrivers) { + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } + } my @binlists = ( "bin/hostname", @@ -932,7 +947,7 @@ chmod(0755,"/tmp/xcatinitrd.$$/init"); "sbin/dhclient", "sbin/dhclient-script", "sbin/ifconfig", - "usr/bin/clear", + "usr/bin/clear", "usr/bin/test", "bin/grep", "bin/echo", @@ -969,324 +984,331 @@ chmod(0755,"/tmp/xcatinitrd.$$/init"); "bin/ln", "bin/chmod", "usr/bin/wc", - "bin/uname" # hostname will use it + "bin/uname" # hostname will use it ); - # add rsync for statelite - #foreach ("bin/cpio","sbin/nash","sbin/busybox.anaconda","sbin/rmmod","sbin/mount.nfs","/usr/bin/rsync") { + # add rsync for statelite + #foreach ("bin/cpio","sbin/nash","sbin/busybox.anaconda","sbin/rmmod","sbin/mount.nfs","/usr/bin/rsync") { foreach (@binlists) { - getlibs($_); - push @filestoadd,$_; - } - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libresolv.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - if($basekernelver ne $kernelver) { - system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); + getlibs($_); + push @filestoadd, $_; + } + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libresolv.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; + if ($basekernelver ne $kernelver) { + system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); unless (-d "$rootimg_dir/lib/modules/$kernelver") { - if(-d "/lib/modules/$kernelver") { - system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); - } - else { - xdie("Cannot read /lib/modules/$kernelver"); - } + if (-d "/lib/modules/$kernelver") { + system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); + } + else { + xdie("Cannot read /lib/modules/$kernelver"); + } } - } - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + } + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$rootimg_dir/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$rootimg_dir/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + foreach (@filestoadd) { + if (ref($_)) { + + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$rootimg_dir/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$rootimg_dir/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } # copy bash to sh system("cd /tmp/xcatinitrd.$$/bin; cp bash sh;"); - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + } + } } - -sub postscripts { # TODO: customized postscripts - generic_post(); - if($mode eq "statelite") { - unless(-d "$rootimg_dir/opt/xcat/") { + +sub postscripts { # TODO: customized postscripts + generic_post(); + if ($mode eq "statelite") { + unless (-d "$rootimg_dir/opt/xcat/") { mkdir "$rootimg_dir/opt/xcat/"; } copy("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; system("$XCATROOT/share/xcat/netboot/add-on/statelite/add_passwd $rootimg_dir"); system("$XCATROOT/share/xcat/netboot/add-on/statelite/add_ssh $rootimg_dir"); - } - if (-d "$installroot/postscripts/hostkeys") { - for my $key (<$installroot/postscripts/hostkeys/*key>) { - copy ($key,"$rootimg_dir/etc/ssh/"); - } - chmod 0600,; - } - if (-d "/$installroot/postscripts/.ssh") { - mkpath("/$rootimg_dir/root/.ssh"); - chmod(0700,"/$rootimg_dir/root/.ssh/"); - for my $file () { - copy ($file,"/$rootimg_dir/root/.ssh/"); - } - chmod(0600,); - } + } + if (-d "$installroot/postscripts/hostkeys") { + for my $key (<$installroot/postscripts/hostkeys/*key>) { + copy($key, "$rootimg_dir/etc/ssh/"); + } + chmod 0600, ; + } + if (-d "/$installroot/postscripts/.ssh") { + mkpath("/$rootimg_dir/root/.ssh"); + chmod(0700, "/$rootimg_dir/root/.ssh/"); + for my $file () { + copy($file, "/$rootimg_dir/root/.ssh/"); + } + chmod(0600, ); + } } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "none / tmpfs defaults 0 0\n"; - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; - } - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - unless ( -r <$rootimg_dir/etc/rc3.d/S??network>) { - symlink "/etc/init.d/network","$rootimg_dir/etc/rc3.d/S10network"; - } - open($cfgfile,">","$rootimg_dir/etc/rc3.d/S60gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style - print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; - print $cfgfile " else\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - chmod(0755,"$rootimg_dir/etc/rc3.d/S60gettyset"); - #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "none / tmpfs defaults 0 0\n"; + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; + } + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + unless (-r <$rootimg_dir/etc/rc3.d/S??network>) { + symlink "/etc/init.d/network", "$rootimg_dir/etc/rc3.d/S10network"; + } + open($cfgfile, ">", "$rootimg_dir/etc/rc3.d/S60gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " if [ -x /sbin/initctl ]; then\n"; #Upstart style + print $cfgfile " initctl emit --no-wait fedora.serial-console-available \$COTTY \$COSPEED\n"; + print $cfgfile " else\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + chmod(0755, "$rootimg_dir/etc/rc3.d/S60gettyset"); + + #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); #add postscript support for redhat - if($mode eq "statelite") { + if ($mode eq "statelite") { print $cfgfile "/opt/xcat/xcatdsklspost 4\n"; - } else { + } else { print $cfgfile "/opt/xcat/xcatdsklspost\n"; - } - close($cfgfile); - - rename(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); -} + } + close($cfgfile); + + rename(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); +} sub get_package_names { - my $plist_file_name=shift; - my %pkgnames=(); - my @tmp_array=(); + my $plist_file_name = shift; + my %pkgnames = (); + my @tmp_array = (); - if ($plist_file_name) { - my $pkgfile; - open($pkgfile,"<","$plist_file_name"); - while (<$pkgfile>) { - chomp; - s/\s+$//; #remove trailing white spaces - next if /^\s*$/; #-- skip empty lines - push(@tmp_array,$_); - } - close($pkgfile); + if ($plist_file_name) { + my $pkgfile; + open($pkgfile, "<", "$plist_file_name"); + while (<$pkgfile>) { + chomp; + s/\s+$//; #remove trailing white spaces + next if /^\s*$/; #-- skip empty lines + push(@tmp_array, $_); + } + close($pkgfile); - if ( @tmp_array > 0) { - my $pkgtext=join(',',@tmp_array); - - #handle the #INLCUDE# tag recursively - my $idir = dirname($plist_file_name); - my $doneincludes=0; - while (not $doneincludes) { - $doneincludes=1; - if ($pkgtext =~ /#INCLUDE:[^#]+#/) { - $doneincludes=0; - $pkgtext =~ s/#INCLUDE:([^#]+)#/include_file($1,$idir)/eg; - } - } - - #print "pkgtext=$pkgtext\n"; - my @tmp=split(',', $pkgtext); - my $pass=1; - foreach (@tmp) { - my $idir; - if (/^--/) { - $idir="POST_REMOVE"; #line starts with -- means the package should be removed after otherpkgs are installed - s/^--//; - } elsif (/^-/) { - $idir="PRE_REMOVE"; #line starts with single - means the package should be removed before otherpkgs are installed - s/^-//; - } elsif (/^#NEW_INSTALL_LIST#/) { - $pass++; - next; - } elsif (/^#/) { - # ignore all other comment lines - next; - } else { - $idir=dirname($_); - } - my $fn=basename($_); - if (exists($pkgnames{$pass}{$idir})) { - my $pa=$pkgnames{$pass}{$idir}; - push(@$pa, $fn); - } else { - $pkgnames{$pass}{$idir}=[$fn]; - } - } - } - } + if (@tmp_array > 0) { + my $pkgtext = join(',', @tmp_array); - return %pkgnames; + #handle the #INLCUDE# tag recursively + my $idir = dirname($plist_file_name); + my $doneincludes = 0; + while (not $doneincludes) { + $doneincludes = 1; + if ($pkgtext =~ /#INCLUDE:[^#]+#/) { + $doneincludes = 0; + $pkgtext =~ s/#INCLUDE:([^#]+)#/include_file($1,$idir)/eg; + } + } + + #print "pkgtext=$pkgtext\n"; + my @tmp = split(',', $pkgtext); + my $pass = 1; + foreach (@tmp) { + my $idir; + if (/^--/) { + $idir = "POST_REMOVE"; #line starts with -- means the package should be removed after otherpkgs are installed + s/^--//; + } elsif (/^-/) { + $idir = "PRE_REMOVE"; #line starts with single - means the package should be removed before otherpkgs are installed + s/^-//; + } elsif (/^#NEW_INSTALL_LIST#/) { + $pass++; + next; + } elsif (/^#/) { + + # ignore all other comment lines + next; + } else { + $idir = dirname($_); + } + my $fn = basename($_); + if (exists($pkgnames{$pass}{$idir})) { + my $pa = $pkgnames{$pass}{$idir}; + push(@$pa, $fn); + } else { + $pkgnames{$pass}{$idir} = [$fn]; + } + } + } + } + + return %pkgnames; } sub include_file { - my $file = shift; - my $idir = shift; - my @text = (); - unless ($file =~ /^\//) { - $file = $idir."/".$file; - } - - open(INCLUDE,$file) || \ - return "#INCLUDEBAD:cannot open $file#"; - - while() { - chomp($_); - s/\s+$//; #remove trailing spaces - next if /^\s*$/; #-- skip empty lines - push(@text, $_); - } - - close(INCLUDE); - - return join(',', @text); + my $file = shift; + my $idir = shift; + my @text = (); + unless ($file =~ /^\//) { + $file = $idir . "/" . $file; + } + + open(INCLUDE, $file) || \ + return "#INCLUDEBAD:cannot open $file#"; + + while () { + chomp($_); + s/\s+$//; #remove trailing spaces + next if /^\s*$/; #-- skip empty lines + push(@text, $_); + } + + close(INCLUDE); + + return join(',', @text); } sub get_profile_def_filename { - my $base=shift; - my $ext=shift; - my $dotpos = rindex($osver, "."); - my $osbase = substr($osver, 0, $dotpos); - if (-r "$base/$profile.$osver.$arch.$ext") { - return "$base/$profile.$osver.$arch.$ext"; - } elsif (-r "$base/$profile.$osbase.$arch.$ext") { - return "$base/$profile.$osbase.$arch.$ext"; - } elsif (-r "$base/$profile.$arch.$ext") { - return "$base/$profile.$arch.$ext"; - } elsif (-r "$base/$profile.$osver.$ext") { - return "$base/$profile.$osver.$ext"; - } elsif (-r "$base/$profile.$osbase.$ext") { - return "$base/$profile.$osbase.$ext"; - } elsif (-r "$base/$profile.$ext") { - return "$base/$profile.$ext"; - } + my $base = shift; + my $ext = shift; + my $dotpos = rindex($osver, "."); + my $osbase = substr($osver, 0, $dotpos); + if (-r "$base/$profile.$osver.$arch.$ext") { + return "$base/$profile.$osver.$arch.$ext"; + } elsif (-r "$base/$profile.$osbase.$arch.$ext") { + return "$base/$profile.$osbase.$arch.$ext"; + } elsif (-r "$base/$profile.$arch.$ext") { + return "$base/$profile.$arch.$ext"; + } elsif (-r "$base/$profile.$osver.$ext") { + return "$base/$profile.$osver.$ext"; + } elsif (-r "$base/$profile.$osbase.$ext") { + return "$base/$profile.$osbase.$ext"; + } elsif (-r "$base/$profile.$ext") { + return "$base/$profile.$ext"; + } - return ""; + return ""; } - + diff --git a/xCAT-server/share/xcat/netboot/sles/genimage b/xCAT-server/share/xcat/netboot/sles/genimage index 64e628aae..ebc09e3de 100755 --- a/xCAT-server/share/xcat/netboot/sles/genimage +++ b/xCAT-server/share/xcat/netboot/sles/genimage @@ -21,11 +21,11 @@ use imgutils; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $dracutmode; #Indicate whether this is a dracut style initrd -my $dracutdir = "dracut"; # The default directory name of dracut +my $dracutmode; #Indicate whether this is a dracut style initrd +my $dracutdir = "dracut"; # The default directory name of dracut my $dracutver; -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -33,21 +33,22 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + #that this method of calling genimage is no longer used if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; my $kerneldir; -my $kernelver = ""; -my $basekernelver; -my $customdir=$fullpath; +my $kernelver = ""; +my $basekernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -58,17 +59,17 @@ my $otherpkglist; my $postinstall_filename; my $rootimg_dir; my $mode; -my $permission; #the permission works only for statelite mode currently +my $permission; #the permission works only for statelite mode currently my $krpmver; my $tempfile; my $prompt; -my $timezone; #the TIMEZONE of the stateless and statelite node +my $timezone; #the TIMEZONE of the stateless and statelite node my $ignorekernelchk; my $noupdate; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } #-- fetch current version form CVS (overwrite locally changed versions) @@ -88,40 +89,40 @@ sub xdie { $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'g=s' => \$krpmver, - 'permission=s' => \$permission, - 'kerneldir=s' => \$kerneldir, - 'timezone=s' => \$timezone, - 'tempfile=s' =>\$tempfile, #internal flag - 'pkglist=s' => \$pkglist, #internal flag - 'srcdir=s' => \$srcdir, #internal flag - 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag - 'otherpkglist=s' => \$otherpkglist, #internal flag - 'postinstall=s' => \$postinstall_filename, #internal flag - 'rootimgdir=s' => \$destdir, #internal flag - 'driverupdatesrc=s' => \$driverupdatesrc, #internal flag - 'interactive' =>\$prompt, - 'onlyinitrd' =>\$onlyinitrd, - 'ignorekernelchk' => \$ignorekernelchk, - 'noupdate' => \$noupdate, - ); + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'g=s' => \$krpmver, + 'permission=s' => \$permission, + 'kerneldir=s' => \$kerneldir, + 'timezone=s' => \$timezone, + 'tempfile=s' => \$tempfile, #internal flag + 'pkglist=s' => \$pkglist, #internal flag + 'srcdir=s' => \$srcdir, #internal flag + 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag + 'otherpkglist=s' => \$otherpkglist, #internal flag + 'postinstall=s' => \$postinstall_filename, #internal flag + 'rootimgdir=s' => \$destdir, #internal flag + 'driverupdatesrc=s' => \$driverupdatesrc, #internal flag + 'interactive' => \$prompt, + 'onlyinitrd' => \$onlyinitrd, + 'ignorekernelchk' => \$ignorekernelchk, + 'noupdate' => \$noupdate, +); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } my %updates_os = (); # the hash for updating osimage table -my %updates = (); # the hash for updating linuximage table +my %updates = (); # the hash for updating linuximage table $permission = "755" unless ($permission); @@ -133,23 +134,25 @@ unless ($arch) { $arch = "x86" if ($arch =~ /i.86$/); } -$srcdir="$installroot/$osver/$arch" unless ($srcdir); +$srcdir = "$installroot/$osver/$arch" unless ($srcdir); $updates{'pkgdir'} = $srcdir if ($tempfile); + #$srcdir = $srcdir . "/1"; -$srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch" unless ($srcdir_otherpkgs); +$srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch" unless ($srcdir_otherpkgs); $updates{'otherpkgdir'} = $srcdir_otherpkgs if ($tempfile); -$destdir="$installroot/netboot/$osver/$arch/$profile" unless ($destdir); +$destdir = "$installroot/netboot/$osver/$arch/$profile" unless ($destdir); $updates{'rootimgdir'} = $destdir if ($tempfile); -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; if ($kernelver && (!$krpmver)) { print "The -g flag for the rpm version of kernel packages needs to be specified when kernel version has been specified.\n"; exit 1; } -$kerneldir = "$installroot/kernels" unless ($kerneldir); # the default directory for 3rd-party kernel is "$installroot/kernels"; +$kerneldir = "$installroot/kernels" unless ($kerneldir); # the default directory for 3rd-party kernel is "$installroot/kernels"; + #$updates{'kerneldir'} = $kerneldir if ($tempfile); unless ($osver and $profile) { @@ -159,23 +162,23 @@ unless ($osver and $profile) { my @ndrivers; if ($netdriver) { - foreach (split /,/,$netdriver) { + foreach (split /,/, $netdriver) { if (/^allupdate$/) { next; } unless (/\.ko$/) { - s/$/.ko/; + s/$/.ko/; } next if (/^$/); - + # Do not include qeth module here # This module is included later on - unless ( $_ =~ m/qeth/i ) { - push @ndrivers, $_; + unless ($_ =~ m/qeth/i) { + push @ndrivers, $_; } } - if ( ($updates{'netdrivers'} ne $netdriver) and $tempfile ) { + if (($updates{'netdrivers'} ne $netdriver) and $tempfile) { $updates{'netdrivers'} = $netdriver; } } @@ -190,440 +193,447 @@ if ($arch eq 'x86' or $arch eq 'x86_64') { } foreach (@ndrivers) { - unless (/\.ko$/) { - s/$/.ko/; - } + unless (/\.ko$/) { + s/$/.ko/; + } } -unless (grep /af_packet/,@ndrivers) { - unshift(@ndrivers,"af_packet.ko"); +unless (grep /af_packet/, @ndrivers) { + unshift(@ndrivers, "af_packet.ko"); } my $osver_host; -if(`grep VERSION /etc/SuSE-release` =~ /VERSION = (\d+)/) { - $osver_host=$1; +if (`grep VERSION /etc/SuSE-release` =~ /VERSION = (\d+)/) { + $osver_host = $1; } else { - $osver_host=11; + $osver_host = 11; } unless ($onlyinitrd) { # now, let's handle the extra packages unless ($imagename) { - $otherpkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "otherpkgs.pkglist"); - unless ($otherpkglist) { $otherpkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } + $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "otherpkgs.pkglist"); + unless ($otherpkglist) { $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } $updates{'otherpkglist'} = $otherpkglist if ($tempfile and $otherpkglist); } - my %extra_hash=(); - %extra_hash=imgutils::get_package_names($otherpkglist) if ($otherpkglist); + my %extra_hash = (); + %extra_hash = imgutils::get_package_names($otherpkglist) if ($otherpkglist); # prepare the chroot environment for the root image mkpath "$rootimg_dir/etc"; mkpath "$rootimg_dir/dev"; + #system "mount -o bind /dev $rootimg_dir/dev"; - unless ( -e "$rootimg_dir/dev/zero") { + unless (-e "$rootimg_dir/dev/zero") { system "mknod $rootimg_dir/dev/zero c 1 5"; } - unless ( -e "$rootimg_dir/dev/null") { + unless (-e "$rootimg_dir/dev/null") { system "mknod $rootimg_dir/dev/null c 1 3"; #that's neccessary for SLES11 } - unless ( -e "$rootimg_dir/dev/random") { + unless (-e "$rootimg_dir/dev/random") { system "mknod $rootimg_dir/dev/random c 1 8"; #that's neccessary for SLES11 } - unless ( -e "$rootimg_dir/dev/urandom") { + unless (-e "$rootimg_dir/dev/urandom") { system "mknod $rootimg_dir/dev/urandom c 1 9"; #that's neccessary for SLES11 } - for (my $i = 0; $i <= 12; $i++) + for (my $i = 0 ; $i <= 12 ; $i++) { - unless ( -e "$rootimg_dir/dev/tty$i") { + unless (-e "$rootimg_dir/dev/tty$i") { system "mknod $rootimg_dir/dev/tty$i c 4 $i"; #that's neccessary for SLES11 } } - open($fd,">>","$rootimg_dir/etc/fstab"); # TODO: is it necessary? - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); - - my $non_interactive; - if (!$prompt) { $non_interactive="--non-interactive --no-gpg-checks --gpg-auto-import-keys"; } + open($fd, ">>", "$rootimg_dir/etc/fstab"); # TODO: is it necessary? + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); - if($osver_host >= 11) {#zypper in SLES11 is different + my $non_interactive; + if (!$prompt) { $non_interactive = "--non-interactive --no-gpg-checks --gpg-auto-import-keys"; } - system("rm -rf $rootimg_dir/etc/zypp/repos.d/$osver-*.repo"); - my @pkgdirs = split(",", $srcdir); - my $dir; - my $i = 0; - # To support multiple paths for osimage.pkgdir - foreach $dir (@pkgdirs) { - if( -d "$dir/1") { - $dir .= "/1"; - } - system("zypper -R $rootimg_dir $non_interactive ar file:$dir $osver-$i"); - $i++; - } + if ($osver_host >= 11) { #zypper in SLES11 is different - #if(-e "$rootimg_dir/etc/zypp/repos.d/$osver.repo") { - # system("rm -rf $rootimg_dir/etc/zypp/repos.d/$osver.repo"); - #} - #system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir $osver"); - #if(-e "$rootimg_dir/etc/zypp/repos.d/${osver}sdk.repo") { - # system("rm -rf $rootimg_dir/etc/zypp/repos.d/${osver}sdk.repo"); - #} - if (opendir(SRCDIR, "$installroot/$osver/$arch/")) { - while (my $tmpfile = readdir(SRCDIR)) { - if ($tmpfile =~ m/^sdk/) { - my $srcdir_sdk = "$installroot/$osver/$arch/${tmpfile}"; - if ( -d "$srcdir_sdk") { - system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir_sdk ${osver}${tmpfile}"); - } - } - } - } - }else { - $srcdir = $srcdir . "/1"; - system("zypper -R $rootimg_dir $non_interactive sa file:$srcdir"); - } + system("rm -rf $rootimg_dir/etc/zypp/repos.d/$osver-*.repo"); + my @pkgdirs = split(",", $srcdir); + my $dir; + my $i = 0; - # Add the rep for kernel packages - if ($kernelver) { - if (! -d $kerneldir) { - print "Cannot find the directory for the kernel at $kerneldir.\n"; - exit 1; - } - if ($osver_host >= 11) { - if (-e "$rootimg_dir/etc/zypp/repos.d/$kernelver.repo") { - system("rm -rf $rootimg_dir/etc/zypp/repos.d/$kernelver.repo"); - } - system("zypper -R $rootimg_dir $non_interactive ar file:$kerneldir $kernelver"); - } else { - system("zypper -R $rootimg_dir $non_interactive sa file:$kerneldir"); - } - } + # To support multiple paths for osimage.pkgdir + foreach $dir (@pkgdirs) { + if (-d "$dir/1") { + $dir .= "/1"; + } + system("zypper -R $rootimg_dir $non_interactive ar file:$dir $osver-$i"); + $i++; + } - #remove the old repository for extra packages - if ($osver_host >= 11) { - my $result=`zypper -R $rootimg_dir $non_interactive lr |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir $non_interactive rr $result"); - } - } else { - my $result=`zypper -R $rootimg_dir $non_interactive sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir $non_interactive sd $result"); - } - } + #if(-e "$rootimg_dir/etc/zypp/repos.d/$osver.repo") { + # system("rm -rf $rootimg_dir/etc/zypp/repos.d/$osver.repo"); + #} + #system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir $osver"); + #if(-e "$rootimg_dir/etc/zypp/repos.d/${osver}sdk.repo") { + # system("rm -rf $rootimg_dir/etc/zypp/repos.d/${osver}sdk.repo"); + #} + if (opendir(SRCDIR, "$installroot/$osver/$arch/")) { + while (my $tmpfile = readdir(SRCDIR)) { + if ($tmpfile =~ m/^sdk/) { + my $srcdir_sdk = "$installroot/$osver/$arch/${tmpfile}"; + if (-d "$srcdir_sdk") { + system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir_sdk ${osver}${tmpfile}"); + } + } + } + } + } else { + $srcdir = $srcdir . "/1"; + system("zypper -R $rootimg_dir $non_interactive sa file:$srcdir"); + } - #add the new repository for extra packages - my %extrapkgnames; - if($osver_host >= 11) { #SLES11 - if(-e "$rootimg_dir/etc/zypp/repos.d/otherpkg.repo") { - system("rm -rf $rootimg_dir/etc/zypp/repos.d/otherpkg.repo"); - } - } - my $index=1; - my $pass; - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { + # Add the rep for kernel packages + if ($kernelver) { + if (!-d $kerneldir) { + print "Cannot find the directory for the kernel at $kerneldir.\n"; + exit 1; + } + if ($osver_host >= 11) { + if (-e "$rootimg_dir/etc/zypp/repos.d/$kernelver.repo") { + system("rm -rf $rootimg_dir/etc/zypp/repos.d/$kernelver.repo"); + } + system("zypper -R $rootimg_dir $non_interactive ar file:$kerneldir $kernelver"); + } else { + system("zypper -R $rootimg_dir $non_interactive sa file:$kerneldir"); + } + } - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$extra_hash{$pass}{INCLUDEBAD}}); - exit 1; - } + #remove the old repository for extra packages + if ($osver_host >= 11) { + my $result = `zypper -R $rootimg_dir $non_interactive lr |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir $non_interactive rr $result"); + } + } else { + my $result = `zypper -R $rootimg_dir $non_interactive sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir $non_interactive sd $result"); + } + } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} - my $whole_path="$srcdir_otherpkgs/$_"; - if (-r "$srcdir_otherpkgs/$_/repodata/repomd.xml") { - if($osver_host >= 11) { - system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir_otherpkgs/$_ otherpkg$index"); - }else { - system("zypper -R $rootimg_dir $non_interactive sa file:$srcdir_otherpkgs/$_"); - } - } else { - if($osver_host >= 11) { - system("zypper -R $rootimg_dir $non_interactive ar -t Plaindir file:$srcdir_otherpkgs/$_ otherpkg$index"); - }else { - system("zypper -R $rootimg_dir $non_interactive sa -t Plaindir file:$srcdir_otherpkgs/$_"); - } - } - $index++; + #add the new repository for extra packages + my %extrapkgnames; + if ($osver_host >= 11) { #SLES11 + if (-e "$rootimg_dir/etc/zypp/repos.d/otherpkg.repo") { + system("rm -rf $rootimg_dir/etc/zypp/repos.d/otherpkg.repo"); + } + } + my $index = 1; + my $pass; + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { - my $pa=$extra_hash{$pass}{$_}; - $extrapkgnames{$pass} .= " " . join(' ', @$pa); - } - } + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $extra_hash{$pass}{INCLUDEBAD} }); + exit 1; + } - #-- add custom repositories to the image - #TODO: should we add the support to otherpkgs for this? we have too many list files and it seems only SLES supports this - # not sure, but it is convenient - my $repolist; + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + my $whole_path = "$srcdir_otherpkgs/$_"; + if (-r "$srcdir_otherpkgs/$_/repodata/repomd.xml") { + if ($osver_host >= 11) { + system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir_otherpkgs/$_ otherpkg$index"); + } else { + system("zypper -R $rootimg_dir $non_interactive sa file:$srcdir_otherpkgs/$_"); + } + } else { + if ($osver_host >= 11) { + system("zypper -R $rootimg_dir $non_interactive ar -t Plaindir file:$srcdir_otherpkgs/$_ otherpkg$index"); + } else { + system("zypper -R $rootimg_dir $non_interactive sa -t Plaindir file:$srcdir_otherpkgs/$_"); + } + } + $index++; + + my $pa = $extra_hash{$pass}{$_}; + $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } + } + + #-- add custom repositories to the image + #TODO: should we add the support to otherpkgs for this? we have too many list files and it seems only SLES supports this + # not sure, but it is convenient + my $repolist; $repolist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "repolist"); unless ($repolist) { $repolist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "repolist"); } - if ( -r "$repolist") { - print "Reading custom repositories\n"; - open($repoconfig,"<","$repolist"); - while (<$repoconfig>) { - chomp; - next if /^\s*#/; - my ($repotype,$repourl,$repoalias) = split m/\|/; - if($osver_host >= 11) { - system("zypper -R $rootimg_dir $non_interactive ar $repourl $repoalias"); - }else { - system("zypper -R $rootimg_dir $non_interactive sa $repourl $repoalias"); - } - } - } + if (-r "$repolist") { + print "Reading custom repositories\n"; + open($repoconfig, "<", "$repolist"); + while (<$repoconfig>) { + chomp; + next if /^\s*#/; + my ($repotype, $repourl, $repoalias) = split m/\|/; + if ($osver_host >= 11) { + system("zypper -R $rootimg_dir $non_interactive ar $repourl $repoalias"); + } else { + system("zypper -R $rootimg_dir $non_interactive sa $repourl $repoalias"); + } + } + } - # Refresh the zypper cache in case there is still old data out there - system("zypper -R $rootimg_dir $non_interactive refresh"); + # Refresh the zypper cache in case there is still old data out there + system("zypper -R $rootimg_dir $non_interactive refresh"); - #my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir --disablerepo=* "; - #$yumcmd .= "install "; - #mkpath("$rootimg_dir/var/lib/yum"); - my $yumcmd; - if( $osver_host < 11) { - $yumcmd = "zypper -R $rootimg_dir $non_interactive install "; - }else { - $yumcmd = "zypper -R $rootimg_dir $non_interactive install -l --no-recommends "; #add -l for SLES11 - } + #my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir --disablerepo=* "; + #$yumcmd .= "install "; + #mkpath("$rootimg_dir/var/lib/yum"); + my $yumcmd; + if ($osver_host < 11) { + $yumcmd = "zypper -R $rootimg_dir $non_interactive install "; + } else { + $yumcmd = "zypper -R $rootimg_dir $non_interactive install -l --no-recommends "; #add -l for SLES11 + } - #install packages from pkglist file - my $pkgnames; - unless ($imagename) { - $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); - unless ($pkglist) { $pkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); } - } + #install packages from pkglist file + my $pkgnames; + unless ($imagename) { + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); + unless ($pkglist) { $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); } + } - if ($pkglist) { + if ($pkglist) { $updates{'pkglist'} = $pkglist if ($tempfile); } else { - print "Unable to find package list for $profile!"; - exit 1; - } + print "Unable to find package list for $profile!"; + exit 1; + } - my %pkg_hash=imgutils::get_package_names($pkglist); - my $index=1; - foreach $pass (sort {$a <=> $b} (keys(%pkg_hash))) { - $pkgnames = ""; - $group_pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { + my %pkg_hash = imgutils::get_package_names($pkglist); + my $index = 1; + foreach $pass (sort { $a <=> $b } (keys(%pkg_hash))) { + $pkgnames = ""; + $group_pkgnames = ""; + foreach (keys(%{ $pkg_hash{$pass} })) { - if($_ eq "INCLUDEBAD") { - print "Unable to open the following pkglist files:\n".join("\n",@{$pkg_hash{$pass}{INCLUDEBAD}}); - exit 1; - } + if ($_ eq "INCLUDEBAD") { + print "Unable to open the following pkglist files:\n" . join("\n", @{ $pkg_hash{$pass}{INCLUDEBAD} }); + exit 1; + } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} - my $pa=$pkg_hash{$pass}{$_}; - # replace the kernel package with the name has the specific version - my @npa = (); - my @npa_group = (); - foreach my $p (@$pa) { - if ($p =~ /^kernel/ && $kernelver) { - # get all files in $srcdir and $kerneldir - my @alldirs = ("$srcdir", "$kerneldir"); - my @allrpms = (); - foreach my $dir (@alldirs) { - my @files = `find $dir -name *.rpm`; - push @allrpms, @files; - } - my @kernelpkgs = (); - if ($p =~ /^kernel$/) { - @kernelpkgs = ("kernel-default","kernel-default-base"); - } elsif ($p =~ /^kernel-ppc64$/) { - @kernelpkgs = ($p, $p."-base"); - } else { - @kernelpkgs = ($p); - } - foreach my $kern (@kernelpkgs) { - my @rpm = grep /$kern-$krpmver/, @allrpms; - if (!@rpm) { - print "Cannot find the kernel package with the versioin $krpmver.\n"; - exit 1; - } - my $kernelname = "$kern-".$krpmver; - push @npa, $kernelname; - } - } else { - if($p =~ s/^@//) - { - push @npa_group, $p; - } - else - { - push @npa, $p; - } - } - } - if (@npa) { - $pkgnames .= " " . join(' ', @npa); - } - if (@npa_group) { - $group_pkgnames .= " " . join(' ', @npa_group); - } - } - my $envlist; - if(exists $pkg_hash{$pass}{ENVLIST}){ - $envlist = join(' ', @{$pkg_hash{$pass}{ENVLIST}}); + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + my $pa = $pkg_hash{$pass}{$_}; + + # replace the kernel package with the name has the specific version + my @npa = (); + my @npa_group = (); + foreach my $p (@$pa) { + if ($p =~ /^kernel/ && $kernelver) { + + # get all files in $srcdir and $kerneldir + my @alldirs = ("$srcdir", "$kerneldir"); + my @allrpms = (); + foreach my $dir (@alldirs) { + my @files = `find $dir -name *.rpm`; + push @allrpms, @files; + } + my @kernelpkgs = (); + if ($p =~ /^kernel$/) { + @kernelpkgs = ("kernel-default", "kernel-default-base"); + } elsif ($p =~ /^kernel-ppc64$/) { + @kernelpkgs = ($p, $p . "-base"); + } else { + @kernelpkgs = ($p); + } + foreach my $kern (@kernelpkgs) { + my @rpm = grep /$kern-$krpmver/, @allrpms; + if (!@rpm) { + print "Cannot find the kernel package with the versioin $krpmver.\n"; + exit 1; + } + my $kernelname = "$kern-" . $krpmver; + push @npa, $kernelname; + } + } else { + if ($p =~ s/^@//) + { + push @npa_group, $p; + } + else + { + push @npa, $p; + } + } + } + if (@npa) { + $pkgnames .= " " . join(' ', @npa); + } + if (@npa_group) { + $group_pkgnames .= " " . join(' ', @npa_group); + } } - if($pkgnames) - { - print "$envlist $yumcmd $pkgnames\n"; - $rc = system("$envlist $yumcmd $pkgnames"); - $rc = $rc >> 8; - if (($rc) && ($rc != '104')) { - print "zypper invocation failed with rc: $rc\n"; - exit 1; - } - } - if($group_pkgnames) - { - print "$envlist $yumcmd -t pattern $group_pkgnames\n"; - $rc = system("$envlist $yumcmd -t pattern $group_pkgnames"); - $rc = $rc >> 8; - if (($rc) && ($rc != '104')) { - print "zypper invocation failed with rc: $rc\n"; - exit 1; - } - } - } + my $envlist; + if (exists $pkg_hash{$pass}{ENVLIST}) { + $envlist = join(' ', @{ $pkg_hash{$pass}{ENVLIST} }); + } + if ($pkgnames) + { + print "$envlist $yumcmd $pkgnames\n"; + $rc = system("$envlist $yumcmd $pkgnames"); + $rc = $rc >> 8; + if (($rc) && ($rc != '104')) { + print "zypper invocation failed with rc: $rc\n"; + exit 1; + } + } + if ($group_pkgnames) + { + print "$envlist $yumcmd -t pattern $group_pkgnames\n"; + $rc = system("$envlist $yumcmd -t pattern $group_pkgnames"); + $rc = $rc >> 8; + if (($rc) && ($rc != '104')) { + print "zypper invocation failed with rc: $rc\n"; + exit 1; + } + } + } - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { - my $index=1; - #remove the old repository for extra packages - if ($osver_host >= 11) { - my $result=`zypper -R $rootimg_dir $non_interactive lr |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir $non_interactive rr $result"); - } - } else { - my $result=`zypper -R $rootimg_dir $non_interactive sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir $non_interactive sd $result"); - } - } + my $index = 1; - foreach (keys(%{$extra_hash{$pass}})) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} - if (-r "$srcdir_otherpkgs/$_/repodata/repomd.xml") { - if($osver_host >= 11) { - system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir_otherpkgs/$_ otherpkg$index"); - } else { + #remove the old repository for extra packages + if ($osver_host >= 11) { + my $result = `zypper -R $rootimg_dir $non_interactive lr |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir $non_interactive rr $result"); + } + } else { + my $result = `zypper -R $rootimg_dir $non_interactive sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir $non_interactive sd $result"); + } + } + + foreach (keys(%{ $extra_hash{$pass} })) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + if (-r "$srcdir_otherpkgs/$_/repodata/repomd.xml") { + if ($osver_host >= 11) { + system("zypper -R $rootimg_dir $non_interactive ar file:$srcdir_otherpkgs/$_ otherpkg$index"); + } else { system("zypper -R $rootimg_dir $non_interactive sa file:$srcdir_otherpkgs/$_"); - } - } else { - if($osver_host >= 11) { - system("zypper -R $rootimg_dir $non_interactive ar -t Plaindir file:$srcdir_otherpkgs/$_ otherpkg$index"); - }else { - system("zypper -R $rootimg_dir $non_interactive sa -t Plaindir file:$srcdir_otherpkgs/$_"); - } - } + } + } else { + if ($osver_host >= 11) { + system("zypper -R $rootimg_dir $non_interactive ar -t Plaindir file:$srcdir_otherpkgs/$_ otherpkg$index"); + } else { + system("zypper -R $rootimg_dir $non_interactive sa -t Plaindir file:$srcdir_otherpkgs/$_"); + } + } $index++; - } + } - # Refresh the zypper cache in case there is still old data out there - system("zypper -R $rootimg_dir $non_interactive refresh"); + # Refresh the zypper cache in case there is still old data out there + system("zypper -R $rootimg_dir $non_interactive refresh"); - #remove the packages that are specified in the otherpkgs.list files with leading '-' - my $envlist; - if(exists $extra_hash{$pass}{ENVLIST}){ - $envlist = join(' ', @{$extra_hash{$pass}{ENVLIST}}); - } + #remove the packages that are specified in the otherpkgs.list files with leading '-' + my $envlist; + if (exists $extra_hash{$pass}{ENVLIST}) { + $envlist = join(' ', @{ $extra_hash{$pass}{ENVLIST} }); + } - my $yumcmd_remove= "zypper -R $rootimg_dir $non_interactive remove "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$envlist $yumcmd_remove $rm_packges"; - $rc = system("$envlist $yumcmd_remove $rm_packges"); - } - } - + my $yumcmd_remove = "zypper -R $rootimg_dir $non_interactive remove "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$envlist $yumcmd_remove $rm_packges"; + $rc = system("$envlist $yumcmd_remove $rm_packges"); + } + } - #add extra packages in the list - if ($extrapkgnames{$pass}) { - print "$envlist $yumcmd $extrapkgnames{$pass}\n"; - $rc = system("$envlist $yumcmd $extrapkgnames{$pass}"); - $rc = $rc >> 8; - if (($rc) && ($rc != '104')) { - print "zypper invocation failed with rc: $rc\n"; - exit 1; - } - } - #remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$envlist $yumcmd_remove $rm_packges"; - $rc = system("$envlist $yumcmd_remove $rm_packges"); - } - } + #add extra packages in the list + if ($extrapkgnames{$pass}) { + print "$envlist $yumcmd $extrapkgnames{$pass}\n"; + $rc = system("$envlist $yumcmd $extrapkgnames{$pass}"); + $rc = $rc >> 8; + if (($rc) && ($rc != '104')) { + print "zypper invocation failed with rc: $rc\n"; + exit 1; + } + } - if (!$noupdate) { - # run zypper update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update; - if ($osver_host >= 11) { - $yumcmd_update = "zypper -R $rootimg_dir $non_interactive update "; - } else { - $yumcmd_update = "zypper -R $rootimg_dir $non_interactive update "; - } - $rc = system("$yumcmd_update"); - } - } + #remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$envlist $yumcmd_remove $rm_packges"; + $rc = system("$envlist $yumcmd_remove $rm_packges"); + } + } - #remove the old repository for extra packages - if ($osver_host >= 11) { - my $result=`zypper -R $rootimg_dir $non_interactive lr |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir $non_interactive rr $result"); - } - } else { - my $result=`zypper -R $rootimg_dir $non_interactive sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir $non_interactive sd $result"); - } - } + if (!$noupdate) { - # ignore any return code + # run zypper update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update; + if ($osver_host >= 11) { + $yumcmd_update = "zypper -R $rootimg_dir $non_interactive update "; + } else { + $yumcmd_update = "zypper -R $rootimg_dir $non_interactive update "; + } + $rc = system("$yumcmd_update"); + } + } - postscripts(); #run 'postscripts' + #remove the old repository for extra packages + if ($osver_host >= 11) { + my $result = `zypper -R $rootimg_dir $non_interactive lr |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir $non_interactive rr $result"); + } + } else { + my $result = `zypper -R $rootimg_dir $non_interactive sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir $non_interactive sd $result"); + } + } + + # ignore any return code + + postscripts(); #run 'postscripts' } unlink "/tmp/genimage.$$.yum.conf"; # added dracut mode -if ( (-d "$rootimg_dir/usr/share/dracut") or (-d "$rootimg_dir/usr/lib/dracut") ) { +if ((-d "$rootimg_dir/usr/share/dracut") or (-d "$rootimg_dir/usr/lib/dracut")) { $dracutmode = 1; - # get dracut version + + # get dracut version $dracutver = `rpm --root $rootimg_dir -qi dracut | grep Version | awk -F' ' '{print \$3}' `; chomp($dracutver); if ($dracutver =~ /^\d\d\d$/) { if ($dracutver >= "033") { $dracutdir = "dracut_033"; } else { - $dracutdir = "dracut"; # The default directory + $dracutdir = "dracut"; # The default directory } } print "Enter the dracut mode. Dracut version: $dracutver. Dracut directory: $dracutdir.\n"; } # default to the first kernel found in the install image if nothing specified explicitly. -# A more accurate guess than whatever the image build server happens to be running +# A more accurate guess than whatever the image build server happens to be running # If specified, that takes precedence. # If image has one, that is used # If all else fails, resort to uname -r like this script did before - -if ( -e "$rootimg_dir/boot/vmlinux" ) { + +if (-e "$rootimg_dir/boot/vmlinux") { $basekernelver = basename(readlink "$rootimg_dir/boot/vmlinux"); if ($basekernelver eq "vmlinux") { $basekernelver = ""; @@ -635,7 +645,7 @@ if ( -e "$rootimg_dir/boot/vmlinux" ) { unless ($basekernelver) { my @KVERS = <$rootimg_dir/boot/vmlinu[xz]-*>; - + # The kernel name is different on s390x, e.g. image-2.6.32.9-0.5-default @KVERS = <$rootimg_dir/boot/image-*> if $arch eq "s390x"; foreach (@KVERS) { @@ -654,21 +664,22 @@ unless ($basekernelver) { } } - @KVERS=<$rootimg_dir/lib/modules/*> unless (scalar @KVERS); + @KVERS = <$rootimg_dir/lib/modules/*> unless (scalar @KVERS); $basekernelver = basename(pop @KVERS) if (scalar @KVERS); $basekernelver = `uname -r` unless ($basekernelver); } $kernelver = $basekernelver unless ($kernelver); chomp $kernelver; + #$updates{kernelver} = $kernelver if ($tempfile); # copy the kernel to $destdir -if ( -e "$rootimg_dir/boot/vmlinux-$kernelver") { +if (-e "$rootimg_dir/boot/vmlinux-$kernelver") { copy("$rootimg_dir/boot/vmlinux-$kernelver", "$destdir/kernel"); -} elsif ( -e "$rootimg_dir/boot/vmlinuz-$kernelver") { +} elsif (-e "$rootimg_dir/boot/vmlinuz-$kernelver") { copy("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); -} elsif ( -e "$rootimg_dir/boot/image-$kernelver") { +} elsif (-e "$rootimg_dir/boot/image-$kernelver") { copy("$rootimg_dir/boot/image-$kernelver", "$destdir/kernel"); } else { xdie "couldn't find the kernel file matched $kernelver in $rootimg_dir/boot !"; @@ -676,24 +687,25 @@ if ( -e "$rootimg_dir/boot/vmlinux-$kernelver") { #-- run postinstall script unless ($imagename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); unless ($postinstall_filename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); } -} +} + +if ($postinstall_filename) { -if ( $postinstall_filename ) { #print "postinstall_filename=$postinstall_filename\n"; - #For Mellonax IB script. In diskless image, the uname -r not returning the rootimg level, + #For Mellonax IB script. In diskless image, the uname -r not returning the rootimg level, #because the "uname -r" only returns the version of the kernel in use - #create a temporary uname script. for every flag except for -r, it should just call the real + #create a temporary uname script. for every flag except for -r, it should just call the real #uname with the same flags and return that info. - if(!( -e "$rootimg_dir/bin/orig_uname")) { + if (!(-e "$rootimg_dir/bin/orig_uname")) { system("mv $rootimg_dir/bin/uname $rootimg_dir/bin/orig_uname"); } my $tmpuname; - open($tmpuname,">","$rootimg_dir/bin/uname"); + open($tmpuname, ">", "$rootimg_dir/bin/uname"); print $tmpuname <>$tempfile"); if ($imagename) { - if (keys(%updates) > 0) { - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$imagename\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - } + if (keys(%updates) > 0) { + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$imagename\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + } } else { - $updates_os{'profile'} = $profile; - $updates_os{'imagetype'} = 'linux'; - $updates_os{'provmethod'} = 'netboot'; - $updates_os{'osname'} = 'Linux'; - $updates_os{'osvers'} = $osver; - $updates_os{'osdistroname'} = 'sles'; # not used currently - $updates_os{'osarch'} = $arch; - # update the imagename for stateless - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - # update the imagename for statelite - $updates_os{'provmethod'} = 'statelite'; - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-statelite-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-statelite-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; + $updates_os{'profile'} = $profile; + $updates_os{'imagetype'} = 'linux'; + $updates_os{'provmethod'} = 'netboot'; + $updates_os{'osname'} = 'Linux'; + $updates_os{'osvers'} = $osver; + $updates_os{'osdistroname'} = 'sles'; # not used currently + $updates_os{'osarch'} = $arch; + + # update the imagename for stateless + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + # update the imagename for statelite + $updates_os{'provmethod'} = 'statelite'; + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-statelite-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-statelite-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; } close FILE; } + #END -mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts; -mkpath "$rootimg_dir/.sllocal/localmnt"; # create place for localdisk mount -mkpath "$rootimg_dir/.sllocal/log"; # create place for localdisk log +mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts; +mkpath "$rootimg_dir/.sllocal/localmnt"; # create place for localdisk mount +mkpath "$rootimg_dir/.sllocal/log"; # create place for localdisk log mkpath "$rootimg_dir/root/.ssh"; # create place for NFS mounts for ssh; #TODO is necessary? # this script will get the directories; # TODO: it seems it is re-copied in liteimg.pm -unless( -r "$pathtofiles/../add-on/statelite/rc.statelite") { +unless (-r "$pathtofiles/../add-on/statelite/rc.statelite") { print "Can't find $pathtofiles/../add-on/statelite/rc.statelite!\n"; exit; } @@ -809,21 +823,21 @@ system("cp $pathtofiles/../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d system("cp $pathtofiles/../add-on/statelite/rc.localdisk $rootimg_dir/etc/init.d/localdisk"); # added dracutmode -unless ($dracutmode) { #in dracut mode, we delegate all this activity - unless (-l "$rootimg_dir/var/lib/dhclient" ) { +unless ($dracutmode) { #in dracut mode, we delegate all this activity + unless (-l "$rootimg_dir/var/lib/dhclient") { mkpath "$rootimg_dir/var/lib/dhclient/"; system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); } - unless (-l "$rootimg_dir/var/lib/dhcp" ) { + unless (-l "$rootimg_dir/var/lib/dhcp") { mkpath "$rootimg_dir/var/lib/dhcp/"; system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); } - } +} # the dhcp client information stores in the directory "/var/lib/dhcpcd/" -unless(-l "$rootimg_dir/var/lib/dhcpcd") { +unless (-l "$rootimg_dir/var/lib/dhcpcd") { mkpath "$rootimg_dir/var/lib/dhcpcd/"; system("touch $rootimg_dir/var/lib/dhcpcd/dhcpcd-$prinic.info"); } @@ -833,8 +847,8 @@ system("cd $rootimg_dir/usr/bin/; ln -s ../../bin/keyctl $rootimg_dir/usr/bin/ke # which is different from the Redhat family -# some rpms mounts the imageroot/proc on the /proc, need to release it, -# otherwise got kernal panic when installing +# some rpms mounts the imageroot/proc on the /proc, need to release it, +# otherwise got kernal panic when installing # sometimes, the proc fs is not mounted, so one warning/error message will display, # and I add one check point here. my $MFD; @@ -843,7 +857,7 @@ my @lines = ; close MFD; my $ret = grep m{$rootimg_dir/proc}, @lines; -if($ret > 0) { +if ($ret > 0) { system("umount -l $rootimg_dir/proc"); } @@ -853,7 +867,7 @@ my @dd_drivers = &load_dd(); # Push the drivers into the @ndrivers base on the order my @new_order = (); foreach my $dd (@dd_drivers) { - unless (grep { $_ eq $dd} @ndrivers) { + unless (grep { $_ eq $dd } @ndrivers) { push @new_order, $dd; } print "Added driver $dd from driver update disk or driver rpm\n"; @@ -867,39 +881,39 @@ if (@new_order) { push @ndrivers, ("ext3.ko", "ext4.ko", "virtio_pci.ko", "virtio_blk.ko", "libata.ko", "scsi_mod.ko", "scsi_dh.ko", "ahci.ko", "megaraid_sas.ko", "sd_mod.ko"); if ($osver_host >= 12) { - push @ndrivers, ("ibmvscsi.ko"); -} else { # for sles11 or lower - push @ndrivers, ("ibmvscsic.ko", "ata_piix.ko", "pcieport.ko"); + push @ndrivers, ("ibmvscsi.ko"); +} else { # for sles11 or lower + push @ndrivers, ("ibmvscsic.ko", "ata_piix.ko", "pcieport.ko"); } if (-f "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/net/ethernet/mellanox/mlx4/mlx4_en.ko") { - for (@ndrivers) { - s/mlx_en/mlx4_en/; - } + for (@ndrivers) { + s/mlx_en/mlx4_en/; + } } -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; if ($driver =~ /libcrc32c.ko/) { push @deps, 'crc32c.ko'; } my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added print "Added $dep as an autodetected depedency\n"; } - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); } } } @@ -908,7 +922,7 @@ close($moddeps); #remove the duplicated drivers my @fulldrivers; foreach my $dn (@ndrivers) { - unless (grep {$_ eq $dn} @fulldrivers) { + unless (grep { $_ eq $dn } @fulldrivers) { push @fulldrivers, $dn; } } @@ -921,80 +935,82 @@ if ($dracutmode) { mkinitrd_dracut("stateless"); mkinitrd_dracut("statelite"); } else { - my @drivers; # backup of @ndrivers + my @drivers; # backup of @ndrivers push @drivers, @ndrivers; mkinitrd("statelite"); - @ndrivers=(); + @ndrivers = (); push @ndrivers, @drivers; mkinitrd("stateless"); } sub getlibs { - my $file = shift; + my $file = shift; my $liblist = `chroot $rootimg_dir ldd $file`; if ($liblist =~ /not a dynamic executable/) { return; } - my @libs = split/\n/,$liblist; + my @libs = split /\n/, $liblist; my @return; foreach (@libs) { unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; $lib =~ s/^\///; - $libhash{$lib}=1; + $libhash{$lib} = 1; next; } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; unless ($temp1 =~ /\//) { next; } $temp1 =~ s/^\///; - $libhash{$temp1}=1; + $libhash{$temp1} = 1; } } #added dracut sub mkinitrd_dracut { - my ($mode) = @_; # the mode is for statelite or stateless + my ($mode) = @_; # the mode is for statelite or stateless - my $dracutmoduledir="$rootimg_dir/usr/share/dracut/modules.d/"; - if ( (! -d $dracutmoduledir) and (-d "$rootimg_dir/usr/lib/dracut/modules.d/")) + my $dracutmoduledir = "$rootimg_dir/usr/share/dracut/modules.d/"; + if ((!-d $dracutmoduledir) and (-d "$rootimg_dir/usr/lib/dracut/modules.d/")) { - $dracutmoduledir="$rootimg_dir/usr/lib/dracut/modules.d/"; + $dracutmoduledir = "$rootimg_dir/usr/lib/dracut/modules.d/"; } if ($dracutver >= "033") { - my $perm = (stat("$fullpath/$dracutdir/patch/syslog/module-setup.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/module-setup.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."module-setup.sh"); + my $perm = (stat("$fullpath/$dracutdir/patch/syslog/module-setup.sh"))[2]; + cp("$fullpath/$dracutdir/patch/syslog/module-setup.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "module-setup.sh"); - $perm = (stat("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."rsyslogd-start.sh"); + $perm = (stat("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh"))[2]; + cp("$fullpath/$dracutdir/patch/syslog/rsyslogd-start.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "rsyslogd-start.sh"); - $perm = (stat("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh"))[2]; - cp("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh", $dracutmoduledir."98syslog/"); - chmod($perm&07777, $dracutmoduledir."98syslog/"."syslog-genrules.sh"); + $perm = (stat("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh"))[2]; + cp("$fullpath/$dracutdir/patch/syslog/syslog-genrules.sh", $dracutmoduledir . "98syslog/"); + chmod($perm & 07777, $dracutmoduledir . "98syslog/" . "syslog-genrules.sh"); } - my $dracutmpath = $dracutmoduledir."97xcat/"; + my $dracutmpath = $dracutmoduledir . "97xcat/"; mkpath($dracutmpath); my $perm = (stat("$fullpath/$dracutdir/check"))[2]; cp("$fullpath/$dracutdir/check", $dracutmpath); - chmod($perm&07777, "$dracutmpath/check"); + chmod($perm & 07777, "$dracutmpath/check"); foreach (@ndrivers) { s/\.ko$//; } + # Add drivers to support local disk push @ndrivers, "ext3"; push @ndrivers, "ext4"; + #remove the duplicated drivers my @fulldrivers; foreach my $dn (@ndrivers) { - unless (grep {$_ eq $dn} @fulldrivers) { + unless (grep { $_ eq $dn } @fulldrivers) { push @fulldrivers, $dn; } } @@ -1004,68 +1020,69 @@ sub mkinitrd_dracut { print "Try to load drivers: $add_drivers to initrd.\n"; my $DRACUTCONF; - if ($mode eq "statelite") { + if ($mode eq "statelite") { + # for statelite - cp("$fullpath/$dracutdir/install.statelite","$dracutmpath/install"); + cp("$fullpath/$dracutdir/install.statelite", "$dracutmpath/install"); $perm = (stat("$fullpath/$dracutdir/install.statelite"))[2]; - chmod($perm&07777, "$dracutmpath/install"); + chmod($perm & 07777, "$dracutmpath/install"); - cp("$installroot/postscripts/updateflag.awk","$dracutmpath/xcat-updateflag"); + cp("$installroot/postscripts/updateflag.awk", "$dracutmpath/xcat-updateflag"); $perm = (stat("$installroot/postscripts/updateflag.awk"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-updateflag"); + chmod($perm & 07777, "$dracutmpath/xcat-updateflag"); - cp("$fullpath/$dracutdir/xcat-prepivot.sh",$dracutmpath); + cp("$fullpath/$dracutdir/xcat-prepivot.sh", $dracutmpath); $perm = (stat("$fullpath/$dracutdir/xcat-prepivot.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-prepivot.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-prepivot.sh"); - cp("$fullpath/$dracutdir/xcat-premount.sh",$dracutmpath); + cp("$fullpath/$dracutdir/xcat-premount.sh", $dracutmpath); $perm = (stat("$fullpath/$dracutdir/xcat-premount.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-premount.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-premount.sh"); #update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); - if (-d glob($dracutmoduledir."[0-9]*fadump")){ + if (-d glob($dracutmoduledir . "[0-9]*fadump")) { print $DRACUTCONF qq{dracutmodules+="xcat nfs base network kernel-modules lvm fadump"\n}; } - else{ + else { print $DRACUTCONF qq{dracutmodules+="xcat nfs base network kernel-modules lvm"\n}; } print $DRACUTCONF qq{add_drivers+="$add_drivers"\n}; print $DRACUTCONF qq{filesystems+="nfs"\n}; close $DRACUTCONF; } elsif ($mode eq "stateless") { - cp("$fullpath/$dracutdir/install.netboot","$dracutmpath/install"); + cp("$fullpath/$dracutdir/install.netboot", "$dracutmpath/install"); $perm = (stat("$fullpath/$dracutdir/install.netboot"))[2]; - chmod($perm&07777, "$dracutmpath/install"); + chmod($perm & 07777, "$dracutmpath/install"); - cp("$fullpath/$dracutdir/xcat-cmdline.sh","$dracutmpath/"); + cp("$fullpath/$dracutdir/xcat-cmdline.sh", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/xcat-cmdline.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-cmdline.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-cmdline.sh"); - cp("$installroot/postscripts/updateflag.awk","$dracutmpath/xcat-updateflag"); + cp("$installroot/postscripts/updateflag.awk", "$dracutmpath/xcat-updateflag"); $perm = (stat("$installroot/postscripts/updateflag.awk"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-updateflag"); + chmod($perm & 07777, "$dracutmpath/xcat-updateflag"); if ($prinic) { my $optspec; - open($optspec,'>>',"$dracutmpath/xcat-cmdline.sh"); + open($optspec, '>>', "$dracutmpath/xcat-cmdline.sh"); print $optspec "PRINIC=$prinic\n"; close $optspec; } - cp("$fullpath/$dracutdir/xcatroot","$dracutmpath/"); + cp("$fullpath/$dracutdir/xcatroot", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/xcatroot"))[2]; - chmod($perm&07777, "$dracutmpath/xcatroot"); + chmod($perm & 07777, "$dracutmpath/xcatroot"); cp("$fullpath/$dracutdir/installkernel", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/installkernel"))[2]; - chmod($perm&07777, "$dracutmpath/installkernel"); + chmod($perm & 07777, "$dracutmpath/installkernel"); # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); - if (-d glob($dracutmoduledir."[0-9]*fadump")){ + if (-d glob($dracutmoduledir . "[0-9]*fadump")) { print $DRACUTCONF qq{dracutmodules+="xcat nfs base network kernel-modules lvm fadump syslog"\n}; } - else{ + else { print $DRACUTCONF qq{dracutmodules+="xcat nfs base network kernel-modules lvm syslog"\n}; } print $DRACUTCONF qq{add_drivers+="$add_drivers"\n}; @@ -1074,51 +1091,52 @@ sub mkinitrd_dracut { xdie "the mode: $mode is not supported by genimage"; } - my $additional_options=undef; - if($rootlimit) + my $additional_options = undef; + if ($rootlimit) { - open(my $ETC_CMDLINE,">","$rootimg_dir/tmp/cmdline"); + open(my $ETC_CMDLINE, ">", "$rootimg_dir/tmp/cmdline"); print $ETC_CMDLINE qq{rootlimit=$rootlimit\n}; close $ETC_CMDLINE; - $additional_options= qq{--include /tmp/cmdline /etc/cmdline}; + $additional_options = qq{--include /tmp/cmdline /etc/cmdline}; } - + # force the dracut run in non-hostonly mode for dracut higher than version 033 if ($dracutver > "033") { $additional_options .= " -N"; } #if "pigz" is available in the rootimg, use "pigz" instead of "gzip" - my $compress=qx(chroot $rootimg_dir bash -c "type -p pigz"|tr -d "\n"); - if ($compress){ + my $compress = qx(chroot $rootimg_dir bash -c "type -p pigz"|tr -d "\n"); + if ($compress) { + #take the online cpu numerber as the pigz processes number - my $processnum=qx(lscpu -p=cpu --online|grep -v '#'|wc -l|tr -d "\n"); + my $processnum = qx(lscpu -p=cpu --online|grep -v '#'|wc -l|tr -d "\n"); $additional_options .= " --compress \"$compress -p $processnum \""; } print "\nchroot $rootimg_dir dracut $additional_options -f /tmp/initrd.$$.gz $kernelver\n"; !system("chroot $rootimg_dir dracut $additional_options -f /tmp/initrd.$$.gz $kernelver") - or die("Error: failed to generate the initial ramdisk for $mode.\n"); + or die("Error: failed to generate the initial ramdisk for $mode.\n"); print "the initial ramdisk for $mode is generated successfully.\n"; move("$rootimg_dir/tmp/initrd.$$.gz", "$destdir/initrd-$mode.gz"); } sub mkinitrd { - my ($mode) = @_; # statelite or stateless + my ($mode) = @_; # statelite or stateless if ($mode eq "statelite") { # additional modules needed on s390x push @ndrivers, qw{qdio.ko ccwgroup.ko qeth.ko qeth_l2.ko qeth_l3.ko} if ($arch eq "s390x"); - + # for nfs my @modlist = qw{sunrpc.ko lockd.ko nfs_acl.ko fscache.ko auth_rpcgss.ko exportfs.ko nfsd.ko nfs.ko}; unshift(@ndrivers, @modlist); - } + } mkpath("/tmp/xcatinitrd.$$/bin"); - symlink("bin","/tmp/xcatinitrd.$$/sbin"); + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); mkpath("/tmp/xcatinitrd.$$/usr/bin"); mkpath("/tmp/xcatinitrd.$$/usr/sbin"); mkpath("/tmp/xcatinitrd.$$/usr/lib"); @@ -1127,8 +1145,8 @@ sub mkinitrd { mkpath("/tmp/xcatinitrd.$$/tmp"); mkpath("/tmp/xcatinitrd.$$/var/run"); mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib/power6");#SLES10 - mkpath("/tmp/xcatinitrd.$$/lib/power7");#SLES10 + mkpath("/tmp/xcatinitrd.$$/lib/power6"); #SLES10 + mkpath("/tmp/xcatinitrd.$$/lib/power7"); #SLES10 mkpath("/tmp/xcatinitrd.$$/lib/mkinitrd/bin"); mkpath("/tmp/xcatinitrd.$$/proc"); mkpath("/tmp/xcatinitrd.$$/sys"); @@ -1137,11 +1155,11 @@ sub mkinitrd { mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); mkpath("/tmp/xcatinitrd.$$/var/lib/dhcpcd"); my $inifile; - open($inifile,">","/tmp/xcatinitrd.$$/init"); + open($inifile, ">", "/tmp/xcatinitrd.$$/init"); print $inifile "#!/bin/bash\n"; -# copied from genimage for rh -# add some functions + # copied from genimage for rh + # add some functions print $inifile < /dev/null && export DEBUG=1\n"; } - print $inifile < /dev/null && shell @@ -1606,40 +1624,41 @@ if [ -r /rootimg.sfs ]; then mount --move /ro /sysroot/ro mount --move /rw /sysroot/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile "echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o size=$rootlimit,mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } - print $inifile " cd /sysroot\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " zcat /rootimg.gz |/bin/cpio -idum\n"; - print $inifile " else\n"; - print $inifile " zcat /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " echo Done\n"; - print $inifile "elif [ -r /rootimg.txz ]; then\n"; - print $inifile " echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o \"size=$rootlimit,mode=755\" -t tmpfs rootfs \$NEWROOT\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } - print $inifile " cd \$NEWROOT\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " tar -Jxvf /rootimg.txz\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 1\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " echo\n"; - print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/bin/bash \n"; - if ($osver_host == 10) { - print $inifile "dhcpcd \${1}\n"; - } else { # for sles11 or higher - # -p is used to keep the network connection during the shutdown. Used for nfs-based statelite shutdown - print $inifile "dhcpcd \${1} -p\n"; - } + print $inifile "cd /\n"; + print $inifile "mkdir \$NEWROOT/var/lib/dhcpcd/\n"; #neccessary for SLES11, not sure for SLES10 + print $inifile "cp /var/lib/dhcpcd/* \$NEWROOT/var/lib/dhcpcd/\n"; + print $inifile "cp /etc/resolv.conf \$NEWROOT/etc/\n"; + print $inifile "cp /etc/HOSTNAME \$NEWROOT/etc/\n"; + print $inifile "mknod \$NEWROOT/dev/console c 5 1\n"; - #-- Bring other NICs up in /bin/netstart in initrd for NIC failover - foreach (split /,/,$othernics) { - if (/^$/) { next; } - print $inifile "dhcpcd $_\n"; - } + #details, see defect https://sourceforge.net/p/xcat/bugs/4741/ + if ($osver =~ /sles11.4/i) { + print $inifile "export ROOTFS_BLKDEV=\"\/\"\n"; + } - print $inifile <" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/bin/bash \n"; + if ($osver_host == 10) { + print $inifile "dhcpcd \${1}\n"; + } else { # for sles11 or higher + # -p is used to keep the network connection during the shutdown. Used for nfs-based statelite shutdown + print $inifile "dhcpcd \${1} -p\n"; + } + + #-- Bring other NICs up in /bin/netstart in initrd for NIC failover + foreach (split /,/, $othernics) { + if (/^$/) { next; } + print $inifile "dhcpcd $_\n"; + } + + print $inifile <> /etc/HOSTNAME END - close($inifile); + close($inifile); - #if "nonodestatus" specified,do not update the nodestatus - system("mkdir -p /tmp/xcatinitrd.$$/tmp/"); - open($inifile, ">","/tmp/xcatinitrd.$$/tmp/updateflag"); + #if "nonodestatus" specified,do not update the nodestatus + system("mkdir -p /tmp/xcatinitrd.$$/tmp/"); + open($inifile, ">", "/tmp/xcatinitrd.$$/tmp/updateflag"); - print $inifile <= 11) { + close($inifile); + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + chmod(0755, "/tmp/xcatinitrd.$$/tmp/updateflag"); + + @filestoadd = (); + foreach (@ndrivers) { + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } + } + if ($mode eq "statelite") { + foreach ("sbin/ifconfig", "usr/bin/clear", "usr/bin/touch", "bin/hostname", "usr/bin/egrep", "bin/ln", "bin/ls", "usr/bin/dirname", "usr/bin/expr", "usr/bin/chroot", "usr/bin/grep", "bin/cpio", "bin/sleep", "bin/mount", "bin/umount", "sbin/dhcpcd", "bin/bash", "sbin/insmod", "bin/mkdir", "bin/mknod", "sbin/ip", "bin/cat", "usr/bin/awk", "usr/bin/wget", "bin/cp", "usr/bin/cpio", "usr/bin/zcat", "usr/bin/gzip", "lib/mkinitrd/bin/run-init", "usr/bin/uniq", "usr/bin/sed", "usr/bin/wc", "bin/sed", "sbin/udevd", "usr/bin/readlink", "usr/sbin/parted", "sbin/mke2fs", "sbin/mkswap", "sbin/swapon", "bin/chmod", "usr/bin/bc", "usr/bin/xz") { + getlibs($_); + push @filestoadd, $_; + } + if ($osver_host >= 11) { foreach ("sbin/mount.nfs", "sbin/umount.nfs", "sbin/udevadm") { getlibs($_); - push @filestoadd,$_; + push @filestoadd, $_; } } - - }else { - foreach ("sbin/ifconfig","usr/bin/clear","usr/bin/touch","usr/bin/grep","usr/bin/egrep","bin/cpio","bin/sleep","bin/mount","sbin/dhcpcd","bin/bash","sbin/insmod","bin/mkdir","bin/mknod","sbin/ip","bin/cat","usr/bin/awk","usr/bin/wget","bin/cp","usr/bin/cpio","usr/bin/zcat","usr/bin/gzip","lib/mkinitrd/bin/run-init","usr/bin/uniq","usr/bin/sed","sbin/udevd", "usr/bin/readlink", "usr/bin/expr", "usr/sbin/parted", "sbin/mke2fs", "sbin/mkswap", "sbin/swapon", "bin/chmod", "usr/bin/bc", "usr/bin/xz") { - getlibs($_); - push @filestoadd,$_; + + } else { + foreach ("sbin/ifconfig", "usr/bin/clear", "usr/bin/touch", "usr/bin/grep", "usr/bin/egrep", "bin/cpio", "bin/sleep", "bin/mount", "sbin/dhcpcd", "bin/bash", "sbin/insmod", "bin/mkdir", "bin/mknod", "sbin/ip", "bin/cat", "usr/bin/awk", "usr/bin/wget", "bin/cp", "usr/bin/cpio", "usr/bin/zcat", "usr/bin/gzip", "lib/mkinitrd/bin/run-init", "usr/bin/uniq", "usr/bin/sed", "sbin/udevd", "usr/bin/readlink", "usr/bin/expr", "usr/sbin/parted", "sbin/mke2fs", "sbin/mkswap", "sbin/swapon", "bin/chmod", "usr/bin/bc", "usr/bin/xz") { + getlibs($_); + push @filestoadd, $_; } - if($osver_host >= 11) { + if ($osver_host >= 11) { getlibs("sbin/udevadm"); - push @filestoadd,"sbin/udevadm"; + push @filestoadd, "sbin/udevadm"; } } - if ($arch =~ /64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libnss_files.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - push @filestoadd,"lib/libnss_files.so.2"; - } + if ($arch =~ /64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libnss_files.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + push @filestoadd, "lib/libnss_files.so.2"; + } # cross-platfrom support on power6&7 etc # ldd can't handle such one scenario: mn is power6, the target platform is power7 - if ($arch =~ /ppc64/) { - system("cp -a -r $rootimg_dir/lib64/* /tmp/xcatinitrd.$$/lib64/"); - } + if ($arch =~ /ppc64/) { + system("cp -a -r $rootimg_dir/lib64/* /tmp/xcatinitrd.$$/lib64/"); + } - push @filestoadd,keys %libhash; + push @filestoadd, keys %libhash; - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - my $pathonrootimage = "$rootimg_dir/tmpfiles"; - my $pathinrootimage = "/tmpfiles"; - mkpath($pathonrootimage); - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcfile = $_->[0]; - system("chroot $rootimg_dir cp $srcfile $pathinrootimage"); - my $srcpath = "$pathonrootimage/".basename($_->[0]); - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - system("chroot $rootimg_dir cp $_ $pathinrootimage"); - my $srcpath = "$pathonrootimage/".basename($_); - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } - rmtree($pathonrootimage); + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + my $pathonrootimage = "$rootimg_dir/tmpfiles"; + my $pathinrootimage = "/tmpfiles"; + mkpath($pathonrootimage); + foreach (@filestoadd) { + if (ref($_)) { - #copy conf files needed by nfs mount in sles11.2 - if($osver_host >= 11) - { - system("cp -r $rootimg_dir/etc/protocols /tmp/xcatinitrd.$$/etc/"); - system("cp -r $rootimg_dir/etc/netconfig /tmp/xcatinitrd.$$/etc/"); - } - - - # Copy udev libraries - system("mkdir -p /tmp/xcatinitrd.$$/etc/udev"); - system("mkdir -p /tmp/xcatinitrd.$$/lib/firmware"); - system("cp -r $rootimg_dir/etc/udev/* /tmp/xcatinitrd.$$/etc/udev"); - system("cp -r $rootimg_dir/bin/uname /tmp/xcatinitrd.$$/bin/"); - if ( -d "$rootimg_dir/lib/firmware/" ) { - system("cp -r $rootimg_dir/lib/firmware/* /tmp/xcatinitrd.$$/lib/firmware"); - } - system("cp -r $rootimg_dir/usr/bin/killall /tmp/xcatinitrd.$$/usr/bin"); - - # Copy rules for network adapter - #my $name = `cat /etc/sysconfig/network/ifcfg-$prinic | grep NAME`; - #my $nic = ''; - #if ($name =~ m/(\d+\.\d+\.\d+)/g) { - # $nic = $&; - #} + #print "$_->[0], $_->[1]\n"; + my $srcfile = $_->[0]; + system("chroot $rootimg_dir cp $srcfile $pathinrootimage"); + my $srcpath = "$pathonrootimage/" . basename($_->[0]); + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + system("chroot $rootimg_dir cp $_ $pathinrootimage"); + my $srcpath = "$pathonrootimage/" . basename($_); + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + rmtree($pathonrootimage); + + #copy conf files needed by nfs mount in sles11.2 + if ($osver_host >= 11) + { + system("cp -r $rootimg_dir/etc/protocols /tmp/xcatinitrd.$$/etc/"); + system("cp -r $rootimg_dir/etc/netconfig /tmp/xcatinitrd.$$/etc/"); + } + + + # Copy udev libraries + system("mkdir -p /tmp/xcatinitrd.$$/etc/udev"); + system("mkdir -p /tmp/xcatinitrd.$$/lib/firmware"); + system("cp -r $rootimg_dir/etc/udev/* /tmp/xcatinitrd.$$/etc/udev"); + system("cp -r $rootimg_dir/bin/uname /tmp/xcatinitrd.$$/bin/"); + if (-d "$rootimg_dir/lib/firmware/") { + system("cp -r $rootimg_dir/lib/firmware/* /tmp/xcatinitrd.$$/lib/firmware"); + } + system("cp -r $rootimg_dir/usr/bin/killall /tmp/xcatinitrd.$$/usr/bin"); + + # Copy rules for network adapter + #my $name = `cat /etc/sysconfig/network/ifcfg-$prinic | grep NAME`; + #my $nic = ''; + #if ($name =~ m/(\d+\.\d+\.\d+)/g) { + # $nic = $&; + #} # Somehow checking for *$nic.rules does not work #if ( -f "/etc/udev/rules.d/*$nic.rules" ) { @@ -1845,12 +1866,12 @@ EOMS #if ( -f "/etc/udev/rules.d/*persistent-net.rules" ) { # system("cp -r /etc/udev/rules.d/*persistent-net.rules /tmp/xcatinitrd.$$/etc/udev/rules.d"); #} - - system("mkdir -p /tmp/xcatinitrd.$$/lib/udev"); - system("cp -r $rootimg_dir/lib/udev/* /tmp/xcatinitrd.$$/lib/udev"); - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$/bin/; ln -sf bash sh"); #neccessary for SLES11 + system("mkdir -p /tmp/xcatinitrd.$$/lib/udev"); + system("cp -r $rootimg_dir/lib/udev/* /tmp/xcatinitrd.$$/lib/udev"); + + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$/bin/; ln -sf bash sh"); #neccessary for SLES11 if ($mode eq "statelite") { system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd-statelite.gz"); print "The initial ramdisk for statelite has been generated successfully!\n"; @@ -1858,41 +1879,41 @@ EOMS system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd-stateless.gz"); print "The initial ramdisk for stateless has been generated successfully!\n"; } - system("rm -rf /tmp/xcatinitrd.$$"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - print "Added driver $_ to initrd\n"; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + print "Added driver $_ to initrd\n"; + } + } } - -sub postscripts { # TODO: customized postscripts + +sub postscripts { # TODO: customized postscripts generic_post(); - unless( -d "$rootimg_dir/opt/xcat/") { + unless (-d "$rootimg_dir/opt/xcat/") { mkdir "$rootimg_dir/opt/xcat/"; } - copy ("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); #TODO: it is not used in stateless + copy("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); #TODO: it is not used in stateless chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; } @@ -1902,7 +1923,7 @@ sub generic_post { # This function is meant to leave the image in a state approx #modify /etc/sysconfig/clock in the image:HWCLOCK="--local", TIMEZONE=site:timezone if ($timezone) { if (-e "$rootimg_dir/etc/sysconfig/clock") { - system("sed -i '".'s!\(TIMEZONE=\).*!\1'."\"$timezone\"!"."' $rootimg_dir/etc/sysconfig/clock"); + system("sed -i '" . 's!\(TIMEZONE=\).*!\1' . "\"$timezone\"!" . "' $rootimg_dir/etc/sysconfig/clock"); } system("chroot $rootimg_dir zic -l $timezone"); } @@ -1913,7 +1934,7 @@ sub generic_post { # This function is meant to leave the image in a state approx unlink("$rootimg_dir/dev/null"); system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; print $cfgfile "proc /proc proc defaults 0 0\n"; @@ -1926,47 +1947,48 @@ sub generic_post { # This function is meant to leave the image in a state approx print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=10m 0 2\n"; } - my $rootfs_name = $profile."_".$arch; + my $rootfs_name = $profile . "_" . $arch; print $cfgfile "$rootfs_name / tmpfs rw 0 1\n"; close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); print $cfgfile "NETWORKING=yes\n"; close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); print $cfgfile "#Dummy resolv.conf to make boot cleaner"; close($cfgfile); + # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no # to skip the break of nfs-based boot if ($prinic) { - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network/ifcfg-$prinic"); - print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\nSTARTMODE=auto\n"; - close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network/ifcfg-$prinic"); + print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\nSTARTMODE=auto\n"; + close($cfgfile); } - foreach (split /,/,$othernics) { + foreach (split /,/, $othernics) { next if (/^$/); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network/ifcfg-$_"); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network/ifcfg-$_"); print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\nSTARTMODE=auto\n"; close($cfgfile); } - + # securetty not needed on s390x if ($arch ne "s390x") { - open( $cfgfile, ">>", "$rootimg_dir/etc/securetty" ); + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); print $cfgfile "ttyS0\n"; print $cfgfile "ttyS1\n"; print $cfgfile "console\n"; close($cfgfile); } - + my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); @passwd = <$cfgfile>; close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); foreach (@passwd) { if (/^root:/) { s/^root:\*/root:x/; @@ -1976,48 +1998,48 @@ sub generic_post { # This function is meant to leave the image in a state approx close($cfgfile); foreach (<$rootimg_dir/etc/skel/.*>) { next if (basename($_) eq '.' or basename($_) eq '..'); - copy $_,"$rootimg_dir/root/"; + copy $_, "$rootimg_dir/root/"; + } + + # gettyset is not found on s390x + if ($arch ne "s390x") { + open($cfgfile, ">", "$rootimg_dir/etc/init.d/gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "### BEGIN INIT INFO\n"; + print $cfgfile "# Provides: gettyset\n"; + print $cfgfile "# Required-Start: sshd\n"; + print $cfgfile "# Required-Stop:\n"; + print $cfgfile "# Default-Start: 3\n"; + print $cfgfile "# Default-Stop: 0 1 2 6\n"; + print $cfgfile "# Short-Description: gettyset\n"; + print $cfgfile "# Description:\n"; + print $cfgfile "### END INIT INFO\n"; + print $cfgfile "VERS=`grep VERSION /etc/SuSE-release`\n"; + print $cfgfile "if [ -n \"\$VERS\" ]; then\n"; + print $cfgfile " VERNUM=`echo \$VERS|awk -F= \'{print \$2}\'|sed -e \'s/ //g\'`\n"; + print $cfgfile "fi\n"; + print $cfgfile "if [ \"\$VERNUM\" -gt 10 ]; then\n"; + print $cfgfile " exit\n"; + print $cfgfile "fi\n"; + print $cfgfile "\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + print $cfgfile "/etc/init.d/boot.localnet start\n"; + + close($cfgfile); + chmod(0755, "$rootimg_dir/etc/init.d/gettyset"); } - - # gettyset is not found on s390x - if ($arch ne "s390x") { - open( $cfgfile, ">", "$rootimg_dir/etc/init.d/gettyset" ); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "### BEGIN INIT INFO\n"; - print $cfgfile "# Provides: gettyset\n"; - print $cfgfile "# Required-Start: sshd\n"; - print $cfgfile "# Required-Stop:\n"; - print $cfgfile "# Default-Start: 3\n"; - print $cfgfile "# Default-Stop: 0 1 2 6\n"; - print $cfgfile "# Short-Description: gettyset\n"; - print $cfgfile "# Description:\n"; - print $cfgfile "### END INIT INFO\n"; - print $cfgfile "VERS=`grep VERSION /etc/SuSE-release`\n"; - print $cfgfile "if [ -n \"\$VERS\" ]; then\n"; - print $cfgfile " VERNUM=`echo \$VERS|awk -F= \'{print \$2}\'|sed -e \'s/ //g\'`\n"; - print $cfgfile "fi\n"; - print $cfgfile "if [ \"\$VERNUM\" -gt 10 ]; then\n"; - print $cfgfile " exit\n"; - print $cfgfile "fi\n"; - print $cfgfile "\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - print $cfgfile "/etc/init.d/boot.localnet start\n"; - - close($cfgfile); - chmod( 0755, "$rootimg_dir/etc/init.d/gettyset" ); - } copy("$installroot/postscripts/xcatpostinit", "$rootimg_dir/etc/init.d/xcatpostinit"); chmod(0755, "$rootimg_dir/etc/init.d/xcatpostinit"); @@ -2034,7 +2056,7 @@ sub generic_post { # This function is meant to leave the image in a state approx foreach my $service (@services) { my $cmd = "chroot $rootimg_dir "; - if (-r "$rootimg_dir/etc/init.d/$service" ) { + if (-r "$rootimg_dir/etc/init.d/$service") { $cmd = $cmd . "insserv -f $service"; system("$cmd"); } @@ -2050,12 +2072,12 @@ sub generic_post { # This function is meant to leave the image in a state approx if (-r '$rootimg_dir/etc/init.d/.depend.start') { my $rc = system("grep sshd $rootimg_dir/etc/init.d/.depend.start | grep TARGETS"); if ($rc) { - system("sed -i '".'s/^\(TARGETS = .*\)$/\1 sshd/'."' $rootimg_dir/etc/init.d/.depend.start"); + system("sed -i '" . 's/^\(TARGETS = .*\)$/\1 sshd/' . "' $rootimg_dir/etc/init.d/.depend.start"); system("ln -s ../sshd $rootimg_dir/etc/init.d/rc3.d/S20sshd"); } my $rc = system("grep gettyset $rootimg_dir/etc/init.d/.depend.start | grep TARGETS"); if ($rc) { - system("sed -i '".'s/^\(TARGETS = .*\)$/\1 gettyset/'."' $rootimg_dir/etc/init.d/.depend.start"); + system("sed -i '" . 's/^\(TARGETS = .*\)$/\1 gettyset/' . "' $rootimg_dir/etc/init.d/.depend.start"); system("ln -s ../gettyset $rootimg_dir/etc/init.d/rc3.d/S60gettyset"); } } @@ -2064,6 +2086,7 @@ sub generic_post { # This function is meant to leave the image in a state approx my $driver_name; my $real_path; + sub get_path () { if ($File::Find::name =~ /\/$driver_name/) { @@ -2072,6 +2095,7 @@ sub get_path () } my @all_real_path; + sub get_all_path () { if ($File::Find::name =~ /\/$driver_name/) { @@ -2084,10 +2108,10 @@ sub get_all_path () # The valid value: dud:/install/dud/dd.img,rpm:/install/rpm/d.rpm, if missing the tag: 'dud'/'rpm' # the 'rpm' is default. # -# If cannot find the driver disk from osimage.driverupdatesrc, will try to search driver disk +# If cannot find the driver disk from osimage.driverupdatesrc, will try to search driver disk # from /install/driverdisk// # -# For driver rpm, the driver list will be gotten from osimage.netdrivers. If not set, copy all the drivers from driver +# For driver rpm, the driver list will be gotten from osimage.netdrivers. If not set, copy all the drivers from driver # rpm to the initrd. # # Return the driver names by loading order @@ -2114,7 +2138,8 @@ sub load_dd() } } } - if (! @dd_list) { + if (!@dd_list) { + # get Driver update disk from the default path if not specified in osimage # check the Driver Update Disk images, it can be .img or .iso if (-d "$installroot/driverdisk/$osver/$arch") { @@ -2122,13 +2147,13 @@ sub load_dd() } } - foreach (split /,/,$netdriver) { + foreach (split /,/, $netdriver) { if (/^allupdate$/) { $Injectalldriver = 1; next; } unless (/\.ko$/) { - s/$/.ko/; + s/$/.ko/; } push @driver_list, $_; } @@ -2146,19 +2171,19 @@ sub load_dd() mkpath "$dd_dir/mods"; my @dd_drivers = (); #driver names - + # Load drivers from each Driver Disk # For multiple dd, if want to make it has order, rename the dd with a number # ahead of the name like 0_xx, 1_xx foreach my $dd (sort(@dd_list)) { - my $rc = system ("mount -o loop $dd $dd_dir/mnt"); + my $rc = system("mount -o loop $dd $dd_dir/mnt"); if ($rc) { print "mount the Driver Disk $dd failed.\n"; next; } - + mkpath "$dd_dir/full"; - + # Copy out the drivers opendir(DIR, "$dd_dir/mnt") || die "Cannot open dir $dd_dir/mnt"; while (my $dir = readdir(DIR)) { @@ -2166,21 +2191,21 @@ sub load_dd() # Every driver update disk can have multiple directories, each directory # has the directory format like /linux/[distribution]/[architechture]-[version]/ - # If the directory name is numeric, then it will be used as order to load the + # If the directory name is numeric, then it will be used as order to load the # the dirviers inside. - # For the directory name which is not numeric, copy them to directory 0. It will be + # For the directory name which is not numeric, copy them to directory 0. It will be # loaled first. - if ($dir !~ /^\d*$/) { + if ($dir !~ /^\d*$/) { mkpath "$dd_dir/full/0"; - system ("cp -rf $dd_dir/mnt/$dir $dd_dir/full/0"); + system("cp -rf $dd_dir/mnt/$dir $dd_dir/full/0"); } else { - system ("cp -rf $dd_dir/mnt/$dir $dd_dir/full/"); + system("cp -rf $dd_dir/mnt/$dir $dd_dir/full/"); } } closedir(DIR); - + # Get all the kernel modules base on the order of directory name. - + # The structure of dd: /linux/[distribution]/[architechture]-[version]/ # The supported arch: i386, ia64, ppc, ppc64, s390, s390x sparc or x86_64. @@ -2188,26 +2213,26 @@ sub load_dd() if ($darch =~ /^x86$/) { $darch = "i386"; } - + # If the version is os version. If the os is "sles11.1", the possible os version # could be "sles11.1", "11.1", "11", "sles11" - my @distro = ($osver); + my @distro = ($osver); my $distro1 = $osver; $distro1 =~ s/[^\d]*//; - push @distro,$distro1; + push @distro, $distro1; my $distro2 = $distro1; $distro2 =~ s/\..*//; - push @distro,$distro2; + push @distro, $distro2; my $distro3 = $osver; $distro3 =~ s/\..*//; - push @distro,$distro3; + push @distro, $distro3; - opendir (FDIR, "$dd_dir/full") || die "Cannot open dir $dd_dir/full"; + opendir(FDIR, "$dd_dir/full") || die "Cannot open dir $dd_dir/full"; my @fulldir = readdir(FDIR); - closedir (FDIR); + closedir(FDIR); # Create the directory for drivers from driver disk - if (! -d "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk") { + if (!-d "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk") { mkpath "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"; } @@ -2220,48 +2245,48 @@ sub load_dd() $vdir = "$dd_dir/full/$dir/linux/suse/$darch-$_"; } } - if (! $vdir) { next; } + if (!$vdir) { next; } # Use the module_order if it has if (-f "$vdir/modules/module.order") { open(ORDER, "<", "$vdir/modules/module.order"); while (my $file = ) { - chomp ($file); + chomp($file); if (-f "$vdir/modules/$file") { $driver_name = $file; - $real_path = ""; + $real_path = ""; find(\&get_path, <$rootimg_dir/lib/modules/$kernelver/*>); if ($real_path eq "") { - system ("cp $vdir/modules/$file $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); + system("cp $vdir/modules/$file $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); } else { - system ("cp $vdir/modules/$file $real_path"); + system("cp $vdir/modules/$file $real_path"); } - + push @dd_drivers, $file; } } } else { - opendir (MDIR, "$vdir/modules") || die "Cannot open dir $vdir/modules"; + opendir(MDIR, "$vdir/modules") || die "Cannot open dir $vdir/modules"; while (my $file = readdir(MDIR)) { if (-f "$vdir/modules/$file" && $file =~ /\.ko/) { $driver_name = $file; - $real_path = ""; + $real_path = ""; find(\&get_path, <$rootimg_dir/lib/modules/$kernelver/*>); if ($real_path eq "") { - system ("cp $vdir/modules/$file $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); + system("cp $vdir/modules/$file $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); } else { - system ("cp $vdir/modules/$file $real_path"); + system("cp $vdir/modules/$file $real_path"); } - + push @dd_drivers, $file; } } } } - + rmtree "$dd_dir/full"; - - my $rc = system ("umount -f $dd_dir/mnt"); + + my $rc = system("umount -f $dd_dir/mnt"); if ($rc) { print "umount the directory $dd_dir/mnt failed\n"; exit 1; @@ -2270,11 +2295,12 @@ sub load_dd() # Loading the drivers from rpm packages if (@rpm_list && ($Injectalldriver || @driver_list)) { + # Extract the files from rpm to the tmp dir mkpath "$dd_dir/rpm"; foreach my $rpm (@rpm_list) { if (-r $rpm) { - if (system ("cd $dd_dir/rpm; rpm2cpio $rpm | cpio -idum")) { + if (system("cd $dd_dir/rpm; rpm2cpio $rpm | cpio -idum")) { print "Error: Cannot extract the files from the rpm $rpm.\n"; } } else { @@ -2284,13 +2310,13 @@ sub load_dd() # To skip the conflict of files that some rpm uses the xxx.ko.new as the name of the driver # Change it back to xxx.ko here - $driver_name = "\*ko.new"; + $driver_name = "\*ko.new"; @all_real_path = (); find(\&get_all_path, <$dd_dir/rpm/*>); foreach my $file (@all_real_path) { my $newname = $file; $newname =~ s/\.new$//; - if (system ("mv -f $file $newname")) { + if (system("mv -f $file $newname")) { print "Error: Could not rename $file\n"; } @@ -2298,7 +2324,7 @@ sub load_dd() # Copy the firmware to the rootimage if (-d "$dd_dir/rpm/lib/firmware") { - system ("cp -rf $dd_dir/rpm/lib/firmware $rootimg_dir/lib"); + system("cp -rf $dd_dir/rpm/lib/firmware $rootimg_dir/lib"); } # if $ignorekernelchk is specified, copy all driver files to target kernel dir @@ -2308,73 +2334,77 @@ sub load_dd() if ($path eq "$dd_dir/rpm/lib/modules/$kernelver") { next; } - + unless (-d "$dd_dir/rpm/lib/modules/$kernelver") { mkpath "$dd_dir/rpm/lib/modules/$kernelver"; } - system ("/bin/cp -rf $path/* $dd_dir/rpm/lib/modules/$kernelver"); + system("/bin/cp -rf $path/* $dd_dir/rpm/lib/modules/$kernelver"); } } - + # Copy the drivers to the rootimage if (-d "$dd_dir/rpm/lib/modules/$kernelver") { - #mkpath "$rootimg_dir/lib/modules/$kernelver/updates/"; - if (@driver_list) { - foreach my $driver (@driver_list) { - $driver_name = $driver; - $real_path = ""; - find(\&get_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); - if ($real_path && $real_path =~ m!$dd_dir/rpm(/lib/modules/$kernelver/.*?)[^\/]*$!) { - # remove the old one if existing - @all_real_path = (); - find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); - foreach (@all_real_path) { - if (-r $_) { - unlink ($_); - } - } - - if (! -d "$rootimg_dir$1") { - mkpath "$rootimg_dir$1"; - } - system ("cp -rf $real_path $rootimg_dir$1"); - push @rpm_drivers, $driver; - } else { - print "Warning: cannot find the driver $driver from the driver rpms\n"; - } + + #mkpath "$rootimg_dir/lib/modules/$kernelver/updates/"; + if (@driver_list) { + foreach my $driver (@driver_list) { + $driver_name = $driver; + $real_path = ""; + find(\&get_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); + if ($real_path && $real_path =~ m!$dd_dir/rpm(/lib/modules/$kernelver/.*?)[^\/]*$!) { + + # remove the old one if existing + @all_real_path = (); + find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); + foreach (@all_real_path) { + if (-r $_) { + unlink($_); + } + } + + if (!-d "$rootimg_dir$1") { + mkpath "$rootimg_dir$1"; + } + system("cp -rf $real_path $rootimg_dir$1"); + push @rpm_drivers, $driver; + } else { + print "Warning: cannot find the driver $driver from the driver rpms\n"; + } + } + } elsif ($Injectalldriver) { + + # copy all the drviers to the rootimage + $driver_name = "\*\.ko"; + @all_real_path = (); + find(\&get_all_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); + my @all_drivers = @all_real_path; + foreach my $new_driver (@all_drivers) { + if (basename($new_driver) =~ /\.ko$/) { + + # remove the old one if existing + $driver_name = basename($new_driver); + @all_real_path = (); + find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); + foreach my $old_driver (@all_real_path) { + if (-r $old_driver) { + unlink($old_driver); + } + } + push @rpm_drivers, basename($new_driver); + } + } + + system("cp -rf $dd_dir/rpm/lib/modules/$kernelver $rootimg_dir/lib/modules/"); } - } elsif ($Injectalldriver) { - # copy all the drviers to the rootimage - $driver_name = "\*\.ko"; - @all_real_path = (); - find(\&get_all_path, <$dd_dir/rpm/lib/modules/$kernelver/*>); - my @all_drivers = @all_real_path; - foreach my $new_driver (@all_drivers) { - if (basename($new_driver) =~ /\.ko$/) { - # remove the old one if existing - $driver_name = basename($new_driver); - @all_real_path = (); - find(\&get_all_path, <$rootimg_dir/lib/modules/$kernelver/*>); - foreach my $old_driver (@all_real_path) { - if (-r $old_driver) { - unlink ($old_driver); - } - } - push @rpm_drivers, basename($new_driver); - } - } - - system ("cp -rf $dd_dir/rpm/lib/modules/$kernelver $rootimg_dir/lib/modules/"); - } } else { - print "Warning: cannot find the kernel $kernelver from drvier rpms\n"; + print "Warning: cannot find the kernel $kernelver from drvier rpms\n"; } push @dd_drivers, @rpm_drivers; } - + # Generate the dependency relationship - system ("chroot '$rootimg_dir' depmod $kernelver"); + system("chroot '$rootimg_dir' depmod $kernelver"); # Clean the env rmtree "$dd_dir"; @@ -2383,7 +2413,7 @@ sub load_dd() } sub usage { - print 'Usage: genimage -o [-a ] -p -i -n [-r ] [-k ] [-g ] [-l rootlimitsize] [--permission ] [--interactive]'."\n"; + print 'Usage: genimage -o [-a ] -p -i -n [-r ] [-k ] [-g ] [-l rootlimitsize] [--permission ] [--interactive]' . "\n"; print " --permission is used for statelite only\n"; print "Examples:\n"; print " genimage -i eth0 -n tg3 -o sles11 -p compute\n"; diff --git a/xCAT-server/share/xcat/netboot/sles/genimage.yum b/xCAT-server/share/xcat/netboot/sles/genimage.yum index f0b287a00..50fa742d1 100755 --- a/xCAT-server/share/xcat/netboot/sles/genimage.yum +++ b/xCAT-server/share/xcat/netboot/sles/genimage.yum @@ -6,61 +6,64 @@ use File::Copy; use File::Find; use Getopt::Long; use Cwd qw(realpath); + #use strict; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch = `uname -m`; chomp($arch); if ($arch =~ /i.86$/) { - $arch = x86; + $arch = x86; } my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver ); + #Default to the first kernel found in the install image if nothing specified explicitly. #A more accurate guess than whatever the image build server happens to be running #If specified, that takes precedence. #if image has one, that is used #if all else fails, resort to uname -r like this script did before -my @KVERS= <$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/*>; +my @KVERS = <$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/*>; if (scalar(@KVERS)) { $basekernelver = basename($KVERS[0]); } @@ -68,207 +71,216 @@ unless ($basekernelver) { $basekernelver = `uname -r`; } unless ($kernelver) { - $kernelver=$basekernelver; + $kernelver = $basekernelver; } chomp($kernelver); unless ($osver and $profile and $netdriver and $prinic) { - print 'Usage: genimage -i -n [-r ] -o -p -k '."\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; - exit 1; + print 'Usage: genimage -i -n [-r ] -o -p -k ' . "\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; + exit 1; } my @ndrivers; -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - if (/^$/) { - next; - } - push @ndrivers,$_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + if (/^$/) { + next; + } + push @ndrivers, $_; } -unless (grep /af_packet/,@ndrivers) { - unshift(@ndrivers,"af_packet.ko"); +unless (grep /af_packet/, @ndrivers) { + unshift(@ndrivers, "af_packet.ko"); } unless ($onlyinitrd) { - my $srcdir = "$installroot/$osver/$arch/1"; - find(\&isyumdir, <$srcdir/>); - print Dumper(@yumdirs); - unless (scalar(@yumdirs)) { - #unless ( -d $srcdir."/repodata" ) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + my $srcdir = "$installroot/$osver/$arch/1"; + find(\&isyumdir, <$srcdir/>); + print Dumper(@yumdirs); + unless (scalar(@yumdirs)) { - #this is for extra packages - my $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch/1"; - my $pkgnames=get_extra_package_names(); - #print "extra pkgnames=$pkgnames\n"; + #unless ( -d $srcdir."/repodata" ) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } - my $yumconfig; - open($yumconfig,">","/tmp/genimage.$$.yum.conf"); - my $repnum=0; - foreach $srcdir (@yumdirs) { - print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; - $repnum += 1; - } - $repnum-=1; - #add the section for other packages - if ($pkgnames) { - print $yumconfig "[$osver-$arch-otherpkgs]\nname=$osver-$arch-otherpkgs\nbaseurl=file://$srcdir_otherpkgs\ngpgpcheck=0\n\n"; - } - close($yumconfig); + #this is for extra packages + my $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch/1"; + my $pkgnames = get_extra_package_names(); - mkpath "$installroot/netboot/$osver/$arch/$profile/rootimg/etc"; - mkpath "$installroot/netboot/$osver/$arch/$profile/rootimg/dev"; - #system "mount -o bind /dev $installroot/netboot/$osver/$arch/$profile/rootimg/dev"; - system "mknod $installroot/netboot/$osver/$arch/$profile/rootimg/dev/zero c 1 5"; - open($fd,">>","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); - #system("zypper -R $installroot/netboot/$osver/$arch/$profile/rootimg/ sa file:$srcdir"); - my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$installroot/netboot/$osver/$arch/$profile/rootimg/ "; - my $yumcmd_base = $yumcmd; - $yumcmd .= "install "; - mkpath("$installroot/netboot/$osver/$arch/$profile/rootimg/var/lib/yum"); - #my $yumcmd = "zypper -R $installroot/netboot/$osver/$arch/$profile/rootimg/ install -y "; + #print "extra pkgnames=$pkgnames\n"; - my $pkglist= get_pkglist_file_name($customdir); - if (!$pkglist) { - $pkglist= get_pkglist_file_name($pathtofiles); - } - #print "pkglist=$pkglist\n"; + my $yumconfig; + open($yumconfig, ">", "/tmp/genimage.$$.yum.conf"); + my $repnum = 0; + foreach $srcdir (@yumdirs) { + print $yumconfig "[$osver-$arch-$repnum]\nname=$osver-$arch-$repnum\nbaseurl=file://$srcdir\ngpgpcheck=0\n\n"; + $repnum += 1; + } + $repnum -= 1; - if (!$pkglist) { - print "Unable to find package list for $profile!"; - return 1; - } + #add the section for other packages + if ($pkgnames) { + print $yumconfig "[$osver-$arch-otherpkgs]\nname=$osver-$arch-otherpkgs\nbaseurl=file://$srcdir_otherpkgs\ngpgpcheck=0\n\n"; + } + close($yumconfig); - open($yumconfig,"<","$pkglist"); - while (<$yumconfig>) { - chomp; - $yumcmd .= $_ . " "; - } - close($yumconfig); + mkpath "$installroot/netboot/$osver/$arch/$profile/rootimg/etc"; + mkpath "$installroot/netboot/$osver/$arch/$profile/rootimg/dev"; - #append extra package names to yum command - if ($pkgnames) { - $yumcmd .= " $pkgnames "; - } + #system "mount -o bind /dev $installroot/netboot/$osver/$arch/$profile/rootimg/dev"; + system "mknod $installroot/netboot/$osver/$arch/$profile/rootimg/dev/zero c 1 5"; + open($fd, ">>", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); - $yumcmd =~ s/ $/\n/; - my $rc = system($yumcmd); - if ($rc) { - print "yum invocation failed\n"; - exit 1; - } + #system("zypper -R $installroot/netboot/$osver/$arch/$profile/rootimg/ sa file:$srcdir"); + my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$installroot/netboot/$osver/$arch/$profile/rootimg/ "; + my $yumcmd_base = $yumcmd; + $yumcmd .= "install "; + mkpath("$installroot/netboot/$osver/$arch/$profile/rootimg/var/lib/yum"); - # run yum update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update = $yumcmd_base . " update "; - $yumcmd_update =~ s/ $/\n/; - $rc = system("$yumcmd_update"); - # ignore any return code + #my $yumcmd = "zypper -R $installroot/netboot/$osver/$arch/$profile/rootimg/ install -y "; + + my $pkglist = get_pkglist_file_name($customdir); + if (!$pkglist) { + $pkglist = get_pkglist_file_name($pathtofiles); + } + + #print "pkglist=$pkglist\n"; + + if (!$pkglist) { + print "Unable to find package list for $profile!"; + return 1; + } + + open($yumconfig, "<", "$pkglist"); + while (<$yumconfig>) { + chomp; + $yumcmd .= $_ . " "; + } + close($yumconfig); + + #append extra package names to yum command + if ($pkgnames) { + $yumcmd .= " $pkgnames "; + } + + $yumcmd =~ s/ $/\n/; + my $rc = system($yumcmd); + if ($rc) { + print "yum invocation failed\n"; + exit 1; + } + + # run yum update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update = $yumcmd_base . " update "; + $yumcmd_update =~ s/ $/\n/; + $rc = system("$yumcmd_update"); + + # ignore any return code - postscripts(); #run 'postscripts' + postscripts(); #run 'postscripts' } unlink "/tmp/genimage.$$.yum.conf"; mkinitrd(); sub getlibs { - my $file = shift; - my $liblist = `chroot $installroot/netboot/$osver/$arch/$profile/rootimg ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - next; - } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } - $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + my $file = shift; + my $liblist = `chroot $installroot/netboot/$osver/$arch/$profile/rootimg ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + unless (/=>/) { + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; + } + $temp1 =~ s/^\///; + $libhash{$temp1} = 1; + } } sub mkinitrd { - mkpath("/tmp/xcatinitrd.$$/bin"); - if($basekernelver eq $kernelver) { - rename(<$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz*>,"$installroot/netboot/$osver/$arch/$profile/kernel"); - } - else { - if(-r "$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz-$kernelver") { - rename("$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz-$kernelver","$installroot/netboot/$osver/$arch/$profile/kernel"); - } elsif(-r "/boot/vmlinuz-$kernelver") { - copy("/boot/vmlinuz-$kernelver","$installroot/netboot/$osver/$arch/$profile/kernel"); - } - else { - xdie("Cannot read /boot/vmlinuz-$kernelver"); - } - } - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/tmp"); - mkpath("/tmp/xcatinitrd.$$/var/run"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib/mkinitrd/bin"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhcpcd"); - my $inifile; - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/bin/bash\n"; - print $inifile "mount -t proc /proc /proc\n"; - print $inifile "mount -t sysfs /sys /sys\n"; - print $inifile "mount -o mode=0755 -t tmpfs /dev /dev\n"; - print $inifile "mkdir /dev/pts\n"; - print $inifile "mount -t devpts -o gid=5,mode=620 /dev/pts /dev/pts\n"; - print $inifile "mkdir /dev/shm\n"; - print $inifile "mkdir /dev/mapper\n"; - print $inifile "mknod /dev/null c 1 3\n"; - print $inifile "mknod /dev/zero c 1 5\n"; - print $inifile "mknod /dev/systty c 4 0\n"; - print $inifile "mknod /dev/tty c 5 0\n"; - print $inifile "mknod /dev/console c 5 1\n"; - print $inifile "mknod /dev/ptmx c 5 2\n"; - print $inifile "mknod /dev/rtc c 10 135\n"; - print $inifile "mknod /dev/tty0 c 4 0\n"; - print $inifile "mknod /dev/tty1 c 4 1\n"; - print $inifile "mknod /dev/tty2 c 4 2\n"; - print $inifile "mknod /dev/tty3 c 4 3\n"; - print $inifile "mknod /dev/tty4 c 4 4\n"; - print $inifile "mknod /dev/tty5 c 4 5\n"; - print $inifile "mknod /dev/tty6 c 4 6\n"; - print $inifile "mknod /dev/tty7 c 4 7\n"; - print $inifile "mknod /dev/tty8 c 4 8\n"; - print $inifile "mknod /dev/tty9 c 4 9\n"; - print $inifile "mknod /dev/tty10 c 4 10\n"; - print $inifile "mknod /dev/tty11 c 4 11\n"; - print $inifile "mknod /dev/tty12 c 4 12\n"; - print $inifile "mknod /dev/ttyS0 c 4 64\n"; - print $inifile "mknod /dev/ttyS1 c 4 65\n"; - print $inifile "mknod /dev/ttyS2 c 4 66\n"; - print $inifile "mknod /dev/ttyS3 c 4 67\n"; - foreach (@ndrivers) { - print $inifile "insmod /lib/$_\n"; - } - print $inifile <, "$installroot/netboot/$osver/$arch/$profile/kernel"); + } + else { + if (-r "$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz-$kernelver") { + rename("$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz-$kernelver", "$installroot/netboot/$osver/$arch/$profile/kernel"); + } elsif (-r "/boot/vmlinuz-$kernelver") { + copy("/boot/vmlinuz-$kernelver", "$installroot/netboot/$osver/$arch/$profile/kernel"); + } + else { + xdie("Cannot read /boot/vmlinuz-$kernelver"); + } + } + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/bin"); + mkpath("/tmp/xcatinitrd.$$/usr/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/lib"); + mkpath("/tmp/xcatinitrd.$$/usr/lib64"); + mkpath("/tmp/xcatinitrd.$$/lib/firmware"); + mkpath("/tmp/xcatinitrd.$$/tmp"); + mkpath("/tmp/xcatinitrd.$$/var/run"); + mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); + mkpath("/tmp/xcatinitrd.$$/lib/mkinitrd/bin"); + mkpath("/tmp/xcatinitrd.$$/proc"); + mkpath("/tmp/xcatinitrd.$$/sys"); + mkpath("/tmp/xcatinitrd.$$/dev/mapper"); + mkpath("/tmp/xcatinitrd.$$/sysroot"); + mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); + mkpath("/tmp/xcatinitrd.$$/var/lib/dhcpcd"); + my $inifile; + open($inifile, ">", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/bin/bash\n"; + print $inifile "mount -t proc /proc /proc\n"; + print $inifile "mount -t sysfs /sys /sys\n"; + print $inifile "mount -o mode=0755 -t tmpfs /dev /dev\n"; + print $inifile "mkdir /dev/pts\n"; + print $inifile "mount -t devpts -o gid=5,mode=620 /dev/pts /dev/pts\n"; + print $inifile "mkdir /dev/shm\n"; + print $inifile "mkdir /dev/mapper\n"; + print $inifile "mknod /dev/null c 1 3\n"; + print $inifile "mknod /dev/zero c 1 5\n"; + print $inifile "mknod /dev/systty c 4 0\n"; + print $inifile "mknod /dev/tty c 5 0\n"; + print $inifile "mknod /dev/console c 5 1\n"; + print $inifile "mknod /dev/ptmx c 5 2\n"; + print $inifile "mknod /dev/rtc c 10 135\n"; + print $inifile "mknod /dev/tty0 c 4 0\n"; + print $inifile "mknod /dev/tty1 c 4 1\n"; + print $inifile "mknod /dev/tty2 c 4 2\n"; + print $inifile "mknod /dev/tty3 c 4 3\n"; + print $inifile "mknod /dev/tty4 c 4 4\n"; + print $inifile "mknod /dev/tty5 c 4 5\n"; + print $inifile "mknod /dev/tty6 c 4 6\n"; + print $inifile "mknod /dev/tty7 c 4 7\n"; + print $inifile "mknod /dev/tty8 c 4 8\n"; + print $inifile "mknod /dev/tty9 c 4 9\n"; + print $inifile "mknod /dev/tty10 c 4 10\n"; + print $inifile "mknod /dev/tty11 c 4 11\n"; + print $inifile "mknod /dev/tty12 c 4 12\n"; + print $inifile "mknod /dev/ttyS0 c 4 64\n"; + print $inifile "mknod /dev/ttyS1 c 4 65\n"; + print $inifile "mknod /dev/ttyS2 c 4 66\n"; + print $inifile "mknod /dev/ttyS3 c 4 67\n"; + + foreach (@ndrivers) { + print $inifile "insmod /lib/$_\n"; + } + print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/bin/bash\n"; - print $inifile "dhcpcd $prinic\n"; - print $inifile "echo -n 'search '> /etc/resolv.conf\n"; - print $inifile "grep DOMAIN /var/lib/dhcpcd/*info|awk -F= '{print \$2}'|awk -F\\' '{print \$2}' >> /etc/resolv.conf\n"; - print $inifile "grep HOSTNAME /var/lib/dhcpcd/*info|awk -F= '{print \$2}'|awk -F\\' '{print \$2}' >> /etc/HOSTNAME\n"; - print $inifile "for names in `grep DNS /var/lib/dhcpcd/*info|awk -F= '{print \$2}'`; do\n"; - print $inifile ' echo nameserver $names >> /etc/resolv.conf'."\n"; - print $inifile "done\n"; + print $inifile " exit\n"; + print $inifile "fi\n"; + print $inifile "cd /\n"; + print $inifile "cp /var/lib/dhcpcd/* /sysroot/var/lib/dhcpcd/\n"; + print $inifile "cp /etc/resolv.conf /sysroot/etc/\n"; + print $inifile "cp /etc/HOSTNAME /sysroot/etc/\n"; + print $inifile "mknod /sysroot/dev/console c 5 1\n"; + print $inifile "exec /lib/mkinitrd/bin/run-init -c /dev/console /sysroot /sbin/init\n"; + close($inifile); + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/bin/bash\n"; + print $inifile "dhcpcd $prinic\n"; + print $inifile "echo -n 'search '> /etc/resolv.conf\n"; + print $inifile "grep DOMAIN /var/lib/dhcpcd/*info|awk -F= '{print \$2}'|awk -F\\' '{print \$2}' >> /etc/resolv.conf\n"; + print $inifile "grep HOSTNAME /var/lib/dhcpcd/*info|awk -F= '{print \$2}'|awk -F\\' '{print \$2}' >> /etc/HOSTNAME\n"; + print $inifile "for names in `grep DNS /var/lib/dhcpcd/*info|awk -F= '{print \$2}'`; do\n"; + print $inifile ' echo nameserver $names >> /etc/resolv.conf' . "\n"; + print $inifile "done\n"; - close($inifile); - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - foreach ("usr/bin/grep","bin/cpio","bin/sleep","bin/mount","sbin/dhcpcd","bin/bash","sbin/insmod","bin/mkdir","bin/mknod","sbin/ip","bin/cat","usr/bin/awk","usr/bin/wget","bin/cp","usr/bin/cpio","usr/bin/zcat","lib/mkinitrd/bin/run-init") { - getlibs($_); - push @filestoadd,$_; - } - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - if($basekernelver ne $kernelver) { - system("rm -rf $installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/$basekernelver"); - unless (-d "$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/$kernelver") { - if(-d "/lib/modules/$kernelver") { - system("cd /lib/modules;cp -r $kernelver $installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/"); - } - else { - xdie("Cannot read /lib/modules/$kernelver"); - } + close($inifile); + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + @filestoadd = (); + foreach (@ndrivers) { + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; } - } - find(\&isnetdriver, <$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/$kernelver/*>); - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$installroot/netboot/$osver/$arch/$profile/rootimg/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$installroot/netboot/$osver/$arch/$profile/rootimg/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + } + foreach ("usr/bin/grep", "bin/cpio", "bin/sleep", "bin/mount", "sbin/dhcpcd", "bin/bash", "sbin/insmod", "bin/mkdir", "bin/mknod", "sbin/ip", "bin/cat", "usr/bin/awk", "usr/bin/wget", "bin/cp", "usr/bin/cpio", "usr/bin/zcat", "lib/mkinitrd/bin/run-init") { + getlibs($_); + push @filestoadd, $_; + } + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; + if ($basekernelver ne $kernelver) { + system("rm -rf $installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/$basekernelver"); + unless (-d "$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/$kernelver") { + if (-d "/lib/modules/$kernelver") { + system("cd /lib/modules;cp -r $kernelver $installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/"); + } + else { + xdie("Cannot read /lib/modules/$kernelver"); + } + } + } + find(\&isnetdriver, <$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/$kernelver/*>); + foreach (@filestoadd) { + if (ref($_)) { - #copy("$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $installroot/netboot/$osver/$arch/$profile/initrd.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$installroot/netboot/$osver/$arch/$profile/rootimg/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$installroot/netboot/$osver/$arch/$profile/rootimg/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + + #copy("$installroot/netboot/$osver/$arch/$profile/rootimg/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $installroot/netboot/$osver/$arch/$profile/initrd.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/ and $File::Find::name !~ /patches/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/ and $File::Find::name !~ /patches/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$installroot/netboot/$osver/$arch/$profile/rootimg/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$installroot/netboot/$osver/$arch/$profile/rootimg/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + } + } } - -sub postscripts { # TODO: customized postscripts - generic_post(); - if (-d "$installroot/postscripts/hostkeys") { - for my $key (<$installroot/postscripts/hostkeys/*key>) { - copy ($key,"$installroot/netboot/$osver/$arch/$profile/rootimg/etc/ssh/"); - } - chmod 0600,; - } - if (-d "/$installroot/postscripts/.ssh") { - mkpath("/$installroot/netboot/$osver/$arch/$profile/rootimg/root/.ssh"); - chmod(0700,"/$installroot/netboot/$osver/$arch/$profile/rootimg/root/.ssh/"); - for my $file () { - copy ($file,"/$installroot/netboot/$osver/$arch/$profile/rootimg/root/.ssh/"); - } - chmod(0600,); - } + +sub postscripts { # TODO: customized postscripts + generic_post(); + if (-d "$installroot/postscripts/hostkeys") { + for my $key (<$installroot/postscripts/hostkeys/*key>) { + copy($key, "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/ssh/"); + } + chmod 0600, ; + } + if (-d "/$installroot/postscripts/.ssh") { + mkpath("/$installroot/netboot/$osver/$arch/$profile/rootimg/root/.ssh"); + chmod(0700, "/$installroot/netboot/$osver/$arch/$profile/rootimg/root/.ssh/"); + for my $file () { + copy($file, "/$installroot/netboot/$osver/$arch/$profile/rootimg/root/.ssh/"); + } + chmod(0600, ); + } } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$installroot/netboot/$osver/$arch/$profile/rootimg/dev/null"); - system("mknod $installroot/netboot/$osver/$arch/$profile/rootimg/dev/null c 1 3"); - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; - } - close($cfgfile); - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - open($cfgfile,">>","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - my @passwd; - open($cfgfile,"<","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$installroot/netboot/$osver/$arch/$profile/rootimg/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$installroot/netboot/$osver/$arch/$profile/rootimg/root/"; - } - open($cfgfile,">","$installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - print $cfgfile "/etc/init.d/boot.localnet start\n"; - print $cfgfile "/opt/xcat/xcatdsklspost\n"; - close($cfgfile); - chmod(0755,"$installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/gettyset"); - #link("$installroot/netboot/$osver/$arch/$profile/rootimg/sbin/init","$installroot/netboot/$osver/$arch/$profile/rootimg/init"); - my $rc = system("grep sshd $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); - if ($rc) { - system("sed -i '".'s/^\(TARGETS = .*\)$/\1 sshd/'."' $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); - system("ln -s ../sshd $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/rc3.d/S20sshd"); - } - my $rc = system("grep gettyset $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); - if ($rc) { - system("sed -i '".'s/^\(TARGETS = .*\)$/\1 gettyset/'."' $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); - system("ln -s ../gettyset $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/rc3.d/S60gettyset"); - } - rename(<$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz*>,"$installroot/netboot/$osver/$arch/$profile/kernel"); + my $cfgfile; + unlink("$installroot/netboot/$osver/$arch/$profile/rootimg/dev/null"); + system("mknod $installroot/netboot/$osver/$arch/$profile/rootimg/dev/null c 1 3"); + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; + } + close($cfgfile); + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } + open($cfgfile, ">>", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + my @passwd; + open($cfgfile, "<", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/passwd"); + + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$installroot/netboot/$osver/$arch/$profile/rootimg/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$installroot/netboot/$osver/$arch/$profile/rootimg/root/"; + } + open($cfgfile, ">", "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + print $cfgfile "/etc/init.d/boot.localnet start\n"; + print $cfgfile "/opt/xcat/xcatdsklspost\n"; + close($cfgfile); + chmod(0755, "$installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/gettyset"); + + #link("$installroot/netboot/$osver/$arch/$profile/rootimg/sbin/init","$installroot/netboot/$osver/$arch/$profile/rootimg/init"); + my $rc = system("grep sshd $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); + if ($rc) { + system("sed -i '" . 's/^\(TARGETS = .*\)$/\1 sshd/' . "' $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); + system("ln -s ../sshd $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/rc3.d/S20sshd"); + } + my $rc = system("grep gettyset $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); + if ($rc) { + system("sed -i '" . 's/^\(TARGETS = .*\)$/\1 gettyset/' . "' $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/.depend.start"); + system("ln -s ../gettyset $installroot/netboot/$osver/$arch/$profile/rootimg/etc/init.d/rc3.d/S60gettyset"); + } + rename(<$installroot/netboot/$osver/$arch/$profile/rootimg/boot/vmlinuz*>, "$installroot/netboot/$osver/$arch/$profile/kernel"); } #get th extra package name sub get_extra_package_names { - my $otherpkglist=get_extra_pkglist_file_name($customdir); - if (!$otherpkglist) { $otherpkglist=get_extra_pkglist_file_name($pathtofiles); } - my $pkgnames; + my $otherpkglist = get_extra_pkglist_file_name($customdir); + if (!$otherpkglist) { $otherpkglist = get_extra_pkglist_file_name($pathtofiles); } + my $pkgnames; - if ($otherpkglist) { - my $pkgfile; - open($pkgfile,"<","$otherpkglist"); - while (<$pkgfile>) { - chomp; - $pkgnames .= $_ . " "; - } - close($pkgfile); - } + if ($otherpkglist) { + my $pkgfile; + open($pkgfile, "<", "$otherpkglist"); + while (<$pkgfile>) { + chomp; + $pkgnames .= $_ . " "; + } + close($pkgfile); + } - return $pkgnames; + return $pkgnames; } sub get_extra_pkglist_file_name { - my $base=shift; - if (-r "$base/$profile.$osver.$arch.otherpkgs.pkglist") { - return "$base/$profile.$osver.$arch.otherpkgs.pkglist"; - } elsif (-r "$base/$profile.$arch.otherpkgs.pkglist") { - return "$base/$profile.$arch.otherpkgs.pkglist"; - } elsif (-r "$base/$profile.$osver.otherpkgs.pkglist") { - return "$base/$profile.$osver.otherpkgs.pkglist"; - } elsif (-r "$base/$profile.otherpkgs.pkglist") { - return "$base/$profile.otherpkgs.pkglist"; - } - return ""; + my $base = shift; + if (-r "$base/$profile.$osver.$arch.otherpkgs.pkglist") { + return "$base/$profile.$osver.$arch.otherpkgs.pkglist"; + } elsif (-r "$base/$profile.$arch.otherpkgs.pkglist") { + return "$base/$profile.$arch.otherpkgs.pkglist"; + } elsif (-r "$base/$profile.$osver.otherpkgs.pkglist") { + return "$base/$profile.$osver.otherpkgs.pkglist"; + } elsif (-r "$base/$profile.otherpkgs.pkglist") { + return "$base/$profile.otherpkgs.pkglist"; + } + return ""; } sub get_pkglist_file_name { - my $base=shift; - if (-r "$base/$profile.$osver.$arch.pkglist") { - return "$base/$profile.$osver.$arch.pkglist"; - } elsif (-r "$base/$profile.$arch.pkglist") { - return "$base/$profile.$arch.pkglist"; - } elsif (-r "$base/$profile.$osver.pkglist") { - return "$base/$profile.$osver.pkglist"; - } elsif (-r "$base/$profile.pkglist") { - return "$base/$profile.pkglist"; - } + my $base = shift; + if (-r "$base/$profile.$osver.$arch.pkglist") { + return "$base/$profile.$osver.$arch.pkglist"; + } elsif (-r "$base/$profile.$arch.pkglist") { + return "$base/$profile.$arch.pkglist"; + } elsif (-r "$base/$profile.$osver.pkglist") { + return "$base/$profile.$osver.pkglist"; + } elsif (-r "$base/$profile.pkglist") { + return "$base/$profile.pkglist"; + } - return ""; + return ""; } diff --git a/xCAT-server/share/xcat/netboot/suse/genimage b/xCAT-server/share/xcat/netboot/suse/genimage index 69f06c020..ffd157a3c 100755 --- a/xCAT-server/share/xcat/netboot/suse/genimage +++ b/xCAT-server/share/xcat/netboot/suse/genimage @@ -11,12 +11,13 @@ use File::Copy; use File::Find; use Getopt::Long; use Cwd qw(realpath); + #use strict; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -24,20 +25,21 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + #that this method of calling genimage is no longer used if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -50,8 +52,8 @@ my $rootimg_dir; my $noupdate; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + die @_; } #-- fetch current version form CVS (overwrite locally changed versions) @@ -71,110 +73,111 @@ sub xdie { $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'onlyinitrd' =>\$onlyinitrd, - 'noupdate' => \$noupdate, + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'onlyinitrd' => \$onlyinitrd, + 'noupdate' => \$noupdate, ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; if ($arch or $osver or $profile) { - print "-o, -p and -a options are not allowed when a image name is specified.\n"; + print "-o, -p and -a options are not allowed when a image name is specified.\n"; exit 1; } + #load the module in memory - eval {require("$::XCATROOT/lib/perl/xCAT/Table.pm")}; + eval { require("$::XCATROOT/lib/perl/xCAT/Table.pm") }; if ($@) { - print $@; - exit 1; - } - - #get the info from the osimage and linux - my $osimagetab=xCAT::Table->new('osimage', -create=>1); - if (!$osimagetab) { - print "The osimage table cannot be opened.\n"; - exit 1; - } - my $linuximagetab=xCAT::Table->new('linuximage', -create=>1); - if (!$linuximagetab) { - print "The linuximage table cannot be opened.\n"; - exit 1; - } - (my $ref) = $osimagetab->getAttribs({imagename => $imagename}, 'osvers', 'osarch', 'profile', 'provmethod'); - if (!$ref) { - print "Cannot find image \'$imagename\' from the osimage table.\n"; - exit 1; - } - (my $ref1) = $linuximagetab->getAttribs({imagename => $imagename}, 'pkglist', 'pkgdir', 'otherpkglist', 'otherpkgdir', 'postinstall', 'rootimgdir'); - if (!$ref1) { - print "Cannot find $imagename from the linuximage table\n"; - exit 1; + print $@; + exit 1; } - $osver=$ref->{'osvers'}; - $arch=$ref->{'osarch'}; - $profile=$ref->{'profile'}; - my $provmethod=$ref->{'provmethod'}; - + #get the info from the osimage and linux + my $osimagetab = xCAT::Table->new('osimage', -create => 1); + if (!$osimagetab) { + print "The osimage table cannot be opened.\n"; + exit 1; + } + my $linuximagetab = xCAT::Table->new('linuximage', -create => 1); + if (!$linuximagetab) { + print "The linuximage table cannot be opened.\n"; + exit 1; + } + (my $ref) = $osimagetab->getAttribs({ imagename => $imagename }, 'osvers', 'osarch', 'profile', 'provmethod'); + if (!$ref) { + print "Cannot find image \'$imagename\' from the osimage table.\n"; + exit 1; + } + (my $ref1) = $linuximagetab->getAttribs({ imagename => $imagename }, 'pkglist', 'pkgdir', 'otherpkglist', 'otherpkgdir', 'postinstall', 'rootimgdir'); + if (!$ref1) { + print "Cannot find $imagename from the linuximage table\n"; + exit 1; + } + + $osver = $ref->{'osvers'}; + $arch = $ref->{'osarch'}; + $profile = $ref->{'profile'}; + my $provmethod = $ref->{'provmethod'}; + unless ($osver and $arch and $profile and $provmethod) { - print"osimage.osvers, osimage.osarch, osimage.profile and osimage.provmethod must be specified for the image $imagename in the database.\n"; - exit 1; + print "osimage.osvers, osimage.osarch, osimage.profile and osimage.provmethod must be specified for the image $imagename in the database.\n"; + exit 1; } if ($provmethod ne 'netboot') { - print "\'$imagename\' cannot be used to build diskless image. Make sure osimage.provmethod is 'netboot'."; - exit 1; + print "\'$imagename\' cannot be used to build diskless image. Make sure osimage.provmethod is 'netboot'."; + exit 1; } - if (! $ref1->{'pkglist'}) { - print"A .pkglist file must be specified for image \'$imagename\' in the linuximage table.\n"; + if (!$ref1->{'pkglist'}) { + print "A .pkglist file must be specified for image \'$imagename\' in the linuximage table.\n"; exit 0; } - $pkglist =$ref1->{'pkglist'}; + $pkglist = $ref1->{'pkglist'}; - $srcdir=$ref1->{'pkgdir'}; - if ($srcdir) { $srcdir="$srcdir/1"; } - $srcdir_otherpkgs=$ref1->{'otherpkgdir'}; - $otherpkglist=$ref1->{'otherpkglist'}; - $postinstall_filename=$ref1->{'postinstall'}; - $destdir=$ref1->{'rootimgdir'}; + $srcdir = $ref1->{'pkgdir'}; + if ($srcdir) { $srcdir = "$srcdir/1"; } + $srcdir_otherpkgs = $ref1->{'otherpkgdir'}; + $otherpkglist = $ref1->{'otherpkglist'}; + $postinstall_filename = $ref1->{'postinstall'}; + $destdir = $ref1->{'rootimgdir'}; } if (!$arch) { $arch = `uname -m`; chomp($arch); if ($arch =~ /i.86$/) { - $arch = "x86"; + $arch = "x86"; } } -if (!$srcdir) { - $srcdir="$installroot/$osver/$arch/1"; +if (!$srcdir) { + $srcdir = "$installroot/$osver/$arch/1"; } -if (!$srcdir_otherpkgs) { - $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch"; +if (!$srcdir_otherpkgs) { + $srcdir_otherpkgs = "$installroot/post/otherpkgs/$osver/$arch"; } if (!$destdir) { - $destdir="$installroot/netboot/$osver/$arch/$profile"; + $destdir = "$installroot/netboot/$osver/$arch/$profile"; } -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; #Default to the first kernel found in the install image if nothing specified explicitly. #A more accurate guess than whatever the image build server happens to be running #If specified, that takes precedence. #if image has one, that is used #if all else fails, resort to uname -r like this script did before -my @KVERS= <$rootimg_dir/lib/modules/*>; +my @KVERS = <$rootimg_dir/lib/modules/*>; if (scalar(@KVERS)) { $basekernelver = basename($KVERS[0]); } @@ -182,350 +185,357 @@ unless ($basekernelver) { $basekernelver = `uname -r`; } unless ($kernelver) { - $kernelver=$basekernelver; + $kernelver = $basekernelver; } chomp($kernelver); unless ($osver and $profile and $netdriver and $prinic) { - print 'Usage: genimage -i -n [-r ] -k -o -p -a '."\n"; - print ' genimage -i -n [-r ] -k '."\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; - print " genimage -i eth0 -ntg3 myimagename\n"; - exit 1; + print 'Usage: genimage -i -n [-r ] -k -o -p -a ' . "\n"; + print ' genimage -i -n [-r ] -k ' . "\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute\n"; + print " genimage -i eth0 -ntg3 myimagename\n"; + exit 1; } my @ndrivers; -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - if (/^$/) { - next; - } - push @ndrivers,$_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + if (/^$/) { + next; + } + push @ndrivers, $_; } -unless (grep /af_packet/,@ndrivers) { - unshift(@ndrivers,"af_packet.ko"); +unless (grep /af_packet/, @ndrivers) { + unshift(@ndrivers, "af_packet.ko"); } my $osver_host; -if(`grep VERSION /etc/SuSE-release` =~ /VERSION = (\d+)/) { - $osver_host=$1; +if (`grep VERSION /etc/SuSE-release` =~ /VERSION = (\d+)/) { + $osver_host = $1; } else { - $osver_host=11; + $osver_host = 11; } unless ($onlyinitrd) { - my %extra_hash=get_extra_package_names(); + my %extra_hash = get_extra_package_names(); - mkpath "$rootimg_dir/etc"; - mkpath "$rootimg_dir/dev"; - #system "mount -o bind /dev $rootimg_dir/dev"; - system "mknod $rootimg_dir/dev/zero c 1 5"; - system "mknod $rootimg_dir/dev/null c 1 3"; #that's neccessary for SLES11 - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for rpm postscripts to see\n"; - close($fd); - if($osver_host == 11) {#zypper in SLES11 is different - if(-e "$rootimg_dir/etc/zypp/repos.d/$osver.repo") { - system("rm -rf $rootimg_dir/etc/zypp/repos.d/$osver.repo"); - } - system("zypper -R $rootimg_dir ar file:$srcdir $osver"); - }else { - system("zypper -R $rootimg_dir sa file:$srcdir"); - } + mkpath "$rootimg_dir/etc"; + mkpath "$rootimg_dir/dev"; - #remove the old repository for extra packages - my $result=`zypper -R $rootimg_dir sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; - if ($result =~ /\S/) { - system("zypper -R $rootimg_dir sd $result"); - } - - #add the new repository for extra packages - my $extrapkgnames; - if($osver_host == 11) { #SLES11 - if(-e "$rootimg_dir/etc/zypp/repos.d/otherpkg.repo") { - system("rm -rf $rootimg_dir/etc/zypp/repos.d/otherpkg.repo"); - } - } - my $index=1; - foreach (keys(%extra_hash)) { - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next;} - my $whole_path="$srcdir_otherpkgs/$_"; - if (-r "$srcdir_otherpkgs/$_/repodata/repomd.xml") { - if($osver_host == 11) { - system("zypper -R $rootimg_dir ar file:$srcdir_otherpkgs/$_ otherpkg$index"); - }else { - system("zypper -R $rootimg_dir sa file:$srcdir_otherpkgs/$_"); - } - } else { - if($osver_host == 11) { - system("zypper -R $rootimg_dir ar -t Plaindir file:$srcdir_otherpkgs/$_ otherpkg$index"); - }else { - system("zypper -R $rootimg_dir sa -t Plaindir file:$srcdir_otherpkgs/$_"); - } - } - $index++; - - my $pa=$extra_hash{$_}; - $extrapkgnames .= " " . join(' ', @$pa); - } - - #-- add custom repositories to the image - my $repolist; - if ( -r "$pathtofiles/$profile.$osver.$arch.repolist") { - $repolist = "$pathtofiles/$profile.$osver.$arch.repolist"; - }elsif ( -r "$pathtofiles/$profile.$osver.repolist") { - $repolist = "$pathtofiles/$profile.$osver.repolist"; - }elsif ( -r "$pathtofiles/$profile.repolist") { - $repolist = "$pathtofiles/$profile.repolist"; - } - - if ( -r "$repolist") { - print "Reading custom repositories\n"; - open($repoconfig,"<","$repolist"); - while (<$repoconfig>) { - chomp; - next if /^\s*#/; - my ($repotype,$repourl,$repoalias) = split m/\|/; - system("zypper -R $rootimg_dir ar $repourl $repoalias"); - } - } - - - # Refresh the zypper cache in case there is still old data out there - system("zypper -R $rootimg_dir refresh"); - - #my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir --disablerepo=* "; - #$yumcmd .= "install "; - #mkpath("$rootimg_dir/var/lib/yum"); - my $yumcmd; - if($osver =~ /suse11/ && $osver_host == 11) { - $yumcmd = "zypper -R $rootimg_dir install -l "; #add -l for SLES11 - }else { - $yumcmd = "zypper -R $rootimg_dir install "; - } - if (!$imagename) { - $pkglist= get_pkglist_file_name($customdir); - if (!$pkglist) { - $pkglist= get_pkglist_file_name($pathtofiles); - } - } - #print "pkglist=$pkglist\n"; - - if (!$pkglist) { - print "Unable to find package list for $profile!"; - exit 1; - } - - my $pkgnames; - open($yumconfig,"<","$pkglist"); - while (<$yumconfig>) { - chomp; - s/\s*#.*//; #-- remove comments - next if /^\s*$/; #-- skip empty lines - $pkgnames .= $_ . " "; - } - close($yumconfig); - - - #$yumcmd =~ s/ $/\n/; - #print "$yumcmd $pkgnames\n"; - my $rc = system("$yumcmd $pkgnames"); - if ($rc) { - print "zypper invocation failed\n"; - exit 1; - } - - #remove the packages that are specified in the otherpkgs.list files with leading '-' - my $yumcmd_remove= "zypper -R $rootimg_dir remove "; - if ((%extra_hash) && (exists ($extra_hash{'PRE_REMOVE'}))) { - my $pa=$extra_hash{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - $rc = system("$yumcmd_remove $rm_packges"); - } - } - - #add extra packages in the list - if ($extrapkgnames) { - #print "$yumcmd $extrapkgnames\n"; - $rc = system("$yumcmd $extrapkgnames"); - if ($rc) { - print "zypper invocation failed\n"; - exit 1; - } - } - - #remove the packages that are specified in the otherpkgs.list files with leading '--' - if ((%extra_hash) && (exists ($extra_hash{'POST_REMOVE'}))) { - my $pa=$extra_hash{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - $rc = system("$yumcmd_remove $rm_packges"); - } - - if (!$noupdate) { - # run zypper update to update any installed rpms - # needed when running genimage again after updating software in repositories - my $yumcmd_update = "zypper -R $rootimg_dir update "; - $rc = system("$yumcmd_update"); - # ignore any return code - } - - - postscripts(); #run 'postscripts' -} -unlink "/tmp/genimage.$$.yum.conf"; - -#-- run postinstall script -if (!$imagename) { - $postinstall_filename= get_postinstall_file_name($customdir); - if (!$postinstall_filename) { - $postinstall_filename= get_postinstall_file_name($pathtofiles); - } -} - -if ( $postinstall_filename ) { - - my @postinstalls = split /,/, $postinstall_filename; - foreach my $postinstall ( split /,/, $postinstall_filename ) { - if ( !-x $postinstall ) { - print "postinstall script $postinstall is not executable\n"; - exit 1; + #system "mount -o bind /dev $rootimg_dir/dev"; + system "mknod $rootimg_dir/dev/zero c 1 5"; + system "mknod $rootimg_dir/dev/null c 1 3"; #that's neccessary for SLES11 + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for rpm postscripts to see\n"; + close($fd); + if ($osver_host == 11) { #zypper in SLES11 is different + if (-e "$rootimg_dir/etc/zypp/repos.d/$osver.repo") { + system("rm -rf $rootimg_dir/etc/zypp/repos.d/$osver.repo"); } - my $rc = system($postinstall, $rootimg_dir,$osver,$arch,$profile); - if($rc) { - print "postinstall script $postinstall failed\n"; + system("zypper -R $rootimg_dir ar file:$srcdir $osver"); + } else { + system("zypper -R $rootimg_dir sa file:$srcdir"); + } + + #remove the old repository for extra packages + my $result = `zypper -R $rootimg_dir sl |grep otherpkg|cut -f2 -d '|'|tr "\n" " "`; + if ($result =~ /\S/) { + system("zypper -R $rootimg_dir sd $result"); + } + + #add the new repository for extra packages + my $extrapkgnames; + if ($osver_host == 11) { #SLES11 + if (-e "$rootimg_dir/etc/zypp/repos.d/otherpkg.repo") { + system("rm -rf $rootimg_dir/etc/zypp/repos.d/otherpkg.repo"); + } + } + my $index = 1; + foreach (keys(%extra_hash)) { + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE")) { next; } + my $whole_path = "$srcdir_otherpkgs/$_"; + if (-r "$srcdir_otherpkgs/$_/repodata/repomd.xml") { + if ($osver_host == 11) { + system("zypper -R $rootimg_dir ar file:$srcdir_otherpkgs/$_ otherpkg$index"); + } else { + system("zypper -R $rootimg_dir sa file:$srcdir_otherpkgs/$_"); + } + } else { + if ($osver_host == 11) { + system("zypper -R $rootimg_dir ar -t Plaindir file:$srcdir_otherpkgs/$_ otherpkg$index"); + } else { + system("zypper -R $rootimg_dir sa -t Plaindir file:$srcdir_otherpkgs/$_"); + } + } + $index++; + + my $pa = $extra_hash{$_}; + $extrapkgnames .= " " . join(' ', @$pa); + } + + #-- add custom repositories to the image + my $repolist; + if (-r "$pathtofiles/$profile.$osver.$arch.repolist") { + $repolist = "$pathtofiles/$profile.$osver.$arch.repolist"; + } elsif (-r "$pathtofiles/$profile.$osver.repolist") { + $repolist = "$pathtofiles/$profile.$osver.repolist"; + } elsif (-r "$pathtofiles/$profile.repolist") { + $repolist = "$pathtofiles/$profile.repolist"; + } + + if (-r "$repolist") { + print "Reading custom repositories\n"; + open($repoconfig, "<", "$repolist"); + while (<$repoconfig>) { + chomp; + next if /^\s*#/; + my ($repotype, $repourl, $repoalias) = split m/\|/; + system("zypper -R $rootimg_dir ar $repourl $repoalias"); + } + } + + + # Refresh the zypper cache in case there is still old data out there + system("zypper -R $rootimg_dir refresh"); + + #my $yumcmd = "yum -y -c /tmp/genimage.$$.yum.conf --installroot=$rootimg_dir --disablerepo=* "; + #$yumcmd .= "install "; + #mkpath("$rootimg_dir/var/lib/yum"); + my $yumcmd; + if ($osver =~ /suse11/ && $osver_host == 11) { + $yumcmd = "zypper -R $rootimg_dir install -l "; #add -l for SLES11 + } else { + $yumcmd = "zypper -R $rootimg_dir install "; + } + if (!$imagename) { + $pkglist = get_pkglist_file_name($customdir); + if (!$pkglist) { + $pkglist = get_pkglist_file_name($pathtofiles); + } + } + + #print "pkglist=$pkglist\n"; + + if (!$pkglist) { + print "Unable to find package list for $profile!"; + exit 1; + } + + my $pkgnames; + open($yumconfig, "<", "$pkglist"); + while (<$yumconfig>) { + chomp; + s/\s*#.*//; #-- remove comments + next if /^\s*$/; #-- skip empty lines + $pkgnames .= $_ . " "; + } + close($yumconfig); + + + #$yumcmd =~ s/ $/\n/; + #print "$yumcmd $pkgnames\n"; + my $rc = system("$yumcmd $pkgnames"); + if ($rc) { + print "zypper invocation failed\n"; + exit 1; + } + + #remove the packages that are specified in the otherpkgs.list files with leading '-' + my $yumcmd_remove = "zypper -R $rootimg_dir remove "; + if ((%extra_hash) && (exists($extra_hash{'PRE_REMOVE'}))) { + my $pa = $extra_hash{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + $rc = system("$yumcmd_remove $rm_packges"); + } + } + + #add extra packages in the list + if ($extrapkgnames) { + + #print "$yumcmd $extrapkgnames\n"; + $rc = system("$yumcmd $extrapkgnames"); + if ($rc) { + print "zypper invocation failed\n"; exit 1; } } -} -#some rpms mounts the imageroot/proc on the /proc, need to release it, -#otherwise got kernal panic when installing -#sometimes, the proc fs is not mounted, so one warning/error message will display, -#and I add one check point here. -my $MTABFD; -open MTABFD, "/etc/mtab"; -my @lines = ; -close MTABFD; + #remove the packages that are specified in the otherpkgs.list files with leading '--' + if ((%extra_hash) && (exists($extra_hash{'POST_REMOVE'}))) { + my $pa = $extra_hash{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + $rc = system("$yumcmd_remove $rm_packges"); + } -my $ret = grep m{$rootimg_dir/proc}, @lines; -if($ret > 0) { - system("umount $rootimg_dir/proc"); -} + if (!$noupdate) { -mkinitrd(); + # run zypper update to update any installed rpms + # needed when running genimage again after updating software in repositories + my $yumcmd_update = "zypper -R $rootimg_dir update "; + $rc = system("$yumcmd_update"); + + # ignore any return code + } + + + postscripts(); #run 'postscripts' + } + unlink "/tmp/genimage.$$.yum.conf"; + + #-- run postinstall script + if (!$imagename) { + $postinstall_filename = get_postinstall_file_name($customdir); + if (!$postinstall_filename) { + $postinstall_filename = get_postinstall_file_name($pathtofiles); + } + } + + if ($postinstall_filename) { + + my @postinstalls = split /,/, $postinstall_filename; + foreach my $postinstall (split /,/, $postinstall_filename) { + if (!-x $postinstall) { + print "postinstall script $postinstall is not executable\n"; + exit 1; + } + my $rc = system($postinstall, $rootimg_dir, $osver, $arch, $profile); + if ($rc) { + print "postinstall script $postinstall failed\n"; + exit 1; + } + } + } + + #some rpms mounts the imageroot/proc on the /proc, need to release it, + #otherwise got kernal panic when installing + #sometimes, the proc fs is not mounted, so one warning/error message will display, + #and I add one check point here. + my $MTABFD; + open MTABFD, "/etc/mtab"; + my @lines = ; + close MTABFD; + + my $ret = grep m{$rootimg_dir/proc}, @lines; + if ($ret > 0) { + system("umount $rootimg_dir/proc"); + } + + mkinitrd(); } sub getlibs { - my $file = shift; - my $liblist = `chroot $rootimg_dir ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - next; - } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } - $temp1 =~ s/^\///; - $libhash{$temp1}=1; - } + my $file = shift; + my $liblist = `chroot $rootimg_dir ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + unless (/=>/) { + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; + } + $temp1 =~ s/^\///; + $libhash{$temp1} = 1; + } } sub mkinitrd { - mkpath("/tmp/xcatinitrd.$$/bin"); - if($basekernelver eq $kernelver) { + mkpath("/tmp/xcatinitrd.$$/bin"); + if ($basekernelver eq $kernelver) { if (-f "$rootimg_dir/boot/vmlinuz-$kernelver") { - rename(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); - } elsif (-f "$rootimg_dir/boot/vmlinux-$kernelver"){ - rename(<$rootimg_dir/boot/vmlinux*>,"$destdir/kernel"); - } + rename(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); + } elsif (-f "$rootimg_dir/boot/vmlinux-$kernelver") { + rename(<$rootimg_dir/boot/vmlinux*>, "$destdir/kernel"); } - else { - if(-r "$rootimg_dir/boot/vmlinuz-$kernelver") { - rename("$rootimg_dir/boot/vmlinuz-$kernelver","$destdir/kernel"); - } elsif(-r "$rootimg_dir/boot/vmlinux-$kernelver") { - rename("$rootimg_dir/boot/vmlinux-$kernelver","$destdir/kernel"); - } elsif(-r "/boot/vmlinuz-$kernelver") { - copy("/boot/vmlinuz-$kernelver","$destdir/kernel"); - } elsif(-r "/boot/vmlinux-$kernelver") {#for SLES10,11 - copy("/boot/vmlinux-$kernelver","$destdir/kernel"); - } - else { - xdie("Cannot read /boot/vmlinuz-$kernelver"); - } - } - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/tmp"); - mkpath("/tmp/xcatinitrd.$$/var/run"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - if($osver =~ /sles/ && $arch eq "ppc64") {#SLES for Power6 - mkpath("/tmp/xcatinitrd.$$/lib64/power6"); - } - mkpath("/tmp/xcatinitrd.$$/lib/power6");#SLES10 - mkpath("/tmp/xcatinitrd.$$/lib/mkinitrd/bin"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhcpcd"); - my $inifile; - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/bin/bash -x\n"; - print $inifile "mount -t proc /proc /proc\n"; - print $inifile "mount -t sysfs /sys /sys\n"; - print $inifile "mount -o mode=0755 -t tmpfs /dev /dev\n"; - print $inifile "mkdir /dev/pts\n"; - print $inifile "mount -t devpts -o gid=5,mode=620 /dev/pts /dev/pts\n"; - print $inifile "mkdir /dev/shm\n"; - print $inifile "mkdir /dev/mapper\n"; + } + else { + if (-r "$rootimg_dir/boot/vmlinuz-$kernelver") { + rename("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } elsif (-r "$rootimg_dir/boot/vmlinux-$kernelver") { + rename("$rootimg_dir/boot/vmlinux-$kernelver", "$destdir/kernel"); + } elsif (-r "/boot/vmlinuz-$kernelver") { + copy("/boot/vmlinuz-$kernelver", "$destdir/kernel"); + } elsif (-r "/boot/vmlinux-$kernelver") { #for SLES10,11 + copy("/boot/vmlinux-$kernelver", "$destdir/kernel"); + } + else { + xdie("Cannot read /boot/vmlinuz-$kernelver"); + } + } + symlink("bin", "/tmp/xcatinitrd.$$/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/bin"); + mkpath("/tmp/xcatinitrd.$$/usr/sbin"); + mkpath("/tmp/xcatinitrd.$$/usr/lib"); + mkpath("/tmp/xcatinitrd.$$/usr/lib64"); + mkpath("/tmp/xcatinitrd.$$/lib/firmware"); + mkpath("/tmp/xcatinitrd.$$/tmp"); + mkpath("/tmp/xcatinitrd.$$/var/run"); + mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - print $inifile "mknod /dev/random c 1 8\n"; - print $inifile "mknod /dev/urandom c 1 9\n"; - print $inifile "mknod /dev/null c 1 3\n"; - print $inifile "mknod /dev/zero c 1 5\n"; - print $inifile "mknod /dev/systty c 4 0\n"; - print $inifile "mknod /dev/tty c 5 0\n"; - print $inifile "mknod /dev/console c 5 1\n"; - print $inifile "mknod /dev/ptmx c 5 2\n"; - print $inifile "mknod /dev/rtc c 10 135\n"; - print $inifile "mknod /dev/tty0 c 4 0\n"; - print $inifile "mknod /dev/tty1 c 4 1\n"; - print $inifile "mknod /dev/tty2 c 4 2\n"; - print $inifile "mknod /dev/tty3 c 4 3\n"; - print $inifile "mknod /dev/tty4 c 4 4\n"; - print $inifile "mknod /dev/tty5 c 4 5\n"; - print $inifile "mknod /dev/tty6 c 4 6\n"; - print $inifile "mknod /dev/tty7 c 4 7\n"; - print $inifile "mknod /dev/tty8 c 4 8\n"; - print $inifile "mknod /dev/tty9 c 4 9\n"; - print $inifile "mknod /dev/tty10 c 4 10\n"; - print $inifile "mknod /dev/tty11 c 4 11\n"; - print $inifile "mknod /dev/tty12 c 4 12\n"; - print $inifile "mknod /dev/ttyS0 c 4 64\n"; - print $inifile "mknod /dev/ttyS1 c 4 65\n"; - print $inifile "mknod /dev/ttyS2 c 4 66\n"; - print $inifile "mknod /dev/ttyS3 c 4 67\n"; - foreach (@ndrivers) { - print $inifile "insmod /lib/$_\n"; - } - print $inifile <", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/bin/bash -x\n"; + print $inifile "mount -t proc /proc /proc\n"; + print $inifile "mount -t sysfs /sys /sys\n"; + print $inifile "mount -o mode=0755 -t tmpfs /dev /dev\n"; + print $inifile "mkdir /dev/pts\n"; + print $inifile "mount -t devpts -o gid=5,mode=620 /dev/pts /dev/pts\n"; + print $inifile "mkdir /dev/shm\n"; + print $inifile "mkdir /dev/mapper\n"; + + print $inifile "mknod /dev/random c 1 8\n"; + print $inifile "mknod /dev/urandom c 1 9\n"; + print $inifile "mknod /dev/null c 1 3\n"; + print $inifile "mknod /dev/zero c 1 5\n"; + print $inifile "mknod /dev/systty c 4 0\n"; + print $inifile "mknod /dev/tty c 5 0\n"; + print $inifile "mknod /dev/console c 5 1\n"; + print $inifile "mknod /dev/ptmx c 5 2\n"; + print $inifile "mknod /dev/rtc c 10 135\n"; + print $inifile "mknod /dev/tty0 c 4 0\n"; + print $inifile "mknod /dev/tty1 c 4 1\n"; + print $inifile "mknod /dev/tty2 c 4 2\n"; + print $inifile "mknod /dev/tty3 c 4 3\n"; + print $inifile "mknod /dev/tty4 c 4 4\n"; + print $inifile "mknod /dev/tty5 c 4 5\n"; + print $inifile "mknod /dev/tty6 c 4 6\n"; + print $inifile "mknod /dev/tty7 c 4 7\n"; + print $inifile "mknod /dev/tty8 c 4 8\n"; + print $inifile "mknod /dev/tty9 c 4 9\n"; + print $inifile "mknod /dev/tty10 c 4 10\n"; + print $inifile "mknod /dev/tty11 c 4 11\n"; + print $inifile "mknod /dev/tty12 c 4 12\n"; + print $inifile "mknod /dev/ttyS0 c 4 64\n"; + print $inifile "mknod /dev/ttyS1 c 4 65\n"; + print $inifile "mknod /dev/ttyS2 c 4 66\n"; + print $inifile "mknod /dev/ttyS3 c 4 67\n"; + + foreach (@ndrivers) { + print $inifile "insmod /lib/$_\n"; + } + print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/bin/bash\n"; - print $inifile "dhcpcd $prinic\n"; + print $inifile " exit\n"; + print $inifile "fi\n"; + print $inifile "cd /\n"; + print $inifile "mkdir /sysroot/var/lib/dhcpcd/\n"; #neccessary for SLES11, not sure for SLES10 + print $inifile "cp /var/lib/dhcpcd/* /sysroot/var/lib/dhcpcd/\n"; + print $inifile "cp /etc/resolv.conf /sysroot/etc/\n"; + print $inifile "cp /etc/HOSTNAME /sysroot/etc/\n"; + print $inifile "mknod /sysroot/dev/console c 5 1\n"; + print $inifile "exec /lib/mkinitrd/bin/run-init -c /dev/console /sysroot /sbin/init\n"; + close($inifile); + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/bin/bash\n"; + print $inifile "dhcpcd $prinic\n"; - #-- Bring other NICs up in /bin/netstart in initrd for NIC failover - foreach (split /,/,$othernics) { - if (/^$/) { next; } - print $inifile "dhcpcd $_\n"; - } + #-- Bring other NICs up in /bin/netstart in initrd for NIC failover + foreach (split /,/, $othernics) { + if (/^$/) { next; } + print $inifile "dhcpcd $_\n"; + } - print $inifile <> /etc/resolv.conf cat /var/lib/dhcpcd/*info | grep HOSTNAME | uniq | awk -F= '{print \$2}'| sed \"s/'//g\" >> /etc/HOSTNAME for names in \$(cat /var/lib/dhcpcd/*info | grep DNS | uniq | awk -F= '{print \$2}' | sed 's/,/\\n/'); do @@ -649,248 +659,254 @@ for names in \$(cat /var/lib/dhcpcd/*info | grep DNS | uniq | awk -F= '{print \$ done END - close($inifile); - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - foreach ("usr/bin/grep","bin/cpio","bin/sleep","bin/mount","sbin/dhcpcd","bin/bash","sbin/insmod","bin/mkdir","bin/mknod","sbin/ip","bin/cat","usr/bin/awk","usr/bin/wget","bin/cp","usr/bin/cpio","usr/bin/zcat","usr/bin/gzip","lib/mkinitrd/bin/run-init","usr/bin/uniq","usr/bin/sed") { - getlibs($_); #there's one small bug for getlibs - push @filestoadd,$_; - } - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - } - else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - if($basekernelver ne $kernelver) { - system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); - unless (-d "$rootimg_dir/lib/modules/$kernelver") { - if(-d "/lib/modules/$kernelver") { - system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); - } - else { - xdie("Cannot read /lib/modules/$kernelver"); - } + close($inifile); + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + @filestoadd = (); + foreach (@ndrivers) { + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; } - } - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$rootimg_dir/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$rootimg_dir/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + } + foreach ("usr/bin/grep", "bin/cpio", "bin/sleep", "bin/mount", "sbin/dhcpcd", "bin/bash", "sbin/insmod", "bin/mkdir", "bin/mknod", "sbin/ip", "bin/cat", "usr/bin/awk", "usr/bin/wget", "bin/cp", "usr/bin/cpio", "usr/bin/zcat", "usr/bin/gzip", "lib/mkinitrd/bin/run-init", "usr/bin/uniq", "usr/bin/sed") { + getlibs($_); #there's one small bug for getlibs + push @filestoadd, $_; + } + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + } + else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; + if ($basekernelver ne $kernelver) { + system("rm -rf $rootimg_dir/lib/modules/$basekernelver"); + unless (-d "$rootimg_dir/lib/modules/$kernelver") { + if (-d "/lib/modules/$kernelver") { + system("cd /lib/modules;cp -r $kernelver $rootimg_dir/lib/modules/"); + } + else { + xdie("Cannot read /lib/modules/$kernelver"); + } + } + } + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + foreach (@filestoadd) { + if (ref($_)) { - #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); - system("cd /tmp/xcatinitrd.$$/bin/; ln -sf bash sh"); #neccessary for SLES11 - system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); - system("rm -rf /tmp/xcatinitrd.$$"); + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$rootimg_dir/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$rootimg_dir/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + + #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); + system("cd /tmp/xcatinitrd.$$/bin/; ln -sf bash sh"); #neccessary for SLES11 + system("cd /tmp/xcatinitrd.$$;find .|cpio -H newc -o|gzip -9 -c - > $destdir/initrd.gz"); + system("rm -rf /tmp/xcatinitrd.$$"); } sub isyumdir { - if ($File::Find::name =~ /\/repodata$/) { - my $location = $File::Find::name; - $location =~ s/\/repodata$//; - push @yumdirs,$location; - } + if ($File::Find::name =~ /\/repodata$/) { + my $location = $File::Find::name; + $location =~ s/\/repodata$//; + push @yumdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + } + } } - -sub postscripts { # TODO: customized postscripts - generic_post(); - if (-d "$installroot/postscripts/hostkeys") { - for my $key (<$installroot/postscripts/hostkeys/*key>) { - copy ($key,"$rootimg_dir/etc/ssh/"); - } - chmod 0600,; - } - if (-d "/$installroot/postscripts/.ssh") { - mkpath("$rootimg_dir/root/.ssh"); - chmod(0700,"$rootimg_dir/root/.ssh/"); - for my $file () { - copy ($file,"$rootimg_dir/root/.ssh/"); - } - chmod(0600,); - } + +sub postscripts { # TODO: customized postscripts + generic_post(); + if (-d "$installroot/postscripts/hostkeys") { + for my $key (<$installroot/postscripts/hostkeys/*key>) { + copy($key, "$rootimg_dir/etc/ssh/"); + } + chmod 0600, ; + } + if (-d "/$installroot/postscripts/.ssh") { + mkpath("$rootimg_dir/root/.ssh"); + chmod(0700, "$rootimg_dir/root/.ssh/"); + for my $file () { + copy($file, "$rootimg_dir/root/.ssh/"); + } + chmod(0600, ); + } } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; - } - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network"); - print $cfgfile "NETWORKING=yes\n"; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); - # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no - # to skip the break of nfs-based boot - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); - print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; - close($cfgfile); - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">","$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); - print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; - close($cfgfile); - } - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - print $cfgfile "console\n"; - close($cfgfile); - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - open($cfgfile,">","$rootimg_dir/etc/init.d/gettyset"); - print $cfgfile "#!/bin/bash\n"; - print $cfgfile "for i in `cat /proc/cmdline`; do\n"; - print $cfgfile ' KEY=`echo $i|cut -d= -f 1`'."\n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; - print $cfgfile " if echo \$VALUE | grep n8r; then\n"; - print $cfgfile " FLOWFLAG=\"-h\"\n"; - print $cfgfile " fi\n"; - print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; - print $cfgfile " init q\n"; - print $cfgfile " fi\n"; - print $cfgfile "done\n"; - print $cfgfile "/etc/init.d/boot.localnet start\n"; - print $cfgfile "/opt/xcat/xcatdsklspost\n"; - close($cfgfile); - chmod(0755,"$rootimg_dir/etc/init.d/gettyset"); - #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); - my $rc = system("grep sshd $rootimg_dir/etc/init.d/.depend.start"); - if ($rc) { - system("sed -i '".'s/^\(TARGETS = .*\)$/\1 sshd/'."' $rootimg_dir/etc/init.d/.depend.start"); - system("ln -s ../sshd $rootimg_dir/etc/init.d/rc3.d/S20sshd"); - } - my $rc = system("grep gettyset $rootimg_dir/etc/init.d/.depend.start"); - if ($rc) { - system("sed -i '".'s/^\(TARGETS = .*\)$/\1 gettyset/'."' $rootimg_dir/etc/init.d/.depend.start"); - system("ln -s ../gettyset $rootimg_dir/etc/init.d/rc3.d/S60gettyset"); - } - if(($osver =~ /sles11/) || ($osver =~ /suse11/) || ($osver =~ /sles10/)) {#for sles11,sles10,suse11 - rename(<$rootimg_dir/boot/vmlinux*>,"$destdir/kernel"); - }else { - rename(<$rootimg_dir/boot/vmlinuz*>,"$destdir/kernel"); - } + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 0\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 0\n"; + } + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network"); + print $cfgfile "NETWORKING=yes\n"; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); + + # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no + # to skip the break of nfs-based boot + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$prinic"); + print $cfgfile "ONBOOT=no\nBOOTPROTO=dhcp\nDEVICE=$prinic\n"; + close($cfgfile); + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">", "$rootimg_dir/etc/sysconfig/network-scripts/ifcfg-$_"); + print $cfgfile "ONBOOT=yes\nBOOTPROTO=dhcp\nDEVICE=$_\n"; + close($cfgfile); + } + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + print $cfgfile "console\n"; + close($cfgfile); + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + open($cfgfile, ">", "$rootimg_dir/etc/init.d/gettyset"); + print $cfgfile "#!/bin/bash\n"; + print $cfgfile "for i in `cat /proc/cmdline`; do\n"; + print $cfgfile ' KEY=`echo $i|cut -d= -f 1`' . "\n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then\n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2`\n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1`\n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1`\n"; + print $cfgfile " if echo \$VALUE | grep n8r; then\n"; + print $cfgfile " FLOWFLAG=\"-h\"\n"; + print $cfgfile " fi\n"; + print $cfgfile " echo xco:2345:respawn:/sbin/agetty \$FLOWFLAG \$COTTY \$COSPEED xterm >> /etc/inittab\n"; + print $cfgfile " init q\n"; + print $cfgfile " fi\n"; + print $cfgfile "done\n"; + print $cfgfile "/etc/init.d/boot.localnet start\n"; + print $cfgfile "/opt/xcat/xcatdsklspost\n"; + close($cfgfile); + chmod(0755, "$rootimg_dir/etc/init.d/gettyset"); + + #link("$rootimg_dir/sbin/init","$rootimg_dir/init"); + my $rc = system("grep sshd $rootimg_dir/etc/init.d/.depend.start"); + if ($rc) { + system("sed -i '" . 's/^\(TARGETS = .*\)$/\1 sshd/' . "' $rootimg_dir/etc/init.d/.depend.start"); + system("ln -s ../sshd $rootimg_dir/etc/init.d/rc3.d/S20sshd"); + } + my $rc = system("grep gettyset $rootimg_dir/etc/init.d/.depend.start"); + if ($rc) { + system("sed -i '" . 's/^\(TARGETS = .*\)$/\1 gettyset/' . "' $rootimg_dir/etc/init.d/.depend.start"); + system("ln -s ../gettyset $rootimg_dir/etc/init.d/rc3.d/S60gettyset"); + } + if (($osver =~ /sles11/) || ($osver =~ /suse11/) || ($osver =~ /sles10/)) { #for sles11,sles10,suse11 + rename(<$rootimg_dir/boot/vmlinux*>, "$destdir/kernel"); + } else { + rename(<$rootimg_dir/boot/vmlinuz*>, "$destdir/kernel"); + } } sub get_extra_pkglist_file_name { - my $base=shift; - if (-r "$base/$profile.$osver.$arch.otherpkgs.pkglist") { - return "$base/$profile.$osver.$arch.otherpkgs.pkglist"; - } elsif (-r "$base/$profile.$arch.otherpkgs.pkglist") { - return "$base/$profile.$arch.otherpkgs.pkglist"; - } elsif (-r "$base/$profile.$osver.otherpkgs.pkglist") { - return "$base/$profile.$osver.otherpkgs.pkglist"; - } elsif (-r "$base/$profile.otherpkgs.pkglist") { - return "$base/$profile.otherpkgs.pkglist"; - } - return ""; + my $base = shift; + if (-r "$base/$profile.$osver.$arch.otherpkgs.pkglist") { + return "$base/$profile.$osver.$arch.otherpkgs.pkglist"; + } elsif (-r "$base/$profile.$arch.otherpkgs.pkglist") { + return "$base/$profile.$arch.otherpkgs.pkglist"; + } elsif (-r "$base/$profile.$osver.otherpkgs.pkglist") { + return "$base/$profile.$osver.otherpkgs.pkglist"; + } elsif (-r "$base/$profile.otherpkgs.pkglist") { + return "$base/$profile.otherpkgs.pkglist"; + } + return ""; } sub get_pkglist_file_name { - my $base=shift; - if (-r "$base/$profile.$osver.$arch.pkglist") { - return "$base/$profile.$osver.$arch.pkglist"; - } elsif (-r "$base/$profile.$arch.pkglist") { - return "$base/$profile.$arch.pkglist"; - } elsif (-r "$base/$profile.$osver.pkglist") { - return "$base/$profile.$osver.pkglist"; - } elsif (-r "$base/$profile.pkglist") { - return "$base/$profile.pkglist"; - } + my $base = shift; + if (-r "$base/$profile.$osver.$arch.pkglist") { + return "$base/$profile.$osver.$arch.pkglist"; + } elsif (-r "$base/$profile.$arch.pkglist") { + return "$base/$profile.$arch.pkglist"; + } elsif (-r "$base/$profile.$osver.pkglist") { + return "$base/$profile.$osver.pkglist"; + } elsif (-r "$base/$profile.pkglist") { + return "$base/$profile.pkglist"; + } - return ""; + return ""; } sub get_postinstall_file_name { - my $base=shift; - if (-x "$base/$profile.$osver.$arch.postinstall") { - return "$base/$profile.$osver.$arch.postinstall"; - } elsif (-x "$base/$profile.$arch.postinstall") { - return "$base/$profile.$arch.postinstall"; - } elsif (-x "$base/$profile.$osver.postinstall") { - return "$base/$profile.$osver.postinstall"; - } elsif (-x "$base/$profile.postinstall") { - return "$base/$profile.postinstall"; - } + my $base = shift; + if (-x "$base/$profile.$osver.$arch.postinstall") { + return "$base/$profile.$osver.$arch.postinstall"; + } elsif (-x "$base/$profile.$arch.postinstall") { + return "$base/$profile.$arch.postinstall"; + } elsif (-x "$base/$profile.$osver.postinstall") { + return "$base/$profile.$osver.postinstall"; + } elsif (-x "$base/$profile.postinstall") { + return "$base/$profile.postinstall"; + } - return ""; + return ""; } diff --git a/xCAT-server/share/xcat/netboot/ubuntu/genimage b/xCAT-server/share/xcat/netboot/ubuntu/genimage index b1641a240..2921543ba 100755 --- a/xCAT-server/share/xcat/netboot/ubuntu/genimage +++ b/xCAT-server/share/xcat/netboot/ubuntu/genimage @@ -23,10 +23,10 @@ use imgutils; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); -my $dracutmode; #Indicate whether this is a dracut style initrd -my $dracutdir = "dracut"; # The default directory name of dracut -my $prinic; #TODO be flexible on node primary nic -my $othernics; #TODO be flexible on node primary nic +my $dracutmode; #Indicate whether this is a dracut style initrd +my $dracutdir = "dracut"; # The default directory name of dracut +my $prinic; #TODO be flexible on node primary nic +my $othernics; #TODO be flexible on node primary nic my $netdriver; my @yumdirs; my $arch; @@ -34,21 +34,22 @@ my %libhash; my @filestoadd; my $profile; my $osver; -my $pathtofiles=dirname($0); -my $fullpath=realpath($pathtofiles); -my $name = basename($0); -my $onlyinitrd=0; +my $pathtofiles = dirname($0); +my $fullpath = realpath($pathtofiles); +my $name = basename($0); +my $onlyinitrd = 0; + #that this method of calling genimage is no longer used if ($name =~ /geninitrd/) { - $onlyinitrd=1; + $onlyinitrd = 1; } my $rootlimit; my $tmplimit; my $installroot = "/install"; my $kerneldir; -my $kernelver = ""; #`uname -r`; -my $basekernelver; # = $kernelver; -my $customdir=$fullpath; +my $kernelver = ""; #`uname -r`; +my $basekernelver; # = $kernelver; +my $customdir = $fullpath; $customdir =~ s/.*share\/xcat/$installroot\/custom/; my $imagename; my $pkglist; @@ -60,7 +61,7 @@ my $otherpkgsdir_internet; my $otherpkglist; my $postinstall_filename; my $rootimg_dir; -my $permission; # the permission works only for statelite mode currently +my $permission; # the permission works only for statelite mode currently my $tempfile; my $prompt; my $noupdate; @@ -68,94 +69,95 @@ my $kernelimage; sub xdie { - system("rm -rf /tmp/xcatinitrd.$$"); - umount_chroot($rootimg_dir); - die @_; + system("rm -rf /tmp/xcatinitrd.$$"); + umount_chroot($rootimg_dir); + die @_; } $SIG{INT} = $SIG{TERM} = sub { xdie "Interrupted" }; GetOptions( - 'a=s' => \$arch, - 'p=s' => \$profile, - 'o=s' => \$osver, - 'n=s' => \$netdriver, - 'i=s' => \$prinic, - 'r=s' => \$othernics, - 'l=s' => \$rootlimit, - 't=s' => \$tmplimit, - 'k=s' => \$kernelver, - 'permission=s' => \$permission, - 'kerneldir=s' => \$kerneldir, - 'tempfile=s' =>\$tempfile, #internal flag - 'pkglist=s' => \$pkglist, #internal flag - 'srcdir=s' => \$srcdir, #internal flag - 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag - 'otherpkglist=s' => \$otherpkglist, #internal flag - 'postinstall=s' => \$postinstall_filename, #internal flag - 'rootimgdir=s' => \$destdir, #internal flag - 'interactive' =>\$prompt, - 'onlyinitrd' =>\$onlyinitrd, - 'noupdate' =>\$noupdate, + 'a=s' => \$arch, + 'p=s' => \$profile, + 'o=s' => \$osver, + 'n=s' => \$netdriver, + 'i=s' => \$prinic, + 'r=s' => \$othernics, + 'l=s' => \$rootlimit, + 't=s' => \$tmplimit, + 'k=s' => \$kernelver, + 'permission=s' => \$permission, + 'kerneldir=s' => \$kerneldir, + 'tempfile=s' => \$tempfile, #internal flag + 'pkglist=s' => \$pkglist, #internal flag + 'srcdir=s' => \$srcdir, #internal flag + 'otherpkgdir=s' => \$srcdir_otherpkgs, #internal flag + 'otherpkglist=s' => \$otherpkglist, #internal flag + 'postinstall=s' => \$postinstall_filename, #internal flag + 'rootimgdir=s' => \$destdir, #internal flag + 'interactive' => \$prompt, + 'onlyinitrd' => \$onlyinitrd, + 'noupdate' => \$noupdate, ); if (@ARGV > 0) { - $imagename=$ARGV[0]; + $imagename = $ARGV[0]; } ############################################################# # The current logic for install deb pkgs -# +# # Pre: 4 parameters and values -# 1. srcdir -- Normally the repo created within copycds +# 1. srcdir -- Normally the repo created within copycds # 2. kerneldir -- The dir admin used in osimage object to specify the repo dir for the special kernel version with 'kernelver' option # 3. otherpkgdir -- The dir admin used to specify the repo dir other pkg list # 4. internet_repo -- The default internet path where the internet mirror is located. -# +# # The pkg installing logic -# -# 1. use debootstrap to create the minimal image from internet_repo based on the pkglist, the kernel will be exclude from pkglist. +# +# 1. use debootstrap to create the minimal image from internet_repo based on the pkglist, the kernel will be exclude from pkglist. # Note: The reason to create image from internet_repo is the pkg libc-bin is not included in ISO repo. # 2. install kernel # Note: At this point, the kerneldir and srcdir are all added as the repo to do pkg upgrade and kernel installation. # 3. install otherpkg -# Note: Then, the deb pkg repo included three types: the srcdir, the kerneldir and the otherpkgdir. +# Note: Then, the deb pkg repo included three types: the srcdir, the kerneldir and the otherpkgdir. # ############################################################## -my %updates_os = (); # the hash for updating osimage table -my %updates = (); # the hash for updating linuximage table +my %updates_os = (); # the hash for updating osimage table +my %updates = (); # the hash for updating linuximage table $permission = "755" unless ($permission); -$updates{'permission'} = $permission if ( $tempfile ); +$updates{'permission'} = $permission if ($tempfile); unless ($arch) { $arch = `uname -m`; chomp($arch); - $arch = "x86" if ($arch =~ /i.86$/); + $arch = "x86" if ($arch =~ /i.86$/); } -$srcdir="$installroot/$osver/$arch" unless ($srcdir); +$srcdir = "$installroot/$osver/$arch" unless ($srcdir); $updates{'pkgdir'} = $srcdir if ($tempfile); -if ($srcdir_otherpkgs){ +if ($srcdir_otherpkgs) { my @tempdirarray = split /,/, $srcdir_otherpkgs; - foreach my $tempdir (@tempdirarray){ - if ($tempdir =~ /^http.*/){ + foreach my $tempdir (@tempdirarray) { + if ($tempdir =~ /^http.*/) { $otherpkgsdir_internet .= "deb " . $tempdir . "\n"; } - else{ + else { $otherpkgsdir_local = $tempdir; } } } $updates{'otherpkgdir'} = $srcdir_otherpkgs if ($tempfile); -$destdir="$installroot/netboot/$osver/$arch/$profile" unless ($destdir); +$destdir = "$installroot/netboot/$osver/$arch/$profile" unless ($destdir); $updates{'rootimgdir'} = $destdir if ($tempfile); -$rootimg_dir="$destdir/rootimg"; +$rootimg_dir = "$destdir/rootimg"; + +$kerneldir = "$installroot/kernels" unless ($kerneldir); # the default directory for 3rd-party kernel is "$installroot/kernels"; -$kerneldir = "$installroot/kernels" unless ($kerneldir); # the default directory for 3rd-party kernel is "$installroot/kernels"; #$updates{'kerneldir'} = $kerneldir if ($tempfile); # Get the subchannels of the given interface @@ -163,35 +165,36 @@ my $subchn; my $readChn; my @chn; if ($arch eq "s390x") { - $subchn = `cat /etc/sysconfig/network-scripts/ifcfg-$prinic | grep "SUBCHANNELS"`; - - if (!$subchn) { - print "SUBCHANNELS need to be given in /etc/sysconfig/network-scripts/ifcfg-$prinic"; - exit 1; - } else { - # Trim right - $subchn =~ s/\s*$//; + $subchn = `cat /etc/sysconfig/network-scripts/ifcfg-$prinic | grep "SUBCHANNELS"`; - # Trim left - $subchn =~ s/^\s*//; - - # Extract subchannels - $subchn =~ s/SUBCHANNELS=//g; - - # Extract read channel - @chn = split( ",", $subchn ); - $readChn = @chn[0]; - } + if (!$subchn) { + print "SUBCHANNELS need to be given in /etc/sysconfig/network-scripts/ifcfg-$prinic"; + exit 1; + } else { + + # Trim right + $subchn =~ s/\s*$//; + + # Trim left + $subchn =~ s/^\s*//; + + # Extract subchannels + $subchn =~ s/SUBCHANNELS=//g; + + # Extract read channel + @chn = split(",", $subchn); + $readChn = @chn[0]; + } } unless ($osver and $profile) { - usage(); - exit 1; + usage(); + exit 1; } my @ndrivers; if ($netdriver) { - if ( ($updates{'netdrivers'} ne $netdriver) and ($tempfile) ) { + if (($updates{'netdrivers'} ne $netdriver) and ($tempfile)) { $updates{'netdrivers'} = $netdriver; } } else { @@ -201,200 +204,203 @@ if ($netdriver) { @ndrivers = qw/bnx2 bnx2x e1000 e1000e igb mlx_en mlx4_en/; } elsif ($arch eq 'ppc64') { @ndrivers = qw/e1000 e1000e igb ibmveth ehea/; - } elsif ($arch eq 's390x') { - @ndrivers = qw/qdio ccwgroup/; + } elsif ($arch eq 's390x') { + @ndrivers = qw/qdio ccwgroup/; } } -foreach (split /,/,$netdriver) { - unless (/\.ko$/) { - s/$/.ko/; - } - next if (/^$/); - push @ndrivers, $_; +foreach (split /,/, $netdriver) { + unless (/\.ko$/) { + s/$/.ko/; + } + next if (/^$/); + push @ndrivers, $_; } foreach (@ndrivers) { - unless (/\.ko$/) { - s/$/.ko/; - } + unless (/\.ko$/) { + s/$/.ko/; + } } -my $uarch=$arch; -$uarch="amd64" if ($arch eq x86_64); +my $uarch = $arch; +$uarch = "amd64" if ($arch eq x86_64); unless ($onlyinitrd) { - @aptdirs=(); + @aptdirs = (); - # Get the ubuntu repo path from osimage.pkgdir - my @srcdirs = split(',', $srcdir); - - my @pkgdir_internet; #Put all the http mirror in ths array, but only the first http mirror which will be used to create bootstrap - my @pkgdir_local; #Put all directories except first in this array - my $masternode = xCAT::TableUtils->get_site_Master(); - $srcdir = undef; - foreach my $dir (@srcdirs) { - if ($dir =~ /^http.*/){ - push @pkgdir_internet, $dir; - } else { - # If multiple pkgdirs are provided, The first path in the value of osimage.pkgdir - if (!$srcdir) { - $srcdir = $dir; - find(\&isaptdir, <$dir/>); - } else { #set other directory to http url - my $osuurl = "http://$masternode$dir ./"; - push @pkgdir_local, $osuurl; - } - } - } - # Add the dir for kernel deb to be installed - if ($kernelver) { - find(\&isaptdir, <$kerneldir/>); - if (!grep /$kerneldir/, @aptdirs) { - print "The repository for $kerneldir should be created before running the genimage.\n"; - } - } - unless (scalar(@aptdirs)) { - print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; - exit 1; - } + # Get the ubuntu repo path from osimage.pkgdir + my @srcdirs = split(',', $srcdir); - my $aptconfig; - open($aptconfig,">","/tmp/genimage.$$.apt.list"); - my $repnum=0; - foreach $tmpsrcdir (@aptdirs) { - print $aptconfig "deb file://$tmpsrcdir main stable\n\n"; - $repnum += 1; - } - $repnum-=1; + my @pkgdir_internet; #Put all the http mirror in ths array, but only the first http mirror which will be used to create bootstrap + my @pkgdir_local; #Put all directories except first in this array + my $masternode = xCAT::TableUtils->get_site_Master(); + $srcdir = undef; + foreach my $dir (@srcdirs) { + if ($dir =~ /^http.*/) { + push @pkgdir_internet, $dir; + } else { - # Add the internet mirror - if (@pkgdir_internet) { - foreach (@pkgdir_internet) { - print $aptconfig "deb $_\n\n"; - } - } - if (@pkgdir_local) { - foreach (@pkgdir_local) { - print $aptconfig "deb $_\n\n"; - } - } - close($aptconfig); - mkpath "$rootimg_dir/etc"; + # If multiple pkgdirs are provided, The first path in the value of osimage.pkgdir + if (!$srcdir) { + $srcdir = $dir; + find(\&isaptdir, <$dir/>); + } else { #set other directory to http url + my $osuurl = "http://$masternode$dir ./"; + push @pkgdir_local, $osuurl; + } + } + } - my $fd; - open($fd,">>","$rootimg_dir/etc/fstab"); - print $fd "#Dummy fstab for dpkg postscripts to see\n"; - close($fd); + # Add the dir for kernel deb to be installed + if ($kernelver) { + find(\&isaptdir, <$kerneldir/>); + if (!grep /$kerneldir/, @aptdirs) { + print "The repository for $kerneldir should be created before running the genimage.\n"; + } + } + unless (scalar(@aptdirs)) { + print "Need $installroot/$osver/$arch/ available from a system that has ran copycds on $osver $arch\n"; + exit 1; + } - my $non_interactive; - if (!$prompt) { $non_interactive="-y"; } + my $aptconfig; + open($aptconfig, ">", "/tmp/genimage.$$.apt.list"); + my $repnum = 0; + foreach $tmpsrcdir (@aptdirs) { + print $aptconfig "deb file://$tmpsrcdir main stable\n\n"; + $repnum += 1; + } + $repnum -= 1; - my @line=split(" ",`ls -lh $installroot/$osver/$arch/dists/ | grep dr`); - my $dist = $line[@line-1]; + # Add the internet mirror + if (@pkgdir_internet) { + foreach (@pkgdir_internet) { + print $aptconfig "deb $_\n\n"; + } + } + if (@pkgdir_local) { + foreach (@pkgdir_local) { + print $aptconfig "deb $_\n\n"; + } + } + close($aptconfig); + mkpath "$rootimg_dir/etc"; - # If there is env in otherpkg list - # apt-get update and apt-get install should be added env param - my $aptgetcmd = "DEBIAN_FRONTEND=noninteractive chroot $rootimg_dir apt-get update"; - my $aptgetcmdby = "DEBIAN_FRONTEND=noninteractive chroot $rootimg_dir apt-get $non_interactive "; - my $aptcachecmd = "DEBIAN_FRONTEND=noninteractive chroot $rootimg_dir apt-get update && chroot $rootimg_dir apt-cache $non_interactive "; - my $aptcmd1 = "debootstrap"; - my $aptcmd2; + my $fd; + open($fd, ">>", "$rootimg_dir/etc/fstab"); + print $fd "#Dummy fstab for dpkg postscripts to see\n"; + close($fd); - # Check whether a local Ubuntu mirror is specified - # if linuximage.pkgdir has http mirror is set, we consider the first http mirror - # as a full Ubuntu mirror which will be used to create bootstrap - if (@pkgdir_internet) { - my $mirrorurl = $pkgdir_internet[0]; - if ($pkgdir_internet[0] =~ /(http.*?) +([^ ]+)/) { - $mirrorurl = $1; - $dist = $2; - $aptcmd2 = "--verbose --arch $uarch $dist $rootimg_dir $mirrorurl"; - } else { - print "Error: In pkgdir, the first http mirror path must includes http URL and distribute name."; - exit 1; - } - } else { - if ($uarch eq 'ppc64el') { - $aptcmd2 = "--verbose --arch $uarch $dist $rootimg_dir http://ports.ubuntu.com/ubuntu-ports/"; - } else { - $aptcmd2 = "--verbose --arch $uarch $dist $rootimg_dir http://archive.ubuntu.com/ubuntu/"; - } - } + my $non_interactive; + if (!$prompt) { $non_interactive = "-y"; } - print "Run cmd [$aptcmd1 $aptcmd2] to create rootimage bootstraps\n"; - my $rc = system("$aptcmd1 $aptcmd2"); - if ($rc) { - print "Error: cannnot create bootstraps for rootimage. Make sure you specified full http mirror path.\n"; - exit 1; - } + my @line = split(" ", `ls -lh $installroot/$osver/$arch/dists/ | grep dr`); + my $dist = $line[ @line - 1 ]; - # Since kernel-image package needs the /proc/cpuinfo file to validate the cpu type, - # copy the /proc/cpuinfo from host node - copy("/proc/cpuinfo", "$rootimg_dir/proc/cpuinfo"); - - # Prepare the installation mirror for the package install - print("Mount /proc, /dev, /sys, pkgdir and otherpkgdir to the rootimg.\n"); - mount_chroot($rootimg_dir, $otherpkgsdir_local, $srcdir, $kerneldir); - - # Add mirrors from pkgdir attributes to rootimage for the pkg install from pkglist - open($aptconfig,">","$rootimg_dir/etc/apt/sources.list"); + # If there is env in otherpkg list + # apt-get update and apt-get install should be added env param + my $aptgetcmd = "DEBIAN_FRONTEND=noninteractive chroot $rootimg_dir apt-get update"; + my $aptgetcmdby = "DEBIAN_FRONTEND=noninteractive chroot $rootimg_dir apt-get $non_interactive "; + my $aptcachecmd = "DEBIAN_FRONTEND=noninteractive chroot $rootimg_dir apt-get update && chroot $rootimg_dir apt-cache $non_interactive "; + my $aptcmd1 = "debootstrap"; + my $aptcmd2; - if ($srcdir) { - print $aptconfig "deb http://$masternode$srcdir $dist main\n"; - } + # Check whether a local Ubuntu mirror is specified + # if linuximage.pkgdir has http mirror is set, we consider the first http mirror + # as a full Ubuntu mirror which will be used to create bootstrap + if (@pkgdir_internet) { + my $mirrorurl = $pkgdir_internet[0]; + if ($pkgdir_internet[0] =~ /(http.*?) +([^ ]+)/) { + $mirrorurl = $1; + $dist = $2; + $aptcmd2 = "--verbose --arch $uarch $dist $rootimg_dir $mirrorurl"; + } else { + print "Error: In pkgdir, the first http mirror path must includes http URL and distribute name."; + exit 1; + } + } else { + if ($uarch eq 'ppc64el') { + $aptcmd2 = "--verbose --arch $uarch $dist $rootimg_dir http://ports.ubuntu.com/ubuntu-ports/"; + } else { + $aptcmd2 = "--verbose --arch $uarch $dist $rootimg_dir http://archive.ubuntu.com/ubuntu/"; + } + } - foreach (@pkgdir_internet) { - print $aptconfig "deb $_\n"; - } - foreach (@pkgdir_local) { - print $aptconfig "deb $_\n"; - } + print "Run cmd [$aptcmd1 $aptcmd2] to create rootimage bootstraps\n"; + my $rc = system("$aptcmd1 $aptcmd2"); + if ($rc) { + print "Error: cannnot create bootstraps for rootimage. Make sure you specified full http mirror path.\n"; + exit 1; + } - close($aptconfig); + # Since kernel-image package needs the /proc/cpuinfo file to validate the cpu type, + # copy the /proc/cpuinfo from host node + copy("/proc/cpuinfo", "$rootimg_dir/proc/cpuinfo"); - # run apt-get upgrade to update any installed debs - my $aptgetcmd_update = $aptgetcmd . "&&". $aptgetcmdby . " upgrade "; - $rc = system("$aptgetcmd_update"); - - # Start to install pkgs in pkglist - unless ($imagename) { - $pkglist= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); - unless ($pkglist) { - $pkglist= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); - } - } + # Prepare the installation mirror for the package install + print("Mount /proc, /dev, /sys, pkgdir and otherpkgdir to the rootimg.\n"); + mount_chroot($rootimg_dir, $otherpkgsdir_local, $srcdir, $kerneldir); - if ($pkglist) { - $updates{'pkglist'} = $pkglist if ($tempfile); - } else { - xdie "Unable to find package list for $profile!"; - } + # Add mirrors from pkgdir attributes to rootimage for the pkg install from pkglist + open($aptconfig, ">", "$rootimg_dir/etc/apt/sources.list"); - my %pkg_hash=imgutils::get_package_names($pkglist); - my $index=1; - my $pass; - foreach $pass (sort {$a <=> $b} (keys(%pkg_hash))) { + if ($srcdir) { + print $aptconfig "deb http://$masternode$srcdir $dist main\n"; + } + + foreach (@pkgdir_internet) { + print $aptconfig "deb $_\n"; + } + foreach (@pkgdir_local) { + print $aptconfig "deb $_\n"; + } + + close($aptconfig); + + # run apt-get upgrade to update any installed debs + my $aptgetcmd_update = $aptgetcmd . "&&" . $aptgetcmdby . " upgrade "; + $rc = system("$aptgetcmd_update"); + + # Start to install pkgs in pkglist + unless ($imagename) { + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "pkglist"); + unless ($pkglist) { + $pkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "pkglist"); + } + } + + if ($pkglist) { + $updates{'pkglist'} = $pkglist if ($tempfile); + } else { + xdie "Unable to find package list for $profile!"; + } + + my %pkg_hash = imgutils::get_package_names($pkglist); + my $index = 1; + my $pass; + foreach $pass (sort { $a <=> $b } (keys(%pkg_hash))) { my $pkgnames = ""; - foreach (keys(%{$pkg_hash{$pass}})) { - if($_ eq "INCLUDEBAD") { - xdie "Unable to open the following pkglist files:\n".join("\n",@{$pkg_hash{$pass}{INCLUDEBAD}}); + foreach (keys(%{ $pkg_hash{$pass} })) { + if ($_ eq "INCLUDEBAD") { + xdie "Unable to open the following pkglist files:\n" . join("\n", @{ $pkg_hash{$pass}{INCLUDEBAD} }); } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} - my $pa=$pkg_hash{$pass}{$_}; + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + my $pa = $pkg_hash{$pass}{$_}; my @npa = (); + # replace the kernel package with the name has the specific version foreach my $p (@$pa) { print "$p\n"; if ($p =~ /^linux-image-server$/ && $kernelver) { - my $kernelname = "linux-image-".$kernelver."-server"; + my $kernelname = "linux-image-" . $kernelver . "-server"; my $searchkern = $aptcachecmd . " search $kernelname"; - my @kernpkgs = `$searchkern`; - my $found = 0; + my @kernpkgs = `$searchkern`; + my $found = 0; foreach my $k (@kernpkgs) { if ($k =~ /\s*linux-image-server[^\s]*\s+([\w\.-]+)/) { - my $version = $1; + my $version = $1; my $relversion = $kernelver; $relversion =~ s/\.[^\.]+$//; if ($version == $relversion) { @@ -423,15 +429,15 @@ unless ($onlyinitrd) { $pkgnames .= join(' ', @npa); } my $envlist; - if(exists $pkg_hash{$pass}{ENVLIST}){ - $envlist = join(',', @{$pkg_hash{$pass}{ENVLIST}}); + if (exists $pkg_hash{$pass}{ENVLIST}) { + $envlist = join(',', @{ $pkg_hash{$pass}{ENVLIST} }); } - + fake_policy_rc_d(); print "$envlist $aptgetcmdby install $pkgnames\n"; my $rc = system("$envlist $aptgetcmdby install --allow-unauthenticated $pkgnames"); - if ($rc) { + if ($rc) { xdie "Failed to install packages $pkgnames\n"; } } @@ -444,174 +450,180 @@ unless ($onlyinitrd) { if ($kernelver) { $kernelimage = "linux-image-$kernelver linux-image-extra-$kernelver linux-firmware"; } - my $aptgetcmd_install = $aptgetcmdby. " install --no-install-recommends ".$kernelimage; + my $aptgetcmd_install = $aptgetcmdby . " install --no-install-recommends " . $kernelimage; $rc = system("$aptgetcmd_install"); } } - + #add the other package directory to for apt-get install - open ($aptconfig,">","$rootimg_dir/etc/apt/sources.list.d/genimage.apt.list"); - if ($otherpkgsdir_internet){ + open($aptconfig, ">", "$rootimg_dir/etc/apt/sources.list.d/genimage.apt.list"); + if ($otherpkgsdir_internet) { print $aptconfig $otherpkgsdir_internet; } close($aptconfig); #backup the /etc/hosts & /etc/resolv.conf - move("$rootimg_dir/etc/hosts", "$rootimg_dir/etc/hosts.bak"); + move("$rootimg_dir/etc/hosts", "$rootimg_dir/etc/hosts.bak"); move("$rootimg_dir/etc/resolv.conf", "$rootimg_dir/etc/resolv.conf.bak"); #copy the mn's /etc/hosts & /etc/resolv.conf to the rootimage - copy("/etc/hosts", "$rootimg_dir/etc/hosts"); + copy("/etc/hosts", "$rootimg_dir/etc/hosts"); copy("/etc/resolv.conf", "$rootimg_dir/etc/resolv.conf"); #Now let's handle extra packages unless ($imagename) { $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "otherpkgs.pkglist"); - unless ($otherpkglist) { $otherpkglist=imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } + unless ($otherpkglist) { $otherpkglist = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "otherpkgs.pkglist"); } } + # Hack uname to get the corrent kernel ver, must be here because pkglist name depend on uname binary, put hacked uname script here to overwrite the orignal uname use_hackuname(); - my %extra_hash=(); + my %extra_hash = (); if ($otherpkglist) { $updates{'otherpkglist'} = $otherpkglist if ($tempfile); %extra_hash = imgutils::get_package_names($otherpkglist); } - my %extrapkgnames; + my %extrapkgnames; if (keys(%extra_hash) > 0) { - open ($aptconfig,">","$rootimg_dir/etc/apt/sources.list.d/genimage1.apt.list"); - my $index=1; - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { - foreach (keys(%{$extra_hash{$pass}})) { - if($_ eq "INCLUDEBAD") { - xdie "Unable to open the following pkglist files:\n".join("\n",@{$extra_hash{$pass}{INCLUDEBAD}}); - } - if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next;} + open($aptconfig, ">", "$rootimg_dir/etc/apt/sources.list.d/genimage1.apt.list"); + my $index = 1; + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { + foreach (keys(%{ $extra_hash{$pass} })) { + if ($_ eq "INCLUDEBAD") { + xdie "Unable to open the following pkglist files:\n" . join("\n", @{ $extra_hash{$pass}{INCLUDEBAD} }); + } + if (($_ eq "PRE_REMOVE") || ($_ eq "POST_REMOVE") || ($_ eq "ENVLIST")) { next; } + #if there is no Packages file in otherpkgsdir local, it will not be added into source list - if ($otherpkgsdir_local) + if ($otherpkgsdir_local) { - my $tmpdir=$otherpkgsdir_local."/".$_; - if (-f $tmpdir . '/Packages' || -f $tmpdir . '/Packages.gz') - { - print $aptconfig "deb file:///mnt/otherpkgdir/$_ ./\n" - } - }; + my $tmpdir = $otherpkgsdir_local . "/" . $_; + if (-f $tmpdir . '/Packages' || -f $tmpdir . '/Packages.gz') + { + print $aptconfig "deb file:///mnt/otherpkgdir/$_ ./\n" + } + } $index++; - my $pa=$extra_hash{$pass}{$_}; + my $pa = $extra_hash{$pass}{$_}; $extrapkgnames{$pass} .= " " . join(' ', @$pa); + } } - } - close($aptconfig); - $index--; + close($aptconfig); + $index--; - foreach $pass (sort {$a <=> $b} (keys(%extra_hash))) { - my $envlist; - if(exists($extra_hash{$pass}{ENVLIST})){ - $envlist = join(' ', @{$extra_hash{$pass}{ENVLIST}}); - } - # remove the packages that are specified in the otherpkgs.list files with leading '-' - my $aptgetcmd_remove= "$aptgetcmd remove "; - if (exists ($extra_hash{$pass}{'PRE_REMOVE'})) { - my $pa=$extra_hash{$pass}{'PRE_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$envlist $aptgetcmd_remove $rm_packges\n"; - $rc = system("$envlist $aptgetcmd_remove $rm_packges"); - } - } + foreach $pass (sort { $a <=> $b } (keys(%extra_hash))) { + my $envlist; + if (exists($extra_hash{$pass}{ENVLIST})) { + $envlist = join(' ', @{ $extra_hash{$pass}{ENVLIST} }); + } - # mount /proc file system since several packages need it. + # remove the packages that are specified in the otherpkgs.list files with leading '-' + my $aptgetcmd_remove = "$aptgetcmd remove "; + if (exists($extra_hash{$pass}{'PRE_REMOVE'})) { + my $pa = $extra_hash{$pass}{'PRE_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$envlist $aptgetcmd_remove $rm_packges\n"; + $rc = system("$envlist $aptgetcmd_remove $rm_packges"); + } + } - # install extra packages - my $aptgetcmd_base = $aptgetcmd; + # mount /proc file system since several packages need it. - #env param need to be added before each chroot - my $aptdevby=$aptgetcmd; - + # install extra packages + my $aptgetcmd_base = $aptgetcmd; - # to prevent "The following packages cannot be authenticated" error, - # invoke apt-get with "--allow-unauthenticated" option - #example:If there is env IBM_PPE_RTE_LICENSE_ACCEPT , it should be in front of chroot - #IBM_PPE_RTE_LICENSE_ACCEPT=yes chroot /install/netboot/ubuntu14.04/ppc64el/compute/rootimg apt-get update&& IBM_PPE_RTE_LICENSE_ACCEPT=yes chroot /install/netboot/ubuntu14.04/ppc64el/compute/rootimg apt-get -y install --allow-unauthenticated pperte-license - $aptdevby .="&& ".$envlist." "; - $aptdevby .=$aptgetcmdby; - $aptdevby .=" install --allow-unauthenticated "; - $aptgetcmd=$aptdevby; - - # append extra pkg names to yum command - if ($extrapkgnames{$pass}) { - $aptgetcmd .= " $extrapkgnames{$pass} "; - $aptgetcmd =~ s/ $/\n/; - - # debug - #print "aptgetcmd=$aptgetcmd\n"; - #my $repo=`cat /tmp/genimage.$$.yum.conf`; - #print "repo=$repo"; - - print "$envlist $aptgetcmd\n"; - my $rc = system("$envlist $aptgetcmd"); - if ($rc) { - xdie "apt-get invocation failed\n"; - } - } else { - print "No Packages marked for install\n"; - } - - # remove the packages that are specified in the otherpkgs.list files with leading '--' - if (exists ($extra_hash{$pass}{'POST_REMOVE'})) { - my $pa=$extra_hash{$pass}{'POST_REMOVE'}; - my $rm_packges= join(' ', @$pa); - if ($rm_packges) { - print "$envlist $aptgetcmd_remove $rm_packges\n"; - $rc = system("$envlist $aptgetcmd_remove $rm_packges"); - } - } - $aptgetcmd = $aptgetcmd_base; - } - } - - if (!$noupdate) { - # run apt-get upgrade to update any installed debs - # needed when running genimage again after updating software in repositories - my $aptgetcmd_update = $aptgetcmd . "&&". $aptgetcmdby . " upgrade "; - $rc = system("$aptgetcmd_update"); - # ignore any return code - } - # Hack uname to get the corrent kernel ver, use the original uname binary - unuse_hackuname(); - - print("Umount /proc, /dev, /sys, pkgdir and otherpkgdir to the rootimg.\n"); - umount_chroot($rootimg_dir); + #env param need to be added before each chroot + my $aptdevby = $aptgetcmd; - `rm -fr $rootimg_dir/etc/apt/sources.list.d/genimage1.apt.list`; - - #recover the /etc/hosts & /etc/reslov.conf - `cd $rootimg_dir/etc/;mv -f hosts.bak hosts;mv -f resolv.conf.bak resolv.conf`; + # to prevent "The following packages cannot be authenticated" error, + # invoke apt-get with "--allow-unauthenticated" option + #example:If there is env IBM_PPE_RTE_LICENSE_ACCEPT , it should be in front of chroot + #IBM_PPE_RTE_LICENSE_ACCEPT=yes chroot /install/netboot/ubuntu14.04/ppc64el/compute/rootimg apt-get update&& IBM_PPE_RTE_LICENSE_ACCEPT=yes chroot /install/netboot/ubuntu14.04/ppc64el/compute/rootimg apt-get -y install --allow-unauthenticated pperte-license + $aptdevby .= "&& " . $envlist . " "; + $aptdevby .= $aptgetcmdby; + $aptdevby .= " install --allow-unauthenticated "; + $aptgetcmd = $aptdevby; - postscripts(); #run 'postscripts' + # append extra pkg names to yum command + if ($extrapkgnames{$pass}) { + $aptgetcmd .= " $extrapkgnames{$pass} "; + $aptgetcmd =~ s/ $/\n/; + + # debug + #print "aptgetcmd=$aptgetcmd\n"; + #my $repo=`cat /tmp/genimage.$$.yum.conf`; + #print "repo=$repo"; + + print "$envlist $aptgetcmd\n"; + my $rc = system("$envlist $aptgetcmd"); + if ($rc) { + xdie "apt-get invocation failed\n"; + } + } else { + print "No Packages marked for install\n"; + } + + # remove the packages that are specified in the otherpkgs.list files with leading '--' + if (exists($extra_hash{$pass}{'POST_REMOVE'})) { + my $pa = $extra_hash{$pass}{'POST_REMOVE'}; + my $rm_packges = join(' ', @$pa); + if ($rm_packges) { + print "$envlist $aptgetcmd_remove $rm_packges\n"; + $rc = system("$envlist $aptgetcmd_remove $rm_packges"); + } + } + $aptgetcmd = $aptgetcmd_base; + } + } + + if (!$noupdate) { + + # run apt-get upgrade to update any installed debs + # needed when running genimage again after updating software in repositories + my $aptgetcmd_update = $aptgetcmd . "&&" . $aptgetcmdby . " upgrade "; + $rc = system("$aptgetcmd_update"); + + # ignore any return code + } + + # Hack uname to get the corrent kernel ver, use the original uname binary + unuse_hackuname(); + + print("Umount /proc, /dev, /sys, pkgdir and otherpkgdir to the rootimg.\n"); + umount_chroot($rootimg_dir); + + + `rm -fr $rootimg_dir/etc/apt/sources.list.d/genimage1.apt.list`; + + #recover the /etc/hosts & /etc/reslov.conf +`cd $rootimg_dir/etc/;mv -f hosts.bak hosts;mv -f resolv.conf.bak resolv.conf`; + + postscripts(); #run 'postscripts' } #-- run postinstall script unless ($imagename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $customdir, "postinstall"); unless ($postinstall_filename) { - $postinstall_filename= imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); + $postinstall_filename = imgutils::get_profile_def_filename($osver, $profile, $arch, $pathtofiles, "postinstall"); } } -if ( $postinstall_filename ) { +if ($postinstall_filename) { $updates{'postinstall'} = $postinstall_filename if ($tempfile); - foreach my $postinstall ( split /,/, $postinstall_filename ) { - if ( !-x $postinstall ) { + foreach my $postinstall (split /,/, $postinstall_filename) { + if (!-x $postinstall) { print "postinstall script $postinstall is not executable\n"; exit 1; } - my $rc = system($postinstall, $rootimg_dir,$osver,$arch,$profile); - if($rc) { + my $rc = system($postinstall, $rootimg_dir, $osver, $arch, $profile); + if ($rc) { print "postinstall script $postinstall failed\n"; exit 1; } @@ -625,12 +637,12 @@ if ( $postinstall_filename ) { # if all else fails, resort to uname -r like this script did before # Kernel name for s390x should be the same: vmlinuz-2.6.18-164.el5 -my @KVERS= <$rootimg_dir/boot/vmlinuz-*>; +my @KVERS = <$rootimg_dir/boot/vmlinuz-*>; foreach (@KVERS) { s/vmlinuz-//; } -@KVERS= <$rootimg_dir/lib/modules/*> unless (scalar(@KVERS)); +@KVERS = <$rootimg_dir/lib/modules/*> unless (scalar(@KVERS)); $basekernelver = basename(pop @KVERS) if (scalar(@KVERS)); @@ -642,11 +654,11 @@ chomp($kernelver); #$updates{'kernelver'} = $kernelver if ($tempfile); # copy the kernel to $destdir -if ( -e "$rootimg_dir/boot/vmlinux-$kernelver") { +if (-e "$rootimg_dir/boot/vmlinux-$kernelver") { cp("$rootimg_dir/boot/vmlinux-$kernelver", "$destdir/kernel"); -} elsif ( -e "$rootimg_dir/boot/vmlinuz-$kernelver") { +} elsif (-e "$rootimg_dir/boot/vmlinuz-$kernelver") { cp("$rootimg_dir/boot/vmlinuz-$kernelver", "$destdir/kernel"); -} elsif ( -e "$rootimg_dir/boot/image-$kernelver") { +} elsif (-e "$rootimg_dir/boot/image-$kernelver") { cp("$rootimg_dir/boot/image-$kernelver", "$destdir/kernel"); } else { xdie("couldn't find the kernel file matched $kernelver in $rootimg_dir/boot"); @@ -658,30 +670,30 @@ my @dd_drivers = &load_dd(); # Push the drivers into the @ndrivers base on the order my @new_order = (); foreach my $dd (@dd_drivers) { - unless (grep { $_ eq $dd} @ndrivers) { + unless (grep { $_ eq $dd } @ndrivers) { push @new_order, $dd; } print "Added driver $dd from driver update disk.\n"; } @ndrivers = (@new_order, @ndrivers); -open($moddeps,"<","$rootimg_dir/lib/modules/$kernelver/modules.dep"); -my @moddeps = <$moddeps>; +open($moddeps, "<", "$rootimg_dir/lib/modules/$kernelver/modules.dep"); +my @moddeps = <$moddeps>; my @checkdeps = @ndrivers; while (scalar @checkdeps) { my $driver = pop @checkdeps; - my @lines = grep /\/$driver:/,@moddeps; + my @lines = grep /\/$driver:/, @moddeps; foreach (@lines) { chomp; s/.*://; s/^\s*//; - my @deps = split /\s+/,$_; + my @deps = split /\s+/, $_; my $dep; foreach $dep (@deps) { $dep =~ s/.*\///; - unless (grep { $_ eq $dep } @ndrivers) { #only add if not added - unshift (@checkdeps,$dep); #recursively check dependencies - unshift (@ndrivers,$dep); + unless (grep { $_ eq $dep } @ndrivers) { #only add if not added + unshift(@checkdeps, $dep); #recursively check dependencies + unshift(@ndrivers, $dep); print "Added $dep as an autodetected depedency\n"; } } @@ -690,13 +702,14 @@ while (scalar @checkdeps) { close($moddeps); if (-d "$rootimg_dir/usr/share/dracut") { $dracutmode = 1; + # get dracut version my $dracutver = `chroot $rootimg_dir dpkg-query -W dracut | awk '{print \$2}'| aek -F- {print \$1}'`; if ($dracutver =~ /^\d\d\d$/) { if ($dracutver >= "009") { $dracutdir = "dracut_009"; } else { - $dracutdir = "dracut"; # The default directory + $dracutdir = "dracut"; # The default directory } } print "Enter the dracut mode. Dracut version: $dracutver. Dracut directory: $dracutdir.\n"; @@ -709,102 +722,108 @@ if (-d "$rootimg_dir/usr/share/dracut") { if ($tempfile) { open(FILE, ">>$tempfile"); if ($imagename) { - if (keys(%updates) > 0) { - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$imagename\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - } + if (keys(%updates) > 0) { + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$imagename\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + } } else { - $updates_os{'profile'} = $profile; - $updates_os{'imagetype'} = 'linux'; - $updates_os{'provmethod'} = 'netboot'; - $updates_os{'osname'} = 'Linux'; - $updates_os{'osvers'} = $osver; - $updates_os{'osarch'} = $arch; - # update the imagename for stateless - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-netboot-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - # update the imagename for statelite - $updates_os{'provmethod'} = 'statelite'; - print FILE "The output for table updates starts here\n"; - print FILE "table::osimage\n"; - print FILE "imagename::$osver-$arch-statelite-$profile\n"; - my @a=%updates_os; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; - - print FILE "The output for table updates starts here\n"; - print FILE "table::linuximage\n"; - print FILE "imagename::$osver-$arch-statelite-$profile\n"; - my @a=%updates; - print FILE join('::',@a) . "\n"; - print FILE "The output for table updates ends here\n"; + $updates_os{'profile'} = $profile; + $updates_os{'imagetype'} = 'linux'; + $updates_os{'provmethod'} = 'netboot'; + $updates_os{'osname'} = 'Linux'; + $updates_os{'osvers'} = $osver; + $updates_os{'osarch'} = $arch; + + # update the imagename for stateless + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-netboot-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + # update the imagename for statelite + $updates_os{'provmethod'} = 'statelite'; + print FILE "The output for table updates starts here\n"; + print FILE "table::osimage\n"; + print FILE "imagename::$osver-$arch-statelite-$profile\n"; + my @a = %updates_os; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; + + print FILE "The output for table updates starts here\n"; + print FILE "table::linuximage\n"; + print FILE "imagename::$osver-$arch-statelite-$profile\n"; + my @a = %updates; + print FILE join('::', @a) . "\n"; + print FILE "The output for table updates ends here\n"; } close FILE; } + #END # statelite .statelite directory added here. # this is where tmpfs will be created. -mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. +mkpath "$rootimg_dir/.statelite"; # create place for NFS mounts. -# this script will get the directories. +# this script will get the directories. # TODO: the file is re-copied in liteimg.pm my $cwd = $FindBin::Bin; unless (-f "$cwd/../add-on/statelite/rc.statelite") { - print "Can't find $cwd/../add-on/statelite/rc.statelite!\n"; - exit 1; + print "Can't find $cwd/../add-on/statelite/rc.statelite!\n"; + exit 1; } system("cp $cwd/../add-on/statelite/rc.statelite $rootimg_dir/etc/init.d/statelite"); + # also need to add this file: # may have already been made into a symbolic link, if so ignore it -unless ($dracutmode) { #in dracut mode, we delegate all this activity - unless (-l "$rootimg_dir/var/lib/dhclient" ) { - mkpath "$rootimg_dir/var/lib/dhclient/"; - system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); +unless ($dracutmode) { #in dracut mode, we delegate all this activity + unless (-l "$rootimg_dir/var/lib/dhclient") { + mkpath "$rootimg_dir/var/lib/dhclient/"; + system("touch $rootimg_dir/var/lib/dhclient/dhclient-$prinic.leases"); } - - unless (-l "$rootimg_dir/var/lib/dhcp" ) { - mkpath "$rootimg_dir/var/lib/dhcp/"; - system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); + + unless (-l "$rootimg_dir/var/lib/dhcp") { + mkpath "$rootimg_dir/var/lib/dhcp/"; + system("touch $rootimg_dir/var/lib/dhcp/dhclient-$prinic.leases"); } } if ($dracutmode) { + # modify etc/rc.sysinit, prevent remounting # TODO: need to find one way to prevent remounting my $SYSINITFILE; my $TMPSYSINITFILE; if (-f "$rootimg_dir/etc/rc.sysinit") { + # backup etc/rc.sysinit file before modifing it system("cp -a $rootimg_dir/etc/rc.sysinit $rootimg_dir/etc/rc.sysinit.backup"); open($SYSINITFILE, "$rootimg_dir/etc/rc.sysinit"); open($TMPSYSINITFILE, '>', "/tmp/rc.sysinit.tmp"); + # find the following lines, # if remount_needed ; then # action $"Remounting root filesystem in read-write mode: " mount -n -o remount,rw / # fi # and change "if remount_needed ; then" to "if false; then" - while(<$SYSINITFILE>) { + while (<$SYSINITFILE>) { if ($_ eq "if remount_needed ; then\n") { $_ = "if false; then\n"; } @@ -816,7 +835,7 @@ if ($dracutmode) { } } -# before mkinitrd, run depmod to generate modules.dep +# before mkinitrd, run depmod to generate modules.dep system("chroot $rootimg_dir depmod $kernelver"); #delete the apt cache @@ -830,49 +849,49 @@ if ($dracutmode) { mkinitrd_dracut("statelite"); mkinitrd_dracut("stateless"); } else { - my @drivers; # backup of @ndrivers + my @drivers; # backup of @ndrivers push @drivers, @ndrivers; mkinitrd("statelite"); - @ndrivers=(); + @ndrivers = (); push @ndrivers, @drivers; mkinitrd("stateless"); } sub getlibs { - my $file = shift; - my $liblist = `chroot $rootimg_dir ldd $file`; - my @libs = split/\n/,$liblist; - my @return; - foreach (@libs) { - if(/statically linked/ or /not a dynamic executable/){ - return; + my $file = shift; + my $liblist = `chroot $rootimg_dir ldd $file`; + my @libs = split /\n/, $liblist; + my @return; + foreach (@libs) { + if (/statically linked/ or /not a dynamic executable/) { + return; } unless (/=>/) { - (my $wjnk, my $lib,my $jnk) = split /\s+/,$_,3; - $lib =~ s/^\///; - $libhash{$lib}=1; - getlibs($lib); - next; + (my $wjnk, my $lib, my $jnk) = split /\s+/, $_, 3; + $lib =~ s/^\///; + $libhash{$lib} = 1; + getlibs($lib); + next; + } + (my $temp1, my $temp2) = split />/, $_, 2; + (my $whitespace, $temp1, $temp2) = split /\s+/, $temp2, 4; + unless ($temp1 =~ /\//) { + next; } - (my $temp1,my $temp2) = split />/,$_,2; - (my $whitespace,$temp1,$temp2) = split /\s+/,$temp2,4; - unless ($temp1 =~ /\//) { - next; - } $temp1 =~ s/^\///; - $libhash{$temp1}=1; + $libhash{$temp1} = 1; getlibs($temp1); - } + } } sub mkinitrd_dracut { - my ($mode) = @_; # the mode is for statelite or stateless + my ($mode) = @_; # the mode is for statelite or stateless my $dracutmpath = "$rootimg_dir/usr/share/dracut/modules.d/97xcat"; mkpath($dracutmpath); my $perm = (stat("$fullpath/$dracutdir/check"))[2]; cp("$fullpath/$dracutdir/check", $dracutmpath); - chmod($perm&07777, "$dracutmpath/check"); + chmod($perm & 07777, "$dracutmpath/check"); foreach (@ndrivers) { s/\.ko$//; } @@ -880,14 +899,15 @@ sub mkinitrd_dracut { my $DRACUTCONF; if ($mode eq "statelite") { - # for statelite - cp("$fullpath/$dracutdir/install.statelite","$dracutmpath/install"); - $perm = (stat("$fullpath/$dracutdir/install.statelite"))[2]; - chmod($perm&07777, "$dracutmpath/install"); - cp("$fullpath/$dracutdir/xcat-prepivot.sh",$dracutmpath); + # for statelite + cp("$fullpath/$dracutdir/install.statelite", "$dracutmpath/install"); + $perm = (stat("$fullpath/$dracutdir/install.statelite"))[2]; + chmod($perm & 07777, "$dracutmpath/install"); + + cp("$fullpath/$dracutdir/xcat-prepivot.sh", $dracutmpath); $perm = (stat("$fullpath/$dracutdir/xcat-prepivot.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-prepivot.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-prepivot.sh"); # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); @@ -896,28 +916,28 @@ sub mkinitrd_dracut { print $DRACUTCONF qq{filesystems+="nfs"\n}; close $DRACUTCONF; } elsif ($mode eq "stateless") { - cp("$fullpath/$dracutdir/install.netboot","$dracutmpath/install"); + cp("$fullpath/$dracutdir/install.netboot", "$dracutmpath/install"); $perm = (stat("$fullpath/$dracutdir/install.netboot"))[2]; - chmod($perm&07777, "$dracutmpath/install"); + chmod($perm & 07777, "$dracutmpath/install"); - cp("$fullpath/$dracutdir/xcat-cmdline.sh","$dracutmpath/"); + cp("$fullpath/$dracutdir/xcat-cmdline.sh", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/xcat-cmdline.sh"))[2]; - chmod($perm&07777, "$dracutmpath/xcat-cmdline.sh"); + chmod($perm & 07777, "$dracutmpath/xcat-cmdline.sh"); if ($prinic) { my $optspec; - open($optspec,'>>',"$dracutmpath/xcat-cmdline.sh"); + open($optspec, '>>', "$dracutmpath/xcat-cmdline.sh"); print $optspec "PRINIC=$prinic\n"; close $optspec; } - cp("$fullpath/$dracutdir/xcatroot","$dracutmpath/"); + cp("$fullpath/$dracutdir/xcatroot", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/xcatroot"))[2]; - chmod($perm&07777, "$dracutmpath/xcatroot"); + chmod($perm & 07777, "$dracutmpath/xcatroot"); cp("$fullpath/$dracutdir/installkernel", "$dracutmpath/"); $perm = (stat("$fullpath/$dracutdir/installkernel"))[2]; - chmod($perm&07777, "$dracutmpath/installkernel"); + chmod($perm & 07777, "$dracutmpath/installkernel"); # update etc/dracut.conf open($DRACUTCONF, '>', "$rootimg_dir/etc/dracut.conf"); @@ -929,55 +949,56 @@ sub mkinitrd_dracut { } !system("chroot $rootimg_dir dracut -f /tmp/initrd.$$.gz $kernelver") - or die("Error: failed to generate the initial ramdisk for $mode.\n"); + or die("Error: failed to generate the initial ramdisk for $mode.\n"); print "the initial ramdisk for $mode is generated successfully.\n"; move("$rootimg_dir/tmp/initrd.$$.gz", "$destdir/initrd-$mode.gz"); } sub mkinitrd { - my ($mode) = @_; # statelite or stateless - if($mode eq "statelite") { + my ($mode) = @_; # statelite or stateless + if ($mode eq "statelite") { push @ndrivers, "fscache.ko"; push @ndrivers, "sunrpc.ko"; push @ndrivers, "lockd.ko"; push @ndrivers, "nfs_acl.ko"; push @ndrivers, "auth_rpcgss.ko"; push @ndrivers, "nfs.ko"; - + # Additional modules needed on s390x if ($arch eq "s390x") { + # The network drivers need to be loaded in this order unshift @ndrivers, "ccwgroup.ko"; unshift @ndrivers, "qdio.ko"; } } - - mkpath("/tmp/xcatinitrd.$$/bin"); - - symlink("bin","/tmp/xcatinitrd.$$/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/bin"); - mkpath("/tmp/xcatinitrd.$$/usr/sbin"); - mkpath("/tmp/xcatinitrd.$$/usr/lib"); - mkpath("/tmp/xcatinitrd.$$/usr/lib64"); - mkpath("/tmp/xcatinitrd.$$/lib/firmware"); - mkpath("/tmp/xcatinitrd.$$/lib64/firmware"); - mkpath("/tmp/xcatinitrd.$$/proc"); - mkpath("/tmp/xcatinitrd.$$/sys"); - mkpath("/tmp/xcatinitrd.$$/dev/mapper"); - mkpath("/tmp/xcatinitrd.$$/sysroot"); - mkpath("/tmp/xcatinitrd.$$/etc/ld.so.conf.d"); - mkpath("/tmp/xcatinitrd.$$/etc/udhcpc"); - mkpath("/tmp/xcatinitrd.$$/usr/share/udhcpc"); - mkpath("/tmp/xcatinitrd.$$/var/lib/dhclient"); - mkpath("/tmp/xcatinitrd.$$/lib/modules/$kernelver"); - my $inifile; -# start writing to the init script. - open($inifile,">","/tmp/xcatinitrd.$$/init"); - print $inifile "#!/bin/busybox sh\n"; - -# add some functions - print $inifile <", "/tmp/xcatinitrd.$$/init"); + print $inifile "#!/bin/busybox sh\n"; + + # add some functions + print $inifile < /dev/null && export DEBUG=1 @@ -1418,52 +1441,53 @@ if [ -r /rootimg.sfs ]; then mount --move /ro \$NEWROOT/ro mount --move /rw \$NEWROOT/rw EOMS - print $inifile "elif [ -r /rootimg.gz ]; then\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"rootimg.gz downloaded,setting up RAM-root tmpfs...\"\n"; - print $inifile " echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o \"size=$rootlimit,mode=755\" -t tmpfs rootfs \$NEWROOT\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } - print $inifile " cd \$NEWROOT\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"Extracting root filesystem:\"\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " if [ -x /bin/cpio ]; then\n"; - print $inifile " zcat /rootimg.gz |/bin/cpio -idum\n"; - print $inifile " else\n"; - print $inifile " zcat /rootimg.gz |cpio -idum\n"; - print $inifile " fi\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"Done...\"\n"; - print $inifile " echo Done\n"; - print $inifile "elif [ -r /rootimg.txz ]; then\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"rootimg.txz downloaded,setting up RAM-root tmpfs...\"\n"; - print $inifile " echo Setting up RAM-root tmpfs.\n"; - if ($rootlimit) { - print $inifile " mount -o \"size=$rootlimit,mode=755\" -t tmpfs rootfs \$NEWROOT\n"; - } else { - print $inifile " mount -o mode=755 -t tmpfs rootfs \$NEWROOT\n"; - } - print $inifile " cd \$NEWROOT\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"Extracting root filesystem:\"\n"; - print $inifile " echo -n \"Extracting root filesystem:\"\n"; - print $inifile " tar -Jxvf /rootimg.txz\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"Done...\"\n"; - print $inifile " echo Done\n"; - print $inifile "else\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"Failed to download image, panicing in 5...\"\n"; - print $inifile " echo -n Failed to download image, panicing in 5...\n"; - print $inifile " for i in 4 3 2 1 0; do\n"; - print $inifile " /bin/sleep 5\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"\$i...\"\n"; - print $inifile " echo -n \$i...\n"; - print $inifile " done\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"You're dead. rpower nodename reset to play again.\"\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"* Did you packimage with -m cpio, -m squashfs, or -m nfs?\"\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"* If using -m squashfs did you include aufs.ko with geninitrd? e.g.: -n tg3,squashfs,aufs,loop\"\n"; - print $inifile " ([ \"\$xcatdebugmode\" = \"1\" ] || [ \"\$xcatdebugmode\" = \"2\" ]) && logger -t xcat -p debug \"If using -m nfs did you export NFS and sync rootimg? And did you include the aufs and nfs modules in the proper order: e.g.: -n tg3,aufs,loop,sunrpc,lockd,nfs_acl,nfs\"\n"; - print $inifile " echo\n"; - print $inifile <"."/tmp/xcatinitrd.$$/bin/netstart"); - print $inifile "#!/bin/bash\n"; - print $inifile "udhcpc -n -q -i \${1} -s /usr/share/udhcpc/default.script\n"; - close($inifile); + open($inifile, ">" . "/tmp/xcatinitrd.$$/bin/netstart"); + print $inifile "#!/bin/bash\n"; + print $inifile "udhcpc -n -q -i \${1} -s /usr/share/udhcpc/default.script\n"; + close($inifile); - open($inifile,">"."/tmp/xcatinitrd.$$/usr/share/udhcpc/default.script"); + open($inifile, ">" . "/tmp/xcatinitrd.$$/usr/share/udhcpc/default.script"); -print $inifile <<'EOF'; + print $inifile <<'EOF'; #!/bin/sh # udhcpc script edited by Tim Riker @@ -1542,14 +1566,14 @@ esac exit 0 EOF - - close($inifile); - #if "nonodestatus" specified,do not update the nodestatus - system("mkdir -p /tmp/xcatinitrd.$$/tmp/"); - open($inifile, ">","/tmp/xcatinitrd.$$/tmp/updateflag"); + close($inifile); - print $inifile <", "/tmp/xcatinitrd.$$/tmp/updateflag"); + + print $inifile < /tmp/ncarg @@ -1571,85 +1595,89 @@ else fi EOMS - close($inifile); + close($inifile); - chmod(0755,"/tmp/xcatinitrd.$$/usr/share/udhcpc/default.script"); + chmod(0755, "/tmp/xcatinitrd.$$/usr/share/udhcpc/default.script"); + + chmod(0755, "/tmp/xcatinitrd.$$/init"); + chmod(0755, "/tmp/xcatinitrd.$$/bin/netstart"); + chmod(0755, "/tmp/xcatinitrd.$$/tmp/updateflag"); + @filestoadd = (); + foreach (@ndrivers) { + if (-f "$customdir/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } elsif (-f "$pathtofiles/$_") { + push @filestoadd, [ $_, "lib/$_" ]; + } + } + + # add rsync for statelite + foreach ("usr/bin/dig", "bin/busybox", "bin/bash", "sbin/mount.nfs", "usr/bin/rsync", "sbin/insmod", "sbin/udevd", "sbin/udevadm", "sbin/modprobe", "sbin/blkid", "sbin/depmod", "usr/bin/wget", "usr/bin/xz") { + getlibs($_); + push @filestoadd, $_; + } - chmod(0755,"/tmp/xcatinitrd.$$/init"); - chmod(0755,"/tmp/xcatinitrd.$$/bin/netstart"); - chmod(0755,"/tmp/xcatinitrd.$$/tmp/updateflag"); - @filestoadd=(); - foreach (@ndrivers) { - if (-f "$customdir/$_") { - push @filestoadd,[$_,"lib/$_"]; - } elsif (-f "$pathtofiles/$_") { - push @filestoadd,[$_,"lib/$_"]; - } - } - # add rsync for statelite - foreach ( "usr/bin/dig","bin/busybox","bin/bash", "sbin/mount.nfs", "usr/bin/rsync", "sbin/insmod", "sbin/udevd", "sbin/udevadm", "sbin/modprobe", "sbin/blkid", "sbin/depmod","usr/bin/wget","usr/bin/xz") { - getlibs($_); - push @filestoadd,$_; - } - # Additional binaries needed for udev on s390x if ($arch eq "s390x") { foreach ("sbin/udevsettle", "sbin/udevtrigger", "sbin/udevd", "sbin/depmod") { getlibs($_); - push @filestoadd,$_; + push @filestoadd, $_; } } - - if ($arch =~ /x86_64/) { - push @filestoadd,"lib64/libnss_dns.so.2"; - push @filestoadd,"lib64/libresolv.so.2"; - } elsif ($arch =~ /ppc64el/) { - push @filestoadd,"lib/powerpc64le-linux-gnu/libnss_files.so.2"; - push @filestoadd,"lib/powerpc64le-linux-gnu/libnss_dns.so.2"; - - } else { - push @filestoadd,"lib/libnss_dns.so.2"; - } - push @filestoadd,keys %libhash; - find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + if ($arch =~ /x86_64/) { + push @filestoadd, "lib64/libnss_dns.so.2"; + push @filestoadd, "lib64/libresolv.so.2"; + } elsif ($arch =~ /ppc64el/) { + push @filestoadd, "lib/powerpc64le-linux-gnu/libnss_files.so.2"; + push @filestoadd, "lib/powerpc64le-linux-gnu/libnss_dns.so.2"; - foreach (@filestoadd) { - if (ref($_)) { - #print "$_->[0], $_->[1]\n"; - my $srcpath = "$rootimg_dir/".$_->[0]; - if (-f "$customdir/".$_->[0]) { - $srcpath="$customdir/".$_->[0]; - } elsif (-f "$pathtofiles/".$_->[0]) { - $srcpath="$pathtofiles/".$_->[0]; - } - mkpath(dirname("/tmp/xcatinitrd.$$/".$_->[1])); - copy($srcpath,"/tmp/xcatinitrd.$$/".$_->[1]); - chmod 0755,"/tmp/xcatinitrd.$$/".$_->[1]; - } else { - #print "$_\n"; - my $srcpath = "$rootimg_dir/$_"; - if (-f "$customdir/$_") { - $srcpath = "$customdir/$_"; - } elsif (-f "$pathtofiles/$_") { - $srcpath = "$pathtofiles/$_"; - } - mkpath(dirname("/tmp/xcatinitrd.$$/$_")); - copy("$srcpath","/tmp/xcatinitrd.$$/$_"); - chmod 0755,"/tmp/xcatinitrd.$$/".$_; - } - } + } else { + push @filestoadd, "lib/libnss_dns.so.2"; + } + push @filestoadd, keys %libhash; - if ( -d "$rootimg_dir/lib/firmware/" ){ + find(\&isnetdriver, <$rootimg_dir/lib/modules/$kernelver/*>); + + foreach (@filestoadd) { + if (ref($_)) { + + #print "$_->[0], $_->[1]\n"; + my $srcpath = "$rootimg_dir/" . $_->[0]; + if (-f "$customdir/" . $_->[0]) { + $srcpath = "$customdir/" . $_->[0]; + } elsif (-f "$pathtofiles/" . $_->[0]) { + $srcpath = "$pathtofiles/" . $_->[0]; + } + mkpath(dirname("/tmp/xcatinitrd.$$/" . $_->[1])); + copy($srcpath, "/tmp/xcatinitrd.$$/" . $_->[1]); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_->[1]; + } else { + + #print "$_\n"; + my $srcpath = "$rootimg_dir/$_"; + if (-f "$customdir/$_") { + $srcpath = "$customdir/$_"; + } elsif (-f "$pathtofiles/$_") { + $srcpath = "$pathtofiles/$_"; + } + mkpath(dirname("/tmp/xcatinitrd.$$/$_")); + copy("$srcpath", "/tmp/xcatinitrd.$$/$_"); + chmod 0755, "/tmp/xcatinitrd.$$/" . $_; + } + } + + if (-d "$rootimg_dir/lib/firmware/") { system("cp -r $rootimg_dir/lib/firmware/* /tmp/xcatinitrd.$$/lib/firmware"); } - if ( -d "$rootimg_dir/lib/modules/$kernelver/" ){ + if (-d "$rootimg_dir/lib/modules/$kernelver/") { system("cp $rootimg_dir/lib/modules/$kernelver/modules.builtin /tmp/xcatinitrd.$$/lib/modules/$kernelver/modules.builtin"); system("cp $rootimg_dir/lib/modules/$kernelver/modules.order /tmp/xcatinitrd.$$/lib/modules/$kernelver/modules.order"); } system("chroot /tmp/xcatinitrd.$$/ depmod $kernelver"); + # Copy udev and network scripts into initrd for s390x, which also works for other platforms # udev system("mkdir -p /tmp/xcatinitrd.$$/etc/udev"); @@ -1658,22 +1686,23 @@ EOMS system("cp -r $rootimg_dir/lib/udev/* /tmp/xcatinitrd.$$/lib/udev"); system("mkdir -p /tmp/xcatinitrd.$$/proc/self"); system("cp -r /proc/self/oom_adj /tmp/xcatinitrd.$$/proc/self"); - + # Network related scripts - symlink("busybox","/tmp/xcatinitrd.$$/bin/pivot_root"); + symlink("busybox", "/tmp/xcatinitrd.$$/bin/pivot_root"); symlink("busybox", "/tmp/xcatinitrd.$$/bin/udhcpc"); symlink("busybox", "/tmp/xcatinitrd.$$/sbin/ifconfig"); symlink("busybox", "/tmp/xcatinitrd.$$/bin/hostname"); symlink("busybox", "/tmp/xcatinitrd.$$/bin/route"); symlink("busybox", "/tmp/xcatinitrd.$$/bin/nc"); - symlink("bash", "/tmp/xcatinitrd.$$/bin/sh"); - symlink("bash", "/tmp/xcatinitrd.$$/sbin/sh"); + symlink("bash", "/tmp/xcatinitrd.$$/bin/sh"); + symlink("bash", "/tmp/xcatinitrd.$$/sbin/sh"); + + my $compress = "gzip"; - my $compress="gzip"; #if pigz is available,use pigz instead of gzip - my $ispigz=system("bash -c 'type -p pigz' >/dev/null 2>&1"); - if($ispigz == 0){ - $compress="pigz"; + my $ispigz = system("bash -c 'type -p pigz' >/dev/null 2>&1"); + if ($ispigz == 0) { + $compress = "pigz"; } #copy("$rootimg_dir/lib/modules/*d","/tmp/xcatinitrd.$$/$_"); @@ -1684,140 +1713,143 @@ EOMS } sub isaptdir { - if ($File::Find::name =~ /\/Packages.gz$/) { - my $location = $File::Find::name; - $location =~ s/\/Packages.gz$//; - push @aptdirs,$location; - } + if ($File::Find::name =~ /\/Packages.gz$/) { + my $location = $File::Find::name; + $location =~ s/\/Packages.gz$//; + push @aptdirs, $location; + } } sub isnetdriver { - foreach (@ndrivers) { - if ($File::Find::name =~ /\/$_/) { - my $filetoadd = $File::Find::name; - $filetoadd =~ s!$rootimg_dir/!!; - push @filestoadd,[$filetoadd,"lib/$_"]; - } - } + foreach (@ndrivers) { + if ($File::Find::name =~ /\/$_/) { + my $filetoadd = $File::Find::name; + $filetoadd =~ s!$rootimg_dir/!!; + push @filestoadd, [ $filetoadd, "lib/$_" ]; + } + } } sub postscripts { - generic_post(); + generic_post(); - # TODO: workaround for kdump on RHEL6 - # add one fake command: fsck.nfs - unless ( -x "$rootimg_dir/sbin/fsck.nfs" ) { + # TODO: workaround for kdump on RHEL6 + # add one fake command: fsck.nfs + unless (-x "$rootimg_dir/sbin/fsck.nfs") { system("echo true > $rootimg_dir/sbin/fsck.nfs; chmod a+x $rootimg_dir/sbin/fsck.nfs"); - } - + } - if( ! -d "$rootimg_dir/opt/xcat/") { - mkdir "$rootimg_dir/opt/xcat/"; - } - copy ("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); - chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; + + if (!-d "$rootimg_dir/opt/xcat/") { + mkdir "$rootimg_dir/opt/xcat/"; + } + copy("$installroot/postscripts/xcatdsklspost", "$rootimg_dir/opt/xcat/"); + chmod '0755', "$rootimg_dir/opt/xcat/xcatdsklspost"; } sub generic_post { #This function is meant to leave the image in a state approximating a normal install - my $cfgfile; - unlink("$rootimg_dir/dev/null"); - system("mknod $rootimg_dir/dev/null c 1 3"); - open($cfgfile,">","$rootimg_dir/etc/fstab"); - print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; - print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; - print $cfgfile "proc /proc proc defaults 0 0\n"; - print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; + my $cfgfile; + unlink("$rootimg_dir/dev/null"); + system("mknod $rootimg_dir/dev/null c 1 3"); + open($cfgfile, ">", "$rootimg_dir/etc/fstab"); + print $cfgfile "devpts /dev/pts devpts gid=5,mode=620 0 0\n"; + print $cfgfile "tmpfs /dev/shm tmpfs defaults 0 0\n"; + print $cfgfile "proc /proc proc defaults 0 0\n"; + print $cfgfile "sysfs /sys sysfs defaults 0 0\n"; - if ($tmplimit) { - print $cfgfile "tmpfs /tmp tmpfs defaults,size=$tmplimit 0 2\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=$tmplimit 0 2\n"; - } else { - print $cfgfile "tmpfs /tmp tmpfs defaults 0 2\n"; - print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 2\n"; - } + if ($tmplimit) { + print $cfgfile "tmpfs /tmp tmpfs defaults,size=$tmplimit 0 2\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults,size=$tmplimit 0 2\n"; + } else { + print $cfgfile "tmpfs /tmp tmpfs defaults 0 2\n"; + print $cfgfile "tmpfs /var/tmp tmpfs defaults 0 2\n"; + } - my $rootfs_name=$profile."_".$arch; - print $cfgfile "$rootfs_name / tmpfs rw 0 1\n"; + my $rootfs_name = $profile . "_" . $arch; + print $cfgfile "$rootfs_name / tmpfs rw 0 1\n"; - open($cfgfile,">","$rootimg_dir/etc/resolv.conf"); - print $cfgfile "#Dummy resolv.conf to make boot cleaner"; - close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/resolv.conf"); + print $cfgfile "#Dummy resolv.conf to make boot cleaner"; + close($cfgfile); - # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no - # to skip the break of nfs-based boot - if ($prinic) { - open($cfgfile,">","$rootimg_dir/etc/network/interfaces"); - print $cfgfile "auto $prinic\niface $prinic inet dhcp\n"; - close($cfgfile); - } - foreach (split /,/,$othernics) { - if (/^$/) { next; } - open($cfgfile,">>","$rootimg_dir/etc/network/interfaces"); - print $cfgfile "auto $_\niface $_ inet dhcp\n"; - close($cfgfile); - } - - # securetty not needed on s390x - if ($arch ne "s390x") { - open($cfgfile,">>","$rootimg_dir/etc/securetty"); - print $cfgfile "ttyS0\n"; - print $cfgfile "ttyS1\n"; - close($cfgfile); - } - - my @passwd; - open($cfgfile,"<","$rootimg_dir/etc/passwd"); - @passwd = <$cfgfile>; - close($cfgfile); - open($cfgfile,">","$rootimg_dir/etc/passwd"); - foreach (@passwd) { - if (/^root:/) { - s/^root:\*/root:x/ - } - print $cfgfile $_; - } - close($cfgfile); - foreach (<$rootimg_dir/etc/skel/.*>) { - if (basename($_) eq '.' or basename($_) eq '..') { - next; - } - copy $_,"$rootimg_dir/root/"; - } - unless ( -r <$rootimg_dir/etc/rc3.d/S??network>) { - symlink "/etc/init.d/networking","$rootimg_dir/etc/rc3.d/S10networking"; - } - - # setup the ttyS configure file - open($cfgfile, ">", "$rootimg_dir/etc/init/ttyS.conf"); - print $cfgfile "start on stopped rc RUNLEVEL=[2345] and "; - print $cfgfile "(not-container or container container CONTAINER=lxc or container CONTAINER=lxc-libvirt) \n"; - print $cfgfile "stop on runlevel [!2345] \n"; - print $cfgfile "respawn \n"; - print $cfgfile "script\n"; - print $cfgfile " for i in `cat /proc/cmdline`; do\n"; - print $cfgfile " KEY=`echo \$i|cut -d= -f 1` \n"; - print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then \n"; - print $cfgfile " VALUE=`echo \$i | cut -d= -f 2` \n"; - print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1` \n"; - print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1` \n"; - print $cfgfile " exec /sbin/getty -L \$COSPEED \$COTTY vt102 \n"; - print $cfgfile " break \n"; - print $cfgfile " fi \n"; - print $cfgfile " done\n"; - print $cfgfile "end script\n"; + # Create the ifcfg-x file for diskless node. But keep the ONBOOT=no + # to skip the break of nfs-based boot + if ($prinic) { + open($cfgfile, ">", "$rootimg_dir/etc/network/interfaces"); + print $cfgfile "auto $prinic\niface $prinic inet dhcp\n"; + close($cfgfile); + } + foreach (split /,/, $othernics) { + if (/^$/) { next; } + open($cfgfile, ">>", "$rootimg_dir/etc/network/interfaces"); + print $cfgfile "auto $_\niface $_ inet dhcp\n"; + close($cfgfile); + } - copy("$installroot/postscripts/xcatpostinit", "$rootimg_dir/etc/init.d/xcatpostinit"); - #the ubuntu default run level is 2 - chmod(0755, "$rootimg_dir/etc/init.d/xcatpostinit"); - system("cd $rootimg_dir/etc/rc2.d; ln -sf ../init.d/xcatpostinit S61xcatpostinit"); - #change the /bin/sh link to /bin/bash - system("cd $rootimg_dir/bin/; ln -sf bash sh"); -} + # securetty not needed on s390x + if ($arch ne "s390x") { + open($cfgfile, ">>", "$rootimg_dir/etc/securetty"); + print $cfgfile "ttyS0\n"; + print $cfgfile "ttyS1\n"; + close($cfgfile); + } + + my @passwd; + open($cfgfile, "<", "$rootimg_dir/etc/passwd"); + @passwd = <$cfgfile>; + close($cfgfile); + open($cfgfile, ">", "$rootimg_dir/etc/passwd"); + foreach (@passwd) { + if (/^root:/) { + s/^root:\*/root:x/ + } + print $cfgfile $_; + } + close($cfgfile); + foreach (<$rootimg_dir/etc/skel/.*>) { + if (basename($_) eq '.' or basename($_) eq '..') { + next; + } + copy $_, "$rootimg_dir/root/"; + } + unless (-r <$rootimg_dir/etc/rc3.d/S??network>) { + symlink "/etc/init.d/networking", "$rootimg_dir/etc/rc3.d/S10networking"; + } + + # setup the ttyS configure file + open($cfgfile, ">", "$rootimg_dir/etc/init/ttyS.conf"); + print $cfgfile "start on stopped rc RUNLEVEL=[2345] and "; + print $cfgfile "(not-container or container container CONTAINER=lxc or container CONTAINER=lxc-libvirt) \n"; + print $cfgfile "stop on runlevel [!2345] \n"; + print $cfgfile "respawn \n"; + print $cfgfile "script\n"; + print $cfgfile " for i in `cat /proc/cmdline`; do\n"; + print $cfgfile " KEY=`echo \$i|cut -d= -f 1` \n"; + print $cfgfile " if [ \"\$KEY\" == \"console\" -a \"\$i\" != \"console=tty0\" ]; then \n"; + print $cfgfile " VALUE=`echo \$i | cut -d= -f 2` \n"; + print $cfgfile " COTTY=`echo \$VALUE|cut -d, -f 1` \n"; + print $cfgfile " COSPEED=`echo \$VALUE|cut -d, -f 2|cut -dn -f 1` \n"; + print $cfgfile " exec /sbin/getty -L \$COSPEED \$COTTY vt102 \n"; + print $cfgfile " break \n"; + print $cfgfile " fi \n"; + print $cfgfile " done\n"; + print $cfgfile "end script\n"; + + copy("$installroot/postscripts/xcatpostinit", "$rootimg_dir/etc/init.d/xcatpostinit"); + + #the ubuntu default run level is 2 + chmod(0755, "$rootimg_dir/etc/init.d/xcatpostinit"); + system("cd $rootimg_dir/etc/rc2.d; ln -sf ../init.d/xcatpostinit S61xcatpostinit"); + + #change the /bin/sh link to /bin/bash + system("cd $rootimg_dir/bin/; ln -sf bash sh"); +} my $driver_name; my $real_path; + sub get_path () { if ($File::Find::name =~ /\/$driver_name/) { @@ -1829,14 +1861,14 @@ sub get_path () sub load_dd () { # Get the Driver Update Disk images, it can be .img or .iso - if (! -d "$installroot/driverdisk/$osver/$arch") { + if (!-d "$installroot/driverdisk/$osver/$arch") { return (); } my @dd_list = `find $installroot/driverdisk/$osver/$arch -type f`; chomp(@dd_list); - if (! @dd_list) { + if (!@dd_list) { return (); } @@ -1844,35 +1876,35 @@ sub load_dd () my $dd_dir = mkdtemp("/tmp/ddtmpXXXXXXX"); mkpath "$dd_dir/mnt"; mkpath "$dd_dir/mods"; - + my @dd_drivers = (); #dirver name - + # Loading drivers from each Driver Disk foreach my $dd (@dd_list) { - my $rc = system ("mount -o loop $dd $dd_dir/mnt"); + my $rc = system("mount -o loop $dd $dd_dir/mnt"); if ($rc) { print "mount the Driver Disk $dd failed.\n"; next; } - - if (! (-f "$dd_dir/mnt/rhdd" || -f "$dd_dir/mnt/modinfo" + + if (!(-f "$dd_dir/mnt/rhdd" || -f "$dd_dir/mnt/modinfo" || -f "$dd_dir/mnt/modules.dep" || -f "$dd_dir/mnt/modules.cgz")) { print "The Driver Disk $dd has not correct format.\n"; - system ("umount -f $dd_dir/mnt"); + system("umount -f $dd_dir/mnt"); next; } - + # Load the modinfo open($modinfo, "<", "$dd_dir/mnt/modinfo"); my @modinfo_lines = <$modinfo>; - my $mod_ver = shift @modinfo_lines; + my $mod_ver = shift @modinfo_lines; chomp($mod_ver); if ($mod_ver !~ /^Version 0/) { print "The Driver Disk $dd has unknown version.\n"; - system ("umount -f $dd_dir/mnt"); + system("umount -f $dd_dir/mnt"); next; } - + foreach my $line (@modinfo_lines) { if ($line !~ /^Version/ && $line =~ /^(\w+)/) { chomp($line); @@ -1882,15 +1914,15 @@ sub load_dd () } } close($modinfo); - - # Copy the firmware + + # Copy the firmware if (-d "$dd_dir/mnt/firmware") { - system ("cp -rf $dd_dir/mnt/firmware $rootimg_dir/lib/firmware"); - } + system("cp -rf $dd_dir/mnt/firmware $rootimg_dir/lib/firmware"); + } # Load the modules.cgz - system ("cd $dd_dir/mods; gunzip -c $dd_dir/mnt/modules.cgz |cpio -id"); - if (! -d "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk") { + system("cd $dd_dir/mods; gunzip -c $dd_dir/mnt/modules.cgz |cpio -id"); + if (!-d "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk") { mkpath "$rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"; } @@ -1902,17 +1934,17 @@ sub load_dd () $driver_name = $d; $driver_name =~ s/.*\///; $real_path = ""; - find (\&get_path, <$rootimg_dir/lib/modules/$kernelver/*>); + find(\&get_path, <$rootimg_dir/lib/modules/$kernelver/*>); if ($real_path eq "") { - system ("cp $d $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); + system("cp $d $rootimg_dir/lib/modules/$kernelver/kernel/drivers/driverdisk"); } else { - system ("cp $d $real_path"); + system("cp $d $real_path"); } } rmtree "$dd_dir/mods/*"; - - my $rc = system ("umount -f $dd_dir/mnt"); + + my $rc = system("umount -f $dd_dir/mnt"); if ($rc) { print "umount the directory $dd_dir/mnt failed\n"; exit 1; @@ -1920,7 +1952,7 @@ sub load_dd () } # Generate the dependency relationship - system ("chroot '$rootimg_dir' depmod $kernelver"); + system("chroot '$rootimg_dir' depmod $kernelver"); # Clean the env rmtree "$dd_dir"; @@ -1930,8 +1962,8 @@ sub load_dd () #To hack the uname sub use_hackuname { - unless ( -e "$rootimg_dir/bin/uname-binary") { - if ( -e -x "$rootimg_dir/bin/uname" ) { + unless (-e "$rootimg_dir/bin/uname-binary") { + if (-e -x "$rootimg_dir/bin/uname") { move("$rootimg_dir/bin/uname", "$rootimg_dir/bin/uname-binary"); } } @@ -1958,29 +1990,30 @@ sub use_hackuname { } sub unuse_hackuname { - if ( -e "$rootimg_dir/bin/uname" ) { - system("rm -fr $rootimg_dir/bin/uname"); + if (-e "$rootimg_dir/bin/uname") { + system("rm -fr $rootimg_dir/bin/uname"); } - if ( -e -x "$rootimg_dir/bin/uname-binary") { - move("$rootimg_dir/bin/uname-binary", "$rootimg_dir/bin/uname"); + if (-e -x "$rootimg_dir/bin/uname-binary") { + move("$rootimg_dir/bin/uname-binary", "$rootimg_dir/bin/uname"); } } #service management in a chrooted environment make no sense -#however, the postinstall script of package instllation depends +#however, the postinstall script of package instllation depends #on it, fake a policy-rc.d to avoid errors during installation sub fake_policy_rc_d { -#POLICY-RC.D Policy layer (/usr/sbin/policy-rc.d) interface: -# ============================================================= -# -# Most Debian systems will not have this script as the need for a policy layer -# is not very common. Most people using chroot jails just need an one-line -# script which returns an exit status of 101 as the jailed -# /usr/sbin/policy-rc.d script. -# -# The /usr/sbin/policy-rc.d file *must* be managed through the alternatives -# system (/usr/sbin/update-alternatives) by any packages providing it. + + #POLICY-RC.D Policy layer (/usr/sbin/policy-rc.d) interface: + # ============================================================= + # + # Most Debian systems will not have this script as the need for a policy layer + # is not very common. Most people using chroot jails just need an one-line + # script which returns an exit status of 101 as the jailed + # /usr/sbin/policy-rc.d script. + # + # The /usr/sbin/policy-rc.d file *must* be managed through the alternatives + # system (/usr/sbin/update-alternatives) by any packages providing it. unless (-e "$rootimg_dir/usr/sbin/policy-rc.d") { my $FAKEFILE; @@ -1999,84 +2032,86 @@ sub fake_policy_rc_d { sub mount_chroot { - my $rootimage_dir = shift; - my $otherpkgdir = shift; - my $pkgdir = shift; - my $kerneldir = shift; + my $rootimage_dir = shift; + my $otherpkgdir = shift; + my $pkgdir = shift; + my $kerneldir = shift; - #postinstall script of package installation - #might access the /proc, /sys and /dev filesystem - #mount /proc, /sys from host - #create /dev based on /dev/ on host - system("mkdir -p $rootimage_dir/proc"); - system("mount proc $rootimage_dir/proc -t proc"); - system("mkdir -p $rootimage_dir/sys"); - system("mount sysfs $rootimage_dir/sys -t sysfs"); - system("mkdir -p $rootimage_dir/dev"); - #system("mount devtmpfs $rootimage_dir/dev -t devtmpfs"); - system("cd /dev;find .|cpio -H newc -o >$rootimage_dir/dev/dev.archive;cd -"); - system("cd $rootimage_dir/dev;cpio -idum<./dev.archive;rm -f ./dev.archive;cd -"); + #postinstall script of package installation + #might access the /proc, /sys and /dev filesystem + #mount /proc, /sys from host + #create /dev based on /dev/ on host + system("mkdir -p $rootimage_dir/proc"); + system("mount proc $rootimage_dir/proc -t proc"); + system("mkdir -p $rootimage_dir/sys"); + system("mount sysfs $rootimage_dir/sys -t sysfs"); + system("mkdir -p $rootimage_dir/dev"); + + #system("mount devtmpfs $rootimage_dir/dev -t devtmpfs"); + system("cd /dev;find .|cpio -H newc -o >$rootimage_dir/dev/dev.archive;cd -"); + system("cd $rootimage_dir/dev;cpio -idum<./dev.archive;rm -f ./dev.archive;cd -"); - if ($pkgdir) { - if (-d $pkgdir) { - mkdir("$rootimage_dir/mnt/pkgdir"); - system("mount --rbind $pkgdir $rootimage_dir/mnt/pkgdir; mount -o remount,ro,rbind $pkgdir $rootimage_dir/mnt/pkgdir"); - } else { - print "The specified pkgdir $pkgdir does not exist!\n" - } - } + if ($pkgdir) { + if (-d $pkgdir) { + mkdir("$rootimage_dir/mnt/pkgdir"); + system("mount --rbind $pkgdir $rootimage_dir/mnt/pkgdir; mount -o remount,ro,rbind $pkgdir $rootimage_dir/mnt/pkgdir"); + } else { + print "The specified pkgdir $pkgdir does not exist!\n" + } + } - if ($kerneldir){ - if(-d $kerneldir){ - mkdir("$rootimage_dir/mnt/kerneldir"); - system("mount --rbind $kerneldir $rootimage_dir/mnt/kerneldir; mount -o remount,ro,rbind $kerneldir $rootimage_dir/mnt/kerneldir"); - }else{ - print "The specified kerneldir $kerneldir does not exist!\n" - } - } + if ($kerneldir) { + if (-d $kerneldir) { + mkdir("$rootimage_dir/mnt/kerneldir"); + system("mount --rbind $kerneldir $rootimage_dir/mnt/kerneldir; mount -o remount,ro,rbind $kerneldir $rootimage_dir/mnt/kerneldir"); + } else { + print "The specified kerneldir $kerneldir does not exist!\n" + } + } - if ($otherpkgdir){ - mkdir("$rootimage_dir/mnt/otherpkgdir"); - if(-d $otherpkgdir){ - system("mount --rbind $otherpkgdir $rootimage_dir/mnt/otherpkgdir; mount -o remount,ro,rbind $otherpkgdir $rootimage_dir/mnt/otherpkgdir"); - }else{ - print "The specified otherpkgdir $otherpkgdir does not exist!\n" - } - } + if ($otherpkgdir) { + mkdir("$rootimage_dir/mnt/otherpkgdir"); + if (-d $otherpkgdir) { + system("mount --rbind $otherpkgdir $rootimage_dir/mnt/otherpkgdir; mount -o remount,ro,rbind $otherpkgdir $rootimage_dir/mnt/otherpkgdir"); + } else { + print "The specified otherpkgdir $otherpkgdir does not exist!\n" + } + } } sub umount_chroot { - my $rootimage_dir = shift; + my $rootimage_dir = shift; - system("umount -l $rootimage_dir/proc"); - system("umount -l $rootimage_dir/sys"); - #system("umount -l $rootimage_dir/dev"); - system("rm -rf $rootimage_dir/dev/*"); + system("umount -l $rootimage_dir/proc"); + system("umount -l $rootimage_dir/sys"); - system("umount -l $rootimage_dir/mnt/pkgdir"); - rmdir("$rootimage_dir/mnt/pkgdir"); + #system("umount -l $rootimage_dir/dev"); + system("rm -rf $rootimage_dir/dev/*"); - my @data = `grep /mnt/otherpkgdir /proc/mounts | cut -f2 -d' ' | sort -r`; - foreach (@data) { - `umount -l $_`; - } - rmdir("$rootimage_dir/mnt/otherpkgdir"); + system("umount -l $rootimage_dir/mnt/pkgdir"); + rmdir("$rootimage_dir/mnt/pkgdir"); - if (-d "$rootimage_dir/mnt/kerneldir") { - system("umount -l $rootimage_dir/mnt/kerneldir"); - rmdir("$rootimage_dir/mnt/kerneldir"); - } + my @data = `grep /mnt/otherpkgdir /proc/mounts | cut -f2 -d' ' | sort -r`; + foreach (@data) { + `umount -l $_`; + } + rmdir("$rootimage_dir/mnt/otherpkgdir"); + + if (-d "$rootimage_dir/mnt/kerneldir") { + system("umount -l $rootimage_dir/mnt/kerneldir"); + rmdir("$rootimage_dir/mnt/kerneldir"); + } } sub usage { - print 'Usage: genimage [ -i ] [ -n ] [-r ] -o -p -k [--permission ] [--interactive]'."\n"; - print " --permission only works with statelite mode\n"; - print "Examples:\n"; - print " genimage -i eth0 -n tg3 -o centos5.1 -p compute \n"; - print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot\n"; - print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot --permission 777\n"; + print 'Usage: genimage [ -i ] [ -n ] [-r ] -o -p -k [--permission ] [--interactive]' . "\n"; + print " --permission only works with statelite mode\n"; + print "Examples:\n"; + print " genimage -i eth0 -n tg3 -o centos5.1 -p compute \n"; + print " genimage -i eth0 -r eth1,eth2 -n tg3,bnx2 -o centos5.1 -p compute --interactive\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot\n"; + print " genimage -i eth0 -n igb,e1000e,e1000,bnx2,tg3 -o centos5.4 -p nfsroot --permission 777\n"; return 0; } diff --git a/xCAT-server/share/xcat/scripts/cfm2xcat b/xCAT-server/share/xcat/scripts/cfm2xcat index a9578b2ae..0d481303e 100755 --- a/xCAT-server/share/xcat/scripts/cfm2xcat +++ b/xCAT-server/share/xcat/scripts/cfm2xcat @@ -44,9 +44,9 @@ my $rc = 0; if ( !GetOptions( - 'h|help' => \$help, - 'i|input=s' => \$input, - 'o|output=s' => \$output, + 'h|help' => \$help, + 'i|input=s' => \$input, + 'o|output=s' => \$output, ) ) { @@ -72,7 +72,7 @@ if (!($output)) # call cfmupdatenode and build cfm distribution files &buildcfmdistfiles($input); -if (-e ($input)) # if anything built +if (-e ($input)) # if anything built { # build the xcat sync files @@ -81,7 +81,7 @@ if (-e ($input)) # if anything built if ($rc == 0) { print - "Conversion finished, please carefully review $output files! Make sure that all the files list to sync to the nodes are relevant and available on the xCAT system in the directory indicated. \n"; +"Conversion finished, please carefully review $output files! Make sure that all the files list to sync to the nodes are relevant and available on the xCAT system in the directory indicated. \n"; } else { @@ -200,12 +200,12 @@ sub buildxcatsyncfile_new { if ($line =~ /^#/) { # skip commments next; } - if ($line =~ /.runclocal/) { # skip sending runclocal + if ($line =~ /.runclocal/) { # skip sending runclocal next; } - my ($sourcefile, $rest) = split("->", $line); - my ($tmpnodes, $destfile) = split("install", $rest); - my ($root2, $strippeddestfile) = split("cfmlocal", $destfile); + my ($sourcefile, $rest) = split("->", $line); + my ($tmpnodes, $destfile) = split("install", $rest); + my ($root2, $strippeddestfile) = split("cfmlocal", $destfile); chomp $strippeddestfile; chop $strippeddestfile; $destfile = $strippeddestfile; @@ -220,6 +220,7 @@ sub buildxcatsyncfile_new { my $goodnr = ""; foreach my $node (@nodes) { if ($node !~ /^\s*$/) { + #skip blanks my @shorthost = split(/\./, $node); $goodnr .= $shorthost[0]; @@ -235,12 +236,12 @@ sub buildxcatsyncfile_new { } open(XCATSF, "> $xcatfile") - or die "Can't open $xcatfile for writing: $!"; + or die "Can't open $xcatfile for writing: $!"; foreach (@xcatsyncfile) { - print XCATSF $_."\n"; + print XCATSF $_ . "\n"; } - close (XCATSF); + close(XCATSF); return 0; } @@ -383,7 +384,7 @@ sub buildxcatrsyncfiles or die "Can't open $newxcatfile for writing: $!"; my $srcfile; my $destfile; - foreach my $sourcefile (keys %{$noderangequeue{$noderange}{'files'}}) + foreach my $sourcefile (keys %{ $noderangequeue{$noderange}{'files'} }) { $srcfile = $sourcefile; $destfile = $noderangequeue{$noderange}{'files'}{$sourcefile}; @@ -438,7 +439,7 @@ sub usage "\t-o - Complete Path to the xCAT xdcp rsync input file(s) created from."; print " the CFM file. Be sure directory exists.\n"; print - " Example: cfm2xcat -i /tmp/migration/cfmfiles -o /tmp/migration/xdcpfiles."; +" Example: cfm2xcat -i /tmp/migration/cfmfiles -o /tmp/migration/xdcpfiles."; print "\n"; return; } diff --git a/xCAT-server/share/xcat/scripts/csm2xcat b/xCAT-server/share/xcat/scripts/csm2xcat index b6782b629..a68a19f7e 100755 --- a/xCAT-server/share/xcat/scripts/csm2xcat +++ b/xCAT-server/share/xcat/scripts/csm2xcat @@ -19,8 +19,8 @@ my $needhelp = 0; my $directory = "/tmp/csm2xcat"; if ( - !GetOptions("help" => \$needhelp, - "dir=s" => \$directory,) + !GetOptions("help" => \$needhelp, + "dir=s" => \$directory,) ) { &usage; @@ -54,7 +54,7 @@ open(LOG, ">$directory/conversion.log") log_this("Conversion finished at " . scalar(localtime())); print - "Conversion finished, please carefully review $directory/conversion.log and check results in the $directory stanza files before using chdef -z to update the database!\n"; +"Conversion finished, please carefully review $directory/conversion.log and check results in the $directory stanza files before using chdef -z to update the database!\n"; close(LOG); exit 0; @@ -273,12 +273,12 @@ sub getNodeinfo { #if ($attr eq "InstallServer") #{ - # if ($value) - # { - # $xcatline = " xcatmaster=$value\n"; - # $xcatline .= " servicenode=$value\n"; + # if ($value) + # { + # $xcatline = " xcatmaster=$value\n"; + # $xcatline .= " servicenode=$value\n"; - #} + #} #} # since we are suggesting that the xCAT MN is a different machine # than the CSM MS, we will not use the Management Server value @@ -307,7 +307,7 @@ sub getNodeinfo } if ($attr eq "InstallDistributionVersion") { - if ( $value + if ($value && $DISTNAME) # put together DistributeName and Version { $xcatline = " os=$DISTNAME"; @@ -335,7 +335,7 @@ sub getNodeinfo } if ($attr eq "HWControlPoint") { - if ($value) + if ($value) { $xcatline = " hcp=$value\n"; } @@ -500,7 +500,7 @@ sub getDevinfo my $xcatline; my $attr; - my $grplist = get_dev_groups($nodename); + my $grplist = get_dev_groups($nodename); my $shortnodename = get_shortname($nodename); $xcatline = "$shortnodename:\n"; # write node name $xcatline .= " objtype=node\n"; @@ -526,8 +526,8 @@ sub getDevinfo my $lcvalue = lc($value); $xcatline = " nodetype=ppc\n"; if ($lcvalue eq "hmc") { - $xcatline .= " mgt=$lcvalue\n"; - $xcatline .= " hwtype=$lcvalue\n"; + $xcatline .= " mgt=$lcvalue\n"; + $xcatline .= " hwtype=$lcvalue\n"; } } } @@ -701,7 +701,7 @@ sub runcmd @$outref = `$cmd`; if ($?) { - $rc = $? ; + $rc = $?; $::RUNCMD_RC = $rc; if ($rc > 0) { @@ -719,11 +719,11 @@ sub usage { print "CSM database to xCAT stanza files migration utility.\n"; print - "Reads the CSM database and creates xCAT stanza files that \ncan be imported using the chdef command into the xCAT database.\n"; +"Reads the CSM database and creates xCAT stanza files that \ncan be imported using the chdef command into the xCAT database.\n"; print "Usage:\n"; print "\t--help - usage\n"; print - "\t--dir - output directory for stanza files.\n Default is /tmp/csm2xcat.\n"; +"\t--dir - output directory for stanza files.\n Default is /tmp/csm2xcat.\n"; print "\n"; return; } diff --git a/xCAT-server/share/xcat/scripts/insptbls b/xCAT-server/share/xcat/scripts/insptbls index 1f83313aa..0957416b6 100755 --- a/xCAT-server/share/xcat/scripts/insptbls +++ b/xCAT-server/share/xcat/scripts/insptbls @@ -8,7 +8,7 @@ # requires xCAT to be installed because it uses xCAT Perl libraries # and xCAT commands # The output is put in /tmp/.output -# for example /tmp/SITE.out +# for example /tmp/SITE.out # ##################################################### BEGIN @@ -25,7 +25,7 @@ use strict; use warnings; -# Use runsqlcmd to run the SQL query to read the list of tables in +# Use runsqlcmd to run the SQL query to read the list of tables in # the XCATDB schema # Then use runsqlcmd to run the inspect on the list of tables, # @@ -33,99 +33,104 @@ my $tablelist; my $help; my $cmd; my @tablist; -GetOptions( 'V|verbose' => \$::VERBOSE, - 't=s' => \$tablelist, - 'h|help' => \$help,); +GetOptions('V|verbose' => \$::VERBOSE, + 't=s' => \$tablelist, + 'h|help' => \$help,); if ($help) { print "DB2 Table Inspect utility.\n"; print - "The script is run on the command line to inspect the xcatdb DB2 database tables.\n"; - print "Output indicates whether compression should be set on the table.\n"; - print "Output is put in /tmp/.output. For example /tmp/SITE.out.\n"; +"The script is run on the command line to inspect the xcatdb DB2 database tables.\n"; + print "Output indicates whether compression should be set on the table.\n"; + print "Output is put in /tmp/.output. For example /tmp/SITE.out.\n"; print "Usage:\n"; print "\t--V - Verbose mode\n"; print "\t--h - usage\n"; print - "\t--t -comma delimitated list of tables.\n Without this flag it inspects all tables in the xcatdb database .\n"; +"\t--t -comma delimitated list of tables.\n Without this flag it inspects all tables in the xcatdb database .\n"; print "\n"; exit 0; } + # check to see if running DB2 my $DBname = xCAT::Utils->get_DBName; if ($DBname ne "DB2") { - - print " Inspect of table only supported for DB2 database\n"; - `logger -p local4.err -t xcat "insptbls:Only supports DB2 database"` ; + + print " Inspect of table only supported for DB2 database\n"; + `logger -p local4.err -t xcat "insptbls:Only supports DB2 database"`; exit 1; - + } -if ($tablelist) { # input list of tables - @tablist=split(/\,/, $tablelist); -} else { # get all tables - $cmd="$::XCATROOT/sbin/runsqlcmd \"select tabname from syscat.tables where TABSCHEMA='XCATDB';\""; - @tablist = xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - `logger -p local4.err -t xcat " insptbls:error in select tabname from syscat.tables"` ; - exit 1; - } +if ($tablelist) { # input list of tables + @tablist = split(/\,/, $tablelist); +} else { # get all tables + $cmd = "$::XCATROOT/sbin/runsqlcmd \"select tabname from syscat.tables where TABSCHEMA='XCATDB';\""; + @tablist = xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { +`logger -p local4.err -t xcat " insptbls:error in select tabname from syscat.tables"`; + exit 1; + } } + # get xcatdb home directory my $homedir = xCAT::Utils->getHomeDir("xcatdb"); my $execdir = $homedir; -$execdir .="\/sqllib\/db2dump\/"; -#inspect each table -my $foundheader=0; -foreach my $table (@tablist) { - chomp $table; - # skip lines untils we find the header unless -t option - if (!($tablelist)) { - if ($foundheader==0) { - if ( !($table =~ /TABNAME/)) { - next; - } else { - $foundheader=1; - next; - } - } - } - # skip blanks and -- lines - $table =~ s/\s*//g; # remove blanks - if ($table =~ /^\s*$/) { # skip blanks - next; - } - if ($table =~ m/[^a-zA-Z0-9_]/) # skip non alphanumeric lines not underscore - { - next; - } - $table =~ tr/a-z/A-Z/; # convert to upper - if ($::VERBOSE) { - print "Inspect of table $table\n"; - } - $cmd = " rm /tmp/$table.out"; # cleanup - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - `logger -p local4.warning -t xcat " insptbls:error $cmd"`; - } else { - `logger -p local4.info -t xcat " insptbls: $cmd"`; - } - $cmd="$::XCATROOT/sbin/runsqlcmd \"INSPECT ROWCOMPESTIMATE TABLE NAME $table results keep $table.res;\""; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - `logger -p local4.warning -t xcat " insptbls:error INSPECT ROWCOMPESTIMATE TABLE NAME $table"`; - } else { - `logger -p local4.info -t xcat " insptbls: INSPECT ROWCOMPESTIMATE TABLE NAME $table"`; - } - $cmd=" \"db2inspf $execdir$table.res /tmp/$table.out;\""; - system("su - xcatdb -c $cmd"); +$execdir .= "\/sqllib\/db2dump\/"; - if ($? > 0) # error - { - `logger -p local4.warning -t xcat "insptbls:error db2inspf $table.res"`; - } else { - `logger -p local4.info -t xcat " insptbls:db2inspf $table.res"`; - } +#inspect each table +my $foundheader = 0; +foreach my $table (@tablist) { + chomp $table; + + # skip lines untils we find the header unless -t option + if (!($tablelist)) { + if ($foundheader == 0) { + if (!($table =~ /TABNAME/)) { + next; + } else { + $foundheader = 1; + next; + } + } + } + + # skip blanks and -- lines + $table =~ s/\s*//g; # remove blanks + if ($table =~ /^\s*$/) { # skip blanks + next; + } + if ($table =~ m/[^a-zA-Z0-9_]/) # skip non alphanumeric lines not underscore + { + next; + } + $table =~ tr/a-z/A-Z/; # convert to upper + if ($::VERBOSE) { + print "Inspect of table $table\n"; + } + $cmd = " rm /tmp/$table.out"; # cleanup + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + `logger -p local4.warning -t xcat " insptbls:error $cmd"`; + } else { + `logger -p local4.info -t xcat " insptbls: $cmd"`; + } + $cmd = "$::XCATROOT/sbin/runsqlcmd \"INSPECT ROWCOMPESTIMATE TABLE NAME $table results keep $table.res;\""; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { +`logger -p local4.warning -t xcat " insptbls:error INSPECT ROWCOMPESTIMATE TABLE NAME $table"`; + } else { +`logger -p local4.info -t xcat " insptbls: INSPECT ROWCOMPESTIMATE TABLE NAME $table"`; + } + $cmd = " \"db2inspf $execdir$table.res /tmp/$table.out;\""; + system("su - xcatdb -c $cmd"); + + if ($? > 0) # error + { + `logger -p local4.warning -t xcat "insptbls:error db2inspf $table.res"`; + } else { + `logger -p local4.info -t xcat " insptbls:db2inspf $table.res"`; + } } exit 0; diff --git a/xCAT-server/share/xcat/scripts/mkay4z b/xCAT-server/share/xcat/scripts/mkay4z index be9d342c4..2f4a10995 100644 --- a/xCAT-server/share/xcat/scripts/mkay4z +++ b/xCAT-server/share/xcat/scripts/mkay4z @@ -19,14 +19,14 @@ use warnings; # Show help if (@ARGV > 0) { - print < { - 'device_name' => '/dev/dasda', - 'type' => 'dasd_eckd_mod' - }, - '0.0.0101' => { - 'device_name' => '/dev/dasdb', - 'type' => 'dasd_eckd_mod' - } + '0.0.0100' => { + 'device_name' => '/dev/dasda', + 'type' => 'dasd_eckd_mod' + }, + '0.0.0101' => { + 'device_name' => '/dev/dasdb', + 'type' => 'dasd_eckd_mod' + } ); my %partitions_default = ( - '/dev/dasda' => { - 'device_fs' => 'ext4', - 'device_size' => 'max', - 'device_mount' => '', - 'device_lvm' => 'VG' - }, - '/dev/dasdb' => { - 'device_fs' => 'ext4', - 'device_size' => 'max', - 'device_mount' => '', - 'device_lvm' => 'VG' - }, - '/dev/VG' => { - 'lvm' => { - 'lv_root' => { - 'name' => 'lv_root', - 'fs' => 'ext4', - 'mount' => '/', - 'size' => '4g' - }, - 'lv_opt' => { - 'name' => 'lv_opt', - 'fs' => 'ext4', - 'mount' => '/opt', - 'size' => 'max' - } - } - } + '/dev/dasda' => { + 'device_fs' => 'ext4', + 'device_size' => 'max', + 'device_mount' => '', + 'device_lvm' => 'VG' + }, + '/dev/dasdb' => { + 'device_fs' => 'ext4', + 'device_size' => 'max', + 'device_mount' => '', + 'device_lvm' => 'VG' + }, + '/dev/VG' => { + 'lvm' => { + 'lv_root' => { + 'name' => 'lv_root', + 'fs' => 'ext4', + 'mount' => '/', + 'size' => '4g' + }, + 'lv_opt' => { + 'name' => 'lv_opt', + 'fs' => 'ext4', + 'mount' => '/opt', + 'size' => 'max' + } + } + } ); # Set default parameters for networking and root password # DHCP is set by default, but can changed based on user input my %parms = ( - 'hosts' => { - 'localhost' => { - 'host_address' => '127.0.0.1', - 'name' => 'localhost' - }, - 'xcat' => { - 'host_address' => 'replace_host_address', - 'name' => 'replace_long_name replace_short_name' - } - }, - 'dns' => { - 'xcat' => { - 'hostname' => 'replace_hostname', - 'dhcp_hostname' => 'true', - 'dhcp_resolv' => 'true', - 'domain' => 'replace_domain', - 'nameserver' => 'replace_nameserver' - } - }, - 'interfaces' => { - 'xcat' => { - 'bootproto' => 'dhcp', - 'device' => 'replace_device', - 'lladdr' => 'replace_lladdr', - 'chanids' => 'replace_ccw_chan_ids' - } - }, - 'root_password' => 'replace_root_password', - 'software' => 'Minimal' + 'hosts' => { + 'localhost' => { + 'host_address' => '127.0.0.1', + 'name' => 'localhost' + }, + 'xcat' => { + 'host_address' => 'replace_host_address', + 'name' => 'replace_long_name replace_short_name' + } + }, + 'dns' => { + 'xcat' => { + 'hostname' => 'replace_hostname', + 'dhcp_hostname' => 'true', + 'dhcp_resolv' => 'true', + 'domain' => 'replace_domain', + 'nameserver' => 'replace_nameserver' + } + }, + 'interfaces' => { + 'xcat' => { + 'bootproto' => 'dhcp', + 'device' => 'replace_device', + 'lladdr' => 'replace_lladdr', + 'chanids' => 'replace_ccw_chan_ids' + } + }, + 'root_password' => 'replace_root_password', + 'software' => 'Minimal' ); # Configure interfaces (static or dhcp) my $dhcp = ''; while (!($dhcp eq 'Y' || $dhcp eq 'y' || $dhcp eq 'Yes' || $dhcp eq 'yes' || $dhcp eq 'N' || $dhcp eq 'n' || $dhcp eq 'No' || $dhcp eq 'no')) { - $dhcp = ask(" Do you want to use DHCP? (yes or no) "); - - if ($dhcp eq 'Y' || $dhcp eq 'y' || $dhcp eq 'Yes' || $dhcp eq 'yes') { - $parms{'interfaces'} = { - 'xcat' => { - 'bootproto' => 'dhcp', - 'device' => 'replace_device', - 'lladdr' => 'replace_lladdr', - 'chanids' => 'replace_ccw_chan_ids' - } - }; - } elsif ($dhcp eq 'N' || $dhcp eq 'n' || $dhcp eq 'No' || $dhcp eq 'no') { - $parms{'interfaces'} = { - 'xcat' => { - 'bootproto' => 'static', - 'device' => 'replace_device', - 'lladdr' => 'replace_lladdr', - 'ipaddr' => 'replace_ipaddr', - 'netmask' => 'replace_netmask', - 'gateway' => 'replace_gateway', - 'broadcast' => 'replace_broadcast', - 'network' => 'replace_network', - 'chanids' => 'replace_ccw_chan_ids' - } - }; - } else { - print " Unknown value!\n"; - } + $dhcp = ask(" Do you want to use DHCP? (yes or no) "); + + if ($dhcp eq 'Y' || $dhcp eq 'y' || $dhcp eq 'Yes' || $dhcp eq 'yes') { + $parms{'interfaces'} = { + 'xcat' => { + 'bootproto' => 'dhcp', + 'device' => 'replace_device', + 'lladdr' => 'replace_lladdr', + 'chanids' => 'replace_ccw_chan_ids' + } + }; + } elsif ($dhcp eq 'N' || $dhcp eq 'n' || $dhcp eq 'No' || $dhcp eq 'no') { + $parms{'interfaces'} = { + 'xcat' => { + 'bootproto' => 'static', + 'device' => 'replace_device', + 'lladdr' => 'replace_lladdr', + 'ipaddr' => 'replace_ipaddr', + 'netmask' => 'replace_netmask', + 'gateway' => 'replace_gateway', + 'broadcast' => 'replace_broadcast', + 'network' => 'replace_network', + 'chanids' => 'replace_ccw_chan_ids' + } + }; + } else { + print " Unknown value!\n"; + } } # Hash array containing autoyast configuration @@ -184,105 +184,109 @@ print <; - $dasd_option = trim($dasd_option); - while (!($dasd_option eq '1' || $dasd_option eq '2' || $dasd_option eq '3' || $dasd_option eq '4')) { - print " Unknown value!\n"; - $dasd_option = <>; - $dasd_option = trim($dasd_option); - } - - # Add dasd to template - if ($dasd_option eq '1') { - # Get virtual address - $addr = ask(" What is the virtual address? "); - while (length($addr) < 4) { # Address length must be 4 - $addr = '0' . $addr; - } - $addr = '0.0.' . $addr; - - # Get dasd type - $ask = 1; - while ($ask) { - $dasd_type = ask(" What is the type? (eckd or fba) "); - if ($dasd_type eq 'eckd') { - $dasd_type = 'dasd_eckd_mod'; - $ask = 0; - } elsif ($dasd_type eq 'fba') { - $dasd_type = 'dasd_fba_mod'; - $ask = 0; - } else { - print " Unknown value!\n"; - } - } - - # Save dasd in hash - $dasd{$addr}{'type'} = $dasd_type; - } - - # Remove dasd from template - elsif ($dasd_option eq '2') { - $addr = ask(" What is the virtual address to remove? "); - while (length($addr) < 4) { # Address length must be 4 - $addr = '0' . $addr; - } - $addr = '0.0.' . $addr; - - # Remove from hash - delete $dasd{$addr}; - } + $dasd_option = <>; + $dasd_option = trim($dasd_option); + while (!($dasd_option eq '1' || $dasd_option eq '2' || $dasd_option eq '3' || $dasd_option eq '4')) { + print " Unknown value!\n"; + $dasd_option = <>; + $dasd_option = trim($dasd_option); + } - elsif ($dasd_option eq '3') { - # Show configuration - print < @device_list) { - print " Unknown value!\n"; - redo; - } - - # Only configure if a device is selected - if (length($selected)) { - $selected = int($selected); - - @args = split(' ', $device_list[$selected]); - $device_name = $args[0]; + $selected = ask("Which device do you want to configure? (See list above)\nLeave blank and hit Enter to go to next step.\n"); + if ($selected && int($selected) > @device_list) { + print " Unknown value!\n"; + redo; + } - # Get device filesystem - $device_fs = ''; - while (!($device_fs eq 'ext2' || $device_fs eq 'ext3' || $device_fs eq 'ext4' || $device_fs eq 'swap')) { - $device_fs = ask(" What is the filesystem for $device_name? (ext2, ext3, ext4, or swap) "); - - if (!($device_fs eq 'ext2' || $device_fs eq 'ext3' || $device_fs eq 'ext4' || $device_fs eq 'swap')) { - print " Unknown value!\n"; - } - } - - # Get partition size - $device_size = ''; - while (!$device_size) { - $device_size = ask(" What is the partition size? (e.g. 1g, 2g, or max) "); - if (!$device_size) { - print " Please give a partition size!"; - } - } - - # Is partition an LVM - $lvm = ''; - while (!($lvm eq 'Y' || $lvm eq 'y' || $lvm eq 'Yes' || $lvm eq 'yes' || $lvm eq 'N' || $lvm eq 'n' || $lvm eq 'No' || $lvm eq 'no')) { - $lvm = ask(" Do you want to assign it to an LVM group? (yes or no) "); - $lvm_group = ""; - $device_mount = ""; - - if ($lvm eq 'Y' || $lvm eq 'y' || $lvm eq 'Yes' || $lvm eq 'yes') { - # Get partition LVM group - $lvm_group = ask(" What is the LVM group? "); - $ask_lvm = 1; - - # Create new entry for volume group - $tmp = '/dev/' . $lvm_group; - $partitions{$tmp}{'device_lvm'} = $lvm_group; - } elsif ($lvm eq 'N' || $lvm eq 'n' || $lvm eq 'No' || $lvm eq 'no') { - # Get partition mount point - $device_mount = ask(" What is the mount point? "); - } else { - print " Unknown value!\n"; - } - } - - # Save dasd in hash - $partitions{$device_name}{'device_fs'} = $device_fs; - $partitions{$device_name}{'device_size'} = $device_size; - $partitions{$device_name}{'device_mount'} = $device_mount; - $partitions{$device_name}{'device_lvm'} = $lvm_group; - } else { - $ask = 0; - } + # Only configure if a device is selected + if (length($selected)) { + $selected = int($selected); + + @args = split(' ', $device_list[$selected]); + $device_name = $args[0]; + + # Get device filesystem + $device_fs = ''; + while (!($device_fs eq 'ext2' || $device_fs eq 'ext3' || $device_fs eq 'ext4' || $device_fs eq 'swap')) { + $device_fs = ask(" What is the filesystem for $device_name? (ext2, ext3, ext4, or swap) "); + + if (!($device_fs eq 'ext2' || $device_fs eq 'ext3' || $device_fs eq 'ext4' || $device_fs eq 'swap')) { + print " Unknown value!\n"; + } + } + + # Get partition size + $device_size = ''; + while (!$device_size) { + $device_size = ask(" What is the partition size? (e.g. 1g, 2g, or max) "); + if (!$device_size) { + print " Please give a partition size!"; + } + } + + # Is partition an LVM + $lvm = ''; + while (!($lvm eq 'Y' || $lvm eq 'y' || $lvm eq 'Yes' || $lvm eq 'yes' || $lvm eq 'N' || $lvm eq 'n' || $lvm eq 'No' || $lvm eq 'no')) { + $lvm = ask(" Do you want to assign it to an LVM group? (yes or no) "); + $lvm_group = ""; + $device_mount = ""; + + if ($lvm eq 'Y' || $lvm eq 'y' || $lvm eq 'Yes' || $lvm eq 'yes') { + + # Get partition LVM group + $lvm_group = ask(" What is the LVM group? "); + $ask_lvm = 1; + + # Create new entry for volume group + $tmp = '/dev/' . $lvm_group; + $partitions{$tmp}{'device_lvm'} = $lvm_group; + } elsif ($lvm eq 'N' || $lvm eq 'n' || $lvm eq 'No' || $lvm eq 'no') { + + # Get partition mount point + $device_mount = ask(" What is the mount point? "); + } else { + print " Unknown value!\n"; + } + } + + # Save dasd in hash + $partitions{$device_name}{'device_fs'} = $device_fs; + $partitions{$device_name}{'device_size'} = $device_size; + $partitions{$device_name}{'device_mount'} = $device_mount; + $partitions{$device_name}{'device_lvm'} = $lvm_group; + } else { + $ask = 0; + } } # Configure LVM partitions my @lvm_list; if ($ask_lvm) { - print <; - - # Add an LVM volume to template - if ($lvm_option eq '1') { - # Get dasd virtual address - $lvm_vol_name = ask(" What is the LVM volume name? "); - - # Get device filesystem - $lvm_vol_fs = ''; - while (!($lvm_vol_fs eq 'ext2' || $lvm_vol_fs eq 'ext3' || $lvm_vol_fs eq 'ext4' || $lvm_vol_fs eq 'swap')) { - $lvm_vol_fs = ask(" What is the LVM volume filesystem? (ext2, ext3, ext4, or swap) "); - - if (!($lvm_vol_fs eq 'ext2' || $lvm_vol_fs eq 'ext3' || $lvm_vol_fs eq 'ext4' || $lvm_vol_fs eq 'swap')) { - print " Unknown value!\n"; - } - } - - # Get partition mount point - $lvm_vol_mount = ask(" what is the Mount point? "); - - # Get partition size - $lvm_vol_size = ask(" What is the LVM volume size? (e.g. 1g, 2g, or max) "); - - # Save dasd in hash - $partitions{$device_name}{'lvm'}{$lvm_vol_name} = { - 'fs' => $lvm_vol_fs, - 'name' => $lvm_vol_name, - 'mount' => $lvm_vol_mount, - 'size' => $lvm_vol_size - }; - } - - # Remove an LVM volume from template - elsif ($lvm_option eq '2') { - my $name = ask(" What is the LVM volume to remove? "); - - # Remove from hash - delete $partitions{$device_name}{'lvm'}{$name}; - } + $lvm_option = <>; - elsif ($lvm_option eq '3') { - # Show configuration - print < $lvm_vol_fs, + 'name' => $lvm_vol_name, + 'mount' => $lvm_vol_mount, + 'size' => $lvm_vol_size + }; + } + + # Remove an LVM volume from template + elsif ($lvm_option eq '2') { + my $name = ask(" What is the LVM volume to remove? "); + + # Remove from hash + delete $partitions{$device_name}{'lvm'}{$name}; + } + + elsif ($lvm_option eq '3') { + + # Show configuration + print < section @@ -504,7 +513,7 @@ my $partitionsSection = createPartitions(\%dasd, \%partitions); # Create section my $dasdModulesSection = createDasdModules(\%dasd); -my $nicModulesSection = createNicModules($parms{'interfaces'}); +my $nicModulesSection = createNicModules($parms{'interfaces'}); # Create section my $hostsSection = createHosts($parms{'hosts'}); @@ -529,7 +538,7 @@ my $scriptsSection = createScripts($parms{'interfaces'}); # Begin to build template # Edit template by replacing place holders: -# insert_devices +# insert_devices # insert_hosts # insert_dns # insert_interfaces @@ -542,56 +551,60 @@ my $scriptsSection = createScripts($parms{'interfaces'}); # Generate autoyast template my $tmpl = ''; if ($version eq '10') { - $tmpl = genSles10Tmpl(); + $tmpl = genSles10Tmpl(); } elsif ($version eq '11') { - $tmpl = genSles11Tmpl(); + $tmpl = genSles11Tmpl(); } # Print out template -open (TMPL, ">$template_path"); +open(TMPL, ">$template_path"); print TMPL "$tmpl"; -close (TMPL); +close(TMPL); open(FILE, $template_path); + # Go through each line my $mod_tmpl = ''; -while(my $ln = ) { - # If the line matches the pattern to replace, print replacement - if($ln =~ 'insert_devices') { - $mod_tmpl .= $dasdSection; - } elsif($ln =~ 'insert_hosts') { - $mod_tmpl .= $hostsSection; - } elsif($ln =~ 'insert_dns') { - $mod_tmpl .= $dnsSection; - } elsif($ln =~ 'insert_interfaces') { - $mod_tmpl .= $interfacesSection; - } elsif($ln =~ 'insert_modules') { - $mod_tmpl .= $dasdModulesSection; - $mod_tmpl .= $nicModulesSection; - } elsif($ln =~ 'insert_partitioning_drives') { - $mod_tmpl .= $partitionsSection; - } elsif($ln =~ 'insert_root_password') { - $mod_tmpl .= $passwordSection; - } elsif($ln =~ 'insert_routes') { - $mod_tmpl .= $routesSection; - } elsif($ln =~ '') { - # Print line - $ln =~ s/\r//g; # Remove return carriage - $mod_tmpl .= $ln; - - $mod_tmpl .= $scriptsSection; - } else { - # Print line - $ln =~ s/\r//g; # Remove return carriage - $mod_tmpl .= $ln; - } +while (my $ln = ) { + + # If the line matches the pattern to replace, print replacement + if ($ln =~ 'insert_devices') { + $mod_tmpl .= $dasdSection; + } elsif ($ln =~ 'insert_hosts') { + $mod_tmpl .= $hostsSection; + } elsif ($ln =~ 'insert_dns') { + $mod_tmpl .= $dnsSection; + } elsif ($ln =~ 'insert_interfaces') { + $mod_tmpl .= $interfacesSection; + } elsif ($ln =~ 'insert_modules') { + $mod_tmpl .= $dasdModulesSection; + $mod_tmpl .= $nicModulesSection; + } elsif ($ln =~ 'insert_partitioning_drives') { + $mod_tmpl .= $partitionsSection; + } elsif ($ln =~ 'insert_root_password') { + $mod_tmpl .= $passwordSection; + } elsif ($ln =~ 'insert_routes') { + $mod_tmpl .= $routesSection; + } elsif ($ln =~ '') { + + # Print line + $ln =~ s/\r//g; # Remove return carriage + $mod_tmpl .= $ln; + + $mod_tmpl .= $scriptsSection; + } else { + + # Print line + $ln =~ s/\r//g; # Remove return carriage + $mod_tmpl .= $ln; + } } close(FILE); # Print out modified template -open (TMPL, ">$template_path"); +open(TMPL, ">$template_path"); print TMPL "$mod_tmpl"; -close (TMPL); +close(TMPL); # Done print "Done! See autoyast template under $template_path\n"; @@ -614,15 +627,16 @@ exit(); #------------------------------------------------------- sub trim { - # Get string - my ($str) = @_; + # Get string + my ($str) = @_; - # Trim right - $str =~ s/\s*$//; - # Trim left - $str =~ s/^\s*//; + # Trim right + $str =~ s/\s*$//; - return ($str); + # Trim left + $str =~ s/^\s*//; + + return ($str); } #------------------------------------------------------- @@ -638,78 +652,79 @@ sub trim { #------------------------------------------------------- sub createDasd { - # Get inputs - my ($dasd_ref, $partition_ref) = @_; - - my %dasd = %$dasd_ref; - my %partition = %$partition_ref; - # dasd hash should include: - # $dasd{$addr}{'device_name'} = $device_name; - # $dasd{$addr}{'type'} = $dasd_type; - # partition hash should include: - # $partitions{$device_name}{'device_fs'} = ''; - # $partitions{$device_name}{'device_size'} = ''; - # $partitions{$device_name}{'device_mount'} = ''; - # $partitions{$device_name}{'device_lvm'} = ''; - # $partitions{$device_name}{'lvm'}{$lvm_vol_name} = { - # 'name' => $lvm_vol_name, - # 'mount' => $lvm_vol_mount, - # 'size' => $lvm_vol_size - # }; - - # Create section - # - # - # None - # none - # 0.0.0100 - # true - # /dev/dasda - # - # /dev/dasda - # /dev/disk/by-path/ccw-0.0.0100 - # - # DASD - # io_subchannel - # - # - # true - # true - # - # - # dasd_eckd_mod - # - # - # - # - # - # false - # /dev/dasda1 (Linux native) - # - # - # - # true - # 1 - # rw - # - # - # - # 0.0.0100 - # - my $xml = ''; - - my $device_name; - my $device_type; - my $partition_info; - foreach my $addr(sort keys %dasd){ - $device_name = $dasd{$addr}{'device_name'}; - $device_type = $dasd{$addr}{'type'}; - - # If this dasd is to be used for Linux - if ($partitions{$device_name}{'device_mount'} || $partitions{$device_name}{'device_lvm'}) { - $partition_info = $device_name . "1 (Linux native)"; - $xml .= < $lvm_vol_name, + # 'mount' => $lvm_vol_mount, + # 'size' => $lvm_vol_size + # }; + + # Create section + # + # + # None + # none + # 0.0.0100 + # true + # /dev/dasda + # + # /dev/dasda + # /dev/disk/by-path/ccw-0.0.0100 + # + # DASD + # io_subchannel + # + # + # true + # true + # + # + # dasd_eckd_mod + # + # + # + # + # + # false + # /dev/dasda1 (Linux native) + # + # + # + # true + # 1 + # rw + # + # + # + # 0.0.0100 + # + my $xml = ''; + + my $device_name; + my $device_type; + my $partition_info; + foreach my $addr (sort keys %dasd) { + $device_name = $dasd{$addr}{'device_name'}; + $device_type = $dasd{$addr}{'type'}; + + # If this dasd is to be used for Linux + if ($partitions{$device_name}{'device_mount'} || $partitions{$device_name}{'device_lvm'}) { + $partition_info = $device_name . "1 (Linux native)"; + $xml .= < None none @@ -748,9 +763,9 @@ sub createDasd { $addr END - } else { - $partition_info = $device_name; - $xml .= < None none @@ -787,10 +802,10 @@ END $addr END - } - } + } + } - return $xml; + return $xml; } #------------------------------------------------------- @@ -806,35 +821,37 @@ END #------------------------------------------------------- sub createInterfaces { - # Get string - my ($interfaces_ref) = @_; - my %interfaces = %$interfaces_ref; - - # Create section - # - # static - # 10.1.100.255 - # eth0 - # 10.1.100.100 - # OSA Express Network card (0.0.0800) - # 255.255.255.0 - # 25 - # auto - # - # - # The layout is different for DHCP: - # - # dhcp - # eth0 - # 02:00:00:FF:FF:FF - # auto - # no - # - my $xml = ''; - foreach my $i(keys %interfaces){ - # Create static interface - if($interfaces{$i}{'bootproto'} eq 'static') { - $xml .= < section + # + # static + # 10.1.100.255 + # eth0 + # 10.1.100.100 + # OSA Express Network card (0.0.0800) + # 255.255.255.0 + # 25 + # auto + # + # + # The layout is different for DHCP: + # + # dhcp + # eth0 + # 02:00:00:FF:FF:FF + # auto + # no + # + my $xml = ''; + foreach my $i (keys %interfaces) { + + # Create static interface + if ($interfaces{$i}{'bootproto'} eq 'static') { + $xml .= < $interfaces{$i}{'bootproto'} $interfaces{$i}{'broadcast'} @@ -846,11 +863,11 @@ sub createInterfaces { auto
END - } - - # Create DHCP interface - else { - $xml .= < $interfaces{$i}{'bootproto'} $interfaces{$i}{'device'} @@ -859,10 +876,10 @@ END no
END - } - } - - return ($xml); + } + } + + return ($xml); } #------------------------------------------------------- @@ -878,14 +895,15 @@ END #------------------------------------------------------- sub createPartitions { - # Get inputs - my ($dasd_ref, $partition_ref) = @_; - - my %dasd = %$dasd_ref; - my %partitions = %$partition_ref; - - # Create section - # + + # Get inputs + my ($dasd_ref, $partition_ref) = @_; + + my %dasd = %$dasd_ref; + my %partitions = %$partition_ref; + + # Create section + # # /dev/dasda # # @@ -904,40 +922,42 @@ sub createPartitions { # # # The layout is different for LVM: - # - # /dev/dasdb - # true - # - # - # true - # false - # ext3 - # false - # false - # VG - # path - # false - # max - # - # - # all - # - my $xml = ''; - - # Go through each partition - foreach my $device_name(sort keys %partitions) { - # Create head - $xml .= < + # /dev/dasdb + # true + # + # + # true + # false + # ext3 + # false + # false + # VG + # path + # false + # max + # + # + # all + # + my $xml = ''; + + # Go through each partition + foreach my $device_name (sort keys %partitions) { + + # Create head + $xml .= < $device_name END - if (exists $partitions{$device_name}{'lvm'} && $partitions{$device_name}{'lvm'}) { - my %lvm_vols = %{ $partitions{$device_name}{'lvm'} }; - foreach my $vol(sort keys %lvm_vols) { - # Create section for LVM volume - $xml .= < section for LVM volume + $xml .= < true false @@ -953,10 +973,11 @@ END $lvm_vols{$vol}{'size'} END - } - } elsif (exists $partitions{$device_name}{'device_lvm'} && $partitions{$device_name}{'device_lvm'}) { - # Create section for LVM group - $xml .= < section for LVM group + $xml .= < true false @@ -971,9 +992,10 @@ END $partitions{$device_name}{'device_size'} END - } else { - # Not an LVM group or volume - $xml .= < true $partitions{$device_name}{'device_fs'} @@ -986,27 +1008,27 @@ END $partitions{$device_name}{'device_size'} END - } - - # Create tail - if (exists $partitions{$device_name}{'device_lvm'} && $partitions{$device_name}{'device_lvm'}) { - $xml .= < tail + if (exists $partitions{$device_name}{'device_lvm'} && $partitions{$device_name}{'device_lvm'}) { + $xml .= < 4M CT_LVM all END - } else { - $xml .= < all END - } - } + } + } - return $xml; + return $xml; } #------------------------------------------------------- @@ -1022,22 +1044,22 @@ END #------------------------------------------------------- sub createHosts { - my ($hosts_ref) = @_; - my %hosts = %$hosts_ref; - - # Create section - # e.g. + my ($hosts_ref) = @_; + my %hosts = %$hosts_ref; + + # Create section + # e.g. # # 10.1.100.100 # # gpok100.endicott.ibm.com gpok100 # # - my $xml = ''; - - # Create host entries - foreach my $i(keys %hosts){ - $xml .= < $hosts{$i}{'host_address'} @@ -1045,9 +1067,9 @@ sub createHosts { END - } - - return $xml; + } + + return $xml; } #------------------------------------------------------- @@ -1063,12 +1085,13 @@ END #------------------------------------------------------- sub createDns { - # Get string - my ($dns_ref) = @_; - my %dns = %$dns_ref; - - # Create section - # false + + # Get string + my ($dns_ref) = @_; + my %dns = %$dns_ref; + + # Create section + # false # false # endicott.ibm.com # gpok100 @@ -1076,8 +1099,8 @@ sub createDns { # 10.1.100.100 # my $xml = ''; - foreach my $i(keys %dns){ - $xml .= <$dns{$i}{'dhcp_hostname'} $dns{$i}{'dhcp_resolv'} $dns{$i}{'domain'} @@ -1086,9 +1109,9 @@ sub createDns { $dns{$i}{'nameserver'} END - } + } - return $xml; + return $xml; } #------------------------------------------------------- @@ -1104,29 +1127,30 @@ END #------------------------------------------------------- sub createDasdModules { - # Get string - my ($dasd_ref) = @_; - my %dasd = %$dasd_ref; - - # Create section - # - # dasd-bus-ccw-0.0.0100 - # dasd_eckd_mod - # - # - my $xml = ''; - foreach my $addr(keys %dasd){ - $xml .= < section + # + # dasd-bus-ccw-0.0.0100 + # dasd_eckd_mod + # + # + + my $xml = ''; + foreach my $addr (keys %dasd) { + $xml .= < dasd-bus-ccw-$addr $dasd{$addr}{'type'} END - } + } - return $xml; + return $xml; } #------------------------------------------------------- @@ -1142,22 +1166,23 @@ END #------------------------------------------------------- sub createNicModules { - # Get hash table - my ($interfaces_ref) = @_; - my %interfaces = %$interfaces_ref; - - # Create section - # - # 0.0.0800 0.0.0801 0.0.0802 - # FOOBAR - # 3 - # eth0 - # qeth - # - # - my $xml = ''; - foreach my $i(sort (keys %interfaces)){ - $xml .= < section + # + # 0.0.0800 0.0.0801 0.0.0802 + # FOOBAR + # 3 + # eth0 + # qeth + # + # + my $xml = ''; + foreach my $i (sort (keys %interfaces)) { + $xml .= < $interfaces{$i}{'chanids'} FOOBAR @@ -1167,9 +1192,9 @@ sub createNicModules { END - } - - return $xml; + } + + return $xml; } #------------------------------------------------------- @@ -1185,30 +1210,31 @@ END #------------------------------------------------------- sub createSoftware { - # Get string - my ($str) = @_; - # Split the software - # e.g. base,gnome - my @software = split(/,/,$str); - - # Create section - # Basis-Devel - # Minimal - # base - # documentation - # file_server - # gnome - # print_server - # x11 + # Get string + my ($str) = @_; + + # Split the software + # e.g. base,gnome + my @software = split(/,/, $str); + + # Create section + # Basis-Devel + # Minimal + # base + # documentation + # file_server + # gnome + # print_server + # x11 my $xml = ''; - foreach (@software){ - $xml .= <$_ END - } + } - return $xml; + return $xml; } #------------------------------------------------------- @@ -1224,36 +1250,39 @@ END #------------------------------------------------------- sub createRoutes { - # Get hash table - my ($interfaces_ref) = @_; - my %interfaces = %$interfaces_ref; - - # Create section - # false - # - # - # default - # - - # 10.1.100.1 - # - - # - # - my $xml = ''; - my $dest = ''; - foreach my $i(sort (keys %interfaces)){ - if(!$dest) { - # The first interface is the default route - $dest = 'default'; - } else { - # Get network - $dest = substr($interfaces{$i}{'ipaddr'}, 0, rindex($interfaces{$i}{'ipaddr'}, '.')); - $dest .= ".0"; - } - - # Do not set gateway for DHCP interface - if(!($interfaces{$i}{'bootproto'} eq 'dhcp')) { - $xml .= < section + # false + # + # + # default + # - + # 10.1.100.1 + # - + # + # + + my $xml = ''; + my $dest = ''; + foreach my $i (sort (keys %interfaces)) { + if (!$dest) { + + # The first interface is the default route + $dest = 'default'; + } else { + + # Get network + $dest = substr($interfaces{$i}{'ipaddr'}, 0, rindex($interfaces{$i}{'ipaddr'}, '.')); + $dest .= ".0"; + } + + # Do not set gateway for DHCP interface + if (!($interfaces{$i}{'bootproto'} eq 'dhcp')) { + $xml .= < $dest - @@ -1261,10 +1290,10 @@ sub createRoutes { - END - } - } - - return $xml; + } + } + + return $xml; } #------------------------------------------------------- @@ -1280,28 +1309,30 @@ END #------------------------------------------------------- sub createScripts { - # Get hash table - my ($interfaces_ref) = @_; - my %interfaces = %$interfaces_ref; - # Default route is being added by autoyast (bug) - # Setting default route in post-script - my $xml = ''; + # Get hash table + my ($interfaces_ref) = @_; + my %interfaces = %$interfaces_ref; + + # Default route is being added by autoyast (bug) + # Setting default route in post-script + my $xml = ''; my $script = ''; - foreach my $i(sort (keys %interfaces)){ - # Set the default route for the firs interface - # Do not set default route for DHCP interface - if(!$script && !($interfaces{$i}{'bootproto'} eq 'dhcp')) { - $script .= < /etc/sysconfig/network/routes END - last; - } - } - - # Create section - if($script) { - $xml .= < section + if ($script) { + $xml .= < END - } - - return $xml; + } + + return $xml; } #------------------------------------------------------- @@ -1334,11 +1365,11 @@ END #------------------------------------------------------- sub ask { - my ($question) = @_; - - print "$question"; - my $answer = <>; - return trim($answer); + my ($question) = @_; + + print "$question"; + my $answer = <>; + return trim($answer); } #------------------------------------------------------- @@ -1354,13 +1385,13 @@ sub ask { #------------------------------------------------------- sub pad { - my ($str, $size) = @_; - - while (length($str) < $size) { - $str = "$str "; - } + my ($str, $size) = @_; - return $str; + while (length($str) < $size) { + $str = "$str "; + } + + return $str; } #------------------------------------------------------- @@ -1376,7 +1407,7 @@ sub pad { #------------------------------------------------------- sub genSles11Tmpl { - my $tmpl = < @@ -1725,8 +1756,8 @@ sub genSles11Tmpl { AUTOYASTEND - # Handle second half - $tmpl .= < @@ -2048,7 +2079,7 @@ AUTOYASTEND AUTOYASTEND - return $tmpl; + return $tmpl; } #------------------------------------------------------- @@ -2064,7 +2095,7 @@ AUTOYASTEND #------------------------------------------------------- sub genSles10Tmpl { - my $tmpl = < @@ -2412,8 +2443,8 @@ sub genSles10Tmpl { /etc/skel AUTOYASTEND - - $tmpl .= < @@ -2735,5 +2766,5 @@ AUTOYASTEND AUTOYASTEND - return $tmpl; + return $tmpl; } diff --git a/xCAT-server/share/xcat/scripts/xcatvio.script b/xCAT-server/share/xcat/scripts/xcatvio.script index 61efa1390..3da6d7751 100755 --- a/xCAT-server/share/xcat/scripts/xcatvio.script +++ b/xCAT-server/share/xcat/scripts/xcatvio.script @@ -22,8 +22,8 @@ $::script =~ s/.*\///; sub runcmd { my ($cmd) = @_; - my $rc=0; - $cmd .= ' 2>&1' ; + my $rc = 0; + $cmd .= ' 2>&1'; msg("Running command $cmd"); $::outref = `$cmd`; if ($?) @@ -31,8 +31,8 @@ sub runcmd $rc = $? >> 8; if ($rc > 0) { - print "$::sdate $0: $::outref\n"; - print $::LOG_FILE "$::sdate $0: $::outref\n"; + print "$::sdate $0: $::outref\n"; + print $::LOG_FILE "$::sdate $0: $::outref\n"; } } return $rc; @@ -57,9 +57,10 @@ if (!-d $logdir) { } my $logfile = $logdir . "/xcat.log"; + # this log should not contain much so it might be ok to let it grow? # at least we'll have the errors preserved -open(LOGFILE,">>",$logfile); +open(LOGFILE, ">>", $logfile); $::LOG_FILE = \*LOGFILE; foreach my $env (keys %ENV) { @@ -70,43 +71,45 @@ my $cmd; my $hostname; my $ipaddr; my $servnode; + # TODO: use the environment variable instead of reading /etc/niminfo # get the name of my service node/NIM master from the /etc/niminfo file if (-f "/etc/niminfo") { - $cmd = "/bin/cat /etc/niminfo | /bin/grep 'NIM_HOSTNAME'"; - &runcmd($cmd); - my $hostline = $::outref; - my $junk; - ($junk, $hostname) = split(/=/, $hostline); - $hostname =~ s/^\s*//; - chomp $hostname; - msg("Info: the hostname is $hostname"); + $cmd = "/bin/cat /etc/niminfo | /bin/grep 'NIM_HOSTNAME'"; + &runcmd($cmd); + my $hostline = $::outref; + my $junk; + ($junk, $hostname) = split(/=/, $hostline); + $hostname =~ s/^\s*//; + chomp $hostname; + msg("Info: the hostname is $hostname"); - $cmd = "host $hostname"; - &runcmd($cmd); - $ipaddr = $::outref; - $ipaddr =~ s/.*is\s+//; - chomp $ipaddr; - msg("Info: the ip address is $ipaddr"); + $cmd = "host $hostname"; + &runcmd($cmd); + $ipaddr = $::outref; + $ipaddr =~ s/.*is\s+//; + chomp $ipaddr; + msg("Info: the ip address is $ipaddr"); - $cmd = "/bin/cat /etc/niminfo | /bin/grep 'NIM_MASTER_HOSTNAME'"; - &runcmd($cmd); - my $SNline = $::outref; - ($junk, $servnode) = split(/=/, $SNline); - $servnode =~ s/^\s*//; - chomp $servnode; + $cmd = "/bin/cat /etc/niminfo | /bin/grep 'NIM_MASTER_HOSTNAME'"; + &runcmd($cmd); + my $SNline = $::outref; + ($junk, $servnode) = split(/=/, $SNline); + $servnode =~ s/^\s*//; + chomp $servnode; - - my $xcatinfo="/etc/xcatinfo"; - open(XCATINFO,">",$xcatinfo); - print XCATINFO "XCATSERVER=$servnode\n"; - close(XCATINFO); + + my $xcatinfo = "/etc/xcatinfo"; + open(XCATINFO, ">", $xcatinfo); + print XCATINFO "XCATSERVER=$servnode\n"; + close(XCATINFO); } else { - msg("Error: could not find /etc/niminfo file, exiting..."); - exit 1; + msg("Error: could not find /etc/niminfo file, exiting..."); + exit 1; } + # Configure TCP/IP # Get the boot nic my $bootnic; @@ -161,19 +164,19 @@ if (defined($ENV{'SEA_ADAPTERS'}) and $ENV{'SEA_ADAPTERS'} =~ /bootnic/i) { msg("Warning: No Virtual Ethernet Adapter found"); $skiptcpip = 1; } else { - my $xcatinfo="/etc/xcatinfo"; - open(XCATINFO,">>",$xcatinfo); + my $xcatinfo = "/etc/xcatinfo"; + open(XCATINFO, ">>", $xcatinfo); print XCATINFO "SEA_ADAPTERS=$bootnic:$vir_nic[0]:1:$ENV{'NIM_IPADDR'}:$ENV{'NIM_NETMASK'}:$hostname\n"; close(XCATINFO); - - my $lsicmd = "/usr/sbin/lsitab bootnicsea > /dev/null 2>&1"; + + my $lsicmd = "/usr/sbin/lsitab bootnicsea > /dev/null 2>&1"; if (&runcmd($lsicmd) != 0) { my $mkicmd = '/usr/sbin/mkitab "bootnicsea:2:wait:/xcatpost/config_bootnicsea > /dev/console 2>&1"'; if (&runcmd($mkicmd) != 0) { msg("Warning: config_bootnicsea: Could not add config_bootnicsea to /etc/inittab.\n") } } - + } } elsif (defined($ENV{'SEA_ADAPTERS'})) { msg("Info: Environment variable SEA_ADAPTERS is $ENV{'SEA_ADAPTERS'}"); @@ -187,10 +190,10 @@ if (defined($ENV{'SEA_ADAPTERS'}) and $ENV{'SEA_ADAPTERS'} =~ /bootnic/i) { $skiptcpip = 1; last; } - $sea_adapters{$phy}{'phy'} = $phy; + $sea_adapters{$phy}{'phy'} = $phy; $sea_adapters{$phy}{'virt'} = $virt; $sea_adapters{$phy}{'vlan'} = $vlan; - $sea_adapters{$phy}{'ip'} = $ip; + $sea_adapters{$phy}{'ip'} = $ip; $sea_adapters{$phy}{'mask'} = $mask; } } else { @@ -209,13 +212,13 @@ if (!$skiptcpip) { msg("Warning: NIM_NETMASK is not specified, using the default 255.255.255.0"); $netmask = "255.255.255.0"; } - + foreach my $phy (keys %sea_adapters) { - my $phy = $sea_adapters{$phy}{'phy'}; + my $phy = $sea_adapters{$phy}{'phy'}; my $virt = $sea_adapters{$phy}{'virt'}; my $vlan = $sea_adapters{$phy}{'vlan'}; - my $ip = $sea_adapters{$phy}{'ip'}; + my $ip = $sea_adapters{$phy}{'ip'}; my $mask = $sea_adapters{$phy}{'mask'}; if ($phy eq $bootnic) { @@ -227,30 +230,31 @@ if (!$skiptcpip) { $cmd = "/usr/ios/cli/ioscli license -accept"; &runcmd($cmd); } - { # detach bootnic + { # detach bootnic if ($bootnicsea and $phy =~ /^ent(\d+)/) { my $phynic_id = $1; - my $en_nic = "en".$phynic_id; - my $ent_nic = "ent".$phynic_id; - my $et_nic = "et".$phynic_id; + my $en_nic = "en" . $phynic_id; + my $ent_nic = "ent" . $phynic_id; + my $et_nic = "et" . $phynic_id; $cmd = "ifconfig $en_nic down; ifconfig $en_nic detach; rmdev -dl $en_nic; rmdev -dl $ent_nic; rmdev -dl $et_nic; cfgmgr;"; if (&runcmd($cmd) != 0) { msg("Error: could not detach bootnic:$bootnic"); next; } } - + } + #$cmd = qq~su - padmin "-c ioscli license -accept; ioscli mkvdev -sea $phy -vadapter $virt -default $virt -defaultid $vlan"~; $cmd = "/usr/ios/cli/ioscli mkvdev -sea $phy -vadapter $virt -default $virt -defaultid $vlan"; if (&runcmd($cmd) != 0) { msg("Error: could not create SEA with physical adapter $phy, virtual adapter $virt and vlan id $vlan"); next; } - my $sea_out = $::outref; - my $sea = undef; - my @out_array = split (/\n/, $sea_out); - foreach (@out_array) { + my $sea_out = $::outref; + my $sea = undef; + my @out_array = split(/\n/, $sea_out); + foreach (@out_array) { if (/(ent\d+)\s*Available/) { $sea = $1; $sea =~ s/t//; @@ -261,6 +265,7 @@ if (!$skiptcpip) { next; } msg("Info: The interface created with mkvdev is: $sea"); + #$cmd = qq~su - padmin "-c ioscli license -accept; ioscli mktcpip -hostname $hostname -inetaddr $ip -interface $sea -netmask $mask"~; $cmd = "/usr/ios/cli/ioscli mktcpip -hostname $hostname -inetaddr $ip -interface $sea -netmask $mask"; if (&runcmd($cmd) != 0) { @@ -293,12 +298,12 @@ if (&runcmd($cmd) != 0) { # Set a temporary root password # - the user-provided root passwd will be set by xcataixpost my $padmin_passwd; -if(defined($ENV{'PADMIN_PASSWD'})) +if (defined($ENV{'PADMIN_PASSWD'})) { $padmin_passwd = $ENV{'PADMIN_PASSWD'}; } -if(!$padmin_passwd) +if (!$padmin_passwd) { msg("Warning: padmin password is not specified, using the default password \"cluster\""); $padmin_passwd = "cluster"; @@ -323,7 +328,7 @@ if (&runcmd($pwcmd) != 0) { my $installdir; if (!$installdir) { - $installdir="/install"; + $installdir = "/install"; } # get the contents of the $installdir/postscripts dir on the server @@ -344,18 +349,20 @@ if (&runcmd($mcmd) != 0) { } my $cpcmd; -if ((@ARGV==0) || ($ARGV[0] != 2)) { +if ((@ARGV == 0) || ($ARGV[0] != 2)) { $cpcmd = "/bin/cp -r /xcatmnt/* /xcatpost >/dev/null 2>&1"; } else { -# when argv[1]=2, there is only one postscript file, -# user wants only download it to save time - $cpcmd= "/bin/cp /xcatmnt/$ARGV[1] /xcatpost >/dev/null 2>&1"; + + # when argv[1]=2, there is only one postscript file, + # user wants only download it to save time + $cpcmd = "/bin/cp /xcatmnt/$ARGV[1] /xcatpost >/dev/null 2>&1"; } if (&runcmd($cpcmd) != 0) { print "$::sdate xcataixscript: Could not copy postscripts to /xcatpost.\n"; print $::LOG_FILE "$::sdate xcataixscript: Could not copy postscripts to /xcatpost.\n"; } + # make sure all are executable my $chcmd = "/bin/chmod +x /xcatpost/*"; diff --git a/xCAT-server/share/xcat/tools/detect_dhcpd b/xCAT-server/share/xcat/tools/detect_dhcpd index f0ba37801..1769ba5f1 100755 --- a/xCAT-server/share/xcat/tools/detect_dhcpd +++ b/xCAT-server/share/xcat/tools/detect_dhcpd @@ -16,81 +16,85 @@ Options: Author: Wang, Xiao Peng\n"; if (!GetOptions( - 'i=s' => \$::IF, - 'm=s' => \$::MACADD, - 't=s' => \$::TIMEOUT, - 'V|verbose' => \$::VERBOSE, - 'h|help' => \$::HELP,)) { - print $::USAGE; - exit 1; + 'i=s' => \$::IF, + 'm=s' => \$::MACADD, + 't=s' => \$::TIMEOUT, + 'V|verbose' => \$::VERBOSE, + 'h|help' => \$::HELP,)) { + print $::USAGE; + exit 1; } if ($::HELP) { print $::USAGE; exit 0; } unless (-x "/usr/sbin/tcpdump") { - print "Error: Please install tcpdump before the detecting.\n"; - exit 1; + print "Error: Please install tcpdump before the detecting.\n"; + exit 1; } my $nic; if ($::IF) { - $nic = $::IF; + $nic = $::IF; } else { - print $::USAGE; - exit 1; + print $::USAGE; + exit 1; } my $start = Time::HiRes::gettimeofday(); $start =~ s/(\d.*)\.(\d.*)/$1/; -if (!$nic) { print "specify a nic\n"; print $::USAGE; exit 1;} +if (!$nic) { print "specify a nic\n"; print $::USAGE; exit 1; } + #my $IP = `ifconfig $nic | grep "inet addr" | awk '{print \$2}' | awk -F: '{print \$2}'`; my $IPADDRMASK = `ip addr show dev $nic | grep inet | grep -v inet6 | awk '{print \$2}' | head -n 1`; -my ($IP,$MASK)= split (/\//,$IPADDRMASK); +my ($IP, $MASK) = split(/\//, $IPADDRMASK); my $MAC; my $tmpMAC; my @ipoutput; if ($::MACADD) { - $MAC = $::MACADD; + $MAC = $::MACADD; } else { -# $MAC = `ifconfig $nic | grep "HWaddr" | /usr/bin/awk '{print \$5}'`; - $tmpMAC = `ip link show $nic | grep ether`; - @ipoutput= split (' ',$tmpMAC); - $MAC=$ipoutput[1]; + + # $MAC = `ifconfig $nic | grep "HWaddr" | /usr/bin/awk '{print \$5}'`; + $tmpMAC = `ip link show $nic | grep ether`; + @ipoutput = split(' ', $tmpMAC); + $MAC = $ipoutput[1]; } chomp($IP); chomp($MAC); if ($::VERBOSE) { - print "Send out dhcp discover from: NIC = $nic, IP = $IP, MAC = $MAC\n"; + print "Send out dhcp discover from: NIC = $nic, IP = $IP, MAC = $MAC\n"; } -if (!$IP || !$MAC) { print "Cannot find IP/MAC\n"; exit 1;} +if (!$IP || !$MAC) { print "Cannot find IP/MAC\n"; exit 1; } # check the distro my $os; if (-f "/etc/redhat-release") { - $os = "rh"; + $os = "rh"; } elsif (-f "/etc/SuSE-release") { - $os = "sles"; + $os = "sles"; } elsif (-f "/etc/lsb-release") { - $os = "ubuntu"; + $os = "ubuntu"; } elsif (-f "/etc/debian_version") { - $os = "debian"; + $os = "debian"; } else { - print "Only support the redhat, sles, ubuntu and debian OS.\n"; - exit 1; + print "Only support the redhat, sles, ubuntu and debian OS.\n"; + exit 1; } + # fork a process to capture the packet by tcpdump my $pid = fork; -if (!defined $pid) { print "Fork failed.\n"; exit 1;} +if (!defined $pid) { print "Fork failed.\n"; exit 1; } my $dumpfile = "/tmp/dhcpdumpfile.log"; if ($pid == 0) { - # Child process - my $cmd = "tcpdump -i $IF port 68 -n -vvvvvv > $dumpfile 2>/dev/null"; - `$cmd`; - exit 0; + + # Child process + my $cmd = "tcpdump -i $IF port 68 -n -vvvvvv > $dumpfile 2>/dev/null"; + `$cmd`; + exit 0; } # generate the discover package @@ -98,104 +102,109 @@ my $package = packdhcppkg($MAC); # send out the package my $sock = IO::Socket::INET->new(Proto => 'udp', - Broadcast => 1, - #ReusePort => 1, - PeerPort => '67', - #LocalAddr => 0, - LocalAddr => $IP, - LocalPort => '68', - PeerAddr => inet_ntoa(INADDR_BROADCAST)); + Broadcast => 1, + + #ReusePort => 1, + PeerPort => '67', + + #LocalAddr => 0, + LocalAddr => $IP, + LocalPort => '68', + PeerAddr => inet_ntoa(INADDR_BROADCAST)); # try the any port if localport 68 has been used unless ($sock) { - $sock = IO::Socket::INET->new(Proto => 'udp', - Broadcast => 1, - PeerPort => '67', - LocalAddr => $IP, - PeerAddr => inet_ntoa(INADDR_BROADCAST)); + $sock = IO::Socket::INET->new(Proto => 'udp', + Broadcast => 1, + PeerPort => '67', + LocalAddr => $IP, + PeerAddr => inet_ntoa(INADDR_BROADCAST)); } unless ($sock) { - print "Create socket error: $@\n"; - kill_child(); - exit 1; + print "Create socket error: $@\n"; + kill_child(); + exit 1; } my $timeout = 10; if ($::TIMEOUT) { - $timeout = $::TIMEOUT; + $timeout = $::TIMEOUT; } -my $end = Time::HiRes::gettimeofday(); +my $end = Time::HiRes::gettimeofday(); $end =~ s/(\d.*)\.(\d.*)/$1/; while ($end - $start <= $timeout) { - $sock->send($package) or die "Send discover error: $@\n"; - sleep 2; - $end = Time::HiRes::gettimeofday(); - $end =~ s/(\d.*)\.(\d.*)/$1/; + $sock->send($package) or die "Send discover error: $@\n"; + sleep 2; + $end = Time::HiRes::gettimeofday(); + $end =~ s/(\d.*)\.(\d.*)/$1/; } kill_child(); + #kill the child process kill 15, $pid; my @pidoftcpdump = `ps -ef | grep -E "[0-9]+:[0-9]+:[0-9]+ tcpdump -i $IF" | awk -F' ' '{print \$2}'`; foreach my $cpid (@pidoftcpdump) { - kill 15, $cpid; -# print "try to kill $cpid\n"; + kill 15, $cpid; + + # print "try to kill $cpid\n"; } sleep 2; -open (FILE, "<$dumpfile") or die "Cannot open $dumpfile\n"; +open(FILE, "<$dumpfile") or die "Cannot open $dumpfile\n"; my %output; -my @snack = (); -my @siaddr = (); +my @snack = (); +my @siaddr = (); my $newsection = 0; -my $offer = 0; +my $offer = 0; $chaddr = (); $ciaddr = (); $siaddr = (); while () { - $line = $_; + $line = $_; - if ($line =~ /^\d\d:\d\d:\d\d/) { - # A new packet was captured. Parse the last one. - if ($::VERBOSE) { - print "The server I found: mac = $chaddr, clientip = $ciaddr, serverip = $siaddr, offer = $offer.\n"; + if ($line =~ /^\d\d:\d\d:\d\d/) { + + # A new packet was captured. Parse the last one. + if ($::VERBOSE) { + print "The server I found: mac = $chaddr, clientip = $ciaddr, serverip = $siaddr, offer = $offer.\n"; + } + if ($os eq "sles") { $offer = 1; } + if ($chaddr =~ /$MAC/i && $offer && $ciaddr && $siaddr && $rsiaddr) { + $output{$rsiaddr}{'client'} = $ciaddr; + $output{$rsiaddr}{'nextsv'} = $siaddr; + } elsif ($nack && $siaddr && !grep(/^$siaddr$/, @snack)) { + push @snack, $siaddr; + } elsif ($siaddr && !grep(/^$siaddr$/, @server)) { + push @server, $siaddr; + } + $offer = 0; + $nack = 0; + $chaddr = (); + $ciaddr = (); + $siaddr = (); + $rsiaddr = (); # the server which responsing the dhcp request } - if ($os eq "sles") { $offer = 1;} - if ($chaddr =~ /$MAC/i && $offer && $ciaddr && $siaddr && $rsiaddr) { - $output{$rsiaddr}{'client'} = $ciaddr; - $output{$rsiaddr}{'nextsv'} = $siaddr; - } elsif ($nack && $siaddr && !grep(/^$siaddr$/, @snack)) { - push @snack, $siaddr; - } elsif ($siaddr && ! grep(/^$siaddr$/,@server)) { - push @server, $siaddr; + if ($line =~ /(\d+\.\d+\.\d+\.\d+)\.[\d\w]+ > \d+\./) { + $rsiaddr = $1; + } + if ($line =~ /\s*DHCP-Message.*: Offer/) { + $offer = 1; + } elsif ($line =~ /\s*DHCP-Message.*: NACK/) { + $nack = 1; + } + if ($line =~ /\s*Client-Ethernet-Address (..:..:..:..:..:..)/) { + $chaddr = $1; + } + if ($line =~ /\s*Your-IP (\d+\.\d+\.\d+.\d+)/) { + $ciaddr = $1; + } + if ($line =~ /\s*Server-IP (\d+\.\d+\.\d+.\d+)/) { + $siaddr = $1; } - $offer = 0; - $nack = 0; - $chaddr = (); - $ciaddr = (); - $siaddr = (); - $rsiaddr = (); # the server which responsing the dhcp request - } - if ($line =~ /(\d+\.\d+\.\d+\.\d+)\.[\d\w]+ > \d+\./) { - $rsiaddr = $1; - } - if ($line =~ /\s*DHCP-Message.*: Offer/) { - $offer = 1; - } elsif ($line =~ /\s*DHCP-Message.*: NACK/) { - $nack = 1; - } - if ($line =~ /\s*Client-Ethernet-Address (..:..:..:..:..:..)/) { - $chaddr = $1; - } - if ($line =~/\s*Your-IP (\d+\.\d+\.\d+.\d+)/) { - $ciaddr = $1; - } - if ($line =~/\s*Server-IP (\d+\.\d+\.\d+.\d+)/) { - $siaddr = $1; - } } close(FILE); @@ -204,137 +213,138 @@ my $sn = scalar(keys %output); print "\n++++++++++++++++++++++++++++++++++\n"; print "There are $sn servers reply the dhcp discover.\n"; foreach my $server (keys %output) { - print " Server:$server assign IP [$output{$server}{'client'}] to you. The next server is [$output{$server}{'nextsv'}]!\n"; + print " Server:$server assign IP [$output{$server}{'client'}] to you. The next server is [$output{$server}{'nextsv'}]!\n"; } print "++++++++++++++++++++++++++++++++++\n\n"; if (scalar(@snack)) { - print "===================================\n"; - print "The dhcp servers which sending out NACK in present network:\n"; - foreach my $nack (@snack) { - print " $nack\n"; - } + print "===================================\n"; + print "The dhcp servers which sending out NACK in present network:\n"; + foreach my $nack (@snack) { + print " $nack\n"; + } } if (scalar(@server)) { - print "===================================\n"; - print "The dhcp servers in present network:\n"; - foreach my $s (@server) { - print " $s\n"; - } + print "===================================\n"; + print "The dhcp servers in present network:\n"; + foreach my $s (@server) { + print " $s\n"; + } } #`rm -f $dumpfile`; exit 0; -sub packdhcppkg{ - my $mymac = shift; - my $package; +sub packdhcppkg { + my $mymac = shift; + my $package; - # add the operation type. 1 - request - $package .= pack("C*",1); + # add the operation type. 1 - request + $package .= pack("C*", 1); - # add the hardware type. 1 - ethernet - $package .= pack("C*",1); + # add the hardware type. 1 - ethernet + $package .= pack("C*", 1); - # add the length of hardware add - $package .= pack("C*",6); + # add the length of hardware add + $package .= pack("C*", 6); - # add the hops - $package .= pack("C*",0); + # add the hops + $package .= pack("C*", 0); - # add the transaction id - $package .= pack("C*",60,61,62,63); + # add the transaction id + $package .= pack("C*", 60, 61, 62, 63); - # add the elapsed time - $package .= pack("C*",0,0); + # add the elapsed time + $package .= pack("C*", 0, 0); - # add the flag 00 - broadcast - $package .= pack("C*",128,0); + # add the flag 00 - broadcast + $package .= pack("C*", 128, 0); - # add the IP of client - $package .= pack("C*",0,0,0,0); + # add the IP of client + $package .= pack("C*", 0, 0, 0, 0); - # add the your IP - $package .= pack("C*",0,0,0,0); + # add the your IP + $package .= pack("C*", 0, 0, 0, 0); - # add the next server IP - $package .= pack("C*",0,0,0,0); + # add the next server IP + $package .= pack("C*", 0, 0, 0, 0); - # add the relay agent IP - $package .= pack("C*",0,0,0,0); + # add the relay agent IP + $package .= pack("C*", 0, 0, 0, 0); - # add the mac address of the client - my @macval; - if ($mymac) { - my @strmac = split(/:/, $mymac); - foreach (@strmac) { - push @macval, hex($_); + # add the mac address of the client + my @macval; + if ($mymac) { + my @strmac = split(/:/, $mymac); + foreach (@strmac) { + push @macval, hex($_); + } + $package .= pack("C*", @macval); + } else { + @macval = ('0', '0', '50', '51', '52', '53'); + $package .= pack("C*", @macval); } - $package .= pack("C*",@macval); - } else { - @macval = ('0','0','50','51','52','53'); - $package .= pack("C*",@macval); - } - # add 10 padding for mac - my @macpad; - foreach (1..10) { - push @macpad, "0"; - } - $package .= pack("C*",@macpad); + # add 10 padding for mac + my @macpad; + foreach (1 .. 10) { + push @macpad, "0"; + } + $package .= pack("C*", @macpad); - # add the hostname of server - my @hs; - foreach (1..64) { - push @hs, "0"; - } - $package .= pack("C*",@hs); + # add the hostname of server + my @hs; + foreach (1 .. 64) { + push @hs, "0"; + } + $package .= pack("C*", @hs); - # add the file name - my @fn; - foreach (1..128) { - push @fn, "0"; - } - $package .= pack("C*",@fn); + # add the file name + my @fn; + foreach (1 .. 128) { + push @fn, "0"; + } + $package .= pack("C*", @fn); - # add the magic cookie - $package .= pack("C*",99,130,83,99); + # add the magic cookie + $package .= pack("C*", 99, 130, 83, 99); - # add the dhcp message type. The last num: 1 - dhcp discover - $package .= pack("C*",53,1,1); + # add the dhcp message type. The last num: 1 - dhcp discover + $package .= pack("C*", 53, 1, 1); - # add the client identifier - $package .= pack("C*",61,7,1); #type, length, hwtype - $package .= pack("C*",@macval); + # add the client identifier + $package .= pack("C*", 61, 7, 1); #type, length, hwtype + $package .= pack("C*", @macval); - # add the parameter request list - $package .= pack("C*",55,10); #type, length - $package .= pack("C*",1,3,6,12,15,28,40,41,42,119); + # add the parameter request list + $package .= pack("C*", 55, 10); #type, length + $package .= pack("C*", 1, 3, 6, 12, 15, 28, 40, 41, 42, 119); - # add the end option - $package .= pack("C*",255); + # add the end option + $package .= pack("C*", 255); - # pad the package to 300 - @strpack = unpack("W*",$package); - my $curleng = length($strpack); + # pad the package to 300 + @strpack = unpack("W*", $package); + my $curleng = length($strpack); - my @padding; - foreach (1..35){ - push @padding, '0'; - } + my @padding; + foreach (1 .. 35) { + push @padding, '0'; + } - $package .= pack("C*",@padding); + $package .= pack("C*", @padding); - return $package; + return $package; } sub kill_child { - kill 15, $pid; - my @pidoftcpdump = `ps -ef | grep -E "[0-9]+:[0-9]+:[0-9]+ tcpdump -i $IF" | awk -F' ' '{print \$2}'`; - foreach my $cpid (@pidoftcpdump) { - kill 15, $cpid; - #print "try to kill $cpid\n"; - } + kill 15, $pid; + my @pidoftcpdump = `ps -ef | grep -E "[0-9]+:[0-9]+:[0-9]+ tcpdump -i $IF" | awk -F' ' '{print \$2}'`; + foreach my $cpid (@pidoftcpdump) { + kill 15, $cpid; + + #print "try to kill $cpid\n"; + } } diff --git a/xCAT-server/share/xcat/tools/mac2linklocal b/xCAT-server/share/xcat/tools/mac2linklocal index 96ab685f5..fc2510f6e 100755 --- a/xCAT-server/share/xcat/tools/mac2linklocal +++ b/xCAT-server/share/xcat/tools/mac2linklocal @@ -3,11 +3,11 @@ # ##################################################### # -# This script will calculate the IPv6 link local address +# This script will calculate the IPv6 link local address # from the mac address # the mac address can be something like # 00215ea68cd9 or 00:21:5e:a6:8c:d9 -# example mac2linklocal 00215ea68cd9 +# example mac2linklocal 00215ea68cd9 # ##################################################### @@ -23,8 +23,8 @@ use warnings; use Getopt::Long; if ( - !GetOptions("h|help" => \$::HELP, - "m=s" => \$::MACADDR,) + !GetOptions("h|help" => \$::HELP, + "m=s" => \$::MACADDR,) ) { &usage; @@ -41,7 +41,7 @@ require xCAT::NetworkUtils; if ($::MACADDR) { - my $linklocal = xCAT::NetworkUtils->linklocaladdr($::MACADDR); + my $linklocal = xCAT::NetworkUtils->linklocaladdr($::MACADDR); print "$linklocal"; } diff --git a/xCAT-server/share/xcat/tools/mktoolscenter b/xCAT-server/share/xcat/tools/mktoolscenter index 616c33462..8766890c7 100755 --- a/xCAT-server/share/xcat/tools/mktoolscenter +++ b/xCAT-server/share/xcat/tools/mktoolscenter @@ -6,7 +6,7 @@ # 1) USER downloads version of BOMC suitable for the mgt node's OSVER and ARCH # 2) We gather machine types and download firmware # 3) We construct the bootable image and set up the NFS mount -# +# # # 2012.04.27 Brian Elliott Finley @@ -15,46 +15,46 @@ BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; use IO::File; -use File::Path; -use File::Copy; +use File::Path; +use File::Copy; use Getopt::Long; use strict; -use constant DEFAULT_LOG_FILE => "mktoolscenter.log"; +use constant DEFAULT_LOG_FILE => "mktoolscenter.log"; -my $surrogate = 0; -my %proxy = ('host',"",'port',"",'user',"",'pw',""); -my $nodels = "/opt/xcat/bin/nodels"; -my %Options = ('interactive',"yes",'warnings','','log',"yes",'dump',"yes"); +my $surrogate = 0; +my %proxy = ('host', "", 'port', "", 'user', "", 'pw', ""); +my $nodels = "/opt/xcat/bin/nodels"; +my %Options = ('interactive', "yes", 'warnings', '', 'log', "yes", 'dump', "yes"); my @warnings; my $logfile = DEFAULT_LOG_FILE; -my $now = localtime; +my $now = localtime; my $help; # # print a warning and wait a bit if warnings are enabled # sub warning { - my $msg = shift; - if ($Options{warnings} ne '') { - print($msg, "\n"); - sleep 10; - } - push(@warnings,$msg); + my $msg = shift; + if ($Options{warnings} ne '') { + print($msg, "\n"); + sleep 10; + } + push(@warnings, $msg); } # # output a value to the log file and stdout # sub output { - if ($Options{log} ne '') { - print(LOG "@_\n"); - } - print("@_\n"); + if ($Options{log} ne '') { + print(LOG "@_\n"); + } + print("@_\n"); } # @@ -62,144 +62,144 @@ sub output { # sub at_exit { - if (@warnings > 0) { - output("WARNINGS FOLLOW"); - while (@warnings > 0) { - output(pop(@warnings)); + if (@warnings > 0) { + output("WARNINGS FOLLOW"); + while (@warnings > 0) { + output(pop(@warnings)); + } } - } } # # Remove leading and trailing whitespaces # sub remove_whitespaces { - my $string = shift; + my $string = shift; - $string =~ s/^\s*//; - $string =~ s/\s*$//; - return $string; + $string =~ s/^\s*//; + $string =~ s/\s*$//; + return $string; } # # Pose a question and get a response # sub question { - my $message = shift; - my $defaultreply = shift; - my $type = shift; - my $reply = ''; + my $message = shift; + my $defaultreply = shift; + my $type = shift; + my $reply = ''; - do { - if ($Options{interactive} ne '') { - print($message, ' [', $defaultreply , '] '); - $reply = ; - $reply = '' unless defined($reply); - chomp($reply); - } - else { - seek (IN, 0, 0) || die "rewind failed"; - while () { - chomp; - if ( /"#"/ ) { - } # scan out comments - elsif ( /$message/ ) { - my $garb; - ($garb, $reply) = split(":"); - seek (IN, 0, 2) || die "seek end failed"; + do { + if ($Options{interactive} ne '') { + print($message, ' [', $defaultreply, '] '); + $reply = ; + $reply = '' unless defined($reply); + chomp($reply); + } + else { + seek(IN, 0, 0) || die "rewind failed"; + while () { + chomp; + if (/"#"/) { + } # scan out comments + elsif (/$message/) { + my $garb; + ($garb, $reply) = split(":"); + seek(IN, 0, 2) || die "seek end failed"; + } + } + if ($reply eq '') { + warning("Question ($message) not present in input file - please rerun in interactive mode"); + at_exit(); + exit(-1); + } } - } - if ($reply eq '') { - warning("Question ($message) not present in input file - please rerun in interactive mode"); - at_exit(); - exit (-1); - } - } - $reply = remove_whitespaces($reply); - if ($reply eq '') { - $reply = $defaultreply; + $reply = remove_whitespaces($reply); + if ($reply eq '') { + $reply = $defaultreply; + } + if ($type eq "yesno") { + if (($reply =~ /^y$/i) || ($reply =~ /^yes$/)) { + $reply = "yes"; + } elsif (($reply =~ /^n$/i) || ($reply =~ /^no$/)) { + $reply = "no"; + } else { + print("Unrecognizable - try again\n"); + $reply = ''; + } + } + } while ($reply eq ''); + if ($Options{log} ne '') { + print(LOG $message, ": ", $reply, "\n"); } - if ($type eq "yesno") { - if (($reply =~ /^y$/i) || ($reply =~ /^yes$/)) { - $reply = "yes"; - } elsif (($reply =~ /^n$/i) || ($reply =~ /^no$/)) { - $reply = "no"; - } else { - print("Unrecognizable - try again\n"); - $reply = ''; - } - } - } while ($reply eq ''); - if ($Options{log} ne '') { - print(LOG $message, ": ", $reply, "\n"); - } - return $reply; + return $reply; } sub usage { - print "Usage: mktoolscenter\n"; - print " --ph \n"; - print " --pp \n"; - print " --puser \n"; - print " --ppw \n"; - print " -l \n"; - print " -s\n"; - print " --nfsserver \n"; - print " --nfspath \n"; - print " --profilename \n"; - print " --help\n\n"; - print "Updates IBM system x server hardware using IBM Bootable Media Creator.\n\n"; - print "Author: Jim Turner\n"; + print "Usage: mktoolscenter\n"; + print " --ph \n"; + print " --pp \n"; + print " --puser \n"; + print " --ppw \n"; + print " -l \n"; + print " -s\n"; + print " --nfsserver \n"; + print " --nfspath \n"; + print " --profilename \n"; + print " --help\n\n"; + print "Updates IBM system x server hardware using IBM Bootable Media Creator.\n\n"; + print "Author: Jim Turner\n"; } # # Begin main # -my $nfsserver='${xcat_server}'; -my $nfspath='#BOMCPATH#'; -my $profilename="bomc"; +my $nfsserver = '${xcat_server}'; +my $nfspath = '#BOMCPATH#'; +my $profilename = "bomc"; -unless (GetOptions("s"=>\$surrogate, "l=s"=>\$logfile, - "ph=s"=>\$proxy{host}, "pp=i"=>\$proxy{port}, - "puser=s"=>\$proxy{user}, "ppw=s"=>\$proxy{pw}, - "nfsserver=s"=>\$nfsserver,"nfspath=s"=>\$nfspath, - "profilename=s"=>\$profilename, "help"=>\$help, -)) { - usage(); - exit(1); +unless (GetOptions("s" => \$surrogate, "l=s" => \$logfile, + "ph=s" => \$proxy{host}, "pp=i" => \$proxy{port}, + "puser=s" => \$proxy{user}, "ppw=s" => \$proxy{pw}, + "nfsserver=s" => \$nfsserver, "nfspath=s" => \$nfspath, + "profilename=s" => \$profilename, "help" => \$help, + )) { + usage(); + exit(1); } if ($help) { usage(); exit 0; } if (@ARGV > 0) { - open(IN,"<",@ARGV[0]) || die "Cannot open input file @ARGV[0]"; - $Options{interactive} = ''; + open(IN, "<", @ARGV[0]) || die "Cannot open input file @ARGV[0]"; + $Options{interactive} = ''; } -if (($proxy{host} ne "") or ($proxy{port} ne "")) { # both or neither - die "Must specify both proxy host and port or neither" - unless (($proxy{host} ne "") and ($proxy{port} ne "")); +if (($proxy{host} ne "") or ($proxy{port} ne "")) { # both or neither + die "Must specify both proxy host and port or neither" + unless (($proxy{host} ne "") and ($proxy{port} ne "")); } my $ARCH = `uname -m`; chomp($ARCH); -my $WEIRDARCH = $ARCH; +my $WEIRDARCH = $ARCH; $WEIRDARCH =~ s/_/-/; my $OSVER = "unknown"; -if ( -e '/etc/SuSE-release' ) { - $OSVER=`grep -h VERSION /etc/SuSE-release |awk '{print $3}'` -} elsif ( -e '/etc/redhat-release' ) { - $OSVER="rhels" . `cat /etc/redhat-release |cut -f7 -d' '`; +if (-e '/etc/SuSE-release') { + $OSVER = `grep -h VERSION /etc/SuSE-release |awk '{print $3}'` +} elsif (-e '/etc/redhat-release') { + $OSVER = "rhels" . `cat /etc/redhat-release |cut -f7 -d' '`; chomp($OSVER); } open(LOG, ">", $logfile) || die "cannnot open logfile"; -print(LOG "# Date: ",$now, "\n"); +print(LOG "# Date: ", $now, "\n"); -output("#Your target OS version and architecture are:", $OSVER, $ARCH ); +output("#Your target OS version and architecture are:", $OSVER, $ARCH); # # if this is a surrogate - these will have to be answered manually @@ -208,12 +208,12 @@ output("#Your target OS version and architecture are:", $OSVER, $ARCH ); my $instroot; my $machines; if ($surrogate eq 0) { - $instroot = `gettab key=installdir site.value`; - my $nodes = `$nodels|tr '\n' ','`; - $machines = `$nodels $nodes vpd.mtm |cut -f2 -d:|sort -u|cut -b2-5 | uniq`; + $instroot = `gettab key=installdir site.value`; + my $nodes = `$nodels|tr '\n' ','`; + $machines = `$nodels $nodes vpd.mtm |cut -f2 -d:|sort -u|cut -b2-5 | uniq`; } else { - $instroot = question("What is the installdir?","/install",''); - $machines = question("What is the list of machine types?","7947",''); + $instroot = question("What is the installdir?", "/install", ''); + $machines = question("What is the list of machine types?", "7947", ''); } # @@ -222,179 +222,180 @@ if ($surrogate eq 0) { chomp($instroot); -my @machines = split("\n",$machines,); +my @machines = split("\n", $machines,); $machines = ''; my $i; -for ($i= 0; $i < @machines; $i++) { - if (@machines[$i] ne '') { - if ($machines ne '') { - $machines .= "," . @machines[$i]; +for ($i = 0 ; $i < @machines ; $i++) { + if (@machines[$i] ne '') { + if ($machines ne '') { + $machines .= "," . @machines[$i]; + } + else { + $machines = @machines[$i]; + } } - else { - $machines = @machines[$i]; - } - } } output("#It appears that you have these machine types in your inventory:", $machines); -while ( question("Would you like to add others?","no","yesno") eq "yes") { - print "Here is a list of known supported machine types: \n\n"; - print " IBM BladeCenter HS12 (8014, 1916, 8028)\n"; - print " IBM BladeCenter HS20 (1883, 8843)\n"; - print " IBM BladeCenter HS21 (8853, 1885)\n"; - print " IBM BladeCenter HS21 XM (7995, 1915)\n"; - print " IBM BladeCenter HS22 (1936, 7870)\n"; - print " IBM BladeCenter HS22V (1949, 7871)\n"; - print " IBM BladeCenter LS20 (8850)\n"; - print " IBM BladeCenter LS21 (7971)\n"; - print " IBM BladeCenter LS22 (7901)\n"; - print " IBM BladeCenter LS41 (7972)\n"; - print " IBM BladeCenter LS42 (7902)\n"; - print " IBM System x3105 (4347)\n"; - print " IBM System x3200 (4362, 4363)\n"; - print " IBM System x3200 M2 (4367, 4368)\n"; - print " IBM System x3200 M3 (7327, 7328)\n"; - print " IBM System x3250 (4364, 4365, 4366)\n"; - print " IBM System x3250 M2 (4190, 4191, 4194)\n"; - print " IBM System x3250 M3 (4251, 4252)\n"; - print " IBM System x3350 (4192, 4193)\n"; - print " IBM System x3400 (7973, 7974, 7975, 7976)\n"; - print " IBM System x3400 M2 (7836, 7837)\n"; - print " IBM System x3400 M3 (7878, 7379)\n"; - print " IBM System x3450 (4197, 7948)\n"; - print " IBM System x3455 (7940, 7941, 7984, 7986)\n"; - print " IBM System x3500 (7977)\n"; - print " IBM System x3500 M2 (7839)\n"; - print " IBM System x3500 M3 (7880)\n"; - print " IBM System x3550 (1913, 7978)\n"; - print " IBM System x3550 M2 (7946)\n"; - print " IBM System x3550 M3 (4254, 7944)\n"; - print " IBM System x3650 (1914, 7979)\n"; - print " IBM System x3650 M2 (7947)\n"; - print " IBM System x3650 M3 (4255, 7945)\n"; - print " IBM System x3655 (7943, 7985)\n"; - print " IBM System x3755 (7163, 8877)\n"; - print " IBM System x3800 (8866)\n"; - print " IBM System x3850 (8863, 7365, 8864, 7362)\n"; - print " IBM System x3850 M2 (7233, 7234, 7141, 7144)\n"; - print " IBM System x3850 X5 (7145, 7146)\n"; - print " IBM System x3950 (8872, 7366, 8878, 7363)\n"; - print " IBM System x3950 M2 (7141, 7233, 7234)\n"; - print " IBM System x3950 E (8874, 7367, 8879, 7364)\n"; - print " IBM System x3950 X5 (7145)\n"; - print " IBM System x iDataPlex dx320 server (6388)\n"; - print " IBM System x iDataPlex dx340 server (7832)\n"; - print " IBM System x iDataPlex dx360 server (7833)\n"; - print " IBM System x iDataPlex dx360 M2 server (7321, 7323, 6380)\n"; - print " IBM System x iDataPlex dx360 M3 server (6391)\n"; - print " IBM eServer xSeries 206m (8485, 8490)\n"; - print " IBM eServer xSeries 226 (8648, 8488)\n"; - print " IBM eServer xSeries 236 (8841)\n"; - print " IBM eServer xSeries 260 (8865)\n"; - print " IBM eServer xSeries 306m (8491, 8849, 1887)\n"; - print " IBM eServer xSeries 336 (8837, 1879)\n"; - print " IBM eServer xSeries 346 (1880, 8840)\n"; - print " IBM eServer xSeries 366 (8863)\n"; - print " IBM eServer xSeries 460 (8874)\n"; - print " IBM eServer xSeries MXE 460 (8874)\n"; - my $add = question("Additional Machine Type is?","6391",''); - if ($machines ne '') { - $machines .= "," . $add; - } - else { - $machines = $add; - } - output("#Current list is now:", $machines); +while (question("Would you like to add others?", "no", "yesno") eq "yes") { + print "Here is a list of known supported machine types: \n\n"; + print " IBM BladeCenter HS12 (8014, 1916, 8028)\n"; + print " IBM BladeCenter HS20 (1883, 8843)\n"; + print " IBM BladeCenter HS21 (8853, 1885)\n"; + print " IBM BladeCenter HS21 XM (7995, 1915)\n"; + print " IBM BladeCenter HS22 (1936, 7870)\n"; + print " IBM BladeCenter HS22V (1949, 7871)\n"; + print " IBM BladeCenter LS20 (8850)\n"; + print " IBM BladeCenter LS21 (7971)\n"; + print " IBM BladeCenter LS22 (7901)\n"; + print " IBM BladeCenter LS41 (7972)\n"; + print " IBM BladeCenter LS42 (7902)\n"; + print " IBM System x3105 (4347)\n"; + print " IBM System x3200 (4362, 4363)\n"; + print " IBM System x3200 M2 (4367, 4368)\n"; + print " IBM System x3200 M3 (7327, 7328)\n"; + print " IBM System x3250 (4364, 4365, 4366)\n"; + print " IBM System x3250 M2 (4190, 4191, 4194)\n"; + print " IBM System x3250 M3 (4251, 4252)\n"; + print " IBM System x3350 (4192, 4193)\n"; + print " IBM System x3400 (7973, 7974, 7975, 7976)\n"; + print " IBM System x3400 M2 (7836, 7837)\n"; + print " IBM System x3400 M3 (7878, 7379)\n"; + print " IBM System x3450 (4197, 7948)\n"; + print " IBM System x3455 (7940, 7941, 7984, 7986)\n"; + print " IBM System x3500 (7977)\n"; + print " IBM System x3500 M2 (7839)\n"; + print " IBM System x3500 M3 (7880)\n"; + print " IBM System x3550 (1913, 7978)\n"; + print " IBM System x3550 M2 (7946)\n"; + print " IBM System x3550 M3 (4254, 7944)\n"; + print " IBM System x3650 (1914, 7979)\n"; + print " IBM System x3650 M2 (7947)\n"; + print " IBM System x3650 M3 (4255, 7945)\n"; + print " IBM System x3655 (7943, 7985)\n"; + print " IBM System x3755 (7163, 8877)\n"; + print " IBM System x3800 (8866)\n"; + print " IBM System x3850 (8863, 7365, 8864, 7362)\n"; + print " IBM System x3850 M2 (7233, 7234, 7141, 7144)\n"; + print " IBM System x3850 X5 (7145, 7146)\n"; + print " IBM System x3950 (8872, 7366, 8878, 7363)\n"; + print " IBM System x3950 M2 (7141, 7233, 7234)\n"; + print " IBM System x3950 E (8874, 7367, 8879, 7364)\n"; + print " IBM System x3950 X5 (7145)\n"; + print " IBM System x iDataPlex dx320 server (6388)\n"; + print " IBM System x iDataPlex dx340 server (7832)\n"; + print " IBM System x iDataPlex dx360 server (7833)\n"; + print " IBM System x iDataPlex dx360 M2 server (7321, 7323, 6380)\n"; + print " IBM System x iDataPlex dx360 M3 server (6391)\n"; + print " IBM eServer xSeries 206m (8485, 8490)\n"; + print " IBM eServer xSeries 226 (8648, 8488)\n"; + print " IBM eServer xSeries 236 (8841)\n"; + print " IBM eServer xSeries 260 (8865)\n"; + print " IBM eServer xSeries 306m (8491, 8849, 1887)\n"; + print " IBM eServer xSeries 336 (8837, 1879)\n"; + print " IBM eServer xSeries 346 (1880, 8840)\n"; + print " IBM eServer xSeries 366 (8863)\n"; + print " IBM eServer xSeries 460 (8874)\n"; + print " IBM eServer xSeries MXE 460 (8874)\n"; + my $add = question("Additional Machine Type is?", "6391", ''); + + if ($machines ne '') { + $machines .= "," . $add; + } + else { + $machines = $add; + } + output("#Current list is now:", $machines); } -my $srcdir = question("Where is the BOMC bin file?","/root/Desktop",''); -my $asudir = question("Where is the ASU tgz file?","/root/Desktop",''); -my $ppath = "$instroot/netboot/toolscenter/$ARCH"; -my $path = "$ppath"."/".$profilename; -my $reponame="repo"; +my $srcdir = question("Where is the BOMC bin file?", "/root/Desktop", ''); +my $asudir = question("Where is the ASU tgz file?", "/root/Desktop", ''); +my $ppath = "$instroot/netboot/toolscenter/$ARCH"; +my $path = "$ppath" . "/" . $profilename; +my $reponame = "repo"; if ($profilename ne "bomc") { - $reponame=$profilename.".repo"; + $reponame = $profilename . ".repo"; } -my $repo = "$ppath/$reponame"; +my $repo = "$ppath/$reponame"; my $one_path = "$instroot/netboot/toolscenter/$ARCH"; my $two_path = "$instroot/netboot/bomc/$ARCH"; while ($path) { - $_ = question("Do you want to change the target path?",$path,''); - last if (( /$one_path/ ) or ( /$two_path/ )); -}; + $_ = question("Do you want to change the target path?", $path, ''); + last if ((/$one_path/) or (/$two_path/)); +} $path = $_; my $sandbox = "$repo/sandbox"; mkpath($path); mkpath($sandbox); my $util = "_utl_bomc*.bin"; -my $asu = "_utl_asu_asut*$WEIRDARCH.tgz"; +my $asu = "_utl_asu_asut*$WEIRDARCH.tgz"; -my $utilfile = "ibm".$util; -if (! -x $utilfile) { - $utilfile = "lnvgy".$util; +my $utilfile = "ibm" . $util; +if (!-x $utilfile) { + $utilfile = "lnvgy" . $util; } -my $asufile = "ibm".$asu; -if (! -x $asufile) { - $asufile = "lnvgy".$asu; +my $asufile = "ibm" . $asu; +if (!-x $asufile) { + $asufile = "lnvgy" . $asu; } -if ( system("cp $srcdir/$utilfile $repo") or system("cp $srcdir/$asufile $repo")) { - output("Error copying input file"); - exit; +if (system("cp $srcdir/$utilfile $repo") or system("cp $srcdir/$asufile $repo")) { + output("Error copying input file"); + exit; } my $optstr = ""; if ($proxy{host} ne "") { - $optstr = " --proxy-address=$proxy{host} --proxy-port=$proxy{port}"; - if ($proxy{user} ne "") { - $optstr .= " --proxy-user=$proxy{user}"; - } - if ($proxy{pw} ne "") { - $optstr .= " --proxy-password=$proxy{pw}"; - } + $optstr = " --proxy-address=$proxy{host} --proxy-port=$proxy{port}"; + if ($proxy{user} ne "") { + $optstr .= " --proxy-user=$proxy{user}"; + } + if ($proxy{pw} ne "") { + $optstr .= " --proxy-password=$proxy{pw}"; + } } -if ( system("chmod +x $repo/$utilfile") or system("cd $repo; tar -zxf $asufile") or system("cd $repo; ./$utilfile --tui -m $machines $optstr -l .")) { - output("Error executing $repo/$utilfile"); - exit; +if (system("chmod +x $repo/$utilfile") or system("cd $repo; tar -zxf $asufile") or system("cd $repo; ./$utilfile --tui -m $machines $optstr -l .")) { + output("Error executing $repo/$utilfile"); + exit; } my $src = "/opt/xcat/share/xcat/templates/cmos_settings"; -if ( system("cp -r $src $repo")) { - output("Error copying $src to $repo"); - exit; +if (system("cp -r $src $repo")) { + output("Error copying $src to $repo"); + exit; } -my $do_asu = question("Do you want to configure CMOS Settings for ASU?","yes","yesno"); +my $do_asu = question("Do you want to configure CMOS Settings for ASU?", "yes", "yesno"); if ($do_asu eq "yes") { - my $sol = question("Do you want these systems configured for SOL?","yes","yesno"); - my $hpc = question("Do you want these systems configured for HPC?","yes","yesno"); - if ($sol eq "yes") { - $sol = "sol"; - } - else { - $sol = "nosol"; - } - - if ($hpc eq "yes") { - $hpc = "hpc"; - } - else { - $hpc = "default"; - } - my $srcp = "$repo/cmos_settings/$sol/$hpc"; - foreach my $node (`$nodels`) { - chomp($node); - my $machine_type = `$nodels $node vpd.mtm |cut -f2 -d: |cut -b2-5 | uniq`; - chomp($machine_type); - if ($machine_type ne '' and -e "$srcp/$machine_type") { - `chtab node=$node firmware.cfgfile="$srcp/$machine_type"`; + my $sol = question("Do you want these systems configured for SOL?", "yes", "yesno"); + my $hpc = question("Do you want these systems configured for HPC?", "yes", "yesno"); + if ($sol eq "yes") { + $sol = "sol"; + } + else { + $sol = "nosol"; + } + + if ($hpc eq "yes") { + $hpc = "hpc"; + } + else { + $hpc = "default"; + } + my $srcp = "$repo/cmos_settings/$sol/$hpc"; + foreach my $node (`$nodels`) { + chomp($node); + my $machine_type = `$nodels $node vpd.mtm |cut -f2 -d: |cut -b2-5 | uniq`; + chomp($machine_type); + if ($machine_type ne '' and -e "$srcp/$machine_type") { + `chtab node=$node firmware.cfgfile="$srcp/$machine_type"`; + } } - } } my $sh; -open($sh, ">","$sandbox/start.sh"); +open($sh, ">", "$sandbox/start.sh"); print $sh <<'ENDOFSH'; #!/bin/sh -x # @@ -553,39 +554,39 @@ my $editstr1 = "perl -pi -e !s|#BOMCPATH#|$repo|! $sandbox/start.sh"; $editstr1 =~ s/!/\'/g; if (system($editstr1)) { - output("Error updating start.sh"); - exit; + output("Error updating start.sh"); + exit; } -my $boot = "_utl_boot*"; -my $bootfile = "ibm".$boot; -if (! -x "$repo/$bootfile") { - $bootfile = "lnvgy".$boot; +my $boot = "_utl_boot*"; +my $bootfile = "ibm" . $boot; +if (!-x "$repo/$bootfile") { + $bootfile = "lnvgy" . $boot; } -if ( system("cd $sandbox; cp $repo/asu* .; cp $repo/cdc_interface* .; cp $repo/$utilfile .; cp -a $repo/uxspi .; cp $repo/$bootfile .; echo y |./$utilfile --tui --pxe=$path --no-acquire --latest --force -l .")) { - output("Error executing $path/$utilfile for the second time"); - exit; +if (system("cd $sandbox; cp $repo/asu* .; cp $repo/cdc_interface* .; cp $repo/$utilfile .; cp -a $repo/uxspi .; cp $repo/$bootfile .; echo y |./$utilfile --tui --pxe=$path --no-acquire --latest --force -l .")) { + output("Error executing $path/$utilfile for the second time"); + exit; } -if ( symlink($repo,"$path/repo") eq 0 ) { - output("Error executing symlink $repo to $path/repo"); - exit; +if (symlink($repo, "$path/repo") eq 0) { + output("Error executing symlink $repo to $path/repo"); + exit; } if ($surrogate eq 1) { - output("Creating tar"); - my $tarme =""; - if ( -d "$instroot/netboot/toolscenter" ) { - $tarme = "$instroot/netboot/toolscenter "; - } - if ( -d "$instroot/netboot/bomc" ) { - $tarme .= "$instroot/netboot/bomc"; - } - if ( system("tar -czf ~/surrogate.tgz $tarme") ) { - output("Error executing tar") ; - } - else { - output("To unpack it tar -zxf surrogate.tgz -C /"); - } + output("Creating tar"); + my $tarme = ""; + if (-d "$instroot/netboot/toolscenter") { + $tarme = "$instroot/netboot/toolscenter "; + } + if (-d "$instroot/netboot/bomc") { + $tarme .= "$instroot/netboot/bomc"; + } + if (system("tar -czf ~/surrogate.tgz $tarme")) { + output("Error executing tar"); + } + else { + output("To unpack it tar -zxf surrogate.tgz -C /"); + } } diff --git a/xCAT-server/share/xcat/tools/nodesw b/xCAT-server/share/xcat/tools/nodesw index 1bf259673..4a3db0f4a 100755 --- a/xCAT-server/share/xcat/tools/nodesw +++ b/xCAT-server/share/xcat/tools/nodesw @@ -3,415 +3,448 @@ use strict; use Socket; use Data::Dumper; use Getopt::Long; + # each 0 is four bits: 0000 0000 -# thus its broken down: -# - ports 1-8 are in the first hex number -# - ports 9-16 are in the second hex number -# - ports 17-24 are in the third hex number -# - ports 25-32 are in the fourth hex number -# - ports 33-40 are in the fifth hex number -# - ports 41-48 are in the sixth hex number -# - ports 49-56 are in the seventh hex number +# thus its broken down: +# - ports 1-8 are in the first hex number +# - ports 9-16 are in the second hex number +# - ports 17-24 are in the third hex number +# - ports 25-32 are in the fourth hex number +# - ports 33-40 are in the fifth hex number +# - ports 41-48 are in the sixth hex number +# - ports 49-56 are in the seventh hex number my @bitmap = (0x01, 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02); -sub getVlanMask{ - my $session = shift; - my $vlan = shift; - my @xs; - my @hs; - my $oid = ".1.3.6.1.2.1.17.7.1.4.3.1.4.$vlan"; - my $hs = $session->get($oid); - if($session->{ErrorNum}){ - die "Couldn't get OID!" . $session->{ErrorStr} . "\n"; - } - $hs =~ s/\"//g; # get rid of quotes! - @hs = split(" ",$hs); - #foreach(@hs){ print "$_\n"; } - @xs = map(hex, @hs); - #foreach (@xs){ - # print $_ . "\n"; - #} - unless(scalar(@xs) eq 7){ - print "Could not get vlan mask for $vlan\n"; - } - #print "Switch mask:\n"; - #printf("%02x %02x %02x %02x %02x %02x %02x\n", @xs); - return(@xs); +sub getVlanMask { + my $session = shift; + my $vlan = shift; + my @xs; + my @hs; + my $oid = ".1.3.6.1.2.1.17.7.1.4.3.1.4.$vlan"; + my $hs = $session->get($oid); + if ($session->{ErrorNum}) { + die "Couldn't get OID!" . $session->{ErrorStr} . "\n"; + } + $hs =~ s/\"//g; # get rid of quotes! + @hs = split(" ", $hs); + + #foreach(@hs){ print "$_\n"; } + @xs = map(hex, @hs); + + #foreach (@xs){ + # print $_ . "\n"; + #} + unless (scalar(@xs) eq 7) { + print "Could not get vlan mask for $vlan\n"; + } + + #print "Switch mask:\n"; + #printf("%02x %02x %02x %02x %02x %02x %02x\n", @xs); + return (@xs); } + # add port 1 # returns a 7 digit hex string to logically or with existing # to add this port to the subnet sub getPortMask { - my $port = shift; - my @portMask; - my $hex; - my $xIndex; - if($port < 9){ $xIndex = 0; - }elsif($port < 17){ $xIndex = 1; - }elsif($port < 25){ $xIndex = 2; - }elsif($port < 33){ $xIndex = 3; - }elsif($port < 41){ $xIndex = 4; - }elsif($port < 49){ $xIndex = 5; - }elsif($port < 57){ $xIndex = 6; - }else{ - print "I don't know how to handle this port...\n"; - exit; - } - $port = $port % 8; - #print "$port\n"; - $hex = $bitmap[$port]; - #printf("%02x\n", $hex); - for(0 .. 6){ - if($_ eq $xIndex){ - push @portMask, $hex; - }else{ - push @portMask, hex(0); - } - } - #print "Port mask:\n"; - #printf("%02x %02x %02x %02x %02x %02x %02x\n", @portMask); - return @portMask; - + my $port = shift; + my @portMask; + my $hex; + my $xIndex; + if ($port < 9) { $xIndex = 0; + } elsif ($port < 17) { $xIndex = 1; + } elsif ($port < 25) { $xIndex = 2; + } elsif ($port < 33) { $xIndex = 3; + } elsif ($port < 41) { $xIndex = 4; + } elsif ($port < 49) { $xIndex = 5; + } elsif ($port < 57) { $xIndex = 6; + } else { + print "I don't know how to handle this port...\n"; + exit; + } + $port = $port % 8; + + #print "$port\n"; + $hex = $bitmap[$port]; + + #printf("%02x\n", $hex); + for (0 .. 6) { + if ($_ eq $xIndex) { + push @portMask, $hex; + } else { + push @portMask, hex(0); + } + } + + #print "Port mask:\n"; + #printf("%02x %02x %02x %02x %02x %02x %02x\n", @portMask); + return @portMask; + } -sub getSwitchInfo{ - my $switch = shift; - my ($version,$community,@junk); -# bunch of xCAT tables stuff here to connect to switch - my $info = `tabdump switches | grep smc001 | sed 's/"//g'`; - if($?){ - # if not in here, we try the defaults. - $version = 1; - $community = "public"; - }else{ - (undef,$version,undef,$community,@junk) = split(/,/,$info); - } +sub getSwitchInfo { + my $switch = shift; + my ($version, $community, @junk); - if($::DEBUG){ - print "switch parameters for $switch:\n"; - print "\tSNMP Version: $version\n"; - print "\tSNMP Community: $community\n"; - } - return($community, $version); + # bunch of xCAT tables stuff here to connect to switch + my $info = `tabdump switches | grep smc001 | sed 's/"//g'`; + if ($?) { + + # if not in here, we try the defaults. + $version = 1; + $community = "public"; + } else { + (undef, $version, undef, $community, @junk) = split(/,/, $info); + } + + if ($::DEBUG) { + print "switch parameters for $switch:\n"; + print "\tSNMP Version: $version\n"; + print "\tSNMP Community: $community\n"; + } + return ($community, $version); } -sub connectToSwitch{ - my $switch = shift; - my $session; - my ($community, $snmpver) = getSwitchInfo($switch); - $session = new SNMP::Session( - DestHost => $switch, - Version => $snmpver, - Community => $community, - UseSprintValue => 1, - ); - unless($session) { - #ERROR: - print "Failed to communicate with $switch\n"; - print $SNMP::Session::ErrorStr . "\n"; - #xCAT::MsgUtils->message("S","Failed to communicate with $switch"); - } - return $session; +sub connectToSwitch { + my $switch = shift; + my $session; + my ($community, $snmpver) = getSwitchInfo($switch); + $session = new SNMP::Session( + DestHost => $switch, + Version => $snmpver, + Community => $community, + UseSprintValue => 1, + ); + unless ($session) { + + #ERROR: + print "Failed to communicate with $switch\n"; + print $SNMP::Session::ErrorStr . "\n"; + + #xCAT::MsgUtils->message("S","Failed to communicate with $switch"); + } + return $session; } -sub xorMasks{ - my $sm = shift; - my $pm = shift; - my @nm; - foreach(0 .. 6){ - my $foo = @$sm[$_] ^ @$pm[$_]; - ##printf("%02x\n", $foo); - $nm[$_] = $foo; - } - return @nm; +sub xorMasks { + my $sm = shift; + my $pm = shift; + my @nm; + foreach (0 .. 6) { + my $foo = @$sm[$_] ^ @$pm[$_]; + ##printf("%02x\n", $foo); + $nm[$_] = $foo; + } + return @nm; } -sub orMasks{ - my $sm = shift; - my $pm = shift; - my @nm; - foreach(0 .. 6){ - my $foo = @$sm[$_] | @$pm[$_]; - ##printf("%02x\n", $foo); - $nm[$_] = $foo; - } - return @nm; +sub orMasks { + my $sm = shift; + my $pm = shift; + my @nm; + foreach (0 .. 6) { + my $foo = @$sm[$_] | @$pm[$_]; + ##printf("%02x\n", $foo); + $nm[$_] = $foo; + } + return @nm; } -sub andMasks{ - my $sm = shift; - my $pm = shift; - my @nm; - foreach(0 .. 6){ - my $foo = @$sm[$_] & @$pm[$_]; - ##printf("%02x\n", $foo); - $nm[$_] = $foo; - } - return @nm; +sub andMasks { + my $sm = shift; + my $pm = shift; + my @nm; + foreach (0 .. 6) { + my $foo = @$sm[$_] & @$pm[$_]; + ##printf("%02x\n", $foo); + $nm[$_] = $foo; + } + return @nm; } -# KLUDGE function because I can't figure out how to do this with +# KLUDGE function because I can't figure out how to do this with # SNMP.pm and I give up after a week of trying. sub snmpset { - my $sess = shift; - my $oid = shift; - my $type = shift; - my $val = shift; - my $snmpset = "/usr/bin/snmpset"; - my ($cmd, $comm, $vers, $switch); - unless(-r "/usr/bin/snmpset"){ - print "/usr/bin/snmpset command not found! Please install net-snmp-utils\n"; - exit 1; - } + my $sess = shift; + my $oid = shift; + my $type = shift; + my $val = shift; + my $snmpset = "/usr/bin/snmpset"; + my ($cmd, $comm, $vers, $switch); + unless (-r "/usr/bin/snmpset") { + print "/usr/bin/snmpset command not found! Please install net-snmp-utils\n"; + exit 1; + } - $comm = $sess->{Community}; - $vers = $sess->{Version}; - $switch = $sess->{DestHost}; + $comm = $sess->{Community}; + $vers = $sess->{Version}; + $switch = $sess->{DestHost}; - $cmd = "$snmpset -c $comm -v $vers $switch $oid $type $val"; - #print "$cmd\n"; - system("$cmd >/dev/null"); - #print "ec: $?\n"; - if($? > 0){ - print "Failed to execute command $cmd\n"; - exit 1; - } - return $?; + $cmd = "$snmpset -c $comm -v $vers $switch $oid $type $val"; + + #print "$cmd\n"; + system("$cmd >/dev/null"); + + #print "ec: $?\n"; + if ($? > 0) { + print "Failed to execute command $cmd\n"; + exit 1; + } + return $?; } -sub addNodeToVlan{ - # to run: switchport allowed vlan add $port (use bitmap) - # snmpset .. $oid1.$vlan x 00 00 00 00 00 00 00 - - my $oid1 = '.1.3.6.1.2.1.17.7.1.4.3.1.4'; - # to run: switchport native vlan $vlan - # snmpset .. $oid2.$port u $vlan - my $oid2 = '.1.3.6.1.2.1.17.7.1.4.5.1.1'; - my $session = shift; - my $vlan = shift; - my $port = shift; - #$oid1 .= ".$vlan"; - #print "$oid1 \n"; - my @xs; # netmask for current switch - my @pm; # netmask for port - my @jm; # the joined netmask - @xs = getVlanMask($session, $vlan); - @pm = getPortMask($port); - @jm = orMasks(\@xs, \@pm); - #print "Join mask:\n"; - printf("%02x %02x %02x %02x %02x %02x %02x\n", @jm) if $::DEBUG; - my $mask = sprintf("%02x %02x %02x %02x %02x %02x %02x ", @jm); +sub addNodeToVlan { - ################################# - # PART 1: add the switchport allowed capability - ################################# + # to run: switchport allowed vlan add $port (use bitmap) + # snmpset .. $oid1.$vlan x 00 00 00 00 00 00 00 - # TODO: This part I can't get working so I'm just going to do an - # snmpset command here instead. - #my $v1 = new SNMP::Varbind([$oid1,$vlan,$mask, 'OCTETSTR']); - #print Dumper($v1); - #$session->set($v1); - #if($session->{ErrorStr}) { - # print "Error! " . $session->{ErrorStr} . "\n"; - #} - snmpset($session, "$oid1.$vlan", "x", "\'$mask\'"); + my $oid1 = '.1.3.6.1.2.1.17.7.1.4.3.1.4'; - ####################################### - # PART 2: add the switchport native - ####################################### + # to run: switchport native vlan $vlan + # snmpset .. $oid2.$port u $vlan + my $oid2 = '.1.3.6.1.2.1.17.7.1.4.5.1.1'; + my $session = shift; + my $vlan = shift; + my $port = shift; - # first get the current one for part 3: - my $currNativeVlan = $session->get("$oid2.$port"); - if($session->{ErrorNum}){ - die "Couldn't get OID!" . $session->{ErrorStr} . "\n"; - } - print "currNativeVLAN: $currNativeVlan\n" if $::DEBUG; - print "$currNativeVlan -> "; - # set the new switchport native vlan - my $v2 = new SNMP::Varbind([$oid2,$port,$vlan,'GAUGE32']); - #print Dumper($v2); - $session->set($v2); - if($session->{ErrorStr}) { - print "Error! " . $session->{ErrorStr} . "\n"; - } - - ####################################### - # PART 3: take it off the other one it is on - ####################################### - delPortFromVlan($session, $port, $currNativeVlan); + #$oid1 .= ".$vlan"; + #print "$oid1 \n"; + my @xs; # netmask for current switch + my @pm; # netmask for port + my @jm; # the joined netmask + @xs = getVlanMask($session, $vlan); + @pm = getPortMask($port); + @jm = orMasks(\@xs, \@pm); + + #print "Join mask:\n"; + printf("%02x %02x %02x %02x %02x %02x %02x\n", @jm) if $::DEBUG; + my $mask = sprintf("%02x %02x %02x %02x %02x %02x %02x ", @jm); + + ################################# + # PART 1: add the switchport allowed capability + ################################# + + # TODO: This part I can't get working so I'm just going to do an + # snmpset command here instead. + #my $v1 = new SNMP::Varbind([$oid1,$vlan,$mask, 'OCTETSTR']); + #print Dumper($v1); + #$session->set($v1); + #if($session->{ErrorStr}) { + # print "Error! " . $session->{ErrorStr} . "\n"; + #} + snmpset($session, "$oid1.$vlan", "x", "\'$mask\'"); + + ####################################### + # PART 2: add the switchport native + ####################################### + + # first get the current one for part 3: + my $currNativeVlan = $session->get("$oid2.$port"); + if ($session->{ErrorNum}) { + die "Couldn't get OID!" . $session->{ErrorStr} . "\n"; + } + print "currNativeVLAN: $currNativeVlan\n" if $::DEBUG; + print "$currNativeVlan -> "; + + # set the new switchport native vlan + my $v2 = new SNMP::Varbind([ $oid2, $port, $vlan, 'GAUGE32' ]); + + #print Dumper($v2); + $session->set($v2); + if ($session->{ErrorStr}) { + print "Error! " . $session->{ErrorStr} . "\n"; + } + + ####################################### + # PART 3: take it off the other one it is on + ####################################### + delPortFromVlan($session, $port, $currNativeVlan); } # returns the vlan number -sub getVlans{ - my $session = shift; - my %vlans; - # IF-MIB:ifName: .1.3.6.1.2.1.31.1.1.1.1 - my $ifName = '.1.3.6.1.2.1.31.1.1.1.1'; - my $varbind = new SNMP::Varbind([$ifName, '']); - $session->getnext($varbind); - if($session->{ErrorStr}) { - print "Error! " . $session->{ErrorStr} . "\n"; - } - # varbind: name: ifName, 1, Port1, OCTETSTR - while($varbind->[2]){ - #print $varbind->[2] . "\n"; - my $name = $varbind->[2]; - if($name =~ /VLAN/){ - #print "Found $name on " . $session->{DestHost} . "\n"; - $name =~ s/VLAN//g; - # we subtract 1000 off the name to give us the actual VLAN. - $vlans{$name} = $varbind->[1] - 1000; - #foreach(@$varbind){ - # print "\t$_\n"; - #} - } - $session->getnext($varbind); - } - #print Dumper(%vlans); - #foreach(keys %vlans){ - # print "VLAN: $_ has value: ". $vlans{$_} ."\n"; - #} - return \%vlans; +sub getVlans { + my $session = shift; + my %vlans; + + # IF-MIB:ifName: .1.3.6.1.2.1.31.1.1.1.1 + my $ifName = '.1.3.6.1.2.1.31.1.1.1.1'; + my $varbind = new SNMP::Varbind([ $ifName, '' ]); + $session->getnext($varbind); + if ($session->{ErrorStr}) { + print "Error! " . $session->{ErrorStr} . "\n"; + } + + # varbind: name: ifName, 1, Port1, OCTETSTR + while ($varbind->[2]) { + + #print $varbind->[2] . "\n"; + my $name = $varbind->[2]; + if ($name =~ /VLAN/) { + + #print "Found $name on " . $session->{DestHost} . "\n"; + $name =~ s/VLAN//g; + + # we subtract 1000 off the name to give us the actual VLAN. + $vlans{$name} = $varbind->[1] - 1000; + + #foreach(@$varbind){ + # print "\t$_\n"; + #} + } + $session->getnext($varbind); + } + + #print Dumper(%vlans); + #foreach(keys %vlans){ + # print "VLAN: $_ has value: ". $vlans{$_} ."\n"; + #} + return \%vlans; } # return 1 if port is on vlan return 0 if not on vlan -sub checkPortVlan{ - my $rc = 0; - my $session = shift; - my $p = shift; - my $v = shift; - my @xs; # netmask for current switch - my @pm; # netmask for port - my @jm; # the joined netmask - @xs = getVlanMask($session, $v); - @pm = getPortMask($p); - @jm = andMasks(\@xs, \@pm); - #print "And Mask:\n"; - #printf("%02x %02x %02x %02x %02x %02x %02x\n", @jm); - my $m = sprintf("%x%x%x%x%x%x%x", @jm); - #print "m: $m\n"; - if($m > 0){ - #print "port $p is on VLAN $v on switch " . $session->{DestHost} . "\n"; - $rc = 1; - } - return $rc; - +sub checkPortVlan { + my $rc = 0; + my $session = shift; + my $p = shift; + my $v = shift; + my @xs; # netmask for current switch + my @pm; # netmask for port + my @jm; # the joined netmask + @xs = getVlanMask($session, $v); + @pm = getPortMask($p); + @jm = andMasks(\@xs, \@pm); + + #print "And Mask:\n"; + #printf("%02x %02x %02x %02x %02x %02x %02x\n", @jm); + my $m = sprintf("%x%x%x%x%x%x%x", @jm); + + #print "m: $m\n"; + if ($m > 0) { + + #print "port $p is on VLAN $v on switch " . $session->{DestHost} . "\n"; + $rc = 1; + } + return $rc; + } sub delPortFromVlan { - my $session = shift; - my $port = shift; - my $vlan = shift; - print "removing port $port from vlan $vlan\n" if $::DEBUG; - # first check and see if its on there: - unless(checkPortVlan($session, $port, $vlan)){ - print "Port $port is not on VLAN $vlan\n"; - } - my @vm = getVlanMask($session, $vlan); - my @pm = getPortMask($port); - my @xm = xorMasks(\@vm, \@pm); - #print "portmask:\n"; - #printf("%02x %02x %02x %02x %02x %02x %02x\n", @pm); - #print "vlanmask:\n"; - #printf("%02x %02x %02x %02x %02x %02x %02x\n", @vm); - #print "xormask:\n"; - #printf("%02x %02x %02x %02x %02x %02x %02x\n", @xm); + my $session = shift; + my $port = shift; + my $vlan = shift; + print "removing port $port from vlan $vlan\n" if $::DEBUG; - # this is the untagged remove - my $oid1 = '.1.3.6.1.2.1.17.7.1.4.3.1.4'; - my $mask = sprintf("%02x %02x %02x %02x %02x %02x %02x ", @xm); - snmpset($session, "$oid1.$vlan", "x", "\'$mask\'"); + # first check and see if its on there: + unless (checkPortVlan($session, $port, $vlan)) { + print "Port $port is not on VLAN $vlan\n"; + } + my @vm = getVlanMask($session, $vlan); + my @pm = getPortMask($port); + my @xm = xorMasks(\@vm, \@pm); + + #print "portmask:\n"; + #printf("%02x %02x %02x %02x %02x %02x %02x\n", @pm); + #print "vlanmask:\n"; + #printf("%02x %02x %02x %02x %02x %02x %02x\n", @vm); + #print "xormask:\n"; + #printf("%02x %02x %02x %02x %02x %02x %02x\n", @xm); + + # this is the untagged remove + my $oid1 = '.1.3.6.1.2.1.17.7.1.4.3.1.4'; + my $mask = sprintf("%02x %02x %02x %02x %02x %02x %02x ", @xm); + snmpset($session, "$oid1.$vlan", "x", "\'$mask\'"); - # this is the tagged remove - my $oid2 = '.1.3.6.1.2.1.17.7.1.4.3.1.2'; - #my $mask = sprintf("%02x %02x %02x %02x %02x %02x %02x ", @xm); - #print "tagged mask: $mask\n"; - snmpset($session, "$oid2.$vlan", "x", "\'$mask\'"); - + # this is the tagged remove + my $oid2 = '.1.3.6.1.2.1.17.7.1.4.3.1.2'; + + #my $mask = sprintf("%02x %02x %02x %02x %02x %02x %02x ", @xm); + #print "tagged mask: $mask\n"; + snmpset($session, "$oid2.$vlan", "x", "\'$mask\'"); + } -sub displayHelp{ - my $ec = shift; - print "nodesw changes the vlan of a node to a specified vlan\n"; - print "requires xCAT 2.0, Switch configured with SNMP sets, and only tested on SMC8648T\n"; - print "nodesw -h|--help\n"; - print "nodesw [-v] vlan \n"; - print "nodesw [-v] show\n\n"; - print "Author: Vallard Benincosa\n"; - exit $ec; +sub displayHelp { + my $ec = shift; + print "nodesw changes the vlan of a node to a specified vlan\n"; + print "requires xCAT 2.0, Switch configured with SNMP sets, and only tested on SMC8648T\n"; + print "nodesw -h|--help\n"; + print "nodesw [-v] vlan \n"; + print "nodesw [-v] show\n\n"; + print "Author: Vallard Benincosa\n"; + exit $ec; } -sub getNodeRange{ - my $nr = shift; - my @nr = `/opt/xcat/bin/nodels $nr switch.switch switch.port`; - my $nh; - chomp(@nr); - if($?){ - print $nr[0]; - exit 1; - } - foreach(@nr){ - my($n,$char,$val) = split(/:/, $_); - $char = (split(/\./,$char))[1]; - $val =~ s/ //g; - $nh->{$n}{$char} = $val; - } +sub getNodeRange { + my $nr = shift; + my @nr = `/opt/xcat/bin/nodels $nr switch.switch switch.port`; + my $nh; + chomp(@nr); + if ($?) { + print $nr[0]; + exit 1; + } + foreach (@nr) { + my ($n, $char, $val) = split(/:/, $_); + $char = (split(/\./, $char))[1]; + $val =~ s/ //g; + $nh->{$n}{$char} = $val; + } - if($::DEBUG){ - foreach(keys %$nh){ - print $_ .":"; - print " switch:" . $nh->{$_}{'switch'} ; - print " port:" . $nh->{$_}{'port'}; - print "\n"; - } - } + if ($::DEBUG) { + foreach (keys %$nh) { + print $_ . ":"; + print " switch:" . $nh->{$_}{'switch'}; + print " port:" . $nh->{$_}{'port'}; + print "\n"; + } + } - # make sure all fields are defined - my $e = 0; - foreach my $node (keys %$nh){ - unless($nh->{$node}{'switch'}){ - print "$node does not have a defined switch in xCAT! (nodels $node switch.switch)\n"; - $e++; - } - unless($nh->{$node}{'port'}){ - print "$node does not have a defined port in xCAT! (nodels $node switch.port)\n"; - $e++; - } - - } - if($e > 0){ - exit 1; - } + # make sure all fields are defined + my $e = 0; + foreach my $node (keys %$nh) { + unless ($nh->{$node}{'switch'}) { + print "$node does not have a defined switch in xCAT! (nodels $node switch.switch)\n"; + $e++; + } + unless ($nh->{$node}{'port'}) { + print "$node does not have a defined port in xCAT! (nodels $node switch.port)\n"; + $e++; + } - # return the node hash - return $nh; + } + if ($e > 0) { + exit 1; + } + + # return the node hash + return $nh; } -sub show{ - my $oid2 = '.1.3.6.1.2.1.17.7.1.4.5.1.1'; - my $nh = shift; - foreach my $node (keys %$nh){ - my $port = $nh->{$node}{'port'}; - my $switch = $nh->{$node}{'switch'}; - my $session = connectToSwitch($switch); - my $currNativeVlan = $session->get("$oid2.$port"); - if($session->{ErrorNum}){ - die "Couldn't get OID!" . $session->{ErrorStr} . "\n"; - } - print "$node: $currNativeVlan\n"; - } +sub show { + my $oid2 = '.1.3.6.1.2.1.17.7.1.4.5.1.1'; + my $nh = shift; + foreach my $node (keys %$nh) { + my $port = $nh->{$node}{'port'}; + my $switch = $nh->{$node}{'switch'}; + my $session = connectToSwitch($switch); + my $currNativeVlan = $session->get("$oid2.$port"); + if ($session->{ErrorNum}) { + die "Couldn't get OID!" . $session->{ErrorStr} . "\n"; + } + print "$node: $currNativeVlan\n"; + } } @@ -425,59 +458,59 @@ sub show{ # connect to switch to see: -my $help =0; +my $help = 0; $::DEBUG = 0; GetOptions( - 'h|help' => \$help, - 'v|verbose' => \$::DEBUG + 'h|help' => \$help, + 'v|verbose' => \$::DEBUG ); -if($help){ - displayHelp(0); +if ($help) { + displayHelp(0); } require SNMP; -$SNMP::debugging = 1; -$SNMP::verbose = 1; +$SNMP::debugging = 1; +$SNMP::verbose = 1; $SNMP::best_guess = 1; -if($::DEBUG){ - print "verbose is set to on!\n"; +if ($::DEBUG) { + print "verbose is set to on!\n"; } -my $nr = ""; +my $nr = ""; my $nodeRange = shift; -my $cmd = shift; -my $vlan = shift; +my $cmd = shift; +my $vlan = shift; -unless ($nodeRange){ - print "missing noderange!\n\n"; - displayHelp(1); +unless ($nodeRange) { + print "missing noderange!\n\n"; + displayHelp(1); } -unless($cmd) { - print "missing operation! [show | vlan ]\n\n"; - displayHelp(1); +unless ($cmd) { + print "missing operation! [show | vlan ]\n\n"; + displayHelp(1); } -if($cmd eq 'vlan'){ - unless($vlan){ - print "missing vlan number!\n\n"; - displayHelp(1); - } - $nr = getNodeRange($nodeRange); - chVlan($nr, $vlan); +if ($cmd eq 'vlan') { + unless ($vlan) { + print "missing vlan number!\n\n"; + displayHelp(1); + } + $nr = getNodeRange($nodeRange); + chVlan($nr, $vlan); -}elsif($cmd eq 'show'){ - print "showing $nodeRange vlan settings\n" if $::DEBUG; - $nr = getNodeRange($nodeRange); - show($nr); - -}else{ - print "unrecognized operation requested: $cmd\n\n"; - displayHelp(1); +} elsif ($cmd eq 'show') { + print "showing $nodeRange vlan settings\n" if $::DEBUG; + $nr = getNodeRange($nodeRange); + show($nr); + +} else { + print "unrecognized operation requested: $cmd\n\n"; + displayHelp(1); } - + ################################################################################ @@ -498,43 +531,45 @@ if($cmd eq 'vlan'){ # addPortToVLAN ################################################################################ # get all VLANs -sub chVlan{ - my $nh = shift; - my $currSwitch = ''; - my ($session, $vlans, $exists); - foreach my $node (keys %$nh){ - my $port = $nh->{$node}{'port'}; - my $switch = $nh->{$node}{'switch'}; - unless($switch eq $currSwitch){ - $session = connectToSwitch($switch); - $vlans = getVlans($session); - $exists = 0; - $currSwitch = $switch; - } +sub chVlan { + my $nh = shift; + my $currSwitch = ''; + my ($session, $vlans, $exists); + foreach my $node (keys %$nh) { + my $port = $nh->{$node}{'port'}; + my $switch = $nh->{$node}{'switch'}; + unless ($switch eq $currSwitch) { + $session = connectToSwitch($switch); + $vlans = getVlans($session); + $exists = 0; + $currSwitch = $switch; + } - foreach(keys %$vlans){ - # see if the requested VLAN actually exists - if( $_ eq $vlan){ - print "VLAN $_ exists on $switch\n" if $::DEBUG; - # if it exists see if its already on it - $exists = 1; - if(checkPortVlan($session, $port, $vlans->{$_})){ - print "$node: port $port already exists on $switch VLAN $vlan\n"; - exit 1; - }else{ - print "Adding Port: $port to VLAN: $vlan\n" if $::DEBUG; - print $node . ": "; - if(addNodeToVlan($session, $vlan, $port) eq 0){ - print "Added port: $port to VLAN: $vlan\n" if $::DEBUG; - print "$vlan\n"; - } - } - } - } - unless($exists){ - print "VLAN $vlan does not exist on " . $session->{DestHost} . "\n"; - exit 1; - } - } + foreach (keys %$vlans) { + + # see if the requested VLAN actually exists + if ($_ eq $vlan) { + print "VLAN $_ exists on $switch\n" if $::DEBUG; + + # if it exists see if its already on it + $exists = 1; + if (checkPortVlan($session, $port, $vlans->{$_})) { + print "$node: port $port already exists on $switch VLAN $vlan\n"; + exit 1; + } else { + print "Adding Port: $port to VLAN: $vlan\n" if $::DEBUG; + print $node . ": "; + if (addNodeToVlan($session, $vlan, $port) eq 0) { + print "Added port: $port to VLAN: $vlan\n" if $::DEBUG; + print "$vlan\n"; + } + } + } + } + unless ($exists) { + print "VLAN $vlan does not exist on " . $session->{DestHost} . "\n"; + exit 1; + } + } } diff --git a/xCAT-server/share/xcat/tools/powervm/configvios b/xCAT-server/share/xcat/tools/powervm/configvios index 08af11603..884e59a76 100755 --- a/xCAT-server/share/xcat/tools/powervm/configvios +++ b/xCAT-server/share/xcat/tools/powervm/configvios @@ -1,13 +1,14 @@ #!/usr/bin/perl -lw package VIOSObj; + sub new { my $type = shift; my %parm = @_; my $this = {}; - $this->{'key'} = $parm{'key'}; - $this->{'conf'} = {}; - $this->{'conf_file'} = $parm{'conf_file'}; + $this->{'key'} = $parm{'key'}; + $this->{'conf'} = {}; + $this->{'conf_file'} = $parm{'conf_file'}; return bless $this, $type; } @@ -15,43 +16,44 @@ sub parse_conf { my $this = shift; my $file = $this->{'conf_file'}; - if(!open (FILE, $file)) + if (!open(FILE, $file)) { - # die("Open file $file failed!\n"); - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Open file $file failed!\n"; - `logger -t xcat -p local4.err $msg`; - return; + # die("Open file $file failed!\n"); + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Open file $file failed!\n"; + `logger -t xcat -p local4.err $msg`; + return; } - my $key = $this->{'key'}; - my $conf = undef; + my $key = $this->{'key'}; + my $conf = undef; my $category = undef; while () { my $line = $_; chomp($line); $line =~ s/[ \n\t\r\f]//g; - next if($line =~ /^\s*#/ || /^\s*$/); - if($line =~ /^\[(.+)\]$/) + next if ($line =~ /^\s*#/ || /^\s*$/); + if ($line =~ /^\[(.+)\]$/) { - last if($category); - if($1 eq $key) + last if ($category); + if ($1 eq $key) { - $conf = \%{$this->{'conf'}}; + $conf = \%{ $this->{'conf'} }; $category = $1; } next; } - next if(!$category); - + next if (!$category); + my @item = split('=', $line); - if($#item == 1) + if ($#item == 1) { - %{$conf} = (%{$conf}, $item[0]=>$item[1]); + %{$conf} = (%{$conf}, $item[0] => $item[1]); } else { - close (FILE); + close(FILE); + #die("Invalid line $line!\n"); chomp(my $date = `/bin/date`); my $msg = "$date configvios: Invaild line $line!\n"; @@ -59,13 +61,14 @@ sub parse_conf return; } } - if(!$conf) + if (!$conf) { - close (FILE); + close(FILE); + #die("Can not found related configuration for $key in file $file\n"); chomp(my $date = `/bin/date`); my $msg = "$date configvios: Can't found related configuration for $key in file $file\n"; - `logger -t xcat -p local4.err $msg`; + `logger -t xcat -p local4.err $msg`; return; } } @@ -73,7 +76,7 @@ sub parse_conf sub run_cmd { my $this = shift; - my $cmd = shift; + my $cmd = shift; print "command is: $cmd\n"; `su - padmin " -c ioscli license -accept; $cmd"`; my $result = $?; @@ -84,191 +87,195 @@ sub config { my $this = shift; $this->parse_conf(); - my $cmd = $this->get_cmd(); + my $cmd = $this->get_cmd(); my $result = $this->run_cmd($cmd); } package VIOSEth; our @ISA = (VIOSObj); + sub get_cmd { - my $this = shift; - my $cmd = undef; - my %config = %{$this->{'conf'}}; - my $cnt = 0; - my @conf = (); + my $this = shift; + my $cmd = undef; + my %config = %{ $this->{'conf'} }; + my $cnt = 0; + my @conf = (); print "Create and configure SEAs..."; - while( my ($key,$value) = each %config ) + while (my ($key, $value) = each %config) { - @conf = ($key,split(',',$value)); - if($#conf != 9) + @conf = ($key, split(',', $value)); + if ($#conf != 9) { - # print "Invalid configuration item $key,$value!\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key=$value!\n"; - `logger -t xcat -p local4.warning $msg`; - next; + # print "Invalid configuration item $key,$value!\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key=$value!\n"; + `logger -t xcat -p local4.warning $msg`; + next; } - $cmd = $cnt > 0 ? $cmd.' && ioscli mkvdev' : 'ioscli mkvdev'; + $cmd = $cnt > 0 ? $cmd . ' && ioscli mkvdev' : 'ioscli mkvdev'; $cnt++; - $cmd = $cmd.' -sea '.$conf[0].' -vadapter '.$conf[1].' -default '.$conf[2].' -defaultid '.$conf[3].' && mktcpip -hostname '.$conf[4]. -' -inetaddr '.$conf[5].' -netmask '.$conf[6].' -interface '.$conf[0].' -gateway '.$conf[7].' -nsrvdomain '.$conf[8].' -nsrvaddr '.$conf[9].' + $cmd = $cmd . ' -sea ' . $conf[0] . ' -vadapter ' . $conf[1] . ' -default ' . $conf[2] . ' -defaultid ' . $conf[3] . ' && mktcpip -hostname ' . $conf[4] . +' -inetaddr ' . $conf[5] . ' -netmask ' . $conf[6] . ' -interface ' . $conf[0] . ' -gateway ' . $conf[7] . ' -nsrvdomain ' . $conf[8] . ' -nsrvaddr ' . $conf[9] . ' -start'; } return $cmd; } package VIOSVg; -our @ISA = ( VIOSObj ); +our @ISA = (VIOSObj); + sub get_cmd { - my $this = shift; - my $cmd = undef; - my $cnt = 0; - my %config = %{$this->{'conf'}}; + my $this = shift; + my $cmd = undef; + my $cnt = 0; + my %config = %{ $this->{'conf'} }; print "Create volume groups..."; - while( my ($key,$value) = each %config ) + while (my ($key, $value) = each %config) { - my @hdisk = split(',', $value); - my $err = 0; + my @hdisk = split(',', $value); + my $err = 0; - foreach (@hdisk) - { - `lspv|grep $_ >/dev/nul 2>&1`; - $err++ if($? != 0) - } + foreach (@hdisk) + { + `lspv|grep $_ >/dev/nul 2>&1`; + $err++ if ($? != 0) + } - if($err != 0) - { - #print "Invalid configuration item $key: hard disk info error\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key:hard disk info error!\n"; - `logger -t xcat -p local4.warning $msg`; - next; - } + if ($err != 0) + { + #print "Invalid configuration item $key: hard disk info error\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key:hard disk info error!\n"; + `logger -t xcat -p local4.warning $msg`; + next; + } - `lsvg $key > /dev/nul 2>&1`; - if($? == 0) - { - #print "Invalid configuration item $key: vg $key already existed\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key:vg $key already existed!\n"; - `logger -t xcat -p local4.warning $msg`; - next; - } + `lsvg $key > /dev/nul 2>&1`; + if ($? == 0) + { + #print "Invalid configuration item $key: vg $key already existed\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key:vg $key already existed!\n"; + `logger -t xcat -p local4.warning $msg`; + next; + } - $cmd = $cnt>0? $cmd.' && ioscli mkvg':'ioscli mkvg'; - $cnt++; - $cmd = $cmd.' -f -vg '.$key.' '."@hdisk"; + $cmd = $cnt > 0 ? $cmd . ' && ioscli mkvg' : 'ioscli mkvg'; + $cnt++; + $cmd = $cmd . ' -f -vg ' . $key . ' ' . "@hdisk"; } return $cmd; } package VIOSLv; -our @ISA = ( VIOSObj ); +our @ISA = (VIOSObj); + sub get_cmd { - my $this = shift; - my $cmd = undef; - my %config = %{$this->{'conf'}}; - my $cnt = 0; - my @conf = (); + my $this = shift; + my $cmd = undef; + my %config = %{ $this->{'conf'} }; + my $cnt = 0; + my @conf = (); print "Create logcial volumes..."; - - while( my ($key,$value) = each %config ) - { - @conf = ($key, split(',', $value)); - if($#conf != 2) - { - #print "Invalid configuration item $key,$value!\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key=$value!\n"; - `logger -t xcat -p local4.warning $msg`; - next; - } - `su - padmin " -c ioscli lslv $conf[0]" > /dev/nul 2>&1`; - if($? == 0) - { - #print "Invalid configuration item $key:the lv name $conf[0] already existed\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key:the lv name $conf[0] already existed!\n"; - `logger -t xcat -p local4.warning $msg`; - next; - } - - `su - padmin " -c ioscli lsvg $conf[1]" > /dev/nul 2>&1`; - if($? != 0) - { - #print "Invalid configuration item $key:the vg $conf[1] doesn't exist\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key:the vg $conf[1] doesn't exist!\n"; - `logger -t xcat -p local4.warning $msg`; - next; - } - - my $ppsnum = `lsvg rootvg |grep "FREE PPs"|awk '{print \$6}'`; - if($conf[2] > $ppsnum) - { - #print "Invalid configuration item $key:there isn't enough space left in $conf[1]\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key:there isn't enough space left in $conf[1]!\n"; + while (my ($key, $value) = each %config) + { + @conf = ($key, split(',', $value)); + if ($#conf != 2) + { + #print "Invalid configuration item $key,$value!\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key=$value!\n"; `logger -t xcat -p local4.warning $msg`; - next; - } + next; + } - $cmd = $cnt>0 ? $cmd.' && ioscli mklv': 'ioscli mklv'; - $cnt++; - $cmd = $cmd.' -lv '.$conf[0].' '.$conf[1].' '.$conf[2]; + `su - padmin " -c ioscli lslv $conf[0]" > /dev/nul 2>&1`; + if ($? == 0) + { + #print "Invalid configuration item $key:the lv name $conf[0] already existed\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key:the lv name $conf[0] already existed!\n"; + `logger -t xcat -p local4.warning $msg`; + next; + } + + `su - padmin " -c ioscli lsvg $conf[1]" > /dev/nul 2>&1`; + if ($? != 0) + { + #print "Invalid configuration item $key:the vg $conf[1] doesn't exist\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key:the vg $conf[1] doesn't exist!\n"; + `logger -t xcat -p local4.warning $msg`; + next; + } + + my $ppsnum = `lsvg rootvg |grep "FREE PPs"|awk '{print \$6}'`; + if ($conf[2] > $ppsnum) + { + #print "Invalid configuration item $key:there isn't enough space left in $conf[1]\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key:there isn't enough space left in $conf[1]!\n"; + `logger -t xcat -p local4.warning $msg`; + next; + } + + $cmd = $cnt > 0 ? $cmd . ' && ioscli mklv' : 'ioscli mklv'; + $cnt++; + $cmd = $cmd . ' -lv ' . $conf[0] . ' ' . $conf[1] . ' ' . $conf[2]; } return $cmd; } package VIOSLvMap; -our @ISA = ( VIOSObj ); +our @ISA = (VIOSObj); + sub get_cmd { - my $this = shift; - my $cmd = undef; - my %config = %{$this->{'conf'}}; - my $cnt = 0; + my $this = shift; + my $cmd = undef; + my %config = %{ $this->{'conf'} }; + my $cnt = 0; print "Mapping logical volumes to virtual adapters..."; - while( my ($key,$value) = each %config ) + while (my ($key, $value) = each %config) { `su - padmin " -c ioscli lslv $value" > /dev/nul 2>&1`; - if($? != 0) + if ($? != 0) { - #print "Invalid configuration item $key: lv $value doesn't exist\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key:lv $value doesn't exist!\n"; - `logger -t xcat -p local4.warning $msg`; - next; + #print "Invalid configuration item $key: lv $value doesn't exist\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key:lv $value doesn't exist!\n"; + `logger -t xcat -p local4.warning $msg`; + next; } - `su - padmin " -c ioscli lsdev -virtual |grep $key " >/dev/nul 2>&1`; - if($? != 0) + `su - padmin " -c ioscli lsdev -virtual |grep $key " >/dev/nul 2>&1`; + if ($? != 0) { - #print "Invaild configuration item $key: virtual adapter $key doesn't exist\n"; - chomp(my $date = `/bin/date`); - my $msg = "$date configvios: Invalid configuration item $key: virtual adapter $key doesn't exist!\n"; - `logger -t xcat -p local4.warning $msg`; - next; + #print "Invaild configuration item $key: virtual adapter $key doesn't exist\n"; + chomp(my $date = `/bin/date`); + my $msg = "$date configvios: Invalid configuration item $key: virtual adapter $key doesn't exist!\n"; + `logger -t xcat -p local4.warning $msg`; + next; } - $cmd = $cnt > 0 ? $cmd.' && ioscli mkvdev' : 'ioscli mkvdev'; + $cmd = $cnt > 0 ? $cmd . ' && ioscli mkvdev' : 'ioscli mkvdev'; $cnt++; - $cmd = $cmd.' -vdev '.$value.' -vadapter '.$key; + $cmd = $cmd . ' -vdev ' . $value . ' -vadapter ' . $key; } return $cmd; } package main; my $conf_file = $ENV{'VIOS_CONF'} ? $ENV{'VIOS_CONF'} : './vios.conf'; -my $vioseth = VIOSEth->new("conf_file"=>$conf_file, "key"=>'SEA_Config'); +my $vioseth = VIOSEth->new("conf_file" => $conf_file, "key" => 'SEA_Config'); $vioseth->config(); -my $viosvg = VIOSVg->new("conf_file"=>$conf_file, "key"=>'Volume_Group'); +my $viosvg = VIOSVg->new("conf_file" => $conf_file, "key" => 'Volume_Group'); $viosvg->config(); -my $vioslv = VIOSLv->new("conf_file"=>$conf_file, "key"=>'Logical_Volume'); +my $vioslv = VIOSLv->new("conf_file" => $conf_file, "key" => 'Logical_Volume'); $vioslv->config(); -my $vioslvmap = VIOSLvMap->new("conf_file"=>$conf_file, "key"=>'Mapping_SCSI'); +my $vioslvmap = VIOSLvMap->new("conf_file" => $conf_file, "key" => 'Mapping_SCSI'); $vioslvmap->config(); exit; diff --git a/xCAT-server/share/xcat/tools/powervm/installsshforvios b/xCAT-server/share/xcat/tools/powervm/installsshforvios index d36e224eb..c5cda8ff7 100755 --- a/xCAT-server/share/xcat/tools/powervm/installsshforvios +++ b/xCAT-server/share/xcat/tools/powervm/installsshforvios @@ -18,7 +18,7 @@ #print "$::sdata xcataixpost: install the openssh and openssl\n"; `cd /xcatpost/packages; /usr/sbin/installp -aXYd . openssh.base openssl.base openssl.license openssh.msg.EN_US`; -if($? != 0) +if ($? != 0) { chomp($date = `/bin/date`); $msg = "$date installsshforvios: installing openssh failed!\n"; @@ -33,6 +33,7 @@ else #print "$::sdate xcataixpost: copy the public key from MN to vios\n"; `mkdir -p /home/padmin/.ssh/; cat /xcatpost/_ssh/authorized_keys >> /home/padmin/.ssh/authorized_keys2 2>&1`; + #print "$::sdate xcataixpost: xdsh -l padmin could logon automatically.\n"; `/xcatpost/remoteshell`; diff --git a/xCAT-server/share/xcat/tools/reorgtbls b/xCAT-server/share/xcat/tools/reorgtbls index b0867ced9..65d8cd9e3 100755 --- a/xCAT-server/share/xcat/tools/reorgtbls +++ b/xCAT-server/share/xcat/tools/reorgtbls @@ -23,7 +23,7 @@ use strict; use warnings; -# Use runsqlcmd to run the SQL query to read the list of tables in +# Use runsqlcmd to run the SQL query to read the list of tables in # the XCATDB schema # Then use runsqlcmd to run the reorg on the list of tables, # allow read/write by other applications during reorg @@ -32,18 +32,18 @@ my $tablelist; my $help; my $cmd; my @tablist; -GetOptions( 'V|verbose' => \$::VERBOSE, - 't=s' => \$tablelist, - 'h|help' => \$help,); +GetOptions('V|verbose' => \$::VERBOSE, + 't=s' => \$tablelist, + 'h|help' => \$help,); if ($help) { print "DB2 Table Reorganization utility.\n"; print - "This script can be set as a cron job or run on the command line to reorg the xcatdb DB2 database tables. It automatically added as a cron job, if you use the db2sqlsetup command to create your DB2 database setup for xCAT. \n"; +"This script can be set as a cron job or run on the command line to reorg the xcatdb DB2 database tables. It automatically added as a cron job, if you use the db2sqlsetup command to create your DB2 database setup for xCAT. \n"; print "Usage:\n"; print "\t--V - Verbose mode\n"; print "\t--h - usage\n"; print - "\t--t -comma delimitated list of tables.\n Without this flag it reorgs all tables in the xcatdb database .\n"; +"\t--t -comma delimitated list of tables.\n Without this flag it reorgs all tables in the xcatdb database .\n"; print "\n"; print "Author: Lissa Valletta\n"; exit 0; @@ -54,68 +54,70 @@ require xCAT::Utils; # check to see if running DB2 my $DBname = xCAT::Utils->get_DBName; if ($DBname ne "DB2") { - - print " Reorg of table only supported for DB2 database\n"; - `logger -p local4.err -t xcat " reorgtbls:Only supports DB2 database"` ; + + print " Reorg of table only supported for DB2 database\n"; + `logger -p local4.err -t xcat " reorgtbls:Only supports DB2 database"`; exit 1; - + } -if ($tablelist) { # input list of tables - @tablist=split(/\,/, $tablelist); -} else { # get all tables - $cmd="$::XCATROOT/sbin/runsqlcmd \"select tabname from syscat.tables where TABSCHEMA='XCATDB';\""; - @tablist = xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - `logger -p local4.err -t xcat " reorgtbls:error in select tabname from syscat.tables"` ; - exit 1; - } +if ($tablelist) { # input list of tables + @tablist = split(/\,/, $tablelist); +} else { # get all tables + $cmd = "$::XCATROOT/sbin/runsqlcmd \"select tabname from syscat.tables where TABSCHEMA='XCATDB';\""; + @tablist = xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { +`logger -p local4.err -t xcat " reorgtbls:error in select tabname from syscat.tables"`; + exit 1; + } } # reorg each table -my $foundheader=0; +my $foundheader = 0; foreach my $table (@tablist) { - chomp $table; - # skip lines untils we find the header unless -t option - if (!($tablelist)) { - if ($foundheader==0) { - if ( !($table =~ /TABNAME/)) { - next; - } else { - $foundheader=1; - next; - } + chomp $table; + + # skip lines untils we find the header unless -t option + if (!($tablelist)) { + if ($foundheader == 0) { + if (!($table =~ /TABNAME/)) { + next; + } else { + $foundheader = 1; + next; + } + } + } + + # skip blanks and -- lines + $table =~ s/\s*//g; # remove blanks + if ($table =~ /^\s*$/) { # skip blanks + next; + } + if ($table =~ m/[^a-zA-Z0-9_]/) # skip non alphanumeric lines not underscore + { + next; + } + $table =~ tr/a-z/A-Z/; # convert to upper + if ($::VERBOSE) { + print " Reorg of table $table\n"; + `logger -p local4.info -t xcat " Reorg of table $table."`; + } + $cmd = "$::XCATROOT/sbin/runsqlcmd \"reorg indexes all for table $table allow write access;\""; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + `logger -p local4.warning -t xcat " reorgtbls:error $cmd"`; + } else { + `logger -p local4.info -t xcat " reorgtbls:reorg indexes for $table"`; + } + $cmd = "$::XCATROOT/sbin/runsqlcmd \"reorg table $table inplace allow write access;\""; + xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + `logger -p local4.warning -t xcat " reorgtbls:error $cmd"`; + } else { + `logger -p local4.info -t xcat " reorgtbls:reorg $table inplace"`; } - } - # skip blanks and -- lines - $table =~ s/\s*//g; # remove blanks - if ($table =~ /^\s*$/) { # skip blanks - next; - } - if ($table =~ m/[^a-zA-Z0-9_]/) # skip non alphanumeric lines not underscore - { - next; - } - $table =~ tr/a-z/A-Z/; # convert to upper - if ($::VERBOSE) { - print " Reorg of table $table\n"; - `logger -p local4.info -t xcat " Reorg of table $table."`; - } - $cmd="$::XCATROOT/sbin/runsqlcmd \"reorg indexes all for table $table allow write access;\""; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - `logger -p local4.warning -t xcat " reorgtbls:error $cmd"`; - } else { - `logger -p local4.info -t xcat " reorgtbls:reorg indexes for $table"`; - } - $cmd="$::XCATROOT/sbin/runsqlcmd \"reorg table $table inplace allow write access;\""; - xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - `logger -p local4.warning -t xcat " reorgtbls:error $cmd"`; - } else { - `logger -p local4.info -t xcat " reorgtbls:reorg $table inplace"`; - } } exit 0; diff --git a/xCAT-server/share/xcat/tools/rmblade b/xCAT-server/share/xcat/tools/rmblade index ad5caa53f..913e79390 100755 --- a/xCAT-server/share/xcat/tools/rmblade +++ b/xCAT-server/share/xcat/tools/rmblade @@ -1,10 +1,10 @@ #!/usr/bin/perl ## snmp for monsetting to remove blade settings from blade when trap is recieved -## example: +## example: ## 1. user removes a blade from the chassis ## 2. snmp trap setup to point here ## 3. this script removes the blade configuration from xCAT -## 4. so if blade is placed in new slot or back in then xCAT goes +## 4. so if blade is placed in new slot or back in then xCAT goes ## through rediscover process again. BEGIN @@ -14,7 +14,7 @@ BEGIN use lib "$::XCATROOT/lib/perl"; use strict; -use Socket; # for name resolution +use Socket; # for name resolution use Getopt::Long; my $help; @@ -41,77 +41,79 @@ EOS require xCAT::Utils; require xCAT::TableUtils; -my $ip=''; -my $mm=''; -my $slot=''; -my $log = "/var/log/xcatsnmp"; +my $ip = ''; +my $mm = ''; +my $slot = ''; +my $log = "/var/log/xcatsnmp"; my $tftpdir = xCAT::TableUtils->getTftpDir(); -open(FILE,">>$log") or die "Can't open log!!!"; +open(FILE, ">>$log") or die "Can't open log!!!"; my $date = `date`; chomp($date); print FILE "==================== $date ============================\n"; sub rmblade { - my $blade = shift; - my $hex = ip2hex($blade); - print FILE "Running: nodech $blade chain.currstate='' chain.currchain=''\n"; - `nodech $blade chain.currstate= chain.currchain=`; - print FILE "Running: chtab -d node=$blade mac\n"; - `chtab -d node=$blade mac`; - print FILE "Running: makedhcp -d $blade\n"; - `makedhcp -d $blade`; - print FILE "Running: rm $tftpdir/pxelinux.cfg/$blade\n"; - `rm $tftpdir/pxelinux.cfg/$blade`; - if($hex){ - print FILE "Running: rm $tftpdir/pxelinux.cfg/$hex\n"; - `rm $tftpdir/pxelinux.cfg/$hex`; - } + my $blade = shift; + my $hex = ip2hex($blade); + print FILE "Running: nodech $blade chain.currstate='' chain.currchain=''\n"; + `nodech $blade chain.currstate= chain.currchain=`; + print FILE "Running: chtab -d node=$blade mac\n"; + `chtab -d node=$blade mac`; + print FILE "Running: makedhcp -d $blade\n"; + `makedhcp -d $blade`; + print FILE "Running: rm $tftpdir/pxelinux.cfg/$blade\n"; + `rm $tftpdir/pxelinux.cfg/$blade`; + + if ($hex) { + print FILE "Running: rm $tftpdir/pxelinux.cfg/$hex\n"; + `rm $tftpdir/pxelinux.cfg/$hex`; + } } sub ip2hex { - my $node = shift; - my $ip = ''; - my @quad; - my $hex = ''; - my $packed_ip = gethostbyname($node); - if(defined $packed_ip){ - $ip = inet_ntoa($packed_ip); - print FILE "IP that was removed is $ip\n"; - @quad = split('\.', $ip); - $hex = sprintf("%02X%02X%02X%02X", @quad); - } - return $hex; + my $node = shift; + my $ip = ''; + my @quad; + my $hex = ''; + my $packed_ip = gethostbyname($node); + if (defined $packed_ip) { + $ip = inet_ntoa($packed_ip); + print FILE "IP that was removed is $ip\n"; + @quad = split('\.', $ip); + $hex = sprintf("%02X%02X%02X%02X", @quad); + } + return $hex; } -foreach (<>){ - if(/ip=UDP/){ - $ip = $_; - chomp($ip); - $ip =~ s/ip=UDP: \[(.*)\]:.*/$1/g; - $mm = gethostbyaddr(inet_aton($ip), AF_INET); - }elsif(/spTrapSourceId=/){ - $slot = $_; - chomp($slot); - $slot =~ s/.*Blade_(\d\d).*/$1/g; - $slot = $slot * 1; # to get rid of the leading 0's. - } +foreach (<>) { + if (/ip=UDP/) { + $ip = $_; + chomp($ip); + $ip =~ s/ip=UDP: \[(.*)\]:.*/$1/g; + $mm = gethostbyaddr(inet_aton($ip), AF_INET); + } elsif (/spTrapSourceId=/) { + $slot = $_; + chomp($slot); + $slot =~ s/.*Blade_(\d\d).*/$1/g; + $slot = $slot * 1; # to get rid of the leading 0's. + } } print "ip: $ip\n"; print "host: $mm\n"; print "slot: $slot\n"; + # we now have slot and amm. Need to now get which blade this is: -my $nlscmd = "nodels mp.id==$slot".'@'."mp.mpa==$mm"; -my $node = `$nlscmd`; +my $nlscmd = "nodels mp.id==$slot" . '@' . "mp.mpa==$mm"; +my $node = `$nlscmd`; chomp($node); print "node: $node\n"; -if($node ne ''){ - system("logger -p local4.info -t xcat 'removing $node configuration from xCAT'"); - print FILE "removing $node configuration from xCAT\n"; - &rmblade($node); -}else{ - system("logger -p local4.info -t xcat 'a blade was removed from $mm:$slot but could not be identified'"); - print FILE "A blade was removed from $mm:$slot but could not be identified\n"; +if ($node ne '') { + system("logger -p local4.info -t xcat 'removing $node configuration from xCAT'"); + print FILE "removing $node configuration from xCAT\n"; + &rmblade($node); +} else { + system("logger -p local4.info -t xcat 'a blade was removed from $mm:$slot but could not be identified'"); + print FILE "A blade was removed from $mm:$slot but could not be identified\n"; } diff --git a/xCAT-server/share/xcat/tools/rmnodecfg b/xCAT-server/share/xcat/tools/rmnodecfg index 8850443bd..af1d3f0d3 100755 --- a/xCAT-server/share/xcat/tools/rmnodecfg +++ b/xCAT-server/share/xcat/tools/rmnodecfg @@ -1,5 +1,5 @@ #!/usr/bin/perl -# removes the configuration of a node so that the next time you reboot +# removes the configuration of a node so that the next time you reboot # a node it forces it to go through the discovery process. # usage: rmnodecfg # this does not remove it completely from xCAT. You may want to do this @@ -35,47 +35,48 @@ require xCAT::Utils; require xCAT::TableUtils; my $blades = shift; -if(! $blades) { - print "Please specify a noderange of blades to remove\n"; - exit; +if (!$blades) { + print "Please specify a noderange of blades to remove\n"; + exit; } my $tftpdir = xCAT::TableUtils->getTftpDir(); -foreach my $blade (`/opt/xcat/bin/nodels $blades`){ - chomp($blade); - my $hex = ip2hex($blade); - my $cmd = "nodech $blade chain.currstate= chain.currchain= chain.chain="; - $cmd = "chtab -d node=$blade chain"; - print "$cmd\n"; - `$cmd`; - $cmd = "chtab -d node=$blade mac"; - print "$cmd\n"; - `$cmd`; - $cmd = "makedhcp -d $blade"; - print "$cmd\n"; - `$cmd`; - $cmd = "rm $tftpdir/pxelinux.cfg/$blade"; - print "$cmd\n"; - `$cmd`; - if($hex){ - $cmd = "rm $tftpdir/pxelinux.cfg/$hex"; +foreach my $blade (`/opt/xcat/bin/nodels $blades`) { + chomp($blade); + my $hex = ip2hex($blade); + my $cmd = "nodech $blade chain.currstate= chain.currchain= chain.chain="; + $cmd = "chtab -d node=$blade chain"; print "$cmd\n"; - `$cmd`; - } + `$cmd`; + $cmd = "chtab -d node=$blade mac"; + print "$cmd\n"; + `$cmd`; + $cmd = "makedhcp -d $blade"; + print "$cmd\n"; + `$cmd`; + $cmd = "rm $tftpdir/pxelinux.cfg/$blade"; + print "$cmd\n"; + `$cmd`; + + if ($hex) { + $cmd = "rm $tftpdir/pxelinux.cfg/$hex"; + print "$cmd\n"; + `$cmd`; + } } sub ip2hex { - my $node = shift; - my $ip = ''; - my @quad; - my $hex = ''; - my $packed_ip = gethostbyname($node); - if(defined $packed_ip){ - $ip = inet_ntoa($packed_ip); - @quad = split('\.', $ip); - $hex = sprintf("%02X%02X%02X%02X", @quad); - } - return $hex; + my $node = shift; + my $ip = ''; + my @quad; + my $hex = ''; + my $packed_ip = gethostbyname($node); + if (defined $packed_ip) { + $ip = inet_ntoa($packed_ip); + @quad = split('\.', $ip); + $hex = sprintf("%02X%02X%02X%02X", @quad); + } + return $hex; } diff --git a/xCAT-server/share/xcat/tools/xCATreg b/xCAT-server/share/xcat/tools/xCATreg index d960576a7..92d610f5b 100755 --- a/xCAT-server/share/xcat/tools/xCATreg +++ b/xCAT-server/share/xcat/tools/xCATreg @@ -22,7 +22,7 @@ # ############################################################################################################################################# -$ENV{PATH} = "/opt/xcat/bin:/opt/xcat/sbin:/opt/xcat/share/xcat/tools:/usr/sbin:/usr/bin:/sbin:/bin"; +$ENV{PATH} = "/opt/xcat/bin:/opt/xcat/sbin:/opt/xcat/share/xcat/tools:/usr/sbin:/usr/bin:/sbin:/bin"; use strict; use warnings; @@ -39,38 +39,40 @@ BEGIN use lib "$::XCATROOT/lib/perl"; my $date; -my $regrootdir="/home/autotest_code"; -my $mailtitle="PPC64LE Cluster"; +my $regrootdir = "/home/autotest_code"; +my $mailtitle = "PPC64LE Cluster"; + #my $regrootdir="/xCATreg"; #my $mailtitle="X Cluster"; -my $logfiledir = "$regrootdir/log"; -my $logfile=""; -my $configfiledir = "$regrootdir/conf"; -my $configfile = "$regrootdir/conf/xCATreg.conf"; -my $xcatcoredowndir = "$regrootdir/xcatsource/xcat-core-build-down"; -my $xcatcoredir = "$regrootdir/xcatsource/xcat-core"; -my $xcatdepdir = "$regrootdir/xcatsource/xcat-dep"; -my $osisodir = "$regrootdir/iso"; -my $regresultdir = "$regrootdir/regresult"; -my $todayregresultdir=""; -my $maildir="$regrootdir/mail"; -my $mailfile=""; -my $rootdir = "$::XCATROOT/share/xcat/tools/autotest"; -my %confkeys; -my $mail_list = 0; -my $needhelp = 0; -my $branch = "master"; +my $logfiledir = "$regrootdir/log"; +my $logfile = ""; +my $configfiledir = "$regrootdir/conf"; +my $configfile = "$regrootdir/conf/xCATreg.conf"; +my $xcatcoredowndir = "$regrootdir/xcatsource/xcat-core-build-down"; +my $xcatcoredir = "$regrootdir/xcatsource/xcat-core"; +my $xcatdepdir = "$regrootdir/xcatsource/xcat-dep"; +my $osisodir = "$regrootdir/iso"; +my $regresultdir = "$regrootdir/regresult"; +my $todayregresultdir = ""; +my $maildir = "$regrootdir/mail"; +my $mailfile = ""; +my $rootdir = "$::XCATROOT/share/xcat/tools/autotest"; +my %confkeys; +my $mail_list = 0; +my $needhelp = 0; +my $branch = "master"; my $management_node = undef; + #my $verbose_mode = 0; my $updates_regression = 0; my %mns; my %pidrecord; my %piderrrecord; my %consumptionrecord; -my $commitinfofile="/tmp/commitinfo"; -my $gitupdateflag = 0; -my $forceregwithoutupdate=0; -my $depupdateflag = 0; +my $commitinfofile = "/tmp/commitinfo"; +my $gitupdateflag = 0; +my $forceregwithoutupdate = 0; +my $depupdateflag = 0; ####################################### # runcmd @@ -83,8 +85,8 @@ sub runcmd { @$outref = `$cmd 2>&1`; if ($?) { - $rc = $? ; - $::RUNCMD_RC = $rc; + $rc = $?; + $::RUNCMD_RC = $rc; } chomp(@$outref); return @$outref; @@ -93,27 +95,27 @@ sub runcmd { ####################################### # clean_outdated_file ####################################### -sub is5daysago{ - my $targetdate= shift; - my $targetdatey=""; - my $targetdatem=""; - my $targetdated=""; - my $datey=""; - my $datem=""; - my $dated=""; - if($targetdate =~ /(\d{4})(\d{2})(\d{2})/){ - $targetdatey=$1; - $targetdatem=$2-1; - $targetdated=$3; +sub is5daysago { + my $targetdate = shift; + my $targetdatey = ""; + my $targetdatem = ""; + my $targetdated = ""; + my $datey = ""; + my $datem = ""; + my $dated = ""; + if ($targetdate =~ /(\d{4})(\d{2})(\d{2})/) { + $targetdatey = $1; + $targetdatem = $2 - 1; + $targetdated = $3; } - if($date =~ /(\d{4})(\d{2})(\d{2})/){ - $datey=$1; - $datem=$2-1; - $dated=$3; + if ($date =~ /(\d{4})(\d{2})(\d{2})/) { + $datey = $1; + $datem = $2 - 1; + $dated = $3; } - my $todays=timelocal(0,0,0,$dated,$datem,$datey); - my $targets=timelocal(0,0,0,$targetdated,$targetdatem,$targetdatey); - if($todays - $targets > 432000){ + my $todays = timelocal(0, 0, 0, $dated, $datem, $datey); + my $targets = timelocal(0, 0, 0, $targetdated, $targetdatem, $targetdatey); + if ($todays - $targets > 432000) { return 1; } return 0; @@ -122,23 +124,23 @@ sub is5daysago{ ####################################### # clean_outdated_file ####################################### -sub clean_outdated_file{ +sub clean_outdated_file { opendir(DIR, "$logfiledir"); - foreach my $file (readdir DIR){ - if($file =~ /xCATreg(\d+).log/){ + foreach my $file (readdir DIR) { + if ($file =~ /xCATreg(\d+).log/) { my $res = is5daysago($1); - if($res){ + if ($res) { &runcmd("rm -f $logfiledir/$file"); } } } closedir(DIR); - + opendir(DIR, "$maildir"); - foreach my $file (readdir DIR){ - if($file =~ /mailreport.(\d+)/){ + foreach my $file (readdir DIR) { + if ($file =~ /mailreport.(\d+)/) { my $res = is5daysago($1); - if($res){ + if ($res) { &runcmd("rm -f $maildir/$file"); } } @@ -146,10 +148,10 @@ sub clean_outdated_file{ closedir(DIR); opendir(DIR, "$regresultdir"); - foreach my $file (readdir DIR){ - if($file =~ /(\d+)/){ + foreach my $file (readdir DIR) { + if ($file =~ /(\d+)/) { my $res = is5daysago($1); - if($res){ + if ($res) { &runcmd("rm -rf $regresultdir/$file"); } } @@ -162,40 +164,40 @@ sub clean_outdated_file{ ####################################### # xCATreg_init ####################################### -sub xCATreg_init{ +sub xCATreg_init { #init important attributes - - $date = `date +"%Y%m%d%H%M%S"`; + + $date = `date +"%Y%m%d%H%M%S"`; chomp($date); - &runcmd("mkdir -p $logfiledir") if(! -e $logfiledir); - &runcmd("mkdir -p $maildir") if(! -e $maildir); - &runcmd("mkdir -p $regresultdir") if(! -e $regresultdir); - &runcmd("mkdir -p $xcatcoredir") if(! -e $xcatcoredir); - - $logfile="xCATreg".$date.".log"; - $todayregresultdir=$regresultdir."/".$date; + &runcmd("mkdir -p $logfiledir") if (!-e $logfiledir); + &runcmd("mkdir -p $maildir") if (!-e $maildir); + &runcmd("mkdir -p $regresultdir") if (!-e $regresultdir); + &runcmd("mkdir -p $xcatcoredir") if (!-e $xcatcoredir); + + $logfile = "xCATreg" . $date . ".log"; + $todayregresultdir = $regresultdir . "/" . $date; &runcmd("mkdir -p $todayregresultdir"); - $mailfile=$maildir."/mailreport.".$date; - - my $cnt=`ps aux|grep xCATreg |grep -v grep|awk '{print \$2}'|wc -l`; - my $out=`ps aux|grep xCATreg |grep -v grep|awk '{print \$2}'`; - for(my $i=1;$i<$cnt+1;$i++){ - my $pid=`echo "$out"|sed -n ${i}p`; - chomp($pid); - next if($pid == $$); - &runcmd("kill $pid"); - } - - clean_outdated_file(); - return 0; + $mailfile = $maildir . "/mailreport." . $date; + + my $cnt = `ps aux|grep xCATreg |grep -v grep|awk '{print \$2}'|wc -l`; + my $out = `ps aux|grep xCATreg |grep -v grep|awk '{print \$2}'`; + for (my $i = 1 ; $i < $cnt + 1 ; $i++) { + my $pid = `echo "$out"|sed -n ${i}p`; + chomp($pid); + next if ($pid == $$); + &runcmd("kill $pid"); + } + + clean_outdated_file(); + return 0; } ####################################### # usage for arguments ####################################### -sub usage{ +sub usage { print "Usage:xCATreg - Run xcat autotest test cases.\n Explanation for the options: -b: when -b is specified, the regression will be done against the specified branch. The default value is master.\n @@ -219,15 +221,15 @@ sub send_msg { my $content; if ($num == 0) { $content = "Fatal error:"; - } elsif($num == 1) { + } elsif ($num == 1) { $content = "Warning:"; - } elsif($num == 2) { + } elsif ($num == 2) { $content = "Notice:"; } my $timestamp = `date +"%Y%m%d%H%M%S"`; chomp($timestamp); - if ( !open (LOGFILE, ">> $logfiledir/$logfile") ) { - return 1; + if (!open(LOGFILE, ">> $logfiledir/$logfile")) { + return 1; } print LOGFILE "$content $timestamp $$: $msg.\n"; close LOGFILE; @@ -237,161 +239,162 @@ sub send_msg { ####################################### # read_conf ####################################### -sub read_conf{ - my $myfile=undef; - my $line=undef; - - if (!open($myfile, "$configfile")) { +sub read_conf { + my $myfile = undef; + my $line = undef; + + if (!open($myfile, "$configfile")) { send_msg(0, "Open $configfile failed"); return 1; } while ($line = <$myfile>) { - $line =~ s/\s//g; - next if($line =~ /^#/); - next if($line eq ""); - my @attr=split(/=/,$line); - $confkeys{$attr[0]} = $attr[1]; - } - close($myfile); - return 0; + $line =~ s/\s//g; + next if ($line =~ /^#/); + next if ($line eq ""); + my @attr = split(/=/, $line); + $confkeys{ $attr[0] } = $attr[1]; + } + close($myfile); + return 0; } ####################################### # mn_install to install all mn ####################################### sub mn_install { - my $mn=shift; - - &runcmd("lsdef|grep $confkeys{$mn}"); - if($?){ - send_msg(0, "[$mn->$confkeys{$mn}][mn_install] Didn't defined $confkeys{$mn} in current control node"); - return 1; - } + my $mn = shift; - my $os = $confkeys{$mn."os"}; - my $arch = "ppc64"; - if($mn !~ /aix/ && $mn =~ /x/){ - $arch="x86_64"; - }elsif($mn !~ /aix/ && $mn =~ /LE/){ - $arch="ppc64le"; - } elsif($mn !~ /aix/ && $mn =~ /EL/){ - $arch="ppc64el"; - } - my $osimage=""; - - if($mn !~ /aix/){ - $osimage=$os."-".$arch."-install-compute"; - }else{ - $osimage="aix"; #????????need to test for aix - } + &runcmd("lsdef|grep $confkeys{$mn}"); + if ($?) { + send_msg(0, "[$mn->$confkeys{$mn}][mn_install] Didn't defined $confkeys{$mn} in current control node"); + return 1; + } - #print "[$mn] : os= $os arch=$arch osimage=$osimage\n"; - - &runcmd("lsdef -t osimage|grep $osimage"); - if($?){ - send_msg(0, "[$mn->$confkeys{$mn}][mn_install] Didn't defined $osimage in current control node"); - return 1; - } - - send_msg(2, "[$mn->$confkeys{$mn}][mn_install] installing $osimage for node $confkeys{$mn}................"); - - if( $arch =~ /x86_64/ || $arch =~ /ppc64le/ || $arch =~ /ppc64el/){ - &runcmd("rmvm $confkeys{$mn} -f -p "); - &runcmd("chdef $confkeys{$mn} mac= "); - &runcmd("mkvm $confkeys{$mn} -s 40G"); - } + my $os = $confkeys{ $mn . "os" }; + my $arch = "ppc64"; + if ($mn !~ /aix/ && $mn =~ /x/) { + $arch = "x86_64"; + } elsif ($mn !~ /aix/ && $mn =~ /LE/) { + $arch = "ppc64le"; + } elsif ($mn !~ /aix/ && $mn =~ /EL/) { + $arch = "ppc64el"; + } + my $osimage = ""; - &runcmd("makedhcp -n"); - &runcmd("makedns -n"); - &runcmd("chdef $confkeys{$mn} status="); - if($?){ - send_msg(0, "[$mn->$confkeys{$mn}][mn_install] Failed to change MN status in current control node"); - return 1; - } + if ($mn !~ /aix/) { + $osimage = $os . "-" . $arch . "-install-compute"; + } else { + $osimage = "aix"; #????????need to test for aix + } + + #print "[$mn] : os= $os arch=$arch osimage=$osimage\n"; + + &runcmd("lsdef -t osimage|grep $osimage"); + if ($?) { + send_msg(0, "[$mn->$confkeys{$mn}][mn_install] Didn't defined $osimage in current control node"); + return 1; + } + + send_msg(2, "[$mn->$confkeys{$mn}][mn_install] installing $osimage for node $confkeys{$mn}................"); + + if ($arch =~ /x86_64/ || $arch =~ /ppc64le/ || $arch =~ /ppc64el/) { + &runcmd("rmvm $confkeys{$mn} -f -p "); + &runcmd("chdef $confkeys{$mn} mac= "); + &runcmd("mkvm $confkeys{$mn} -s 40G"); + } + + &runcmd("makedhcp -n"); + &runcmd("makedns -n"); + &runcmd("chdef $confkeys{$mn} status="); + if ($?) { + send_msg(0, "[$mn->$confkeys{$mn}][mn_install] Failed to change MN status in current control node"); + return 1; + } - &runcmd("nodeset $confkeys{$mn} osimage=$osimage"); - if( $arch =~ /x86_64/ || $arch =~ /ppc64le/ || $arch =~ /ppc64el/){ - &runcmd("rpower $confkeys{$mn} boot"); - }else{ - &runcmd("rnetboot $confkeys{$mn}"); - } - - &runcmd("sleep 600"); - &runcmd("a=0;while ! `lsdef -l $confkeys{$mn}|grep status|grep booted >/dev/null`; do sleep 30;((a++));if [ \$a -gt 100 ];then break;fi done"); + &runcmd("nodeset $confkeys{$mn} osimage=$osimage"); + if ($arch =~ /x86_64/ || $arch =~ /ppc64le/ || $arch =~ /ppc64el/) { + &runcmd("rpower $confkeys{$mn} boot"); + } else { + &runcmd("rnetboot $confkeys{$mn}"); + } -# if($mn !~ /ubuntu/){ -# &runcmd("sleep 300"); -# &runcmd("a=0;while ! `lsdef -l $confkeys{$mn}|grep status|grep booted >/dev/null`; do sleep 10;((a++));if [ \$a -gt 200 ];then break;fi done");} -# else{ -# &runcmd("sleep 1800"); -# } - - &runcmd("lsdef -l $confkeys{$mn}|grep status|grep booted >/dev/null"); - if($?){ + &runcmd("sleep 600"); + &runcmd("a=0;while ! `lsdef -l $confkeys{$mn}|grep status|grep booted >/dev/null`; do sleep 30;((a++));if [ \$a -gt 100 ];then break;fi done"); + + # if($mn !~ /ubuntu/){ + # &runcmd("sleep 300"); + # &runcmd("a=0;while ! `lsdef -l $confkeys{$mn}|grep status|grep booted >/dev/null`; do sleep 10;((a++));if [ \$a -gt 200 ];then break;fi done");} + # else{ + # &runcmd("sleep 1800"); + # } + + &runcmd("lsdef -l $confkeys{$mn}|grep status|grep booted >/dev/null"); + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][mn_install] install $osimage for node $confkeys{$mn} failed"); return 1; - } - - if($mn =~ /ubuntu/){ - system("xdsh $confkeys{$mn} \"rm -rf /bin/sh\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"ln -s /bin/bash /bin/sh\""); - } -# if($mn =~ /ubuntu/){ -# system("updatenode $confkeys{$mn} -P \"confignics -s\" >/dev/null 2>&1"); -# system("xdsh $confkeys{$mn} \"iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE\" >/dev/null 2>&1"); -# system("xdsh $confkeys{$mn} \"iptables -A FORWARD -i eth1 -j ACCEPT\" >/dev/null 2>&1"); -# system("xdsh $confkeys{$mn} \"iptables -A FORWARD -i eth1 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT\" >/dev/null 2>&1"); -# } - if($os =~ /rhels7/){ - system("xdsh $confkeys{$mn} \"yum -y install bzip2 > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"yum -y install createrepo > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); - } + } + + if ($mn =~ /ubuntu/) { + system("xdsh $confkeys{$mn} \"rm -rf /bin/sh\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"ln -s /bin/bash /bin/sh\""); + } + + # if($mn =~ /ubuntu/){ + # system("updatenode $confkeys{$mn} -P \"confignics -s\" >/dev/null 2>&1"); + # system("xdsh $confkeys{$mn} \"iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE\" >/dev/null 2>&1"); + # system("xdsh $confkeys{$mn} \"iptables -A FORWARD -i eth1 -j ACCEPT\" >/dev/null 2>&1"); + # system("xdsh $confkeys{$mn} \"iptables -A FORWARD -i eth1 -o eth0 -m state --state RELATED,ESTABLISHED -j ACCEPT\" >/dev/null 2>&1"); + # } + if ($os =~ /rhels7/) { + system("xdsh $confkeys{$mn} \"yum -y install bzip2 > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"yum -y install createrepo > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); + } return 0; } ####################################### # down dep ####################################### -sub down_dep{ - my $mn=shift; +sub down_dep { + my $mn = shift; send_msg(2, "[$mn->$confkeys{$mn}][down xcatdep] starting to down the latest xcat dep"); - my $downxcatdepdir="$regrootdir/curl/$mn"; + my $downxcatdepdir = "$regrootdir/curl/$mn"; `mkdir -p $downxcatdepdir`; - my $curllink = $confkeys{$mn."curllink"}; + my $curllink = $confkeys{ $mn . "curllink" }; my $deplink; - if (! -f "$downxcatdepdir/curlhtml1"){ - send_msg(2, "it is first time to down xcatdep"); - ` curl "$curllink/" |grep "xcat-dep-" > "$downxcatdepdir/curlhtml1" `; - ` tail -1 "$downxcatdepdir/curlhtml1" > "$downxcatdepdir/curlfile"`; - $deplink = `cat "$downxcatdepdir"/"curlfile" |awk '{print \$6}' |sed 's/"/ /g' |awk '{print \$2}' `; - `mkdir -p $xcatdepdir/$mn`; - ` wget -P "$xcatdepdir/$mn" -c $curllink/$deplink `; - if($?){ - send_msg(0, "download xcatdep failed"); - return 1; - } - $depupdateflag=1; - }else{ - `curl "$curllink/" |grep "xcat-dep-" > "$downxcatdepdir/curlhtml2" `; - ` diff "$downxcatdepdir"/"curlhtml1" "$downxcatdepdir"/"curlhtml2"`; - if ($?==0) { - send_msg(2, "no update for xcatdep "); - $depupdateflag=0; - }else{ - ` tail -1 "$downxcatdepdir"/"curlhtml2"> "$downxcatdepdir"/"curlfile"`; - $deplink = `cat "$downxcatdepdir"/"curlfile" |awk '{print \$6}' |sed 's/"/ /g' |awk '{print \$2}' `; - ` rm -rf $xcatdepdir/$mn`; - `mkdir -p $xcatdepdir/$mn`; - ` wget -P "$xcatdepdir/$mn" -c $curllink/$deplink `; - if($?){ - send_msg(2, "download xcatdep failed"); - return 1; - } - `mv "$downxcatdepdir"/"curlhtml2" "$downxcatdepdir"/"curlhtml1" -f `; - $depupdateflag=2; - } - } + if (!-f "$downxcatdepdir/curlhtml1") { + send_msg(2, "it is first time to down xcatdep"); +` curl "$curllink/" |grep "xcat-dep-" > "$downxcatdepdir/curlhtml1" `; + ` tail -1 "$downxcatdepdir/curlhtml1" > "$downxcatdepdir/curlfile"`; + $deplink = `cat "$downxcatdepdir"/"curlfile" |awk '{print \$6}' |sed 's/"/ /g' |awk '{print \$2}' `; + `mkdir -p $xcatdepdir/$mn`; + ` wget -P "$xcatdepdir/$mn" -c $curllink/$deplink `; + if ($?) { + send_msg(0, "download xcatdep failed"); + return 1; + } + $depupdateflag = 1; + } else { + `curl "$curllink/" |grep "xcat-dep-" > "$downxcatdepdir/curlhtml2" `; + ` diff "$downxcatdepdir"/"curlhtml1" "$downxcatdepdir"/"curlhtml2"`; + if ($? == 0) { + send_msg(2, "no update for xcatdep "); + $depupdateflag = 0; + } else { +` tail -1 "$downxcatdepdir"/"curlhtml2"> "$downxcatdepdir"/"curlfile"`; + $deplink = `cat "$downxcatdepdir"/"curlfile" |awk '{print \$6}' |sed 's/"/ /g' |awk '{print \$2}' `; + ` rm -rf $xcatdepdir/$mn`; + `mkdir -p $xcatdepdir/$mn`; + ` wget -P "$xcatdepdir/$mn" -c $curllink/$deplink `; + if ($?) { + send_msg(2, "download xcatdep failed"); + return 1; + } +`mv "$downxcatdepdir"/"curlhtml2" "$downxcatdepdir"/"curlhtml1" -f `; + $depupdateflag = 2; + } + } return ($depupdateflag); } @@ -399,210 +402,215 @@ sub down_dep{ # down xcat-core build ########################################### sub down_xcat_core_build { - my $mn=shift; + my $mn = shift; send_msg(2, "[$mn->$confkeys{$mn}][down xcatcore] starting to down the latest xcat core"); - my $downxcatcoredowndir="$xcatcoredowndir/$mn"; - if (! -f "$xcatcoredowndir/$mn"){ - `mkdir -p $xcatcoredowndir/$mn`; + my $downxcatcoredowndir = "$xcatcoredowndir/$mn"; + if (!-f "$xcatcoredowndir/$mn") { + `mkdir -p $xcatcoredowndir/$mn`; } - my $downxcatcoreip = $confkeys{$mn."downxcatcoreip"}; - my $downxcatcoredir = $confkeys{$mn."downxcatcoredir"}; - my $latestxcatcoredir = `ssh $downxcatcoreip ls -rt $downxcatcoredir / |tail -1 |awk '{printf \$0}'`; - my $xcatcorename = $confkeys{$mn."xcatcorename"}; - `scp -r $downxcatcoreip\:$downxcatcoredir/$latestxcatcoredir/$xcatcorename $downxcatcoredowndir `; - if($? != 0){ - send_msg(0,"[$mn->$confkeys{$mn}][down_xcat_core_build] failed"); - return 1; + my $downxcatcoreip = $confkeys{ $mn . "downxcatcoreip" }; + my $downxcatcoredir = $confkeys{ $mn . "downxcatcoredir" }; + my $latestxcatcoredir = `ssh $downxcatcoreip ls -rt $downxcatcoredir / |tail -1 |awk '{printf \$0}'`; + my $xcatcorename = $confkeys{ $mn . "xcatcorename" }; +`scp -r $downxcatcoreip\:$downxcatcoredir/$latestxcatcoredir/$xcatcorename $downxcatcoredowndir `; + if ($? != 0) { + send_msg(0, "[$mn->$confkeys{$mn}][down_xcat_core_build] failed"); + return 1; } - } +} ####################################### # copy code ####################################### sub copy_code { - my $mn=shift; - + my $mn = shift; + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] starting to copy the latest xcat code and dep"); - my $dnsserver=`cat /etc/hosts |grep $confkeys{$mn}|awk '{print \$1}'|head -n 1`; + my $dnsserver = `cat /etc/hosts |grep $confkeys{$mn}|awk '{print \$1}'|head -n 1`; chomp($dnsserver); my $res = system("xdsh $confkeys{$mn} \"sed -i 's:nameserver .*:nameserver $dnsserver:g' /etc/resolv.conf\" >/dev/null 2>&1"); - if($res != 0){ + if ($res != 0) { send_msg(0, "[$mn->$confkeys{$mn}][install_xcat] modify resolv.conf in $mn failed"); return 1; - } + } - #copy xcat-dep tarball to MN:/ - my $depball=""; - if($mn =~ /aix/){ - $depball = `ls -l $xcatdepdir/$mn|awk '{print \$9}'|grep aix|tail -n 1`; - }elsif($mn =~ /ubuntu/){ - $depball = `ls -l $xcatdepdir/$mn|awk '{print \$9}'|grep ubuntu|tail -n 1`; - }else{ - $depball = `ls -l $xcatdepdir/$mn|awk '{print \$9}'|grep 'xcat-dep'|tail -n 1`; - } - chomp($depball); - print "depball is $depball\n"; - my $coreball = `ls -l $xcatcoredowndir/$mn|awk '{print \$9}'|tail -n 1`; - chomp($coreball); - if ($depball eq ""){ - send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find dep tarball for $mn under dir $xcatdepdir"); - return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find dep tarball $depball for $mn"); - if ($coreball eq ""){ - send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find core tarball for $mn under dir $coreball"); - return 1; - } + #copy xcat-dep tarball to MN:/ + my $depball = ""; + if ($mn =~ /aix/) { + $depball = `ls -l $xcatdepdir/$mn|awk '{print \$9}'|grep aix|tail -n 1`; + } elsif ($mn =~ /ubuntu/) { + $depball = `ls -l $xcatdepdir/$mn|awk '{print \$9}'|grep ubuntu|tail -n 1`; + } else { + $depball = `ls -l $xcatdepdir/$mn|awk '{print \$9}'|grep 'xcat-dep'|tail -n 1`; + } + chomp($depball); + print "depball is $depball\n"; + my $coreball = `ls -l $xcatcoredowndir/$mn|awk '{print \$9}'|tail -n 1`; + chomp($coreball); + if ($depball eq "") { + send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find dep tarball for $mn under dir $xcatdepdir"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find dep tarball $depball for $mn"); + if ($coreball eq "") { + send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find core tarball for $mn under dir $coreball"); + return 1; + } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find core tarball $coreball for $mn"); + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find core tarball $coreball for $mn"); $res = system("scp $xcatdepdir/$mn/$depball root\@$confkeys{$mn}:/ >/dev/null"); - if ($res){ + if ($res) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy $depball to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy $depball to $mn successfully"); - - $res = system("scp $xcatcoredowndir/$mn/$coreball root\@$confkeys{$mn}:/ >/dev/null"); - if ($res){ - send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy $coreball to $mn failed"); - return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy $coreball to $mn successfully"); - - $res = system("xdsh $confkeys{$mn} 'cd / && tar xvf /$depball' >/dev/null 2>&1"); - if ($?){ + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy $depball to $mn successfully"); + + $res = system("scp $xcatcoredowndir/$mn/$coreball root\@$confkeys{$mn}:/ >/dev/null"); + if ($res) { + send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy $coreball to $mn failed"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy $coreball to $mn successfully"); + + $res = system("xdsh $confkeys{$mn} 'cd / && tar xvf /$depball' >/dev/null 2>&1"); + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] untar $depball in $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] untar $depball in $mn successfully"); - $res = system("xdsh $confkeys{$mn} 'cd / && tar xvf /$coreball' >/dev/null 2>&1"); - if ($?){ + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] untar $depball in $mn successfully"); + $res = system("xdsh $confkeys{$mn} 'cd / && tar xvf /$coreball' >/dev/null 2>&1"); + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] untar $coreball in $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] untar $coreball in $mn successfully"); - + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] untar $coreball in $mn successfully"); + #copy xcat-core source code to MN:/ - if($mn =~ /ubuntux/){ + if ($mn =~ /ubuntux/) { + + #defect 107 Automation ENV replaces the link file to real file before running xcat build + $res = system("xdsh $confkeys{$mn} 'mkdir -p /xcatbuild' && rsync -avz $xcatcoredir root\@$confkeys{$mn}:/xcatbuild/ >/dev/null"); + } else { + #defect 107 Automation ENV replaces the link file to real file before running xcat build - $res = system("xdsh $confkeys{$mn} 'mkdir -p /xcatbuild' && rsync -avz $xcatcoredir root\@$confkeys{$mn}:/xcatbuild/ >/dev/null"); - }else{ - #defect 107 Automation ENV replaces the link file to real file before running xcat build $res = system("rsync -avz $xcatcoredir root\@$confkeys{$mn}:/ >/dev/null"); - } - if ($res){ + } + if ($res) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy the latest xcat code to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy the latest xcat code to $mn successfully"); + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy the latest xcat code to $mn successfully"); #copy /etc/hosts file to MN - $res = system("scp /etc/hosts root\@$confkeys{$mn}:/etc >/dev/null"); - if ($?){ + $res = system("scp /etc/hosts root\@$confkeys{$mn}:/etc >/dev/null"); + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy /etc/hosts to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy /etc/hosts to $mn successfully"); + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy /etc/hosts to $mn successfully"); - my $os = $confkeys{$mn."os"}; - my $regconf=$mn.".conf"; - system("sed -i 's|os=\\S*|os=$os|g' $configfiledir/$regconf"); - - my $arch = "ppc64"; - if($mn !~ /aix/ && $mn =~ /x/){ - $arch="x86_64"; - }elsif($mn !~ /aix/ && $mn =~ /LE/){ - $arch="ppc64le"; - }elsif($mn !~ /aix/ && $mn =~ /EL/){ - $arch="ppc64el"; - } - my $iso; - - #copy specific files to MN for each platform - if($mn =~ /rh/){ + my $os = $confkeys{ $mn . "os" }; + my $regconf = $mn . ".conf"; + system("sed -i 's|os=\\S*|os=$os|g' $configfiledir/$regconf"); + + my $arch = "ppc64"; + if ($mn !~ /aix/ && $mn =~ /x/) { + $arch = "x86_64"; + } elsif ($mn !~ /aix/ && $mn =~ /LE/) { + $arch = "ppc64le"; + } elsif ($mn !~ /aix/ && $mn =~ /EL/) { + $arch = "ppc64el"; + } + my $iso; + + #copy specific files to MN for each platform + if ($mn =~ /rh/) { $res = system("scp /install/$os/$arch/RPM-GPG-KEY-redhat-release root\@$confkeys{$mn}:/ >/dev/null"); - if ($?){ + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy RPM-GPG-KEY-redhat-release to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy RPM-GPG-KEY-redhat-release to $mn successfully"); - - $os =~ /(\D+)(\d+\.\d+)/; - $iso=`ls -l $osisodir|awk '{print \$9}'|grep RHEL`; - chomp($iso); - #print "[$mn->$confkeys{$mn}][copy_code] iso=$iso\n"; - if ($iso eq ""){ + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy RPM-GPG-KEY-redhat-release to $mn successfully"); + + $os =~ /(\D+)(\d+\.\d+)/; + $iso = `ls -l $osisodir|awk '{print \$9}'|grep RHEL`; + chomp($iso); + + #print "[$mn->$confkeys{$mn}][copy_code] iso=$iso\n"; + if ($iso eq "") { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find iso for $os and $arch under dir $osisodir"); return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find $iso for os=$os and arch=$arch"); + } + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find $iso for os=$os and arch=$arch"); $res = system("scp $osisodir/$iso root\@$confkeys{$mn}:/ >/dev/null"); - if ($?){ + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn successfully"); - system ("sed -i 's|^ISO=/\\S*|ISO=/$iso|g' $configfiledir/$regconf"); - } - - if($mn =~ /sles/){ + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn successfully"); + system("sed -i 's|^ISO=/\\S*|ISO=/$iso|g' $configfiledir/$regconf"); + } + + if ($mn =~ /sles/) { $os =~ /(\D+)(\d+)\.?(\d?)/; - if($3){ - $iso=`ls -l $osisodir| awk '{print \$9}'|grep SLE|grep $arch |grep -- "-$2-SP$3-" |tail -n 1`; - }else{ - $iso=`ls -l $osisodir| awk '{print \$9}'|grep SLE|grep $arch |grep -v "SP"|grep -- "-$2-"|tail -n 1`; + if ($3) { + $iso = `ls -l $osisodir| awk '{print \$9}'|grep SLE|grep $arch |grep -- "-$2-SP$3-" |tail -n 1`; + } else { + $iso = `ls -l $osisodir| awk '{print \$9}'|grep SLE|grep $arch |grep -v "SP"|grep -- "-$2-"|tail -n 1`; } chomp($iso); - #print "[$mn->$confkeys{$mn}][copy_code] iso=$iso\n"; - if ($iso eq ""){ + + #print "[$mn->$confkeys{$mn}][copy_code] iso=$iso\n"; + if ($iso eq "") { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find ISO for os=$os and arch=$arch under dir $osisodir"); return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find $iso for os=$os and arch=$arch"); - + } + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find $iso for os=$os and arch=$arch"); + $res = system("scp $osisodir/$iso root\@$confkeys{$mn}:/ >/dev/null"); - if ($?){ + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn successfully"); - system ("sed -i 's|^ISO=/\\S*|ISO=/$iso|g' $configfiledir/$regconf"); + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn successfully"); + system("sed -i 's|^ISO=/\\S*|ISO=/$iso|g' $configfiledir/$regconf"); - if($os =~ /sles11/){ + if ($os =~ /sles11/) { $res = system("xdsh $confkeys{$mn} \"mv /usr/lib/rpm/find-requires /usr/lib/rpm/find-requires.org\" && scp $osisodir/find-requires $confkeys{$mn}:/usr/lib/rpm/ > /dev/null"); - if ($?){ + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] For sles11, copy find-requires to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] For sles11, copy find-requires to $mn successfully"); - } - } - if($mn =~ /ubuntu/){ + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] For sles11, copy find-requires to $mn successfully"); + } + } + if ($mn =~ /ubuntu/) { $os =~ /(\D+)(\d+\.\d+\.?\d?)/; - my $osversion = $2; - if ($mn =~ /ubuntux/){ - $iso=`ls -l $osisodir| awk '{print \$9}'|grep ubuntu|grep amd64 |grep $osversion |tail -n 1`; - }elsif($mn =~ /ubuntuEL/){ - $iso=`ls -l $osisodir| awk '{print \$9}'|grep ubuntu|grep ppc64el |grep $osversion |tail -n 1`; - } - chomp($iso); - #print "[$mn->$confkeys{$mn}][copy_code] iso=$iso\n"; - if ($iso eq ""){ + my $osversion = $2; + if ($mn =~ /ubuntux/) { + $iso = `ls -l $osisodir| awk '{print \$9}'|grep ubuntu|grep amd64 |grep $osversion |tail -n 1`; + } elsif ($mn =~ /ubuntuEL/) { + $iso = `ls -l $osisodir| awk '{print \$9}'|grep ubuntu|grep ppc64el |grep $osversion |tail -n 1`; + } + chomp($iso); + + #print "[$mn->$confkeys{$mn}][copy_code] iso=$iso\n"; + if ($iso eq "") { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] can't find ISO for os=$os and arch=$arch under dir $osisodir"); return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find $iso for os=$os and arch=$arch"); - - $res = system("scp $osisodir/$iso root\@$confkeys{$mn}:/ >/dev/null"); - if ($?){ + } + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] find $iso for os=$os and arch=$arch"); + + $res = system("scp $osisodir/$iso root\@$confkeys{$mn}:/ >/dev/null"); + if ($?) { send_msg(0, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn failed"); return 1; } - send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn successfully"); - system ("sed -i 's|^ISO=/\\S*|ISO=/$iso|g' $configfiledir/$regconf"); - } + send_msg(2, "[$mn->$confkeys{$mn}][copy_code] copy ISO $iso to $mn successfully"); + system("sed -i 's|^ISO=/\\S*|ISO=/$iso|g' $configfiledir/$regconf"); + } return 0; } @@ -611,92 +619,93 @@ sub copy_code { ####################################### sub install_xcat { my $mn = shift; - send_msg(2, "[$mn->$confkeys{$mn}][install_xcat] starting to install xcat in $confkeys{$mn}"); - - my $os = $confkeys{$mn."os"}; - my $arch = "ppc64"; - if($mn !~ /aix/ && $mn =~ /x/){ - $arch="x86_64"; - }elsif($mn !~ /aix/ && $mn =~ /LE/){ - $arch="ppc64le"; - }elsif($mn !~ /aix/ && $mn =~ /EL/){ - $arch="ppc64el"; + send_msg(2, "[$mn->$confkeys{$mn}][install_xcat] starting to install xcat in $confkeys{$mn}"); + + my $os = $confkeys{ $mn . "os" }; + my $arch = "ppc64"; + if ($mn !~ /aix/ && $mn =~ /x/) { + $arch = "x86_64"; + } elsif ($mn !~ /aix/ && $mn =~ /LE/) { + $arch = "ppc64le"; + } elsif ($mn !~ /aix/ && $mn =~ /EL/) { + $arch = "ppc64el"; + } + if ($mn =~ /ubuntu/) { + system("xdsh $confkeys{$mn} \"echo \"nameserver 9.0.2.1\" >> /etc/resolv.conf\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'apt-get -y install software-properties-common' >/dev/null 2>&1"); + if ($mn =~ /ubuntux/) { + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc) main\"' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc)-updates main\"' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc) universe\"' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc)-updates universe\"' >/dev/null 2>&1"); + } elsif ($mn =~ /ubuntuEL/) { + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc) main\"' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc)-updates main\"' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc) universe\"' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc)-updates universe\"' >/dev/null 2>&1"); } - if($mn =~ /ubuntu/){ - system("xdsh $confkeys{$mn} \"echo \"nameserver 9.0.2.1\" >> /etc/resolv.conf\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'apt-get -y install software-properties-common' >/dev/null 2>&1"); - if($mn =~ /ubuntux/){ - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc) main\"' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc)-updates main\"' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc) universe\"' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://archive.ubuntu.com/ubuntu \$(lsb_release -sc)-updates universe\"' >/dev/null 2>&1"); - }elsif($mn =~ /ubuntuEL/){ - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc) main\"' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc)-updates main\"' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc) universe\"' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'add-apt-repository \"deb http://ports.ubuntu.com/ubuntu-ports \$(lsb_release -sc)-updates universe\"' >/dev/null 2>&1"); - } - system("xdsh $confkeys{$mn} \"wget -O - \"http://sourceforge.net/projects/xcat/files/ubuntu/apt.key/download\" | apt-key add -\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'apt-get clean all' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'apt-get update' >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} 'apt-get -y install build-essential dpkg-dev dh-make debhelper fakeroot gnupg lintian pbuilder quilt reprepro libsoap-lite-perl libdbi-perl' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"wget -O - \"http://sourceforge.net/projects/xcat/files/ubuntu/apt.key/download\" | apt-key add -\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'apt-get clean all' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'apt-get update' >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} 'apt-get -y install build-essential dpkg-dev dh-make debhelper fakeroot gnupg lintian pbuilder quilt reprepro libsoap-lite-perl libdbi-perl' >/dev/null 2>&1"); } - - if($mn =~ /rh/){ - $os =~ /(\D+)(\d+)\.?(\d?)/; - system("xdsh $confkeys{$mn} \"cd /xcat-core && ./mklocalrepo.sh\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"cd /xcat-dep/rh$2/$arch && ./mklocalrepo.sh\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"rpm --import /RPM-GPG-KEY-redhat-release\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"yum -y install xCAT xCAT-test > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); - if($os =~ /rhels7/){ - system("xdsh $confkeys{$mn} \"yum -y install mariadb-devel mariadb-libs mariadb-server mariadb-bench mariadb perl-DBD-MySQL mysql-connector-odbc unixODBC\" >/dev/null 2>&1"); - }elsif($os =~ /rhels6/){ - system("xdsh $confkeys{$mn} \"yum -y install mysql-server mysql mysql-bench mysql-devel mysql-connector-odbc\" >/dev/null 2>&1"); - } - system("xdsh $confkeys{$mn} \"source /etc/profile.d/xcat.sh\" >/dev/null 2>&1"); - if($mn =~ /rhx/){ - system("xdsh $confkeys{$mn} \"yum install -y perl-Sys-Virt\" >/dev/null 2>&1"); - } - }elsif($mn =~ /sles/){ - $os =~ /(\D+)(\d+)\.?(\d?)/; - system("xdsh $confkeys{$mn} \"zypper ar file:///xcat-dep/sles$2/$arch xCAT-dep\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"zypper ar file:///xcat-core xCAT-core\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"zypper sl -U\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"zypper --gpg-auto-import-keys search --match-exact -s screen\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"zypper -n install xCAT xCAT-test > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"zypper -n install createrepo\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"zypper -n install mysql-client libmysqlclient_r15 libqt4-sql-mysql libmysqlclient15 perl-DBD-mysql mysql unixODBC\" >/dev/null 2>&1"); - system("xdsh $confkeys{$mn} \"source /etc/profile.d/xcat.sh\" >/dev/null 2>&1"); - if($mn =~ /slesLE/){ - system ("xdsh $confkeys{$mn} \"zypper -n install perl-Net-DNS-0.80-1.ppc64le\">/dev/null 2>&1"); - } - if($mn =~ /slesx/){ - system("xdsh $confkeys{$mn} \"zypper -n install perl-Sys-Virt\" >/dev/null 2>&1"); - } - }elsif($mn =~ /ubuntux/){ + + if ($mn =~ /rh/) { + $os =~ /(\D+)(\d+)\.?(\d?)/; + system("xdsh $confkeys{$mn} \"cd /xcat-core && ./mklocalrepo.sh\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"cd /xcat-dep/rh$2/$arch && ./mklocalrepo.sh\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"rpm --import /RPM-GPG-KEY-redhat-release\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"yum -y install xCAT xCAT-test > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); + if ($os =~ /rhels7/) { + system("xdsh $confkeys{$mn} \"yum -y install mariadb-devel mariadb-libs mariadb-server mariadb-bench mariadb perl-DBD-MySQL mysql-connector-odbc unixODBC\" >/dev/null 2>&1"); + } elsif ($os =~ /rhels6/) { + system("xdsh $confkeys{$mn} \"yum -y install mysql-server mysql mysql-bench mysql-devel mysql-connector-odbc\" >/dev/null 2>&1"); + } + system("xdsh $confkeys{$mn} \"source /etc/profile.d/xcat.sh\" >/dev/null 2>&1"); + if ($mn =~ /rhx/) { + system("xdsh $confkeys{$mn} \"yum install -y perl-Sys-Virt\" >/dev/null 2>&1"); + } + } elsif ($mn =~ /sles/) { + $os =~ /(\D+)(\d+)\.?(\d?)/; + system("xdsh $confkeys{$mn} \"zypper ar file:///xcat-dep/sles$2/$arch xCAT-dep\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"zypper ar file:///xcat-core xCAT-core\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"zypper sl -U\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"zypper --gpg-auto-import-keys search --match-exact -s screen\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"zypper -n install xCAT xCAT-test > /var/log/xcat/install_xcat.log 2>&1\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"zypper -n install createrepo\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"zypper -n install mysql-client libmysqlclient_r15 libqt4-sql-mysql libmysqlclient15 perl-DBD-mysql mysql unixODBC\" >/dev/null 2>&1"); + system("xdsh $confkeys{$mn} \"source /etc/profile.d/xcat.sh\" >/dev/null 2>&1"); + + if ($mn =~ /slesLE/) { + system("xdsh $confkeys{$mn} \"zypper -n install perl-Net-DNS-0.80-1.ppc64le\">/dev/null 2>&1"); + } + if ($mn =~ /slesx/) { + system("xdsh $confkeys{$mn} \"zypper -n install perl-Sys-Virt\" >/dev/null 2>&1"); + } + } elsif ($mn =~ /ubuntux/) { system("xdsh $confkeys{$mn} \"/xcat-core/mklocalrepo.sh\" >/dev/null 2>&1"); system("xdsh $confkeys{$mn} \"/xcat-dep/mklocalrepo.sh\" >/dev/null 2>&1"); system("xdsh $confkeys{$mn} 'apt-get clean all' >/dev/null 2>&1"); system("xdsh $confkeys{$mn} 'apt-get update' >/dev/null 2>&1"); system("xdsh $confkeys{$mn} 'apt-get -y install xcat xCAT-test > /var/log/xcat/install_xcat.log 2>&1' >/dev/null 2>&1"); - }elsif($mn =~ /ubuntuEL/){ + } elsif ($mn =~ /ubuntuEL/) { system("xdsh $confkeys{$mn} \"/xcat-core/mklocalrepo.sh\" >/dev/null 2>&1"); system("xdsh $confkeys{$mn} \"/xcat-dep/mklocalrepo.sh\" >/dev/null 2>&1"); system("xdsh $confkeys{$mn} 'apt-get clean all' >/dev/null 2>&1"); system("xdsh $confkeys{$mn} 'apt-get update' >/dev/null 2>&1"); system("xdsh $confkeys{$mn} 'apt-get -y install xcat xCAT-test > /var/log/xcat/install_xcat.log 2>&1' >/dev/null 2>&1"); - system("scp $osisodir/mini.iso $confkeys{$mn}:/ "); - } - - #check if MN is installed successful - my $lsdefout = `xdsh $confkeys{$mn} '/opt/xcat/bin/lsdef -v'`; - chomp($lsdefout); - if($lsdefout !~ /lsdef - Version/ ){ - send_msg(0, "[$mn->$confkeys{$mn}][install_xcat] install xcat in $mn failed"); - return 1; + system("scp $osisodir/mini.iso $confkeys{$mn}:/ "); } - + + #check if MN is installed successful + my $lsdefout = `xdsh $confkeys{$mn} '/opt/xcat/bin/lsdef -v'`; + chomp($lsdefout); + if ($lsdefout !~ /lsdef - Version/) { + send_msg(0, "[$mn->$confkeys{$mn}][install_xcat] install xcat in $mn failed"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][install_xcat] install xcat in $mn successfully"); return 0; } @@ -705,220 +714,222 @@ sub install_xcat { # do test ####################################### sub do_test { - my $mn = shift; - my $os = $confkeys{$mn."os"}; - my $casestop=1; + my $mn = shift; + my $os = $confkeys{ $mn . "os" }; + my $casestop = 1; - send_msg(2, "[$mn->$confkeys{$mn}][do_test] starting to run regression test in $confkeys{$mn}"); - - my $regconf=$mn.".conf"; - my $res = system("scp $configfiledir/$regconf root\@$confkeys{$mn}:/opt/xcat/share/xcat/tools/autotest/default.conf >/dev/null"); - if ($res != 0){ - send_msg(0, "[$mn->$confkeys{$mn}][do_test] copy $configfiledir/$regconf to $mn failed"); - return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][do_test] copy $configfiledir/$regconf to $mn successfully"); - if($os =~ /rhels7/){ - system("scp /opt/xcat/share/xcat/install/rh/service.rhels7.ppc64.otherpkgs.pkglist root\@$confkeys{$mn}:/opt/xcat/share/xcat/install/rh >/dev/null"); - } - my $diskfull_installation_flat_testcase=""; - my $diskless_installation_flat_testcase=""; - my $statelite_installation_flat_testcase=""; - my $sn_installation_hierarchy_testcase=""; - my $diskfull_installation_hierarchy_testcase=""; - my $diskless_installation_hierarchy_testcase=""; - my $statelite_installation_hierarchy_by_ramdisk_testcase=""; - my $statelite_installation_hierarchy_by_nfs_testcase=""; - my $setup_dockerhost_testcase=""; - my $batbundle=""; - if((($mn =~ /sles/) || ($mn =~ /rh/)) && ($mn !~ /E/)){ - $diskfull_installation_flat_testcase="reg_linux_diskfull_installation_flat"; - $diskless_installation_flat_testcase="reg_linux_diskless_installation_flat"; - $statelite_installation_flat_testcase="reg_linux_statelite_installation_flat"; - $sn_installation_hierarchy_testcase="reg_linux_SN_installation_hierarchy"; - $diskfull_installation_hierarchy_testcase="reg_linux_diskfull_installation_hierarchy"; - $diskless_installation_hierarchy_testcase="reg_linux_diskless_installation_hierarchy"; - $statelite_installation_hierarchy_by_ramdisk_testcase="reg_linux_statelite_installation_hierarchy_by_ramdisk"; - $statelite_installation_hierarchy_by_nfs_testcase="reg_linux_statelite_installation_hierarchy_by_nfs"; - $batbundle="p_rhels_cmd.bundle" if($mn =~ /rhp/); - $batbundle="x_rhels_cmd.bundle" if($mn =~ /rhx/); - $batbundle="p_sles_cmd.bundle" if($mn =~ /slesp/); - $batbundle="x_sles_cmd.bundle" if($mn =~ /slesx/); - }elsif($mn =~ /ubuntux/){ - $diskfull_installation_flat_testcase="Ubuntu_full_installation_flat_x86_vm"; - $diskless_installation_flat_testcase="Ubuntu_diskless_installation_flat_x86_vm"; - $setup_dockerhost_testcase="Full_installation_flat_docker"; - $batbundle="x_ubuntu_cmd.bundle"; - }elsif($mn =~ /E/){ - $diskfull_installation_flat_testcase="Full_installation_flat_p8_le"; - $diskless_installation_flat_testcase="Diskless_installation_flat_p8_le"; - $batbundle="le_rhels_cmd.bundle" if($mn =~ /rhLE/); - $batbundle="le_sles_cmd.bundle" if($mn =~ /slesLE/); - $batbundle="le_ubuntu_cmd.bundle" if($mn =~ /ubuntuEL/); - } - if(($mn !~ /ubuntu/) && ($mn !~ /E/)){ - { - my $rc; + send_msg(2, "[$mn->$confkeys{$mn}][do_test] starting to run regression test in $confkeys{$mn}"); - #diskfull installation in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskfull installation test in flat mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskfull_installation_flat_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskfull installation test in flat mode in $mn.....[done]"); - last if($rc != 0); + my $regconf = $mn . ".conf"; + my $res = system("scp $configfiledir/$regconf root\@$confkeys{$mn}:/opt/xcat/share/xcat/tools/autotest/default.conf >/dev/null"); + if ($res != 0) { + send_msg(0, "[$mn->$confkeys{$mn}][do_test] copy $configfiledir/$regconf to $mn failed"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][do_test] copy $configfiledir/$regconf to $mn successfully"); + if ($os =~ /rhels7/) { + system("scp /opt/xcat/share/xcat/install/rh/service.rhels7.ppc64.otherpkgs.pkglist root\@$confkeys{$mn}:/opt/xcat/share/xcat/install/rh >/dev/null"); + } + my $diskfull_installation_flat_testcase = ""; + my $diskless_installation_flat_testcase = ""; + my $statelite_installation_flat_testcase = ""; + my $sn_installation_hierarchy_testcase = ""; + my $diskfull_installation_hierarchy_testcase = ""; + my $diskless_installation_hierarchy_testcase = ""; + my $statelite_installation_hierarchy_by_ramdisk_testcase = ""; + my $statelite_installation_hierarchy_by_nfs_testcase = ""; + my $setup_dockerhost_testcase = ""; + my $batbundle = ""; - #commands bundle in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing all commands test in flat mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -b $batbundle\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do all commands test in flat mode in $mn.....[done]"); - last if($rc != 0); - - #diskless installation in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskless installation test in flat mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskless_installation_flat_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskless installation test in flat mode in $mn.....[done]"); - last if($rc != 0); - - #statelite installation in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing statelite installation test in flat mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $statelite_installation_flat_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do statelite installation test in flat mode in $mn.....[done]"); - last if($rc != 0); - - #deploy SN - send_msg(2, "[$mn->$confkeys{$mn}][do_test] setting up mysql for installing SN in $mn....."); - $res = system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"XCATMYSQLADMIN_PW=12345 XCATMYSQLROOT_PW=12345 /opt/xcat/bin/mysqlsetup -i\"' >/dev/null 2>&1"); - if ($res != 0){ - send_msg(0, "[$mn->$confkeys{$mn}][do_test] set up mysql for installing SN in $mn failed"); - return 1; - } - $res = system ("xdsh $confkeys{$mn} \"echo \\\"GRANT ALL on xcatdb.* TO xcatadmin@\'%\' IDENTIFIED BY \'12345\'\;\\\" | mysql -u root -p12345\" >/dev/null 2>&1"); - if ($res != 0){ - send_msg(0, "[$mn->$confkeys{$mn}][do_test] grant right to mysql for installing SN in $mn failed"); - return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][do_test] set up mysql for installing SN in $mn.....[done]"); - - send_msg(2, "[$mn->$confkeys{$mn}][do_test] preparing xcat ball for installing SN in $mn....."); - my $os = $confkeys{$mn."os"}; - my $arch = "ppc64"; - if(($mn !~ /aix/) && ($mn =~ /x/)){ - $arch="x86_64"; - }elsif($mn !~ /aix/ && $mn =~ /LE/){ - $arch="ppc64le"; - }elsif($mn !~ /aix/ && $mn =~ /EL/){ - $arch="ppc64el"; - } - my $xcatballpath = "/install/post/otherpkgs/$os/$arch/xcat"; - $res = system("xdsh $confkeys{$mn} \"mkdir -p $xcatballpath/xcat-core && cp -r /xcat-core/* $xcatballpath/xcat-core && cp -r /xcat-dep $xcatballpath\""); - if ($res != 0){ - send_msg(0, "[$mn->$confkeys{$mn}][do_test] prepare xcat ball for installing SN in $mn failed"); - return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][do_test] prepare xcat ball for installing SN in $mn.....[done]"); - - if($mn =~ /rhp/){ - my $ping_sn_on_rhp_pid = fork(); - if( !defined($ping_sn_on_rhp_pid)){ - send_msg(0, "fork process for trigger random number generator on redhat+ppc environment to install SN error"); - exit; - }elsif($ping_sn_on_rhp_pid ==0){ - send_msg(2, "....fork 1 process[pid=$$] for trigger random number generator on redhat+ppc environment to install SN.........."); - my $snnodename = `cat $configfiledir/$regconf |grep SN|grep =|awk -F'=' '{print \$2}'`; - chomp($snnodename); - &runcmd("sleep 900"); - my $timecnt=0; - while($timecnt < 180){ - my $booted = system("xdsh $confkeys{$mn} \"lsdef -l $snnodename|grep status|grep booted\""); - last if($booted==0); - - my $booting = system("xdsh $confkeys{$mn} \"lsdef -l $snnodename|grep status|grep booting\""); - system("xdsh $confkeys{$mn} \"xdsh $snnodename \"echo 1\"\"") if($booting==0); - - &runcmd("sleep 10"); - $timecnt++; - } - send_msg(2, "....process[pid=$$] for trigger random number generator on redhat+ppc environment to install SN....[exit]"); - exit 0; - } - } - - send_msg(2, "[$mn->$confkeys{$mn}][do_test] installing SN....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $sn_installation_hierarchy_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] install SN.....[done]"); - last if($rc != 0); - - #diskfull installation in hierarchy mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskfull installation test in hierarchy mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskfull_installation_hierarchy_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskfull installation test in hierarchy mode in $mn.....[done]"); - last if($rc != 0); - - #diskless installation in hierarchy mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskless installation test in hierarchy mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskless_installation_hierarchy_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskless installation test in hierarchy mode in $mn.....[done]"); - last if($rc != 0); - - #statelite installation by ramdisk in hierarchy mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing statelite installation by ramdisk test in hierarchy mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $statelite_installation_hierarchy_by_ramdisk_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do statelite installation by ramdisk test in hierarchy mode in $mn.....[done]"); - last if($rc != 0); - - #statelite installation by nfs in hierarchy mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing statelite installation by nfs test in hierarchy mode in $mn....."); - $rc=system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $statelite_installation_hierarchy_by_nfs_testcase\" >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do statelite installation by nfs test in hierarchy mode in $mn.....[done]"); - last if($rc != 0); - - $casestop=0; - } - }else{ + if ((($mn =~ /sles/) || ($mn =~ /rh/)) && ($mn !~ /E/)) { + $diskfull_installation_flat_testcase = "reg_linux_diskfull_installation_flat"; + $diskless_installation_flat_testcase = "reg_linux_diskless_installation_flat"; + $statelite_installation_flat_testcase = "reg_linux_statelite_installation_flat"; + $sn_installation_hierarchy_testcase = "reg_linux_SN_installation_hierarchy"; + $diskfull_installation_hierarchy_testcase = "reg_linux_diskfull_installation_hierarchy"; + $diskless_installation_hierarchy_testcase = "reg_linux_diskless_installation_hierarchy"; + $statelite_installation_hierarchy_by_ramdisk_testcase = "reg_linux_statelite_installation_hierarchy_by_ramdisk"; + $statelite_installation_hierarchy_by_nfs_testcase = "reg_linux_statelite_installation_hierarchy_by_nfs"; + $batbundle = "p_rhels_cmd.bundle" if ($mn =~ /rhp/); + $batbundle = "x_rhels_cmd.bundle" if ($mn =~ /rhx/); + $batbundle = "p_sles_cmd.bundle" if ($mn =~ /slesp/); + $batbundle = "x_sles_cmd.bundle" if ($mn =~ /slesx/); + } elsif ($mn =~ /ubuntux/) { + $diskfull_installation_flat_testcase = "Ubuntu_full_installation_flat_x86_vm"; + $diskless_installation_flat_testcase = "Ubuntu_diskless_installation_flat_x86_vm"; + $setup_dockerhost_testcase = "Full_installation_flat_docker"; + $batbundle = "x_ubuntu_cmd.bundle"; + } elsif ($mn =~ /E/) { + $diskfull_installation_flat_testcase = "Full_installation_flat_p8_le"; + $diskless_installation_flat_testcase = "Diskless_installation_flat_p8_le"; + $batbundle = "le_rhels_cmd.bundle" if ($mn =~ /rhLE/); + $batbundle = "le_sles_cmd.bundle" if ($mn =~ /slesLE/); + $batbundle = "le_ubuntu_cmd.bundle" if ($mn =~ /ubuntuEL/); + } + if (($mn !~ /ubuntu/) && ($mn !~ /E/)) { { - my $rc=0; + my $rc; - #diskless installation in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskless installation test in flat mode in $mn....."); - $rc=system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskless_installation_flat_testcase\"' >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskless installation test in flat mode in $mn.....[done]"); - last if($rc != 0); + #diskfull installation in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskfull installation test in flat mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskfull_installation_flat_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskfull installation test in flat mode in $mn.....[done]"); + last if ($rc != 0); - #diskfull installation in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskfull installation test in flat mode in $mn....."); - $rc=system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskfull_installation_flat_testcase\"' >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskfull installation test in flat mode in $mn.....[done]"); - last if($rc != 0); - - if($mn =~ /ubuntux/){ - #set up dockerhosts - send_msg(2, "[$mn->$confkeys{$mn}][do_test] setupdockerhost $mn....."); - $rc=system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $setup_dockerhost_testcase\"' >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] setup dockerhosts $mn.....[done]"); - last if($rc != 0); + #commands bundle in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing all commands test in flat mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -b $batbundle\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do all commands test in flat mode in $mn.....[done]"); + last if ($rc != 0); + + #diskless installation in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskless installation test in flat mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskless_installation_flat_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskless installation test in flat mode in $mn.....[done]"); + last if ($rc != 0); + + #statelite installation in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing statelite installation test in flat mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $statelite_installation_flat_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do statelite installation test in flat mode in $mn.....[done]"); + last if ($rc != 0); + + #deploy SN + send_msg(2, "[$mn->$confkeys{$mn}][do_test] setting up mysql for installing SN in $mn....."); + $res = system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"XCATMYSQLADMIN_PW=12345 XCATMYSQLROOT_PW=12345 /opt/xcat/bin/mysqlsetup -i\"' >/dev/null 2>&1"); + if ($res != 0) { + send_msg(0, "[$mn->$confkeys{$mn}][do_test] set up mysql for installing SN in $mn failed"); + return 1; + } + $res = system("xdsh $confkeys{$mn} \"echo \\\"GRANT ALL on xcatdb.* TO xcatadmin@\'%\' IDENTIFIED BY \'12345\'\;\\\" | mysql -u root -p12345\" >/dev/null 2>&1"); + if ($res != 0) { + send_msg(0, "[$mn->$confkeys{$mn}][do_test] grant right to mysql for installing SN in $mn failed"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][do_test] set up mysql for installing SN in $mn.....[done]"); + + send_msg(2, "[$mn->$confkeys{$mn}][do_test] preparing xcat ball for installing SN in $mn....."); + my $os = $confkeys{ $mn . "os" }; + my $arch = "ppc64"; + if (($mn !~ /aix/) && ($mn =~ /x/)) { + $arch = "x86_64"; + } elsif ($mn !~ /aix/ && $mn =~ /LE/) { + $arch = "ppc64le"; + } elsif ($mn !~ /aix/ && $mn =~ /EL/) { + $arch = "ppc64el"; + } + my $xcatballpath = "/install/post/otherpkgs/$os/$arch/xcat"; + $res = system("xdsh $confkeys{$mn} \"mkdir -p $xcatballpath/xcat-core && cp -r /xcat-core/* $xcatballpath/xcat-core && cp -r /xcat-dep $xcatballpath\""); + if ($res != 0) { + send_msg(0, "[$mn->$confkeys{$mn}][do_test] prepare xcat ball for installing SN in $mn failed"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][do_test] prepare xcat ball for installing SN in $mn.....[done]"); + + if ($mn =~ /rhp/) { + my $ping_sn_on_rhp_pid = fork(); + if (!defined($ping_sn_on_rhp_pid)) { + send_msg(0, "fork process for trigger random number generator on redhat+ppc environment to install SN error"); + exit; + } elsif ($ping_sn_on_rhp_pid == 0) { + send_msg(2, "....fork 1 process[pid=$$] for trigger random number generator on redhat+ppc environment to install SN.........."); + my $snnodename = `cat $configfiledir/$regconf |grep SN|grep =|awk -F'=' '{print \$2}'`; + chomp($snnodename); + &runcmd("sleep 900"); + my $timecnt = 0; + while ($timecnt < 180) { + my $booted = system("xdsh $confkeys{$mn} \"lsdef -l $snnodename|grep status|grep booted\""); + last if ($booted == 0); + + my $booting = system("xdsh $confkeys{$mn} \"lsdef -l $snnodename|grep status|grep booting\""); + system("xdsh $confkeys{$mn} \"xdsh $snnodename \"echo 1\"\"") if ($booting == 0); + + &runcmd("sleep 10"); + $timecnt++; } - - #commands bundle in flat mode test - send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing all commands test in flat mode in $mn....."); - $rc=system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -b $batbundle\"' >/dev/null 2>&1"); - send_msg(2, "[$mn->$confkeys{$mn}][do_test] do all commands test in flat mode in $mn.....[done]"); - $casestop=0; - } + send_msg(2, "....process[pid=$$] for trigger random number generator on redhat+ppc environment to install SN....[exit]"); + exit 0; + } + } + + send_msg(2, "[$mn->$confkeys{$mn}][do_test] installing SN....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $sn_installation_hierarchy_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] install SN.....[done]"); + last if ($rc != 0); + + #diskfull installation in hierarchy mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskfull installation test in hierarchy mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskfull_installation_hierarchy_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskfull installation test in hierarchy mode in $mn.....[done]"); + last if ($rc != 0); + + #diskless installation in hierarchy mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskless installation test in hierarchy mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskless_installation_hierarchy_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskless installation test in hierarchy mode in $mn.....[done]"); + last if ($rc != 0); + + #statelite installation by ramdisk in hierarchy mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing statelite installation by ramdisk test in hierarchy mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $statelite_installation_hierarchy_by_ramdisk_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do statelite installation by ramdisk test in hierarchy mode in $mn.....[done]"); + last if ($rc != 0); + + #statelite installation by nfs in hierarchy mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing statelite installation by nfs test in hierarchy mode in $mn....."); + $rc = system("xdsh $confkeys{$mn} \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $statelite_installation_hierarchy_by_nfs_testcase\" >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do statelite installation by nfs test in hierarchy mode in $mn.....[done]"); + last if ($rc != 0); + + $casestop = 0; + } + } else { + { + my $rc = 0; + + #diskless installation in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskless installation test in flat mode in $mn....."); + $rc = system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskless_installation_flat_testcase\"' >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskless installation test in flat mode in $mn.....[done]"); + last if ($rc != 0); + + #diskfull installation in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing diskfull installation test in flat mode in $mn....."); + $rc = system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $diskfull_installation_flat_testcase\"' >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do diskfull installation test in flat mode in $mn.....[done]"); + last if ($rc != 0); + + if ($mn =~ /ubuntux/) { + + #set up dockerhosts + send_msg(2, "[$mn->$confkeys{$mn}][do_test] setupdockerhost $mn....."); + $rc = system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -t $setup_dockerhost_testcase\"' >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] setup dockerhosts $mn.....[done]"); + last if ($rc != 0); + } + + #commands bundle in flat mode test + send_msg(2, "[$mn->$confkeys{$mn}][do_test] doing all commands test in flat mode in $mn....."); + $rc = system("ssh -t $confkeys{$mn} 'exec bash -l -i -c \"xcattest -f /opt/xcat/share/xcat/tools/autotest/default.conf -b $batbundle\"' >/dev/null 2>&1"); + send_msg(2, "[$mn->$confkeys{$mn}][do_test] do all commands test in flat mode in $mn.....[done]"); + $casestop = 0; + } } - if($casestop){ + if ($casestop) { send_msg(2, "[$mn->$confkeys{$mn}][do_test] the regression job in $mn was broken by one case."); - }else{ + } else { send_msg(2, "[$mn->$confkeys{$mn}][do_test] run the whole regression test in $mn finished"); } - + send_msg(2, "[$mn->$confkeys{$mn}][install_xcat] run regression test in $mn finished"); - - $res = system("scp -r $confkeys{$mn}:/opt/xcat/share/xcat/tools/autotest/result/* $todayregresultdir/$mn/ >/dev/null 2>&1"); - if ($res != 0){ - send_msg(0, "[$mn->$confkeys{$mn}][do_test] copy regression result to $todayregresultdir/$mn/ failed"); - return 1; - } - send_msg(2, "[$mn->$confkeys{$mn}][do_test] copy regression result to $todayregresultdir/$mn/ successfully"); + + $res = system("scp -r $confkeys{$mn}:/opt/xcat/share/xcat/tools/autotest/result/* $todayregresultdir/$mn/ >/dev/null 2>&1"); + if ($res != 0) { + send_msg(0, "[$mn->$confkeys{$mn}][do_test] copy regression result to $todayregresultdir/$mn/ failed"); + return 1; + } + send_msg(2, "[$mn->$confkeys{$mn}][do_test] copy regression result to $todayregresultdir/$mn/ successfully"); return 0; @@ -927,224 +938,227 @@ sub do_test { ####################################### # creat report ####################################### -sub creat_report{ +sub creat_report { my $mailreport .= "======================================\n"; - $mailreport .= " Regression Result Summary\n"; - $mailreport .= "======================================\n\n"; - # $gitupdateflag = 0 git update out of time - # $gitupdateflag = 1 there isn't new code checkin in last one day - # $gitupdateflag = 2 git update failed - if($gitupdateflag==0){ - $mailreport .= "Get the latest xcat code from git out of time, stop regression test today!!!\n\n\n"; - &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); - &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); - return 0; - }elsif($gitupdateflag==1 && ! $forceregwithoutupdate){ - $mailreport .= "There isn't new code checkin last one day, stop regression test today!!!\n\n\n"; - &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); - &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); - return 0; - }elsif($gitupdateflag==1 && $forceregwithoutupdate){ - $mailreport .= "There isn't new code checkin last one day, But force to run regresson today!!!\n\n\n"; - &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); - }elsif($gitupdateflag==2){ - $mailreport .= "Get the latest xcat source code from git error, stop regression test today!!!\n\n\n"; - &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); - &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); - return 0; - } - - while(my($k,$v) = each %pidrecord){ - my $scenario="[".$confkeys{$k."os"}; - if($k=~/p/){ - $scenario.="+PPC64] "; - }elsif($k=~ /E/){ - $scenario.="+PPC64LE] "; - }elsif($k=~/x/){ - $scenario.="+x86_64] "; - } - $mailreport .= "$scenario\n"; - my $batbundle=""; - my $totalcase=0; + $mailreport .= " Regression Result Summary\n"; + $mailreport .= "======================================\n\n"; - if($k=~ /slesp/ || $k =~ /rhx/ || $k=~ /slesx/ || $k =~ /rhp/){ - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/p_rhels_cmd.bundle" if($k =~ /rhp/); - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/x_rhels_cmd.bundle" if($k =~ /rhx/); - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/p_sles_cmd.bundle" if($k =~ /slesp/); - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/x_sles_cmd.bundle" if($k =~ /slesx/); - $totalcase=`cat $batbundle|wc -l`; - $totalcase+=8; - }elsif($k =~ /ubuntux/){ - $batbundle="/$xcatcoredir/xCAT-test/autotest/bundle/x_ubuntu_cmd.bundle"; - $totalcase=`cat $batbundle|wc -l`; - $totalcase+=3; - }elsif($k =~ /E/){ - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/le_rhels_cmd.bundle" if($k =~ /rhLE/); - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/le_sles_cmd.bundle" if($k =~ /slesLE/); - $batbundle="$xcatcoredir/xCAT-test/autotest/bundle/le_ubuntu_cmd.bundle" if($k =~ /ubuntuEL/); - $totalcase=`cat $batbundle|wc -l`; - $totalcase+=2; - } - - - if ($v == 0){ # whole regression test finished - my $h=int($consumptionrecord{$k}/3600); - my $m=int(($consumptionrecord{$k} - $h*3600)/60); - my $s=($consumptionrecord{$k} - $h*3600)%60; - my $consumption="$h hours $m minutes $s seconds"; - $mailreport .= "\tTime consumption: $consumption\n"; - - if($piderrrecord{$k} ne ""){ - $mailreport .= "\tDeploy MN result: $piderrrecord{$k}\n"; - $mailreport .= "\tTotalCase $totalcase TotalRun 0 Failed 0\n"; - next; - } - - my $totalcnt=0; - my $failcnt=0; - my $faillist=""; - opendir(DIR, "$todayregresultdir/$k"); - foreach my $file (readdir DIR) - { - next if($file !~ /xcattest.log/); - my $cnt = `cat $todayregresultdir/$k/$file |grep -- "------END::"|wc -l`; - $totalcnt+=int($cnt); - for(my $i=1;$i<$cnt+1;$i++){ - my $line=`cat $todayregresultdir/$k/$file |grep -- "------END::"|sed -n ${i}p`; - chomp($line); - if($line =~ /------END::([a-zA-Z0-9_-]+)::([a-zA-Z0-9_-]+)::Time.+/){ - my $failedcase=$1; - if($2 =~ /Failed/){ - $failcnt++; - $faillist.=$failedcase.", "; - } - } - } - } - - closedir(DIR); - - my $lastfile = `ls -lrt $todayregresultdir/$k|grep "xcattest.log"|tail -1|awk '{print \$9}'`; - chomp($lastfile); - my $lastline=`cat $todayregresultdir/$k/$lastfile |grep -- "------END::"|tail -1`; - chomp($lastline); - my $lastcase; - $lastcase=$1 if($lastline =~ /------END::([a-zA-Z0-9_-]+)::([a-zA-Z0-9_-]+)::Time.+/); - - $mailreport .= "\tTotalCase $totalcase TotalRun $totalcnt Failed $failcnt\n\tFailed cases: $faillist\n\tFinal environment stop at $lastcase\n"; - }else{ # regression test out of time - $mailreport .= "\tTime consumption: Out of 9 hours!!!!!!\n"; - } + # $gitupdateflag = 0 git update out of time + # $gitupdateflag = 1 there isn't new code checkin in last one day + # $gitupdateflag = 2 git update failed + if ($gitupdateflag == 0) { + $mailreport .= "Get the latest xcat code from git out of time, stop regression test today!!!\n\n\n"; + &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); + &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); + return 0; + } elsif ($gitupdateflag == 1 && !$forceregwithoutupdate) { + $mailreport .= "There isn't new code checkin last one day, stop regression test today!!!\n\n\n"; + &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); + &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); + return 0; + } elsif ($gitupdateflag == 1 && $forceregwithoutupdate) { + $mailreport .= "There isn't new code checkin last one day, But force to run regresson today!!!\n\n\n"; + &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); + } elsif ($gitupdateflag == 2) { + $mailreport .= "Get the latest xcat source code from git error, stop regression test today!!!\n\n\n"; + &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); + &runcmd("mv $commitinfofile $commitinfofile.old && echo \"\" > $commitinfofile"); + return 0; } - - &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); + + while (my ($k, $v) = each %pidrecord) { + my $scenario = "[" . $confkeys{ $k . "os" }; + if ($k =~ /p/) { + $scenario .= "+PPC64] "; + } elsif ($k =~ /E/) { + $scenario .= "+PPC64LE] "; + } elsif ($k =~ /x/) { + $scenario .= "+x86_64] "; + } + $mailreport .= "$scenario\n"; + my $batbundle = ""; + my $totalcase = 0; + + if ($k =~ /slesp/ || $k =~ /rhx/ || $k =~ /slesx/ || $k =~ /rhp/) { + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/p_rhels_cmd.bundle" if ($k =~ /rhp/); + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/x_rhels_cmd.bundle" if ($k =~ /rhx/); + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/p_sles_cmd.bundle" if ($k =~ /slesp/); + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/x_sles_cmd.bundle" if ($k =~ /slesx/); + $totalcase = `cat $batbundle|wc -l`; + $totalcase += 8; + } elsif ($k =~ /ubuntux/) { + $batbundle = "/$xcatcoredir/xCAT-test/autotest/bundle/x_ubuntu_cmd.bundle"; + $totalcase = `cat $batbundle|wc -l`; + $totalcase += 3; + } elsif ($k =~ /E/) { + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/le_rhels_cmd.bundle" if ($k =~ /rhLE/); + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/le_sles_cmd.bundle" if ($k =~ /slesLE/); + $batbundle = "$xcatcoredir/xCAT-test/autotest/bundle/le_ubuntu_cmd.bundle" if ($k =~ /ubuntuEL/); + $totalcase = `cat $batbundle|wc -l`; + $totalcase += 2; + } + + + if ($v == 0) { # whole regression test finished + my $h = int($consumptionrecord{$k} / 3600); + my $m = int(($consumptionrecord{$k} - $h * 3600) / 60); + my $s = ($consumptionrecord{$k} - $h * 3600) % 60; + my $consumption = "$h hours $m minutes $s seconds"; + $mailreport .= "\tTime consumption: $consumption\n"; + + if ($piderrrecord{$k} ne "") { + $mailreport .= "\tDeploy MN result: $piderrrecord{$k}\n"; + $mailreport .= "\tTotalCase $totalcase TotalRun 0 Failed 0\n"; + next; + } + + my $totalcnt = 0; + my $failcnt = 0; + my $faillist = ""; + opendir(DIR, "$todayregresultdir/$k"); + foreach my $file (readdir DIR) + { + next if ($file !~ /xcattest.log/); + my $cnt = `cat $todayregresultdir/$k/$file |grep -- "------END::"|wc -l`; + $totalcnt += int($cnt); + for (my $i = 1 ; $i < $cnt + 1 ; $i++) { + my $line = `cat $todayregresultdir/$k/$file |grep -- "------END::"|sed -n ${i}p`; + chomp($line); + if ($line =~ /------END::([a-zA-Z0-9_-]+)::([a-zA-Z0-9_-]+)::Time.+/) { + my $failedcase = $1; + if ($2 =~ /Failed/) { + $failcnt++; + $faillist .= $failedcase . ", "; + } + } + } + } + + closedir(DIR); + + my $lastfile = `ls -lrt $todayregresultdir/$k|grep "xcattest.log"|tail -1|awk '{print \$9}'`; + chomp($lastfile); + my $lastline = `cat $todayregresultdir/$k/$lastfile |grep -- "------END::"|tail -1`; + chomp($lastline); + my $lastcase; + $lastcase = $1 if ($lastline =~ /------END::([a-zA-Z0-9_-]+)::([a-zA-Z0-9_-]+)::Time.+/); + + $mailreport .= "\tTotalCase $totalcase TotalRun $totalcnt Failed $failcnt\n\tFailed cases: $faillist\n\tFinal environment stop at $lastcase\n"; + } else { # regression test out of time + $mailreport .= "\tTime consumption: Out of 9 hours!!!!!!\n"; + } + } + + &runcmd("touch $mailfile && echo \"$mailreport\" > $mailfile"); return 0; } ####################################### # send email ####################################### -sub send_email{ - my $checkinlist=""; - my $cnt =`cat $commitinfofile |grep '20[0-9][0-9] [-+]0[0-9]00'|awk '{print \$1}' |grep -v root|sort | uniq|wc -l`; - my $out =`cat $commitinfofile |grep '20[0-9][0-9] [-+]0[0-9]00'|awk '{print \$1}' |grep -v root|sort | uniq`; - for(my $i=1;$i<$cnt+1;$i++){ - my $tmpline=`echo "$out"|sed -n ${i}p`; - chomp($tmpline); - $checkinlist.= "$tmpline "; - } - - my $totalcnt=0; - my $failcnt=0; - my $totalcase=0; -$cnt =`cat $mailfile |grep "Total"|grep "Failed"|wc -l`; - $out =`cat $mailfile |grep "Total"|grep "Failed"`; - for(my $i=1;$i<$cnt+1;$i++){ - my $tmpline=`echo "$out"|sed -n ${i}p`; - chomp($tmpline); - if($tmpline =~ /TotalCase (\d+) TotalRun (\d+) Failed (\d+)/){ - $totalcase+=$1; - $totalcnt+=$2; - $failcnt+=$3; - } - } - - # $gitupdateflag = 0 git update out of time - # $gitupdateflag = 1 there isn't new code checkin in last one day - # $gitupdateflag = 2 git update failed - $depupdateflag = `cat $logfiledir/$logfile |grep "updated for xcat dep" `; - my $subject=""; - if($gitupdateflag==0 || $gitupdateflag==2){ - $subject = "[$mailtitle] Git update failed, stop regression test today!!!"; - }elsif($gitupdateflag==1 && ! $forceregwithoutupdate){ - $subject = "[$mailtitle] No code checkin, stop regression test today!!!"; - }elsif($gitupdateflag==1 && $forceregwithoutupdate){ - `cat $logfiledir/$logfile |grep "updated for xcat dep" `; - if($?==0){ - $subject = "[$mailtitle] TotalCase:".$totalcase.", TotalRun:".$totalcnt.", Fail:".$failcnt.", Branch:".$branch.", xcatdep updated, Checkin: NO ONE !!"; - }else{ - $subject = "[$mailtitle] TotalCase:".$totalcase.", TotalRun:".$totalcnt.", Fail:".$failcnt.", Branch:".$branch.", xcatdep no updated, Checkin: NO ONE !!"; - } - }else{ - `cat $logfiledir/$logfile |grep "updated for xcat dep" `; - if($?==0){ - $subject = "[$mailtitle] TotalCase:".$totalcase.", TotalRun:".$totalcnt.", Fail:".$failcnt.", Branch:".$branch.", xcatdep updated, Checkin: ".$checkinlist; - }else{ - $subject = "[$mailtitle] TotalCase:".$totalcase.", TotalRun:".$totalcnt.", Fail:".$failcnt.", Branch:".$branch.", xcatdep no updated, Checkin: ".$checkinlist; - } - } +sub send_email { + my $checkinlist = ""; + my $cnt = `cat $commitinfofile |grep '20[0-9][0-9] [-+]0[0-9]00'|awk '{print \$1}' |grep -v root|sort | uniq|wc -l`; + my $out = `cat $commitinfofile |grep '20[0-9][0-9] [-+]0[0-9]00'|awk '{print \$1}' |grep -v root|sort | uniq`; + for (my $i = 1 ; $i < $cnt + 1 ; $i++) { + my $tmpline = `echo "$out"|sed -n ${i}p`; + chomp($tmpline); + $checkinlist .= "$tmpline "; + } + + my $totalcnt = 0; + my $failcnt = 0; + my $totalcase = 0; + $cnt = `cat $mailfile |grep "Total"|grep "Failed"|wc -l`; + $out = `cat $mailfile |grep "Total"|grep "Failed"`; + for (my $i = 1 ; $i < $cnt + 1 ; $i++) { + my $tmpline = `echo "$out"|sed -n ${i}p`; + chomp($tmpline); + if ($tmpline =~ /TotalCase (\d+) TotalRun (\d+) Failed (\d+)/) { + $totalcase += $1; + $totalcnt += $2; + $failcnt += $3; + } + } + + # $gitupdateflag = 0 git update out of time + # $gitupdateflag = 1 there isn't new code checkin in last one day + # $gitupdateflag = 2 git update failed + $depupdateflag = `cat $logfiledir/$logfile |grep "updated for xcat dep" `; + my $subject = ""; + if ($gitupdateflag == 0 || $gitupdateflag == 2) { + $subject = "[$mailtitle] Git update failed, stop regression test today!!!"; + } elsif ($gitupdateflag == 1 && !$forceregwithoutupdate) { + $subject = "[$mailtitle] No code checkin, stop regression test today!!!"; + } elsif ($gitupdateflag == 1 && $forceregwithoutupdate) { + `cat $logfiledir/$logfile |grep "updated for xcat dep" `; + if ($? == 0) { + $subject = "[$mailtitle] TotalCase:" . $totalcase . ", TotalRun:" . $totalcnt . ", Fail:" . $failcnt . ", Branch:" . $branch . ", xcatdep updated, Checkin: NO ONE !!"; + } else { + $subject = "[$mailtitle] TotalCase:" . $totalcase . ", TotalRun:" . $totalcnt . ", Fail:" . $failcnt . ", Branch:" . $branch . ", xcatdep no updated, Checkin: NO ONE !!"; + } + } else { + `cat $logfiledir/$logfile |grep "updated for xcat dep" `; + if ($? == 0) { + $subject = "[$mailtitle] TotalCase:" . $totalcase . ", TotalRun:" . $totalcnt . ", Fail:" . $failcnt . ", Branch:" . $branch . ", xcatdep updated, Checkin: " . $checkinlist; + } else { + $subject = "[$mailtitle] TotalCase:" . $totalcase . ", TotalRun:" . $totalcnt . ", Fail:" . $failcnt . ", Branch:" . $branch . ", xcatdep no updated, Checkin: " . $checkinlist; + } + } my $mailreport .= "\n\n======================================\n"; - $mailreport .= " Commit Codes Last Day\n"; - $mailreport .= "======================================\n\n"; - - &runcmd("echo \"$mailreport\">> $mailfile"); - &runcmd("cat $commitinfofile >> $mailfile"); - - my $attachfile="/tmp/failed_case_detail.txt"; - &runcmd("echo \"\" > $attachfile"); - if($failcnt > 0){ + $mailreport .= " Commit Codes Last Day\n"; + $mailreport .= "======================================\n\n"; + + &runcmd("echo \"$mailreport\">> $mailfile"); + &runcmd("cat $commitinfofile >> $mailfile"); + + my $attachfile = "/tmp/failed_case_detail.txt"; + &runcmd("echo \"\" > $attachfile"); + if ($failcnt > 0) { opendir(DIR, "$todayregresultdir"); - foreach my $subdir (readdir DIR){ - next if($subdir =~ /^\./); + foreach my $subdir (readdir DIR) { + next if ($subdir =~ /^\./); + #print "subdir-> $subdir\n"; - - my $scenario="[".$confkeys{$subdir."os"}; - if($subdir =~ /p/){ - $scenario.="+PPC64] "; - }elsif($subdir =~ /x/){ - $scenario.="+x86_64] "; - }elsif($subdir =~ /E/){ - $scenario.="+ppc64le] "; - } + + my $scenario = "[" . $confkeys{ $subdir . "os" }; + if ($subdir =~ /p/) { + $scenario .= "+PPC64] "; + } elsif ($subdir =~ /x/) { + $scenario .= "+x86_64] "; + } elsif ($subdir =~ /E/) { + $scenario .= "+ppc64le] "; + } my $separator .= "\n###############################################################\n"; $separator .= " $scenario\n"; $separator .= "###############################################################\n\n"; - &runcmd("echo \"$separator\" >> $attachfile"); + &runcmd("echo \"$separator\" >> $attachfile"); opendir(SUBDIR, "$todayregresultdir/$subdir"); - foreach my $file (readdir SUBDIR){ - next if($file !~ /^failedcases/); - next if(-z "$todayregresultdir/$subdir/$file"); + foreach my $file (readdir SUBDIR) { + next if ($file !~ /^failedcases/); + next if (-z "$todayregresultdir/$subdir/$file"); + #print "\t$file\n"; system("cat $todayregresultdir/$subdir/$file >> $attachfile"); } } - } - - if($mail_list){ - if($failcnt > 0){ - system("cat $mailfile"." | /bin/mail -s \"$subject\" -a $attachfile \"$mail_list\""); - }else{ - system("cat $mailfile"." | /bin/mail -s \"$subject\" \"$mail_list\""); - } - }else{ - if($failcnt > 0){ - system("cat $mailfile"." | /bin/mail -s \"$subject\" -a $attachfile \"$confkeys{mailgroup}\""); - }else{ - system("cat $mailfile"." | /bin/mail -s \"$subject\" \"$confkeys{mailgroup}\""); - } - } + } + + if ($mail_list) { + if ($failcnt > 0) { + system("cat $mailfile" . " | /bin/mail -s \"$subject\" -a $attachfile \"$mail_list\""); + } else { + system("cat $mailfile" . " | /bin/mail -s \"$subject\" \"$mail_list\""); + } + } else { + if ($failcnt > 0) { + system("cat $mailfile" . " | /bin/mail -s \"$subject\" -a $attachfile \"$confkeys{mailgroup}\""); + } else { + system("cat $mailfile" . " | /bin/mail -s \"$subject\" \"$confkeys{mailgroup}\""); + } + } return 0; } @@ -1156,72 +1170,73 @@ $cnt =`cat $mailfile |grep "Total"|grep "Failed"|wc -l`; #1 code is already at latest version #2 someting error ####################################### -sub git_update{ - send_msg(2, "[git update] starting to update xcat source code from git"); - +sub git_update { + send_msg(2, "[git update] starting to update xcat source code from git"); + my $res = system("cd $xcatcoredir && git checkout $branch > /dev/nul 2>&1"); - if ($res != 0){ + if ($res != 0) { send_msg(0, "[git update] change to branch $branch....[failed]"); return 2; } send_msg(2, "[git update] change to branch $branch....[ok]"); - - my $gitpulloutput = "/tmp/gitpulloutput"; - my $trytime=1; - while($trytime < 4){ + + my $gitpulloutput = "/tmp/gitpulloutput"; + my $trytime = 1; + while ($trytime < 4) { $res = system("cd $xcatcoredir && git pull > $gitpulloutput 2>&1"); - if ($res != 0){ + if ($res != 0) { send_msg(0, "[git update] pull the latest code to control node....[$trytime failed]"); - $trytime++; - &runcmd("sleep 120"); - }else{ - last; - } - } - - if($trytime == 4){ + $trytime++; + &runcmd("sleep 120"); + } else { + last; + } + } + + if ($trytime == 4) { send_msg(0, "[git update] pull the latest code to control node....[finally failed]"); - return 2; - } - + return 2; + } + $res = system("grep 'Already up-to-date' $gitpulloutput > /dev/nul 2>&1"); - if ($res == 0 && ! $forceregwithoutupdate) { + if ($res == 0 && !$forceregwithoutupdate) { send_msg(2, "[git update] code is already at latest version. exit regresson"); return 1; - }elsif($res == 0 && $forceregwithoutupdate){ + } elsif ($res == 0 && $forceregwithoutupdate) { send_msg(2, "[git update] code is already at latest version. But force to run regresson"); return 0; - } - send_msg(2, "[git update] pull the latest code to control node....[ok]"); - - my $lastcommitfile="/tmp/lastcommitfile"; - my $lastcommitinfo; - if (-f $lastcommitfile){ + } + send_msg(2, "[git update] pull the latest code to control node....[ok]"); + + my $lastcommitfile = "/tmp/lastcommitfile"; + my $lastcommitinfo; + if (-f $lastcommitfile) { $lastcommitinfo = `cat $lastcommitfile`; - chomp($lastcommitinfo); - }else{ - $lastcommitinfo = ""; - } - #print "lastcommitinfo=$lastcommitinfo\n"; - - if($lastcommitinfo eq ""){ + chomp($lastcommitinfo); + } else { + $lastcommitinfo = ""; + } + + #print "lastcommitinfo=$lastcommitinfo\n"; + + if ($lastcommitinfo eq "") { $res = system("cd $xcatcoredir && git log --since=\"1 days ago\" --pretty=format:\"%cn %ad %s\" --name-status > $commitinfofile"); - if ($res != 0 || (-f $commitinfofile and -z _)){ + if ($res != 0 || (-f $commitinfofile and -z _)) { send_msg(0, "[git update] get commit information....[failed]"); return 2; } send_msg(0, "[git update] get commit information....[ok]"); - }else{ + } else { $res = system("cd $xcatcoredir && git log $lastcommitinfo..HEAD --pretty=format:\"%cn %ad %s\" --name-status > $commitinfofile"); - if ($res != 0 || (-f $commitinfofile and -z _)){ + if ($res != 0 || (-f $commitinfofile and -z _)) { send_msg(0, "[git update] get commit information....[failed]"); return 2; } send_msg(2, "[git update] get commit information....[ok]"); - } - - $res = system("cd $xcatcoredir && git log -n 1|awk 'NR==1'|awk '{print \$2}' > $lastcommitfile"); - if ($res != 0){ + } + + $res = system("cd $xcatcoredir && git log -n 1|awk 'NR==1'|awk '{print \$2}' > $lastcommitfile"); + if ($res != 0) { send_msg(0, "[git update] get latest commit number failed"); exit; } @@ -1233,6 +1248,7 @@ sub git_update{ # step 0. Parse input arguments ####################################### send_msg(2, "step 1, Parse input arguments............"); + =pod if ( !GetOptions("--help|h|?" => \$needhelp, @@ -1244,14 +1260,15 @@ if ( "e=s" => \$send_msg) ) =cut + if ( !GetOptions("--help|h|?" => \$needhelp, - "f=s" => \$configfile, - "b=s" => \$branch, - "m=s" => \$management_node, - "a" => \$forceregwithoutupdate, - "e=s" => \$mail_list) -) + "f=s" => \$configfile, + "b=s" => \$branch, + "m=s" => \$management_node, + "a" => \$forceregwithoutupdate, + "e=s" => \$mail_list) + ) { &usage; send_msg(0, "step 0, PARSE ARGUMENTS returns error, exit"); @@ -1269,28 +1286,28 @@ xCATreg_init(); ############################################################### # Mainfunction ############################################################### -send_msg(2,"........................"); -send_msg(2,"........................"); -send_msg(2,".....ooooO.............."); -send_msg(2,"....(....)....Ooooo....."); -send_msg(2,".....\\..(.....(....)...."); -send_msg(2,"......\\__).....)../....."); -send_msg(2,"..............(_ /......"); -send_msg(2,"........................"); -send_msg(2,".........START ........."); -send_msg(2,"........................"); +send_msg(2, "........................"); +send_msg(2, "........................"); +send_msg(2, ".....ooooO.............."); +send_msg(2, "....(....)....Ooooo....."); +send_msg(2, ".....\\..(.....(....)...."); +send_msg(2, "......\\__).....)../....."); +send_msg(2, "..............(_ /......"); +send_msg(2, "........................"); +send_msg(2, ".........START ........."); +send_msg(2, "........................"); ####################################### # step 1. Read configuration files ####################################### send_msg(2, "step 2, Reading xCATreg conf............"); my $rst = read_conf(); -unless (! $rst) { +unless (!$rst) { send_msg(0, "read xCATreg configuration failed...........exit"); exit; } foreach my $k (keys %confkeys) { -print "$k = $confkeys{$k}\n"; + print "$k = $confkeys{$k}\n"; } # begin to find which mn should be used @@ -1311,174 +1328,176 @@ if ($management_node) { } } -pipe PREAD,CWRITE; +pipe PREAD, CWRITE; my $gitpid = fork(); -if( !defined($gitpid)){ +if (!defined($gitpid)) { send_msg(0, "fork process for git update error"); exit; -}elsif($gitpid ==0){ +} elsif ($gitpid == 0) { close PREAD; send_msg(2, "..........fork 1 process[pid=$$] for git update.........."); my $res = git_update(); - if($res > 1){ - send_msg(0, "git_update......[failed]"); - syswrite CWRITE,"git update failed\n"; - close CWRITE; + if ($res > 1) { + send_msg(0, "git_update......[failed]"); + syswrite CWRITE, "git update failed\n"; + close CWRITE; exit 1; } - if($res == 1){ - send_msg(2, "git_update......[not find new code]"); - syswrite CWRITE,"git update got nothing\n"; - close CWRITE; + if ($res == 1) { + send_msg(2, "git_update......[not find new code]"); + syswrite CWRITE, "git update got nothing\n"; + close CWRITE; exit 1; - } - send_msg(2, "git_update......[ok]"); - syswrite CWRITE,"git update successful\n"; + } + send_msg(2, "git_update......[ok]"); + syswrite CWRITE, "git update successful\n"; close CWRITE; - exit 0; + exit 0; } -{#main process +{ #main process close CWRITE; my $gitstarttime = time(); - my $gitprocess=1; - my $gitselect = new IO::Select; - $gitselect->add(\*PREAD); - while($gitprocess){ + my $gitprocess = 1; + my $gitselect = new IO::Select; + $gitselect->add(\*PREAD); + while ($gitprocess) { my @hdls; - if (@hdls = $gitselect->can_read(0)) { - my $hdl; - foreach $hdl (@hdls) { - if ($hdl == \*PREAD) { - my $line; - chomp($line=); - if ($line){ - if($line =~ /successful/){ - send_msg(2, "[[main]]: $line"); - $gitupdateflag=3; - } - if($line =~ /failed/){ - send_msg(0, "[[main]]: $line"); - $gitupdateflag=2; - } - if($line =~ /nothing/){ - send_msg(2, "[[main]]: there isn't new code checkin during last one day."); - $gitupdateflag=1; - } - $gitprocess = 0; - } - } - } - } + if (@hdls = $gitselect->can_read(0)) { + my $hdl; + foreach $hdl (@hdls) { + if ($hdl == \*PREAD) { + my $line; + chomp($line = ); + if ($line) { + if ($line =~ /successful/) { + send_msg(2, "[[main]]: $line"); + $gitupdateflag = 3; + } + if ($line =~ /failed/) { + send_msg(0, "[[main]]: $line"); + $gitupdateflag = 2; + } + if ($line =~ /nothing/) { + send_msg(2, "[[main]]: there isn't new code checkin during last one day."); + $gitupdateflag = 1; + } + $gitprocess = 0; + } + } + } + } - if(time() - $gitstarttime > 7200) { - #if(time() - $gitstarttime > 2) { - send_msg(0, "[[main]] 2 hours is expired. git update out of time"); - last; - } - &runcmd("sleep 2"); - } - close PREAD; - - &runcmd("kill $gitpid") if($gitprocess==1); + if (time() - $gitstarttime > 7200) { + + #if(time() - $gitstarttime > 2) { + send_msg(0, "[[main]] 2 hours is expired. git update out of time"); + last; + } + &runcmd("sleep 2"); + } + close PREAD; + + &runcmd("kill $gitpid") if ($gitprocess == 1); send_msg(2, "[[main]]........git process[$gitpid] exit successful.............."); - - # $gitupdateflag = 0 git update out of time - # $gitupdateflag = 1 there isn't new code checkin in last one day - # $gitupdateflag = 2 there is something wrong during git update - if($gitupdateflag<3){ - send_msg(2, "[[main]]: creat regression result report..........."); - $rst = creat_report(); - if ($rst) { - send_msg(0, "[[main]]: creat regression result report...........[FAILED]"); - }else{ - send_msg(2, "[[main]]: creat regression result report...........[OK]"); - - send_msg(2, "[[main]]: send report email..........."); - $rst = send_email(); - if ($rst) { - send_msg(0, "[[main]]: send report email...........[FAILED]"); - }else{ - send_msg(2, "[[main]]: send report email...........[OK]"); - } - } - exit 1; - } - send_msg(2, "[[main]]: git update successful, start regression today........"); - #exit 0 + # $gitupdateflag = 0 git update out of time + # $gitupdateflag = 1 there isn't new code checkin in last one day + # $gitupdateflag = 2 there is something wrong during git update + if ($gitupdateflag < 3) { + send_msg(2, "[[main]]: creat regression result report..........."); + $rst = creat_report(); + if ($rst) { + send_msg(0, "[[main]]: creat regression result report...........[FAILED]"); + } else { + send_msg(2, "[[main]]: creat regression result report...........[OK]"); + + send_msg(2, "[[main]]: send report email..........."); + $rst = send_email(); + if ($rst) { + send_msg(0, "[[main]]: send report email...........[FAILED]"); + } else { + send_msg(2, "[[main]]: send report email...........[OK]"); + } + } + exit 1; + } + send_msg(2, "[[main]]: git update successful, start regression today........"); + + #exit 0 } my $platformfork = 0; -my $timingork = 0; +my $timingork = 0; + # begin child process -pipe CONTROLREAD,MNWRITE; +pipe CONTROLREAD, MNWRITE; foreach my $m (keys %mns) { $platformfork += 1; - my $mn = $mns{$m}; + my $mn = $mns{$m}; my $pid = fork(); - if ( !defined($pid) ) { - send_msg(0, "fork process for $m error"); + if (!defined($pid)) { + send_msg(0, "fork process for $m error"); exit; - } elsif ( $pid == 0 ) { # child process - send_msg(2, "..........fork process[pid=$$] for $m [$confkeys{$m}].........."); + } elsif ($pid == 0) { # child process + send_msg(2, "..........fork process[pid=$$] for $m [$confkeys{$m}].........."); close CONTROLREAD; - my $res; - - ####################################### - # step 3. download xcat core - ######################################## - send_msg(2, "[$m]step 3, Running down_xcat_core..............."); - $res = down_xcat_core_build($m); - if ($res) { - syswrite MNWRITE,"REPORTFROM:$m->$mn: download xcat core for $mn failed\n"; - exit 1; + my $res; + + ####################################### + # step 3. download xcat core + ######################################## + send_msg(2, "[$m]step 3, Running down_xcat_core..............."); + $res = down_xcat_core_build($m); + if ($res) { + syswrite MNWRITE, "REPORTFROM:$m->$mn: download xcat core for $mn failed\n"; + exit 1; } - send_msg(2, "[$m]step 3, Run down_xcat_core...............[OK]"); - + send_msg(2, "[$m]step 3, Run down_xcat_core...............[OK]"); + ####################################### # step 4. Install MNs, ####################################### send_msg(2, "[$m]step 4, Running mn_install..............."); $res = mn_install($m); if ($res) { - syswrite MNWRITE,"REPORTFROM:$m->$mn: install $mn failed\n"; + syswrite MNWRITE, "REPORTFROM:$m->$mn: install $mn failed\n"; exit 1; } - send_msg(2, "[$m]step 4, Run mn_install...............[OK]"); + send_msg(2, "[$m]step 4, Run mn_install...............[OK]"); ####################################### # step 5. Down xcatdep to MNs ####################################### send_msg(2, "[$m]step 5, Down xcatdep..............."); $depupdateflag = down_dep($m); - if ($depupdateflag ==2){ + if ($depupdateflag == 2) { send_msg(2, "[$m]step 5, updated for xcat dep"); - }else{ - send_msg(2, "[$m]step 5, no update for xcat dep"); + } else { + send_msg(2, "[$m]step 5, no update for xcat dep"); } ####################################### # step 6. Copy code to MNs ####################################### send_msg(2, "[$m]step 6, Running copy_code..............."); - $res = copy_code($m); + $res = copy_code($m); if ($res) { - syswrite MNWRITE,"REPORTFROM:$m->$mn: copy xcat source code to $mn failed\n"; + syswrite MNWRITE, "REPORTFROM:$m->$mn: copy xcat source code to $mn failed\n"; exit 1; } - send_msg(2, "[$m]step 6, Run copy_code...............[OK]"); - + send_msg(2, "[$m]step 6, Run copy_code...............[OK]"); + ######################################## # step 7. Read xCAT MN's configuration ####################################### send_msg(2, "[$m]step 7, Running install_xcat..............."); $res = install_xcat($m); if ($res) { - syswrite MNWRITE,"REPORTFROM:$m->$mn: install new xcat in $mn failed\n"; + syswrite MNWRITE, "REPORTFROM:$m->$mn: install new xcat in $mn failed\n"; exit 1; } - send_msg(2, "[$m]step 7, Run install_xcat...............[OK]"); - + send_msg(2, "[$m]step 7, Run install_xcat...............[OK]"); + ####################################### # step 8. Genrate local configuration file for xcattest # Do test @@ -1487,93 +1506,94 @@ foreach my $m (keys %mns) { send_msg(2, "[$m]step 8, Running do_test..............."); $res = do_test($m); if ($res) { - syswrite MNWRITE,"REPORTFROM:$m->$mn: run regression test cases in $mn failed\n"; + syswrite MNWRITE, "REPORTFROM:$m->$mn: run regression test cases in $mn failed\n"; exit 1; } - send_msg(2, "[$m]step 8, Running do_test...............[OK]"); - + send_msg(2, "[$m]step 8, Running do_test...............[OK]"); + send_msg(2, "whole regression test for $mn finished"); - syswrite MNWRITE,"REPORTFROM:$m->$mn: whole regression test are successful\n"; + syswrite MNWRITE, "REPORTFROM:$m->$mn: whole regression test are successful\n"; exit 0; - } # end of child process + } # end of child process &runcmd("mkdir -p $todayregresultdir/$m"); - $pidrecord{$m} = $pid; + $pidrecord{$m} = $pid; $piderrrecord{$m} = ""; -} # end of foreach +} # end of foreach -{ # parent process - close MNWRITE; - my $rst; - my $regstarttime = time(); - - my $select = new IO::Select; - $select->add(\*CONTROLREAD); - while ($platformfork) { - my @hdls; - if (@hdls = $select->can_read(0)) { - my $hdl; - foreach $hdl (@hdls) { - if ($hdl == \*CONTROLREAD) { - my $line; - chomp($line=); - if ($line){ - if($line =~ /successful/){ - send_msg(2, "[[main]]: $line"); - $line =~ s/^REPORTFROM:(.+)->.+/$1/g; - $pidrecord{$line} = 0; - $consumptionrecord{$line} = time() - $regstarttime; - } - if($line =~ /failed/){ - send_msg(0, "[[main]]: $line"); - my $tmp = $line; - $line =~ s/^REPORTFROM:(.+)->.+/$1/g; - $pidrecord{$line} = 0; - $consumptionrecord{$line} = time() - $regstarttime; - $tmp =~ s/REPORTFROM:.+->.+:(.+)/$1/g; - $piderrrecord{$line} = $tmp; - } - $platformfork -= 1; - } - } - } - } - - if(time() - $regstarttime > 36000) { - #if($curtime - $regstarttime > 10) { - send_msg(1, "[timing] 8 hours is expired"); - last; - } - &runcmd("sleep 1"); - } - - close CONTROLREAD; - if($platformfork){ +{ # parent process + close MNWRITE; + my $rst; + my $regstarttime = time(); + + my $select = new IO::Select; + $select->add(\*CONTROLREAD); + while ($platformfork) { + my @hdls; + if (@hdls = $select->can_read(0)) { + my $hdl; + foreach $hdl (@hdls) { + if ($hdl == \*CONTROLREAD) { + my $line; + chomp($line = ); + if ($line) { + if ($line =~ /successful/) { + send_msg(2, "[[main]]: $line"); + $line =~ s/^REPORTFROM:(.+)->.+/$1/g; + $pidrecord{$line} = 0; + $consumptionrecord{$line} = time() - $regstarttime; + } + if ($line =~ /failed/) { + send_msg(0, "[[main]]: $line"); + my $tmp = $line; + $line =~ s/^REPORTFROM:(.+)->.+/$1/g; + $pidrecord{$line} = 0; + $consumptionrecord{$line} = time() - $regstarttime; + $tmp =~ s/REPORTFROM:.+->.+:(.+)/$1/g; + $piderrrecord{$line} = $tmp; + } + $platformfork -= 1; + } + } + } + } + + if (time() - $regstarttime > 36000) { + + #if($curtime - $regstarttime > 10) { + send_msg(1, "[timing] 8 hours is expired"); + last; + } + &runcmd("sleep 1"); + } + + close CONTROLREAD; + if ($platformfork) { send_msg(0, "[[main]]: there are $platformfork platform's regression test return out of time"); - while(my($k,$v) = each %pidrecord){ + while (my ($k, $v) = each %pidrecord) { &runcmd("kill $v") if ($v != 0); } - }else{ - send_msg(2, "[[main]]: all platform's regression test return on time"); - } - - send_msg(2, "[[main]]: creat regression result report..........."); - $rst = creat_report(); - if ($rst) { - send_msg(0, "[[main]]: creat regression result report...........[FAILED]"); - }else{ + } else { + send_msg(2, "[[main]]: all platform's regression test return on time"); + } + + send_msg(2, "[[main]]: creat regression result report..........."); + $rst = creat_report(); + if ($rst) { + send_msg(0, "[[main]]: creat regression result report...........[FAILED]"); + } else { send_msg(2, "[[main]]: creat regression result report...........[OK]"); - - send_msg(2, "[[main]]: send report email..........."); - $rst = send_email(); - if ($rst) { - send_msg(0, "[[main]]: send report email...........[FAILED]"); - }else{ - send_msg(2, "[[main]]: send report email...........[OK]"); - } - } - send_msg(2, "[[main]]: main process exit"); - exit 0; + + send_msg(2, "[[main]]: send report email..........."); + $rst = send_email(); + if ($rst) { + send_msg(0, "[[main]]: send report email...........[FAILED]"); + } else { + send_msg(2, "[[main]]: send report email...........[OK]"); + } + } + send_msg(2, "[[main]]: main process exit"); + exit 0; } diff --git a/xCAT-server/xCAT-wsapi/xcatrhevh.cgi b/xCAT-server/xCAT-wsapi/xcatrhevh.cgi index d56811288..0a4119d80 100755 --- a/xCAT-server/xCAT-wsapi/xcatrhevh.cgi +++ b/xCAT-server/xCAT-wsapi/xcatrhevh.cgi @@ -9,42 +9,43 @@ use IO::Socket::INET; use IO::Socket::SSL; IO::Socket::SSL->import('inet4'); -my $q = CGI->new; -my $url = $q->url; -my $pathInfo = $q->path_info; -my $peerAdd = $q->remote_addr; +my $q = CGI->new; +my $url = $q->url; +my $pathInfo = $q->path_info; +my $peerAdd = $q->remote_addr; my $iaddr = inet_aton($peerAdd); -my $peerhost = gethostbyaddr($iaddr, AF_INET); +my $peerhost = gethostbyaddr($iaddr, AF_INET); $peerhost =~ s/\..*//; if ($pathInfo =~ /^\/rhevh_finish_install\/(.*)$/) { - if ($1 eq $peerhost) { - &rhevhupdateflag($peerhost); - my $cmd = "rhevhupdateflag"; - } + if ($1 eq $peerhost) { + &rhevhupdateflag($peerhost); + my $cmd = "rhevhupdateflag"; + } } + # check mapping of the IP and hostname sub rhevhupdateflag { - my $node = shift; + my $node = shift; - my $socket = IO::Socket::INET->new( - PeerAddr => "127.0.0.1", - PeerPort => '3001', - Timeout => 15,); - my $client; - if ($socket) { - $client = IO::Socket::SSL->start_SSL($socket, - Timeout => 0, - ); - } + my $socket = IO::Socket::INET->new( + PeerAddr => "127.0.0.1", + PeerPort => '3001', + Timeout => 15,); + my $client; + if ($socket) { + $client = IO::Socket::SSL->start_SSL($socket, + Timeout => 0, + ); + } - my $req1 = "rhevhupdateflag"; - my $req2 = ""; - my $req = $req1.$node.$req2; + my $req1 = "rhevhupdateflag"; + my $req2 = ""; + my $req = $req1 . $node . $req2; - print $client $req; + print $client $req; } diff --git a/xCAT-server/xCAT-wsapi/xcatws.cgi b/xCAT-server/xCAT-wsapi/xcatws.cgi index 55a4adbed..30a04cecc 100755 --- a/xCAT-server/xCAT-wsapi/xcatws.cgi +++ b/xCAT-server/xCAT-wsapi/xcatws.cgi @@ -1,7 +1,7 @@ #!/usr/bin/perl # IBM(c) 2014 EPL license http://www.eclipse.org/legal/epl-v10.html use strict; -use CGI qw/:standard/; #todo: remove :standard when the code only uses object oriented interface +use CGI qw/:standard/; #todo: remove :standard when the code only uses object oriented interface use Data::Dumper; #talk to the server @@ -52,25 +52,25 @@ my %URIdef = ( desc => "[URI:/nodes] - The node list resource.", desc1 => "This resource can be used to display all the nodes which have been defined in the xCAT database.", matcher => '^/nodes$', - GET => { + GET => { desc => "Get all the nodes in xCAT.", desc1 => "The attributes details for the node will not be displayed.", usage => "||Json format: An array of node names.|", example => "|Get all the node names from xCAT database.|GET|/nodes|[\n \"node1\",\n \"node2\",\n \"node3\",\n]|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout_remove_appended_type, - } + } }, nodeallattr => { - desc => "[URI:/nodes/{noderange}] - The node resource", + desc => "[URI:/nodes/{noderange}] - The node resource", matcher => '^/nodes/[^/]*$', - GET => { + GET => { desc => "Get all the attibutes for the node {noderange}.", desc1 => "The keyword ALLRESOURCES can be used as {noderange} which means to get node attributes for all the nodes.", usage => "||$usagemsg{objreturn}|", example => "|Get all the attibutes for node \'node1\'.|GET|/nodes/node1|{\n \"node1\":{\n \"profile\":\"compute\",\n \"netboot\":\"xnba\",\n \"arch\":\"x86_64\",\n \"mgt\":\"ipmi\",\n \"groups\":\"all\",\n ...\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -78,7 +78,7 @@ my %URIdef = ( desc => "Change the attibutes for the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Change the attributes mgt=dfm and netboot=yaboot.|PUT|/nodes/node1 {\"mgt\":\"dfm\",\"netboot\":\"yaboot\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -86,15 +86,15 @@ my %URIdef = ( desc => "Create the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Create a node with attributes groups=all, mgt=dfm and netboot=yaboot|POST|/nodes/node1 {\"groups\":\"all\",\"mgt\":\"dfm\",\"netboot\":\"yaboot\"}||", - cmd => "mkdef", + cmd => "mkdef", fhandler => \&defhdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the node {noderange}.", - usage => "||$usagemsg{non_getreturn}|", - example => "|Delete the node node1|DELETE|/nodes/node1||", - cmd => "rmdef", + desc => "Remove the node {noderange}.", + usage => "||$usagemsg{non_getreturn}|", + example => "|Delete the node node1|DELETE|/nodes/node1||", + cmd => "rmdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -102,12 +102,12 @@ my %URIdef = ( nodeattr => { desc => "[URI:/nodes/{noderange}/attrs/{attr1,attr2,attr3 ...}] - The attributes resource for the node {noderange}", matcher => '^/nodes/[^/]*/attrs/\S+$', - GET => { + GET => { desc => "Get the specific attributes for the node {noderange}.", desc1 => "The keyword ALLRESOURCES can be used as {noderange} which means to get node attributes for all the nodes.", usage => "||$usagemsg{objreturn}|", example => "|Get the attributes {groups,mgt,netboot} for node node1|GET|/nodes/node1/attrs/groups,mgt,netboot|{\n \"node1\":{\n \"netboot\":\"xnba\",\n \"mgt\":\"ipmi\",\n \"groups\":\"all\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -115,19 +115,19 @@ my %URIdef = ( desc => "Change attributes for the node {noderange}. DataBody: {attr1:v1,att2:v2,att3:v3 ...}.", usage => "||An array of node objects.|", example => "|Get the attributes {groups,mgt,netboot} for node node1|GET|/nodes/node1/attrs/groups;mgt;netboot||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, - } + } }, nodestat => { desc => "[URI:/nodes/{noderange}/nodestat}] - The attributes resource for the node {noderange}", matcher => '^/nodes/[^/]*/nodestat$', - GET => { + GET => { desc => "Get the running status for the node {noderange}.", usage => "||An object which includes multiple entries like: : { nodestat : }|", example => "|Get the running status for node node1|GET|/nodes/node1/nodestat|{\n \"node1\":{\n \"nodestat\":\"noping\"\n }\n}|", - cmd => "nodestat", + cmd => "nodestat", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -135,11 +135,11 @@ my %URIdef = ( nodehost => { desc => "[URI:/nodes/{noderange}/host] - The mapping of ip and hostname for the node {noderange}", matcher => '^/nodes/[^/]*/host$', - POST => { + POST => { desc => "Create the mapping of ip and hostname record for the node {noderange}.", usage => "||$usagemsg{non_getreturn}|", example => "|Create the mapping of ip and hostname record for node \'node1\'.|POST|/nodes/node1/host||", - cmd => "makehosts", + cmd => "makehosts", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -147,11 +147,11 @@ my %URIdef = ( noderename => { desc => "[URI:/nodes/{noderange}/rename] - Change old_nodename into new_nodename", matcher => '^/nodes/[^/]*/rename$', - PUT => { - desc => "Change node name.", + PUT => { + desc => "Change node name.", usage => "||$usagemsg{non_getreturn}|", example => "|Change nodename for node \'node1\'.|PUT|/nodes/node1/rename||", - cmd => "chdef", + cmd => "chdef", fhandler => \&actionhdl, outhdler => \&defout_remove_appended_info, }, @@ -159,20 +159,20 @@ my %URIdef = ( nodedns => { desc => "[URI:/nodes/{noderange}/dns] - The dns record resource for the node {noderange}", matcher => '^/nodes/[^/]*/dns$', - POST => { + POST => { desc => "Create the dns record for the node {noderange}.", desc1 => "The prerequisite of the POST operation is the mapping of ip and noderange for the node has been added in the /etc/hosts.", usage => "||$usagemsg{non_getreturn}|", example => "|Create the dns record for node \'node1\'.|POST|/nodes/node1/dns||", - cmd => "makedns", + cmd => "makedns", fhandler => \&actionhdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the dns record for the node {noderange}.", + desc => "Remove the dns record for the node {noderange}.", usage => "||$usagemsg{non_getreturn}|", example => "|Delete the dns record for node node1|DELETE|/nodes/node1/dns||", - cmd => "makedns", + cmd => "makedns", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -180,19 +180,19 @@ my %URIdef = ( nodedhcp => { desc => "[URI:/nodes/{noderange}/dhcp] - The dhcp record resource for the node {noderange}", matcher => '^/nodes/[^/]*/dhcp$', - POST => { - desc => "Create the dhcp record for the node {noderange}.", + POST => { + desc => "Create the dhcp record for the node {noderange}.", usage => "||$usagemsg{non_getreturn}|", example => "|Create the dhcp record for node \'node1\'.|POST|/nodes/node1/dhcp||", - cmd => "makedhcp", + cmd => "makedhcp", fhandler => \&actionhdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the dhcp record for the node {noderange}.", + desc => "Remove the dhcp record for the node {noderange}.", usage => "||$usagemsg{non_getreturn}|", example => "|Delete the dhcp record for node node1|DELETE|/nodes/node1/dhcp||", - cmd => "makedhcp", + cmd => "makedhcp", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -200,11 +200,11 @@ my %URIdef = ( power => { desc => "[URI:/nodes/{noderange}/power] - The power resource for the node {noderange}", matcher => '^/nodes/[^/]*/power$', - GET => { + GET => { desc => "Get the power status for the node {noderange}.", usage => "||An object which includes multiple entries like: : { power : }|", example => "|Get the power status.|GET|/nodes/node1/power|{\n \"node1\":{\n \"power\":\"on\"\n }\n}|", - cmd => "rpower", + cmd => "rpower", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -212,31 +212,31 @@ my %URIdef = ( desc => "Change power status for the node {noderange}.", usage => "|Json Formatted DataBody: {action:on/off/reset ...}.|$usagemsg{non_getreturn}|", example => "|Change the power status to on|PUT|/nodes/node1/power {\"action\":\"on\"}||", - cmd => "rpower", + cmd => "rpower", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, console => { desc => "[URI:/nodes/{noderange}/console] - The console configuration for the node {noderange}", matcher => '^/nodes/[^/]*/console$', - PUT => { + PUT => { desc => "Update conserver configuration for the node {noderange}.", usage => "|Json Formatted DataBody: {action:on/off}.|$usagemsg{non_getreturn}|", example => "|Enable the console capability for node1|PUT|/nodes/node1/console {\"action\":\"on\"}||", - cmd => "makeconservercf", + cmd => "makeconservercf", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, energy => { desc => "[URI:/nodes/{noderange}/energy] - The energy resource for the node {noderange}", matcher => '^/nodes/[^/]*/energy$', - GET => { - desc => "Get all the energy status for the node {noderange}.", + GET => { + desc => "Get all the energy status for the node {noderange}.", usage => "||$usagemsg{objreturn}|", example => "|Get all the energy attributes.|GET|/nodes/node1/energy|{\n \"node1\":{\n \"cappingmin\":\"272.3 W\",\n \"cappingmax\":\"354.0 W\"\n ...\n }\n}|", - cmd => "renergy", + cmd => "renergy", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -244,20 +244,20 @@ my %URIdef = ( desc => "Change energy attributes for the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: {powerattr:value}.|$usagemsg{non_getreturn}|", example => "|Turn on the cappingstatus to [on]|PUT|/nodes/node1/energy {\"cappingstatus\":\"on\"}||", - cmd => "renergy", + cmd => "renergy", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, energyattr => { disable => 1, desc => "[URI:/nodes/{noderange}/energy/{cappingmaxmin,cappingstatus,cappingvalue ...}] - The specific energy attributes resource for the node {noderange}", matcher => '^/nodes/[^/]*/energy/\S+$', - GET => { + GET => { desc => "Get the specific energy attributes cappingmaxmin,cappingstatus,cappingvalue ... for the node {noderange}.", usage => "||$usagemsg{objreturn}|", example => "|Get the energy attributes which are specified in the URI.|GET|/nodes/node1/energy/cappingmaxmin,cappingstatus|{\n \"node1\":{\n \"cappingmin\":\"272.3 W\",\n \"cappingmax\":\"354.0 W\"\n }\n}|", - cmd => "renergy", + cmd => "renergy", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -265,20 +265,20 @@ my %URIdef = ( desc => "Change energy attributes for the node {noderange}. ", usage => "|$usagemsg{objchparam} DataBody: {powerattr:value}.|$usagemsg{non_getreturn}|", example => "|Turn on the cappingstatus to [on]|PUT|/nodes/node1/energy {\"cappingstatus\":\"on\"}||", - cmd => "renergy", + cmd => "renergy", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, serviceprocessor => { disable => 1, desc => "[URI:/nodes/{noderange}/sp/{community|ip|netmask|...}] - The attribute resource of service processor for the node {noderange}", matcher => '^/nodes/[^/]*/sp/\S+$', - GET => { + GET => { desc => "Get the specific attributes for service processor resource.", usage => "||$usagemsg{objreturn}|", example => "|Get the snmp community for the service processor of node1.|GET|/nodes/node1/sp/community|{\n \"node1\":{\n \"SP SNMP Community\":\"public\"\n }\n}|", - cmd => "rspconfig", + cmd => "rspconfig", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -286,29 +286,29 @@ my %URIdef = ( desc => "Change the specific attributes for the service processor resource. ", usage => "|$usagemsg{objchparam} DataBody: {community:public}.|$usagemsg{non_getreturn}|", example => "|Set the snmp community to [mycommunity].|PUT|/nodes/node1/sp/community {\"value\":\"mycommunity\"}||", - cmd => "rspconfig", + cmd => "rspconfig", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, macaddress => { disable => 1, desc => "[URI:/nodes/{noderange}/mac] - The mac address resource for the node {noderange}", matcher => '^/nodes/[^/]*/mac$', - GET => { + GET => { desc => "Get the mac address for the node {noderange}. Generally, it also updates the mac attribute of the node.", - cmd => "getmacs", + cmd => "getmacs", fhandler => \&common, }, }, nextboot => { desc => "[URI:/nodes/{noderange}/nextboot] - The temporary bootorder resource in next boot for the node {noderange}", matcher => '^/nodes/[^/]*/nextboot$', - GET => { - desc => "Get the next bootorder.", + GET => { + desc => "Get the next bootorder.", usage => "||$usagemsg{objreturn}|", example => "|Get the bootorder for the next boot. (It's only valid after setting.)|GET|/nodes/node1/nextboot|{\n \"node1\":{\n \"nextboot\":\"Network\"\n }\n}|", - cmd => "rsetboot", + cmd => "rsetboot", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -316,19 +316,19 @@ my %URIdef = ( desc => "Change the next boot order. ", usage => "|$usagemsg{objchparam} DataBody: {order:net/hd}.|$usagemsg{non_getreturn}|", example => "|Set the bootorder for the next boot.|PUT|/nodes/node1/nextboot {\"order\":\"net\"}||", - cmd => "rsetboot", + cmd => "rsetboot", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, bootorder => { desc => "[URI:/nodes/{noderange}/bootorder] - The permanent bootorder resource for the node {noderange}", matcher => '^/nodes/[^/]*/bootorder$', - GET => { - desc => "Get the permanent boot order.", + GET => { + desc => "Get the permanent boot order.", usage => "|?|?|", example => "|Get the permanent bootorder for the node1.|GET|/nodes/node1/bootorder|?|", - cmd => "rbootseq", + cmd => "rbootseq", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -336,19 +336,19 @@ my %URIdef = ( desc => "Change the boot order. DataBody: {\"order\":\"net,hd\"}.", usage => "|Put data: Json formatted order:value pair.|?|", example => "|Set the permanent bootorder for the node1.|PUT|/nodes/node1/bootorder|?|", - cmd => "rbootseq", + cmd => "rbootseq", fhandler => \&actionhdl, outhdler => \&noout, - } + } }, vitals => { desc => "[URI:/nodes/{noderange}/vitals] - The vitals resources for the node {noderange}", matcher => '^/nodes/[^/]*/vitals$', - GET => { - desc => "Get all the vitals attibutes.", + GET => { + desc => "Get all the vitals attibutes.", usage => "||$usagemsg{objreturn}|", example => "|Get all the vitails attributes for the node1.|GET|/nodes/node1/vitals|{\n \"node1\":{\n \"SysBrd Fault\":\"0\",\n \"CPUs\":\"0\",\n \"Fan 4A Tach\":\"3330 RPM\",\n \"Drive 15\":\"0\",\n \"SysBrd Vol Fault\":\"0\",\n \"nvDIMM Flash\":\"0\",\n \"Progress\":\"0\"\n ...\n }\n}|", - cmd => "rvitals", + cmd => "rvitals", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -357,11 +357,11 @@ my %URIdef = ( disable => 1, desc => "[URI:/nodes/{noderange}/vitals/{temp|voltage|wattage|fanspeed|power|leds...}] - The specific vital attributes for the node {noderange}", matcher => '^/nodes/[^/]*/vitals/\S+$', - GET => { - desc => "Get the specific vitals attibutes.", + GET => { + desc => "Get the specific vitals attibutes.", usage => "||$usagemsg{objreturn}|", example => "|Get the \'fanspeed\' vitals attribute.|GET|/nodes/node1/vitals/fanspeed|{\n \"node1\":{\n \"Fan 1A Tach\":\"3219 RPM\",\n \"Fan 4B Tach\":\"2688 RPM\",\n \"Fan 3B Tach\":\"2560 RPM\",\n \"Fan 4A Tach\":\"3330 RPM\",\n \"Fan 2A Tach\":\"3293 RPM\",\n \"Fan 1B Tach\":\"2592 RPM\",\n \"Fan 3A Tach\":\"3182 RPM\",\n \"Fan 2B Tach\":\"2592 RPM\"\n }\n}|", - cmd => "rvitals", + cmd => "rvitals", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -369,11 +369,11 @@ my %URIdef = ( inventory => { desc => "[URI:/nodes/{noderange}/inventory] - The inventory attributes for the node {noderange}", matcher => '^/nodes/[^/]*/inventory$', - GET => { - desc => "Get all the inventory attibutes.", + GET => { + desc => "Get all the inventory attibutes.", usage => "||$usagemsg{objreturn}|", example => "|Get all the inventory attributes for node1.|GET|/nodes/node1/inventory|{\n \"node1\":{\n \"DIMM 21 \":\"8GB PC3-12800 (1600 MT/s) ECC RDIMM\",\n \"DIMM 1 Manufacturer\":\"Hyundai Electronics\",\n \"Power Supply 2 Board FRU Number\":\"94Y8105\",\n \"DIMM 9 Model\":\"HMT31GR7EFR4C-PB\",\n \"DIMM 8 Manufacture Location\":\"01\",\n \"DIMM 13 Manufacturer\":\"Hyundai Electronics\",\n \"DASD Backplane 4\":\"Not Present\",\n ...\n }\n}|", - cmd => "rinv", + cmd => "rinv", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -381,11 +381,11 @@ my %URIdef = ( inventoryattr => { desc => "[URI:/nodes/{noderange}/inventory/{pci|model...}] - The specific inventory attributes for the node {noderange}", matcher => '^/nodes/[^/]*/inventory/\S+$', - GET => { - desc => "Get the specific inventory attibutes.", + GET => { + desc => "Get the specific inventory attibutes.", usage => "||$usagemsg{objreturn}|", example => "|Get the \'model\' inventory attribute for node1.|GET|/nodes/node1/inventory/model|{\n \"node1\":{\n \"System Description\":\"System x3650 M4\",\n \"System Model/MTM\":\"7915C2A\"\n }\n}|", - cmd => "rinv", + cmd => "rinv", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -393,36 +393,36 @@ my %URIdef = ( eventlog => { desc => "[URI:/nodes/{noderange}/eventlog] - The eventlog resource for the node {noderange}", matcher => '^/nodes/[^/]*/eventlog$', - GET => { - desc => "Get all the eventlog for the node {noderange}.", + GET => { + desc => "Get all the eventlog for the node {noderange}.", usage => "||$usagemsg{objreturn}|", example => "|Get all the eventlog for node1.|GET|/nodes/node1/eventlog|{\n \"node1\":{\n \"eventlog\":[\n \"03/19/2014 15:17:58 Event Logging Disabled, Log Area Reset/Cleared (SEL Fullness)\"\n ]\n }\n}|", - cmd => "reventlog", + cmd => "reventlog", fhandler => \&actionhdl, outhdler => \&actionout, }, DELETE => { - desc => "Clean up the event log for the node {noderange}.", + desc => "Clean up the event log for the node {noderange}.", usage => "||$usagemsg{non_getreturn}|", example => "|Delete all the event log for node1.|DELETE|/nodes/node1/eventlog|[\n {\n \"eventlog\":[\n \"SEL cleared\"\n ],\n \"name\":\"node1\"\n }\n]|", - cmd => "reventlog", + cmd => "reventlog", fhandler => \&actionhdl, outhdler => \&noout, }, }, beacon => { desc => "[URI:/nodes/{noderange}/beacon] - The beacon resource for the node {noderange}", - matcher => '^/nodes/[^/]*/beacon$', + matcher => '^/nodes/[^/]*/beacon$', GET_backup => { - desc => "Get the beacon status for the node {noderange}.", - cmd => "rbeacon", + desc => "Get the beacon status for the node {noderange}.", + cmd => "rbeacon", fhandler => \&common, }, PUT => { desc => "Change the beacon status for the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: {action:on/off/blink}.|$usagemsg{non_getreturn}|", example => "|Turn on the beacon.|PUT|/nodes/node1/beacon {\"action\":\"on\"}|[\n {\n \"name\":\"node1\",\n \"beacon\":\"on\"\n }\n]|", - cmd => "rbeacon", + cmd => "rbeacon", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -430,10 +430,10 @@ my %URIdef = ( vm => { desc => "[URI:/nodes/{noderange}/vm] - The virtualization node {noderange}.", desc1 => "The node should be a virtual machine of type kvm, esxi ...", - matcher => '^/nodes/[^/]*/vm$', + matcher => '^/nodes/[^/]*/vm$', GET_backup => { - desc => "Get the vm status for the node {noderange}.", - cmd => "lsvm", + desc => "Get the vm status for the node {noderange}.", + cmd => "lsvm", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -443,7 +443,7 @@ my %URIdef = ( example => "|Set memory to 3000MB.|PUT|/nodes/node1/vm {\"memorysize\":\"3000\"}||", example1 => "|Add a new 20G disk.|PUT|/nodes/node1/vm {\"adddisk\":\"20G\"}||", example2 => "|Purge the disk \'hdb\'.|PUT|/nodes/node1/vm {\"purgedisk\":\"hdb\"}||", - cmd => "chvm", + cmd => "chvm", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -451,7 +451,7 @@ my %URIdef = ( desc => "Create the vm node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: \n Set CPU count - {\"cpucount\":\"numberofcpu\"}\n Set memory size - {\"memorysize\":\"sizeofmemory(MB)\"}\n Set disk size - {\"disksize\":\"sizeofdisk\"}\n Do it by force - {\"force\":\"yes\"}|$usagemsg{non_getreturn}|", example => "|Create the vm node1 with a 30G disk, 2048M memory and 2 cpus.|POST|/nodes/node1/vm {\"disksize\":\"30G\",\"memorysize\":\"2048\",\"cpucount\":\"2\"}||", - cmd => "mkvm", + cmd => "mkvm", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -459,34 +459,34 @@ my %URIdef = ( desc => "Remove the vm node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: \n Purge disk - {\"purge\":\"yes\"}\n Do it by force - {\"force\":\"yes\"}|$usagemsg{non_getreturn}|", example => "|Remove the vm node1 by force and purge the disk.|DELETE|/nodes/node1/vm {\"force\":\"yes\",\"purge\":\"yes\"}||", - cmd => "rmvm", + cmd => "rmvm", fhandler => \&actionhdl, outhdler => \&noout, }, }, vmclone => { desc => "[URI:/nodes/{noderange}/vmclone] - The clone resource for the virtual node {noderange}.", - desc1 => "The node should be a virtual machine of kvm, esxi ...", + desc1 => "The node should be a virtual machine of kvm, esxi ...", matcher => '^/nodes/[^/]*/vmclone$', - POST => { + POST => { desc => "Create a clone master from node {noderange}. Or clone the node {noderange} from a clone master.", usage => "|$usagemsg{objchparam} DataBody: \n Clone a master named \"mastername\" - {\"tomaster\":\"mastername\"}\n Clone a node from master \"mastername\" - {\"frommaster\":\"mastername\"}\n Use Detach mode - {\"detach\":\"yes\"}\n Do it by force - {\"force\":\"yes\"}|The messages of creating Clone target.|", example1 => "|Create a clone master named \"vmmaster\" from the node1.|POST|/nodes/node1/vmclone {\"tomaster\":\"vmmaster\",\"detach\":\"yes\"}|{\n \"node1\":{\n \"vmclone\":\"Cloning of node1.hda.qcow2 complete (clone uses 9633.19921875 for a disk size of 30720MB)\"\n }\n}|", example2 => "|Clone the node1 from the clone master named \"vmmaster\".|POST|/nodes/node1/vmclone {\"frommaster\":\"vmmaster\"}||", - cmd => "clonevm", + cmd => "clonevm", fhandler => \&actionhdl, outhdler => \&actionout, }, }, vmmigrate => { desc => "[URI:/nodes/{noderange}/vmmigrate] - The virtualization resource for migration.", - desc1 => "The node should be a virtual machine of kvm, esxi ...", + desc1 => "The node should be a virtual machine of kvm, esxi ...", matcher => '^/nodes/[^/]*/vmmigrate$', - POST => { + POST => { desc => "Migrate a node to targe node.", usage => "|$usagemsg{objchparam} DataBody: {\"target\":\"targethost\"}.", example => "|Migrate node1 to target host host2.|POST|/nodes/node1/vmmigrate {\"target\":\"host2\"}||", - cmd => "rmigrate", + cmd => "rmigrate", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -494,11 +494,11 @@ my %URIdef = ( updating => { desc => "[URI:/nodes/{noderange}/updating] - The updating resource for the node {noderange}", matcher => '^/nodes/[^/]*/updating$', - POST => { + POST => { desc => "Update the node with file syncing, software maintenance and rerun postscripts.", usage => "||An array of messages for performing the node updating.|", example => "|Initiate an updatenode process.|POST|/nodes/node2/updating|[\n \"There were no syncfiles defined to process. File synchronization has completed.\",\n \"Performing software maintenance operations. This could take a while, if there are packages to install.\n\",\n \"node2: Wed Mar 20 15:01:43 CST 2013 Running postscript: ospkgs\",\n \"node2: Running of postscripts has completed.\"\n]|", - cmd => "updatenode", + cmd => "updatenode", fhandler => \&actionhdl, outhdler => \&infoout, }, @@ -506,11 +506,11 @@ my %URIdef = ( filesyncing => { desc => "[URI:/nodes/{noderange}/filesyncing] - The filesyncing resource for the node {noderange}", matcher => '^/nodes/[^/]*/filesyncing$', - POST => { + POST => { desc => "Sync files for the node {noderange}.", usage => "||An array of messages for performing the file syncing for the node.|", example => "|Initiate an file syncing process.|POST|/nodes/node2/filesyncing|[\n \"There were no syncfiles defined to process. File synchronization has completed.\"\n]|", - cmd => "updatenode", + cmd => "updatenode", fhandler => \&actionhdl, outhdler => \&infoout, }, @@ -518,11 +518,11 @@ my %URIdef = ( software_maintenance => { desc => "[URI:/nodes/{noderange}/sw] - The software maintenance for the node {noderange}", matcher => '^/nodes/[^/]*/sw$', - POST => { + POST => { desc => "Perform the software maintenance process for the node {noderange}.", usage => "||$usagemsg{objreturn}|", example => "|Initiate an software maintenance process.|POST|/nodes/node2/sw|{\n \"node2\":[\n \" Wed Apr 3 09:05:42 CST 2013 Running postscript: ospkgs\",\n \" Unable to read consumer identity\",\n \" Postscript: ospkgs exited with code 0\",\n \" Wed Apr 3 09:05:44 CST 2013 Running postscript: otherpkgs\",\n \" ./otherpkgs: no extra rpms to install\",\n \" Postscript: otherpkgs exited with code 0\",\n \" Running of Software Maintenance has completed.\"\n ]\n}|", - cmd => "updatenode", + cmd => "updatenode", fhandler => \&actionhdl, outhdler => \&infoout, }, @@ -530,11 +530,11 @@ my %URIdef = ( postscript => { desc => "[URI:/nodes/{noderange}/postscript] - The postscript resource for the node {noderange}", matcher => '^/nodes/[^/]*/postscript$', - POST => { + POST => { desc => "Run the postscripts for the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: {scripts:[p1,p2,p3,...]}.|$usagemsg{objreturn}|", example => "|Initiate an updatenode process.|POST|/nodes/node2/postscript {\"scripts\":[\"syslog\",\"remoteshell\"]}|{\n \"node2\":[\n \" Wed Apr 3 09:01:33 CST 2013 Running postscript: syslog\",\n \" Shutting down system logger: [ OK ]\",\n \" Starting system logger: [ OK ]\",\n \" Postscript: syslog exited with code 0\",\n \" Wed Apr 3 09:01:33 CST 2013 Running postscript: remoteshell\",\n \" Stopping sshd: [ OK ]\",\n \" Starting sshd: [ OK ]\",\n \" Postscript: remoteshell exited with code 0\",\n \" Running of postscripts has completed.\"\n ]\n}|", - cmd => "updatenode", + cmd => "updatenode", fhandler => \&actionhdl, outhdler => \&infoout, }, @@ -542,11 +542,11 @@ my %URIdef = ( nodeshell => { desc => "[URI:/nodes/{noderange}/nodeshell] - The nodeshell resource for the node {noderange}", matcher => '^/nodes/[^/]*/nodeshell$', - POST => { + POST => { desc => "Run the command in the shell of the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: set environment {ENV:{en1:v1,en2:v2}}, raw command {raw:[op1,op2]}, direct command {command:[cmd1,cmd2]}.|$usagemsg{objreturn}|", example => "|Run the \'date\' command on the node2.|POST|/nodes/node2/nodeshell {\"command\":[\"date\",\"ls\"]}|{\n \"node2\":[\n \" Wed Apr 3 08:30:26 CST 2013\",\n \" testline1\",\n \" testline2\"\n ]\n}|Use ENV and raw command on the node2.|POST|/nodes/node2/nodeshell {\"ENV\":{\"DSH_REMOTE_PASSWORD\":\"cluster\",\"DSH_FROM_USERID\":\"root\",\"DSH_TO_USERID\":\"root\"},\"raw\":[\"-K\"]}|[\n \"/usr/bin/ssh setup is complete.\",\n \"return code = 0\"\n]|", - cmd => "xdsh", + cmd => "xdsh", fhandler => \&actionhdl, outhdler => \&infoout, }, @@ -554,11 +554,11 @@ my %URIdef = ( nodecopy => { desc => "[URI:/nodes/{noderange}/nodecopy] - The nodecopy resource for the node {noderange}", matcher => '^/nodes/[^/]*/nodecopy$', - POST => { + POST => { desc => "Copy files to the node {noderange}.", usage => "|$usagemsg{objchparam} DataBody: {src:[file1,file2],target:dir}.|$usagemsg{non_getreturn}|", example => "|Copy files /tmp/f1 and /tmp/f2 from xCAT MN to the node2:/tmp.|POST|/nodes/node2/nodecopy {\"src\":[\"/tmp/f1\",\"/tmp/f2\"],\"target\":\"/tmp\"}|no output for succeeded copy.|", - cmd => "xdcp", + cmd => "xdcp", fhandler => \&actionhdl, outhdler => \&infoout, }, @@ -566,29 +566,30 @@ my %URIdef = ( subnodes => { desc => "[URI:/nodes/{noderange}/subnodes] - The sub-nodes resources for the node {noderange}", matcher => '^/nodes/[^/]*/subnodes$', - GET => { - desc => "Return the Children nodes for the node {noderange}.", + GET => { + desc => "Return the Children nodes for the node {noderange}.", usage => "||$usagemsg{objreturn}|", example => "|Get all the children nodes for node \'node1\'.|GET|/nodes/node1/subnodes|{\n \"cmm01node09\":{\n \"mpa\":\"ngpcmm01\",\n \"parent\":\"ngpcmm01\",\n \"serial\":\"1035CDB\",\n \"mtm\":\"789523X\",\n \"cons\":\"fsp\",\n \"hwtype\":\"blade\",\n \"objtype\":\"node\",\n \"groups\":\"blade,all,p260\",\n \"mgt\":\"fsp\",\n \"nodetype\":\"ppc,osi\",\n \"slotid\":\"9\",\n \"hcp\":\"10.1.9.9\",\n \"id\":\"1\"\n },\n ...\n}|", - cmd => "rscan", + cmd => "rscan", fhandler => \&actionhdl, outhdler => \&defout, }, + # the put should be implemented by customer that using GET to get all the resources and define it with PUT /nodes/ PUT_bak => { desc => "Update the Children node for the node {noderange}.", - cmd => "rscan", + cmd => "rscan", fhandler => \&common, }, }, bootstate => { desc => "[URI:/nodes/{noderange}/bootstate] - The boot state resource for node {noderange}.", matcher => '^/nodes/[^/]*/bootstate$', - GET => { - desc => "Get boot state.", + GET => { + desc => "Get boot state.", usage => "||$usagemsg{objreturn}|", example => "|Get the next boot state for the node1.|GET|/nodes/node1/bootstate|{\n \"node1\":{\n \"bootstat\":\"boot\"\n }\n}|", - cmd => "nodeset", + cmd => "nodeset", fhandler => \&actionhdl, outhdler => \&actionout, }, @@ -596,7 +597,7 @@ my %URIdef = ( desc => "Set the boot state.", usage => "|$usagemsg{objchparam} DataBody: {osimage:xxx}/{state:offline}.|$usagemsg{non_getreturn}|", example => "|Set the next boot state for the node1.|PUT|/nodes/node1/bootstate {\"osimage\":\"rhels6.4-x86_64-install-compute\"}||", - cmd => "nodeset", + cmd => "nodeset", fhandler => \&actionhdl, outhdler => \&noout, }, @@ -612,24 +613,24 @@ my %URIdef = ( desc => "[URI:/groups] - The group list resource.", desc1 => "This resource can be used to display all the groups which have been defined in the xCAT database.", matcher => '^/groups$', - GET => { + GET => { desc => "Get all the groups in xCAT.", desc1 => "The attributes details for the group will not be displayed.", usage => "||Json format: An array of group names.|", example => "|Get all the group names from xCAT database.|GET|/groups|[\n \"__mgmtnode\",\n \"all\",\n \"compute\",\n \"ipmi\",\n \"kvm\",\n]|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout_remove_appended_type, - } + } }, group_allattr => { - desc => "[URI:/groups/{groupname}] - The group resource", + desc => "[URI:/groups/{groupname}] - The group resource", matcher => '^/groups/[^/]*$', - GET => { - desc => "Get all the attibutes for the group {groupname}.", + GET => { + desc => "Get all the attibutes for the group {groupname}.", usage => "||$usagemsg{objreturn}|", example => "|Get all the attibutes for group \'all\'.|GET|/groups/all|{\n \"all\":{\n \"members\":\"zxnode2,nodexxx,node1,node4\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -637,7 +638,7 @@ my %URIdef = ( desc => "Change the attibutes for the group {groupname}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Change the attributes mgt=dfm and netboot=yaboot.|PUT|/groups/all {\"mgt\":\"dfm\",\"netboot\":\"yaboot\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -645,11 +646,11 @@ my %URIdef = ( group_attr => { desc => "[URI:/groups/{groupname}/attrs/{attr1,attr2,attr3 ...}] - The attributes resource for the group {groupname}", matcher => '^/groups/[^/]*/attrs/\S+$', - GET => { + GET => { desc => "Get the specific attributes for the group {groupname}.", usage => "||$usagemsg{objreturn}|", example => "|Get the attributes {mgt,netboot} for group all|GET|/groups/all/attrs/mgt,netboot|{\n \"all\":{\n \"netboot\":\"yaboot\",\n \"mgt\":\"dfm\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -659,113 +660,114 @@ my %URIdef = ( #### definition for services resources: dns, dhcp, hostname services => { host => { - desc => "[URI:/services/host] - The hostname resource.", + desc => "[URI:/services/host] - The hostname resource.", matcher => '^/services/host$', - POST => { + POST => { desc => "Create the ip/hostname records for all the nodes to /etc/hosts.", usage => "||$usagemsg{non_getreturn}|", example => "|Create the ip/hostname records for all the nodes to /etc/hosts.|POST|/services/host||", - cmd => "makehosts", + cmd => "makehosts", fhandler => \&nonobjhdl, outhdler => \&noout, - } + } }, dns => { - desc => "[URI:/services/dns] - The dns service resource.", + desc => "[URI:/services/dns] - The dns service resource.", matcher => '^/services/dns$', - POST => { - desc => "Initialize the dns service.", - usage => "||$usagemsg{non_getreturn}|", - example => "|Initialize the dns service.|POST|/services/dns||", - cmd => "makedns", + POST => { + desc => "Initialize the dns service.", + usage => "||$usagemsg{non_getreturn}|", + example => "|Initialize the dns service.|POST|/services/dns||", + cmd => "makedns", fhandler => \&nonobjhdl, outhdler => \&noout, - } + } }, bmcdiscover => { desc => "[URI:/services/bmcdiscover] - The bmc which does support nmap in the xCAT cluster.", matcher => '^/services/bmcdiscover/[^/]+$', - GET => { - desc => "Get all the bmc alive.", + GET => { + desc => "Get all the bmc alive.", usage => "||$usagemsg{objreturn}|", example => "|Get all the bmc which do not support slp in the network.|", - cmd => "bmcdiscover", + cmd => "bmcdiscover", fhandler => \&bmclisthdl, outhdler => \&defout_remove_appended_info, - } + } }, checkbmcauth => { desc => "[URI:/services/checkbmcauth] - Check if bmc user or password is correct.", matcher => '^/services/checkbmcauth/[^/]*/[^/]+$', - GET => { - desc => "Check if bmc user or password is correct.", + GET => { + desc => "Check if bmc user or password is correct.", usage => "||$usagemsg{objreturn}|", example => "|Check bmc user or password.|GET|/services/checkbmcauth||", - cmd => "bmcdiscover", + cmd => "bmcdiscover", fhandler => \&bmccheckhdl, outhdler => \&defout_remove_appended_info, - } + } }, getbmcipsource => { desc => "[URI:/services/getbmcipsource] - Get BMC IP Address source.", matcher => '^/services/getbmcipsource/[^/]*/[^/]+$', - GET => { - desc => "Get BMC IP Address source.", + GET => { + desc => "Get BMC IP Address source.", usage => "||$usagemsg{objreturn}|", example => "|Get BMC IP Address source.|GET|/services/getbmcipsource||", - cmd => "bmcdiscover", + cmd => "bmcdiscover", fhandler => \&bmccheckhdl, outhdler => \&defout_remove_appended_info, - } + } }, dhcp => { - desc => "[URI:/services/dhcp] - The dhcp service resource.", + desc => "[URI:/services/dhcp] - The dhcp service resource.", matcher => '^/services/dhcp$', - POST => { + POST => { desc => "Create the dhcpd.conf for all the networks which are defined in the xCAT Management Node.", usage => "||$usagemsg{non_getreturn}|", example => "|Create the dhcpd.conf and restart the dhcpd.|POST|/services/dhcp||", - cmd => "makedhcp", + cmd => "makedhcp", fhandler => \&nonobjhdl, outhdler => \&noout, - } + } }, + # todo: for slpnode, we need use the query attribute to specify the network parameter for lsslp command slpnodes => { desc => "[URI:/services/slpnodes] - The nodes which support SLP in the xCAT cluster", matcher => '^/services/slpnodes', - GET => { + GET => { desc => "Get all the nodes which support slp protocol in the network.", usage => "||$usagemsg{objreturn}|", example => "|Get all the nodes which support slp in the network.|GET|/services/slpnodes|{\n \"ngpcmm01\":{\n \"mpa\":\"ngpcmm01\",\n \"otherinterfaces\":\"10.1.9.101\",\n \"serial\":\"100037A\",\n \"mtm\":\"789392X\",\n \"hwtype\":\"cmm\",\n \"side\":\"2\",\n \"objtype\":\"node\",\n \"nodetype\":\"mp\",\n \"groups\":\"cmm,all,cmm-zet\",\n \"mgt\":\"blade\",\n \"hidden\":\"0\",\n \"mac\":\"5c:f3:fc:25:da:99\"\n },\n ...\n}|", - cmd => "lsslp", + cmd => "lsslp", fhandler => \&nonobjhdl, outhdler => \&defout, }, PUT_bakcup => { - desc => "Update the discovered nodes to database.", - cmd => "lsslp", + desc => "Update the discovered nodes to database.", + cmd => "lsslp", fhandler => \&common, }, }, specific_slpnodes => { desc => "[URI:/services/slpnodes/{CEC|FRAME|MM|IVM|RSA|HMC|CMM|IMM2|FSP...}] - The slp nodes with specific service type in the xCAT cluster", matcher => '^/services/slpnodes/[^/]*$', - GET => { + GET => { desc => "Get all the nodes with specific slp service type in the network.", usage => "||$usagemsg{objreturn}|", example => "|Get all the CMM nodes which support slp in the network.|GET|/services/slpnodes/CMM|{\n \"ngpcmm01\":{\n \"mpa\":\"ngpcmm01\",\n \"otherinterfaces\":\"10.1.9.101\",\n \"serial\":\"100037A\",\n \"mtm\":\"789392X\",\n \"hwtype\":\"cmm\",\n \"side\":\"2\",\n \"objtype\":\"node\",\n \"nodetype\":\"mp\",\n \"groups\":\"cmm,all,cmm-zet\",\n \"mgt\":\"blade\",\n \"hidden\":\"0\",\n \"mac\":\"5c:f3:fc:25:da:99\"\n },\n \"Server--SNY014BG27A01K\":{\n \"mpa\":\"Server--SNY014BG27A01K\",\n \"otherinterfaces\":\"10.1.9.106\",\n \"serial\":\"100CF0A\",\n \"mtm\":\"789392X\",\n \"hwtype\":\"cmm\",\n \"side\":\"1\",\n \"objtype\":\"node\",\n \"nodetype\":\"mp\",\n \"groups\":\"cmm,all,cmm-zet\",\n \"mgt\":\"blade\",\n \"hidden\":\"0\",\n \"mac\":\"34:40:b5:df:0a:be\"\n }\n}|", - cmd => "lsslp", + cmd => "lsslp", fhandler => \&nonobjhdl, outhdler => \&defout, }, PUT_backup => { - desc => "Update the discovered nodes to database.", - cmd => "lsslp", + desc => "Update the discovered nodes to database.", + cmd => "lsslp", fhandler => \&common, }, }, @@ -773,28 +775,28 @@ my %URIdef = ( nbimage => { desc => "[URI:/nbimage] - Create netboot root image for specified arch.", matcher => '^/services/nbimage/arch/[ppc64|x86_64]', - POST => { + POST => { desc => "creates a network boot root image", usage => "|$usagemsg{objchparam} DataBody: {\"onlyconfigfile\":\"[true|yes|Y|1]|[false|no|N|0]\"}.|$usagemsg{non_getreturn}|", example => "|Create a network boot root iamge for the specified arch|", - cmd => "mknb", + cmd => "mknb", fhandler => \&actionhdl, }, }, }, - + #### definition for network resources networks => { allnetwork => { desc => "[URI:/networks] - The network list resource.", desc1 => "This resource can be used to display all the networks which have been defined in the xCAT database.", matcher => '^\/networks$', - GET => { + GET => { desc => "Get all the networks in xCAT.", desc1 => "The attributes details for the networks will not be displayed.", usage => "||Json format: An array of networks names.|", example => "|Get all the networks names from xCAT database.|GET|/networks|[\n \"network1\",\n \"network2\",\n \"network3\",\n]|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout_remove_appended_type, }, @@ -802,20 +804,20 @@ my %URIdef = ( desc => "Create the networks resources base on the network configuration on xCAT MN.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Create the networks resources base on the network configuration on xCAT MN.|POST|/networks||", - cmd => "makenetworks", + cmd => "makenetworks", fhandler => \&actionhdl, outhdler => \&noout, }, }, network_allattr => { - desc => "[URI:/networks/{netname}] - The network resource", + desc => "[URI:/networks/{netname}] - The network resource", matcher => '^\/networks\/[^\/]*$', - GET => { + GET => { desc => "Get all the attibutes for the network {netname}.", desc1 => "The keyword ALLRESOURCES can be used as {netname} which means to get network attributes for all the networks.", usage => "||$usagemsg{objreturn}|", example => "|Get all the attibutes for network \'network1\'.|GET|/networks/network1|{\n \"network1\":{\n \"gateway\":\"\",\n \"mask\":\"255.255.255.0\",\n \"mgtifname\":\"eth2\",\n \"net\":\"10.0.0.0\",\n \"tftpserver\":\"10.0.0.119\",\n ...\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -823,7 +825,7 @@ my %URIdef = ( desc => "Change the attibutes for the network {netname}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Change the attributes mgtifname=eth0 and net=10.1.0.0.|PUT|/networks/network1 {\"mgtifname\":\"eth0\",\"net\":\"10.1.0.0\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -831,15 +833,15 @@ my %URIdef = ( desc => "Create the network {netname}. DataBody: {attr1:v1,att2:v2...}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Create a network with attributes gateway=10.1.0.1, mask=255.255.0.0 |POST|/networks/network1 {\"gateway\":\"10.1.0.1\",\"mask\":\"255.255.0.0\"}||", - cmd => "mkdef", + cmd => "mkdef", fhandler => \&defhdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the network {netname}.", + desc => "Remove the network {netname}.", usage => "||$usagemsg{non_getreturn}|", example => "|Delete the network network1|DELETE|/networks/network1||", - cmd => "rmdef", + cmd => "rmdef", fhandler => \&defhdl, outhdler => \&noout }, @@ -847,12 +849,12 @@ my %URIdef = ( network_attr => { desc => "[URI:/networks/{netname}/attrs/attr1,attr2,...] - The attributes resource for the network {netname}", matcher => '^\/networks\/[^\/]*/attrs/\S+$', - GET => { + GET => { desc => "Get the specific attributes for the network {netname}.", desc1 => "The keyword ALLRESOURCES can be used as {netname} which means to get network attributes for all the networks.", usage => "||$usagemsg{objreturn}|", example => "|Get the attributes {groups,mgt,netboot} for network network1|GET|/networks/network1/attrs/gateway,mask,mgtifname,net,tftpserver|{\n \"network1\":{\n \"gateway\":\"9.114.34.254\",\n \"mask\":\"255.255.255.0\",\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -860,9 +862,9 @@ my %URIdef = ( desc => "Change attributes for the network {netname}. DataBody: {attr1:v1,att2:v2,att3:v3 ...}.", usage => "||An array of network objects.|", example => "|Get the attributes {gateway,mask,mgtifname,net,tftpserver} for networks network1|GET|/networks/network1/attrs/gateway;mask;net||", - cmd => "chdef", + cmd => "chdef", fhandler => \&noout, - } + } }, }, @@ -870,39 +872,41 @@ my %URIdef = ( #### definition for osimage resources osimages => { osimage => { - desc => "[URI:/osimages] - The osimage resource.", + desc => "[URI:/osimages] - The osimage resource.", matcher => '^\/osimages$', - GET => { - desc => "Get all the osimage in xCAT.", + GET => { + desc => "Get all the osimage in xCAT.", usage => "||Json format: An array of osimage names.|", example => "|Get all the osimage names.|GET|/osimages|[\n \"sles11.2-x86_64-install-compute\",\n \"sles11.2-x86_64-install-iscsi\",\n \"sles11.2-x86_64-install-iscsiibft\",\n \"sles11.2-x86_64-install-service\"\n]|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout_remove_appended_type, }, POST => { desc => "Create the osimage resources base on the parameters specified in the Data body.", + #usage => "|$usagemsg{objchparam} DataBody: {iso:isoname\\file:filename\\node:noderange,params:[{attr1:value1,attr2:value2}]}|$usagemsg{non_getreturn}|", usage => "|$usagemsg{objchparam} DataBody: {iso:isoname\\file:filename,params:[{attr1:value1,attr2:value2}]}|$usagemsg{non_getreturn}|", example1 => "|Create osimage resources based on the ISO specified|POST|/osimages {\"iso\":\"/iso/RHEL6.4-20130130.0-Server-ppc64-DVD1.iso\"}||", example2 => "|Create osimage resources based on an xCAT image or configuration file|POST|/osimages {\"file\":\"/tmp/sles11.2-x86_64-install-compute.tgz\"}||", + # TD: the imgcapture need to be moved to nodes/.*/osimages # example3 => "|Create a image based on the specified Linux diskful node|POST|/osimages {\"node\":\"rhcn1\"}||", - cmd => "copycds", + cmd => "copycds", fhandler => \&imgophdl, outhdler => \&noout, }, }, osimage_allattr => { - desc => "[URI:/osimages/{imgname}] - The osimage resource", + desc => "[URI:/osimages/{imgname}] - The osimage resource", matcher => '^\/osimages\/[^\/]*$', - GET => { + GET => { desc => "Get all the attibutes for the osimage {imgname}.", desc1 => "The keyword ALLRESOURCES can be used as {imgname} which means to get image attributes for all the osimages.", usage => "||$usagemsg{objreturn}|", example => "|Get the attributes for the specified osimage.|GET|/osimages/sles11.2-x86_64-install-compute|{\n \"sles11.2-x86_64-install-compute\":{\n \"provmethod\":\"install\",\n \"profile\":\"compute\",\n \"template\":\"/opt/xcat/share/xcat/install/sles/compute.sles11.tmpl\",\n \"pkglist\":\"/opt/xcat/share/xcat/install/sles/compute.sles11.pkglist\",\n \"osvers\":\"sles11.2\",\n \"osarch\":\"x86_64\",\n \"osname\":\"Linux\",\n \"imagetype\":\"linux\",\n \"otherpkgdir\":\"/install/post/otherpkgs/sles11.2/x86_64\",\n \"osdistroname\":\"sles11.2-x86_64\",\n \"pkgdir\":\"/install/sles11.2/x86_64\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -911,7 +915,7 @@ my %URIdef = ( desc => "Create the osimage {imgname}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,attr2:v2]|$usagemsg{non_getreturn}|", example => "|Create a osimage obj with the specified parameters.|POST|/osimages/sles11.3-ppc64-install-compute {\"osvers\":\"sles11.3\",\"osarch\":\"ppc64\",\"osname\":\"Linux\",\"provmethod\":\"install\",\"profile\":\"compute\"}||", - cmd => "mkdef", + cmd => "mkdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -919,15 +923,15 @@ my %URIdef = ( desc => "Change the attibutes for the osimage {imgname}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,attr2:v2...}|$usagemsg{non_getreturn}|", example => "|Change the 'osvers' and 'osarch' attributes for the osiamge.|PUT|/osimages/sles11.2-ppc64-install-compute/ {\"osvers\":\"sles11.3\",\"osarch\":\"x86_64\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the osimage {imgname}.", + desc => "Remove the osimage {imgname}.", usage => "||$usagemsg{non_getreturn}|", example => "|Delete the specified osimage.|DELETE|/osimages/sles11.3-ppc64-install-compute||", - cmd => "rmdef", + cmd => "rmdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -935,21 +939,22 @@ my %URIdef = ( osimage_attr => { desc => "[URI:/osimages/{imgname}/attrs/attr1,attr2,attr3 ...] - The attributes resource for the osimage {imgname}", matcher => '^\/osimages\/[^\/]*/attrs/\S+$', - GET => { + GET => { desc => "Get the specific attributes for the osimage {imgname}.", desc1 => "The keyword ALLRESOURCES can be used as {imgname} which means to get image attributes for all the osimages.", usage => "||Json format: An array of attr:value pairs for the specified osimage.|", example => "|Get the specified attributes.|GET|/osimages/sles11.2-ppc64-install-compute/attrs/imagetype,osarch,osname,provmethod|{\n \"sles11.2-ppc64-install-compute\":{\n \"provmethod\":\"install\",\n \"osname\":\"Linux\",\n \"osarch\":\"ppc64\",\n \"imagetype\":\"linux\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, + # TD, the implementation may need to be change. PUT_backup => { desc => "Change the attibutes for the osimage {imgname}.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,attr2:v2...}|$usagemsg{non_getreturn}|", example => "|Change the 'osvers' and 'osarch' attributes for the osiamge.|PUT|/osimages/sles11.2-ppc64-install-compute/attrs/osvers;osarch {\"osvers\":\"sles11.3\",\"osarch\":\"x86_64\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -958,20 +963,20 @@ my %URIdef = ( osimage_op => { desc => "[URI:/osimages/{imgname}/instance] - The instance for the osimage {imgname}", matcher => '^\/osimages\/[^\/]*/instance$', - POST => { + POST => { desc => "Operate the instance of the osimage {imgname}.", usage => "|$usagemsg{objchparam} DataBody: {action:gen\\pack\\export,params:[{attr1:value1,attr2:value2...}]}|$usagemsg{non_getreturn}|", example1 => "|Generates a stateless image based on the specified osimage|POST|/osimages/sles11.2-x86_64-install-compute/instance {\"action\":\"gen\"}||", example2 => "|Packs the stateless image from the chroot file system based on the specified osimage|POST|/osimages/sles11.2-x86_64-install-compute/instance {\"action\":\"pack\"}||", example3 => "|Exports an xCAT image based on the specified osimage|POST|/osimages/sles11.2-x86_64-install-compute/instance {\"action\":\"export\"}||", - cmd => "", + cmd => "", fhandler => \&imgophdl, }, DELETE => { desc => "Delete the stateless or statelite image instance for the osimage {imgname} from the file system", usage => "||$usagemsg{non_getreturn}", example => "|Delete the stateless image for the specified osimage|DELETE|/osimages/sles11.2-x86_64-install-compute/instance||", - cmd => "rmimage", + cmd => "rmimage", fhandler => \&imgophdl, }, }, @@ -982,28 +987,28 @@ my %URIdef = ( #### definition for policy resources policy => { policy => { - desc => "[URI:/policy] - The policy resource.", + desc => "[URI:/policy] - The policy resource.", matcher => '^\/policy$', - GET => { - desc => "Get all the policies in xCAT.", + GET => { + desc => "Get all the policies in xCAT.", desc1 => "It will dislplay all the policy resource.", usage => "||$usagemsg{objreturn}|", example => "|Get all the policy objects.|GET|/policy|[\n \"1\",\n \"1.2\",\n \"2\",\n \"4.8\"\n]|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout_remove_appended_type, }, }, policy_allattr => { - desc => "[URI:/policy/{policy_priority}] - The policy resource", + desc => "[URI:/policy/{policy_priority}] - The policy resource", matcher => '^\/policy\/[^\/]*$', - GET => { + GET => { desc => "Get all the attibutes for a policy {policy_priority}.", desc1 => "It will display all the policy attributes for one policy resource.", desc2 => "The keyword ALLRESOURCES can be used as {policy_priority} which means to get policy attributes for all the policies.", usage => "||$usagemsg{objreturn}|", example => "|Get all the attribute for policy 1.|GET|/policy/1|{\n \"1\":{\n \"name\":\"root\",\n \"rule\":\"allow\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -1012,7 +1017,7 @@ my %URIdef = ( desc1 => "It will change one or more attributes for a policy.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Set the name attribute for policy 3.|PUT|/policy/3 {\"name\":\"root\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -1021,16 +1026,16 @@ my %URIdef = ( desc1 => "It will creat a new policy resource.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Create a new policy 10.|POST|/policy/10 {\"name\":\"root\",\"commands\":\"rpower\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&defhdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the policy {policy_priority}.", - desc1 => "Remove one or more policy resource.", - usage => "||$usagemsg{non_getreturn}|", - example => "|Delete the policy 10.|DELETE|/policy/10||", - cmd => "rmdef", + desc => "Remove the policy {policy_priority}.", + desc1 => "Remove one or more policy resource.", + usage => "||$usagemsg{non_getreturn}|", + example => "|Delete the policy 10.|DELETE|/policy/10||", + cmd => "rmdef", fhandler => \&defhdl, outhdler => \&noout, }, @@ -1038,13 +1043,13 @@ my %URIdef = ( policy_attr => { desc => "[URI:/policy/{policyname}/attrs/{attr1,attr2,attr3,...}] - The attributes resource for the policy {policy_priority}", matcher => '^\/policy\/[^\/]*/attrs/\S+$', - GET => { + GET => { desc => "Get the specific attributes for the policy {policy_priority}.", desc1 => "It will get one or more attributes of a policy.", desc2 => "The keyword ALLRESOURCES can be used as {policy_priority} which means to get policy attributes for all the policies.", usage => "||$usagemsg{objreturn}|", example => "|Get the name and rule attributes for policy 1.|GET|/policy/1/attrs/name,rule|{\n \"1\":{\n \"name\":\"root\",\n \"rule\":\"allow\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&defhdl, outhdler => \&defout, }, @@ -1056,12 +1061,12 @@ my %URIdef = ( desc => "[URI:/globalconf] - The global configuration resource.", desc1 => "This resource can be used to display all the global configuration which have been defined in the xCAT database.", matcher => '^\/globalconf$', - GET => { - desc => "Get all the xCAT global configuration.", - desc1=> "It will display all the global attributes.", + GET => { + desc => "Get all the xCAT global configuration.", + desc1 => "It will display all the global attributes.", usage => "||$usagemsg{objreturn}|", example => "|Get all the global configuration|GET|/globalconf|{\n \"clustersite\":{\n \"xcatconfdir\":\"/etc/xcat\",\n \"tftpdir\":\"/tftpboot\",\n ...\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&sitehdl, outhdler => \&defout, }, @@ -1070,19 +1075,19 @@ my %URIdef = ( desc1 => "One or more global attributes could be added/modified.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Add one or more attributes to xCAT database|POST|/globalconf {\"domain\":\"cluster.com\",\"mydomain\":\"mycluster.com\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&sitehdl, }, }, site => { desc => "[URI:/globalconf/attrs/{attr1,attr2 ...}] - The specific global configuration resource.", matcher => '^\/globalconf/attrs/\S+$', - GET => { - desc => "Get the specific configuration in global.", + GET => { + desc => "Get the specific configuration in global.", desc1 => "It will display one or more global attributes.", usage => "||$usagemsg{objreturn}|", example => "|Get the \'master\' and \'domain\' configuration.|GET|/globalconf/attrs/master,domain|{\n \"clustersite\":{\n \"domain\":\"cluster.com\",\n \"master\":\"192.168.1.15\"\n }\n}|", - cmd => "lsdef", + cmd => "lsdef", fhandler => \&sitehdl, outhdler => \&defout, }, @@ -1091,7 +1096,7 @@ my %URIdef = ( desc1 => "It can be used for changing/adding global attributes.", usage => "|$usagemsg{objchparam} DataBody: {attr1:v1,att2:v2,...}.|$usagemsg{non_getreturn}|", example => "|Change/Add the domain attribute.|PUT|/globalconf/attrs/domain {\"domain\":\"cluster.com\"}||", - cmd => "chdef", + cmd => "chdef", fhandler => \&sitehdl, outhdler => \&noout, }, @@ -1099,16 +1104,16 @@ my %URIdef = ( desc => "Create the global configuration entry. DataBody: {name:value}.", usage => "||$usagemsg{non_getreturn}|", example => "|Create the domain attribute|POST|/globalconf/attrs/domain {\"domain\":\"cluster.com\"}|?|", - cmd => "chdef", + cmd => "chdef", fhandler => \&sitehdl, outhdler => \&noout, }, DELETE => { - desc => "Remove the site attributes.", + desc => "Remove the site attributes.", desc1 => "Used for femove one or more global attributes.", usage => "||$usagemsg{non_getreturn}|", example => "|Remove the domain configure.|DELETE|/globalconf/attrs/domain||", - cmd => "chdef", + cmd => "chdef", fhandler => \&sitehdl, outhdler => \&noout, }, @@ -1121,10 +1126,10 @@ my %URIdef = ( desc => "[URI:/tables/{tablelist}/nodes/{noderange}] - The node table resource", desc1 => "For a large number of nodes, this API call can be faster than using the corresponding nodes resource. The disadvantage is that you need to know the table names the attributes are stored in.", matcher => '^/tables/[^/]+/nodes/[^/]+$', - GET => { + GET => { desc => "Get attibutes of tables for a noderange.", usage => "||An object containing each table. Within each table object is an array of node objects containing the attributes.|", - example1 => qq(|Get all the columns from table nodetype for node1 and node2.|GET|/tables/nodetype/nodes/node1,node2|{\n \"nodetype\":[\n {\n \"provmethod\":\"rhels6.4-x86_64-install-compute\",\n \"profile\":\"compute\",\n \"arch\":\"x86_64\",\n \"name\":\"node1\",\n \"os\":\"rhels6.4\"\n },\n {\n \"provmethod\":\"rhels6.3-x86_64-install-compute\",\n \"profile\":\"compute\",\n \"arch\":\"x86_64\",\n \"name\":\"node2\",\n \"os\":\"rhels6.3\"\n }\n ]\n}|), + example1 => qq(|Get all the columns from table nodetype for node1 and node2.|GET|/tables/nodetype/nodes/node1,node2|{\n \"nodetype\":[\n {\n \"provmethod\":\"rhels6.4-x86_64-install-compute\",\n \"profile\":\"compute\",\n \"arch\":\"x86_64\",\n \"name\":\"node1\",\n \"os\":\"rhels6.4\"\n },\n {\n \"provmethod\":\"rhels6.3-x86_64-install-compute\",\n \"profile\":\"compute\",\n \"arch\":\"x86_64\",\n \"name\":\"node2\",\n \"os\":\"rhels6.3\"\n }\n ]\n}|), example2 => qq(|Get all the columns from tables nodetype and noderes for node1 and node2.|GET|/tables/nodetype,noderes/nodes/node1,node2|{\n \"noderes\":[\n {\n \"installnic\":\"mac\",\n \"netboot\":\"xnba\",\n \"name\":\"node1\",\n \"nfsserver\":\"192.168.1.15\"\n },\n {\n \"installnic\":\"mac\",\n \"netboot\":\"pxe\",\n \"name\":\"node2\",\n \"proxydhcp\":\"no\"\n }\n ],\n \"nodetype\":[\n {\n \"provmethod\":\"rhels6.4-x86_64-install-compute\",\n \"profile\":\"compute\",\n \"arch\":\"x86_64\",\n \"name\":\"node1\",\n \"os\":\"rhels6.4\"\n },\n {\n \"provmethod\":\"rhels6.3-x86_64-install-compute\",\n \"profile\":\"compute\",\n \"arch\":\"x86_64\",\n \"name\":\"node2\",\n \"os\":\"rhels6.3\"\n }\n ]\n}|), fhandler => \&tablenodehdl, outhdler => \&tableout, @@ -1141,7 +1146,7 @@ my %URIdef = ( desc => "[URI:/tables/{tablelist}/nodes/nodes/{noderange}/{attrlist}] - The node table attributes resource", desc1 => "For a large number of nodes, this API call can be faster than using the corresponding nodes resource. The disadvantage is that you need to know the table names the attributes are stored in.", matcher => '^/tables/[^/]+/nodes/[^/]+/[^/]+$', - GET => { + GET => { desc => "Get table attibutes for a noderange.", usage => "||An object containing each table. Within each table object is an array of node objects containing the attributes.|", example => qq(|Get OS and ARCH attributes from nodetype table for node1 and node2.|GET|/tables/nodetype/nodes/node1,node2/os,arch|{\n \"nodetype\":[\n {\n \"arch\":\"x86_64\",\n \"name\":\"node1\",\n \"os\":\"rhels6.4\"\n },\n {\n \"arch\":\"x86_64\",\n \"name\":\"node2\",\n \"os\":\"rhels6.3\"\n }\n ]\n}|), @@ -1160,7 +1165,7 @@ my %URIdef = ( desc => "[URI:/tables/{tablelist}/rows] - The non-node table resource", desc1 => "Use this for tables that don't have node name as the key of the table, for example: passwd, site, networks, polciy, etc.", matcher => '^/tables/[^/]+/rows$', - GET => { + GET => { desc => "Get all rows from non-node tables.", usage => "||An object containing each table. Within each table object is an array of row objects containing the attributes.|", example => qq(|Get all rows from networks table.|GET|/tables/networks/rows|{\n \"networks\":[\n {\n \"netname\":\"192_168_13_0-255_255_255_0\",\n \"gateway\":\"192.168.13.254\",\n \"staticrangeincrement\":\"1\",\n \"net\":\"192.168.13.0\",\n \"mask\":\"255.255.255.0\"\n },\n {\n \"netname\":\"192_168_12_0-255_255_255_0\",\n \"gateway\":\"192.168.12.254\",\n \"staticrangeincrement\":\"1\",\n \"net\":\"192.168.12.0\",\n \"mask\":\"255.255.255.0\"\n },\n ]\n}|), @@ -1173,7 +1178,7 @@ my %URIdef = ( desc1 => "Use this for tables that don't have node name as the key of the table, for example: passwd, site, networks, polciy, etc.", desc2 => "{keys} should be the name=value pairs which are used to search table. e.g. {keys} should be [net=192.168.1.0,mask=255.255.255.0] for networks table query since the net and mask are the keys of networks table.", matcher => '^/tables/[^/]+/rows/[^/]+$', - GET => { + GET => { desc => "Get attibutes for rows from non-node tables.", usage => "||An object containing each table. Within each table object is an array of row objects containing the attributes.|", example => qq(|Get row which net=192.168.1.0,mask=255.255.255.0 from networks table.|GET|/tables/networks/rows/net=192.168.1.0,mask=255.255.255.0|{\n \"networks\":[\n {\n \"mgtifname\":\"eth0\",\n \"netname\":\"192_168_1_0-255_255_255_0\",\n \"tftpserver\":\"192.168.1.15\",\n \"gateway\":\"192.168.1.100\",\n \"staticrangeincrement\":\"1\",\n \"net\":\"192.168.1.0\",\n \"mask\":\"255.255.255.0\"\n }\n ]\n}|), @@ -1199,7 +1204,7 @@ my %URIdef = ( desc => "[URI:/tables/{tablelist}/rows/{keys}/{attrlist}] - The non-node table attributes resource", desc1 => "Use this for tables that don't have node name as the key of the table, for example: passwd, site, networks, polciy, etc.", matcher => '^/tables/[^/]+/rows/[^/]+/[^/]+$', - GET => { + GET => { desc => "Get specific attibutes for rows from non-node tables.", usage => "||An object containing each table. Within each table object is an array of row objects containing the attributes.|", example => qq(|Get attributes mgtifname and tftpserver which net=192.168.1.0,mask=255.255.255.0 from networks table.|GET|/tables/networks/rows/net=192.168.1.0,mask=255.255.255.0/mgtifname,tftpserver|{\n \"networks\":[\n {\n \"mgtifname\":\"eth0\",\n \"tftpserver\":\"192.168.1.15\"\n }\n ]\n}|), @@ -1212,10 +1217,10 @@ my %URIdef = ( #### definition for tokens resources tokens => { tokens => { - desc => "[URI:/tokens] - The authentication token resource.", + desc => "[URI:/tokens] - The authentication token resource.", matcher => '^\/tokens', - POST => { - desc => "Create a token.", + POST => { + desc => "Create a token.", usage => "||An array of all the global configuration list.|", example => "|Aquire a token for user \'root\'.|POST|/tokens {\"userName\":\"root\",\"userPW\":\"cluster\"}|{\n \"token\":{\n \"id\":\"a6e89b59-2b23-429a-b3fe-d16807dd19eb\",\n \"expire\":\"2014-3-8 14:55:0\"\n }\n}|", fhandler => \&nonobjhdl, @@ -1223,36 +1228,37 @@ my %URIdef = ( }, POST_backup => { desc => "Add the site attributes. DataBody: {attr1:v1,att2:v2...}.", - usage => "|?|?|", - example => "|?|?|?|?|", - cmd => "chdef", + usage => "|?|?|", + example => "|?|?|?|?|", + cmd => "chdef", fhandler => \&sitehdl, }, }, }, - + ### interface to access local system resource which is not managed by xcat directly ### localres can be looked as a top level non-xcat resource pool ### rest operation will trasfer the target resource to xcatd plugin to handle the non-xcat resource localres => { localres => { - desc => "[URI:/localres/*] - The local non-xcat resource.", + desc => "[URI:/localres/*] - The local non-xcat resource.", matcher => '^/localres(/[^/]*)+$', - GET => { + GET => { desc => "List information for the target system resource.", usage => "||For target resource can match any resource type which can be proccssed by the resthelper plugin.|", example => qq(|List adapters on MN machine|GET|/localres/interface/|{\n \"interfaces\":[\n\"eth0\",\n \"eth1\",\n]"|), - cmd => "localrest", + cmd => "localrest", fhandler => \&localreshdl, outhdler => \&localresout, }, - } - } + } + } ); # supported formats my %formatters = ( 'json' => \&wrapJson, + #'html' => \&wrapHtml, #'xml' => \&wrapXml ); @@ -1298,18 +1304,18 @@ my $STATUS_CREATED = "201 Created"; #### Main procedure to handle the REST request # To get the HTTP elements through perl CGI module -my $q = CGI->new; -my $pathInfo = $q->path_info; # the resource specification, i.e. everything in the url after xcatws +my $q = CGI->new; +my $pathInfo = $q->path_info; # the resource specification, i.e. everything in the url after xcatws my $requestType = $q->request_method(); # GET, PUT, POST, PATCH, DELETE -my $userAgent = $q->user_agent(); # the client program: curl, etc. -my @path = split(/\//, $pathInfo); # The uri path like /nodes/node1/... +my $userAgent = $q->user_agent(); # the client program: curl, etc. +my @path = split(/\//, $pathInfo); # The uri path like /nodes/node1/... # Define the golbal variables which will be used through the handling process -my $pageContent = ''; # Global var containing the ouptut back to the rest client -my %header_info; #Global var containing the extra info to the http header -my $request = {clienttype => 'ws'}; # Global var that holds the request to send to xcatd -my $format = 'json'; # The output format for a request invoke -my $xmlinstalled; # Global var to speicfy whether the xml modules have been loaded +my $pageContent = ''; # Global var containing the ouptut back to the rest client +my %header_info; #Global var containing the extra info to the http header +my $request = { clienttype => 'ws' }; # Global var that holds the request to send to xcatd +my $format = 'json'; # The output format for a request invoke +my $xmlinstalled; # Global var to speicfy whether the xml modules have been loaded # To easy the perl debug, this script can be run directly with 'perl -d' # This script also support to generate the rest api doc automatically. @@ -1318,12 +1324,13 @@ my $dbgdata; sub dbgusage { print "Usage:\n $0 -h\n $0 -g rst > ../../docs/source/advanced/restapi/restapi_resource/restapi_reference.rst (generate document)\n $0 {GET|PUT|POST|DELETE} URI user:password \'{data}\'\n"; } if ($ARGV[0] eq "-h") { - dbgusage(); + dbgusage(); exit 0; } elsif ($ARGV[0] eq "-g") { + # generate the document require genrestapidoc; - if (defined ($ARGV[1])) { + if (defined($ARGV[1])) { genrestapidoc::gendoc(\%URIdef, $ARGV[1]); } else { genrestapidoc::gendoc(\%URIdef); @@ -1333,29 +1340,31 @@ if ($ARGV[0] eq "-h") { displayUsage(); exit 0; } elsif ($ARGV[0] =~ /(GET|PUT|POST|DELETE)/) { + # parse the parameters when run this script locally $requestType = $ARGV[0]; - $pathInfo= $ARGV[1]; + $pathInfo = $ARGV[1]; unless ($pathInfo) { dbgusage(); exit 1; } - + if ($ARGV[2] =~ /(.*):(.*)/) { $ENV{userName} = $1; $ENV{password} = $2; } else { - dbgusage(); + dbgusage(); exit 0; } - $dbgdata = $ARGV[3] if defined ($ARGV[3]); -} elsif (defined ($ARGV[0])) { - dbgusage(); + $dbgdata = $ARGV[3] if defined($ARGV[3]); +} elsif (defined($ARGV[0])) { + dbgusage(); exit 1; } -my $JSON; # global ptr to the json object. Its set by loadJSON() +my $JSON; # global ptr to the json object. Its set by loadJSON() + # Since the json is the only supported format, load it at beginning # need to do this early, so we can fetch the PUT/POST params -loadJSON(); +loadJSON(); # the input parameters from both the url and put/post data will be combined and then # separated into the general params (not specific to the api call) and params specific to the call @@ -1364,16 +1373,16 @@ loadJSON(); # $paramhash - all parameters that come from the url or put/post data except the ones that are put in $generalparams my ($generalparams, $paramhash) = fetchParameters(); -my $DEBUGGING = $generalparams->{debug}; # turn on or off the debugging output by setting debug=1 (or 2) in the url string +my $DEBUGGING = $generalparams->{debug}; # turn on or off the debugging output by setting debug=1 (or 2) in the url string if ($DEBUGGING) { displaydebugmsg(); } -# The filter flag is used to group the nodes which have the same output -my $XCOLL = $generalparams->{xcoll}; +# The filter flag is used to group the nodes which have the same output +my $XCOLL = $generalparams->{xcoll}; # Process the format requested -$format = $generalparams->{format} if (defined ($generalparams->{format})); +$format = $generalparams->{format} if (defined($generalparams->{format})); # Remove the last '/' in the pathInfo $pathInfo =~ s/\/$//; @@ -1399,6 +1408,7 @@ $pathInfo =~ s/\/$//; #} if ($format eq 'json') { + # make the output to be readable if 'pretty=1' is specified if ($generalparams->{pretty}) { $JSON->indent(1); } } @@ -1411,9 +1421,10 @@ my $uriLayer1; # Get all the layers in the URI my @layers = split('\/', $pathInfo); -shift (@layers); +shift(@layers); if ($#layers < 0) { + # If no resource was specified, list all the resource groups which have been defined in the %URIdef my $json; foreach (sort keys %URIdef) { @@ -1422,7 +1433,7 @@ if ($#layers < 0) { if ($json) { addPageContent($JSON->encode($json)); } - sendResponseMsg($STATUS_OK); # this will also exit + sendResponseMsg($STATUS_OK); # this will also exit } else { $uriLayer1 = $layers[0]; } @@ -1439,50 +1450,57 @@ $request->{tokens}->[0]->{tokenid}->[0] = $ENV{'HTTP_X_AUTH_TOKEN'} if (defined( # find and invoke the correct handler and output handler functions my $outputdata; my $handled; -if (defined ($URIdef{$uriLayer1})) { +if (defined($URIdef{$uriLayer1})) { + # Make sure the resource has been defined - foreach my $res (keys %{$URIdef{$uriLayer1}}) { + foreach my $res (keys %{ $URIdef{$uriLayer1} }) { my $matcher = $URIdef{$uriLayer1}->{$res}->{matcher}; if ($pathInfo =~ m|$matcher|) { + # matched to a resource - unless (defined ($URIdef{$uriLayer1}->{$res}->{$requestType})) { - error("request method '$requestType' is not supported on resource '$pathInfo'", $STATUS_NOT_ALLOWED); + unless (defined($URIdef{$uriLayer1}->{$res}->{$requestType})) { + error("request method '$requestType' is not supported on resource '$pathInfo'", $STATUS_NOT_ALLOWED); } - if (defined ($URIdef{$uriLayer1}->{$res}->{$requestType}->{fhandler})) { - my $params; - - $params->{'cmd'} = $URIdef{$uriLayer1}->{$res}->{$requestType}->{cmd} if (defined ($URIdef{$uriLayer1}->{$res}->{$requestType}->{cmd})); - $params->{'outputhdler'} = $URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler} if (defined ($URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler})); - $params->{'layers'} = \@layers; - $params->{'resourcegroup'} = $uriLayer1; - $params->{'resourcename'} = $res; - # Call the handler subroutine which specified in 'fhandler' to send request to xcatd and get the response - $outputdata = $URIdef{$uriLayer1}->{$res}->{$requestType}->{fhandler}->($params); - # Filter the output data from the response - $outputdata = filterData ($outputdata); - # Restructure the output data with the subroutine which is specified in 'outhdler' - if (defined ($URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler})) { - $outputdata = $URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler}->($outputdata, $params); - } else { - # Call the appropriate formatting function stored in the formatters hash as default output handler - if (exists $formatters{$format}) { - $formatters{$format}->($outputdata); - } - } - - $handled = 1; - last; + if (defined($URIdef{$uriLayer1}->{$res}->{$requestType}->{fhandler})) { + my $params; + + $params->{'cmd'} = $URIdef{$uriLayer1}->{$res}->{$requestType}->{cmd} if (defined($URIdef{$uriLayer1}->{$res}->{$requestType}->{cmd})); + $params->{'outputhdler'} = $URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler} if (defined($URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler})); + $params->{'layers'} = \@layers; + $params->{'resourcegroup'} = $uriLayer1; + $params->{'resourcename'} = $res; + + # Call the handler subroutine which specified in 'fhandler' to send request to xcatd and get the response + $outputdata = $URIdef{$uriLayer1}->{$res}->{$requestType}->{fhandler}->($params); + + # Filter the output data from the response + $outputdata = filterData($outputdata); + + # Restructure the output data with the subroutine which is specified in 'outhdler' + if (defined($URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler})) { + $outputdata = $URIdef{$uriLayer1}->{$res}->{$requestType}->{outhdler}->($outputdata, $params); + } else { + + # Call the appropriate formatting function stored in the formatters hash as default output handler + if (exists $formatters{$format}) { + $formatters{$format}->($outputdata); + } + } + + $handled = 1; + last; } } } } else { + # not matches to any resource group. Check the 'resource group' to improve the performance - error("Unspported resource.",$STATUS_NOT_FOUND); + error("Unspported resource.", $STATUS_NOT_FOUND); } # the URI cannot match to any resources which are defined in %URIdef unless ($handled) { - error("Unspported resource.",$STATUS_NOT_FOUND); + error("Unspported resource.", $STATUS_NOT_FOUND); } @@ -1502,19 +1520,19 @@ else { #=========================================================== -# Subrutines -sub isGET { return uc($requestType) eq "GET"; } -sub isPost { return uc($requestType) eq "POST"; } -sub isPut { return uc($requestType) eq "PUT"; } -sub isPost { return uc($requestType) eq "POST"; } -sub isPatch { return uc($requestType) eq "PATCH"; } +# Subrutines +sub isGET { return uc($requestType) eq "GET"; } +sub isPost { return uc($requestType) eq "POST"; } +sub isPut { return uc($requestType) eq "PUT"; } +sub isPost { return uc($requestType) eq "POST"; } +sub isPatch { return uc($requestType) eq "PATCH"; } sub isDelete { return uc($requestType) eq "DELETE"; } -#handle the output for def command and rscan -#handle the input like +#handle the output for def command and rscan +#handle the input like # ===raw xml input -# $d->{info}->[msg list] - each msg could be mulitple msg which split with '\n' +# $d->{info}->[msg list] - each msg could be mulitple msg which split with '\n' # $d->{data}->[msg list] # # ===msg format @@ -1538,14 +1556,14 @@ sub defout { my $nodename; my $lines; my @alldata; - if (defined ($d->{info})) { - foreach (@{$d->{info}}) { - push @alldata, split ('\n', $_); + if (defined($d->{info})) { + foreach (@{ $d->{info} }) { + push @alldata, split('\n', $_); } $lines = \@alldata; - } elsif (defined ($d->{data})) { - foreach (@{$d->{data}}) { - push @alldata, split ('\n', $_); + } elsif (defined($d->{data})) { + foreach (@{ $d->{data} }) { + push @alldata, split('\n', $_); } $lines = \@alldata; } @@ -1557,15 +1575,15 @@ sub defout { last; } if ($l =~ /^Object name: / || $l =~ /^\S+:$/) { # start new node - if ($l =~ /^Object name:\s+(\S+)/) { # handle the output of lsdef -t + if ($l =~ /^Object name:\s+(\S+)/) { # handle the output of lsdef -t $nodename = $1; } - if ($l =~ /^(\S+):$/) { # handle the output for stanza format '-z' + if ($l =~ /^(\S+):$/) { # handle the output for stanza format '-z' $nodename = $1; } } - else { # just an attribute of the current node - if (! $nodename) { error('improperly formatted lsdef output from xcatd', $STATUS_TEAPOT); } + else { # just an attribute of the current node + if (!$nodename) { error('improperly formatted lsdef output from xcatd', $STATUS_TEAPOT); } my ($attr, $val) = $l =~ /^\s*(\S+?)=(.*)$/; if (!defined($attr)) { error('improperly formatted lsdef output from xcatd', $STATUS_TEAPOT); } $json->{$nodename}->{$attr} = $val; @@ -1578,9 +1596,9 @@ sub defout { } #handle the output for lsdef -t command -#handle the input like +#handle the input like # ===raw xml input -# $d->{info}->[msg list] - each msg could be mulitple msg which split with '\n' +# $d->{info}->[msg list] - each msg could be mulitple msg which split with '\n' # # ===msg format # node1 (node) @@ -1657,9 +1675,11 @@ sub defout_remove_appended_info { my $jsonnode; my $lines = $d->{info}; foreach my $l (@$lines) { - # if ($l =~ /^(\S*)\s+\(.*\)$/) { # start new node - push (@{$json}, $l); - # } + + # if ($l =~ /^(\S*)\s+\(.*\)$/) { # start new node + push(@{$json}, $l); + + # } } } if ($json) { @@ -1681,9 +1701,9 @@ sub localresout { } # hanlde the output which has the node irrelevant message (e.g. the output for updatenode command) -# handle the input like +# handle the input like # ===raw xml input -# $d->{info}->[msg list] - each msg could be mulitple msg which split with '\n' +# $d->{info}->[msg list] - each msg could be mulitple msg which split with '\n' # $d->{data}->[msg list] # $d->{data}->{contents}->[msg list] # @@ -1704,29 +1724,29 @@ sub localresout { # the msg with the name in the head. sub infoout { - my $data = shift; - my $param =shift; + my $data = shift; + my $param = shift; my $json; foreach my $d (@$data) { - if (defined ($d->{info})) { - foreach (@{$d->{info}}) { - push @{$json}, split ('\n', $_); + if (defined($d->{info})) { + foreach (@{ $d->{info} }) { + push @{$json}, split('\n', $_); } } - if (defined ($d->{data})) { + if (defined($d->{data})) { if (ref($d->{data}->[0]) ne "HASH") { - foreach (@{$d->{data}}) { - push @{$json}, split ('\n', $_); + foreach (@{ $d->{data} }) { + push @{$json}, split('\n', $_); } } else { if (defined($d->{data}->[0]->{contents})) { - push @{$json}, @{$d->{data}->[0]->{contents}}; + push @{$json}, @{ $d->{data}->[0]->{contents} }; } } } - if (defined ($d->{error})) { - push @{$json}, @{$d->{error}}; + if (defined($d->{error})) { + push @{$json}, @{ $d->{error} }; } } @@ -1735,12 +1755,12 @@ sub infoout { my $jsonnode; foreach (@{$json}) { if (/^(\S+):(.*)$/) { - push @{$jsonnode->{$1}}, $2 if ($2 !~ /^\s*$/); + push @{ $jsonnode->{$1} }, $2 if ($2 !~ /^\s*$/); } } if (!$jsonnode && $json) { - push (@{$jsonnode},@{$json}); + push(@{$jsonnode}, @{$json}); } addPageContent($JSON->encode($jsonnode), 1); return; @@ -1752,7 +1772,7 @@ sub infoout { # hanlde the output which is node relevant (rpower, rinv, rvitals ...) # the output must be grouped with 'node' as key -# handle the input like +# handle the input like # ===raw xml input # $d->{node}->{name}->[name] # this is must have, otherwise ignore the msg # $d->{node}->{data}->[msg] @@ -1784,41 +1804,45 @@ sub infoout { # } # } sub actionout { - my $data = shift; - my $param =shift; + my $data = shift; + my $param = shift; my $jsonnode; foreach my $d (@$data) { - unless (defined ($d->{node}->[0]->{name})) { + unless (defined($d->{node}->[0]->{name})) { next; } - if (defined ($d->{node}->[0]->{data}) && (ref($d->{node}->[0]->{data}->[0]) ne "HASH" || ! defined($d->{node}->[0]->{data}->[0]->{contents}))) { + if (defined($d->{node}->[0]->{data}) && (ref($d->{node}->[0]->{data}->[0]) ne "HASH" || !defined($d->{node}->[0]->{data}->[0]->{contents}))) { + # no $d->{node}->{data}->{contents} or $d->{node}->[0]->{data} is not hash - $jsonnode->{$d->{node}->[0]->{name}->[0]}->{$param->{'resourcename'}} = $d->{node}->[0]->{data}->[0]; - } elsif (defined ($d->{node}->[0]->{data}->[0]->{contents})) { + $jsonnode->{ $d->{node}->[0]->{name}->[0] }->{ $param->{'resourcename'} } = $d->{node}->[0]->{data}->[0]; + } elsif (defined($d->{node}->[0]->{data}->[0]->{contents})) { if (defined($d->{node}->[0]->{data}->[0]->{desc})) { + # has $d->{node}->{data}->{desc} - $jsonnode->{$d->{node}->[0]->{name}->[0]}->{$d->{node}->[0]->{data}->[0]->{desc}->[0]} = $d->{node}->[0]->{data}->[0]->{contents}->[0]; + $jsonnode->{ $d->{node}->[0]->{name}->[0] }->{ $d->{node}->[0]->{data}->[0]->{desc}->[0] } = $d->{node}->[0]->{data}->[0]->{contents}->[0]; } else { + # use resourcename as the record name if ($param->{'resourcename'} eq "eventlog") { - push @{$jsonnode->{$d->{node}->[0]->{name}->[0]}->{$param->{'resourcename'}}}, $d->{node}->[0]->{data}->[0]->{contents}->[0]; + push @{ $jsonnode->{ $d->{node}->[0]->{name}->[0] }->{ $param->{'resourcename'} } }, $d->{node}->[0]->{data}->[0]->{contents}->[0]; } elsif ($param->{'resourcename'} =~ /(vitals|inventory)/) { + # handle output of rvital and rinv for ppc node #push @{$jsonnode->{$d->{node}->[0]->{name}->[0]}}, $d->{node}->[0]->{data}->[0]->{contents}->[0]; - push @{$jsonnode->{$d->{node}->[0]->{name}->[0]}->{Message}}, $d->{node}->[0]->{data}->[0]->{contents}->[0]; + push @{ $jsonnode->{ $d->{node}->[0]->{name}->[0] }->{Message} }, $d->{node}->[0]->{data}->[0]->{contents}->[0]; } else { - $jsonnode->{$d->{node}->[0]->{name}->[0]}->{$param->{'resourcename'}} = $d->{node}->[0]->{data}->[0]->{contents}->[0]; + $jsonnode->{ $d->{node}->[0]->{name}->[0] }->{ $param->{'resourcename'} } = $d->{node}->[0]->{data}->[0]->{contents}->[0]; } } - } + } } addPageContent($JSON->encode($jsonnode), 1) if ($jsonnode); } # hanlde the output which has the token id -# handle the input like +# handle the input like # ===raw xml input # $d->{data}->{token}->{id} # $d->{data}->{token}->{expire} @@ -1827,7 +1851,7 @@ sub tokenout { my $json; foreach my $d (@$data) { - if (defined ($d->{data}) && defined ($d->{data}->[0]->{token})) { + if (defined($d->{data}) && defined($d->{data}->[0]->{token})) { $json->{token}->{id} = $d->{data}->[0]->{token}->[0]->{id}->[0]; $json->{token}->{expire} = $d->{data}->[0]->{token}->[0]->{expire}->[0]; } @@ -1854,7 +1878,7 @@ sub noout { } addPageContent(qq(["Debug: the operation has been done successfully"])); -### finish the debugging +### finish the debugging } # The operation callback subroutine for def related resource (lsdef, chdef ...) @@ -1863,21 +1887,21 @@ sub defhdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; # set the command name $request->{command} = $params->{'cmd'}; # push the -t args for *def command my $resrctype = $params->{'resourcegroup'}; - $resrctype =~ s/s$//; # remove the last 's' as the type of object + $resrctype =~ s/s$//; # remove the last 's' as the type of object push @args, ('-t', $resrctype); # push the object name - node/noderange - if (defined ($urilayers[1])) { + if (defined($urilayers[1])) { if ($urilayers[1] eq "ALLRESOURCES") { unless (isGET()) { - error("Keyword ALLRESOURCES is only supported for GET Action.",$STATUS_NOT_FOUND); + error("Keyword ALLRESOURCES is only supported for GET Action.", $STATUS_NOT_FOUND); } push @args, '-l'; } else { @@ -1888,23 +1912,24 @@ sub defhdl { # For the put/post which specifies attributes like mgt=ipmi groups=all foreach my $k (keys(%$paramhash)) { push @args, "$k=$paramhash->{$k}" if ($k); - } - + } + if ($params->{'resourcename'} eq "allnode") { push @args, '-s'; } elsif ($params->{'resourcename'} =~ /(nodeattr|osimage_attr|group_attr|policy_attr|network_attr)/) { - # if /nodes/node1/attrs/attr1,att2 is specified, for get request, + + # if /nodes/node1/attrs/attr1,att2 is specified, for get request, # use 'lsdef -i' to specify the attribute list my $attrs = $urilayers[3]; $attrs =~ s/;/,/g; if (isGET()) { push @args, ('-i', $attrs); - } + } } - push @{$request->{arg}}, @args; - my $req = genRequest(); + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; @@ -1916,13 +1941,13 @@ sub actionhdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; # set the command name $request->{command} = $params->{'cmd'}; # push the object name - node/noderange - if (defined ($urilayers[1])) { + if (defined($urilayers[1])) { $request->{noderange} = $urilayers[1]; } @@ -1930,12 +1955,13 @@ sub actionhdl { if (isGET()) { push @args, 'stat'; } elsif ($paramhash->{'action'}) { + #my @v = keys(%$paramhash); push @args, $paramhash->{'action'}; } else { - error("Missed Action.",$STATUS_NOT_FOUND); + error("Missed Action.", $STATUS_NOT_FOUND); } - } elsif ($params->{'resourcename'} =~ /(energy|energyattr)/) { + } elsif ($params->{'resourcename'} =~ /(energy|energyattr)/) { if (isGET()) { if ($params->{'resourcename'} eq "energy") { push @args, 'all'; @@ -1947,9 +1973,9 @@ sub actionhdl { my @params = keys(%$paramhash); push @args, "$params[0]=$paramhash->{$params[0]}"; } else { - error("Missed Action.",$STATUS_NOT_FOUND); + error("Missed Action.", $STATUS_NOT_FOUND); } - } elsif ($params->{'resourcename'}eq "bootstate") { + } elsif ($params->{'resourcename'} eq "bootstate") { if (isGET()) { push @args, 'stat'; } elsif ($paramhash->{'action'}) { @@ -1957,28 +1983,30 @@ sub actionhdl { } elsif ($paramhash) { my @params = keys(%$paramhash); if ($params[0] eq "state") { + # hanlde the {state:offline} - push @args, $paramhash->{$params[0]}; + push @args, $paramhash->{ $params[0] }; } else { + # handle the {osimage:imagename} push @args, "$params[0]=$paramhash->{$params[0]}"; } } else { - error("Missed Action.",$STATUS_NOT_FOUND); + error("Missed Action.", $STATUS_NOT_FOUND); } - } elsif ($params->{'resourcename'} eq "nextboot") { + } elsif ($params->{'resourcename'} eq "nextboot") { if (isGET()) { push @args, 'stat'; } elsif ($paramhash->{'order'}) { push @args, $paramhash->{'order'}; } else { - error("Missed Action.",$STATUS_NOT_FOUND); + error("Missed Action.", $STATUS_NOT_FOUND); } } elsif ($params->{'resourcename'} =~ /(vitals|vitalsattr|inventory|inventoryattr)/) { if (defined($urilayers[3])) { my @attrs = split(';', $urilayers[3]); push @args, @attrs; - } else { # default, get all attrs + } else { # default, get all attrs push @args, "all"; } } elsif ($params->{'resourcename'} eq "serviceprocessor") { @@ -1986,11 +2014,11 @@ sub actionhdl { push @args, $urilayers[3]; } elsif (isPut() or isPost()) { if ($paramhash->{'value'} and defined($urilayers[3])) { - push @args, $urilayers[3]."=".$paramhash->{'value'}; + push @args, $urilayers[3] . "=" . $paramhash->{'value'}; } else { foreach my $key (keys %$paramhash) { if (($key ne '') and (exists($paramhash->{$key}))) { - push @args, $key."=".$paramhash->{$key}; + push @args, $key . "=" . $paramhash->{$key}; } } } @@ -2011,48 +2039,48 @@ sub actionhdl { push @args, '-S'; } elsif ($params->{'resourcename'} eq "postscript") { push @args, '-P'; - if (defined ($paramhash->{'scripts'})) { - push @args, join (',', @{$paramhash->{'scripts'}}); + if (defined($paramhash->{'scripts'})) { + push @args, join(',', @{ $paramhash->{'scripts'} }); } } elsif ($params->{'resourcename'} eq "nodeshell") { - if(%$paramhash) + if (%$paramhash) { - foreach my $key1 (keys %$paramhash) { - if ( $key1 eq "ENV" && defined ($paramhash->{'ENV'})) { - foreach my $key (keys %{$paramhash->{'ENV'}}) { - if (($key ne '') and (exists($paramhash->{'ENV'}->{$key}))) { - push (@{$request->{env}},"$key=$paramhash->{'ENV'}->{$key}"); - } - } - next; + foreach my $key1 (keys %$paramhash) { + if ($key1 eq "ENV" && defined($paramhash->{'ENV'})) { + foreach my $key (keys %{ $paramhash->{'ENV'} }) { + if (($key ne '') and (exists($paramhash->{'ENV'}->{$key}))) { + push(@{ $request->{env} }, "$key=$paramhash->{'ENV'}->{$key}"); + } + } + next; + } + elsif ($key1 eq "raw" && defined($paramhash->{'raw'})) { + if (ref($paramhash->{'raw'}) eq "ARRAY") { + push @args, join(';', @{ $paramhash->{'raw'} }); + } else { + push @args, $paramhash->{'raw'}; + } + next; + } + elsif ($key1 eq "command" && defined($paramhash->{'command'})) { + if (ref($paramhash->{'command'}) eq "ARRAY") { + push @args, join(';', @{ $paramhash->{'command'} }); + } else { + push @args, $paramhash->{'command'}; + } + next; + } } - elsif ( $key1 eq "raw" && defined ($paramhash->{'raw'})) { - if (ref($paramhash->{'raw'}) eq "ARRAY") { - push @args, join (';', @{$paramhash->{'raw'}}); - } else { - push @args, $paramhash->{'raw'}; - } - next; - } - elsif ( $key1 eq "command" && defined ($paramhash->{'command'})) { - if (ref($paramhash->{'command'}) eq "ARRAY") { - push @args, join (';', @{$paramhash->{'command'}}); - } else { - push @args, $paramhash->{'command'}; - } - next; - } - } } else { - error ("Lack of operation data.",$STATUS_BAD_REQUEST,3); + error("Lack of operation data.", $STATUS_BAD_REQUEST, 3); } } elsif ($params->{'resourcename'} eq "nodecopy") { - if (defined ($paramhash->{'src'})) { - push @args, @{$paramhash->{'src'}}; + if (defined($paramhash->{'src'})) { + push @args, @{ $paramhash->{'src'} }; } - if (defined ($paramhash->{'target'})) { + if (defined($paramhash->{'target'})) { push @args, $paramhash->{'target'}; } } elsif ($params->{'resourcename'} =~ /(dns|dhcp)/) { @@ -2064,84 +2092,89 @@ sub actionhdl { push @args, '-z'; } } elsif ($params->{'resourcename'} eq "vm") { + # handle the virtual machine if (isGET()) { + # do nothing for kvm and esxi - }elsif (isPut()) { # change the configuration of vm - if (defined ($paramhash->{'adddisk'})) { #add new disk + } elsif (isPut()) { # change the configuration of vm + if (defined($paramhash->{'adddisk'})) { #add new disk push @args, ('-a', $paramhash->{'adddisk'}); } + #if (defined ($paramhash->{'rmdisk'})) { #remove disk # push @args, ('-d', $paramhash->{'rmdisk'}); #} - if (defined ($paramhash->{'purgedisk'})) { #purge disk + if (defined($paramhash->{'purgedisk'})) { #purge disk push @args, ('-p', $paramhash->{'purgedisk'}); } - if (defined ($paramhash->{'resizedisk'})) { #change the disk size - $paramhash->{'resizedisk'} =~ s/\:/=/; # replace : to be = in the param + if (defined($paramhash->{'resizedisk'})) { #change the disk size + $paramhash->{'resizedisk'} =~ s/\:/=/; # replace : to be = in the param push @args, ('--resize', $paramhash->{'resizedisk'}); } - if (defined ($paramhash->{'memorysize'})) { #change the memory size + if (defined($paramhash->{'memorysize'})) { #change the memory size push @args, ('--mem', $paramhash->{'memorysize'}); } - if (defined ($paramhash->{'cpucount'})) { #change the cpu size + if (defined($paramhash->{'cpucount'})) { #change the cpu size push @args, ('--cpus', $paramhash->{'cpucount'}); } - } elsif (isPost()) { # create virtual machine - if (defined ($paramhash->{'master'})) { # specify the master node for clone + } elsif (isPost()) { # create virtual machine + if (defined($paramhash->{'master'})) { # specify the master node for clone push @args, ('-m', $paramhash->{'master'}); } - if (defined ($paramhash->{'disksize'})) { # specify disk size + if (defined($paramhash->{'disksize'})) { # specify disk size push @args, ('-s', $paramhash->{'disksize'}); } - if (defined ($paramhash->{'memorysize'})) { #specify the memory size + if (defined($paramhash->{'memorysize'})) { #specify the memory size push @args, ('--mem', $paramhash->{'memorysize'}); } - if (defined ($paramhash->{'cpucount'})) { #specify the cpu size + if (defined($paramhash->{'cpucount'})) { #specify the cpu size push @args, ('--cpus', $paramhash->{'cpucount'}); } - if (defined ($paramhash->{'force'}) && $paramhash->{'force'} eq "yes") { # force the recreate + if (defined($paramhash->{'force'}) && $paramhash->{'force'} eq "yes") { # force the recreate push @args, "-f"; } } elsif (isDelete()) { - if (defined ($paramhash->{'force'}) && $paramhash->{'force'} eq "yes") { # force the recreate + if (defined($paramhash->{'force'}) && $paramhash->{'force'} eq "yes") { # force the recreate push @args, "-f"; } - if (defined ($paramhash->{'purge'}) && $paramhash->{'purge'} eq "yes") { # purge disk when remove the vm + if (defined($paramhash->{'purge'}) && $paramhash->{'purge'} eq "yes") { # purge disk when remove the vm push @args, "-p"; } } } elsif ($params->{'resourcename'} eq "vmclone") { + # handle the clone of virtual machine if (isPost()) { - if (defined ($paramhash->{'tomaster'})) { + if (defined($paramhash->{'tomaster'})) { push @args, ("-t", $paramhash->{'tomaster'}); - } elsif (defined ($paramhash->{'frommaster'})) { + } elsif (defined($paramhash->{'frommaster'})) { push @args, ("-b", $paramhash->{'frommaster'}); } else { - error ("Lack of operation data.",$STATUS_BAD_REQUEST,3); + error("Lack of operation data.", $STATUS_BAD_REQUEST, 3); } - - if (defined ($paramhash->{'detach'}) && $paramhash->{'detach'} eq "yes") { + + if (defined($paramhash->{'detach'}) && $paramhash->{'detach'} eq "yes") { push @args, "-d"; } - if (defined ($paramhash->{'force'}) && $paramhash->{'force'} eq "yes") { # force the recreate + if (defined($paramhash->{'force'}) && $paramhash->{'force'} eq "yes") { # force the recreate push @args, "-f"; } } } elsif (($params->{'resourcename'} eq "vmmigrate")) { + # handle the migration of virtual machine if (isPost()) { - if (defined ($paramhash->{'target'})) { + if (defined($paramhash->{'target'})) { push @args, $paramhash->{'target'}; } else { - error ("Lack of operation data.",$STATUS_BAD_REQUEST,3); + error("Lack of operation data.", $STATUS_BAD_REQUEST, 3); } } - } elsif ($params->{'resourcename'} eq "noderename") { + } elsif ($params->{'resourcename'} eq "noderename") { if (isPut()) { - if (defined ($paramhash->{'newNode'})) { #specify the new name for node + if (defined($paramhash->{'newNode'})) { #specify the new name for node push @args, ('-t', "node"); push @args, ('-o', $urilayers[1]); push @args, ('-n', $paramhash->{'newNode'}); @@ -2154,9 +2187,9 @@ sub actionhdl { if (defined($paramhash->{'onlyconfigfile'})) { my $tmp_value = $paramhash->{'onlyconfigfile'}; if ($tmp_value =~ /true|yes|Y|1/i) { - push @args, "-c"; + push @args, "-c"; } elsif ($tmp_value !~ /false|no|N|0/i) { - error ("Option value \"$tmp_value\" invalid.", $STATUS_BAD_REQUEST, 3); + error("Option value \"$tmp_value\" invalid.", $STATUS_BAD_REQUEST, 3); } } } @@ -2165,14 +2198,14 @@ sub actionhdl { if ($paramhash->{'action'}) { my $option = $paramhash->{'action'}; my %op_hash = ('on' => '', 'off' => '-d'); - push @args, $op_hash{$paramhash->{'action'}}; + push @args, $op_hash{ $paramhash->{'action'} }; } else { - error("Missed Action.",$STATUS_NOT_FOUND); + error("Missed Action.", $STATUS_NOT_FOUND); } } - push @{$request->{arg}}, @args; - my $req = genRequest(); + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; @@ -2181,7 +2214,7 @@ sub actionhdl { sub localreshdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; # set the command name $request->{command} = $params->{'cmd'}; @@ -2203,10 +2236,11 @@ sub localreshdl { foreach my $item (@urilayers) { push @args, $item if $item ne 'detail' && $item ne 'file'; } - push @{$request->{arg}}, @args; - # localrest is single plugin handler, use sequntial to avoid of multi-level processes + push @{ $request->{arg} }, @args; + + # localrest is single plugin handler, use sequntial to avoid of multi-level processes $request->{'sequential'}->[0] = 1; - my $req = genRequest(); + my $req = genRequest(); my $responses = sendRequest($req); return $responses; } @@ -2217,7 +2251,7 @@ sub nonobjhdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; # set the command name $request->{command} = $params->{'cmd'}; @@ -2237,9 +2271,9 @@ sub nonobjhdl { $request->{gettoken}->[0]->{username}->[0] = $generalparams->{userName} if (defined($generalparams->{userName})); $request->{gettoken}->[0]->{password}->[0] = $generalparams->{userPW} if (defined($generalparams->{userPW})); } - - push @{$request->{arg}}, @args; - my $req = genRequest(); + + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; @@ -2249,12 +2283,12 @@ sub nonobjhdl { # operate image instance for a osimage sub imgophdl { my $params = shift; - my @args = (); + my @args = (); if (isPost()) { if ($params->{'resourcename'} eq "osimage_op") { my $action = $paramhash->{'action'}; unless ($action) { - error("Missed Action.",$STATUS_NOT_FOUND); + error("Missed Action.", $STATUS_NOT_FOUND); } elsif ($action eq "gen") { $params->{'cmd'} = "genimage"; } elsif ($action eq "pack") { @@ -2262,33 +2296,34 @@ sub imgophdl { } elsif ($action eq "export") { $params->{'cmd'} = "imgexport"; } else { - error("Incorrect action:$action.",$STATUS_BAD_REQUEST); + error("Incorrect action:$action.", $STATUS_BAD_REQUEST); } } elsif ($params->{'resourcename'} eq "osimage") { if (exists($paramhash->{'iso'})) { $params->{'cmd'} = "copycds"; - push @{$params->{layers}}, $paramhash->{'iso'}; + push @{ $params->{layers} }, $paramhash->{'iso'}; } elsif (exists($paramhash->{'file'})) { $params->{'cmd'} = "imgimport"; - push @{$params->{layers}}, $paramhash->{'file'}; + push @{ $params->{layers} }, $paramhash->{'file'}; } elsif (exists($paramhash->{'node'})) { $params->{'cmd'} = "imgcapture"; + #push @{$params->{layers}}, $paramhash->{'node'}; - push @{$request->{noderange}}, $paramhash->{'node'}; + push @{ $request->{noderange} }, $paramhash->{'node'}; } else { - error("Invalid source.",$STATUS_NOT_FOUND); + error("Invalid source.", $STATUS_NOT_FOUND); } } } $request->{command} = $params->{'cmd'}; - push @args, $params->{layers}->[1]; + push @args, $params->{layers}->[1]; if (exists($paramhash->{'params'})) { - foreach (keys %{$paramhash->{'params'}->[0]}) { + foreach (keys %{ $paramhash->{'params'}->[0] }) { push @args, ($_, $paramhash->{'params'}->[0]->{$_}); } } - push @{$request->{arg}}, @args; - my $req = genRequest(); + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; } @@ -2296,31 +2331,32 @@ sub imgophdl { sub sitehdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; # set the command name $request->{command} = $params->{'cmd'}; + # push the -t args push @args, '-t'; push @args, 'site'; - if (isGET()) { + if (isGET()) { push @args, 'clustersite'; - } - if (defined ($urilayers[2])){ + } + if (defined($urilayers[2])) { if (isGET()) { push @args, ('-i', $urilayers[2]); - } + } } if (isDelete()) { - if (defined ($urilayers[2])){ + if (defined($urilayers[2])) { push @args, "$urilayers[2]="; - } + } } foreach my $k (keys(%$paramhash)) { push @args, "$k=$paramhash->{$k}" if ($k); } - push @{$request->{arg}}, @args; - my $req = genRequest(); + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; @@ -2332,7 +2368,8 @@ sub tablenodehdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; + # the array elements for @urilayers are: # 0 - 'table' # 1 - @@ -2346,7 +2383,7 @@ sub tablenodehdl { if (!defined($urilayers[3]) || $urilayers[3] eq 'ALLNODES') { $request->{command} = 'getTablesAllNodeAttribs'; } else { - $request->{command} = 'getTablesNodesAttribs'; + $request->{command} = 'getTablesNodesAttribs'; $request->{noderange} = $urilayers[3]; } @@ -2369,16 +2406,16 @@ sub tablenodehdl { # if they specified attrs, sort/group them by table my $attrlist = $urilayers[4]; - if (!defined($attrlist)) { $attrlist = 'ALL'; } # attr=ALL means get all non-blank attributes + if (!defined($attrlist)) { $attrlist = 'ALL'; } # attr=ALL means get all non-blank attributes my @attrs = split(/,/, $attrlist); my %attrhash; foreach my $a (@attrs) { if ($a =~ /\./) { my ($table, $attr) = split(/\./, $a); - push @{$attrhash{$table}}, $attr; + push @{ $attrhash{$table} }, $attr; } - else { # the attr doesn't have a table qualifier so apply to all tables - foreach my $t (@tables) { push @{$attrhash{$t}}, $a; } + else { # the attr doesn't have a table qualifier so apply to all tables + foreach my $t (@tables) { push @{ $attrhash{$t} }, $a; } } } @@ -2386,27 +2423,28 @@ sub tablenodehdl { foreach my $tname (@tables) { my $table = { tablename => $tname }; if (defined($attrhash{$tname})) { $table->{attr} = $attrhash{$tname}; } - else { $table->{attr} = 'ALL'; } - push @{$request->{table}}, $table; + else { $table->{attr} = 'ALL'; } + push @{ $request->{table} }, $table; } my $req = genRequest(); + # disabling the KeyAttr option is important in this case, so xmlin doesn't pull the name attribute # out of the node hash and make it the key - my $responses = sendRequest($req, {SuppressEmpty => undef, ForceArray => 0, KeyAttr => []}); + my $responses = sendRequest($req, { SuppressEmpty => undef, ForceArray => 0, KeyAttr => [] }); return $responses; } #get bmc ip address source -#check if bmc user or password is correct +#check if bmc user or password is correct sub bmccheckhdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; my $bmc_ip; my $bmc_user; my $bmc_pw; @@ -2417,33 +2455,33 @@ sub bmccheckhdl { # get bmc ip if (defined($urilayers[2])) { - $bmc_ip=$urilayers[2]; + $bmc_ip = $urilayers[2]; } # get bmc user and password if (defined($urilayers[3])) { - my @keyvals = split(/,/, $urilayers[3]); - foreach my $kv (@keyvals) + my @keyvals = split(/,/, $urilayers[3]); + foreach my $kv (@keyvals) + { + my ($key, $value) = split(/\s*=\s*/, $kv, 2); + if ($key eq "bmcuser") { - my ($key, $value) = split(/\s*=\s*/, $kv, 2); - if ($key eq "bmcuser") - { - $bmc_user=$value; - } - elsif ($key eq "bmcpw") - { - $bmc_pw=$value; - } + $bmc_user = $value; } + elsif ($key eq "bmcpw") + { + $bmc_pw = $value; + } + } } - + if ($params->{'resourcename'} eq "checkbmcauth") { if (isGET()) { push @args, "-i"; push @args, $bmc_ip; - if ( defined($bmc_user) && $bmc_user ne "none") + if (defined($bmc_user) && $bmc_user ne "none") { push @args, "-u"; push @args, $bmc_user; @@ -2459,7 +2497,7 @@ sub bmccheckhdl { if (isGET()) { push @args, "-i"; push @args, $bmc_ip; - if ( defined($bmc_user) && $bmc_user ne "none" ) + if (defined($bmc_user) && $bmc_user ne "none") { push @args, "-u"; push @args, $bmc_user; @@ -2470,8 +2508,8 @@ sub bmccheckhdl { } } - push @{$request->{arg}}, @args; - my $req = genRequest(); + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; @@ -2486,9 +2524,10 @@ sub bmclisthdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; my $m_value; my $ip_range; + # the array elements for @urilayers are: # 0 - 'bmcdiscover' # 1 - (optional) @@ -2497,30 +2536,30 @@ sub bmclisthdl { $request->{command} = $params->{'cmd'}; # get method and ip_range - if (defined($urilayers[2])) + if (defined($urilayers[2])) { - my @keyvals = split(/,/, $urilayers[2]); - foreach my $kv (@keyvals) + my @keyvals = split(/,/, $urilayers[2]); + foreach my $kv (@keyvals) + { + my ($key, $value) = split(/\s*=\s*/, $kv, 2); + if ($key eq "method") { - my ($key, $value) = split(/\s*=\s*/, $kv, 2); - if ($key eq "method") - { - $m_value=$value; - } - elsif ($key eq "iprange") - { - $ip_range=$value; - } + $m_value = $value; } + elsif ($key eq "iprange") + { + $ip_range = $value; + } + } } if ($params->{'resourcename'} eq "bmcdiscover") { if (isGET()) { - if ( defined($m_value) ) + if (defined($m_value)) { - push @args, "-s"; - push @args, $m_value; + push @args, "-s"; + push @args, $m_value; } push @args, "--range"; push @args, $ip_range; @@ -2528,8 +2567,8 @@ sub bmclisthdl { } - push @{$request->{arg}}, @args; - my $req = genRequest(); + push @{ $request->{arg} }, @args; + my $req = genRequest(); my $responses = sendRequest($req); return $responses; @@ -2541,7 +2580,8 @@ sub tablerowhdl { my $params = shift; my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; + # the array elements for @urilayers are: # 0 - 'table' # 1 - @@ -2552,12 +2592,13 @@ sub tablerowhdl { # do stuff that is common between getAttribs and getTablesAllRowAttribs my @tables = split(/,/, $urilayers[1]); my $attrlist = $urilayers[4]; - if (!defined($attrlist)) { $attrlist = 'ALL'; } # attr=ALL means get all non-blank attributes + if (!defined($attrlist)) { $attrlist = 'ALL'; } # attr=ALL means get all non-blank attributes my @attrs = split(/,/, $attrlist); # get all rows for potentially multiple tables if (!defined($urilayers[3]) || $urilayers[3] eq 'ALLROWS') { $request->{command} = 'getTablesAllRowAttribs'; + # For getTablesAllRowAttribs, the rest of the request strucutre needs to look like this: # table => [ # { @@ -2580,10 +2621,10 @@ sub tablerowhdl { foreach my $a (@attrs) { if ($a =~ /\./) { my ($table, $attr) = split(/\./, $a); - push @{$attrhash{$table}}, $attr; + push @{ $attrhash{$table} }, $attr; } - else { # the attr doesn't have a table qualifier so apply to all tables - foreach my $t (@tables) { push @{$attrhash{$t}}, $a; } + else { # the attr doesn't have a table qualifier so apply to all tables + foreach my $t (@tables) { push @{ $attrhash{$t} }, $a; } } } @@ -2591,8 +2632,8 @@ sub tablerowhdl { foreach my $tname (@tables) { my $table = { tablename => $tname }; if (defined($attrhash{$tname})) { $table->{attr} = $attrhash{$tname}; } - else { $table->{attr} = 'ALL'; } - push @{$request->{table}}, $table; + else { $table->{attr} = 'ALL'; } + push @{ $request->{table} }, $table; } } @@ -2600,6 +2641,7 @@ sub tablerowhdl { else { if (scalar(@tables) > 1) { error('currently you can only specify keys for a single table.', $STATUS_BAD_REQUEST); } $request->{command} = 'getAttribs'; + # For getAttribs, the rest of the request strucutre needs to look like this: # { # table => networks, @@ -2617,16 +2659,17 @@ sub tablerowhdl { my @keyvals = split(/,/, $urilayers[3]); foreach my $kv (@keyvals) { my ($key, $value) = split(/\s*=\s*/, $kv, 2); - $request->{keys}->{$key} = $value; + $request->{keys}->{$key} = $value; } } - foreach my $a (@attrs) { push @{$request->{attr}}, $a; } + foreach my $a (@attrs) { push @{ $request->{attr} }, $a; } } my $req = genRequest(); + # disabling the KeyAttr option is important in this case, so xmlin doesn't pull the name attribute # out of the node hash and make it the key - my $responses = sendRequest($req, {SuppressEmpty => undef, ForceArray => 0, KeyAttr => []}); + my $responses = sendRequest($req, { SuppressEmpty => undef, ForceArray => 0, KeyAttr => [] }); return $responses; } @@ -2637,6 +2680,7 @@ sub tablerowhdl { sub tableout { my $data = shift; my $json = {}; + # For the table get calls, we turned off ForceArray and KeyAttr for XMLin(), so the output is a little # different than usual. Each element is a hash with key "table" that is either a hash or array of hashes. # Each element of that is a hash with 2 keys called "tablename" and "node". The latter has either: an array of node hashes, @@ -2644,21 +2688,23 @@ sub tableout { # We are producing json that is a hash of table name keys that each have an array of node objects. foreach my $d (@$data) { my $table = $d->{table}; - if (!defined($table)) { # special case for the getAttribs cmd - $json->{$request->{table}}->[0] = $d; + if (!defined($table)) { # special case for the getAttribs cmd + $json->{ $request->{table} }->[0] = $d; last; } + #debug(Dumper($d)); debug (Dumper($jsonnode)); - if (ref($table) eq 'HASH') { $table = [$table]; } # if a single table, make it a 1 element array of tables + if (ref($table) eq 'HASH') { $table = [$table]; } # if a single table, make it a 1 element array of tables foreach my $t (@$table) { - my $jsonnodes = []; # start an array of node objects for this table + my $jsonnodes = []; # start an array of node objects for this table my $tabname = $t->{tablename}; - if (!defined($tabname)) { $tabname = 'unknown' . $::i++; } #todo: have lissa fix this bug - $json->{$tabname} = $jsonnodes; # add it into the top level hash + if (!defined($tabname)) { $tabname = 'unknown' . $::i++; } #todo: have lissa fix this bug + $json->{$tabname} = $jsonnodes; # add it into the top level hash my $node = $t->{node}; if (!defined($node)) { $node = $t->{row}; } + #debug(Dumper($d)); debug (Dumper($jsonnode)); - if (ref($node) eq 'HASH') { $node = [$node]; } # if a single node, make it a 1 element array of nodes + if (ref($node) eq 'HASH') { $node = [$node]; } # if a single node, make it a 1 element array of nodes foreach my $n (@$node) { push @$jsonnodes, $n; } } } @@ -2675,7 +2721,8 @@ sub tablenodeputhdl { # example => '|Change the nodehm.mgmt and noderes.netboot attributes for nodes node1-node5.|PUT|/tables/nodes/node1-node5 {"nodehm":{"mgmt":"ipmi"},"noderes":{"netboot":"xnba"}}||', my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; + # the array elements for @urilayers are: # 0 - 'table' # 1 - @@ -2683,7 +2730,7 @@ sub tablenodeputhdl { # 3 - # set the command name - $request->{command} = 'setNodesAttribs'; + $request->{command} = 'setNodesAttribs'; $request->{noderange} = $urilayers[3]; # For setNodesAttribs, the rest of the request strucutre looks like this: @@ -2705,26 +2752,28 @@ sub tablenodeputhdl { # } # Get table list in the URI - my @uritbs = split(/,/, $urilayers[1]); + my @uritbs = split(/,/, $urilayers[1]); # Go thru the list of tables (which are the top level keys in paramhash) my $tables = []; $request->{arg}->{table} = $tables; foreach my $k (keys(%$paramhash)) { my $intable = $k; + # Check the validity of tables - if (! grep(/^$intable$/, @uritbs)) { + if (!grep(/^$intable$/, @uritbs)) { error("The table $intable is NOT in the URI.", $STATUS_BAD_REQUEST); } my $attrhash = $paramhash->{$k}; - my $outtable = { name=>$intable, attr=>$attrhash }; + my $outtable = { name => $intable, attr => $attrhash }; push @$tables, $outtable; - } + } my $req = genRequest(); + # disabling the KeyAttr option is important in this case, so xmlin doesn't pull the name attribute # out of the node hash and make it the key - my $responses = sendRequest($req, {SuppressEmpty => undef, ForceArray => 1, KeyAttr => []}); + my $responses = sendRequest($req, { SuppressEmpty => undef, ForceArray => 1, KeyAttr => [] }); return $responses; } @@ -2739,7 +2788,8 @@ sub tablerowputhdl { # example => '|Creat a route row in the routes table.|PUT|/tables/routes/rows/routename=privnet {"net":"10.0.1.0","mask":"255.255.255.0","gateway":"10.0.1.254","ifname":"eth1"}||', my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; + # the array elements for @urilayers are: # 0 - 'table' # 1 - @@ -2752,11 +2802,11 @@ sub tablerowputhdl { # For setAttribs, the rest of the xml request strucutre looks like this: # routes
# - # foo + # foo # # - # 10.0.1.0 - # This is a test + # 10.0.1.0 + # This is a test # # set the table name and keys @@ -2764,16 +2814,17 @@ sub tablerowputhdl { my @keyvals = split(/,/, $urilayers[3]); foreach my $kv (@keyvals) { my ($key, $value) = split(/\s*=\s*/, $kv, 2); - $request->{keys}->{$key} = $value; + $request->{keys}->{$key} = $value; } # the attribute/value hash is already in paramhash $request->{attr} = $paramhash; my $req = genRequest(); + # disabling the KeyAttr option is important in this case, so xmlin doesn't pull the name attribute # out of the node hash and make it the key - my $responses = sendRequest($req, {SuppressEmpty => undef, ForceArray => 1, KeyAttr => []}); + my $responses = sendRequest($req, { SuppressEmpty => undef, ForceArray => 1, KeyAttr => [] }); return $responses; } @@ -2788,7 +2839,8 @@ sub tablerowdelhdl { # example => '|Delete a route row in the routes table.|PUT|/tables/routes/rows/routename=privnet||', my @args; - my @urilayers = @{$params->{'layers'}}; + my @urilayers = @{ $params->{'layers'} }; + # the array elements for @urilayers are: # 0 - 'table' # 1 - @@ -2808,19 +2860,20 @@ sub tablerowdelhdl { # # set the table name and attr/vals - my $table = {}; # will hold the name and attr/vals - $request->{table}->[0] = $table; #todo: the xcat delEntries cmd supports multiple tables in 1 request. We could support this if the attr names were table.attr + my $table = {}; # will hold the name and attr/vals + $request->{table}->[0] = $table; #todo: the xcat delEntries cmd supports multiple tables in 1 request. We could support this if the attr names were table.attr $table->{name} = $urilayers[1]; my @attrvals = split(/,/, $urilayers[3]); foreach my $av (@attrvals) { my ($attr, $value) = split(/\s*=\s*/, $av, 2); - $table->{attr}->{$attr} = $value; + $table->{attr}->{$attr} = $value; } my $req = genRequest(); + # disabling the KeyAttr option is important in this case, so xmlin doesn't pull the name attribute # out of the node hash and make it the key - my $responses = sendRequest($req, {SuppressEmpty => undef, ForceArray => 1, KeyAttr => []}); + my $responses = sendRequest($req, { SuppressEmpty => undef, ForceArray => 1, KeyAttr => [] }); return $responses; } @@ -2830,19 +2883,19 @@ sub tablerowdelhdl { sub displayUsage { foreach my $group (keys %URIdef) { print "Resource Group: $group\n"; - foreach my $res (keys %{$URIdef{$group}}) { + foreach my $res (keys %{ $URIdef{$group} }) { print " Resource: $res\n"; print " $URIdef{$group}->{$res}->{desc}\n"; - if (defined ($URIdef{$group}->{$res}->{GET})) { + if (defined($URIdef{$group}->{$res}->{GET})) { print " GET: $URIdef{$group}->{$res}->{GET}->{desc}\n"; } - if (defined ($URIdef{$group}->{$res}->{PUT})) { + if (defined($URIdef{$group}->{$res}->{PUT})) { print " PUT: $URIdef{$group}->{$res}->{PUT}->{desc}\n"; } - if (defined ($URIdef{$group}->{$res}->{POST})) { + if (defined($URIdef{$group}->{$res}->{POST})) { print " POST: $URIdef{$group}->{$res}->{POST}->{desc}\n"; } - if (defined ($URIdef{$group}->{$res}->{DELETE})) { + if (defined($URIdef{$group}->{$res}->{DELETE})) { print " DELETE: $URIdef{$group}->{$res}->{DELETE}->{desc}\n"; } } @@ -2864,92 +2917,100 @@ sub displayUsage { # Otherwise, pass the output to the outputhandler for the specific resource sub filterData { - my $data = shift; + my $data = shift; + #debugandexit(Dumper($data)); my $outputdata; my $outputerror; - my @errmsgindata; # put the out->{data} for error message output - + my @errmsgindata; # put the out->{data} for error message output + #trim the serverdone message off foreach (@{$data}) { if (defined($_->{error})) { if (ref($_->{error}) eq 'ARRAY') { - foreach my $msg (@{$_->{error}}) { + foreach my $msg (@{ $_->{error} }) { if ($msg =~ /(Permission denied|Authentication failure)/) { + # return 401 Unauthorized error("Authentication failure", $STATUS_UNAUTH); } else { - push @{$outputerror->{error}}, $msg; + push @{ $outputerror->{error} }, $msg; } } } else { - push @{$outputerror->{error}}, $_->{error}; + push @{ $outputerror->{error} }, $_->{error}; } - - if (defined ($_->{errorcode})) { + + if (defined($_->{errorcode})) { if (ref($_->{errorcode}) eq 'ARRAY') { $outputerror->{errorcode} = $_->{errorcode}->[0]; } else { $outputerror->{errorcode} = $_->{errorcode}; } } else { + # set the default errorcode to '1' $outputerror->{errorcode} = '1'; } } elsif (defined($_->{errorcode}) && $_->{errorcode}->[0] ne "0") { # defined errorcode, but not define the error msg $outputerror->{errorcode} = $_->{errorcode}->[0]; - if (defined ($_->{data}) && ref($_->{data}->[0]) ne "HASH") { + if (defined($_->{data}) && ref($_->{data}->[0]) ne "HASH") { + # to get the message in data for the case that errorcode is set but no 'error' attr push @errmsgindata, $_->{data}->[0]; } if (@errmsgindata) { - push @{$outputerror->{error}}, @errmsgindata; + push @{ $outputerror->{error} }, @errmsgindata; } else { - push @{$outputerror->{error}}, "Failed with unknown reason."; + push @{ $outputerror->{error} }, "Failed with unknown reason."; } } - # handle the output like + # handle the output like # # node1 # Unable to identify plugin for this command, check relevant tables: nodehm.power,mgt;nodehm.mgt # 1 # - if (defined($_->{node}) && defined ($_->{node}->[0]->{error})) { - if (defined ($_->{node}->[0]->{name})) { - push @{$outputerror->{error}}, "$_->{node}->[0]->{name}->[0]: ".$_->{node}->[0]->{error}->[0]; + if (defined($_->{node}) && defined($_->{node}->[0]->{error})) { + if (defined($_->{node}->[0]->{name})) { + push @{ $outputerror->{error} }, "$_->{node}->[0]->{name}->[0]: " . $_->{node}->[0]->{error}->[0]; } - if (defined ($_->{node}->[0]->{errorcode})) { + if (defined($_->{node}->[0]->{errorcode})) { $outputerror->{errorcode} = $_->{node}->[0]->{errorcode}->[0]; } else { + # set the default errorcode to '1' $outputerror->{errorcode} = '1'; } - } + } if (exists($_->{serverdone})) { - if (defined ($outputerror->{error}) || defined ($outputerror->{error})) { - addPageContent($JSON->encode($outputerror)); - #return the default http error code to be 403 forbidden - sendResponseMsg($STATUS_FORBIDDEN); - #} else { + if (defined($outputerror->{error}) || defined($outputerror->{error})) { + addPageContent($JSON->encode($outputerror)); + + #return the default http error code to be 403 forbidden + sendResponseMsg($STATUS_FORBIDDEN); + + #} else { #otherwise, ignore the 'servicedone' data - # next; + # next; } else { - delete ($_->{serverdone}); + delete($_->{serverdone}); if (scalar(keys %{$_}) > 0) { push @{$outputdata}, $_; } } } else { - if (defined ($_->{data}) && ref($_->{data}->[0]) ne "HASH") { + if (defined($_->{data}) && ref($_->{data}->[0]) ne "HASH") { + # to get the message in data for the case that errorcode is set but no 'error' attr push @errmsgindata, $_->{data}->[0]; } push @{$outputdata}, $_; - } + } } return $outputdata; @@ -2958,6 +3019,7 @@ sub filterData { # Structure the response perl data structure into well-formed json. Since the structure of the # xml output that comes from xcatd is inconsistent and not very structured, we have a lot of work to do. sub wrapJson { + # this is an array of responses from xcatd. Often all the output comes back in 1 response, but not always. my $data = shift; @@ -2977,7 +3039,7 @@ sub wrapJson { # 2nd param - A flag to specify the format of 1st param: 1 - json formatted standard xcat output data sub addPageContent { my $newcontent = shift; - my $userdata = shift; + my $userdata = shift; if ($userdata && $XCOLL) { my $group; @@ -2986,17 +3048,17 @@ sub addPageContent { foreach my $node (keys %{$hash}) { if (ref($hash->{$node}) eq "HASH") { my $value; - foreach (sort (keys %{$hash->{$node}})) { + foreach (sort (keys %{ $hash->{$node} })) { $value .= "$_$hash->{$node}->{$_}"; } - push @{$group->{$value}->{node}}, $node; + push @{ $group->{$value}->{node} }, $node; $group->{$value}->{orig} = $hash->{$node}; } elsif (ref($hash->{$node}) eq "ARRAY") { my $value; - foreach (sort (@{$hash->{$node}})) { + foreach (sort (@{ $hash->{$node} })) { $value .= "$_"; } - push @{$group->{$value}->{node}}, $node; + push @{ $group->{$value}->{node} }, $node; $group->{$value}->{orig} = $hash->{$node}; } } @@ -3004,15 +3066,15 @@ sub addPageContent { my $groupout; foreach my $value (keys %{$group}) { if (defined $group->{$value}->{node}) { - my $nodes = join(',', @{$group->{$value}->{node}}); - if (defined ($group->{$value}->{orig})) { + my $nodes = join(',', @{ $group->{$value}->{node} }); + if (defined($group->{$value}->{orig})) { $groupout->{$nodes} = $group->{$value}->{orig}; } } } $newcontent = $JSON->encode($groupout) if ($groupout); } - + $pageContent .= $newcontent; } @@ -3037,12 +3099,12 @@ sub sendResponseMsg { if ($header_info{attachment}) { print $q->header(-status => $code, - -type => $tempFormat, - -attachment => $header_info{attachment}, - -Content_length => length($pageContent)); + -type => $tempFormat, + -attachment => $header_info{attachment}, + -Content_length => length($pageContent)); } else { print $q->header(-status => $code, -type => $tempFormat); - if ($pageContent) { $pageContent .= "\n"; } # if there is any content, append a newline + if ($pageContent) { $pageContent .= "\n"; } # if there is any content, append a newline } print $pageContent; exit(0); @@ -3057,7 +3119,7 @@ sub genRequest { # The response returned to the caller of this function has already been converted from xml to perl structure. sub sendRequest { my $request = shift; - my $xmlinoptions = shift; # optional arg to not set ForceArray on the XMLin() call + my $xmlinoptions = shift; # optional arg to not set ForceArray on the XMLin() call my $sitetab; my $retries = 0; @@ -3081,27 +3143,27 @@ sub sendRequest { my $client; if (-r $keyfile and -r $certfile and -r $cafile) { $client = IO::Socket::SSL->new( - PeerAddr => $xcatHost, - SSL_key_file => $keyfile, - SSL_cert_file => $certfile, - SSL_ca_file => $cafile, - SSL_verify_mode => SSL_VERIFY_PEER, + PeerAddr => $xcatHost, + SSL_key_file => $keyfile, + SSL_cert_file => $certfile, + SSL_ca_file => $cafile, + SSL_verify_mode => SSL_VERIFY_PEER, SSL_verifycn_scheme => "none", - SSL_use_cert => 1, - Timeout => 15,); + SSL_use_cert => 1, + Timeout => 15,); } else { $client = IO::Socket::SSL->new( - PeerAddr => $xcatHost, + PeerAddr => $xcatHost, SSL_verify_mode => 0, - Timeout => 15,); + Timeout => 15,); } unless ($client) { if ($@ =~ /SSL Timeout/) { - error("Connection failure: SSL Timeout or incorrect certificates in ~/.xcat",$STATUS_TIMEOUT); + error("Connection failure: SSL Timeout or incorrect certificates in ~/.xcat", $STATUS_TIMEOUT); } else { - error("Connection failurexx: $@",$STATUS_SERVICE_UNAVAILABLE); + error("Connection failurexx: $@", $STATUS_SERVICE_UNAVAILABLE); } } @@ -3111,13 +3173,14 @@ sub sendRequest { my $response; my $rsp; my $fullResponse = []; - my $cleanexit = 0; + my $cleanexit = 0; while (<$client>) { $response .= $_; if (m/<\/xcatresponse>/) { #replace ESC with xxxxESCxxx because XMLin cannot handle it if ($DEBUGGING) { + #addPageContent("DEBUG: response from xcatd: " . $response . "\n"); } $response =~ s/\e/xxxxESCxxxx/g; @@ -3125,14 +3188,15 @@ sub sendRequest { #bmp: i added the $xmlinoptions var because for the table output it saved me processing if everything # wasn't forced into arrays. Consider if that could save you processing on other api calls too. - if (!$xmlinoptions) { $xmlinoptions = {SuppressEmpty => undef, ForceArray => 1}; } + if (!$xmlinoptions) { $xmlinoptions = { SuppressEmpty => undef, ForceArray => 1 }; } $rsp = XML::Simple::XMLin($response, %$xmlinoptions); + #debug(Dumper($rsp)); #add ESC back foreach my $key (keys %$rsp) { if (ref($rsp->{$key}) eq 'ARRAY') { - foreach my $text (@{$rsp->{$key}}) { + foreach my $text (@{ $rsp->{$key} }) { next unless defined $text; $text =~ s/xxxxESCxxxx/\e/g; } @@ -3151,7 +3215,7 @@ sub sendRequest { } } unless ($cleanexit) { - error("communication with the xCAT server seems to have been ended prematurely",$STATUS_SERVICE_UNAVAILABLE); + error("communication with the xCAT server seems to have been ended prematurely", $STATUS_SERVICE_UNAVAILABLE); } if ($DEBUGGING == 2) { @@ -3165,42 +3229,46 @@ sub sendRequest { # 2nd output param - All the params from url params and 'PUTDATA'/'POSTDATA' except the ones in @generalparamlis sub fetchParameters { my @generalparamlist = qw(userName userPW pretty debug xcoll); + # 1st check for put/post data and put that in the hash my $pdata; - if (isPut()) { - $pdata = $q->param('PUTDATA'); + if (isPut()) { + $pdata = $q->param('PUTDATA'); + # in the sles 11.x, the 'PUTDATA' param is not supported for PUT method # so we have to work around it by getting it by myself unless ($pdata) { - if (-f "/etc/SuSE-release") {# SUSE os + if (-f "/etc/SuSE-release") { # SUSE os if ($ENV{'CONTENT_TYPE'} =~ /json/) { $q->read_from_client(\$pdata, $ENV{'CONTENT_LENGTH'}); } } } } elsif (isPost()) { - $pdata = $q->param('POSTDATA'); - } elsif (isDelete()) { + $pdata = $q->param('POSTDATA'); + } elsif (isDelete()) { if ($ENV{'CONTENT_TYPE'} =~ /json/) { $q->read_from_client(\$pdata, $ENV{'CONTENT_LENGTH'}); - } + } } - + if ($dbgdata) { $pdata = $dbgdata; } - + my $genparms = {}; my $phash; if ($pdata) { $phash = eval { $JSON->decode($pdata); }; - if ($@) { + if ($@) { + # remove the code location information to make the output looks better if ($@ =~ m/ at \//) { $@ =~ s/ at \/.*$//; } - error("$@",$STATUS_BAD_REQUEST); + error("$@", $STATUS_BAD_REQUEST); } + #debug("phash=" . Dumper($phash)); if (ref($phash) ne 'HASH') { error("put or post data must be a json object (hash/dict).", $STATUS_BAD_REQUEST); } @@ -3216,12 +3284,12 @@ sub fetchParameters { # now get params from the url (if any of the keys overlap, the url value will overwrite the put/post value) foreach my $p ($q->url_param) { - my @a = $q->url_param($p); # this could be a single value or an array, have to figure it out + my @a = $q->url_param($p); # this could be a single value or an array, have to figure it out my $value; - if (scalar(@a) > 1) { $value = [@a]; } # convert it to a reference to an array - else { $value = $a[0]; } - if (grep(/^$p$/, @generalparamlist)) { $genparms->{$p} = $value; } - else { $phash->{$p} = $value; } + if (scalar(@a) > 1) { $value = [@a]; } # convert it to a reference to an array + else { $value = $a[0]; } + if (grep(/^$p$/, @generalparamlist)) { $genparms->{$p} = $value; } + else { $phash->{$p} = $value; } } return ($genparms, $phash); @@ -3230,18 +3298,18 @@ sub fetchParameters { # Load the XML::Simple module sub loadXML { if ($xmlinstalled) { return; } - + $xmlinstalled = eval { require XML::Simple; }; unless ($xmlinstalled) { - error('The XML::Simple perl module is missing. Install perl-XML-Simple before using the xCAT REST web services API with this format."}',$STATUS_SERVICE_UNAVAILABLE); + error('The XML::Simple perl module is missing. Install perl-XML-Simple before using the xCAT REST web services API with this format."}', $STATUS_SERVICE_UNAVAILABLE); } $XML::Simple::PREFERRED_PARSER = 'XML::Parser'; } # Load the JSON perl module, if not already loaded. Sets the $JSON global var. sub loadJSON { - if ($JSON) { return; } # already loaded - # require JSON dynamically and let them know if it is not installed + if ($JSON) { return; } # already loaded + # require JSON dynamically and let them know if it is not installed my $jsoninstalled = eval { require JSON; }; unless ($jsoninstalled) { error("JSON perl module missing. Install perl-JSON before using the xCAT REST web services API.", $STATUS_SERVICE_UNAVAILABLE); @@ -3253,12 +3321,12 @@ sub loadJSON { sub error { my ($errmsg, $httpcode, $errorcode) = @_; my $json; - $json->{error} = $errmsg; + $json->{error} = $errmsg; $json->{errorcode} = '2'; if ($errorcode) { $json->{errorcode} = $errorcode; } - + addPageContent($JSON->encode($json)); sendResponseMsg($httpcode); } @@ -3277,11 +3345,13 @@ sub debugandexit { } sub displaydebugmsg { - addPageContent($q->p("DEBUG: generalparams:". Dumper($generalparams))); - addPageContent($q->p("DEBUG: paramhash:". Dumper($paramhash))); + addPageContent($q->p("DEBUG: generalparams:" . Dumper($generalparams))); + addPageContent($q->p("DEBUG: paramhash:" . Dumper($paramhash))); addPageContent($q->p("DEBUG: q->request_method: $requestType\n")); + #addPageContent($q->p("DEBUG: q->user_agent: $userAgent\n")); addPageContent($q->p("DEBUG: pathInfo: $pathInfo\n")); + #addPageContent($q->p("DEBUG: path " . Dumper(@path) . "\n")); #foreach (keys(%ENV)) { addPageContent($q->p("DEBUG: ENV{$_}: $ENV{$_}\n")); } #addPageContent($q->p("DEBUG: userName=".$paramhash->{userName}.", password=".$paramhash->{password}."\n")); @@ -3289,7 +3359,7 @@ sub displaydebugmsg { #if ($pdata) { addPageContent($q->p("DEBUG: pdata: $pdata\n")); } addPageContent("\n"); if ($DEBUGGING == 3) { - sendResponseMsg($STATUS_OK); # this will also exit + sendResponseMsg($STATUS_OK); # this will also exit } } diff --git a/xCAT-test/autotest/testcase/installation/customize_sleep_for_sn b/xCAT-test/autotest/testcase/installation/customize_sleep_for_sn index 8cb28a999..5c4c1ce7c 100755 --- a/xCAT-test/autotest/testcase/installation/customize_sleep_for_sn +++ b/xCAT-test/autotest/testcase/installation/customize_sleep_for_sn @@ -1,28 +1,28 @@ #!/usr/bin/env perl -my $os=$ARGV[0]; -my $arch=$ARGV[1]; -my $log="/tmp/pre_deploy_sn.log"; +my $os = $ARGV[0]; +my $arch = $ARGV[1]; +my $log = "/tmp/pre_deploy_sn.log"; -my $orgclusterconffile="/opt/xcat/share/xcat/tools/autotest/default.conf"; +my $orgclusterconffile = "/opt/xcat/share/xcat/tools/autotest/default.conf"; my $snnodename = `cat $orgclusterconffile |grep -E '^SN\s*='|awk -F'=' '{print \$2}'`; chomp($snnodename); `echo "SN=$snnodename" >> $log`; sleep 300; -my $timecnt=0; -while($timecnt < 200){ - my $booted=system("lsdef -l $snnodename|grep status|grep booted > /dev/null 2>&1"); - last if($booted==0); - - if($os =~ /rhel/i && $arch =~ /^ppc64$/i){ - my $booting=system("lsdef -l $snnodename|grep status|grep booting > /dev/null 2>&1"); - system("xdsh $snnodename \"echo 1\"") if($booting==0); +my $timecnt = 0; +while ($timecnt < 200) { + my $booted = system("lsdef -l $snnodename|grep status|grep booted > /dev/null 2>&1"); + last if ($booted == 0); + + if ($os =~ /rhel/i && $arch =~ /^ppc64$/i) { + my $booting = system("lsdef -l $snnodename|grep status|grep booting > /dev/null 2>&1"); + system("xdsh $snnodename \"echo 1\"") if ($booting == 0); `echo "send signal to $snnodename for the $timecnt times" >> $log`; } - + sleep 10; $timecnt++; -} - +} + exit 0; diff --git a/xCAT-test/autotest/testcase/installation/pre_deploy_sn b/xCAT-test/autotest/testcase/installation/pre_deploy_sn index d02f342a8..4ef510174 100755 --- a/xCAT-test/autotest/testcase/installation/pre_deploy_sn +++ b/xCAT-test/autotest/testcase/installation/pre_deploy_sn @@ -2,27 +2,28 @@ $ENV{TERM} = "xterm-256color"; -my $os=$ARGV[0]; -my $arch=$ARGV[1]; -my $log="/tmp/pre_deploy_sn.log"; +my $os = $ARGV[0]; +my $arch = $ARGV[1]; +my $log = "/tmp/pre_deploy_sn.log"; -sub runcmd{ - my $cmd=shift; +sub runcmd { + my $cmd = shift; `$cmd >> $log 2>&1`; - if($?){ + if ($?) { + #print "run $cmd ....[error]\n"; exit 1; } } -$cmd="XCATMYSQLADMIN_PW=12345 XCATMYSQLROOT_PW=12345 /opt/xcat/bin/mysqlsetup -i -V"; +$cmd = "XCATMYSQLADMIN_PW=12345 XCATMYSQLROOT_PW=12345 /opt/xcat/bin/mysqlsetup -i -V"; runcmd("$cmd"); -$cmd="echo \"GRANT ALL on xcatdb.* TO xcatadmin@\'%\' IDENTIFIED BY \'12345\'\;\" | mysql -u root -p12345"; +$cmd = "echo \"GRANT ALL on xcatdb.* TO xcatadmin@\'%\' IDENTIFIED BY \'12345\'\;\" | mysql -u root -p12345"; runcmd("$cmd"); my $xcatballpath = "/install/post/otherpkgs/$os/$arch/xcat"; -$cmd="mkdir -p $xcatballpath/xcat-core && cp -r /xcat-core/* $xcatballpath/xcat-core && cp -r /xcat-dep $xcatballpath"; +$cmd = "mkdir -p $xcatballpath/xcat-core && cp -r /xcat-core/* $xcatballpath/xcat-core && cp -r /xcat-dep $xcatballpath"; runcmd("$cmd"); exit 0; diff --git a/xCAT-test/restapitest b/xCAT-test/restapitest index 1621a116b..83ba63c38 100755 --- a/xCAT-test/restapitest +++ b/xCAT-test/restapitest @@ -28,7 +28,7 @@ ################################################################################ BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use Getopt::Long qw{:config bundling no_ignore_case}; use Data::Dumper; @@ -49,24 +49,24 @@ my $loperator; my $debug; my $defaulthash; my $defaulthttpresult = 0; -my $outputfile = "/tmp/testrestapiresult"; +my $outputfile = "/tmp/testrestapiresult"; if ( - !GetOptions("h|?" => \$help, - "m=s" => \$method, - "t=s" => \$token, - "r=s" => \$resource, - "h=s" => \$host, - "u=s" => \$user, - "p=s" => \$passwd, - "P=s" => \$port, - "d=s" => \$data, - "c=s" => \$cert, - "n=s" => \$hostname, - "o=s" => \$output, - "O=s" => \$loperator, - "debug" => \$debug, - ) + !GetOptions("h|?" => \$help, + "m=s" => \$method, + "t=s" => \$token, + "r=s" => \$resource, + "h=s" => \$host, + "u=s" => \$user, + "p=s" => \$passwd, + "P=s" => \$port, + "d=s" => \$data, + "c=s" => \$cert, + "n=s" => \$hostname, + "o=s" => \$output, + "O=s" => \$loperator, + "debug" => \$debug, + ) ) { &usage; exit 1; @@ -83,15 +83,15 @@ if ($help) { ############################################################## # flag check ############################################################## -if ($method ) { - unless( $resource ) { +if ($method) { + unless ($resource) { print "-m must be used with -r \n"; &usage; exit 0; } } -if ($resource ) { - unless($method) { +if ($resource) { + unless ($method) { print "-r must be used with -m \n"; &usage; exit 0; @@ -103,44 +103,45 @@ if ($resource ) { # ONLY check result,exit immediately ############################################################## if ($output and !defined($method)) { - my $res = check_result($output,$loperator,$outputfile); - log_debug(2, "check result runs with $output and $loperator, result is $res\n" ); + my $res = check_result($output, $loperator, $outputfile); + log_debug(2, "check result runs with $output and $loperator, result is $res\n"); exit $res; } ############################################################## # Give default values for optional vars. ############################################################### -my $rootdir = "$::XCATROOT/share/xcat/tools/autotest"; +my $rootdir = "$::XCATROOT/share/xcat/tools/autotest"; my $resultdir = "$rootdir/result"; -my $logfile = "$rootdir/result/restapitest.log"; +my $logfile = "$rootdir/result/restapitest.log"; + #/opt/xcat/share/xcat/tools/autotest/result/restapitest.log my $confile = "$rootdir/default.conf"; # read configuration file -if (!open (CONF, "<$confile")) { - log_debug(1,"can't open configuration file $confile"); - exit 1; +if (!open(CONF, "<$confile")) { + log_debug(1, "can't open configuration file $confile"); + exit 1; } my %confhash; -while (){ +while () { if (/restapi-(\w+)=(\S+)/) { - $confhash{$1}=$2; + $confhash{$1} = $2; } } # get token my $defaultserver = $confhash{DefaultServer}; -my $defaultuser = $confhash{DefaultUser1}; +my $defaultuser = $confhash{DefaultUser1}; my $DefaultPasswd = $confhash{DefaultPasswd1}; my $gettoken = `curl -X POST -k 'https://$defaultserver/xcatws/tokens?userName=$defaultuser&password=$DefaultPasswd' -H Content-Type:application/json --data '{"userName":"$defaultuser","password":"$DefaultPasswd"}' 2>/dev/null`; my $reshash = parse_json($gettoken); -my $token1 = $$reshash{token}{id}; +my $token1 = $$reshash{token}{id}; # get hostname unless ($hostname) { - $hostname = `hostname`; + $hostname = `hostname`; chomp($hostname); } unless ($defaultserver) { @@ -151,58 +152,59 @@ unless ($defaultserver) { # keey default test result for save my $res = run_restapi($method, $resource, $data, "", $port, "$host", "$defaultuser", "$DefaultPasswd"); -$defaulthash = parse_json($res); +$defaulthash = parse_json($res); $defaulthttpresult = check_errcode(); # debug and log info -log_debug(3, "get token $token1. \n" ); -log_debug(3, "get first default user $confhash{DefaultUser1} \n" ); -log_debug(3, "get first default user's passwd is $confhash{DefaultPasswd1} \n" ); -log_debug(3, "get second default user $confhash{DefaultUser2} \n" ); -log_debug(3, "get second default user's passwd is $confhash{DefaultPasswd2} \n" ); -log_debug(3, "get path of ca $confhash{Cert} \n" ); -log_debug(3, "get server $defaultserver from configuration file and it is $host\n" ); +log_debug(3, "get token $token1. \n"); +log_debug(3, "get first default user $confhash{DefaultUser1} \n"); +log_debug(3, "get first default user's passwd is $confhash{DefaultPasswd1} \n"); +log_debug(3, "get second default user $confhash{DefaultUser2} \n"); +log_debug(3, "get second default user's passwd is $confhash{DefaultPasswd2} \n"); +log_debug(3, "get path of ca $confhash{Cert} \n"); +log_debug(3, "get server $defaultserver from configuration file and it is $host\n"); log_debug(3, "get hostname $hostname.\n"); -log_debug(3, "default result is $res. \n" ); -log_debug(3, "default resulthash is: \n" ); -log_debug(3,$defaulthash); -log_debug(3, "default errcode is $defaulthttpresult \n" ); -log_debug(3,"**************begin to run more restapi test, stop when post***************"); +log_debug(3, "default result is $res. \n"); +log_debug(3, "default resulthash is: \n"); +log_debug(3, $defaulthash); +log_debug(3, "default errcode is $defaulthttpresult \n"); +log_debug(3, "**************begin to run more restapi test, stop when post***************"); #################################################### # Begin to run test cases #################################################### -my @users = ($confhash{DefaultUser1},$confhash{DefaultUser2}, $user); -my @passwds = ($confhash{DefaultPasswd1},$confhash{DefaultPasswd2}, $passwd); +my @users = ($confhash{DefaultUser1}, $confhash{DefaultUser2}, $user); +my @passwds = ($confhash{DefaultPasswd1}, $confhash{DefaultPasswd2}, $passwd); my @tokens = ("", $token1, $token); my @certs = ("", $confhash{Cert}, $cert); my $i = 0; -unless ($method eq "POST") { # Should not post sevral times +unless ($method eq "POST") { # Should not post sevral times for my $u (@users) { - next unless($u); + next unless ($u); my $p = $passwds[$i]; $i++; for my $t (@tokens) { - for my $c (@certs){ + for my $c (@certs) { + #if ($method eq "POST" and ($resource =~ /^\/nodes\/(\w+)$/)) { # `/opt/xcat/bin/rmdef $1`; # log_debug(2,"restapi test rmdef $1\n"); #} my $res = run_restapi($method, $resource, $data, $c, $port, $host, $u, $p, $t); - if($res){ + if ($res) { my $reshash = parse_json($res); - log_debug(2,"parse curl result and got:\n"); - log_debug(2,$reshash); + log_debug(2, "parse curl result and got:\n"); + log_debug(2, $reshash); if (%$reshash != %$defaulthash) { - log_debug(3, "restapi test cases run different result with $method, $resource, $data, $c, $port, $host, $u, $p, $t\n" ); + log_debug(3, "restapi test cases run different result with $method, $resource, $data, $c, $port, $host, $u, $p, $t\n"); exit 1; } } my $errcode = check_errcode(); - log_debug(2,"get curl error code: $errcode\n"); + log_debug(2, "get curl error code: $errcode\n"); if ($errcode != $defaulthttpresult) { - log_debug(3, "restapi test cases run different error code with $method, $resource, $data, $c, $port, $host, $u, $p, $t\n" ); + log_debug(3, "restapi test cases run different error code with $method, $resource, $data, $c, $port, $host, $u, $p, $t\n"); exit 1; } } @@ -213,12 +215,12 @@ unless ($method eq "POST") { # Should not post sevral times # check result ############################################################## if ($output) { - my $res = check_result($output,$loperator,$res); - log_debug(2, "check result runs with $output and $loperator, result is $res\n" ); + my $res = check_result($output, $loperator, $res); + log_debug(2, "check result runs with $output and $loperator, result is $res\n"); exit $res; } -exit $defaulthttpresult; +exit $defaulthttpresult; ################################################ # begin subroutine @@ -250,12 +252,12 @@ sub usage sub log_debug { my $flag = shift; - my $msg = shift; + my $msg = shift; if ($flag & 0x2) { - if($debug){ - if(ref($msg) eq 'HASH') { + if ($debug) { + if (ref($msg) eq 'HASH') { print Dumper($msg); - } elsif( ref($msg) eq 'ARRAY') { + } elsif (ref($msg) eq 'ARRAY') { print Dumper($msg); } else { print "$msg"; @@ -263,8 +265,8 @@ sub log_debug } } if ($flag & 0x1) { - open (LOG, ">>$logfile") - or return 1; + open(LOG, ">>$logfile") + or return 1; my $date = `date`; print LOG "$date\: $msg\n"; } @@ -274,18 +276,18 @@ sub log_debug ######################### sub run_restapi { - my ($m,$r,$d,$c,$p,$h,$u,$a,$t) = @_; + my ($m, $r, $d, $c, $p, $h, $u, $a, $t) = @_; my $cmd = "curl"; $cmd .= " -X $m"; unless ($c) { $cmd .= " -k "; - }else { + } else { $cmd .= " --cacert $c"; } - if($t){ + if ($t) { $cmd .= " -H X-Auth-Token:$t "; } - if($t or $c){ + if ($t or $c) { $cmd .= " 'https://$hostname"; } else { $cmd .= " 'https://$h"; @@ -295,21 +297,21 @@ sub run_restapi } $cmd .= "/xcatws"; $cmd .= "$r?"; - unless($t){ + unless ($t) { $cmd .= "userName=$u&password=$a'"; - }else { + } else { $cmd .= "'"; } - if($d) { + if ($d) { $cmd .= " -H Content-Type:application/json --data '$d'"; } $cmd .= " -D /tmp/err.log"; - log_debug(1,"Begin to run restapi test with $cmd"); + log_debug(1, "Begin to run restapi test with $cmd"); my $res = `$cmd 2>/dev/null`; - log_debug(2,"run curl: $cmd\n"); - log_debug(2,"result is $res\n"); - if (!open (RESULT, ">$outputfile")) { - log_debug(1,"wirte outputfile error"); + log_debug(2, "run curl: $cmd\n"); + log_debug(2, "result is $res\n"); + if (!open(RESULT, ">$outputfile")) { + log_debug(1, "wirte outputfile error"); } print RESULT $res; close RESULT; @@ -324,49 +326,55 @@ sub parse_json my $input = shift; my %hash; if ($input =~ /:/) { + # for those who look like: # {"networks":[{"mgtifname":"eth1","mask":"255.255.255.0"},{"mgtifname":"eth1","mask":"255.255.255.0"}]} if ($input =~ /^\[(.*)\]$/s) { my $content = $1; - log_debug(2, "[:] content is $content \n" ); + log_debug(2, "[:] content is $content \n"); parse_json($content); } + # for those who look like: # {"Vc68m4hsp01":{"parent":"Server-9119-590-SN02C5F9E","pprofile":"Vc68m4hsp01"},"p5ih_c75vios":{"parent":"P5IH-SN02012EB-A","mgt":"hmc","id":"2"},"p5ih_lpar04":{"parent":"P5IH-SN02013EB-A","pprofile":"p5ih_lpar04"}} - elsif($input =~ /^"(\S+?)\":{\S+},/){ + elsif ($input =~ /^"(\S+?)\":{\S+},/) { $input =~ s/},/}%/; my @contents = split /%/, $input; my @reval; + # record result foreach my $t (@contents) { - log_debug(2, ":{}, content is $t \n" ); - my $re = parse_json($t); - push @reval, $re; + log_debug(2, ":{}, content is $t \n"); + my $re = parse_json($t); + push @reval, $re; } + # merge hash foreach my $t (@reval) { - if(ref($t) =~ "HASH") { - foreach my $k (keys %$t){ + if (ref($t) =~ "HASH") { + foreach my $k (keys %$t) { $hash{$k} = $$t{$k}; } } } return \%hash; } - elsif( $input =~ /^{\S+},{\S+}/ and !($input =~ /]/)){ + elsif ($input =~ /^{\S+},{\S+}/ and !($input =~ /]/)) { $input =~ s/},{/}%{/; my @contents = split /%/, $input; my @reval; + # record result - foreach my $t (@contents) { - log_debug(2, "{},{}, content is $t \n" ); - my $re = parse_json($t); - push @reval, $re; + foreach my $t (@contents) { + log_debug(2, "{},{}, content is $t \n"); + my $re = parse_json($t); + push @reval, $re; } + # merge hash foreach my $t (@reval) { - if(ref($t) =~ "HASH") { - foreach my $k (keys %$t){ + if (ref($t) =~ "HASH") { + foreach my $k (keys %$t) { $hash{$k} = $$t{$k}; } } @@ -378,44 +386,49 @@ sub parse_json # {"clustersite":{"domain":"cluster.com","master":"192.168.1.15"}} elsif ($input =~ /^\s*{(.*)}\s*$/s) { my $content = $1; - log_debug(2, "{} content is $content \n" ); + log_debug(2, "{} content is $content \n"); parse_json($content); } - elsif( $input =~ /],\"\S+\":/){ + elsif ($input =~ /],\"\S+\":/) { $input =~ s/],\"(\S+)\":/]%\"$1\":/; my @contents = split /%/, $input; my @reval; + # record result - foreach my $t (@contents) { - log_debug(2, "],:, content is $t \n" ); - my $re = parse_json($t); - push @reval, $re; + foreach my $t (@contents) { + log_debug(2, "],:, content is $t \n"); + my $re = parse_json($t); + push @reval, $re; } + # merge hash foreach my $t (@reval) { - if(ref($t) =~ "HASH") { - foreach my $k (keys %$t){ + if (ref($t) =~ "HASH") { + foreach my $k (keys %$t) { $hash{$k} = $$t{$k}; } } } return \%hash; } + # for those who look like # "domain":"cluster.com","master":"192.168.1.15" elsif ($input =~ /,/ and !($input =~ /}/)) { my @contents = split /,/, $input; my @reval; + # record result foreach my $t (@contents) { - log_debug(2, ", content is $t \n"); - my $re = parse_json($t); - push @reval, $re; + log_debug(2, ", content is $t \n"); + my $re = parse_json($t); + push @reval, $re; } + # merge hash foreach my $t (@reval) { - if(ref($t) =~ "HASH") { - foreach my $k (keys %$t){ + if (ref($t) =~ "HASH") { + foreach my $k (keys %$t) { $hash{$k} = $$t{$k}; } } @@ -423,18 +436,21 @@ sub parse_json return \%hash; } + # for those who look like: # "clustersite":{"domain":"cluster.com","master":"192.168.1.15"} # "domain":"cluster.com" elsif ($input =~ /\"(\S+?)\":(.+)/s) { - my $key = $1; + my $key = $1; my $value = $2; if ($value =~ /{/) { + # "clustersite":{"domain":"cluster.com","master":"192.168.1.15"} - log_debug(2, "{ content is $value \n" ); - $hash{$key} = parse_json($value, $key); + log_debug(2, "{ content is $value \n"); + $hash{$key} = parse_json($value, $key); return \%hash; } else { + # "domain":"cluster.com" $value =~ /\"(\S+)\"/; $hash{$key} = $1; @@ -442,6 +458,7 @@ sub parse_json } } } + # for those who look like # ["10.1.255.250","192.168.200.16","192.168.200.19","192.168.200.22"] else { @@ -463,19 +480,19 @@ sub parse_json ############################ sub check_errcode { - if(!open (ERRLOG, "){ + while () { if (/HTTP\/\w*\.*\w* (\w+) (\w+)/) { - $num = $1; - last; + $num = $1; + last; } } close ERRLOG; - log_debug(2,"can't get errorcode\n") unless($num); + log_debug(2, "can't get errorcode\n") unless ($num); return $num; } @@ -484,11 +501,11 @@ sub check_errcode ############################ sub check_result { - my $data = shift; + my $data = shift; my $opterator = shift; - my $output = shift; - if ( !open (OUTPUT, "<$output")) { - log_debug(1,"can't read output file"); + my $output = shift; + if (!open(OUTPUT, "<$output")) { + log_debug(1, "can't read output file"); return 1; } my $res; @@ -498,87 +515,87 @@ sub check_result close OUTPUT; log_debug(2, "\nbegin to parse json for expected value: \n"); - my $expects = transf_hash(parse_json($data)); # one entry + my $expects = transf_hash(parse_json($data)); # one entry log_debug(2, "\nbegin to parse json for actual result: \n"); - my $actuals = transf_hash(parse_json($res)); # serval entries + my $actuals = transf_hash(parse_json($res)); # serval entries - log_debug(2,"expected result is:\n"); - log_debug(2,$expects); - log_debug(2,"testcase run result is \n"); - log_debug(2,$actuals); + log_debug(2, "expected result is:\n"); + log_debug(2, $expects); + log_debug(2, "testcase run result is \n"); + log_debug(2, $actuals); my $flag = 0; my %flaghash; - my $expect = $$expects[0]; # $expect = ANY:ANY:x86_64 + my $expect = $$expects[0]; # $expect = ANY:ANY:x86_64 - my @expectvalue = split /:/, $expect; #@expectvalue = ANY, ANY, x86_64 + my @expectvalue = split /:/, $expect; #@expectvalue = ANY, ANY, x86_64 $flag = 0; - foreach my $expval (@expectvalue) { # $expval = ANY - foreach my $actual (@$actuals) { # $actual = nodetype:arch:x86_64 - if($flaghash{$actual} eq "none"){ - next; + foreach my $expval (@expectvalue) { # $expval = ANY + foreach my $actual (@$actuals) { # $actual = nodetype:arch:x86_64 + if ($flaghash{$actual} eq "none") { + next; } my @actualvalue = split /:/, $actual; # @actualvalue = nodetype, arch, x86_64 - log_debug(2,"begin to compare $expval and $actualvalue[$flag]"); + log_debug(2, "begin to compare $expval and $actualvalue[$flag]"); - if(($expval eq "restapiarray" ) and ($actualvalue[$flag] eq "restapiarray")){ - next; - } + if (($expval eq "restapiarray") and ($actualvalue[$flag] eq "restapiarray")) { + next; + } - if(($expval eq $actualvalue[$flag]) or ($expval eq "ANY")) { #ANY =~ nodetype + if (($expval eq $actualvalue[$flag]) or ($expval eq "ANY")) { #ANY =~ nodetype $flaghash{$actual} = "eq"; } elsif (($actualvalue[$flag] =~ $expval) or ($expval eq "ANY")) { $flaghash{$actual} = "match"; } else { $flaghash{$actual} = "none"; } - log_debug(2,", compare result is $flaghash{$actual}\n"); + log_debug(2, ", compare result is $flaghash{$actual}\n"); } $flag++; } - log_debug(2,"search result is \n"); - log_debug(2,\%flaghash); + log_debug(2, "search result is \n"); + log_debug(2, \%flaghash); - if ($opterator eq "!="){ + if ($opterator eq "!=") { foreach my $val (keys %flaghash) { if ($flaghash{$val} eq "eq") { - log_debug(2,"compare result: failed\n"); - return 1; # fail + log_debug(2, "compare result: failed\n"); + return 1; # fail } - } - log_debug(2,"compare result: succeed\n"); - return 0; #succeed + } + log_debug(2, "compare result: succeed\n"); + return 0; #succeed } - if ($opterator eq "=="){ + if ($opterator eq "==") { foreach my $val (keys %flaghash) { if ($flaghash{$val} eq "eq") { - log_debug(2,"compare result: succeed\n"); - return 0; # succeed + log_debug(2, "compare result: succeed\n"); + return 0; # succeed } - } - log_debug(2,"compare result: failed\n"); - return 1; #fail + } + log_debug(2, "compare result: failed\n"); + return 1; #fail } - if ($opterator eq "=~"){ + if ($opterator eq "=~") { foreach my $val (keys %flaghash) { if ($flaghash{$val} eq "match") { - log_debug(2,"compare result: succeed\n"); - return 0; # succeed + log_debug(2, "compare result: succeed\n"); + return 0; # succeed } - } - log_debug(2,"compare result: failed\n"); - return 1; #fail + } + log_debug(2, "compare result: failed\n"); + return 1; #fail } - if ($opterator eq "!=~"){ + if ($opterator eq "!=~") { foreach my $val (keys %flaghash) { if ($flaghash{$val} eq "match") { - log_debug(2,"compare result: failed\n"); - return 1; # fail + log_debug(2, "compare result: failed\n"); + return 1; # fail } - } - log_debug(2,"compare result: succeed\n"); - return 0; #succeed + } + log_debug(2, "compare result: succeed\n"); + return 0; #succeed } } @@ -589,21 +606,21 @@ sub check_result sub find_key { my $input = shift; - my $en = shift; - my $ou = shift; - if( ref($input) =~ "HASH") { + my $en = shift; + my $ou = shift; + if (ref($input) =~ "HASH") { foreach my $val (keys %$input) { - my $tmp = $$en; # keey head + my $tmp = $$en; # keey head $$en .= "$val:"; my $t1 = find_key($$input{$val}, $en, $ou); - if ($$en eq ""){ - $$en = $tmp; #restore head + if ($$en eq "") { + $$en = $tmp; #restore head } } } else { $$en .= $input; push @$ou, $$en; - $$en = ""; # clear entry; + $$en = ""; # clear entry; } } diff --git a/xCAT-test/xcattest b/xCAT-test/xcattest index 12a6ec2d3..871da212f 100755 --- a/xCAT-test/xcattest +++ b/xCAT-test/xcattest @@ -12,24 +12,24 @@ BEGIN $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } use lib "$::XCATROOT/lib/perl"; -my $rootdir = "$::XCATROOT/share/xcat/tools/autotest"; -my $needhelp = 0; -my $configfile = "$rootdir/default.conf"; +my $rootdir = "$::XCATROOT/share/xcat/tools/autotest"; +my $needhelp = 0; +my $configfile = "$rootdir/default.conf"; my $bundle_list = undef; -my $case_list = undef; -my $cmd_list = undef; -my $needshow = 0; -my $restore = 0; -my $ret = 0; -my $string1 = undef; +my $case_list = undef; +my $cmd_list = undef; +my $needshow = 0; +my $restore = 0; +my $ret = 0; +my $string1 = undef; if ( - !GetOptions("h|?" => \$needhelp, - "f=s" => \$configfile, - "b=s" => \$bundle_list, - "t=s" => \$case_list, - "c=s" => \$cmd_list, - "l" => \$needshow, - "restore"=>\$restore) + !GetOptions("h|?" => \$needhelp, + "f=s" => \$configfile, + "b=s" => \$bundle_list, + "t=s" => \$case_list, + "c=s" => \$cmd_list, + "l" => \$needshow, + "restore" => \$restore) ) { &usage; @@ -52,14 +52,15 @@ if ($needhelp) # cmd: array # check: array -my @cases=(); -if($needshow){ +my @cases = (); +if ($needshow) { &loadcase; exit 0; } -my $resultdir = "$rootdir/result"; +my $resultdir = "$rootdir/result"; my $stop_to_keep_env = 0; + #Create result directory mkdir $resultdir unless -d $resultdir; @@ -77,40 +78,43 @@ open(LOG_ERR, ">$resultdir/failedcases.$timestamp") #config{script_prev}->[] #config{script_post}->[] #config{var}{varname} -my %config=(); +my %config = (); $ret = &getConfig; -if($ret != 0){ +if ($ret != 0) { goto EXIT; } $ret = &init; -if($ret != 0){ +if ($ret != 0) { goto EXIT; } my @filespath = (); + #loading and check cases $ret = &loadcase; -if($ret != 0){ +if ($ret != 0) { goto EXIT; } + #run case -&reordercases if(defined($bundle_list) || defined($case_list)); +&reordercases if (defined($bundle_list) || defined($case_list)); &runcase; EXIT: -if($restore){ +if ($restore) { &uninit; } &log_this("\nxCAT automated test finished at " . scalar(localtime())); &log_this("Please check results in the $resultdir, \nand see $resultdir/failedcases.$timestamp file for failed cases.\nsee $resultdir/performance.report.$timestamp file for time consumption"); close(LOG); close(LOG_ERR); -my $reportfile="$resultdir/performance.report.$timestamp"; -my $tmpreport="$resultdir/xcattest.log.$timestamp"; -&getreport($tmpreport,$reportfile); -if($stop_to_keep_env){ +my $reportfile = "$resultdir/performance.report.$timestamp"; +my $tmpreport = "$resultdir/xcattest.log.$timestamp"; +&getreport($tmpreport, $reportfile); + +if ($stop_to_keep_env) { exit 1; -}else{ +} else { exit 0; } @@ -122,7 +126,7 @@ if($stop_to_keep_env){ sub log_this { - if($needshow){ + if ($needshow) { return; } print LOG join("\n", @_), "\n"; @@ -146,74 +150,74 @@ sub getConfig log_this("******************************"); log_this("Reading Configure"); log_this("******************************"); - if(!(-e $configfile)){ - log_this("Warning: The xCAT test Configure file doesn't exist!"); - return 0; + if (!(-e $configfile)) { + log_this("Warning: The xCAT test Configure file doesn't exist!"); + return 0; } - my $type = undef; #Script_Prev,Script_Post,Table,Object,System,Custom - my $sub_type = undef; # The string after $type_ - # Script--> - # Script_Prev - # Script_Post - # Table---> - # Table_xxxxx - # Object--> - # Object_xxxx - # System----> - # Custom----> + my $type = undef; #Script_Prev,Script_Post,Table,Object,System,Custom + my $sub_type = undef; # The string after $type_ + # Script--> + # Script_Prev + # Script_Post + # Table---> + # Table_xxxxx + # Object--> + # Object_xxxx + # System----> + # Custom----> - my $name = undef; - my $attr = undef; + my $name = undef; + my $attr = undef; my $value = undef; - my $c = 0; - my $cmd = undef; + my $c = 0; + my $cmd = undef; my $mgt_name = undef; open(FILE, "$configfile") or die "can't to open $configfile"; - while(my $line = ) { + while (my $line = ) { $line = &trim($line); - next if(length($line) == 0); + next if (length($line) == 0); #Table name can not contain "_" - if($line =~ /\[\s*(\w+)\_(\w+)\s*\]/) { - $type = $1; + if ($line =~ /\[\s*(\w+)\_(\w+)\s*\]/) { + $type = $1; $sub_type = $2; - $name = undef; - $c = 0; - }elsif($line =~ /\[\s*System|Custom\s*\]/){ + $name = undef; + $c = 0; + } elsif ($line =~ /\[\s*System|Custom\s*\]/) { $type = "Varible"; - }elsif ($type eq "Table") { + } elsif ($type eq "Table") { ##TABLE BLOCK## - if($line =~ /(\w+)\s*=\s*([\w\.\-]+)/) { - $attr = $1; + if ($line =~ /(\w+)\s*=\s*([\w\.\-]+)/) { + $attr = $1; $value = $2; - if($name&&($config{table}{$sub_type}{$name}{__KEY__} ne $attr)){ - $config{table}{$sub_type}{$name}{$attr}=$value; + if ($name && ($config{table}{$sub_type}{$name}{__KEY__} ne $attr)) { + $config{table}{$sub_type}{$name}{$attr} = $value; } else { $name = $value; - $config{table}{$sub_type}{$name}{__KEY__}=$attr; + $config{table}{$sub_type}{$name}{__KEY__} = $attr; } } - }elsif ($type eq "Object") { + } elsif ($type eq "Object") { ##OBJECT BLOCK## - if($line =~ /(\w+)\s*=\s*([:\w\.\-\/]+)/) { - $attr = $1; - $value = $2; - if($attr eq "Name"){ - $name = $value; - } elsif(!defined($name)){ - print "Please give name for Object\n"; - close FILE; - return 1; - } else { - $config{object}{$sub_type}{$name}{$attr}=$value; - } + if ($line =~ /(\w+)\s*=\s*([:\w\.\-\/]+)/) { + $attr = $1; + $value = $2; + if ($attr eq "Name") { + $name = $value; + } elsif (!defined($name)) { + print "Please give name for Object\n"; + close FILE; + return 1; + } else { + $config{object}{$sub_type}{$name}{$attr} = $value; + } } - }elsif ($type eq "Script") { + } elsif ($type eq "Script") { ##SCRIPT_BLOCK## - if($sub_type eq "Prev") { + if ($sub_type eq "Prev") { $config{script_prev}->[$c] = $line; $c = $c + 1; } @@ -223,29 +227,29 @@ sub getConfig } } elsif ($type eq "Varible") { ##NODE_BLOCK## - if($line =~ /(\w+)\s*=\s*([\w\.\-\+\/:]+)/) { + if ($line =~ /(\w+)\s*=\s*([\w\.\-\+\/:]+)/) { $config{var}{$1} = $2; } } } - if(exists $config{object}){ - foreach my $type (keys %{$config{object}}){ - foreach my $name (keys %{$config{object}{$type}}){ + if (exists $config{object}) { + foreach my $type (keys %{ $config{object} }) { + foreach my $name (keys %{ $config{object}{$type} }) { log_this("OBJECT:$name,TYPE:$type"); - foreach my $attr (keys %{$config{object}{$type}{$name}}){ + foreach my $attr (keys %{ $config{object}{$type}{$name} }) { log_this(" $attr = $config{object}{$type}{$name}{$attr};"); } } } } - if(exists $config{table}){ - foreach my $type (keys %{$config{table}}){ + if (exists $config{table}) { + foreach my $type (keys %{ $config{table} }) { log_this("TABLE:$type"); - foreach my $name (keys %{$config{table}{$type}}){ + foreach my $name (keys %{ $config{table}{$type} }) { log_this(" $config{table}{$type}{$name}{__KEY__} = $name"); - foreach my $attr (keys %{$config{table}{$type}{$name}}){ - if($attr ne '__KEY__'){ + foreach my $attr (keys %{ $config{table}{$type}{$name} }) { + if ($attr ne '__KEY__') { log_this(" $attr = $config{table}{$type}{$name}{$attr}"); } } @@ -253,23 +257,23 @@ sub getConfig } } } - if(exists $config{script_prev}){ + if (exists $config{script_prev}) { log_this("Script_Prev:"); - foreach $cmd (@{$config{script_prev}}){ + foreach $cmd (@{ $config{script_prev} }) { log_this(" $cmd"); } } - if(exists $config{script_post}){ + if (exists $config{script_post}) { log_this("Script_Post:"); - foreach $cmd (@{$config{script_post}}){ + foreach $cmd (@{ $config{script_post} }) { log_this(" $cmd"); } } - if(exists $config{var}){ + if (exists $config{var}) { log_this("Varible:"); - foreach my $varname (keys %{$config{var}}){ + foreach my $varname (keys %{ $config{var} }) { log_this(" $varname = $config{var}{$varname}"); } } @@ -280,13 +284,13 @@ sub getConfig sub init { - if($restore){ + if ($restore) { log_this("******************************"); log_this("Backup current xCAT database"); log_this("******************************"); &runcmd("mkdir -p /tmp/xCATdbbackup"); &runcmd("dumpxCATdb -p /tmp/xCATdbbackup"); - if($::RUNCMD_RC != 0){ + if ($::RUNCMD_RC != 0) { &log_this("Fail to backup xCAT database"); &runcmd("rm -rf /tmp/xCATdbbackup"); $restore = 0; @@ -297,42 +301,42 @@ sub init log_this("Initialize xCAT test evironment"); log_this("******************************"); my $cmd = undef; - foreach $cmd (@{$config{script_prev}}){ + foreach $cmd (@{ $config{script_prev} }) { log_this("$cmd"); &runcmd($cmd); - if($::RUNCMD_RC != 0){ + if ($::RUNCMD_RC != 0) { &log_this("Fail to run $cmd"); return 1; } } - if(exists $config{object}){ - foreach my $type (keys %{$config{object}}){ - foreach my $name (keys %{$config{object}{$type}}){ + if (exists $config{object}) { + foreach my $type (keys %{ $config{object} }) { + foreach my $name (keys %{ $config{object}{$type} }) { $cmd = "chdef -t $type -o $name"; - foreach my $attr (keys %{$config{object}{$type}{$name}}){ - $cmd = $cmd." $attr=$config{object}{$type}{$name}{$attr}"; + foreach my $attr (keys %{ $config{object}{$type}{$name} }) { + $cmd = $cmd . " $attr=$config{object}{$type}{$name}{$attr}"; } log_this($cmd); runcmd($cmd); - if($::RUNCMD_RC != 0){ + if ($::RUNCMD_RC != 0) { log_this("Fail to run $cmd"); return 1; } } } } - if(exists $config{table}){ - foreach my $type (keys %{$config{table}}){ - foreach my $name (keys %{$config{table}{$type}}){ + if (exists $config{table}) { + foreach my $type (keys %{ $config{table} }) { + foreach my $name (keys %{ $config{table}{$type} }) { $cmd = "chtab $config{table}{$type}{$name}{__KEY__}=$name"; - foreach my $attr (keys %{$config{table}{$type}{$name}}){ - if($attr ne '__KEY__'){ - $cmd = $cmd." $type.$attr=$config{table}{$type}{$name}{$attr}"; + foreach my $attr (keys %{ $config{table}{$type}{$name} }) { + if ($attr ne '__KEY__') { + $cmd = $cmd . " $type.$attr=$config{table}{$type}{$name}{$attr}"; } } log_this($cmd); &runcmd($cmd); - if($::RUNCMD_RC != 0){ + if ($::RUNCMD_RC != 0) { &log_this("Fail to run $cmd"); return 1; } @@ -340,30 +344,30 @@ sub init } } - if(!exists $config{var}{OS}){ + if (!exists $config{var}{OS}) { my @output = runcmd("uname"); $config{var}{OS} = $output[0]; log_this("Detecting: OS = $config{var}{OS}"); } else { - $config{var}{OS} = lc($config{var}{OS}); - } - - if(!exists $config{var}{ARCH}){ - if(!exists $config{var}{CN}){ + $config{var}{OS} = lc($config{var}{OS}); + } + + if (!exists $config{var}{ARCH}) { + if (!exists $config{var}{CN}) { $config{var}{ARCH} = "Unknown"; log_this("No compute node defined,can't get ARCH of compute node"); } else { - $config{var}{ARCH} = getnodeattr($config{var}{CN},"arch"); - if($config{var}{ARCH} =~ /ppc/){ + $config{var}{ARCH} = getnodeattr($config{var}{CN}, "arch"); + if ($config{var}{ARCH} =~ /ppc/) { $config{var}{ARCH} = 'ppc'; - }elsif($config{var}{ARCH}=~/86/){ + } elsif ($config{var}{ARCH} =~ /86/) { $config{var}{ARCH} = 'x86'; } log_this("Detecting: ARCH = $config{var}{ARCH}"); } } - if(!exists $config{var}{HCP}){ - if(!exists $config{var}{CN}){ + if (!exists $config{var}{HCP}) { + if (!exists $config{var}{CN}) { $config{var}{HCP} = "Unknown"; log_this("No compute node defined,can't get HCP TYPE of compute node"); } else { @@ -380,37 +384,38 @@ sub uninit log_this("******************************"); log_this("un-initialize xCAT test evironment"); log_this("******************************"); - my $cmd = undef;; -# if(exists $config{object}){ -# foreach my $type (keys %{$config{object}}){ -# foreach my $name (keys %{$config{object}{$type}}){ -# $cmd = "rmdef -t $type -o $name"; -# log_this($cmd); -# runcmd($cmd); -# if($::RUNCMD_RC != 0){ -# log_this("Fail to run $cmd"); -# return 1; -# } -# } -# } -# } -# if(exists $config{table}){ -# foreach my $type (keys %{$config{table}}){ -# foreach my $name (keys %{$config{table}{$type}}){ -# $cmd = "chtab -d $config{table}{$type}{$name}{__KEY__}=$name $type"; -# log_this($cmd); -# runcmd($cmd); -# if($::RUNCMD_RC != 0){ -# log_this("Fail to run $cmd"); -# return 1; -# } -# } -# } -# } - foreach $cmd (@{$config{script_post}}){ + my $cmd = undef; + + # if(exists $config{object}){ + # foreach my $type (keys %{$config{object}}){ + # foreach my $name (keys %{$config{object}{$type}}){ + # $cmd = "rmdef -t $type -o $name"; + # log_this($cmd); + # runcmd($cmd); + # if($::RUNCMD_RC != 0){ + # log_this("Fail to run $cmd"); + # return 1; + # } + # } + # } + # } + # if(exists $config{table}){ + # foreach my $type (keys %{$config{table}}){ + # foreach my $name (keys %{$config{table}{$type}}){ + # $cmd = "chtab -d $config{table}{$type}{$name}{__KEY__}=$name $type"; + # log_this($cmd); + # runcmd($cmd); + # if($::RUNCMD_RC != 0){ + # log_this("Fail to run $cmd"); + # return 1; + # } + # } + # } + # } + foreach $cmd (@{ $config{script_post} }) { log_this($cmd); runcmd($cmd); - if($::RUNCMD_RC != 0){ + if ($::RUNCMD_RC != 0) { log_this("Fail to run $cmd"); return 1; } @@ -420,32 +425,34 @@ sub uninit &runcmd("rm -rf /tmp/xCATdbbackup"); return 0; } + sub Get_Files_Recursive { - my $dir = $_[0]; - foreach $dir (@_) + my $dir = $_[0]; + foreach $dir (@_) + { + opendir(my $d, $dir); + for (; ;) { - opendir(my $d, $dir) ; - for (;;) - { - my $direntry = readdir($d); - last unless defined $direntry; - next if $direntry =~ m/^\.\w*/; - next if $direntry eq '..'; - if ( -d $dir."/".$direntry) - { - Get_Files_Recursive ($dir."/".$direntry); - } - else - { my $dirpath = $dir.'/'.$direntry."\n"; - print $dir.'/'.$direntry."\n"; - #print $dir."\n"; - push (@filespath, glob("$dirpath")); + my $direntry = readdir($d); + last unless defined $direntry; + next if $direntry =~ m/^\.\w*/; + next if $direntry eq '..'; + if (-d $dir . "/" . $direntry) + { + Get_Files_Recursive($dir . "/" . $direntry); + } + else + { my $dirpath = $dir . '/' . $direntry . "\n"; + print $dir. '/' . $direntry . "\n"; - } - } - closedir($d); + #print $dir."\n"; + push(@filespath, glob("$dirpath")); + + } } + closedir($d); + } } @@ -455,7 +462,8 @@ sub loadcase log_this("loading test cases"); log_this("******************************"); my $casedir = "/opt/xcat/share/xcat/tools/autotest/testcase"; - my @files = (); + my @files = (); + #if($cmd_list){ # my @cmds = split /,/,$cmd_list; # for my $cmd (@cmds){ @@ -465,160 +473,162 @@ sub loadcase # @files = glob("$casedir/*/*"); #} Get_Files_Recursive("$casedir"); - for(my $countfile = 0; $countfile<@filespath; $countfile++) - { - if ($cmd_list){ - my @cmds = split /,/,$cmd_list; - for( my $countcmd = 0; $countcmd<@cmds; $countcmd++){ - if ($filespath[$countfile] =~ m/\/$cmds[$countcmd]\/case/){ - push (@files, glob("$filespath[$countfile]")); - } - } - } else{ - push (@files, glob("$filespath[$countfile]")); - } - } + for (my $countfile = 0 ; $countfile < @filespath ; $countfile++) + { + if ($cmd_list) { + my @cmds = split /,/, $cmd_list; + for (my $countcmd = 0 ; $countcmd < @cmds ; $countcmd++) { + if ($filespath[$countfile] =~ m/\/$cmds[$countcmd]\/case/) { + push(@files, glob("$filespath[$countfile]")); + } + } + } else { + push(@files, glob("$filespath[$countfile]")); + } + } my $file; my $line; - my $i = 0; - my $j = -1; - my $z = 0; + my $i = 0; + my $j = -1; + my $z = 0; my $skip = 0; - my @caserange = (); - my @rightcase = (); + my @caserange = (); + my @rightcase = (); my @notrightcase = (); - if($bundle_list){ + if ($bundle_list) { my @bundles = split /,/, $bundle_list; - foreach my $bundle (@bundles){ - if(!open(FILE, "<$rootdir/bundle/$bundle")){ + foreach my $bundle (@bundles) { + if (!open(FILE, "<$rootdir/bundle/$bundle")) { log_this("can't open $rootdir/bundle/$bundle"); return 1; } - while($line=){ + while ($line = ) { $line = trim($line); - next if(length($line) == 0); + next if (length($line) == 0); push(@caserange, $line); } close(FILE); } } - if($case_list){ - @caserange = split /,/, $case_list; + if ($case_list) { + @caserange = split /,/, $case_list; } - foreach $file (@files){ - if(!open(FILE, "<$file")){ + foreach $file (@files) { + if (!open(FILE, "<$file")) { log_this("can't open $file"); return 1; } - while($line=){ + while ($line = ) { $line = &trim($line); - next if(length($line) == 0); - #skip comment lines - next if($line =~ /^\s*#/); - #TODO: description line is treated as a comment line for now - next if($line =~ /^description\s*:/); + next if (length($line) == 0); - if($line =~ /^start\s*:\s*([\w-]+)/){ + #skip comment lines + next if ($line =~ /^\s*#/); + + #TODO: description line is treated as a comment line for now + next if ($line =~ /^description\s*:/); + + if ($line =~ /^start\s*:\s*([\w-]+)/) { $skip = 0; my $name = $1; - if( $caserange[0] && !(grep {/^$name$/} @caserange)){ + if ($caserange[0] && !(grep { /^$name$/ } @caserange)) { $skip = 1; next; } - $j = -1; - $cases[$i]={}; - $cases[$i]->{name}=$name; - $cases[$i]->{filename}=$file; - if(!$needshow){ - $cases[$i]->{cmd}=[]; - $cases[$i]->{check}=[]; - $cases[$i]->{cmdcheck}=[]; + $j = -1; + $cases[$i] = {}; + $cases[$i]->{name} = $name; + $cases[$i]->{filename} = $file; + if (!$needshow) { + $cases[$i]->{cmd} = []; + $cases[$i]->{check} = []; + $cases[$i]->{cmdcheck} = []; push(@rightcase, $name); - }else{ + } else { $skip = 1; - $i = $i + 1; + $i = $i + 1; } - }elsif($line =~ /^os\s*:\s*(\w[\w\,]+)/){ + } elsif ($line =~ /^os\s*:\s*(\w[\w\,]+)/) { next if $skip; - $string1=$1; - if($string1 =~ /^rhels\s*/ && -f "/etc/redhat-release"){ - $cases[$i]->{os}="rhels"; - }elsif($string1 =~ /^sles\s*/ && -f "/etc/SuSE-release"){ - $cases[$i]->{os}="sles"; - }elsif($string1 =~ /^ubuntu\s*/ && -f "/etc/lsb-release"){ - $cases[$i]->{os}="ubuntu"; + $string1 = $1; + if ($string1 =~ /^rhels\s*/ && -f "/etc/redhat-release") { + $cases[$i]->{os} = "rhels"; + } elsif ($string1 =~ /^sles\s*/ && -f "/etc/SuSE-release") { + $cases[$i]->{os} = "sles"; + } elsif ($string1 =~ /^ubuntu\s*/ && -f "/etc/lsb-release") { + $cases[$i]->{os} = "ubuntu"; } - else{ - $cases[$i]->{os}=$string1; + else { + $cases[$i]->{os} = $string1; } chomp($cases[$i]->{os}); - chomp($config{var}{OS}); - if($cases[$i]->{os} !~ /$config{var}{OS}/){ - if((($config{var}{OS} =~ /^Linux\s*/i) && ($cases[$i]->{os} =~ /^aix\s*/i)) || (($config{var}{OS} =~ /^aix\s*/i) && ($cases[$i]->{os} !~ /^aix\s*/i)) || (($config{var}{OS} =~ /^rhels\s*/i) && ($cases[$i]->{os} !~ /^Linux\s*/i)) || (($config{var}{OS} =~ /^sles\s*/i) && ($cases[$i]->{os} !~ /^Linux\s*/i)) || (($config{var}{OS} =~ /^ubuntu\s*/i) && ($cases[$i]->{os} !~ /^Linux\s*/i))){ + chomp($config{var}{OS}); + if ($cases[$i]->{os} !~ /$config{var}{OS}/) { + if ((($config{var}{OS} =~ /^Linux\s*/i) && ($cases[$i]->{os} =~ /^aix\s*/i)) || (($config{var}{OS} =~ /^aix\s*/i) && ($cases[$i]->{os} !~ /^aix\s*/i)) || (($config{var}{OS} =~ /^rhels\s*/i) && ($cases[$i]->{os} !~ /^Linux\s*/i)) || (($config{var}{OS} =~ /^sles\s*/i) && ($cases[$i]->{os} !~ /^Linux\s*/i)) || (($config{var}{OS} =~ /^ubuntu\s*/i) && ($cases[$i]->{os} !~ /^Linux\s*/i))) { push(@notrightcase, $cases[$i]->{name}); pop(@rightcase); $skip = 1; } } - }elsif($line =~ /^arch\s*:\s*(\w[\w\,]+)/){ + } elsif ($line =~ /^arch\s*:\s*(\w[\w\,]+)/) { next if $skip; - $cases[$i]->{arch}=$1; - if($cases[$i]->{arch} !~ /$config{var}{ARCH}/){ + $cases[$i]->{arch} = $1; + if ($cases[$i]->{arch} !~ /$config{var}{ARCH}/) { push(@notrightcase, $cases[$i]->{name}); pop(@rightcase); $skip = 1; } - }elsif($line =~ /^hcp\s*:\s*(\w[\w\,]+)/){ + } elsif ($line =~ /^hcp\s*:\s*(\w[\w\,]+)/) { next if $skip; - $cases[$i]->{hcp}=$1; - if($cases[$i]->{hcp} !~ /$config{var}{HCP}/){ + $cases[$i]->{hcp} = $1; + if ($cases[$i]->{hcp} !~ /$config{var}{HCP}/) { push(@notrightcase, $cases[$i]->{name}); pop(@rightcase); $skip = 1; } - }elsif($line =~ /^type\s*:\s*(\w[\w\,-]+)/){ + } elsif ($line =~ /^type\s*:\s*(\w[\w\,-]+)/) { next if $skip; - $cases[$i]->{type}=$1; - if($cases[$i]->{type} !~ /$config{var}{TYPE}/){ + $cases[$i]->{type} = $1; + if ($cases[$i]->{type} !~ /$config{var}{TYPE}/) { push(@notrightcase, $cases[$i]->{name}); pop(@rightcase); $skip = 1; } - }elsif($line =~ /^stop\s*:\s*(\w[\w\,]+)/){ + } elsif ($line =~ /^stop\s*:\s*(\w[\w\,]+)/) { next if $skip; - $cases[$i]->{stop}=$1; - }elsif($line =~ /^cmd\s*:\s*([\/\$\w].+)/){ + $cases[$i]->{stop} = $1; + } elsif ($line =~ /^cmd\s*:\s*([\/\$\w].+)/) { next if $skip; - $j = $j + 1; - $z = 0; - $cases[$i]->{cmd}->[$j]=&getvar($1); - if($cases[$i]->{cmd}->[$j] eq ''){ + $j = $j + 1; + $z = 0; + $cases[$i]->{cmd}->[$j] = &getvar($1); + if ($cases[$i]->{cmd}->[$j] eq '') { close(FILE); return 1; } - }elsif($line =~ /^check\s*:\s*(\w.+)/){ + } elsif ($line =~ /^check\s*:\s*(\w.+)/) { next if $skip; $cases[$i]->{check}->[$j][$z] = &getvar($1); - if($cases[$i]->{check}->[$j][$z] eq ''){ + if ($cases[$i]->{check}->[$j][$z] eq '') { close(FILE); return 1; } $z = $z + 1; - }elsif($line =~ /^cmdcheck\s*:\s*(\w.+)/){ + } elsif ($line =~ /^cmdcheck\s*:\s*(\w.+)/) { next if $skip; $cases[$i]->{cmdcheck}->[$j][$z] = &getvar($1); - if($cases[$i]->{cmdcheck}->[$j][$z] eq ''){ + if ($cases[$i]->{cmdcheck}->[$j][$z] eq '') { close(FILE); return 1; } $z = $z + 1; - }elsif($line =~ /^end/){ + } elsif ($line =~ /^end/) { next if $skip; $i = $i + 1; } @@ -626,13 +636,13 @@ sub loadcase close(FILE); } - if($needshow){ - foreach my $case (@cases){ + if ($needshow) { + foreach my $case (@cases) { print "$case->{name}\n"; } return 0; } - log_this("To run:", @rightcase); + log_this("To run:", @rightcase); log_this("Not to run:", @notrightcase); return 0; } @@ -641,19 +651,20 @@ sub getnodeattr { my ($node, $attr) = @_; my @output = runcmd("lsdef -t node -o $node -i $attr"); - my $t ; - if($::RUNCMD_RC){ - # return "Unknown"; - foreach $t (1 .. 40) { - log_this("could not get node attr $attr "); - @output = runcmd("lsdef -t node -o $node -i $attr"); - last if ($::RUNCMD_RC == 0); - } + my $t; + if ($::RUNCMD_RC) { + + # return "Unknown"; + foreach $t (1 .. 40) { + log_this("could not get node attr $attr "); + @output = runcmd("lsdef -t node -o $node -i $attr"); + last if ($::RUNCMD_RC == 0); + } } - if($::RUNCMD_RC == 0){ - foreach my $output1 (@output){ - if($output1 =~ /$attr=(\w.+)/){ + if ($::RUNCMD_RC == 0) { + foreach my $output1 (@output) { + if ($output1 =~ /$attr=(\w.+)/) { log_this("$attr is $1"); return $1; } @@ -661,30 +672,34 @@ sub getnodeattr } return "Unknown"; } + sub gettablevalue { - my($keyname, $key, $colname, $table) = @_; + my ($keyname, $key, $colname, $table) = @_; my @output = runcmd("gettab $keyname=$key $table\.$colname"); return $output[0]; } + #to remove space and comment sub trim { - my $str = shift @_; - if($str){ -# $str =~ s/\#/__wellnumber__/g; - $str =~ s/^\s+|#.+|\s+$//g; - # $str =~ s/__wellnumber__/#/g; - } - return $str; + my $str = shift @_; + if ($str) { + + # $str =~ s/\#/__wellnumber__/g; + $str =~ s/^\s+|#.+|\s+$//g; + + # $str =~ s/__wellnumber__/#/g; + } + return $str; } sub getvar { my $str = shift @_; - while($str =~ /\$\$(\w+)/){ + while ($str =~ /\$\$(\w+)/) { my $varname = $1; - if(exists ($config{var}{$varname})){ + if (exists($config{var}{$varname})) { $str =~ s/\$\$$varname/$config{var}{$varname}/g; } else { log_this("Error:can't get varible $varname"); @@ -693,90 +708,94 @@ sub getvar } return $str; } + sub getfunc { - my $str = shift @_; - my $func = undef; - my @para = (); + my $str = shift @_; + my $func = undef; + my @para = (); my $parameter = undef; - my $value = undef; - while($str =~ /__(\w+)\(([\s\,\w\$]*)\)__/){ - $func = $1; + my $value = undef; + while ($str =~ /__(\w+)\(([\s\,\w\$]*)\)__/) { + $func = $1; $parameter = $2; log_this("parameter is $parameter,fun is $func"); @para = split /\s*,\s*/, trim($parameter); - if($func eq "GETNODEATTR"){ - $value= getnodeattr(@para); + if ($func eq "GETNODEATTR") { + $value = getnodeattr(@para); log_this("value is $value"); - if($value eq "Unknown"){ + if ($value eq "Unknown") { $value = ''; } - }elsif($func eq "INC"){ + } elsif ($func eq "INC") { $value = $para[0] + 1; - }elsif($func eq "GETTABLEVALUE"){ - $value= gettablevalue(@para); + } elsif ($func eq "GETTABLEVALUE") { + $value = gettablevalue(@para); } $str =~ s/__$func\($parameter\)__/$value/g; } return $str; } + sub runcase { log_this("******************************"); log_this("Start to run test cases"); log_this("******************************"); - my @output = (); - my $rc = 0; - my $j = 0; - my $z = 0; - my $lvalue = undef; - my $rvalue = undef; - my $op = undef; - my $failed = 0; - my $total = 0; + my @output = (); + my $rc = 0; + my $j = 0; + my $z = 0; + my $lvalue = undef; + my $rvalue = undef; + my $op = undef; + my $failed = 0; + my $total = 0; my $failnum = 0; - foreach my $case (@cases){ + foreach my $case (@cases) { my @record = (); $failed = 0; - $j = 0; - $total = $total + 1; - my $now1=timelocal(localtime()); - my $time1=scalar(localtime()); + $j = 0; + $total = $total + 1; + my $now1 = timelocal(localtime()); + my $time1 = scalar(localtime()); log_this("------START:$$case{name}::Time:$time1------"); push @record, "------START:$$case{name}::Time:$time1------"; push @record, "FILENAME:$$case{filename}"; - foreach my $cmd (@{$$case{cmd}}){ + + foreach my $cmd (@{ $$case{cmd} }) { $cmd = getfunc($cmd); -#by - my $runstart=timelocal(localtime()); + #by + my $runstart = timelocal(localtime()); log_this("\nRUN:$cmd"); push(@record, "\nRUN:$cmd"); @output = &runcmd($cmd); - $rc = $::RUNCMD_RC; -#by - my $runstop=timelocal(localtime()); - my $diffduration=$runstop-$runstart; + $rc = $::RUNCMD_RC; + + #by + my $runstop = timelocal(localtime()); + my $diffduration = $runstop - $runstart; log_this("\n[$cmd] Running Time:$diffduration sec"); - push(@record,("\n[$cmd] Running Time:$diffduration sec")); + push(@record, ("\n[$cmd] Running Time:$diffduration sec")); - log_this("RETURN: rc = $rc","OUTPUT:",@output); - push(@record,("RETURN rc = $rc","OUTPUT:",@output)); + log_this("RETURN: rc = $rc", "OUTPUT:", @output); + push(@record, ("RETURN rc = $rc", "OUTPUT:", @output)); - foreach my $check (@{$$case{check}->[$j]}){ - if($failed){ + foreach my $check (@{ $$case{check}->[$j] }) { + if ($failed) { last; } - if($check =~ /rc\s*([=!]+)\s*(\d+)/){ + if ($check =~ /rc\s*([=!]+)\s*(\d+)/) { $lvalue = $rc; - $op = $1; + $op = $1; $rvalue = $2; - if((($op eq '!=') && ($lvalue == $rvalue)) - ||(($op eq '==') && ($lvalue != $rvalue))){ + if ((($op eq '!=') && ($lvalue == $rvalue)) + || (($op eq '==') && ($lvalue != $rvalue))) { $failed = 1; } - if($failed){ + if ($failed) { log_this("CHECK:rc $op $rvalue\t[Failed]"); push(@record, "CHECK:rc $op $rvalue\t[Failed]"); last; @@ -785,18 +804,18 @@ sub runcase push(@record, "CHECK:rc $op $rvalue\t[Pass]"); } } elsif ($check =~ /output\s*([=!~]+)\s*(\S.*)/ - && $check !~ /output\s*([=!~])\1/){ - $lvalue = join ("\n",@output); - $op = $1; + && $check !~ /output\s*([=!~])\1/) { + $lvalue = join("\n", @output); + $op = $1; $rvalue = $2; $rvalue = getfunc($rvalue); - if((($op eq '=~' )&&($lvalue !~ /$rvalue/)) - ||(($op eq '!~')&&($lvalue =~ /$rvalue/)) - ||(($op eq '==')&&($lvalue ne $rvalue)) - ||(($op eq '!=')&&($lvalue eq $rvalue))){ + if ((($op eq '=~') && ($lvalue !~ /$rvalue/)) + || (($op eq '!~') && ($lvalue =~ /$rvalue/)) + || (($op eq '==') && ($lvalue ne $rvalue)) + || (($op eq '!=') && ($lvalue eq $rvalue))) { $failed = 1; } - if($failed){ + if ($failed) { log_this("CHECK:output $op $rvalue\t[Failed]"); push(@record, "CHECK:output $op $rvalue\t[Failed]"); last; @@ -804,33 +823,33 @@ sub runcase log_this("CHECK:output $op $rvalue\t[Pass]"); push(@record, "CHECK:output $op $rvalue\t[Pass]"); } - } elsif ($check =~ /output\s*~~\s*(\S.*)/){ - $op = "~~"; + } elsif ($check =~ /output\s*~~\s*(\S.*)/) { + $op = "~~"; $failed = 1; $rvalue = $1; $rvalue = getfunc($rvalue); my $num; if ($rvalue =~ /(\d+)/) { - $num = $1; + $num = $1; } $rvalue =~ s/(\d+)//; foreach my $line (@output) { - chomp($line); - if ($line =~ /$rvalue/) { - if ($num =~ /^\d+$/) { - my $max = $num *1.1; - my $min = $num *0.9; - $line =~ /.*:.*: (\d+) /; - if ($1 < $max && $1 > $min) { - $failed = 0; - last; - } - } else { - next; - } - } + chomp($line); + if ($line =~ /$rvalue/) { + if ($num =~ /^\d+$/) { + my $max = $num * 1.1; + my $min = $num * 0.9; + $line =~ /.*:.*: (\d+) /; + if ($1 < $max && $1 > $min) { + $failed = 0; + last; + } + } else { + next; + } + } } - if($failed){ + if ($failed) { log_this("CHECK:output $op $rvalue $num\t[Failed]"); push(@record, "CHECK:output $op $rvalue\t[Failed]"); last; @@ -840,11 +859,11 @@ sub runcase } } } - foreach my $cmdcheck (@{$$case{cmdcheck}->[$j]}){ - if($cmdcheck) { + foreach my $cmdcheck (@{ $$case{cmdcheck}->[$j] }) { + if ($cmdcheck) { &runcmd($cmdcheck); $rc = $::RUNCMD_RC; - if($rc == 1) { + if ($rc == 1) { log_this("CMDCHECK:output $cmdcheck\t[Failed]"); push(@record, "CHECK:output $cmdcheck\t[Failed]"); } elsif ($rc == 0) { @@ -855,21 +874,21 @@ sub runcase } $j = $j + 1; } - my $now2=timelocal(localtime()); + my $now2 = timelocal(localtime()); my $time2 = scalar(localtime()); - my $diff=$now2-$now1; - if($failed){ + my $diff = $now2 - $now1; + if ($failed) { log_this("------END::$$case{name}::Failed::Time:$time2 ::Duration::$diff sec------"); - push (@record,"------END::$$case{name}::Failed::Time:$time2 ::Duration::$diff sec------"); + push(@record, "------END::$$case{name}::Failed::Time:$time2 ::Duration::$diff sec------"); } else { - log_this("------END::$$case{name}::Passed::Time:$time2 ::Duration::$diff sec------"); - push (@record,"------END::$$case{name}::Passed::Time:$time2 ::Duration::$diff sec------"); + log_this("------END::$$case{name}::Passed::Time:$time2 ::Duration::$diff sec------"); + push(@record, "------END::$$case{name}::Passed::Time:$time2 ::Duration::$diff sec------"); } - if($failed){ + if ($failed) { $failnum = $failnum + 1; log_error(@record); - if(defined ($$case{stop}) && ($$case{stop} =~ /^yes$/)){ - $stop_to_keep_env=1; + if (defined($$case{stop}) && ($$case{stop} =~ /^yes$/)) { + $stop_to_keep_env = 1; last; } } @@ -877,6 +896,7 @@ sub runcase log_this("\n\n"); log_this("------Total: $total , Failed: $failnum------"); } + sub runcmd { my ($cmd) = @_; @@ -886,8 +906,8 @@ sub runcmd @$outref = `$cmd 2>&1`; if ($?) { - $rc = $? ; - $rc = $rc >> 8; + $rc = $?; + $rc = $rc >> 8; $::RUNCMD_RC = $rc; } chomp(@$outref); @@ -908,61 +928,61 @@ sub usage sub getreport { - open (INDOC, ">$_[1]") || die ("open STDOUT failed"); + open(INDOC, ">$_[1]") || die("open STDOUT failed"); print INDOC "Testcase Duration\n"; print INDOC "------------------------------------------------------------------------------\n"; close(INDOC); - open (STDOUT, ">>$_[1]") || die ("open STDOUT failed"); - open FD,"<$_[0]" or die "$?"; - while(){ - if(/Time/){ - s/------//g; - $_ .= "\n" if /END/; - print STDOUT $_; + open(STDOUT, ">>$_[1]") || die("open STDOUT failed"); + open FD, "<$_[0]" or die "$?"; + while () { + if (/Time/) { + s/------//g; + $_ .= "\n" if /END/; + print STDOUT $_; } - } + } -close(FD); -close(STDOUT); + close(FD); + close(STDOUT); } -sub reordercases{ +sub reordercases { my @caserange = (); my $line; - if($bundle_list){ + if ($bundle_list) { my @bundles = split /,/, $bundle_list; - foreach my $bundle (@bundles){ - if(!open(FILE, "<$rootdir/bundle/$bundle")){ + foreach my $bundle (@bundles) { + if (!open(FILE, "<$rootdir/bundle/$bundle")) { log_this("can't open $rootdir/bundle/$bundle"); return 1; } - while($line=){ + while ($line = ) { $line = trim($line); - next if(length($line) == 0); + next if (length($line) == 0); push(@caserange, $line); } close(FILE); } } - if($case_list){ - @caserange = split /,/, $case_list; + if ($case_list) { + @caserange = split /,/, $case_list; } - my @tmpcases=(); - foreach my $case (@caserange){ - my $i=0; - my $hit=0; - foreach my $runcase (@cases){ - if($runcase->{name} eq $case){ - $hit=1; + my @tmpcases = (); + foreach my $case (@caserange) { + my $i = 0; + my $hit = 0; + foreach my $runcase (@cases) { + if ($runcase->{name} eq $case) { + $hit = 1; last; - } - $i++; - next; - } - push(@tmpcases, $cases[$i]) if($hit); + } + $i++; + next; + } + push(@tmpcases, $cases[$i]) if ($hit); } - @cases=@tmpcases; + @cases = @tmpcases; } diff --git a/xCAT-test/xmlapi/xmldriver b/xCAT-test/xmlapi/xmldriver index c355b976c..977038365 100755 --- a/xCAT-test/xmlapi/xmldriver +++ b/xCAT-test/xmlapi/xmldriver @@ -3,9 +3,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -28,12 +28,12 @@ my $bname = basename($0); #----------------------------------------------------------------------------- # Main - $ENV{'XCATXMLTRACE'}=1; -my $XML=`cat /root/lissa/xmlapi/getTablesAllRowAttribsreq`; +$ENV{'XCATXMLTRACE'} = 1; +my $XML = `cat /root/lissa/xmlapi/getTablesAllRowAttribsreq`; -my $data=$XML; +my $data = $XML; -$ENV{'XCATSHOWXML'}=1; +$ENV{'XCATSHOWXML'} = 1; xCAT::Client::submit_request($data, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-test/xmlapi/xmldriver.old b/xCAT-test/xmlapi/xmldriver.old index 581d5f400..1f1afed27 100755 --- a/xCAT-test/xmlapi/xmldriver.old +++ b/xCAT-test/xmlapi/xmldriver.old @@ -3,9 +3,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -28,8 +28,9 @@ my $bname = basename($0); #----------------------------------------------------------------------------- # Main - $ENV{'XCATXMLTRACE'}=1; -my $XML=`cat /root/lissa/PCM/api/getTablesAllRowAttribsreq`; +$ENV{'XCATXMLTRACE'} = 1; +my $XML = `cat /root/lissa/PCM/api/getTablesAllRowAttribsreq`; + #my $XML=`cat /root/lissa/PCM/api/getAllEntriesreq `; #my $XML=`cat /root/lissa/PCM/api/setNodesAttribsreq `; #y $XML=`cat /root/lissa/PCM/api/getTablesAllNodeAttribsreq `; @@ -51,9 +52,9 @@ my $XML=`cat /root/lissa/PCM/api/getTablesAllRowAttribsreq`; #my $XML=`cat /root/lissa/PCM/api/setAttribsreq `; #my $XML=`cat /root/lissa/PCM/api/noderangereq `; -my $data=$XML; +my $data = $XML; -$ENV{'XCATSHOWXML'}=1; +$ENV{'XCATSHOWXML'} = 1; xCAT::Client::submit_request($data, \&xCAT::Client::handle_response); exit $xCAT::Client::EXITCODE; diff --git a/xCAT-test/xmlapi/xmldriver.org b/xCAT-test/xmlapi/xmldriver.org index dbc4bbc5e..3465b33ad 100644 --- a/xCAT-test/xmlapi/xmldriver.org +++ b/xCAT-test/xmlapi/xmldriver.org @@ -3,9 +3,9 @@ BEGIN { $::XCATROOT = - $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} - : -d '/opt/xcat' ? '/opt/xcat' - : '/usr'; + $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} + : -d '/opt/xcat' ? '/opt/xcat' + : '/usr'; } use lib "$::XCATROOT/lib/perl"; use strict; @@ -33,8 +33,8 @@ my $bname = basename($0); # Main -my $XML=`cat /root/lissa/PCM/api/getAllEntriesreq `; -my $data=$XML; +my $XML = `cat /root/lissa/PCM/api/getAllEntriesreq `; +my $data = $XML; diff --git a/xCAT-vlan/xpod2man b/xCAT-vlan/xpod2man index 19d43d399..36a5a78a2 100755 --- a/xCAT-vlan/xpod2man +++ b/xCAT-vlan/xpod2man @@ -8,17 +8,19 @@ # done relative to that. use strict; + #use lib '.'; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = "$ENV{'HOME'}/tmp"; if (system("mkdir -p $cachedir")) { die "Error: could not create $cachedir.\n"; } my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the cmd overview page. @@ -29,12 +31,12 @@ my @pods = getPodList($poddir); print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } @@ -43,15 +45,17 @@ my @dummyPods = createDummyPods($poddir, \@pods); # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + #print "$podfile, $htmlfile, $poddir, $htmldir\n"; convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -68,72 +72,77 @@ exit; # if that pod does not exist, create an empty one that will satisfy pod2html # keep track of all dummy pods created, so they can be removed later sub createDummyPods { - my ($poddir, $pods) = @_; - my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; - #print "Running cmd: ", $cmd, "\n"; - my @lines = `$cmd`; - if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } - #my @lines; - #system($cmd); - my @dummyPods; - foreach my $l (@lines) { - #print "$l\n"; - my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line - # The above line should create the array with every other entry being the man page name - # and every other entry is the section # (5 or 7) - my $cmd; - while ($cmd=shift @matches) { - #foreach my $m (@matches) { - my $section = shift @matches; - my $filename = "$poddir/man$section/$cmd.$section.pod"; - #print "$filename\n"; - if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } - } - } - - - # Create these empty files - print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; - mkdir "$poddir/man7"; - foreach my $d (@dummyPods) { - if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } - else { close TMP; } - } - - return @dummyPods; + my ($poddir, $pods) = @_; + my $cmd = "grep -r -E 'L<.+\\([57]\\)\\|.+\\.[57]>' " . $poddir; + + #print "Running cmd: ", $cmd, "\n"; + my @lines = `$cmd`; + if ($?) { print "Did not find any section 5 man page, creating dummy pods...\n"; print join('', @lines); } + + #my @lines; + #system($cmd); + my @dummyPods; + foreach my $l (@lines) { + + #print "$l\n"; + my @matches = $l =~ /L<([^\(]+)\(([57])\)\|\1\.[57]>/g; # get all the matches in the line + # The above line should create the array with every other entry being the man page name + # and every other entry is the section # (5 or 7) + my $cmd; + while ($cmd = shift @matches) { + + #foreach my $m (@matches) { + my $section = shift @matches; + my $filename = "$poddir/man$section/$cmd.$section.pod"; + + #print "$filename\n"; + if (!(grep /^$filename$/, @$pods) && !(grep /^$filename$/, @dummyPods)) { push @dummyPods, $filename; } + } + } + + + # Create these empty files + print "Creating empty linked-to files: ", join(', ', @dummyPods), "\n"; + mkdir "$poddir/man7"; + foreach my $d (@dummyPods) { + if (!open(TMP, ">>$d")) { warn "Could not create dummy pod file $d ($!)\n"; } + else { close TMP; } + } + + return @dummyPods; } # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the xcat man page that gives a summary description of each xcat cmd. sub writesummarypage { - my $file = shift; # relative path file name of the man page - # the rest of @_ contains the pod files that describe each cmd + my $file = shift; # relative path file name of the man page + # the rest of @_ contains the pod files that describe each cmd - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME B - extreme Cluster Administration Tool. @@ -159,56 +168,58 @@ i.e. all the commands in section 1, then the commands in section 3, etc. =over 12 EOS1 -# extract the summary for each cmd from its man page -foreach my $manpage (@_) { - my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; - # Suck in the whole file, then we will parse it. - open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; - my @contents = ; - my $wholemanpage = join('', @contents); - close(MANPAGE); - # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline - my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; - if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } - if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } - $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off - $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off - print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n".$description."\n"; -} + # extract the summary for each cmd from its man page + foreach my $manpage (@_) { + my ($sectionnum) = $manpage =~ /\.(\d+)\.pod$/; -# Artificially add the xcattest cmd, because the xCAT-test rpm will add this -print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + # Suck in the whole file, then we will parse it. + open(MANPAGE, "$manpage") or die "Error: could not open $manpage for reading.\n"; + my @contents = ; + my $wholemanpage = join('', @contents); + close(MANPAGE); - print FILE <<"EOS3"; + # This regex matches: optional space, =head1, space, title, space, cmd, space, description, newline + my ($cmd, $description) = $wholemanpage =~ /^\s*=head1\s+\S+\s+(\S+)\s+(.+?)\n/si; + if (!defined($cmd)) { print "Warning: $manpage is not in a recognized structure. It will be ignored.\n"; next; } + if (!defined($description)) { print "Warning: $manpage does not have a description for $cmd. It will be ignored.\n"; next; } + $cmd =~ s/^.<(.+)>$/$1/; # if the cmd name has pod formatting around it, strip it off + $description =~ s/^-\s*//; # if the description has a leading hypen, strip it off + print FILE "\n=item L<$cmd($sectionnum)|$cmd.$sectionnum>\n\n" . $description . "\n"; + } + + # Artificially add the xcattest cmd, because the xCAT-test rpm will add this + print FILE "\n=item L\n\nRun automated xCAT test cases.\n"; + + print FILE <<"EOS3"; =back EOS3 - close FILE; + close FILE; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man1", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man1", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } diff --git a/xCAT/postscripts/HPCbootstatus.aix b/xCAT/postscripts/HPCbootstatus.aix index 6b4ddc3d5..6833aff0c 100644 --- a/xCAT/postscripts/HPCbootstatus.aix +++ b/xCAT/postscripts/HPCbootstatus.aix @@ -6,10 +6,12 @@ use IO::Socket; # Report the appstatus to xcatd on MN. my $timeout = 300; + # The number of items to check, currently including: # gpfs-daemon, gpfs-quorum, gpfs-filesystem, lapi-pnsd, loadl-schedd, loadl-startd my $itemnum = 6; -my $passed = 0; +my $passed = 0; + # Set sleep time my $interval = 15; @@ -17,15 +19,16 @@ my $master; # Get server IP from xcatinfo file if (-f "/etc/xcatinfo") { - # if this file exists assume it has the correct server name - my $cmd = "cat /etc/xcatinfo | grep 'XCATSERVER'"; - my $SNline = `$cmd`; - my ($junk, $servnode) = split(/=/, $SNline); - chomp $servnode; - $servnode =~ s/^\s*//; - if ($servnode) { - $master = $servnode; - } + + # if this file exists assume it has the correct server name + my $cmd = "cat /etc/xcatinfo | grep 'XCATSERVER'"; + my $SNline = `$cmd`; + my ($junk, $servnode) = split(/=/, $SNline); + chomp $servnode; + $servnode =~ s/^\s*//; + if ($servnode) { + $master = $servnode; + } } my $gpfsd = "hpcbootstatus gpfs-daemon=up"; @@ -34,7 +37,7 @@ my $gpfsq = "hpcbootstatus gpfs-quorum=achieved"; # add HPCbootstatus.aix to /etc/inittab for diskful node reboot # see if it is already there my $cmd = "/usr/sbin/lsitab hpcbootstatus > /dev/null 2>&1"; -my $rc = system("$cmd") >>8; +my $rc = system("$cmd") >> 8; if ($rc != 0) { # add new entry @@ -44,16 +47,16 @@ if ($rc != 0) while (1) { - my $count= 0; - + my $count = 0; + # Check gpfs-daemon via port 1191. my $cmd = "netstat -nA|grep 1191"; - my $rc = `$cmd`; + my $rc = `$cmd`; - if($rc) + if ($rc) { # send message to xcatd - if (&updateflag($master,$gpfsd) != 0) + if (&updateflag($master, $gpfsd) != 0) { print "HPCbootstatus.aix: Failed to report $gpfsd to xcatd on $master!\n"; } @@ -62,12 +65,12 @@ while (1) # Check gpfs-quorum via /usr/lpp/mmfs/bin/mmgetstate $cmd = "/usr/lpp/mmfs/bin/mmgetstate -s|grep achieved"; - $rc = `$cmd`; - - if($rc) + $rc = `$cmd`; + + if ($rc) { # send message to xcatd - if (&updateflag($master,$gpfsq) != 0) + if (&updateflag($master, $gpfsq) != 0) { print "HPCbootstatus.aix: Failed to report $gpfsq to xcatd on $master!\n"; } @@ -76,10 +79,10 @@ while (1) # Check gpfs-filesystem via /usr/sbin/mount $cmd = "cat /tmp/mount |grep mmfs |awk '{print \$2}'"; - my @fs = `$cmd`; + my @fs = `$cmd`; my $new = ""; - if(scalar @fs) + if (scalar @fs) { foreach my $line (@fs) { @@ -90,23 +93,23 @@ while (1) # send message to xcatd my $gpfsf = "hpcbootstatus gpfs-filesystem=$new"; - if (&updateflag($master,$gpfsf) != 0) + if (&updateflag($master, $gpfsf) != 0) { print "HPCbootstatus.aix: Failed to report $gpfsf to xcatd on $master!\n"; } $count++; } - + # Check LAPI via lssrc $cmd = "/usr/bin/lssrc -s pnsd |/usr/bin/awk '(NR==2){print \$3}'"; - $rc = `$cmd`; + $rc = `$cmd`; - if($rc) + if ($rc) { # send message to xcatd chomp $rc; my $lapi = "hpcbootstatus lapi-pnsd=$rc"; - if (&updateflag($master,$lapi) != 0) + if (&updateflag($master, $lapi) != 0) { print "HPCbootstatus.aix: Failed to report $lapi to xcatd on $master!\n"; } @@ -115,14 +118,14 @@ while (1) # Check loadl-schedd via llrstatus $cmd = "/usr/bin/llrstatus -h `hostname` -r %sca %scs"; - $rc = `$cmd`; + $rc = `$cmd`; - if($rc) + if ($rc) { # send message to xcatd chomp $rc; my $llsc = "hpcbootstatus loadl-schedd=$rc"; - if (&updateflag($master,$llsc) != 0) + if (&updateflag($master, $llsc) != 0) { print "HPCbootstatus.aix: Failed to report $llsc to xcatd on $master!\n"; } @@ -131,14 +134,14 @@ while (1) # Check loadl-startd via llrstatus $cmd = "/usr/bin/llrstatus -h `hostname` -r %sta %sts"; - $rc = `$cmd`; + $rc = `$cmd`; - if($rc) + if ($rc) { # send message to xcatd chomp $rc; my $llst = "hpcbootstatus loadl-startd=$rc"; - if (&updateflag($master,$llst) != 0) + if (&updateflag($master, $llst) != 0) { print "HPCbootstatus.aix: Failed to report $llst to xcatd on $master!\n"; } @@ -146,7 +149,7 @@ while (1) } # All is done or timeout? - if (($count == $itemnum ) || ($passed >= $timeout)) + if (($count == $itemnum) || ($passed >= $timeout)) { last; } @@ -158,40 +161,40 @@ while (1) ############################################################ # # updateflag -# Tells xCAT on the server about the appstatus. +# Tells xCAT on the server about the appstatus. # e.g. $status = "hpcbootstatus loadl-schedd=1!Avail"; # ############################################################ -sub updateflag { +sub updateflag { my $server = shift; my $status = shift; - my $port = "3002"; #by default - + my $port = "3002"; #by default + my $servip = `host $server | awk '{print \$3}'`; chomp($servip); - $servip =~ s/,$//; # remove trailing comma - my $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); + $servip =~ s/,$//; # remove trailing comma + my $remote = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); my $try = 10; while (!$remote && $try-- > 0) { sleep 1; - $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); + $remote = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); print "HPCbootstatus.aix: Cannot connect to host \'$servip\'\n"; } - unless ($remote) { + unless ($remote) { print "HPCbootstatus.aix: Cannot connect to host \'$servip\'\n"; - return 1; + return 1; } $remote->autoflush(1); my $line; - while (defined ($line = <$remote>)) { + while (defined($line = <$remote>)) { chomp $line; if ($line eq "ready") { - print $remote "$status\n"; + print $remote "$status\n"; } elsif ($line eq "done") { - last; + last; } } close $remote; diff --git a/xCAT/postscripts/aixremoteshell b/xCAT/postscripts/aixremoteshell index 7db4cb038..c0a6baffe 100755 --- a/xCAT/postscripts/aixremoteshell +++ b/xCAT/postscripts/aixremoteshell @@ -32,19 +32,19 @@ # MAIN use strict; use IO::Socket; -my $useSocketSSL=eval { require IO::Socket::SSL; }; +my $useSocketSSL = eval { require IO::Socket::SSL; }; if ($useSocketSSL) { - require IO::Socket::SSL; + require IO::Socket::SSL; } use Getopt::Long; my $rc = 0; # Override from site table -my $usesshonaix = $ENV{'USESSHONAIX'}; -my $master = $ENV{'MASTER'}; -my $node = $ENV{'NODE'}; -my $nodetype = $ENV{'NTYPE'}; -my $enablesshbetweennodes = $ENV{'ENABLESSHBETWEENNODES'}; +my $usesshonaix = $ENV{'USESSHONAIX'}; +my $master = $ENV{'MASTER'}; +my $node = $ENV{'NODE'}; +my $nodetype = $ENV{'NTYPE'}; +my $enablesshbetweennodes = $ENV{'ENABLESSHBETWEENNODES'}; my $msg; my $home; my $cmd; @@ -53,56 +53,59 @@ my $username = "root"; Getopt::Long::Configure("bundling"); Getopt::Long::Configure("pass_through"); GetOptions( - 'd|do' => \$runscript + 'd|do' => \$runscript ); + # the postscript only runs if called with -d flag from remoteshell unless ($runscript) { - my $msg = "aixremoteshell called without -d flag, do nothing."; - `logger -t xcat -p local4.err $msg`; - exit 0; + my $msg = "aixremoteshell called without -d flag, do nothing."; + `logger -t xcat -p local4.err $msg`; + exit 0; } my @root = split ':', (`/bin/grep ^$username /etc/passwd 2>&1`); $home = $root[5]; -# root home directory must be root system + +# root home directory must be root system $rc = &runcmd("chown root $home"); if ($rc != 0) { - my $msg = "It fails to chown root $home"; - `logger -t xcat -p local4.err $msg`; - exit 1; + my $msg = "It fails to chown root $home"; + `logger -t xcat -p local4.err $msg`; + exit 1; } $rc = &runcmd("chgrp system $home"); if ($rc != 0) { - my $msg = "It fails to chgrp system $home"; - `logger -t xcat -p local4.err $msg`; - exit 1; + my $msg = "It fails to chgrp system $home"; + `logger -t xcat -p local4.err $msg`; + exit 1; } $usesshonaix =~ tr/a-z/A-Z/; # convert to upper if ((!defined($usesshonaix)) || ($usesshonaix eq "0") || ($usesshonaix eq "NO")) -{ # setting up rsh - # setup .rhosts if not already setup +{ # setting up rsh + # setup .rhosts if not already setup $cmd = "/bin/grep \"^$master root\" /.rhosts"; `$cmd 2>&1`; my $rc = $? >> 8; if ($rc) - { # if not found, then add entry in .rhosts + { # if not found, then add entry in .rhosts &runcmd("/bin/echo $master root >> /.rhosts"); chmod 0600, "/.rhosts"; } } else -{ - # setting up ssh - if (&setupSSH != 0) { - my $msg = "Failed to setup ssh on $node.\n"; - `logger -t xcat -p local4.err $msg`; -# print $msg; - exit 0; - } +{ + # setting up ssh + if (&setupSSH != 0) { + my $msg = "Failed to setup ssh on $node.\n"; + `logger -t xcat -p local4.err $msg`; + + # print $msg; + exit 0; + } } exit 0; @@ -117,8 +120,8 @@ sub setupSSH my $sshconfig = "/etc/ssh/ssh_config"; if (-e $sshdconfig) - { # ssh installed - my $tmp="$sshdconfig.ORIG"; + { # ssh installed + my $tmp = "$sshdconfig.ORIG"; if (!(-e "$sshdconfig.ORIG")) { &runcmd("cp $sshdconfig $sshdconfig.ORIG"); @@ -128,6 +131,7 @@ sub setupSSH &runcmd("echo \"MaxStartups 1024\" >>$sshdconfig"); &runcmd("echo \"ListenAddress ::\" >>$sshdconfig"); &runcmd("echo \"ListenAddress 0.0.0.0\" >>$sshdconfig"); + #&runcmd("echo \"PasswordAuthentication no\" >>$sshdconfig"); if (!(-e "$sshconfig.ORIG")) { @@ -162,94 +166,96 @@ sub setupSSH exit 0; } - # get the name of my service node/NIM master from /etc/xcatinfo - # ! use value of MASTER env variable instead - $::servnode = $master; + # get the name of my service node/NIM master from /etc/xcatinfo + # ! use value of MASTER env variable instead + $::servnode = $master; - my $response=&getresponse("ssh_dsa_hostkey"); - if (defined ($response) ) { - my $fd; - my $filename = "/etc/ssh/ssh_host_dsa_key"; - &runcmd("mkdir -p /etc/ssh"); - open($fd, '>',$filename); - print $fd $response; - close($fd); - - # set the permissions - my $cmd = "chmod 600 $filename > /dev/null 2>&1"; - &runcmd($cmd); - } - else { + my $response = &getresponse("ssh_dsa_hostkey"); + if (defined($response)) { + my $fd; + my $filename = "/etc/ssh/ssh_host_dsa_key"; + &runcmd("mkdir -p /etc/ssh"); + open($fd, '>', $filename); + print $fd $response; + close($fd); + + # set the permissions + my $cmd = "chmod 600 $filename > /dev/null 2>&1"; + &runcmd($cmd); + } + else { $msg = "aixremoteshell: Could not get ssh_host_dsa_key file.\n"; `logger -t xcat -p local4.err $msg`; } - my $response=&getresponse("ssh_rsa_hostkey"); - if (defined ($response) ) { - my $fd; - my $filename = "/etc/ssh/ssh_host_rsa_key"; - &runcmd("mkdir -p /etc/ssh"); - open($fd, '>',$filename); - print $fd $response; - close($fd); + my $response = &getresponse("ssh_rsa_hostkey"); + if (defined($response)) { + my $fd; + my $filename = "/etc/ssh/ssh_host_rsa_key"; + &runcmd("mkdir -p /etc/ssh"); + open($fd, '>', $filename); + print $fd $response; + close($fd); - # set the permissions - my $cmd = "chmod 600 $filename > /dev/null 2>&1"; - &runcmd($cmd); - } - else { + # set the permissions + my $cmd = "chmod 600 $filename > /dev/null 2>&1"; + &runcmd($cmd); + } + else { $msg = "aixremoteshell: Could not get ssh_host_rsa_key file.\n"; `logger -t xcat -p local4.err $msg`; } - # is there is a ecdsa host key on the node, then get the one from the MN/SN - my $filename = "/etc/ssh/ssh_host_ecdsa_key"; - if (-e $filename) { - my $response=&getresponse("ssh_ecdsa_hostkey"); - if (defined ($response) ) { - my $fd; - &runcmd("mkdir -p /etc/ssh"); - open($fd, '>',$filename); - print $fd $response; - close($fd); - # set the permissions - my $cmd = "chmod 600 $filename > /dev/null 2>&1"; - &runcmd($cmd); - } - else { - $msg = "aixremoteshell: Could not get ssh_host_ecdsa_key file.\n"; - `logger -t xcat -p local4.err $msg`; - } + # is there is a ecdsa host key on the node, then get the one from the MN/SN + my $filename = "/etc/ssh/ssh_host_ecdsa_key"; + if (-e $filename) { + my $response = &getresponse("ssh_ecdsa_hostkey"); + if (defined($response)) { + my $fd; + &runcmd("mkdir -p /etc/ssh"); + open($fd, '>', $filename); + print $fd $response; + close($fd); + + # set the permissions + my $cmd = "chmod 600 $filename > /dev/null 2>&1"; + &runcmd($cmd); + } + else { + $msg = "aixremoteshell: Could not get ssh_host_ecdsa_key file.\n"; + `logger -t xcat -p local4.err $msg`; + } } - if ( $nodetype eq "service") { - &runcmd("mkdir -p /etc/xcat/hostkeys; cp /etc/ssh/ssh* /etc/xcat/hostkeys/. > /dev/null 2>&1"); - } + if ($nodetype eq "service") { + &runcmd("mkdir -p /etc/xcat/hostkeys; cp /etc/ssh/ssh* /etc/xcat/hostkeys/. > /dev/null 2>&1"); + } + # Decide whether to enable passwordless ssh between the nodes if ($enablesshbetweennodes eq "YES") { - my $response=&getresponse("ssh_root_key"); - if (defined ($response) ) { - my $fd; - my $filename = "/.ssh/id_rsa"; - &runcmd("mkdir -p /.ssh"); - open($fd, '>',$filename); - print $fd $response; - close($fd); + my $response = &getresponse("ssh_root_key"); + if (defined($response)) { + my $fd; + my $filename = "/.ssh/id_rsa"; + &runcmd("mkdir -p /.ssh"); + open($fd, '>', $filename); + print $fd $response; + close($fd); - # set the permissions - my $cmd = "chmod 600 $filename > /dev/null 2>&1"; - &runcmd($cmd); + # set the permissions + my $cmd = "chmod 600 $filename > /dev/null 2>&1"; + &runcmd($cmd); - if ( -f "/.ssh/id_rsa" ) { - &runcmd("ssh-keygen -y -f /.ssh/id_rsa > /.ssh/id_rsa.pub"); - } - } - else { + if (-f "/.ssh/id_rsa") { + &runcmd("ssh-keygen -y -f /.ssh/id_rsa > /.ssh/id_rsa.pub"); + } + } + else { $msg = "aixremoteshell: Could not get id_rsa file.\n"; `logger -t xcat -p local4.err $msg`; - } + } } - return 0; + return 0; } ##################################################### @@ -263,56 +269,58 @@ sub setupSSH ##################################################### sub getresponse { - my ($req) = @_; + my ($req) = @_; - my $port = "3001"; + my $port = "3001"; - # open listener connection to wait for check from management node - my $lpid = &openlistener(); + # open listener connection to wait for check from management node + my $lpid = &openlistener(); - # open a socket to request credentials - my $sock = IO::Socket::SSL->new( - PeerAddr => $::servnode, - PeerPort => $port, - Proto => 'tcp', - ); + # open a socket to request credentials + my $sock = IO::Socket::SSL->new( + PeerAddr => $::servnode, + PeerPort => $port, + Proto => 'tcp', + ); - unless ($sock) { - my $msg = "aixremoteshell: Cannot connect to host \'$::servnode\'\n"; - `logger -t xcat -p local4.err $msg`; - #print $msg; - kill 2, $lpid; - return undef; - } + unless ($sock) { + my $msg = "aixremoteshell: Cannot connect to host \'$::servnode\'\n"; + `logger -t xcat -p local4.err $msg`; - # request must be in XML format - print $sock "\n"; - print $sock " getcredentials\n"; - print $sock " $req\n"; - print $sock " 300\n"; - print $sock "\n"; + #print $msg; + kill 2, $lpid; + return undef; + } -#TODO - do we have to try again after waiting for a bit???? - my $response=''; - my $line; - while (defined ($line = <$sock>)) { - # skip xml tags - next if ($line =~ /^\s*\n"; + print $sock " getcredentials\n"; + print $sock " $req\n"; + print $sock " 300\n"; + print $sock "\n"; - # once we get to serverdone we have the whole response - if ($line =~ m/<\/serverdone>/) { - last: - } - $response .= $line; - } + #TODO - do we have to try again after waiting for a bit???? + my $response = ''; + my $line; + while (defined($line = <$sock>)) { - close ($sock); + # skip xml tags + next if ($line =~ /^\s*/) { + last: + } + $response .= $line; + } + + close($sock); + + kill 2, $lpid; + if ($response) { + return $response; + } + return undef; } ##################################################### @@ -323,57 +331,60 @@ sub getresponse ##################################################### sub openlistener { - my $node = $ENV{'NODE'}; + my $node = $ENV{'NODE'}; - # fork a child process to open a socket to listen for communication - # from the server - my $pid = fork; - unless (defined $pid) { - # fork failed - $msg = "aixremoteshell: Could not fork process.\n"; - `logger -t xcat -p local4.err $msg`; - print $msg; - return undef; - } + # fork a child process to open a socket to listen for communication + # from the server + my $pid = fork; + unless (defined $pid) { - if ($pid != 0) { - # This is the parent process, just return + # fork failed + $msg = "aixremoteshell: Could not fork process.\n"; + `logger -t xcat -p local4.err $msg`; + print $msg; + return undef; + } + + if ($pid != 0) { + + # This is the parent process, just return return $pid; } - my $listener = IO::Socket::INET->new( - LocalPort => '300', - Proto => 'tcp', - Listen => '64', - Reuse => 1 - ); + my $listener = IO::Socket::INET->new( + LocalPort => '300', + Proto => 'tcp', + Listen => '64', + Reuse => 1 + ); - unless ($listener) { - my $msg = "aixremoteshell: Cannot open socket on \'$node\'\n"; - `logger -t xcat -p local4.err $msg`; - print $msg; - exit 1; - } + unless ($listener) { + my $msg = "aixremoteshell: Cannot open socket on \'$node\'\n"; + `logger -t xcat -p local4.err $msg`; + print $msg; + exit 1; + } - # xcatd sends a quick req to see if we are really asking - # for info - this listener checks for the req and says ok - my $client; - while ($client = $listener->accept()) { - # $client is the new connection - my $text=<$client>; + # xcatd sends a quick req to see if we are really asking + # for info - this listener checks for the req and says ok + my $client; + while ($client = $listener->accept()) { - # see if we got "CREDOKBYYOU?" - if ($text =~ /CREDOKBYYOU?/) { - print $client "CREDOKBYME"; - close($client); - close($listener); - exit 0; - } - close($client); - } - close($client); - close($listener); - exit 0; + # $client is the new connection + my $text = <$client>; + + # see if we got "CREDOKBYYOU?" + if ($text =~ /CREDOKBYYOU?/) { + print $client "CREDOKBYME"; + close($client); + close($listener); + exit 0; + } + close($client); + } + close($client); + close($listener); + exit 0; } # @@ -384,7 +395,7 @@ sub runcmd my ($cmd) = @_; my $rc = 0; $cmd .= ' 2>&1'; - $::outref = `$cmd`; + $::outref = `$cmd`; if ($?) { $rc = $? >> 8; @@ -392,7 +403,8 @@ sub runcmd { my $msg = "$cmd returned rc=$rc @$::outref\n"; `logger -t xcat -p local4.info $msg`; -# print $msg; + + # print $msg; } } return 0; diff --git a/xCAT/postscripts/aixswupdate b/xCAT/postscripts/aixswupdate index 3db8dd2de..2dec2c4b4 100755 --- a/xCAT/postscripts/aixswupdate +++ b/xCAT/postscripts/aixswupdate @@ -22,14 +22,14 @@ Getopt::Long::Configure("bundling"); $Getopt::Long::ignorecase = 0; if ( !GetOptions( - 'f=s' => \$::FILENAME, # software list file name (full) - 's=s' => \$::SERVER, - 'i=s' => \$::INSTP_FLAGS, # installp flags - 'r=s' => \$::RPM_FLAGS, # RPM flags - 'e=s' => \$::EMGR_FLAGS, # emgr flags - 'n|nfsv4' => \$::NFSV4, - 'd|altsrc' => \$::ALTSRC, - 'a|all' => \$::ALLSW + 'f=s' => \$::FILENAME, # software list file name (full) + 's=s' => \$::SERVER, + 'i=s' => \$::INSTP_FLAGS, # installp flags + 'r=s' => \$::RPM_FLAGS, # RPM flags + 'e=s' => \$::EMGR_FLAGS, # emgr flags + 'n|nfsv4' => \$::NFSV4, + 'd|altsrc' => \$::ALTSRC, + 'a|all' => \$::ALLSW ) ) { # Gather options @@ -82,12 +82,12 @@ my $mtcmd; if ($::NFSV4) { $mtcmd = - qq~/bin/mkdir -m 644 -p $localsrc; /usr/sbin/mount -o vers=4 $servnode:$mntdir $localsrc~; +qq~/bin/mkdir -m 644 -p $localsrc; /usr/sbin/mount -o vers=4 $servnode:$mntdir $localsrc~; } else { $mtcmd = - qq~/bin/mkdir -m 644 -p $localsrc; /usr/sbin/mount $servnode:$mntdir $localsrc~; +qq~/bin/mkdir -m 644 -p $localsrc; /usr/sbin/mount $servnode:$mntdir $localsrc~; } $rc = &runcmd($mtcmd); @@ -157,16 +157,16 @@ if (-f $listfile) # clean up tmp files my $rmcmd = qq~/bin/rm -R $emgrfile $instpfile~; - print "Running: \'$rmcmd\'\n"; - $rc = &runcmd($rmcmd); + print "Running: \'$rmcmd\'\n"; + $rc = &runcmd($rmcmd); if ($rc != 0) { - # "Could not remove $emgrfile and $instpfile.\n"; - } + # "Could not remove $emgrfile and $instpfile.\n"; + } # unmount source dir my $umtcmd = qq~/usr/sbin/umount /xcatswmnt~; - print "Running: \'$umtcmd\'\n"; + print "Running: \'$umtcmd\'\n"; $rc = &runcmd($umtcmd); if ($rc != 0) { @@ -243,10 +243,10 @@ sub do_rpms # - need to test rpms to make sure all will install # - add test to rpm cmd if not included in rpm_flags # - my @doinstall = split /\s+/, $pkg_string; + my @doinstall = split /\s+/, $pkg_string; my @dontinstall = (); - if ( ($rflags =~ /\-i/) + if (($rflags =~ /\-i/) || ($rflags =~ /install /) || ($rflags =~ /U/) || ($rflags =~ /update /)) @@ -327,7 +327,7 @@ sub do_rpms $rpmcmd = qq~/usr/bin/rpm $rflags ~; } - print "Running: \'$rpmcmd\'\n"; + print "Running: \'$rpmcmd\'\n"; my $rc = &runcmd($rpmcmd); print "$::outref\n"; @@ -342,7 +342,7 @@ sub do_rpms if (scalar(@dontinstall)) { print - "The following RPM packages were already installed and were not reinstalled:\n"; +"The following RPM packages were already installed and were not reinstalled:\n"; my @rpms; foreach my $rpm (@dontinstall) { @@ -406,7 +406,7 @@ sub do_emgr $emgrcmd .= qq~ -f $emgrfile ~; } - print "Running: \'$emgrcmd\'\n"; + print "Running: \'$emgrcmd\'\n"; my $rc = &runcmd($emgrcmd); print "$::outref\n"; @@ -492,7 +492,7 @@ sub do_installp } } - print "Running: \'$inpcmd\'\n"; + print "Running: \'$inpcmd\'\n"; my $rc = &runcmd($inpcmd); print "$::outref\n"; diff --git a/xCAT/postscripts/config_bootnicsea b/xCAT/postscripts/config_bootnicsea index 45ae983b2..0e3ad7cca 100644 --- a/xCAT/postscripts/config_bootnicsea +++ b/xCAT/postscripts/config_bootnicsea @@ -2,12 +2,13 @@ if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use strict; use File::Path; use Getopt::Long; + # script file name $::script = $0; $::script =~ s/.*\///; @@ -20,8 +21,8 @@ $::script =~ s/.*\///; sub runcmd { my ($cmd) = @_; - my $rc=0; - $cmd .= ' 2>&1' ; + my $rc = 0; + $cmd .= ' 2>&1'; msg("Running command $cmd"); $::outref = `$cmd`; if ($?) @@ -41,6 +42,7 @@ sub msg my $str = shift; $::sdate = `/bin/date`; chomp $::sdate; + #print "$::sdate $::script $str\n"; print $::LOG_FILE "$::sdate $::script $str\n"; } @@ -54,19 +56,20 @@ if (!-d $logdir) { } my $logfile = $logdir . "/xcat.log"; + # this log should not contain much so it might be ok to let it grow? # at least we'll have the errors preserved -open(LOGFILE,">>",$logfile); +open(LOGFILE, ">>", $logfile); $::LOG_FILE = \*LOGFILE; my $xcatinfo; -open($xcatinfo,"<","/etc/xcatinfo"); +open($xcatinfo, "<", "/etc/xcatinfo"); my @sea_info = <$xcatinfo>; close($xcatinfo); -my ($phy,$vir,$vlan,$ip,$mask,$host); +my ($phy, $vir, $vlan, $ip, $mask, $host); foreach my $sea_line (@sea_info) { if ($sea_line =~ /SEA_ADAPTERS=(.*)$/) { - ($phy,$vir,$vlan,$ip,$mask,$host) = split (/:/,$1); + ($phy, $vir, $vlan, $ip, $mask, $host) = split(/:/, $1); last; } } @@ -78,7 +81,7 @@ if (!$phy || !$vir || !$vlan) { msg("Info: phy:$phy,vir:$vir,vlan:$vlan,ip:$ip-$mask, hostname:$host"); } -unless($mask) { +unless ($mask) { $mask = "255.255.255.0"; } @@ -88,12 +91,12 @@ unless($mask) { $cmd = "/usr/ios/cli/ioscli license -accept"; &runcmd($cmd); } -{ # detach bootnic +{ # detach bootnic if ($phy =~ /^ent(\d+)/) { my $phynic_id = $1; - my $en_nic = "en".$phynic_id; - my $ent_nic = "ent".$phynic_id; - my $et_nic = "et".$phynic_id; + my $en_nic = "en" . $phynic_id; + my $ent_nic = "ent" . $phynic_id; + my $et_nic = "et" . $phynic_id; $cmd = "ifconfig $en_nic down; ifconfig $en_nic detach; rmdev -dl $en_nic; rmdev -dl $ent_nic; rmdev -dl $et_nic; cfgmgr;"; if (&runcmd($cmd) != 0) { msg("Error: could not detach nic:$phy"); @@ -101,17 +104,17 @@ unless($mask) { } } } -{ # create sea adapter and config it - #$cmd = qq~su - padmin "-c ioscli license -accept; ioscli mkvdev -sea $phy -vadapter $virt -default $virt -defaultid $vlan"~; +{ # create sea adapter and config it + #$cmd = qq~su - padmin "-c ioscli license -accept; ioscli mkvdev -sea $phy -vadapter $virt -default $virt -defaultid $vlan"~; $cmd = "/usr/ios/cli/ioscli mkvdev -sea $phy -vadapter $vir -default $vir -defaultid $vlan"; if (&runcmd($cmd) != 0) { msg("Error: could not create SEA with physical adapter $phy, virtual adapter $vir and vlan id $vlan"); exit 1; } - my $sea_out = $::outref; - my $sea = undef; - my @out_array = split (/\n/, $sea_out); - foreach (@out_array) { + my $sea_out = $::outref; + my $sea = undef; + my @out_array = split(/\n/, $sea_out); + foreach (@out_array) { if (/(ent\d+)\s*Available/) { $sea = $1; $sea =~ s/t//; @@ -122,6 +125,7 @@ unless($mask) { exit 1; } msg("Info: The interface created with mkvdev is: $sea"); + #$cmd = qq~su - padmin "-c ioscli license -accept; ioscli mktcpip -host $host -inetaddr $ip -interface $sea -netmask $mask"~; $cmd = "/usr/ios/cli/ioscli mktcpip -hostname $host -inetaddr $ip -interface $sea -netmask $mask"; if (&runcmd($cmd) != 0) { @@ -130,9 +134,9 @@ unless($mask) { } { - my $lsicmd = "/usr/sbin/lsitab bootnicsea > /dev/null 2>&1"; + my $lsicmd = "/usr/sbin/lsitab bootnicsea > /dev/null 2>&1"; if (&runcmd($lsicmd) == 0) { - my $rmicmd = 'rmitab "bootnicsea" > /dev/null 2>&1'; + my $rmicmd = 'rmitab "bootnicsea" > /dev/null 2>&1'; if (&runcmd($rmicmd) != 0) { msg("Warning: config_bootnicsea: Could not remove config_bootnicsea from /etc/inittab.\n") } diff --git a/xCAT/postscripts/configeth_aix b/xCAT/postscripts/configeth_aix index 673df3301..3021208f1 100755 --- a/xCAT/postscripts/configeth_aix +++ b/xCAT/postscripts/configeth_aix @@ -24,6 +24,7 @@ if ($^O =~ /^aix/i) { # Usually do not have to set this... my $gateway; + #$gateway = '1.2.3.254'; # Take primary node name, add "-eth1" for linux and "-en1" for AIX and @@ -42,45 +43,78 @@ sub getipaddr() if ($socket6support) # the getaddrinfo and getnameinfo supports both IPv4 and IPv6 { - my ($family, $socket, $protocol, $ip, $name) = Socket6::getaddrinfo($iporhost,0); + my ($family, $socket, $protocol, $ip, $name) = Socket6::getaddrinfo($iporhost, 0); if ($ip) { return (Socket6::getnameinfo($ip, Socket6::NI_NUMERICHOST()))[0]; } - return undef; + return undef; } else { - return inet_ntoa(inet_aton($iporhost)) + return inet_ntoa(inet_aton($iporhost)) } } my $host = `echo $ENV{NODE} |sed "s/-hf[0-9]//g"`; chomp($host); my $hostname = "$host-$nic"; -my $ip = &getipaddr($hostname); +my $ip = &getipaddr($hostname); if (!$ip) { system("logger -t xcat 'configeth: cannot resolve $hostname.'"); exit 1; } if ($^O =~ /^aix/i) { - if ($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) { - runcmd("chdev -l 'en$nic_num' -a netaddr=$ip -a netmask=$netmask -a state='up'"); - } else { #ipv6 - runcmd("autoconf6 -6i en$nic_num"); - } + if ($ip =~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) { + runcmd("chdev -l 'en$nic_num' -a netaddr=$ip -a netmask=$netmask -a state='up'"); + } else { #ipv6 + runcmd("autoconf6 -6i en$nic_num"); + } } elsif (($ENV{OSVER} && ($ENV{OSVER} =~ /sles|suse/i)) || (-f "/etc/SuSE-release")) { + + # Write the info to the ifcfg file + my $dir = "/etc/sysconfig/network"; + if (!open(FILE, ">$dir/ifcfg-$nic")) { system("logger -t xcat 'configeth: cannot open $dir/ifcfg-$nic.'"); exit 1; } + + # Not sure what is really REQUIRED from below -- copied the eth file from + # the system + print FILE "BOOTPROTO=\'static\'\n"; + print FILE "BROADCAST=\'\'\n"; + print FILE "ETHTOOL_OPTIONS=\'\'\n"; + print FILE "IPADDR=\'" . $ip . "\'\n"; + print FILE "MTU=\'\'\n"; + print FILE "NAME=\'\'\n"; + print FILE "NETMASK=\'" . $netmask . "\'\n"; + print FILE "NETWORK=\'\'\n"; + print FILE "REMOTE_IPADDR=\'\'\n"; + print FILE "STARTMODE=\'onboot\'\n"; + print FILE "UNIQUE=\'\'\n"; + print FILE "USERCONTROL=\'no\'\n"; + print FILE "_nm_name=\'static-0\'\n"; + + close FILE; + runcmd("ifup $nic"); + + my $nic = 'eth0'; + + # make file for eth0, too + if (!-f "$dir/ifcfg-$nic") { + my $hostname = "$ENV{NODE}"; + my $ip = &getipaddr($hostname); + if (!$ip) { system("logger -t xcat 'configeth: cannot resolve $hostname.'"); exit 1; } + # Write the info to the ifcfg file my $dir = "/etc/sysconfig/network"; if (!open(FILE, ">$dir/ifcfg-$nic")) { system("logger -t xcat 'configeth: cannot open $dir/ifcfg-$nic.'"); exit 1; } + # Not sure what is really REQUIRED from below -- copied the eth file from # the system print FILE "BOOTPROTO=\'static\'\n"; print FILE "BROADCAST=\'\'\n"; print FILE "ETHTOOL_OPTIONS=\'\'\n"; - print FILE "IPADDR=\'".$ip."\'\n"; + print FILE "IPADDR=\'" . $ip . "\'\n"; print FILE "MTU=\'\'\n"; print FILE "NAME=\'\'\n"; - print FILE "NETMASK=\'".$netmask."\'\n"; + print FILE "NETMASK=\'" . $netmask . "\'\n"; print FILE "NETWORK=\'\'\n"; print FILE "REMOTE_IPADDR=\'\'\n"; print FILE "STARTMODE=\'onboot\'\n"; @@ -90,66 +124,37 @@ elsif (($ENV{OSVER} && ($ENV{OSVER} =~ /sles|suse/i)) || (-f "/etc/SuSE-release" close FILE; runcmd("ifup $nic"); - - my $nic = 'eth0'; - # make file for eth0, too - if (! -f "$dir/ifcfg-$nic") { - my $hostname = "$ENV{NODE}"; - my $ip = &getipaddr($hostname); - if (!$ip) { system("logger -t xcat 'configeth: cannot resolve $hostname.'"); exit 1; } - - # Write the info to the ifcfg file - my $dir = "/etc/sysconfig/network"; - if (!open(FILE, ">$dir/ifcfg-$nic")) { system("logger -t xcat 'configeth: cannot open $dir/ifcfg-$nic.'"); exit 1; } - # Not sure what is really REQUIRED from below -- copied the eth file from - # the system - print FILE "BOOTPROTO=\'static\'\n"; - print FILE "BROADCAST=\'\'\n"; - print FILE "ETHTOOL_OPTIONS=\'\'\n"; - print FILE "IPADDR=\'".$ip."\'\n"; - print FILE "MTU=\'\'\n"; - print FILE "NAME=\'\'\n"; - print FILE "NETMASK=\'".$netmask."\'\n"; - print FILE "NETWORK=\'\'\n"; - print FILE "REMOTE_IPADDR=\'\'\n"; - print FILE "STARTMODE=\'onboot\'\n"; - print FILE "UNIQUE=\'\'\n"; - print FILE "USERCONTROL=\'no\'\n"; - print FILE "_nm_name=\'static-0\'\n"; - - close FILE; - runcmd("ifup $nic"); - } + } } else { - # Write the info to the ifcfg file - my $dir = "/etc/sysconfig/network-scripts"; - if (!open(FILE, ">$dir/ifcfg-$nic")) { system("logger -t xcat 'configeth: cannot open $dir/ifcfg-$nic.'"); exit 1; } - print FILE "DEVICE=$nic\n"; - print FILE "BOOTPROTO=none\n"; - print FILE "IPADDR=$ip\n"; - print FILE "NETMASK=$netmask\n"; - if (defined($gateway)) { print FILE "GATEWAY=$gateway\n"; } - print FILE "ONBOOT=yes\n"; - close FILE; + # Write the info to the ifcfg file + my $dir = "/etc/sysconfig/network-scripts"; + if (!open(FILE, ">$dir/ifcfg-$nic")) { system("logger -t xcat 'configeth: cannot open $dir/ifcfg-$nic.'"); exit 1; } + print FILE "DEVICE=$nic\n"; + print FILE "BOOTPROTO=none\n"; + print FILE "IPADDR=$ip\n"; + print FILE "NETMASK=$netmask\n"; + if (defined($gateway)) { print FILE "GATEWAY=$gateway\n"; } + print FILE "ONBOOT=yes\n"; + close FILE; - runcmd("$dir/ifup $nic"); + runcmd("$dir/ifup $nic"); } system("logger -t xcat 'configeth: successfully configured $nic.'"); exit 0; sub runcmd { - my $cmd = shift @_; - $cmd .= ' 2>&1'; - my @output = `$cmd`; - my $rc = $? >> 8; - if ($rc) { - system("logger -t xcat 'configeth: command $cmd failed with rc $rc: " . join('',@output) . "'"); - my $errout= "configeth: command $cmd failed with rc $rc."; - echo $errout; - exit $rc; - } + my $cmd = shift @_; + $cmd .= ' 2>&1'; + my @output = `$cmd`; + my $rc = $? >> 8; + if ($rc) { + system("logger -t xcat 'configeth: command $cmd failed with rc $rc: " . join('', @output) . "'"); + my $errout = "configeth: command $cmd failed with rc $rc."; + echo $errout; + exit $rc; + } } #$master=$ENV{MASTER}; diff --git a/xCAT/postscripts/configfirewall b/xCAT/postscripts/configfirewall index eb2c81fa9..800127378 100755 --- a/xCAT/postscripts/configfirewall +++ b/xCAT/postscripts/configfirewall @@ -16,7 +16,7 @@ $Getopt::Long::ignorecase = 0; my @allowed_ports = ("22", "53", "69", "80", "443", "873", "3001", "3002"); -if(scalar(@ARGV) == 0) +if (scalar(@ARGV) == 0) { &usage(); exit 0; @@ -24,10 +24,10 @@ if(scalar(@ARGV) == 0) if ( !GetOptions( - 'private=s' => \$::opt_private, - 'public=s' => \$::opt_public, - 'nat' => \$::opt_nat, - 'ports=s' => \$::opt_ports, + 'private=s' => \$::opt_private, + 'public=s' => \$::opt_public, + 'nat' => \$::opt_nat, + 'ports=s' => \$::opt_ports, ) ) { @@ -37,14 +37,15 @@ if ( } # Invalid input arguments -if(scalar(@ARGV) > 0) +if (scalar(@ARGV) > 0) { print "Unknown options @ARGV\n"; &usage(); exit 1; } + # --private and --public must be used together -if(($::opt_private && !$::opt_public) || (!$::opt_private && $::opt_public)) +if (($::opt_private && !$::opt_public) || (!$::opt_private && $::opt_public)) { print "Flags --private and --public must be used together\n"; &usage(); @@ -74,48 +75,48 @@ if ($::opt_ports) if (-f "/etc/redhat-release") { - #From Redhat7, firewalld is used as the default firewall service, - #however, it does not support complex firewall rules. + #From Redhat7, firewalld is used as the default firewall service, + #however, it does not support complex firewall rules. #So we'd better disable firewalld and use iptables service #iptables service is shiped in iptables-services package in rhels7 iso, #which is not installed by default, it should be installed - if ( -f "/usr/lib/systemd/system/firewalld.service" ){ - if (system("systemctl is-active firewalld > /dev/null 2>&1") == 0){ - print "firewalld is running, stopping firewalld service \n"; - if(system ("service firewalld stop") ==0 ) - { - print "\n[success]\n"; - } - else - { - print "\n[failed]\n"; - exit 1 - } - } + if (-f "/usr/lib/systemd/system/firewalld.service") { + if (system("systemctl is-active firewalld > /dev/null 2>&1") == 0) { + print "firewalld is running, stopping firewalld service \n"; + if (system("service firewalld stop") == 0) + { + print "\n[success]\n"; + } + else + { + print "\n[failed]\n"; + exit 1 + } + } - if (system("systemctl is-enabled firewalld > /dev/null 2>&1") == 0){ - print "disabling firewalld service \n"; - if( system("systemctl disable firewalld") ==0) - { - print "\n[success]\n"; - } - else - { - print "\n[failed]\n"; - exit 1 - } - } + if (system("systemctl is-enabled firewalld > /dev/null 2>&1") == 0) { + print "disabling firewalld service \n"; + if (system("systemctl disable firewalld") == 0) + { + print "\n[success]\n"; + } + else + { + print "\n[failed]\n"; + exit 1 + } + } } - if ( (! -f "/usr/lib/systemd/system/iptables.service") && (! -f "/etc/init.d/iptables")){ - print "please install iptables-services (for redhat 7) or iptables package first by running:\n"; - print "on redhat7:\tyum install iptables-services\n"; - print " others:\tyum install iptables\n"; - exit 1 + if ((!-f "/usr/lib/systemd/system/iptables.service") && (!-f "/etc/init.d/iptables")) { + print "please install iptables-services (for redhat 7) or iptables package first by running:\n"; + print "on redhat7:\tyum install iptables-services\n"; + print " others:\tyum install iptables\n"; + exit 1 } - if($::opt_private && $::opt_public) + if ($::opt_private && $::opt_public) { &setup_ip_forwarding(); my $cmd = &generate_iptables_conf($::opt_private, $::opt_public); @@ -146,13 +147,13 @@ elsif (-f "/etc/SuSE-release") { my $conffile; my $conf; - if($::opt_private && $::opt_public) + if ($::opt_private && $::opt_public) { &setup_ip_forwarding(); $conffile = "/etc/sysconfig/SuSEfirewall2"; my @privates = split /,/, $::opt_private; my $privintf = join(' ', @privates); - + # Configuration content # if the public and private interface is the same, # do not set FW_DEV_EXT @@ -180,7 +181,7 @@ elsif (-f "/etc/SuSE-release") print CONFFILE $conf; close(CONFFILE); - # restart firewall + # restart firewall #my $cmd = "service SuSEfirewall2_setup restart"; #system($cmd); xCAT::Utils->restartservice("firewall"); @@ -196,7 +197,7 @@ elsif (system("grep -i ubuntu /etc/issue > /dev/null 2>&1") == 0) { my $fwconf = "/etc/fwrules.ubuntu"; - if($::opt_private && $::opt_public) + if ($::opt_private && $::opt_public) { &setup_ip_forwarding(); my $cmd = &generate_iptables_conf($::opt_private, $::opt_public); @@ -231,7 +232,7 @@ exit 0; sub usage() { - print "Usage:\n configfirewall --private --public [--nat] [--ports ]\n"; + print "Usage:\n configfirewall --private --public [--nat] [--ports ]\n"; } sub generate_iptables_conf() @@ -252,7 +253,8 @@ sub generate_iptables_conf() $cmd .= "iptables -A INPUT -i $publicintf -m state --state NEW -p tcp --dport $port -j ACCEPT;"; $cmd .= "iptables -A INPUT -i $publicintf -m state --state NEW -p udp --dport $port -j ACCEPT;"; } - # Reject settings for public interface + + # Reject settings for public interface $cmd .= "iptables -A INPUT -i $publicintf -j REJECT --reject-with icmp-port-unreachable;"; # Setup for private interfaces @@ -266,21 +268,22 @@ sub generate_iptables_conf() sub setup_ip_forwarding() { # Enable ip forwarding - my $conf_file="/etc/sysctl.conf"; + my $conf_file = "/etc/sysctl.conf"; `grep "net.ipv4.ip_forward" $conf_file`; if ($? == 0) { - `sed -i "s/^net.ipv4.ip_forward = .*/net.ipv4.ip_forward = 1/" $conf_file`; +`sed -i "s/^net.ipv4.ip_forward = .*/net.ipv4.ip_forward = 1/" $conf_file`; } else { `echo "net.ipv4.ip_forward = 1" >> $conf_file`; } `sysctl -e -p $conf_file`; } + sub generate_nat_conf() { my ($privintf, $pubintf) = @_; my $cmd; - my @privates = split /,/, $privintf; + my @privates = split /,/, $privintf; # Setup forward for public interface $cmd .= "iptables -t nat -A POSTROUTING -o $pubintf -j MASQUERADE;"; @@ -289,7 +292,7 @@ sub generate_nat_conf() foreach my $intf (@privates) { $cmd .= "iptables -A FORWARD -i $intf -j ACCEPT;"; - $cmd .= "iptables -A FORWARD -i $intf -o $pubintf -m state --state RELATED,ESTABLISHED -j ACCEPT;"; + $cmd .= "iptables -A FORWARD -i $intf -o $pubintf -m state --state RELATED,ESTABLISHED -j ACCEPT;"; } return $cmd; } diff --git a/xCAT/postscripts/confignimsh b/xCAT/postscripts/confignimsh index 9c18db13e..bae5dc534 100755 --- a/xCAT/postscripts/confignimsh +++ b/xCAT/postscripts/confignimsh @@ -37,13 +37,13 @@ use Socket; my $master = $ENV{'MASTER'}; my $mhost; my $shortmaster; -my $returnval=0; +my $returnval = 0; if ($master =~ /\d+\.\d+\.\d+\.\d+/) { - my $packedaddr = inet_aton($master); - $mhost = gethostbyaddr($packedaddr, AF_INET); + my $packedaddr = inet_aton($master); + $mhost = gethostbyaddr($packedaddr, AF_INET); } else { - $mhost = $master; + $mhost = $master; } ($shortmaster = $mhost) =~ s/\..*$//; chomp $shortmaster; @@ -64,30 +64,30 @@ chomp $shortname; # save off the existing niminfo file if (-f "/etc/niminfo") { - runcmd("mv /etc/niminfo /etc/niminfo.bak"); + runcmd("mv /etc/niminfo /etc/niminfo.bak"); } # create new niminfo file and start nimsh daemon etc. runcmd("niminit -a name=$shortname -a master=$shortmaster -a connect='nimsh'"); -# configure nimsh to use ssl +# configure nimsh to use ssl runcmd("nimclient -c"); # get rid of the .rhost - ???? if (-f "/.rhosts") { - runcmd("mv /.rhost /.rhost.orig"); + runcmd("mv /.rhost /.rhost.orig"); } exit $returnval; sub runcmd { - my $cmd = shift @_; - $cmd .= ' 2>&1'; - my @output = `$cmd`; - my $rc = $? >> 8; - if ($rc) { - system("logger -t xcat -p local4.err 'confignimsh: command $cmd failed with rc $rc: " . join('',@output) . "'"); - $returnval=$rc; - exit $rc; - } + my $cmd = shift @_; + $cmd .= ' 2>&1'; + my @output = `$cmd`; + my $rc = $? >> 8; + if ($rc) { + system("logger -t xcat -p local4.err 'confignimsh: command $cmd failed with rc $rc: " . join('', @output) . "'"); + $returnval = $rc; + exit $rc; + } } diff --git a/xCAT/postscripts/db2install b/xCAT/postscripts/db2install index 85cd3f397..33fa21450 100755 --- a/xCAT/postscripts/db2install +++ b/xCAT/postscripts/db2install @@ -35,7 +35,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -69,27 +69,27 @@ chomp $::sdate; $::hname = `hostname`; chomp $::hname; -$::MN = $ENV{'MASTER'}; # as known by the node -$::databaseloc = $ENV{'DATABASELOC'}; # directory for db instance -my $installdir = $ENV{'INSTALLDIR'}; # installdir +$::MN = $ENV{'MASTER'}; # as known by the node +$::databaseloc = $ENV{'DATABASELOC'}; # directory for db instance +my $installdir = $ENV{'INSTALLDIR'}; # installdir # check to see if the databaseloc attribute is in the installdir attribute # directory path. If it is error out and send something to syslog -my @installlocdir = split '/', $installdir; # get base of installdir -my @dblocdir = split '/',$::databaseloc; # get base of database -if ($installlocdir[1] eq $dblocdir[1] ) { # if they match,error - my $msg="db2install:The site databaseloc attribute is set to the directory or a sub-directory of the site table installloc or installdir attribute or the default of /install. This is not a supported configuration."; - `logger -t xcat -p local4.err $msg`; - exit(1); +my @installlocdir = split '/', $installdir; # get base of installdir +my @dblocdir = split '/', $::databaseloc; # get base of database +if ($installlocdir[1] eq $dblocdir[1]) { # if they match,error + my $msg = "db2install:The site databaseloc attribute is set to the directory or a sub-directory of the site table installloc or installdir attribute or the default of /install. This is not a supported configuration."; + `logger -t xcat -p local4.err $msg`; + exit(1); } if ($::osname eq 'AIX') { - $::installdb2dir = "/opt/IBM/db2/V9.7"; # default + $::installdb2dir = "/opt/IBM/db2/V9.7"; # default } else -{ # linux - $::installdb2dir = "/opt/ibm/db2/V9.7"; # default +{ # linux + $::installdb2dir = "/opt/ibm/db2/V9.7"; # default } my $msg; @@ -98,7 +98,7 @@ my $msg; my $db2install = $::installdb2dir; $db2install .= "\/instance"; if (!(-e ($db2install))) -{ # not already installed +{ # not already installed $::db2installloc = $ENV{'DB2INSTALLLOC'}; if (!$::db2installloc) { @@ -106,7 +106,7 @@ if (!(-e ($db2install))) } chomp $::db2installloc; $::db2installloc =~ - s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes + s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes # startNFS $rc = &startNFS; @@ -133,7 +133,7 @@ if (!(-e ($db2install))) else { $msg = - "db2install:Cannot mount the site.db2installloc directory to get the db2 code to install. Setup cannot continue.\n"; +"db2install:Cannot mount the site.db2installloc directory to get the db2 code to install. Setup cannot continue.\n"; `logger -t xcat -p local4.err $msg`; exit(1); } @@ -150,7 +150,7 @@ $rc = &getcfgloc; if ($rc != 0) { # could not get the cfgloc file, cannot continue $msg = - "db2install:Cannot get the cfgloc file from the MN. Client setup cannot continue. \n"; +"db2install:Cannot get the cfgloc file from the MN. Client setup cannot continue. \n"; `logger -t xcat -p local4.err $msg`; exit 1; } @@ -367,7 +367,7 @@ sub mountdb2code sub installdb2code { my $msg; - my $rc = 0; + my $rc = 0; my $installcode; my $installcode1 = "$::installloc/ese/db2_install"; my $installcode2 = "$::installloc/server/db2_install"; @@ -380,24 +380,25 @@ sub installdb2code `logger -t xcat -p local4.err $msg`; exit 1; } + # pick the correct install directory - if (-e $installcode1 ) { - $installcode=$installcode1; + if (-e $installcode1) { + $installcode = $installcode1; } else { - if (-e $installcode2 ) { - $installcode=$installcode2; - } else { - if (-e $installcode3 ) { - $installcode=$installcode3; + if (-e $installcode2) { + $installcode = $installcode2; } else { - $installcode=$installcode4; - } - } - } + if (-e $installcode3) { + $installcode = $installcode3; + } else { + $installcode = $installcode4; + } + } + } my $expect_log = "/tmp/xcatexpect.log"; $msg = - "db2install:Starting DB2 install. Monitor progress in $expect_log on the node. \n"; +"db2install:Starting DB2 install. Monitor progress in $expect_log on the node. \n"; `logger -t xcat -p local4.info $msg`; my $db2sql; my $timeout = 1000; #sets Expect default timeout, 0 accepts immediately @@ -467,23 +468,23 @@ sub installdb2code my @result = $db2sql->expect( $timeout, [ - $dir_prompt, - sub { - $db2sql->send("no\r"); - $db2sql->clear_accum(); - $db2sql->exp_continue(); - } + $dir_prompt, + sub { + $db2sql->send("no\r"); + $db2sql->clear_accum(); + $db2sql->exp_continue(); + } ], [ - $product_prompt, - sub { + $product_prompt, + sub { - $db2sql->send("CLIENT\r"); - $db2sql->exp_continue(); + $db2sql->send("CLIENT\r"); + $db2sql->exp_continue(); - } + } ] - ); + ); ########################################## # Expect error - report and quit ########################################## @@ -551,14 +552,15 @@ sub rundb2sqlsetup chomp $xcatcfg; my ($database, $instance, $password) = split('\|', $xcatcfg); if ($::databaseloc) { - if (!(-e $::databaseloc)) { # if it does not exist, create it - &runcmd("mkdir -p $::databaseloc"); - } - $cmd = - "DATABASELOC=$::databaseloc XCATDB2SERVER=$::MN XCATDB2PW=$password $::XCATROOT/bin/db2sqlsetup -i -C"; + + if (!(-e $::databaseloc)) { # if it does not exist, create it + &runcmd("mkdir -p $::databaseloc"); + } + $cmd = +"DATABASELOC=$::databaseloc XCATDB2SERVER=$::MN XCATDB2PW=$password $::XCATROOT/bin/db2sqlsetup -i -C"; } else { - $cmd = - "XCATDB2SERVER=$::MN XCATDB2PW=$password $::XCATROOT/bin/db2sqlsetup -i -C"; + $cmd = +"XCATDB2SERVER=$::MN XCATDB2PW=$password $::XCATROOT/bin/db2sqlsetup -i -C"; } $msg = "db2install:Running Client setup. \"$::XCATROOT/bin/db2sqlsetup -i -C\"\n"; `logger -t xcat -p local4.info $msg`; @@ -593,10 +595,10 @@ sub getresponse # open a socket to request data my $sock = IO::Socket::SSL->new( - PeerAddr => $::MN, - PeerPort => $port, - Proto => 'tcp', - ); + PeerAddr => $::MN, + PeerPort => $port, + Proto => 'tcp', + ); # try a few more times my $times = 1; @@ -606,10 +608,10 @@ sub getresponse $times++; $sock = IO::Socket::SSL->new( - PeerAddr => $::MN, - PeerPort => $port, - Proto => 'tcp', - ); + PeerAddr => $::MN, + PeerPort => $port, + Proto => 'tcp', + ); if ($times == 5) { last; @@ -693,11 +695,11 @@ sub openlistener my $listener = IO::Socket::INET->new( - LocalPort => '300', - Proto => 'tcp', - Listen => '64', - Reuse => 1 - ); + LocalPort => '300', + Proto => 'tcp', + Listen => '64', + Reuse => 1 + ); unless ($listener) { diff --git a/xCAT/postscripts/odbcsetup b/xCAT/postscripts/odbcsetup index 85e65728a..61350432d 100755 --- a/xCAT/postscripts/odbcsetup +++ b/xCAT/postscripts/odbcsetup @@ -24,7 +24,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -34,7 +34,7 @@ use xCAT::MsgUtils; # MAIN -my $rc = 0; +my $rc = 0; my $cmd; # setup some important variable @@ -44,8 +44,10 @@ chomp $::sdate; my $msg; + # get location of database $::databaseloc = $ENV{'DATABASELOC'}; + # check the /etc/xcat/cfgloc file to see if MySQL or DB2 # if it is not here, error out my $dbname = xCAT::Utils->get_DBName; @@ -65,17 +67,17 @@ else &setupmysqlodbc; } else { - if ($dbname eq "PG") - { - $msg = "odbcsetup:Setting up ODBC for PostgreSQL"; - `logger -t xcat -p local4.info $msg`; - &setupPGodbc; - } else { - $msg = - "odbcsetup:cfgloc file does not contain MySQL, DB2 or PG, will not setup ODBC."; - `logger -t xcat -p local4.err $msg`; - exit 1; - } + if ($dbname eq "PG") + { + $msg = "odbcsetup:Setting up ODBC for PostgreSQL"; + `logger -t xcat -p local4.info $msg`; + &setupPGodbc; + } else { + $msg = +"odbcsetup:cfgloc file does not contain MySQL, DB2 or PG, will not setup ODBC."; + `logger -t xcat -p local4.err $msg`; + exit 1; + } } } @@ -107,9 +109,9 @@ sub setupdb2odbc chomp $xcatcfg; my ($database, $instance, $password) = split('\|', $xcatcfg); if ($::databaseloc) { - $cmd = "DATABASELOC=$::databaseloc $::XCATROOT/bin/db2sqlsetup -o -C"; + $cmd = "DATABASELOC=$::databaseloc $::XCATROOT/bin/db2sqlsetup -o -C"; } else { - $cmd = "$::XCATROOT/bin/db2sqlsetup -o -C"; + $cmd = "$::XCATROOT/bin/db2sqlsetup -o -C"; } $msg = "odbcsetup: Running Client ODBC setup. \"$cmd\"\n"; `logger -t xcat -p local4.info $msg`; diff --git a/xCAT/postscripts/redirectps b/xCAT/postscripts/redirectps index 484abdc49..4263037b1 100755 --- a/xCAT/postscripts/redirectps +++ b/xCAT/postscripts/redirectps @@ -2,7 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html ##################################################### # -# xCAT post script for diskless nodes +# xCAT post script for diskless nodes # to redirect paging space to external NFS server, # which is specified through nfsserver attribute # @@ -10,12 +10,12 @@ if (!$ENV{'NFSSERVER'}) { - `logger -t xcat -p local4.err "environment variable does not exist, exiting..."`; - exit -1; +`logger -t xcat -p local4.err "environment variable does not exist, exiting..."`; + exit -1; } -my $nfsserver = $ENV{'NFSSERVER'}; -my @ps = (); +my $nfsserver = $ENV{'NFSSERVER'}; +my @ps = (); my @nfsserverps = (); my $cmd = "lsps -t nfs -c"; @@ -68,26 +68,26 @@ foreach my $psline (@ps) $cmd = "rmps $psname"; &runcmd($cmd); } - + sub runcmd { my ($cmd) = @_; - my $rc=0; - $cmd .= ' 2>&1' ; + my $rc = 0; + $cmd .= ' 2>&1'; @::outref = `$cmd`; if ($?) { $rc = $? >> 8; if ($rc > 0) { - `logger -t xcat -p local4.err "runcmd $cmd failed, error message is:"`; +`logger -t xcat -p local4.err "runcmd $cmd failed, error message is:"`; my $errmsg; foreach my $err (@::outref) { $errmsg .= $err; } `logger -t xcat -p local4.err "$errmsg"`; - exit -1; + exit -1; } } return $rc; diff --git a/xCAT/postscripts/servicenode b/xCAT/postscripts/servicenode index caf38b294..ee67b1a6f 100755 --- a/xCAT/postscripts/servicenode +++ b/xCAT/postscripts/servicenode @@ -40,23 +40,24 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; use strict; + # MAIN use IO::Socket; -my $useSocketSSL=eval { require IO::Socket::SSL; }; +my $useSocketSSL = eval { require IO::Socket::SSL; }; if ($useSocketSSL) { - require IO::Socket::SSL; + require IO::Socket::SSL; } # MAIN -my $rc=0; -my $msg=""; +my $rc = 0; +my $msg = ""; $::osname = `uname`; chomp $::osname; @@ -69,10 +70,10 @@ chomp $::hname; my $installdir = $ENV{'INSTALLDIR'}; if (!$installdir) { - $installdir="/install"; + $installdir = "/install"; } chomp $installdir; -$installdir =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes +$installdir =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes # update security certificates keys for service node # This section is used for the updatenode -k function, which sets the @@ -81,33 +82,34 @@ if ($ENV{UPDATESECURITY} && $ENV{UPDATESECURITY} eq "1") { $::servnode = $ENV{'MASTER'}; # only run for service node - if (! -f "/etc/xCATSN") { + if (!-f "/etc/xCATSN") { exit 0; } # copy the postscripts to /install/postscripts, if not mounted -require xCAT::Utils; + require xCAT::Utils; my $mounted = xCAT::Utils->isMounted($installdir); - if ($mounted == 0) { # not mounted - if (&runcmd("mkdir -p $installdir/postscripts; cp -p -R /xcatpost/* $installdir/postscripts > /dev/null 2>&1") != 0 ) { - $msg = "$::sdate servicenode: Could not copy postscripts to $installdir/postscripts.\n"; - `logger -t xcat -p local4.warning $msg`; - } + if ($mounted == 0) { # not mounted + if (&runcmd("mkdir -p $installdir/postscripts; cp -p -R /xcatpost/* $installdir/postscripts > /dev/null 2>&1") != 0) { + $msg = "$::sdate servicenode: Could not copy postscripts to $installdir/postscripts.\n"; + `logger -t xcat -p local4.warning $msg`; + } } # copy the certificates - ©certs; + ©certs; if ($::osname eq 'AIX') { + # get the xCAT credentials from the server &getcreds; - } else { # Linux - # call xcatserver,xcatclient to transfer the SSL credentials and cfgloc - `logger -t xcat -p local4.info $::sdate servicenode: running xcatserver -d`; - &runcmd("xcatserver -d"); - `logger -t xcat -p local4.info $::sdate servicenode: running xcatclient -d`; - &runcmd("xcatclient -d"); + } else { # Linux + # call xcatserver,xcatclient to transfer the SSL credentials and cfgloc +`logger -t xcat -p local4.info $::sdate servicenode: running xcatserver -d`; + &runcmd("xcatserver -d"); +`logger -t xcat -p local4.info $::sdate servicenode: running xcatclient -d`; + &runcmd("xcatclient -d"); } - + exit 0; } @@ -115,29 +117,30 @@ require xCAT::Utils; if ($::osname eq 'AIX') { - # AIX service node setup - $rc = &setupAIXsn; - if ( $rc != 0) { - my $msg="$::sdate servicenode: One or more errors occurred when attempting to configure node $::hname as an xCAT service node.\n"; -# print "$msg\n"; - `logger -t xcat -p local4.warning $msg`; - } -} + # AIX service node setup + $rc = &setupAIXsn; + if ($rc != 0) { + my $msg = "$::sdate servicenode: One or more errors occurred when attempting to configure node $::hname as an xCAT service node.\n"; + + # print "$msg\n"; + `logger -t xcat -p local4.warning $msg`; + } +} else { - # Linux setup - # remove OpenIPMI-tools - # install xcat from /install/xcat - # Copy Certificates, and config file to apprpriate directories - # from /install and restart xcatd - &runcmd("rpm -e OpenIPMI-tools"); + # Linux setup + # remove OpenIPMI-tools + # install xcat from /install/xcat + # Copy Certificates, and config file to apprpriate directories + # from /install and restart xcatd + &runcmd("rpm -e OpenIPMI-tools"); - ©certs; - - `logger -t xcat -p local4.info $::sdate servicenode: running xcatserver -d`; - &runcmd("xcatserver -d"); - `logger -t xcat -p local4.info $::sdate servicenode: running xcatclient -d`; - &runcmd("xcatclient -d"); + ©certs; + +`logger -t xcat -p local4.info $::sdate servicenode: running xcatserver -d`; + &runcmd("xcatserver -d"); + `logger -t xcat -p local4.info $::sdate servicenode: running xcatclient -d`; + &runcmd("xcatclient -d"); } `logger -t xcat -p local4.info $::sdate servicenode: rc=$rc`; @@ -151,50 +154,51 @@ exit $rc; sub runcmd { my ($cmd) = @_; - my $rc=0; + my $rc = 0; - $cmd .= ' 2>&1' ; + $cmd .= ' 2>&1'; - # my $outref = []; - # @$outref = `$cmd`; + # my $outref = []; + # @$outref = `$cmd`; - $::outref = []; - $::outref = `$cmd`; + $::outref = []; + $::outref = `$cmd`; if ($?) { $rc = $? >> 8; if ($rc > 0) { - my $msg="$::sdate servicenode: $cmd returned rc=$rc \n"; + my $msg = "$::sdate servicenode: $cmd returned rc=$rc \n"; `logger -t xcat -p local4.info $msg`; - return 1; + return 1; } } - return 0; + return 0; } # do AIX service node setup sub setupAIXsn { - my $error=0; + my $error = 0; - # get the name of my service node/NIM master from the MASTER env var - $::servnode = $ENV{'MASTER'}; + # get the name of my service node/NIM master from the MASTER env var + $::servnode = $ENV{'MASTER'}; - # makes it a service node - if (&runcmd("touch /etc/xCATSN") != 0 ) { - $msg = "$::sdate servicenode: Could not touch /etc/xCATSN\n"; + # makes it a service node + if (&runcmd("touch /etc/xCATSN") != 0) { + $msg = "$::sdate servicenode: Could not touch /etc/xCATSN\n"; `logger -t xcat -p local4.warning $msg`; } - # copy the postscripts to /install/postscripts - if (&runcmd("mkdir -p $installdir/postscripts; cp -p -R /xcatpost/* $installdir/postscripts > /dev/null 2>&1") != 0 ) { - $msg = "$::sdate servicenode: Could not copy postscripts to $installdir/postscripts.\n"; - `logger -t xcat -p local4.warning $msg`; - } + # copy the postscripts to /install/postscripts + if (&runcmd("mkdir -p $installdir/postscripts; cp -p -R /xcatpost/* $installdir/postscripts > /dev/null 2>&1") != 0) { + $msg = "$::sdate servicenode: Could not copy postscripts to $installdir/postscripts.\n"; + `logger -t xcat -p local4.warning $msg`; + } + + # check if /install/postscripts is in /etc/exports + if (&runcmd("/bin/cat /etc/exports 2>/dev/null | grep '$installdir/postscripts ' >/dev/null 2>&1") != 0) { - # check if /install/postscripts is in /etc/exports - if (&runcmd("/bin/cat /etc/exports 2>/dev/null | grep '$installdir/postscripts ' >/dev/null 2>&1") != 0) { # if not add it and make sure it is exported my $res; if ($ENV{'USENFSV4ONAIX'} && ($ENV{'USENFSV4ONAIX'} =~ /1|Yes|yes|YES|Y|y/)) @@ -212,50 +216,52 @@ sub setupAIXsn } } - # make sure we don't have xCATMN file - if (-f "/etc/xCATMN") { - if (&runcmd("rm /etc/xCATMN") != 0 ) { - $msg = "$::sdate servicenode: Could not remove /etc/xCATMN\n"; - `logger -t xcat -p local4.warning $msg`; - } - } - - # call copycerts - ©certs; - # get the xCAT credentials from the server - &getcreds; - - # Add the xcatd subsystem to the AIX - my $mkssys_cmd = "mkssys -p $::XCATROOT/sbin/xcatd -s xcatd -u 0 -S -n 15 -f 15 -a '-f' "; - - if (&runcmd($mkssys_cmd) != 0) { - $msg = "$::sdate servicenode: Could not create subsystem for xcatd. It maybe already have been added.\n"; - `logger -t xcat -p local4.warning $msg`; - } - - # start xcatd - if (&runcmd("$::XCATROOT/sbin/restartxcatd") != 0) { - $msg = "$::sdate servicenode: Could not start xcatd.\n\n $::outref \n"; - `logger -t xcat -p local4.warning $msg`; + # make sure we don't have xCATMN file + if (-f "/etc/xCATMN") { + if (&runcmd("rm /etc/xCATMN") != 0) { + $msg = "$::sdate servicenode: Could not remove /etc/xCATMN\n"; + `logger -t xcat -p local4.warning $msg`; + } } - # add xcatd to /etc/inittab??? - my $mkitab_cmd = qq~/usr/sbin/mkitab "xcatd:2:once:$::XCATROOT/sbin/restartxcatd > /dev/console 2>&1"~; + # call copycerts + ©certs; - if (&runcmd($mkitab_cmd) != 0) { - # error might just mean that the entry is already there! + # get the xCAT credentials from the server + &getcreds; - # $msg = "$::sdate servicenode: Could not add xcatd to /etc/inittab.\n"; - # `logger -t xcat $msg`; - } + # Add the xcatd subsystem to the AIX + my $mkssys_cmd = "mkssys -p $::XCATROOT/sbin/xcatd -s xcatd -u 0 -S -n 15 -f 15 -a '-f' "; - # set ulimit - so we can copy over large files - like spot - if (&runcmd("/usr/bin/chuser fsize=-1 root") != 0) { - $msg = "$::sdate servicenode: Could not change ulimit\n"; - `logger -t xcat -p local4.warning $msg`; - } + if (&runcmd($mkssys_cmd) != 0) { + $msg = "$::sdate servicenode: Could not create subsystem for xcatd. It maybe already have been added.\n"; + `logger -t xcat -p local4.warning $msg`; + } - # stop inetd, make sure bootp & tftp are in /etc/inetd.conf and restart + # start xcatd + if (&runcmd("$::XCATROOT/sbin/restartxcatd") != 0) { + $msg = "$::sdate servicenode: Could not start xcatd.\n\n $::outref \n"; + `logger -t xcat -p local4.warning $msg`; + } + + # add xcatd to /etc/inittab??? + my $mkitab_cmd = qq~/usr/sbin/mkitab "xcatd:2:once:$::XCATROOT/sbin/restartxcatd > /dev/console 2>&1"~; + + if (&runcmd($mkitab_cmd) != 0) { + + # error might just mean that the entry is already there! + + # $msg = "$::sdate servicenode: Could not add xcatd to /etc/inittab.\n"; + # `logger -t xcat $msg`; + } + + # set ulimit - so we can copy over large files - like spot + if (&runcmd("/usr/bin/chuser fsize=-1 root") != 0) { + $msg = "$::sdate servicenode: Could not change ulimit\n"; + `logger -t xcat -p local4.warning $msg`; + } + + # stop inetd, make sure bootp & tftp are in /etc/inetd.conf and restart if (&runcmd("stopsrc -s inetd") != 0) { $msg = "$::sdate servicenode: Could not stop inetd.\n"; `logger -t xcat -p local4.warning $msg`; @@ -282,10 +288,10 @@ sub setupAIXsn print TMPINETD $l . "\n"; } } - close (TMPINETD); - close (INETDFILE); + close(TMPINETD); + close(INETDFILE); - if (&runcmd("mv $tmp_inetd_file $inetd_file_name > /dev/null 2>&1") != 0) { + if (&runcmd("mv $tmp_inetd_file $inetd_file_name > /dev/null 2>&1") != 0) { $msg = "$::sdate servicenode: Could not update /etc/inetd.conf.\n"; `logger -t xcat -p local4.warning $msg`; } @@ -295,103 +301,104 @@ sub setupAIXsn `logger -t xcat -p local4.warning $msg`; } - # do nim master setup - master fileset already installed + # do nim master setup - master fileset already installed if (&runcmd("/usr/sbin/nim_master_setup -a mk_resource=no") != 0) { $msg = "$::sdate servicenode: Could not run nim_master_setup.\n"; `logger -t xcat -p local4.warning $msg`; } - # - # TODO - can configure NIM to use SSL - "nimconfig -c" - # !!!!! can't do diskless nodes w/ nimsh & SSL enabled!!!! - # + # + # TODO - can configure NIM to use SSL - "nimconfig -c" + # !!!!! can't do diskless nodes w/ nimsh & SSL enabled!!!! + # - # restore the original .rhosts that was removed by NIM setup - if (&runcmd("cp /.rhosts.prev /.rhosts ") != 0 ) { - $msg = "$::sdate servicenode: Could not restore the .rhosts file.\n"; - `logger -t xcat -p local4.warning $msg`; - } + # restore the original .rhosts that was removed by NIM setup + if (&runcmd("cp /.rhosts.prev /.rhosts ") != 0) { + $msg = "$::sdate servicenode: Could not restore the .rhosts file.\n"; + `logger -t xcat -p local4.warning $msg`; + } - return 0; + return 0; } ##################################################### # -# getcreds ( For AIX) . +# getcreds ( For AIX) . # Same function in xcatserver,xcatclient for Linux # Get xCAT SSL credentials and DB cfgloc file # ##################################################### sub getcreds { - my $response=&getresponse("xcat_client_cred"); - if (defined ($response) ) { - my $fd; - my $filename = "/.xcat/client-cred.pem"; - &runcmd("mkdir -p /.xcat"); - &runcmd("chmod 700 /.xcat > /dev/null 2>&1"); - open($fd, '>',$filename); - print $fd $response; - close($fd); + my $response = &getresponse("xcat_client_cred"); + if (defined($response)) { + my $fd; + my $filename = "/.xcat/client-cred.pem"; + &runcmd("mkdir -p /.xcat"); + &runcmd("chmod 700 /.xcat > /dev/null 2>&1"); + open($fd, '>', $filename); + print $fd $response; + close($fd); - # set the permissions - my $cmd = "chmod 600 $filename > /dev/null 2>&1"; - &runcmd($cmd); - } - else { - $msg = "$::sdate servicenode: Could not get client-cred.pem file.\n"; - `logger -t xcat -p local4.warning $msg`; - } + # set the permissions + my $cmd = "chmod 600 $filename > /dev/null 2>&1"; + &runcmd($cmd); + } + else { + $msg = "$::sdate servicenode: Could not get client-cred.pem file.\n"; + `logger -t xcat -p local4.warning $msg`; + } - $response=&getresponse("xcat_server_cred"); - if (defined ($response) ) { - my $fd; - my $filename = "/etc/xcat/cert/server-cred.pem"; - &runcmd("mkdir -p /etc/xcat/cert"); - open($fd, '>',$filename); - print $fd $response; - close($fd); + $response = &getresponse("xcat_server_cred"); + if (defined($response)) { + my $fd; + my $filename = "/etc/xcat/cert/server-cred.pem"; + &runcmd("mkdir -p /etc/xcat/cert"); + open($fd, '>', $filename); + print $fd $response; + close($fd); - # set the permissions - my $cmd = "chmod 600 /etc/xcat/cert/* > /dev/null 2>&1"; - &runcmd($cmd); - } - else { + # set the permissions + my $cmd = "chmod 600 /etc/xcat/cert/* > /dev/null 2>&1"; + &runcmd($cmd); + } + else { $msg = "$::sdate servicenode: Could not get server-cred.pem file.\n"; `logger -t xcat -p local4.warning $msg`; } - $response=&getresponse("xcat_cfgloc"); - if (defined ($response) ) { - # need to change entry to use the name of the server as - # know by this node + $response = &getresponse("xcat_cfgloc"); + if (defined($response)) { + + # need to change entry to use the name of the server as + # know by this node # except for db2 which has a different format, no host my $newstr; - if ($response =~ /^DB2:/){ - $newstr = $response; + if ($response =~ /^DB2:/) { + $newstr = $response; } else { - my ($begin, $tmp) = split(';', $response); - my ($tmp2, $end, $end2) = split('\|', $tmp); - my ($tmp3, $oldserv) = split('=', $tmp2); - $newstr = "$begin;$tmp3=$::servnode|$end|$end2"; + my ($begin, $tmp) = split(';', $response); + my ($tmp2, $end, $end2) = split('\|', $tmp); + my ($tmp3, $oldserv) = split('=', $tmp2); + $newstr = "$begin;$tmp3=$::servnode|$end|$end2"; } - my $fd; - my $filename = "/etc/xcat/cfgloc"; - &runcmd("mkdir -p /etc/xcat"); - open($fd, '>',$filename); - print $fd $newstr; - close($fd); + my $fd; + my $filename = "/etc/xcat/cfgloc"; + &runcmd("mkdir -p /etc/xcat"); + open($fd, '>', $filename); + print $fd $newstr; + close($fd); - # set the permissions - my $cmd = "chmod 600 $filename > /dev/null 2>&1"; - &runcmd($cmd); - } - else { + # set the permissions + my $cmd = "chmod 600 $filename > /dev/null 2>&1"; + &runcmd($cmd); + } + else { $msg = "$::sdate servicenode: Could not get cfgloc file.\n"; `logger -t xcat -p local4.warning $msg`; } - return 0; + return 0; } ##################################################### @@ -405,72 +412,74 @@ sub getcreds ##################################################### sub getresponse { - my ($req) = @_; + my ($req) = @_; - my $port = "3001"; - my $node = $ENV{'NODE'}; + my $port = "3001"; + my $node = $ENV{'NODE'}; - # open listener connection to wait for check from management node - my $lpid = &openlistener(); + # open listener connection to wait for check from management node + my $lpid = &openlistener(); - # open a socket to request credentials - my $sock = IO::Socket::SSL->new( - PeerAddr => $::servnode, - PeerPort => $port, - Proto => 'tcp', - ); + # open a socket to request credentials + my $sock = IO::Socket::SSL->new( + PeerAddr => $::servnode, + PeerPort => $port, + Proto => 'tcp', + ); - # try a few more times - my $times=1; - while (!$sock) { - sleep(2); - $times++; - $sock = IO::Socket::SSL->new( - PeerAddr => $::servnode, - PeerPort => $port, - Proto => 'tcp', - ); - if ($times == 5) { - last; - } - } + # try a few more times + my $times = 1; + while (!$sock) { + sleep(2); + $times++; + $sock = IO::Socket::SSL->new( + PeerAddr => $::servnode, + PeerPort => $port, + Proto => 'tcp', + ); + if ($times == 5) { + last; + } + } - unless ($sock) { - my $msg = "$::sdate servicenode: Cannot connect to host \'$::servnode\'\n"; - `logger -t xcat -p local4.err $msg`; - print $msg; - return undef; - } + unless ($sock) { + my $msg = "$::sdate servicenode: Cannot connect to host \'$::servnode\'\n"; + `logger -t xcat -p local4.err $msg`; + print $msg; + return undef; + } - # request must be in XML format - print $sock "\n"; - print $sock " getcredentials\n"; - print $sock " $req\n"; - print $sock " 300\n"; - print $sock "\n"; + # request must be in XML format + print $sock "\n"; + print $sock " getcredentials\n"; + print $sock " $req\n"; + print $sock " 300\n"; + print $sock "\n"; -#TODO - do we have to try again after waiting for a bit???? - my $response=''; - my $line; - while (defined ($line = <$sock>)) { - # skip xml tags - next if ($line =~ /^\s*)) { - # once we get to serverdone we have the whole response - if ($line =~ m/<\/serverdone>/) { - last: - } - $response .= $line; - } + # skip xml tags + next if ($line =~ /^\s*/) { + last: + } + $response .= $line; + } - kill 2, $lpid; - if ($response) { - return $response; - } - return undef; + close($sock); + + #print "resp = \'$response\'\n"; + + kill 2, $lpid; + if ($response) { + return $response; + } + return undef; } ##################################################### @@ -481,62 +490,67 @@ sub getresponse ##################################################### sub openlistener { - my $node = $ENV{'NODE'}; + my $node = $ENV{'NODE'}; require xCAT::Utils; - # fork a child process to open a socket to listen for communication - # from the server - my $pid = xCAT::Utils->xfork; - unless (defined $pid) { - # fork failed - $msg = "$::sdate servicenode: Could not fork process.\n"; - `logger -t xcat -p local4.err $msg`; - #print $msg; - return undef; - } - if ($pid != 0) { - # This is the parent process, just return + # fork a child process to open a socket to listen for communication + # from the server + my $pid = xCAT::Utils->xfork; + unless (defined $pid) { + + # fork failed + $msg = "$::sdate servicenode: Could not fork process.\n"; + `logger -t xcat -p local4.err $msg`; + + #print $msg; + return undef; + } + + if ($pid != 0) { + + # This is the parent process, just return return $pid; } - my $listener = IO::Socket::INET->new( - LocalPort => '300', - Proto => 'tcp', - Listen => '64', - Reuse => 1 - ); + my $listener = IO::Socket::INET->new( + LocalPort => '300', + Proto => 'tcp', + Listen => '64', + Reuse => 1 + ); - unless ($listener) { - my $msg = "$::sdate servicenode: Cannot open socket on \'$node\'\n"; - `logger -t xcat -p local4.err $msg`; - print $msg; - exit 1; - } + unless ($listener) { + my $msg = "$::sdate servicenode: Cannot open socket on \'$node\'\n"; + `logger -t xcat -p local4.err $msg`; + print $msg; + exit 1; + } - # xcatd sends a quick req to see if we are really asking - # for info - this listener checks for the req and says ok - my $client; - while ($client = $listener->accept()) { - # $client is the new connection - my $text=<$client>; + # xcatd sends a quick req to see if we are really asking + # for info - this listener checks for the req and says ok + my $client; + while ($client = $listener->accept()) { - # see if we got "CREDOKBYYOU?" - if ($text =~ /CREDOKBYYOU?/) { - print $client "CREDOKBYME"; - close($client); - close($listener); - exit 0; - } - close($client); - } - close($client); - close($listener); - exit 0; + # $client is the new connection + my $text = <$client>; + + # see if we got "CREDOKBYYOU?" + if ($text =~ /CREDOKBYYOU?/) { + print $client "CREDOKBYME"; + close($client); + close($listener); + exit 0; + } + close($client); + } + close($client); + close($listener); + exit 0; } ##################################################### # -# copycerts +# copycerts # Setup the /etc/xcat/ca, /etc/xcat/cert, ~/.xcat directories with # SSL certificates from the /xcatpost/_xcat directory # These certificate are needed to access the Databases from the SN @@ -546,9 +560,10 @@ sub copycerts { my $rc = 0; `touch /etc/xCATSN`; + # get roots home directory - my @user= getpwuid($>); - my $homedir=$user[7]; + my @user = getpwuid($>); + my $homedir = $user[7]; if (-d "/xcatpost/_xcat") { if (!(-d "$homedir/.xcat")) @@ -584,26 +599,27 @@ sub copycerts `logger -t xcat -p local4.warning $msg`; } + # if AIX, only need for AIX because xcatserver script does it for Linux - if ($^O =~ /^aix/i) { - if (-d "/xcatpost/_xcat") - { - if (!(-d "/etc/xcat")) + if ($^O =~ /^aix/i) { + if (-d "/xcatpost/_xcat") { - mkdir("/etc/xcat", 0755); + if (!(-d "/etc/xcat")) + { + mkdir("/etc/xcat", 0755); + } + if (!(-d "/etc/xcat/cert")) + { + mkdir("/etc/xcat/cert", 0755); + } + `cp -f -rp /xcatpost/_xcat/* /etc/xcat/cert`; + `chmod 0600 /etc/xcat/cert/*`; } - if (!(-d "/etc/xcat/cert")) + else { - mkdir("/etc/xcat/cert", 0755); + $msg = "$::sdate servicenode: /xcatpost/_xcat directory does not exist\n"; + `logger -t xcat -p local4.warning $msg`; } - `cp -f -rp /xcatpost/_xcat/* /etc/xcat/cert`; - `chmod 0600 /etc/xcat/cert/*`; - } - else - { - $msg = "$::sdate servicenode: /xcatpost/_xcat directory does not exist\n"; - `logger -t xcat -p local4.warning $msg`; - } } return $rc; } diff --git a/xCAT/postscripts/setupnfsv4replication b/xCAT/postscripts/setupnfsv4replication index 663fcd1cf..40c1e631c 100755 --- a/xCAT/postscripts/setupnfsv4replication +++ b/xCAT/postscripts/setupnfsv4replication @@ -2,7 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html ##################################################### # -# xCAT post script for diskless nodes +# xCAT post script for diskless nodes # to setup tunable parameters for NFSv4 replication failover # It only works on AIX for now # @@ -10,7 +10,7 @@ # Change these two parameters according to your requirements $::NFSRETRIES = 3; -$::NFSTIMEO = 50; +$::NFSTIMEO = 50; # Candidate commands: mount, df, lsfs, nfs4cl showfs # Only the mount command could list all file systems @@ -39,7 +39,7 @@ foreach my $line (@::outref) push @nfs4fs, $mountedover; } } - + foreach my $nfs4mnt (@nfs4fs) { my $nfscmd = "nfs4cl setfsoptions $nfs4mnt timeo=$::NFSTIMEO; nfs4cl setfsoptions $nfs4mnt retrans=$::NFSRETRIES"; @@ -49,15 +49,15 @@ foreach my $nfs4mnt (@nfs4fs) sub runcmd { my ($cmd) = @_; - my $rc=0; - $cmd .= ' 2>&1' ; + my $rc = 0; + $cmd .= ' 2>&1'; @::outref = `$cmd`; if ($?) { $rc = $? >> 8; if ($rc > 0) { - `logger -t xcat -p local4.err "runcmd $cmd failed, error message is:"`; +`logger -t xcat -p local4.err "runcmd $cmd failed, error message is:"`; my $errmsg; foreach my $err (@::outref) { @@ -65,7 +65,7 @@ sub runcmd } `logger -t xcat -p local4.err "$errmsg"`; - exit; + exit; } } return $rc; diff --git a/xCAT/postscripts/startsyncfiles.aix b/xCAT/postscripts/startsyncfiles.aix index 54d33f1b6..982e7c611 100644 --- a/xCAT/postscripts/startsyncfiles.aix +++ b/xCAT/postscripts/startsyncfiles.aix @@ -3,7 +3,7 @@ ##################################################### # # xCAT post script for AIX nodes -# This script will send command "syncfiles" to the xcatd on +# This script will send command "syncfiles" to the xcatd on # management node or service node to initiate the sync file # operation by xdcp command # @@ -11,16 +11,16 @@ use XML::Simple; -my $useSocketSSL=eval { require IO::Socket::SSL; }; +my $useSocketSSL = eval { require IO::Socket::SSL; }; if ($useSocketSSL) { - require IO::Socket::SSL; + require IO::Socket::SSL; } my $port = "3001"; -my $remote = IO::Socket::SSL->new( Proto => "tcp", PeerAddr => $ENV{MASTER}, PeerPort => $port, ); +my $remote = IO::Socket::SSL->new(Proto => "tcp", PeerAddr => $ENV{MASTER}, PeerPort => $port,); unless ($remote) { - `logger -t xcat -p local4.err "startsyncfiles: Cannot connect to host $ENV{MASTER}"`; - exit 0; +`logger -t xcat -p local4.err "startsyncfiles: Cannot connect to host $ENV{MASTER}"`; + exit 0; } # Send Syncing File request to the xcatd @@ -29,27 +29,27 @@ print $remote " syncfiles\n"; print $remote "\n"; -my $response=''; +my $response = ''; my $rsp; my $rc = 0; while (<$remote>) { - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - $rsp = eval { XMLin($response,SuppressEmpty=>undef,ForceArray=>1) }; + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + $rsp = eval { XMLin($response, SuppressEmpty => undef, ForceArray => 1) }; - if ($rsp->{errorcode}) { - $rc = $rsp->{errorcode}[0]; - } elsif ($rsp->{error}) { - $rc = $rsp->{error}[0]; - } - if ($rsp->{serverdone}) { - close $remote; - if ($rc) { $rc = 1; } - exit $rc; - } + if ($rsp->{errorcode}) { + $rc = $rsp->{errorcode}[0]; + } elsif ($rsp->{error}) { + $rc = $rsp->{error}[0]; + } + if ($rsp->{serverdone}) { + close $remote; + if ($rc) { $rc = 1; } + exit $rc; + } - $response=''; - } + $response = ''; + } } diff --git a/xCAT/postscripts/xcataixpost b/xCAT/postscripts/xcataixpost index 58f204131..4b27972d5 100755 --- a/xCAT/postscripts/xcataixpost +++ b/xCAT/postscripts/xcataixpost @@ -8,22 +8,22 @@ # diskless and diskfull AIX nodes as setup by xcataixscript # # It is run by the updatenode cmd -P by calling xcatdsklspost 1 -m/-M (mode 1) -# updatenode cmd -k by calling xcatdsklspost 5 (mode 5) +# updatenode cmd -k by calling xcatdsklspost 5 (mode 5) # moncfg command (-c 3) option c means refresh /xcatpost # For full install called from aixinstall.pm plugin with no parameters -# +# ##################################################### # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use strict; use File::Path; use IO::Socket; -my $useSocketSSL=eval { require IO::Socket::SSL; }; +my $useSocketSSL = eval { require IO::Socket::SSL; }; use Getopt::Long; use XML::Simple; use Sys::Hostname; @@ -33,21 +33,21 @@ use Sys::Hostname; my $logdir = "/var/log/xcat"; if (!-d $logdir) { - mkpath($logdir); + mkpath($logdir); } -$::NOERROR=0; # used to control whether to display an error -$::sdate = `/bin/date`; +$::NOERROR = 0; # used to control whether to display an error +$::sdate = `/bin/date`; chomp $::sdate; my $logfile = $logdir . "/xcat.log"; `logger -t xcat -p local4.info "my logfile is $logfile"`; # this log should not contain much so it might be ok to let it grow? # at least we'll have the errors preserved -open(LOGFILE,">>",$logfile); +open(LOGFILE, ">>", $logfile); $::LOG_FILE = \*LOGFILE; unless ($useSocketSSL) { - `logger -t xcat -p local4.info "xcataixpost: Error: cannot load necessary library IO::Socket::SSL."`; +`logger -t xcat -p local4.info "xcataixpost: Error: cannot load necessary library IO::Socket::SSL."`; print $::LOG_FILE "$::sdate xcataixpost: Error: cannot load necessary library IO::Socket::SSL.\n"; exit 1; @@ -58,100 +58,105 @@ unless ($useSocketSSL) { # # the -c means get a fresh copy of the postscripts from the server # -m means we are updating the node -# -M means we are updating the service node /etc/xcatinfo file -my $idir; +# -M means we are updating the service node /etc/xcatinfo file +my $idir; my $nfsv4; Getopt::Long::Configure("no_pass_through"); $Getopt::Long::ignorecase = 0; if (!GetOptions('copy|c' => \$::opt_c, - 'm=s' => \$::opt_m, - 'M=s' => \$::opt_M, - 'tftp=s'=> \$::opt_tftpdir, - 'installdir=s'=> \$idir, - 'nfsv4=s'=> \$nfsv4)) + 'm=s' => \$::opt_m, + 'M=s' => \$::opt_M, + 'tftp=s' => \$::opt_tftpdir, + 'installdir=s' => \$idir, + 'nfsv4=s' => \$nfsv4)) { # Gather options - exit 1; -} + exit 1; +} my $mode; -if (@ARGV<1) { # not running updatenode +if (@ARGV < 1) { # not running updatenode - sleep int(rand(10)); # installing don't hit daemon with too many requests + sleep int(rand(10)); # installing don't hit daemon with too many requests } else { - $mode= $ARGV[0]; - `logger -t xcat -p local4.info "$::sdate xcataixpost: Running mode=$mode"`; + $mode = $ARGV[0]; + `logger -t xcat -p local4.info "$::sdate xcataixpost: Running mode=$mode"`; } -my $TFTPDIR=$::opt_tftpdir; +my $TFTPDIR = $::opt_tftpdir; my $servnode; # create new xcatinfo file if -M value is provided if ($::opt_M) { - if(-f "/etc/xcatinfo") { - # backup the old file - or remove ??? - my $cpcmd = "cp /etc/xcatinfo /etc/xcatinfo.orig 2>/dev/null"; - if (&runcmd($cpcmd) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not copy /etc/xcatinfo file."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not copy /etc/xcatinfo file.\n"; - } - } + if (-f "/etc/xcatinfo") { - # put the new server in the file - my $xcatinfo="/etc/xcatinfo"; - open(XCATINFO,">",$xcatinfo); - print XCATINFO "XCATSERVER=$::opt_M\n"; - close(XCATINFO); + # backup the old file - or remove ??? + my $cpcmd = "cp /etc/xcatinfo /etc/xcatinfo.orig 2>/dev/null"; + if (&runcmd($cpcmd) != 0) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not copy /etc/xcatinfo file."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not copy /etc/xcatinfo file.\n"; + } + } - chomp $::opt_M; - $servnode = $::opt_M; - $servnode =~ s/^\s*//; + # put the new server in the file + my $xcatinfo = "/etc/xcatinfo"; + open(XCATINFO, ">", $xcatinfo); + print XCATINFO "XCATSERVER=$::opt_M\n"; + close(XCATINFO); + + chomp $::opt_M; + $servnode = $::opt_M; + $servnode =~ s/^\s*//; } if ($::opt_m) { - chomp $::opt_m; - $servnode = $::opt_m; - $servnode =~ s/^\s*//; + chomp $::opt_m; + $servnode = $::opt_m; + $servnode =~ s/^\s*//; } unless ($servnode) { - if (-f "/etc/xcatinfo") { - # if this file exists assume it has the correct server name - my $cmd = "cat /etc/xcatinfo | grep 'XCATSERVER'"; - &runcmd($cmd); - my $SNline = $::outref; - my $junk; - ($junk, $servnode) = split(/=/, $SNline); - chomp $servnode; - $servnode =~ s/^\s*//; - } elsif (-f "/etc/niminfo") { - # get the name of my service node (NIM master) from /etc/niminfo - my $cmd = "cat /etc/niminfo | grep 'NIM_NAME'"; - &runcmd($cmd); - my $line = $::outref; - my $junk; - my $myname; - ($junk, $myname) = split(/=/, $line); - chomp $myname; - if ($myname ne "master") { - $cmd = "cat /etc/niminfo | grep 'NIM_MASTER_HOSTNAME'"; - &runcmd($cmd); - my $SNline = $::outref; - ($junk, $servnode) = split(/=/, $SNline); - if ($servnode) { - chomp $servnode; - $servnode =~ s/^\s*//; - # save the servnode from niminfo in xcatinfo - my $xcatinfo="/etc/xcatinfo"; - open(XCATINFO,">",$xcatinfo); - print XCATINFO "XCATSERVER=$servnode\n"; - close(XCATINFO); - } - } - } + if (-f "/etc/xcatinfo") { + + # if this file exists assume it has the correct server name + my $cmd = "cat /etc/xcatinfo | grep 'XCATSERVER'"; + &runcmd($cmd); + my $SNline = $::outref; + my $junk; + ($junk, $servnode) = split(/=/, $SNline); + chomp $servnode; + $servnode =~ s/^\s*//; + } elsif (-f "/etc/niminfo") { + + # get the name of my service node (NIM master) from /etc/niminfo + my $cmd = "cat /etc/niminfo | grep 'NIM_NAME'"; + &runcmd($cmd); + my $line = $::outref; + my $junk; + my $myname; + ($junk, $myname) = split(/=/, $line); + chomp $myname; + + if ($myname ne "master") { + $cmd = "cat /etc/niminfo | grep 'NIM_MASTER_HOSTNAME'"; + &runcmd($cmd); + my $SNline = $::outref; + ($junk, $servnode) = split(/=/, $SNline); + if ($servnode) { + chomp $servnode; + $servnode =~ s/^\s*//; + + # save the servnode from niminfo in xcatinfo + my $xcatinfo = "/etc/xcatinfo"; + open(XCATINFO, ">", $xcatinfo); + print XCATINFO "XCATSERVER=$servnode\n"; + close(XCATINFO); + } + } + } } unless ($servnode) { - `logger -t xcat -p local4.info " $::sdate xcataixpost: Could not determine server name."`; +`logger -t xcat -p local4.info " $::sdate xcataixpost: Could not determine server name."`; print $::LOG_FILE "$::sdate xcataixpost: Could not determine server name.\n "; exit 1; @@ -160,156 +165,166 @@ unless ($servnode) { # create the xcatpost dir my $cmd = "mkdir -p /xcatpost"; if (&runcmd($cmd) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not create the /xcatpost directory."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not create the /xcatpost directory.\n"; - exit 1; +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not create the /xcatpost directory."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not create the /xcatpost directory.\n"; + exit 1; } # get the xCAT hostname and the mypostscript file if (&getxcatname($servnode) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not determine xCAT node name."`; +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not determine xCAT node name."`; print $::LOG_FILE "$::sdate xcataixpost: Could not determine xCAT node name.\n"; exit 1; } -my $xcatname=$::XCATNAME; -my $scriptname=$::SCRIPTNAME; +my $xcatname = $::XCATNAME; +my $scriptname = $::SCRIPTNAME; # get the installdir to use my $installdir; my $usenfsv4; if (-f $scriptname) { + # set the timezone my $cmd = "cat $scriptname | grep 'INSTALLDIR='"; &runcmd($cmd); my $dline = $::outref; - my ($junk, $installdir) = split(/=/, $dline); + my ($junk, $installdir) = split(/=/, $dline); if ($installdir) { - chomp $installdir; - $installdir =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes + chomp $installdir; + $installdir =~ s/^(\'|\")(.*)(\"|\')$/$2/; # remove any surrounding quotes } $cmd = "cat $scriptname | grep 'USENFSV4ONAIX='"; &runcmd($cmd); $dline = $::outref; - ($junk, $usenfsv4) = split(/=/, $dline); + ($junk, $usenfsv4) = split(/=/, $dline); if ($usenfsv4) { chomp $usenfsv4; } } if (!$installdir) { - $installdir = "/install"; + $installdir = "/install"; } # if the /xcatpost dir has not been populated or the -c option is # specified then do the mount and copy of /install/postscripts -if ( !(-f "/xcatpost/xcataixpost") || $::opt_c ) { +if (!(-f "/xcatpost/xcataixpost") || $::opt_c) { - # get the contents of the /install/postscripts dir on the server - # - mount dir from server and copy files - my $mcmd; - if ($usenfsv4 && ($usenfsv4 =~ /1|Yes|yes|YES|Y|y/)) - { - $mcmd = "mkdir -p /xcatmnt; mount -o vers=4 $servnode:$installdir/postscripts /xcatmnt"; - } else { - $mcmd = "mkdir -p /xcatmnt; mount $servnode:$installdir/postscripts /xcatmnt"; - } - if (&runcmd($mcmd) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not mount $installdir/postscripts from $servnode."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not mount $installdir/postscripts from $servnode.\n"; - } + # get the contents of the /install/postscripts dir on the server + # - mount dir from server and copy files + my $mcmd; + if ($usenfsv4 && ($usenfsv4 =~ /1|Yes|yes|YES|Y|y/)) + { + $mcmd = "mkdir -p /xcatmnt; mount -o vers=4 $servnode:$installdir/postscripts /xcatmnt"; + } else { + $mcmd = "mkdir -p /xcatmnt; mount $servnode:$installdir/postscripts /xcatmnt"; + } + if (&runcmd($mcmd) != 0) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not mount $installdir/postscripts from $servnode."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not mount $installdir/postscripts from $servnode.\n"; + } - my $cpcmd; + my $cpcmd; - if ((@ARGV==0) || ($ARGV[0] != 2)) { - #$cpcmd = "cp -p -R /xcatmnt/* /xcatpost 2>/dev/null"; - $cpcmd = "/usr/bin/rsync -Lprogtz /xcatmnt/* /xcatpost 2>/dev/null"; - } else { - # when argv[1]=2, there is only one postscript file, - # user wants only download it to save time - $cpcmd= "cp /xcatmnt/$ARGV[1] /xcatpost >/dev/null 2>&1"; - } + if ((@ARGV == 0) || ($ARGV[0] != 2)) { - if (&runcmd($cpcmd) != 0) { - # print "$::sdate xcataixpost: Could not copy postscripts to /xcatpost.\n"; - # print $::LOG_FILE "$::sdate xcataixpost: Could not copy postscripts to /xcatpost.\n"; - } + #$cpcmd = "cp -p -R /xcatmnt/* /xcatpost 2>/dev/null"; + $cpcmd = "/usr/bin/rsync -Lprogtz /xcatmnt/* /xcatpost 2>/dev/null"; + } else { - my $ucmd = "umount /xcatmnt; rmdir /xcatmnt"; - if (&runcmd($ucmd) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not unmount $installdir."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not unmount $installdir/postscripts.\n"; - } + # when argv[1]=2, there is only one postscript file, + # user wants only download it to save time + $cpcmd = "cp /xcatmnt/$ARGV[1] /xcatpost >/dev/null 2>&1"; + } -} # end recopy postscripts + if (&runcmd($cpcmd) != 0) { + + # print "$::sdate xcataixpost: Could not copy postscripts to /xcatpost.\n"; + # print $::LOG_FILE "$::sdate xcataixpost: Could not copy postscripts to /xcatpost.\n"; + } + + my $ucmd = "umount /xcatmnt; rmdir /xcatmnt"; + if (&runcmd($ucmd) != 0) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not unmount $installdir."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not unmount $installdir/postscripts.\n"; + } + +} # end recopy postscripts # make sure all are executable my $chcmd = "chmod +x /xcatpost/*"; if (&runcmd($chcmd) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not change /xcatpost file permissions."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not change /xcatpost file permissions.\n"; +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not change /xcatpost file permissions."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not change /xcatpost file permissions.\n"; } + # set TZ only on install -if (@ARGV==0) { - if (-f $scriptname) { - # set the timezone - my $cmd = "cat $scriptname | grep 'TIMEZONE='"; - &runcmd($cmd); - my $TZline = $::outref; - my ($junk, $tz) = split(/=/, $TZline); - if ($tz) { - chomp $tz; - my $tzcmd = qq~/usr/bin/chtz $tz >/dev/null 2>&1~; - if (&runcmd($tzcmd) != 0) { - my $msg = "$::sdate xcataixpost: Could not set timezone.\n"; - `logger -t xcat -p local4.warning $msg`; - } else { - &runcmd("export TZ=$tz"); - } +if (@ARGV == 0) { + if (-f $scriptname) { + + # set the timezone + my $cmd = "cat $scriptname | grep 'TIMEZONE='"; + &runcmd($cmd); + my $TZline = $::outref; + my ($junk, $tz) = split(/=/, $TZline); + if ($tz) { + chomp $tz; + my $tzcmd = qq~/usr/bin/chtz $tz >/dev/null 2>&1~; + if (&runcmd($tzcmd) != 0) { + my $msg = "$::sdate xcataixpost: Could not set timezone.\n"; + `logger -t xcat -p local4.warning $msg`; + } else { + &runcmd("export TZ=$tz"); + } + } } - } } # check & run the postscript -my $nodesetstat="standalone"; +my $nodesetstat = "standalone"; if (-f $scriptname) { # when called by the updatenode command, # modify the UPDATENODE flag to 1 if (@ARGV > 0) { - if ($ARGV[0] == 1 || $ARGV[0] == 2) { - my $TMP=`sed -e 's/UPDATENODE=0/UPDATENODE=1/g' $scriptname`; - `echo "$TMP" > $scriptname`; - } elsif ($ARGV[0] == 5) { - my $TMP=`sed -e 's/UPDATENODE=0/UPDATENODE=1\\\nUPDATESECURITY=1\\\nexport UPDATESECURITY/g' $scriptname`; - `echo "$TMP" > $scriptname`; - } + if ($ARGV[0] == 1 || $ARGV[0] == 2) { + my $TMP = `sed -e 's/UPDATENODE=0/UPDATENODE=1/g' $scriptname`; + `echo "$TMP" > $scriptname`; + } elsif ($ARGV[0] == 5) { + my $TMP = `sed -e 's/UPDATENODE=0/UPDATENODE=1\\\nUPDATESECURITY=1\\\nexport UPDATESECURITY/g' $scriptname`; + `echo "$TMP" > $scriptname`; + } } + # see if any arguments and if there are script on the argument list - my $lengtharg1=0; - if (defined ($ARGV[1])) { - $lengtharg1= length ($ARGV[1]); + my $lengtharg1 = 0; + if (defined($ARGV[1])) { + $lengtharg1 = length($ARGV[1]); } - if ((@ARGV>1) && ($lengtharg1 != 0)) { # no postscript list - my $scripts=$ARGV[1]; - `logger -t xcat -p local4.info "$::sdate xcataixpost: ARGV > 1."`; - my $POSTS=join('\n', split(',', $scripts)); - #print "scripts=$scripts\n"; - #remove all the postbootscripts - my $PSTMP=`sed "/# postbootscripts-start-here/,/# postbootscripts-end-here/ d" $scriptname`; - `echo "$PSTMP" > $scriptname`; - #remove all the postscripts - my $TMP=`sed "/# postscripts-start-here/,/# postscripts-end-here/ d" $scriptname`; - `echo "$TMP" > $scriptname`; - `echo "# postscripts-start-here" >> $scriptname`; - #add requested postscripts in - `echo "$POSTS" | tr "," "\n" >> $scriptname`; - `echo "# postscripts-end-here" >> $scriptname`; + if ((@ARGV > 1) && ($lengtharg1 != 0)) { # no postscript list + my $scripts = $ARGV[1]; + `logger -t xcat -p local4.info "$::sdate xcataixpost: ARGV > 1."`; + my $POSTS = join('\n', split(',', $scripts)); + + #print "scripts=$scripts\n"; + #remove all the postbootscripts + my $PSTMP = `sed "/# postbootscripts-start-here/,/# postbootscripts-end-here/ d" $scriptname`; + `echo "$PSTMP" > $scriptname`; + + #remove all the postscripts + my $TMP = `sed "/# postscripts-start-here/,/# postscripts-end-here/ d" $scriptname`; + `echo "$TMP" > $scriptname`; + `echo "# postscripts-start-here" >> $scriptname`; + + #add requested postscripts in + `echo "$POSTS" | tr "," "\n" >> $scriptname`; + `echo "# postscripts-end-here" >> $scriptname`; } # use the run_ps subroutine to run the postscripts - my $TMP1=`sed "/# postscripts-start-here/,/# postscripts-end-here/ s/\\(.*\\)/run_ps \\1/;s/run_ps *#/#/;s/run_ps *\$//" $scriptname`; + my $TMP1 = `sed "/# postscripts-start-here/,/# postscripts-end-here/ s/\\(.*\\)/run_ps \\1/;s/run_ps *#/#/;s/run_ps *\$//" $scriptname`; `echo "$TMP1" > $scriptname`; - my $TMP2=`sed "/# postbootscripts-start-here/,/# postbootscripts-end-here/ s/\\(.*\\)/run_ps \\1/;s/run_ps *#/#/;s/run_ps *\$//" $scriptname`; + my $TMP2 = `sed "/# postbootscripts-start-here/,/# postbootscripts-end-here/ s/\\(.*\\)/run_ps \\1/;s/run_ps *#/#/;s/run_ps *\$//" $scriptname`; `echo " # subroutine used to run postscripts run_ps () { @@ -329,9 +344,9 @@ run_ps () { " > $scriptname`; `echo "$TMP2" >> $scriptname`; - $nodesetstat=`grep "NODESETSTATE=" $scriptname|awk -F \= '{print \$2}'`; + $nodesetstat = `grep "NODESETSTATE=" $scriptname|awk -F \= '{print \$2}'`; chomp($nodesetstat); - $ENV{PATH}="/xcatpost:$ENV{PATH}"; + $ENV{PATH} = "/xcatpost:$ENV{PATH}"; &runcmd("cd /xcatpost;$scriptname"); if ($::outref) { print "$::sdate xcataixpost: run: $cmd - $::outref\n"; @@ -341,77 +356,81 @@ run_ps () { print $::LOG_FILE "$::sdate xcataixpost: run: $cmd \n"; } } else { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not find post script for $xcatname."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not find post script for $xcatname.\n"; +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not find post script for $xcatname."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not find post script for $xcatname.\n"; } -if (@ARGV<1) { # not running updatenode - my $update=1; - if (-f $scriptname) { - my $CNS=`grep NODESTATUS= $scriptname`; - if ((!$?) && ($CNS =~ /\'0\'|\'N\'|\'n\'/)) { $update=0;} #only update is nonodestatus is not set in the site table - } - if ($update) { - my $keywd="installstatus"; - my $state="booted"; - if (&updateflag($keywd, $state) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Failed to update the xCAT server."`; - print $::LOG_FILE "$::sdate xcataixpost: Failed to update the xCAT server..\n"; - } - } +if (@ARGV < 1) { # not running updatenode + my $update = 1; + if (-f $scriptname) { + my $CNS = `grep NODESTATUS= $scriptname`; + if ((!$?) && ($CNS =~ /\'0\'|\'N\'|\'n\'/)) { $update = 0; } #only update is nonodestatus is not set in the site table + } + if ($update) { + my $keywd = "installstatus"; + my $state = "booted"; + if (&updateflag($keywd, $state) != 0) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Failed to update the xCAT server."`; + print $::LOG_FILE "$::sdate xcataixpost: Failed to update the xCAT server..\n"; + } + } } else { - #called by updatenode, tell user it is done - `logger -t xcat -p local4.info "xcataixpost finished running postscripts"`; - print $::LOG_FILE "$::sdate xcataixpost: returned from postscript.\n"; + + #called by updatenode, tell user it is done + `logger -t xcat -p local4.info "xcataixpost finished running postscripts"`; + print $::LOG_FILE "$::sdate xcataixpost: returned from postscript.\n"; } if (-f $scriptname) { - if ($::ROOTPW) { - chomp $::ROOTPW; - my $pwcmd; + if ($::ROOTPW) { + chomp $::ROOTPW; + my $pwcmd; - if ($::CRYPTMETHOD) { - $pwcmd = qq~echo "root:$::ROOTPW" | /bin/chpasswd -e -c >/dev/null 2>&1~; - } else { - $pwcmd = qq~echo "root:$::ROOTPW" | /bin/chpasswd -c >/dev/null 2>&1~; - } - if (&runcmd($pwcmd) != 0) { - my $msg = "$::sdate xcataixpost: Could not set root password.\n"; - `logger -t xcat -p local4.warning $msg`; - } - } + if ($::CRYPTMETHOD) { + $pwcmd = qq~echo "root:$::ROOTPW" | /bin/chpasswd -e -c >/dev/null 2>&1~; + } else { + $pwcmd = qq~echo "root:$::ROOTPW" | /bin/chpasswd -c >/dev/null 2>&1~; + } + if (&runcmd($pwcmd) != 0) { + my $msg = "$::sdate xcataixpost: Could not set root password.\n"; + `logger -t xcat -p local4.warning $msg`; + } + } } # If this is a diskfull node then remove the xcat entry in the inittab file $nodesetstat =~ s/'|"//g; if ($nodesetstat eq 'standalone') { + # see if it is already there my $lsicmd = "/usr/sbin/lsitab xcat > /dev/null 2>&1"; if (&runcmd($lsicmd, 0) == 0) { + # ok - remove the entry my $rmitab_cmd = 'rmitab "xcat" > /dev/null 2>&1'; if (&runcmd($rmitab_cmd) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not remove xcataixpost from /etc/inittab."`; +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not remove xcataixpost from /etc/inittab."`; print $::LOG_FILE "$::sdate xcataixpost: Could not remove xcataixpost from /etc/inittab.\n"; } } } if ($nodesetstat eq 'diskless') { + # see if BASECUST_REMOVAL is set in /etc/niminfo if (-f "/etc/niminfo") { - $::NOERROR=1; - $cmd = "cat /etc/niminfo | grep 'BASECUST_REMOVAL'"; + $::NOERROR = 1; + $cmd = "cat /etc/niminfo | grep 'BASECUST_REMOVAL'"; &runcmd($cmd); my $line = $::outref; - my ($junk, $torm) = split(/=/, $line); + my ($junk, $torm) = split(/=/, $line); - $::NOERROR=0; - $cmd = "cat /etc/niminfo | grep 'NIM_HOSTNAME'"; + $::NOERROR = 0; + $cmd = "cat /etc/niminfo | grep 'NIM_HOSTNAME'"; &runcmd($cmd); $line = $::outref; - my ($junkn, $hostn) = split(/=/, $line); + my ($junkn, $hostn) = split(/=/, $line); if ($torm) { chomp $hostn; @@ -421,11 +440,11 @@ if ($nodesetstat eq 'diskless') { # so that it will not be present in the subsequent reboots my $keywd = "basecustremv"; if (&updateflag($keywd, $hostn) != 0) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Failed to update the xCAT server."`; +`logger -t xcat -p local4.info "$::sdate xcataixpost: Failed to update the xCAT server."`; print $::LOG_FILE "$::sdate xcataixpost: Failed to update the xCAT server.\n"; } } - } + } } my $cleanupxcatpost = `grep "CLEANUPXCATPOST=" $scriptname|awk -F \= '{print \$2}'`; @@ -447,169 +466,174 @@ exit 0; ##################################################### sub getmypost { - my $xcatname=shift; - my $scriptname=shift; + my $xcatname = shift; + my $scriptname = shift; - # If the tftpdir is not /tftpboot, + # If the tftpdir is not /tftpboot, # should use the -s flag to specify the tftpdir. # using gettab to get the tftpdir from MN/SN is not efficient # and has problem with sending multiple commands through one socket connection - if( !defined($TFTPDIR) ) { - $TFTPDIR="/tftpboot"; + if (!defined($TFTPDIR)) { + $TFTPDIR = "/tftpboot"; } # remove the mypostscript file, so make sure we get a new one - + &runcmd("rm -rf $scriptname"); # try to get the file with tftp first it is normal the file is not available, do not report - # error - `tftp -o $scriptname $servnode $TFTPDIR/mypostscripts/mypostscript.$xcatname 2>&1`; - if ((-e $scriptname) && (! (-z $scriptname))) { # got the file and it is not empty - `logger -t xcat -p local4.info "$::sdate xcataixpost: tftp got $scriptname."`; + # error +`tftp -o $scriptname $servnode $TFTPDIR/mypostscripts/mypostscript.$xcatname 2>&1`; + if ((-e $scriptname) && (!(-z $scriptname))) { # got the file and it is not empty +`logger -t xcat -p local4.info "$::sdate xcataixpost: tftp got $scriptname."`; - my $content; - if (!open($content, "<", $scriptname) ) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not open $scriptname."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not open $scriptname.\n"; - close $content; - return 1; - } - while (<$content>) { - my $line = $_; - $line =~ s/^\s+//; - if ($line =~ /=/) { - my ($attr, $val) = $line =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/; - if( defined( $attr ) ) { - if ($attr eq 'ROOTPW') { - $::ROOTPW=$val; - } - if ($attr eq 'CRYPTMETHOD') { - $::CRYPTMETHOD=$val; - } - } + my $content; + if (!open($content, "<", $scriptname)) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not open $scriptname."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not open $scriptname.\n"; + close $content; + return 1; } - } # end while - close $content; - - } - if (-z $scriptname) { # file is empty , get rid of it - &runcmd("rm -rf $scriptname"); - } - + while (<$content>) { + my $line = $_; + $line =~ s/^\s+//; + if ($line =~ /=/) { + my ($attr, $val) = $line =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/; + if (defined($attr)) { + if ($attr eq 'ROOTPW') { + $::ROOTPW = $val; + } + if ($attr eq 'CRYPTMETHOD') { + $::CRYPTMETHOD = $val; + } + } + } + } # end while + close $content; - # if could not get the file, then ask for the data + } + if (-z $scriptname) { # file is empty , get rid of it + &runcmd("rm -rf $scriptname"); + } - if(!( -f $scriptname)) { - my $port = "3001"; - # open a socket to request credentials - my $remote = IO::Socket::SSL->new( - PeerAddr => $servnode, - PeerPort => $port, - Proto => 'tcp', - ); - # get ready to create the file - if (!open(POSTSCRIPT, ">$scriptname") ) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not open $scriptname."`; - print $::LOG_FILE "$::sdate xcataixpost: Could not open $scriptname.\n" -; - close $remote; - return 1; - } - # setup the perl library path for xcat-dep packages - # this is necessary for AIX 5.3V/61H and beyond - # but does not hurt old AIX versions - print POSTSCRIPT "PERL5LIB='/usr/opt/perl5/lib/5.8.2:/usr/opt/perl5/lib/5.8.2/aix-thread-multi:/usr/opt/perl5/lib/site_perl/5.8.2:/usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi'\n"; - print POSTSCRIPT "export PERL5LIB\n"; - - unless ($remote) { - `logger -t xcat -p local4.info "$::sdate xcataixpost: Cannot connect to host \'$servnode\'"`; - print $::LOG_FILE "$::sdate xcataixpost: Cannot connect to host \'$servnode\'\n"; - return 1; - } + # if could not get the file, then ask for the data - # request must be in XML format - print $remote "\n"; - print $remote " getpostscript\n"; - print $remote "\n"; + if (!(-f $scriptname)) { + my $port = "3001"; - `logger -t xcat -p local4.info "$::sdate xcataixpost: calling getpostscript to get the data"`; - # get reponse in XML format - my $response=''; - my $rsp; - while (<$remote>) { - $response .= $_; - if ($response =~ m/<\/xcatresponse>/) { - $rsp = eval { XMLin($response,SuppressEmpty=>undef,ForceArray=>1) }; - if ($rsp->{serverdone}) { - last; - } - # now create the mypostscript* files from the sent data - foreach my $line (@{$rsp->{data}}) { - $line =~ s/^\s+//; - if ($line =~ /=/) { - my ($attr, $val) = $line =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/; - if ($attr eq 'ROOTPW') { - $::ROOTPW=$val; - } - if ($attr eq 'CRYPTMETHOD') { - $::CRYPTMETHOD=$val; - } - } - if (($line =~ /ROOTPW/) || ($line =~ /CRYPTMETHOD/)) { - next; - } - print POSTSCRIPT "$line"; - } - $response=''; + # open a socket to request credentials + my $remote = IO::Socket::SSL->new( + PeerAddr => $servnode, + PeerPort => $port, + Proto => 'tcp', + ); - } - } # end while + # get ready to create the file + if (!open(POSTSCRIPT, ">$scriptname")) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not open $scriptname."`; + print $::LOG_FILE "$::sdate xcataixpost: Could not open $scriptname.\n" + ; + close $remote; + return 1; + } - close(POSTSCRIPT); - close $remote; - } + # setup the perl library path for xcat-dep packages + # this is necessary for AIX 5.3V/61H and beyond + # but does not hurt old AIX versions + print POSTSCRIPT "PERL5LIB='/usr/opt/perl5/lib/5.8.2:/usr/opt/perl5/lib/5.8.2/aix-thread-multi:/usr/opt/perl5/lib/site_perl/5.8.2:/usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi'\n"; + print POSTSCRIPT "export PERL5LIB\n"; - return 0; + + unless ($remote) { +`logger -t xcat -p local4.info "$::sdate xcataixpost: Cannot connect to host \'$servnode\'"`; + print $::LOG_FILE "$::sdate xcataixpost: Cannot connect to host \'$servnode\'\n"; + return 1; + } + + # request must be in XML format + print $remote "\n"; + print $remote " getpostscript\n"; + print $remote "\n"; + +`logger -t xcat -p local4.info "$::sdate xcataixpost: calling getpostscript to get the data"`; + + # get reponse in XML format + my $response = ''; + my $rsp; + while (<$remote>) { + $response .= $_; + if ($response =~ m/<\/xcatresponse>/) { + $rsp = eval { XMLin($response, SuppressEmpty => undef, ForceArray => 1) }; + if ($rsp->{serverdone}) { + last; + } + + # now create the mypostscript* files from the sent data + foreach my $line (@{ $rsp->{data} }) { + $line =~ s/^\s+//; + if ($line =~ /=/) { + my ($attr, $val) = $line =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/; + if ($attr eq 'ROOTPW') { + $::ROOTPW = $val; + } + if ($attr eq 'CRYPTMETHOD') { + $::CRYPTMETHOD = $val; + } + } + if (($line =~ /ROOTPW/) || ($line =~ /CRYPTMETHOD/)) { + next; + } + print POSTSCRIPT "$line"; + } + $response = ''; + + } + } # end while + + close(POSTSCRIPT); + close $remote; + } + + return 0; } ############################################################ # # updateflag -# Tells xCAT on the server that the post scripts is done. +# Tells xCAT on the server that the post scripts is done. # ############################################################ -sub updateflag { - my $keywd=shift; - my $state=shift; - - my $port = "3002"; +sub updateflag { + my $keywd = shift; + my $state = shift; + + my $port = "3002"; my $servip = `host $servnode | awk '{print \$3}'`; chomp($servip); - $servip =~ s/,$//; # remove trailing comma - my $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); + $servip =~ s/,$//; # remove trailing comma + my $remote = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); my $try = 10; while (!$remote && $try-- > 0) { sleep 1; - $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); + $remote = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $servip, PeerPort => $port, Timeout => 0); print $::LOG_FILE "$::sdate xcataixpost: Cannot connect to host \'$servip\'\n"; } - unless ($remote) { + unless ($remote) { print "$::sdate xcataixpost: Cannot connect to host \'$servip\'\n"; print $::LOG_FILE "$::sdate xcataixpost: Cannot connect to host \'$servip\'\n"; - return 1; + return 1; } $remote->autoflush(1); my $line; - while (defined ($line = <$remote>)) { + while (defined($line = <$remote>)) { chomp $line; if ($line eq "ready") { - print $remote "$keywd $state\n"; + print $remote "$keywd $state\n"; } elsif ($line eq "done") { - last; + last; } } close $remote; @@ -620,7 +644,7 @@ sub updateflag { # # run the command # the first argument is the command string -# the second argument is the log flag, +# the second argument is the log flag, # 0 - does NOT log error message # 1 - log error message # if it is not specified, it equals to 1 @@ -630,11 +654,11 @@ sub runcmd { my ($cmd, $logerr) = @_; - if(! defined($logerr)) { + if (!defined($logerr)) { $logerr = 1; } - my $rc=0; - $cmd .= ' 2>&1' ; + my $rc = 0; + $cmd .= ' 2>&1'; $::outref = []; $::outref = `$cmd`; if ($?) @@ -642,18 +666,18 @@ sub runcmd $rc = $? >> 8; if ($rc > 0 && $logerr) { - if ($::NOERROR == 0) { # print the error message - if ($::outref) { - print "$::sdate xcataixpost: run: $cmd - $::outref\n"; - print $::LOG_FILE "$::sdate xcataixpost: run: $cmd - $::outref\n"; - } else { - print "$::sdate xcataixpost: run: $cmd \n"; - print $::LOG_FILE "$::sdate xcataixpost: run: $cmd \n"; - } - } + if ($::NOERROR == 0) { # print the error message + if ($::outref) { + print "$::sdate xcataixpost: run: $cmd - $::outref\n"; + print $::LOG_FILE "$::sdate xcataixpost: run: $cmd - $::outref\n"; + } else { + print "$::sdate xcataixpost: run: $cmd \n"; + print $::LOG_FILE "$::sdate xcataixpost: run: $cmd \n"; + } + } } } - return $rc; + return $rc; } ############################################################ @@ -665,113 +689,115 @@ sub runcmd ############################################################ sub getxcatname { - my $servnode=shift; + my $servnode = shift; + + my $xcatname; + my $scriptname; + my $xcatshort; + my $xcatlong; - my $xcatname; - my $scriptname; - my $xcatshort; - my $xcatlong; # updatenode will input the nodename as an ENV variable NODE # if we have this name, need not try anything else. - if ($ENV{NODE} ) { - $xcatname=$ENV{NODE}; + if ($ENV{NODE}) { + $xcatname = $ENV{NODE}; - # put the nodename in /etc/xcatinfo TODO, need logic not to - # wipe out XCATSERVER or add multiple entries + # put the nodename in /etc/xcatinfo TODO, need logic not to + # wipe out XCATSERVER or add multiple entries - `logger -t xcat -p local4.info "$::sdate xcataixpost:name=$xcatname"`; - $scriptname = "/xcatpost/myxcatpost_" . $xcatname; - if (&getmypost($xcatname,$scriptname) == 0) { - $::XCATNAME=$xcatname; - $::SCRIPTNAME=$scriptname; - } - return 0; + `logger -t xcat -p local4.info "$::sdate xcataixpost:name=$xcatname"`; + $scriptname = "/xcatpost/myxcatpost_" . $xcatname; + if (&getmypost($xcatname, $scriptname) == 0) { + $::XCATNAME = $xcatname; + $::SCRIPTNAME = $scriptname; + } + return 0; } - - # find out what interface we use to contact the server - my $NIP; - my $tcmd=qq~/bin/traceroute $servnode~; - if (&runcmd($tcmd) != 0) { - print "$::sdate xcataixpost: Could not run traceroute.\n"; - print $::LOG_FILE "$::sdate xcataixpost: Could not run traceroute\n"; - } else { - my @lines = ( split(/\n/, $::outref)); - foreach my $l (@lines) - { - if ($l =~ /^source should be/) { - my ($n1, $n2, $n3, $nip) = split(/\s+/, $l); - chomp $l; - $l =~ s/^\s+//; - $NIP=$nip; - } - } - } - if ($NIP) { - # traceroute gave us an ip - $xcatname=gethostbyaddr(inet_aton($NIP), AF_INET); - if ($xcatname =~ /\./) { - $xcatlong=$xcatname; - ($xcatshort = $xcatname) =~ s/\..*//; - } else { - $xcatlong=""; - $xcatshort=$xcatname; - } + # find out what interface we use to contact the server + my $NIP; + my $tcmd = qq~/bin/traceroute $servnode~; + if (&runcmd($tcmd) != 0) { + print "$::sdate xcataixpost: Could not run traceroute.\n"; + print $::LOG_FILE "$::sdate xcataixpost: Could not run traceroute\n"; + } else { + my @lines = (split(/\n/, $::outref)); + foreach my $l (@lines) + { + if ($l =~ /^source should be/) { + my ($n1, $n2, $n3, $nip) = split(/\s+/, $l); + chomp $l; + $l =~ s/^\s+//; + $NIP = $nip; + } + } + } - # try short name - if ($xcatshort) { - $scriptname = "/xcatpost/myxcatpost_" . $xcatshort; - if (&getmypost($xcatshort,$scriptname) == 0) { - $::XCATNAME=$xcatshort; - $::SCRIPTNAME=$scriptname; - return 0; - } - } + if ($NIP) { - # try long name - if any - if ($xcatlong) { - $scriptname = "/xcatpost/myxcatpost_" . $xcatlong; - if (&getmypost($xcatlong,$scriptname) == 0) { - $::XCATNAME=$xcatlong; - $::SCRIPTNAME=$scriptname; + # traceroute gave us an ip + $xcatname = gethostbyaddr(inet_aton($NIP), AF_INET); + if ($xcatname =~ /\./) { + $xcatlong = $xcatname; + ($xcatshort = $xcatname) =~ s/\..*//; + } else { + $xcatlong = ""; + $xcatshort = $xcatname; + } + + # try short name + if ($xcatshort) { + $scriptname = "/xcatpost/myxcatpost_" . $xcatshort; + if (&getmypost($xcatshort, $scriptname) == 0) { + $::XCATNAME = $xcatshort; + $::SCRIPTNAME = $scriptname; return 0; } } - } - # couldn't find NIP so try the primary hostname - $xcatname=hostname(); - if ($xcatname =~ /\./) { - $xcatlong=$xcatname; + # try long name - if any + if ($xcatlong) { + $scriptname = "/xcatpost/myxcatpost_" . $xcatlong; + if (&getmypost($xcatlong, $scriptname) == 0) { + $::XCATNAME = $xcatlong; + $::SCRIPTNAME = $scriptname; + return 0; + } + } + } + + # couldn't find NIP so try the primary hostname + $xcatname = hostname(); + if ($xcatname =~ /\./) { + $xcatlong = $xcatname; ($xcatshort = $xcatname) =~ s/\..*//; } else { - $xcatlong=""; - $xcatshort=$xcatname; + $xcatlong = ""; + $xcatshort = $xcatname; } # try short hostname if ($xcatshort) { $scriptname = "/xcatpost/myxcatpost_" . $xcatshort; - if (&getmypost($xcatshort,$scriptname) == 0) { - $::XCATNAME=$xcatshort; - $::SCRIPTNAME=$scriptname; + if (&getmypost($xcatshort, $scriptname) == 0) { + $::XCATNAME = $xcatshort; + $::SCRIPTNAME = $scriptname; return 0; } } - - # try long hostname - if any + + # try long hostname - if any if ($xcatlong) { $scriptname = "/xcatpost/myxcatpost_" . $xcatlong; - if (&getmypost($xcatlong,$scriptname) == 0) { - $::XCATNAME=$xcatlong; - $::SCRIPTNAME=$scriptname; + if (&getmypost($xcatlong, $scriptname) == 0) { + $::XCATNAME = $xcatlong; + $::SCRIPTNAME = $scriptname; return 0; } } - # if we get here we've exhaused all possibilities - `logger -t xcat -p local4.info "$::sdate xcataixpost: Could not get the xCAT post script for this node."`; + # if we get here we've exhaused all possibilities +`logger -t xcat -p local4.info "$::sdate xcataixpost: Could not get the xCAT post script for this node."`; print $::LOG_FILE "$::sdate xcataixpost: Could not get the xCAT post script for this node.\n"; - return 1; + return 1; } diff --git a/xCAT/postscripts/xcataixscript b/xCAT/postscripts/xcataixscript index 51951fe2b..976f937e3 100644 --- a/xCAT/postscripts/xcataixscript +++ b/xCAT/postscripts/xcataixscript @@ -9,12 +9,12 @@ # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use File::Path; use IO::Socket; -my $useSocketSSL=eval { require IO::Socket::SSL; }; +my $useSocketSSL = eval { require IO::Socket::SSL; }; use Getopt::Long; use XML::Simple; @@ -23,7 +23,7 @@ use XML::Simple; $logdir = "/var/log/xcat"; if (!-d $logdir) { - mkpath($logdir); + mkpath($logdir); } $::sdate = `/bin/date`; @@ -32,7 +32,7 @@ my $logfile = $logdir . "/xcat.log"; # this log should not contain much so it might be ok to let it grow? # at least we'll have the errors preserved -open(LOGFILE,">>",$logfile); +open(LOGFILE, ">>", $logfile); $::LOG_FILE = \*LOGFILE; # get hostname @@ -40,22 +40,23 @@ $::shorthost = `hostname -s`; chomp $::shorthost; my $servnode; + # get the name of my service node/NIM master from the /etc/niminfo file if (-f "/etc/niminfo") { - $cmd = "/bin/cat /etc/niminfo | /bin/grep 'NIM_MASTER_HOSTNAME'"; - &runcmd($cmd); - my $SNline = $::outref; - my $junk; - ($junk, $servnode) = split(/=/, $SNline); + $cmd = "/bin/cat /etc/niminfo | /bin/grep 'NIM_MASTER_HOSTNAME'"; + &runcmd($cmd); + my $SNline = $::outref; + my $junk; + ($junk, $servnode) = split(/=/, $SNline); - # save the servnode from niminfo in xcatinfo - my $xcatinfo="/etc/xcatinfo"; - open(XCATINFO,">",$xcatinfo); - print XCATINFO "XCATSERVER=$servnode\n"; - close(XCATINFO); + # save the servnode from niminfo in xcatinfo + my $xcatinfo = "/etc/xcatinfo"; + open(XCATINFO, ">", $xcatinfo); + print XCATINFO "XCATSERVER=$servnode\n"; + close(XCATINFO); } else { - print "$::sdate xcataixscript: Could not find /etc/niminfo file.\n"; - print $::LOG_FILE "$::sdate xcataixscript: Could not find /etc/niminfo file.\n"; + print "$::sdate xcataixscript: Could not find /etc/niminfo file.\n"; + print $::LOG_FILE "$::sdate xcataixscript: Could not find /etc/niminfo file.\n"; } $servnode =~ s/^\s*//; chomp $servnode; @@ -63,24 +64,24 @@ chomp $servnode; # create the xcatpost dir my $cmd = "/bin/mkdir -m 755 -p /xcatpost"; if (&runcmd($cmd) != 0) { - print "$::sdate xcataixscript: Could not make the /xcatpost directory.\n"; - print $::LOG_FILE "$::sdate xcataixscript: Could not make the /xcatpost directory.\n"; + print "$::sdate xcataixscript: Could not make the /xcatpost directory.\n"; + print $::LOG_FILE "$::sdate xcataixscript: Could not make the /xcatpost directory.\n"; } -# Set a temporary root password +# Set a temporary root password # - the user-provided root passwd will be set by xcataixpost my $pwcmd = qq~/bin/echo "root:xcatroot" | /bin/chpasswd -c >/dev/null 2>&1~; if (&runcmd($pwcmd) != 0) { - print "$::sdate xcataixscript: Could not set password.\n"; - print $::LOG_FILE "$::sdate xcataixscript: Could not set password.\n"; + print "$::sdate xcataixscript: Could not set password.\n"; + print $::LOG_FILE "$::sdate xcataixscript: Could not set password.\n"; } # need fix to support INSTALLDIR !!!!! -# socket doesn't work at this point of install so need another +# socket doesn't work at this point of install so need another # way to get INSTALLDIR value!!! my $installdir; if (!$installdir) { - $installdir="/install"; + $installdir = "/install"; } # get the contents of the $installdir/postscripts dir on the server @@ -100,12 +101,13 @@ if (&runcmd($mcmd) != 0) { } my $cpcmd; -if ((@ARGV==0) || ($ARGV[0] != 2)) { +if ((@ARGV == 0) || ($ARGV[0] != 2)) { $cpcmd = "/bin/cp -r /xcatmnt/* /xcatpost >/dev/null 2>&1"; } else { + # when argv[1]=2, there is only one postscript file, # user wants only download it to save time - $cpcmd= "/bin/cp /xcatmnt/$ARGV[1] /xcatpost >/dev/null 2>&1"; + $cpcmd = "/bin/cp /xcatmnt/$ARGV[1] /xcatpost >/dev/null 2>&1"; } if (&runcmd($cpcmd) != 0) { @@ -130,12 +132,13 @@ if (&runcmd($ucmd) != 0) { # see if it is already there my $lsicmd = "/usr/sbin/lsitab xcat > /dev/null 2>&1"; if (&runcmd($lsicmd) != 0) { - # ok - create the entry - my $mkitab_cmd = '/usr/sbin/mkitab "xcat:2:wait:/xcatpost/xcataixpost > /dev/console 2>&1"'; - if (&runcmd($mkitab_cmd) != 0) { - print "$::sdate xcataixscript: Could not add xcataixpost to /etc/inittab.\n"; - print $::LOG_FILE "$::sdate xcataixscript: Could not add xcataixpost to /etc/inittab.\n"; - } + + # ok - create the entry + my $mkitab_cmd = '/usr/sbin/mkitab "xcat:2:wait:/xcatpost/xcataixpost > /dev/console 2>&1"'; + if (&runcmd($mkitab_cmd) != 0) { + print "$::sdate xcataixscript: Could not add xcataixpost to /etc/inittab.\n"; + print $::LOG_FILE "$::sdate xcataixscript: Could not add xcataixpost to /etc/inittab.\n"; + } } close($::LOG_FILE); @@ -150,17 +153,17 @@ exit 0; sub runcmd { my ($cmd) = @_; - my $rc=0; - $cmd .= ' 2>&1' ; + my $rc = 0; + $cmd .= ' 2>&1'; $::outref = `$cmd`; if ($?) { $rc = $? >> 8; if ($rc > 0) { - print "$::sdate xcataixscript: $::outref\n"; - print $::LOG_FILE "$::sdate xcataixscript: $::outref\n"; + print "$::sdate xcataixscript: $::outref\n"; + print $::LOG_FILE "$::sdate xcataixscript: $::outref\n"; } } - return $rc; + return $rc; }