2008-09-19 15:34:08 +00:00
#!/usr/bin/env perl
# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html
use strict;
use warnings;
use Carp qw(cluck confess);
BEGIN
{
$::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat';
2011-03-22 15:06:13 +00:00
# Required when using DB2 as the xCAT database:
$ENV{'DB2INSTANCE'} = 'xcatdb';
$ENV{'EXTSHM'} = 'ON';
2011-12-04 13:04:58 +00:00
if (defined $ENV{ENABLE_TRACE_CODE}) {
use lib "$ENV{'XCATROOT'}/lib/perl";
use lib "/opt/xcat/lib/perl";
2014-01-02 07:02:24 +00:00
require xCAT::Enabletrace;
xCAT::Enabletrace->loadtrace();
2011-12-04 13:04:58 +00:00
}
2008-09-19 15:34:08 +00:00
}
2009-07-28 17:29:16 +00:00
2013-08-16 11:05:32 +00:00
my $sslctl;
my $udpctl;
2009-07-28 17:29:16 +00:00
# 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) {
2012-08-08 17:48:03 +00:00
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));
2009-07-28 17:29:16 +00:00
}
2008-09-19 15:34:08 +00:00
use lib "$::XCATROOT/lib/perl";
2013-04-04 20:11:05 +00:00
use Storable qw(freeze thaw store_fd fd_retrieve);
2008-09-19 15:34:08 +00:00
use xCAT::Utils;
2012-08-09 03:58:34 +00:00
use xCAT::TableUtils;
use xCAT::NetworkUtils;
2008-09-19 15:34:08 +00:00
use xCAT::MsgUtils;
2012-06-21 13:00:38 +00:00
use xCAT::xcatd;
2013-03-29 11:38:14 +00:00
my $IOCompress =1;
my $os = xCAT::Utils->osver();
my $arch = `uname -p`;
# These do not have the IO::Uncompress rpm available
if (($^O =~ /^aix/i) || ($os =~ /^sle[sc]10/) || (($os =~ /^rh.*5$/) && ($arch =~ /ppc64/))){
$IOCompress =0;
}
if ($IOCompress == 1 ) {
eval {require IO::Uncompress::Gunzip;}
}
2008-09-19 15:34:08 +00:00
use File::Path;
use Time::HiRes qw(sleep);
use Thread qw(yield);
2012-04-29 00:13:41 +00:00
use Fcntl qw/:DEFAULT :flock/;
2008-09-19 15:34:08 +00:00
use xCAT::Client qw(submit_request);
my $clientselect = new IO::Select;
my $sslclients = 0; #THROTTLE
2009-09-24 21:06:51 +00:00
my $maxsslclients = 64; #default
2013-08-16 11:05:32 +00:00
my $batchclients = 50;
2011-06-15 15:09:39 +00:00
my @deferredmsgargs; # hold argumentlist for MsgUtils call until after fork
#parallelizing logging overhead with real work
2008-09-19 15:34:08 +00:00
sub xexit {
while (wait() > 0) {
yield;
}
exit @_;
}
my $dispatch_children=0;
my %dispatched_children=();
my $plugin_numchildren=0;
my %plugin_children;
my $inet6support;
2009-06-02 11:38:23 +00:00
if ($^O =~ /^aix/i) { # disable AIX IPV6 TODO
2009-06-01 20:39:29 +00:00
$inet6support = 0;
2009-06-02 18:40:06 +00:00
} else {
$inet6support=eval { require Socket6 };
2009-06-01 20:39:29 +00:00
}
2008-09-19 15:34:08 +00:00
if ($inet6support) {
$inet6support = eval { require IO::Socket::INET6 };
}
if ($inet6support) {
2009-05-29 13:53:49 +00:00
$inet6support = eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet6'); 1; };
}
2012-12-11 11:11:00 +00:00
2012-12-12 02:52:42 +00:00
if ($^O =~ /^linux/i) {
# Is IPv6 enabled on the MN or SN at all?
my $ipv6enabled = `ip addr | grep inet6`;
if (!$ipv6enabled) {
$inet6support = 0;
}
2012-12-11 11:11:00 +00:00
}
2008-09-19 15:34:08 +00:00
unless ($inet6support) {
eval { require Socket };
eval { require IO::Socket::INET };
2009-11-21 17:44:46 +00:00
eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet4'); };
2008-09-19 15:34:08 +00:00
}
my $dispatch_requests = 1; # govern whether commands are dispatchable
use IO::Socket;
2011-06-08 18:46:01 +00:00
#use IO::Handle;
2008-09-19 15:34:08 +00:00
use IO::Select;
use XML::Simple;
2009-07-16 14:46:05 +00:00
$XML::Simple::PREFERRED_PARSER='XML::Parser';
2008-09-19 15:34:08 +00:00
use xCAT::Table;
2009-08-06 12:43:27 +00:00
my $dbmaster;
2009-01-09 22:25:35 +00:00
use xCAT::ExtTab;
2011-12-04 13:04:58 +00:00
use Data::Dumper;
2008-09-19 15:34:08 +00:00
use Getopt::Long;
use Sys::Syslog qw(:DEFAULT setlogsock);
openlog("xcatd",,"local4");
2014-06-11 17:20:42 +00:00
# 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 qw(Sys::Syslog);
2008-09-19 15:34:08 +00:00
setlogsock(["tcp","unix","stream"]);
2014-06-11 17:20:42 +00:00
use warnings qw(Sys::Syslog);
2008-09-19 15:34:08 +00:00
use xCAT::NotifHandler;
use xCAT_monitoring::monitorctrl;
Getopt::Long::Configure("bundling");
Getopt::Long::Configure("pass_through");
use Storable qw(dclone);
2012-04-29 00:13:41 +00:00
use POSIX qw(WNOHANG setsid :errno_h);
2008-09-19 15:34:08 +00:00
my $pidfile;
my $foreground;
GetOptions(
'pidfile|p=s' => \$pidfile,
'foreground|f' => \$foreground
);
2013-01-14 13:12:02 +00:00
unless ($pidfile) {
$pidfile = "/var/run/xcatd.pid";
}
2008-09-19 15:34:08 +00:00
#start syslog if it is not up
if (xCAT::Utils->isLinux()) {
my $init_file="/etc/init.d/syslog";
2013-08-16 11:05:32 +00:00
if ((-f "/etc/fedora-release") || (-f "/etc/redhat-release") || (-f "/etc/lsb-release")){
2008-09-19 15:34:08 +00:00
$init_file="/etc/init.d/rsyslog";
}
2009-10-06 16:46:18 +00:00
if ( -x $init_file ) {
my $result=`$init_file status 2>&1`;
if ($result !~ /running/i) {
`$init_file start`;
}
2008-09-19 15:34:08 +00:00
}
} else {
my $result=`lssrc -s syslogd 2>&1`;
if ($result !~ /active/i) {
`startsrc -s syslogd`;
}
}
my $quit = 0;
my $port;
my $sport;
my $domain;
my $xcatdir;
2009-09-27 03:03:17 +00:00
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
2010-10-04 17:06:20 +00:00
while (!($sitetab=xCAT::Table->new('site')) && $retries < 200)
2009-09-27 03:03:17 +00:00
{
print ("Can not open basic site table for configuration, waiting the database to be initialized.\n");
sleep 1;
$retries++;
}
2008-09-19 15:34:08 +00:00
unless ($sitetab) {
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S","ERROR: Unable to open basic site table for configuration");
die;
2008-09-19 15:34:08 +00:00
}
my ($tmp) = $sitetab->getAttribs({'key'=>'xcatdport'},'value');
unless ($tmp) {
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S","ERROR:Need xcatdport defined in site table, try chtab key=xcatdport site.value=3001");
die;
2008-09-19 15:34:08 +00:00
}
$port = $tmp->{value};
2012-06-21 17:27:22 +00:00
($tmp) = $sitetab->getAttribs({'key'=>'xcatiport'},'value');
2012-06-21 17:27:15 +00:00
if ($tmp) {
$sport = $tmp->{value};
}
2012-02-19 03:16:51 +00:00
($tmp) = $sitetab->getAttribs({'key'=>'xcatmaxconnections'},'value');
if ($tmp and $tmp->{value}) { $maxsslclients = $tmp->{value}; }
2013-08-16 11:05:32 +00:00
($tmp) = $sitetab->getAttribs({'key'=>'xcatmaxbatchconnections'},'value');
if ($tmp and $tmp->{value}) { $batchclients = $tmp->{value}; }
2008-09-19 15:34:08 +00:00
my $plugins_dir=$::XCATROOT.'/lib/perl/xCAT_plugin';
($tmp) = $sitetab->getAttribs({'key'=>'xcatconfdir'},'value');
$xcatdir = (($tmp and $tmp->{value}) ? $tmp->{value} : "/etc/xcat");
$sitetab->close;
my $progname;
2012-05-02 19:57:58 +00:00
my $pipeexpected;
2008-09-19 15:34:08 +00:00
$SIG{PIPE} = sub {
2012-05-02 19:57:58 +00:00
if ($pipeexpected) { return; }
2010-12-20 09:30:09 +00:00
confess "SIGPIPE $$progname encountered a broken pipe (probably Ctrl-C by client)";
2008-09-19 15:34:08 +00:00
};
$progname = \$0;
2009-01-09 22:25:35 +00:00
2010-09-01 14:10:18 +00:00
#create and update any xCAt tables
2009-01-09 22:25:35 +00:00
#create the user defined external database tables if they do not exist.
#update the tables if there are schema changes.
2010-08-26 13:53:46 +00:00
# runsqlcmd runs sql scripts provided by the user in
# /opt/xcat/lib/perl/xCAT_schema
2009-01-09 22:25:35 +00:00
if (xCAT::Utils->isMN()) {
2010-09-01 14:10:18 +00:00
# update schema for xCAT tables
2010-09-15 12:42:45 +00:00
my @table;
push @table,xCAT::Table->getTableList();
foreach my $tablename (@table) {
2010-09-01 14:10:18 +00:00
my $tablelisttab=xCAT::Table->new($tablename,-create=>1);
my $rc= $tablelisttab->updateschema();
$tablelisttab->close;
}
# update schema for user tables
2009-01-09 22:25:35 +00:00
xCAT::ExtTab->updateTables();
2010-09-01 14:10:18 +00:00
# run any sql commands
2010-08-26 13:53:46 +00:00
`$::XCATROOT/sbin/runsqlcmd`;
2009-01-09 22:25:35 +00:00
}
2012-10-02 17:52:18 +00:00
my $startupchild;
my $startupparent;
2008-09-19 15:34:08 +00:00
sub daemonize {
chdir('/');
umask 0022;
my $pid;
2012-10-02 17:52:18 +00:00
socketpair($startupparent,$startupchild,AF_UNIX,SOCK_STREAM,PF_UNSPEC);
2009-12-11 08:28:47 +00:00
if (! defined($pid = xCAT::Utils->xfork)) {
xCAT::MsgUtils->message("S","Can't fork: $!");
die;
}
2008-09-19 15:34:08 +00:00
if ($pid) {
2012-10-02 17:52:18 +00:00
close($startupparent); # the launcher only wants to examing startupchild
2008-09-19 15:34:08 +00:00
if ($pidfile) {
open(PFILE, '>', $pidfile);
print PFILE $pid;
close (PFILE);
} else {
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S","xCATd starting as PID $pid");
2008-09-19 15:34:08 +00:00
}
2012-10-02 17:52:18 +00:00
my $result=<$startupchild>;
chomp($result);
unless ($result) { exit (1); }
if ($result ne "SUCCESS") {
xCAT::MsgUtils->message("S","xCATd failed to start: $result");
exit(1);
}
2008-09-19 15:34:08 +00:00
exit;
}
2012-10-02 17:52:18 +00:00
close($startupchild); # only want child to report up to parent...
2009-12-11 08:28:47 +00:00
if (! open STDIN, '/dev/null') {
2012-10-02 17:52:18 +00:00
print $startupparent "Can't read /dev/null: $!\n";
2009-12-11 08:28:47 +00:00
die;
}
2008-09-19 15:34:08 +00:00
open STDOUT, '>/dev/null';
open STDERR, '>/dev/null';
$0='xcatd';
$progname = \$0;
2009-12-11 08:28:47 +00:00
if (! setsid) {
xCAT::MsgUtils->message("S","Can't start new session");
2012-10-02 17:52:18 +00:00
print $startupparent "Can't start new session\n";
2009-12-11 08:28:47 +00:00
die;
}
2008-09-19 15:34:08 +00:00
}
my %cmd_handlers;
sub do_installm_service {
2012-06-21 17:27:15 +00:00
unless ($sport) { return; }
2008-09-19 15:34:08 +00:00
#This function servers as a handler for messages from installing nodes
my $socket;
2010-07-08 20:49:12 +00:00
my $installpidfile;
my $retry=1;
$SIG{USR2} = sub {
2011-08-25 17:07:23 +00:00
if ($socket) { #do not mess with pid file except when we still have the socket.
2012-09-20 14:30:14 +00:00
unlink("/var/run/xcat/installservice.pid"); close($socket); $quit=1;
2010-07-08 20:49:12 +00:00
xCAT::MsgUtils->message("S","xcatd install monitor $$ quiescing");
2011-08-25 17:07:23 +00:00
}
};
if ($inet6support) {
$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);
}
2012-09-20 14:30:14 +00:00
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
2011-08-25 17:07:23 +00:00
#TODO: lsof or similar may be a more accurate measure
2010-07-08 20:49:12 +00:00
my $pid = <$installpidfile>;
if ($pid) {
$retry=100; #grace period for old instance to get out of the way, 5 seconds
kill 12,$pid;
yield(); # let peer have a shot at closure
}
close($installpidfile);
}
while (not $socket and $retry) {
$retry--;
2008-09-19 15:34:08 +00:00
if ($inet6support) {
$socket = IO::Socket::INET6->new(LocalPort=>$sport,
Proto => 'tcp',
ReuseAddr => 1,
2009-08-22 13:18:55 +00:00
Listen => 8192);
2008-09-19 15:34:08 +00:00
} else {
$socket = IO::Socket::INET->new(LocalPort=>$sport,
Proto => 'tcp',
ReuseAddr => 1,
2009-08-22 13:18:55 +00:00
Listen => 8192);
2008-09-19 15:34:08 +00:00
}
2010-07-08 20:49:12 +00:00
sleep 0.05; #up to 50 ms outage possible
}
2008-09-19 15:34:08 +00:00
unless ($socket) {
xCAT::MsgUtils->message("S","xcatd unable to open install monitor services on $sport");
die;
}
2011-08-25 17:07:23 +00:00
#we have the socket, now we claim the pid file as our own
2012-09-20 14:30:14 +00:00
open($installpidfile,">","/var/run/xcat/installservice.pid"); #if here, everyone else has unlinked installservicepid or doesn't care
2011-08-25 17:07:23 +00:00
print $installpidfile $$;
close($installpidfile);
2008-09-19 15:34:08 +00:00
until ($quit) {
2009-12-11 08:28:47 +00:00
$SIG{ALRM} = sub { xCAT::MsgUtils->message("S","XCATTIMEOUT"); die; };
2008-09-19 15:34:08 +00:00
my $conn;
next unless $conn = $socket->accept;
2014-03-31 21:48:58 +00:00
my $client_name;
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); }
} else {
($client_name,$client_aliases) = gethostbyaddr($conn->peeraddr,AF_INET);
}
$clients[0] = $client_name;
if ($client_aliases) {
push @clients, split(/\s+/,$client_aliases);
}
2008-09-19 15:34:08 +00:00
2012-08-16 13:54:27 +00:00
my $validclient=0;
my $node;
my $domain;
2012-11-02 13:57:28 +00:00
2012-08-16 13:54:27 +00:00
foreach my $client (@clients) {
2014-03-31 21:48:58 +00:00
my @ndn = ($client);
my $nd = xCAT::NetworkUtils->getNodeDomains(\@ndn);
my %nodedomains = %{$nd};
$domain = $nodedomains{$client};
$client =~ s/\..*//;
if ($domain) {
$client =~ s/\.$domain//;
} else {
2012-08-16 13:54:27 +00:00
$client =~ s/\..*//;
2014-03-31 21:48:58 +00:00
}
#ensure this is coming from a node IP at least
($node) = noderange($client);
if ($node) { #Means the source isn't valid
$validclient=1;
last;
}
2012-08-16 13:54:27 +00:00
}
2008-09-19 15:34:08 +00:00
unless ($validclient) {
close($conn);
next;
}
2012-08-14 11:48:59 +00:00
my $tftpdir = xCAT::TableUtils->getTftpDir();
2008-09-19 15:34:08 +00:00
eval {
alarm(2);
print $conn "ready\n";
while (my $text = <$conn>) {
alarm(0);
print $conn "done\n";
$text =~ s/\r//g;
if ($text =~ /next/) {
my %request = (
command => [ 'nodeset' ],
node => [ $node ],
arg => [ 'next' ],
);
#node should be blocked, race condition may occur otherwise
#my $pid=xCAT::Utils->xfork();
2008-09-25 03:04:56 +00:00
#unless ($pid) { #fork off the nodeset and potential slowness
plugin_command(\%request,undef,\&build_response);
# exit(0);
#}
2009-09-15 17:12:51 +00:00
close($conn);
2008-09-29 16:33:21 +00:00
} elsif ($text =~ /installstatus/) {
2012-12-03 18:53:59 +00:00
my @tmpa=split(' ', $text);
2008-09-29 16:33:21 +00:00
for (my $i = 1; $i <= @tmpa-1; $i++) {
my $newstat=$tmpa[$i];
my %request = (
command => [ 'updatenodestat' ],
2012-10-11 08:48:20 +00:00
node => [ $node ],
arg => [ "$newstat" ],
);
#node should be blocked, race condition may occur otherwise
2008-09-29 16:33:21 +00:00
#my $pid=xCAT::Utils->xfork();
#unless ($pid) { #fork off the nodeset and potential slowness
plugin_command(\%request,undef,\&build_response);
# exit(0);
#}
}
2008-09-25 03:04:56 +00:00
close($conn);
2008-09-19 15:34:08 +00:00
} 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/*");
close($conn);
} elsif ($text =~ /locktftpdir/) {
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}}) {
print $conn $_;
}
print $conn "#END OF SCRIPT\n";
close($conn);
2009-06-04 15:33:44 +00:00
} elsif ($text =~ /^syncfiles/) {
plugin_command({command=>['syncfiles'],_xcat_clienthost=>[$node]},undef,\&build_response);
print $conn "syncfiles done\n";
close($conn);
2008-09-19 15:34:08 +00:00
} elsif ($text =~ /^setiscsiparms/) {
$text =~ s/^setiscsiparms\s+//;
my $kname;
my $iname;
my $kcmdline;
($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'});
$bptab->close;
$chaintab->close;
undef $bptab;
undef $chaintab;
my %request = (
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);
xexit(0);
}
2010-11-24 07:07:23 +00:00
} elsif ($text =~ /hpcbootstatus/) {
$text =~ s/hpcbootstatus //;
chomp $text;
my %request = (
command => [ 'updatenodeappstat' ],
node => [ $node ],
arg => [ "$text" ],
);
plugin_command(\%request,undef,\&build_response);
close($conn);
2011-08-26 03:43:35 +00:00
} 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/mv /tmp/$text.nimtmp $myfile`;
close($conn);
}
2008-09-19 15:34:08 +00:00
alarm(2);
}
alarm(0);
};
if ($@) {
if ($@ =~ /XCATTIMEOUT/) {
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: ".$@);
}
}
}
2012-09-20 14:30:14 +00:00
if (open($installpidfile,"<","/var/run/xcat/installservice.pid")) {
2010-07-08 20:49:12 +00:00
my $pid = <$installpidfile>;
if ($pid == $$) { #if our pid, unlink the file, otherwise, we managed to see the pid after someone else created it
2012-09-20 14:30:14 +00:00
unlink("/var/run/xcat/installservice.pid");
2010-07-08 20:49:12 +00:00
}
close($installpidfile);
}
2008-09-19 15:34:08 +00:00
}
2013-08-16 11:05:32 +00:00
sub update_udpcontext_from_sslctl {
my %args = @_;
my $udpcontext = $args{udpcontext};
my $select = $args{select};
my $msg;
eval { $msg = fd_retrieve($sslctl); };
if ($msg) {
#remember new count and, if new connection and we have a fudge factor, decrese fudge factor optimisticly assuming it's the right one
$udpcontext->{sslclientcount} = $msg->{sslclientcount};
if ($udpcontext->{clientfudge} and $msg->{clientcountchange} > 0) { $udpcontext->{clientfudge} -= $msg->{clientcountchange}; }
} else {
$select->remove($sslctl); close($sslctl); #something went horribly wrong
}
}
sub grant_tcrequests {
my $requestors = shift;
my $udpcontext = shift;
my $availableslots = $batchclients;
$availableslots -= $udpcontext->{clientfudge}; #value that forecasts the pressure
$availableslots -= $udpcontext->{sslclientcount}; #subtract all currently really active sessions
my $oldtime = time()-180; #drop requests older than three minutes if still around
foreach my $rkey (keys %{$requestors}) {
if ($requestors->{$rkey}->{timestamp} < $oldtime) { delete $requestors->{$rkey}; next; }
unless ($availableslots > 0) { next; } # no slots, ignore requests for now
$udpcontext->{clientfudge}+=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
}
}
2008-09-19 15:34:08 +00:00
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
$dispatch_requests=0;
2013-08-16 11:05:32 +00:00
my $udpcontext;
$udpcontext->{clientfudge}=0;
$udpcontext->{sslclientcount}=0;
2010-07-08 20:49:12 +00:00
my $udppidfile;
my $retry=1;
my $socket;
$SIG{USR2} = sub {
2011-08-25 17:07:23 +00:00
if ($socket) {
#only clear out pid file when we still have socket.
2012-09-20 14:30:14 +00:00
unlink("/var/run/xcat/udpservice.pid"); close($socket); $quit=1; $socket=0;
2011-08-25 17:07:23 +00:00
xCAT::MsgUtils->message("S","xcatd udp service $$ quiescing");
2011-08-30 15:10:21 +00:00
}
2011-08-25 17:07:23 +00:00
};
2013-08-16 11:05:32 +00:00
if ($inet6support) {
2011-08-25 17:07:23 +00:00
$socket = IO::Socket::INET6->new(LocalPort => $port,
Proto => 'udp',
2013-08-16 11:05:32 +00:00
);
2011-08-25 17:07:23 +00:00
} else {
$socket = IO::Socket::INET->new(LocalPort => $port,
Proto => 'udp',
Domain => AF_INET);
}
2012-09-20 14:30:14 +00:00
if (not $socket and open($udppidfile,"<","/var/run/xcat/udpservice.pid")) {
2010-07-08 20:49:12 +00:00
my $pid = <$udppidfile>;
if ($pid) {
$retry=100; #grace period for old instance to get out of the way, 5 seconds
kill 12,$pid;
yield(); # let peer have a shot at closure
}
close($udppidfile);
}
2008-09-19 15:34:08 +00:00
my $select = new IO::Select;
2010-07-08 20:49:12 +00:00
while (not $socket and $retry) {
2013-08-16 11:05:32 +00:00
if ($inet6support) {
2008-09-19 15:34:08 +00:00
$socket = IO::Socket::INET6->new(LocalPort => $port,
Proto => 'udp',
2013-08-16 11:05:32 +00:00
);
2008-09-19 15:34:08 +00:00
} else {
$socket = IO::Socket::INET->new(LocalPort => $port,
Proto => 'udp',
Domain => AF_INET);
}
2010-07-08 20:49:12 +00:00
sleep 0.05;
}
2008-09-19 15:34:08 +00:00
openlog("xCAT UDP",'','local4');
unless ($socket) {
xCAT::MsgUtils->message("S","xCAT UDP service unable to open port $port: $!");
closelog();
die "Unable to start UDP on $port";
}
2011-08-25 17:07:23 +00:00
#only take udp pid if we get the socket
2012-09-20 14:30:14 +00:00
open($udppidfile,">","/var/run/xcat/udpservice.pid"); #if here, everyone else has unlinked udpservicepid or doesn't care
2011-08-25 17:07:23 +00:00
print $udppidfile $$;
close($udppidfile);
2008-09-19 15:34:08 +00:00
$select->add($socket);
2013-08-16 11:05:32 +00:00
$udpcontext->{socket} = $socket;
$select->add($sslctl);
2008-09-19 15:34:08 +00:00
my $data;
my $part;
my $sport;
my $client;
my $peerhost;
my %packets;
my $actualpid=$$;
until ($quit) {
eval {
2013-08-16 11:05:32 +00:00
my $tcclients; # hash reference to store traffic control requests
2008-09-19 15:34:08 +00:00
while (1) {
2009-05-06 20:07:05 +00:00
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");
exit(1);
}
2013-02-18 20:27:20 +00:00
until ($select->can_read(5)) { #Wait for data
if ($quit) { last; };
populate_site_hash();
yield;
}
2013-08-16 11:05:32 +00:00
my @hdls;
while (@hdls = $select->can_read(0)) { #Pull all buffer data that can be pulled
my $hdl;
foreach $hdl (@hdls) {
if ($hdl == $socket) {
2008-09-19 15:34:08 +00:00
$part = $socket->recv($data,1500);
2013-08-16 11:05:32 +00:00
$packets{$part} = [$part,$data];
} elsif ($hdl == $sslctl) {
update_udpcontext_from_sslctl(udpcontext=>$udpcontext,select=>$select);
} else {
print "Something is wrong in udp process (search xcatd for this string)\n";
}
}
2008-09-19 15:34:08 +00:00
}
foreach my $pkey (keys %packets) {
2013-08-16 11:05:32 +00:00
my $saddr = $packets{$pkey}->[0];
my $clientn;
my $clientip;
if ($inet6support) {
($client,$sport) = Socket6::getnameinfo($saddr);
($clientip,$sport) = Socket6::getnameinfo($saddr,Socket6::NI_NUMERICHOST());
if ($clientip =~ /::ffff:.*\..*\./) {
$clientip =~ s/^::ffff://;
}
if ($client =~ /::ffff:.*\..*\./) {
$client =~ s/^::ffff://;
}
} else {
($sport,$clientn) = sockaddr_in($saddr);
$clientip = inet_ntoa($clientn);
$client=gethostbyaddr($clientn,AF_INET);
}
2008-09-19 15:34:08 +00:00
$data=$packets{$pkey}->[1];
2013-03-29 11:38:14 +00:00
if ($data =~ /^\037\213/) { #per rfc 1952, these two bytes are gzip, and they are invalid for
2013-01-25 14:37:17 +00:00
#xcatrequest xml, so go ahead and decompress it
2013-03-29 11:38:14 +00:00
my $bigdata;
IO::Uncompress::Gunzip::gunzip(\$data,\$bigdata);
$data = $bigdata
}
2013-08-16 11:05:32 +00:00
if ($data =~ /^<xcat/) { #xml format
2008-09-19 15:34:08 +00:00
my $req = eval { XMLin($data, SuppressEmpty=>undef,ForceArray=>1) };
2013-08-16 11:05:32 +00:00
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;
2008-09-19 15:34:08 +00:00
$req->{'_xcat_clientport'}=$sport;
2013-08-16 11:05:32 +00:00
if (defined($cmd_handlers{"findme"}) and xCAT::NetworkUtils->nodeonmynet($clientip)) { #only discover from ips that appear to be on a managed network
2012-02-06 22:28:07 +00:00
xCAT::MsgUtils->message("S","xcatd: Processing discovery request from ".$req->{'_xcat_clientip'});
2008-09-19 15:34:08 +00:00
$req->{cacheonly}->[0] = 1;
plugin_command($req,undef,\&build_response);
if ($req->{cacheonly}->[0]) {
delete $req->{cacheonly};
plugin_command($req,undef,\&build_response);
}
2012-02-05 17:37:47 +00:00
} else {
2013-08-16 11:05:32 +00:00
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");
2012-02-05 17:37:47 +00:00
}
2008-09-19 15:34:08 +00:00
}
2013-08-16 11:05:32 +00:00
} else { # for *now*, we'll do a tiny YAML subset
if ($data =~ /^resourcerequest: xcatd$/) {
$tcclients->{$pkey}={ sockaddr=>$packets{$pkey}->[0], timestamp=>time() }
}
} # JSON maybe one day if important
2008-09-19 15:34:08 +00:00
if ($quit) { last; }
2013-08-16 11:05:32 +00:00
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];
} elsif ($hdl == $sslctl) {
update_udpcontext_from_sslctl(udpcontext=>$udpcontext,select=>$select);
}
}
2008-09-19 15:34:08 +00:00
}
#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; }
2013-08-16 11:05:32 +00:00
grant_tcrequests($tcclients,$udpcontext);
2008-09-19 15:34:08 +00:00
}
};
if ($@) {
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.
2009-05-06 20:07:05 +00:00
xCAT::MsgUtils->message("S","xcatd: Something ludicrous happpened, bailing to avoid fork bomb, double check perl XS modules like 'net-snmp-perl'");
2008-09-19 15:34:08 +00:00
exit 1;
}
}
2012-09-20 14:30:14 +00:00
if (open($udppidfile,"<","/var/run/xcat/udpservice.pid")) {
2010-07-08 20:49:12 +00:00
my $pid = <$udppidfile>;
if ($pid == $$) { #if our pid, unlink the file, otherwise, we managed to see the pid after someone else created it
2012-09-20 14:30:14 +00:00
unlink("/var/run/xcat/udpservice.pid");
2010-07-08 20:49:12 +00:00
}
close($udppidfile);
}
2008-09-19 15:34:08 +00:00
}
sub scan_plugins {
2012-02-18 19:34:57 +00:00
my $serialdest = shift;
2008-09-19 15:34:08 +00:00
my @plugins=glob($plugins_dir."/*.pm");
foreach (@plugins) {
/.*\/([^\/]*).pm$/;
my $modname = $1;
2009-11-18 14:51:19 +00:00
unless ( eval { require "$_" }) {
xCAT::MsgUtils->message("S","Error loading module ".$_." ...skipping");
next;
}
2008-09-19 15:34:08 +00:00
no strict 'refs';
2012-03-01 16:21:27 +00:00
my $cmd_adds;
eval {
$cmd_adds=${"xCAT_plugin::".$modname."::"}{handled_commands}->();
};
if ($@) {
xCAT::MsgUtils->message("S","Error registering module ".$_." ...skipping");
next;
}
2008-09-19 15:34:08 +00:00
foreach (keys %$cmd_adds) {
my $value = $_;
2010-08-25 17:46:09 +00:00
my @modulehandlerinfos;
if (ref $cmd_adds->{$_}) {
2010-08-25 18:13:20 +00:00
@modulehandlerinfos=@{$cmd_adds->{$value}};
2008-09-19 15:34:08 +00:00
} else {
2010-08-25 18:13:20 +00:00
@modulehandlerinfos=($cmd_adds->{$value});
2010-08-25 17:46:09 +00:00
}
2010-08-25 18:13:20 +00:00
unless (defined($cmd_handlers{$value})) {
$cmd_handlers{$value} = [ ];
2010-08-25 17:46:09 +00:00
}
# Add every plugin registration to cmd_handlers
foreach (@modulehandlerinfos) {
2010-08-25 18:13:20 +00:00
push @{$cmd_handlers{$value}},[$modname,$_];
2008-09-19 15:34:08 +00:00
}
}
}
2009-03-28 05:57:08 +00:00
foreach (@plugins) {
2009-03-28 06:17:42 +00:00
no strict 'refs';
2009-03-28 05:57:08 +00:00
/.*\/([^\/]*).pm$/;
my $modname = $1;
unless (defined(${"xCAT_plugin::".$modname."::"}{init_plugin})) {
next;
}
2009-03-28 06:17:42 +00:00
${"xCAT_plugin::".$modname."::"}{init_plugin}->(\&do_request);
2009-03-28 05:57:08 +00:00
}
2013-04-04 20:11:05 +00:00
if ($serialdest) { store_fd(\%cmd_handlers,$serialdest); }; #print $serialdest freeze(\%cmd_handlers); };
2008-09-19 15:34:08 +00:00
}
2012-02-18 19:34:57 +00:00
my $pid_init;
my $readpipe;
my $writepipe;
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..
close($writepipe);
2013-04-04 20:11:05 +00:00
%cmd_handlers = %{fd_retrieve($readpipe)};
2012-02-18 19:34:57 +00:00
} else {
2013-08-16 11:05:32 +00:00
$$progname = "xcatd: plugin initialization";
2012-02-18 19:34:57 +00:00
scan_plugins($writepipe);
exit(0);
}
} else {
print "Unable to branch the initialization portion, will use more memory\n";
scan_plugins();
}
2009-09-23 14:09:12 +00:00
unless (xCAT::Utils->isLinux()) { # messes up the output of the service cmd on linux
eval {
xCAT::MsgUtils->message("S","xCATd: service starting");
};
}
2008-09-19 15:34:08 +00:00
if ($@) {
print "ERROR: $@";
xexit;
}
unless ($foreground) {
daemonize;
}
2009-08-06 12:43:27 +00:00
$dbmaster=xCAT::Table::init_dbworker;
2008-09-19 15:34:08 +00:00
my $CHILDPID=0; #Global for reapers
2010-07-08 20:49:12 +00:00
my %immediatechildren;
2008-09-19 15:34:08 +00:00
sub generic_reaper {
2013-06-10 14:43:50 +00:00
local($!);
2010-07-08 20:49:12 +00:00
while (($CHILDPID=waitpid(-1,WNOHANG)) > 0) {
2008-09-19 15:34:08 +00:00
yield;
}
$SIG{CHLD} = \&generic_reaper;
}
sub ssl_reaper {
2013-06-10 14:43:50 +00:00
local($!);
2013-08-16 11:05:32 +00:00
my $numdone = 0;
2010-07-08 20:49:12 +00:00
while (($CHILDPID=waitpid(-1,WNOHANG)) > 0) {
if ($immediatechildren{$CHILDPID}) {
delete $immediatechildren{$CHILDPID};
2013-08-16 11:05:32 +00:00
$sslclients--;
$numdone--;
2010-07-08 20:49:12 +00:00
}
2008-09-19 15:34:08 +00:00
}
2013-08-16 11:05:32 +00:00
store_fd({clientcountchange=>$numdone,sslclientcount=>$sslclients},$udpctl); #notify udp service of how many clients are active
2008-09-19 15:34:08 +00:00
$SIG{CHLD} = \&ssl_reaper;
}
sub dispatch_reaper {
2013-08-16 11:05:32 +00:00
local($!);
2008-09-19 15:34:08 +00:00
while (($CHILDPID =waitpid(-1, WNOHANG)) > 0) {
if ($dispatched_children{$CHILDPID}) {
delete $dispatched_children{$CHILDPID};
$dispatch_children--;
}
}
$SIG{CHLD} = \&dispatch_reaper;
}
sub plugin_reaper {
2013-06-10 14:43:50 +00:00
local($!);
2008-09-19 15:34:08 +00:00
while (($CHILDPID = waitpid(-1, WNOHANG)) > 0) {
if ($plugin_children{$CHILDPID}) {
delete $plugin_children{$CHILDPID};
$plugin_numchildren--;
}
}
$SIG{CHLD} = \&plugin_reaper;
}
$SIG{CHLD} = \&generic_reaper;
2009-12-03 08:01:33 +00:00
my $pid_UDP;
my $pid_MON;
2008-09-19 15:34:08 +00:00
$SIG{TERM} = $SIG{INT} = sub {
2010-02-05 12:23:06 +00:00
#printf("Asked to quit...\n");
2008-09-19 15:34:08 +00:00
$quit++;
foreach (keys %dispatched_children) {
kill 2, $_;
}
foreach (keys %plugin_children) {
kill 2, $_;
}
2009-12-03 08:01:33 +00:00
if ($pid_UDP) {
kill 2, $pid_UDP;
}
if ($pid_MON) {
kill 2, $pid_MON;
2013-01-29 02:03:28 +00:00
kill 12, $pid_MON;
2009-12-03 08:01:33 +00:00
}
xCAT::Table::shut_dbworker;
if ($dbmaster) {
kill 2, $dbmaster;
}
2008-09-19 15:34:08 +00:00
$SIG{ALRM} = sub { xexit 0; }; #die "Did not close out in time for 5 second grace period"; };
alarm(2);
};
2013-08-16 11:05:32 +00:00
socketpair($sslctl, $udpctl,AF_UNIX,SOCK_STREAM,PF_UNSPEC);
my $prevfh = select($udpctl);
$|=1;
select($sslctl);
$|=1;
select($prevfh);
2009-12-03 08:01:33 +00:00
$pid_UDP = xCAT::Utils->xfork;
2009-12-11 08:28:47 +00:00
if (! defined $pid_UDP) {
xCAT::MsgUtils->message("S", "Unable to fork for UDP/TCP");
die;
}
2009-12-03 08:01:33 +00:00
unless ($pid_UDP) {
2013-08-16 11:05:32 +00:00
close($udpctl);
2008-09-19 15:34:08 +00:00
$$progname="xcatd: UDP listener";
do_udp_service;
xexit(0);
}
2013-08-16 11:05:32 +00:00
close($sslctl);
2009-12-03 08:01:33 +00:00
$pid_MON = xCAT::Utils->xfork;
2009-12-11 08:28:47 +00:00
if (! defined $pid_MON) {
xCAT::MsgUtils->message("S", "Unable to fork installmonitor");
die;
}
2009-12-03 08:01:33 +00:00
unless ($pid_MON) {
2008-09-19 15:34:08 +00:00
$$progname="xcatd: install monitor";
2013-08-16 11:05:32 +00:00
close($udpctl);
2008-09-19 15:34:08 +00:00
do_installm_service;
xexit(0);
}
$$progname="xcatd: SSL listener";
2010-07-08 20:49:12 +00:00
2011-12-04 13:04:58 +00:00
# Enable the signals for the subroutine calling trace
2012-03-12 11:54:28 +00:00
$SIG{TRAP} = sub {
if (-f "/tmp/xcatcallingtrace.flag") {
if (open (TRACEFLAG, "</tmp/xcatcallingtrace.flag")) {
my $traceflag = <TRACEFLAG>;
if($traceflag == 1) {
&enable_callingtrace;
print "enabled calling trace\n";
} else {
&disable_callingtrace;
print "dislabled calling trace\n";
}
close (TRACEFLAG);
}
}
};
2011-12-04 13:04:58 +00:00
2010-07-08 20:49:12 +00:00
#setup signal in NotifHandler so that the cache can be updated
xCAT::NotifHandler::setup($$, $dbmaster);
#start the monitoring process
xCAT_monitoring::monitorctrl::start($$);
my $peername;
my $ssltimeout;
my $retry=1;
2008-09-19 15:34:08 +00:00
openlog("xCAT SSL","","local4");
2009-05-29 13:53:49 +00:00
my $listener;
2010-07-08 20:49:12 +00:00
my $mainpidfile;
2011-08-25 17:07:23 +00:00
$SIG{USR2} = sub {
if ($listener) {
2012-09-20 14:30:14 +00:00
unlink("/var/run/xcat/mainservice.pid"); close($listener); $quit=1; $listener=0;
2011-08-25 17:07:23 +00:00
xCAT::MsgUtils->message("S","xcatd main service $$ quiescing");
}
};
if ($inet6support) {
$listener = IO::Socket::INET6->new(
LocalPort => $port,
Listen => 8192,
Reuse => 1,
);
} else {
$listener = IO::Socket::INET->new(
LocalPort => $port,
Listen => 8192,
Reuse => 1,
);
}
2012-09-20 14:30:14 +00:00
if (not $listener and open($mainpidfile,"<","/var/run/xcat/mainservice.pid")) {
2010-07-08 20:49:12 +00:00
my $pid = <$mainpidfile>;
if ($pid) {
$retry=100; #grace period for old instance to get out of the way, 5 seconds
kill 12,$pid;
yield(); # let peer have a shot at closure
}
close($mainpidfile);
}
while (not $listener and $retry) {
$retry--;
if ($inet6support) {
$listener = IO::Socket::INET6->new(
LocalPort => $port,
Listen => 8192,
Reuse => 1,
);
} else {
$listener = IO::Socket::INET->new(
LocalPort => $port,
Listen => 8192,
Reuse => 1,
);
}
sleep(0.05);
2009-05-29 13:53:49 +00:00
}
2012-03-21 15:14:07 +00:00
my $listenwatcher = IO::Select->new($listener);
2008-09-19 15:34:08 +00:00
unless ($listener) {
2009-12-03 08:01:33 +00:00
kill 2, $pid_UDP;
kill 2, $pid_MON;
xCAT::Table::shut_dbworker;
if ($dbmaster) {
kill 2, $dbmaster;
}
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S","xCAT service unable to open SSL services on $port: $!");
2008-09-19 15:34:08 +00:00
closelog();
2012-10-02 17:52:18 +00:00
if ($startupparent) {
print $startupparent "Unable to perform socket takeover from existing xCAT instance\n";
}
2008-09-19 15:34:08 +00:00
die "ERROR:Unable to start xCAT service on port $port.";
}
2012-10-02 17:52:18 +00:00
if ($startupparent) {
print $startupparent "SUCCESS\n";
2012-10-08 18:05:36 +00:00
close($startupparent);
2012-10-02 17:52:18 +00:00
}
2011-08-25 17:07:23 +00:00
#only write to pid file if we have listener, listener ownership serves as lock to protect integrity
2012-09-20 14:30:14 +00:00
open($mainpidfile,">","/var/run/xcat/mainservice.pid"); #if here, everyone else has unlinked mainservicepid or doesn't care
2011-08-25 17:07:23 +00:00
print $mainpidfile $$;
close($mainpidfile);
2008-09-19 15:34:08 +00:00
closelog();
2012-03-21 15:14:07 +00:00
my @pendingconnections;
my $tconn;
2008-09-19 15:34:08 +00:00
until ($quit) {
$SIG{CHLD} = \&ssl_reaper; #set here to ensure that signal handler is not corrupted during loop
2012-03-21 15:14:07 +00:00
if (@pendingconnections) {
2012-03-21 17:50:24 +00:00
while ($listenwatcher->can_read(0)) { #grab everything we can, but don't spend any time waiting for more
2012-03-21 15:14:07 +00:00
$tconn = $listener->accept;
2012-03-21 17:50:24 +00:00
unless ($tconn) { next; }
2012-03-21 15:14:07 +00:00
push @pendingconnections,$tconn;
}
} else {
2012-03-21 17:50:24 +00:00
$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...
2012-03-21 15:14:07 +00:00
push @pendingconnections,$tconn;
2008-09-19 15:34:08 +00:00
}
2012-03-21 17:50:24 +00:00
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
2012-03-21 15:14:07 +00:00
$listenwatcher->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
}
2012-03-21 17:50:24 +00:00
#we have a pending connection and we are under the threshold, grab one from the list and process it...
2012-03-21 15:14:07 +00:00
my $cnnection=shift @pendingconnections;
my $connection;
2008-09-19 15:34:08 +00:00
my $child = xCAT::Utils->xfork(); #Yes we fork, IO::Socket::SSL is not threadsafe..
2010-07-08 20:49:12 +00:00
if ($child) {
$immediatechildren{$child}=1;
}
2008-09-19 15:34:08 +00:00
unless (defined $child) {
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S","xCATd cannot fork");
die;
2008-09-19 15:34:08 +00:00
}
if ($child == 0) {
2013-08-16 11:05:32 +00:00
close($udpctl);
2010-02-15 15:40:35 +00:00
$SIG{TERM} = $SIG{INT} = {};
2008-09-19 15:34:08 +00:00
$SIG{CHLD} = \&generic_reaper; #THROTTLE
$listener->close;
2013-03-01 21:26:35 +00:00
populate_site_hash();
my %extrasslargs;
if ($::XCATSITEVALS{xcatsslversion}) { $extrasslargs{SSL_version} = $::XCATSITEVALS{xcatsslversion}; }
if ($::XCATSITEVALS{xcatsslciphers}) { $extrasslargs{SSL_cipher_list} = $::XCATSITEVALS{xcatsslciphers}; }
use Data::Dumper;
2008-09-19 15:34:08 +00:00
$SIG{ALRM} = sub { $ssltimeout = 1; die; };
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,
2013-03-01 21:26:35 +00:00
SSL_verify_mode=> 1,
%extrasslargs,
2008-09-19 15:34:08 +00:00
);
alarm(0);
};
$SIG{ALRM}='DEFAULT';
if ($@) { #SSL failure
close($cnnection);
xexit 0;
}
unless ($connection) {
xexit 0;
}
$clientselect->add($connection);
my $peerhost=undef;
2009-03-15 20:23:48 +00:00
my $peerfqdn=undef;
2008-09-19 15:34:08 +00:00
my $peer=$connection->peer_certificate("owner");
if ($peer) {
$peer =~ m/CN=([^\/]*)/;
$peername = $1;
} else {
$peername=undef;
}
2012-11-02 13:57:28 +00:00
2008-09-19 15:34:08 +00:00
if ($inet6support) {
$peerhost = gethostbyaddr($connection->peeraddr,AF_INET6);
} else {
$peerhost = gethostbyaddr($connection->peeraddr,AF_INET);
}
unless ($peerhost) { $peerhost = gethostbyaddr($connection->peeraddr,AF_INET); }
2009-03-15 20:23:48 +00:00
$peerfqdn=$peerhost;
2012-06-21 16:11:06 +00:00
my $peerhostorg=$peerhost; # save original with domain for validation
2012-11-02 13:57:28 +00:00
2013-01-17 21:43:09 +00:00
if ($peerhost) {
my @hosts;
push (@hosts, $peerhost);
my $nd = xCAT::NetworkUtils->getNodeDomains(\@hosts);
my %nodedomains = %$nd;
$domain = $nodedomains{$peerhost};
}
2012-11-02 13:57:28 +00:00
2012-06-21 16:11:06 +00:00
if ($domain) {
2009-04-22 17:18:06 +00:00
# strip off domain if set
2010-02-25 03:08:32 +00:00
$peerhost && $peerhost =~ s/\.$domain\.*$//;
2009-04-22 17:18:06 +00:00
} else {
# otherwise just strip off whatever comes after the first dot
2010-10-11 05:59:45 +00:00
$peerhost && $peerhost =~ s/\..*//;
2009-04-22 17:18:06 +00:00
}
2010-02-25 03:08:32 +00:00
$peerhost && $peerhost =~ s/-eth\d*$//;
$peerhost && $peerhost =~ s/-myri\d*$//;
$peerhost && $peerhost =~ s/-ib\d*$//;
2008-09-19 15:34:08 +00:00
#printf('info'.": xcatd: connection from ".($peername ? $peername . "@" . $peerhost : $peerhost)."\n");
2010-02-25 03:08:32 +00:00
$$progname="xCATd SSL: Instance for ".($peername ? $peername ."@".$peerhost : $peerhost) if $peerhost;
2012-06-21 16:11:06 +00:00
service_connection($connection,$peername,$peerhost,$peerfqdn,$peerhostorg);
2008-09-19 15:34:08 +00:00
xexit(0);
}
$sslclients++; #THROTTLE
2013-08-16 11:05:32 +00:00
store_fd({clientcountchange=>1,sslclientcount=>$sslclients},$udpctl); #notify udp service of how many clients are active
2008-09-19 15:34:08 +00:00
$cnnection->close();
}
2012-09-20 14:30:14 +00:00
if (open($mainpidfile,"<","/var/run/xcat/mainservice.pid")) {
2010-07-08 20:49:12 +00:00
my $pid = <$mainpidfile>;
if ($pid == $$) { #if our pid, unlink the file, otherwise, we managed to see the pid after someone else created it
2012-09-20 14:30:14 +00:00
unlink("/var/run/xcat/mainservice.pid");
2010-07-08 20:49:12 +00:00
}
close($mainpidfile);
}
if ($listener) { $listener->close; }
2011-06-24 13:59:30 +00:00
my $lastpid;
while (keys %immediatechildren) {
$lastpid=wait();
if ($immediatechildren{$lastpid}) {
delete $immediatechildren{$lastpid};
}
}
2009-08-06 12:43:27 +00:00
xCAT::Table::shut_dbworker;
if ($dbmaster) {
kill 2, $dbmaster;
}
2008-09-19 15:34:08 +00:00
#stop the monitoring process
xCAT_monitoring::monitorctrl::stop($$);
my $parent_fd;
my %resps;
sub plugin_command {
my $req = shift;
my $sock = shift;
my $callback = shift;
my %handler_hash;
2009-11-13 19:51:33 +00:00
my $usesiteglobal = 0;
2008-09-26 22:57:55 +00:00
use xCAT::NodeRange qw/extnoderange nodesmissed noderange/;
2008-09-19 15:34:08 +00:00
$Main::resps={};
my @nodes;
2011-06-24 18:19:07 +00:00
@ARGV = ();
2008-09-19 15:34:08 +00:00
if ($req->{node}) {
@nodes = @{$req->{node}};
} elsif ($req->{noderange} and $req->{noderange}->[0]) {
2012-05-16 15:11:26 +00:00
xCAT::NodeRange::retain_cache(0); #if the request has a 'noderange' element, take the performance hit for the sake of freshness
2008-09-19 15:34:08 +00:00
@nodes = noderange($req->{noderange}->[0]);
if (nodesmissed) {
2010-04-26 21:41:39 +00:00
my $rsp = {errorcode=>1,error=>"Invalid nodes and/or groups in noderange: ".join(',',nodesmissed)};
2008-09-19 15:34:08 +00:00
$rsp->{serverdone} = {};
if ($sock) {
print $sock XMLout($rsp,RootName=>'xcatresponse' ,NoAttr=>1);
}
return ($rsp);
}
unless (@nodes) {
$req->{emptynoderange} = [1];
}
2011-08-18 02:48:34 +00:00
2008-09-19 15:34:08 +00:00
}
if (@nodes) { $req->{node} = \@nodes; }
my %unhandled_nodes;
foreach (@nodes) {
$unhandled_nodes{$_}=1;
}
my $useunhandled=0;
if (defined($cmd_handlers{$req->{command}->[0]})) {
my $hdlspec;
2009-08-27 23:18:23 +00:00
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
2012-03-25 15:16:11 +00:00
my %hdlrcaches;
2008-09-19 15:34:08 +00:00
foreach (@{$cmd_handlers{$req->{command}->[0]}}) {
$hdlspec =$_->[1];
my $ownmod = $_->[0];
2009-08-27 23:18:23 +00:00
if ($hdlspec =~ /^site:/) { #A site entry specifies a plugin
my $sitekey = $hdlspec;
$sitekey =~ s/^site://;
2012-03-25 15:16:05 +00:00
if ($::XCATSITEVALS{$sitekey}) {#A site style plugin specification is just like
2009-08-27 23:18:23 +00:00
#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) {
2012-03-25 15:16:05 +00:00
$handler_hash{$::XCATSITEVALS{$sitekey}} = 1;
2009-11-13 19:51:33 +00:00
$usesiteglobal = 1;
2009-08-27 23:18:23 +00:00
}
foreach (@nodes) { #Specified a specific plugin, not a table lookup
2012-03-25 15:16:05 +00:00
$handler_hash{$::XCATSITEVALS{$sitekey}}->{$_} = 1;
2009-08-27 23:18:23 +00:00
}
}
} elsif ($hdlspec =~ /:/) { #Specificed a table lookup path for plugin name
2009-11-24 15:12:39 +00:00
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;
my $table;
my $cols;
($table,$cols) = split(/:/,$hdlspec);
my @colmns=split(/,/,$cols);
my @columns;
2012-03-25 15:16:11 +00:00
my $hdlrtable=0;
unless ($hdlrcaches{$hdlspec}) {
$hdlrtable=xCAT::Table->new($table,-create=>0);
unless ($hdlrtable) {
next;
}
}
2009-11-24 15:12:39 +00:00
my $node;
my $colvals = {};
foreach my $colu (@colmns) {
if ($colu =~ /=/) { #a value redirect to a pattern/specific name
my $coln; my $colv;
($coln,$colv) = split(/=/,$colu,2);
$colvals->{$coln} = $colv;
push (@columns,$coln);
} else {
push (@columns,$colu);
}
2008-09-19 15:34:08 +00:00
}
2009-11-24 15:12:39 +00:00
unless (@nodes) { #register the plugin in the event of usage
$handler_hash{$ownmod} = 1;
$useglobals = 1;
}
if ($hdlrtable) {
2012-03-25 15:16:11 +00:00
$hdlrcaches{$hdlspec} = $hdlrtable->getNodesAttribs(\@nodes,\@columns);
2009-11-24 15:12:39 +00:00
}
foreach $node (@nodes) {
2012-03-25 15:16:11 +00:00
unless ($hdlrcaches{$hdlspec}) { next; }
my $attribs = $hdlrcaches{$hdlspec}->{$node}->[0]; #$hdlrtable->getNodeAttribs($node,\@columns);
2009-11-24 15:12:39 +00:00
unless (defined($attribs)) { next; }
foreach (@columns) {
my $col=$_;
if (defined($attribs->{$col})) {
if ($colvals->{$col}) { #A pattern match style request.
if ($attribs->{$col} =~ /$colvals->{$col}/) {
$handler_hash{$ownmod}->{$node} = 1;
delete $unhandled_nodes{$node};
last;
}
} else {
# call the plugin that matches the table value for that node
if ($attribs->{$col} =~ /$ownmod/) {
$handler_hash{$attribs->{$col}}->{$node} = 1;
delete $unhandled_nodes{$node};
last;
}
2008-09-19 15:34:08 +00:00
}
}
}
}
2012-03-25 15:16:11 +00:00
$hdlrtable->close if $hdlrtable;
2009-11-24 15:12:39 +00:00
} # end if (@nodes)
2008-09-19 15:34:08 +00:00
} else {
2009-08-27 23:18:23 +00:00
push @globalhandlers,$hdlspec;
}
}
2009-08-28 01:33:35 +00:00
if ($useglobals == 1) { #Behavior when globals have not been overriden
my $hdlspec;
foreach $hdlspec (@globalhandlers) {
unless (@nodes) {
$handler_hash{$hdlspec} = 1;
}
foreach (@nodes) { #Specified a specific plugin, not a table lookup
$handler_hash{$hdlspec}->{$_} = 1;
}
}
} elsif ($useglobals == 0) {
2009-11-13 19:51:33 +00:00
unless (@nodes or $usesiteglobal) { #if something like 'makedhcp -n',
foreach (keys %handler_hash) {
if ($handler_hash{$_} == 1) {
delete ($handler_hash{$_})
}
}
}
2009-08-28 01:33:35 +00:00
foreach $hdlspec (@globalhandlers) {
2009-11-13 19:51:33 +00:00
unless (@nodes or $usesiteglobal) {
$handler_hash{$hdlspec} = 1;
}
2009-08-28 01:33:35 +00:00
foreach (keys %unhandled_nodes) { #Specified a specific plugin, not a table lookup
$handler_hash{$hdlspec}->{$_} = 1;
}
}
} #Otherwise, global handler is implicitly disabled
2009-08-27 23:18:23 +00:00
} else {
return 1; #TODO: error back that request has no known plugin for it
}
2008-09-19 15:34:08 +00:00
if ($useunhandled) {
2009-11-24 15:12:39 +00:00
my $queuelist='';
foreach (@{$cmd_handlers{$req->{command}->[0]}}) {
my $queueitem = $_->[1];
if (($queueitem =~ /:/) and !($queuelist =~ /($queueitem)/)) {
$queuelist .= "$_->[1];";
}
2008-09-19 15:34:08 +00:00
}
2009-11-24 15:12:39 +00:00
$queuelist =~ s/;$//;
2008-09-19 15:34:08 +00:00
$queuelist =~ s/:/./g;
2012-03-25 17:45:27 +00:00
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]}]};
}
print $sock XMLout($xcatresponse,KeepRoot=>1,NoAttr=>1);
} else {
foreach (keys %unhandled_nodes) {
2008-09-19 15:34:08 +00:00
my $tabdesc = $queuelist;
$tabdesc =~ s/=.*$//;
2008-11-11 15:42:04 +00:00
$callback->({node=>[{name=>[$_],error=>['Unable to identify plugin for this command, check relevant tables: '.$tabdesc],errorcode=>[1]}]});
2008-09-19 15:34:08 +00:00
}
}
}
2012-12-14 04:23:45 +00:00
my %xcatresponses = ( xcatresponse => [] );
2008-09-19 15:34:08 +00:00
$plugin_numchildren=0;
%plugin_children=();
2010-01-27 10:24:34 +00:00
# save the old signal
my $old_sig_chld = $SIG{CHLD};
2008-09-19 15:34:08 +00:00
$SIG{CHLD} = \&plugin_reaper; #sub {my $plugpid; while (($plugpid = waitpid(-1, WNOHANG)) > 0) { if ($plugin_children{$plugpid}) { delete $plugin_children{$plugpid}; $plugin_numchildren--; } } };
my $check_fds;
if ($sock) {
$check_fds = new IO::Select;
}
2012-12-14 04:23:45 +00:00
# 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
2012-12-18 08:53:57 +00:00
my $old_parent_fd = $parent_fd;
2012-12-14 04:23:45 +00:00
$parent_fd = 0;
foreach (sort(keys %handler_hash)) {
my $modname = $_;
$Main::resps={};
if (-r $plugins_dir."/".$modname.".pm") {
require $plugins_dir."/".$modname.".pm";
$plugin_numchildren++;
my $oldprogname=$$progname;
$$progname=$oldprogname.": $modname instance";
unless ($handler_hash{$_} == 1) {
#ok, if nodes have numbers, this sorts them numerically... roughly..
2013-01-02 22:04:14 +00:00
#if node doesn't, then it sorts out alphabetically.
2012-12-19 16:40:29 +00:00
my @nodes = sort {($a =~ /(\d+)/ ? $1 : -1)[0] <=> ($b =~ /(\d+)/ ? $1 : -1)[0] || $a cmp $b } (keys %{$handler_hash{$_}});
2012-12-14 04:23:45 +00:00
$req->{node}=\@nodes;
}
no strict "refs";
eval { #REMOVEEVALFORDEBUG
if ($dispatch_requests) {
dispatch_request($req,$callback,$modname);
} else {
$SIG{CHLD}='DEFAULT';
${"xCAT_plugin::".$modname."::"}{process_request}->($req,$callback,\&do_request);
}
$$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";
if (ref $handler_hash{$_}) {
foreach my $node (keys %{$handler_hash{$_}}) {
if ($sock) {
print $sock XMLout({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]},NoAttr=>1,RootName=>'xcatresponse');
} else {
$callback->({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]});
}
}
} else {
if ($sock) {
print $sock XMLout({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]},NoAttr=>1,RootName=>'xcatresponse');
} else {
$callback->({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]});
}
}
}
push @{$xcatresponses{xcatresponse}}, $Main::resps;
}
2012-12-18 08:53:57 +00:00
$parent_fd = $old_parent_fd;
2012-12-14 04:23:45 +00:00
} else {
2013-11-21 08:51:00 +00:00
my $req_back = undef;
2012-12-14 04:23:45 +00:00
# executing plugins parallel
2008-09-19 15:34:08 +00:00
foreach (keys %handler_hash) {
my $modname = $_;
2009-05-06 20:07:05 +00:00
my $shouldbealivepid=$$;
2008-09-19 15:34:08 +00:00
if (-r $plugins_dir."/".$modname.".pm") {
require $plugins_dir."/".$modname.".pm";
$plugin_numchildren++;
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..
2009-12-11 08:28:47 +00:00
if (! socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) {
xCAT::MsgUtils->message("S", "socketpair failed: $!");
die;
}
2008-09-19 15:34:08 +00:00
#pipe($pfd,$cfd);
2011-06-08 18:46:01 +00:00
my $oldfh = select $parfd;
$|=1;
select $pfd;
$|=1;
select $oldfh;
2010-01-04 19:04:50 +00:00
binmode($parfd,':utf8');
binmode($pfd,':utf8');
2008-09-19 15:34:08 +00:00
$child = xCAT::Utils->xfork;
} else {
2013-11-21 08:51:00 +00:00
if ($req_back) {
$req = dclone($req_back);
} else {
$req_back = dclone($req);
}
2008-09-19 15:34:08 +00:00
$child = 0;
}
2009-12-11 08:28:47 +00:00
unless (defined $child) {
xCAT::MsgUtils->message("S", "Fork failed");
die;
}
2008-09-19 15:34:08 +00:00
if ($child == 0) {
2012-12-05 03:04:13 +00:00
setpgrp(0,0);
2008-09-19 15:34:08 +00:00
if ($parfd) { #If xCAT is doing multiple requests in same communication PID, things would get unfortunate otherwise
$parent_fd = $parfd;
}
2012-12-18 08:53:57 +00:00
my $org_parent_fd = $parent_fd;
2008-09-19 15:34:08 +00:00
my $oldprogname=$$progname;
$$progname=$oldprogname.": $modname instance";
if ($sock) { close $pfd; }
unless ($handler_hash{$_} == 1) {
2011-04-26 18:29:08 +00:00
#ok, if nodes have numbers, this sorts them numerically... roughly..
2013-01-02 22:04:14 +00:00
#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{$_}});
2008-09-19 15:34:08 +00:00
$req->{node}=\@nodes;
}
no strict "refs";
2009-01-31 22:45:22 +00:00
eval { #REMOVEEVALFORDEBUG
2008-09-19 15:34:08 +00:00
if ($dispatch_requests) {
dispatch_request($req,$callback,$modname);
} else {
$SIG{CHLD}='DEFAULT';
${"xCAT_plugin::".$modname."::"}{process_request}->($req,$callback,\&do_request);
}
$$progname=$oldprogname;
2012-12-18 08:53:57 +00:00
$parent_fd = $org_parent_fd;
2008-09-19 15:34:08 +00:00
if ($sock) {
close($parent_fd);
xexit(0);
}
2010-06-01 18:04:25 +00:00
$@=""; #sometimes a child 'eval' doesn't clean up $@, if we make it this far, no non-eval bug bombed out
2009-01-31 22:45:22 +00:00
}; #REMOVEEVALFORDEBUG
2009-05-06 20:07:05 +00:00
if ($sock or $shouldbealivepid != $$) { #We shouldn't still be alive, try to send as much detail to parent as possible as to why
2009-01-31 22:45:22 +00:00
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);
}
xCAT::MsgUtils->message("S","xcatd: $error");
$callback->({error=>[$error],errorcode=>[1]});
xexit(0); #Die like we should have done
2009-06-22 15:03:46 +00:00
} 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..
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S", "$@");
2009-06-22 15:03:46 +00:00
die $@;
2009-01-31 22:45:22 +00:00
}
2008-09-19 15:34:08 +00:00
} else {
$plugin_children{$child}=1;
close $parfd;
$check_fds->add($pfd);
}
2009-03-25 14:33:08 +00:00
} else {
my $pm_name = $plugins_dir."/".$modname.".pm";
2010-04-01 14:04:34 +00:00
if (ref $handler_hash{$_}) {
foreach my $node (keys %{$handler_hash{$_}}) {
if ($sock) {
print $sock XMLout({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]},NoAttr=>1,RootName=>'xcatresponse');
} else {
$callback->({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]});
}
}
} else {
if ($sock) {
print $sock XMLout({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]},NoAttr=>1,RootName=>'xcatresponse');
} else {
$callback->({data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]});
}
2009-03-25 14:33:08 +00:00
}
2008-09-19 15:34:08 +00:00
}
}
2012-12-14 04:23:45 +00:00
}
2010-01-27 10:24:34 +00:00
unless ($sock) {
# restore the old signal
$SIG{CHLD} = $old_sig_chld;
return $Main::resps
}
2011-06-15 15:09:39 +00:00
if (@deferredmsgargs) { xCAT::MsgUtils->message(@deferredmsgargs) };
@deferredmsgargs=();
2012-03-25 18:10:48 +00:00
my $nextxmittime = time()+1;
2008-09-19 15:34:08 +00:00
while (($plugin_numchildren > 0) and ($check_fds->count > 0)) { #this tracks end of useful data from children much more closely
2012-03-25 18:10:48 +00:00
relay_fds($check_fds,$xcatresponses{xcatresponse});
if (time() > $nextxmittime) {
$nextxmittime = time()+1;
send_pending_responses(\%xcatresponses,$sock);
$xcatresponses{xcatresponse}=[];
}
}
if (scalar(@{$xcatresponses{xcatresponse}})) {
send_pending_responses(\%xcatresponses,$sock);
$xcatresponses{xcatresponse}=[];
2008-09-19 15:34:08 +00:00
}
#while (relay_fds($check_fds,$sock)) {}
2010-01-27 10:24:34 +00:00
# restore the old signal
$SIG{CHLD} = $old_sig_chld;
2008-09-19 15:34:08 +00:00
my %done;
$done{serverdone} = {};
if ($req->{transid}) {
$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);
2012-03-16 18:41:47 +00:00
my $deadline = time()+5;
while ($deadline > time()) { #sometimes can_write exits prematurely without waiting the whole time.....
if ($clientpresence->can_write(5)) {
print $sock XMLout(\%done,RootName => 'xcatresponse',NoAttr=>1);
last;
}
}
2008-09-19 15:34:08 +00:00
}
}
my $dispatch_parentfd;
sub dispatch_callback {
my $rspo = shift;
unless ($rspo) {
return;
}
my $rsp = {%$rspo}; # deep copy
delete $rsp->{serverdone};
unless (%$rsp) { return; }
2013-04-04 20:11:05 +00:00
store_fd($rsp,$dispatch_parentfd);
2010-01-07 16:54:33 +00:00
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
xexit 0;
}
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
next;
}
if ($rsp = <$dispatch_parentfd>) {
if ($rsp =~ /die/ or $quit) {
xexit 0;
2008-09-19 15:34:08 +00:00
}
2010-01-07 16:54:33 +00:00
last;
} else {
$parselect->remove($dispatch_parentfd); #Block until parent acks data
last;
2008-09-19 15:34:08 +00:00
}
2010-01-07 16:54:33 +00:00
$selbits = $parselect->bits;
yield;
2008-09-19 15:34:08 +00:00
}
}
sub relay_dispatch {
my $fds = shift;
2010-01-07 16:54:33 +00:00
my $dispatch_cb = shift;
2012-05-02 19:57:58 +00:00
my @ready_ins;
eval {
@ready_ins = $fds->can_read(1);
};
if ($@) { undef $@; return 0; }
2008-09-19 15:34:08 +00:00
foreach my $rin (@ready_ins) {
my $data;
2013-04-04 20:11:05 +00:00
my $response;
eval {
$response = fd_retrieve($rin);
};
if ($@ and $@ =~ /^Magic number checking on storable file/) { #this most likely means we ran over the end of available input
2008-09-19 15:34:08 +00:00
$fds->remove($rin);
close($rin);
2013-04-04 20:11:05 +00:00
} else {
print $rin "dfin\n";
$dispatch_cb->($response);
2008-09-19 15:34:08 +00:00
}
}
yield; #At this point, explicitly yield to other processes. If children will have more data, this process would otherwise uselessly loop on data that never will be. If children are all done, still no harm in waiting a short bit for a timeslice to come back
return scalar(@ready_ins);
}
sub dispatch_request {
%dispatched_children=();
my $req = shift;
2010-01-07 16:54:33 +00:00
my $dispatch_cb = shift;
2008-09-19 15:34:08 +00:00
my $modname = shift;
my $reqs = [];
my $child_fdset = new IO::Select;
no strict "refs";
2010-01-27 10:24:34 +00:00
# save the old signal
my $old_sig_chld = $SIG{CHLD};
2008-09-19 15:34:08 +00:00
#Hierarchy support. Originally, the default scope for noderange commands was
#going to be the servicenode associated unless overriden.
#However, assume for example that you have blades and a blade is the service node
#rpower being executed by the servicenode for one of its subnodes would have to
#reach it's own management module. This has the potential to be non-trivial for some quite possible network configurations.
#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
2012-02-05 17:51:51 +00:00
if ((not (defined $req->{_xcatpreprocessed}->[0] and $req->{_xcatpreprocessed}->[0] == 1)) and (defined(${"xCAT_plugin::".$modname."::"}{preprocess_request}))) {
2008-09-19 15:34:08 +00:00
$SIG{CHLD}='DEFAULT';
$reqs = ${"xCAT_plugin::".$modname."::"}{preprocess_request}->($req,$dispatch_cb,\&do_request);
} else { #otherwise, pass it in without hierarchy support
$reqs = [$req];
}
$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--; } } };
2012-05-02 19:57:58 +00:00
$SIG{TERM} = $SIG{INT} = sub {
foreach (keys %dispatched_children) {
kill 2, $_;
}
};
2012-07-20 09:54:54 +00:00
# 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'} ) {
my $in_modname = undef;
if (ref $req->{'_modname'} eq 'ARRAY') {
$in_modname = $req->{'_modname'}->[0];
} else {
$in_modname = $req->{'_modname'};
}
if ($in_modname ne $modname) {
$reqs = [];
}
}
2012-05-02 19:57:58 +00:00
2008-09-19 15:34:08 +00:00
my $onlyone=0;
if (defined $reqs and (scalar(@{$reqs}) == 1)) {
2008-08-11 18:13:35 +00:00
$onlyone=1;
}
2008-01-26 00:23:23 +00:00
foreach (@{$reqs}) {
my $pfd;
2008-01-27 17:37:24 +00:00
my $parfd; #use a private variable so it won't trounce itself recursively
2008-01-26 00:23:23 +00:00
my $child;
delete $_->{noderange};
2009-05-06 20:07:05 +00:00
if (ref $_->{'_xcatdest'} and (ref $_->{'_xcatdest'}) eq 'ARRAY') {
_->{'_xcatdest'} = $_->{'_xcatdest'}->[0];
}
2012-08-09 03:58:34 +00:00
if ($onlyone and not ($_->{'_xcatdest'} and xCAT::NetworkUtils->thishostisnot($_->{'_xcatdest'}))) {
2008-08-11 18:32:42 +00:00
$SIG{CHLD}='DEFAULT';
2012-05-17 14:03:04 +00:00
if ($_->{'_xcatdelay'} and not ref $_->{'_xcatdelay'}) { sleep $_->{'_xcatdelay'}; }
2008-08-11 18:13:35 +00:00
${"xCAT_plugin::".$modname."::"}{process_request}->($_,$dispatch_cb,\&do_request);
return;
}
2009-12-11 08:28:47 +00:00
if (! socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC)) {
xCAT::MsgUtils->message("S", "ERROR: socketpair: $!");
die;
}
2011-06-08 18:46:01 +00:00
my $oldfh = select $parfd;
$|=1;
select $pfd;
$|=1;
select $oldfh;
2010-01-04 19:04:50 +00:00
binmode($parfd,':utf8');
binmode($pfd,':utf8');
2008-01-26 00:23:23 +00:00
$child = xCAT::Utils->xfork;
if ($child) {
2008-04-24 17:26:30 +00:00
$dispatch_children++;
2008-04-21 15:27:11 +00:00
$dispatched_children{$child}=1;
2008-01-26 00:23:23 +00:00
$child_fdset->add($pfd);
2012-05-22 21:11:14 +00:00
close($parfd);
2008-01-26 00:23:23 +00:00
next;
}
unless (defined $child) {
$dispatch_cb->({error=>['Fork failure dispatching request'],errorcode=>[1]});
}
2012-05-22 21:11:14 +00:00
close($pfd);
2008-08-11 18:32:42 +00:00
$SIG{CHLD}='DEFAULT';
2008-04-21 15:27:11 +00:00
$dispatch_parentfd = $parfd;
2009-02-28 22:38:48 +00:00
my @prexcatdests=();
my @xcatdests=();
2012-05-17 14:03:04 +00:00
if ($_->{'_xcatdelay'} and not ref $_->{'_xcatdelay'}) { sleep $_->{'_xcatdelay'}; }
2009-02-28 22:38:48 +00:00
if (ref($_->{'_xcatdest'}) eq 'ARRAY') { #If array, consider it an 'anycast' operation, broadcast done through dupe
#requests, or an alternative join '&' maybe?
@prexcatdests=@{$_->{'_xcatdest'}};
} else {
@prexcatdests=($_->{'_xcatdest'});
}
foreach (@prexcatdests) {
2009-05-06 20:07:44 +00:00
if ($_ and /,/) {
2009-02-28 22:38:48 +00:00
push @xcatdests,split /,/,$_;
} else {
push @xcatdests,$_;
}
2008-08-07 14:43:58 +00:00
}
2009-02-28 22:38:48 +00:00
my $xcatdest;
2009-03-04 21:17:59 +00:00
my $numdests=scalar(@xcatdests);
my $request_satisfied=0;
2009-02-28 22:38:48 +00:00
foreach $xcatdest (@xcatdests) {
2009-04-23 20:09:14 +00:00
my $dlock;
2012-08-09 03:58:34 +00:00
if ($xcatdest and xCAT::NetworkUtils->thishostisnot($xcatdest)) {
2009-09-15 20:58:45 +00:00
#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);
2009-02-28 22:38:48 +00:00
$ENV{XCATHOST} = ($xcatdest =~ /:/ ? $xcatdest : $xcatdest.":3001" );
$$progname.=": connection to ".$ENV{XCATHOST};
2009-04-23 20:09:14 +00:00
my $errstr;
2009-02-28 22:38:48 +00:00
eval {
undef $_->{'_xcatdest'};
2012-07-20 09:54:54 +00:00
#mainly used by SN to filter out the incorrect module that xcat command came into
$_->{'_modname'} = $modname;
2009-02-28 22:38:48 +00:00
xCAT::Client::submit_request($_,\&dispatch_callback,$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/ca.pem");
};
if ($@) {
2009-04-23 20:09:14 +00:00
$errstr=$@;
}
2009-09-15 20:58:45 +00:00
#unlink("/var/lock/xcat/dispatchto_$xcatdest");
#flock($dlock,LOCK_UN);
2009-04-23 20:09:14 +00:00
if ($errstr) {
2009-03-04 21:17:59 +00:00
if ($numdests == 1) {
2013-08-16 11:05:32 +00:00
dispatch_callback({error=>["Unable to dispatch hierarchical sub-command to ".$ENV{XCATHOST}.". This service node may be down or its xcatd daemon may not be responding."],errorcode=>[1]});
2009-03-04 21:17:59 +00:00
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);
}
2009-02-28 22:38:48 +00:00
next;
2009-03-04 18:01:26 +00:00
} else {
2009-03-04 21:17:59 +00:00
$request_satisfied=1;
2009-03-04 18:01:26 +00:00
last;
}
2009-02-28 22:38:48 +00:00
} else {
$$progname.=": locally executing";
$SIG{CHLD}='DEFAULT';
${"xCAT_plugin::".$modname."::"}{process_request}->($_,\&dispatch_callback,\&do_request);
last;
}
2008-01-25 15:07:53 +00:00
}
2010-07-07 16:22:27 +00:00
if (!(xCAT::Utils->isServiceNode())) { # not on a service node
if ($numdests > 1 and not $request_satisfied) {
2009-03-04 21:17:59 +00:00
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]});
2010-07-07 16:22:27 +00:00
}
2009-03-04 21:17:59 +00:00
}
2008-04-24 17:26:30 +00:00
xexit;
2008-01-25 15:07:53 +00:00
}
2010-01-07 16:54:33 +00:00
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.
2010-01-27 10:24:34 +00:00
# restore the old signal
$SIG{CHLD} = $old_sig_chld;
2008-01-24 13:37:34 +00:00
}
2008-05-14 14:57:37 +00:00
2007-10-26 22:44:33 +00:00
sub do_request {
my $req = shift;
my $second = shift;
my $rsphandler = \&build_response;
my $sock = undef;
if ($second) {
if (ref($second) eq "CODE") {
$rsphandler = $second;
} elsif (ref($second) eq "GLOB") {
$sock = $second;
}
}
#my $sock = shift; #If no sock, will return a response hash
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{serverdone} = {};
@{$resp{node}}=@nodes;
if ($req->{transid}) {
$resp{transid}=$req->{transid}->[0];
}
if ($sock) {
print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1);
} else {
return (\%resp);
}
} else {
my %resp=(error=>"Unsupported request");
$resp{serverdone} = {};
if ($req->{transid}) {
$resp{transid}=$req->{transid}->[0];
}
if ($sock) {
print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1);
} else {
return (\%resp);
}
}
}
sub convey_response {
my $resp=shift;
#TODO: This is where the following will/may happen:
#-Track transaction id
#-Save output for deferred commands
unless ($parent_fd) {
build_response($resp);
return;
}
2011-06-16 18:22:28 +00:00
unless ($resp) { return; }
2012-05-02 19:57:58 +00:00
$pipeexpected=1;
2011-06-15 18:36:22 +00:00
#$resp = XMLout($resp,KeyAttr=>[], NoAttr=>1,RootName=>'xcatresponse');
2009-11-23 18:57:20 +00:00
#sanitize the response, to avoid being killed by non-printable bytes
2011-06-15 18:36:22 +00:00
#$resp =~ tr/\011-\177/?/c;
2010-06-24 18:29:50 +00:00
#seeing if using utf-8 offloads potential issues to client terminal, it didn't
2013-04-04 20:11:05 +00:00
store_fd($resp,$parent_fd);
2008-05-16 18:12:46 +00:00
yield; #parent must get timeslice anyway before an ack could possibly return
2008-04-21 15:27:11 +00:00
my $parsel = new IO::Select;
$parsel->add($parent_fd);
2008-05-16 18:12:46 +00:00
my $selbits = $parsel->bits;
my $rsp;
while ($selbits && ($rsp = select($selbits, undef, undef, 5))) { #block up to five seconds
if ($quit) { # Obey quit flag
xexit 0;
}
if ($rsp == 0) { #This means the filedescriptor was removed
last;
}
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
last;
} else {
$parsel->remove($parent_fd);
2008-05-25 01:27:26 +00:00
last;
2008-05-16 18:12:46 +00:00
}
}
yield; #If still around, it means a peer process still hasn't gotten to us, so might as well yield
$selbits = $parsel->bits;
2007-10-26 22:44:33 +00:00
}
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.
# Note: Need to create a new "deep clone" copy of each response structure
# otherwise the next call will overwrite the reference we pushed on
# the response array
my $resp = shift;
foreach (keys %$resp) {
my $subresp = dclone($resp->{$_});
2011-03-08 16:58:40 +00:00
if (ref $subresp eq 'ARRAY') {
push (@{$Main::resps->{$_}}, @{$subresp});
} else {
push (@{$Main::resps->{$_}}, $subresp);
}
2007-10-26 22:44:33 +00:00
}
}
2008-09-27 19:24:02 +00:00
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;
2008-09-28 18:46:48 +00:00
unless (defined $id and defined $pass) {
return undef;
}
2008-09-27 19:24:02 +00:00
my $passent=$passtab->getAttribs({key=>'xcat',username=>$id},['password']);
unless ($passent) {
return undef;
}
$passent=$passent->{password};
2009-12-15 06:34:55 +00:00
my $encryptedpass = crypt($pass,$passent);
if ($encryptedpass eq $passent) {
return $id;
}elsif ($pass eq $passent) {
2008-09-27 19:24:02 +00:00
return $id;
}
2009-12-15 06:34:55 +00:00
# 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
# if ($pass eq $passent) {
# return $id;
# }
2008-09-27 19:24:02 +00:00
#If here, unable to validate given credential
return undef;
}
2010-10-20 18:37:09 +00:00
sub populate_site_hash {
2010-10-22 13:28:22 +00:00
%::XCATSITEVALS=();
2010-10-20 18:37:09 +00:00
my $sitetab = xCAT::Table->new('site',-create=>0);
unless ($sitetab) { return; }
my @records = $sitetab->getAllAttribs(qw/key value/);
foreach (@records) {
$::XCATSITEVALS{$_->{key}}=$_->{value};
}
}
2008-09-27 19:24:02 +00:00
2007-10-26 22:44:33 +00:00
sub service_connection {
my $sock = shift;
my $peername = shift;
my $peerhost = shift;
2009-03-15 20:23:48 +00:00
my $peerfqdn = shift;
2012-06-21 16:11:06 +00:00
my $peerhostorg = shift;
2007-10-26 22:44:33 +00:00
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
#Give only 15 seconds of silence allowed or terminate connection. Using alarm since we are in thread-unsafe world anyway
my $timedout = 0;
$SIG{ALRM} = sub { $timedout = 1; die; };
2009-01-31 22:45:22 +00:00
my $evalpid = $$;
eval { #REMOVEEVALFORDEBUG
2007-10-26 22:44:33 +00:00
my $request;
my $req=undef;
2012-04-29 00:13:41 +00:00
my $line;
my $clientsel = new IO::Select;
$clientsel->add($sock);
while (1) {
$line="";
unless ($clientsel->can_read(15)) { last; } #don't let an unresponsive client hold us up
2012-05-15 19:43:39 +00:00
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);
2012-04-29 00:13:41 +00:00
my $bytesread;
do { $bytesread=sysread($sock,$line,65536,length($line)) } while ($bytesread);
if (length($line)==0) {
2013-08-16 11:05:32 +00:00
if (not defined $bytesread and (($! == EAGAIN) or ($! == ECHILD))) { next; } #
2012-04-29 00:13:41 +00:00
last;
}
2012-05-16 15:11:26 +00:00
$flags=fcntl($sock,F_GETFL,0);
2012-05-15 19:43:39 +00:00
$flags &= ~O_NONBLOCK; #now we want *print* to be blocking IO
fcntl($sock,F_SETFL,$flags);
2012-04-29 00:13:41 +00:00
$request .= $line;
2007-10-26 22:44:33 +00:00
#$req = eval { XMLin($request, ForceArray => [ 'attribute' , 'attributepair' ]) };
2012-04-29 00:13:41 +00:00
if ($line =~ m/<\/xcatrequest>/) {
2007-10-26 22:44:33 +00:00
$req = eval { XMLin($request, SuppressEmpty=>undef,ForceArray=>1) };
2008-09-27 19:24:02 +00:00
#first change peername on 'becomeuser' tag if present and valid
if (defined $req->{becomeuser}) {
2008-09-28 16:08:12 +00:00
$peername=becomeuser($req->{becomeuser}->[0]->{username}->[0],
2008-09-27 19:24:02 +00:00
$req->{becomeuser}->[0]->{password}->[0]);
unless (defined $peername) {
my $resp={error=>["Authentication failure"],errorcode=>[1]};
$resp->{serverdone}={};
print $sock XMLout($resp,RootName => 'xcatresponse',NoAttr=>1);
return;
}
delete($req->{becomeuser}); #Remove it to keep it from view
}
2014-04-07 11:57:57 +00:00
# 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],
$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);
$year += 1900;
my $htime = "$year-$mon-$mday $hour:$min:$sec";
$resp = {data=>[{token => [{id => $tokenid, expire => $htime}]}]};
} else {
$resp={error=>["Authentication failure"],errorcode=>[1]};
}
$resp->{serverdone}=[ undef ] ;
2014-05-08 08:48:33 +00:00
print $sock XMLout($resp,RootName => 'xcatresponse',NoAttr=>1);
2014-04-07 11:57:57 +00:00
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 ] ;
2014-05-08 08:48:33 +00:00
print $sock XMLout($resp,RootName => 'xcatresponse',NoAttr=>1);
2014-04-07 11:57:57 +00:00
return;
}
delete($req->{tokenid});
}
2007-10-26 22:44:33 +00:00
#we have a full request..
#printf $request."\n";
$request="";
2012-06-21 16:11:06 +00:00
if (xCAT::xcatd->validate($peername,$peerhost,$req,$peerhostorg,\@deferredmsgargs)) {
2008-01-25 15:07:53 +00:00
$req->{'_xcat_authname'} = [$peername];
$req->{'_xcat_clienthost'} = [$peerhost];
2009-03-15 20:23:48 +00:00
$req->{'_xcat_clientfqdn'} = [$peerfqdn];
2008-01-25 15:07:53 +00:00
$req->{'_xcat_clientport'}= [$peerport];
2009-06-26 14:50:08 +00:00
$$progname="xCATd SSL: ".$req->{command}->[0];
2009-08-26 19:41:30 +00:00
if ($req->{noderange} && defined($req->{noderange}->[0])) {
2009-06-26 14:50:08 +00:00
$$progname .= " to ".$req->{noderange}->[0];
}
2010-02-25 03:08:32 +00:00
if($peerhost){
$$progname .= " for ".($peername ? $peername ."@".$peerhost : $peerhost);
}
2008-09-28 16:08:12 +00:00
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"];
} else {
$resp->{data}=["Unauthenticated"];
}
$resp->{serverdone}={};
print $sock XMLout($resp,RootName => 'xcatresponse',NoAttr=>1);
} elsif ($cmd_handlers{$req->{command}->[0]}) {
2012-04-26 14:35:29 +00:00
plugin_command($req,$sock,\&convey_response);
2007-10-26 22:44:33 +00:00
} elsif ($req->{command}->[0] eq "noderange" and $req->{noderange}) {
2012-05-16 15:11:26 +00:00
xCAT::NodeRange::retain_cache(0); #if the request has a 'noderange' element, take the performance hit for the sake of freshness
2007-10-26 22:44:33 +00:00
my @nodes = noderange($req->{noderange}->[0]);
my %resp;
if (nodesmissed) {
$resp{warning}="Invalid nodes in noderange:".join ',',nodesmissed;
}
$resp{serverdone} = {};
@{$resp{node}}=@nodes;
if ($req->{transid}) {
$resp{transid}=$req->{transid}->[0];
}
print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1);
next;
2008-09-26 22:57:55 +00:00
} 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}={};
print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1);
2008-09-27 15:23:43 +00:00
next;
2007-10-26 22:44:33 +00:00
} else {
my %resp=(error=>"Unsupported request");
$resp{serverdone} = {};
if ($req->{transid}) {
$resp{transid}=$req->{transid}->[0];
}
2010-10-31 12:44:06 +00:00
xCAT::MsgUtils->message("S","Unsupported request: peername=$peername, peerhost=$peerhost,peerfqdn=$peerfqdn,peerport=$peerport, command=".$req->{command}->[0]);
2007-10-26 22:44:33 +00:00
print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1);
next;
}
} else {
my %resp=(error=>"Permission denied for request");
$resp{serverdone} = {};
if ($req->{transid}) {
$resp{transid}=$req->{transid}->[0];
}
2010-10-31 12:44:06 +00:00
xCAT::MsgUtils->message("S","Permission denied for request: peername=$peername, peerhost=$peerhost,peerfqdn=$peerfqdn,peerport=$peerport command= ".$req->{command}->[0]);
2007-10-26 22:44:33 +00:00
my $response=XMLout(\%resp,RootName =>'xcatresponse',NoAttr => 1);
print $sock $response;
next;
}
}
}
2009-01-31 22:45:22 +00:00
}; #REMOVEEVALFORDEBUG
2007-10-26 22:44:33 +00:00
if ($@) { # The eval statement caught a program bug..
2008-04-21 18:48:07 +00:00
if ($@ =~ /^SIGPIPE/) {
2008-08-10 12:57:50 +00:00
xCAT::MsgUtils->message("S","xcatd: Unexpected client disconnect");
2008-07-14 15:15:35 +00:00
if ($sock) {
eval {
print $sock XMLout({error=>"Generic PIPE error occurred. $@"},RootName=>'xcatresponse',NoAttr=>1);
};
}
} elsif ($@ =~ /Client abort requested/) {
2008-04-21 18:48:07 +00:00
} else {
2008-07-14 15:15:35 +00:00
my $errstr="A fatal error was encountered, the following information may help identify a bug: $@";
chomp($errstr);
2008-08-10 12:57:50 +00:00
xCAT::MsgUtils->message("S","xcatd: possible BUG encountered by xCAT TCP service: ".$@);
2008-07-14 15:15:35 +00:00
if ($sock) {
eval {
print $sock XMLout({error=>$errstr},RootName=>'xcatresponse',NoAttr=>1);
};
}
2007-10-26 22:44:33 +00:00
}
2009-01-31 22:45:22 +00:00
} 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");
#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.
print $sock,XMLout({error=>"A child jumped to where it should never ever be, this shouldn't be possible, please report this bug"});
2007-10-26 22:44:33 +00:00
}
2009-12-11 08:28:47 +00:00
$SIG{ALRM}= sub { xCAT::MsgUtils->message("S","$$ failed shutting down"); die;};
2008-05-13 23:33:16 +00:00
alarm(10);
2007-10-26 22:44:33 +00:00
foreach (keys %tables) {
$tables{$_}->commit;
}
2008-04-21 15:27:11 +00:00
$sock->close(SSL_fast_shutdown=>1);
2007-10-26 22:44:33 +00:00
if ($timedout == 1) {
printf ("Client timeout");
}
}
2012-03-25 18:10:48 +00:00
sub send_pending_responses {
my $xcatresponse = shift;
my $sock = shift;
my $resp = XMLout($xcatresponse,KeyAttr=>[], NoAttr=>1,KeepRoot=>1);
#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
eval {
2012-05-01 20:00:30 +00:00
my $rsplen = length($resp);
my $blocks = int($rsplen/4096)-1;
if ($rsplen%4096) {
$blocks += 1;
}
foreach (0..$blocks) {
2013-08-16 11:05:32 +00:00
do {
syswrite($sock,$resp,4096,$_*4096);
} while (($! == EAGAIN) or ($! == ECHILD));
2012-05-01 20:00:30 +00:00
}
2012-03-25 18:10:48 +00:00
};
}
2007-10-26 22:44:33 +00:00
sub relay_fds { #Relays file descriptors from pipes to children to the SSL socket
my $fds = shift;
2012-03-25 18:10:48 +00:00
my $replyqueue=shift;
2008-08-11 16:17:16 +00:00
my $goneclient=0;
2007-10-26 22:44:33 +00:00
my $collate = ( scalar @_ > 0 ? shift : 0);
my @readyset = $fds->can_read(1);
my $rfh;
my $rc = @readyset;
my $text;
foreach $rfh (@readyset) { #go through each child, extract a complete, atomic message
my $line;
2011-06-15 18:36:22 +00:00
my $resp;
2013-04-04 20:11:05 +00:00
eval {
$resp = fd_retrieve($rfh);
};
if ($@ and $@ =~ /^Magic number checking on storable file/) { #this most likely means we ran over the end of available input
$fds->remove($rfh);
close($rfh);
} else {
push @$replyqueue,$resp;
print $rfh "nfin\n";
2007-10-26 22:44:33 +00:00
}
}
2008-08-11 16:17:16 +00:00
foreach my $rin ($clientselect->can_read(0)) {
my $subselect = new IO::Select;
$subselect->add($rin);
my $clientintr="";
my $subdata;
while ($subselect->can_read(1)) {
if ($subdata=<$rin>) {
$clientintr.=$subdata;
} else {
$subselect->remove($rin);
close($rin);
}
}
2012-05-01 17:52:55 +00:00
chomp($clientintr);
2008-08-11 16:17:16 +00:00
unless ($clientintr) {
next;
}
$clientintr=XMLin($clientintr, SuppressEmpty=>undef,ForceArray=>1 );
if ($clientintr->{abortcommand}->[0]) {
2012-05-02 19:57:58 +00:00
$pipeexpected=1;
2008-08-11 16:17:16 +00:00
print "Aborting...";
foreach (keys %plugin_children) {
print "Sending INT to $_\n";
2012-12-05 03:04:13 +00:00
kill -15, $_;
2008-08-11 16:17:16 +00:00
}
foreach my $cin ($fds->handles) {
print $cin "die\n";
$fds->remove($cin);
close($cin);
}
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S", "Client abort requested");
2012-05-02 19:57:58 +00:00
exit(0);
2008-08-11 16:17:16 +00:00
}
}
2008-03-10 15:36:44 +00:00
yield; #Give other processes, including children, explicit control, to avoid uselessly aggressive looping
2008-08-11 16:17:16 +00:00
if ($goneclient) {
2009-12-11 08:28:47 +00:00
xCAT::MsgUtils->message("S", "SIGPIPE $$progname encountered a broken pipe (Sudden client disconnect)");
die;
2008-08-11 16:17:16 +00:00
}
2007-10-26 22:44:33 +00:00
return $rc;
}
2011-12-04 13:04:58 +00:00
# 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
2012-03-12 11:54:28 +00:00
# call the subroutine scan_plugins to fill the symbol table
2013-10-24 14:41:48 +00:00
#scan_plugins();
2011-12-04 13:04:58 +00:00
# Backup the trace log
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;
if (-e "/var/log/xcat/subcallingtrace") {
system("mv /var/log/xcat/subcallingtrace /var/log/xcat/subcallingtrace$time");
}
# Start the trace log
xCAT::MsgUtils->start_logging("subcallingtrace");
# Read the subroutine list from the configuration file
if (-f "/tmp/xcatcallingtrace.cfg") {
if (! open (FUNLIST, "</tmp/xcatcallingtrace.cfg")) {
xCAT::MsgUtils->message("SL", "Enable subroutine calling trace failed: cannot open /tmp/xcatcallingtrace.cfg");
xCAT::MsgUtils->stop_logging();
return 1;
}
my $cfg = <FUNLIST>;
chomp($cfg);
my @funlist;
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
while (<CFG>) {
push @funlist, $_;
}
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;
}
# Parse the function list
foreach (@funlist) {
if (/(.*::.*)\((.*)\)/) { # if the format is xCAT::plugin(f1,f2)
my $pkg = $1;
my @funcs = split /,/, $2;
foreach (@funcs) {
chomp;
s/^\s*//;
push @pluginfuncs, "\*".$pkg."::".$_;
}
} else { # if the format is f1,f2, only for the functions in the xcatd
s/^\s*\(//;
s/\)\s*$//;
my @funcs = split /,/;
foreach (@funcs) {
chomp;
s/^\s*//;
push @xcatdfuncs, "\*main::".$_;
}
}
}
close (FUNLIST);
} else {
$enableall = 1;
}
no strict 'refs';
my @debugfuns = ();
# Get the functions of xcatd
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 (<XCATDLINES>) {
if (/^\s*sub\s+([^\s]*)/) {
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
&& 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;
}
}
}
# 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/";
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 = ();
if (-r $module_file) {
open (LINES, "<$module_file") or last;
while (<LINES>) {
if (/^\s*sub\s+([^\s]*)/) {
push @sub_in_pm, $1;
}
}
close (LINES);
}
# Search the symbol from the space of plugin
foreach my $fun (keys %{$plugin->{$xcatplugin}}) {
my $symfun = $plugin->{$xcatplugin}{$fun};
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;
}
}
}
}
}
# return a new subroutine with some debug code to output the trace log
# and calling the original subroutine at the last
sub add_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 "Arguments: \n$args\n";
print $::LOG_FILE_HANDLE "Calling stack: \n $callstack\n";
&$orig;
};
}
# Replace the original subroutine with a trace log added one
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 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";
}
}
print $::LOG_FILE_HANDLE "####################################################\n";
}
# Go through all the trace log added subroutines, replace it with the original one
sub disable_callingtrace {
no strict 'refs';
print $::LOG_FILE_HANDLE "##########Disabled the calling trace for: ##########\n" if ($::LOG_FILE_HANDLE);
foreach my $glob (keys %::DEBUG_FUN) {
if (defined $::DEBUG_FUN{$glob}{'orig'}) {
*{"$glob"} = $::DEBUG_FUN{$glob}{'orig'};
2012-03-12 11:54:28 +00:00
print $::LOG_FILE_HANDLE "$glob\n" if ($::LOG_FILE_HANDLE);
2011-12-04 13:04:58 +00:00
}
}
print $::LOG_FILE_HANDLE "####################################################\n" if ($::LOG_FILE_HANDLE);
xCAT::MsgUtils->stop_logging();
}