From fe8752991bb49c5c910a098f799f6bccfd77ca4f Mon Sep 17 00:00:00 2001 From: phamt Date: Fri, 4 May 2012 14:45:17 +0000 Subject: [PATCH] Synched up 2.7 branch with trunk for xCAT-UI and zVM plugin. git-svn-id: https://svn.code.sf.net/p/xcat/code/xcat-core/branches/2.7@12528 8638fb3e-16cb-4fca-ae20-7b5d299a9bcd --- perl-xCAT/xCAT/zvmCPUtils.pm | 652 +-- perl-xCAT/xCAT/zvmUtils.pm | 1289 +++-- xCAT-UI/configure.php | 4 +- xCAT-UI/css/login.css | 10 +- xCAT-UI/css/style.css | 118 +- xCAT-UI/debian/dirs | 1 + xCAT-UI/debian/install | 2 + xCAT-UI/debian/links | 2 + xCAT-UI/debian/postinst | 8 +- xCAT-UI/debian/prerm | 8 +- xCAT-UI/debian/rules | 4 +- xCAT-UI/ganglianode.php | 64 +- xCAT-UI/help.php | 4 +- xCAT-UI/index.php | 4 +- xCAT-UI/js/configure/configure.js | 728 ++- xCAT-UI/js/configure/discover.js | 560 +- xCAT-UI/js/configure/service.js | 525 ++ xCAT-UI/js/configure/update.js | 487 +- xCAT-UI/js/custom/blade.js | 1373 +++-- xCAT-UI/js/custom/customUtils.js | 845 ++- xCAT-UI/js/custom/esx.js | 1066 ++-- xCAT-UI/js/custom/hmc.js | 1887 +++---- xCAT-UI/js/custom/ipmi.js | 1351 +++-- xCAT-UI/js/custom/kvm.js | 1070 ++-- xCAT-UI/js/custom/zvm.js | 3253 +++++------ xCAT-UI/js/custom/zvmUtils.js | 6898 ++++++++++++++--------- xCAT-UI/js/help/help.js | 38 +- xCAT-UI/js/monitor/gangliamon.js | 832 ++- xCAT-UI/js/monitor/monitor.js | 596 +- xCAT-UI/js/monitor/rmcmon.js | 1721 +++--- xCAT-UI/js/monitor/xcatmon.js | 688 +-- xCAT-UI/js/nodes/mtm.js | 70 +- xCAT-UI/js/nodes/nodes.js | 5103 ++++++++--------- xCAT-UI/js/nodes/nodeset.js | 656 ++- xCAT-UI/js/nodes/physical.js | 1739 +++--- xCAT-UI/js/nodes/rnetboot.js | 356 +- xCAT-UI/js/nodes/updatenode.js | 732 ++- xCAT-UI/js/provision/images.js | 2185 ++++--- xCAT-UI/js/provision/provision.js | 264 +- xCAT-UI/js/rcons/rcons.js | 522 +- xCAT-UI/js/service/service.js | 3191 ++++++----- xCAT-UI/js/service/utils.js | 543 +- xCAT-UI/js/srv_xcatauth.js | 102 +- xCAT-UI/js/ui.js | 1554 +++-- xCAT-UI/js/xcatauth.js | 127 +- xCAT-UI/lib/cmd.php | 62 +- xCAT-UI/lib/functions.php | 142 +- xCAT-UI/lib/rcons.php | 4 +- xCAT-UI/lib/srv_cmd.php | 48 +- xCAT-UI/lib/srv_functions.php | 446 +- xCAT-UI/lib/srv_log.php | 24 +- xCAT-UI/lib/systemcmd.php | 36 +- xCAT-UI/lib/tabRestore.php | 14 +- xCAT-UI/lib/ui.php | 139 +- xCAT-UI/lib/upload.php | 34 +- xCAT-UI/lib/zCmd.php | 10 +- xCAT-UI/monitor.php | 4 +- xCAT-UI/provision.php | 4 +- xCAT-UI/rcons.php | 30 +- xCAT-UI/service.php | 86 +- xCAT-UI/xCAT-UI.spec | 23 +- xCAT-UI/xcat/plugins/web.pm | 4092 +++++++------- xCAT-UI/xcat/plugins/webportal.pm | 1340 ++--- xCAT-server/lib/xcat/plugins/zvm.pm | 8130 ++++++++++++++------------- 64 files changed, 30211 insertions(+), 27689 deletions(-) create mode 100644 xCAT-UI/debian/links create mode 100644 xCAT-UI/js/configure/service.js diff --git a/perl-xCAT/xCAT/zvmCPUtils.pm b/perl-xCAT/xCAT/zvmCPUtils.pm index 376257746..30bf96ae6 100644 --- a/perl-xCAT/xCAT/zvmCPUtils.pm +++ b/perl-xCAT/xCAT/zvmCPUtils.pm @@ -2,8 +2,8 @@ #------------------------------------------------------- =head1 - - This is a CP utility plugin for z/VM. + + This is a CP utility plugin for z/VM. =cut @@ -18,604 +18,604 @@ use warnings; =head3 getUserId - Description : Get the user ID of a given node - Arguments : Node - Returns : UserID - Example : my $userID = xCAT::zvmCPUtils->getUserId($node); + Description : Get the user ID of a given node + Arguments : Node + Returns : UserID + Example : my $userID = xCAT::zvmCPUtils->getUserId($node); =cut #------------------------------------------------------- sub getUserId { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get user ID using VMCP - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q userid"`; - my @results = split( ' ', $out ); + # Get user ID using VMCP + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q userid"`; + my @results = split( ' ', $out ); - return ( $results[0] ); + return ( $results[0] ); } #------------------------------------------------------- =head3 getHost - Description : Get the z/VM host of a given node - Arguments : Node - Returns : z/VM host - Example : my $host = xCAT::zvmCPUtils->getHost($node); + Description : Get the z/VM host of a given node + Arguments : Node + Returns : z/VM host + Example : my $host = xCAT::zvmCPUtils->getHost($node); =cut #------------------------------------------------------- sub getHost { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get host using VMCP - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q userid"`; - my @results = split( ' ', $out ); - my $host = $results[2]; + # Get host using VMCP + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q userid"`; + my @results = split( ' ', $out ); + my $host = $results[2]; - return ($host); + return ($host); } #------------------------------------------------------- =head3 getPrivileges - Description : Get the privilege class of a given node - Arguments : Node - Returns : Privilege class - Example : my $class = xCAT::zvmCPUtils->getPrivileges($node); + Description : Get the privilege class of a given node + Arguments : Node + Returns : Privilege class + Example : my $class = xCAT::zvmCPUtils->getPrivileges($node); =cut #------------------------------------------------------- sub getPrivileges { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get privilege class - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q priv"`; - my @out = split( '\n', $out ); - $out[1] = xCAT::zvmUtils->trimStr( $out[1] ); - $out[2] = xCAT::zvmUtils->trimStr( $out[2] ); - my $str = " $out[1]\n $out[2]\n"; + # Get privilege class + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q priv"`; + my @out = split( '\n', $out ); + $out[1] = xCAT::zvmUtils->trimStr( $out[1] ); + $out[2] = xCAT::zvmUtils->trimStr( $out[2] ); + my $str = " $out[1]\n $out[2]\n"; - return ($str); + return ($str); } #------------------------------------------------------- =head3 getMemory - Description : Get the memory of a given node - Arguments : Node - Returns : Memory - Example : my $memory = xCAT::zvmCPUtils->getMemory($node); + Description : Get the memory of a given node + Arguments : Node + Returns : Memory + Example : my $memory = xCAT::zvmCPUtils->getMemory($node); =cut #------------------------------------------------------- sub getMemory { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get memory - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual storage"`; - my @out = split( '=', $out ); + # Get memory + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual storage"`; + my @out = split( '=', $out ); - return ( xCAT::zvmUtils->trimStr( $out[1] ) ); + return ( xCAT::zvmUtils->trimStr( $out[1] ) ); } #------------------------------------------------------- =head3 getCpu - Description : Get the processor(s) of a given node - Arguments : Node - Returns : Processor(s) - Example : my $proc = xCAT::zvmCPUtils->getCpu($node); + Description : Get the processor(s) of a given node + Arguments : Node + Returns : Processor(s) + Example : my $proc = xCAT::zvmCPUtils->getCpu($node); =cut #------------------------------------------------------- sub getCpu { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get processors - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual cpus"`; - my $str = xCAT::zvmUtils->tabStr($out); + # Get processors + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual cpus"`; + my $str = xCAT::zvmUtils->tabStr($out); - return ($str); + return ($str); } #------------------------------------------------------- =head3 getNic - Description : Get the network interface card (NIC) of a given node - Arguments : Node - Returns : NIC(s) - Example : my $nic = xCAT::zvmCPUtils->getNic($node); + Description : Get the network interface card (NIC) of a given node + Arguments : Node + Returns : NIC(s) + Example : my $nic = xCAT::zvmCPUtils->getNic($node); =cut #------------------------------------------------------- sub getNic { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get NIC - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual nic"`; - my $str = xCAT::zvmUtils->tabStr($out); + # Get NIC + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual nic"`; + my $str = xCAT::zvmUtils->tabStr($out); - return ($str); + return ($str); } #------------------------------------------------------- =head3 getNetworkNames - Description : Get a list of network names available to a given node - Arguments : Node - Returns : Network names - Example : my $lans = xCAT::zvmCPUtils->getNetworkNames($node); + Description : Get a list of network names available to a given node + Arguments : Node + Returns : Network names + Example : my $lans = xCAT::zvmCPUtils->getNetworkNames($node); =cut #------------------------------------------------------- sub getNetworkNames { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get network names - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan | egrep 'LAN|VSWITCH'"`; - my @lines = split( '\n', $out ); - my @parms; - my $names; - foreach (@lines) { - - # Trim output - $_ = xCAT::zvmUtils->trimStr($_); - @parms = split( ' ', $_ ); - - # Get the network name - if ( $parms[0] eq "LAN" ) { - - # Determine if this network is a hipersocket - # Only hipersocket guest LANs are supported - if ( $_ =~ m/Type: HIPERS/i ) { - $names .= $parms[0] . ":HIPERS " . $parms[1] . " " . $parms[2] . "\n"; - } else { - $names .= $parms[0] . ":QDIO " . $parms[1] . " " . $parms[2] . "\n"; - } - } elsif ( $parms[0] eq "VSWITCH" ) { - $names .= $parms[0] . " " . $parms[1] . " " . $parms[2] . "\n"; - } - } + # Get network names + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan | egrep 'LAN|VSWITCH'"`; + my @lines = split( '\n', $out ); + my @parms; + my $names; + foreach (@lines) { + + # Trim output + $_ = xCAT::zvmUtils->trimStr($_); + @parms = split( ' ', $_ ); + + # Get the network name + if ( $parms[0] eq "LAN" ) { + + # Determine if this network is a hipersocket + # Only hipersocket guest LANs are supported + if ( $_ =~ m/Type: HIPERS/i ) { + $names .= $parms[0] . ":HIPERS " . $parms[1] . " " . $parms[2] . "\n"; + } else { + $names .= $parms[0] . ":QDIO " . $parms[1] . " " . $parms[2] . "\n"; + } + } elsif ( $parms[0] eq "VSWITCH" ) { + $names .= $parms[0] . " " . $parms[1] . " " . $parms[2] . "\n"; + } + } - return ($names); + return ($names); } #------------------------------------------------------- =head3 getNetworkNamesArray - Description : Get an array of network names available to a given node - Arguments : Node - Returns : Array of networks names - Example : my @networks = xCAT::zvmCPUtils->getNetworkNamesArray($node); + Description : Get an array of network names available to a given node + Arguments : Node + Returns : Array of networks names + Example : my @networks = xCAT::zvmCPUtils->getNetworkNamesArray($node); =cut #------------------------------------------------------- sub getNetworkNamesArray { - # Get inputs - my ( $class, $node ) = @_; - my @networks; - my %netHash; - - # Get the networks used by the node - my $out = `ssh $node "vmcp q v nic" | egrep -i "VSWITCH|LAN"`; - my @lines = split( '\n', $out ); - - # Loop through each line - my $line; - my @words; - my $name; - foreach(@lines) { - # Get network name - # Line should contain: MAC: 02-00-01-00-00-12 VSWITCH: SYSTEM VSW1 - $line = xCAT::zvmUtils->trimStr( $_ ); - @words = split( ' ', $line ); - if (@words) { - $name = xCAT::zvmUtils->trimStr( $words[4] ); - - # If network is not 'None' - if ($name ne 'None') { - # Save network - $netHash{$name} = 1; - } - } - } - - # Push networks into array - foreach $name ( keys %netHash ) { - push(@networks, $name); - } - - return @networks; + # Get inputs + my ( $class, $node ) = @_; + my @networks; + my %netHash; + + # Get the networks used by the node + my $out = `ssh $node "vmcp q v nic" | egrep -i "VSWITCH|LAN"`; + my @lines = split( '\n', $out ); + + # Loop through each line + my $line; + my @words; + my $name; + foreach(@lines) { + # Get network name + # Line should contain: MAC: 02-00-01-00-00-12 VSWITCH: SYSTEM VSW1 + $line = xCAT::zvmUtils->trimStr( $_ ); + @words = split( ' ', $line ); + if (@words) { + $name = xCAT::zvmUtils->trimStr( $words[4] ); + + # If network is not 'None' + if ($name ne 'None') { + # Save network + $netHash{$name} = 1; + } + } + } + + # Push networks into array + foreach $name ( keys %netHash ) { + push(@networks, $name); + } + + return @networks; } #------------------------------------------------------- =head3 getNetwork - Description : Get the network info for a given node - Arguments : Node - Network name - Returns : Network configuration - Example : my $config = xCAT::zvmCPUtils->getNetwork($node, $netName); + Description : Get the network info for a given node + Arguments : Node + Network name + Returns : Network configuration + Example : my $config = xCAT::zvmCPUtils->getNetwork($node, $netName); =cut #------------------------------------------------------- sub getNetwork { - # Get inputs - my ( $class, $node, $netName ) = @_; + # Get inputs + my ( $class, $node, $netName ) = @_; - # Get network info - my $out; - if ( $netName eq "all" ) { - $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan"`; - } else { - $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan $netName"`; - } + # Get network info + my $out; + if ( $netName eq "all" ) { + $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan"`; + } else { + $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan $netName"`; + } - return ($out); + return ($out); } #------------------------------------------------------- =head3 getDisks - Description : Get the disk(s) of given node - Arguments : Node - Returns : Disk(s) - Example : my $storage = xCAT::zvmCPUtils->getDisks($node); + Description : Get the disk(s) of given node + Arguments : Node + Returns : Disk(s) + Example : my $storage = xCAT::zvmCPUtils->getDisks($node); =cut #------------------------------------------------------- sub getDisks { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get disks - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual dasd"`; - my $str = xCAT::zvmUtils->tabStr($out); + # Get disks + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q virtual dasd"`; + my $str = xCAT::zvmUtils->tabStr($out); - return ($str); + return ($str); } #------------------------------------------------------- =head3 loadVmcp - Description : Load Linux VMCP module on a given node - Arguments : Node - Returns : Nothing - Example : xCAT::zvmCPUtils->loadVmcp($node); + Description : Load Linux VMCP module on a given node + Arguments : Node + Returns : Nothing + Example : xCAT::zvmCPUtils->loadVmcp($node); =cut #------------------------------------------------------- sub loadVmcp { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Load Linux VMCP module - my $out = `ssh -o ConnectTimeout=5 $node "modprobe vmcp"`; - return; + # Load Linux VMCP module + my $out = `ssh -o ConnectTimeout=5 $node "modprobe vmcp"`; + return; } #------------------------------------------------------- =head3 getVswitchId - Description : Get the VSwitch ID(s) of given node - Arguments : Node - Returns : VSwitch ID(s) - Example : my @vswitch = xCAT::zvmCPUtils->getVswitchId($node); + Description : Get the VSwitch ID(s) of given node + Arguments : Node + Returns : VSwitch ID(s) + Example : my @vswitch = xCAT::zvmCPUtils->getVswitchId($node); =cut #------------------------------------------------------- sub getVswitchId { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get VSwitch - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q v nic" | grep "VSWITCH"`; - my @lines = split( '\n', $out ); - my @parms; - my @vswitch; - foreach (@lines) { - @parms = split( ' ', $_ ); - push( @vswitch, $parms[4] ); - } + # Get VSwitch + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q v nic" | grep "VSWITCH"`; + my @lines = split( '\n', $out ); + my @parms; + my @vswitch; + foreach (@lines) { + @parms = split( ' ', $_ ); + push( @vswitch, $parms[4] ); + } - return @vswitch; + return @vswitch; } #------------------------------------------------------- =head3 grantVSwitch - Description : Grant VSwitch access for a given userID - Arguments : HCP node - User ID - VSWITCH ID - Returns : Operation results (Done/Failed) - Example : my $out = xCAT::zvmCPUtils->grantVswitch($callback, $hcp, $userId, $vswitchId); + Description : Grant VSwitch access for a given userID + Arguments : HCP node + User ID + VSWITCH ID + Returns : Operation results (Done/Failed) + Example : my $out = xCAT::zvmCPUtils->grantVswitch($callback, $hcp, $userId, $vswitchId); =cut #------------------------------------------------------- sub grantVSwitch { - # Get inputs - my ( $class, $callback, $hcp, $userId, $vswitchId ) = @_; + # Get inputs + my ( $class, $callback, $hcp, $userId, $vswitchId ) = @_; - # Grant VSwitch for specified userID - my $out = `ssh $hcp "vmcp set vswitch $vswitchId grant $userId"`; - $out = xCAT::zvmUtils->trimStr($out); + # Grant VSwitch for specified userID + my $out = `ssh $hcp "vmcp set vswitch $vswitchId grant $userId"`; + $out = xCAT::zvmUtils->trimStr($out); - # If return string contains 'Command complete' - Operation was successful - my $retStr; - if ( $out =~ m/Command complete/i ) { - $retStr = "Done\n"; - } else { - $retStr = "Failed\n"; - return $retStr; - } + # If return string contains 'Command complete' - Operation was successful + my $retStr; + if ( $out =~ m/Command complete/i ) { + $retStr = "Done\n"; + } else { + $retStr = "Failed\n"; + return $retStr; + } - return $retStr; + return $retStr; } #------------------------------------------------------- =head3 flashCopy - Description : Flash copy (Class B users only) - Arguments : Node - Source address - Target address - Returns : Operation results (Done/Failed) - Example : my $results = xCAT::zvmCPUtils->flashCopy($node, $srcAddr, $targetAddr); + Description : Flash copy (Class B users only) + Arguments : Node + Source address + Target address + Returns : Operation results (Done/Failed) + Example : my $results = xCAT::zvmCPUtils->flashCopy($node, $srcAddr, $targetAddr); =cut #------------------------------------------------------- sub flashCopy { - # Get inputs - my ( $class, $node, $srcAddr, $tgtAddr ) = @_; + # Get inputs + my ( $class, $node, $srcAddr, $tgtAddr ) = @_; - # Flash copy - my $out = `ssh $node "vmcp flashcopy $srcAddr 0 end to $tgtAddr 0 end synchronous"`; - $out = xCAT::zvmUtils->trimStr($out); + # Flash copy + my $out = `ssh $node "vmcp flashcopy $srcAddr 0 end to $tgtAddr 0 end synchronous"`; + $out = xCAT::zvmUtils->trimStr($out); - # If return string contains 'Command complete' - Operation was successful - my $retStr = ""; - if ( $out =~ m/Command complete/i ) { - $retStr = "Done\n"; - } else { - $out = xCAT::zvmUtils->tabStr($out); - $retStr = "Failed\n$out"; - } + # If return string contains 'Command complete' - Operation was successful + my $retStr = ""; + if ( $out =~ m/Command complete/i ) { + $retStr = "Done\n"; + } else { + $out = xCAT::zvmUtils->tabStr($out); + $retStr = "Failed\n$out"; + } - return $retStr; + return $retStr; } #------------------------------------------------------- =head3 punch2Reader - Description : Write file to z/VM punch and transfer it to reader - Arguments : HCP node - UserID to receive file - Source file - Target file to be created by punch (e.g. sles.parm) - Options, e.g. -t (Convert EBCDIC to ASCII) - Returns : Operation results (Done/Failed) - Example : my $rc = xCAT::zvmCPUtils->punch2Reader($hcp, $userId, $srcFile, $tgtFile, $options); + Description : Write file to z/VM punch and transfer it to reader + Arguments : HCP node + UserID to receive file + Source file + Target file to be created by punch (e.g. sles.parm) + Options, e.g. -t (Convert EBCDIC to ASCII) + Returns : Operation results (Done/Failed) + Example : my $rc = xCAT::zvmCPUtils->punch2Reader($hcp, $userId, $srcFile, $tgtFile, $options); =cut #------------------------------------------------------- sub punch2Reader { - my ( $class, $hcp, $userId, $srcFile, $tgtFile, $options ) = @_; + my ( $class, $hcp, $userId, $srcFile, $tgtFile, $options ) = @_; - # Punch to reader - my $out = `ssh -o ConnectTimeout=5 $hcp "vmur punch $options -u $userId -r $srcFile -N $tgtFile"`; + # Punch to reader + my $out = `ssh -o ConnectTimeout=5 $hcp "vmur punch $options -u $userId -r $srcFile -N $tgtFile"`; - # If punch is successful -- Look for this string - my $searchStr = "created and transferred"; - if ( !( $out =~ m/$searchStr/i ) ) { - $out = "Failed\n"; - } else { - $out = "Done\n"; - } + # If punch is successful -- Look for this string + my $searchStr = "created and transferred"; + if ( !( $out =~ m/$searchStr/i ) ) { + $out = "Failed\n"; + } else { + $out = "Done\n"; + } - return $out; + return $out; } #------------------------------------------------------- =head3 purgeReader - Description : Purge reader (Class D users only) - Arguments : HCP node - UserID to purge reader - Returns : Nothing - Example : my $rc = xCAT::zvmCPUtils->purgeReader($hcp, $userId); + Description : Purge reader (Class D users only) + Arguments : HCP node + UserID to purge reader + Returns : Nothing + Example : my $rc = xCAT::zvmCPUtils->purgeReader($hcp, $userId); =cut #------------------------------------------------------- sub purgeReader { - my ( $class, $hcp, $userId ) = @_; + my ( $class, $hcp, $userId ) = @_; - # Purge reader - my $out = `ssh -o ConnectTimeout=5 $hcp "vmcp purge $userId rdr all"`; + # Purge reader + my $out = `ssh -o ConnectTimeout=5 $hcp "vmcp purge $userId rdr all"`; - return; + return; } #------------------------------------------------------- =head3 sendCPCmd - Description : Send CP command to a given userID (Class C users only) - Arguments : HCP node - UserID to send CP command - Returns : Nothing - Example : xCAT::zvmCPUtils->sendCPCmd($hcp, $userId, $cmd); + Description : Send CP command to a given userID (Class C users only) + Arguments : HCP node + UserID to send CP command + Returns : Nothing + Example : xCAT::zvmCPUtils->sendCPCmd($hcp, $userId, $cmd); =cut #------------------------------------------------------- sub sendCPCmd { - my ( $class, $hcp, $userId, $cmd ) = @_; + my ( $class, $hcp, $userId, $cmd ) = @_; - # Send CP command to given userID - my $out = `ssh $hcp "vmcp send cp $userId $cmd"`; + # Send CP command to given userID + my $out = `ssh $hcp "vmcp send cp $userId $cmd"`; - return; + return; } #------------------------------------------------------- =head3 getNetworkLayer - Description : Get the network layer for a given node - Arguments : Node - Network name - Returns : 2 - Layer 2 - 3 - Layer 3 - -1 - Failed to get network layer - Example : my $layer = xCAT::zvmCPUtils->getNetworkLayer($node); + Description : Get the network layer for a given node + Arguments : Node + Network name + Returns : 2 - Layer 2 + 3 - Layer 3 + -1 - Failed to get network layer + Example : my $layer = xCAT::zvmCPUtils->getNetworkLayer($node); =cut #------------------------------------------------------- sub getNetworkLayer { - my ( $class, $node, $netName ) = @_; + my ( $class, $node, $netName ) = @_; - # Exit if the network name is not given - if ( !$netName ) { - return -1; - } + # Exit if the network name is not given + if ( !$netName ) { + return -1; + } - # Get network type (Layer 2 or 3) - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan $netName"`; - if ( !$out ) { - return -1; - } + # Get network type (Layer 2 or 3) + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q lan $netName"`; + if ( !$out ) { + return -1; + } - # Go through each line - my $layer = 3; # Default to layer 3 - my @lines = split( '\n', $out ); - foreach (@lines) { + # Go through each line + my $layer = 3; # Default to layer 3 + my @lines = split( '\n', $out ); + foreach (@lines) { - # If the line contains ETHERNET, then it is a layer 2 network - if ( $_ =~ m/ETHERNET/i ) { - $layer = 2; - } - } + # If the line contains ETHERNET, then it is a layer 2 network + if ( $_ =~ m/ETHERNET/i ) { + $layer = 2; + } + } - return $layer; + return $layer; } #------------------------------------------------------- =head3 getNetworkType - Description : Get the network type of a given network - Arguments : HCP node - Name of network - Returns : Network type (VSWITCH/HIPERS/QDIO) - Example : my $netType = xCAT::zvmCPUtils->getNetworkType($hcp, $netName); + Description : Get the network type of a given network + Arguments : HCP node + Name of network + Returns : Network type (VSWITCH/HIPERS/QDIO) + Example : my $netType = xCAT::zvmCPUtils->getNetworkType($hcp, $netName); =cut #------------------------------------------------------- sub getNetworkType { - my ( $class, $hcp, $netName ) = @_; + my ( $class, $hcp, $netName ) = @_; - # Get network details - my $out = `ssh -o ConnectTimeout=5 $hcp "vmcp q lan $netName" | grep "Type"`; + # Get network details + my $out = `ssh -o ConnectTimeout=5 $hcp "vmcp q lan $netName" | grep "Type"`; - # Go through each line and determine network type - my @lines = split( '\n', $out ); - my $netType = ""; - foreach (@lines) { + # Go through each line and determine network type + my @lines = split( '\n', $out ); + my $netType = ""; + foreach (@lines) { - # Virtual switch - if ( $_ =~ m/VSWITCH/i ) { - $netType = "VSWITCH"; - } + # Virtual switch + if ( $_ =~ m/VSWITCH/i ) { + $netType = "VSWITCH"; + } - # HiperSocket guest LAN - elsif ( $_ =~ m/HIPERS/i ) { - $netType = "HIPERS"; - } + # HiperSocket guest LAN + elsif ( $_ =~ m/HIPERS/i ) { + $netType = "HIPERS"; + } - # QDIO guest LAN - elsif ( $_ =~ m/QDIO/i ) { - $netType = "QDIO"; - } - } + # QDIO guest LAN + elsif ( $_ =~ m/QDIO/i ) { + $netType = "QDIO"; + } + } - return $netType; + return $netType; } #------------------------------------------------------- =head3 defineCpu - Description : Add processor(s) to given node - Arguments : Node - Returns : Nothing - Example : my $out = xCAT::zvmCPUtils->defineCpu($node, $addr, $type); + Description : Add processor(s) to given node + Arguments : Node + Returns : Nothing + Example : my $out = xCAT::zvmCPUtils->defineCpu($node, $addr, $type); =cut #------------------------------------------------------- sub defineCpu { - # Get inputs - my ( $class, $node, $addr, $type ) = @_; + # Get inputs + my ( $class, $node, $addr, $type ) = @_; - # Define processor(s) - my $out = `ssh -o ConnectTimeout=5 $node "vmcp define cpu $addr type $type"`; + # Define processor(s) + my $out = `ssh -o ConnectTimeout=5 $node "vmcp define cpu $addr type $type"`; - return ($out); + return ($out); } diff --git a/perl-xCAT/xCAT/zvmUtils.pm b/perl-xCAT/xCAT/zvmUtils.pm index aeaf711d8..4a2980e68 100644 --- a/perl-xCAT/xCAT/zvmUtils.pm +++ b/perl-xCAT/xCAT/zvmUtils.pm @@ -3,7 +3,7 @@ =head1 - This is a utility plugin for z/VM. + This is a utility plugin for z/VM. =cut @@ -19,1130 +19,1173 @@ use warnings; #------------------------------------------------------- =head3 getNodeProps - Description : Get node properties - Arguments : Table - Node - Properties - Returns : Node properties from given table - Example : my $propVals = xCAT::zvmUtils->getNodeProps($tabName, $node, $propNames); + Description : Get node properties + Arguments : Table + Node + Properties + Returns : Node properties from given table + Example : my $propVals = xCAT::zvmUtils->getNodeProps($tabName, $node, $propNames); =cut #------------------------------------------------------- sub getNodeProps { - # Get inputs - my ( $class, $tabName, $node, @propNames ) = @_; + # Get inputs + my ( $class, $tabName, $node, @propNames ) = @_; - # Get table - my $tab = xCAT::Table->new($tabName); + # Get table + my $tab = xCAT::Table->new($tabName); - # Get property values - my $propVals = $tab->getNodeAttribs( $node, [@propNames] ); + # Get property values + my $propVals = $tab->getNodeAttribs( $node, [@propNames] ); - return ($propVals); + return ($propVals); } #------------------------------------------------------- =head3 getTabPropsByKey - Description : Get table entry properties by key - Arguments : Table - Key name - Key value - Requested properties - Returns : Table entry properties - Example : my $propVals = xCAT::zvmUtils->getTabPropsByKey($tabName, $key, $keyValue, @reqProps); + Description : Get table entry properties by key + Arguments : Table + Key name + Key value + Requested properties + Returns : Table entry properties + Example : my $propVals = xCAT::zvmUtils->getTabPropsByKey($tabName, $key, $keyValue, @reqProps); =cut #------------------------------------------------------- sub getTabPropsByKey { - # Get inputs - my ( $class, $tabName, $key, $keyVal, @propNames ) = @_; + # Get inputs + my ( $class, $tabName, $key, $keyVal, @propNames ) = @_; - # Get table - my $tab = xCAT::Table->new($tabName); - my $propVals; + # Get table + my $tab = xCAT::Table->new($tabName); + my $propVals; - # Get table attributes matching given key - $propVals = $tab->getAttribs( { $key => $keyVal }, @propNames ); - return ($propVals); + # Get table attributes matching given key + $propVals = $tab->getAttribs( { $key => $keyVal }, @propNames ); + return ($propVals); } #------------------------------------------------------- =head3 getAllTabEntries - Description : Get all entries within given table - Arguments : Table name - Returns : All table entries - Example : my $entries = xCAT::zvmUtils->getAllTabEntries($tabName); + Description : Get all entries within given table + Arguments : Table name + Returns : All table entries + Example : my $entries = xCAT::zvmUtils->getAllTabEntries($tabName); =cut #------------------------------------------------------- sub getAllTabEntries { - # Get inputs - my ( $class, $tabName ) = @_; + # Get inputs + my ( $class, $tabName ) = @_; - # Get table - my $tab = xCAT::Table->new($tabName); - my $entries; + # Get table + my $tab = xCAT::Table->new($tabName); + my $entries; - # Get all entries within given table - $entries = $tab->getAllEntries(); - return ($entries); + # Get all entries within given table + $entries = $tab->getAllEntries(); + return ($entries); } #------------------------------------------------------- =head3 setNodeProp - Description : Set a node property in a given table - Arguments : Table - Node - Property name - Property value - Returns : Nothing - Example : xCAT::zvmUtils->setNodeProp($tabName, $node, $propName, $propVal); + Description : Set a node property in a given table + Arguments : Table + Node + Property name + Property value + Returns : Nothing + Example : xCAT::zvmUtils->setNodeProp($tabName, $node, $propName, $propVal); =cut #------------------------------------------------------- sub setNodeProp { - # Get inputs - my ( $class, $tabName, $node, $propName, $propVal ) = @_; + # Get inputs + my ( $class, $tabName, $node, $propName, $propVal ) = @_; - # Get table - my $tab = xCAT::Table->new( $tabName, -create => 1, -autocommit => 0 ); + # Get table + my $tab = xCAT::Table->new( $tabName, -create => 1, -autocommit => 0 ); - # Set property - $tab->setAttribs( { 'node' => $node }, { $propName => $propVal } ); + # Set property + $tab->setAttribs( { 'node' => $node }, { $propName => $propVal } ); - # Save table - $tab->commit; + # Save table + $tab->commit; - return; + return; } #------------------------------------------------------- =head3 setNodeProps - Description : Set node properties in a given table - Arguments : Table - Node - Reference to property name/value hash - Returns : Nothing - Example : xCAT::zvmUtils->setNodeProps($tabName, $node, \%propHash); + Description : Set node properties in a given table + Arguments : Table + Node + Reference to property name/value hash + Returns : Nothing + Example : xCAT::zvmUtils->setNodeProps($tabName, $node, \%propHash); =cut #------------------------------------------------------- sub setNodeProps { - # Get inputs - my ( $class, $tabName, $node, $propHash ) = @_; + # Get inputs + my ( $class, $tabName, $node, $propHash ) = @_; - # Get table - my $tab = xCAT::Table->new( $tabName, -create => 1, -autocommit => 0 ); + # Get table + my $tab = xCAT::Table->new( $tabName, -create => 1, -autocommit => 0 ); - # Set property - $tab->setAttribs( { 'node' => $node }, $propHash ); + # Set property + $tab->setAttribs( { 'node' => $node }, $propHash ); - # Save table - $tab->commit; + # Save table + $tab->commit; - return; + return; } #------------------------------------------------------- =head3 delTabEntry - Description : Delete a table entry - Arguments : Table - Key name - Key value - Returns : Nothing - Example : xCAT::zvmUtils->delTabEntry($tabName, $keyName, $keyVal); + Description : Delete a table entry + Arguments : Table + Key name + Key value + Returns : Nothing + Example : xCAT::zvmUtils->delTabEntry($tabName, $keyName, $keyVal); =cut #------------------------------------------------------- sub delTabEntry { - # Get inputs - my ( $class, $tabName, $keyName, $keyVal ) = @_; + # Get inputs + my ( $class, $tabName, $keyName, $keyVal ) = @_; - # Get table - my $tab = xCAT::Table->new( $tabName, -create => 1, -autocommit => 0 ); + # Get table + my $tab = xCAT::Table->new( $tabName, -create => 1, -autocommit => 0 ); - # Delete entry from table - my %key = ( $keyName => $keyVal ); - $tab->delEntries( \%key ); + # Delete entry from table + my %key = ( $keyName => $keyVal ); + $tab->delEntries( \%key ); - # Save table - $tab->commit; + # Save table + $tab->commit; - return; + return; } #------------------------------------------------------- =head3 tabStr - Description : Tab a string (4 spaces) - Arguments : String - Returns : Tabbed string - Example : my $str = xCAT::zvmUtils->tabStr($str); + Description : Tab a string (4 spaces) + Arguments : String + Returns : Tabbed string + Example : my $str = xCAT::zvmUtils->tabStr($str); =cut #------------------------------------------------------- sub tabStr { - # Get inputs - my ( $class, $inStr ) = @_; - my @lines = split( "\n", $inStr ); + # Get inputs + my ( $class, $inStr ) = @_; + my @lines = split( "\n", $inStr ); - # Tab output - my $outStr; - foreach (@lines) { - $outStr .= " $_\n"; - } + # Tab output + my $outStr; + foreach (@lines) { + $outStr .= " $_\n"; + } - return ($outStr); + return ($outStr); } #------------------------------------------------------- =head3 trimStr - Description : Trim the whitespaces in a string - Arguments : String - Returns : Trimmed string - Example : my $str = xCAT::zvmUtils->trimStr($str); + Description : Trim the whitespaces in a string + Arguments : String + Returns : Trimmed string + Example : my $str = xCAT::zvmUtils->trimStr($str); =cut #------------------------------------------------------- sub trimStr { - # Get string - my ( $class, $str ) = @_; + # Get string + my ( $class, $str ) = @_; - # Trim right - $str =~ s/\s*$//; + # Trim right + $str =~ s/\s*$//; - # Trim left - $str =~ s/^\s*//; + # Trim left + $str =~ s/^\s*//; - return ($str); + return ($str); } #------------------------------------------------------- =head3 replaceStr - Description : Replace a given pattern in a string - Arguments : String - Returns : New string - Example : my $str = xCAT::zvmUtils->replaceStr($str, $pattern, $replacement); + Description : Replace a given pattern in a string + Arguments : String + Returns : New string + Example : my $str = xCAT::zvmUtils->replaceStr($str, $pattern, $replacement); =cut #------------------------------------------------------- sub replaceStr { - # Get string - my ( $class, $str, $pattern, $replacement ) = @_; + # Get string + my ( $class, $str, $pattern, $replacement ) = @_; - # Replace string - $str =~ s/$pattern/$replacement/g; + # Replace string + $str =~ s/$pattern/$replacement/g; - return ($str); + return ($str); } #------------------------------------------------------- =head3 printLn - Description : Print a string to stdout - Arguments : String - Returns : Nothing - Example : xCAT::zvmUtils->printLn($callback, $str); + Description : Print a string to stdout + Arguments : String + Returns : Nothing + Example : xCAT::zvmUtils->printLn($callback, $str); =cut #------------------------------------------------------- sub printLn { - # Get inputs - my ( $class, $callback, $str ) = @_; + # Get inputs + my ( $class, $callback, $str ) = @_; - # Print string - my $rsp; - $rsp->{data}->[0] = "$str"; - xCAT::MsgUtils->message( "I", $rsp, $callback ); + # Print string + my $rsp; + $rsp->{data}->[0] = "$str"; + xCAT::MsgUtils->message( "I", $rsp, $callback ); - return; + return; } #------------------------------------------------------- =head3 isZvmNode - Description : Determines if a given node is in the 'zvm' table - Arguments : Node - Returns : TRUE Node exists - FALSE Node does not exists - Example : my $out = xCAT::zvmUtils->isZvmNode($node); + Description : Determines if a given node is in the 'zvm' table + Arguments : Node + Returns : TRUE Node exists + FALSE Node does not exists + Example : my $out = xCAT::zvmUtils->isZvmNode($node); =cut #------------------------------------------------------- sub isZvmNode { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # zVM guest ID - my $id; + # zVM guest ID + my $id; - # Look in 'zvm' table - my $tab = xCAT::Table->new( 'zvm', -create => 1, -autocommit => 0 ); + # Look in 'zvm' table + my $tab = xCAT::Table->new( 'zvm', -create => 1, -autocommit => 0 ); - my @results = $tab->getAllAttribsWhere( "node like '%" . $node . "%'", 'userid' ); - foreach (@results) { + my @results = $tab->getAllAttribsWhere( "node like '%" . $node . "%'", 'userid' ); + foreach (@results) { - # Get userID - $id = $_->{'userid'}; + # Get userID + $id = $_->{'userid'}; - # Return 'TRUE' if given node is in the table - if ($id) { - return ('TRUE'); - } - } + # Return 'TRUE' if given node is in the table + if ($id) { + return ('TRUE'); + } + } - return ('FALSE'); + return ('FALSE'); } #------------------------------------------------------- =head3 getHwcfg - Description : Get the hardware configuration file path (SUSE only) - e.g. /etc/sysconfig/hardwarehwcfg-qeth-bus-ccw-0.0.0600 - Arguments : Node - Returns : Hardware configuration file path - Example : my $hwcfg = xCAT::zvmUtils->getHwcfg($node); + Description : Get the hardware configuration file path (SUSE only) + e.g. /etc/sysconfig/hardwarehwcfg-qeth-bus-ccw-0.0.0600 + Arguments : Node + Returns : Hardware configuration file path + Example : my $hwcfg = xCAT::zvmUtils->getHwcfg($node); =cut #------------------------------------------------------- sub getHwcfg { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get OS - my $os = xCAT::zvmUtils->getOs($node); + # Get OS + my $os = xCAT::zvmUtils->getOs($node); - # Get network configuration file path - my $out; - my @parms; + # Get network configuration file path + my $out; + my @parms; - # If it is SUSE - hwcfg-qeth file is in /etc/sysconfig/hardware - if ( $os =~ m/SUSE/i ) { - $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/hardware/hwcfg-qeth*"`; - @parms = split( '\n', $out ); - return ( $parms[0] ); - } + # If it is SUSE - hwcfg-qeth file is in /etc/sysconfig/hardware + if ( $os =~ m/SUSE/i ) { + $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/hardware/hwcfg-qeth*"`; + @parms = split( '\n', $out ); + return ( $parms[0] ); + } - # If no file is found - Return nothing - return; + # If no file is found - Return nothing + return; } #------------------------------------------------------- =head3 getIp - Description : Get the IP address of a given node - Arguments : Node - Returns : IP address of given node - Example : my $ip = xCAT::zvmUtils->getIp($node); + Description : Get the IP address of a given node + Arguments : Node + Returns : IP address of given node + Example : my $ip = xCAT::zvmUtils->getIp($node); =cut #------------------------------------------------------- sub getIp { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get IP address - # You need the extra space in the pattern, - # else it will confuse gpok2 with gpok21 - my $out = `cat /etc/hosts | grep "$node "`; - my @parms = split( ' ', $out ); + # Get IP address + # You need the extra space in the pattern, + # else it will confuse gpok2 with gpok21 + my $out = `cat /etc/hosts | grep "$node "`; + my @parms = split( ' ', $out ); - return $parms[0]; + return $parms[0]; } #------------------------------------------------------- =head3 getIfcfg - Description : Get the network configuration file path of a given node - * Red Hat - /etc/sysconfig/network-scripts/ifcfg-eth - * SUSE - /etc/sysconfig/network/ifcfg-qeth - Arguments : Node - Returns : Network configuration file path - Example : my $ifcfg = xCAT::zvmUtils->getIfcfg($node); + Description : Get the network configuration file path of a given node + * Red Hat - /etc/sysconfig/network-scripts/ifcfg-eth + * SUSE - /etc/sysconfig/network/ifcfg-qeth + Arguments : Node + Returns : Network configuration file path + Example : my $ifcfg = xCAT::zvmUtils->getIfcfg($node); =cut #------------------------------------------------------- sub getIfcfg { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get OS - my $os = xCAT::zvmUtils->getOs($node); + # Get OS + my $os = xCAT::zvmUtils->getOs($node); - # Get network configuration file path - my $out; - my @parms; + # Get network configuration file path + my $out; + my @parms; - # If it is Red Hat - ifcfg-qeth file is in /etc/sysconfig/network-scripts - if ( $os =~ m/Red Hat/i ) { - $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network-scripts/ifcfg-eth*"`; - @parms = split( '\n', $out ); - return ( $parms[0] ); - } + # If it is Red Hat - ifcfg-qeth file is in /etc/sysconfig/network-scripts + if ( $os =~ m/Red Hat/i ) { + $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network-scripts/ifcfg-eth*"`; + @parms = split( '\n', $out ); + return ( $parms[0] ); + } - # If it is SUSE - ifcfg-qeth file is in /etc/sysconfig/network - elsif ( $os =~ m/SUSE/i ) { - $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network/ifcfg-qeth*"`; - @parms = split( '\n', $out ); - return ( $parms[0] ); - } + # If it is SUSE - ifcfg-qeth file is in /etc/sysconfig/network + elsif ( $os =~ m/SUSE/i ) { + $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network/ifcfg-qeth*"`; + @parms = split( '\n', $out ); + return ( $parms[0] ); + } - # If no file is found - Return nothing - return; + # If no file is found - Return nothing + return; } #------------------------------------------------------- =head3 getIfcfgByNic - Description : Get the network configuration file path of a given node - Arguments : Node - NIC address - Returns : Network configuration file path - Example : my $ifcfg = xCAT::zvmUtils->getIfcfgByNic($node, $nic); + Description : Get the network configuration file path of a given node + Arguments : Node + NIC address + Returns : Network configuration file path + Example : my $ifcfg = xCAT::zvmUtils->getIfcfgByNic($node, $nic); =cut #------------------------------------------------------- sub getIfcfgByNic { - # Get inputs - my ( $class, $node, $nic ) = @_; + # Get inputs + my ( $class, $node, $nic ) = @_; - # Get OS - my $os = xCAT::zvmUtils->getOs($node); + # Get OS + my $os = xCAT::zvmUtils->getOs($node); - # Get network configuration file path - my $out; - my @parms; + # Get network configuration file path + my $out; + my @parms; - # If it is Red Hat - ifcfg-qeth file is in /etc/sysconfig/network-scripts - if ( $os =~ m/Red Hat/i ) { - $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network-scripts/ifcfg-eth*"`; - @parms = split( '\n', $out ); + # If it is Red Hat - ifcfg-qeth file is in /etc/sysconfig/network-scripts + if ( $os =~ m/Red Hat/i ) { + $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network-scripts/ifcfg-eth*"`; + @parms = split( '\n', $out ); - # Go through each line - foreach (@parms) { + # Go through each line + foreach (@parms) { - # If the network file contains the NIC address - $out = `ssh -o ConnectTimeout=5 $node "cat $_" | grep "$nic"`; - if ($out) { + # If the network file contains the NIC address + $out = `ssh -o ConnectTimeout=5 $node "cat $_" | grep "$nic"`; + if ($out) { - # Return network file path - return ($_); - } - } - } + # Return network file path + return ($_); + } + } + } - # If it is SLES 10 - ifcfg-qeth file is in /etc/sysconfig/network - elsif ( $os =~ m/SUSE Linux Enterprise Server 10/i ) { - $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network/ifcfg-qeth*" | grep -i "$nic"`; - @parms = split( '\n', $out ); - return ( $parms[0] ); - } + # If it is SLES 10 - ifcfg-qeth file is in /etc/sysconfig/network + elsif ( $os =~ m/SUSE Linux Enterprise Server 10/i ) { + $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network/ifcfg-qeth*" | grep -i "$nic"`; + @parms = split( '\n', $out ); + return ( $parms[0] ); + } - # If it is SLES 11 - ifcfg-qeth file is in /etc/sysconfig/network - elsif ( $os =~ m/SUSE Linux Enterprise Server 11/i ) { + # If it is SLES 11 - ifcfg-qeth file is in /etc/sysconfig/network + elsif ( $os =~ m/SUSE Linux Enterprise Server 11/i ) { - # Get a list of ifcfg-eth files found - $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network/ifcfg-eth*"`; - my @file = split( '\n', $out ); + # Get a list of ifcfg-eth files found + $out = `ssh -o ConnectTimeout=5 $node "ls /etc/sysconfig/network/ifcfg-eth*"`; + my @file = split( '\n', $out ); - # Go through each ifcfg-eth file - foreach (@file) { + # Go through each ifcfg-eth file + foreach (@file) { - # If the network file contains the NIC address - $out = `ssh -o ConnectTimeout=5 $node "cat $_" | grep -i "$nic"`; - if ($out) { + # If the network file contains the NIC address + $out = `ssh -o ConnectTimeout=5 $node "cat $_" | grep -i "$nic"`; + if ($out) { - # Return ifcfg-eth file path - return ($_); - } - } - } + # Return ifcfg-eth file path + return ($_); + } + } + } - # If no file is found - Return nothing - return; + # If no file is found - Return nothing + return; } #------------------------------------------------------- =head3 sendFile - Description : SCP a file to a given node - Arguments : Node - Source file - Target file - Returns : Nothing - Example : xCAT::zvmUtils->sendFile($node, $srcFile, $trgtFile); + Description : SCP a file to a given node + Arguments : Node + Source file + Target file + Returns : Nothing + Example : xCAT::zvmUtils->sendFile($node, $srcFile, $trgtFile); =cut #------------------------------------------------------- sub sendFile { - # Get inputs - my ( $class, $node, $srcFile, $trgtFile ) = @_; + # Get inputs + my ( $class, $node, $srcFile, $trgtFile ) = @_; - # Create destination string - my $dest = "root@" . $node; + # Create destination string + my $dest = "root@" . $node; - # SCP directory entry file over to HCP - my $out = `scp $srcFile $dest:$trgtFile`; + # SCP directory entry file over to HCP + my $out = `scp $srcFile $dest:$trgtFile`; - return; + return; } #------------------------------------------------------- =head3 getRootDeviceAddr - Description : Get the root device address of a given node - Arguments : Node - Returns : Root device address - Example : my $deviceAddr = xCAT::zvmUtils->getRootDeviceAddr($node); + Description : Get the root device address of a given node + Arguments : Node + Returns : Root device address + Example : my $deviceAddr = xCAT::zvmUtils->getRootDeviceAddr($node); =cut #------------------------------------------------------- sub getRootDeviceAddr { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get the root device node - # LVM is not supported - my $out = `ssh $node "mount" | grep "/ type" | sed 's/1//'`; - my @parms = split( " ", $out ); - @parms = split( "/", xCAT::zvmUtils->trimStr( $parms[0] ) ); - my $devNode = $parms[0]; + # Get the root device node + # LVM is not supported + my $out = `ssh $node "mount" | grep "/ type" | sed 's/1//'`; + my @parms = split( " ", $out ); + @parms = split( "/", xCAT::zvmUtils->trimStr( $parms[0] ) ); + my $devNode = $parms[0]; - # Get disk address - $out = `ssh $node "cat /proc/dasd/devices" | grep "$devNode" | sed 's/(ECKD)//' | sed 's/(FBA )//' | sed 's/0.0.//'`; - @parms = split( " ", $out ); - return ( $parms[0] ); + # Get disk address + $out = `ssh $node "cat /proc/dasd/devices" | grep "$devNode" | sed 's/(ECKD)//' | sed 's/(FBA )//' | sed 's/0.0.//'`; + @parms = split( " ", $out ); + return ( $parms[0] ); } #------------------------------------------------------- =head3 disableEnableDisk - Description : Disable/enable a disk for a given node - Arguments : Device address - Option (-d|-e) - Returns : Nothing - Example : my $out = xCAT::zvmUtils->disableEnableDisk($callback, $node, $option, $devAddr); + Description : Disable/enable a disk for a given node + Arguments : Device address + Option (-d|-e) + Returns : Nothing + Example : my $out = xCAT::zvmUtils->disableEnableDisk($callback, $node, $option, $devAddr); =cut #------------------------------------------------------- sub disableEnableDisk { - # Get inputs - my ( $class, $callback, $node, $option, $devAddr ) = @_; + # Get inputs + my ( $class, $callback, $node, $option, $devAddr ) = @_; - # Disable/enable disk - my $out; - if ( $option eq "-d" || $option eq "-e" ) { - $out = `ssh $node "chccwdev $option $devAddr"`; - } + # Disable/enable disk + my $out; + if ( $option eq "-d" || $option eq "-e" ) { + $out = `ssh $node "chccwdev $option $devAddr"`; + } - return ($out); + return ($out); } #------------------------------------------------------- =head3 getMdisks - Description : Get the MDISK statements in the user entry of a given node - Arguments : Node - Returns : MDISK statements - Example : my @mdisks = xCAT::zvmUtils->getMdisks($callback, $node); + Description : Get the MDISK statements in the user entry of a given node + Arguments : Node + Returns : MDISK statements + Example : my @mdisks = xCAT::zvmUtils->getMdisks($callback, $node); =cut #------------------------------------------------------- sub getMdisks { - # Get inputs - my ( $class, $callback, $node ) = @_; + # Get inputs + my ( $class, $callback, $node ) = @_; - # Directory where executables are - my $dir = '/opt/zhcp/bin'; + # Directory where executables are + my $dir = '/opt/zhcp/bin'; - # Get HCP - my @propNames = ( 'hcp', 'userid' ); - my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); - my $hcp = $propVals->{'hcp'}; + # Get HCP + my @propNames = ( 'hcp', 'userid' ); + my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); + my $hcp = $propVals->{'hcp'}; - # Get node userID - my $userId = $propVals->{'userid'}; + # Get node userID + my $userId = $propVals->{'userid'}; - my $out = `ssh $hcp "$dir/getuserentry $userId" | grep "MDISK"`; + my $out = `ssh $hcp "$dir/getuserentry $userId" | grep "MDISK"`; - # Get MDISK statements - my @lines = split( '\n', $out ); - my @disks; - foreach (@lines) { - $_ = xCAT::zvmUtils->trimStr($_); + # Get MDISK statements + my @lines = split( '\n', $out ); + my @disks; + foreach (@lines) { + $_ = xCAT::zvmUtils->trimStr($_); - # Save MDISK statements - push( @disks, $_ ); - } + # Save MDISK statements + push( @disks, $_ ); + } - return (@disks); + return (@disks); +} + +#------------------------------------------------------- + +=head3 getDedicates + + Description : Get the DEDICATE statements in the user entry of a given node + Arguments : Node + Returns : DEDICATE statements + Example : my @dedicates = xCAT::zvmUtils->getDedicates($callback, $node); + +=cut + +#------------------------------------------------------- +sub getDedicates { + + # Get inputs + my ( $class, $callback, $node ) = @_; + + # Directory where executables are + my $dir = '/opt/zhcp/bin'; + + # Get HCP + my @propNames = ( 'hcp', 'userid' ); + my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); + my $hcp = $propVals->{'hcp'}; + + # Get node userID + my $userId = $propVals->{'userid'}; + + my $out = `ssh $hcp "$dir/getuserentry $userId" | grep "DEDICATE"`; + + # Get DEDICATE statements + my @lines = split( '\n', $out ); + my @dedicates; + foreach (@lines) { + $_ = xCAT::zvmUtils->trimStr($_); + + # Save MDISK statements + push( @dedicates, $_ ); + } + + return (@dedicates); } #------------------------------------------------------- =head3 getUserEntryWODisk - Description : Get the user entry of a given node without MDISK statments, - and save it to a file - Arguments : Node - File name to save user entry under - Returns : Nothing - Example : my $out = xCAT::zvmUtils->getUserEntryWODisk($callback, $node, $file); + Description : Get the user entry of a given node without MDISK statments, + and save it to a file + Arguments : Node + File name to save user entry under + Returns : Nothing + Example : my $out = xCAT::zvmUtils->getUserEntryWODisk($callback, $node, $file); =cut #------------------------------------------------------- sub getUserEntryWODisk { - # Get inputs - my ( $class, $callback, $node, $file ) = @_; + # Get inputs + my ( $class, $callback, $node, $file ) = @_; - # Directory where executables are - my $dir = '/opt/zhcp/bin'; + # Directory where executables are + my $dir = '/opt/zhcp/bin'; - # Get node properties from 'zvm' table - my @propNames = ( 'hcp', 'userid' ); - my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); + # Get node properties from 'zvm' table + my @propNames = ( 'hcp', 'userid' ); + my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); - # Get HCP - my $hcp = $propVals->{'hcp'}; - if ( !$hcp ) { - xCAT::zvmUtils->printLn( $callback, "Error: Missing node HCP" ); - return; - } + # Get HCP + my $hcp = $propVals->{'hcp'}; + if ( !$hcp ) { + xCAT::zvmUtils->printLn( $callback, "Error: Missing node HCP" ); + return; + } - # Get node userID - my $userId = $propVals->{'userid'}; - if ( !$userId ) { - xCAT::zvmUtils->printLn( $callback, "Error: Missing node ID" ); - return; - } + # Get node userID + my $userId = $propVals->{'userid'}; + if ( !$userId ) { + xCAT::zvmUtils->printLn( $callback, "Error: Missing node ID" ); + return; + } - my $out = `ssh $hcp "$dir/getuserentry $userId" | grep -v "MDISK"`; + my $out = `ssh $hcp "$dir/getuserentry $userId" | grep -v "MDISK"`; - # Create a file to save output - open( DIRENTRY, ">$file" ); + # Create a file to save output + open( DIRENTRY, ">$file" ); - # Save output - my @lines = split( '\n', $out ); - foreach (@lines) { + # Save output + my @lines = split( '\n', $out ); + foreach (@lines) { - # Trim line - $_ = xCAT::zvmUtils->trimStr($_); + # Trim line + $_ = xCAT::zvmUtils->trimStr($_); - # Write directory entry into file - print DIRENTRY "$_\n"; - } - close(DIRENTRY); + # Write directory entry into file + print DIRENTRY "$_\n"; + } + close(DIRENTRY); - return; + return; } #------------------------------------------------------- =head3 appendHostname - Description : Append a hostname in front of a given string - Arguments : Hostname - String - Returns : String appended with hostname - Example : my $str = xCAT::zvmUtils->appendHostname($hostname, $str); + Description : Append a hostname in front of a given string + Arguments : Hostname + String + Returns : String appended with hostname + Example : my $str = xCAT::zvmUtils->appendHostname($hostname, $str); =cut #------------------------------------------------------- sub appendHostname { - my ( $class, $hostname, $str ) = @_; + my ( $class, $hostname, $str ) = @_; - # Append hostname to every line - my @outLn = split( "\n", $str ); - $str = ""; - foreach (@outLn) { - $str .= "$hostname: " . $_ . "\n"; - } + # Append hostname to every line + my @outLn = split( "\n", $str ); + $str = ""; + foreach (@outLn) { + $str .= "$hostname: " . $_ . "\n"; + } - return $str; + return $str; } #------------------------------------------------------- =head3 checkOutput - Description : Check the return of given output - Arguments : Output string - Returns : 0 Good output - -1 Bad output - Example : my $rtn = xCAT::zvmUtils->checkOutput($callback, $out); + Description : Check the return of given output + Arguments : Output string + Returns : 0 Good output + -1 Bad output + Example : my $rtn = xCAT::zvmUtils->checkOutput($callback, $out); =cut #------------------------------------------------------- sub checkOutput { - my ( $class, $callback, $out ) = @_; + my ( $class, $callback, $out ) = @_; - # Check output string - my @outLn = split( "\n", $out ); - foreach (@outLn) { + # Check output string + my @outLn = split( "\n", $out ); + foreach (@outLn) { - # If output contains 'Failed', return -1 - if ( $_ =~ m/Failed/i ) { - return -1; - } - } + # If output contains 'Failed', return -1 + if ( $_ =~ m/Failed/i ) { + return -1; + } + } - return 0; + return 0; } #------------------------------------------------------- =head3 getDeviceNode - Description : Get the device node for a given address - Arguments : Node - Disk address - Returns : Device node - Example : my $devNode = xCAT::zvmUtils->getDeviceNode($node, $tgtAddr); + Description : Get the device node for a given address + Arguments : Node + Disk address + Returns : Device node + Example : my $devNode = xCAT::zvmUtils->getDeviceNode($node, $tgtAddr); =cut #------------------------------------------------------- sub getDeviceNode { - my ( $class, $node, $tgtAddr ) = @_; + my ( $class, $node, $tgtAddr ) = @_; - # Determine device node - my $out = `ssh $node "cat /proc/dasd/devices" | grep ".$tgtAddr("`; - my @words = split( ' ', $out ); - my $tgtDevNode; + # Determine device node + my $out = `ssh $node "cat /proc/dasd/devices" | grep ".$tgtAddr("`; + my @words = split( ' ', $out ); + my $tgtDevNode; - # /proc/dasd/devices look similar to this: - # 0.0.0100(ECKD) at ( 94: 0) is dasda : active at blocksize: 4096, 1802880 blocks, 7042 MB - # Look for the string 'is' - my $i = 0; - while ( $tgtDevNode ne 'is' ) { - $tgtDevNode = $words[$i]; - $i++; - } + # /proc/dasd/devices look similar to this: + # 0.0.0100(ECKD) at ( 94: 0) is dasda : active at blocksize: 4096, 1802880 blocks, 7042 MB + # Look for the string 'is' + my $i = 0; + while ( $tgtDevNode ne 'is' ) { + $tgtDevNode = $words[$i]; + $i++; + } - return $words[$i]; + return $words[$i]; } #------------------------------------------------------- =head3 isAddressUsed - Description : Check if a given address is used - Arguments : Node - Disk address - Returns : 0 Address used - -1 Address not used - Example : my $ans = xCAT::zvmUtils->isAddressUsed($node, $address); + Description : Check if a given address is used + Arguments : Node + Disk address + Returns : 0 Address used + -1 Address not used + Example : my $ans = xCAT::zvmUtils->isAddressUsed($node, $address); =cut #------------------------------------------------------- sub isAddressUsed { - my ( $class, $node, $address ) = @_; + my ( $class, $node, $address ) = @_; - # Search for disk address - my $out = `ssh -o ConnectTimeout=5 $node "vmcp q v dasd" | grep "DASD $address"`; - if ($out) { - return 0; - } + # Search for disk address + my $out = `ssh -o ConnectTimeout=5 $node "vmcp q v dasd" | grep "DASD $address"`; + if ($out) { + return 0; + } - return -1; + return -1; } #------------------------------------------------------- =head3 getMacID - Description : Get the MACID from /opt/zhcp/conf/next_macid on the HCP - Arguments : HCP node - Returns : MACID - Example : my $macId = xCAT::zvmUtils->getMacID($hcp); + Description : Get the MACID from /opt/zhcp/conf/next_macid on the HCP + Arguments : HCP node + Returns : MACID + Example : my $macId = xCAT::zvmUtils->getMacID($hcp); =cut #------------------------------------------------------- sub getMacID { - my ( $class, $hcp ) = @_; + my ( $class, $hcp ) = @_; - # Check /opt/zhcp/conf directory on HCP - my $out = `ssh -o ConnectTimeout=5 $hcp "test -d /opt/zhcp/conf && echo 'Directory exists'"`; - if ( $out =~ m/Directory exists/i ) { + # Check /opt/zhcp/conf directory on HCP + my $out = `ssh -o ConnectTimeout=5 $hcp "test -d /opt/zhcp/conf && echo 'Directory exists'"`; + if ( $out =~ m/Directory exists/i ) { - # Check next_macid file - $out = `ssh -o ConnectTimeout=5 $hcp "test -e /opt/zhcp/conf/next_macid && echo 'File exists'"`; - if ( $out =~ m/File exists/i ) { + # Check next_macid file + $out = `ssh -o ConnectTimeout=5 $hcp "test -e /opt/zhcp/conf/next_macid && echo 'File exists'"`; + if ( $out =~ m/File exists/i ) { - # Do nothing - } else { + # Do nothing + } else { - # Create next_macid file - $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; - } - } else { + # Create next_macid file + $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; + } + } else { - # Create /opt/zhcp/conf directory - # Create next_mac - Contains next MAC address to use - $out = `ssh -o ConnectTimeout=5 $hcp "mkdir /opt/zhcp/conf"`; - $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; - } + # Create /opt/zhcp/conf directory + # Create next_mac - Contains next MAC address to use + $out = `ssh -o ConnectTimeout=5 $hcp "mkdir /opt/zhcp/conf"`; + $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; + } - # Read /opt/zhcp/conf/next_macid file - $out = `ssh -o ConnectTimeout=5 $hcp "cat /opt/zhcp/conf/next_macid"`; - my $macId = xCAT::zvmUtils->trimStr($out); + # Read /opt/zhcp/conf/next_macid file + $out = `ssh -o ConnectTimeout=5 $hcp "cat /opt/zhcp/conf/next_macid"`; + my $macId = xCAT::zvmUtils->trimStr($out); - return $macId; + return $macId; } #------------------------------------------------------- =head3 generateMacId - Description : Generate a new MACID - Arguments : zHCP node - Returns : Nothing - Example : my $macId = xCAT::zvmUtils->generateMacId($hcp); + Description : Generate a new MACID + Arguments : zHCP node + Returns : Nothing + Example : my $macId = xCAT::zvmUtils->generateMacId($hcp); =cut #------------------------------------------------------- sub generateMacId { - my ( $class, $hcp ) = @_; + my ( $class, $hcp ) = @_; - # Check /opt/zhcp/conf directory on HCP - my $out = `ssh -o ConnectTimeout=5 $hcp "test -d /opt/zhcp/conf && echo 'Directory exists'"`; - if ( $out =~ m/Directory exists/i ) { + # Check /opt/zhcp/conf directory on HCP + my $out = `ssh -o ConnectTimeout=5 $hcp "test -d /opt/zhcp/conf && echo 'Directory exists'"`; + if ( $out =~ m/Directory exists/i ) { - # Check next_macid file - $out = `ssh -o ConnectTimeout=5 $hcp "test -e /opt/zhcp/conf/next_macid && echo 'File exists'"`; - if ( $out =~ m/File exists/i ) { + # Check next_macid file + $out = `ssh -o ConnectTimeout=5 $hcp "test -e /opt/zhcp/conf/next_macid && echo 'File exists'"`; + if ( $out =~ m/File exists/i ) { - # Do nothing - } else { + # Do nothing + } else { - # Create next_macid file - $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; - } - } else { + # Create next_macid file + $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; + } + } else { - # Create /opt/zhcp/conf directory - # Create next_mac - Contains next MAC address to use - $out = `ssh -o ConnectTimeout=5 $hcp "mkdir /opt/zhcp/conf"`; - $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; - } + # Create /opt/zhcp/conf directory + # Create next_mac - Contains next MAC address to use + $out = `ssh -o ConnectTimeout=5 $hcp "mkdir /opt/zhcp/conf"`; + $out = `ssh -o ConnectTimeout=5 $hcp "echo 'FFFFF0' > /opt/zhcp/conf/next_macid"`; + } - # Read /opt/zhcp/conf/next_macid file - $out = `ssh -o ConnectTimeout=5 $hcp "cat /opt/zhcp/conf/next_macid"`; - my $macId = xCAT::zvmUtils->trimStr($out); - my $int; + # Read /opt/zhcp/conf/next_macid file + $out = `ssh -o ConnectTimeout=5 $hcp "cat /opt/zhcp/conf/next_macid"`; + my $macId = xCAT::zvmUtils->trimStr($out); + my $int; - if ($macId) { + if ($macId) { - # Convert hexadecimal - decimal - $int = hex($macId); - $macId = sprintf( "%d", $int ); + # Convert hexadecimal - decimal + $int = hex($macId); + $macId = sprintf( "%d", $int ); - # Generate new MAC suffix - $macId = $macId - 1; + # Generate new MAC suffix + $macId = $macId - 1; - # Convert decimal - hexadecimal - $macId = sprintf( "%X", $macId ); + # Convert decimal - hexadecimal + $macId = sprintf( "%X", $macId ); - # Save new MACID - $out = `ssh -o ConnectTimeout=5 $hcp "echo $macId > /opt/zhcp/conf/next_macid"`; - } + # Save new MACID + $out = `ssh -o ConnectTimeout=5 $hcp "echo $macId > /opt/zhcp/conf/next_macid"`; + } - return; + return; } #------------------------------------------------------- =head3 createMacAddr - Description : Create a MAC address using the HCP MAC prefix and a given MAC suffix - Arguments : Node - MAC suffix - Returns : MAC address - Example : my $mac = xCAT::zvmUtils->createMacAddr($node, $suffix); + Description : Create a MAC address using the HCP MAC prefix and a given MAC suffix + Arguments : Node + MAC suffix + Returns : MAC address + Example : my $mac = xCAT::zvmUtils->createMacAddr($node, $suffix); =cut #------------------------------------------------------- sub createMacAddr { - my ( $class, $node, $suffix ) = @_; + my ( $class, $node, $suffix ) = @_; - # Get node properties from 'zvm' table - my @propNames = ('hcp'); - my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); + # Get node properties from 'zvm' table + my @propNames = ('hcp'); + my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames ); - # Get HCP - my $hcp = $propVals->{'hcp'}; - if ( !$hcp ) { - return -1; - } + # Get HCP + my $hcp = $propVals->{'hcp'}; + if ( !$hcp ) { + return -1; + } - # Get HCP MAC address - # Get the first MAC address found - my $out = `ssh -o ConnectTimeout=5 $hcp "vmcp q v nic" | grep "MAC:"`; - my @lines = split( "\n", $out ); - my @vars = split( " ", $lines[0] ); + # Get HCP MAC address + # Get the first MAC address found + my $out = `ssh -o ConnectTimeout=5 $hcp "vmcp q v nic" | grep "MAC:"`; + my @lines = split( "\n", $out ); + my @vars = split( " ", $lines[0] ); - # Extract MAC prefix - my $prefix = $vars[1]; - $prefix = xCAT::zvmUtils->replaceStr( $prefix, "-", "" ); - $prefix = substr( $prefix, 0, 6 ); + # Extract MAC prefix + my $prefix = $vars[1]; + $prefix = xCAT::zvmUtils->replaceStr( $prefix, "-", "" ); + $prefix = substr( $prefix, 0, 6 ); - # Generate MAC address of source node - my $mac = $prefix . $suffix; + # Generate MAC address of source node + my $mac = $prefix . $suffix; - # If length is less than 12, append a zero - if ( length($mac) != 12 ) { - $mac = "0" . $mac; - } + # If length is less than 12, append a zero + if ( length($mac) != 12 ) { + $mac = "0" . $mac; + } - # Format MAC address - $mac = - substr( $mac, 0, 2 ) . ":" - . substr( $mac, 2, 2 ) . ":" - . substr( $mac, 4, 2 ) . ":" - . substr( $mac, 6, 2 ) . ":" - . substr( $mac, 8, 2 ) . ":" - . substr( $mac, 10, 2 ); + # Format MAC address + $mac = + substr( $mac, 0, 2 ) . ":" + . substr( $mac, 2, 2 ) . ":" + . substr( $mac, 4, 2 ) . ":" + . substr( $mac, 6, 2 ) . ":" + . substr( $mac, 8, 2 ) . ":" + . substr( $mac, 10, 2 ); - return $mac; + return $mac; } #------------------------------------------------------- =head3 getOs - Description : Get the operating system of a given node - Arguments : Node - Returns : Operating system name - Example : my $osName = xCAT::zvmUtils->getOs($node); + Description : Get the operating system of a given node + Arguments : Node + Returns : Operating system name + Example : my $osName = xCAT::zvmUtils->getOs($node); =cut #------------------------------------------------------- sub getOs { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get operating system - my $out = `ssh -o ConnectTimeout=10 $node "cat /etc/*release"`; - my @results = split( '\n', $out ); - return ( xCAT::zvmUtils->trimStr( $results[0] ) ); + # Get operating system + my $out = `ssh -o ConnectTimeout=10 $node "cat /etc/*release"`; + my @results = split( '\n', $out ); + return ( xCAT::zvmUtils->trimStr( $results[0] ) ); } #------------------------------------------------------- =head3 getArch - Description : Get the architecture of a given node - Arguments : Node - Returns : Architecture of node - Example : my $arch = xCAT::zvmUtils->getArch($node); + Description : Get the architecture of a given node + Arguments : Node + Returns : Architecture of node + Example : my $arch = xCAT::zvmUtils->getArch($node); =cut #------------------------------------------------------- sub getArch { - # Get inputs - my ( $class, $node ) = @_; + # Get inputs + my ( $class, $node ) = @_; - # Get host using VMCP - my $arch = `ssh $node "uname -p"`; + # Get host using VMCP + my $arch = `ssh $node "uname -p"`; - return ( xCAT::zvmUtils->trimStr($arch) ); + return ( xCAT::zvmUtils->trimStr($arch) ); } #------------------------------------------------------- =head3 getUserProfile - Description : Get the user profile - Arguments : Profile name - Returns : User profile - Example : my $profile = xCAT::zvmUtils->getUserProfile($hcp, $name); + Description : Get the user profile + Arguments : Profile name + Returns : User profile + Example : my $profile = xCAT::zvmUtils->getUserProfile($hcp, $name); =cut #------------------------------------------------------- sub getUserProfile { - # Get inputs - my ( $class, $hcp, $profile ) = @_; + # Get inputs + my ( $class, $hcp, $profile ) = @_; - # Set directory where executables are on zHCP - my $hcpDir = "/opt/zhcp/bin"; + # Set directory where executables are on zHCP + my $hcpDir = "/opt/zhcp/bin"; - my $out; + my $out; - # Set directory for cache - my $cache = '/var/opt/zhcp/cache'; - # If the cache directory does not exist - if (!(`ssh $hcp "test -d $cache && echo Exists"`)) { - # Create cache directory - $out = `ssh $hcp "mkdir -p $cache"`; - } + # Set directory for cache + my $cache = '/var/opt/zhcp/cache'; + # If the cache directory does not exist + if (!(`ssh $hcp "test -d $cache && echo Exists"`)) { + # Create cache directory + $out = `ssh $hcp "mkdir -p $cache"`; + } - # Set output file name - my $file = "$cache/$profile.profile"; + # Set output file name + my $file = "$cache/$profile.profile"; - # If a cache for the user profile exists - if (`ssh $hcp "ls $file"`) { + # If a cache for the user profile exists + if (`ssh $hcp "ls $file"`) { - # Get current Epoch - my $curTime = time(); + # Get current Epoch + my $curTime = time(); - # Get time of last change as seconds since Epoch - my $fileTime = xCAT::zvmUtils->trimStr(`ssh $hcp "stat -c %Z $file"`); + # Get time of last change as seconds since Epoch + my $fileTime = xCAT::zvmUtils->trimStr(`ssh $hcp "stat -c %Z $file"`); - # If the current time is greater than 5 minutes of the file timestamp - my $interval = 300; # 300 seconds = 5 minutes * 60 seconds/minute - if ( $curTime > $fileTime + $interval ) { + # If the current time is greater than 5 minutes of the file timestamp + my $interval = 300; # 300 seconds = 5 minutes * 60 seconds/minute + if ( $curTime > $fileTime + $interval ) { - # Get user profiles and save it in a file - $out = `ssh $hcp "$hcpDir/getuserprofile $profile > $file"`; - } - } else { + # Get user profiles and save it in a file + $out = `ssh $hcp "$hcpDir/getuserprofile $profile > $file"`; + } + } else { - # Get user profiles and save it in a file - $out = `ssh $hcp "$hcpDir/getuserprofile $profile > $file"`; - } + # Get user profiles and save it in a file + $out = `ssh $hcp "$hcpDir/getuserprofile $profile > $file"`; + } - # Return the file contents - $out = `ssh $hcp "cat $file"`; - return $out; + # Return the file contents + $out = `ssh $hcp "cat $file"`; + return $out; } #------------------------------------------------------- =head3 inArray - Description : Checks if a value exists in an array - Arguments : Search value - Search array - Returns : The searched expression - Example : my $rtn = xCAT::zvmUtils->inArray($needle, @haystack); + Description : Checks if a value exists in an array + Arguments : Search value + Search array + Returns : The searched expression + Example : my $rtn = xCAT::zvmUtils->inArray($needle, @haystack); =cut #------------------------------------------------------- sub inArray { - # Get inputs - my ( $class, $needle, @haystack ) = @_; - return grep{ $_ eq $needle } @haystack; + # Get inputs + my ( $class, $needle, @haystack ) = @_; + return grep{ $_ eq $needle } @haystack; } #------------------------------------------------------- =head3 getOsVersion - Description : Get the operating system of a given node - Arguments : Node - Returns : Operating system name - Example : my $os = xCAT::zvmUtils->getOsVersion($node); + Description : Get the operating system of a given node + Arguments : Node + Returns : Operating system name + Example : my $os = xCAT::zvmUtils->getOsVersion($node); =cut #------------------------------------------------------- sub getOsVersion { - - # Get inputs - my ( $class, $node ) = @_; + + # Get inputs + my ( $class, $node ) = @_; - my $os = ''; - my $version = ''; + my $os = ''; + my $version = ''; - # Get operating system - my $release = `ssh -o ConnectTimeout=2 $node "cat /etc/*release"`; - my @lines = split('\n', $release); - if (grep(/SLES|Enterprise Server/, @lines)) { - $os = 'sles'; - $version = $lines[0]; - $version =~ tr/\.//; - $version =~ s/[^0-9]*([0-9]+).*/$1/; - $os = $os . $version; - - # Append service level - $version = `echo "$release" | grep "LEVEL"`; - $version =~ tr/\.//; - $version =~ s/[^0-9]*([0-9]+).*/$1/; - $os = $os . 'sp' . $version; - } elsif (grep(/Red Hat Enterprise Linux Server/, @lines)) { - $os = 'rhel'; - $version = $lines[0]; - $version =~ tr/\.//; - $version =~ s/([A-Za-z\s\(\)]+)//g; - $os = $os . $version; - } + # Get operating system + my $release = `ssh -o ConnectTimeout=2 $node "cat /etc/*release"`; + my @lines = split('\n', $release); + if (grep(/SLES|Enterprise Server/, @lines)) { + $os = 'sles'; + $version = $lines[0]; + $version =~ tr/\.//; + $version =~ s/[^0-9]*([0-9]+).*/$1/; + $os = $os . $version; + + # Append service level + $version = `echo "$release" | grep "LEVEL"`; + $version =~ tr/\.//; + $version =~ s/[^0-9]*([0-9]+).*/$1/; + $os = $os . 'sp' . $version; + } elsif (grep(/Red Hat Enterprise Linux Server/, @lines)) { + $os = 'rhel'; + $version = $lines[0]; + $version =~ tr/\.//; + $version =~ s/([A-Za-z\s\(\)]+)//g; + $os = $os . $version; + } - return xCAT::zvmUtils->trimStr($os); + return xCAT::zvmUtils->trimStr($os); } \ No newline at end of file diff --git a/xCAT-UI/configure.php b/xCAT-UI/configure.php index 0d754e90f..f518ad157 100644 --- a/xCAT-UI/configure.php +++ b/xCAT-UI/configure.php @@ -10,8 +10,8 @@ loadPage(); /* Login user */ if (!isAuthenticated()) { - login(); + login(); } else { - loadContent(); + loadContent(); } ?> \ No newline at end of file diff --git a/xCAT-UI/css/login.css b/xCAT-UI/css/login.css index 1e8be9733..8aea60065 100644 --- a/xCAT-UI/css/login.css +++ b/xCAT-UI/css/login.css @@ -30,11 +30,11 @@ body { padding: 5px; } -#login label{ +#login label { font: bold 12px sans-serif; } -#login_status { +#login-status { font: bold 12px sans-serif; } @@ -44,7 +44,7 @@ body { float: right; } -#login_form { +#login-form { background-color: #f5f5f5; height: 280px; -moz-border-radius: 3px; @@ -52,9 +52,9 @@ body { border-radius: 3px; } -#loginfo { +#log-info { margin: 5px 0px; text-align: right; color: #f5f5f5; - font-weight:bold; + font-weight: bold; } \ No newline at end of file diff --git a/xCAT-UI/css/style.css b/xCAT-UI/css/style.css index 066636d80..58f7b2828 100644 --- a/xCAT-UI/css/style.css +++ b/xCAT-UI/css/style.css @@ -1,11 +1,10 @@ -/*--------------- Dialogs ---------------*/ +/*--- Dialogs ---*/ .ui-dialog input { border: solid 1px #BDBDBD; font: 12px sans-serif; } -.ui-dialog label,.ui-dialog input,.ui-dialog p,.ui-dialog button,.ui-dialog td - { +.ui-dialog label,.ui-dialog input,.ui-dialog p,.ui-dialog button,.ui-dialog td { font: 12px sans-serif; } @@ -13,12 +12,11 @@ font: 12px sans-serif; } -.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button - { +.ui-widget input,.ui-widget select,.ui-widget textarea,.ui-widget button { font: 12px sans-serif; } -/*--------------- Tooltip ---------------*/ +/*--- Tooltip ---*/ .tooltip { background-color: #000; border: 1px solid #fff; @@ -37,7 +35,7 @@ margin: 0px; } -/*--------------- Header ---------------*/ +/*--- Header ---*/ #header { height: 39px; width: 1000px; @@ -90,15 +88,7 @@ color: #FF0000; } -#layoutselector { - padding: 2px 10px 0px 2px; /* Top right left bottom*/ - text-align: right; - color: #FFC125; - text-decoration: none; - display: block; -} - -/*--------------- Body and content ---------------*/ +/*--- Body and content ---*/ body { background: #1C1C1C; font: 12px sans-serif; @@ -124,7 +114,7 @@ pre { font-size: 10px; } -/*--------------- Groups ---------------*/ +/*--- Groups ---*/ #groups { width: 150px; vertical-align: top; @@ -178,7 +168,7 @@ pre { border-top: thin solid #E7EBFF; } -/*--------------- Nodes section ---------------*/ +/*--- Nodes section ---*/ #nodes { width: 790px; min-height: 570px; @@ -204,7 +194,7 @@ pre { line-height: 1; } -/*--------------- Info/warning bar ---------------*/ +/*--- Info and warning bar ---*/ span.ui-icon-info { float: left; margin-right: 0.3em; @@ -227,7 +217,7 @@ span.ui-icon-info { text-align: center } -/*--------------- jQuery tabs ---------------*/ +/*--- jQuery tabs ---*/ .tab { font: 12px sans-serif; border-style: none; @@ -248,7 +238,7 @@ span.ui-icon-info { cursor: pointer; } -/*--------------- Inventory and user entry ---------------*/ +/*--- Inventory and user entry ---*/ .tab table { border-width: 1px; border-spacing: 0px; @@ -326,7 +316,7 @@ legend { height: 300px; } -/*--------------- menu Div Actions bar ---------------*/ +/*--- menu Div Actions bar ---*/ .menuDiv { padding: 0.5em; height: 30px; @@ -373,7 +363,7 @@ legend { margin: 0; } -/*--------------- jQuery datatable ---------------*/ +/*--- jQuery datatable ---*/ .dataTables_wrapper { overflow: auto; width: auto; @@ -414,8 +404,7 @@ legend { } /*** < > buttons ***/ -.paginate_disabled_previous,.paginate_enabled_previous,.paginate_disabled_next,.paginate_enabled_next - { +.paginate_disabled_previous,.paginate_enabled_previous,.paginate_disabled_next,.paginate_enabled_next { height: 19px; width: 19px; margin-left: 2px; @@ -472,7 +461,7 @@ legend { color: #FF0000; } -/*--------------- Editable column ---------------*/ +/*--- Editable column ---*/ .tab .datatable textarea { font: 12px sans-serif; border: solid 1px #BDBDBD; @@ -498,7 +487,7 @@ legend { background: none; } -/*--------------- jQuery context menu ---------------*/ +/*--- jQuery context menu ---*/ .context-menu-theme-vista { background: #FAFAFA url(../images/contextmenu/context-menu-bg.gif) repeat-y left top; @@ -536,8 +525,7 @@ legend { background-image: none; } -.context-menu-theme-vista .context-menu-item-hover .context-menu-item-inner - { +.context-menu-theme-vista .context-menu-item-hover .context-menu-item-inner { padding: 3px 15px 3px 35px; margin-left: 0px; } @@ -546,7 +534,7 @@ legend { color: #A7A7A7; } -/*--------------- Forms ---------------*/ +/*--- Forms ---*/ .form label { color: #424242; line-height: 1.5; @@ -613,7 +601,7 @@ table a:hover { border: solid 1px #d4d4d4; } -/*--------------- Provision disk table ---------------*/ +/*--- Provision disk table ---*/ .provision table { border-width: 1px; border-spacing: 0px; @@ -630,7 +618,7 @@ table a:hover { width: 60px; } -/*--------------- Provision and clone table ---------------*/ +/*--- Provision and clone table ---*/ .special table { border-width: 1px; border-spacing: 0px; @@ -646,52 +634,52 @@ table a:hover { padding: 3px; } -/*--------------- Provision and monitor forms ---------------*/ -.monitornormal { +/*--- Provision and monitor forms ---*/ +.monitor-normal { background: #66CD00; cursor: pointer; } -.mornitorwarning { +.mornitor-warning { background: #FFD700; cursor: pointer; } -.monitorerror { +.monitor-error { background: #FF3030; } -.monitorunknown { +.monitor-unknown { background: #8B8B7A; } -.monitornodeli { +.monitor-node-li { width: 10px; height: 10px; float: left; border: 1px solid white; } -.monitorsumdiv { +.monitor-sum-div { width: 300px; height: 180px; float: left; margin: 0px 0px 10px 10px; } -.monitorsumdiv td { +.monitor-sum-div td { padding: 0; border-style: none; font-size: 10px; } -.monitornodediv { +.monitor-node-div { width: 240px; height: 120px; margin: 0px 0px 15px 0px; } -.monitorzoomlink { +.monitor-zoom-link { cursor: pointer; color: blue; } @@ -710,7 +698,7 @@ table a:hover { height: 150px; } -/*--------------- Physical layout section ---------------*/ +/*--- Physical layout section ---*/ .frameDiv { width: 179px; height: 500px; @@ -768,7 +756,7 @@ table a:hover { height: 11px; } -.fspcheckbox { +.fspCheckbox { padding: 0px; margin: 3px 3px 1px 3px; } @@ -796,7 +784,7 @@ table a:hover { background: url(../images/nodes/blade.jpg); } -.xnodeDiv { +.xNodeDiv { font-size: 12px; height: 21px; line-height: 21px; @@ -809,45 +797,7 @@ table a:hover { display: inline-block; } -/*--------------- Discovery section ---------------*/ -.discoverstep { - width: 960px; - vertical-align: top; - background-color: #A9D0F5; - padding: 0px 0px 0px 5px; - -moz-border-radius: .3em; - -webkit-border-radius: .3em; - border-radius: .3em; -} - -.discovercurrentstep { - background-color: yellow; - font: normal bold 12px/35px sans-serif; - padding: 5px; -} - -.discovercontent { - width: 960px; - display: inline-table; - padding: 0; -} - -.discovercontent table { - border: none; -} - -.discovercontent td { - border: none; - text-align: left; -} - -.discovercontent th { - font: normal bold 15px sans-serif; - text-align: center; - border: none; -} - -/*--------------- jqPlot Pie legend ---------------*/ +/*--- jqPlot Pie legend ---*/ td.jqplot-table-legend { border-width: 0px; } diff --git a/xCAT-UI/debian/dirs b/xCAT-UI/debian/dirs index b77ad3059..c3b9dcda6 100644 --- a/xCAT-UI/debian/dirs +++ b/xCAT-UI/debian/dirs @@ -1 +1,2 @@ opt/xcat/ui +opt/xcat/lib/perl/xCAT_plugin/ diff --git a/xCAT-UI/debian/install b/xCAT-UI/debian/install index fe2a1d9c2..381506ea3 100644 --- a/xCAT-UI/debian/install +++ b/xCAT-UI/debian/install @@ -5,3 +5,5 @@ etc opt/xcat/ui/ images opt/xcat/ui/ js opt/xcat/ui/ lib opt/xcat/ui/ +xcat/plugins/web.pm opt/xcat/lib/perl/xCAT_plugin +xcat/plugins/webportal.pm opt/xcat/lib/perl/xCAT_plugin diff --git a/xCAT-UI/debian/links b/xCAT-UI/debian/links new file mode 100644 index 000000000..fe5104bc6 --- /dev/null +++ b/xCAT-UI/debian/links @@ -0,0 +1,2 @@ +#opt/xcat/ui/etc/apache2/conf.d/xcat-ui.conf etc/apache2/conf.d/xcat-ui.conf +opt/xcat/bin/xcatclientnnr opt/xcat/bin/webportal diff --git a/xCAT-UI/debian/postinst b/xCAT-UI/debian/postinst index 537e87de3..140259940 100644 --- a/xCAT-UI/debian/postinst +++ b/xCAT-UI/debian/postinst @@ -1,5 +1,5 @@ #!/bin/sh -# postinst script for openmpi +# postinst script for xcat-ui # # see: dh_installdeb(1) @@ -21,9 +21,9 @@ set -e case "$1" in configure) apachedaemon=apache2 - /bin/rm -f /etc/$apachedaemon/conf.d/xcat-ui.conf - /bin/ln -s /opt/xcat/ui/etc/apache2/conf.d/xcat-ui.conf /etc/$apachedaemon/conf.d/xcat-ui.conf - /etc/init.d/$apachedaemon reload + /bin/rm -f /etc/apache2/conf.d/xcat-ui.conf + /bin/ln -s /opt/xcat/ui/etc/apache2/conf.d/xcat-ui.conf /etc/apache2/conf.d/xcat-ui.conf + /etc/init.d/apache2 restart # automatically put the encrypted passwd into the xcat passwd db /opt/xcat/sbin/chtab key=xcat,username=root passwd.password=`grep root /etc/shadow|cut -d : -f 2` diff --git a/xCAT-UI/debian/prerm b/xCAT-UI/debian/prerm index 5d63843a9..b0146377a 100644 --- a/xCAT-UI/debian/prerm +++ b/xCAT-UI/debian/prerm @@ -22,11 +22,9 @@ case "$1" in ;; remove) - apachedaemon=apache2 - - echo "Undoing $apachedaemon configuration for xCAT..." - /bin/rm -f /etc/$apachedaemon/conf.d/xcat-ui.conf - /etc/init.d/$apachedaemon reload + echo "Undoing apache2 configuration for xCAT..." + /bin/rm -f /etc/apache2/conf.d/xcat-ui.conf + /etc/init.d/apache2 restart ;; failed-upgrade) diff --git a/xCAT-UI/debian/rules b/xCAT-UI/debian/rules index 21bd68bda..ce79be57f 100644 --- a/xCAT-UI/debian/rules +++ b/xCAT-UI/debian/rules @@ -25,7 +25,7 @@ install: dh_testdir dh_testroot dh_installdirs - dh_install + dh_install -X".svn" dh_link @@ -41,7 +41,7 @@ binary-arch: dh_installchangelogs dh_installdocs # dh_installexamples - dh_install + dh_install -X".svn" # dh_installmenu # dh_installdebconf # dh_installlogrotate diff --git a/xCAT-UI/ganglianode.php b/xCAT-UI/ganglianode.php index 370fbefcf..3ee6b5d89 100644 --- a/xCAT-UI/ganglianode.php +++ b/xCAT-UI/ganglianode.php @@ -1,17 +1,18 @@ - - Node {$_GET['n']} Ganglia Report - - - - - - - + + Node {$_GET['n']} Ganglia Report + + + + + + + EEE; ?> + + - - - -
- - - - - - - - - - - -
-
- + + + + +
+ + + + + + + + + + + +
+
+ EEE; ?> \ No newline at end of file diff --git a/xCAT-UI/help.php b/xCAT-UI/help.php index d9d5b552c..95bf6e353 100644 --- a/xCAT-UI/help.php +++ b/xCAT-UI/help.php @@ -10,8 +10,8 @@ loadPage(); /* Login user */ if (!isAuthenticated()) { - login(); + login(); } else { - loadContent(); + loadContent(); } ?> \ No newline at end of file diff --git a/xCAT-UI/index.php b/xCAT-UI/index.php index dadb7b817..b55a5842c 100644 --- a/xCAT-UI/index.php +++ b/xCAT-UI/index.php @@ -11,8 +11,8 @@ loadPage(); /* Login user */ if (!isAuthenticated()) { - login(); + login(); } else { - loadContent(); + loadContent(); } ?> \ No newline at end of file diff --git a/xCAT-UI/js/configure/configure.js b/xCAT-UI/js/configure/configure.js index 5e88d4174..2adcd2cec 100644 --- a/xCAT-UI/js/configure/configure.js +++ b/xCAT-UI/js/configure/configure.js @@ -7,36 +7,30 @@ var configDatatables = new Object(); // Datatables on the config page /** * Set the datatable * - * @param id - * The ID of the datatable - * @param obj - * Datatable object - * @return Nothing + * @param id The ID of the datatable + * @param obj Datatable object */ function setConfigDatatable(id, obj) { - configDatatables[id] = obj; + configDatatables[id] = obj; } /** * Get the datatable with the given ID * - * @param id - * The ID of the datatable + * @param id The ID of the datatable * @return Datatable object */ function getConfigDatatable(id) { - return configDatatables[id]; + return configDatatables[id]; } /** * Set the configure tab * - * @param obj - * Tab object - * @return Nothing + * @param obj Tab object */ function setConfigTab(obj) { - configTabs = obj; + configTabs = obj; } /** @@ -46,449 +40,449 @@ function setConfigTab(obj) { * @return Tab object */ function getConfigTab() { - return configTabs; + return configTabs; } /** * Load configure page - * - * @return Nothing */ function loadConfigPage() { - // If the configure page has already been loaded - if ($('#content').children().length) { - // Do not reload configure page - return; - } + // If the configure page has already been loaded + if ($('#content').children().length) { + // Do not reload configure page + return; + } - // Create configure tab - var tab = new Tab(); - setConfigTab(tab); - tab.init(); - $('#content').append(tab.object()); + // Create configure tab + var tab = new Tab(); + setConfigTab(tab); + tab.init(); + $('#content').append(tab.object()); - // Create loader - var loader = $('
').append(createLoader()); + // Create loader + var loader = $('
').append(createLoader()); - // Add tab to configure xCAT tables - tab.add('configTablesTab', 'Tables', loader, false); + // Add tab to configure xCAT tables + tab.add('configTablesTab', 'Tables', loader, false); - // Add the update tab - tab.add('updateTab', 'Update', '', false); - - // Add the discover tab - tab.add('discoverTab', 'Discover', '', false); + // Add the update tab + tab.add('updateTab', 'Update', '', false); + + // Add the discover tab + tab.add('discoverTab', 'Discover', '', false); + + // Add the self-service tab + tab.add('serviceTab', 'Service', '', false); - // Get list of tables and their descriptions - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : '-d', - msg : '' - }, + // Get list of tables and their descriptions + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : '-d', + msg : '' + }, - success : loadTableNames - }); + success : loadTableNames + }); - loadUpdatePage(); - loadDiscoverPage(); + loadUpdatePage(); + loadDiscoverPage(); + loadServicePage(); } /** * Load xCAT database table names and their descriptions * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function loadTableNames(data) { - // Get output - var tables = data.rsp; + // Get output + var tables = data.rsp; - // Remove loader - var tabId = 'configTablesTab'; - $('#' + tabId).find('img').hide(); + // Remove loader + var tabId = 'configTablesTab'; + $('#' + tabId).find('img').hide(); - // Create a groups division - var tablesDIV = $('
'); - $('#' + tabId).append(tablesDIV); + // Create a groups division + var tablesDIV = $('
'); + $('#' + tabId).append(tablesDIV); - // Create info bar - var infoBar = createInfoBar('Select a table to view or edit.'); - tablesDIV.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Select a table to view or edit.'); + tablesDIV.append(infoBar); - // Create a list for the tables - var list = $(''); - // Loop through each table - for ( var i = 0; i < tables.length; i++) { - // Create a link for each table - var args = tables[i].split(':'); - var link = $('' + args[0] + ''); + // Create a list for the tables + var list = $(''); + // Loop through each table + for ( var i = 0; i < tables.length; i++) { + // Create a link for each table + var args = tables[i].split(':'); + var link = $('' + args[0] + ''); - // Open table on click - link.bind('click', function(e) { - // Get table ID that was clicked - var id = (e.target) ? e.target.id : e.srcElement.id; + // Open table on click + link.bind('click', function(e) { + // Get table ID that was clicked + var id = (e.target) ? e.target.id : e.srcElement.id; - // Create loader - var loader = $('
').append(createLoader()); + // Create loader + var loader = $('
').append(createLoader()); - // Add a new tab for this table - var configTab = getConfigTab(); - if (!$('#' + id + 'Tab').length) { - configTab.add(id + 'Tab', id, loader, true); + // Add a new tab for this table + var configTab = getConfigTab(); + if (!$('#' + id + 'Tab').length) { + configTab.add(id + 'Tab', id, loader, true); - // Get contents of selected table - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : id, - msg : id - }, + // Get contents of selected table + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : id, + msg : id + }, - success : loadTable - }); - } + success : loadTable + }); + } - // Select new tab - configTab.select(id + 'Tab'); - }); + // Select new tab + configTab.select(id + 'Tab'); + }); - var item = $('
  • '); - item.append(link); + var item = $('
  • '); + item.append(link); - // Append the table description - item.append(': ' + args[1]); + // Append the table description + item.append(': ' + args[1]); - // Append item to list - list.append(item); - } + // Append item to list + list.append(item); + } - tablesDIV.append(list); + tablesDIV.append(list); } /** * Load a given database table * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function loadTable(data) { - // Get response - var rsp = data.rsp; - // Get table ID - var id = data.msg; + // Get response + var rsp = data.rsp; + // Get table ID + var id = data.msg; - // Remove loader - var tabId = id + 'Tab'; - $('#' + tabId).find('img').remove(); + // Remove loader + var tabId = id + 'Tab'; + $('#' + tabId).find('img').remove(); - // Create info bar - var infoBar = createInfoBar('Click on a cell to edit. Click outside the table to write to the cell. Once you are satisfied with how the table looks, click on Save.'); - $('#' + tabId).append(infoBar); + // Create info bar + var infoBar = createInfoBar('Click on a cell to edit. Click outside the table to write to the cell. Once you are satisfied with how the table looks, click on Save.'); + $('#' + tabId).append(infoBar); - // Create action bar - var actionBar = $('
    '); - $('#' + tabId).append(actionBar); + // Create action bar + var actionBar = $('
    '); + $('#' + tabId).append(actionBar); - // Get table headers - var args = rsp[0].replace('#', ''); - var headers = args.split(','); + // Get table headers + var args = rsp[0].replace('#', ''); + var headers = args.split(','); - // Create container for original table contents - var origCont = new Array(); // Original table content - origCont[0] = rsp[0].split(','); // Headers + // Create container for original table contents + var origCont = new Array(); // Original table content + origCont[0] = rsp[0].split(','); // Headers - // Create container for new table contents - var newCont = new Object(); - var tmp = new Object(); - tmp[0] = '#' + headers[0]; // Put a # in front of the header - for ( var i = 1; i < headers.length; i++) { - tmp[i] = headers[i]; - } - newCont[0] = tmp; + // Create container for new table contents + var newCont = new Object(); + var tmp = new Object(); + tmp[0] = '#' + headers[0]; // Put a # in front of the header + for ( var i = 1; i < headers.length; i++) { + tmp[i] = headers[i]; + } + newCont[0] = tmp; - // Create a new datatable - var tableId = id + 'Datatable'; - var table = new DataTable(tableId); + // Create a new datatable + var tableId = id + 'Datatable'; + var table = new DataTable(tableId); - // Add column for the remove row button - headers.unshift(''); - table.init(headers); - headers.shift(); + // Add column for the remove row button + headers.unshift(''); + table.init(headers); + headers.shift(); - // Append datatable to tab - $('#' + tabId).append(table.object()); + // Append datatable to tab + $('#' + tabId).append(table.object()); - // Data table - var dTable; + // Add table rows + // Start with the 2nd row (1st row is the headers) + for ( var i = 1; i < rsp.length; i++) { + // Split into columns + var cols = rsp[i].split(','); - // Add table rows - // Start with the 2nd row (1st row is the headers) - for ( var i = 1; i < rsp.length; i++) { - // Split into columns - var cols = rsp[i].split(','); + // Go through each column + for ( var j = 0; j < cols.length; j++) { - // Go through each column - for ( var j = 0; j < cols.length; j++) { + // If the column is not complete + if (cols[j].count('"') == 1) { + while (cols[j].count('"') != 2) { + // Merge this column with the adjacent one + cols[j] = cols[j] + "," + cols[j + 1]; - // If the column is not complete - if (cols[j].count('"') == 1) { - while (cols[j].count('"') != 2) { - // Merge this column with the adjacent one - cols[j] = cols[j] + "," + cols[j + 1]; + // Remove merged row + cols.splice(j + 1, 1); + } + } - // Remove merged row - cols.splice(j + 1, 1); - } - } + // Replace quote + cols[j] = cols[j].replace(new RegExp('"', 'g'), ''); + } - // Replace quote - cols[j] = cols[j].replace(new RegExp('"', 'g'), ''); - } + // Add remove button + cols.unshift(''); - // Add remove button - cols.unshift(''); + // Add row + table.add(cols); - // Add row - table.add(cols); + // Save original table content + origCont[i] = cols; + } - // Save original table content - origCont[i] = cols; - } + // Turn table into datatable + var dTable = $('#' + id + 'Datatable').dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%", + "bAutoWidth": true + }); - /** - * Enable editable columns - */ - // Do not make 1st column editable - $('#' + tableId + ' td:not(td:nth-child(1))').editable( - function(value, settings) { - // Get column index - var colPos = this.cellIndex; - // Get row index - var rowPos = dTable.fnGetPosition(this.parentNode); + /** + * Enable editable columns + */ + // Do not make 1st column editable + $('#' + tableId + ' td:not(td:nth-child(1))').editable( + function(value, settings) { + // Get column index + var colPos = this.cellIndex; + // Get row index + var rowPos = dTable.fnGetPosition(this.parentNode); - // Update datatable - dTable.fnUpdate(value, rowPos, colPos); + // Update datatable + dTable.fnUpdate(value, rowPos, colPos); - return (value); - }, { - onblur : 'submit', // Clicking outside editable area submits changes - type : 'textarea', - placeholder: ' ', - height : '30px' // The height of the text area - }); + return (value); + }, { + onblur : 'submit', // Clicking outside editable area submits changes + type : 'textarea', + placeholder: ' ', + height : '30px' // The height of the text area + }); + + // Create action bar + var actionBar = $('
    '); + + var saveLnk = $('Save'); + saveLnk.click(function() { + // Get table ID and name + var tableId = $(this).parents('.dataTables_wrapper').attr('id').replace('_wrapper', ''); + var tableName = tableId.replace('Datatable', ''); + + // Get datatable + var dTable = $('#' + tableId).dataTable(); + // Get the nodes from the table + var dRows = dTable.fnGetNodes(); - // Turn table into datatable - dTable = $('#' + id + 'Datatable').dataTable({ - 'iDisplayLength': 50, - 'bLengthChange': false, - "sScrollX": "100%", - "bAutoWidth": true - }); + // Go through each row + for ( var i = 0; i < dRows.length; i++) { + // If there is row with values + if (dRows[i]) { + // Go through each column + // Ignore the 1st column because it is a button + var cols = dRows[i].childNodes; + var vals = new Object(); + for ( var j = 1; j < cols.length; j++) { + var val = cols.item(j).firstChild.nodeValue; + + // Insert quotes + if (val == ' ') { + vals[j - 1] = ''; + } else { + vals[j - 1] = val; + } + } - // Create action bar - var actionBar = $('
    '); - - var saveLnk = $('Save'); - saveLnk.click(function() { - // Get table ID and name - var tableId = $(this).parents('.dataTables_wrapper').attr('id').replace('_wrapper', ''); - var tableName = tableId.replace('Datatable', ''); - - // Get datatable - var dTable = $('#' + tableId).dataTable(); - // Get the nodes from the table - var dRows = dTable.fnGetNodes(); + // Save row + newCont[i + 1] = vals; + } + } + + // Update xCAT table + $.ajax({ + type : 'POST', + url : 'lib/tabRestore.php', + dataType : 'json', + data : { + table : tableName, + cont : newCont + }, + success : function(data) { + // Create info message + var dialog = $('
    ').append(createInfoBar('Changes saved!')); + + // Open dialog + dialog.dialog({ + modal: true, + title: 'Info', + width: 400, + buttons: { + "Ok": function(){ + $(this).dialog("close"); + } + } + }); + } + }); + }); + + var undoLnk = $('Undo'); + undoLnk.click(function() { + // Get table ID + var tableId = $(this).parents('.dataTables_wrapper').attr('id').replace('_wrapper', ''); + + // Get datatable + var dTable = $('#' + tableId).dataTable(); + + // Clear entire datatable + dTable.fnClearTable(); - // Go through each row - for ( var i = 0; i < dRows.length; i++) { - // If there is row with values - if (dRows[i]) { - // Go through each column - // Ignore the 1st column because it is a button - var cols = dRows[i].childNodes; - var vals = new Object(); - for ( var j = 1; j < cols.length; j++) { - var val = cols.item(j).firstChild.nodeValue; - - // Insert quotes - if (val == ' ') { - vals[j - 1] = ''; - } else { - vals[j - 1] = val; - } - } + // Add original content back into datatable + for ( var i = 1; i < origCont.length; i++) { + dTable.fnAddData(origCont[i], true); + } - // Save row - newCont[i + 1] = vals; - } - } - - // Update xCAT table - $.ajax( { - type : 'POST', - url : 'lib/tabRestore.php', - dataType : 'json', - data : { - table : tableName, - cont : newCont - }, - success : function(data) { - alert('Changes saved'); - } - }); - }); - - var undoLnk = $('Undo'); - undoLnk.click(function() { - // Get table ID - var tableId = $(this).parents('.dataTables_wrapper').attr('id').replace('_wrapper', ''); - - // Get datatable - var dTable = $('#' + tableId).dataTable(); - - // Clear entire datatable - dTable.fnClearTable(); + // Enable editable columns (again) + // Do not make 1st column editable + $('#' + tableId + ' td:not(td:nth-child(1))').editable( + function(value, settings) { + // Get column index + var colPos = this.cellIndex; + // Get row index + var rowPos = dTable.fnGetPosition(this.parentNode); - // Add original content back into datatable - for ( var i = 1; i < origCont.length; i++) { - dTable.fnAddData(origCont[i], true); - } + // Update datatable + dTable.fnUpdate(value, rowPos, colPos); - // Enable editable columns (again) - // Do not make 1st column editable - $('#' + tableId + ' td:not(td:nth-child(1))').editable( - function(value, settings) { - // Get column index - var colPos = this.cellIndex; - // Get row index - var rowPos = dTable.fnGetPosition(this.parentNode); + return (value); + }, { + onblur : 'submit', // Clicking outside editable area submits changes + type : 'textarea', + placeholder: ' ', + height : '30px' // The height of the text area + }); + }); + + var addLnk = $('Add row'); + addLnk.click(function() { + // Create an empty row + var row = new Array(); - // Update datatable - dTable.fnUpdate(value, rowPos, colPos); + /** + * Remove button + */ + row.push(''); + for ( var i = 0; i < headers.length; i++) { + row.push(''); + } - return (value); - }, { - onblur : 'submit', // Clicking outside editable area submits changes - type : 'textarea', - placeholder: ' ', - height : '30px' // The height of the text area - }); - }); - - var addLnk = $('Add row'); - addLnk.click(function() { - // Create an empty row - var row = new Array(); + // Get table ID and name + var tableId = $(this).parents('.dataTables_wrapper').attr('id').replace('_wrapper', ''); + + // Get datatable + var dTable = $('#' + tableId).dataTable(); + + // Add the row to the data table + dTable.fnAddData(row); - /** - * Remove button - */ - row.push(''); - for ( var i = 0; i < headers.length; i++) { - row.push(''); - } + // Enable editable columns (again) + // Do not make 1st column editable + $('#' + tableId + ' td:not(td:nth-child(1))').editable( + function(value, settings) { + // Get column index + var colPos = this.cellIndex; + // Get row index + var rowPos = dTable.fnGetPosition(this.parentNode); - // Get table ID and name - var tableId = $(this).parents('.dataTables_wrapper').attr('id').replace('_wrapper', ''); - var tableName = tableId.replace('Datatable', ''); - - // Get datatable - var dTable = $('#' + tableId).dataTable(); - - // Add the row to the data table - dTable.fnAddData(row); + // Update datatable + dTable.fnUpdate(value, rowPos, colPos); - // Enable editable columns (again) - // Do not make 1st column editable - $('#' + tableId + ' td:not(td:nth-child(1))').editable( - function(value, settings) { - // Get column index - var colPos = this.cellIndex; - // Get row index - var rowPos = dTable.fnGetPosition(this.parentNode); - - // Update datatable - dTable.fnUpdate(value, rowPos, colPos); - - return (value); - }, { - onblur : 'submit', // Clicking outside editable area submits changes - type : 'textarea', - placeholder: ' ', - height : '30px' // The height of the text area - }); - }); - - // Actions - var actionsLnk = 'Actions'; - var actsMenu = createMenu([saveLnk, undoLnk, addLnk]); - - // Create an action menu - var actionsMenu = createMenu([ [ actionsLnk, actsMenu ] ]); - actionsMenu.superfish(); - actionsMenu.css('display', 'inline-block'); - actionBar.append(actionsMenu); - - // Set correct theme for action menu - actionsMenu.find('li').hover(function() { - setMenu2Theme($(this)); - }, function() { - setMenu2Normal($(this)); - }); - - // Create a division to hold actions menu - var menuDiv = $(''); - $('#' + id + 'Datatable_wrapper').prepend(menuDiv); - menuDiv.append(actionBar); - $('#' + id + 'Datatable_filter').appendTo(menuDiv); + return (value); + }, { + onblur : 'submit', // Clicking outside editable area submits changes + type : 'textarea', + placeholder: ' ', + height : '30px' // The height of the text area + }); + }); + + // Create an action menu + var actionsMenu = createMenu([saveLnk, undoLnk, addLnk]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + id + 'Datatable_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + id + 'Datatable_filter').appendTo(menuDiv); } /** * Delete a row in the data table * - * @param obj - * The object that was clicked - * @return Nothing + * @param obj The object that was clicked */ function deleteRow(obj) { - // Get table ID - var tableId = $(obj).parents('table').attr('id'); + // Get table ID + var tableId = $(obj).parents('table').attr('id'); - // Get datatable - var dTable = $('#' + tableId).dataTable(); + // Get datatable + var dTable = $('#' + tableId).dataTable(); - // Get all nodes within the datatable - var rows = dTable.fnGetNodes(); - // Get target row - var tgtRow = $(obj).parent().parent().get(0); + // Get all nodes within the datatable + var rows = dTable.fnGetNodes(); + // Get target row + var tgtRow = $(obj).parent().parent().get(0); - // Find the target row in the datatable - for ( var i in rows) { - // If the row matches the target row - if (rows[i] == tgtRow) { - // Remove row - dTable.fnDeleteRow(i, null, true); - break; - } - } + // Find the target row in the datatable + for ( var i in rows) { + // If the row matches the target row + if (rows[i] == tgtRow) { + // Remove row + dTable.fnDeleteRow(i, null, true); + break; + } + } } /** * Count the number of occurrences of a specific character in a string * - * @param c - * Character to count + * @param c Character to count * @return The number of occurrences */ String.prototype.count = function(c) { - return (this.length - this.replace(new RegExp(c, 'g'), '').length)/c.length; + return (this.length - this.replace(new RegExp(c, 'g'), '').length)/c.length; }; \ No newline at end of file diff --git a/xCAT-UI/js/configure/discover.js b/xCAT-UI/js/configure/discover.js index 82e212be5..a94aeddd2 100644 --- a/xCAT-UI/js/configure/discover.js +++ b/xCAT-UI/js/configure/discover.js @@ -1,408 +1,372 @@ -/*associate the step name with step number*/ -var steps = ['Platform', 'Complete']; +// Associate the step name with step number +var steps = [ 'Platform', 'Complete' ]; -/*associate the function with step number*/ -var initFunctions = [initSelectPlatform, complete]; +// Associate the function with step number +var initFunctions = [ initSelectPlatform, complete ]; +var nextFunctions = [ getPlatform, undefined ]; -/*associate the function witch should be called before the page changed(when click next or back) - *if there is no need to call functions, use undefined.*/ -var nextFunctions = [getPlatform, undefined]; - -/*save current step number*/ +// Save current step number var currentStep = 0; -/*save user's input*/ +// Save user's input var discoverEnv; /** - * create the discover page - * - * @return nothing + * Create the discovery page */ -function loadDiscoverPage(){ - currentStep = 0; - discoverEnv = new Object(); - - $('#discoverTab').append('
    '); - initSelectPlatform(); +function loadDiscoverPage() { + currentStep = 0; + discoverEnv = new Object(); + + $('#discoverTab').append('
    '); + initSelectPlatform(); } /** - * create the navigator buttons on the bottom of discover page - * - * @param - * - * @return nothing + * Create the navigation buttons on the bottom of discovery page */ -function createDiscoverButtons(){ - var buttonDiv = $('
    '); - var backButton = createBackButton(); - var nextButton = createNextButton(); - var cancelButton = createCancelButton(); - - if (backButton) - buttonDiv.append(backButton); - - if (nextButton) - buttonDiv.append(nextButton); - - if (cancelButton) - buttonDiv.append(cancelButton); +function createDiscoverButtons() { + var buttonDiv = $('
    '); + var backButton = createBackButton(); + var nextButton = createNextButton(); + var cancelButton = createCancelButton(); - $('#discoverContentDiv').append(buttonDiv); + if (backButton) + buttonDiv.append(backButton); + + if (nextButton) + buttonDiv.append(nextButton); + + if (cancelButton) + buttonDiv.append(cancelButton); + + $('#discoverContentDiv').append(buttonDiv); } -function createCancelButton(){ - if (0 == currentStep) - return undefined; - - if ((steps.length - 1) == currentStep) - return undefined; - - var cancelbutton = createButton('Cancel'); - cancelbutton.bind('click', function(){ - $('#discoverTab').empty(); - for (var name in discoverEnv) - removeDiscoverEnv(name); - loadDiscoverPage(); - }); - - return cancelbutton; +function createCancelButton() { + if (0 == currentStep) + return undefined; + + if ((steps.length - 1) == currentStep) + return undefined; + + var cancelbutton = createButton('Cancel'); + cancelbutton.bind('click', function() { + $('#discoverTab').empty(); + for (var name in discoverEnv) + removeDiscoverEnv(name); + loadDiscoverPage(); + }); + + return cancelbutton; } /** - * create the next button base on the currentStep, the last step does not need this button - * - * @return nothing + * Create the next button base on the current step, + * the last step does not need this button */ -function createNextButton(){ - var tempFlag = true; - if ((steps.length - 1) == currentStep) - return undefined; - - var nextButton = createButton('Next'); - nextButton.bind('click', function(){ - if (nextFunctions[currentStep]) - tempFlag = nextFunctions[currentStep]('next'); - - if (!tempFlag) - return; - currentStep ++; - initFunctions[currentStep]('next'); - }); - - return nextButton; +function createNextButton() { + var tempFlag = true; + if ((steps.length - 1) == currentStep) + return undefined; + + var nextButton = createButton('Next'); + nextButton.bind('click', function() { + if (nextFunctions[currentStep]) + tempFlag = nextFunctions[currentStep]('next'); + + if (!tempFlag) + return; + currentStep++; + initFunctions[currentStep]('next'); + }); + + return nextButton; } /** - * create the next button base on the currentStep, the first step does not need this button - * - * @return nothing + * Create the next button base on the current step, + * the first step does not need this button */ -function createBackButton(){ - var tempFlag = true; - if (0 == currentStep) - return undefined; - - var backButton = createButton('Back'); - backButton.bind('click', function(){ - if (nextFunctions[currentStep]) - tempFlag = nextFunctions[currentStep]('back'); - - if (!tempFlag) - return; - - currentStep--; +function createBackButton() { + var tempFlag = true; + if (0 == currentStep) + return undefined; - initFunctions[currentStep]('back'); - }); - - return backButton; + var backButton = createButton('Back'); + backButton.bind('click', function() { + if (nextFunctions[currentStep]) + tempFlag = nextFunctions[currentStep]('back'); + + if (!tempFlag) + return; + + currentStep--; + + initFunctions[currentStep]('back'); + }); + + return backButton; } /** - * get the input value on discover page + * Get the input value on discovery page * - * @param envName - * value's name(discoverEnv's key) - * @return - * if there is assciate value, return the value. - * else return null. + * @param envName Value name (discoverEnv key) + * @return If there is an associate value, return the value, else return NULL */ -function getDiscoverEnv(envName){ - if (discoverEnv[envName]) - return discoverEnv[envName]; - else - return ''; +function getDiscoverEnv(envName) { + if (discoverEnv[envName]) + return discoverEnv[envName]; + else + return ''; } /** - * set the input value on discover page + * Set the input value on discovery page * - * @param envName - * value's name(discoverEnv's key) - * @param envValue - * value - * @return nothing + * @param envName Value name (discoverEnv key) + * @param envValue Value */ -function setDiscoverEnv(envName, envValue){ - if (envName) - discoverEnv[envName] = envValue; +function setDiscoverEnv(envName, envValue) { + if (envName) + discoverEnv[envName] = envValue; } /** - * delete the input value on discover page + * Delete the input value on discovery page * - * @param envName - * value's name(discoverEnv's key) - * @return nothing + * @param envName Value name (discoverEnv's key) */ -function removeDiscoverEnv(envName){ - if (discoverEnv[envName]) - delete discoverEnv[envName]; +function removeDiscoverEnv(envName) { + if (discoverEnv[envName]) + delete discoverEnv[envName]; } /** - * Expand the noderange into node names. + * Expand the noderange into node names * - * @param nodeRange - * @return node names array + * @param nodeRange Node range + * @return Array of node names */ -function expandNR(nodeRange){ - var retArray = new Array(); - var tempResult; - if ('' == nodeRange) - return retArray; - - tempResult = nodeRange.match(/(.*?)\[(.*?)\](.*)/); - if (null != tempResult){ - var parts = tempResult[2].split('-'); - if (2 > parts.length) - return retArray; - - var start = Number(parts[0]); - var end = Number(parts[1]); - var len = parts[0].length; - for (var i = parts[0]; i <= parts[1]; i++){ - var ts = i.toString(); - if (ts.length < len) - ts = "000000".substring(0, (len - ts.length)) + ts; +function expandNR(nodeRange) { + var retArray = new Array(); + var tempResult; + if ('' == nodeRange) + return retArray; - retArray = retArray.concat(expandNR(tempResult[1] + ts + tempResult[3])); - } - return retArray; - } - - var tempArray = nodeRange.split('-'); - if (2 > tempArray.length){ - retArray.push(nodeRange); - return retArray; - } - - var begin = tempArray[0].match(/^(\D+)(\d+)$/); - if (2 > begin){ - retArray.push(nodeRange); - return retArray; - } - - var end = tempArray[1].match(/^(\D+)(\d+)$/); - if (2 > end){ - retArray.push(nodeRange); - return retArray; - } - - if (begin[1] != end[1]){ - retArray.push(nodeRange); - return retArray; - } - - var prefix = begin[1]; - var len = begin[2].length; - for (var i = begin[2]; i <= end[2]; i++){ - var ts = i.toString(); - if (ts.length < len) - ts = "000000".substring(0, (len - ts.length)) + ts; - retArray.push(prefix + ts); - } - - return retArray; + tempResult = nodeRange.match(/(.*?)\[(.*?)\](.*)/); + if (null != tempResult) { + var parts = tempResult[2].split('-'); + if (2 > parts.length) + return retArray; + + var len = parts[0].length; + for (var i = parts[0]; i <= parts[1]; i++) { + var ts = i.toString(); + if (ts.length < len) + ts = "000000".substring(0, (len - ts.length)) + ts; + + retArray = retArray.concat(expandNR(tempResult[1] + ts + + tempResult[3])); + } + + return retArray; + } + + var tempArray = nodeRange.split('-'); + if (2 > tempArray.length) { + retArray.push(nodeRange); + return retArray; + } + + var begin = tempArray[0].match(/^(\D+)(\d+)$/); + if (2 > begin) { + retArray.push(nodeRange); + return retArray; + } + + var end = tempArray[1].match(/^(\D+)(\d+)$/); + if (2 > end) { + retArray.push(nodeRange); + return retArray; + } + + if (begin[1] != end[1]) { + retArray.push(nodeRange); + return retArray; + } + + var prefix = begin[1]; + var len = begin[2].length; + for (var i = begin[2]; i <= end[2]; i++) { + var ts = i.toString(); + if (ts.length < len) + ts = "000000".substring(0, (len - ts.length)) + ts; + retArray.push(prefix + ts); + } + + return retArray; } /** - * collect all inputs' value from the page + * Collect all input values from the page * - * @return true: this step is correct, can go to the next page - * false: this step contains error. + * @return True if this step is correct and can go to the next page, false if this step contains error */ -function collectInputValue(){ - $('#discoverContentDiv input[type=text]').each(function(){ - var name = $(this).attr('name'); - var value = $(this).attr('value'); - if ('' != value) - setDiscoverEnv(name, value); - else - removeDiscoverEnv(name); - }); - - return true; +function collectInputValue() { + $('#discoverContentDiv input[type=text]').each(function() { + var name = $(this).attr('name'); + var value = $(this).attr('value'); + if ('' != value) + setDiscoverEnv(name, value); + else + removeDiscoverEnv(name); + }); + + return true; } /** - * verify the ip address, + * Verify the IP address * - * @param - * - * @return true: for valid IP address - * false : for invalid IP address + * @param ip IP address + * @return True if IP address is valid, false otherwise */ -function verifyIp(ip){ +function verifyIp(ip) { var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-4])$/; return reg.test(ip); } /** - * transfer ip into decimal + * Transalate IP into decimal * - * @param - * - * @return decimal type ip address + * @param ip IP address + * @return Decimal type for IP address */ -function ip2Decimal(ip){ +function ip2Decimal(ip) { if (!verifyIp(ip)) return 0; - + var retIp = 0; var tempArray = ip.split('.'); - for (var i = 0; i < 4; i++){ + for (var i = 0; i < 4; i++) { retIp = (retIp << 8) | parseInt(tempArray[i]); } - - //change the int into unsigned int type + + // Change the int into unsigned int type retIp = retIp >>> 0; return retIp; } /** - * calculate the end IP address by start IP and the number of IP range. - * - * @param - * - * @return + * Calculate the ending IP address from the starting IP address and the IP range number. */ -function calcEndIp(ipStart, num){ +function calcEndIp(ipStart, num) { var sum = 0; var tempNum = Number(num); var temp = /(\d+)\.(\d+)\.(\d+)\.(\d+)/; var ipArray = temp.exec(ipStart); - + ipArray.shift(); sum = Number(ipArray[3]) + tempNum; - if (sum <= 254){ + if (sum <= 254) { ipArray[3] = sum; return (ipArray.join('.')); } - + ipArray[3] = sum % 254; - + sum = Number(ipArray[2]) + parseInt(sum / 254); - if (sum <= 255){ + if (sum <= 255) { ipArray[2] = sum; return (ipArray.join('.')); } - + ipArray[2] = sum % 255; - + sum = Number(ipArray[1]) + parseInt(sum / 255); - if (sum <= 255){ + if (sum <= 255) { ipArray[1] = sum; return (ipArray.join('.')); } - + ipArray[1] = sum % 255; ipArray[0] = ipArray[0] + parseInt(sum / 255); return (ipArray.join('.')); } /** - * Step 1: show the wizard's function - * platform selector(system P or system X) - * - * @return nothing + * Step 1: Show the wizard's function platform selector (System p or System x) */ -function initSelectPlatform(){ - var type = ''; - - $('#discoverContentDiv').empty(); - $('.tooltip').remove(); - - var selectPlatform = $('

    ' + steps[currentStep] + '

    '); - - var infoMsg = 'This wizard will guide you through the process of defining the naming conventions within' + - 'your cluster, discovering the hardware on your network, and automatically defining it in the xCAT' + - 'database. Choose which type of hardware you want to discover, and then click Next.'; - var info = createInfoBar(infoMsg); - selectPlatform.append(info); - - var hwList = $('
      Platforms available:
    '); - hwList.append('
  • '); - hwList.append('
  • BladeCenter
  • '); - hwList.append('
  • System p hardware (P7 IH)
  • '); - hwList.append('
  • System p hardware (Non P7 IH)
  • '); - - hwList.find('li').css('padding', '2px 10px'); - selectPlatform.append(hwList); - - $('#discoverContentDiv').append(selectPlatform); - - if (getDiscoverEnv('machineType')) - type = getDiscoverEnv('machineType'); - else - type = 'ih'; - - $('#discoverContentDiv #' + type).attr('checked', 'checked'); - createDiscoverButtons(); +function initSelectPlatform() { + var type = ''; + + $('#discoverContentDiv').empty(); + $('.tooltip').remove(); + + var selectPlatform = $('

    ' + steps[currentStep] + '

    '); + + var infoMsg = 'This wizard will guide you through the process of defining the naming conventions within' + + 'your cluster, discovering the hardware on your network, and automatically defining it in the xCAT' + + 'database. Choose which type of hardware you want to discover, and then click Next.'; + var info = createInfoBar(infoMsg); + selectPlatform.append(info); + + var hwList = $('
      Platforms available:
    '); + hwList.append('
  • '); + hwList.append('
  • BladeCenter
  • '); + hwList.append('
  • System p hardware (P7 IH)
  • '); + hwList.append('
  • System p hardware (Non P7 IH)
  • '); + + hwList.find('li').css('padding', '2px 10px'); + selectPlatform.append(hwList); + + $('#discoverContentDiv').append(selectPlatform); + + if (getDiscoverEnv('machineType')) + type = getDiscoverEnv('machineType'); + else + type = 'ih'; + + $('#discoverContentDiv #' + type).attr('checked', 'checked'); + createDiscoverButtons(); } /** * Step 1: Get the platform type - * - * @return true */ -function getPlatform(){ - var radioValue = $('#discoverContentDiv :checked').attr('id'); - var platformObj; - switch(radioValue){ - case 'ih': - case 'nonih': - platformObj = new hmcPlugin(); - break; - case 'idataplex': - platformObj = new ipmiPlugin(); - break; - case 'blade': - break; - } - - steps = ['Platform'].concat(platformObj.getStep(), 'compelte'); - initFunctions = [initSelectPlatform].concat(platformObj.getInitFunction(), complete); - nextFunctions = [getPlatform].concat(platformObj.getNextFunction(), undefined); - setDiscoverEnv('machineType', radioValue); - return true; +function getPlatform() { + var radioValue = $('#discoverContentDiv :checked').attr('id'); + var platformObj = null; + switch (radioValue) { + case 'ih': + case 'nonih': + platformObj = new hmcPlugin(); + break; + case 'idataplex': + platformObj = new ipmiPlugin(); + break; + case 'blade': + break; + } + + steps = [ 'Platform' ].concat(platformObj.getStep(), 'compelte'); + initFunctions = [ initSelectPlatform ].concat(platformObj.getInitFunction(), complete); + nextFunctions = [ getPlatform ].concat(platformObj.getNextFunction(), undefined); + setDiscoverEnv('machineType', radioValue); + return true; } /** - * last step: complete - * - * @param - * - * @return + * Last step: Complete */ -function complete(){ - $('#discoverContentDiv').empty(); - $('.tooltip').remove(); - var showStr = '

    ' + steps[currentStep] + '

    '; - showStr += 'You can go to the nodes page to check nodes which were defined just now.'; - $('#discoverContentDiv').append(showStr); - - createDiscoverButtons(); +function complete() { + $('#discoverContentDiv').empty(); + $('.tooltip').remove(); + var showStr = '

    ' + steps[currentStep] + '

    '; + showStr += 'You can go to the nodes page to check nodes which were defined just now.'; + $('#discoverContentDiv').append(showStr); + + createDiscoverButtons(); } \ No newline at end of file diff --git a/xCAT-UI/js/configure/service.js b/xCAT-UI/js/configure/service.js new file mode 100644 index 000000000..ddd422034 --- /dev/null +++ b/xCAT-UI/js/configure/service.js @@ -0,0 +1,525 @@ +/** + * Global variables + */ +var topPriority = 0; + +/** + * Load the service portal's provision page + * + * @param tabId Tab ID where page will reside + */ +function loadServicePage(tabId) { + // Create info bar + var infoBar = createInfoBar('Select a platform to configure, then click Ok.'); + + // Create self-service portal page + var tabId = 'serviceTab'; + var servicePg = $('
    '); + $('#' + tabId).append(infoBar, servicePg); + + // Create radio buttons for platforms + var hwList = $('
      Platforms available:
    '); + var esx = $('
  • ESX
  • '); + var kvm = $('
  • KVM
  • '); + var zvm = $('
  • z\/VM
  • '); + + hwList.append(esx); + hwList.append(kvm); + hwList.append(zvm); + servicePg.append(hwList); + + /** + * Ok + */ + var okBtn = createButton('Ok'); + okBtn.bind('click', function(event) { + var configTabs = getConfigTab(); + + // Get hardware that was selected + var hw = $(this).parent().find('input[name="hw"]:checked').val(); + var newTabId = hw + 'ProvisionTab'; + + if ($('#' + newTabId).size() > 0){ + configTabs.select(newTabId); + } else { + var title = ''; + + // Create an instance of the plugin + var plugin = null; + switch (hw) { + case "kvm": + plugin = new kvmPlugin(); + title = 'KVM'; + break; + case "esx": + plugin = new esxPlugin(); + title = 'ESX'; + break; + case "zvm": + plugin = new zvmPlugin(); + title = 'z/VM'; + + // Get zVM host names + if (!$.cookie('srv_zvm')){ + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webportal', + tgt : '', + args : 'lszvm', + msg : '' + }, + + success : function(data) { + setzVMCookies(data); + } + }); + } + + break; + } + + // Select tab + configTabs.add(newTabId, title, '', true); + configTabs.select(newTabId); + plugin.loadConfigPage(newTabId); + } + }); + + servicePg.append(okBtn); +} + +/** + * Load the user panel where users can be created, modified, or deleted + * + * @param panelId Panel ID + */ +function loadUserPanel(panelId) { + // Get users list + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'passwd', + msg : panelId + }, + + success : loadUserTable + }); +} + +/** + * Load user datatable + * + * @param data HTTP request data + */ +function loadUserTable(data) { + // Get response + var rsp = data.rsp; + // Get panel ID + var panelId = data.msg; + + // Wipe panel clean + $('#' + panelId).empty(); + + // Add info bar + $('#' + panelId).append(createInfoBar('Create, edit, and delete users for the self-service portal. Double-click on a cell to edit a users properties. Click outside the table to save changes. Hit the Escape key to ignore changes.')); + + // Get table headers + // The table headers in the passwd table are: key, username, password, cryptmethod, comments, and disable + var headers = new Array('priority', 'username', 'password', 'max-vm'); + + // Create a new datatable + var tableId = 'userDatatable'; + var table = new DataTable(tableId); + + // Add column for the checkbox + headers.unshift(''); + table.init(headers); + headers.shift(); + + // Append datatable to panel + $('#' + panelId).append(table.object()); + + // Add table rows + // Start with the 2nd row (1st row is the headers) + for ( var i = 1; i < rsp.length; i++) { + // Split into columns + var tmp = rsp[i].split(','); + + // Go through each column + for (var j = 0; j < tmp.length; j++) { + // Replace quote + tmp[j] = tmp[j].replace(new RegExp('"', 'g'), ''); + } + + // Only add users having the key = xcat + if (tmp[0] == 'xcat') { + // Columns are: priority, username, password, and max-vm + var cols = new Array('', tmp[1], tmp[2], ''); + + // Add remove button where id = user name + cols.unshift(''); + + // Add row + table.add(cols); + } + } + + // Turn table into datatable + $('#' + tableId).dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%", + "bAutoWidth": true + }); + + // Create action bar + var actionBar = $('
    '); + + var createLnk = $('Create'); + createLnk.click(function() { + openCreateUserDialog(); + }); + + var deleteLnk = $('Delete'); + deleteLnk.click(function() { + var users = getNodesChecked(tableId); + if (users) { + openDeleteUserDialog(users); + } + }); + + var refreshLnk = $('Refresh'); + refreshLnk.click(function() { + loadUserPanel(panelId); + }); + + // Create an action menu + var actionsMenu = createMenu([createLnk, deleteLnk, refreshLnk]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + tableId + '_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + tableId + '_filter').appendTo(menuDiv); + + // Get policy data + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'policy', + msg : tableId + }, + + success : loadUserTable4Policy + }); + + /** + * Enable editable cells + */ + // Do not make 1st or 2nd column editable + $('#' + tableId + ' td:not(td:nth-child(1),td:nth-child(2))').editable( + function(value, settings) { + // If users did not make changes, return the value directly + // jeditable saves the old value in this.revert + if ($(this).attr('revert') == value){ + return value; + } + + var panelId = $(this).parents('.ui-accordion-content').attr('id'); + + // Get column index + var colPos = this.cellIndex; + + // Get row index + var dTable = $('#' + tableId).dataTable(); + var rowPos = dTable.fnGetPosition(this.parentNode); + + // Update datatable + dTable.fnUpdate(value, rowPos, colPos, false); + + // Get table headers + var headers = $('#' + nodesTableId).parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); + + // Get user attributes + var priority = $(this).parent().find('td:eq(1)').text(); + var user = $(this).parent().find('td:eq(2)').text(); + var password = $(this).parent().find('td:eq(3)').text(); + var maxVM = $(this).parent().find('td:eq(4)').text(); + + // Send command to change user attributes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'updateuser;' + priority + ';' + user + ';' + password + ';' + maxVM, + msg : panelId + }, + success : updatePanel + }); + + return value; + }, { + onblur : 'submit', // Clicking outside editable area submits changes + type : 'textarea', + placeholder: ' ', + event : "dblclick", // Double click and edit + height : '30px' // The height of the text area + }); + + // Resize accordion + $('#' + tableId).parents('.ui-accordion').accordion('resize'); +} + +/** + * Update user datatable for policy + * + * @param data HTTP request data + */ +function loadUserTable4Policy(data) { + // Get response + var rsp = data.rsp; + // Get datatable ID + var tableId = data.msg; + + // Get datatable + var datatable = $('#' + tableId).dataTable(); + + // Update max-vm column + // The data coming back contains: priority, name, host, commands, noderange, parameters, time, rule, comments, disable + + // Start with the 2nd row (1st row is the headers) + topPriority = 0; + for ( var i = 1; i < rsp.length; i++) { + // Split into columns + var tmp = rsp[i].split(','); + + // Go through each column + for (var j = 0; j < tmp.length; j++) { + // Replace quote + tmp[j] = tmp[j].replace(new RegExp('"', 'g'), ''); + } + + // Get the row containing the user name + var rowPos = -1; + if (tmp[1]) + rowPos = findRow(tmp[1], '#' + tableId, 2); + + // Update the priority and max-vm columns + if (rowPos > -1) { + var maxVM = tmp[8].replace('max-vm:', ''); + maxVM = maxVM.replace(';', ''); + datatable.fnUpdate(maxVM, rowPos, 4, false); + + var priority = tmp[0]; + datatable.fnUpdate(priority, rowPos, 1, false); + + // Set the highest priority + if (priority > topPriority) + topPriority = priority; + } + } + + // Adjust column sizes + adjustColumnSize(tableId); + + // Resize accordion + $('#' + tableId).parents('.ui-accordion').accordion('resize'); +} + +/** + * Open a dialog to create a user + */ +function openCreateUserDialog() { + var dialogId = 'createUser'; + var dialog = $('
    '); + var info = createInfoBar('Create an xCAT user. A priority will be generated for the new user.'); + dialog.append(info); + + // Generate the user priority + var userPriority = parseFloat(topPriority) + 0.01; + userPriority = userPriority.toPrecision(3); + + // Create node inputs + dialog.append($('
    ')); + dialog.append($('
    ')); + dialog.append($('
    ')); + dialog.append($('
    ')); + + dialog.dialog({ + title: 'Create user', + modal: true, + width: 400, + close: function(){ + $(this).remove(); + }, + buttons: { + "OK" : function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Change dialog buttons + $('#' + dialogId).dialog('option', 'buttons', { + 'Close':function(){ + $(this).dialog('close'); + } + }); + + var priority = $(this).find('input[name="priority"]').val(); + var user = $(this).find('input[name="username"]').val(); + var password = $(this).find('input[name="password"]').val(); + var maxVM = $(this).find('input[name="maxvm"]').val(); + + // Verify inputs are provided + if (!user || !password || !maxVM) { + var warn = createWarnBar('Please provide a value for each missing field!'); + warn.prependTo($(this)); + } else { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'updateuser;' + priority + ';' + user + ';' + password + ';' + maxVM, + msg : dialogId + }, + success : updatePanel + }); + + // Update highest priority + topPriority = priority; + } + }, + "Cancel": function(){ + $(this).dialog('close'); + } + } + }); +} + +/** + * Update dialog + * + * @param data HTTP request data + */ +function updatePanel(data) { + var dialogId = data.msg; + var infoMsg; + + // Create info message + if (jQuery.isArray(data.rsp)) { + infoMsg = ''; + for (var i in data.rsp) { + infoMsg += data.rsp[i] + '
    '; + } + } else { + infoMsg = data.rsp; + } + + // Create info bar with close button + var infoBar = $('
    ').css('margin', '5px 0px'); + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px' + }); + + // Create close button to close info bar + var close = $('').css({ + 'display': 'inline-block', + 'float': 'right' + }).click(function() { + $(this).parent().remove(); + }); + + var msg = $('
    ' + infoMsg + '
    ').css({ + 'display': 'inline-block', + 'width': '85%' + }); + + infoBar.append(icon, msg, close); + infoBar.prependTo($('#' + dialogId)); +} + +/** + * Open dialog to confirm user delete + * + * @param users Users to delete + */ +function openDeleteUserDialog(users) { + // Create form to delete disk to pool + var dialogId = 'deleteUser'; + var deleteForm = $('
    '); + + // Create info bar + var info = createInfoBar('Are you sure you want to delete ' + users.replace(new RegExp(',', 'g'), ', ') + '?'); + deleteForm.append(info); + + // Open dialog to delete user + deleteForm.dialog({ + title:'Delete user', + modal: true, + width: 400, + close: function(){ + $(this).remove(); + }, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + // Delete user + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'deleteuser;' + users, + msg : dialogId + }, + success : updatePanel + }); + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); +} + +/** + * Round a floating point to a given precision + * + * @param value Floating point + * @param precision Decimal precision + * @returns Floating point number + */ +function toFixed(value, precision) { + var power = Math.pow(10, precision || 0); + return String(Math.round(value * power) / power); +} \ No newline at end of file diff --git a/xCAT-UI/js/configure/update.js b/xCAT-UI/js/configure/update.js index 0478576f5..c8e41db07 100644 --- a/xCAT-UI/js/configure/update.js +++ b/xCAT-UI/js/configure/update.js @@ -1,321 +1,310 @@ /** * Load update page - * - * @return Nothing */ function loadUpdatePage() { - var repositoryDiv = $('
    '); - var rpmDiv = $('
    '); - var statusDiv = createStatusBar("update"); - statusDiv.hide(); + var repositoryDiv = $('
    '); + var rpmDiv = $('
    '); + var statusDiv = createStatusBar("update"); + statusDiv.hide(); - $('#updateTab').append(statusDiv); - $('#updateTab').append('
    '); - $('#updateTab').append(repositoryDiv); - $('#updateTab').append(rpmDiv); + $('#updateTab').append(statusDiv); + $('#updateTab').append('
    '); + $('#updateTab').append(repositoryDiv); + $('#updateTab').append(rpmDiv); - var infoBar = createInfoBar('Select the repository to use and the RPMs to update, then click Update.'); - repositoryDiv.append(infoBar); + var infoBar = createInfoBar('Select the repository to use and the RPMs to update, then click Update.'); + repositoryDiv.append(infoBar); - repositoryDiv.append("
    Repository
    "); - $.ajax( { - url : 'lib/systemcmd.php', - dataType : 'json', - data : { - cmd : 'ostype' - }, + repositoryDiv.append("
    Repository
    "); + $.ajax( { + url : 'lib/systemcmd.php', + dataType : 'json', + data : { + cmd : 'ostype' + }, - success : showRepository - }); + success : showRepository + }); - rpmDiv.append("
    "); - $.ajax( { - url : 'lib/systemcmd.php', - dataType : 'json', - data : { - cmd : 'rpm -q xCAT-client perl-xCAT xCAT-server xCAT xCAT-rmc xCAT-UI' - }, + rpmDiv.append("
    "); + $.ajax( { + url : 'lib/systemcmd.php', + dataType : 'json', + data : { + cmd : 'rpm -q xCAT-client perl-xCAT xCAT-server xCAT xCAT-rmc xCAT-UI' + }, - success : showRpmInfo - }); + success : showRpmInfo + }); } /** - * Show the RPM Repository, it can use user's last choice and input + * Show the RPM repository (it can use the user's last choice and input) * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function showRepository(data) { - var develRepository = ""; - var stableRepository = ""; - var show = ""; + var develRepository = ""; + var stableRepository = ""; + var show = ""; - // Get the corresponding repository by OS Type - if (data.rsp == "aix") { - // No repository exists for AIX on sourceforge! - develRepository = "http://xcat.sourceforge.net/aix/devel/xcat-core/"; - stableRepository = "http://xcat.sourceforge.net/aix/xcat-core/"; - } else { - develRepository = "http://sourceforge.net/projects/xcat/files/yum/devel/xcat-core/"; - stableRepository = "http://sourceforge.net/projects/xcat/files/yum/stable/xcat-core/"; - } + // Get the corresponding repository by OS Type + if (data.rsp == "aix") { + // No repository exists for AIX on Sourceforge! + develRepository = "http://xcat.sourceforge.net/aix/devel/xcat-core/"; + stableRepository = "http://xcat.sourceforge.net/aix/xcat-core/"; + } else { + develRepository = "http://sourceforge.net/projects/xcat/files/yum/devel/xcat-core/"; + stableRepository = "http://sourceforge.net/projects/xcat/files/yum/stable/xcat-core/"; + } - var repoList = $('
      '); + var repoList = $('
        '); - // Display the Devel Repository, remember user's last selection - show = show + "
      1. "; - show = show + "Development: " + develRepository + "
      2. "; - repoList.append(show); + // Display the Devel Repository, remember user's last selection + show = show + "
      3. "; + show = show + "Development: " + develRepository + "
      4. "; + repoList.append(show); - // Display the Stable Repository, remember user's last selection - show = "
      5. "; - show = show + "Stable: " + stableRepository + "
      6. "; - repoList.append(show); + // Display the Stable Repository, remember user's last selection + show = "
      7. "; + show = show + "Stable: " + stableRepository + "
      8. "; + repoList.append(show); - // Display the Input Repository, remember user's last selection - if (($.cookie('xcatrepository')) && ($.cookie('xcatrepository') != 1) - && ($.cookie('xcatrepository') != 2)) { - show = "
      9. Other: "; - show += ""; - } else { - show = "
      10. Other: "; - show += ""; - } - repoList.append(show); - - $('#repository fieldset').append(repoList); + // Display the Input Repository, remember user's last selection + if (($.cookie('xcatrepository')) && ($.cookie('xcatrepository') != 1) + && ($.cookie('xcatrepository') != 2)) { + show = "
      11. Other: "; + show += ""; + } else { + show = "
      12. Other: "; + show += ""; + } + repoList.append(show); + + $('#repository fieldset').append(repoList); } /** * Show all xCAT RPMs * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function showRpmInfo(data) { - var rpms = null; - var show = ""; - var rpmNames = new Array("xCAT-client", "perl-xCAT", "xCAT-server", "xCAT", "xCAT-rmc", - "xCAT-UI"); - var temp = 0; - if (null == data.rsp) { - $('#rpm fieldset').append("Error getting RPMs!"); - return; - } + var rpms = null; + var show = ""; + var rpmNames = new Array("xCAT-client", "perl-xCAT", "xCAT-server", "xCAT", "xCAT-rmc", + "xCAT-UI"); + var temp = 0; + if (null == data.rsp) { + $('#rpm fieldset').append("Error getting RPMs!"); + return; + } - rpms = data.rsp.split(/\n/); - - // No rpm installed, return - if (1 > rpms.length) { - $('#rpm fieldset').append("No RPMs installed!"); - return; - } + rpms = data.rsp.split(/\n/); + + // No rpm installed, return + if (1 > rpms.length) { + $('#rpm fieldset').append("No RPMs installed!"); + return; + } - // Clear the old data - $('#rpm fieldset').children().remove(); - $('#rpm fieldset').append("xCAT RPMs"); - show = ""; - show += ""; - show += ""; - show += ""; - show += ""; - for (temp = 0; temp < rpms.length; temp++) { - // Empty line continue - if (!rpms[temp]) { - continue; - } + // Clear the old data + $('#rpm fieldset').children().remove(); + $('#rpm fieldset').append("xCAT RPMs"); + show = "
        Package NameVersion
        "; + show += ""; + show += ""; + show += ""; + show += ""; + for (temp = 0; temp < rpms.length; temp++) { + // Empty line continue + if (!rpms[temp]) { + continue; + } - // The RPM is not installed, continue - if (rpms[temp].indexOf("not") != -1) { - continue; - } + // The RPM is not installed, continue + if (rpms[temp].indexOf("not") != -1) { + continue; + } - // Show the version in table - show += ""; - show += ""; - show += ""; - show += ""; - } - show += "
        Package NameVersion
        " + rpmNames[temp] + "" - + rpms[temp].substr(rpmNames[temp].length + 1) + "
        "; - show += ""; - $('#rpm fieldset').append(show); + // Show the version in table + show += ""; + show += ""; + show += "" + rpmNames[temp] + "" + + rpms[temp].substr(rpmNames[temp].length + 1) + ""; + show += ""; + } + show += ""; + show += ""; + $('#rpm fieldset').append(show); - // Add the update button - var updateButton = createButton('Update'); - $('#rpm fieldset').append(updateButton); - updateButton.bind('click', function() { - updateRpm(); - }); + // Add the update button + var updateButton = createButton('Update'); + $('#rpm fieldset').append(updateButton); + updateButton.bind('click', function() { + updateRpm(); + }); } /** * Select all checkboxes - * - * @return Nothing */ function updateSelectAll() { - var check_status = $('#selectall').attr('checked'); - $('input:checkbox').attr('checked', check_status); + var check_status = $('#selectall').attr('checked'); + $('input:checkbox').attr('checked', check_status); } /** * Update selected xCAT RPMs - * - * @return Nothing */ function updateRpm() { - // Remove any warning messages - $('#updateTab').find('.ui-state-error').remove(); + // Remove any warning messages + $('#updateTab').find('.ui-state-error').remove(); - var rpmPath = $('input[type=radio]:checked').val(); - var rpmPathType = "0"; - var rpms = ""; - var temp = ""; + var rpmPath = $('input[type=radio]:checked').val(); + var rpmPathType = "0"; + var rpms = ""; + var temp = ""; - if (undefined == rpmPath) { - rpmPath = ""; - } + if (undefined == rpmPath) { + rpmPath = ""; + } - // Select other and we should use the value in the input - if ("" == rpmPath) { - // Store repo in a cookie - rpmPath = $('#repositoryaddr').val(); - rpmPathType = rpmPath; - } else { - if (-1 == rpmPath.toLowerCase().indexOf("devel")) { - rpmPathType = "2"; - } else { - rpmPathType = "1"; - } - } + // Select other and we should use the value in the input + if ("" == rpmPath) { + // Store repo in a cookie + rpmPath = $('#repositoryaddr').val(); + rpmPathType = rpmPath; + } else { + if (-1 == rpmPath.toLowerCase().indexOf("devel")) { + rpmPathType = "2"; + } else { + rpmPathType = "1"; + } + } - $("input[type=checkbox]:checked").each(function() { - temp = $(this).val(); - if ("" == temp) { - return true; - } + $("input[type=checkbox]:checked").each(function() { + temp = $(this).val(); + if ("" == temp) { + return true; + } - var pattern = new RegExp("^" + temp + ",|," + temp + ","); - if (pattern.test(rpms)) { - return true; - } - rpms = rpms + temp + ","; - }); + var pattern = new RegExp("^" + temp + ",|," + temp + ","); + if (pattern.test(rpms)) { + return true; + } + + rpms = rpms + temp + ","; + }); - if (0 < rpms.length) { - rpms = rpms.slice(0, -1); - } + if (0 < rpms.length) { + rpms = rpms.slice(0, -1); + } - // Check RPM and repository - var errMsg = ''; - if (!rpms) { - errMsg = "Please select an RPM!
        "; - } + // Check RPM and repository + var errMsg = ''; + if (!rpms) { + errMsg = "Please select an RPM!
        "; + } - if (!rpmPath) { - errMsg += "Please select or specify a repository!"; - } + if (!rpmPath) { + errMsg += "Please select or specify a repository!"; + } - if (!rpms || !rpmPath) { - // Show warning message - var warn = createWarnBar(errMsg); - warn.prependTo($('#updateTab')); - return; - } + if (!rpms || !rpmPath) { + // Show warning message + var warn = createWarnBar(errMsg); + warn.prependTo($('#updateTab')); + return; + } - // Remember users' choice and input - $.cookie('xcatrepository', rpmPathType, { - path : '/xcat', - expires : 10 - }); + // Remember users' choice and input + $.cookie('xcatrepository', rpmPathType, { + path : '/xcat', + expires : 10 + }); - $('#update').show(); - $('#update div').empty(); - $('#update div').append("

        Updating " + rpms + " from " + rpmPath + "

        "); - $('#update div').append(""); - $('#rpm button').attr('disabled', 'true'); + $('#update').show(); + $('#update div').empty(); + $('#update div').append("

        Updating " + rpms + " from " + rpmPath + "

        "); + $('#update div').append(""); + $('#rpm button').attr('disabled', 'true'); - // Send the update command to server - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'update;' + rpms + ";" + rpmPath, - msg : '' - }, + // Send the update command to server + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'update;' + rpms + ";" + rpmPath, + msg : '' + }, - success : showUpdateResult - }); + success : showUpdateResult + }); } /** * Show the results of the RPM update * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function showUpdateResult(data) { - var temp = 0; - $('#loadingpic').remove(); + var temp = 0; + $('#loadingpic').remove(); - var resArray = data.rsp[0].split(/\n/); - if (0 < resArray.length) { - // Show last lines - if (('' == resArray[resArray.length - 1]) && (resArray.length > 1)) { - $('#update div').append('
        ' + resArray[resArray.length - 2] + '
        '); - } else { - $('#update div').append('
        ' + resArray[resArray.length - 1] + '
        '); - } + var resArray = data.rsp[0].split(/\n/); + if (0 < resArray.length) { + // Show last lines + if (('' == resArray[resArray.length - 1]) && (resArray.length > 1)) { + $('#update div').append('
        ' + resArray[resArray.length - 2] + '
        '); + } else { + $('#update div').append('
        ' + resArray[resArray.length - 1] + '
        '); + } - // Create link to show details - $('#update div').append('
        Show details'); - $('#update div a').css( { - 'color' : '#0000FF', - 'cursor' : 'pointer' - }).bind('click', function() { - // Toggle details and change text - $('#resDetail').toggle(); - if ($('#update div a').text() == 'Show details') { - $('#update div a').text('Hide details'); - } else { - $('#update div a').text('Show details'); - } - }); + // Create link to show details + $('#update div').append('
        Show details'); + $('#update div a').css( { + 'color' : '#0000FF', + 'cursor' : 'pointer' + }).bind('click', function() { + // Toggle details and change text + $('#resDetail').toggle(); + if ($('#update div a').text() == 'Show details') { + $('#update div a').text('Hide details'); + } else { + $('#update div a').text('Show details'); + } + }); - var resDetail = $('
        ');
        -		resDetail.hide();
        -		$('#update div').append(resDetail);
        -		for (temp = 0; temp < resArray.length; temp++) {
        -			resDetail.append(resArray[temp] + '
        '); - } - } + var resDetail = $('
        ');
        +        resDetail.hide();
        +        $('#update div').append(resDetail);
        +        for (temp = 0; temp < resArray.length; temp++) {
        +            resDetail.append(resArray[temp] + '
        '); + } + } - // Update the rpm info - $.ajax( { - url : 'lib/systemcmd.php', - dataType : 'json', - data : { - cmd : 'rpm -q xCAT-client perl-xCAT xCAT-server xCAT xCAT-rmc xCAT-UI' - }, + // Update the rpm info + $.ajax( { + url : 'lib/systemcmd.php', + dataType : 'json', + data : { + cmd : 'rpm -q xCAT-client perl-xCAT xCAT-server xCAT xCAT-rmc xCAT-UI' + }, - success : showRpmInfo - }); + success : showRpmInfo + }); - $('#rpm button').attr('disabled', ''); + $('#rpm button').attr('disabled', ''); } \ No newline at end of file diff --git a/xCAT-UI/js/custom/blade.js b/xCAT-UI/js/custom/blade.js index b181089f6..d153a179c 100644 --- a/xCAT-UI/js/custom/blade.js +++ b/xCAT-UI/js/custom/blade.js @@ -2,13 +2,11 @@ * Execute when the DOM is fully loaded */ $(document).ready(function() { - // Load utility scripts (if any) + // Load utility scripts (if any) }); /** * Constructor - * - * @return Nothing */ var bladePlugin = function() { @@ -17,9 +15,7 @@ var bladePlugin = function() { /** * Clone node (service page) * - * @param node - * Node to clone - * @return Nothing + * @param node Node to clone */ bladePlugin.prototype.serviceClone = function(node) { @@ -28,172 +24,160 @@ bladePlugin.prototype.serviceClone = function(node) { /** * Load provision page (service page) * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ bladePlugin.prototype.loadServiceProvisionPage = function(tabId) { - + }; /** * Show node inventory (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ bladePlugin.prototype.loadServiceInventory = function(data) { - + }; /** * Load node inventory * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ bladePlugin.prototype.loadInventory = function(data) { - var args = data.msg.split(','); - var tabId = args[0].replace('out=', ''); - var node = args[1].replace('node=', ''); - - // Get node inventory - var inv = data.rsp; + var args = data.msg.split(','); + var tabId = args[0].replace('out=', ''); + var node = args[1].replace('node=', ''); + + // Get node inventory + var inv = data.rsp; - // Remove loader - $('#' + tabId).find('img').remove(); + // Remove loader + $('#' + tabId).find('img').remove(); - // Create division to hold inventory - var invDiv = $('
        '); - - // Create a fieldset - var fieldSet = $('
        '); - var legend = $('Hardware'); - fieldSet.append(legend); - var oList = $('
          '); - fieldSet.append(oList); - invDiv.append(fieldSet); + // Create division to hold inventory + var invDiv = $('
          '); + + // Create a fieldset + var fieldSet = $('
          '); + var legend = $('Hardware'); + fieldSet.append(legend); + var oList = $('
            '); + fieldSet.append(oList); + invDiv.append(fieldSet); - // Loop through each line - var item; - for (var k = 0; k < inv.length; k++) { - // Remove node name in front - var str = inv[k].replace(node + ': ', ''); - str = jQuery.trim(str); + // Loop through each line + var item; + for (var k = 0; k < inv.length; k++) { + // Remove node name in front + var str = inv[k].replace(node + ': ', ''); + str = jQuery.trim(str); - // Append the string to a list - item = $('
          1. '); - item.append(str); - oList.append(item); - } + // Append the string to a list + item = $('
          2. '); + item.append(str); + oList.append(item); + } - // Append to inventory form - $('#' + tabId).append(invDiv); + // Append to inventory form + $('#' + tabId).append(invDiv); }; /** * Load clone page * - * @param node - * Source node to clone - * @return Nothing + * @param node Source node to clone */ bladePlugin.prototype.loadClonePage = function(node) { - // Get nodes tab - var tab = getNodesTab(); - var newTabId = node + 'CloneTab'; + // Get nodes tab + var tab = getNodesTab(); + var newTabId = node + 'CloneTab'; - // If there is no existing clone tab - if (!$('#' + newTabId).length) { - // Create info bar - var infoBar = createInfoBar('Not supported'); + // If there is no existing clone tab + if (!$('#' + newTabId).length) { + // Create info bar + var infoBar = createInfoBar('Not supported'); - // Create clone form - var cloneForm = $('
            '); - cloneForm.append(infoBar); + // Create clone form + var cloneForm = $('
            '); + cloneForm.append(infoBar); - // Add clone tab - tab.add(newTabId, 'Clone', cloneForm, true); - } - - tab.select(newTabId); + // Add clone tab + tab.add(newTabId, 'Clone', cloneForm, true); + } + + tab.select(newTabId); }; /** * Load provision page * - * @param tabId - * The provision tab ID - * @return Nothing + * @param tabId The provision tab ID */ bladePlugin.prototype.loadProvisionPage = function(tabId) { - // Get OS image names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS image names + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); + success : setOSImageCookies + }); - // Get groups - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'extnoderange', - tgt : '/.*', - args : 'subgroups', - msg : '' - }, + // Get groups + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'extnoderange', + tgt : '/.*', + args : 'subgroups', + msg : '' + }, - success : setGroupsCookies - }); + success : setGroupsCookies + }); - // Get provision tab instance - var inst = tabId.replace('bladeProvisionTab', ''); + // Get provision tab instance + var inst = tabId.replace('bladeProvisionTab', ''); - // Create provision form - var provForm = $('
            '); + // Create provision form + var provForm = $('
            '); - // Create info bar - var infoBar = createInfoBar('Provision a blade. This will install an operating system onto the blade.'); - provForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Provision a blade. This will install an operating system onto the blade.'); + provForm.append(infoBar); - // Append to provision tab - $('#' + tabId).append(provForm); + // Append to provision tab + $('#' + tabId).append(provForm); - // Create provision existing node division - var provExisting = createBladeProvisionExisting(inst); - provForm.append(provExisting); + // Create provision existing node division + var provExisting = createBladeProvisionExisting(inst); + provForm.append(provExisting); }; /** * Load resources - * - * @return Nothing */ bladePlugin.prototype.loadResources = function() { - // Get resource tab ID - var tabId = 'bladeResourceTab'; - // Remove loader - $('#' + tabId).find('img').remove(); - - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // Get resource tab ID + var tabId = 'bladeResourceTab'; + // Remove loader + $('#' + tabId).find('img').remove(); + + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create resource form - var resrcForm = $('
            '); - resrcForm.append(infoBar); - - $('#' + tabId).append(resrcForm); + // Create resource form + var resrcForm = $('
            '); + resrcForm.append(infoBar); + + $('#' + tabId).append(resrcForm); }; /** @@ -202,138 +186,138 @@ bladePlugin.prototype.loadResources = function() { bladePlugin.prototype.addNode = function() { var addNodeForm = $('
            '); var info = createInfoBar('Add a BladeCenter node'); - addNodeForm.append(info); + addNodeForm.append(info); var typeFS = $('
            '); - var typeLegend = $('Type'); - typeFS.append(typeLegend); - addNodeForm.append(typeFS); - - var settingsFS = $('
            '); - var nodeLegend = $('Settings'); - settingsFS.append(nodeLegend); - addNodeForm.append(settingsFS); - - typeFS.append('
            ' + - '' + - '' + - '
            '); + var typeLegend = $('Type'); + typeFS.append(typeLegend); + addNodeForm.append(typeFS); - // Change dialog width - $('#addBladeCenter').dialog('option', 'width', '400'); - - typeFS.find('#typeSelect').bind('change', function(){ - // Remove any existing warnings - $('#addBladeCenter .ui-state-error').remove(); - settingsFS.find('div').remove(); - - // Change dialog width - $('#addBladeCenter').dialog('option', 'width', '400'); - + var settingsFS = $('
            '); + var nodeLegend = $('Settings'); + settingsFS.append(nodeLegend); + addNodeForm.append(settingsFS); + + typeFS.append('
            ' + + '' + + '' + + '
            '); + + // Change dialog width + $('#addBladeCenter').dialog('option', 'width', '400'); + + typeFS.find('#typeSelect').bind('change', function(){ + // Remove any existing warnings + $('#addBladeCenter .ui-state-error').remove(); + settingsFS.find('div').remove(); + + // Change dialog width + $('#addBladeCenter').dialog('option', 'width', '400'); + var nodeType = $(this).val(); switch (nodeType) { - case 'amm': - settingsFS.append('
            '); - settingsFS.append('
            '); - settingsFS.append('
            '); - settingsFS.append('
            '); - break; - case 'blade': - settingsFS.append('
            '); - settingsFS.append('
            '); - settingsFS.append('
            '); - settingsFS.append('
            JS LS
            '); - settingsFS.append('
            '); - break; - case 'scan': - settingsFS.append('
            '); - - // Change dialog width - $('#addBladeCenter').dialog('option', 'width', '650'); - break; + case 'amm': + settingsFS.append('
            '); + settingsFS.append('
            '); + settingsFS.append('
            '); + settingsFS.append('
            '); + break; + case 'blade': + settingsFS.append('
            '); + settingsFS.append('
            '); + settingsFS.append('
            '); + settingsFS.append('
            JS LS
            '); + settingsFS.append('
            '); + break; + case 'scan': + settingsFS.append('
            '); + + // Change dialog width + $('#addBladeCenter').dialog('option', 'width', '650'); + break; } - - // Do not continue if node type is AMM - if ($(this).val() == 'amm') { - return; - } - - // Gather AMM nodes - settingsFS.find('select:eq(0)').after(createLoader()); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : '-t;node;-w;mgt==blade;-w;id==0', - msg : nodeType - }, - success : function(data) { - var position = 0; - var tmp = ''; - var options = ''; - - // Remove the loading image - settingsFS.find('img').remove(); + + // Do not continue if node type is AMM + if ($(this).val() == 'amm') { + return; + } + + // Gather AMM nodes + settingsFS.find('select:eq(0)').after(createLoader()); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : '-t;node;-w;mgt==blade;-w;id==0', + msg : nodeType + }, + success : function(data) { + var position = 0; + var tmp = ''; + var options = ''; + + // Remove the loading image + settingsFS.find('img').remove(); - // Do not continue if no AMM nodes are found - if (data.rsp.length < 1) { - $('#addBladeCenter').prepend(createWarnBar('Please define an AMM node before continuing')); - return; - } + // Do not continue if no AMM nodes are found + if (data.rsp.length < 1) { + $('#addBladeCenter').prepend(createWarnBar('Please define an AMM node before continuing')); + return; + } - // Create options for AMM nodes - for (var i in data.rsp){ - tmp = data.rsp[i]; - position = tmp.indexOf(' '); - tmp = tmp.substring(0, position); - options += ''; - } + // Create options for AMM nodes + for (var i in data.rsp){ + tmp = data.rsp[i]; + position = tmp.indexOf(' '); + tmp = tmp.substring(0, position); + options += ''; + } - // Select the first AMM node - settingsFS.find('select:eq(0)').append(options); - if (data.msg != 'scan') { - return; - } - - // Create Scan button - var scan = createButton('Scan'); - scan.bind('click', function(){ - var ammName = settingsFS.find('select:eq(0)').val(); - settingsFS.prepend(createLoader()); - $('#bcSettings button').attr('disabled', 'disabled'); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rscan', - tgt : ammName, - args : '', - msg : '' - }, - - /** - * Show scanned results for AMM - * - * @param data Data returned from HTTP request - */ - success: function(data){ - showScanAmmResult(data.rsp[0]); - } - }); - }); - - settingsFS.find('select:eq(0)').after(scan); - } - }); + // Select the first AMM node + settingsFS.find('select:eq(0)').append(options); + if (data.msg != 'scan') { + return; + } + + // Create Scan button + var scan = createButton('Scan'); + scan.bind('click', function(){ + var ammName = settingsFS.find('select:eq(0)').val(); + settingsFS.prepend(createLoader()); + $('#bcSettings button').attr('disabled', 'disabled'); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rscan', + tgt : ammName, + args : '', + msg : '' + }, + + /** + * Show scanned results for AMM + * + * @param data Data returned from HTTP request + */ + success: function(data){ + showScanAmmResult(data.rsp[0]); + } + }); + }); + + settingsFS.find('select:eq(0)').after(scan); + } + }); }); - // Create dialog for BladeCenter + // Create dialog for BladeCenter addNodeForm.dialog({ modal : true, width : 400, @@ -342,7 +326,7 @@ bladePlugin.prototype.addNode = function() { $(".ui-dialog-titlebar-close").hide(); }, close : function(){ - $(this).remove(); + $(this).remove(); }, buttons : { 'Ok' : function() { @@ -355,7 +339,7 @@ bladePlugin.prototype.addNode = function() { } else if(addMethod == "blade") { addBladeNode(); } else{ - addMmScanNode(); + addMmScanNode(); } }, 'Cancel' : function() { @@ -372,27 +356,27 @@ bladePlugin.prototype.addNode = function() { * Add AMM node */ function addAmmNode(){ - var args = ''; - var errorMsg = ''; + var args = ''; + var errorMsg = ''; - // Check for missing inputs - $('#addBladeCenter input').each(function(){ - if (!$(this).val()) { - errorMsg = 'Please provide a value for each missing field!'; - } - - args += $(this).val() + ','; - }); - - // Do not continue if error was found - if (errorMsg) { - $('#addBladeCenter').prepend(createWarnBar(errorMsg)); - return; - } + // Check for missing inputs + $('#addBladeCenter input').each(function(){ + if (!$(this).val()) { + errorMsg = 'Please provide a value for each missing field!'; + } + + args += $(this).val() + ','; + }); + + // Do not continue if error was found + if (errorMsg) { + $('#addBladeCenter').prepend(createWarnBar(errorMsg)); + return; + } - args = args.substring(0, args.length - 1); + args = args.substring(0, args.length - 1); - // Add the loader + // Add the loader $('#addBladeCenter').append(createLoader()); $('.ui-dialog-buttonpane .ui-button').attr('disabled', true); $.ajax( { @@ -405,7 +389,7 @@ function addAmmNode(){ msg : '' }, success : function(data) { - // Remove loader + // Remove loader $('#addBladeCenter').find('img').remove(); $('#addBladeCenter').prepend(createInfoBar('AMM node was successfully added')); $('#addBladeCenter').dialog("option", "buttons", { @@ -421,7 +405,7 @@ function addAmmNode(){ * Add blade node */ function addBladeNode(){ - // Get blade node attributes + // Get blade node attributes var name = $('#bcSettings input[name="bladeName"]').val(); var group = $('#bcSettings input[name="bladeGroup"]').val(); var id = $('#bcSettings input[name="bladeId"]').val(); @@ -429,10 +413,10 @@ function addBladeNode(){ var mpa = $('#bcSettings select[name="bladeMpa"]').val(); var args = '-t;node;-o;' + name - + ';id=' + id - + ';nodetype=osi;groups=' + group - + ';mgt=blade;mpa=' + mpa - + ';serialflow=hard'; + + ';id=' + id + + ';nodetype=osi;groups=' + group + + ';mgt=blade;mpa=' + mpa + + ';serialflow=hard'; // Set the serial speed and port for LS series blade if (series != 'js') { @@ -458,7 +442,7 @@ function addBladeNode(){ msg : '' }, success : function(data) { - // Remove loader + // Remove loader $('#addBladeCenter').find('img').remove(); // Gather response and display it @@ -484,106 +468,104 @@ function addBladeNode(){ /** * Show rscan results * - * @param results - * Results from rscan of blade MPA - * @return Nothing + * @param results Results from rscan of blade MPA */ function showScanAmmResult(results){ - var rSection = $('
            '); - - // Create table to hold results - var rTable = $('
            '); - - // Reset scan results area - $('#addBladeCenter #scanResults').remove(); - $('#bcSettings img').remove(); - $('#bcSettings button').attr('disabled', ''); - if (!results) - return; - - // Do not continue if there are no results - var rows = results.split("\n"); - if (rows.length < 2){ - $('#bcSettings').prepend(createWarnBar(rows[0])); - return; - } - - // Add the table header - var fields = rows[0].match(/\S+/g); - var column = fields.length; - var row = $(''); - row.append(''); - for(var i in fields){ - row.append('' + fields[i] + ''); - } - rTable.append(row); - - // Add table body - var line; - for (var i = 1; i < rows.length; i++) { - line = rows[i]; - - if (!line) - continue; - - var fields = line.match(/\S+/g); - if (fields[0] == 'mm') - continue; - - // Create a row for each result - var row = $(''); - row.append(''); - - // Add column for each field - for (var j = 0; j < column; j++){ - if (fields[j]) { - if (j == 1) { - row.append(''); - } else { - row.append('' + fields[j] + ''); - } - } else { - row.append(''); - } - } - - // Append row to table - rTable.append(row); - } - - rSection.append(rTable); - $('#bcSettings').prepend(rSection); + var rSection = $('
            '); + + // Create table to hold results + var rTable = $('
            '); + + // Reset scan results area + $('#addBladeCenter #scanResults').remove(); + $('#bcSettings img').remove(); + $('#bcSettings button').attr('disabled', ''); + if (!results) + return; + + // Do not continue if there are no results + var rows = results.split("\n"); + if (rows.length < 2){ + $('#bcSettings').prepend(createWarnBar(rows[0])); + return; + } + + // Add the table header + var fields = rows[0].match(/\S+/g); + var column = fields.length; + var row = $(''); + row.append(''); + for(var i in fields){ + row.append('' + fields[i] + ''); + } + rTable.append(row); + + // Add table body + var line; + for (var i = 1; i < rows.length; i++) { + line = rows[i]; + + if (!line) + continue; + + var fields = line.match(/\S+/g); + if (fields[0] == 'mm') + continue; + + // Create a row for each result + var row = $(''); + row.append(''); + + // Add column for each field + for (var j = 0; j < column; j++){ + if (fields[j]) { + if (j == 1) { + row.append(''); + } else { + row.append('' + fields[j] + ''); + } + } else { + row.append(''); + } + } + + // Append row to table + rTable.append(row); + } + + rSection.append(rTable); + $('#bcSettings').prepend(rSection); } /** * Add AMM scanned node */ function addMmScanNode(){ - // Get the AMM name - var ammName = $('#bcSettings select').val(); - var nodeName = ''; - - $('#bcSettings :checked').each(function() { - if ($(this).attr('name')) { - nodeName += $(this).attr('name') + ','; - nodeName += $(this).parents('tr').find('input').eq(1).val() + ','; - } - }); - - if (!nodeName) { - $('#addBladeCenter').prepend(createWarnBar('Please select a node!')); - return; - } - - // Disabled button - $('.ui-dialog-buttonpane button').attr('disabled', 'disabled'); - - nodeName = nodeName.substr(0, nodeName.length - 1); - $('#nodeAttrs').append(createLoader()); - - // Send add request - $.ajax({ - url : 'lib/cmd.php', + // Get the AMM name + var ammName = $('#bcSettings select').val(); + var nodeName = ''; + + $('#bcSettings :checked').each(function() { + if ($(this).attr('name')) { + nodeName += $(this).attr('name') + ','; + nodeName += $(this).parents('tr').find('input').eq(1).val() + ','; + } + }); + + if (!nodeName) { + $('#addBladeCenter').prepend(createWarnBar('Please select a node!')); + return; + } + + // Disabled button + $('.ui-dialog-buttonpane button').attr('disabled', 'disabled'); + + nodeName = nodeName.substr(0, nodeName.length - 1); + $('#nodeAttrs').append(createLoader()); + + // Send add request + $.ajax({ + url : 'lib/cmd.php', dataType : 'json', data : { cmd : 'webrun', @@ -592,376 +574,373 @@ function addMmScanNode(){ msg : '' }, success : function(data){ - $('#addBladeCenter').dialog('close'); + $('#addBladeCenter').dialog('close'); } - }); + }); } /** * Create provision existing node division * - * @param inst - * Provision tab instance + * @param inst Provision tab instance * @return Provision existing node division */ function createBladeProvisionExisting(inst) { - // Create provision existing division - var provExisting = $('
            '); + // Create provision existing division + var provExisting = $('
            '); - // Create node fieldset - var nodeFS = $('
            '); - var nodeLegend = $('Node'); - nodeFS.append(nodeLegend); - - var nodeAttr = $('
            '); - nodeFS.append($('
            ')); - nodeFS.append(nodeAttr); - - // Create image fieldset - var imgFS = $('
            '); - var imgLegend = $('Image'); - imgFS.append(imgLegend); - - var imgAttr = $('
            '); - imgFS.append($('
            ')); - imgFS.append(imgAttr); - - provExisting.append(nodeFS, imgFS); - - // Create group input - var group = $('
            '); - var groupLabel = $(''); - group.append(groupLabel); + // Create node fieldset + var nodeFS = $('
            '); + var nodeLegend = $('Node'); + nodeFS.append(nodeLegend); + + var nodeAttr = $('
            '); + nodeFS.append($('
            ')); + nodeFS.append(nodeAttr); + + // Create image fieldset + var imgFS = $('
            '); + var imgLegend = $('Image'); + imgFS.append(imgLegend); + + var imgAttr = $('
            '); + imgFS.append($('
            ')); + imgFS.append(imgAttr); + + provExisting.append(nodeFS, imgFS); + + // Create group input + var group = $('
            '); + var groupLabel = $(''); + group.append(groupLabel); - // Turn on auto complete for group - var dTableDivId = 'bladeNodesDatatableDIV' + inst; // Division ID where nodes datatable will be appended - var groupNames = $.cookie('groups'); - if (groupNames) { - // Split group names into an array - var tmp = groupNames.split(','); + // Turn on auto complete for group + var dTableDivId = 'bladeNodesDatatableDIV' + inst; // Division ID where nodes datatable will be appended + var groupNames = $.cookie('groups'); + if (groupNames) { + // Split group names into an array + var tmp = groupNames.split(','); - // Create drop down for groups - var groupSelect = $(''); - groupSelect.append(''); - for ( var i in tmp) { - // Add group into drop down - var opt = $(''); - groupSelect.append(opt); - } - group.append(groupSelect); + // Create drop down for groups + var groupSelect = $(''); + groupSelect.append(''); + for ( var i in tmp) { + // Add group into drop down + var opt = $(''); + groupSelect.append(opt); + } + group.append(groupSelect); - // Create node datatable - groupSelect.change(function() { - // Get group selected - var thisGroup = $(this).val(); - // If a valid group is selected - if (thisGroup) { - createNodesDatatable(thisGroup, dTableDivId); - } // End of if (thisGroup) - }); - } else { - // If no groups are cookied - var groupInput = $(''); - group.append(groupInput); - } - nodeAttr.append(group); + // Create node datatable + groupSelect.change(function() { + // Get group selected + var thisGroup = $(this).val(); + // If a valid group is selected + if (thisGroup) { + createNodesDatatable(thisGroup, dTableDivId); + } // End of if (thisGroup) + }); + } else { + // If no groups are cookied + var groupInput = $(''); + group.append(groupInput); + } + nodeAttr.append(group); - // Create node input - var node = $('
            '); - var nodeLabel = $(''); - var nodeDatatable = $('

            Select a group to view its nodes

            '); - node.append(nodeLabel); - node.append(nodeDatatable); - nodeAttr.append(node); + // Create node input + var node = $('
            '); + var nodeLabel = $(''); + var nodeDatatable = $('

            Select a group to view its nodes

            '); + node.append(nodeLabel); + node.append(nodeDatatable); + nodeAttr.append(node); - // Create boot method drop down - var method = $('
            '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - imgAttr.append(method); - - // Create operating system input - var os = $('
            '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function() { - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - imgAttr.append(os); + // Create boot method drop down + var method = $('
            '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + + '' + ); + method.append(methodLabel); + method.append(methodSelect); + imgAttr.append(method); + + // Create operating system input + var os = $('
            '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function() { + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + imgAttr.append(os); - // Create architecture input - var arch = $('
            '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function() { - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - imgAttr.append(arch); + // Create architecture input + var arch = $('
            '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function() { + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + imgAttr.append(arch); - // Create profile input - var profile = $('
            '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function() { - var tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - imgAttr.append(profile); + // Create profile input + var profile = $('
            '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function() { + var tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + imgAttr.append(profile); - /** - * Provision existing - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); - var ready = true; - var errorMessage = ''; + /** + * Provision existing + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); + var ready = true; + var errorMessage = ''; - // Get provision tab ID - var thisTabId = 'bladeProvisionTab' + inst; - - // Get nodes that were checked - var dTableId = 'bladeNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - if (!tgts) { - errorMessage += 'You need to select a node. '; - ready = false; - } - - // Check booth method - var boot = $('#' + thisTabId + ' select[name=bootMethod]'); - if (!boot.val()) { - errorMessage += 'You need to select a boot method. '; - boot.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - boot.css('border', 'solid #BDBDBD 1px'); - } - - // Check operating system image - var os = $('#' + thisTabId + ' input[name=os]'); - if (!os.val()) { - errorMessage += 'You need to select a operating system image. '; - os.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - os.css('border', 'solid #BDBDBD 1px'); - } - - // Check architecture - var arch = $('#' + thisTabId + ' input[name=arch]'); - if (!arch.val()) { - errorMessage += 'You need to select an architecture. '; - arch.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - arch.css('border', 'solid #BDBDBD 1px'); - } - - // Check profile - var profile = $('#' + thisTabId + ' input[name=profile]'); - if (!profile.val()) { - errorMessage += 'You need to select a profile. '; - profile.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - profile.css('border', 'solid #BDBDBD 1px'); - } - - // If all inputs are valid, ready to provision - if (ready) { - // Disable provision button - $(this).attr('disabled', 'true'); - - // Prepend status bar - var statBar = createStatusBar('bladeProvisionStatBar' + inst); - statBar.append(createLoader('')); - statBar.prependTo($('#' + thisTabId)); + // Get provision tab ID + var thisTabId = 'bladeProvisionTab' + inst; + + // Get nodes that were checked + var dTableId = 'bladeNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + if (!tgts) { + errorMessage += 'You need to select a node. '; + ready = false; + } + + // Check booth method + var boot = $('#' + thisTabId + ' select[name=bootMethod]'); + if (!boot.val()) { + errorMessage += 'You need to select a boot method. '; + boot.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + boot.css('border', 'solid #BDBDBD 1px'); + } + + // Check operating system image + var os = $('#' + thisTabId + ' input[name=os]'); + if (!os.val()) { + errorMessage += 'You need to select a operating system image. '; + os.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + os.css('border', 'solid #BDBDBD 1px'); + } + + // Check architecture + var arch = $('#' + thisTabId + ' input[name=arch]'); + if (!arch.val()) { + errorMessage += 'You need to select an architecture. '; + arch.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + arch.css('border', 'solid #BDBDBD 1px'); + } + + // Check profile + var profile = $('#' + thisTabId + ' input[name=profile]'); + if (!profile.val()) { + errorMessage += 'You need to select a profile. '; + profile.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + profile.css('border', 'solid #BDBDBD 1px'); + } + + // If all inputs are valid, ready to provision + if (ready) { + // Disable provision button + $(this).attr('disabled', 'true'); + + // Prepend status bar + var statBar = createStatusBar('bladeProvisionStatBar' + inst); + statBar.append(createLoader('')); + statBar.prependTo($('#' + thisTabId)); - // Disable all inputs - var inputs = $('#' + thisTabId + ' input'); - inputs.attr('disabled', 'disabled'); - - // Disable all selects - var selects = $('#' + thisTabId + ' select'); - selects.attr('disabled', 'disabled'); - - /** - * (1) Set operating system - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : tgts + ';noderes.netboot=xnba;nodetype.os=' + os.val() + ';nodetype.arch=' + arch.val() + ';nodetype.profile=' + profile.val() + ';nodetype.provmethod=' + boot.val(), - msg : 'cmd=nodeadd;out=' + inst - }, + // Disable all inputs + var inputs = $('#' + thisTabId + ' input'); + inputs.attr('disabled', 'disabled'); + + // Disable all selects + var selects = $('#' + thisTabId + ' select'); + selects.attr('disabled', 'disabled'); + + /** + * (1) Set operating system + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : tgts + ';noderes.netboot=xnba;nodetype.os=' + os.val() + ';nodetype.arch=' + arch.val() + ';nodetype.profile=' + profile.val() + ';nodetype.provmethod=' + boot.val(), + msg : 'cmd=nodeadd;out=' + inst + }, - success : updateBladeProvisionExistingStatus - }); - } else { - // Show warning message - var warn = createWarnBar(errorMessage); - warn.prependTo($(this).parent().parent()); - } - }); - provExisting.append(provisionBtn); + success : updateBladeProvisionExistingStatus + }); + } else { + // Show warning message + var warn = createWarnBar(errorMessage); + warn.prependTo($(this).parent().parent()); + } + }); + provExisting.append(provisionBtn); - return provExisting; + return provExisting; } /** * Update the provision existing node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateBladeProvisionExistingStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); - // Get command invoked - var cmd = args[0].replace('cmd=', ''); - // Get provision tab instance - var inst = args[1].replace('out=', ''); - - // Get provision tab and status bar ID - var statBarId = 'bladeProvisionStatBar' + inst; - var tabId = 'bladeProvisionTab' + inst; - - /** - * (2) Remote install - */ - if (cmd == 'nodeadd') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + // Get command invoked + var cmd = args[0].replace('cmd=', ''); + // Get provision tab instance + var inst = args[1].replace('out=', ''); + + // Get provision tab and status bar ID + var statBarId = 'bladeProvisionStatBar' + inst; + var tabId = 'bladeProvisionTab' + inst; + + /** + * (2) Remote install + */ + if (cmd == 'nodeadd') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // Get parameters - var os = $('#' + tabId + ' input[name="os"]').val(); - var profile = $('#' + tabId + ' input[name="profile"]').val(); - var arch = $('#' + tabId + ' input[name="arch"]').val(); - - // Get nodes that were checked - var dTableId = 'bladeNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - - // Begin installation - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rbootseq', - tgt : tgts, - args : 'net,hd', - msg : 'cmd=rbootseq;out=' + inst - }, + // Get parameters + var os = $('#' + tabId + ' input[name="os"]').val(); + var profile = $('#' + tabId + ' input[name="profile"]').val(); + var arch = $('#' + tabId + ' input[name="arch"]').val(); + + // Get nodes that were checked + var dTableId = 'bladeNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + + // Begin installation + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rbootseq', + tgt : tgts, + args : 'net,hd', + msg : 'cmd=rbootseq;out=' + inst + }, - success : updateBladeProvisionExistingStatus - }); - } - - /** - * (3) Prepare node for boot - */ - if (cmd == 'nodeadd') { - // Get provision method - var bootMethod = $('#' + tabId + ' select[name=bootMethod]').val(); - - // Get nodes that were checked - var dTableId = 'bladeNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeset', - tgt : tgts, - args : bootMethod, - msg : 'cmd=nodeset;out=' + inst - }, + success : updateBladeProvisionExistingStatus + }); + } + + /** + * (3) Prepare node for boot + */ + if (cmd == 'nodeadd') { + // Get provision method + var bootMethod = $('#' + tabId + ' select[name=bootMethod]').val(); + + // Get nodes that were checked + var dTableId = 'bladeNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeset', + tgt : tgts, + args : bootMethod, + msg : 'cmd=nodeset;out=' + inst + }, - success : updateBladeProvisionExistingStatus - }); - } - - /** - * (4) Power on node - */ - if (cmd == 'nodeset') { - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // Get nodes that were checked - var dTableId = 'bladeNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : tgts, - args : 'boot', - msg : 'cmd=rpower;out=' + inst - }, + success : updateBladeProvisionExistingStatus + }); + } + + /** + * (4) Power on node + */ + if (cmd == 'nodeset') { + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Get nodes that were checked + var dTableId = 'bladeNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : tgts, + args : 'boot', + msg : 'cmd=rpower;out=' + inst + }, - success : updateBladeProvisionExistingStatus - }); - } - - /** - * (5) Done - */ - else if (cmd == 'rpower') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - $('#' + statBarId).find('img').remove(); - - // If installation was successful - if (prg.html().indexOf('Error') == -1) { - $('#' + statBarId).find('div').append('
            It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install.
            '); - } - } + success : updateBladeProvisionExistingStatus + }); + } + + /** + * (5) Done + */ + else if (cmd == 'rpower') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + $('#' + statBarId).find('img').remove(); + + // If installation was successful + if (prg.html().indexOf('Error') == -1) { + $('#' + statBarId).find('div').append('
            It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install.
            '); + } + } } \ No newline at end of file diff --git a/xCAT-UI/js/custom/customUtils.js b/xCAT-UI/js/custom/customUtils.js index cb97008ef..add88765e 100644 --- a/xCAT-UI/js/custom/customUtils.js +++ b/xCAT-UI/js/custom/customUtils.js @@ -1,409 +1,400 @@ /** * Create nodes datatable for a given group * - * @param group - * Group name - * @param outId - * Division ID to append datatable + * @param group Group name + * @param outId Division ID to append datatable * @return Nodes datatable */ function createNodesDatatable(group, outId) { - // Get group nodes - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : group, - msg : outId - }, + // Get group nodes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : group, + msg : outId + }, - /** - * Create nodes datatable - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success : function(data) { - // Data returned - var rsp = data.rsp; + /** + * Create nodes datatable + * + * @param data Data returned from HTTP request + */ + success : function(data) { + // Data returned + var rsp = data.rsp; - // Get output ID - var outId = data.msg; - // Get datatable ID - var dTableId = outId.replace('DIV', ''); + // Get output ID + var outId = data.msg; + // Get datatable ID + var dTableId = outId.replace('DIV', ''); - // Node attributes hash - var attrs = new Object(); - // Node attributes - var headers = new Object(); + // Node attributes hash + var attrs = new Object(); + // Node attributes + var headers = new Object(); - // Clear nodes datatable division - $('#' + outId).empty(); + // Clear nodes datatable division + $('#' + outId).empty(); - // Create nodes datatable - var node, args; - for ( var i in rsp) { - // Get node - var pos = rsp[i].indexOf('Object name:'); - if (pos > -1) { - var temp = rsp[i].split(': '); - node = jQuery.trim(temp[1]); + // Create nodes datatable + var node = null; + var args; + for ( var i in rsp) { + // Get node + var pos = rsp[i].indexOf('Object name:'); + if (pos > -1) { + var temp = rsp[i].split(': '); + node = jQuery.trim(temp[1]); - // Create a hash for the node attributes - attrs[node] = new Object(); - i++; - } + // Create a hash for the node attributes + attrs[node] = new Object(); + i++; + } - // Get key and value - args = rsp[i].split('='); - var key = jQuery.trim(args[0]); - var val = jQuery.trim(args[1]); + // Get key and value + args = rsp[i].split('='); + var key = jQuery.trim(args[0]); + var val = jQuery.trim(args[1]); - // Create hash table - attrs[node][key] = val; - headers[key] = 1; - } + // Create hash table + attrs[node][key] = val; + headers[key] = 1; + } - // Sort headers - var sorted = new Array(); - for ( var key in headers) { - sorted.push(key); - } - sorted.sort(); + // Sort headers + var sorted = new Array(); + for ( var key in headers) { + sorted.push(key); + } + sorted.sort(); - // Add column for check box and node - sorted.unshift('', 'node'); + // Add column for check box and node + sorted.unshift('', 'node'); - // Create nodes datatable - var dTable = new DataTable(dTableId); - dTable.init(sorted); + // Create nodes datatable + var dTable = new DataTable(dTableId); + dTable.init(sorted); - // Go through each node - for ( var node in attrs) { - // Create a row - var row = new Array(); - // Create a check box - var checkBx = ''; - row.push(checkBx, node); + // Go through each node + for ( var node in attrs) { + // Create a row + var row = new Array(); + // Create a check box + var checkBx = ''; + row.push(checkBx, node); - // Go through each header - for ( var i = 2; i < sorted.length; i++) { - // Add node attributes to the row - var key = sorted[i]; - var val = attrs[node][key]; - if (val) { - row.push(val); - } else { - row.push(''); - } - } + // Go through each header + for ( var i = 2; i < sorted.length; i++) { + // Add node attributes to the row + var key = sorted[i]; + var val = attrs[node][key]; + if (val) { + row.push(val); + } else { + row.push(''); + } + } - // Add row to table - dTable.add(row); - } + // Add row to table + dTable.add(row); + } - $('#' + outId).append(dTable.object()); - $('#' + dTableId).dataTable(); - } // End of function(data) - }); + $('#' + outId).append(dTable.object()); + $('#' + dTableId).dataTable(); + } // End of function(data) + }); } /** * Create provision existing node division * - * @param plugin - * Plugin name to create division for - * @param inst - * Provision tab instance + * @param plugin Plugin name to create division for + * @param inst Provision tab instance * @return Provision existing node division */ function createProvisionExisting(plugin, inst) { - // Create provision existing division and hide it - var provExisting = $('
            ').hide(); + // Create provision existing division and hide it + var provExisting = $('
            ').hide(); - // Create group input - var group = $('
            '); - var groupLabel = $(''); - group.append(groupLabel); + // Create group input + var group = $('
            '); + var groupLabel = $(''); + group.append(groupLabel); - // Turn on auto complete for group - var dTableDivId = plugin + 'NodesDatatableDIV' + inst; // Division ID where nodes datatable will be appended - var groupNames = $.cookie('groups'); - if (groupNames) { - // Split group names into an array - var tmp = groupNames.split(','); + // Turn on auto complete for group + var dTableDivId = plugin + 'NodesDatatableDIV' + inst; // Division ID where nodes datatable will be appended + var groupNames = $.cookie('groups'); + if (groupNames) { + // Split group names into an array + var tmp = groupNames.split(','); - // Create drop down for groups - var groupSelect = $(''); - groupSelect.append(''); - for ( var i in tmp) { - // Add group into drop down - var opt = $(''); - groupSelect.append(opt); - } - group.append(groupSelect); + // Create drop down for groups + var groupSelect = $(''); + groupSelect.append(''); + for ( var i in tmp) { + // Add group into drop down + var opt = $(''); + groupSelect.append(opt); + } + group.append(groupSelect); - // Create node datatable - groupSelect.change(function() { - // Get group selected - var thisGroup = $(this).val(); - // If a valid group is selected - if (thisGroup) { - createNodesDatatable(thisGroup, dTableDivId); - } // End of if (thisGroup) - }); - } else { - // If no groups are cookied - var groupInput = $(''); - group.append(groupInput); - } - provExisting.append(group); + // Create node datatable + groupSelect.change(function() { + // Get group selected + var thisGroup = $(this).val(); + // If a valid group is selected + if (thisGroup) { + createNodesDatatable(thisGroup, dTableDivId); + } // End of if (thisGroup) + }); + } else { + // If no groups are cookied + var groupInput = $(''); + group.append(groupInput); + } + provExisting.append(group); - // Create node input - var node = $('
            '); - var nodeLabel = $(''); - var nodeDatatable = $('

            Select a group to view its nodes

            '); - node.append(nodeLabel); - node.append(nodeDatatable); - provExisting.append(node); + // Create node input + var node = $('
            '); + var nodeLabel = $(''); + var nodeDatatable = $('

            Select a group to view its nodes

            '); + node.append(nodeLabel); + node.append(nodeDatatable); + provExisting.append(node); - // Create boot method drop down - var method = $('
            '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - provExisting.append(method); + // Create boot method drop down + var method = $('
            '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + ); + method.append(methodLabel); + method.append(methodSelect); + provExisting.append(method); - // Create boot type drop down - var type = $('
            '); - var typeLabel = $(''); - var typeSelect = $(''); - typeSelect.append('' - + '' - + '' - ); - type.append(typeLabel); - type.append(typeSelect); - provExisting.append(type); + // Create boot type drop down + var type = $('
            '); + var typeLabel = $(''); + var typeSelect = $(''); + typeSelect.append('' + + '' + + '' + ); + type.append(typeLabel); + type.append(typeSelect); + provExisting.append(type); - // Create operating system input - var os = $('
            '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function() { - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - provExisting.append(os); + // Create operating system input + var os = $('
            '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function() { + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + provExisting.append(os); - // Create architecture input - var arch = $('
            '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function() { - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - provExisting.append(arch); + // Create architecture input + var arch = $('
            '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function() { + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + provExisting.append(arch); - // Create profile input - var profile = $('
            '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function() { - var tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - provExisting.append(profile); + // Create profile input + var profile = $('
            '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function() { + var tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + provExisting.append(profile); - /** - * Provision existing - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // TODO Insert provision code here - openDialog('info', 'Not yet supported'); - }); - provExisting.append(provisionBtn); + /** + * Provision existing + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // TODO Insert provision code here + openDialog('info', 'Not yet supported'); + }); + provExisting.append(provisionBtn); - return provExisting; + return provExisting; } /** * Create provision new node division * - * @param inst - * Provision tab instance + * @param inst Provision tab instance * @return Provision new node division */ function createProvisionNew(plugin, inst) { - // Create provision new node division - var provNew = $('
            '); + // Create provision new node division + var provNew = $('
            '); - // Create node input - var nodeName = $('
            '); - provNew.append(nodeName); + // Create node input + var nodeName = $('
            '); + provNew.append(nodeName); - // Create group input - var group = $('
            '); - var groupLabel = $(''); - var groupInput = $(''); - groupInput.one('focus', function() { - var groupNames = $.cookie('groups'); - if (groupNames) { - // Turn on auto complete - $(this).autocomplete({ - source: groupNames.split(',') - }); - } - }); - group.append(groupLabel); - group.append(groupInput); - provNew.append(group); + // Create group input + var group = $('
            '); + var groupLabel = $(''); + var groupInput = $(''); + groupInput.one('focus', function() { + var groupNames = $.cookie('groups'); + if (groupNames) { + // Turn on auto complete + $(this).autocomplete({ + source: groupNames.split(',') + }); + } + }); + group.append(groupLabel); + group.append(groupInput); + provNew.append(group); - // Create boot method drop down - var method = $('
            '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - provNew.append(method); + // Create boot method drop down + var method = $('
            '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + ); + method.append(methodLabel); + method.append(methodSelect); + provNew.append(method); - // Create boot type drop down - var type = $('
            '); - var typeLabel = $(''); - var typeSelect = $(''); - typeSelect.append('' - + '' - + '' - ); - type.append(typeLabel); - type.append(typeSelect); - provNew.append(type); + // Create boot type drop down + var type = $('
            '); + var typeLabel = $(''); + var typeSelect = $(''); + typeSelect.append('' + + '' + + '' + ); + type.append(typeLabel); + type.append(typeSelect); + provNew.append(type); - // Create operating system input - var os = $('
            '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function() { - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - provNew.append(os); + // Create operating system input + var os = $('
            '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function() { + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + provNew.append(os); - // Create architecture input - var arch = $('
            '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function() { - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - provNew.append(arch); + // Create architecture input + var arch = $('
            '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function() { + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + provNew.append(arch); - // Create profile input - var profile = $('
            '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function() { - var tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - provNew.append(profile); + // Create profile input + var profile = $('
            '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function() { + var tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + provNew.append(profile); - /** - * Provision new node - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // TODO Insert provision code here - openDialog('info', 'Not yet supported'); - }); - provNew.append(provisionBtn); + /** + * Provision new node + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // TODO Insert provision code here + openDialog('info', 'Not yet supported'); + }); + provNew.append(provisionBtn); - return provNew; + return provNew; } /** * Create section to provision node * - * @param plugin - * Plugin name - * @param container - * Container to hold provision section - * @return Nothing + * @param plugin Plugin name + * @param container Container to hold provision section */ function appendProvisionSection(plugin, container) { - // Get provision tab ID + // Get provision tab ID var tabId = container.parents('.tab').attr('id'); - if (plugin == 'quick') - appendProvision4Url(container); // For provisioning based on argmunents found in URL + if (plugin == 'quick') + appendProvision4Url(container); // For provisioning based on argmunents found in URL else - appendProvision4NoUrl(plugin, container); + appendProvision4NoUrl(plugin, container); // Add provision button var provisionBtn = createButton('Provision'); provisionBtn.bind('click', function(){ - provisionNode(tabId); + provisionNode(tabId); }); container.append(provisionBtn); @@ -451,34 +442,30 @@ function appendProvisionSection(plugin, container) { /** * Create provision node section using URL * - * @param container - * Container to hold provision section + * @param container Container to hold provision section * @returns Nothing */ -function appendProvision4Url(container){ - // Get provision tab ID - var tabId = container.parents('.tab').attr('id'); +function appendProvision4Url(container){ + // Create node fieldset + var nodeFS = $('
            '); + var nodeLegend = $('Node'); + nodeFS.append(nodeLegend); + container.append(nodeFS); + + var nodeAttr = $('
            '); + nodeFS.append($('
            ')); + nodeFS.append(nodeAttr); + + // Create image fieldset + var imgFS = $('
            '); + var imgLegend = $('Image'); + imgFS.append(imgLegend); + container.append(imgFS); + + var imgAttr = $('
            '); + imgFS.append($('
            ')); + imgFS.append(imgAttr); - // Create node fieldset - var nodeFS = $('
            '); - var nodeLegend = $('Node'); - nodeFS.append(nodeLegend); - container.append(nodeFS); - - var nodeAttr = $('
            '); - nodeFS.append($('
            ')); - nodeFS.append(nodeAttr); - - // Create image fieldset - var imgFS = $('
            '); - var imgLegend = $('Image'); - imgFS.append(imgLegend); - container.append(imgFS); - - var imgAttr = $('
            '); - imgFS.append($('
            ')); - imgFS.append(imgAttr); - var query = window.location.search; var args = query.substr(1).split('&'); var parms = new Object(); @@ -492,15 +479,15 @@ function appendProvision4Url(container){ var master = ''; if (parms['master']) - master = parms['master']; + master = parms['master']; var nfsserver = ''; if (parms['nfsserver']) - nfsserver = parms['nfsserver']; + nfsserver = parms['nfsserver']; var tftpserver = ''; if (parms['tftpserver']) - tftpserver = parms['tftpserver']; + tftpserver = parms['tftpserver']; nodeAttr.append('
            '); @@ -518,37 +505,34 @@ function appendProvision4Url(container){ /** * Create section to provision node using no URL * - * @param plugin - * Create provision section for given plugin - * @param container - * Container to hold provision section - * @returns Nothing + * @param plugin Create provision section for given plugin + * @param container Container to hold provision section */ function appendProvision4NoUrl(plugin, container){ - // Get provision tab ID + // Get provision tab ID var tabId = container.parents('.tab').attr('id'); - // Create node fieldset - var nodeFS = $('
            '); - var nodeLegend = $('Node'); - nodeFS.append(nodeLegend); - container.append(nodeFS); - - var nodeAttr = $('
            '); - nodeFS.append($('
            ')); - nodeFS.append(nodeAttr); - - // Create image fieldset - var imgFS = $('
            '); - var imgLegend = $('Image'); - imgFS.append(imgLegend); - container.append(imgFS); - - var imgAttr = $('
            '); - imgFS.append($('
            ')); - imgFS.append(imgAttr); - - // Select group name + // Create node fieldset + var nodeFS = $('
            '); + var nodeLegend = $('Node'); + nodeFS.append(nodeLegend); + container.append(nodeFS); + + var nodeAttr = $('
            '); + nodeFS.append($('
            ')); + nodeFS.append(nodeAttr); + + // Create image fieldset + var imgFS = $('
            '); + var imgLegend = $('Image'); + imgFS.append(imgLegend); + container.append(imgFS); + + var imgAttr = $('
            '); + imgFS.append($('
            ')); + imgFS.append(imgAttr); + + // Select group name var group = $('
            ').append(''); var groupSelect = $(''); group.append(groupSelect); @@ -557,26 +541,26 @@ function appendProvision4NoUrl(plugin, container){ var tmp = groupNames.split(','); groupSelect.append(''); // Append empty group name for (var i in tmp) - groupSelect.append(''); + groupSelect.append(''); } nodeAttr.append(group); // Select node from table var nodes = $('
            '); - var nodesTable = $('

            Select a group to view its nodes

            '); - nodes.append(nodesTable); - nodeAttr.append(nodes); - + var nodesTable = $('

            Select a group to view its nodes

            '); + nodes.append(nodesTable); + nodeAttr.append(nodes); + // Select architecture var arch = $('
            ').append(''); var archName = $.cookie('osarchs'); if (archName) { - var archSelect = $(''); - arch.append(archSelect); - + var archSelect = $(''); + arch.append(archSelect); + var tmp = archName.split(','); for (var i in tmp) - archSelect.append(''); + archSelect.append(''); } else { arch.append(''); } @@ -602,12 +586,9 @@ function appendProvision4NoUrl(plugin, container){ /** * Provision node * - * @param tabId - * Provision tab ID - * @return Nothing + * @param tabId Provision tab ID */ function provisionNode(tabId) { - var plugin = tabId; var errorMessage = ""; var args = new Array(); var node = ""; @@ -635,7 +616,7 @@ function provisionNode(tabId) { if (tabId == 'quick') { node = args.shift(); } else { - // Select platform, get node names from table checkbox + // Select platform, get node names from table checkbox args.unshift($('#' + tabId + ' input[name=arch]').val()); node = getCheckedByObj($('#' + tabId + ' #nodesTable')); } @@ -651,18 +632,15 @@ function provisionNode(tabId) { var provision = args.join(','); var url = 'lib/cmd.php?cmd=webrun&tgt=&args=provision;' + - node + ';' + imageName + ';' + provision + ';' + software + '&msg=&opts=flush'; + node + ';' + imageName + ';' + provision + ';' + software + '&msg=&opts=flush'; $('#' + tabId).prepend(createIFrame(url)); } /** * Create advance option * - * @param imagename - * Image name - * @param outId - * Output area ID - * @return Nothing + * @param image Image name + * @param outId Output area ID */ function createAdvancedOptions(image, outId) { $.ajax({ @@ -700,26 +678,23 @@ function createAdvancedOptions(image, outId) { return; if (provMethod == 'install') { - // Create advanced fieldset - var advancedFS = $('
            ').append($('Advanced')); - $('#' + outId + ' div.form fieldset:eq(1)').after(advancedFS); - - advancedFS.append('
            Install Ganglia monitoring
            '); - } - } + // Create advanced fieldset + var advancedFS = $('
            ').append($('Advanced')); + $('#' + outId + ' div.form fieldset:eq(1)').after(advancedFS); + + advancedFS.append('
            Install Ganglia monitoring
            '); + } + } }); } /** * Create nodes table * - * @param group - * Group name - * @param outId - * Output section ID - * @return Nothing + * @param group Group name + * @param outId Output section ID */ -function createNodesTable(group, outId) { +function createNodesTable(group, outId) { // Get group nodes $.ajax({ url : 'lib/cmd.php', @@ -755,9 +730,9 @@ function createNodesTable(group, outId) { outId.empty().append(nTable); if (nodes.length > 10) - outId.css('height', '300px'); + outId.css('height', '300px'); else - outId.css('height', 'auto'); + outId.css('height', 'auto'); } }); } @@ -765,8 +740,7 @@ function createNodesTable(group, outId) { /** * Get select element names * - * @param obj - * Object to get selected element names + * @param obj Object to get selected element names * @return Nodes name seperate by a comma */ function getCheckedByObj(obj) { @@ -789,17 +763,14 @@ function getCheckedByObj(obj) { /** * Select all checkboxes in the table * - * @param event - * Event on element - * @param obj - * Object triggering event - * @return Nothing + * @param event Event on element + * @param obj Object triggering event */ function selectAll4Table(event, obj) { - // Get datatable ID - // This will ascend from - var tableObj = obj.parents('table').find('tbody'); - var status = obj.attr('checked'); - tableObj.find(' :checkbox').attr('checked', status); - event.stopPropagation(); + // Get datatable ID + // This will ascend from
            + var tableObj = obj.parents('table').find('tbody'); + var status = obj.attr('checked'); + tableObj.find(' :checkbox').attr('checked', status); + event.stopPropagation(); } \ No newline at end of file diff --git a/xCAT-UI/js/custom/esx.js b/xCAT-UI/js/custom/esx.js index 8ffa72b5c..105769dfc 100644 --- a/xCAT-UI/js/custom/esx.js +++ b/xCAT-UI/js/custom/esx.js @@ -2,7 +2,7 @@ * Execute when the DOM is fully loaded */ $(document).ready(function() { - // Load utility scripts (if any) + // Load utility scripts (if any) }); /** @@ -14,465 +14,499 @@ var esxPlugin = function() { }; +/** + * Configure self-service page + */ +esxPlugin.prototype.loadConfigPage = function(tabId) { + var configAccordion = $('
            '); + + // Create accordion panel for user + var userSection = $('
            '); + var userLnk = $('

            Users

            ').click(function () { + // Do not load panel again if it is already loaded + if ($('#esxConfigUser').find('.dataTables_wrapper').length) + return; + else + $('#esxConfigUser').append(createLoader('')); + + // Get user data + loadUserPanel('esxConfigUser'); + }); + + // Create accordion panel for profiles + var profileSection = $('
            '); + profileSection.append(createInfoBar('Create, edit, and delete virtual machine profiles used in the self-service portal')); + var profileLnk = $('

            Profiles

            ').click(function () { + + }); + + // Create accordion panel for groups + var groupsSection = $('
            '); + var groupsLnk = $('

            Groups

            ').click(function () { + + }); + + // Create accordion panel for nodes + var nodeSection = $('
            '); + nodeSection.append(createInfoBar('Modify node attributes')); + var nodeLnk = $('

            Nodes

            ').click(function () { + + }); + + configAccordion.append(userLnk, userSection, profileLnk, profileSection, groupsLnk, groupsSection, nodeLnk, nodeSection); + $('#' + tabId).append(configAccordion); + configAccordion.accordion(); + + userLnk.trigger('click'); +}; + /** * Clone node (service page) * - * @param node - * Node to clone - * @return Nothing + * @param node Node to clone */ esxPlugin.prototype.serviceClone = function(node) { - + openDialog('info', 'Not yet supported'); }; /** * Load provision page (service page) * * @param tabId - * Tab ID where page will reside + * Tab ID where page will reside * @return Nothing */ esxPlugin.prototype.loadServiceProvisionPage = function(tabId) { - + $('#' + tabId).append(createInfoBar('Not yet supported')); }; /** * Show node inventory (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ esxPlugin.prototype.loadServiceInventory = function(data) { - + }; /** * Load node inventory * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ esxPlugin.prototype.loadInventory = function(data) { - var args = data.msg.split(','); - var tabId = args[0].replace('out=', ''); - var node = args[1].replace('node=', ''); - - // Get node inventory - var inv = data.rsp; + var args = data.msg.split(','); + var tabId = args[0].replace('out=', ''); + var node = args[1].replace('node=', ''); + + // Get node inventory + var inv = data.rsp; - // Remove loader - $('#' + tabId).find('img').remove(); + // Remove loader + $('#' + tabId).find('img').remove(); - // Create division to hold inventory - var invDivId = tabId + 'Inventory'; - var invDiv = $('
            '); - - // Create a fieldset - var fieldSet = $('
            '); - var legend = $('Hardware'); - fieldSet.append(legend); - - var oList = $('
              '); - fieldSet.append(oList); - invDiv.append(fieldSet); + // Create division to hold inventory + var invDivId = tabId + 'Inventory'; + var invDiv = $('
              '); + + // Create a fieldset + var fieldSet = $('
              '); + var legend = $('Hardware'); + fieldSet.append(legend); + + var oList = $('
                '); + fieldSet.append(oList); + invDiv.append(fieldSet); - // Loop through each line - var item; - for (var k = 0; k < inv.length; k++) { - // Remove node name - var attr = inv[k].replace(node + ': ', ''); - attr = jQuery.trim(attr); + // Loop through each line + var item; + for (var k = 0; k < inv.length; k++) { + // Remove node name + var attr = inv[k].replace(node + ': ', ''); + attr = jQuery.trim(attr); - // Append attribute to list - item = $('
              1. '); - item.append(attr); - oList.append(item); - } + // Append attribute to list + item = $('
              2. '); + item.append(attr); + oList.append(item); + } - // Append to inventory form - $('#' + tabId).append(invDiv); + // Append to inventory form + $('#' + tabId).append(invDiv); }; /** * Load clone page * - * @param node - * Source node to clone - * @return Nothing + * @param node Source node to clone */ esxPlugin.prototype.loadClonePage = function(node) { - // Get nodes tab - var tab = getNodesTab(); - var newTabId = node + 'CloneTab'; + // Get nodes tab + var tab = getNodesTab(); + var newTabId = node + 'CloneTab'; - // If there is no existing clone tab - if (!$('#' + newTabId).length) { - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // If there is no existing clone tab + if (!$('#' + newTabId).length) { + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create clone form - var cloneForm = $('
                '); - cloneForm.append(infoBar); + // Create clone form + var cloneForm = $('
                '); + cloneForm.append(infoBar); - // Add clone tab - tab.add(newTabId, 'Clone', cloneForm, true); - } - - tab.select(newTabId); + // Add clone tab + tab.add(newTabId, 'Clone', cloneForm, true); + } + + tab.select(newTabId); }; /** * Load provision page * - * @param tabId - * The provision tab ID - * @return Nothing + * @param tabId The provision tab ID */ esxPlugin.prototype.loadProvisionPage = function(tabId) { - // Get OS image names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS image names + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); + success : setOSImageCookies + }); - // Get groups - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'extnoderange', - tgt : '/.*', - args : 'subgroups', - msg : '' - }, + // Get groups + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'extnoderange', + tgt : '/.*', + args : 'subgroups', + msg : '' + }, - success : setGroupsCookies - }); + success : setGroupsCookies + }); - // Create provision form - var provForm = $('
                '); + // Create provision form + var provForm = $('
                '); - // Create info bar - var infoBar = createInfoBar('Provision an ESX virtual machine.'); - provForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Provision an ESX virtual machine.'); + provForm.append(infoBar); - // Append to provision tab - $('#' + tabId).append(provForm); - - // Create VM fieldset - var vmFS = $('
                '); - var vmLegend = $('Virtual Machine'); - vmFS.append(vmLegend); - - var vmAttr = $('
                '); - vmFS.append($('
                ')); - vmFS.append(vmAttr); - - // Create hardware fieldset - var hwFS = $('
                '); - var hwLegend = $('Hardware'); - hwFS.append(hwLegend); - - var hwAttr = $('
                '); - hwFS.append($('
                ')); - hwFS.append(hwAttr); - - // Create image fieldset - var imgFS = $('
                '); - var imgLegend = $('Image'); - imgFS.append(imgLegend); - - var imgAttr = $('
                '); - imgFS.append($('
                ')); - imgFS.append(imgAttr); - - provForm.append(vmFS, hwFS, imgFS); - - // Create hypervisor input - var host = $('
                '); - var hostLabel = $(''); - host.append(hostLabel); - var hostInput = $(''); - host.append(hostInput); - vmAttr.append(host); - - // Create group input - var group = $('
                '); - var groupLabel = $(''); - group.append(groupLabel); + // Append to provision tab + $('#' + tabId).append(provForm); + + // Create VM fieldset + var vmFS = $('
                '); + var vmLegend = $('Virtual Machine'); + vmFS.append(vmLegend); + + var vmAttr = $('
                '); + vmFS.append($('
                ')); + vmFS.append(vmAttr); + + // Create hardware fieldset + var hwFS = $('
                '); + var hwLegend = $('Hardware'); + hwFS.append(hwLegend); + + var hwAttr = $('
                '); + hwFS.append($('
                ')); + hwFS.append(hwAttr); + + // Create image fieldset + var imgFS = $('
                '); + var imgLegend = $('Image'); + imgFS.append(imgLegend); + + var imgAttr = $('
                '); + imgFS.append($('
                ')); + imgFS.append(imgAttr); + + provForm.append(vmFS, hwFS, imgFS); + + // Create hypervisor input + var host = $('
                '); + var hostLabel = $(''); + host.append(hostLabel); + var hostInput = $(''); + host.append(hostInput); + vmAttr.append(host); + + // Create group input + var group = $('
                '); + var groupLabel = $(''); + group.append(groupLabel); - // Turn on auto complete for group - var groupNames = $.cookie('groups'); - if (groupNames) { - // Split group names into an array - var tmp = groupNames.split(','); + // Turn on auto complete for group + var groupNames = $.cookie('groups'); + if (groupNames) { + // Split group names into an array + var tmp = groupNames.split(','); - // Create drop down for groups - var groupSelect = $(''); - groupSelect.append(''); - for ( var i in tmp) { - // Add group into drop down - var opt = $(''); - groupSelect.append(opt); - } - group.append(groupSelect); - } else { - // If no groups are cookied - var groupInput = $(''); - group.append(groupInput); - } - vmAttr.append(group); + // Create drop down for groups + var groupSelect = $(''); + groupSelect.append(''); + for ( var i in tmp) { + // Add group into drop down + var opt = $(''); + groupSelect.append(opt); + } + group.append(groupSelect); + } else { + // If no groups are cookied + var groupInput = $(''); + group.append(groupInput); + } + vmAttr.append(group); - // Create node input - var node = $('
                '); - var nodeLabel = $(''); - var nodeInput = $(''); - node.append(nodeLabel); - node.append(nodeInput); - vmAttr.append(node); + // Create node input + var node = $('
                '); + var nodeLabel = $(''); + var nodeInput = $(''); + node.append(nodeLabel); + node.append(nodeInput); + vmAttr.append(node); - // Create memory input - var memory = $('
                '); - var memoryLabel = $(''); - var memoryInput = $(''); - memory.append(memoryLabel); - memory.append(memoryInput); - hwAttr.append(memory); - - // Create processor dropdown - var cpu = $('
                '); - var cpuLabel = $(''); - var cpuSelect = $(''); - cpuSelect.append('' - + '' - + '' - + '' - + '' - + '' - + '' - + '' - ); - cpu.append(cpuLabel); - cpu.append(cpuSelect); - hwAttr.append(cpu); - - // Create NIC dropdown - var nic = $('
                '); - var nicLabel = $(''); - var nicInput = $(''); - nic.append(nicLabel); - nic.append(nicInput); - hwAttr.append(nic); - - // Create disk input - var disk = $('
                '); - var diskLabel = $(''); - var diskInput = $(''); - var diskSizeSelect = $(''); - diskSizeSelect.append('' + - '' - ); - disk.append(diskLabel, diskInput, diskSizeSelect); - hwAttr.append(disk); - - // Create disk storage input - var storage = $('
                '); - var storageLabel = $(''); - var storageInput = $(''); - storage.append(storageLabel); - storage.append(storageInput); - hwAttr.append(storage); - - // Create operating system input - var os = $('
                '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function() { - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - imgAttr.append(os); - - // Create architecture input - var arch = $('
                '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function() { - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - imgAttr.append(arch); - - // Create profile input - var profile = $('
                '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function() { - var tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - imgAttr.append(profile); - - // Create boot method dropdown - var method = $('
                '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - imgAttr.append(method); + // Create memory input + var memory = $('
                '); + var memoryLabel = $(''); + var memoryInput = $(''); + memory.append(memoryLabel); + memory.append(memoryInput); + hwAttr.append(memory); + + // Create processor dropdown + var cpu = $('
                '); + var cpuLabel = $(''); + var cpuSelect = $(''); + cpuSelect.append('' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + ); + cpu.append(cpuLabel); + cpu.append(cpuSelect); + hwAttr.append(cpu); + + // Create NIC dropdown + var nic = $('
                '); + var nicLabel = $(''); + var nicInput = $(''); + nic.append(nicLabel); + nic.append(nicInput); + hwAttr.append(nic); + + // Create disk input + var disk = $('
                '); + var diskLabel = $(''); + var diskInput = $(''); + var diskSizeSelect = $(''); + diskSizeSelect.append('' + + '' + ); + disk.append(diskLabel, diskInput, diskSizeSelect); + hwAttr.append(disk); + + // Create disk storage input + var storage = $('
                '); + var storageLabel = $(''); + var storageInput = $(''); + storage.append(storageLabel); + storage.append(storageInput); + hwAttr.append(storage); + + // Create operating system input + var os = $('
                '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function() { + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + imgAttr.append(os); + + // Create architecture input + var arch = $('
                '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function() { + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + imgAttr.append(arch); + + // Create profile input + var profile = $('
                '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function() { + var tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + imgAttr.append(profile); + + // Create boot method dropdown + var method = $('
                '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + + '' + ); + method.append(methodLabel); + method.append(methodSelect); + imgAttr.append(method); - /** - * Provision existing - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); - var ready = true; - - // Get tab ID - var tabId = $(this).parents('.ui-tabs-panel').attr('id'); - - // Check if fields are properly filled in - var inputs = $('#' + tabId + ' input:visible'); - for ( var i = 0; i < inputs.length; i++) { - if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'storage') { - inputs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - inputs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } - - var selects = $('#' + tabId + ' select:visible'); - for ( var i = 0; i < selects.length; i++) { - if (!selects.eq(i).val()) { - selects.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - selects.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } - - if (ready) { - var inst = tabId.replace('kvmProvisionTab', ''); - - // Prepend status bar - var statBar = createStatusBar('kvmProvisionStatBar' + inst); - statBar.append(createLoader('')); - statBar.prependTo($('#' + tabId)); - - var host = $('#' + tabId + ' input[name=host]').val(); - var group = $('#' + tabId + ' select[name=group]').val(); - var node = $('#' + tabId + ' input[name=node]').val(); - - var memory = $('#' + tabId + ' input[name=memory]').val(); - var cpu = $('#' + tabId + ' select[name=cpu]').val(); - var nic = $('#' + tabId + ' input[name=nic]').val(); - var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); - var storage = $('#' + tabId + ' input[name=storage]').val(); - - var os = $('#' + tabId + ' input[name=os]').val(); - var arch = $('#' + tabId + ' input[name=arch]').val(); - var profile = $('#' + tabId + ' input[name=profile]').val(); - var boot = $('#' + tabId + ' select[name=bootMethod]').val(); - - /** - * (1) Define node - */ - var args = '-t;node;-o;' + node + - ';vmhost=' + host + - ';groups=' + group + - ';vmmemory=' + memory + - ';vmcpus=' + cpu + - ';vmnics=' + nic + - ';vmstorage=' + storage + - ';os=' + os + - ';arch=' + arch + - ';profile=' + profile + - ';netboot=xnba' + - ';nodetype=osi' + - ';serialport=0' + - ';serialspeed=115200' + - ';mgt=esx'; - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : args, - msg : 'cmd=chdef;out=' + inst - }, + /** + * Provision existing + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); + var ready = true; + + // Get tab ID + var tabId = $(this).parents('.ui-tabs-panel').attr('id'); + + // Check if fields are properly filled in + var inputs = $('#' + tabId + ' input:visible'); + for ( var i = 0; i < inputs.length; i++) { + if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'storage') { + inputs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + inputs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } + + var selects = $('#' + tabId + ' select:visible'); + for ( var i = 0; i < selects.length; i++) { + if (!selects.eq(i).val()) { + selects.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + selects.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } + + if (ready) { + var inst = tabId.replace('kvmProvisionTab', ''); + + // Prepend status bar + var statBar = createStatusBar('kvmProvisionStatBar' + inst); + statBar.append(createLoader('')); + statBar.prependTo($('#' + tabId)); + + var host = $('#' + tabId + ' input[name=host]').val(); + var group = $('#' + tabId + ' select[name=group]').val(); + var node = $('#' + tabId + ' input[name=node]').val(); + + var memory = $('#' + tabId + ' input[name=memory]').val(); + var cpu = $('#' + tabId + ' select[name=cpu]').val(); + var nic = $('#' + tabId + ' input[name=nic]').val(); + var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); + var storage = $('#' + tabId + ' input[name=storage]').val(); + + var os = $('#' + tabId + ' input[name=os]').val(); + var arch = $('#' + tabId + ' input[name=arch]').val(); + var profile = $('#' + tabId + ' input[name=profile]').val(); + var boot = $('#' + tabId + ' select[name=bootMethod]').val(); + + /** + * (1) Define node + */ + var args = '-t;node;-o;' + node + + ';vmhost=' + host + + ';groups=' + group + + ';vmmemory=' + memory + + ';vmcpus=' + cpu + + ';vmnics=' + nic + + ';vmstorage=' + storage + + ';os=' + os + + ';arch=' + arch + + ';profile=' + profile + + ';netboot=xnba' + + ';nodetype=osi' + + ';serialport=0' + + ';serialspeed=115200' + + ';mgt=esx'; + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : args, + msg : 'cmd=chdef;out=' + inst + }, - success : updateESXProvisionStatus - }); - } else { - // Show warning message - var warn = createWarnBar('Please provide a value for each missing field.'); - warn.prependTo($(this).parent().parent()); - } - }); - provForm.append(provisionBtn); + success : updateESXProvisionStatus + }); + } else { + // Show warning message + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this).parent().parent()); + } + }); + provForm.append(provisionBtn); }; /** * Load resources - * - * @return Nothing */ esxPlugin.prototype.loadResources = function() { - // Get resource tab ID - var tabId = 'esxResourceTab'; - // Remove loader - $('#' + tabId).find('img').remove(); - - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // Get resource tab ID + var tabId = 'esxResourceTab'; + // Remove loader + $('#' + tabId).find('img').remove(); + + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create resource form - var resrcForm = $('
                '); - resrcForm.append(infoBar); - - $('#' + tabId).append(resrcForm); + // Create resource form + var resrcForm = $('
                '); + resrcForm.append(infoBar); + + $('#' + tabId).append(resrcForm); }; /** @@ -485,12 +519,12 @@ esxPlugin.prototype.addNode = function() { // Create node inputs dialog.append($('
                ')); - dialog.append($('
                ')); - dialog.append($('
                ')); - dialog.append($('
                ')); + dialog.append($('
                ')); + dialog.append($('
                ')); + dialog.append($('
                ')); dialog.dialog({ - title: 'Add node', + title: 'Add node', modal: true, width: 400, close: function(){$(this).remove();}, @@ -505,7 +539,7 @@ esxPlugin.prototype.addNode = function() { * Add ESX node */ function addEsxNode(){ - var attr, args; + var attr, args; var errorMessage = ''; // Remove existing warnings @@ -534,17 +568,17 @@ function addEsxNode(){ // Change dialog buttons $('#addEsx').dialog('option', 'buttons', { - 'Close':function(){ - $('#addEsx').dialog('close'); - } + 'Close':function(){ + $('#addEsx').dialog('close'); + } }); // Generate chdef arguments args = '-t;node;-o;' + $('#addEsx input[name="node"]').val() - + ';ip=' + $('#addEsx input[name="ip"]').val() - + ';groups=' + $('#addEsx input[name="groups"]').val() - + ';vmhost=' + $('#addEsx input[name="vmhost"]').val() - + ';mgt=esx;netboot=xnba;nodetype=osi;profile=compute'; + + ';ip=' + $('#addEsx input[name="ip"]').val() + + ';groups=' + $('#addEsx input[name="groups"]').val() + + ';vmhost=' + $('#addEsx input[name="vmhost"]').val() + + ';mgt=esx;netboot=xnba;nodetype=osi;profile=compute'; $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -555,19 +589,19 @@ function addEsxNode(){ msg : '' }, success: function(data) { - // Update /etc/hosts - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : '' - } - }); - - // Remove loader + // Update /etc/hosts + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : '' + } + }); + + // Remove loader $('#addEsx img').remove(); // Get return message @@ -586,112 +620,110 @@ function addEsxNode(){ /** * Update the provision node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateESXProvisionStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); - // Get command invoked - var cmd = args[0].replace('cmd=', ''); - // Get provision tab instance - var inst = args[1].replace('out=', ''); - - // Get provision tab and status bar ID - var statBarId = 'kvmProvisionStatBar' + inst; - var tabId = 'kvmProvisionTab' + inst; - - var node = $('#' + tabId + ' input[name=node]').val(); - - /** - * (2) Create virtual machine - */ - if (cmd == 'chdef') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + // Get command invoked + var cmd = args[0].replace('cmd=', ''); + // Get provision tab instance + var inst = args[1].replace('out=', ''); + + // Get provision tab and status bar ID + var statBarId = 'kvmProvisionStatBar' + inst; + var tabId = 'kvmProvisionTab' + inst; + + var node = $('#' + tabId + ' input[name=node]').val(); + + /** + * (2) Create virtual machine + */ + if (cmd == 'chdef') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // Get parameters - var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); - - // Begin installation - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'mkvm', - tgt : '', - args : node + ';-s;' + disk, - msg : 'cmd=mkvm;out=' + inst - }, + // Get parameters + var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); + + // Begin installation + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'mkvm', + tgt : '', + args : node + ';-s;' + disk, + msg : 'cmd=mkvm;out=' + inst + }, - success : updateESXProvisionStatus - }); - } - - /** - * (3) Prepare node for boot - */ - if (cmd == 'mkvm') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // Get provision method - var boot = $('#' + tabId + ' select[name=bootMethod]').val(); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeset', - tgt : node, - args : boot, - msg : 'cmd=nodeset;out=' + inst - }, + success : updateESXProvisionStatus + }); + } + + /** + * (3) Prepare node for boot + */ + if (cmd == 'mkvm') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Get provision method + var boot = $('#' + tabId + ' select[name=bootMethod]').val(); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeset', + tgt : node, + args : boot, + msg : 'cmd=nodeset;out=' + inst + }, - success : updateESXProvisionStatus - }); - } - - /** - * (4) Power on node - */ - if (cmd == 'nodeset') { - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : node, - args : 'on', - msg : 'cmd=rpower;out=' + inst - }, + success : updateESXProvisionStatus + }); + } + + /** + * (4) Power on node + */ + if (cmd == 'nodeset') { + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : node, + args : 'on', + msg : 'cmd=rpower;out=' + inst + }, - success : updateESXProvisionStatus - }); - } - - /** - * (5) Done - */ - else if (cmd == 'rpower') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - $('#' + statBarId).find('img').remove(); - - // If installation was successful - if (prg.html().indexOf('Error') == -1) { - $('#' + statBarId).find('div').append('
                It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install.
                '); - } - } + success : updateESXProvisionStatus + }); + } + + /** + * (5) Done + */ + else if (cmd == 'rpower') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + $('#' + statBarId).find('img').remove(); + + // If installation was successful + if (prg.html().indexOf('Error') == -1) { + $('#' + statBarId).find('div').append('
                It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install.
                '); + } + } } \ No newline at end of file diff --git a/xCAT-UI/js/custom/hmc.js b/xCAT-UI/js/custom/hmc.js index 33e7df115..29de5e6bd 100644 --- a/xCAT-UI/js/custom/hmc.js +++ b/xCAT-UI/js/custom/hmc.js @@ -2,7 +2,7 @@ * Execute when the DOM is fully loaded */ $(document).ready(function() { - // Load utility scripts + // Load utility scripts }); /** @@ -19,45 +19,27 @@ var hmcPlugin = function() { * * @return Discovery steps */ -hmcPlugin.prototype.getStep = function(){ - return ['Basic patterns', - 'Supernode', - 'More patterns', - 'Power on hardware', - 'Discover frames', - 'Management node', - 'Update definitions', - 'Create LPARs']; +hmcPlugin.prototype.getStep = function() { + return [ 'Basic patterns', 'Supernode', 'More patterns', + 'Power on hardware', 'Discover frames', 'Management node', + 'Update definitions', 'Create LPARs' ]; }; -hmcPlugin.prototype.getInitFunction = function(){ - return [powerInitBasicPattern, - powerInitSupernode, - powerInitSiteTable, - powerInitPoweronHardware, - powerInitDiscoverFrames, - powerInitConfig, - powerInitUpdateDefinition, - powerInitCreateLpar]; +hmcPlugin.prototype.getInitFunction = function() { + return [ powerInitBasicPattern, powerInitSupernode, powerInitSiteTable, + powerInitPoweronHardware, powerInitDiscoverFrames, powerInitConfig, + powerInitUpdateDefinition, powerInitCreateLpar ]; }; -hmcPlugin.prototype.getNextFunction = function(){ - return [checkBasicPattern, - checkSupernode, - checkSiteTable, - undefined, - checkFrameMtms, - undefined, - undefined, - collectInputValue]; +hmcPlugin.prototype.getNextFunction = function() { + return [ checkBasicPattern, checkSupernode, checkSiteTable, undefined, + checkFrameMtms, undefined, undefined, collectInputValue ]; }; /** * Clone node (service page) * - * @param node - * Node to clone - * @return Nothing + * @param node Node to clone */ hmcPlugin.prototype.serviceClone = function(node) { @@ -66,127 +48,122 @@ hmcPlugin.prototype.serviceClone = function(node) { /** * Load provision page (service page) * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ hmcPlugin.prototype.loadServiceProvisionPage = function(tabId) { - + }; /** * Show node inventory (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ hmcPlugin.prototype.loadServiceInventory = function(data) { - + }; /** * Load node inventory * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ hmcPlugin.prototype.loadInventory = function(data) { - // Get arguments - var args = data.msg.split(','); - // Get tab ID - var tabId = args[0].replace('out=', ''); - // Get node - var node = args[1].replace('node=', ''); - // Get node inventory - var inv = data.rsp; + // Get arguments + var args = data.msg.split(','); + // Get tab ID + var tabId = args[0].replace('out=', ''); + // Get node + var node = args[1].replace('node=', ''); + // Get node inventory + var inv = data.rsp; - // Remove loader - $('#' + tabId).find('img').remove(); + // Remove loader + $('#' + tabId).find('img').remove(); - // Create division to hold inventory - var invDivId = tabId + 'Inventory'; - var invDiv = $('
                '); + // Create division to hold inventory + var invDivId = tabId + 'Inventory'; + var invDiv = $('
                '); - // Loop through each line - var fieldSet, legend, oList, item; - for (var k = 0; k < inv.length; k++) { - // Remove node name in front - var str = inv[k].replace(node + ': ', ''); - str = jQuery.trim(str); + // Loop through each line + var fieldSet = null; + var legend = null; + var oList = null; + var item = null; + for (var k = 0; k < inv.length; k++) { + // Remove node name in front + var str = inv[k].replace(node + ': ', ''); + str = jQuery.trim(str); - // If string is a header - if (str.indexOf('I/O Bus Information') > -1 || str.indexOf('Machine Configuration Info') > -1) { - // Create a fieldset - fieldSet = $('
                '); - legend = $('' + str + ''); - fieldSet.append(legend); - oList = $('
                  '); - fieldSet.append(oList); - invDiv.append(fieldSet); - } else { - // If no fieldset is defined - if (!fieldSet) { - // Define general fieldset - fieldSet = $('
                  '); - legend = $('General'); - fieldSet.append(legend); - oList = $('
                    '); - fieldSet.append(oList); - invDiv.append(fieldSet); - } + // If string is a header + if (str.indexOf('I/O Bus Information') > -1 + || str.indexOf('Machine Configuration Info') > -1) { + // Create a fieldset + fieldSet = $('
                    '); + legend = $('' + str + ''); + fieldSet.append(legend); + oList = $('
                      '); + fieldSet.append(oList); + invDiv.append(fieldSet); + } else { + // If no fieldset is defined + if (!fieldSet) { + // Define general fieldset + fieldSet = $('
                      '); + legend = $('General'); + fieldSet.append(legend); + oList = $('
                        '); + fieldSet.append(oList); + invDiv.append(fieldSet); + } - // Append the string to a list - item = $('
                      1. '); - item.append(str); - oList.append(item); - } - } + // Append the string to a list + item = $('
                      2. '); + item.append(str); + oList.append(item); + } + } - // Append to inventory form - $('#' + tabId).append(invDiv); + // Append to inventory form + $('#' + tabId).append(invDiv); }; /** * Load clone page * - * @param node - * Source node to clone - * @return Nothing + * @param node Source node to clone */ hmcPlugin.prototype.loadClonePage = function(node) { - // Get nodes tab - var tab = getNodesTab(); - var newTabId = node + 'CloneTab'; + // Get nodes tab + var tab = getNodesTab(); + var newTabId = node + 'CloneTab'; - // If there is no existing clone tab - if (!$('#' + newTabId).length) { - // Create status bar and hide it - var statBarId = node + 'CloneStatusBar'; - var statBar = $('
                        ').hide(); + // If there is no existing clone tab + if (!$('#' + newTabId).length) { + // Create status bar and hide it + var statBarId = node + 'CloneStatusBar'; + var statBar = $('
                        ') + .hide(); - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create clone form - var cloneForm = $('
                        '); - cloneForm.append(statBar); - cloneForm.append(infoBar); + // Create clone form + var cloneForm = $('
                        '); + cloneForm.append(statBar); + cloneForm.append(infoBar); - // Add clone tab - tab.add(newTabId, 'Clone', cloneForm, true); - } + // Add clone tab + tab.add(newTabId, 'Clone', cloneForm, true); + } - tab.select(newTabId); + tab.select(newTabId); }; /** * Load provision page * - * @param tabId - * The provision tab ID - * @return Nothing + * @param tabId The provision tab ID */ hmcPlugin.prototype.loadProvisionPage = function(tabId) { // Create provision form @@ -198,138 +175,144 @@ hmcPlugin.prototype.loadProvisionPage = function(tabId) { // Append to provision tab $('#' + tabId).append(provForm); - + // Append provisioning section for HMC appendProvisionSection('hmc', provForm); }; /** * Load resources - * - * @return Nothing */ hmcPlugin.prototype.loadResources = function() { - // Get resource tab ID - var tabId = 'hmcResourceTab'; - // Remove loader - $('#' + tabId).find('img').remove(); + // Get resource tab ID + var tabId = 'hmcResourceTab'; + // Remove loader + $('#' + tabId).find('img').remove(); - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create resource form - var resrcForm = $('
                        '); - resrcForm.append(infoBar); + // Create resource form + var resrcForm = $('
                        '); + resrcForm.append(infoBar); - $('#' + tabId).append(resrcForm); + $('#' + tabId).append(resrcForm); }; /** * Add node range */ hmcPlugin.prototype.addNode = function() { - var dialog = $('
                        '); - dialog.append(createInfoBar('Add a System p node range')); - - // Create option to select node type - dialog.append('
                        ' + - '
                        '); - dialog.append('
                        '); - - // Show dialog - dialog.dialog({ + var dialog = $('
                        '); + dialog.append(createInfoBar('Add a System p node range')); + + // Create option to select node type + dialog.append('
                        ' + + '
                        '); + dialog.append('
                        '); + + // Show dialog + dialog.dialog({ modal : true, width : 400, title : 'Add node', - close : function(){$('#addHmc').remove();} - }); - - // Bind to select change event - $('#nodeType').bind('change', function() { - // Remove existing warnings - $('#addHmc .ui-state-error').remove(); - - // Clear settings section - $('#nodeSettings').empty(); - if ($(this).val() == 'HMC') { - $('#addHmc').dialog('option', 'width', '400'); - $('#nodeSettings').append('
                        '); - $('#nodeSettings').append('
                        '); - $('#nodeSettings').append('
                        '); - $('#nodeSettings').append('
                        '); - - // Change dialog buttons - $('#addHmc').dialog('option', 'buttons', { - 'Add': function() {addHmcNode();}, - 'Cancel': function() {$('#addHmc').dialog('close');} - }); - } else { - // Add loader - $('#nodeSettings').append(createLoader()); - - // Change dialog buttons - $('#addHmc').dialog('option', 'buttons', { - 'Cancel': function() {$('#addHmc').dialog('close');} - }); - - // Set to longer dialog width - $('#addHmc').dialog('option', 'width', '650'); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodels', - tgt : 'all', - args : 'nodetype.nodetype==hmc', - msg : '' - }, - success : function(data) { - // Remove loader - $('#nodeSettings img').remove(); - drawHmcSelector(data.rsp); - } - }); - } - }); - - // Trigger select event change - $('#nodeType').trigger('change'); + close : function() { + $('#addHmc').remove(); + } + }); + + // Bind to select change event + $('#nodeType').bind('change', + function() { + // Remove existing warnings + $('#addHmc .ui-state-error').remove(); + + // Clear settings section + $('#nodeSettings').empty(); + if ($(this).val() == 'HMC') { + $('#addHmc').dialog('option', 'width', '400'); + $('#nodeSettings').append('
                        '); + $('#nodeSettings').append('
                        '); + $('#nodeSettings').append('
                        '); + $('#nodeSettings').append('
                        '); + + // Change dialog buttons + $('#addHmc').dialog('option', 'buttons', { + 'Add' : function() { + addHmcNode(); + }, + 'Cancel' : function() { + $('#addHmc').dialog('close'); + } + }); + } else { + // Add loader + $('#nodeSettings').append(createLoader()); + + // Change dialog buttons + $('#addHmc').dialog('option', 'buttons', { + 'Cancel' : function() { + $('#addHmc').dialog('close'); + } + }); + + // Set to longer dialog width + $('#addHmc').dialog('option', 'width', '650'); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodels', + tgt : 'all', + args : 'nodetype.nodetype==hmc', + msg : '' + }, + success : function(data) { + // Remove loader + $('#nodeSettings img').remove(); + drawHmcSelector(data.rsp); + } + }); + } + }); + + // Trigger select event change + $('#nodeType').trigger('change'); }; /** * Add HMC node */ -function addHmcNode(){ - // Remove existing warnings +function addHmcNode() { + // Remove existing warnings $('#addHmc .ui-state-error').remove(); - - var errorMessage = ''; - var args = ''; - $('#nodeSettings input').each(function(){ - if (!$(this).val()) - errorMessage = 'Please provide a value for each missing field!'; - args += $(this).val() + ','; - }); - - // Do no continue if an error is found - if (errorMessage){ - $('#addHmc').prepend(createWarnBar(errorMessage)); - return; - } - - // Disabled button - $('.ui-dialog-buttonpane button').attr('disabled', 'disabled'); - // Remove last comma - args = args.substr(0, args.length - 1); - - // Append loader - $('#nodeSettings').append(createLoader()); - - // Send request to add HMC - $.ajax({ - url : 'lib/cmd.php', + + var errorMessage = ''; + var args = ''; + $('#nodeSettings input').each(function() { + if (!$(this).val()) + errorMessage = 'Please provide a value for each missing field!'; + args += $(this).val() + ','; + }); + + // Do no continue if an error is found + if (errorMessage) { + $('#addHmc').prepend(createWarnBar(errorMessage)); + return; + } + + // Disabled button + $('.ui-dialog-buttonpane button').attr('disabled', 'disabled'); + // Remove last comma + args = args.substr(0, args.length - 1); + + // Append loader + $('#nodeSettings').append(createLoader()); + + // Send request to add HMC + $.ajax({ + url : 'lib/cmd.php', dataType : 'json', data : { cmd : 'webrun', @@ -337,170 +320,169 @@ function addHmcNode(){ args : 'addnode;hmc;' + args, msg : '' }, - success : function(data){ - $('#addHmc').dialog('close'); + success : function(data) { + $('#addHmc').dialog('close'); } - }); + }); } /** * Add HMCs into dialog * - * @param hmcs - * HMCs - * @return Nothing + * @param hmcs HMCs */ -function drawHmcSelector(hmcs){ - // Remove existing warnings +function drawHmcSelector(hmcs) { + // Remove existing warnings $('#addHmc .ui-state-error').remove(); - - // Do not continue if no HMCs are given - if (hmcs.length < 1) { - $('#addHmc').prepend(createWarnBar('Please define an HMC node first!')); - return; - } - - // Add HMCs into a dropdown and add scan button - var hmcSelect = $(''); - var scanButton = createButton('Scan'); - for (var i in hmcs) { - hmcSelect.append(''); - } - - $('#nodeSettings').append($('
                        ').append(hmcSelect, scanButton)); - - scanButton.bind('click', function() { - var hmcname = $('#nodeSettings select').val(); - $('#nodeSettings').append(createLoader()); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rscan', - tgt : hmcname, - args : '', - msg : '' - }, - success : function(data) { - // Remove loader - $('#nodeSettings img').remove(); - - // Draw table with checkboxes - drawRscanResult(data.rsp[0]); - - // Add the add button - $('#addHmc').dialog('option', 'buttons', { - 'Add': function(){addPNode();}, - 'Cancel': function(){$('#addHmc').dialog('close');} - }); - } - }); - }); + + // Do not continue if no HMCs are given + if (hmcs.length < 1) { + $('#addHmc').prepend(createWarnBar('Please define an HMC node first!')); + return; + } + + // Add HMCs into a dropdown and add scan button + var hmcSelect = $(''); + var scanButton = createButton('Scan'); + for (var i in hmcs) { + hmcSelect.append(''); + } + + $('#nodeSettings').append($('
                        ').append(hmcSelect, scanButton)); + + scanButton.bind('click', function() { + var hmcname = $('#nodeSettings select').val(); + $('#nodeSettings').append(createLoader()); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rscan', + tgt : hmcname, + args : '', + msg : '' + }, + success : function(data) { + // Remove loader + $('#nodeSettings img').remove(); + + // Draw table with checkboxes + drawRscanResult(data.rsp[0]); + + // Add the add button + $('#addHmc').dialog('option', 'buttons', { + 'Add' : function() { + addPNode(); + }, + 'Cancel' : function() { + $('#addHmc').dialog('close'); + } + }); + } + }); + }); } /** * Draw table showing HMC rscan results * - * @param results - * Data returned from rscan - * @return Nothing + * @param results Data returned from rscan */ -function drawRscanResult(results) { - var tmpRegex = /\S+/g; - var idRegex = /^\d+$/; - var rSection = $('
                        '); - var rTable = $('
                        '); - - // Empty node settings section - $('#nodeSettings div').remove(); - if (!results) - return; - - var lines = results.split("\n"); - // Do not continue if no results are found - if (lines.length < 2) { - return; - } - - var fields = lines[0].match(tmpRegex); - var cols = fields.length; - - // Add table header - var tHead = $('').append(''); - for(var i in fields) { - tHead.append('' + fields[i] + ''); - } - rTable.append(tHead); - - // Add table body - var tBody = $(''); - rTable.append(tBody); - for (var i = 1; i < lines.length; i++) { - var row = $(''); - - // Go to next row if there is nothing - if (!lines[i]) - continue; - - fields = lines[i].match(tmpRegex); - - // Go to next row if this row is the HMC - if (fields[0] == 'hmc') - continue; - - // If the 3rd field is empty, create an empty column - if (!idRegex.test(fields[2])) - fields = [fields[0], fields[1], ''].concat(fields.slice(2)); - row.append(''); - - // Go through each field and add it to the row as a column - for(var j = 0; j < cols; j++) { - var col = $(''); - if (fields[j]) { - if (j == 1) - col.append(''); - else - col.append(fields[j]); - } - } - - tBody.append(row); - } - - rSection.append(rTable); - $('#nodeSettings').append(rSection); +function drawRscanResult(results) { + var tmpRegex = /\S+/g; + var idRegex = /^\d+$/; + var rSection = $('
                        '); + var rTable = $('
                        '); + + // Empty node settings section + $('#nodeSettings div').remove(); + if (!results) + return; + + var lines = results.split("\n"); + // Do not continue if no results are found + if (lines.length < 2) { + return; + } + + var fields = lines[0].match(tmpRegex); + var cols = fields.length; + + // Add table header + var tHead = $('').append(''); + for (var i in fields) { + tHead.append('' + fields[i] + ''); + } + rTable.append(tHead); + + // Add table body + var tBody = $(''); + rTable.append(tBody); + for (var i = 1; i < lines.length; i++) { + var row = $(''); + + // Go to next row if there is nothing + if (!lines[i]) + continue; + + fields = lines[i].match(tmpRegex); + + // Go to next row if this row is the HMC + if (fields[0] == 'hmc') + continue; + + // If the 3rd field is empty, create an empty column + if (!idRegex.test(fields[2])) + fields = [ fields[0], fields[1], '' ].concat(fields.slice(2)); + row.append(''); + + // Go through each field and add it to the row as a column + for (var j = 0; j < cols; j++) { + var col = $(''); + if (fields[j]) { + if (j == 1) + col.append(''); + else + col.append(fields[j]); + } + } + + tBody.append(row); + } + + rSection.append(rTable); + $('#nodeSettings').append(rSection); } /** - * Add System p node, contains frame, cec, lpar - * - * @return Nothing + * Add System p node (contains frame, CEC, LPAR) */ -function addPNode(){ - // Get the HMC name - var hmcname = $('#nodeSettings select').val(); - var nodename = ''; - // Get checked nodes - $('#nodeSettings :checked').each(function() { - if ($(this).attr('name')) { - nodename += $(this).attr('name') + ','; - nodename += $(this).parents('tr').find('input').eq(1).val() + ','; - } - }); - - if (!nodename) { - alert('You should select nodes first!'); - return; - } - - // Disabled the button - $('.ui-dialog-buttonpane button').attr('disabled', 'disabled'); - - nodename = nodename.substr(0, nodename.length - 1); - $('#nodeSettings').append(createLoader()); - // Send the add request - $.ajax({ - url : 'lib/cmd.php', +function addPNode() { + // Get the HMC name + var hmcname = $('#nodeSettings select').val(); + var nodename = ''; + + // Get checked nodes + $('#nodeSettings :checked').each(function() { + if ($(this).attr('name')) { + nodename += $(this).attr('name') + ','; + nodename += $(this).parents('tr').find('input').eq(1).val() + ','; + } + }); + + if (!nodename) { + alert('You should select nodes first!'); + return; + } + + // Disabled the button + $('.ui-dialog-buttonpane button').attr('disabled', 'disabled'); + + nodename = nodename.substr(0, nodename.length - 1); + $('#nodeSettings').append(createLoader()); + // Send the add request + $.ajax({ + url : 'lib/cmd.php', dataType : 'json', data : { cmd : 'webrun', @@ -509,110 +491,94 @@ function addPNode(){ msg : '' }, success : function(data) { - // Refresh the area on the right side - $('#addHmc').dialog('close'); - $('.selectgroup').trigger('click'); + // Refresh the area on the right side + $('#addHmc').dialog('close'); + $('.selectgroup').trigger('click'); } - }); + }); } /** - * Select all checkbox in a table - * - * @return Nothing + * Select all checkbox in a table */ -function selectAllRscanNode(obj){ - var status = $(obj).attr('checked'); - $(obj).parents('table').find(':checkbox').attr('checked', status); +function selectAllRscanNode(obj) { + var status = $(obj).attr('checked'); + $(obj).parents('table').find(':checkbox').attr('checked', status); } /** - * Step 2: Cluster basic patterns - * users can input the switches' name range, the number of port, start ip and port prefix - * hmcs' name range, number and start ip - * frames' name range, number and start ip - * drawers' name range, number and start ip - * - * @param - * - * @return + * Step 2: Cluster basic patterns */ -function powerInitBasicPattern(){ +function powerInitBasicPattern() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); + var showString = '

                        ' + steps[currentStep] + '

                        '; showString += ''; - //Frame title + showString += ''; - //Frame Name - showString += ''; - //use the super node configure file to calculate the cec's number + showString += ''; + + // Use the super node to configure file and calculate the CEC's number showString += ''; - //CEC title showString += ''; - //CEC name - showString += ''; - //Number of LPARs per Drawer: - showString += ''; + showString += ''; + + showString += ''; - //Lpar title showString += ''; - //lpar name - showString += ''; - - //hmc title + showString += ''; + showString += ''; - //hmc name - showString += ''; - //Number of Frames per HMC - showString += ''; + showString += ''; + + showString += ''; showString += ''; showString += '

                        Frames:

                        Name Range:
                        Name Range:

                        Drawers:

                        Name Range:Number of LPARs per Drawer:
                        Name Range:Number of LPARs per Drawer:

                        Lpars:

                        Name Range:
                        Name Range:

                        HMCs:

                        Name Range:Number of Frames per HMC:
                        Name Range:Number of Frames per HMC:
                        Hardware Managment:HMC  '; showString += 'DFM
                        '; - + $('#discoverContentDiv').append(showString); - + $('#discoverContentDiv [title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 1 + position : "center right", + offset : [ -2, 10 ], + effect : "fade", + opacity : 1 }); - - //change the radio inputs' checked status - if (getDiscoverEnv('hmcFlag')){ + + // Change the radio input checked status + if (getDiscoverEnv('hmcFlag')) { $('#discoverContentDiv :radio[value=hmc]').attr('checked', 'checked'); - } - else{ + } else { $('#discoverContentDiv :radio[value=dfm]').attr('checked', 'checked'); } - + createDiscoverButtons(); } /** - * Step 2: check basic patterns - * when user input the basic patterns, we should check if the input is correct. - * @param - * - * @return + * Step 2: Check basic patterns when user input the basic patterns */ -function checkBasicPattern(operType){ +function checkBasicPattern(operType) { collectInputValue(); - //click back button, do not need check, only collect input value is ok. - if ('back' == operType){ + if ('back' == operType) { return true; } - + $('#patternDiv .ui-state-error').remove(); - + var errMessage = ''; var tempName = ''; var frameNum = 0; @@ -622,87 +588,85 @@ function checkBasicPattern(operType){ var cecNumPerFrame = getDiscoverEnv('cecNumPerFrame'); var frameNumPerHmc = getDiscoverEnv('frameNumPerHmc'); var lparNumPerCec = getDiscoverEnv('lparNumPerCec'); - - //check the frame name + + // Check the frame name tempName = getDiscoverEnv('frameName'); - if (!tempName){ + if (!tempName) { errMessage += 'Input the Frame Name Range.
                        '; - } - else{ + } else { frameNum = expandNR(tempName).length; } - - //check the cec name + + // Check the CEC name tempName = getDiscoverEnv('cecName'); - if (!tempName){ + if (!tempName) { errMessage += 'Input the CEC Name Range.
                        '; - } - else{ + } else { cecNum = expandNR(tempName).length; } - - //lpar number per cec - if (!lparNumPerCec){ + + // LPAR number per CEC + if (!lparNumPerCec) { errMessage += 'Input the Lpar Number Per Drawer.
                        '; } - - //check the lpar name + + // Check the LPAR name tempName = getDiscoverEnv('lparName'); - if (!tempName){ + if (!tempName) { errMessage += 'Input the Lpar Name Range.
                        '; - } - else{ + } else { lparNum = expandNR(tempName).length; } - - //check the hmc name + + // Check the HMC name tempName = getDiscoverEnv('hmcName'); - if (!tempName){ + if (!tempName) { errMessage += 'Input the HMC Name Range.
                        '; - } - else{ + } else { hmcNum = expandNR(tempName).length; } - - //frame number per hmc - if (!frameNumPerHmc){ + + // Frame number per HMC + if (!frameNumPerHmc) { errMessage += 'Input the Frame Number Per HMC.
                        '; } - - //the hardware management type is hmc. - if ('hmc' == $('#discoverContentDiv :checked').attr('value')){ + + // Hardware management type is HMC + if ('hmc' == $('#discoverContentDiv :checked').attr('value')) { setDiscoverEnv('hmcFlag', true); - } - else{ + } else { removeDiscoverEnv('hmcFlag'); } - - //the input value check is finished. - if ('' != errMessage){ + + // Input value check is finished + if ('' != errMessage) { var warnBar = createWarnBar(errMessage); $('#patternDiv').prepend(warnBar); return false; } - - //check the connections between all numbers. - if (getDiscoverEnv('hmcFlag')){ - if ((Number(frameNumPerHmc) * hmcNum) < frameNum){ - errMessage += 'The frame number should less than ' + Number(cecNumPerFrame) * frameNum + - ' ("the number of hmc" * "the number of frame managed by per hmc")'; + + // Check the connections between all numbers + if (getDiscoverEnv('hmcFlag')) { + if ((Number(frameNumPerHmc) * hmcNum) < frameNum) { + errMessage += 'The frame number should less than ' + + Number(cecNumPerFrame) + * frameNum + + ' ("the number of hmc" * "the number of frame managed by per hmc")'; } } - - if ((Number(lparNumPerCec) * cecNum) != lparNum){ - errMessage += 'The number of Lpars calculate by Name Range should be ' + Number(lparNumPerCec) * cecNum + - '("the number of Drawers" * "the number of lpar per drawer")'; + + if ((Number(lparNumPerCec) * cecNum) != lparNum) { + errMessage += 'The number of Lpars calculate by Name Range should be ' + + Number(lparNumPerCec) * cecNum + + '("the number of Drawers" * "the number of lpar per drawer")'; } - - if ('' != errMessage){ + + if ('' != errMessage) { var warnBar = createWarnBar(errMessage); $('#patternDiv').prepend(warnBar); return false; } - + setDiscoverEnv('cecNum', cecNum); setDiscoverEnv('frameNum', frameNum); setDiscoverEnv('lparNum', lparNum); @@ -711,94 +675,92 @@ function checkBasicPattern(operType){ } /** - * Step 3: allowed the users to edit the super node condigure file - * - * @param - * - * @return + * Step 3: Allow the users to edit the super node configure file */ -function powerInitSupernode(){ +function powerInitSupernode() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - $('#discoverContentDiv').append('

                        ' + steps[currentStep] + '

                        '); + $('#discoverContentDiv').append( + '

                        ' + + steps[currentStep] + '

                        '); createDiscoverButtons(); - - //add the introduction about the page + + // Add the introduction about the page var infoStr = '
                        The supernode-list file lists what supernode numbers should be '; infoStr += 'given to each CEC in each frame. Here is a sample file:
                        '; infoStr += 'frame1: 0, 1, 16
                        frame2: 17, 32
                        frame3: 33, 48, 49
                        '; infoStr += 'frame4: 64 , 65, 80
                        frame5: 81, 96
                        frame6: 97(1), 112(1), 113(1), 37(1), 55, 71
                        '; - infoStr += 'The name before the colon is the node name of the frame BPC. The numbers after the colon ' + - 'are the supernode numbers to assign to the groups of CECs in that frame from bottom to top. ' + - 'Each supernode contains 4 CECs, unless it is immediately followed by "(#)", in which case the ' + - 'number in parenthesis indicates how many CECs are in this supernode.
                        '; + infoStr += 'The name before the colon is the node name of the frame BPC. The numbers after the colon ' + + 'are the supernode numbers to assign to the groups of CECs in that frame from bottom to top. ' + + 'Each supernode contains 4 CECs, unless it is immediately followed by "(#)", in which case the ' + + 'number in parenthesis indicates how many CECs are in this supernode.
                        '; + var InfoBar = createInfoBar(infoStr); $('#discoverContentDiv #supernodeDiv').append(InfoBar); - + var frameArray = expandNR(getDiscoverEnv('frameName')); var showStr = '
                        '; - for (var i in frameArray){ - showStr += ''; + for (var i in frameArray) { + showStr += ''; } + showStr += '
                        ' + frameArray[i] + ':
                        ' + frameArray[i] + + ':
                        '; $('#discoverContentDiv #supernodeDiv').append(showStr); } /** - * Step 3: check the super node configure file - * - * @param - * - * @return + * Step 3: Check the super node configure file */ -function checkSupernode(operType){ +function checkSupernode(operType) { collectInputValue(); - - if ('back' == operType){ + + if ('back' == operType) { return true; } - + $('#supernodeDiv .ui-state-error').remove(); - + var errString = ''; var eceNum = 0; var args = ''; var frameArray = expandNR(getDiscoverEnv('frameName')); - for (var i in frameArray){ + for (var i in frameArray) { var sp_config = getDiscoverEnv('sp_' + frameArray[i]); - if (sp_config){ + if (sp_config) { eceNum += calcCec(sp_config); - if (0 == i){ + if (0 == i) { args += frameArray[i] + ': ' + sp_config; - } - else{ + } else { args += '\n' + frameArray[i] + ': ' + sp_config; } - } - else{ - errString += 'Input the super node configure for ' + frameArray[i] + '
                        '; + } else { + errString += 'Input the super node configure for ' + frameArray[i] + + '
                        '; } } - + args += '\n'; - + var warnBar; - if (errString){ + if (errString) { warnBar = createWarnBar(errString); $('#supernodeDiv').prepend(warnBar); return false; } - + var cecArray = expandNR(getDiscoverEnv('cecName')); - if (eceNum != cecArray.length){ - errString += 'The number of CEC calculated from supernode configure is ' + eceNum + ', but the number ' + - 'calculated from CECs\' Name Range is ' + cecArray.length + '. Reconfigure the supernode please.'; + if (eceNum != cecArray.length) { + errString += 'The number of CEC calculated from supernode configure is ' + + eceNum + ', but the number ' + 'calculated from CECs\' Name Range is ' + cecArray.length + + '. Reconfigure the supernode please.'; warnBar = createWarnBar(errString); $('#supernodeDiv').prepend(warnBar); return false; } - + $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -809,48 +771,44 @@ function checkSupernode(operType){ msg : '' } }); - + return true; } -function calcCec(spConfigStr){ +function calcCec(spConfigStr) { var tempArray = spConfigStr.split(','); var num = 0; var reg = /\(([1-4])\)/; - for (var i in tempArray){ + for (var i in tempArray) { var regRes = reg.exec(tempArray[i]); - if (regRes && regRes[1]){ + if (regRes && regRes[1]) { num += Number(regRes[1]); - } - else{ + } else { num += 4; } } - + return num; } /** - * Step 4: show the field which need to be configured in site table - * - * @param - * - * @return + * Step 4: Show the field which need to be configured in the site table */ -function powerInitSiteTable(operType){ +function powerInitSiteTable(operType) { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showDiv = $('

                        ' + steps[currentStep] + '(Site info)

                        '); + var showDiv = $('

                        ' + + steps[currentStep] + '(Site info)

                        '); var statBar = createStatusBar('siteTableStat'); statBar.find('div').append(createLoader()); showDiv.append(statBar); $('#discoverContentDiv').append(showDiv); - - if (getDiscoverEnv('domainname')){ + + if (getDiscoverEnv('domainname')) { showSiteArea(); return; } - + $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -860,196 +818,193 @@ function powerInitSiteTable(operType){ args : 'site', msg : '' }, - - success : function(data){ + + success : function(data) { setDiscoverEnv('domainname', ''); - setDiscoverEnv('nameserver',''); - for (var i in data.rsp){ + setDiscoverEnv('nameserver', ''); + for (var i in data.rsp) { var tempArray = data.rsp[i].split(','); var tempValue = tempArray[1]; - switch (tempArray[0]){ - case '"domain"':{ - setDiscoverEnv('domainname', tempValue.substr(1, tempValue.length - 2)); - } + switch (tempArray[0]) { + case '"domain"': { + setDiscoverEnv('domainname', tempValue.substr(1, + tempValue.length - 2)); + } break; - case '"nameservers"':{ - setDiscoverEnv('nameserver', tempValue.substr(1, tempValue.length - 2)); - } + case '"nameservers"': { + setDiscoverEnv('nameserver', tempValue.substr(1, + tempValue.length - 2)); + } break; } } showSiteArea(); } - }); + }); } /** - * Step 4: when the values are ready, create the table - * - * @param - * - * @return + * Step 4: When the values are ready, create the table */ -function showSiteArea(){ +function showSiteArea() { var showString = ''; - //domain name: - showString += ''; + + showString += ''; - //Name server - showString += ''; - - //ntp server - showString += ''; + showString += ''; + + showString += ''; showString += '
                        Domain Name:
                        Domain Name:
                        Name server:
                        DHCP Dynamic Range:-
                        Name server:
                        DHCP Dynamic Range:-
                        '; - + $('#discoverContentDiv div').eq(0).append(showString); - + $('#discoverContentDiv [title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 1 + position : "center right", + offset : [ -2, 10 ], + effect : "fade", + opacity : 1 }); - - $('#discoverContentDiv input[name=ipStart]').bind('change', function(){ - if (verifyIp($(this).attr('value'))){ - var tempNum = Number(getDiscoverEnv('frameNum')) * 4 + Number(getDiscoverEnv('cecNum')) * 4 + - Number(getDiscoverEnv('lparNum')) + Number(getDiscoverEnv('hmcNum')); - var ipEnd = calcEndIp($(this).attr('value'), tempNum); - if (!verifyIp(ipEnd)){ - ipEnd = ''; - } - $('#discoverContentDiv input[name=ipEnd]').attr('value', ipEnd); - } - else{ - $('#discoverContentDiv input[name=ipEnd]').attr('value', ''); - } - }); - - //show the current network interface configure + + $('#discoverContentDiv input[name=ipStart]').bind( + 'change', + function() { + if (verifyIp($(this).attr('value'))) { + var tempNum = Number(getDiscoverEnv('frameNum')) * 4 + + Number(getDiscoverEnv('cecNum')) * 4 + + Number(getDiscoverEnv('lparNum')) + + Number(getDiscoverEnv('hmcNum')); + var ipEnd = calcEndIp($(this).attr('value'), tempNum); + if (!verifyIp(ipEnd)) { + ipEnd = ''; + } + $('#discoverContentDiv input[name=ipEnd]').attr('value', + ipEnd); + } else { + $('#discoverContentDiv input[name=ipEnd]') + .attr('value', ''); + } + }); + + // Show the current network interface configuration $.ajax({ url : 'lib/systemcmd.php', dataType : 'json', data : { cmd : 'ifconfig | grep -E "encap|Mask"' }, - - success : function(data){ - $('#discoverContentDiv #siteTableStat div').html('Current network interface configuration:
                        ' + 
                        -                        data.rsp + '
                        '); + + success : function(data) { + $('#discoverContentDiv #siteTableStat div').html( + 'Current network interface configuration:
                        '
                        +                            + data.rsp + '
                        '); } }); createDiscoverButtons(); } /** - * Step 4: check the input are all filled - * - * @param - * - * @return + * Step 4: Check that the inputs are all filled */ -function checkSiteTable(operType){ +function checkSiteTable(operType) { $('#discoverContentDiv input[name=ipStart]').trigger('change'); collectInputValue(); - - if ('back' == operType){ + + if ('back' == operType) { return true; } - + $('#discoverContentDiv .ui-state-error').remove(); var errMessage = ''; - if (!getDiscoverEnv('domainname')){ + if (!getDiscoverEnv('domainname')) { errMessage += 'Input the domain name.
                        '; } - - if (!getDiscoverEnv('nameserver')){ + + if (!getDiscoverEnv('nameserver')) { errMessage += 'Input the name server.
                        '; } - - if (!getDiscoverEnv('ipEnd')){ + + if (!getDiscoverEnv('ipEnd')) { errMessage += 'Input the DHCP Dynamic Range.
                        '; } - - if ('' == errMessage){ - //update the dynamic ip to xcat db by xcatsetup and run makedhcp - $.ajax({ + + if ('' == errMessage) { + $.ajax({ url : 'lib/cmd.php', dataType : 'json', data : { cmd : 'webrun', tgt : '', - args : 'dynamiciprange;' + getDiscoverEnv('ipStart') + '-' + getDiscoverEnv('ipEnd'), + args : 'dynamiciprange;' + getDiscoverEnv('ipStart') + '-' + + getDiscoverEnv('ipEnd'), msg : '' } - }); + }); return true; } - + var warnBar = createWarnBar(errMessage); $('#discoverContentDiv #siteDiv').prepend(warnBar); return false; } /** - * Step 5: told users to power on machines - * - * @param - * - * @return + * Step 5: Tell users to power on machines */ -function powerInitPoweronHardware(){ +function powerInitPoweronHardware() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showStr = '

                        ' + steps[currentStep] + - '

                        Do the following manual steps now:

                        '; + var showStr = '

                        ' + steps[currentStep] + + '

                        Do the following manual steps now:

                        '; showStr += '
                        • 1. Power on the HMCs.
                        • '; showStr += '
                        • 2. Configure the HMC\'s static IP and enable the SLP & SSH ports by HMC GUI
                        • '; showStr += '
                        • 3. Power on all of Frames.
                        • '; showStr += '
                        • 4. Click Next to discover the hardware on the service network.
                        '; - + $('#discoverContentDiv').append(showStr); - + createDiscoverButtons(); } /** - * Step 6: discover all frames from the cluster and map all mtms with frame name - * - * @param - * - * @return + * Step 6: Discover all frames from the cluster and map all MTMs with frame name */ -function powerInitDiscoverFrames(){ +function powerInitDiscoverFrames() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showDiv = $('

                        ' + steps[currentStep] + '

                        '); + var showDiv = $('

                        ' + + steps[currentStep] + '

                        '); var statBar = createStatusBar('framedisc'); showDiv.append(statBar); $('#discoverContentDiv').append(showDiv); - $('#discoverShow').append('
                        '); + + $('#discoverShow fieldset table') + .append( + ''); } -function deleteMap(obj){ +function deleteMap(obj) { var mname = $(obj).parent().prev().html(); var fname = $(obj).parent().prev().prev().prev().html(); - + $(obj).parent().parent().remove(); - - $('#frameTd').append('

                        ' + fname + '

                        '); - $('#mtmsTd').append('

                        ' + mname + '

                        '); + + $('#frameTd').append( + '

                        ' + + fname + '

                        '); + $('#mtmsTd').append( + '

                        ' + + mname + '

                        '); } /** - * Step 6: write the frame and mtms map file - * - * @param - * - * @return + * Step 6: Write the frame and MTMs map file */ -function checkFrameMtms(operType){ - //check the number of radio button +function checkFrameMtms(operType) { + // Check the number of radio button var vpdFileCon = ''; $('#discoverShow .ui-state-error').remove(); - if (0 < $('#discoverShow :radio').size()){ + if (0 < $('#discoverShow :radio').size()) { var warnBar = createWarnBar('Map all of the frame with mtms.'); $('#discoverContentDiv #discoverShow').prepend(warnBar); return false; } - - //find out all maps - var maps = ''; - $('#discoverShow fieldset tr').each(function(){ - var fname = $(this).children().eq(0).html(); - var mtms = $(this).children().eq(2).html(); - var pos = mtms.lastIndexOf('-'); - var startpos = mtms.indexOf(':'); - maps += (fname + ',' + mtms + ';'); - vpdFileCon += fname + ':\n'; - vpdFileCon += ' objtype=node\n serial=' + mtms.substring(pos + 1) + '\n'; - vpdFileCon += ' mtm=' + mtms.substring(startpos + 1, pos) + '\n side=A\n'; - }); - + // Find out all maps + var maps = ''; + $('#discoverShow fieldset tr').each( + function() { + var fname = $(this).children().eq(0).html(); + var mtms = $(this).children().eq(2).html(); + var pos = mtms.lastIndexOf('-'); + var startpos = mtms.indexOf(':'); + + maps += (fname + ',' + mtms + ';'); + vpdFileCon += fname + ':\n'; + vpdFileCon += ' objtype=node\n serial=' + + mtms.substring(pos + 1) + '\n'; + vpdFileCon += ' mtm=' + mtms.substring(startpos + 1, pos) + + '\n side=A\n'; + }); + maps = maps.substr(0, maps.length - 1); setDiscoverEnv('framemtmsmap', maps); - - if ('back' == operType){ + + if ('back' == operType) { return true; } - - //write the maps into vpd table + + // Write the maps into vpd table $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -1196,91 +1167,90 @@ function checkFrameMtms(operType){ msg : '' } }); - + return true; } /** - * Step 7: create the xcatsetup configure file and run xcatsetup to define all objects - * in xcat database. - * - * @param - * - * @return + * Step 7: Create the xcatsetup configure file and run xcatsetup to define all + * objects in xcat database. */ -function powerInitConfig(operType){ +function powerInitConfig(operType) { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showStr = '

                        ' + steps[currentStep] + '

                        '; + var showStr = '

                        ' + steps[currentStep] + + '

                        '; + var iconClass = ''; - if ('back' == operType){ + if ('back' == operType) { iconClass = 'ui-icon-check'; - } - else{ + } else { iconClass = 'ui-icon-gear'; } + showStr += '
                          '; - showStr += '
                        • Create configure file for xcatsetup.
                        • '; - showStr += '
                        • Wrote Objects into xCAT database by xcatsetup.
                        • '; + showStr += '
                        • Create configure file for xcatsetup.
                        • '; + showStr += '
                        • Wrote Objects into xCAT database by xcatsetup.
                        • '; showStr += '
                        '; - + $('#discoverContentDiv').append(showStr); - - if ('back' == operType){ + + if ('back' == operType) { createDiscoverButtons(); return; } - + createSetupFile(); } /** - * Step 7: create the xcat configure file - * - * @param - * - * @return + * Step 7: Create the xcat configure file */ -function createSetupFile(){ +function createSetupFile() { var fileContent = ''; - + $('#fileLine').append(createLoader()); - //site info + + // Site info fileContent += 'xcat-site:\n'; fileContent += ' domain = ' + getDiscoverEnv('domainname') + '\n'; - if (getDiscoverEnv('hmcFlag')){ - //do nothing - } - else{ + if (getDiscoverEnv('hmcFlag')) { + // Do nothing + } else { fileContent += ' use-direct-fsp-control = 1\n'; } - - //dhcp ip range + + // DHCP IP range fileContent += 'xcat-service-lan:\n'; - fileContent += ' dhcp-dynamic-range = ' + getDiscoverEnv('ipStart') + '-' + getDiscoverEnv('ipEnd') + '\n'; - - //hmc - if (getDiscoverEnv('hmcName')){ + fileContent += ' dhcp-dynamic-range = ' + getDiscoverEnv('ipStart') + '-' + + getDiscoverEnv('ipEnd') + '\n'; + + // HMC + if (getDiscoverEnv('hmcName')) { fileContent += 'xcat-hmcs:\n'; fileContent += ' hostname-range = ' + getDiscoverEnv('hmcName') + '\n'; } - - //frame + + // Frame fileContent += 'xcat-frames:\n'; fileContent += ' hostname-range = ' + getDiscoverEnv('frameName') + '\n'; - fileContent += ' num-frames-per-hmc = ' + getDiscoverEnv('frameNumPerHmc') + '\n'; + fileContent += ' num-frames-per-hmc = ' + getDiscoverEnv('frameNumPerHmc') + + '\n'; fileContent += ' vpd-file = /tmp/webvpd.stanza\n'; - - //cec + + // CEC fileContent += 'xcat-cecs:\n'; fileContent += ' hostname-range = ' + getDiscoverEnv('cecName') + '\n'; fileContent += ' delete-unused-cecs = 1\n'; fileContent += ' supernode-list = /tmp/websupernode.txt\n'; - - //lpar + + // LPAR fileContent += 'xcat-lpars:\n'; - fileContent += ' num-lpars-per-cec = ' + getDiscoverEnv('lparNumPerCec') + '\n'; + fileContent += ' num-lpars-per-cec = ' + getDiscoverEnv('lparNumPerCec') + + '\n'; fileContent += ' hostname-range = ' + getDiscoverEnv('lparName') + '\n'; - + $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -1290,8 +1260,8 @@ function createSetupFile(){ args : 'writeconfigfile;/tmp/webxcat.conf;' + fileContent, msg : '' }, - - success : function(){ + + success : function() { $('#fileLine img').remove(); var tempSpan = $('#fileLine').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1302,13 +1272,9 @@ function createSetupFile(){ } /** - * Step 7: run the xcatsetup command - * - * @param - * - * @return + * Step 7: Run the xcatsetup command */ -function runSetup(){ +function runSetup() { $('#setupLine').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1319,8 +1285,8 @@ function runSetup(){ args : '/tmp/webxcat.conf', msg : '' }, - - success : function(){ + + success : function() { $('#setupLine img').remove(); var tempSpan = $('#setupLine').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1331,51 +1297,51 @@ function runSetup(){ } /** - * Step 8: discover all hmc,cec in cluster and update into xcat database - * - * @param - * - * @return + * Step 8: Discover all HMC and CEC in the cluster and update into xCAT database */ -function powerInitUpdateDefinition(operType){ +function powerInitUpdateDefinition(operType) { $('#discoverContentDiv').empty(); $('.tooltip').remove(); + var iconClass = ''; - if ('back' == operType){ + if ('back' == operType) { iconClass = 'ui-icon-check'; - } - else{ + } else { iconClass = 'ui-icon-gear'; } + var showStr = '

                        ' + steps[currentStep] + '

                        '; showStr += '
                          '; - showStr += '
                        • Update Frames into xCAT database.
                        • '; - showStr += '
                        • Discover HMCs.
                        • '; - showStr += '
                        • Update HMCs into xCAT database.
                        • '; - showStr += '
                        • Make hardware connections for Frames.
                        • '; - showStr += '
                        • Discover CECs and update into xCAT database.
                        • '; - showStr += '
                        • Make hardware connections for CECs.
                        • '; - showStr += '
                        • Configured DHCP.
                        • '; + showStr += '
                        • Update Frames into xCAT database.
                        • '; + showStr += '
                        • Discover HMCs.
                        • '; + showStr += '
                        • Update HMCs into xCAT database.
                        • '; + showStr += '
                        • Make hardware connections for Frames.
                        • '; + showStr += '
                        • Discover CECs and update into xCAT database.
                        • '; + showStr += '
                        • Make hardware connections for CECs.
                        • '; + showStr += '
                        • Configured DHCP.
                        • '; showStr += '
                        '; - + $('#discoverContentDiv').append(showStr); - - if ('back' == operType){ + + if ('back' == operType) { createDiscoverButtons(); return; } - + lsslpWriteFrame(); } /** - * Step 8: write all the lsslp -s FRAME info into database - * - * @param - * - * @return + * Step 8: Write all lsslp frame info into the database */ -function lsslpWriteFrame(){ +function lsslpWriteFrame() { $('#frameLine').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1386,8 +1352,8 @@ function lsslpWriteFrame(){ args : '-s;FRAME;-w', msg : '' }, - - success : function(){ + + success : function() { $('#frameLine img').remove(); var tempSpan = $('#frameLine').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1398,13 +1364,9 @@ function lsslpWriteFrame(){ } /** - * Step 8: write all the lsslp -s HMC info into database - * - * @param - * - * @return + * Step 8: Write all the lsslp HMC info into database */ -function lsslpWriteHMC(){ +function lsslpWriteHMC() { $('#hmcLine1').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1415,42 +1377,46 @@ function lsslpWriteHMC(){ args : 'discover;hmc', msg : '' }, - - success : function(data){ - //modify the page elements + + success : function(data) { + // modify the page elements $('#hmcLine1 img').remove(); var tempSpan = $('#hmcLine1').find('span'); tempSpan.removeClass('ui-icon-gear'); tempSpan.addClass('ui-icon-check'); $('#hmcLine2').append(createLoader()); - + var hmcArray = expandNR(getDiscoverEnv('hmcName')); var mtmsArray = data.rsp[0].split(';'); var tempPar = ''; - - if (hmcArray.length != mtmsArray.length){ - //error info + + if (hmcArray.length != mtmsArray.length) { + // Error info $('#hmcLine2 img').remove(); - var warnBar = createWarnBar('Error: Defined ' + hmcArray.length + ' HMCs, but discovered ' + mtmsArray.length + - ' HMCs. Please check the configuration.'); + var warnBar = createWarnBar('Error: Defined ' + hmcArray.length + + ' HMCs, but discovered ' + mtmsArray.length + + ' HMCs. Please check the configuration.'); $('#discoverContentDiv div').prepend(warnBar); createDiscoverButtons(); return; } - - //create the hmc and mtms pair string - for (var i in hmcArray){ + + // Create the HMC and MTMs pair string + for (var i in hmcArray) { var tPos = mtmsArray[i].lastIndexOf('-'); - var startPos= mtmsArray[i].indexOf(':'); - if ('' == tempPar){ - tempPar += hmcArray[i] + ',' + mtmsArray[i].substring(startPos + 1, tPos) + ',' +mtmsArray[i].substring(tPos + 1); - } - else{ - tempPar += ':' + hmcArray[i] + ',' + mtmsArray[i].substring(startPos + 1, tPos) + ',' +mtmsArray[i].substring(tPos + 1); + var startPos = mtmsArray[i].indexOf(':'); + if ('' == tempPar) { + tempPar += hmcArray[i] + ',' + + mtmsArray[i].substring(startPos + 1, tPos) + ',' + + mtmsArray[i].substring(tPos + 1); + } else { + tempPar += ':' + hmcArray[i] + ',' + + mtmsArray[i].substring(startPos + 1, tPos) + ',' + + mtmsArray[i].substring(tPos + 1); } } - - //write the mtms and hmcname pair into vpd table + + // Write MTMs and HMC name pair into vpd table $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -1460,8 +1426,8 @@ function lsslpWriteHMC(){ args : 'updatevpd;' + tempPar, msg : '' }, - success: function(){ - //run lsslp and write all infomation into datatable + success : function() { + // Run lsslp and write all info into datatable $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -1471,31 +1437,27 @@ function lsslpWriteHMC(){ args : '-s;HMC;-w', msg : '' }, - success: function(){ + success : function() { $('#hmcLine2 img').remove(); var tempSpan = $('#hmcLine2').find('span'); tempSpan.removeClass('ui-icon-gear'); tempSpan.addClass('ui-icon-check'); mkhwconnFrame(); } - }); + }); } - }); + }); } }); } /** - * Step 8: make the hardware connection for frames. - * - * @param - * - * @return + * Step 8: Make the hardware connection for frames */ -function mkhwconnFrame(){ - $('#frameLine2').append(createLoader()); - $.ajax({ - url : 'lib/cmd.php', +function mkhwconnFrame() { + $('#frameLine2').append(createLoader()); + $.ajax({ + url : 'lib/cmd.php', dataType : 'json', data : { cmd : 'mkhwconn', @@ -1503,7 +1465,7 @@ function mkhwconnFrame(){ args : '-t', msg : '' }, - success: function(){ + success : function() { $('#frameLine2 img').remove(); var tempSpan = $('#frameLine2').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1514,13 +1476,9 @@ function mkhwconnFrame(){ } /** - * Step 8: write all the lsslp -s cec info into database - * - * @param - * - * @return + * Step 8: Write all the lsslp cec info into database */ -function lsslpWriteCec(){ +function lsslpWriteCec() { $('#cecLine').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1531,7 +1489,7 @@ function lsslpWriteCec(){ args : '-s;CEC;-w', msg : '' }, - success: function(){ + success : function() { $('#cecLine img').remove(); var tempSpan = $('#cecLine').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1542,13 +1500,9 @@ function lsslpWriteCec(){ } /** - * Step 8: make hardware connection for cecs - * - * @param - * - * @return + * Step 8: Make hardware connection for CECs */ -function mkhwconnCec(){ +function mkhwconnCec() { $('#cecLine2').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1559,7 +1513,7 @@ function mkhwconnCec(){ args : '-t', msg : '' }, - success: function(){ + success : function() { $('#cecLine2 img').remove(); var tempSpan = $('#cecLine2').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1570,13 +1524,9 @@ function mkhwconnCec(){ } /** - * Step 8: create the dhcp configure file - * - * @param - * - * @return + * Step 8: Create the DHCP configure file */ -function configDHCP(){ +function configDHCP() { $('#dhcpLine').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1587,8 +1537,8 @@ function configDHCP(){ args : '-n', msg : '' }, - - success : function(){ + + success : function() { $('#dhcpLine img').remove(); var tempSpan = $('#dhcpLine').find('span'); tempSpan.removeClass('ui-icon-gear'); @@ -1599,147 +1549,150 @@ function configDHCP(){ } /** - * Step 9: create lpars - * - * @param - * - * @return + * Step 9: Create LPARs */ -function powerInitCreateLpar(){ +function powerInitCreateLpar() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showDiv = $('

                        ' + steps[currentStep] + '

                        '); - switch (getDiscoverEnv('machineType')){ - case 'ih':{ + var showDiv = $('

                        ' + + steps[currentStep] + '

                        '); + switch (getDiscoverEnv('machineType')) { + case 'ih': ihCreateLpar(showDiv); - } - break; - case 'nonih':{ + break; + case 'nonih': nonihCreateLpar(showDiv); - } - break; + break; default: - break; + break; } + $('#discoverContentDiv').append(showDiv); createDiscoverButtons(); } -function ihCreateLpar(parentDiv){ - var showStr = 'Partition Rule:
                        ' + - 'If all the octants configuration value are same in one CEC, it will be " -r 0-7:value".
                        ' + - 'If the octants use the different configuration value in one cec, it will be "-r 0:value1,1:value2,...7:value7", or "-r 0:value1,1-7:value2".
                        ' + - 'The octants configuration value for one Octant could be 1, 2, 3, 4, 5 . The meanings of the octants configuration value are as following:
                        ' + - '1 - 1 partition with all cpus and memory of the octant
                        ' + - '2 - 2 partitions with a 50/50 split of cpus and memory
                        ' + - '3 - 3 partitions with a 25/25/50 split of cpus and memory
                        ' + - '4 - 4 partitions with a 25/25/25/25 split of cpus and memory
                        ' + - '5 - 2 partitions with a 25/75 split of cpus and memory
                        ' + - 'Define the configuration rule for one CEC, and create all Lpars on all CECs by this rule. Or ignore this step.'; - +function ihCreateLpar(parentDiv) { + var showStr = 'Partition Rule:
                        ' + + 'If all the octants configuration value are same in one CEC, it will be " -r 0-7:value".
                        ' + + 'If the octants use the different configuration value in one cec, it will be "-r 0:value1,1:value2,...7:value7", or "-r 0:value1,1-7:value2".
                        ' + + 'The octants configuration value for one Octant could be 1, 2, 3, 4, 5 . The meanings of the octants configuration value are as following:
                        ' + + '1 - 1 partition with all cpus and memory of the octant
                        ' + + '2 - 2 partitions with a 50/50 split of cpus and memory
                        ' + + '3 - 3 partitions with a 25/25/50 split of cpus and memory
                        ' + + '4 - 4 partitions with a 25/25/25/25 split of cpus and memory
                        ' + + '5 - 2 partitions with a 25/75 split of cpus and memory
                        ' + + 'Define the configuration rule for one CEC, and create all Lpars on all CECs by this rule. Or ignore this step.'; + parentDiv.append(createInfoBar(showStr)); - parentDiv.append('
                        ' + $('#discoverShow').append('
                        ' + '
                        '); - - if (getDiscoverEnv('framemtmsmap')){ - $('#framedisc div').html('Mapping the frame name and mtms which discovered by lsslp.' + - 'Select the frame name, then select the mtms.'); + + if (getDiscoverEnv('framemtmsmap')) { + $('#framedisc div').html( + 'Mapping the frame name and mtms which discovered by lsslp.' + + 'Select the frame name, then select the mtms.'); + var mapArray = getDiscoverEnv('framemtmsmap').split(';'); - for(var i in mapArray){ + for (var i in mapArray) { var tempArray = mapArray[i].split(','); showMap(tempArray[0], tempArray[1]); } - + createDiscoverButtons(); return; } + + statBar.find('div').append('Discovering all Frames by lsslp.').append( + createLoader()); - statBar.find('div').append('Discovering all Frames by lsslp.').append(createLoader()); - //use lsslp to find all bpas in cluster $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -1059,133 +1014,149 @@ function powerInitDiscoverFrames(){ args : 'discover;frame', msg : '' }, - - success : function(data){ + + success : function(data) { var tempInfo = data.rsp[0]; - if (-1 != tempInfo.indexOf('Error')){ + if (-1 != tempInfo.indexOf('Error')) { $('#framedisc div').html(tempInfo); createDiscoverButtons(); return; } - + var mtmsArray = tempInfo.split(';'); var frameArray = expandNR(getDiscoverEnv('frameName')); - //chech the defined number and discovered number - if (mtmsArray.length != frameArray.length){ - $('#framedisc div').html('Error: Definded Number is ' + frameArray.length + - ', but lsslp discovered Number is ' + mtmsArray.length + ', please check your configure!'); + + // Check the defined number and discovered number + if (mtmsArray.length != frameArray.length) { + $('#framedisc div').html( + 'Error: Definded Number is ' + frameArray.length + + ', but lsslp discovered Number is ' + + mtmsArray.length + + ', please check your configure!'); createDiscoverButtons(); return; } - - $('#framedisc div').html('Mapping the frame name and mtms which discovered by lsslp.' + - 'Select the frame name, then select the mtms.'); - - for (var i in frameArray){ - $('#frameTd').append('

                        ' + - frameArray[i] + '

                        '); - + + $('#framedisc div').html( + 'Mapping the frame name and mtms which discovered by lsslp.' + + 'Select the frame name, then select the mtms.'); + + for (var i in frameArray) { + $('#frameTd').append( + '

                        ' + + frameArray[i] + '

                        '); + } - - for (var i in mtmsArray){ - $('#mtmsTd').append('

                        ' + - mtmsArray[i] + '

                        '); + + for (var i in mtmsArray) { + $('#mtmsTd').append( + '

                        ' + + mtmsArray[i] + '

                        '); } - + createDiscoverButtons(); } }); } -function createMap(obj){ +function createMap(obj) { var fname = ''; var mname = ''; - - if ($('#discoverShow :checked').size() < 2){ + + if ($('#discoverShow :checked').size() < 2) { return; } - - if('frameradio' == $(obj).attr('name')){ + + if ('frameradio' == $(obj).attr('name')) { fname = $(obj).next().html(); mname = $('#discoverShow input[name=mtmsradio]:checked').next().html(); - } - else{ + } else { fname = $('#discoverShow input[name=frameradio]:checked').next().html(); mname = $(obj).next().html(); } - + $('#discoverShow :checked').parent().remove(); showMap(fname, mname); } -function showMap(fname, mname){ +function showMap(fname, mname) { var rowClass = ''; - - if ($('#discoverShow fieldset').size() < 1){ - $('#discoverShow').append('
                        Frame and MTMS map
                        '); + + if ($('#discoverShow fieldset').size() < 1) { + $('#discoverShow') + .append( + '
                        Frame and MTMS map
                        '); } - - if (0 == $('#discoverShow fieldset tr').size() % 2){ + + if (0 == $('#discoverShow fieldset tr').size() % 2) { rowClass = 'odd'; - } - else{ + } else { rowClass = 'even'; } - - $('#discoverShow fieldset table').append('
                        ' + fname + - '<---->' + mname + - '
                        ' + + fname + + '<---->' + + mname + + '
                        ' + - '
                        Partition Configuration:
                        '); - + parentDiv.append('
                        ' + + '
                        Partition Configuration:
                        '); + var lparButton = createButton('Create Lpars'); parentDiv.find('td').eq(2).append(lparButton); - - lparButton.bind('click', function(){ - var reg = /(([0-7]|[0-7]-[0-7]):[1-5],)*(([0-7]|[0-7]-[0-7]):[1-5])$/g; - var lparCount = 0; - $('#discoverContentDiv .ui-state-error').remove(); - collectInputValue(); - var inputStr = getDiscoverEnv('partconf'); - var testArray = reg.exec(inputStr); - if (!testArray || inputStr != testArray[0]){ - var warnBar = createWarnBar('Input the correct configuration rule.'); - $('#discoverContentDiv').prepend(warnBar); - return; - } - var ruleArray = inputStr.split(','); - for (var i in ruleArray){ - var octantCount = 0; - var octantArray = ruleArray[i].split(':'); - var octantRule = Number(octantArray[1]); - var pos = octantArray[0].indexOf('-'); - if (5 == octantRule){ - octantRule = 2; + lparButton.bind('click', + function() { + var reg = /(([0-7]|[0-7]-[0-7]):[1-5],)*(([0-7]|[0-7]-[0-7]):[1-5])$/g; + var lparCount = 0; + $('#discoverContentDiv .ui-state-error').remove(); + collectInputValue(); + var inputStr = getDiscoverEnv('partconf'); + var testArray = reg.exec(inputStr); + if (!testArray || inputStr != testArray[0]) { + var warnBar = createWarnBar('Input the correct configuration rule.'); + $('#discoverContentDiv').prepend(warnBar); + return; } - if (-1 == pos){ - octantCount = 1; - } - else{ - var startIndex = Number(octantArray[0].substring(0, pos)); - var endIndex = Number(octantArray[0].substring(pos + 1)); - octantCount = endIndex - startIndex + 1; - } - - lparCount += octantCount * octantRule; - } - - if (getDiscoverEnv('lparNumPerCec') != lparCount){ - var warnBar = createWarnBar('The LPAR number per CEC is ' + getDiscoverEnv('lparNumPerCec') + ', but the configuration ' + - 'rule calculation is ' + lparCount + '.'); - $('#discoverContentDiv').prepend(warnBar); - return; - } - - var diaDiv = $('
                        '); - diaDiv.append('
                          '); - diaDiv.append(createLoader()); - diaDiv.dialog({ - modal: true, - width: 600, - title: 'Creating Lpars...' - }); - - $('.ui-dialog-titlebar-close').hide(); - - var cecArray = expandNR(getDiscoverEnv('cecName')); - for (var i in cecArray){ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'mkvm', - tgt : cecArray[i] + 'nodes', - args : '-i;1;-m;non-interleaved;-r;' + inputStr, - msg : cecArray[i] + ';' + cecArray.length - }, - - success : function(data) { - //update the dialogure - var tempArray = data.msg.split(';'); - updateCreateLparDia(tempArray[0], Number(tempArray[1])); + var ruleArray = inputStr.split(','); + for (var i in ruleArray) { + var octantCount = 0; + var octantArray = ruleArray[i].split(':'); + var octantRule = Number(octantArray[1]); + var pos = octantArray[0].indexOf('-'); + if (5 == octantRule) { + octantRule = 2; } + + if (-1 == pos) { + octantCount = 1; + } else { + var startIndex = Number(octantArray[0] + .substring(0, pos)); + var endIndex = Number(octantArray[0] + .substring(pos + 1)); + octantCount = endIndex - startIndex + 1; + } + + lparCount += octantCount * octantRule; + } + + if (getDiscoverEnv('lparNumPerCec') != lparCount) { + var warnBar = createWarnBar('The LPAR number per CEC is ' + + getDiscoverEnv('lparNumPerCec') + + ', but the configuration ' + + 'rule calculation is ' + lparCount + '.'); + $('#discoverContentDiv').prepend(warnBar); + return; + } + + var diaDiv = $('
                          '); + diaDiv.append('
                            '); + diaDiv.append(createLoader()); + diaDiv.dialog({ + modal : true, + width : 600, + title : 'Creating Lpars...' }); - } - }); + + $('.ui-dialog-titlebar-close').hide(); + + var cecArray = expandNR(getDiscoverEnv('cecName')); + for (var i in cecArray) { + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'mkvm', + tgt : cecArray[i] + 'nodes', + args : '-i;1;-m;non-interleaved;-r;' + + inputStr, + msg : cecArray[i] + ';' + cecArray.length + }, + + success : function(data) { + // update the dialogure + var tempArray = data.msg.split(';'); + updateCreateLparDia(tempArray[0], + Number(tempArray[1])); + } + }); + } + }); } -function updateCreateLparDia(cecname, cecNum){ +function updateCreateLparDia(cecname, cecNum) { $('#createLparDiv ul').append('
                          • Creating lpars on ' + cecname + ' competed.
                          • '); - - if (cecNum != $('#createLparDiv li').size()){ + + if (cecNum != $('#createLparDiv li').size()) { return; } - + $('#createLparDiv').empty(); - $('#createLparDiv').append('

                            All lpars are created. You must:
                            1. reboot the all CECS.
                            '+ - '2.use chvm to assign the I/O slots to the new LPAR.

                            '); - + $('#createLparDiv').append('

                            All lpars are created. You must:
                            1. reboot the all CECS.
                            ' + + '2.use chvm to assign the I/O slots to the new LPAR.

                            '); + var chvmButton = createButton('OK'); $('#createLparDiv').append(chvmButton); - chvmButton.bind('click', function(){ + chvmButton.bind('click', function() { $('#createLparDiv').dialog('destroy'); $('#createLparDiv').remove(); }); } -function nonihCreateLpar(parentDiv){ +function nonihCreateLpar(parentDiv) { var showStr = 'The machine type is not P7 IH, so you had to create lpars by command line manually.'; parentDiv.append(createInfoBar(showStr)); return; diff --git a/xCAT-UI/js/custom/ipmi.js b/xCAT-UI/js/custom/ipmi.js index 7fb21ac3e..86d7d476b 100644 --- a/xCAT-UI/js/custom/ipmi.js +++ b/xCAT-UI/js/custom/ipmi.js @@ -2,13 +2,11 @@ * Execute when the DOM is fully loaded */ $(document).ready(function() { - // Load utility scripts (if any) + // Load utility scripts (if any) }); /** * Constructor - * - * @return Nothing */ var ipmiPlugin = function() { @@ -19,29 +17,28 @@ var ipmiPlugin = function() { * * @return Discovery steps */ -ipmiPlugin.prototype.getStep = function(){ - return ['Basic patterns', 'Switches', 'Network', 'Services', 'Power on hardware']; +ipmiPlugin.prototype.getStep = function() { + return [ 'Basic patterns', 'Switches', 'Network', 'Services', + 'Power on hardware' ]; }; /** - * return steps's init function for hardware discovery wizard - * - * @return Nothing + * Return step init function for hardware discovery wizard */ -ipmiPlugin.prototype.getInitFunction = function(){ - return [idataplexInitBasic, idataplexInitSwitch, idataplexInitNetwork, idataplexInitService, idataplexInitPowerOn]; +ipmiPlugin.prototype.getInitFunction = function() { + return [ idataplexInitBasic, idataplexInitSwitch, idataplexInitNetwork, + idataplexInitService, idataplexInitPowerOn ]; }; -ipmiPlugin.prototype.getNextFunction = function(){ - return [idataplexCheckBasic, undefined, idataplexCheckNetwork, undefined, undefined]; +ipmiPlugin.prototype.getNextFunction = function() { + return [ idataplexCheckBasic, undefined, idataplexCheckNetwork, undefined, + undefined ]; }; /** * Clone node (service page) * - * @param node - * Node to clone - * @return Nothing + * @param node Node to clone */ ipmiPlugin.prototype.serviceClone = function(node) { @@ -50,171 +47,161 @@ ipmiPlugin.prototype.serviceClone = function(node) { /** * Load provision page (service page) * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ ipmiPlugin.prototype.loadServiceProvisionPage = function(tabId) { - + }; /** * Show node inventory (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ ipmiPlugin.prototype.loadServiceInventory = function(data) { - + }; /** * Load node inventory * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ ipmiPlugin.prototype.loadInventory = function(data) { - var args = data.msg.split(','); - var tabId = args[0].replace('out=', ''); - var node = args[1].replace('node=', ''); - - // Get node inventory - var inv = data.rsp; + var args = data.msg.split(','); + var tabId = args[0].replace('out=', ''); + var node = args[1].replace('node=', ''); - // Remove loader - $('#' + tabId).find('img').remove(); + // Get node inventory + var inv = data.rsp; - // Create division to hold inventory - var invDiv = $('
                            '); - - // Create a fieldset - var fieldSet = $('
                            '); - var legend = $('Hardware'); - fieldSet.append(legend); - - var oList = $('
                              '); - fieldSet.append(oList); - invDiv.append(fieldSet); + // Remove loader + $('#' + tabId).find('img').remove(); - // Loop through each line - var item; - for (var k = 0; k < inv.length; k++) { - // Remove node name - var attr = inv[k].replace(node + ': ', ''); - attr = jQuery.trim(attr); + // Create division to hold inventory + var invDiv = $('
                              '); - // Append attribute to list - item = $('
                            1. '); - item.append(attr); - oList.append(item); - } + // Create a fieldset + var fieldSet = $('
                              '); + var legend = $('Hardware'); + fieldSet.append(legend); - // Append to inventory form - $('#' + tabId).append(invDiv); + var oList = $('
                                '); + fieldSet.append(oList); + invDiv.append(fieldSet); + + // Loop through each line + var item; + for ( var k = 0; k < inv.length; k++) { + // Remove node name + var attr = inv[k].replace(node + ': ', ''); + attr = jQuery.trim(attr); + + // Append attribute to list + item = $('
                              1. '); + item.append(attr); + oList.append(item); + } + + // Append to inventory form + $('#' + tabId).append(invDiv); }; /** * Load clone page * - * @param node - * Source node to clone - * @return Nothing + * @param node Source node to clone */ ipmiPlugin.prototype.loadClonePage = function(node) { - // Get nodes tab - var tab = getNodesTab(); - var newTabId = node + 'CloneTab'; + // Get nodes tab + var tab = getNodesTab(); + var newTabId = node + 'CloneTab'; - // If there is no existing clone tab - if (!$('#' + newTabId).length) { - // Create info bar - var infoBar = createInfoBar('Not supported'); + // If there is no existing clone tab + if (!$('#' + newTabId).length) { + // Create info bar + var infoBar = createInfoBar('Not supported'); - // Create clone form - var cloneForm = $('
                                '); - cloneForm.append(infoBar); + // Create clone form + var cloneForm = $('
                                '); + cloneForm.append(infoBar); - // Add clone tab - tab.add(newTabId, 'Clone', cloneForm, true); - } - - tab.select(newTabId); + // Add clone tab + tab.add(newTabId, 'Clone', cloneForm, true); + } + + tab.select(newTabId); }; /** * Load provision page * - * @param tabId - * The provision tab ID - * @return Nothing + * @param tabId The provision tab ID */ ipmiPlugin.prototype.loadProvisionPage = function(tabId) { - // Get OS image names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS image names + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); + success : setOSImageCookies + }); - // Get groups - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'extnoderange', - tgt : '/.*', - args : 'subgroups', - msg : '' - }, + // Get groups + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'extnoderange', + tgt : '/.*', + args : 'subgroups', + msg : '' + }, - success : setGroupsCookies - }); + success : setGroupsCookies + }); - // Get provision tab instance - var inst = tabId.replace('ipmiProvisionTab', ''); + // Get provision tab instance + var inst = tabId.replace('ipmiProvisionTab', ''); - // Create provision form - var provForm = $('
                                '); + // Create provision form + var provForm = $('
                                '); - // Create info bar - var infoBar = createInfoBar('Provision an iDataPlex. This will install an operating system onto the iDataPlex.'); - provForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Provision an iDataPlex. This will install an operating system onto the iDataPlex.'); + provForm.append(infoBar); - // Append to provision tab - $('#' + tabId).append(provForm); + // Append to provision tab + $('#' + tabId).append(provForm); - // Create provision existing node division - var provExisting = createIpmiProvisionExisting(inst); - provForm.append(provExisting); + // Create provision existing node division + var provExisting = createIpmiProvisionExisting(inst); + provForm.append(provExisting); }; /** * Load resources */ ipmiPlugin.prototype.loadResources = function() { - // Get resource tab ID - var tabId = 'ipmiResourceTab'; - // Remove loader - $('#' + tabId).find('img').remove(); - - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // Get resource tab ID + var tabId = 'ipmiResourceTab'; + // Remove loader + $('#' + tabId).find('img').remove(); - // Create resource form - var resrcForm = $('
                                '); - resrcForm.append(infoBar); - - $('#' + tabId).append(resrcForm); + // Create info bar + var infoBar = createInfoBar('Not yet supported'); + + // Create resource form + var resrcForm = $('
                                '); + resrcForm.append(infoBar); + + $('#' + tabId).append(resrcForm); }; /** @@ -224,21 +211,31 @@ ipmiPlugin.prototype.addNode = function() { var dialog = $('
                                '); var info = createInfoBar('Add a iDataPlex node'); dialog.append(info); - + // Create node inputs - dialog.append($('
                                ')); - dialog.append($('
                                ')); - dialog.append($('
                                ')); - dialog.append($('
                                ')); + dialog + .append($('
                                ')); + dialog + .append($('
                                ')); + dialog + .append($('
                                ')); + dialog + .append($('
                                ')); dialog.dialog({ - title: 'Add node', - modal: true, - width: 400, - close: function(){$(this).remove();}, - buttons: { - "OK" : function(){addIdataplex();}, - "Cancel": function(){$(this).dialog('close');} + title : 'Add node', + modal : true, + width : 400, + close : function() { + $(this).remove(); + }, + buttons : { + "OK" : function() { + addIdataplex(); + }, + "Cancel" : function() { + $(this).dialog('close'); + } } }); }; @@ -246,47 +243,47 @@ ipmiPlugin.prototype.addNode = function() { /** * Add iDataPlex node range */ -function addIdataplex(){ - var attr, args; +function addIdataplex() { + var attr, args; var errorMessage = ''; - + // Remove existing warnings $('#addIdplx .ui-state-error').remove(); - + // Return input border colors to normal $('#addIdplx input').css('border', 'solid #BDBDBD 1px'); - + // Check node attributes - $('#addIdplx input').each(function(){ + $('#addIdplx input').each(function() { attr = $(this).val(); if (!attr) { errorMessage = "Please provide a value for each missing field!"; $(this).css('border', 'solid #FF0000 1px'); } }); - + // Show error message (if any) if (errorMessage) { $('#addIdplx').prepend(createWarnBar(errorMessage)); return; } - + // Create loader $('#addIdplx').append(createLoader()); - + // Change dialog buttons $('#addIdplx').dialog('option', 'buttons', { - 'Close':function(){ - $('#addIdplx').dialog('close'); - } + 'Close' : function() { + $('#addIdplx').dialog('close'); + } }); - + // Generate chdef arguments - args = '-t;node;-o;' + $('#addIdplx input[name="node"]').val() - + ';ip=' + $('#addIdplx input[name="ip"]').val() - + ';mac=' + $('#addIdplx input[name="mac"]').val() - + ';groups=' + $('#addIdplx input[name="groups"]').val() - + ';mgt=ipmi;netboot=xnba;nodetype=osi;profile=compute'; + args = '-t;node;-o;' + $('#addIdplx input[name="node"]').val() + ';ip=' + + $('#addIdplx input[name="ip"]').val() + ';mac=' + + $('#addIdplx input[name="mac"]').val() + ';groups=' + + $('#addIdplx input[name="groups"]').val() + + ';mgt=ipmi;netboot=xnba;nodetype=osi;profile=compute'; $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -296,28 +293,28 @@ function addIdataplex(){ args : args, msg : '' }, - success: function(data) { - // Update /etc/hosts - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : '' - } - }); - - // Remove loader + success : function(data) { + // Update /etc/hosts + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : '' + } + }); + + // Remove loader $('#addIdplx img').remove(); - + // Get return message var message = ''; - for (var i in data.rsp) { + for ( var i in data.rsp) { message += data.rsp[i] + '
                                '; } - + // Show return message if (message) $('#addIdplx').prepend(createInfoBar(message)); @@ -328,411 +325,416 @@ function addIdataplex(){ /** * Create provision existing node division * - * @param inst - * Provision tab instance + * @param inst Provision tab instance * @return Provision existing node division */ function createIpmiProvisionExisting(inst) { - // Create provision existing division - var provExisting = $('
                                '); + // Create provision existing division + var provExisting = $('
                                '); - // Create node fieldset - var nodeFS = $('
                                '); - var nodeLegend = $('Node'); - nodeFS.append(nodeLegend); - - var nodeAttr = $('
                                '); - nodeFS.append($('
                                ')); - nodeFS.append(nodeAttr); - - // Create image fieldset - var imgFS = $('
                                '); - var imgLegend = $('Image'); - imgFS.append(imgLegend); - - var imgAttr = $('
                                '); - imgFS.append($('
                                ')); - imgFS.append(imgAttr); - - provExisting.append(nodeFS, imgFS); - - // Create group input - var group = $('
                                '); - var groupLabel = $(''); - group.append(groupLabel); + // Create node fieldset + var nodeFS = $('
                                '); + var nodeLegend = $('Node'); + nodeFS.append(nodeLegend); - // Turn on auto complete for group - var dTableDivId = 'ipmiNodesDatatableDIV' + inst; // Division ID where nodes datatable will be appended - var groupNames = $.cookie('groups'); - if (groupNames) { - // Split group names into an array - var tmp = groupNames.split(','); + var nodeAttr = $('
                                '); + nodeFS + .append($('
                                ')); + nodeFS.append(nodeAttr); - // Create drop down for groups - var groupSelect = $(''); - groupSelect.append(''); - for ( var i in tmp) { - // Add group into drop down - var opt = $(''); - groupSelect.append(opt); - } - group.append(groupSelect); + // Create image fieldset + var imgFS = $('
                                '); + var imgLegend = $('Image'); + imgFS.append(imgLegend); - // Create node datatable - groupSelect.change(function() { - // Get group selected - var thisGroup = $(this).val(); - // If a valid group is selected - if (thisGroup) { - createNodesDatatable(thisGroup, dTableDivId); - } // End of if (thisGroup) - }); - } else { - // If no groups are cookied - var groupInput = $(''); - group.append(groupInput); - } - nodeAttr.append(group); + var imgAttr = $('
                                '); + imgFS + .append($('
                                ')); + imgFS.append(imgAttr); - // Create node input - var node = $('
                                '); - var nodeLabel = $(''); - var nodeDatatable = $('

                                Select a group to view its nodes

                                '); - node.append(nodeLabel); - node.append(nodeDatatable); - nodeAttr.append(node); + provExisting.append(nodeFS, imgFS); - // Create boot method drop down - var method = $('
                                '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - imgAttr.append(method); - - // Create operating system input - var os = $('
                                '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function() { - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - imgAttr.append(os); + // Create group input + var group = $('
                                '); + var groupLabel = $(''); + group.append(groupLabel); - // Create architecture input - var arch = $('
                                '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function() { - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - imgAttr.append(arch); + // Turn on auto complete for group + var dTableDivId = 'ipmiNodesDatatableDIV' + inst; // Division ID where + // nodes datatable will + // be appended + var groupNames = $.cookie('groups'); + if (groupNames) { + // Split group names into an array + var tmp = groupNames.split(','); - // Create profile input - var profile = $('
                                '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function() { - var tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - imgAttr.append(profile); + // Create drop down for groups + var groupSelect = $(''); + groupSelect.append(''); + for ( var i in tmp) { + // Add group into drop down + var opt = $(''); + groupSelect.append(opt); + } + group.append(groupSelect); - /** - * Provision existing - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); - var ready = true; - var errorMessage = ''; + // Create node datatable + groupSelect.change(function() { + // Get group selected + var thisGroup = $(this).val(); + // If a valid group is selected + if (thisGroup) { + createNodesDatatable(thisGroup, dTableDivId); + } // End of if (thisGroup) + }); + } else { + // If no groups are cookied + var groupInput = $(''); + group.append(groupInput); + } + nodeAttr.append(group); - // Get provision tab ID - var thisTabId = 'ipmiProvisionTab' + inst; - - // Get nodes that were checked - var dTableId = 'ipmiNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - if (!tgts) { - errorMessage += 'You need to select a node. '; - ready = false; - } - - // Check booth method - var boot = $('#' + thisTabId + ' select[name=bootMethod]'); - if (!boot.val()) { - errorMessage += 'You need to select a boot method. '; - boot.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - boot.css('border', 'solid #BDBDBD 1px'); - } - - // Check operating system image - var os = $('#' + thisTabId + ' input[name=os]'); - if (!os.val()) { - errorMessage += 'You need to select a operating system image. '; - os.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - os.css('border', 'solid #BDBDBD 1px'); - } - - // Check architecture - var arch = $('#' + thisTabId + ' input[name=arch]'); - if (!arch.val()) { - errorMessage += 'You need to select an architecture. '; - arch.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - arch.css('border', 'solid #BDBDBD 1px'); - } - - // Check profile - var profile = $('#' + thisTabId + ' input[name=profile]'); - if (!profile.val()) { - errorMessage += 'You need to select a profile. '; - profile.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - profile.css('border', 'solid #BDBDBD 1px'); - } - - // If all inputs are valid, ready to provision - if (ready) { - // Disable provision button - $(this).attr('disabled', 'true'); - - // Prepend status bar - var statBar = createStatusBar('ipmiProvisionStatBar' + inst); - statBar.append(createLoader('')); - statBar.prependTo($('#' + thisTabId)); + // Create node input + var node = $('
                                '); + var nodeLabel = $(''); + var nodeDatatable = $('

                                Select a group to view its nodes

                                '); + node.append(nodeLabel); + node.append(nodeDatatable); + nodeAttr.append(node); - // Disable all inputs - var inputs = $('#' + thisTabId + ' input'); - inputs.attr('disabled', 'disabled'); - - // Disable all selects - var selects = $('#' + thisTabId + ' select'); - selects.attr('disabled', 'disabled'); - - /** - * (1) Set operating system - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : tgts + ';noderes.netboot=xnba;nodetype.os=' + os.val() + ';nodetype.arch=' + arch.val() + ';nodetype.profile=' + profile.val() + ';nodetype.provmethod=' + boot.val(), - msg : 'cmd=nodeadd;out=' + inst - }, + // Create boot method drop down + var method = $('
                                '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + + ''); + method.append(methodLabel); + method.append(methodSelect); + imgAttr.append(method); - success : updateIpmiProvisionExistingStatus - }); - } else { - // Show warning message - var warn = createWarnBar(errorMessage); - warn.prependTo($(this).parent().parent()); - } - }); - provExisting.append(provisionBtn); + // Create operating system input + var os = $('
                                '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function() { + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source : tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + imgAttr.append(os); - return provExisting; + // Create architecture input + var arch = $('
                                '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function() { + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source : tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + imgAttr.append(arch); + + // Create profile input + var profile = $('
                                '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function() { + var tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source : tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + imgAttr.append(profile); + + /** + * Provision existing + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); + var ready = true; + var errorMessage = ''; + + // Get provision tab ID + var thisTabId = 'ipmiProvisionTab' + inst; + + // Get nodes that were checked + var dTableId = 'ipmiNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + if (!tgts) { + errorMessage += 'You need to select a node. '; + ready = false; + } + + // Check booth method + var boot = $('#' + thisTabId + ' select[name=bootMethod]'); + if (!boot.val()) { + errorMessage += 'You need to select a boot method. '; + boot.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + boot.css('border', 'solid #BDBDBD 1px'); + } + + // Check operating system image + var os = $('#' + thisTabId + ' input[name=os]'); + if (!os.val()) { + errorMessage += 'You need to select a operating system image. '; + os.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + os.css('border', 'solid #BDBDBD 1px'); + } + + // Check architecture + var arch = $('#' + thisTabId + ' input[name=arch]'); + if (!arch.val()) { + errorMessage += 'You need to select an architecture. '; + arch.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + arch.css('border', 'solid #BDBDBD 1px'); + } + + // Check profile + var profile = $('#' + thisTabId + ' input[name=profile]'); + if (!profile.val()) { + errorMessage += 'You need to select a profile. '; + profile.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + profile.css('border', 'solid #BDBDBD 1px'); + } + + // If all inputs are valid, ready to provision + if (ready) { + // Disable provision button + $(this).attr('disabled', 'true'); + + // Prepend status bar + var statBar = createStatusBar('ipmiProvisionStatBar' + inst); + statBar.append(createLoader('')); + statBar.prependTo($('#' + thisTabId)); + + // Disable all inputs + var inputs = $('#' + thisTabId + ' input'); + inputs.attr('disabled', 'disabled'); + + // Disable all selects + var selects = $('#' + thisTabId + ' select'); + selects.attr('disabled', 'disabled'); + + /** + * (1) Set operating system + */ + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : tgts + ';noderes.netboot=xnba;nodetype.os=' + + os.val() + ';nodetype.arch=' + arch.val() + + ';nodetype.profile=' + profile.val() + + ';nodetype.provmethod=' + boot.val(), + msg : 'cmd=nodeadd;out=' + inst + }, + + success : updateIpmiProvisionExistingStatus + }); + } else { + // Show warning message + var warn = createWarnBar(errorMessage); + warn.prependTo($(this).parent().parent()); + } + }); + provExisting.append(provisionBtn); + + return provExisting; } /** * Update the provision existing node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateIpmiProvisionExistingStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); - // Get command invoked - var cmd = args[0].replace('cmd=', ''); - // Get provision tab instance - var inst = args[1].replace('out=', ''); - - // Get provision tab and status bar ID - var statBarId = 'ipmiProvisionStatBar' + inst; - var tabId = 'ipmiProvisionTab' + inst; - - /** - * (2) Remote install - */ - if (cmd == 'nodeadd') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + // Get command invoked + var cmd = args[0].replace('cmd=', ''); + // Get provision tab instance + var inst = args[1].replace('out=', ''); - // Get parameters - var os = $('#' + tabId + ' input[name="os"]').val(); - var profile = $('#' + tabId + ' input[name="profile"]').val(); - var arch = $('#' + tabId + ' input[name="arch"]').val(); - - // Get nodes that were checked - var dTableId = 'ipmiNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - - // Begin installation - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'rinstall;' + os + ';' + profile + ';' + arch + ';' + tgts, - msg : 'cmd=rinstall;out=' + inst - }, + // Get provision tab and status bar ID + var statBarId = 'ipmiProvisionStatBar' + inst; + var tabId = 'ipmiProvisionTab' + inst; - success : updateIpmiProvisionExistingStatus - }); - } - - /** - * (3) Done - */ - else if (cmd == 'rinstall') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - $('#' + statBarId).find('img').remove(); - - // If installation was successful - if (prg.html().indexOf('Error') == -1) { - $('#' + statBarId).find('div').append('
                                It will take several minutes before the nodes are up and ready. Use nodestat to check the status of the install.
                                '); - } - } + /** + * (2) Remote install + */ + if (cmd == 'nodeadd') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Get parameters + var os = $('#' + tabId + ' input[name="os"]').val(); + var profile = $('#' + tabId + ' input[name="profile"]').val(); + var arch = $('#' + tabId + ' input[name="arch"]').val(); + + // Get nodes that were checked + var dTableId = 'ipmiNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + + // Begin installation + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'rinstall;' + os + ';' + profile + ';' + arch + ';' + + tgts, + msg : 'cmd=rinstall;out=' + inst + }, + + success : updateIpmiProvisionExistingStatus + }); + } + + /** + * (3) Done + */ + else if (cmd == 'rinstall') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + $('#' + statBarId).find('img').remove(); + + // If installation was successful + if (prg.html().indexOf('Error') == -1) { + $('#' + statBarId) + .find('div') + .append( + '
                                It will take several minutes before the nodes are up and ready. Use nodestat to check the status of the install.
                                '); + } + } } /** - * step 2: init the idataplex basic pattern - * - * @param - * - * @return + * Step 2: Init the iDataplex basic pattern */ -function idataplexInitBasic(){ +function idataplexInitBasic() { var tempip = ''; $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showString = '

                                ' + steps[currentStep] + '

                                '; + var showString = '

                                ' + + steps[currentStep] + '

                                '; showString += ''; - //nodes title + showString += ''; - //nodes name range - showString += ''; - //nodes start ip - if (getDiscoverEnv('idataplexnodeip')){ + showString += ''; + + if (getDiscoverEnv('idataplexnodeip')) { tempip = getDiscoverEnv('idataplexnodeip'); - } - else{ + } else { tempip = '172.30.20.1'; } - showString += ''; - //num-nodes-per-frame - showString += ''; - //bmc title + showString += ''; + + showString += ''; + showString += ''; - //bmc name range - showString += ''; - //bmc start ip - if (getDiscoverEnv('idataplexbmcip')){ + showString += ''; + + if (getDiscoverEnv('idataplexbmcip')) { tempip = getDiscoverEnv('idataplexbmcip'); - } - else{ + } else { tempip = '172.30.120.1'; } - showString += ''; - //switches title + showString += ''; + showString += ''; - //switches name range - showString += ''; - //switches start ip - if (getDiscoverEnv('idataplexswitchip')){ + showString += ''; + + if (getDiscoverEnv('idataplexswitchip')) { tempip = getDiscoverEnv('idataplexswitchip'); - } - else{ + } else { tempip = '172.30.10.1'; } - showString += ''; - //nodes per switch - showString += ''; + showString += ''; + + showString += ''; showString += '

                                Nodes:

                                Name Range:
                                Name Range:Start IP:
                                Nodes number
                                per Frame:
                                Start IP:
                                Nodes number
                                per Frame:

                                BMCs:

                                Name Range:
                                Name Range:Start IP:
                                Start IP:

                                Switches:

                                Name Range:
                                Name Range:Start IP:
                                Nodes number
                                per Switch:
                                Start IP:
                                Nodes number
                                per Switch:
                                '; - + $('#discoverContentDiv').append(showString); - + $('#discoverContentDiv [title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 1 + position : "center right", + offset : [ -2, 10 ], + effect : "fade", + opacity : 1 }); - + createDiscoverButtons(); } /** - * step 2: collect and check the basic pattern input on page. + * Step 2: Collect and check the basic pattern input * - * @param - * - * @return false: the input contains error, can not go to next step - * true : the input are correct, go to the next step + * @param operType Operating type + * @return True if the inputs are correct, false otherwise */ -function idataplexCheckBasic(operType){ +function idataplexCheckBasic(operType) { collectInputValue(); - //click back button, do not need check, only collect input value is ok. - if ('back' == operType){ + if ('back' == operType) { return true; } - + $('#patternDiv .ui-state-error').remove(); var errMessage = ''; var nodename = getDiscoverEnv('idataplexnodename'); @@ -743,65 +745,64 @@ function idataplexCheckBasic(operType){ var switchip = getDiscoverEnv('idataplexswitchip'); var nodesperswitch = getDiscoverEnv('idataplexperswitch'); var nodesperframe = getDiscoverEnv('idataplexperframe'); - - //all fields should input - if (!nodename){ + + if (!nodename) { errMessage += 'Input the Nodes name.
                                '; } - - if (!verifyIp(nodeip)){ + + if (!verifyIp(nodeip)) { errMessage += 'Input valid Nodes start ip.
                                '; } - - if (!bmcname){ + + if (!bmcname) { errMessage += 'Input the BMC name.
                                '; } - - if (!verifyIp(bmcip)){ + + if (!verifyIp(bmcip)) { errMessage += 'Input valid BMC start ip.
                                '; } - - if (!switchname){ + + if (!switchname) { errMessage += 'Input the switch name.
                                '; } - - if (!verifyIp(switchip)){ + + if (!verifyIp(switchip)) { errMessage += 'Input valid switch start ip.
                                '; } - - if (!nodesperswitch){ + + if (!nodesperswitch) { errMessage += 'Input the nodes number per switch.
                                '; } - - if (!nodesperframe){ + + if (!nodesperframe) { errMessage += 'Input the nodes number per frame.
                                '; } - - if ('' != errMessage){ + + if ('' != errMessage) { var warnBar = createWarnBar(errMessage); $('#patternDiv').prepend(warnBar); return false; } - - //check the relations among nodes, bmcs and switches + + // Check the relations among nodes, bmcs and switches var nodeNum = expandNR(nodename).length; var bmcNum = expandNR(bmcname).length; var switchNum = expandNR(switchname).length; var tempNumber = 0; - - //nodes number and bmc number - if (nodeNum != bmcNum){ + + // Node number and BMC number + if (nodeNum != bmcNum) { errMessage += 'The number of Node must equal the number of BMC.
                                '; } - - //nodes' number calculate by switches + + // Node number calculate by switches tempNumber += Number(nodesperswitch) * switchNum; - - if (tempNumber < nodeNum){ + + if (tempNumber < nodeNum) { errMessage += 'Input the node number per switch correctly.
                                '; } - - if ('' != errMessage){ + + if ('' != errMessage) { var warnBar = createWarnBar(errMessage); $('#patternDiv').prepend(warnBar); return false; @@ -811,121 +812,111 @@ function idataplexCheckBasic(operType){ } /** - * step 3: tell users to configure the switches. - * - * @param - * - * @return + * Step 3: Tell users to configure the switches */ -function idataplexInitSwitch(){ +function idataplexInitSwitch() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); var switchArray = expandNR(getDiscoverEnv('idataplexswitchname')); var switchIp = getDiscoverEnv('idataplexswitchip'); - var showString = '

                                ' + steps[currentStep] + '

                                '; - showString += '

                                You defined ' + switchArray.length +' switches in last step. Configure them manually please:
                                '; - showString += '

                                • 1. Start IP address: ' + switchIp + ', and the IPs must be continuous.
                                • '; + var showString = '

                                  ' + + steps[currentStep] + '

                                  '; + showString += '

                                  You defined ' + switchArray.length + + ' switches in last step. Configure them manually please:
                                  '; + showString += '

                                  • 1. Start IP address: ' + switchIp + + ', and the IPs must be continuous.
                                  • '; showString += '
                                  • 2. Enable the SNMP agent on switches.
                                  • '; showString += '
                                  • 3. If you want to use the SNMP V3, the user/password and AuthProto (default is \'md5\') should be set in the switches table.
                                  • '; showString += '
                                  • 4. Click the next button.
                                  • '; showString += '

                                    '; $('#discoverContentDiv').append(showString); - + createDiscoverButtons(); } /** - * step 4: init the interface and dhcp dynamic range for hardware discovery page. - * - * @param - * - * @return + * Step 4: Init the interface and DHCP dynamic range for hardware discovery page */ -function idataplexInitNetwork(){ +function idataplexInitNetwork() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); var startIp = '172.30.200.1'; var endIp = '172.30.255.254'; - var showDiv = $('

                                    ' + steps[currentStep] + '

                                    '); + var showDiv = $('

                                    ' + + steps[currentStep] + '

                                    '); var infoBar = createInfoBar('Make sure the discovery NIC\'s IP, start IP addresses and DHCP dynamic IP range are in the same subnet.'); showDiv.append(infoBar); - //init the ip range by input - if (getDiscoverEnv('idataplexIpStart')){ + + // Init the IP range by input + if (getDiscoverEnv('idataplexIpStart')) { startIp = getDiscoverEnv('idataplexIpStart'); } - - if (getDiscoverEnv('idataplexIpEnd')){ + + if (getDiscoverEnv('idataplexIpEnd')) { endIp = getDiscoverEnv('idataplexIpEnd'); } var showString = ''; - showString += ''; + showString += ''; showString += '
                                    DHCP Dynamic Range:-
                                    DHCP Dynamic Range:-
                                    '; showDiv.append(showString); - + $('#discoverContentDiv').append(showDiv); - + $('#discoverContentDiv [title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 1 + position : "center right", + offset : [ -2, 10 ], + effect : "fade", + opacity : 1 }); - + createDiscoverButtons(); } /** - * step 4: check the dynamic range for dhcp - * - * @param - * - * @return + * Step 4: Check the dynamic range for DHCP */ -function idataplexCheckNetwork(operType){ +function idataplexCheckNetwork(operType) { collectInputValue(); - //click back button, do not need check, only collect input value is ok. - if ('back' == operType){ + if ('back' == operType) { return true; } - + $('#networkDiv .ui-state-error').remove(); var startIp = getDiscoverEnv('idataplexIpStart'); var endIp = getDiscoverEnv('idataplexIpEnd'); var errMessage = ''; - if(!verifyIp(startIp)){ + if (!verifyIp(startIp)) { errMessage += 'Input the correct start IP address.
                                    '; } - - if(!verifyIp(endIp)){ + + if (!verifyIp(endIp)) { errMessage += 'Input the correct end IP address.
                                    '; } - - if ('' != errMessage){ + + if ('' != errMessage) { var warnBar = createWarnBar(errMessage); $('#networkDiv').prepend(warnBar); return false; } - - if (ip2Decimal(endIp) <= ip2Decimal(startIp)){ + + if (ip2Decimal(endIp) <= ip2Decimal(startIp)) { var warnBar = createWarnBar('the end IP must larger than start IP.
                                    '); $('#networkDiv').prepend(warnBar); return false; } - + return true; } /** - * step 5: configure service by xcat command and restart - * - * @param - * - * @return + * Step 5: Configure service by xCAT command and restart */ -function idataplexInitService(operType){ +function idataplexInitService(operType) { $('#discoverContentDiv').empty(); $('.tooltip').remove(); var showStr = '

                                    ' + steps[currentStep] + '

                                    '; @@ -939,61 +930,55 @@ function idataplexInitService(operType){ showStr += '
                                  '; showStr += '
                                  '; $('#discoverContentDiv').append(showStr); - - if ('back' == operType){ + + if ('back' == operType) { createDiscoverButtons(); return; } - + idataplexCreateSetupFile(); } /** - * step 5: create the stanza file for xcatsetup - * - * @param - * - * @return + * Step 5: Create the stanza file for xcatsetup */ -function idataplexCreateSetupFile(){ +function idataplexCreateSetupFile() { var fileContent = ''; - - //add the waiting loader on page + + // Add the waiting loader $('#fileLine').append(createLoader()); + + fileContent += "xcat-site:\n" + " domain = cluster.com\n" + + " cluster-type = idataplex\n"; + + fileContent += "xcat-service-lan:\n" + " dhcp-dynamic-range = " + + getDiscoverEnv('idataplexIpStart') + "-" + + getDiscoverEnv('idataplexIpEnd') + "\n"; - //site - fileContent += "xcat-site:\n" + - " domain = cluster.com\n" + - " cluster-type = idataplex\n"; - - //xcat-service-lan - fileContent += "xcat-service-lan:\n" + - " dhcp-dynamic-range = " + getDiscoverEnv('idataplexIpStart') + "-" + getDiscoverEnv('idataplexIpEnd') + "\n"; - //xcat-switch - fileContent += "xcat-switches:\n" + - " hostname-range = " + getDiscoverEnv('idataplexswitchname') + "\n" + - " starting-ip = " + getDiscoverEnv('idataplexswitchip') + "\n"; - - //xcat-node - fileContent += "xcat-nodes:\n" + - " hostname-range = " + getDiscoverEnv('idataplexnodename') + "\n" + - " starting-ip = " + getDiscoverEnv('idataplexnodeip') + "\n" + - " num-nodes-per-switch = " + getDiscoverEnv('idataplexperswitch') + "\n" + - " num-nodes-per-frame = " + getDiscoverEnv('idataplexperframe') + "\n"; - - //xcat-bmc - fileContent += "xcat-bmcs:\n" + - " hostname-range = " + getDiscoverEnv('idataplexbmcname') + "\n" + - " starting-ip = " + getDiscoverEnv('idataplexbmcip') + "\n"; - + fileContent += "xcat-switches:\n" + " hostname-range = " + + getDiscoverEnv('idataplexswitchname') + "\n" + " starting-ip = " + + getDiscoverEnv('idataplexswitchip') + "\n"; + + fileContent += "xcat-nodes:\n" + " hostname-range = " + + getDiscoverEnv('idataplexnodename') + "\n" + " starting-ip = " + + getDiscoverEnv('idataplexnodeip') + "\n" + + " num-nodes-per-switch = " + + getDiscoverEnv('idataplexperswitch') + "\n" + + " num-nodes-per-frame = " + getDiscoverEnv('idataplexperframe') + + "\n"; + + fileContent += "xcat-bmcs:\n" + " hostname-range = " + + getDiscoverEnv('idataplexbmcname') + "\n" + " starting-ip = " + + getDiscoverEnv('idataplexbmcip') + "\n"; + $.ajax({ url : 'lib/systemcmd.php', dataType : 'json', data : { cmd : 'echo -e "' + fileContent + '" > /tmp/webxcat.conf' }, - - success : function(data){ + + success : function(data) { $('#fileLine img').remove(); var tempSpan = $('#fileLine').find('span'); tempSpan.removeClass('ui-icon-wrench'); @@ -1004,13 +989,9 @@ function idataplexCreateSetupFile(){ } /** - * step 5: run xcatsetup to create the database for idataplex cluster - * - * @param - * - * @return + * Step 5: Run xcatsetup to create the database for iDataplex cluster */ -function idataplexSetup(){ +function idataplexSetup() { $('#setupLine').append(createLoader()); $.ajax({ url : 'lib/cmd.php', @@ -1021,8 +1002,8 @@ function idataplexSetup(){ args : '/tmp/webxcat.conf', msg : '' }, - - success : function(data){ + + success : function(data) { $('#setupLine img').remove(); var tempSpan = $('#setupLine').find('span'); tempSpan.removeClass('ui-icon-wrench'); @@ -1032,67 +1013,31 @@ function idataplexSetup(){ }); } /** - * step 5: run makehosts for idataplex - * - * @param - * - * @return + * Step 5: Run makehosts for iDataplex */ -function idataplexMakehosts(){ +function idataplexMakehosts() { createDiscoverButtons(); } + /** - * step 5: run makedns for idataplex - * - * @param - * - * @return + * Step 6: Tell users to power on all hardware for discovery */ -function idataplexMakedns(){ - -} -/** - * step 5: run make dhcp for idataplex - * - * @param - * - * @return - */ -function idataplexMakedhcp(){ - -} -/** - * step 5: run make conserver for idataplex - * - * @param - * - * @return - */ -function idataplexMakeconserver(){ - -} -/** - * step 6: tell users to power on all hardware for discovery - * - * @param - * - * @return - */ -function idataplexInitPowerOn(){ +function idataplexInitPowerOn() { $('#discoverContentDiv').empty(); $('.tooltip').remove(); - var showString = '

                                  ' + steps[currentStep] + '

                                  '; - showString += 'Walk over to each idataplex server and push the power button to power on.
                                  ' + - 'After about 5-10 minutes, nodes should be configured and ready for hardware management.
                                  '; + var showString = '

                                  ' + + steps[currentStep] + '

                                  '; + showString += 'Walk over to each idataplex server and push the power button to power on.
                                  ' + + 'After about 5-10 minutes, nodes should be configured and ready for hardware management.
                                  '; $('#discoverContentDiv').append(showString); - - //add the refresh button + + // Add the refresh button var refreshButton = createButton("Refresh"); $('#poweronDiv').append(refreshButton); - refreshButton.bind('click', function(){ + refreshButton.bind('click', function() { var tempObj = $('#poweronDiv div p'); tempObj.empty().append(createLoader()); - + $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -1102,18 +1047,18 @@ function idataplexInitPowerOn(){ args : 'stat', msg : '' }, - - success : function(data){ + + success : function(data) { var tempObj = $('#poweronDiv div p'); tempObj.empty(); - for(var i in data.rsp){ + for ( var i in data.rsp) { tempObj.append(data.rsp[i] + '
                                  '); } } }); }); - - //add the info area + + // Add the info area var infoBar = createInfoBar('Click the refresh button to check all nodes\' status.'); $('#poweronDiv').append(infoBar); createDiscoverButtons(); diff --git a/xCAT-UI/js/custom/kvm.js b/xCAT-UI/js/custom/kvm.js index 90c5d9318..5a16c13e4 100644 --- a/xCAT-UI/js/custom/kvm.js +++ b/xCAT-UI/js/custom/kvm.js @@ -2,494 +2,524 @@ * Execute when the DOM is fully loaded */ $(document).ready(function() { - // Load utility scripts (if any) + // Load utility scripts (if any) }); /** * Constructor - * - * @return Nothing */ var kvmPlugin = function() { }; +/** + * Configure self-service page + */ +kvmPlugin.prototype.loadConfigPage = function(tabId) { + var configAccordion = $('
                                  '); + + // Create accordion panel for user + var userSection = $('
                                  '); + var userLnk = $('

                                  Users

                                  ').click(function () { + // Do not load panel again if it is already loaded + if ($('#kvmConfigUser').find('.dataTables_wrapper').length) + return; + else + $('#kvmConfigUser').append(createLoader('')); + + // Get user data + loadUserPanel('kvmConfigUser'); + }); + + // Create accordion panel for profiles + var profileSection = $('
                                  '); + profileSection.append(createInfoBar('Create, edit, and delete virtual machine profiles used in the self-service portal')); + var profileLnk = $('

                                  Profiles

                                  ').click(function () { + + }); + + // Create accordion panel for groups + var groupsSection = $('
                                  '); + var groupsLnk = $('

                                  Groups

                                  ').click(function () { + + }); + + // Create accordion panel for nodes + var nodeSection = $('
                                  '); + nodeSection.append(createInfoBar('Modify node attributes')); + var nodeLnk = $('

                                  Nodes

                                  ').click(function () { + + }); + + configAccordion.append(userLnk, userSection, profileLnk, profileSection, groupsLnk, groupsSection, nodeLnk, nodeSection); + $('#' + tabId).append(configAccordion); + configAccordion.accordion(); + + userLnk.trigger('click'); +}; + /** * Clone node (service page) * - * @param node - * Node to clone - * @return Nothing + * @param node Node to clone */ kvmPlugin.prototype.serviceClone = function(node) { - + openDialog('info', 'Not yet supported'); }; /** * Load provision page (service page) * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ kvmPlugin.prototype.loadServiceProvisionPage = function(tabId) { - + $('#' + tabId).append(createInfoBar('Not yet supported')); }; /** * Show node inventory (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ kvmPlugin.prototype.loadServiceInventory = function(data) { - + }; /** * Load node inventory * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ kvmPlugin.prototype.loadInventory = function(data) { - var args = data.msg.split(','); - var tabId = args[0].replace('out=', ''); - var node = args[1].replace('node=', ''); - - // Get node inventory - var inv = data.rsp; + var args = data.msg.split(','); + var tabId = args[0].replace('out=', ''); + var node = args[1].replace('node=', ''); + + // Get node inventory + var inv = data.rsp; - // Remove loader - $('#' + tabId).find('img').remove(); + // Remove loader + $('#' + tabId).find('img').remove(); - // Create division to hold inventory - var invDiv = $('
                                  '); - - // Create a fieldset - var fieldSet = $('
                                  '); - var legend = $('Hardware'); - fieldSet.append(legend); - - var oList = $('
                                    '); - fieldSet.append(oList); - invDiv.append(fieldSet); + // Create division to hold inventory + var invDiv = $('
                                    '); + + // Create a fieldset + var fieldSet = $('
                                    '); + var legend = $('Hardware'); + fieldSet.append(legend); + + var oList = $('
                                      '); + fieldSet.append(oList); + invDiv.append(fieldSet); - // Loop through each line - var item; - for (var k = 0; k < inv.length; k++) { - // Remove node name - var attr = inv[k].replace(node + ': ', ''); - attr = jQuery.trim(attr); + // Loop through each line + var item; + for (var k = 0; k < inv.length; k++) { + // Remove node name + var attr = inv[k].replace(node + ': ', ''); + attr = jQuery.trim(attr); - // Append attribute to list - item = $('
                                    1. '); - item.append(attr); - oList.append(item); - } + // Append attribute to list + item = $('
                                    2. '); + item.append(attr); + oList.append(item); + } - // Append to inventory form - $('#' + tabId).append(invDiv); + // Append to inventory form + $('#' + tabId).append(invDiv); }; /** * Load clone page * - * @param node - * Source node to clone - * @return Nothing + * @param node Source node to clone */ kvmPlugin.prototype.loadClonePage = function(node) { - // Get nodes tab - var tab = getNodesTab(); - var newTabId = node + 'CloneTab'; + // Get nodes tab + var tab = getNodesTab(); + var newTabId = node + 'CloneTab'; - // If there is no existing clone tab - if (!$('#' + newTabId).length) { - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // If there is no existing clone tab + if (!$('#' + newTabId).length) { + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create clone form - var cloneForm = $('
                                      '); - cloneForm.append(infoBar); + // Create clone form + var cloneForm = $('
                                      '); + cloneForm.append(infoBar); - // Add clone tab - tab.add(newTabId, 'Clone', cloneForm, true); - } - - tab.select(newTabId); + // Add clone tab + tab.add(newTabId, 'Clone', cloneForm, true); + } + + tab.select(newTabId); }; /** * Load provision page * - * @param tabId - * The provision tab ID - * @return Nothing + * @param tabId The provision tab ID */ kvmPlugin.prototype.loadProvisionPage = function(tabId) { - // Get OS image names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS image names + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); + success : setOSImageCookies + }); - // Get groups - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'extnoderange', - tgt : '/.*', - args : 'subgroups', - msg : '' - }, + // Get groups + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'extnoderange', + tgt : '/.*', + args : 'subgroups', + msg : '' + }, - success : setGroupsCookies - }); + success : setGroupsCookies + }); - // Create provision form - var provForm = $('
                                      '); + // Create provision form + var provForm = $('
                                      '); - // Create info bar - var infoBar = createInfoBar('Provision an KVM virtual machine.'); - provForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Provision an KVM virtual machine.'); + provForm.append(infoBar); - // Append to provision tab - $('#' + tabId).append(provForm); - - // Create VM fieldset - var vmFS = $('
                                      '); - var vmLegend = $('Virtual Machine'); - vmFS.append(vmLegend); - - var vmAttr = $('
                                      '); - vmFS.append($('
                                      ')); - vmFS.append(vmAttr); - - // Create hardware fieldset - var hwFS = $('
                                      '); - var hwLegend = $('Hardware'); - hwFS.append(hwLegend); - - var hwAttr = $('
                                      '); - hwFS.append($('
                                      ')); - hwFS.append(hwAttr); - - // Create image fieldset - var imgFS = $('
                                      '); - var imgLegend = $('Image'); - imgFS.append(imgLegend); - - var imgAttr = $('
                                      '); - imgFS.append($('
                                      ')); - imgFS.append(imgAttr); - - provForm.append(vmFS, hwFS, imgFS); - - // Create hypervisor input - var host = $('
                                      '); - var hostLabel = $(''); - host.append(hostLabel); - var hostInput = $(''); - host.append(hostInput); - vmAttr.append(host); - - // Create group input - var group = $('
                                      '); - var groupLabel = $(''); - group.append(groupLabel); + // Append to provision tab + $('#' + tabId).append(provForm); + + // Create VM fieldset + var vmFS = $('
                                      '); + var vmLegend = $('Virtual Machine'); + vmFS.append(vmLegend); + + var vmAttr = $('
                                      '); + vmFS.append($('
                                      ')); + vmFS.append(vmAttr); + + // Create hardware fieldset + var hwFS = $('
                                      '); + var hwLegend = $('Hardware'); + hwFS.append(hwLegend); + + var hwAttr = $('
                                      '); + hwFS.append($('
                                      ')); + hwFS.append(hwAttr); + + // Create image fieldset + var imgFS = $('
                                      '); + var imgLegend = $('Image'); + imgFS.append(imgLegend); + + var imgAttr = $('
                                      '); + imgFS.append($('
                                      ')); + imgFS.append(imgAttr); + + provForm.append(vmFS, hwFS, imgFS); + + // Create hypervisor input + var host = $('
                                      '); + var hostLabel = $(''); + host.append(hostLabel); + var hostInput = $(''); + host.append(hostInput); + vmAttr.append(host); + + // Create group input + var group = $('
                                      '); + var groupLabel = $(''); + group.append(groupLabel); - // Turn on auto complete for group - var groupNames = $.cookie('groups'); - if (groupNames) { - // Split group names into an array - var tmp = groupNames.split(','); + // Turn on auto complete for group + var groupNames = $.cookie('groups'); + if (groupNames) { + // Split group names into an array + var tmp = groupNames.split(','); - // Create drop down for groups - var groupSelect = $(''); - groupSelect.append(''); - for ( var i in tmp) { - // Add group into drop down - var opt = $(''); - groupSelect.append(opt); - } - group.append(groupSelect); - } else { - // If no groups are cookied - var groupInput = $(''); - group.append(groupInput); - } - vmAttr.append(group); + // Create drop down for groups + var groupSelect = $(''); + groupSelect.append(''); + for ( var i in tmp) { + // Add group into drop down + var opt = $(''); + groupSelect.append(opt); + } + group.append(groupSelect); + } else { + // If no groups are cookied + var groupInput = $(''); + group.append(groupInput); + } + vmAttr.append(group); - // Create node input - var node = $('
                                      '); - var nodeLabel = $(''); - var nodeInput = $(''); - node.append(nodeLabel); - node.append(nodeInput); - vmAttr.append(node); + // Create node input + var node = $('
                                      '); + var nodeLabel = $(''); + var nodeInput = $(''); + node.append(nodeLabel); + node.append(nodeInput); + vmAttr.append(node); - // Create memory input - var memory = $('
                                      '); - var memoryLabel = $(''); - var memoryInput = $(''); - memory.append(memoryLabel); - memory.append(memoryInput); - hwAttr.append(memory); - - // Create processor dropdown - var cpu = $('
                                      '); - var cpuLabel = $(''); - var cpuSelect = $(''); - cpuSelect.append('' - + '' - + '' - + '' - + '' - + '' - + '' - + '' - ); - cpu.append(cpuLabel); - cpu.append(cpuSelect); - hwAttr.append(cpu); - - // Create NIC dropdown - var nic = $('
                                      '); - var nicLabel = $(''); - var nicInput = $(''); - nic.append(nicLabel); - nic.append(nicInput); - hwAttr.append(nic); - - // Create disk input - var disk = $('
                                      '); - var diskLabel = $(''); - var diskInput = $(''); - var diskSizeSelect = $(''); - diskSizeSelect.append('' + - '' - ); - disk.append(diskLabel, diskInput, diskSizeSelect); - hwAttr.append(disk); - - // Create disk storage input - var storage = $('
                                      '); - var storageLabel = $(''); - var storageInput = $(''); - storage.append(storageLabel); - storage.append(storageInput); - hwAttr.append(storage); - - // Create operating system input - var os = $('
                                      '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function() { - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - imgAttr.append(os); - - // Create architecture input - var arch = $('
                                      '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function() { - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - imgAttr.append(arch); - - // Create profile input - var profile = $('
                                      '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function() { - var tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - imgAttr.append(profile); - - // Create boot method dropdown - var method = $('
                                      '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - imgAttr.append(method); + // Create memory input + var memory = $('
                                      '); + var memoryLabel = $(''); + var memoryInput = $(''); + memory.append(memoryLabel); + memory.append(memoryInput); + hwAttr.append(memory); + + // Create processor dropdown + var cpu = $('
                                      '); + var cpuLabel = $(''); + var cpuSelect = $(''); + cpuSelect.append('' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + ); + cpu.append(cpuLabel); + cpu.append(cpuSelect); + hwAttr.append(cpu); + + // Create NIC dropdown + var nic = $('
                                      '); + var nicLabel = $(''); + var nicInput = $(''); + nic.append(nicLabel); + nic.append(nicInput); + hwAttr.append(nic); + + // Create disk input + var disk = $('
                                      '); + var diskLabel = $(''); + var diskInput = $(''); + var diskSizeSelect = $(''); + diskSizeSelect.append('' + + '' + ); + disk.append(diskLabel, diskInput, diskSizeSelect); + hwAttr.append(disk); + + // Create disk storage input + var storage = $('
                                      '); + var storageLabel = $(''); + var storageInput = $(''); + storage.append(storageLabel); + storage.append(storageInput); + hwAttr.append(storage); + + // Create operating system input + var os = $('
                                      '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function() { + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + imgAttr.append(os); + + // Create architecture input + var arch = $('
                                      '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function() { + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + imgAttr.append(arch); + + // Create profile input + var profile = $('
                                      '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function() { + var tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + imgAttr.append(profile); + + // Create boot method dropdown + var method = $('
                                      '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + + '' + ); + method.append(methodLabel); + method.append(methodSelect); + imgAttr.append(method); - /** - * Provision existing - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); - var ready = true; - - // Get tab ID - var tabId = $(this).parents('.ui-tabs-panel').attr('id'); - - // Check if fields are properly filled in - var inputs = $('#' + tabId + ' input:visible'); - for ( var i = 0; i < inputs.length; i++) { - if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'storage') { - inputs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - inputs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } - - var selects = $('#' + tabId + ' select:visible'); - for ( var i = 0; i < selects.length; i++) { - if (!selects.eq(i).val()) { - selects.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - selects.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } - - if (ready) { - var inst = tabId.replace('kvmProvisionTab', ''); - - // Prepend status bar - var statBar = createStatusBar('kvmProvisionStatBar' + inst); - statBar.append(createLoader('')); - statBar.prependTo($('#' + tabId)); - - var host = $('#' + tabId + ' input[name=host]').val(); - var group = $('#' + tabId + ' select[name=group]').val(); - var node = $('#' + tabId + ' input[name=node]').val(); - - var memory = $('#' + tabId + ' input[name=memory]').val(); - var cpu = $('#' + tabId + ' select[name=cpu]').val(); - var nic = $('#' + tabId + ' input[name=nic]').val(); - var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); - var storage = $('#' + tabId + ' input[name=storage]').val(); - - var os = $('#' + tabId + ' input[name=os]').val(); - var arch = $('#' + tabId + ' input[name=arch]').val(); - var profile = $('#' + tabId + ' input[name=profile]').val(); - var boot = $('#' + tabId + ' select[name=bootMethod]').val(); - - /** - * (1) Define node - */ - var args = '-t;node;-o;' + node + - ';vmhost=' + host + - ';groups=' + group + - ';vmmemory=' + memory + - ';vmcpus=' + cpu + - ';vmnics=' + nic + - ';vmstorage=' + storage + - ';os=' + os + - ';arch=' + arch + - ';profile=' + profile + - ';netboot=xnba' + - ';nodetype=osi' + - ';serialport=0' + - ';serialspeed=115200' + - ';mgt=kvm'; - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : args, - msg : 'cmd=chdef;out=' + inst - }, + /** + * Provision existing + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parents('.ui-tabs-panel').find('.ui-state-error').remove(); + var ready = true; + + // Get tab ID + var tabId = $(this).parents('.ui-tabs-panel').attr('id'); + + // Check if fields are properly filled in + var inputs = $('#' + tabId + ' input:visible'); + for ( var i = 0; i < inputs.length; i++) { + if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'storage') { + inputs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + inputs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } + + var selects = $('#' + tabId + ' select:visible'); + for ( var i = 0; i < selects.length; i++) { + if (!selects.eq(i).val()) { + selects.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + selects.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } + + if (ready) { + var inst = tabId.replace('kvmProvisionTab', ''); + + // Prepend status bar + var statBar = createStatusBar('kvmProvisionStatBar' + inst); + statBar.append(createLoader('')); + statBar.prependTo($('#' + tabId)); + + var host = $('#' + tabId + ' input[name=host]').val(); + var group = $('#' + tabId + ' select[name=group]').val(); + var node = $('#' + tabId + ' input[name=node]').val(); + + var memory = $('#' + tabId + ' input[name=memory]').val(); + var cpu = $('#' + tabId + ' select[name=cpu]').val(); + var nic = $('#' + tabId + ' input[name=nic]').val(); + var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); + var storage = $('#' + tabId + ' input[name=storage]').val(); + + var os = $('#' + tabId + ' input[name=os]').val(); + var arch = $('#' + tabId + ' input[name=arch]').val(); + var profile = $('#' + tabId + ' input[name=profile]').val(); + var boot = $('#' + tabId + ' select[name=bootMethod]').val(); + + /** + * (1) Define node + */ + var args = '-t;node;-o;' + node + + ';vmhost=' + host + + ';groups=' + group + + ';vmmemory=' + memory + + ';vmcpus=' + cpu + + ';vmnics=' + nic + + ';vmstorage=' + storage + + ';os=' + os + + ';arch=' + arch + + ';profile=' + profile + + ';netboot=xnba' + + ';nodetype=osi' + + ';serialport=0' + + ';serialspeed=115200' + + ';mgt=kvm'; + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : args, + msg : 'cmd=chdef;out=' + inst + }, - success : updateKVMProvisionStatus - }); - } else { - // Show warning message - var warn = createWarnBar('Please provide a value for each missing field.'); - warn.prependTo($(this).parent().parent()); - } - }); - provForm.append(provisionBtn); + success : updateKVMProvisionStatus + }); + } else { + // Show warning message + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this).parent().parent()); + } + }); + provForm.append(provisionBtn); }; /** * Load resources - * - * @return Nothing */ kvmPlugin.prototype.loadResources = function() { - // Get resource tab ID - var tabId = 'kvmResourceTab'; - // Remove loader - $('#' + tabId).find('img').remove(); - - // Create info bar - var infoBar = createInfoBar('Not yet supported'); + // Get resource tab ID + var tabId = 'kvmResourceTab'; + // Remove loader + $('#' + tabId).find('img').remove(); + + // Create info bar + var infoBar = createInfoBar('Not yet supported'); - // Create resource form - var resrcForm = $('
                                      '); - resrcForm.append(infoBar); - - $('#' + tabId).append(resrcForm); + // Create resource form + var resrcForm = $('
                                      '); + resrcForm.append(infoBar); + + $('#' + tabId).append(resrcForm); }; /** * Add node range */ kvmPlugin.prototype.addNode = function() { - var dialog = $('
                                      '); + var dialog = $('
                                      '); var info = createInfoBar('Add a KVM node'); dialog.append(info); // Create node inputs dialog.append($('
                                      ')); - dialog.append($('
                                      ')); - dialog.append($('
                                      ')); - dialog.append($('
                                      ')); + dialog.append($('
                                      ')); + dialog.append($('
                                      ')); + dialog.append($('
                                      ')); dialog.dialog({ - title: 'Add node', + title: 'Add node', modal: true, width: 400, close: function(){$(this).remove();}, @@ -504,7 +534,7 @@ kvmPlugin.prototype.addNode = function() { * Add iDataPlex node range */ function addKvmNode(){ - var attr, args; + var attr, args; var errorMessage = ''; // Remove existing warnings @@ -533,17 +563,17 @@ function addKvmNode(){ // Change dialog buttons $('#addKvm').dialog('option', 'buttons', { - 'Close':function(){ - $('#addKvm').dialog('close'); - } + 'Close':function(){ + $('#addKvm').dialog('close'); + } }); // Generate chdef arguments args = '-t;node;-o;' + $('#addKvm input[name="node"]').val() - + ';ip=' + $('#addKvm input[name="ip"]').val() - + ';groups=' + $('#addKvm input[name="groups"]').val() - + ';vmhost=' + $('#addKvm input[name="vmhost"]').val() - + ';mgt=kvm;netboot=xnba;nodetype=osi;profile=compute'; + + ';ip=' + $('#addKvm input[name="ip"]').val() + + ';groups=' + $('#addKvm input[name="groups"]').val() + + ';vmhost=' + $('#addKvm input[name="vmhost"]').val() + + ';mgt=kvm;netboot=xnba;nodetype=osi;profile=compute'; $.ajax({ url : 'lib/cmd.php', dataType : 'json', @@ -554,19 +584,19 @@ function addKvmNode(){ msg : '' }, success: function(data) { - // Update /etc/hosts - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : '' - } - }); - - // Remove loader + // Update /etc/hosts + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : '' + } + }); + + // Remove loader $('#addKvm img').remove(); // Get return message @@ -585,112 +615,110 @@ function addKvmNode(){ /** * Update the provision node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateKVMProvisionStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); - // Get command invoked - var cmd = args[0].replace('cmd=', ''); - // Get provision tab instance - var inst = args[1].replace('out=', ''); - - // Get provision tab and status bar ID - var statBarId = 'kvmProvisionStatBar' + inst; - var tabId = 'kvmProvisionTab' + inst; - - var node = $('#' + tabId + ' input[name=node]').val(); - - /** - * (2) Create virtual machine - */ - if (cmd == 'chdef') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + // Get command invoked + var cmd = args[0].replace('cmd=', ''); + // Get provision tab instance + var inst = args[1].replace('out=', ''); + + // Get provision tab and status bar ID + var statBarId = 'kvmProvisionStatBar' + inst; + var tabId = 'kvmProvisionTab' + inst; + + var node = $('#' + tabId + ' input[name=node]').val(); + + /** + * (2) Create virtual machine + */ + if (cmd == 'chdef') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // Get parameters - var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); - - // Begin installation - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'mkvm', - tgt : '', - args : node + ';-s;' + disk, - msg : 'cmd=mkvm;out=' + inst - }, + // Get parameters + var disk = $('#' + tabId + ' input[name=disk]').val() + $('#' + tabId + ' select[name=diskUnit]').val(); + + // Begin installation + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'mkvm', + tgt : '', + args : node + ';-s;' + disk, + msg : 'cmd=mkvm;out=' + inst + }, - success : updateKVMProvisionStatus - }); - } - - /** - * (3) Prepare node for boot - */ - if (cmd == 'mkvm') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // Get provision method - var boot = $('#' + tabId + ' select[name=bootMethod]').val(); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeset', - tgt : node, - args : boot, - msg : 'cmd=nodeset;out=' + inst - }, + success : updateKVMProvisionStatus + }); + } + + /** + * (3) Prepare node for boot + */ + if (cmd == 'mkvm') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Get provision method + var boot = $('#' + tabId + ' select[name=bootMethod]').val(); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeset', + tgt : node, + args : boot, + msg : 'cmd=nodeset;out=' + inst + }, - success : updateKVMProvisionStatus - }); - } - - /** - * (4) Power on node - */ - if (cmd == 'nodeset') { - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : node, - args : 'on', - msg : 'cmd=rpower;out=' + inst - }, + success : updateKVMProvisionStatus + }); + } + + /** + * (4) Power on node + */ + if (cmd == 'nodeset') { + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : node, + args : 'on', + msg : 'cmd=rpower;out=' + inst + }, - success : updateKVMProvisionStatus - }); - } - - /** - * (5) Done - */ - else if (cmd == 'rpower') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - $('#' + statBarId).find('img').remove(); - - // If installation was successful - if (prg.html().indexOf('Error') == -1) { - $('#' + statBarId).find('div').append('
                                      It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install.
                                      '); - } - } + success : updateKVMProvisionStatus + }); + } + + /** + * (5) Done + */ + else if (cmd == 'rpower') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + $('#' + statBarId).find('img').remove(); + + // If installation was successful + if (prg.html().indexOf('Error') == -1) { + $('#' + statBarId).find('div').append('
                                      It will take several minutes before the nodes are up and ready. Use rcons to monitor the status of the install.
                                      '); + } + } } \ No newline at end of file diff --git a/xCAT-UI/js/custom/zvm.js b/xCAT-UI/js/custom/zvm.js index 814461ee9..ec48ef6f4 100644 --- a/xCAT-UI/js/custom/zvm.js +++ b/xCAT-UI/js/custom/zvm.js @@ -2,1760 +2,1803 @@ * Execute when the DOM is fully loaded */ $(document).ready(function() { - // Load utility scripts - includeJs("js/custom/zvmUtils.js"); + // Load utility scripts + includeJs("js/custom/zvmUtils.js"); }); /** * Constructor - * - * @return Nothing */ var zvmPlugin = function() { - + +}; + +/** + * Configure self-service configure page + */ +zvmPlugin.prototype.loadConfigPage = function(tabId) { + var configAccordion = $('
                                      '); + + // Create accordion panel for user + var userSection = $('
                                      '); + var userLnk = $('

                                      Users

                                      ').click(function () { + // Do not load panel again if it is already loaded + if ($('#zvmConfigUser').find('.dataTables_wrapper').length) + return; + else + $('#zvmConfigUser').append(createLoader('')); + + loadUserPanel('zvmConfigUser'); + }); + + // Create accordion panel for profiles + var profileSection = $('
                                      '); + var profileLnk = $('

                                      Profiles

                                      ').click(function () { + // Do not load panel again if it is already loaded + if ($('#zvmConfigProfile').find('.dataTables_wrapper').length) + return; + else + $('#zvmConfigProfile').append(createLoader('')); + + queryProfiles('zvmConfigProfile'); + }); + + // Create accordion panel for images + var imgSection = $('
                                      '); + var imgLnk = $('

                                      Images

                                      ').click(function () { + // Do not load panel again if it is already loaded + if ($('#zvmConfigImages').find('.dataTables_wrapper').length) + return; + else + $('#zvmConfigImages').append(createLoader('')); + + queryImages('zvmConfigImages'); + }); + + // Create accordion panel for groups + var groupsSection = $('
                                      '); + var groupsLnk = $('

                                      Groups

                                      ').click(function () { + // Do not load panel again if it is already loaded + if ($('#zvmConfigGroups').find('.dataTables_wrapper').length) + return; + else + $('#zvmConfigGroups').append(createLoader('')); + + queryGroups('zvmConfigGroups'); + }); + + configAccordion.append(userLnk, userSection, profileLnk, profileSection, imgLnk, imgSection, groupsLnk, groupsSection); + $('#' + tabId).append(configAccordion); + configAccordion.accordion(); + + userLnk.trigger('click'); }; /** * Clone node (service page) * - * @param node - * Node to clone - * @return Nothing + * @param node Node to clone */ -zvmPlugin.prototype.serviceClone = function(node) { - var owner = $.cookie('xcat_username'); - var group = getUserNodeAttr(node, 'groups'); - - // Submit request to clone VM - // webportal clonezlinux [src node] [group] [owner] - var iframe = createIFrame('lib/srv_cmd.php?cmd=webportal&tgt=&args=clonezlinux;' + node + ';' + group + ';' + owner + '&msg=&opts=flush'); - iframe.prependTo($('#manageTab')); +zvmPlugin.prototype.serviceClone = function(node) { + var owner = $.cookie('xcat_username'); + var group = getUserNodeAttr(node, 'groups'); + + // Submit request to clone VM + // webportal clonezlinux [src node] [group] [owner] + var iframe = createIFrame('lib/srv_cmd.php?cmd=webportal&tgt=&args=clonezlinux;' + node + ';' + group + ';' + owner + '&msg=&opts=flush'); + iframe.prependTo($('#manageTab')); }; /** * Load provision page (service page) * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ zvmPlugin.prototype.loadServiceProvisionPage = function(tabId) { - // Create provision form - var provForm = $('
                                      '); + // Create provision form + var provForm = $('
                                      '); - // Create info bar - var infoBar = createInfoBar('Provision a Linux virtual machine on System z by selecting the appropriate choices below. Once you are ready, click on Provision to provision the virtual machine.'); - provForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Provision a Linux virtual machine on System z by selecting the appropriate choices below. Once you are ready, click on Provision to provision the virtual machine.'); + provForm.append(infoBar); - // Append to provision tab - $('#' + tabId).append(provForm); - - // Create provision table - var provTable = $(''); - var provBody = $(''); - var provFooter = $(''); - provTable.append(provHeader, provBody, provFooter); - provForm.append(provTable); - - provHeader.children('th').css({ - 'font': 'bold 12px verdana, arial, helvetica, sans-serif' - }); - - // Create row to contain selections - var provRow = $(''); - provBody.append(provRow); - // Create columns for zVM, group, and image - var zvmCol = $(''); - provRow.append(zvmCol); - var groupCol = $(''); - provRow.append(groupCol); - var imageCol = $(''); - provRow.append(imageCol); - - provRow.children('td').css({ - 'min-width': '250px' - }); - - /** - * Provision VM - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().find('.ui-state-error').remove(); - - var hcp = $('#select-table tbody tr:eq(0) td:eq(0) input[name="hcp"]:checked').val(); - var group = $('#select-table tbody tr:eq(0) td:eq(1) input[name="group"]:checked').val(); - var img = $('#select-table tbody tr:eq(0) td:eq(2) input[name="image"]:checked').val(); - var owner = $.cookie('xcat_username'); - - if(!hcp || !group || !img) { - // Show warning message - var warn = createWarnBar('You need to select an option for each column'); - warn.prependTo($(this).parent()); - } else { - // Begin by creating VM - createzVM(tabId, group, hcp, img, owner); - } - }); - provForm.append(provisionBtn); - - // Load zVMs, groups, and images into their respective columns - loadSrvGroups(groupCol); - loadOSImages(imageCol); - - // Get zVM host names - if (!$.cookie('srv_zvm')){ - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webportal', - tgt : '', - args : 'lszvm', - msg : '' - }, + // Append to provision tab + $('#' + tabId).append(provForm); + + // Create provision table + var provTable = $('
                                      zVM Group Image
                                      '); + var provBody = $(''); + var provFooter = $(''); + provTable.append(provHeader, provBody, provFooter); + provForm.append(provTable); + + provHeader.children('th').css({ + 'font': 'bold 12px verdana, arial, helvetica, sans-serif' + }); + + // Create row to contain selections + var provRow = $(''); + provBody.append(provRow); + // Create columns for zVM, group, and image + var zvmCol = $(''); + provRow.append(zvmCol); + var groupCol = $(''); + provRow.append(groupCol); + var imageCol = $(''); + provRow.append(imageCol); + + provRow.children('td').css({ + 'min-width': '250px' + }); + + /** + * Provision VM + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().find('.ui-state-error').remove(); + + var hcp = $('#select-table tbody tr:eq(0) td:eq(0) input[name="hcp"]:checked').val(); + var group = $('#select-table tbody tr:eq(0) td:eq(1) input[name="group"]:checked').val(); + var img = $('#select-table tbody tr:eq(0) td:eq(2) input[name="image"]:checked').val(); + var owner = $.cookie('xcat_username'); + + if(!hcp || !group || !img) { + // Show warning message + var warn = createWarnBar('You need to select an option for each column'); + warn.prependTo($(this).parent()); + } else { + // Begin by creating VM + createzVM(tabId, group, hcp, img, owner); + } + }); + provForm.append(provisionBtn); + + // Load zVMs, groups, and images into their respective columns + loadSrvGroups(groupCol); + loadOSImages(imageCol); + + // Get zVM host names + if (!$.cookie('srv_zvm')){ + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webportal', + tgt : '', + args : 'lszvm', + msg : '' + }, - success : function(data) { - setzVMCookies(data); - loadzVMs(zvmCol); - } - }); - } else { - loadzVMs(zvmCol); - } + success : function(data) { + setzVMCookies(data); + loadzVMs(zvmCol); + } + }); + } else { + loadzVMs(zvmCol); + } }; /** * Show node inventory (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ zvmPlugin.prototype.loadServiceInventory = function(data) { - var args = data.msg.split(','); + var args = data.msg.split(','); - // Get tab ID - var tabId = args[0].replace('out=', ''); - // Get node - var node = args[1].replace('node=', ''); - // Get node inventory - var inv = data.rsp[0].split(node + ':'); + // Get tab ID + var tabId = args[0].replace('out=', ''); + // Get node + var node = args[1].replace('node=', ''); + // Get node inventory + var inv = data.rsp[0].split(node + ':'); - // Remove loader - $('#' + tabId).find('img').remove(); + // Remove loader + $('#' + tabId).find('img').remove(); - // Create array of property keys - var keys = new Array('userId', 'host', 'os', 'arch', 'hcp', 'priv', 'memory', 'proc', 'disk', 'nic'); + // Create array of property keys + var keys = new Array('userId', 'host', 'os', 'arch', 'hcp', 'priv', 'memory', 'proc', 'disk', 'nic'); - // Create hash table for property names - var attrNames = new Object(); - attrNames['userId'] = 'z/VM UserID:'; - attrNames['host'] = 'z/VM Host:'; - attrNames['os'] = 'Operating System:'; - attrNames['arch'] = 'Architecture:'; - attrNames['hcp'] = 'HCP:'; - attrNames['priv'] = 'Privileges:'; - attrNames['memory'] = 'Total Memory:'; - attrNames['proc'] = 'Processors:'; - attrNames['disk'] = 'Disks:'; - attrNames['nic'] = 'NICs:'; + // Create hash table for property names + var attrNames = new Object(); + attrNames['userId'] = 'z/VM UserID:'; + attrNames['host'] = 'z/VM Host:'; + attrNames['os'] = 'Operating System:'; + attrNames['arch'] = 'Architecture:'; + attrNames['hcp'] = 'HCP:'; + attrNames['priv'] = 'Privileges:'; + attrNames['memory'] = 'Total Memory:'; + attrNames['proc'] = 'Processors:'; + attrNames['disk'] = 'Disks:'; + attrNames['nic'] = 'NICs:'; - // Create hash table for node attributes - var attrs = getAttrs(keys, attrNames, inv); + // Create hash table for node attributes + var attrs = getAttrs(keys, attrNames, inv); - // Create division to hold inventory - var invDivId = node + 'Inventory'; - var invDiv = $('
                                      '); - - var infoBar = createInfoBar('Below is the inventory for the virtual machine you selected.'); - invDiv.append(infoBar); - - /** - * General info section - */ - var fieldSet = $('
                                      '); - var legend = $('General'); - fieldSet.append(legend); - var oList = $('
                                        '); - var item, label, args; - - // Loop through each property - for ( var k = 0; k < 5; k++) { - // Create a list item for each property - item = $('
                                      1. '); - - // Create a label - Property name - label = $(''); - item.append(label); - - for ( var l = 0; l < attrs[keys[k]].length; l++) { - // Create a input - Property value(s) - // Handle each property uniquely - item.append(attrs[keys[k]][l]); - } - - oList.append(item); - } - // Append to inventory form - fieldSet.append(oList); - invDiv.append(fieldSet); - - /** - * Monitoring section - */ - fieldSet = $('
                                        '); - legend = $('Monitoring [Refresh]'); - fieldSet.append(legend); - getMonitorMetrics(node); - - // Refresh monitoring charts on-click - legend.find('a').click(function() { - getMonitorMetrics(node); - }); - - // Append to inventory form - invDiv.append(fieldSet); - - /** - * Hardware info section - */ - var hwList, hwItem; - fieldSet = $('
                                        '); - legend = $('Hardware'); - fieldSet.append(legend); - oList = $('
                                          '); - - // Loop through each property - var label; - for (k = 5; k < keys.length; k++) { - // Create a list item - item = $('
                                        1. '); - - // Create a list to hold the property value(s) - hwList = $('
                                            '); - hwItem = $('
                                          • '); - - /** - * Privilege section - */ - if (keys[k] == 'priv') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Loop through each line - for (l = 0; l < attrs[keys[k]].length; l++) { - // Create a new list item for each line - hwItem = $('
                                          • '); - - // Determine privilege - args = attrs[keys[k]][l].split(' '); - if (args[0] == 'Directory:') { - label = $(''); - hwItem.append(label); - hwItem.append(args[1]); - } else if (args[0] == 'Currently:') { - label = $(''); - hwItem.append(label); - hwItem.append(args[1]); - } - - hwList.append(hwItem); - } - - item.append(hwList); - } - - /** - * Memory section - */ - else if (keys[k] == 'memory') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Loop through each value line - for (l = 0; l < attrs[keys[k]].length; l++) { - // Create a new list item for each line - hwItem = $('
                                          • '); - hwItem.append(attrs[keys[k]][l]); - hwList.append(hwItem); - } - - item.append(hwList); - } - - /** - * Processor section - */ - else if (keys[k] == 'proc') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Create a table to hold processor data - var procTable = $('
                                            zVM Group Image
                                            '); - var procBody = $(''); - - // Table columns - Type, Address, ID, Base, Dedicated, and Affinity - var procTabRow = $(' Type Address ID Base Dedicated Affinity '); - procTable.append(procTabRow); - var procType, procAddr, procId, procAff; - - // Loop through each processor - var n, temp; - for (l = 0; l < attrs[keys[k]].length; l++) { - if (attrs[keys[k]][l]) { - args = attrs[keys[k]][l].split(' '); - - // Get processor type, address, ID, and affinity - n = 3; - temp = args[args.length - n]; - while (!jQuery.trim(temp)) { - n = n + 1; - temp = args[args.length - n]; - } - procType = $('' + temp + ''); - procAddr = $('' + args[1] + ''); - procId = $('' + args[5] + ''); - procAff = $('' + args[args.length - 1] + ''); + // Create division to hold inventory + var invDivId = node + 'Inventory'; + var invDiv = $('
                                            '); - // Base processor - if (args[6] == '(BASE)') { - baseProc = $('' + true + ''); - } else { - baseProc = $('' + false + ''); - } + var infoBar = createInfoBar('Below is the inventory for the virtual machine you selected.'); + invDiv.append(infoBar); + + /** + * General info section + */ + var fieldSet = $('
                                            '); + var legend = $('General'); + fieldSet.append(legend); + var oList = $('
                                              '); + var item, label, args; + + // Loop through each property + for ( var k = 0; k < 5; k++) { + // Create a list item for each property + item = $('
                                            1. '); + + // Create a label - Property name + label = $(''); + item.append(label); + + for ( var l = 0; l < attrs[keys[k]].length; l++) { + // Create a input - Property value(s) + // Handle each property uniquely + item.append(attrs[keys[k]][l]); + } + + oList.append(item); + } + // Append to inventory form + fieldSet.append(oList); + invDiv.append(fieldSet); - // Dedicated processor - if (args[args.length - 3] == 'DEDICATED') { - dedicatedProc = $('' + true + ''); - } else { - dedicatedProc = $('' + false + ''); - } + /** + * Monitoring section + */ + fieldSet = $('
                                              '); + legend = $('Monitoring [Refresh]'); + fieldSet.append(legend); + getMonitorMetrics(node); - // Create a new row for each processor - procTabRow = $(''); - procTabRow.append(procType); - procTabRow.append(procAddr); - procTabRow.append(procId); - procTabRow.append(baseProc); - procTabRow.append(dedicatedProc); - procTabRow.append(procAff); - procBody.append(procTabRow); - } - } - - procTable.append(procBody); - item.append(procTable); - } - - /** - * Disk section - */ - else if (keys[k] == 'disk') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Create a table to hold disk (DASD) data - var dasdTable = $('
                                              '); - var dasdBody = $(''); - - // Table columns - Virtual Device, Type, VolID, Type of Access, and Size - var dasdTabRow = $(' Virtual Device # Type VolID Type of Access Size '); - dasdTable.append(dasdTabRow); - var dasdVDev, dasdType, dasdVolId, dasdAccess, dasdSize; - - // Loop through each DASD - for (l = 0; l < attrs[keys[k]].length; l++) { - if (attrs[keys[k]][l]) { - args = attrs[keys[k]][l].split(' '); - - // Get DASD virtual device, type, volume ID, access, and size - dasdVDev = $('' + args[1] + ''); - dasdType = $('' + args[2] + ''); - dasdVolId = $('' + args[3] + ''); - dasdAccess = $('' + args[4] + ''); - dasdSize = $('' + args[args.length - 9] + ' ' + args[args.length - 8] + ''); + // Refresh monitoring charts on-click + legend.find('a').click(function() { + getMonitorMetrics(node); + }); - // Create a new row for each DASD - dasdTabRow = $(''); - dasdTabRow.append(dasdVDev); - dasdTabRow.append(dasdType); - dasdTabRow.append(dasdVolId); - dasdTabRow.append(dasdAccess); - dasdTabRow.append(dasdSize); - dasdBody.append(dasdTabRow); - } - } + // Append to inventory form + invDiv.append(fieldSet); - dasdTable.append(dasdBody); - item.append(dasdTable); - } + /** + * Hardware info section + */ + var hwList, hwItem; + fieldSet = $('
                                              '); + legend = $('Hardware'); + fieldSet.append(legend); + oList = $('
                                                '); - /** - * NIC section - */ - else if (keys[k] == 'nic') { - // Create a label - Property name - label = $(''); - item.append(label); + // Loop through each property + var label; + for (k = 5; k < keys.length; k++) { + // Create a list item + item = $('
                                              1. '); - // Create a table to hold NIC data - var nicTable = $('
                                                '); - var nicBody = $(''); + // Create a list to hold the property value(s) + hwList = $('
                                                  '); + hwItem = $('
                                                • '); - // Table columns - Virtual device, Adapter Type, Port Name, # of Devices, MAC Address, and LAN Name - var nicTabRow = $('Virtual Device # Adapter Type Port Name # of Devices LAN Name'); - nicTable.append(nicTabRow); - var nicVDev, nicType, nicPortName, nicNumOfDevs, nicLanName; + /** + * Privilege section + */ + if (keys[k] == 'priv') { + // Create a label - Property name + label = $(''); + item.append(label); - // Loop through each NIC (Data contained in 2 lines) - for (l = 0; l < attrs[keys[k]].length; l = l + 2) { - if (attrs[keys[k]][l]) { - args = attrs[keys[k]][l].split(' '); + // Loop through each line + for (l = 0; l < attrs[keys[k]].length; l++) { + // Create a new list item for each line + hwItem = $('
                                                • '); + + // Determine privilege + args = attrs[keys[k]][l].split(' '); + if (args[0] == 'Directory:') { + label = $(''); + hwItem.append(label); + hwItem.append(args[1]); + } else if (args[0] == 'Currently:') { + label = $(''); + hwItem.append(label); + hwItem.append(args[1]); + } + + hwList.append(hwItem); + } + + item.append(hwList); + } + + /** + * Memory section + */ + else if (keys[k] == 'memory') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Loop through each value line + for (l = 0; l < attrs[keys[k]].length; l++) { + // Create a new list item for each line + hwItem = $('
                                                • '); + hwItem.append(attrs[keys[k]][l]); + hwList.append(hwItem); + } + + item.append(hwList); + } + + /** + * Processor section + */ + else if (keys[k] == 'proc') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Create a table to hold processor data + var procTable = $('
                                                  '); + var procBody = $(''); + + // Table columns - Type, Address, ID, Base, Dedicated, and Affinity + var procTabRow = $(' Type Address ID Base Dedicated Affinity '); + procTable.append(procTabRow); + var procType, procAddr, procId, procAff; + + // Loop through each processor + var n, temp; + for (l = 0; l < attrs[keys[k]].length; l++) { + if (attrs[keys[k]][l]) { + args = attrs[keys[k]][l].split(' '); + + // Get processor type, address, ID, and affinity + n = 3; + temp = args[args.length - n]; + while (!jQuery.trim(temp)) { + n = n + 1; + temp = args[args.length - n]; + } + procType = $('' + temp + ''); + procAddr = $('' + args[1] + ''); + procId = $('' + args[5] + ''); + procAff = $('' + args[args.length - 1] + ''); - // Get NIC virtual device, type, port name, and number of devices - nicVDev = $('' + args[1] + ''); - nicType = $('' + args[3] + ''); - nicPortName = $('' + args[10] + ''); - nicNumOfDevs = $('' + args[args.length - 1] + ''); + // Base processor + if (args[6] == '(BASE)') { + baseProc = $('' + true + ''); + } else { + baseProc = $('' + false + ''); + } - args = attrs[keys[k]][l + 1].split(' '); - nicLanName = $('' + args[args.length - 2] + ' ' + args[args.length - 1] + ''); + // Dedicated processor + if (args[args.length - 3] == 'DEDICATED') { + dedicatedProc = $('' + true + ''); + } else { + dedicatedProc = $('' + false + ''); + } - // Create a new row for each DASD - nicTabRow = $(''); - nicTabRow.append(nicVDev); - nicTabRow.append(nicType); - nicTabRow.append(nicPortName); - nicTabRow.append(nicNumOfDevs); - nicTabRow.append(nicLanName); + // Create a new row for each processor + procTabRow = $(''); + procTabRow.append(procType); + procTabRow.append(procAddr); + procTabRow.append(procId); + procTabRow.append(baseProc); + procTabRow.append(dedicatedProc); + procTabRow.append(procAff); + procBody.append(procTabRow); + } + } + + procTable.append(procBody); + item.append(procTable); + } + + /** + * Disk section + */ + else if (keys[k] == 'disk') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Create a table to hold disk (DASD) data + var dasdTable = $('
                                                  '); + var dasdBody = $(''); + + // Table columns - Virtual Device, Type, VolID, Type of Access, and Size + var dasdTabRow = $(' Virtual Device # Type VolID Type of Access Size '); + dasdTable.append(dasdTabRow); + var dasdVDev, dasdType, dasdVolId, dasdAccess, dasdSize; + + // Loop through each DASD + for (l = 0; l < attrs[keys[k]].length; l++) { + if (attrs[keys[k]][l]) { + args = attrs[keys[k]][l].split(' '); + + // Get DASD virtual device, type, volume ID, access, and size + dasdVDev = $('' + args[1] + ''); + dasdType = $('' + args[2] + ''); + dasdVolId = $('' + args[3] + ''); + dasdAccess = $('' + args[4] + ''); + dasdSize = $('' + args[args.length - 9] + ' ' + args[args.length - 8] + ''); - nicBody.append(nicTabRow); - } - } + // Create a new row for each DASD + dasdTabRow = $(''); + dasdTabRow.append(dasdVDev); + dasdTabRow.append(dasdType); + dasdTabRow.append(dasdVolId); + dasdTabRow.append(dasdAccess); + dasdTabRow.append(dasdSize); + dasdBody.append(dasdTabRow); + } + } - nicTable.append(nicBody); - item.append(nicTable); - } + dasdTable.append(dasdBody); + item.append(dasdTable); + } - oList.append(item); - } + /** + * NIC section + */ + else if (keys[k] == 'nic') { + // Create a label - Property name + label = $(''); + item.append(label); - // Append inventory to division - fieldSet.append(oList); - invDiv.append(fieldSet); - invDiv.find('th').css({ - 'padding': '5px 10px', - 'font-weight': 'bold' - }); + // Create a table to hold NIC data + var nicTable = $('
                                                  '); + var nicBody = $(''); - // Append to tab - $('#' + tabId).append(invDiv); + // Table columns - Virtual device, Adapter Type, Port Name, # of Devices, MAC Address, and LAN Name + var nicTabRow = $('Virtual Device # Adapter Type Port Name # of Devices LAN Name'); + nicTable.append(nicTabRow); + var nicVDev, nicType, nicPortName, nicNumOfDevs, nicLanName; + + // Loop through each NIC (Data contained in 2 lines) + for (l = 0; l < attrs[keys[k]].length; l = l + 2) { + if (attrs[keys[k]][l]) { + args = attrs[keys[k]][l].split(' '); + + // Get NIC virtual device, type, port name, and number of devices + nicVDev = $('' + args[1] + ''); + nicType = $('' + args[3] + ''); + nicPortName = $('' + args[10] + ''); + nicNumOfDevs = $('' + args[args.length - 1] + ''); + + args = attrs[keys[k]][l + 1].split(' '); + nicLanName = $('' + args[args.length - 2] + ' ' + args[args.length - 1] + ''); + + // Create a new row for each DASD + nicTabRow = $(''); + nicTabRow.append(nicVDev); + nicTabRow.append(nicType); + nicTabRow.append(nicPortName); + nicTabRow.append(nicNumOfDevs); + nicTabRow.append(nicLanName); + + nicBody.append(nicTabRow); + } + } + + nicTable.append(nicBody); + item.append(nicTable); + } + + oList.append(item); + } + + // Append inventory to division + fieldSet.append(oList); + invDiv.append(fieldSet); + invDiv.find('th').css({ + 'padding': '5px 10px', + 'font-weight': 'bold' + }); + + // Append to tab + $('#' + tabId).append(invDiv); }; /** * Load clone page * - * @param node - * Source node to clone - * @return Nothing + * @param node Source node to clone */ zvmPlugin.prototype.loadClonePage = function(node) { - // Get nodes tab - var tab = getNodesTab(); - var newTabId = node + 'CloneTab'; + // Get nodes tab + var tab = getNodesTab(); + var newTabId = node + 'CloneTab'; - // If there is no existing clone tab - if (!$('#' + newTabId).length) { - // Get table headers - var tableId = $('#' + node).parents('table').attr('id'); - var headers = $('#' + tableId).parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); - var cols = new Array(); - for ( var i = 0; i < headers.length; i++) { - var col = headers.eq(i).text(); - cols.push(col); - } + // If there is no existing clone tab + if (!$('#' + newTabId).length) { + // Get table headers + var tableId = $('#' + node).parents('table').attr('id'); + var headers = $('#' + tableId).parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); + var cols = new Array(); + for ( var i = 0; i < headers.length; i++) { + var col = headers.eq(i).text(); + cols.push(col); + } - // Get hardware control point column - var hcpCol = $.inArray('hcp', cols); + // Get hardware control point column + var hcpCol = $.inArray('hcp', cols); - // Get hardware control point - var nodeRow = $('#' + node).parent().parent(); - var datatable = $('#' + getNodesTableId()).dataTable(); - var rowPos = datatable.fnGetPosition(nodeRow.get(0)); - var aData = datatable.fnGetData(rowPos); - var hcp = aData[hcpCol]; + // Get hardware control point + var nodeRow = $('#' + node).parent().parent(); + var datatable = $('#' + getNodesTableId()).dataTable(); + var rowPos = datatable.fnGetPosition(nodeRow.get(0)); + var aData = datatable.fnGetData(rowPos); + var hcp = aData[hcpCol]; - // Create status bar and hide it - var statBarId = node + 'CloneStatusBar'; - var statBar = createStatusBar(statBarId).hide(); + // Create status bar and hide it + var statBarId = node + 'CloneStatusBar'; + var statBar = createStatusBar(statBarId).hide(); - // Create info bar - var infoBar = createInfoBar('Clone a zVM node.'); + // Create info bar + var infoBar = createInfoBar('Clone a zVM node.'); - // Create clone form - var cloneForm = $('
                                                  '); - cloneForm.append(statBar); - cloneForm.append(infoBar); - - // Create VM fieldset - var vmFS = $('
                                                  '); - var vmLegend = $('Virtual Machine'); - vmFS.append(vmLegend); - cloneForm.append(vmFS); - - var vmAttr = $('
                                                  '); - vmFS.append($('
                                                  ')); - vmFS.append(vmAttr); - - // Create hardware fieldset - var hwFS = $('
                                                  '); - var hwLegend = $('Hardware'); - hwFS.append(hwLegend); - cloneForm.append(hwFS); - - var hwAttr = $('
                                                  '); - hwFS.append($('
                                                  ')); - hwFS.append(hwAttr); - - vmAttr.append('
                                                  '); - vmAttr.append('
                                                  '); - vmAttr.append('
                                                  '); - vmAttr.append('
                                                  '); + // Create clone form + var cloneForm = $('
                                                  '); + cloneForm.append(statBar); + cloneForm.append(infoBar); + + // Create VM fieldset + var vmFS = $('
                                                  '); + var vmLegend = $('Virtual Machine'); + vmFS.append(vmLegend); + cloneForm.append(vmFS); + + var vmAttr = $('
                                                  '); + vmFS.append($('
                                                  ')); + vmFS.append(vmAttr); + + // Create hardware fieldset + var hwFS = $('
                                                  '); + var hwLegend = $('Hardware'); + hwFS.append(hwLegend); + cloneForm.append(hwFS); + + var hwAttr = $('
                                                  '); + hwFS.append($('
                                                  ')); + hwFS.append(hwAttr); + + vmAttr.append('
                                                  '); + vmAttr.append('
                                                  '); + vmAttr.append('
                                                  '); + vmAttr.append('
                                                  '); - // Create group input - var group = $('
                                                  '); - var groupLabel = $(''); - var groupInput = $(''); - groupInput.one('focus', function(){ - var groupNames = $.cookie('groups'); - if (groupNames) { - // Turn on auto complete - $(this).autocomplete({ - source: groupNames.split(',') - }); - } - }); - group.append(groupLabel); - group.append(groupInput); - vmAttr.append(group); - - // Create an advanced link to set IP address and hostname - var advancedLnk = $(''); - vmAttr.append(advancedLnk); - var advanced = $('
                                                  ').hide(); - vmAttr.append(advanced); - - var ip = $('
                                                  '); - advanced.append(ip); - var hostname = $('
                                                  '); - advanced.append(hostname); - - // Show IP address and hostname inputs on-click - advancedLnk.click(function() { - advanced.toggle(); - }); + // Create group input + var group = $('
                                                  '); + var groupLabel = $(''); + var groupInput = $(''); + groupInput.one('focus', function(){ + var groupNames = $.cookie('groups'); + if (groupNames) { + // Turn on auto complete + $(this).autocomplete({ + source: groupNames.split(',') + }); + } + }); + group.append(groupLabel); + group.append(groupInput); + vmAttr.append(group); + + // Create an advanced link to set IP address and hostname + var advancedLnk = $(''); + vmAttr.append(advancedLnk); + var advanced = $('
                                                  ').hide(); + vmAttr.append(advanced); + + var ip = $('
                                                  '); + advanced.append(ip); + var hostname = $('
                                                  '); + advanced.append(hostname); + + // Show IP address and hostname inputs on-click + advancedLnk.click(function() { + advanced.toggle(); + }); - // Get list of disk pools - var temp = hcp.split('.'); - var diskPools = $.cookie(temp[0] + 'diskpools'); + // Get list of disk pools + var temp = hcp.split('.'); + var diskPools = $.cookie(temp[0] + 'diskpools'); - // Create disk pool input - var poolDiv = $('
                                                  '); - var poolLabel = $(''); - var poolInput = $('').autocomplete({ - source: diskPools.split(',') - }); - poolDiv.append(poolLabel); - poolDiv.append(poolInput); - hwAttr.append(poolDiv); + // Create disk pool input + var poolDiv = $('
                                                  '); + var poolLabel = $(''); + var poolInput = $('').autocomplete({ + source: diskPools.split(',') + }); + poolDiv.append(poolLabel); + poolDiv.append(poolInput); + hwAttr.append(poolDiv); - hwAttr.append('
                                                  '); + hwAttr.append('
                                                  '); - // Generate tooltips - cloneForm.find('div input[title]').tooltip({ - position : "center right", - offset : [ -2, 10 ], - effect : "fade", - opacity : 0.7, - predelay: 800, - events : { - def : "mouseover,mouseout", - input : "mouseover,mouseout", - widget : "focus mouseover,blur mouseout", - tooltip : "mouseover,mouseout" - } - }); - - /** - * Clone node - */ - var cloneBtn = createButton('Clone'); - cloneBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - var ready = true; - var errMsg = ''; + // Generate tooltips + cloneForm.find('div input[title]').tooltip({ + position : "center right", + offset : [ -2, 10 ], + effect : "fade", + opacity : 0.7, + predelay: 800, + events : { + def : "mouseover,mouseout", + input : "mouseover,mouseout", + widget : "focus mouseover,blur mouseout", + tooltip : "mouseover,mouseout" + } + }); + + /** + * Clone node + */ + var cloneBtn = createButton('Clone'); + cloneBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + var ready = true; + var errMsg = ''; - // Check node name, userId, hardware control point, group, and password - var inputs = $('#' + newTabId + ' input'); - for ( var i = 0; i < inputs.length; i++) { - if (!inputs.eq(i).val() - && inputs.eq(i).attr('name') != 'diskPw' - && inputs.eq(i).attr('name') != 'diskPool') { - inputs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - inputs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } + // Check node name, userId, hardware control point, group, and password + var inputs = $('#' + newTabId + ' input'); + for ( var i = 0; i < inputs.length; i++) { + if (!inputs.eq(i).val() + && inputs.eq(i).attr('name') != 'diskPw' + && inputs.eq(i).attr('name') != 'diskPool') { + inputs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + inputs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } - // Write error message - if (!ready) { - errMsg = errMsg + 'Please provide a value for each missing field.
                                                  '; - } + // Write error message + if (!ready) { + errMsg = errMsg + 'Please provide a value for each missing field.
                                                  '; + } - // Get target node - var nodeRange = $('#' + newTabId + ' input[name=tgtNode]').val(); - // Get target user ID - var userIdRange = $('#' + newTabId + ' input[name=tgtUserId]').val(); - // Get IP address range - var ipRange = $('#' + newTabId + ' input[name=ip]').val(); - // Get hostname range - var hostnameRange = $('#' + newTabId + ' input[name=hostname]').val(); + // Get target node + var nodeRange = $('#' + newTabId + ' input[name=tgtNode]').val(); + // Get target user ID + var userIdRange = $('#' + newTabId + ' input[name=tgtUserId]').val(); + // Get IP address range + var ipRange = $('#' + newTabId + ' input[name=ip]').val(); + // Get hostname range + var hostnameRange = $('#' + newTabId + ' input[name=hostname]').val(); - // Check node range and user ID range - if (nodeRange.indexOf('-') > -1 || userIdRange.indexOf('-') > -1 || ipRange.indexOf('-') > -1 || hostnameRange.indexOf('-') > -1) { - if (nodeRange.indexOf('-') < 0 || userIdRange.indexOf('-') < 0) { - errMsg = errMsg + 'A user ID range and node range needs to be given.
                                                  '; - ready = false; - } else { - var tmp = nodeRange.split('-'); + // Check node range and user ID range + if (nodeRange.indexOf('-') > -1 || userIdRange.indexOf('-') > -1 || ipRange.indexOf('-') > -1 || hostnameRange.indexOf('-') > -1) { + if (nodeRange.indexOf('-') < 0 || userIdRange.indexOf('-') < 0) { + errMsg = errMsg + 'A user ID range and node range needs to be given.
                                                  '; + ready = false; + } else { + var tmp = nodeRange.split('-'); - // Get node base name - var nodeBase = tmp[0].match(/[a-zA-Z]+/); - // Get starting index - var nodeStart = parseInt(tmp[0].match(/\d+/)); - // Get ending index - var nodeEnd = parseInt(tmp[1].match(/\d+/)); + // Get node base name + var nodeBase = tmp[0].match(/[a-zA-Z]+/); + // Get starting index + var nodeStart = parseInt(tmp[0].match(/\d+/)); + // Get ending index + var nodeEnd = parseInt(tmp[1].match(/\d+/)); - tmp = userIdRange.split('-'); + tmp = userIdRange.split('-'); - // Get user ID base name - var userIdBase = tmp[0].match(/[a-zA-Z]+/); - // Get starting index - var userIdStart = parseInt(tmp[0].match(/\d+/)); - // Get ending index - var userIdEnd = parseInt(tmp[1].match(/\d+/)); - - var ipStart = "", ipEnd = ""; - if (ipRange) { - tmp = ipRange.split('-'); - - // Get starting IP address - ipStart = tmp[0].substring(tmp[0].lastIndexOf(".") + 1); - // Get ending IP address - ipEnd = tmp[1].substring(tmp[1].lastIndexOf(".") + 1); - } - - var hostnameStart = "", hostnameEnd = ""; - if (hostnameRange) { - tmp = hostnameRange.split('-'); - - // Get starting hostname - hostnameStart = parseInt(tmp[0].substring(0, tmp[0].indexOf(".")).match(/\d+/)); - // Get ending hostname - hostnameEnd = parseInt(tmp[1].substring(0, tmp[1].indexOf(".")).match(/\d+/)); - } - - // If starting and ending index do not match - if (!(nodeStart == userIdStart) || !(nodeEnd == userIdEnd)) { - // Not ready to provision - errMsg = errMsg + 'The node range and user ID range does not match.
                                                  '; - ready = false; - } - - // If an IP address range is given and the starting and ending index do not match - if (ipRange && !(nodeStart == ipStart) || !(nodeEnd == ipEnd)) { - errMsg = errMsg + 'The node range and IP address range does not match. '; - ready = false; - } - - // If a hostname range is given and the starting and ending index do not match - if (hostnameRange && !(nodeStart == hostnameStart) || !(nodeEnd == hostnameEnd)) { - errMsg = errMsg + 'The node range and hostname range does not match. '; - ready = false; - } - } - } + // Get user ID base name + var userIdBase = tmp[0].match(/[a-zA-Z]+/); + // Get starting index + var userIdStart = parseInt(tmp[0].match(/\d+/)); + // Get ending index + var userIdEnd = parseInt(tmp[1].match(/\d+/)); + + var ipStart = "", ipEnd = ""; + if (ipRange) { + tmp = ipRange.split('-'); + + // Get starting IP address + ipStart = tmp[0].substring(tmp[0].lastIndexOf(".") + 1); + // Get ending IP address + ipEnd = tmp[1].substring(tmp[1].lastIndexOf(".") + 1); + } + + var hostnameStart = "", hostnameEnd = ""; + if (hostnameRange) { + tmp = hostnameRange.split('-'); + + // Get starting hostname + hostnameStart = parseInt(tmp[0].substring(0, tmp[0].indexOf(".")).match(/\d+/)); + // Get ending hostname + hostnameEnd = parseInt(tmp[1].substring(0, tmp[1].indexOf(".")).match(/\d+/)); + } + + // If starting and ending index do not match + if (!(nodeStart == userIdStart) || !(nodeEnd == userIdEnd)) { + // Not ready to provision + errMsg = errMsg + 'The node range and user ID range does not match.
                                                  '; + ready = false; + } + + // If an IP address range is given and the starting and ending index do not match + if (ipRange && !(nodeStart == ipStart) || !(nodeEnd == ipEnd)) { + errMsg = errMsg + 'The node range and IP address range does not match. '; + ready = false; + } + + // If a hostname range is given and the starting and ending index do not match + if (hostnameRange && !(nodeStart == hostnameStart) || !(nodeEnd == hostnameEnd)) { + errMsg = errMsg + 'The node range and hostname range does not match. '; + ready = false; + } + } + } - // Get source node, hardware control point, group, disk pool, and disk password - var srcNode = $('#' + newTabId + ' input[name=srcNode]').val(); - var hcp = $('#' + newTabId + ' input[name=newHcp]').val(); - var group = $('#' + newTabId + ' input[name=newGroup]').val(); - var diskPool = $('#' + newTabId + ' input[name=diskPool]').val(); - var diskPw = $('#' + newTabId + ' input[name=diskPw]').val(); + // Get source node, hardware control point, group, disk pool, and disk password + var srcNode = $('#' + newTabId + ' input[name=srcNode]').val(); + var hcp = $('#' + newTabId + ' input[name=newHcp]').val(); + var group = $('#' + newTabId + ' input[name=newGroup]').val(); + var diskPool = $('#' + newTabId + ' input[name=diskPool]').val(); + var diskPw = $('#' + newTabId + ' input[name=diskPw]').val(); - // If a value is given for every input - if (ready) { - // Disable all inputs - var inputs = $('#' + newTabId + ' input'); - inputs.attr('disabled', 'disabled'); - - // If a node range is given - if (nodeRange.indexOf('-') > -1) { - var tmp = nodeRange.split('-'); + // If a value is given for every input + if (ready) { + // Disable all inputs + var inputs = $('#' + newTabId + ' input'); + inputs.attr('disabled', 'disabled'); + + // If a node range is given + if (nodeRange.indexOf('-') > -1) { + var tmp = nodeRange.split('-'); - // Get node base name - var nodeBase = tmp[0].match(/[a-zA-Z]+/); - // Get starting index - var nodeStart = parseInt(tmp[0].match(/\d+/)); - // Get ending index - var nodeEnd = parseInt(tmp[1].match(/\d+/)); + // Get node base name + var nodeBase = tmp[0].match(/[a-zA-Z]+/); + // Get starting index + var nodeStart = parseInt(tmp[0].match(/\d+/)); + // Get ending index + var nodeEnd = parseInt(tmp[1].match(/\d+/)); - tmp = userIdRange.split('-'); + tmp = userIdRange.split('-'); - // Get user ID base name - var userIdBase = tmp[0].match(/[a-zA-Z]+/); - - var ipBase = ""; - if (ipRange) { - tmp = ipRange.split('-'); - - // Get network base - ipBase = tmp[0].substring(0, tmp[0].lastIndexOf(".") + 1); - } - - var domain = ""; - if (hostnameRange) { - tmp = hostnameRange.split('-'); - - // Get domain name - domain = tmp[0].substring(tmp[0].indexOf(".")); - } - - // Loop through each node in the node range - for ( var i = nodeStart; i <= nodeEnd; i++) { - var node = nodeBase + i.toString(); - var userId = userIdBase + i.toString(); - var inst = i + '/' + nodeEnd; - - var args = node - + ';zvm.hcp=' + hcp - + ';zvm.userid=' + userId - + ';nodehm.mgt=zvm' - + ';groups=' + group; - - if (ipRange) { - var ip = ipBase + i.toString(); - args += ';hosts.ip=' + ip; - } - - if (hostnameRange) { - var hostname = node + domain; - args += ';hosts.hostnames=' + hostname; - } - - /** - * (1) Define node - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : args, - msg : 'cmd=nodeadd;inst=' + inst - + ';out=' + statBarId - + ';node=' + node - }, + // Get user ID base name + var userIdBase = tmp[0].match(/[a-zA-Z]+/); + + var ipBase = ""; + if (ipRange) { + tmp = ipRange.split('-'); + + // Get network base + ipBase = tmp[0].substring(0, tmp[0].lastIndexOf(".") + 1); + } + + var domain = ""; + if (hostnameRange) { + tmp = hostnameRange.split('-'); + + // Get domain name + domain = tmp[0].substring(tmp[0].indexOf(".")); + } + + // Loop through each node in the node range + for ( var i = nodeStart; i <= nodeEnd; i++) { + var node = nodeBase + i.toString(); + var userId = userIdBase + i.toString(); + var inst = i + '/' + nodeEnd; + + var args = node + + ';zvm.hcp=' + hcp + + ';zvm.userid=' + userId + + ';nodehm.mgt=zvm' + + ';groups=' + group; + + if (ipRange) { + var ip = ipBase + i.toString(); + args += ';hosts.ip=' + ip; + } + + if (hostnameRange) { + var hostname = node + domain; + args += ';hosts.hostnames=' + hostname; + } + + /** + * (1) Define node + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : args, + msg : 'cmd=nodeadd;inst=' + inst + + ';out=' + statBarId + + ';node=' + node + }, - success : updateZCloneStatus - }); - } - } else { - var args = nodeRange - + ';zvm.hcp=' + hcp - + ';zvm.userid=' + userIdRange - + ';nodehm.mgt=zvm' - + ';groups=' + group; - - if (ipRange) - args += ';hosts.ip=' + ipRange; - - if (hostnameRange) - args += ';hosts.hostnames=' + hostnameRange; - - /** - * (1) Define node - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : args, - msg : 'cmd=nodeadd;inst=1/1;out=' + statBarId - + ';node=' + nodeRange - }, + success : updateZCloneStatus + }); + } + } else { + var args = nodeRange + + ';zvm.hcp=' + hcp + + ';zvm.userid=' + userIdRange + + ';nodehm.mgt=zvm' + + ';groups=' + group; + + if (ipRange) + args += ';hosts.ip=' + ipRange; + + if (hostnameRange) + args += ';hosts.hostnames=' + hostnameRange; + + /** + * (1) Define node + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : args, + msg : 'cmd=nodeadd;inst=1/1;out=' + statBarId + + ';node=' + nodeRange + }, - success : updateZCloneStatus - }); - } + success : updateZCloneStatus + }); + } - // Create loader - $('#' + statBarId).find('div').append(createLoader()); - $('#' + statBarId).show(); + // Create loader + $('#' + statBarId).find('div').append(createLoader()); + $('#' + statBarId).show(); - // Disable clone button - $(this).attr('disabled', 'true'); - } else { - // Show warning message - var warn = createWarnBar(errMsg); - warn.prependTo($(this).parent().parent()); - } - }); - cloneForm.append(cloneBtn); + // Disable clone button + $(this).attr('disabled', 'true'); + } else { + // Show warning message + var warn = createWarnBar(errMsg); + warn.prependTo($(this).parent().parent()); + } + }); + cloneForm.append(cloneBtn); - // Add clone tab - tab.add(newTabId, 'Clone', cloneForm, true); - } + // Add clone tab + tab.add(newTabId, 'Clone', cloneForm, true); + } - tab.select(newTabId); + tab.select(newTabId); }; /** * Load node inventory * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ zvmPlugin.prototype.loadInventory = function(data) { - var args = data.msg.split(','); + var args = data.msg.split(','); - // Get tab ID - var tabId = args[0].replace('out=', ''); - // Get node - var node = args[1].replace('node=', ''); - // Get node inventory - var inv = data.rsp[0].split(node + ':'); + // Get tab ID + var tabId = args[0].replace('out=', ''); + // Get node + var node = args[1].replace('node=', ''); + // Get node inventory + var inv = data.rsp[0].split(node + ':'); - // Remove loader - $('#' + tabId).find('img').remove(); + // Remove loader + $('#' + tabId).find('img').remove(); - // Create status bar - var statBarId = node + 'StatusBar'; - var statBar = createStatusBar(statBarId); + // Create status bar + var statBarId = node + 'StatusBar'; + var statBar = createStatusBar(statBarId); - // Add loader to status bar and hide it - var loader = createLoader(node + 'StatusBarLoader').hide(); - statBar.find('div').append(loader); - statBar.hide(); + // Add loader to status bar and hide it + var loader = createLoader(node + 'StatusBarLoader').hide(); + statBar.find('div').append(loader); + statBar.hide(); - // Create array of property keys - var keys = new Array('userId', 'host', 'os', 'arch', 'hcp', 'priv', 'memory', 'proc', 'disk', 'nic'); + // Create array of property keys + var keys = new Array('userId', 'host', 'os', 'arch', 'hcp', 'priv', 'memory', 'proc', 'disk', 'nic'); - // Create hash table for property names - var attrNames = new Object(); - attrNames['userId'] = 'z/VM UserID:'; - attrNames['host'] = 'z/VM Host:'; - attrNames['os'] = 'Operating System:'; - attrNames['arch'] = 'Architecture:'; - attrNames['hcp'] = 'HCP:'; - attrNames['priv'] = 'Privileges:'; - attrNames['memory'] = 'Total Memory:'; - attrNames['proc'] = 'Processors:'; - attrNames['disk'] = 'Disks:'; - attrNames['nic'] = 'NICs:'; + // Create hash table for property names + var attrNames = new Object(); + attrNames['userId'] = 'z/VM UserID:'; + attrNames['host'] = 'z/VM Host:'; + attrNames['os'] = 'Operating System:'; + attrNames['arch'] = 'Architecture:'; + attrNames['hcp'] = 'HCP:'; + attrNames['priv'] = 'Privileges:'; + attrNames['memory'] = 'Total Memory:'; + attrNames['proc'] = 'Processors:'; + attrNames['disk'] = 'Disks:'; + attrNames['nic'] = 'NICs:'; - // Create hash table for node attributes - var attrs = getAttrs(keys, attrNames, inv); - - // Create division to hold user entry - var ueDivId = node + 'UserEntry'; - var ueDiv = $('
                                                  '); - - // Create division to hold inventory - var invDivId = node + 'Inventory'; - var invDiv = $('
                                                  '); - - /** - * Show user entry - */ - var toggleLinkId = node + 'ToggleLink'; - var toggleLink = $('Show directory entry'); - toggleLink.one('click', function(event) { - // Toggle inventory division - $('#' + invDivId).toggle(); - - // Create loader - var loader = createLoader(node + 'TabLoader'); - loader = $('
                                                  ').append(loader); - ueDiv.append(loader); - - // Get user entry - var msg = 'out=' + ueDivId + ';node=' + node; - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : node, - args : '', - msg : msg - }, - - success : loadUserEntry - }); - - // Change text - $(this).text('Show inventory'); - - // Disable toggle link - $(this).unbind(event); - }); - - // Align toggle link to the right - var toggleLnkDiv = $('
                                                  ').css( { - 'text-align' : 'right' - }); - toggleLnkDiv.append(toggleLink); - - /** - * General info section - */ - var fieldSet = $('
                                                  '); - var legend = $('General'); - fieldSet.append(legend); - var oList = $('
                                                    '); - var item, label, args; - - // Loop through each property - for ( var k = 0; k < 5; k++) { - // Create a list item for each property - item = $('
                                                  1. '); - - // Create a label - Property name - label = $(''); - item.append(label); - - for ( var l = 0; l < attrs[keys[k]].length; l++) { - // Create a input - Property value(s) - // Handle each property uniquely - item.append(attrs[keys[k]][l]); - } - - oList.append(item); - } - // Append to inventory form - fieldSet.append(oList); - invDiv.append(fieldSet); - - /** - * Hardware info section - */ - var hwList, hwItem; - fieldSet = $('
                                                    '); - legend = $('Hardware'); - fieldSet.append(legend); - oList = $('
                                                      '); - - // Loop through each property - var label; - for (k = 5; k < keys.length; k++) { - // Create a list item - item = $('
                                                    1. '); - - // Create a list to hold the property value(s) - hwList = $('
                                                        '); - hwItem = $('
                                                      • '); - - /** - * Privilege section - */ - if (keys[k] == 'priv') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Loop through each line - for (l = 0; l < attrs[keys[k]].length; l++) { - // Create a new list item for each line - hwItem = $('
                                                      • '); - - // Determine privilege - args = attrs[keys[k]][l].split(' '); - if (args[0] == 'Directory:') { - label = $(''); - hwItem.append(label); - hwItem.append(args[1]); - } else if (args[0] == 'Currently:') { - label = $(''); - hwItem.append(label); - hwItem.append(args[1]); - } - - hwList.append(hwItem); - } - - item.append(hwList); - } - - /** - * Memory section - */ - else if (keys[k] == 'memory') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Loop through each value line - for (l = 0; l < attrs[keys[k]].length; l++) { - // Create a new list item for each line - hwItem = $('
                                                      • '); - hwItem.append(attrs[keys[k]][l]); - hwList.append(hwItem); - } - - item.append(hwList); - } - - /** - * Processor section - */ - else if (keys[k] == 'proc') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Create a table to hold processor data - var procTable = $('
                                                        '); - var procBody = $(''); - var procFooter = $(''); - - // Table columns - Type, Address, ID, Base, Dedicated, and Affinity - var procTabRow = $(' Type Address ID Base Dedicated Affinity '); - procTable.append(procTabRow); - var procId, procAff; - - /** - * Remove processor - */ - var contextMenu = [{ - 'Remove' : function(menuItem, menu) { - var addr = $(this).text(); - - // Open dialog to confirm - var confirmDialog = $('

                                                        Are you sure you want to remove this processor?

                                                        '); - confirmDialog.dialog({ - modal: true, - width: 300, - buttons: { - "Ok": function(){ - removeProcessor(node, addr); - $(this).dialog("close"); - }, - "Cancel": function() { - $(this).dialog("close"); - } - } - }); - } - }]; - - // Loop through each processor - var n, temp; - var procType, procAddr, procLink; - for (l = 0; l < attrs[keys[k]].length; l++) { - if (attrs[keys[k]][l]) { - args = attrs[keys[k]][l].split(' '); - - // Get processor type, address, ID, and affinity - n = 3; - temp = args[args.length - n]; - while (!jQuery.trim(temp)) { - n = n + 1; - temp = args[args.length - n]; - } - procType = $('' + temp + ''); - procAddr = $(''); - procLink = $('' + args[1] + ''); - - // Append context menu to link - procLink.contextMenu(contextMenu, { - theme : 'vista' - }); - - procAddr.append(procLink); - procId = $('' + args[5] + ''); - procAff = $('' + args[args.length - 1] + ''); + // Create hash table for node attributes + var attrs = getAttrs(keys, attrNames, inv); - // Base processor - if (args[6] == '(BASE)') { - baseProc = $('' + true + ''); - } else { - baseProc = $('' + false + ''); - } + // Create division to hold user entry + var ueDivId = node + 'UserEntry'; + var ueDiv = $('
                                                        '); + + // Create division to hold inventory + var invDivId = node + 'Inventory'; + var invDiv = $('
                                                        '); + + /** + * Show user entry + */ + var toggleLinkId = node + 'ToggleLink'; + var toggleLink = $('Show directory entry'); + toggleLink.one('click', function(event) { + // Toggle inventory division + $('#' + invDivId).toggle(); + + // Create loader + var loader = createLoader(node + 'TabLoader'); + loader = $('
                                                        ').append(loader); + ueDiv.append(loader); + + // Get user entry + var msg = 'out=' + ueDivId + ';node=' + node; + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : node, + args : '', + msg : msg + }, + + success : loadUserEntry + }); + + // Change text + $(this).text('Show inventory'); + + // Disable toggle link + $(this).unbind(event); + }); + + // Align toggle link to the right + var toggleLnkDiv = $('
                                                        ').css( { + 'text-align' : 'right' + }); + toggleLnkDiv.append(toggleLink); + + /** + * General info section + */ + var fieldSet = $('
                                                        '); + var legend = $('General'); + fieldSet.append(legend); + var oList = $('
                                                          '); + var item, label, args; + + // Loop through each property + for ( var k = 0; k < 5; k++) { + // Create a list item for each property + item = $('
                                                        1. '); + + // Create a label - Property name + label = $(''); + item.append(label); + + for ( var l = 0; l < attrs[keys[k]].length; l++) { + // Create a input - Property value(s) + // Handle each property uniquely + item.append(attrs[keys[k]][l]); + } + + oList.append(item); + } + // Append to inventory form + fieldSet.append(oList); + invDiv.append(fieldSet); + + /** + * Hardware info section + */ + var hwList, hwItem; + fieldSet = $('
                                                          '); + legend = $('Hardware'); + fieldSet.append(legend); + oList = $('
                                                            '); + + // Loop through each property + var label; + for (k = 5; k < keys.length; k++) { + // Create a list item + item = $('
                                                          1. '); + + // Create a list to hold the property value(s) + hwList = $('
                                                              '); + hwItem = $('
                                                            • '); + + /** + * Privilege section + */ + if (keys[k] == 'priv') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Loop through each line + for (l = 0; l < attrs[keys[k]].length; l++) { + // Create a new list item for each line + hwItem = $('
                                                            • '); + + // Determine privilege + args = attrs[keys[k]][l].split(' '); + if (args[0] == 'Directory:') { + label = $(''); + hwItem.append(label); + hwItem.append(args[1]); + } else if (args[0] == 'Currently:') { + label = $(''); + hwItem.append(label); + hwItem.append(args[1]); + } + + hwList.append(hwItem); + } + + item.append(hwList); + } + + /** + * Memory section + */ + else if (keys[k] == 'memory') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Loop through each value line + for (l = 0; l < attrs[keys[k]].length; l++) { + // Create a new list item for each line + hwItem = $('
                                                            • '); + hwItem.append(attrs[keys[k]][l]); + hwList.append(hwItem); + } + + item.append(hwList); + } + + /** + * Processor section + */ + else if (keys[k] == 'proc') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Create a table to hold processor data + var procTable = $('
                                                              '); + var procBody = $(''); + var procFooter = $(''); + + // Table columns - Type, Address, ID, Base, Dedicated, and Affinity + var procTabRow = $(' Type Address ID Base Dedicated Affinity '); + procTable.append(procTabRow); + var procId, procAff; + + /** + * Remove processor + */ + var contextMenu = [{ + 'Remove' : function(menuItem, menu) { + var addr = $(this).text(); + + // Open dialog to confirm + var confirmDialog = $('

                                                              Are you sure you want to remove this processor?

                                                              '); + confirmDialog.dialog({ + modal: true, + width: 300, + buttons: { + "Ok": function(){ + removeProcessor(node, addr); + $(this).dialog("close"); + }, + "Cancel": function() { + $(this).dialog("close"); + } + } + }); + } + }]; + + // Loop through each processor + var n, temp; + var procType, procAddr, procLink; + for (l = 0; l < attrs[keys[k]].length; l++) { + if (attrs[keys[k]][l]) { + args = attrs[keys[k]][l].split(' '); + + // Get processor type, address, ID, and affinity + n = 3; + temp = args[args.length - n]; + while (!jQuery.trim(temp)) { + n = n + 1; + temp = args[args.length - n]; + } + procType = $('' + temp + ''); + procAddr = $(''); + procLink = $('' + args[1] + ''); + + // Append context menu to link + procLink.contextMenu(contextMenu, { + theme : 'vista' + }); + + procAddr.append(procLink); + procId = $('' + args[5] + ''); + procAff = $('' + args[args.length - 1] + ''); - // Dedicated processor - if (args[args.length - 3] == 'DEDICATED') { - dedicatedProc = $('' + true + ''); - } else { - dedicatedProc = $('' + false + ''); - } + // Base processor + if (args[6] == '(BASE)') { + baseProc = $('' + true + ''); + } else { + baseProc = $('' + false + ''); + } - // Create a new row for each processor - procTabRow = $(''); - procTabRow.append(procType); - procTabRow.append(procAddr); - procTabRow.append(procId); - procTabRow.append(baseProc); - procTabRow.append(dedicatedProc); - procTabRow.append(procAff); - procBody.append(procTabRow); - } - } - - procTable.append(procBody); - - /** - * Add processor - */ - var addProcLink = $('Add temporary processor'); - addProcLink.bind('click', function(event) { - openAddProcDialog(node); - }); - - procFooter.append(addProcLink); - procTable.append(procFooter); - item.append(procTable); - } - - /** - * Disk section - */ - else if (keys[k] == 'disk') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Create a table to hold disk (DASD) data - var dasdTable = $('
                                                              '); - var dasdBody = $(''); - var dasdFooter = $(''); - - /** - * Remove disk - */ - contextMenu = [{ - 'Remove' : function(menuItem, menu) { - var addr = $(this).text(); - - // Open dialog to confirm - var confirmDialog = $('

                                                              Are you sure you want to remove this disk?

                                                              '); - confirmDialog.dialog({ - modal: true, - width: 300, - buttons: { - "Ok": function(){ - removeDisk(node, addr); - $(this).dialog("close"); - }, - "Cancel": function() { - $(this).dialog("close"); - } - } - }); - } - }]; - - // Table columns - Virtual Device, Type, VolID, Type of Access, and Size - var dasdTabRow = $(' Virtual Device # Type VolID Type of Access Size '); - dasdTable.append(dasdTabRow); - var dasdVDev, dasdType, dasdVolId, dasdAccess, dasdSize; - - // Loop through each DASD - for (l = 0; l < attrs[keys[k]].length; l++) { - if (attrs[keys[k]][l]) { - args = attrs[keys[k]][l].split(' '); - - // Get DASD virtual device, type, volume ID, access, and size - dasdVDev = $(''); - dasdLink = $('' + args[1] + ''); + // Dedicated processor + if (args[args.length - 3] == 'DEDICATED') { + dedicatedProc = $('' + true + ''); + } else { + dedicatedProc = $('' + false + ''); + } - // Append context menu to link - dasdLink.contextMenu(contextMenu, { - theme : 'vista' - }); - dasdVDev.append(dasdLink); + // Create a new row for each processor + procTabRow = $(''); + procTabRow.append(procType); + procTabRow.append(procAddr); + procTabRow.append(procId); + procTabRow.append(baseProc); + procTabRow.append(dedicatedProc); + procTabRow.append(procAff); + procBody.append(procTabRow); + } + } + + procTable.append(procBody); + + /** + * Add processor + */ + var addProcLink = $('Add temporary processor'); + addProcLink.bind('click', function(event) { + openAddProcDialog(node); + }); + + procFooter.append(addProcLink); + procTable.append(procFooter); + item.append(procTable); + } + + /** + * Disk section + */ + else if (keys[k] == 'disk') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Create a table to hold disk (DASD) data + var dasdTable = $('
                                                              '); + var dasdBody = $(''); + var dasdFooter = $(''); + + /** + * Remove disk + */ + contextMenu = [{ + 'Remove' : function(menuItem, menu) { + var addr = $(this).text(); + + // Open dialog to confirm + var confirmDialog = $('

                                                              Are you sure you want to remove this disk?

                                                              '); + confirmDialog.dialog({ + modal: true, + width: 300, + buttons: { + "Ok": function(){ + removeDisk(node, addr); + $(this).dialog("close"); + }, + "Cancel": function() { + $(this).dialog("close"); + } + } + }); + } + }]; + + // Table columns - Virtual Device, Type, VolID, Type of Access, and Size + var dasdTabRow = $(' Virtual Device # Type VolID Type of Access Size '); + dasdTable.append(dasdTabRow); + var dasdVDev, dasdType, dasdVolId, dasdAccess, dasdSize; + + // Loop through each DASD + for (l = 0; l < attrs[keys[k]].length; l++) { + if (attrs[keys[k]][l]) { + args = attrs[keys[k]][l].split(' '); + + // Get DASD virtual device, type, volume ID, access, and size + dasdVDev = $(''); + dasdLink = $('' + args[1] + ''); - dasdType = $('' + args[2] + ''); - dasdVolId = $('' + args[3] + ''); - dasdAccess = $('' + args[4] + ''); - dasdSize = $('' + args[args.length - 9] + ' ' + args[args.length - 8] + ''); + // Append context menu to link + dasdLink.contextMenu(contextMenu, { + theme : 'vista' + }); + dasdVDev.append(dasdLink); - // Create a new row for each DASD - dasdTabRow = $(''); - dasdTabRow.append(dasdVDev); - dasdTabRow.append(dasdType); - dasdTabRow.append(dasdVolId); - dasdTabRow.append(dasdAccess); - dasdTabRow.append(dasdSize); - dasdBody.append(dasdTabRow); - } - } - - dasdTable.append(dasdBody); - - /** - * Add disk - */ - var addDasdLink = $('Add disk'); - addDasdLink.bind('click', function(event) { - var hcp = attrs['hcp'][0].split('.'); - openAddDiskDialog(node, hcp[0]); - }); - dasdFooter.append(addDasdLink); - dasdTable.append(dasdFooter); - - item.append(dasdTable); - } - - /** - * NIC section - */ - else if (keys[k] == 'nic') { - // Create a label - Property name - label = $(''); - item.append(label); - - // Create a table to hold NIC data - var nicTable = $('
                                                              '); - var nicBody = $(''); - var nicFooter = $(''); - - /** - * Remove NIC - */ - contextMenu = [ { - 'Remove' : function(menuItem, menu) { - var addr = $(this).text(); - - // Open dialog to confirm - var confirmDialog = $('

                                                              Are you sure you want to remove this NIC?

                                                              '); - confirmDialog.dialog({ - modal: true, - width: 300, - buttons: { - "Ok": function(){ - removeNic(node, addr); - $(this).dialog("close"); - }, - "Cancel": function() { - $(this).dialog("close"); - } - } - }); - } - } ]; - - // Table columns - Virtual device, Adapter Type, Port Name, # of Devices, MAC Address, and LAN Name - var nicTabRow = $(' Virtual Device # Adapter Type Port Name # of Devices LAN Name'); - nicTable.append(nicTabRow); - var nicVDev, nicType, nicPortName, nicNumOfDevs, nicLanName; - - // Loop through each NIC (Data contained in 2 lines) - for (l = 0; l < attrs[keys[k]].length; l = l + 2) { - if (attrs[keys[k]][l]) { - args = attrs[keys[k]][l].split(' '); + dasdType = $('' + args[2] + ''); + dasdVolId = $('' + args[3] + ''); + dasdAccess = $('' + args[4] + ''); + dasdSize = $('' + args[args.length - 9] + ' ' + args[args.length - 8] + ''); - // Get NIC virtual device, type, port name, and number of devices - nicVDev = $(''); - nicLink = $('' + args[1] + ''); + // Create a new row for each DASD + dasdTabRow = $(''); + dasdTabRow.append(dasdVDev); + dasdTabRow.append(dasdType); + dasdTabRow.append(dasdVolId); + dasdTabRow.append(dasdAccess); + dasdTabRow.append(dasdSize); + dasdBody.append(dasdTabRow); + } + } + + dasdTable.append(dasdBody); + + /** + * Add disk + */ + var addDasdLink = $('Add disk'); + addDasdLink.bind('click', function(event) { + var hcp = attrs['hcp'][0].split('.'); + openAddDiskDialog(node, hcp[0]); + }); + dasdFooter.append(addDasdLink); + dasdTable.append(dasdFooter); + + item.append(dasdTable); + } + + /** + * NIC section + */ + else if (keys[k] == 'nic') { + // Create a label - Property name + label = $(''); + item.append(label); + + // Create a table to hold NIC data + var nicTable = $('
                                                              '); + var nicBody = $(''); + var nicFooter = $(''); + + /** + * Remove NIC + */ + contextMenu = [ { + 'Remove' : function(menuItem, menu) { + var addr = $(this).text(); + + // Open dialog to confirm + var confirmDialog = $('

                                                              Are you sure you want to remove this NIC?

                                                              '); + confirmDialog.dialog({ + modal: true, + width: 300, + buttons: { + "Ok": function(){ + removeNic(node, addr); + $(this).dialog("close"); + }, + "Cancel": function() { + $(this).dialog("close"); + } + } + }); + } + } ]; + + // Table columns - Virtual device, Adapter Type, Port Name, # of Devices, MAC Address, and LAN Name + var nicTabRow = $(' Virtual Device # Adapter Type Port Name # of Devices LAN Name'); + nicTable.append(nicTabRow); + var nicVDev, nicType, nicPortName, nicNumOfDevs, nicLanName; + + // Loop through each NIC (Data contained in 2 lines) + for (l = 0; l < attrs[keys[k]].length; l = l + 2) { + if (attrs[keys[k]][l]) { + args = attrs[keys[k]][l].split(' '); - // Append context menu to link - nicLink.contextMenu(contextMenu, { - theme : 'vista' - }); - nicVDev.append(nicLink); + // Get NIC virtual device, type, port name, and number of devices + nicVDev = $(''); + nicLink = $('' + args[1] + ''); - nicType = $('' + args[3] + ''); - nicPortName = $('' + args[10] + ''); - nicNumOfDevs = $('' + args[args.length - 1] + ''); + // Append context menu to link + nicLink.contextMenu(contextMenu, { + theme : 'vista' + }); + nicVDev.append(nicLink); - args = attrs[keys[k]][l + 1].split(' '); - nicLanName = $('' + args[args.length - 2] + ' ' + args[args.length - 1] + ''); + nicType = $('' + args[3] + ''); + nicPortName = $('' + args[10] + ''); + nicNumOfDevs = $('' + args[args.length - 1] + ''); - // Create a new row for each DASD - nicTabRow = $(''); - nicTabRow.append(nicVDev); - nicTabRow.append(nicType); - nicTabRow.append(nicPortName); - nicTabRow.append(nicNumOfDevs); - nicTabRow.append(nicLanName); + args = attrs[keys[k]][l + 1].split(' '); + nicLanName = $('' + args[args.length - 2] + ' ' + args[args.length - 1] + ''); - nicBody.append(nicTabRow); - } - } + // Create a new row for each DASD + nicTabRow = $(''); + nicTabRow.append(nicVDev); + nicTabRow.append(nicType); + nicTabRow.append(nicPortName); + nicTabRow.append(nicNumOfDevs); + nicTabRow.append(nicLanName); + + nicBody.append(nicTabRow); + } + } - nicTable.append(nicBody); + nicTable.append(nicBody); - /** - * Add NIC - */ - var addNicLink = $('Add NIC'); - addNicLink.bind('click', function(event) { - var hcp = attrs['hcp'][0].split('.'); - openAddNicDialog(node, hcp[0]); - }); - nicFooter.append(addNicLink); - nicTable.append(nicFooter); + /** + * Add NIC + */ + var addNicLink = $('Add NIC'); + addNicLink.bind('click', function(event) { + var hcp = attrs['hcp'][0].split('.'); + openAddNicDialog(node, hcp[0]); + }); + nicFooter.append(addNicLink); + nicTable.append(nicFooter); - item.append(nicTable); - } + item.append(nicTable); + } - oList.append(item); - } + oList.append(item); + } - // Append inventory to division - fieldSet.append(oList); - invDiv.append(fieldSet); + // Append inventory to division + fieldSet.append(oList); + invDiv.append(fieldSet); - // Append to tab - $('#' + tabId).append(statBar); - $('#' + tabId).append(toggleLnkDiv); - $('#' + tabId).append(ueDiv); - $('#' + tabId).append(invDiv); + // Append to tab + $('#' + tabId).append(statBar); + $('#' + tabId).append(toggleLnkDiv); + $('#' + tabId).append(ueDiv); + $('#' + tabId).append(invDiv); }; /** * Load provision page * - * @param tabId - * The provision tab ID - * @return Nothing + * @param tabId The provision tab ID */ zvmPlugin.prototype.loadProvisionPage = function(tabId) { - // Get OS image names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS image names + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); + success : setOSImageCookies + }); - // Get groups - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'extnoderange', - tgt : '/.*', - args : 'subgroups', - msg : '' - }, + // Get groups + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'extnoderange', + tgt : '/.*', + args : 'subgroups', + msg : '' + }, - success : setGroupsCookies - }); - - // Get provision tab instance - var inst = tabId.replace('zvmProvisionTab', ''); + success : setGroupsCookies + }); + + // Get provision tab instance + var inst = tabId.replace('zvmProvisionTab', ''); - // Create provision form - var provForm = $('
                                                              '); + // Create provision form + var provForm = $('
                                                              '); - // Create status bar - var statBarId = 'zProvisionStatBar' + inst; - var statBar = createStatusBar(statBarId).hide(); - provForm.append(statBar); + // Create status bar + var statBarId = 'zProvisionStatBar' + inst; + var statBar = createStatusBar(statBarId).hide(); + provForm.append(statBar); - // Create loader - var loader = createLoader('zProvisionLoader' + inst).hide(); - statBar.find('div').append(loader); + // Create loader + var loader = createLoader('zProvisionLoader' + inst).hide(); + statBar.find('div').append(loader); - // Create info bar - var infoBar = createInfoBar('Provision a node on System z.'); - provForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Provision a node on System z.'); + provForm.append(infoBar); - // Append to provision tab - $('#' + tabId).append(provForm); + // Append to provision tab + $('#' + tabId).append(provForm); - var typeFS = $('
                                                              '); - var typeLegend = $('Type'); - typeFS.append(typeLegend); - provForm.append(typeFS); - - // Create provision type drop down - var provType = $('
                                                              '); - var typeLabel = $(''); - var typeSelect = $(''); - var provNewNode = $(''); - var provExistNode = $(''); - typeSelect.append(provNewNode); - typeSelect.append(provExistNode); - provType.append(typeLabel); - provType.append(typeSelect); - typeFS.append(provType); - - /** - * Create provision new node division - */ - var provNew = createZProvisionNew(inst); - provForm.append(provNew); - - /** - * Create provision existing node division - */ - var provExisting = createZProvisionExisting(inst); - provForm.append(provExisting); + var typeFS = $('
                                                              '); + var typeLegend = $('Type'); + typeFS.append(typeLegend); + provForm.append(typeFS); + + // Create provision type drop down + var provType = $('
                                                              '); + var typeLabel = $(''); + var typeSelect = $(''); + var provNewNode = $(''); + var provExistNode = $(''); + typeSelect.append(provNewNode); + typeSelect.append(provExistNode); + provType.append(typeLabel); + provType.append(typeSelect); + typeFS.append(provType); + + /** + * Create provision new node division + */ + var provNew = createZProvisionNew(inst); + provForm.append(provNew); + + /** + * Create provision existing node division + */ + var provExisting = createZProvisionExisting(inst); + provForm.append(provExisting); - // Toggle provision new/existing on select - typeSelect.change(function(){ - var selected = $(this).val(); - if (selected == 'new') { - provNew.toggle(); - provExisting.toggle(); - } else { - provNew.toggle(); - provExisting.toggle(); - } - }); + // Toggle provision new/existing on select + typeSelect.change(function(){ + var selected = $(this).val(); + if (selected == 'new') { + provNew.toggle(); + provExisting.toggle(); + } else { + provNew.toggle(); + provExisting.toggle(); + } + }); }; /** * Load the resources - * - * @return Nothing */ -zvmPlugin.prototype.loadResources = function() { - // Reset resource table - setDiskDataTable(''); - setNetworkDataTable(''); - - // Get hardware control points - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodels', - tgt : 'mgt==zvm', - args : 'zvm.hcp', - msg : '' - }, - success : getZResources - }); +zvmPlugin.prototype.loadResources = function() { + // Reset resource table + setDiskDataTable(''); + setNetworkDataTable(''); + + // Get hardware control points + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodels', + tgt : 'mgt==zvm', + args : 'zvm.hcp', + msg : '' + }, + success : getZResources + }); }; /** * Add node range - * - * @return Nothing */ zvmPlugin.prototype.addNode = function() { - // Create form to add node range - var addNodeForm = $('
                                                              '); - var info = createInfoBar('Add a z/VM node range'); - addNodeForm.append(info); - addNodeForm.append('
                                                              '); - addNodeForm.append('
                                                              '); - addNodeForm.append('
                                                              '); - addNodeForm.append('
                                                              '); - addNodeForm.append('
                                                              '); - addNodeForm.append('
                                                              '); - - // Open form as a dialog - addNodeForm.dialog({ - title: 'Add node', - modal: true, - width: 400, - buttons: { - "Ok": function(){ - // Remove any warning messages - $(this).find('.ui-state-error').remove(); - - // Get inputs - var nodeRange = $(this).find('input[name=node]').val(); - var ipRange = $(this).find('input[name=ip]').val(); - var hostnameRange = $(this).find('input[name=hostname]').val(); - var userIdRange = $(this).find('input[name=userId]').val(); - var group = $(this).find('input[name=groups]').val(); - var hcp = $(this).find('input[name=hcp]').val(); - - // Show warning message if inputs are not complete - if (!nodeRange || !userIdRange || !group || !hcp) { - var warn = createWarnBar('Please provide a value for each missing field!'); - warn.prependTo($(this)); - } else { - // Check node range and user ID range - // Range can be given as gpok10-gpok20, gpok[10-20], or gpok10+10 - var errMsg = ''; - var ready = true; - if (nodeRange.indexOf('-') > -1 || userIdRange.indexOf('-') > -1) { - if (nodeRange.indexOf('-') < 0 || userIdRange.indexOf('-') < 0) { - errMsg = errMsg + 'A user ID range and node range needs to be given. '; - ready = false; - } else { - var tmp = nodeRange.split('-'); + // Create form to add node range + var addNodeForm = $('
                                                              '); + var info = createInfoBar('Add a z/VM node range'); + addNodeForm.append(info); + addNodeForm.append('
                                                              '); + addNodeForm.append('
                                                              '); + addNodeForm.append('
                                                              '); + addNodeForm.append('
                                                              '); + addNodeForm.append('
                                                              '); + addNodeForm.append('
                                                              '); - // Get starting index - var nodeStart = parseInt(tmp[0].match(/\d+/)); - // Get ending index - var nodeEnd = parseInt(tmp[1].match(/\d+/)); + // Open form as a dialog + addNodeForm.dialog({ + title: 'Add node', + modal: true, + width: 400, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get inputs + var nodeRange = $(this).find('input[name=node]').val(); + var ipRange = $(this).find('input[name=ip]').val(); + var hostnameRange = $(this).find('input[name=hostname]').val(); + var userIdRange = $(this).find('input[name=userId]').val(); + var group = $(this).find('input[name=groups]').val(); + var hcp = $(this).find('input[name=hcp]').val(); + + // Show warning message if inputs are not complete + if (!nodeRange || !userIdRange || !group || !hcp) { + var warn = createWarnBar('Please provide a value for each missing field!'); + warn.prependTo($(this)); + } else { + // Check node range and user ID range + // Range can be given as gpok10-gpok20, gpok[10-20], or gpok10+10 + var errMsg = ''; + var ready = true; + if (nodeRange.indexOf('-') > -1 || userIdRange.indexOf('-') > -1) { + if (nodeRange.indexOf('-') < 0 || userIdRange.indexOf('-') < 0) { + errMsg = errMsg + 'A user ID range and node range needs to be given. '; + ready = false; + } else { + var tmp = nodeRange.split('-'); - tmp = userIdRange.split('-'); + // Get starting index + var nodeStart = parseInt(tmp[0].match(/\d+/)); + // Get ending index + var nodeEnd = parseInt(tmp[1].match(/\d+/)); - // Get starting index - var userIdStart = parseInt(tmp[0].match(/\d+/)); - // Get ending index - var userIdEnd = parseInt(tmp[1].match(/\d+/)); - - var ipStart = "", ipEnd = ""; - if (ipRange) { - tmp = ipRange.split('-'); - - // Get starting IP address - ipStart = tmp[0].substring(tmp[0].lastIndexOf(".") + 1); - // Get ending IP address - ipEnd = tmp[1].substring(tmp[1].lastIndexOf(".") + 1); - } - - var hostnameStart = "", hostnameEnd = ""; - if (hostnameRange) { - tmp = hostnameRange.split('-'); - - // Get starting hostname - hostnameStart = parseInt(tmp[0].substring(0, tmp[0].indexOf(".")).match(/\d+/)); - // Get ending hostname - hostnameEnd = parseInt(tmp[1].substring(0, tmp[1].indexOf(".")).match(/\d+/)); - } - - // If starting and ending index do not match - if (!(nodeStart == userIdStart) || !(nodeEnd == userIdEnd)) { - errMsg = errMsg + 'The node range and user ID range does not match. '; - ready = false; - } - - // If an IP address range is given and the starting and ending index do not match - if (ipRange && !(nodeStart == ipStart) || !(nodeEnd == ipEnd)) { - errMsg = errMsg + 'The node range and IP address range does not match. '; - ready = false; - } - - // If a hostname range is given and the starting and ending index do not match - if (hostnameRange && !(nodeStart == hostnameStart) || !(nodeEnd == hostnameEnd)) { - errMsg = errMsg + 'The node range and hostname range does not match. '; - ready = false; - } - } - } - - // If there are no errors - if (ready) { - $('#addZvm').append(createLoader()); - - // Change dialog buttons - $('#addZvm').dialog('option', 'buttons', { - 'Close':function(){ - $('#addZvm').dialog('close'); - } - }); - - // If a node range is given - if (nodeRange.indexOf('-') > -1 && userIdRange.indexOf('-') > -1) { - var tmp = nodeRange.split('-'); - - // Get node base name - var nodeBase = tmp[0].match(/[a-zA-Z]+/); - // Get starting index - var nodeStart = parseInt(tmp[0].match(/\d+/)); - // Get ending index - var nodeEnd = parseInt(tmp[1].match(/\d+/)); - - tmp = userIdRange.split('-'); - - // Get user ID base name - var userIdBase = tmp[0].match(/[a-zA-Z]+/); - - var ipBase = ""; - if (ipRange) { - tmp = ipRange.split('-'); - - // Get network base - ipBase = tmp[0].substring(0, tmp[0].lastIndexOf(".") + 1); - } - - var domain = ""; - if (hostnameRange) { - tmp = hostnameRange.split('-'); - - // Get domain name - domain = tmp[0].substring(tmp[0].indexOf(".")); - } - - // Loop through each node in the node range - for ( var i = nodeStart; i <= nodeEnd; i++) { - var node = nodeBase + i.toString(); - var userId = userIdBase + i.toString(); - var inst = i + '/' + nodeEnd; - - var args = node + ';zvm.hcp=' + hcp - + ';zvm.userid=' + userId - + ';nodehm.mgt=zvm' + ';groups=' + group; - - if (ipRange) { - var ip = ipBase + i.toString(); - args += ';hosts.ip=' + ip; - } - - if (hostnameRange) { - var hostname = node + domain; - args += ';hosts.hostnames=' + hostname; - } - - /** - * (1) Define node - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : args, - msg : 'cmd=addnewnode;inst=' + inst + ';noderange=' + nodeRange - }, - - /** - * Return function on successful AJAX call - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success : function (data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); - - // Get instance returned and node range - var inst = args[1].replace('inst=', ''); - var nodeRange = args[2].replace('noderange=', ''); - - // If the last node was added - var tmp = inst.split('/'); - if (tmp[0] == tmp[1]) { - // Update /etc/hosts - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : '' - } - }); - - // Remove loader - $('#addZvm img').remove(); - - // If there was an error, do not continue - if (rsp.length) { - $('#addZvm').prepend(createWarnBar('Failed to create node definitions')); - } else { - $('#addZvm').prepend(createInfoBar('Node definitions created for ' + nodeRange)); - } - } - } - }); - } - } else { - var args = nodeRange + ';zvm.hcp=' + hcp - + ';zvm.userid=' + userIdRange - + ';nodehm.mgt=zvm' + ';groups=' + group; - - if (ipRange) - args += ';hosts.ip=' + ipRange; - - if (hostnameRange) - args += ';hosts.hostnames=' + hostnameRange; - - // Only one node to add - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : args, - msg : 'cmd=addnewnode;node=' + nodeRange - }, - - /** - * Return function on successful AJAX call - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success : function (data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); - var node = args[1].replace('node=', ''); - - // Update /etc/hosts - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : '' - } - }); - - // Remove loader - $('#addZvm img').remove(); - - // If there was an error, do not continue - if (rsp.length) { - $('#addZvm').prepend(createWarnBar('Failed to create node definitions')); - } else { - $('#addZvm').prepend(createInfoBar('Node definitions created for ' + node)); - } - } - }); - } - } else { - // Show warning message - var warn = createWarnBar(errMsg); - warn.prependTo($(this)); - } - } // End of else - }, - "Cancel": function(){ - $(this).dialog( "close" ); - } - } - }); + tmp = userIdRange.split('-'); + + // Get starting index + var userIdStart = parseInt(tmp[0].match(/\d+/)); + // Get ending index + var userIdEnd = parseInt(tmp[1].match(/\d+/)); + + var ipStart = "", ipEnd = ""; + if (ipRange) { + tmp = ipRange.split('-'); + + // Get starting IP address + ipStart = tmp[0].substring(tmp[0].lastIndexOf(".") + 1); + // Get ending IP address + ipEnd = tmp[1].substring(tmp[1].lastIndexOf(".") + 1); + } + + var hostnameStart = "", hostnameEnd = ""; + if (hostnameRange) { + tmp = hostnameRange.split('-'); + + // Get starting hostname + hostnameStart = parseInt(tmp[0].substring(0, tmp[0].indexOf(".")).match(/\d+/)); + // Get ending hostname + hostnameEnd = parseInt(tmp[1].substring(0, tmp[1].indexOf(".")).match(/\d+/)); + } + + // If starting and ending index do not match + if (!(nodeStart == userIdStart) || !(nodeEnd == userIdEnd)) { + errMsg = errMsg + 'The node range and user ID range does not match. '; + ready = false; + } + + // If an IP address range is given and the starting and ending index do not match + if (ipRange && !(nodeStart == ipStart) || !(nodeEnd == ipEnd)) { + errMsg = errMsg + 'The node range and IP address range does not match. '; + ready = false; + } + + // If a hostname range is given and the starting and ending index do not match + if (hostnameRange && !(nodeStart == hostnameStart) || !(nodeEnd == hostnameEnd)) { + errMsg = errMsg + 'The node range and hostname range does not match. '; + ready = false; + } + } + } + + // If there are no errors + if (ready) { + $('#addZvm').append(createLoader()); + + // Change dialog buttons + $('#addZvm').dialog('option', 'buttons', { + 'Close':function(){ + $('#addZvm').dialog('close'); + } + }); + + // If a node range is given + if (nodeRange.indexOf('-') > -1 && userIdRange.indexOf('-') > -1) { + var tmp = nodeRange.split('-'); + + // Get node base name + var nodeBase = tmp[0].match(/[a-zA-Z]+/); + // Get starting index + var nodeStart = parseInt(tmp[0].match(/\d+/)); + // Get ending index + var nodeEnd = parseInt(tmp[1].match(/\d+/)); + + tmp = userIdRange.split('-'); + + // Get user ID base name + var userIdBase = tmp[0].match(/[a-zA-Z]+/); + + var ipBase = ""; + if (ipRange) { + tmp = ipRange.split('-'); + + // Get network base + ipBase = tmp[0].substring(0, tmp[0].lastIndexOf(".") + 1); + } + + var domain = ""; + if (hostnameRange) { + tmp = hostnameRange.split('-'); + + // Get domain name + domain = tmp[0].substring(tmp[0].indexOf(".")); + } + + // Loop through each node in the node range + for ( var i = nodeStart; i <= nodeEnd; i++) { + var node = nodeBase + i.toString(); + var userId = userIdBase + i.toString(); + var inst = i + '/' + nodeEnd; + + var args = node + ';zvm.hcp=' + hcp + + ';zvm.userid=' + userId + + ';nodehm.mgt=zvm' + ';groups=' + group; + + if (ipRange) { + var ip = ipBase + i.toString(); + args += ';hosts.ip=' + ip; + } + + if (hostnameRange) { + var hostname = node + domain; + args += ';hosts.hostnames=' + hostname; + } + + /** + * (1) Define node + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : args, + msg : 'cmd=addnewnode;inst=' + inst + ';noderange=' + nodeRange + }, + + /** + * Return function on successful AJAX call + * + * @param data + * Data returned from HTTP request + * @return Nothing + */ + success : function (data) { + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); + + // Get instance returned and node range + var inst = args[1].replace('inst=', ''); + var nodeRange = args[2].replace('noderange=', ''); + + // If the last node was added + var tmp = inst.split('/'); + if (tmp[0] == tmp[1]) { + // Update /etc/hosts + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : '' + } + }); + + // Remove loader + $('#addZvm img').remove(); + + // If there was an error, do not continue + if (rsp.length) { + $('#addZvm').prepend(createWarnBar('Failed to create node definitions')); + } else { + $('#addZvm').prepend(createInfoBar('Node definitions created for ' + nodeRange)); + } + } + } + }); + } + } else { + var args = nodeRange + ';zvm.hcp=' + hcp + + ';zvm.userid=' + userIdRange + + ';nodehm.mgt=zvm' + ';groups=' + group; + + if (ipRange) + args += ';hosts.ip=' + ipRange; + + if (hostnameRange) + args += ';hosts.hostnames=' + hostnameRange; + + // Only one node to add + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : args, + msg : 'cmd=addnewnode;node=' + nodeRange + }, + + /** + * Return function on successful AJAX call + * + * @param data + * Data returned from HTTP request + * @return Nothing + */ + success : function (data) { + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); + var node = args[1].replace('node=', ''); + + // Update /etc/hosts + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : '' + } + }); + + // Remove loader + $('#addZvm img').remove(); + + // If there was an error, do not continue + if (rsp.length) { + $('#addZvm').prepend(createWarnBar('Failed to create node definitions')); + } else { + $('#addZvm').prepend(createInfoBar('Node definitions created for ' + node)); + } + } + }); + } + } else { + // Show warning message + var warn = createWarnBar(errMsg); + warn.prependTo($(this)); + } + } // End of else + }, + "Cancel": function(){ + $(this).dialog( "close" ); + } + } + }); }; \ No newline at end of file diff --git a/xCAT-UI/js/custom/zvmUtils.js b/xCAT-UI/js/custom/zvmUtils.js index ca55c3ea1..993a82d57 100644 --- a/xCAT-UI/js/custom/zvmUtils.js +++ b/xCAT-UI/js/custom/zvmUtils.js @@ -7,2960 +7,4762 @@ var networkDatatable; // zVM datatable containing networks /** * Get the disk datatable * - * @param Nothing * @return Data table object */ function getDiskDataTable() { - return diskDatatable; + return diskDatatable; } /** * Set the disk datatable * - * @param table - * Data table object - * @return Nothing + * @param table Data table object */ function setDiskDataTable(table) { - diskDatatable = table; + diskDatatable = table; } /** * Get the network datatable * - * @param Nothing * @return Data table object */ function getNetworkDataTable() { - return networkDatatable; + return networkDatatable; } /** * Set the network datatable * - * @param table - * Data table object - * @return Nothing + * @param table Data table object */ function setNetworkDataTable(table) { - networkDatatable = table; + networkDatatable = table; } /** * Load HCP specific info * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function loadHcpInfo(data) { - var args = data.msg.split(';'); - - // Get group - var group = args[0].replace('group=', ''); - // Get hardware control point - var hcp = args[1].replace('hcp=', ''); - - // Get user directory entry - var userEntry = data.rsp; - if (userEntry[0].indexOf('Failed') < 0) { - if (hcp) { - // If there is no cookie for the disk pool names - if (!$.cookie(hcp + 'diskpools')) { - // Get disk pools - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--diskpoolnames', - msg : hcp - }, + var args = data.msg.split(';'); + + // Get group + var group = args[0].replace('group=', ''); + // Get hardware control point + var hcp = args[1].replace('hcp=', ''); + + // Get user directory entry + var userEntry = data.rsp; + if (userEntry[0].indexOf('Failed') < 0) { + if (hcp) { + // If there is no cookie for the disk pool names + if (!$.cookie(hcp + 'diskpools')) { + // Get disk pools + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcp, + args : '--diskpoolnames', + msg : hcp + }, - success : setDiskPoolCookies - }); - } + success : setDiskPoolCookies + }); + } - // If there is no cookie for the network names - if (!$.cookie(hcp + 'networks')) { - // Get network names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--getnetworknames', - msg : hcp - }, + // If there is no cookie for the network names + if (!$.cookie(hcp + 'networks')) { + // Get network names + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcp, + args : '--getnetworknames', + msg : hcp + }, - success : setNetworkCookies - }); - } - } // End of if (hcp) - } else { - // Create warning dialog - var warning = createWarnBar('z/VM SMAPI is not responding to ' + hcp + '. It needs to be reset.'); - var warnDialog = $('
                                                              ').append(warning); - - // Open dialog - warnDialog.dialog({ - title:'Warning', - modal: true, - width: 400, - buttons: { - "Reset": function(){ - $(this).dialog("close"); - - // Reset SMAPI - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : hcp, - args : '--resetsmapi', - msg : 'group=' + group + ';hcp=' + hcp - }, - - /** - * Refresh group tab - * - * @param data - * Data from HTTP request - * @return Nothing - */ - success : function(data) { - var args = data.msg.split(';'); - - // Get group - var group = args[0].replace('group=', ''); - // Get hardware control point - var hcp = args[1].replace('hcp=', ''); - - // Clear nodes division - $('#nodes').children().remove(); - // Create loader - var loader = $('
                                                              ').append(createLoader()); - - // Create a tab for this group - var tab = new Tab(); - setNodesTab(tab); - tab.init(); - $('#nodes').append(tab.object()); - tab.add('nodesTab', 'Nodes', loader, false); - - // Get nodes within selected group - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : group, - msg : group - }, - - success : loadNodes - }); - } // End of function - }); - }, - - "Ignore": function() { - $(this).dialog("close"); - } - } - }); - } + success : setNetworkCookies + }); + } + } // End of if (hcp) + } else { + // Create warning dialog + var warning = createWarnBar('z/VM SMAPI is not responding to ' + hcp + '. It needs to be reset.'); + var warnDialog = $('
                                                              ').append(warning); + + // Open dialog + warnDialog.dialog({ + title:'Warning', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Reset": function(){ + $(this).dialog("close"); + + // Reset SMAPI + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : hcp, + args : '--resetsmapi', + msg : 'group=' + group + ';hcp=' + hcp + }, + + /** + * Refresh group tab + * + * @param data + * Data from HTTP request + * @return Nothing + */ + success : function(data) { + var args = data.msg.split(';'); + + // Get group + var group = args[0].replace('group=', ''); + + // Clear nodes division + $('#nodes').children().remove(); + // Create loader + var loader = $('
                                                              ').append(createLoader()); + + // Create a tab for this group + var tab = new Tab(); + setNodesTab(tab); + tab.init(); + $('#nodes').append(tab.object()); + tab.add('nodesTab', 'Nodes', loader, false); + + // Get nodes within selected group + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : group, + msg : group + }, + + success : loadNodes + }); + } // End of function + }); + }, + + "Ignore": function() { + $(this).dialog("close"); + } + } + }); + } } /** * Load user entry of a given node * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function loadUserEntry(data) { - var args = data.msg.split(';'); + var args = data.msg.split(';'); - // Get tab ID - var ueDivId = args[0].replace('out=', ''); - // Get node - var node = args[1].replace('node=', ''); - // Get user directory entry - var userEntry = data.rsp[0].split(node + ':'); + // Get tab ID + var ueDivId = args[0].replace('out=', ''); + // Get node + var node = args[1].replace('node=', ''); + // Get user directory entry + var userEntry = data.rsp[0].split(node + ':'); - // Remove loader - $('#' + node + 'TabLoader').remove(); + // Remove loader + $('#' + node + 'TabLoader').remove(); - var toggleLinkId = node + 'ToggleLink'; - $('#' + toggleLinkId).click(function() { - // Get text within this link - var lnkText = $(this).text(); + var toggleLinkId = node + 'ToggleLink'; + $('#' + toggleLinkId).click(function() { + // Get text within this link + var lnkText = $(this).text(); - // Toggle user entry division - $('#' + node + 'UserEntry').toggle(); - // Toggle inventory division - $('#' + node + 'Inventory').toggle(); + // Toggle user entry division + $('#' + node + 'UserEntry').toggle(); + // Toggle inventory division + $('#' + node + 'Inventory').toggle(); - // Change text - if (lnkText == 'Show directory entry') { - $(this).text('Show inventory'); - } else { - $(this).text('Show directory entry'); - } - }); + // Change text + if (lnkText == 'Show directory entry') { + $(this).text('Show inventory'); + } else { + $(this).text('Show directory entry'); + } + }); - // Put user entry into a list - var fieldSet = $('
                                                              '); - var legend = $('Directory Entry'); - fieldSet.append(legend); + // Put user entry into a list + var fieldSet = $('
                                                              '); + var legend = $('Directory Entry'); + fieldSet.append(legend); - var txtArea = $(''); - for ( var i = 1; i < userEntry.length; i++) { - userEntry[i] = jQuery.trim(userEntry[i]); - txtArea.append(userEntry[i]); + var txtArea = $(''); + for ( var i = 1; i < userEntry.length; i++) { + userEntry[i] = jQuery.trim(userEntry[i]); + txtArea.append(userEntry[i]); - if (i < userEntry.length) { - txtArea.append('\n'); - } - } - txtArea.attr('readonly', 'readonly'); - fieldSet.append(txtArea); + if (i < userEntry.length) { + txtArea.append('\n'); + } + } + txtArea.attr('readonly', 'readonly'); + fieldSet.append(txtArea); - /** - * Edit user entry - */ - txtArea.bind('dblclick', function(event) { - txtArea.attr('readonly', ''); - txtArea.css( { - 'border-width' : '1px' - }); + /** + * Edit user entry + */ + txtArea.bind('dblclick', function(event) { + txtArea.attr('readonly', ''); + txtArea.css( { + 'border-width' : '1px' + }); - saveBtn.show(); - cancelBtn.show(); - saveBtn.css('display', 'inline-table'); - cancelBtn.css('display', 'inline-table'); - }); - - /** - * Save - */ - var saveBtn = createButton('Save').hide(); - saveBtn.bind('click', function(event) { - // Show loader - $('#' + node + 'StatusBarLoader').show(); - $('#' + node + 'StatusBar').show(); + saveBtn.show(); + cancelBtn.show(); + saveBtn.css('display', 'inline-table'); + cancelBtn.css('display', 'inline-table'); + }); + + /** + * Save + */ + var saveBtn = createButton('Save').hide(); + saveBtn.bind('click', function(event) { + // Show loader + $('#' + node + 'StatusBarLoader').show(); + $('#' + node + 'StatusBar').show(); - // Replace user entry - var newUserEntry = jQuery.trim(txtArea.val()) + '\n'; + // Replace user entry + var newUserEntry = jQuery.trim(txtArea.val()) + '\n'; - // Replace user entry - $.ajax( { - url : 'lib/zCmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--replacevs', - att : newUserEntry, - msg : node - }, + // Replace user entry + $.ajax( { + url : 'lib/zCmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--replacevs', + att : newUserEntry, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); - // Increment node process and save it in a cookie - incrementNodeProcess(node); + // Increment node process and save it in a cookie + incrementNodeProcess(node); - txtArea.attr('readonly', 'readonly'); - txtArea.css( { - 'border-width' : '0px' - }); + txtArea.attr('readonly', 'readonly'); + txtArea.css( { + 'border-width' : '0px' + }); - // Disable save button - $(this).hide(); - cancelBtn.hide(); - }); + // Disable save button + $(this).hide(); + cancelBtn.hide(); + }); - /** - * Cancel - */ - var cancelBtn = createButton('Cancel').hide(); - cancelBtn.bind('click', function(event) { - txtArea.attr('readonly', 'readonly'); - txtArea.css( { - 'border-width' : '0px' - }); + /** + * Cancel + */ + var cancelBtn = createButton('Cancel').hide(); + cancelBtn.bind('click', function(event) { + txtArea.attr('readonly', 'readonly'); + txtArea.css( { + 'border-width' : '0px' + }); - cancelBtn.hide(); - saveBtn.hide(); - }); + cancelBtn.hide(); + saveBtn.hide(); + }); - // Create info bar - var infoBar = createInfoBar('Double click on the directory entry to edit it.'); + // Create info bar + var infoBar = createInfoBar('Double click on the directory entry to edit it.'); - // Append user entry into division - $('#' + ueDivId).append(infoBar); - $('#' + ueDivId).append(fieldSet); - $('#' + ueDivId).append(saveBtn); - $('#' + ueDivId).append(cancelBtn); + // Append user entry into division + $('#' + ueDivId).append(infoBar); + $('#' + ueDivId).append(fieldSet); + $('#' + ueDivId).append(saveBtn); + $('#' + ueDivId).append(cancelBtn); } /** * Increment number of processes running against a node * - * @param node - * Node to increment running processes - * @return Nothing + * @param node Node to increment running processes */ function incrementNodeProcess(node) { - // Get current processes - var procs = $.cookie(node + 'processes'); - if (procs) { - // One more process - procs = parseInt(procs) + 1; - $.cookie(node + 'processes', procs); - } else { - $.cookie(node + 'processes', 1); - } + // Get current processes + var procs = $.cookie(node + 'processes'); + if (procs) { + // One more process + procs = parseInt(procs) + 1; + $.cookie(node + 'processes', procs); + } else { + $.cookie(node + 'processes', 1); + } } /** * Update provision new node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateZProvisionNewStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); - // Get command invoked - var cmd = args[0].replace('cmd=', ''); - // Get output ID - var out2Id = args[1].replace('out=', ''); - - // Get status bar ID - var statBarId = 'zProvisionStatBar' + out2Id; - // Get provision tab ID - var tabId = 'zvmProvisionTab' + out2Id; - // Get loader ID - var loaderId = 'zProvisionLoader' + out2Id; - - // Get node name - var node = $('#' + tabId + ' input[name=nodeName]').val(); - - /** - * (2) Update /etc/hosts - */ - if (cmd == 'nodeadd') { - // If there was an error, do not continue - if (rsp.length) { - $('#' + loaderId).hide(); - $('#' + statBarId).find('div').append('
                                                              (Error) Failed to create node definition
                                                              '); - } else { - $('#' + statBarId).find('div').append('
                                                              Node definition created for ' + node + '
                                                              '); - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : 'cmd=makehosts;out=' + out2Id - }, + // Get command invoked + var cmd = args[0].replace('cmd=', ''); + // Get output ID + var out2Id = args[1].replace('out=', ''); - success : updateZProvisionNewStatus - }); - } - } + // Get status bar ID + var statBarId = 'zProvisionStatBar' + out2Id; + // Get provision tab ID + var tabId = 'zvmProvisionTab' + out2Id; + // Get loader ID + var loaderId = 'zProvisionLoader' + out2Id; - /** - * (3) Update DNS - */ - else if (cmd == 'makehosts') { - // If there was an error, do not continue - if (rsp.length) { - $('#' + loaderId).hide(); - $('#' + statBarId).find('div').append('
                                                              (Error) Failed to update /etc/hosts
                                                              '); - } else { - $('#' + statBarId).find('div').append('
                                                              /etc/hosts updated
                                                              '); - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makedns', - tgt : '', - args : '', - msg : 'cmd=makedns;out=' + out2Id - }, + // Get node name + var node = $('#' + tabId + ' input[name=nodeName]').val(); - success : updateZProvisionNewStatus - }); - } - } + /** + * (2) Update /etc/hosts + */ + if (cmd == 'nodeadd') { + // If there was an error, do not continue + if (rsp.length) { + $('#' + loaderId).hide(); + $('#' + statBarId).find('div').append('
                                                              (Error) Failed to create node definition
                                                              '); + } else { + $('#' + statBarId).find('div').append('
                                                              Node definition created for ' + node + '
                                                              '); + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : 'cmd=makehosts;out=' + out2Id + }, + + success : updateZProvisionNewStatus + }); + } + } - /** - * (4) Create user entry - */ - else if (cmd == 'makedns') { - // Reset number of tries - $.cookie('tries4' + tabId, 0); + /** + * (3) Update DNS + */ + else if (cmd == 'makehosts') { + // If there was an error, do not continue + if (rsp.length) { + $('#' + loaderId).hide(); + $('#' + statBarId).find('div').append('
                                                              (Error) Failed to update /etc/hosts
                                                              '); + } else { + $('#' + statBarId).find('div').append('
                                                              /etc/hosts updated
                                                              '); + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makedns', + tgt : '', + args : '', + msg : 'cmd=makedns;out=' + out2Id + }, - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + success : updateZProvisionNewStatus + }); + } + } - // Get user entry - var userEntry = $('#' + tabId + ' textarea').val(); - - // Create user entry - $.ajax( { - url : 'lib/zCmd.php', - dataType : 'json', - data : { - cmd : 'mkvm', - tgt : node, - args : '', - att : userEntry, - msg : 'cmd=mkvm;out=' + out2Id - }, + /** + * (4) Create user entry + */ + else if (cmd == 'makedns') { + // Reset number of tries + $.cookie('tries4' + tabId, 0); - success : updateZProvisionNewStatus - }); - } + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - /** - * (5) Add disk - */ - else if (cmd == 'mkvm') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + // Get user entry + var userEntry = $('#' + tabId + ' textarea').val(); + + // Create user entry + $.ajax( { + url : 'lib/zCmd.php', + dataType : 'json', + data : { + cmd : 'mkvm', + tgt : node, + args : '', + att : userEntry, + msg : 'cmd=mkvm;out=' + out2Id + }, - // If there was an error, do not continue - if (prg.html().indexOf('Error') > -1) { - // Try again - var tries = parseInt($.cookie('tries4' + tabId)); - if (tries < 2) { - $('#' + statBarId).find('div').append('
                                                              Trying again...
                                                              '); - tries = tries + 1; + success : updateZProvisionNewStatus + }); + } - // One more try - $.cookie('tries4' + tabId, tries); + /** + * (5) Add disk + */ + else if (cmd == 'mkvm') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // Get user entry - var userEntry = $('#' + tabId + ' textarea').val(); - // Create user entry - $.ajax( { - url : 'lib/zCmd.php', - dataType : 'json', - data : { - cmd : 'mkvm', - tgt : node, - args : '', - att : userEntry, - msg : 'cmd=mkvm;out=' + out2Id - }, + // If there was an error, do not continue + if (prg.html().indexOf('Error') > -1) { + // Try again + var tries = parseInt($.cookie('tries4' + tabId)); + if (tries < 2) { + $('#' + statBarId).find('div').append('
                                                              Trying again...
                                                              '); + tries = tries + 1; - success : updateZProvisionNewStatus - }); - } else { - $('#' + loaderId).hide(); - } - } else { - // Reset number of tries - $.cookie('tries4' + tabId, 0); + // One more try + $.cookie('tries4' + tabId, tries); - // Set cookie for number of disks - var diskRows = $('#' + tabId + ' table:visible tbody tr'); - $.cookie('disks2add' + out2Id, diskRows.length); - if (diskRows.length > 0) { - for ( var i = 0; i < diskRows.length; i++) { - // Get disk type, address, size, mode, pool, and password - var diskArgs = diskRows.eq(i).find('td'); - var type = diskArgs.eq(1).find('select').val(); - var address = diskArgs.eq(2).find('input').val(); - var size = diskArgs.eq(3).find('input').val(); - var mode = diskArgs.eq(4).find('select').val(); - var pool = diskArgs.eq(5).find('input').val(); - var password = diskArgs.eq(6).find('input').val(); - - // Create ajax arguments - var args = ''; - if (type == '3390') { - args = '--add' + type + ';' + pool + ';' + address - + ';' + size + ';' + mode + ';' + password + ';' - + password + ';' + password; - } else if (type == '9336') { - var blkSize = '512'; - args = '--add' + type + ';' + pool + ';' + address + ';' - + blkSize + ';' + size + ';' + mode + ';' + password + ';' - + password + ';' + password; - } + // Get user entry + var userEntry = $('#' + tabId + ' textarea').val(); + // Create user entry + $.ajax( { + url : 'lib/zCmd.php', + dataType : 'json', + data : { + cmd : 'mkvm', + tgt : node, + args : '', + att : userEntry, + msg : 'cmd=mkvm;out=' + out2Id + }, - // Add disk - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : args, - msg : 'cmd=chvm;out=' + out2Id - }, + success : updateZProvisionNewStatus + }); + } else { + $('#' + loaderId).hide(); + } + } else { + // Reset number of tries + $.cookie('tries4' + tabId, 0); - success : updateZProvisionNewStatus - }); - } - } else { - $('#' + loaderId).hide(); - } - } - } + // Set cookie for number of disks + var diskRows = $('#' + tabId + ' table:visible tbody tr'); + $.cookie('disks2add' + out2Id, diskRows.length); + if (diskRows.length > 0) { + for ( var i = 0; i < diskRows.length; i++) { + // Get disk type, address, size, mode, pool, and password + var diskArgs = diskRows.eq(i).find('td'); + var type = diskArgs.eq(1).find('select').val(); + var address = diskArgs.eq(2).find('input').val(); + var size = diskArgs.eq(3).find('input').val(); + var mode = diskArgs.eq(4).find('select').val(); + var pool = diskArgs.eq(5).find('input').val(); + var password = diskArgs.eq(6).find('input').val(); + + // Create ajax arguments + var args = ''; + if (type == '3390') { + args = '--add' + type + ';' + pool + ';' + address + + ';' + size + ';' + mode + ';' + password + ';' + + password + ';' + password; + } else if (type == '9336') { + var blkSize = '512'; + args = '--add' + type + ';' + pool + ';' + address + ';' + + blkSize + ';' + size + ';' + mode + ';' + password + ';' + + password + ';' + password; + } - /** - * (6) Set operating system for given node - */ - else if (cmd == 'chvm') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + // Add disk + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : args, + msg : 'cmd=chvm;out=' + out2Id + }, - // If there was an error, do not continue - if (prg.html().indexOf('Error') > -1) { - $('#' + loaderId).hide(); + success : updateZProvisionNewStatus + }); + } + } else { + $('#' + loaderId).hide(); + } + } + } - // Try again - var tries = parseInt($.cookie('tries4' + tabId)); - if (tries < 2) { - $('#' + statBarId).find('div').append('
                                                              Trying again...
                                                              '); - tries = tries + 1; + /** + * (6) Set operating system for given node + */ + else if (cmd == 'chvm') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // One more try - $.cookie('tries4' + tabId, tries); + // If there was an error, do not continue + if (prg.html().indexOf('Error') > -1) { + $('#' + loaderId).hide(); - // Set cookie for number of disks - var diskRows = $('#' + tabId + ' table:visible tbody tr'); - $.cookie('disks2add' + out2Id, diskRows.length); - if (diskRows.length > 0) { - for ( var i = 0; i < diskRows.length; i++) { - // Get disk type, address, size, pool, and password - var diskArgs = diskRows.eq(i).find('td'); - var type = diskArgs.eq(1).find('select').val(); - var address = diskArgs.eq(2).find('input').val(); - var size = diskArgs.eq(3).find('input').val(); - var mode = diskArgs.eq(4).find('select').val(); - var pool = diskArgs.eq(5).find('input').val(); - var password = diskArgs.eq(6).find('input').val(); - - // Create ajax arguments - var args = ''; - if (type == '3390') { - args = '--add' + type + ';' + pool + ';' + address - + ';' + size + ';' + mode + ';' + password + ';' - + password + ';' + password; - } else if (type == '9336') { - var blkSize = '512'; - args = '--add' + type + ';' + pool + ';' + address + ';' - + blkSize + ';' + size + ';' + mode + ';' + password + ';' - + password + ';' + password; - } + // Try again + var tries = parseInt($.cookie('tries4' + tabId)); + if (tries < 2) { + $('#' + statBarId).find('div').append('
                                                              Trying again...
                                                              '); + tries = tries + 1; - // Add disk - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : args, - msg : 'cmd=chvm;out=' + out2Id - }, + // One more try + $.cookie('tries4' + tabId, tries); - success : updateZProvisionNewStatus - }); - } - } else { - $('#' + loaderId).hide(); - } - } else { - $('#' + loaderId).hide(); - } - } else { - // Reset number of tries - $.cookie('tries4' + tabId, 0); - - // Get operating system image - var osImage = $('#' + tabId + ' input[name=os]:visible').val(); - - // Get cookie for number of disks - var disks2add = $.cookie('disks2add' + out2Id); - // One less disk to add - disks2add = disks2add - 1; - // Set cookie for number of disks - $.cookie('disks2add' + out2Id, disks2add); + // Set cookie for number of disks + var diskRows = $('#' + tabId + ' table:visible tbody tr'); + $.cookie('disks2add' + out2Id, diskRows.length); + if (diskRows.length > 0) { + for ( var i = 0; i < diskRows.length; i++) { + // Get disk type, address, size, pool, and password + var diskArgs = diskRows.eq(i).find('td'); + var type = diskArgs.eq(1).find('select').val(); + var address = diskArgs.eq(2).find('input').val(); + var size = diskArgs.eq(3).find('input').val(); + var mode = diskArgs.eq(4).find('select').val(); + var pool = diskArgs.eq(5).find('input').val(); + var password = diskArgs.eq(6).find('input').val(); + + // Create ajax arguments + var args = ''; + if (type == '3390') { + args = '--add' + type + ';' + pool + ';' + address + + ';' + size + ';' + mode + ';' + password + ';' + + password + ';' + password; + } else if (type == '9336') { + var blkSize = '512'; + args = '--add' + type + ';' + pool + ';' + address + ';' + + blkSize + ';' + size + ';' + mode + ';' + password + ';' + + password + ';' + password; + } - // If an operating system image is given - if (osImage) { - var tmp = osImage.split('-'); + // Add disk + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : args, + msg : 'cmd=chvm;out=' + out2Id + }, - // Get operating system, architecture, provision method, and profile - var os = tmp[0]; - var arch = tmp[1]; - var profile = tmp[3]; + success : updateZProvisionNewStatus + }); + } + } else { + $('#' + loaderId).hide(); + } + } else { + $('#' + loaderId).hide(); + } + } else { + // Reset number of tries + $.cookie('tries4' + tabId, 0); + + // Get operating system image + var osImage = $('#' + tabId + ' input[name=os]:visible').val(); + + // Get cookie for number of disks + var disks2add = $.cookie('disks2add' + out2Id); + // One less disk to add + disks2add = disks2add - 1; + // Set cookie for number of disks + $.cookie('disks2add' + out2Id, disks2add); - // If the last disk is added - if (disks2add < 1) { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : node + ';noderes.netboot=zvm;nodetype.os=' - + os + ';nodetype.arch=' + arch - + ';nodetype.profile=' + profile, - msg : 'cmd=noderes;out=' + out2Id - }, + // If an operating system image is given + if (osImage) { + var tmp = osImage.split('-'); - success : updateZProvisionNewStatus - }); - } - } else { - $('#' + loaderId).hide(); - } - } - } + // Get operating system, architecture, provision method, and profile + var os = tmp[0]; + var arch = tmp[1]; + var profile = tmp[3]; - /** - * (7) Update DHCP - */ - else if (cmd == 'noderes') { - // If there was an error, do not continue - if (rsp.length) { - $('#' + loaderId).hide(); - $('#' + statBarId).find('div').append('
                                                              (Error) Failed to set operating system
                                                              '); - } else { - $('#' + statBarId).find('div').append('
                                                              Operating system for ' + node + ' set
                                                              '); - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makedhcp', - tgt : '', - args : '-a', - msg : 'cmd=makedhcp;out=' + out2Id - }, + // If the last disk is added + if (disks2add < 1) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : node + ';noderes.netboot=zvm;nodetype.os=' + + os + ';nodetype.arch=' + arch + + ';nodetype.profile=' + profile, + msg : 'cmd=noderes;out=' + out2Id + }, - success : updateZProvisionNewStatus - }); - } - } + success : updateZProvisionNewStatus + }); + } + } else { + $('#' + loaderId).hide(); + } + } + } - /** - * (8) Prepare node for boot - */ - else if (cmd == 'makedhcp') { - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeset', - tgt : node, - args : 'install', - msg : 'cmd=nodeset;out=' + out2Id - }, + /** + * (7) Update DHCP + */ + else if (cmd == 'noderes') { + // If there was an error, do not continue + if (rsp.length) { + $('#' + loaderId).hide(); + $('#' + statBarId).find('div').append('
                                                              (Error) Failed to set operating system
                                                              '); + } else { + $('#' + statBarId).find('div').append('
                                                              Operating system for ' + node + ' set
                                                              '); + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makedhcp', + tgt : '', + args : '-a', + msg : 'cmd=makedhcp;out=' + out2Id + }, - success : updateZProvisionNewStatus - }); - } + success : updateZProvisionNewStatus + }); + } + } - /** - * (9) Boot node to network - */ - else if (cmd == 'nodeset') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // If there was an error - // Do not continue - if (prg.html().indexOf('Error') > -1) { - $('#' + loaderId).hide(); - } else { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rnetboot', - tgt : node, - args : 'ipl=000C', - msg : 'cmd=rnetboot;out=' + out2Id - }, + /** + * (8) Prepare node for boot + */ + else if (cmd == 'makedhcp') { + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeset', + tgt : node, + args : 'install', + msg : 'cmd=nodeset;out=' + out2Id + }, - success : updateZProvisionNewStatus - }); - } - } + success : updateZProvisionNewStatus + }); + } - /** - * (10) Done - */ - else if (cmd == 'rnetboot') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - if (prg.html().indexOf('Error') < 0) { - $('#' + statBarId).find('div').append('
                                                              Open a VNC viewer to see the installation progress.  It might take a couple of minutes before you can connect.
                                                              '); - } + /** + * (9) Boot node to network + */ + else if (cmd == 'nodeset') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // If there was an error + // Do not continue + if (prg.html().indexOf('Error') > -1) { + $('#' + loaderId).hide(); + } else { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rnetboot', + tgt : node, + args : 'ipl=000C', + msg : 'cmd=rnetboot;out=' + out2Id + }, - // Hide loader - $('#' + loaderId).hide(); - } + success : updateZProvisionNewStatus + }); + } + } + + /** + * (10) Done + */ + else if (cmd == 'rnetboot') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + if (prg.html().indexOf('Error') < 0) { + $('#' + statBarId).find('div').append('
                                                              Open a VNC viewer to see the installation progress.  It might take a couple of minutes before you can connect.
                                                              '); + } + + // Hide loader + $('#' + loaderId).hide(); + } } /** * Update the provision existing node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateZProvisionExistingStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); - // Get command invoked - var cmd = args[0].replace('cmd=', ''); - // Get provision tab instance - var inst = args[1].replace('out=', ''); - - // Get provision tab and status bar ID - var statBarId = 'zProvisionStatBar' + inst; - var tabId = 'zvmProvisionTab' + inst; - - /** - * (2) Prepare node for boot - */ - if (cmd == 'nodeadd') { - // Get operating system - var bootMethod = $('#' + tabId + ' select[name=bootMethod]').val(); - - // Get nodes that were checked - var dTableId = 'zNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeset', - tgt : tgts, - args : bootMethod, - msg : 'cmd=nodeset;out=' + inst - }, + // Get command invoked + var cmd = args[0].replace('cmd=', ''); + // Get provision tab instance + var inst = args[1].replace('out=', ''); + + // Get provision tab and status bar ID + var statBarId = 'zProvisionStatBar' + inst; + var tabId = 'zvmProvisionTab' + inst; + + /** + * (2) Prepare node for boot + */ + if (cmd == 'nodeadd') { + // Get operating system + var bootMethod = $('#' + tabId + ' select[name=bootMethod]').val(); + + // Get nodes that were checked + var dTableId = 'zNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeset', + tgt : tgts, + args : bootMethod, + msg : 'cmd=nodeset;out=' + inst + }, - success : updateZProvisionExistingStatus - }); - } - - /** - * (3) Boot node from network - */ - else if (cmd == 'nodeset') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + success : updateZProvisionExistingStatus + }); + } + + /** + * (3) Boot node from network + */ + else if (cmd == 'nodeset') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // If there was an error, do not continue - if (prg.html().indexOf('Error') > -1) { - var loaderId = 'zProvisionLoader' + inst; - $('#' + loaderId).remove(); - return; - } - - // Get nodes that were checked - var dTableId = 'zNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - - // Boot node from network - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rnetboot', - tgt : tgts, - args : 'ipl=000C', - msg : 'cmd=rnetboot;out=' + inst - }, + // If there was an error, do not continue + if (prg.html().indexOf('Error') > -1) { + var loaderId = 'zProvisionLoader' + inst; + $('#' + loaderId).remove(); + return; + } + + // Get nodes that were checked + var dTableId = 'zNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + + // Boot node from network + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rnetboot', + tgt : tgts, + args : 'ipl=000C', + msg : 'cmd=rnetboot;out=' + inst + }, - success : updateZProvisionExistingStatus - }); - } - - /** - * (4) Done - */ - else if (cmd == 'rnetboot') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - var loaderId = 'zProvisionLoader' + inst; - $('#' + loaderId).remove(); - } + success : updateZProvisionExistingStatus + }); + } + + /** + * (4) Done + */ + else if (cmd == 'rnetboot') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + var loaderId = 'zProvisionLoader' + inst; + $('#' + loaderId).remove(); + } } /** * Update zVM node status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateZNodeStatus(data) { - var node = data.msg; - var rsp = data.rsp; + var node = data.msg; + var rsp = data.rsp; - // Get cookie for number processes performed against this node - var actions = $.cookie(node + 'processes'); - // One less process - actions = actions - 1; - $.cookie(node + 'processes', actions); - - if (actions < 1) { - // Hide loader when there are no more processes - var statusBarLoaderId = node + 'StatusBarLoader'; - $('#' + statusBarLoaderId).hide(); - } + // Get cookie for number processes performed against this node + var actions = $.cookie(node + 'processes'); + // One less process + actions = actions - 1; + $.cookie(node + 'processes', actions); + + if (actions < 1) { + // Hide loader when there are no more processes + var statusBarLoaderId = node + 'StatusBarLoader'; + $('#' + statusBarLoaderId).hide(); + } - var statBarId = node + 'StatusBar'; - - // Write ajax response to status bar - var prg = writeRsp(rsp, '[A-Za-z0-9._-]+:'); - $('#' + statBarId).find('div').append(prg); + var statBarId = node + 'StatusBar'; + + // Write ajax response to status bar + var prg = writeRsp(rsp, '[A-Za-z0-9._-]+:'); + $('#' + statBarId).find('div').append(prg); } /** * Update clone status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateZCloneStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); - var cmd = args[0].replace('cmd=', ''); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); + var cmd = args[0].replace('cmd=', ''); - // Get provision instance - var inst = args[1].replace('inst=', ''); - // Get output division ID - var out2Id = args[2].replace('out=', ''); + // Get provision instance + var inst = args[1].replace('inst=', ''); + // Get output division ID + var out2Id = args[2].replace('out=', ''); - /** - * (2) Update /etc/hosts - */ - if (cmd == 'nodeadd') { - var node = args[3].replace('node=', ''); + /** + * (2) Update /etc/hosts + */ + if (cmd == 'nodeadd') { + var node = args[3].replace('node=', ''); - // If there was an error, do not continue - if (rsp.length) { - $('#' + out2Id).find('img').hide(); - $('#' + out2Id).find('div').append('
                                                              (Error) Failed to create node definition
                                                              '); - } else { - $('#' + out2Id).find('div').append('
                                                              Node definition created for ' + node + '
                                                              '); - - // If last node definition was created - var tmp = inst.split('/'); - if (tmp[0] == tmp[1]) { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : 'cmd=makehosts;inst=' + inst + ';out=' + out2Id - }, + // If there was an error, do not continue + if (rsp.length) { + $('#' + out2Id).find('img').hide(); + $('#' + out2Id).find('div').append('
                                                              (Error) Failed to create node definition
                                                              '); + } else { + $('#' + out2Id).find('div').append('
                                                              Node definition created for ' + node + '
                                                              '); + + // If last node definition was created + var tmp = inst.split('/'); + if (tmp[0] == tmp[1]) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : 'cmd=makehosts;inst=' + inst + ';out=' + out2Id + }, - success : updateZCloneStatus - }); - } - } - } + success : updateZCloneStatus + }); + } + } + } - /** - * (3) Update DNS - */ - else if (cmd == 'makehosts') { - // If there was an error, do not continue - if (rsp.length) { - $('#' + out2Id).find('img').hide(); - $('#' + out2Id).find('div').append('
                                                              (Error) Failed to update /etc/hosts
                                                              '); - } else { - $('#' + out2Id).find('div').append('
                                                              /etc/hosts updated
                                                              '); - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makedns', - tgt : '', - args : '', - msg : 'cmd=makedns;inst=' + inst + ';out=' + out2Id - }, + /** + * (3) Update DNS + */ + else if (cmd == 'makehosts') { + // If there was an error, do not continue + if (rsp.length) { + $('#' + out2Id).find('img').hide(); + $('#' + out2Id).find('div').append('
                                                              (Error) Failed to update /etc/hosts
                                                              '); + } else { + $('#' + out2Id).find('div').append('
                                                              /etc/hosts updated
                                                              '); + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makedns', + tgt : '', + args : '', + msg : 'cmd=makedns;inst=' + inst + ';out=' + out2Id + }, - success : updateZCloneStatus - }); - } - } + success : updateZCloneStatus + }); + } + } - /** - * (4) Clone - */ - else if (cmd == 'makedns') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + out2Id).find('div').append(prg); - - // Get clone tab - var tabId = out2Id.replace('CloneStatusBar', 'CloneTab'); + /** + * (4) Clone + */ + else if (cmd == 'makedns') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + out2Id).find('div').append(prg); + + // Get clone tab + var tabId = out2Id.replace('CloneStatusBar', 'CloneTab'); - // If a node range is given - var tgtNodeRange = $('#' + tabId + ' input[name=tgtNode]').val(); - var tgtNodes = ''; - if (tgtNodeRange.indexOf('-') > -1) { - var tmp = tgtNodeRange.split('-'); - - // Get node base name - var nodeBase = tmp[0].match(/[a-zA-Z]+/); - // Get the starting index - var nodeStart = parseInt(tmp[0].match(/\d+/)); - // Get the ending index - var nodeEnd = parseInt(tmp[1].match(/\d+/)); - for ( var i = nodeStart; i <= nodeEnd; i++) { - // Do not append comma for last node - if (i == nodeEnd) { - tgtNodes += nodeBase + i.toString(); - } else { - tgtNodes += nodeBase + i.toString() + ','; - } - } - } else { - tgtNodes = tgtNodeRange; - } - - // Get other inputs - var srcNode = $('#' + tabId + ' input[name=srcNode]').val(); - hcp = $('#' + tabId + ' input[name=newHcp]').val(); - var group = $('#' + tabId + ' input[name=newGroup]').val(); - var diskPool = $('#' + tabId + ' input[name=diskPool]').val(); - var diskPw = $('#' + tabId + ' input[name=diskPw]').val(); - if (!diskPw) { - diskPw = ''; - } + // If a node range is given + var tgtNodeRange = $('#' + tabId + ' input[name=tgtNode]').val(); + var tgtNodes = ''; + if (tgtNodeRange.indexOf('-') > -1) { + var tmp = tgtNodeRange.split('-'); + + // Get node base name + var nodeBase = tmp[0].match(/[a-zA-Z]+/); + // Get the starting index + var nodeStart = parseInt(tmp[0].match(/\d+/)); + // Get the ending index + var nodeEnd = parseInt(tmp[1].match(/\d+/)); + for ( var i = nodeStart; i <= nodeEnd; i++) { + // Do not append comma for last node + if (i == nodeEnd) { + tgtNodes += nodeBase + i.toString(); + } else { + tgtNodes += nodeBase + i.toString() + ','; + } + } + } else { + tgtNodes = tgtNodeRange; + } + + // Get other inputs + var srcNode = $('#' + tabId + ' input[name=srcNode]').val(); + hcp = $('#' + tabId + ' input[name=newHcp]').val(); + var group = $('#' + tabId + ' input[name=newGroup]').val(); + var diskPool = $('#' + tabId + ' input[name=diskPool]').val(); + var diskPw = $('#' + tabId + ' input[name=diskPw]').val(); + if (!diskPw) { + diskPw = ''; + } - // Clone - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'mkvm', - tgt : tgtNodes, - args : srcNode + ';pool=' + diskPool + ';pw=' + diskPw, - msg : 'cmd=mkvm;inst=' + inst + ';out=' + out2Id - }, + // Clone + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'mkvm', + tgt : tgtNodes, + args : srcNode + ';pool=' + diskPool + ';pw=' + diskPw, + msg : 'cmd=mkvm;inst=' + inst + ';out=' + out2Id + }, - success : updateZCloneStatus - }); - } + success : updateZCloneStatus + }); + } - /** - * (5) Done - */ - else if (cmd == 'mkvm') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + out2Id).find('div').append(prg); - - // Hide loader - $('#' + out2Id).find('img').hide(); - } + /** + * (5) Done + */ + else if (cmd == 'mkvm') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + out2Id).find('div').append(prg); + + // Hide loader + $('#' + out2Id).find('img').hide(); + } } /** * Get zVM resources * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function getZResources(data) { - // Do not continue if there is no output - if (data.rsp) { - // Loop through each line - var node, hcp; - var hcpHash = new Object(); - for ( var i in data.rsp) { - node = data.rsp[i][0]; - hcp = data.rsp[i][1]; - hcpHash[hcp] = 1; - } + // Do not continue if there is no output + if (data.rsp) { + // Push hardware control points into an array + var node, hcp; + var hcpHash = new Object(); + for (var i in data.rsp) { + node = data.rsp[i][0]; + hcp = data.rsp[i][1]; + hcpHash[hcp] = 1; + } - // Create an array for hardware control points - var hcps = new Array(); - for ( var key in hcpHash) { - hcps.push(key); - // Get the short host name - hcp = key.split('.')[0]; + // Create an array for hardware control points + var hcps = new Array(); + for (var key in hcpHash) { + // Get the short host name + hcp = key.split('.')[0]; + hcps.push(hcp); + } - // Get disk pools - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--diskpoolnames', - msg : hcp - }, + // Set hardware control point cookie + $.cookie('hcp', hcps); + + // Delete loader + var tabId = 'zvmResourceTab'; + $('#' + tabId).find('img[src="images/loader.gif"]').remove(); + + // Create accordion panel for disk + var resourcesAccordion = $('
                                                              '); + var diskSection = $('
                                                              '); + var diskLnk = $('

                                                              Disks

                                                              ').click(function () { + // Do not load panel again if it is already loaded + if ($('#zvmDiskResource').children().length) + return; + else + $('#zvmDiskResource').append(createLoader('')); + + // Resize accordion + $('#zvmResourceAccordion').accordion('resize'); + + // Create a array for hardware control points + var hcps = new Array(); + if ($.cookie('hcp').indexOf(',') > -1) + hcps = $.cookie('hcp').split(','); + else + hcps.push($.cookie('hcp')); + + // Query the disk pools for each + for (var i in hcps) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcps[i], + args : '--diskpoolnames', + msg : hcps[i] + }, - success : getDiskPool - }); + success : getDiskPool + }); + } + }); + + // Create accordion panel for network + var networkSection = $('
                                                              '); + var networkLnk = $('

                                                              Networks

                                                              ').click(function () { + // Do not load panel again if it is already loaded + if ($('#zvmNetworkResource').children().length) + return; + else + $('#zvmNetworkResource').append(createLoader('')); + + // Resize accordion + $('#zvmResourceAccordion').accordion('resize'); + + // Create a array for hardware control points + var hcps = new Array(); + if ($.cookie('hcp').indexOf(',') > -1) + hcps = $.cookie('hcp').split(','); + else + hcps.push($.cookie('hcp')); + + for ( var i in hcps) { + // Gather networks from hardware control points + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcps[i], + args : '--getnetworknames', + msg : hcps[i] + }, - // Get network names - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--getnetworknames', - msg : hcp - }, - - success : getNetwork - }); - } - - // Set cookie - $.cookie('hcp', hcps); - } + success : getNetwork + }); + } + }); + + resourcesAccordion.append(diskLnk, diskSection, networkLnk, networkSection); + + // Append accordion to tab + $('#' + tabId).append(resourcesAccordion); + resourcesAccordion.accordion(); + diskLnk.trigger('click'); + } } /** * Get node attributes from HTTP request data * - * @param propNames - * Hash table of property names - * @param keys - * Property keys - * @param data - * Data from HTTP request + * @param propNames Hash table of property names + * @param keys Property keys + * @param data Data from HTTP request * @return Hash table of property values */ function getAttrs(keys, propNames, data) { - // Create hash table for property values - var attrs = new Object(); + // Create hash table for property values + var attrs = new Object(); - // Go through inventory and separate each property out - var curKey; // Current property key - var addLine; // Add a line to the current property? - for ( var i = 1; i < data.length; i++) { - addLine = true; + // Go through inventory and separate each property out + var curKey = null; // Current property key + var addLine; // Add a line to the current property? + for ( var i = 1; i < data.length; i++) { + addLine = true; - // Loop through property keys - // Does this line contains one of the properties? - for ( var j = 0; j < keys.length; j++) { - // Find property name - if (data[i].indexOf(propNames[keys[j]]) > -1) { - attrs[keys[j]] = new Array(); + // Loop through property keys + // Does this line contains one of the properties? + for ( var j = 0; j < keys.length; j++) { + // Find property name + if (data[i].indexOf(propNames[keys[j]]) > -1) { + attrs[keys[j]] = new Array(); - // Get rid of property name in the line - data[i] = data[i].replace(propNames[keys[j]], ''); - // Trim the line - data[i] = jQuery.trim(data[i]); + // Get rid of property name in the line + data[i] = data[i].replace(propNames[keys[j]], ''); + // Trim the line + data[i] = jQuery.trim(data[i]); - // Do not insert empty line - if (data[i].length > 0) { - attrs[keys[j]].push(data[i]); - } + // Do not insert empty line + if (data[i].length > 0) { + attrs[keys[j]].push(data[i]); + } - curKey = keys[j]; - addLine = false; // This line belongs to a property - } - } + curKey = keys[j]; + addLine = false; // This line belongs to a property + } + } - // Line does not contain a property - // Must belong to previous property - if (addLine && data[i].length > 1) { - data[i] = jQuery.trim(data[i]); - attrs[curKey].push(data[i]); - } - } + // Line does not contain a property + // Must belong to previous property + if (addLine && data[i].length > 1) { + data[i] = jQuery.trim(data[i]); + attrs[curKey].push(data[i]); + } + } - return attrs; + return attrs; } /** * Create add processor dialog * - * @param node - * Node to add processor to - * @return Nothing + * @param node Node to add processor to */ -function openAddProcDialog(node) { - // Create form to add processor - var addProcForm = $('
                                                              '); - // Create info bar - var info = createInfoBar('Add a temporary processor to this virtual server.'); - addProcForm.append(info); - addProcForm.append('
                                                              '); - addProcForm.append('
                                                              '); - - // Create drop down for processor type - var procType = $('
                                                              '); - procType.append(''); - var typeSelect = $(''); - typeSelect.append('' - + '' - + '' - + '' - ); - procType.append(typeSelect); - addProcForm.append(procType); - - // Open dialog to add processor - addProcForm.dialog({ - title:'Add processor', - modal: true, - width: 400, - buttons: { - "Ok": function(){ - // Remove any warning messages - $(this).find('.ui-state-error').remove(); - - // Get inputs - var node = $(this).find('input[name=procNode]').val(); - var address = $(this).find('input[name=procAddress]').val(); - var type = $(this).find('select[name=procType]').val(); - - // If inputs are not complete, show warning message - if (!node || !address || !type) { - var warn = createWarnBar('Please provide a value for each missing field.'); - warn.prependTo($(this)); - } else { - // Add processor - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--addprocessoractive;' + address + ';' + type, - msg : node - }, +function openAddProcDialog(node) { + // Create form to add processor + var addProcForm = $('
                                                              '); + // Create info bar + var info = createInfoBar('Add a temporary processor to this virtual server.'); + addProcForm.append(info); + addProcForm.append('
                                                              '); + addProcForm.append('
                                                              '); - success : updateZNodeStatus - }); + // Create drop down for processor type + var procType = $('
                                                              '); + procType.append(''); + var typeSelect = $(''); + typeSelect.append('' + + '' + + '' + + '' + ); + procType.append(typeSelect); + addProcForm.append(procType); - // Increment node process - incrementNodeProcess(node); + // Open dialog to add processor + addProcForm.dialog({ + title:'Add processor', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get inputs + var node = $(this).find('input[name=procNode]').val(); + var address = $(this).find('input[name=procAddress]').val(); + var type = $(this).find('select[name=procType]').val(); + + // If inputs are not complete, show warning message + if (!node || !address || !type) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Add processor + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--addprocessoractive;' + address + ';' + type, + msg : node + }, - // Show loader - var statusId = node + 'StatusBar'; - var statusBarLoaderId = node + 'StatusBarLoader'; - $('#' + statusBarLoaderId).show(); - $('#' + statusId).show(); - - // Close dialog - $(this).dialog( "close" ); - } - }, - "Cancel": function() { - $(this).dialog( "close" ); - } - } - }); + success : updateZNodeStatus + }); + + // Increment node process + incrementNodeProcess(node); + + // Show loader + var statusId = node + 'StatusBar'; + var statusBarLoaderId = node + 'StatusBarLoader'; + $('#' + statusBarLoaderId).show(); + $('#' + statusId).show(); + + // Close dialog + $(this).dialog( "close" ); + } + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); } /** * Create add disk dialog * - * @param node - * Node to add disk to - * @param hcp - * Hardware control point of node - * @return Nothing + * @param node Node to add disk to + * @param hcp Hardware control point of node */ function openAddDiskDialog(node, hcp) { - // Get list of disk pools - var cookie = $.cookie(hcp + 'diskpools'); - var pools = cookie.split(','); - - // Create form to add disk - var addDiskForm = $('
                                                              '); - // Create info bar - var info = createInfoBar('Add a ECKD|3390 or FBA|9336 disk to this virtual server.'); - addDiskForm.append(info); - addDiskForm.append('
                                                              '); - addDiskForm.append('
                                                              '); - addDiskForm.append('
                                                              '); - addDiskForm.append('
                                                              '); - - // Create drop down for disk pool - var diskPool = $('
                                                              '); - diskPool.append(''); - var poolSelect = $(''); - for ( var i = 0; i < pools.length; i++) { - poolSelect.append(''); - } - diskPool.append(poolSelect); - addDiskForm.append(diskPool); + // Get list of disk pools + var cookie = $.cookie(hcp + 'diskpools'); + var pools = cookie.split(','); + + // Create form to add disk + var addDiskForm = $('
                                                              '); + // Create info bar + var info = createInfoBar('Add a ECKD|3390 or FBA|9336 disk to this virtual server.'); + addDiskForm.append(info); + addDiskForm.append('
                                                              '); + addDiskForm.append('
                                                              '); + addDiskForm.append('
                                                              '); + addDiskForm.append('
                                                              '); + + // Create drop down for disk pool + var diskPool = $('
                                                              '); + diskPool.append(''); + var poolSelect = $(''); + for ( var i = 0; i < pools.length; i++) { + poolSelect.append(''); + } + diskPool.append(poolSelect); + addDiskForm.append(diskPool); - // Create drop down for disk mode - var diskMode = $('
                                                              '); - diskMode.append(''); - var modeSelect = $(''); - modeSelect.append('' - + '' - + '' - + '' - + '' - + '' - + '' - ); - diskMode.append(modeSelect); - addDiskForm.append(diskMode); + // Create drop down for disk mode + var diskMode = $('
                                                              '); + diskMode.append(''); + var modeSelect = $(''); + modeSelect.append('' + + '' + + '' + + '' + + '' + + '' + + '' + ); + diskMode.append(modeSelect); + addDiskForm.append(diskMode); - addDiskForm.append('
                                                              '); + addDiskForm.append('
                                                              '); - // Open dialog to add disk - addDiskForm.dialog({ - title:'Add disk', - modal: true, - width: 400, - buttons: { - "Ok": function(){ - // Remove any warning messages - $(this).find('.ui-state-error').remove(); - - // Get inputs - var node = $(this).find('input[name=diskNode]').val(); - var type = $(this).find('select[name=diskType]').val(); - var address = $(this).find('input[name=diskAddress]').val(); - var size = $(this).find('input[name=diskSize]').val(); - var pool = $(this).find('select[name=diskPool]').val(); - var mode = $(this).find('select[name=diskMode]').val(); - var password = $(this).find('input[name=diskPassword]').val(); - - // If inputs are not complete, show warning message - if (!node || !type || !address || !size || !pool || !mode) { - var warn = createWarnBar('Please provide a value for each missing field.'); - warn.prependTo($(this)); - } else { - // Add disk - if (type == '3390') { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--add3390;' + pool + ';' + address + ';' + size - + ';' + mode + ';' + password + ';' + password + ';' + password, - msg : node - }, + // Open dialog to add disk + addDiskForm.dialog({ + title:'Add disk', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get inputs + var node = $(this).find('input[name=diskNode]').val(); + var type = $(this).find('select[name=diskType]').val(); + var address = $(this).find('input[name=diskAddress]').val(); + var size = $(this).find('input[name=diskSize]').val(); + var pool = $(this).find('select[name=diskPool]').val(); + var mode = $(this).find('select[name=diskMode]').val(); + var password = $(this).find('input[name=diskPassword]').val(); + + // If inputs are not complete, show warning message + if (!node || !type || !address || !size || !pool || !mode) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Add disk + if (type == '3390') { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--add3390;' + pool + ';' + address + ';' + size + + ';' + mode + ';' + password + ';' + password + ';' + password, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); - // Increment node process - incrementNodeProcess(node); + // Increment node process + incrementNodeProcess(node); - // Show loader - var statusId = node + 'StatusBar'; - var statusBarLoaderId = node + 'StatusBarLoader'; - $('#' + statusBarLoaderId).show(); - $('#' + statusId).show(); - } else if (type == '9336') { - // Default block size for FBA volumes = 512 - var blkSize = '512'; - - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--add9336;' + pool + ';' + address + ';' + blkSize + ';' + size - + ';' + mode + ';' + password + ';' + password + ';' + password, - msg : node - }, + // Show loader + var statusId = node + 'StatusBar'; + var statusBarLoaderId = node + 'StatusBarLoader'; + $('#' + statusBarLoaderId).show(); + $('#' + statusId).show(); + } else if (type == '9336') { + // Default block size for FBA volumes = 512 + var blkSize = '512'; + + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--add9336;' + pool + ';' + address + ';' + blkSize + ';' + size + + ';' + mode + ';' + password + ';' + password + ';' + password, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); - // Increment node process - incrementNodeProcess(node); + // Increment node process + incrementNodeProcess(node); - // Show loader - var statusId = node + 'StatusBar'; - var statusBarLoaderId = node + 'StatusBarLoader'; - $('#' + statusBarLoaderId).show(); - $('#' + statusId).show(); - } - - // Close dialog - $(this).dialog( "close" ); - } // End of else - }, - "Cancel": function() { - $(this).dialog( "close" ); - } - } - }); + // Show loader + var statusId = node + 'StatusBar'; + var statusBarLoaderId = node + 'StatusBarLoader'; + $('#' + statusBarLoaderId).show(); + $('#' + statusId).show(); + } + + // Close dialog + $(this).dialog( "close" ); + } // End of else + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); } /** * Create add NIC dialog * - * @param node - * Node to add NIC to - * @param hcp - * Hardware control point of node - * @return Nothing + * @param node Node to add NIC to + * @param hcp Hardware control point of node */ function openAddNicDialog(node, hcp) { - // Get network names - var networks = $.cookie(hcp + 'networks').split(','); - - // Create form to add NIC - var addNicForm = $('
                                                              '); - // Create info bar - var info = createInfoBar('Add a NIC to this virtual server.'); - addNicForm.append(info); - addNicForm.append('
                                                              '); - addNicForm.append('
                                                              '); - - // Create drop down for NIC types - var nicType = $('
                                                              '); - nicType.append(''); - var nicTypeSelect = $(''); - nicTypeSelect.append('' - + '' - + '' - ); - nicType.append(nicTypeSelect); - addNicForm.append(nicType); - - // Create drop down for network types - var networkType = $('
                                                              '); - networkType.append(''); - var networkTypeSelect = $(''); - networkTypeSelect.append('' - + '' - + '' - ); - networkType.append(networkTypeSelect); - addNicForm.append(networkType); - - // Create drop down for network names - var gLansQdioSelect = $(''); - var gLansHipersSelect = $(''); - var vswitchSelect = $(''); - for ( var i = 0; i < networks.length; i++) { - var network = networks[i].split(' '); - var networkOption = $(''); - if (network[0] == 'VSWITCH') { - vswitchSelect.append(networkOption); - } else if (network[0] == 'LAN:QDIO') { - gLansQdioSelect.append(networkOption); - } else if (network[0] == 'LAN:HIPERS') { - gLansHipersSelect.append(networkOption); - } - } - - // Hide network name drop downs until the NIC type and network type is selected - // QDIO Guest LAN drop down - var guestLanQdio = $('
                                                              ').hide(); - guestLanQdio.append(''); - guestLanQdio.append(gLansQdioSelect); - addNicForm.append(guestLanQdio); - - // HIPERS Guest LAN drop down - var guestLanHipers = $('
                                                              ').hide(); - guestLanHipers.append(''); - guestLanHipers.append(gLansHipersSelect); - addNicForm.append(guestLanHipers); - - // VSWITCH drop down - var vswitch = $('
                                                              ').hide(); - vswitch.append(''); - vswitch.append(vswitchSelect); - addNicForm.append(vswitch); - - // Show network names on change - networkTypeSelect.change(function(){ - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - // Get NIC type and network type - var nicType = $(this).parent().parent().find('select[name=nicType]').val(); - var networkType = $(this).val(); - - // Hide network name drop downs - var guestLanQdio = $(this).parent().parent().find('select[name=nicLanQdioName]').parent(); - var guestLanHipers = $(this).parent().parent().find('select[name=nicLanHipersName]').parent(); - var vswitch = $(this).parent().parent().find('select[name=nicVSwitchName]').parent(); - guestLanQdio.hide(); - guestLanHipers.hide(); - vswitch.hide(); - - // Show correct network name - if (networkType == 'Guest LAN' && nicType == 'QDIO') { - guestLanQdio.show(); - } else if (networkType == 'Guest LAN' && nicType == 'HiperSockets') { - guestLanHipers.show(); - } else if (networkType == 'Virtual Switch') { - if (nicType == 'QDIO') { - vswitch.show(); - } else { - // No such thing as HIPERS VSWITCH - var warn = createWarnBar('The selected choices are not valid.'); - warn.prependTo($(this).parent().parent()); - } - } - }); - - // Show network names on change - nicTypeSelect.change(function(){ - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - // Get NIC type and network type - var nicType = $(this).val(); - var networkType = $(this).parent().parent().find('select[name=nicNetworkType]').val(); + // Get network names + var networks = $.cookie(hcp + 'networks').split(','); + + // Create form to add NIC + var addNicForm = $('
                                                              '); + // Create info bar + var info = createInfoBar('Add a NIC to this virtual server.'); + addNicForm.append(info); + addNicForm.append('
                                                              '); + addNicForm.append('
                                                              '); + + // Create drop down for NIC types + var nicType = $('
                                                              '); + nicType.append(''); + var nicTypeSelect = $(''); + nicTypeSelect.append('' + + '' + + '' + ); + nicType.append(nicTypeSelect); + addNicForm.append(nicType); + + // Create drop down for network types + var networkType = $('
                                                              '); + networkType.append(''); + var networkTypeSelect = $(''); + networkTypeSelect.append('' + + '' + + '' + ); + networkType.append(networkTypeSelect); + addNicForm.append(networkType); + + // Create drop down for network names + var gLansQdioSelect = $(''); + var gLansHipersSelect = $(''); + var vswitchSelect = $(''); + for ( var i = 0; i < networks.length; i++) { + var network = networks[i].split(' '); + var networkOption = $(''); + if (network[0] == 'VSWITCH') { + vswitchSelect.append(networkOption); + } else if (network[0] == 'LAN:QDIO') { + gLansQdioSelect.append(networkOption); + } else if (network[0] == 'LAN:HIPERS') { + gLansHipersSelect.append(networkOption); + } + } + + // Hide network name drop downs until the NIC type and network type is selected + // QDIO Guest LAN drop down + var guestLanQdio = $('
                                                              ').hide(); + guestLanQdio.append(''); + guestLanQdio.append(gLansQdioSelect); + addNicForm.append(guestLanQdio); + + // HIPERS Guest LAN drop down + var guestLanHipers = $('
                                                              ').hide(); + guestLanHipers.append(''); + guestLanHipers.append(gLansHipersSelect); + addNicForm.append(guestLanHipers); + + // VSWITCH drop down + var vswitch = $('
                                                              ').hide(); + vswitch.append(''); + vswitch.append(vswitchSelect); + addNicForm.append(vswitch); + + // Show network names on change + networkTypeSelect.change(function(){ + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + // Get NIC type and network type + var nicType = $(this).parent().parent().find('select[name=nicType]').val(); + var networkType = $(this).val(); + + // Hide network name drop downs + var guestLanQdio = $(this).parent().parent().find('select[name=nicLanQdioName]').parent(); + var guestLanHipers = $(this).parent().parent().find('select[name=nicLanHipersName]').parent(); + var vswitch = $(this).parent().parent().find('select[name=nicVSwitchName]').parent(); + guestLanQdio.hide(); + guestLanHipers.hide(); + vswitch.hide(); + + // Show correct network name + if (networkType == 'Guest LAN' && nicType == 'QDIO') { + guestLanQdio.show(); + } else if (networkType == 'Guest LAN' && nicType == 'HiperSockets') { + guestLanHipers.show(); + } else if (networkType == 'Virtual Switch') { + if (nicType == 'QDIO') { + vswitch.show(); + } else { + // No such thing as HIPERS VSWITCH + var warn = createWarnBar('The selected choices are not valid.'); + warn.prependTo($(this).parent().parent()); + } + } + }); + + // Show network names on change + nicTypeSelect.change(function(){ + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + // Get NIC type and network type + var nicType = $(this).val(); + var networkType = $(this).parent().parent().find('select[name=nicNetworkType]').val(); - // Hide network name drop downs - var guestLanQdio = $(this).parent().parent().find('select[name=nicLanQdioName]').parent(); - var guestLanHipers = $(this).parent().parent().find('select[name=nicLanHipersName]').parent(); - var vswitch = $(this).parent().parent().find('select[name=nicVSwitchName]').parent(); - guestLanQdio.hide(); - guestLanHipers.hide(); - vswitch.hide(); - - // Show correct network name - if (networkType == 'Guest LAN' && nicType == 'QDIO') { - guestLanQdio.show(); - } else if (networkType == 'Guest LAN' && nicType == 'HiperSockets') { - guestLanHipers.show(); - } else if (networkType == 'Virtual Switch') { - if (nicType == 'QDIO') { - vswitch.show(); - } else { - // No such thing as HIPERS VSWITCH - var warn = createWarnBar('The selected choices are not valid.'); - warn.prependTo($(this).parent().parent()); - } - } - }); - - // Open dialog to add NIC - addNicForm.dialog({ - title:'Add NIC', - modal: true, - width: 400, - buttons: { - "Ok": function(){ - // Remove any warning messages - $(this).find('.ui-state-error').remove(); - - var ready = true; - var errMsg = ''; - - // Get inputs - var node = $(this).find('input[name=nicNode]').val(); - var nicType = $(this).find('select[name=nicType]').val(); - var networkType = $(this).find('select[name=nicNetworkType]').val(); - var address = $(this).find('input[name=nicAddress]').val(); - - // If inputs are not complete, show warning message - if (!node || !nicType || !networkType || !address) { - errMsg = 'Please provide a value for each missing field.
                                                              '; - ready = false; - } - - // If a HIPERS VSWITCH is selected, show warning message - if (nicType == 'HiperSockets' && networkType == 'Virtual Switch') { - errMsg += 'The selected choices are not valid.'; - ready = false; - } - - // If there are errors - if (!ready) { - // Show warning message - var warn = createWarnBar(errMsg); - warn.prependTo($(this)); - } else { - // Add guest LAN - if (networkType == 'Guest LAN') { - var temp; - if (nicType == 'QDIO') { - temp = $(this).find('select[name=nicLanQdioName]').val().split(' '); - } else { - temp = $(this).find('select[name=nicLanHipersName]').val().split(' '); - } - - var lanOwner = temp[0]; - var lanName = temp[1]; - - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--addnic;' + address + ';' + nicType + ';3', - msg : 'node=' + node + ';addr=' + address + ';lan=' - + lanName + ';owner=' + lanOwner - }, - success : connect2GuestLan - }); - } + // Hide network name drop downs + var guestLanQdio = $(this).parent().parent().find('select[name=nicLanQdioName]').parent(); + var guestLanHipers = $(this).parent().parent().find('select[name=nicLanHipersName]').parent(); + var vswitch = $(this).parent().parent().find('select[name=nicVSwitchName]').parent(); + guestLanQdio.hide(); + guestLanHipers.hide(); + vswitch.hide(); + + // Show correct network name + if (networkType == 'Guest LAN' && nicType == 'QDIO') { + guestLanQdio.show(); + } else if (networkType == 'Guest LAN' && nicType == 'HiperSockets') { + guestLanHipers.show(); + } else if (networkType == 'Virtual Switch') { + if (nicType == 'QDIO') { + vswitch.show(); + } else { + // No such thing as HIPERS VSWITCH + var warn = createWarnBar('The selected choices are not valid.'); + warn.prependTo($(this).parent().parent()); + } + } + }); + + // Open dialog to add NIC + addNicForm.dialog({ + title:'Add NIC', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + var ready = true; + var errMsg = ''; + + // Get inputs + var node = $(this).find('input[name=nicNode]').val(); + var nicType = $(this).find('select[name=nicType]').val(); + var networkType = $(this).find('select[name=nicNetworkType]').val(); + var address = $(this).find('input[name=nicAddress]').val(); + + // If inputs are not complete, show warning message + if (!node || !nicType || !networkType || !address) { + errMsg = 'Please provide a value for each missing field.
                                                              '; + ready = false; + } + + // If a HIPERS VSWITCH is selected, show warning message + if (nicType == 'HiperSockets' && networkType == 'Virtual Switch') { + errMsg += 'The selected choices are not valid.'; + ready = false; + } + + // If there are errors + if (!ready) { + // Show warning message + var warn = createWarnBar(errMsg); + warn.prependTo($(this)); + } else { + // Add guest LAN + if (networkType == 'Guest LAN') { + var temp; + if (nicType == 'QDIO') { + temp = $(this).find('select[name=nicLanQdioName]').val().split(' '); + } else { + temp = $(this).find('select[name=nicLanHipersName]').val().split(' '); + } + + var lanOwner = temp[0]; + var lanName = temp[1]; + + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--addnic;' + address + ';' + nicType + ';3', + msg : 'node=' + node + ';addr=' + address + ';lan=' + + lanName + ';owner=' + lanOwner + }, + success : connect2GuestLan + }); + } - // Add virtual switch - else if (networkType == 'Virtual Switch' && nicType == 'QDIO') { - var temp = $(this).find('select[name=nicVSwitchName]').val().split(' '); - var vswitchName = temp[1]; + // Add virtual switch + else if (networkType == 'Virtual Switch' && nicType == 'QDIO') { + var temp = $(this).find('select[name=nicVSwitchName]').val().split(' '); + var vswitchName = temp[1]; - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--addnic;' + address + ';' + nicType + ';3', - msg : 'node=' + node + ';addr=' + address + ';vsw=' - + vswitchName - }, + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--addnic;' + address + ';' + nicType + ';3', + msg : 'node=' + node + ';addr=' + address + ';vsw=' + + vswitchName + }, - success : connect2VSwitch - }); - } - - // Increment node process - incrementNodeProcess(node); + success : connect2VSwitch + }); + } + + // Increment node process + incrementNodeProcess(node); - // Show loader - $('#' + node + 'StatusBarLoader').show(); - $('#' + node + 'StatusBar').show(); - - // Close dialog - $(this).dialog( "close" ); - } // End of else - }, - "Cancel": function(){ - $(this).dialog( "close" ); - } - } - }); + // Show loader + $('#' + node + 'StatusBarLoader').show(); + $('#' + node + 'StatusBar').show(); + + // Close dialog + $(this).dialog( "close" ); + } // End of else + }, + "Cancel": function(){ + $(this).dialog( "close" ); + } + } + }); } /** * Remove processor * - * @param node - * Node where processor is attached - * @param address - * Virtual address of processor - * @return Nothing + * @param node Node where processor is attached + * @param address Virtual address of processor */ function removeProcessor(node, address) { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--removeprocessor;' + address, - msg : node - }, + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--removeprocessor;' + address, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); - // Increment node process - incrementNodeProcess(node); + // Increment node process + incrementNodeProcess(node); - // Show loader - $('#' + node + 'StatusBarLoader').show(); - $('#' + node + 'StatusBar').show(); + // Show loader + $('#' + node + 'StatusBarLoader').show(); + $('#' + node + 'StatusBar').show(); } /** * Remove disk * - * @param node - * Node where disk is attached - * @param address - * Virtual address of disk - * @return Nothing + * @param node Node where disk is attached + * @param address Virtual address of disk */ function removeDisk(node, address) { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--removedisk;' + address, - msg : node - }, + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--removedisk;' + address, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); - // Increment node process - incrementNodeProcess(node); + // Increment node process + incrementNodeProcess(node); - // Show loader - $('#' + node + 'StatusBarLoader').show(); - $('#' + node + 'StatusBar').show(); + // Show loader + $('#' + node + 'StatusBarLoader').show(); + $('#' + node + 'StatusBar').show(); } /** * Remove NIC * - * @param node - * Node where NIC is attached - * @param address - * Virtual address of NIC - * @return Nothing + * @param node Node where NIC is attached + * @param address Virtual address of NIC */ function removeNic(node, nic) { - var args = nic.split('.'); - var address = args[0]; + var args = nic.split('.'); + var address = args[0]; - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--removenic;' + address, - msg : node - }, + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--removenic;' + address, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); - // Increment node process - incrementNodeProcess(node); + // Increment node process + incrementNodeProcess(node); - // Show loader - $('#' + node + 'StatusBarLoader').show(); - $('#' + node + 'StatusBar').show(); + // Show loader + $('#' + node + 'StatusBarLoader').show(); + $('#' + node + 'StatusBar').show(); } /** * Set a cookie for the network names of a given node * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function setNetworkCookies(data) { - if (data.rsp) { - var node = data.msg; - var networks = data.rsp[0].split(node + ': '); - - // Set cookie to expire in 60 minutes - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (60 * 60 * 1000)); - $.cookie(node + 'networks', networks, { expires: exDate }); - } + if (data.rsp) { + var node = data.msg; + var networks = data.rsp[0].split(node + ': '); + + // Set cookie to expire in 60 minutes + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (60 * 60 * 1000)); + $.cookie(node + 'networks', networks, { expires: exDate }); + } } /** * Get contents of each disk pool * - * @param data - * HTTP request data - * @return Nothing + * @param data HTTP request data */ function getDiskPool(data) { - if (data.rsp) { - var hcp = data.msg; - var pools = data.rsp[0].split(hcp + ': '); + if (data.rsp) { + var hcp = data.msg; + var pools = data.rsp[0].split(hcp + ': '); - // Get contents of each disk pool - for ( var i in pools) { - if (pools[i]) { - pools[i] = jQuery.trim(pools[i]); - - // Get used space - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--diskpool;' + pools[i] + ';used', - msg : 'hcp=' + hcp + ';pool=' + pools[i] + ';stat=used' - }, + // Get contents of each disk pool + for ( var i in pools) { + if (pools[i]) { + pools[i] = jQuery.trim(pools[i]); + + // Get used space + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcp, + args : '--diskpool;' + pools[i] + ';used', + msg : 'hcp=' + hcp + ';pool=' + pools[i] + ';stat=used' + }, - success : loadDiskPoolTable - }); + success : loadDiskPoolTable + }); - // Get free space - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--diskpool;' + pools[i] + ';free', - msg : 'hcp=' + hcp + ';pool=' + pools[i] + ';stat=free' - }, + // Get free space + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcp, + args : '--diskpool;' + pools[i] + ';free', + msg : 'hcp=' + hcp + ';pool=' + pools[i] + ';stat=free' + }, - success : loadDiskPoolTable - }); - } // End of if - } // End of for - } + success : loadDiskPoolTable + }); + } // End of if + } // End of for + } } /** * Get details of each network * - * @param data - * HTTP request data - * @return Nothing + * @param data HTTP request data */ function getNetwork(data) { - if (data.rsp) { - var hcp = data.msg; - var networks = data.rsp[0].split(hcp + ': '); + if (data.rsp) { + var hcp = data.msg; + var networks = data.rsp[0].split(hcp + ': '); - // Loop through each network - for ( var i = 1; i < networks.length; i++) { - var args = networks[i].split(' '); - var type = args[0]; - var name = args[2]; + // Loop through each network + for ( var i = 1; i < networks.length; i++) { + var args = networks[i].split(' '); + var type = args[0]; + var name = args[2]; - // Get network details - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : hcp, - args : '--getnetwork;' + name, - msg : 'hcp=' + hcp + ';type=' + type + ';network=' + name - }, + // Get network details + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcp, + args : '--getnetwork;' + name, + msg : 'hcp=' + hcp + ';type=' + type + ';network=' + name + }, - success : loadNetworkTable - }); - } // End of for - } // End of if + success : loadNetworkTable + }); + } // End of for + } // End of if } /** * Load disk pool contents into a table * - * @param data - * HTTP request data - * @return Nothing + * @param data HTTP request data */ function loadDiskPoolTable(data) { - var args = data.msg.split(';'); - var hcp = args[0].replace('hcp=', ''); - var pool = args[1].replace('pool=', ''); - var stat = args[2].replace('stat=', ''); - var tmp = data.rsp[0].split(hcp + ': '); + // Remove loader + var panelId = 'zvmDiskResource'; + $('#' + panelId).find('img[src="images/loader.gif"]').remove(); + + var args = data.msg.split(';'); + var hcp = args[0].replace('hcp=', ''); + var pool = args[1].replace('pool=', ''); + var stat = args[2].replace('stat=', ''); + var tmp = data.rsp[0].split(hcp + ': '); - // Remove loader - var loaderId = 'zvmResourceLoader'; - if ($('#' + loaderId).length) { - $('#' + loaderId).remove(); - } + // Resource tab ID + var info = $('#' + panelId).find('.ui-state-highlight'); + // If there is no info bar + if (!info.length) { + // Create info bar + info = createInfoBar('Below are disks that are defined in the EXTENT CONTROL file.'); + $('#' + panelId).append(info); + } - // Resource tab ID - var tabID = 'zvmResourceTab'; - var info = $('#' + tabID).find('.ui-state-highlight'); - // If there is no info bar - if (!info.length) { - // Create info bar - info = createInfoBar('Below are disks and networks found by the hardware control point. It shows disk pools defined in the EXTENT CONTROL file and LANs|VSWITCHes available to use.'); - $('#' + tabID).append(info); - } + // Get datatable + var tableId = 'zDiskDataTable'; + var dTable = getDiskDataTable(); + if (!dTable) { + // Create a datatable + var table = new DataTable(tableId); + // Resource headers: volume ID, device type, start address, and size + table.init( [ '', 'HCP', 'Pool', 'Status', 'Region', 'Device type', 'Starting address', 'Size' ]); - // Get datatable - var dTable = getDiskDataTable(); - if (!dTable) { - // Create disks section - var fieldSet = $('
                                                              '); - var legend = $('Disks'); - fieldSet.append(legend); + // Append datatable to panel + $('#' + panelId).append(table.object()); - // Create a datatable - var tableID = 'zDiskDataTable'; - var table = new DataTable(tableID); - // Resource headers: volume ID, device type, start address, and size - table.init( [ 'HCP', 'Pool', 'Status', 'Volume ID', 'Device type', 'Start address', 'Size' ]); + // Turn into datatable + dTable = $('#' + tableId).dataTable(); + setDiskDataTable(dTable); + } - // Append datatable to tab - fieldSet.append(table.object()); - $('#' + tabID).append(fieldSet); + // Skip index 0 and 1 because it contains nothing + for ( var i = 2; i < tmp.length; i++) { + tmp[i] = jQuery.trim(tmp[i]); + var diskAttrs = tmp[i].split(' '); + dTable.fnAddData( [ '', hcp, pool, stat, diskAttrs[0], diskAttrs[1], diskAttrs[2], diskAttrs[3] ]); + } + + // Create actions menu + if (!$('#zvmResourceActions').length) { + // Empty filter area + $('#' + tableId + '_length').empty(); + + // Add disk to pool + var addLnk = $('Add'); + addLnk.bind('click', function(event){ + openAddDisk2PoolDialog(); + }); + + // Delete disk from pool + var removeLnk = $('Remove'); + removeLnk.bind('click', function(event){ + var disks = getNodesChecked(tableId); + openRemoveDiskFromPoolDialog(disks); + }); + + // Refresh table + var refreshLnk = $('Refresh'); + refreshLnk.bind('click', function(event){ + $('#zvmDiskResource').empty().append(createLoader('')); + setDiskDataTable(''); + + // Create a array for hardware control points + var hcps = new Array(); + if ($.cookie('hcp').indexOf(',') > -1) + hcps = $.cookie('hcp').split(','); + else + hcps.push($.cookie('hcp')); + + // Query the disk pools for each + for (var i in hcps) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : hcps[i], + args : '--diskpoolnames', + msg : hcps[i] + }, - // Turn into datatable - dTable = $('#' + tableID).dataTable(); - setDiskDataTable(dTable); - } + success : getDiskPool + }); + } + }); + + // Create action bar + var actionBar = $('
                                                              '); + + // Create an action menu + var actionsMenu = createMenu([addLnk, removeLnk, refreshLnk]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + tableId + '_length').prepend(menuDiv); + $('#' + tableId + '_length').css({ + 'padding': '0px', + 'width': '500px' + }); + $('#' + tableId + '_filter').css('padding', '10px'); + menuDiv.append(actionBar); + } + + // Resize accordion + $('#zvmResourceAccordion').accordion('resize'); +} - // Skip index 0 and 1 because it contains nothing - for ( var i = 2; i < tmp.length; i++) { - tmp[i] = jQuery.trim(tmp[i]); - var diskAttrs = tmp[i].split(' '); - dTable.fnAddData( [ hcp, pool, stat, diskAttrs[0], diskAttrs[1], diskAttrs[2], diskAttrs[3] ]); - } +/** + * Open dialog to remove disk from pool + * + * @param disks2remove Disks selected in table + */ +function openRemoveDiskFromPoolDialog(disks2remove) { + // Create form to delete disk to pool + var dialogId = 'zvmDeleteDiskFromPool'; + var deleteDiskForm = $('
                                                              '); + + // Create info bar + var info = createInfoBar('Remove a disk from a disk pool defined in the EXTENT CONTROL.'); + deleteDiskForm.append(info); + var action = $('
                                                              '); + var actionSelect = $(''); + action.append(actionSelect); + + var hcp = $('
                                                              '); + var hcpSelect = $(''); + hcp.append(hcpSelect); + + // Set region input based on those selected on table (if any) + var region = $('
                                                              '); + var group = $('
                                                              '); + deleteDiskForm.append(action, hcp, region, group); + + // Create a array for hardware control points + var hcps = new Array(); + if ($.cookie('hcp').indexOf(',') > -1) + hcps = $.cookie('hcp').split(','); + else + hcps.push($.cookie('hcp')); + + // Append options for hardware control points + for (var i in hcps) { + hcpSelect.append($('')); + } + + actionSelect.change(function() { + if ($(this).val() == '1' || $(this).val() == '3') { + region.show(); + group.hide(); + } else if ($(this).val() == '2') { + region.show(); + group.show(); + } else if ($(this).val() == '7') { + region.val('FOOBAR'); + region.hide(); + group.show(); + } + }); + + // Open dialog to delete disk + deleteDiskForm.dialog({ + title:'Delete disk from pool', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 500, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get inputs + var action = $(this).find('select[name=action]').val(); + var hcp = $(this).find('select[name=hcp]').val(); + var region = $(this).find('input[name=region]').val(); + var group = $(this).find('input[name=group]').val(); + + // If inputs are not complete, show warning message + if (!action || !hcp) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + var args; + if (action == '2' || action == '7') + args = region + ';' + group; + else + args = group; + + // Remove disk from pool + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : hcp, + args : '--removediskfrompool;' + action + ';' + args, + msg : dialogId + }, + + success : updateResourceDialog + }); + } + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); +} + +/** + * Open dialog to add disk to pool + */ +function openAddDisk2PoolDialog() { + // Create form to add disk to pool + var dialogId = 'zvmAddDisk2Pool'; + var addDiskForm = $('
                                                              '); + // Create info bar + var info = createInfoBar('Add a disk to a disk pool defined in the EXTENT CONTROL. The disk has to already be attached to SYSTEM.'); + addDiskForm.append(info); + var action = $('
                                                              '); + var actionSelect = $(''); + action.append(actionSelect); + + var hcp = $('
                                                              '); + var hcpSelect = $(''); + hcp.append(hcpSelect); + var region = $('
                                                              '); + var volume = $('
                                                              '); + var group = $('
                                                              '); + addDiskForm.append(action, hcp, region, volume, group); + + // Create a array for hardware control points + var hcps = new Array(); + if ($.cookie('hcp').indexOf(',') > -1) + hcps = $.cookie('hcp').split(','); + else + hcps.push($.cookie('hcp')); + + // Append options for hardware control points + for (var i in hcps) { + hcpSelect.append($('')); + } + + actionSelect.change(function() { + if ($(this).val() == '4') { + volume.show(); + } else if ($(this).val() == '5') { + volume.hide(); + } + }); + + // Open dialog to add disk + addDiskForm.dialog({ + title:'Add disk to pool', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 500, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get inputs + var action = $(this).find('select[name=action]').val(); + var hcp = $(this).find('select[name=hcp]').val(); + var region = $(this).find('input[name=region]').val(); + var volume = $(this).find('input[name=volume]').val(); + var group = $(this).find('input[name=group]').val(); + + // If inputs are not complete, show warning message + if (!action || !hcp || !region || !group) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + var args; + if (action == '4') + args = region + ';' + volume + ';' + group; + else + args = region + ';' + group; + + // Add disk to pool + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : hcp, + args : '--adddisk2pool;' + action + ';' + args, + msg : dialogId + }, + + success : updateResourceDialog + }); + } + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); +} + +/** + * Update resource dialog + * + * @param data HTTP request data + */ +function updateResourceDialog(data) { + var dialogId = data.msg; + var infoMsg; + + // Create info message + if (jQuery.isArray(data.rsp)) { + infoMsg = ''; + for (var i in data.rsp) { + infoMsg += data.rsp[i] + '
                                                              '; + } + } else { + infoMsg = data.rsp; + } + + // Create info bar with close button + var infoBar = $('
                                                              ').css('margin', '5px 0px'); + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px' + }); + + // Create close button to close info bar + var close = $('').css({ + 'display': 'inline-block', + 'float': 'right' + }).click(function() { + $(this).parent().remove(); + }); + + var msg = $('
                                                              ' + infoMsg + '
                                                              ').css({ + 'display': 'inline-block', + 'width': '90%' + }); + + infoBar.append(icon, msg, close); + infoBar.prependTo($('#' + dialogId)); +} + +/** + * Select all checkboxes in the datatable + * + * @param event Event on element + * @param obj Object triggering event + */ +function selectAllDisk(event, obj) { + // Get datatable ID + // This will ascend from + var tableObj = obj.parents('.datatable'); + var status = obj.attr('checked'); + tableObj.find(' :checkbox').attr('checked', status); + event.stopPropagation(); } /** * Load network details into a table * - * @param data - * HTTP request data - * @return Nothing + * @param data HTTP request data */ function loadNetworkTable(data) { - var args = data.msg.split(';'); - var hcp = args[0].replace('hcp=', ''); - var type = args[1].replace('type=', ''); - var name = args[2].replace('network=', ''); - var tmp = data.rsp[0].split(hcp + ': '); + // Remove loader + var panelId = 'zvmNetworkResource'; + $('#' + panelId).find('img[src="images/loader.gif"]').remove(); + + var args = data.msg.split(';'); + var hcp = args[0].replace('hcp=', ''); + var type = args[1].replace('type=', ''); + var name = args[2].replace('network=', ''); + var tmp = data.rsp[0].split(hcp + ': '); - // Remove loader - var loaderId = 'zvmResourceLoader'; - if ($('#' + loaderId).length) { - $('#' + loaderId).remove(); - } + // Resource tab ID + var info = $('#' + panelId).find('.ui-state-highlight'); + // If there is no info bar + if (!info.length) { + // Create info bar + info = createInfoBar('Below are LANs/VSWITCHes available to use.'); + $('#' + panelId).append(info); + } - // Resource tab ID - var tabId = 'zvmResourceTab'; - var info = $('#' + tabId).find('.ui-state-highlight'); - // If there is no info bar - if (!info.length) { - // Create info bar - info = createInfoBar('Below are disks and networks found by the hardware control point. It shows disk pools defined in the EXTENT CONTROL file and LANs|VSWITCHes available to use.'); - $('#' + tabId).append(info); - } + // Get datatable + var dTable = getNetworkDataTable(); + if (!dTable) { + // Create table + var tableId = 'zNetworkDataTable'; + var table = new DataTable(tableId); + table.init( [ 'HCP', 'Type', 'Name', 'Details' ]); - // Get datatable - var dTable = getNetworkDataTable(); - if (!dTable) { - // Create networks section - var fieldSet = $('
                                                              '); - var legend = $('Networks'); - fieldSet.append(legend); + // Append datatable to tab + $('#' + panelId).append(table.object()); - // Create table - var tableId = 'zNetworkDataTable'; - var table = new DataTable(tableId); - table.init( [ 'HCP', 'Type', 'Name', 'Details' ]); + // Turn into datatable + dTable = $('#' + tableId).dataTable(); + setNetworkDataTable(dTable); - // Append datatable to tab - fieldSet.append(table.object()); - $('#' + tabId).append(fieldSet); + // Set the column width + var cols = table.object().find('thead tr th'); + cols.eq(0).css('width', '20px'); // HCP column + cols.eq(1).css('width', '20px'); // Type column + cols.eq(2).css('width', '20px'); // Name column + cols.eq(3).css({'width': '600px'}); // Details column + } - // Turn into datatable - dTable = $('#' + tableId).dataTable(); - setNetworkDataTable(dTable); - - // Set the column width - var cols = table.object().find('thead tr th'); - cols.eq(0).css('width', '20px'); // HCP column - cols.eq(1).css('width', '20px'); // Type column - cols.eq(2).css('width', '20px'); // Name column - cols.eq(3).css({'width': '600px'}); // Details column - } - - // Skip index 0 because it contains nothing - var details = '
                                                              ';
                                                              -	for ( var i = 1; i < tmp.length; i++) {
                                                              -		details += tmp[i];
                                                              -	}
                                                              -	details += '
                                                              '; - - dTable.fnAddData( [ hcp, type, name, details ]); + // Skip index 0 because it contains nothing + var details = '
                                                              ';
                                                              +    for ( var i = 1; i < tmp.length; i++) {
                                                              +        details += tmp[i];
                                                              +    }
                                                              +    details += '
                                                              '; + + dTable.fnAddData([ '
                                                              ' + hcp + '
                                                              ', '
                                                              ' + type + '
                                                              ', '
                                                              ' + name + '
                                                              ', details ]); + + // Resize accordion + $('#zvmResourceAccordion').accordion('resize'); } /** * Connect a NIC to a Guest LAN * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function connect2GuestLan(data) { - var rsp = data.rsp; - var args = data.msg.split(';'); - var node = args[0].replace('node=', ''); - var address = args[1].replace('addr=', ''); - var lanName = args[2].replace('lan=', ''); - var lanOwner = args[3].replace('owner=', ''); - - // Write ajax response to status bar - var prg = writeRsp(rsp, node + ': '); - $('#' + node + 'StatusBar').find('div').append(prg); - - // Connect NIC to Guest LAN - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--connectnic2guestlan;' + address + ';' + lanName + ';' - + lanOwner, - msg : node - }, + var rsp = data.rsp; + var args = data.msg.split(';'); + var node = args[0].replace('node=', ''); + var address = args[1].replace('addr=', ''); + var lanName = args[2].replace('lan=', ''); + var lanOwner = args[3].replace('owner=', ''); + + // Write ajax response to status bar + var prg = writeRsp(rsp, node + ': '); + $('#' + node + 'StatusBar').find('div').append(prg); + + // Connect NIC to Guest LAN + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--connectnic2guestlan;' + address + ';' + lanName + ';' + + lanOwner, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); } /** * Connect a NIC to a VSwitch * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function connect2VSwitch(data) { - var rsp = data.rsp; - var args = data.msg.split(';'); - var node = args[0].replace('node=', ''); - var address = args[1].replace('addr=', ''); - var vswitchName = args[2].replace('vsw=', ''); - - // Write ajax response to status bar - var prg = writeRsp(rsp, node + ': '); - $('#' + node + 'StatusBar').find('div').append(prg); + var rsp = data.rsp; + var args = data.msg.split(';'); + var node = args[0].replace('node=', ''); + var address = args[1].replace('addr=', ''); + var vswitchName = args[2].replace('vsw=', ''); + + // Write ajax response to status bar + var prg = writeRsp(rsp, node + ': '); + $('#' + node + 'StatusBar').find('div').append(prg); - // Connect NIC to VSwitch - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chvm', - tgt : node, - args : '--connectnic2vswitch;' + address + ';' + vswitchName, - msg : node - }, + // Connect NIC to VSwitch + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chvm', + tgt : node, + args : '--connectnic2vswitch;' + address + ';' + vswitchName, + msg : node + }, - success : updateZNodeStatus - }); + success : updateZNodeStatus + }); } /** * Create provision existing node division * - * @param inst - * Provision tab instance + * @param inst Provision tab instance * @return Provision existing node division */ function createZProvisionExisting(inst) { - // Create provision existing and hide it - var provExisting = $('
                                                              ').hide(); - - var vmFS = $('
                                                              '); - var vmLegend = $('Virtual Machine'); - vmFS.append(vmLegend); - provExisting.append(vmFS); - - var vmAttr = $('
                                                              '); - vmFS.append($('
                                                              ')); - vmFS.append(vmAttr); - - var osFS = $('
                                                              '); - var osLegend = $('Operating System'); - osFS.append(osLegend); - provExisting.append(osFS); - - var osAttr = $('
                                                              '); - osFS.append($('
                                                              ')); - osFS.append(osAttr); - - // Create group input - var group = $('
                                                              '); - var groupLabel = $(''); - group.append(groupLabel); - - // Turn on auto complete for group - var groupNames = $.cookie('groups'); - if (groupNames) { - // Split group names into an array - var tmp = groupNames.split(','); - - // Create drop down for groups - var groupSelect = $(''); - groupSelect.append(''); - for (var i in tmp) { - // Add group into drop down - var opt = $(''); - groupSelect.append(opt); - } - group.append(groupSelect); - - // Create node datatable - groupSelect.change(function(){ - // Get group selected - var thisGroup = $(this).val(); - // If a valid group is selected - if (thisGroup) { - createNodesDatatable(thisGroup, 'zNodesDatatableDIV' + inst); - } - }); - } else { - // If no groups are cookied - var groupInput = $(''); - group.append(groupInput); - } - vmAttr.append(group); + // Create provision existing and hide it + var provExisting = $('
                                                              ').hide(); + + var vmFS = $('
                                                              '); + var vmLegend = $('Virtual Machine'); + vmFS.append(vmLegend); + provExisting.append(vmFS); + + var vmAttr = $('
                                                              '); + vmFS.append($('
                                                              ')); + vmFS.append(vmAttr); + + var osFS = $('
                                                              '); + var osLegend = $('Operating System'); + osFS.append(osLegend); + provExisting.append(osFS); + + var osAttr = $('
                                                              '); + osFS.append($('
                                                              ')); + osFS.append(osAttr); + + // Create group input + var group = $('
                                                              '); + var groupLabel = $(''); + group.append(groupLabel); + + // Turn on auto complete for group + var groupNames = $.cookie('groups'); + if (groupNames) { + // Split group names into an array + var tmp = groupNames.split(','); + + // Create drop down for groups + var groupSelect = $(''); + groupSelect.append(''); + for (var i in tmp) { + // Add group into drop down + var opt = $(''); + groupSelect.append(opt); + } + group.append(groupSelect); + + // Create node datatable + groupSelect.change(function(){ + // Get group selected + var thisGroup = $(this).val(); + // If a valid group is selected + if (thisGroup) { + createNodesDatatable(thisGroup, 'zNodesDatatableDIV' + inst); + } + }); + } else { + // If no groups are cookied + var groupInput = $(''); + group.append(groupInput); + } + vmAttr.append(group); - // Create node input - var node = $('
                                                              '); - var nodeLabel = $(''); - var nodeDatatable = $('

                                                              Select a group to view its nodes

                                                              '); - node.append(nodeLabel); - node.append(nodeDatatable); - vmAttr.append(node); - - // Create operating system image input - var os = $('
                                                              '); - var osLabel = $(''); - var osInput = $(''); - // Get image names on focus - osInput.one('focus', function(){ - var imageNames = $.cookie('imagenames'); - if (imageNames) { - // Turn on auto complete - $(this).autocomplete({ - source: imageNames.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - osAttr.append(os); - - // Create boot method drop down - var bootMethod = $('
                                                              '); - var methoddLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - ); - bootMethod.append(methoddLabel); - bootMethod.append(methodSelect); - osAttr.append(bootMethod); - - // Generate tooltips - provExisting.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - } - }); - - /** - * Provision existing - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - var ready = true; - var errMsg = ''; + // Create node input + var node = $('
                                                              '); + var nodeLabel = $(''); + var nodeDatatable = $('

                                                              Select a group to view its nodes

                                                              '); + node.append(nodeLabel); + node.append(nodeDatatable); + vmAttr.append(node); + + // Create operating system image input + var os = $('
                                                              '); + var osLabel = $(''); + var osInput = $(''); + // Get image names on focus + osInput.one('focus', function(){ + var imageNames = $.cookie('imagenames'); + if (imageNames) { + // Turn on auto complete + $(this).autocomplete({ + source: imageNames.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + osAttr.append(os); + + // Create boot method drop down + var bootMethod = $('
                                                              '); + var methoddLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + ); + bootMethod.append(methoddLabel); + bootMethod.append(methodSelect); + osAttr.append(bootMethod); + + // Generate tooltips + provExisting.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.7, + predelay: 800, + events: { + def: "mouseover,mouseout", + input: "mouseover,mouseout", + widget: "focus mouseover,blur mouseout", + tooltip: "mouseover,mouseout" + } + }); + + /** + * Provision existing + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + var ready = true; + var errMsg = ''; - // Get provision tab ID - var thisTabId = $(this).parent().parent().parent().attr('id'); - // Get provision tab instance - var inst = thisTabId.replace('zvmProvisionTab', ''); - - // Get nodes that were checked - var dTableId = 'zNodesDatatable' + inst; - var tgts = getNodesChecked(dTableId); - if (!tgts) { - errMsg += 'You need to select a node.
                                                              '; - ready = false; - } - - // Check operating system image - var os = $('#' + thisTabId + ' input[name=os]:visible'); - if (!os.val()) { - errMsg += 'You need to select a operating system image.'; - os.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - os.css('border', 'solid #BDBDBD 1px'); - } - - // If all inputs are valid, ready to provision - if (ready) { - // Disable provision button - $(this).attr('disabled', 'true'); - - // Show loader - $('#zProvisionStatBar' + inst).show(); - $('#zProvisionLoader' + inst).show(); + // Get provision tab ID + var thisTabId = $(this).parent().parent().parent().attr('id'); + // Get provision tab instance + var inst = thisTabId.replace('zvmProvisionTab', ''); + + // Get nodes that were checked + var dTableId = 'zNodesDatatable' + inst; + var tgts = getNodesChecked(dTableId); + if (!tgts) { + errMsg += 'You need to select a node.
                                                              '; + ready = false; + } + + // Check operating system image + var os = $('#' + thisTabId + ' input[name=os]:visible'); + if (!os.val()) { + errMsg += 'You need to select a operating system image.'; + os.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + os.css('border', 'solid #BDBDBD 1px'); + } + + // If all inputs are valid, ready to provision + if (ready) { + // Disable provision button + $(this).attr('disabled', 'true'); + + // Show loader + $('#zProvisionStatBar' + inst).show(); + $('#zProvisionLoader' + inst).show(); - // Disable all inputs - var inputs = $('#' + thisTabId + ' input:visible'); - inputs.attr('disabled', 'disabled'); - - // Disable all selects - var selects = $('#' + thisTabId + ' select'); - selects.attr('disabled', 'disabled'); - - // Get operating system image - var osImage = $('#' + thisTabId + ' input[name=os]:visible').val(); - var tmp = osImage.split('-'); - var os = tmp[0]; - var arch = tmp[1]; - var profile = tmp[3]; - - /** - * (1) Set operating system - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : tgts + ';noderes.netboot=zvm;nodetype.os=' + os + ';nodetype.arch=' + arch + ';nodetype.profile=' + profile, - msg : 'cmd=nodeadd;out=' + inst - }, + // Disable all inputs + var inputs = $('#' + thisTabId + ' input:visible'); + inputs.attr('disabled', 'disabled'); + + // Disable all selects + var selects = $('#' + thisTabId + ' select'); + selects.attr('disabled', 'disabled'); + + // Get operating system image + var osImage = $('#' + thisTabId + ' input[name=os]:visible').val(); + var tmp = osImage.split('-'); + var os = tmp[0]; + var arch = tmp[1]; + var profile = tmp[3]; + + /** + * (1) Set operating system + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : tgts + ';noderes.netboot=zvm;nodetype.os=' + os + ';nodetype.arch=' + arch + ';nodetype.profile=' + profile, + msg : 'cmd=nodeadd;out=' + inst + }, - success : updateZProvisionExistingStatus - }); - } else { - // Show warning message - var warn = createWarnBar(errMsg); - warn.prependTo($(this).parent().parent()); - } - }); - provExisting.append(provisionBtn); - - return provExisting; + success : updateZProvisionExistingStatus + }); + } else { + // Show warning message + var warn = createWarnBar(errMsg); + warn.prependTo($(this).parent().parent()); + } + }); + provExisting.append(provisionBtn); + + return provExisting; } /** * Create provision new node division * - * @param inst - * Provision tab instance + * @param inst Provision tab instance * @return Provision new node division */ function createZProvisionNew(inst) { - // Create provision new node division - var provNew = $('
                                                              '); - - // Create VM fieldset - var vmFS = $('
                                                              '); - var vmLegend = $('Virtual Machine'); - vmFS.append(vmLegend); - provNew.append(vmFS); - - var vmAttr = $('
                                                              '); - vmFS.append($('
                                                              ')); - vmFS.append(vmAttr); - - // Create OS fieldset - var osFS = $('
                                                              '); - var osLegend = $('Operating System'); - osFS.append(osLegend); - provNew.append(osFS); - - // Create hardware fieldset - var hwFS = $('
                                                              '); - var hwLegend = $('Hardware'); - hwFS.append(hwLegend); - provNew.append(hwFS); - - var hwAttr = $('
                                                              '); - hwFS.append($('
                                                              ')); - hwFS.append(hwAttr); - - var osAttr = $('
                                                              '); - osFS.append($('
                                                              ')); - osFS.append(osAttr); - - // Create group input - var group = $('
                                                              '); - var groupLabel = $(''); - var groupInput = $(''); - // Get groups on-focus - groupInput.one('focus', function(){ - var groupNames = $.cookie('groups'); - if (groupNames) { - // Turn on auto complete - $(this).autocomplete({ - source: groupNames.split(',') - }); - } - }); - group.append(groupLabel); - group.append(groupInput); - vmAttr.append(group); - - // Create node input - var nodeName = $('
                                                              '); - var nodeLabel = $(''); - var nodeInput = $(''); - nodeName.append(nodeLabel); - nodeName.append(nodeInput); - vmAttr.append(nodeName); - - // Create user ID input - var userId = $('
                                                              '); - vmAttr.append(userId); - - // Create hardware control point input - var hcpDiv = $('
                                                              '); - var hcpLabel = $(''); - var hcpInput = $(''); - hcpInput.blur(function() { - if ($(this).val()) { - var args = $(this).val().split('.'); - if (!$.cookie(args[0] + 'diskpools')) { - // Get disk pools - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsvm', - tgt : args[0], - args : '--diskpoolnames', - msg : args[0] - }, + // Create provision new node division + var provNew = $('
                                                              '); - success : setDiskPoolCookies - }); - } - } - }); - hcpDiv.append(hcpLabel); - hcpDiv.append(hcpInput); - vmAttr.append(hcpDiv); - - // Create an advanced link to set IP address and hostname - var advancedLnk = $(''); - vmAttr.append(advancedLnk); - var advanced = $('
                                                              ').hide(); - vmAttr.append(advanced); - - var ip = $('
                                                              '); - advanced.append(ip); - var hostname = $('
                                                              '); - advanced.append(hostname); - - // Show IP address and hostname inputs on-click - advancedLnk.click(function() { - advanced.toggle(); - }); + // Create VM fieldset + var vmFS = $('
                                                              '); + var vmLegend = $('Virtual Machine'); + vmFS.append(vmLegend); + provNew.append(vmFS); + + var vmAttr = $('
                                                              '); + vmFS.append($('
                                                              ')); + vmFS.append(vmAttr); + + // Create OS fieldset + var osFS = $('
                                                              '); + var osLegend = $('Operating System'); + osFS.append(osLegend); + provNew.append(osFS); + + // Create hardware fieldset + var hwFS = $('
                                                              '); + var hwLegend = $('Hardware'); + hwFS.append(hwLegend); + provNew.append(hwFS); + + var hwAttr = $('
                                                              '); + hwFS.append($('
                                                              ')); + hwFS.append(hwAttr); + + var osAttr = $('
                                                              '); + osFS.append($('
                                                              ')); + osFS.append(osAttr); + + // Create group input + var group = $('
                                                              '); + var groupLabel = $(''); + var groupInput = $(''); + // Get groups on-focus + groupInput.one('focus', function(){ + var groupNames = $.cookie('groups'); + if (groupNames) { + // Turn on auto complete + $(this).autocomplete({ + source: groupNames.split(',') + }); + } + }); + group.append(groupLabel); + group.append(groupInput); + vmAttr.append(group); + + // Create node input + var nodeName = $('
                                                              '); + var nodeLabel = $(''); + var nodeInput = $(''); + nodeName.append(nodeLabel); + nodeName.append(nodeInput); + vmAttr.append(nodeName); - // Create operating system image input - var os = $('
                                                              '); - var osLabel = $(''); - var osInput = $(''); - // Get image names on focus - osInput.one('focus', function(){ - var imageNames = $.cookie('imagenames'); - if (imageNames) { - // Turn on auto complete - $(this).autocomplete({ - source: imageNames.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - osAttr.append(os); + // Create user ID input + var userId = $('
                                                              '); + vmAttr.append(userId); - // Create user entry input - var defaultChkbox = $('').click(function() { - // Remove any warning messages - $(this).parents('.form').find('.ui-state-error').remove(); - - // Get tab ID - var thisTabId = $(this).parents('.ui-tabs-panel').attr('id'); - - // Get objects for HCP, user ID, and OS - var hcp = $('#' + thisTabId + ' input[name=hcp]'); - var userId = $('#' + thisTabId + ' input[name=userId]'); - var os = $('#' + thisTabId + ' input[name=os]'); - - // Get default user entry when clicked - if ($(this).attr('checked')) { - if (!hcp.val() || !os.val() || !userId.val()) { - // Show warning message - var warn = createWarnBar('Please specify the hardware control point, operating system, and user ID before checking this box'); - warn.prependTo($(this).parents('.form')); - - // Highlight empty fields - jQuery.each([hcp, os, userId], function() { - if (!$(this).val()) { - $(this).css('border', 'solid #FF0000 1px'); - } - }); - } else { - // Un-highlight empty fields - jQuery.each([hcp, os, userId], function() { - $(this).css('border', 'solid #BDBDBD 1px'); - }); + // Create hardware control point input + var hcpDiv = $('
                                                              '); + var hcpLabel = $(''); + var hcpInput = $(''); + hcpInput.blur(function() { + if ($(this).val()) { + var args = $(this).val().split('.'); + if (!$.cookie(args[0] + 'diskpools')) { + // Get disk pools + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsvm', + tgt : args[0], + args : '--diskpoolnames', + msg : args[0] + }, + + success : setDiskPoolCookies + }); + } + } + }); + hcpDiv.append(hcpLabel); + hcpDiv.append(hcpInput); + vmAttr.append(hcpDiv); + + // Create an advanced link to set IP address and hostname + var advancedLnk = $(''); + vmAttr.append(advancedLnk); + var advanced = $('
                                                              ').hide(); + vmAttr.append(advanced); + + var ip = $('
                                                              '); + advanced.append(ip); + var hostname = $('
                                                              '); + advanced.append(hostname); + + // Show IP address and hostname inputs on-click + advancedLnk.click(function() { + advanced.toggle(); + }); - // Get profile name - var tmp = os.val().split('-'); - var profile = tmp[3]; - - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'getdefaultuserentry;' + hcp.val() + ';' + profile, - msg : thisTabId - }, - - success:function(data) { - // Populate user entry - var tabId = data.msg; - var entry = new String(data.rsp); - var userId = $('#' + tabId + ' input[name=userId]').val(); - entry = entry.replace(new RegExp('LXUSR', 'g'), userId); - $('#' + tabId + ' textarea:visible').val(entry); - } - }); - } - } else { - $('#' + thisTabId + ' textarea:visible').val(''); - - // Un-highlight empty fields - jQuery.each([hcp, os, userId], function() { - $(this).css('border', 'solid #BDBDBD 1px'); - }); - } - }); - var userEntry = $('
                                                              '); - userEntry.append($('').append(defaultChkbox, 'Use default')); - hwAttr.append(userEntry); + // Create operating system image input + var os = $('
                                                              '); + var osLabel = $(''); + var osInput = $(''); + // Get image names on focus + osInput.one('focus', function(){ + var imageNames = $.cookie('imagenames'); + if (imageNames) { + // Turn on auto complete + $(this).autocomplete({ + source: imageNames.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + osAttr.append(os); - // Create disk table - var diskDiv = $('
                                                              '); - var diskLabel = $(''); - var diskTable = $('
                                                              '); - var diskHeader = $(' Type Address Size Mode Pool Password '); - // Adjust header width - diskHeader.find('th').css( { - 'width' : '80px' - }); - diskHeader.find('th').eq(0).css( { - 'width' : '20px' - }); - var diskBody = $(''); - var diskFooter = $(''); + // Create user entry input + var defaultChkbox = $('').click(function() { + // Remove any warning messages + $(this).parents('.form').find('.ui-state-error').remove(); + + // Get tab ID + var thisTabId = $(this).parents('.ui-tabs-panel').attr('id'); + + // Get objects for HCP, user ID, and OS + var userId = $('#' + thisTabId + ' input[name=userId]'); + var os = $('#' + thisTabId + ' input[name=os]'); + + // Get default user entry when clicked + if ($(this).attr('checked')) { + if (!os.val() || !userId.val()) { + // Show warning message + var warn = createWarnBar('Please specify the operating system and user ID before checking this box'); + warn.prependTo($(this).parents('.form')); + + // Highlight empty fields + jQuery.each([os, userId], function() { + if (!$(this).val()) { + $(this).css('border', 'solid #FF0000 1px'); + } + }); + } else { + // Un-highlight empty fields + jQuery.each([os, userId], function() { + $(this).css('border', 'solid #BDBDBD 1px'); + }); - /** - * Add disks - */ - var addDiskLink = $('Add disk'); - addDiskLink.bind('click', function(event) { - // Create a row - var diskRow = $(''); + // Get profile name + var tmp = os.val().split('-'); + var profile = tmp[3]; + + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'getdefaultuserentry;' + profile, + msg : thisTabId + }, + + success:function(data) { + // Populate user entry + var tabId = data.msg; + var entry = new String(data.rsp); + var userId = $('#' + tabId + ' input[name=userId]').val(); + entry = entry.replace(new RegExp('LXUSR', 'g'), userId); + $('#' + tabId + ' textarea:visible').val(entry); + } + }); + } + } else { + $('#' + thisTabId + ' textarea:visible').val(''); + + // Un-highlight empty fields + jQuery.each([os, userId], function() { + $(this).css('border', 'solid #BDBDBD 1px'); + }); + } + }); + var userEntry = $('
                                                              '); + userEntry.append($('').append(defaultChkbox, 'Use default')); + hwAttr.append(userEntry); - // Add remove button - var removeBtn = $(''); - var col = $('').append(removeBtn); - removeBtn.bind('click', function(event) { - diskRow.remove(); - }); - diskRow.append(col); + // Create disk table + var diskDiv = $('
                                                              '); + var diskLabel = $(''); + var diskTable = $('
                                                              '); + var diskHeader = $(' Type Address Size Mode Pool Password '); + // Adjust header width + diskHeader.find('th').css( { + 'width' : '80px' + }); + diskHeader.find('th').eq(0).css( { + 'width' : '20px' + }); + var diskBody = $(''); + var diskFooter = $(''); - // Create disk type drop down - var diskType = $(''); - var diskTypeSelect = $(''); - diskTypeSelect.append('' - + '' - ); - diskType.append(diskTypeSelect); - diskRow.append(diskType); + /** + * Add disks + */ + var addDiskLink = $('Add disk'); + addDiskLink.bind('click', function(event) { + // Create a row + var diskRow = $(''); - // Create disk address input - var diskAddr = $(''); - diskRow.append(diskAddr); + // Add remove button + var removeBtn = $(''); + var col = $('').append(removeBtn); + removeBtn.bind('click', function(event) { + diskRow.remove(); + }); + diskRow.append(col); - // Create disk size input - var diskSize = $(''); - diskRow.append(diskSize); - - // Create disk mode input - var diskMode = $(''); - var diskModeSelect = $(''); - diskModeSelect.append('' - + '' - + '' - + '' - + '' - + '' - + '' - ); - diskMode.append(diskModeSelect); - diskRow.append(diskMode); + // Create disk type drop down + var diskType = $(''); + var diskTypeSelect = $(''); + diskTypeSelect.append('' + + '' + ); + diskType.append(diskTypeSelect); + diskRow.append(diskType); - // Get list of disk pools - var thisTabId = $(this).parents('.tab').attr('id'); - var thisHcp = $('#' + thisTabId + ' input[name=hcp]').val(); - var definedPools; - if (thisHcp) { - // Get node without domain name - var temp = thisHcp.split('.'); - definedPools = $.cookie(temp[0] + 'diskpools'); - } + // Create disk address input + var diskAddr = $(''); + diskRow.append(diskAddr); - // Create disk pool input - // Turn on auto complete for disk pool - var diskPoolInput = $('').autocomplete({ - source: definedPools.split(',') - }); - var diskPool = $('').append(diskPoolInput); - diskRow.append(diskPool); + // Create disk size input + var diskSize = $(''); + diskRow.append(diskSize); + + // Create disk mode input + var diskMode = $(''); + var diskModeSelect = $(''); + diskModeSelect.append('' + + '' + + '' + + '' + + '' + + '' + + '' + ); + diskMode.append(diskModeSelect); + diskRow.append(diskMode); - // Create disk password input - var diskPw = $(''); - diskRow.append(diskPw); + // Get list of disk pools + var thisTabId = $(this).parents('.tab').attr('id'); + var thisHcp = $('#' + thisTabId + ' input[name=hcp]').val(); + var definedPools = null; + if (thisHcp) { + // Get node without domain name + var temp = thisHcp.split('.'); + definedPools = $.cookie(temp[0] + 'diskpools'); + } - diskBody.append(diskRow); - - // Generate tooltips - diskBody.find('td input[title]').tooltip({ - position: "top right", - offset: [-4, 4], - effect: "fade", - opacity: 0.7, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - } - }); - }); - - // Create disk table - diskFooter.append(addDiskLink); - diskTable.append(diskHeader); - diskTable.append(diskBody); - diskTable.append(diskFooter); - - diskDiv.append(diskLabel); - diskDiv.append(diskTable); - hwAttr.append(diskDiv); - - // Generate tooltips - provNew.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - } - }); - - /** - * Provision new - */ - var provisionBtn = createButton('Provision'); - provisionBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - var ready = true; - var errMsg = ''; + // Create disk pool input + // Turn on auto complete for disk pool + var diskPoolInput = $('').autocomplete({ + source: definedPools.split(',') + }); + var diskPool = $('').append(diskPoolInput); + diskRow.append(diskPool); - // Get tab ID - var thisTabId = $(this).parents('.ui-tabs-panel').attr('id'); - // Get provision tab instance - var inst = thisTabId.replace('zvmProvisionTab', ''); + // Create disk password input + var diskPw = $(''); + diskRow.append(diskPw); - // Check node name, userId, hardware control point, and group - var inputs = $('#' + thisTabId + ' input:visible'); - for ( var i = 0; i < inputs.length; i++) { - // Do not check OS or disk password - if (!inputs.eq(i).val() - && inputs.eq(i).attr('name') != 'os' - && inputs.eq(i).attr('type') != 'password') { - inputs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - inputs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } + diskBody.append(diskRow); + + // Generate tooltips + diskBody.find('td input[title]').tooltip({ + position: "top right", + offset: [-4, 4], + effect: "fade", + opacity: 0.7, + predelay: 800, + events: { + def: "mouseover,mouseout", + input: "mouseover,mouseout", + widget: "focus mouseover,blur mouseout", + tooltip: "mouseover,mouseout" + } + }); + }); + + // Create disk table + diskFooter.append(addDiskLink); + diskTable.append(diskHeader); + diskTable.append(diskBody); + diskTable.append(diskFooter); + + diskDiv.append(diskLabel); + diskDiv.append(diskTable); + hwAttr.append(diskDiv); + + // Generate tooltips + provNew.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.7, + predelay: 800, + events: { + def: "mouseover,mouseout", + input: "mouseover,mouseout", + widget: "focus mouseover,blur mouseout", + tooltip: "mouseover,mouseout" + } + }); + + /** + * Provision new + */ + var provisionBtn = createButton('Provision'); + provisionBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + var ready = true; + var errMsg = ''; - // Check user entry - var thisUserEntry = $('#' + thisTabId + ' textarea:visible'); - thisUserEntry.val(thisUserEntry.val().toUpperCase()); - if (!thisUserEntry.val()) { - thisUserEntry.css('border', 'solid #FF0000 1px'); - ready = false; - } else { - thisUserEntry.css('border', 'solid #BDBDBD 1px'); - } - - // Show error message for missing inputs - if (!ready) { - errMsg = errMsg + 'Please provide a value for each missing field.
                                                              '; - } + // Get tab ID + var thisTabId = $(this).parents('.ui-tabs-panel').attr('id'); + // Get provision tab instance + var inst = thisTabId.replace('zvmProvisionTab', ''); - // Check if user entry contains user ID - var thisUserId = $('#' + thisTabId + ' input[name=userId]:visible'); - var pos = thisUserEntry.val().indexOf('USER ' + thisUserId.val().toUpperCase()); - if (pos < 0) { - errMsg = errMsg + 'The directory entry does not contain the correct user ID.
                                                              '; - ready = false; - } + // Check node name, userId, hardware control point, and group + var inputs = $('#' + thisTabId + ' input:visible'); + for ( var i = 0; i < inputs.length; i++) { + // Do not check OS or disk password + if (!inputs.eq(i).val() + && inputs.eq(i).attr('name') != 'os' + && inputs.eq(i).attr('type') != 'password') { + inputs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + inputs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } - // If no operating system is specified, create only user entry - os = $('#' + thisTabId + ' input[name=os]:visible'); - - // Check number of disks - var diskRows = $('#' + thisTabId + ' table tr'); - // If an OS is given, disks are needed - if (os.val() && (diskRows.length < 1)) { - errMsg = errMsg + 'You need to add at some disks.
                                                              '; - ready = false; - } + // Check user entry + var thisUserEntry = $('#' + thisTabId + ' textarea:visible'); + thisUserEntry.val(thisUserEntry.val().toUpperCase()); + if (!thisUserEntry.val()) { + thisUserEntry.css('border', 'solid #FF0000 1px'); + ready = false; + } else { + thisUserEntry.css('border', 'solid #BDBDBD 1px'); + } + + // Show error message for missing inputs + if (!ready) { + errMsg = errMsg + 'Please provide a value for each missing field.
                                                              '; + } - // Check address, size, mode, pool, and password - var diskArgs = $('#' + thisTabId + ' table input:visible'); - for ( var i = 0; i < diskArgs.length; i++) { - if (!diskArgs.eq(i).val() - && diskArgs.eq(i).attr('type') != 'password') { - diskArgs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - diskArgs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } - - // If inputs are valid, ready to provision - if (ready) { - if (!os.val()) { - // If no OS is given, create a virtual server - var msg = ''; - if (diskRows.length > 0) { - msg = 'Do you want to create a virtual server without an operating system?'; - } else { - // If no disks are given, create a virtual server (no disk) - msg = 'Do you want to create a virtual server without an operating system or disks?'; - } + // Check if user entry contains user ID + var thisUserId = $('#' + thisTabId + ' input[name=userId]:visible'); + var pos = thisUserEntry.val().indexOf('USER ' + thisUserId.val().toUpperCase()); + if (pos < 0) { + errMsg = errMsg + 'The directory entry does not contain the correct user ID.
                                                              '; + ready = false; + } - // Open dialog to confirm - var confirmDialog = $('

                                                              ' + msg + '

                                                              '); - confirmDialog.dialog({ - title:'Confirm', - modal: true, - width: 400, - buttons: { - "Ok": function(){ - // Disable provision button - provisionBtn.attr('disabled', 'true'); - - // Show loader - $('#zProvisionStatBar' + inst).show(); - $('#zProvisionLoader' + inst).show(); + // If no operating system is specified, create only user entry + os = $('#' + thisTabId + ' input[name=os]:visible'); + + // Check number of disks + var diskRows = $('#' + thisTabId + ' table tr'); + // If an OS is given, disks are needed + if (os.val() && (diskRows.length < 1)) { + errMsg = errMsg + 'You need to add at some disks.
                                                              '; + ready = false; + } - // Disable add disk button - addDiskLink.attr('disabled', 'true'); - - // Disable close button on disk table - $('#' + thisTabId + ' table span').unbind('click'); - - // Disable all inputs - var inputs = $('#' + thisTabId + ' input'); - inputs.attr('disabled', 'disabled'); - - // Disable all selects - var selects = $('#' + thisTabId + ' select'); - selects.attr('disabled', 'disabled'); - - // Add a new line at the end of the user entry - var textarea = $('#' + thisTabId + ' textarea'); - var tmp = jQuery.trim(textarea.val()); - textarea.val(tmp + '\n'); - textarea.attr('readonly', 'readonly'); - textarea.css( { - 'background-color' : '#F2F2F2' - }); + // Check address, size, mode, pool, and password + var diskArgs = $('#' + thisTabId + ' table input:visible'); + for ( var i = 0; i < diskArgs.length; i++) { + if (!diskArgs.eq(i).val() + && diskArgs.eq(i).attr('type') != 'password') { + diskArgs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + diskArgs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } + + // If inputs are valid, ready to provision + if (ready) { + if (!os.val()) { + // If no OS is given, create a virtual server + var msg = ''; + if (diskRows.length > 0) { + msg = 'Do you want to create a virtual server without an operating system?'; + } else { + // If no disks are given, create a virtual server (no disk) + msg = 'Do you want to create a virtual server without an operating system or disks?'; + } - // Get node name - var node = $('#' + thisTabId + ' input[name=nodeName]').val(); - // Get userId - var userId = $('#' + thisTabId + ' input[name=userId]').val(); - // Get hardware control point - var hcp = $('#' + thisTabId + ' input[name=hcp]').val(); - // Get group - var group = $('#' + thisTabId + ' input[name=group]').val(); - // Get IP address and hostname - var ip = $('#' + thisTabId + ' input[name=ip]').val(); - var hostname = $('#' + thisTabId + ' input[name=hostname]').val(); - - // Generate arguments to sent - var args = node + ';zvm.hcp=' + hcp - + ';zvm.userid=' + userId - + ';nodehm.mgt=zvm' - + ';groups=' + group; - if (ip) - args += ';hosts.ip=' + ip; - - if (hostname) - args += ';hosts.hostnames=' + hostname; + // Open dialog to confirm + var confirmDialog = $('

                                                              ' + msg + '

                                                              '); + confirmDialog.dialog({ + title:'Confirm', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function(){ + // Disable provision button + provisionBtn.attr('disabled', 'true'); + + // Show loader + $('#zProvisionStatBar' + inst).show(); + $('#zProvisionLoader' + inst).show(); - /** - * (1) Define node - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : args, - msg : 'cmd=nodeadd;out=' + inst - }, + // Disable add disk button + addDiskLink.attr('disabled', 'true'); + + // Disable close button on disk table + $('#' + thisTabId + ' table span').unbind('click'); + + // Disable all inputs + var inputs = $('#' + thisTabId + ' input'); + inputs.attr('disabled', 'disabled'); + + // Disable all selects + var selects = $('#' + thisTabId + ' select'); + selects.attr('disabled', 'disabled'); + + // Add a new line at the end of the user entry + var textarea = $('#' + thisTabId + ' textarea'); + var tmp = jQuery.trim(textarea.val()); + textarea.val(tmp + '\n'); + textarea.attr('readonly', 'readonly'); + textarea.css( { + 'background-color' : '#F2F2F2' + }); - success : updateZProvisionNewStatus - }); - - $(this).dialog("close"); - }, - "Cancel": function() { - $(this).dialog("close"); - } - } - }); - } else { - /** - * Create a virtual server and install OS - */ + // Get node name + var node = $('#' + thisTabId + ' input[name=nodeName]').val(); + // Get userId + var userId = $('#' + thisTabId + ' input[name=userId]').val(); + // Get hardware control point + var hcp = $('#' + thisTabId + ' input[name=hcp]').val(); + // Get group + var group = $('#' + thisTabId + ' input[name=group]').val(); + // Get IP address and hostname + var ip = $('#' + thisTabId + ' input[name=ip]').val(); + var hostname = $('#' + thisTabId + ' input[name=hostname]').val(); + + // Generate arguments to sent + var args = node + ';zvm.hcp=' + hcp + + ';zvm.userid=' + userId + + ';nodehm.mgt=zvm' + + ';groups=' + group; + if (ip) + args += ';hosts.ip=' + ip; + + if (hostname) + args += ';hosts.hostnames=' + hostname; - // Disable provision button - $(this).attr('disabled', 'true'); - - // Show loader - $('#zProvisionStatBar' + inst).show(); - $('#zProvisionLoader' + inst).show(); + /** + * (1) Define node + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : args, + msg : 'cmd=nodeadd;out=' + inst + }, - // Disable add disk button - addDiskLink.attr('disabled', 'true'); - - // Disable close button on disk table - $('#' + thisTabId + ' table span').unbind('click'); + success : updateZProvisionNewStatus + }); + + $(this).dialog("close"); + }, + "Cancel": function() { + $(this).dialog("close"); + } + } + }); + } else { + /** + * Create a virtual server and install OS + */ - // Disable all inputs - var inputs = $('#' + thisTabId + ' input'); - inputs.attr('disabled', 'disabled'); - inputs.css( { - 'background-color' : '#F2F2F2' - }); - - // Disable all selects - var selects = $('#' + thisTabId + ' select'); - selects.attr('disabled', 'disabled'); - selects.css( { - 'background-color' : '#F2F2F2' - }); - - // Add a new line at the end of the user entry - var textarea = $('#' + thisTabId + ' textarea'); - var tmp = jQuery.trim(textarea.val()); - textarea.val(tmp + '\n'); - textarea.attr('readonly', 'readonly'); - textarea.css( { - 'background-color' : '#F2F2F2' - }); + // Disable provision button + $(this).attr('disabled', 'true'); + + // Show loader + $('#zProvisionStatBar' + inst).show(); + $('#zProvisionLoader' + inst).show(); - // Get node name - var node = $('#' + thisTabId + ' input[name=nodeName]').val(); - // Get userId - var userId = $('#' + thisTabId + ' input[name=userId]').val(); - // Get hardware control point - var hcp = $('#' + thisTabId + ' input[name=hcp]').val(); - // Get group - var group = $('#' + thisTabId + ' input[name=group]').val(); - // Get IP address and hostname - var ip = $('#' + thisTabId + ' input[name=ip]').val(); - var hostname = $('#' + thisTabId + ' input[name=hostname]').val(); - - // Generate arguments to sent - var args = node + ';zvm.hcp=' + hcp - + ';zvm.userid=' + userId - + ';nodehm.mgt=zvm' - + ';groups=' + group; - if (ip) - args += ';hosts.ip=' + ip; - - if (hostname) - args += ';hosts.hostnames=' + hostname; + // Disable add disk button + addDiskLink.attr('disabled', 'true'); + + // Disable close button on disk table + $('#' + thisTabId + ' table span').unbind('click'); - /** - * (1) Define node - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : args, - msg : 'cmd=nodeadd;out=' + inst - }, + // Disable all inputs + var inputs = $('#' + thisTabId + ' input'); + inputs.attr('disabled', 'disabled'); + inputs.css( { + 'background-color' : '#F2F2F2' + }); + + // Disable all selects + var selects = $('#' + thisTabId + ' select'); + selects.attr('disabled', 'disabled'); + selects.css( { + 'background-color' : '#F2F2F2' + }); + + // Add a new line at the end of the user entry + var textarea = $('#' + thisTabId + ' textarea'); + var tmp = jQuery.trim(textarea.val()); + textarea.val(tmp + '\n'); + textarea.attr('readonly', 'readonly'); + textarea.css( { + 'background-color' : '#F2F2F2' + }); - success : updateZProvisionNewStatus - }); - } - } else { - // Show warning message - var warn = createWarnBar(errMsg); - warn.prependTo($(this).parent().parent()); - } - }); - provNew.append(provisionBtn); - - return provNew; + // Get node name + var node = $('#' + thisTabId + ' input[name=nodeName]').val(); + // Get userId + var userId = $('#' + thisTabId + ' input[name=userId]').val(); + // Get hardware control point + var hcp = $('#' + thisTabId + ' input[name=hcp]').val(); + // Get group + var group = $('#' + thisTabId + ' input[name=group]').val(); + // Get IP address and hostname + var ip = $('#' + thisTabId + ' input[name=ip]').val(); + var hostname = $('#' + thisTabId + ' input[name=hostname]').val(); + + // Generate arguments to sent + var args = node + ';zvm.hcp=' + hcp + + ';zvm.userid=' + userId + + ';nodehm.mgt=zvm' + + ';groups=' + group; + if (ip) + args += ';hosts.ip=' + ip; + + if (hostname) + args += ';hosts.hostnames=' + hostname; + + /** + * (1) Define node + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : args, + msg : 'cmd=nodeadd;out=' + inst + }, + + success : updateZProvisionNewStatus + }); + } + } else { + // Show warning message + var warn = createWarnBar(errMsg); + warn.prependTo($(this).parent().parent()); + } + }); + provNew.append(provisionBtn); + + return provNew; } /** * Load zVMs into column (service page) * - * @param col - * Table column where OS images will be placed - * @return Nothing + * @param col Table column where OS images will be placed */ function loadzVMs(col) { - // Get group names and description and append to group column - var groupNames = $.cookie('srv_zvms').split(','); - var radio, zvmBlock, args, zvm, hcp; - for (var i in groupNames) { - args = groupNames[i].split(':'); - zvm = args[0]; - hcp = args[1]; - - // Create block for each group - zvmBlock = $('
                                                              ').css({ - 'border': '1px solid', - 'max-width': '200px', - 'margin': '5px auto', - 'padding': '5px', - 'display': 'block', - 'vertical-align': 'middle', - 'cursor': 'pointer', - 'white-space': 'normal' - }).click(function(){ - $(this).children('input:radio').attr('checked', 'checked'); - $(this).parents('td').find('div').attr('class', 'ui-state-default'); - $(this).attr('class', 'ui-state-active'); - }); - radio = $('').css('display', 'none'); - zvmBlock.append(radio, $('' + zvm + ' managed by ' + hcp + '')); - zvmBlock.children('span').css({ - 'display': 'block', - 'margin': '5px', - 'text-align': 'left' - }); - col.append(zvmBlock); - } + // Get group names and description and append to group column + var groupNames = $.cookie('srv_zvms').split(','); + var radio, zvmBlock, args, zvm, hcp; + for (var i in groupNames) { + args = groupNames[i].split(':'); + zvm = args[0]; + hcp = args[1]; + + // Create block for each group + zvmBlock = $('
                                                              ').css({ + 'border': '1px solid', + 'max-width': '200px', + 'margin': '5px auto', + 'padding': '5px', + 'display': 'block', + 'vertical-align': 'middle', + 'cursor': 'pointer', + 'white-space': 'normal' + }).click(function(){ + $(this).children('input:radio').attr('checked', 'checked'); + $(this).parents('td').find('div').attr('class', 'ui-state-default'); + $(this).attr('class', 'ui-state-active'); + }); + radio = $('').css('display', 'none'); + zvmBlock.append(radio, $('' + zvm + ' managed by ' + hcp + '')); + zvmBlock.children('span').css({ + 'display': 'block', + 'margin': '5px', + 'text-align': 'left' + }); + col.append(zvmBlock); + } } /** * Load groups into column * - * @param col - * Table column where OS images will be placed - * @return Nothing + * @param col Table column where OS images will be placed */ function loadSrvGroups(col) { - // Get group names and description and append to group column - var groupNames = $.cookie('srv_groups').split(','); - var groupBlock, radio, args, name, ip, hostname, desc; - for (var i in groupNames) { - args = groupNames[i].split(':'); - name = args[0]; - ip = args[1]; - hostname = args[2]; - desc = args[3]; - - // Create block for each group - groupBlock = $('
                                                              ').css({ - 'border': '1px solid', - 'max-width': '200px', - 'margin': '5px auto', - 'padding': '5px', - 'display': 'block', - 'vertical-align': 'middle', - 'cursor': 'pointer', - 'white-space': 'normal' - }).click(function(){ - $(this).children('input:radio').attr('checked', 'checked'); - $(this).parents('td').find('div').attr('class', 'ui-state-default'); - $(this).attr('class', 'ui-state-active'); - }); - radio = $('').css('display', 'none'); - groupBlock.append(radio, $('' + name + ': ' + desc + '')); - groupBlock.children('span').css({ - 'display': 'block', - 'margin': '5px', - 'text-align': 'left' - }); - col.append(groupBlock); - } + // Get group names and description and append to group column + var groupNames = $.cookie('srv_groups').split(','); + var groupBlock, radio, args, name, ip, hostname, desc; + for (var i in groupNames) { + args = groupNames[i].split(':'); + name = args[0]; + ip = args[1]; + hostname = args[2]; + desc = args[3]; + + // Create block for each group + groupBlock = $('
                                                              ').css({ + 'border': '1px solid', + 'max-width': '200px', + 'margin': '5px auto', + 'padding': '5px', + 'display': 'block', + 'vertical-align': 'middle', + 'cursor': 'pointer', + 'white-space': 'normal' + }).click(function(){ + $(this).children('input:radio').attr('checked', 'checked'); + $(this).parents('td').find('div').attr('class', 'ui-state-default'); + $(this).attr('class', 'ui-state-active'); + }); + radio = $('').css('display', 'none'); + groupBlock.append(radio, $('' + name + ': ' + desc + '')); + groupBlock.children('span').css({ + 'display': 'block', + 'margin': '5px', + 'text-align': 'left' + }); + col.append(groupBlock); + } } /** * Load OS images into column * - * @param col - * Table column where OS images will be placed - * @return Nothing + * @param col Table column where OS images will be placed */ function loadOSImages(col) { - // Get group names and description and append to group column - var imgNames = $.cookie('srv_imagenames').split(','); - var imgBlock, radio, args, name, desc; - for (var i in imgNames) { - args = imgNames[i].split(':'); - name = args[0]; - desc = args[1]; - - // Create block for each image - imgBlock = $('
                                                              ').css({ - 'border': '1px solid', - 'max-width': '200px', - 'margin': '5px auto', - 'padding': '5px', - 'display': 'block', - 'vertical-align': 'middle', - 'cursor': 'pointer', - 'white-space': 'normal' - }).click(function(){ - $(this).children('input:radio').attr('checked', 'checked'); - $(this).parents('td').find('div').attr('class', 'ui-state-default'); - $(this).attr('class', 'ui-state-active'); - }); - radio = $('').css('display', 'none'); - imgBlock.append(radio, $('' + name + ': ' + desc + '')); - imgBlock.children('span').css({ - 'display': 'block', - 'margin': '5px', - 'text-align': 'left' - }); - col.append(imgBlock); - } + // Get group names and description and append to group column + var imgNames = $.cookie('srv_imagenames').split(','); + var imgBlock, radio, args, name, desc; + for (var i in imgNames) { + args = imgNames[i].split(':'); + name = args[0]; + desc = args[1]; + + // Create block for each image + imgBlock = $('
                                                              ').css({ + 'border': '1px solid', + 'max-width': '200px', + 'margin': '5px auto', + 'padding': '5px', + 'display': 'block', + 'vertical-align': 'middle', + 'cursor': 'pointer', + 'white-space': 'normal' + }).click(function(){ + $(this).children('input:radio').attr('checked', 'checked'); + $(this).parents('td').find('div').attr('class', 'ui-state-default'); + $(this).attr('class', 'ui-state-active'); + }); + radio = $('').css('display', 'none'); + imgBlock.append(radio, $('' + name + ': ' + desc + '')); + imgBlock.children('span').css({ + 'display': 'block', + 'margin': '5px', + 'text-align': 'left' + }); + col.append(imgBlock); + } } /** * Set a cookie for zVM host names (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function setzVMCookies(data) { - if (data.rsp) { - var zvms = new Array(); - for ( var i = 0; i < data.rsp.length; i++) { - zvms.push(data.rsp[i]); - } - - // Set cookie to expire in 60 minutes - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie('srv_zvms', zvms, { expires: exDate }); - } + if (data.rsp) { + var zvms = new Array(); + for ( var i = 0; i < data.rsp.length; i++) { + zvms.push(data.rsp[i]); + } + + // Set cookie to expire in 60 minutes + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie('srv_zvms', zvms, { expires: exDate }); + } } /** * Set a cookie for disk pool names of a given node (service page) * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function setDiskPoolCookies(data) { - if (data.rsp) { - var node = data.msg; - var pools = data.rsp[0].split(node + ': '); - for (var i in pools) { - pools[i] = jQuery.trim(pools[i]); - } - - // Set cookie to expire in 60 minutes - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie(node + 'diskpools', pools, { expires: exDate }); - } + if (data.rsp) { + var node = data.msg; + var pools = data.rsp[0].split(node + ': '); + for (var i in pools) { + pools[i] = jQuery.trim(pools[i]); + } + + // Set cookie to expire in 60 minutes + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie(node + 'diskpools', pools, { expires: exDate }); + } } /** * Create virtual machine (service page) * - * @param tabId - * Tab ID - * @param group - * Group - * @param hcp - * Hardware control point - * @param img - * OS image - * @return Nothing + * @param tabId Tab ID + * @param group Group + * @param hcp Hardware control point + * @param img OS image */ function createzVM(tabId, group, hcp, img, owner) { - // Submit request to create VM - // webportal provzlinux [group] [hcp] [image] [owner] - var iframe = createIFrame('lib/srv_cmd.php?cmd=webportal&tgt=&args=provzlinux;' + group + ';' + hcp + ';' + img + ';' + owner + '&msg=&opts=flush'); - iframe.prependTo($('#' + tabId)); + // Submit request to create VM + // webportal provzlinux [group] [hcp] [image] [owner] + var iframe = createIFrame('lib/srv_cmd.php?cmd=webportal&tgt=&args=provzlinux;' + group + ';' + hcp + ';' + img + ';' + owner + '&msg=&opts=flush'); + iframe.prependTo($('#' + tabId)); +} + +/** + * Query the profiles that exists + * + * @param panelId Panel ID + */ +function queryProfiles(panelId) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : panelId + }, + + success : function(data) { + var panelId = data.msg; + setOSImageCookies(data); + configProfilePanel(panelId); + } + }); +} + +/** + * Query the images that exists + * + * @param panelId Panel ID + */ +function queryImages(panelId) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : panelId + }, + + success : configImagePanel + }); +} + +/** + * Query the groups that exists + * + * @param panelId Panel ID + */ +function queryGroups(panelId) { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'hosts', + msg : panelId + }, + + success : configGroupPanel + }); +} + +/** + * Panel to configure groups + * + * @param data Data from HTTP request + */ +function configGroupPanel(data) { + var panelId = data.msg; + var rsp = data.rsp; + + // Wipe panel clean + $('#' + panelId).empty(); + + // Add info bar + $('#' + panelId).append(createInfoBar('Create, edit, and delete groups for the self-service portal.')); + + // Create table + var tableId = 'zvmGroupTable'; + var table = new DataTable(tableId); + table.init(['', 'Name', 'Selectable', 'IP', 'Hostname', 'Network', 'Description']); + + // Insert groups into table + var nodePos = 0; + var ipPos = 0; + var hostnamePos = 0; + var commentsPos = 0; + var desc, selectable, tmp; + // Get column index for each attribute + var colNameArray = rsp[0].substr(1).split(','); + for (var i in colNameArray){ + switch (colNameArray[i]){ + case 'node': + nodePos = i; + break; + + case 'ip': + ipPos = i; + break; + + case 'hostnames': + hostnamePos = i; + break; + + case 'comments': + commentsPos = i; + break; + + default : + break; + } + } + + // Go through each index + for (var i = 1; i < rsp.length; i++) { + // Get image name + var cols = rsp[i].split(','); + var name = cols[nodePos].replace(new RegExp('"', 'g'), ''); + var ip = cols[ipPos].replace(new RegExp('"', 'g'), ''); + var hostname = cols[hostnamePos].replace(new RegExp('"', 'g'), ''); + var comments = cols[commentsPos].replace(new RegExp('"', 'g'), ''); + + // Set default description and selectable + selectable = "no"; + network = ""; + desc = "No description"; + + if (comments) { + tmp = comments.split('|'); + for (var j = 0; j < tmp.length; j++) { + // Save description + if (tmp[j].indexOf('description:') > -1) { + desc = tmp[j].replace('description:', ''); + desc = jQuery.trim(desc); + } + + // Save network + if (tmp[j].indexOf('network:') > -1) { + network = tmp[j].replace('network:', ''); + network = jQuery.trim(network); + } + + // Is the group selectable? + if (tmp[j].indexOf('selectable:') > -1) { + selectable = tmp[j].replace('selectable:', ''); + selectable = jQuery.trim(selectable); + } + } + } + + // Columns are: name, selectable, network, and description + var cols = new Array(name, selectable, ip, hostname, network, desc); + + // Add remove button where id = user name + cols.unshift(''); + + // Add row + table.add(cols); + } + + // Append datatable to tab + $('#' + panelId).append(table.object()); + + // Turn into datatable + $('#' + tableId).dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%", + "bAutoWidth": true + }); + + // Create action bar + var actionBar = $('
                                                              '); + + // Create a group + var createLnk = $('Create'); + createLnk.click(function() { + groupDialog(); + }); + + // Edit a group + var editLnk = $('Edit'); + editLnk.click(function() { + var groups = $('#' + tableId + ' input[type=checkbox]:checked'); + for (var i in groups) { + var group = groups.eq(i).attr('name'); + if (group) { + // Column order is: name, selectable, network, and description + var cols = groups.eq(i).parents('tr').find('td'); + var selectable = cols.eq(2).text(); + var ip = cols.eq(3).text(); + var hostnames = cols.eq(4).text(); + var network = cols.eq(5).text(); + var description = cols.eq(6).text(); + + editGroupDialog(group, selectable, ip, hostnames, network, description); + } + } + }); + + // Delete a profile + var deleteLnk = $('Delete'); + deleteLnk.click(function() { + var groups = getNodesChecked(tableId); + if (groups) { + deleteGroupDialog(groups); + } + }); + + // Refresh profiles table + var refreshLnk = $('Refresh'); + refreshLnk.click(function() { + queryGroups(panelId); + }); + + // Create an action menu + var actionsMenu = createMenu([createLnk, editLnk, deleteLnk, refreshLnk]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + tableId + '_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + tableId + '_filter').appendTo(menuDiv); + + // Resize accordion + $('#zvmConfigAccordion').accordion('resize'); +} + +/** + * Panel to configure OS images + * + * @param data Data from HTTP request + */ +function configImagePanel(data) { + var panelId = data.msg; + var rsp = data.rsp; + + // Wipe panel clean + $('#' + panelId).empty(); + + // Add info bar + $('#' + panelId).append(createInfoBar('Create, edit, and delete operating system images for the self-service portal.')); + + // Create table + var tableId = 'zvmImageTable'; + var table = new DataTable(tableId); + table.init(['', 'Name', 'Selectable', 'OS Version', 'Profile', 'Method', 'Description']); + + // Insert images into table + var imagePos = 0; + var profilePos = 0; + var osversPos = 0; + var osarchPos = 0; + var provMethodPos = 0; + var comments = 0; + var desc, selectable, tmp; + // Get column index for each attribute + var colNameArray = rsp[0].substr(1).split(','); + for (var i in colNameArray){ + switch (colNameArray[i]){ + case 'imagename': { + imagePos = i; + } + break; + + case 'profile':{ + profilePos = i; + } + break; + + case 'osvers':{ + osversPos = i; + } + break; + + case 'osarch':{ + osarchPos = i; + } + break; + + case 'comments':{ + comments = i; + } + break; + + case 'provmethod':{ + provMethodPos = i; + } + break; + + default : + break; + } + } + + // Go through each index + for (var i = 1; i < rsp.length; i++) { + // Get image name + var cols = rsp[i].split(','); + var name = cols[imagePos].replace(new RegExp('"', 'g'), ''); + var profile = cols[profilePos].replace(new RegExp('"', 'g'), ''); + var provMethod = cols[provMethodPos].replace(new RegExp('"', 'g'), ''); + var osVer = cols[osversPos].replace(new RegExp('"', 'g'), ''); + var osArch = cols[osarchPos].replace(new RegExp('"', 'g'), ''); + var osComments = cols[comments].replace(new RegExp('"', 'g'), ''); + + // Only save install boot and s390x architectures + if (osArch == "s390x") { + // Set default description and selectable + selectable = "no"; + desc = "No description"; + + if (osComments) { + tmp = osComments.split('|'); + for (var j = 0; j < tmp.length; j++) { + // Save description + if (tmp[j].indexOf('description:') > -1) { + desc = tmp[j].replace('description:', ''); + desc = jQuery.trim(desc); + } + + // Is the image selectable? + if (tmp[j].indexOf('selectable:') > -1) { + selectable = tmp[j].replace('selectable:', ''); + selectable = jQuery.trim(selectable); + } + } + } + + // Columns are: name, selectable, OS version, profile, method, and description + var cols = new Array(name, selectable, osVer, profile, provMethod, desc); + + // Add remove button where id = user name + cols.unshift(''); + + // Add row + table.add(cols); + } + } + + // Append datatable to tab + $('#' + panelId).append(table.object()); + + // Turn into datatable + $('#' + tableId).dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%", + "bAutoWidth": true + }); + + // Create action bar + var actionBar = $('
                                                              '); + + // Create a profile + var createLnk = $('Create'); + createLnk.click(function() { + imageDialog(); + }); + + // Edit a profile + var editLnk = $('Edit'); + editLnk.click(function() { + var images = $('#' + tableId + ' input[type=checkbox]:checked'); + for (var i in images) { + var image = images.eq(i).attr('name'); + if (image) { + // Column order is: profile, selectable, disk pool, disk size, and directory entry + var cols = images.eq(i).parents('tr').find('td'); + var selectable = cols.eq(2).text(); + var osVersion = cols.eq(3).text(); + var profile = cols.eq(4).text(); + var method = cols.eq(5).text(); + var description = cols.eq(6).text(); + + editImageDialog(image, selectable, osVersion, profile, method, description); + } + } + }); + + // Delete a profile + var deleteLnk = $('Delete'); + deleteLnk.click(function() { + var images = getNodesChecked(tableId); + if (images) { + deleteImageDialog(images); + } + }); + + // Refresh profiles table + var refreshLnk = $('Refresh'); + refreshLnk.click(function() { + queryImages(panelId); + }); + + // Create an action menu + var actionsMenu = createMenu([createLnk, editLnk, deleteLnk, refreshLnk]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + tableId + '_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + tableId + '_filter').appendTo(menuDiv); + + // Resize accordion + $('#zvmConfigAccordion').accordion('resize'); +} + +/** + * Panel to configure directory entries and disks for a profile + * + * @param panelId Panel ID + */ +function configProfilePanel(panelId) { + // Wipe panel clean + $('#' + panelId).empty(); + + // Add info bar + $('#' + panelId).append(createInfoBar('Create, edit, and delete profiles for the self-service portal. It is important to note the default z/VM user ID for any profile should be LXUSR.')); + + // Create table + var tableId = 'zvmProfileTable'; + var table = new DataTable(tableId); + table.init(['', 'Profile', 'Disk pool', 'Disk size', 'Directory entry']); + + // Insert profiles into table + var profiles = $.cookie('profiles').split(','); + profiles.push('default'); // Add default profile + for (var i in profiles) { + if (profiles[i]) { + // Columns are: profile, selectable, description, disk pool, disk size, and directory entry + var cols = new Array(profiles[i], '', '', ''); + + // Add remove button where id = user name + cols.unshift(''); + + // Add row + table.add(cols); + } + } + + // Append datatable to tab + $('#' + panelId).append(table.object()); + + // Turn into datatable + $('#' + tableId).dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%", + "bAutoWidth": true + }); + + // Create action bar + var actionBar = $('
                                                              '); + + // Create a profile + var createLnk = $('Create'); + createLnk.click(function() { + profileDialog(); + }); + + // Edit a profile + var editLnk = $('Edit'); + editLnk.click(function() { + var profiles = $('#' + tableId + ' input[type=checkbox]:checked'); + for (var i in profiles) { + var profile = profiles.eq(i).attr('name'); + if (profile) { + // Column order is: profile, selectable, disk pool, disk size, and directory entry + var cols = profiles.eq(i).parents('tr').find('td'); + var pool = cols.eq(2).text(); + var size = cols.eq(3).text(); + var entry = cols.eq(4).html().replace(new RegExp('
                                                              ', 'g'), '\n'); + + editProfileDialog(profile, pool, size, entry); + } + } + }); + + // Delete a profile + var deleteLnk = $('Delete'); + deleteLnk.click(function() { + var profiles = getNodesChecked(tableId); + if (profiles) { + openDeleteProfileDialog(profiles); + } + }); + + // Refresh profiles table + var refreshLnk = $('Refresh'); + refreshLnk.click(function() { + queryProfiles(panelId); + }); + + // Create an action menu + var actionsMenu = createMenu([createLnk, editLnk, deleteLnk, refreshLnk]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + tableId + '_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + tableId + '_filter').appendTo(menuDiv); + + // Resize accordion + $('#zvmConfigAccordion').accordion('resize'); + + // Query directory entries and disk pool/size for each profile + for (var i in profiles) { + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'getdefaultuserentry;' + profiles[i], + msg : 'out=' + panelId + ';profile=' + profiles[i] + }, + + success: insertDirectoryEntry + }); + + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'getzdiskinfo;' + profiles[i], + msg : 'out=' + panelId + ';profile=' + profiles[i] + }, + + success: insertDiskInfo + }); + } +} + +/** + * Insert the directory entry into the profile table + * + * @param data Data from HTTP request + */ +function insertDirectoryEntry(data) { + var tableId = 'zvmProfileTable'; + var args = data.msg.split(';'); + + var profile = args[1].replace('profile=', ''); + + // Do not continue if there is nothing + if (!data.rsp.length) + return; + + var entry = data.rsp[0].replace(new RegExp('\n', 'g'), '
                                                              '); + + // Get the row containing the profile + var rowPos = findRow(profile, '#' + tableId, 1); + if (rowPos < 0) + return; + + // Update the directory entry column + var dTable = $('#' + tableId).dataTable(); + dTable.fnUpdate(entry, rowPos, 4, false); + + // Adjust table styling + $('#' + tableId + ' td:nth-child(5)').css({ + 'text-align': 'left' + }); + adjustColumnSize(tableId); +} + +/** + * Insert the disk info into the profile table + * + * @param data Data from HTTP request + */ +function insertDiskInfo(data) { + var tableId = 'zvmProfileTable'; + var args = data.msg.split(';'); + + var profile = args[1].replace('profile=', ''); + + // Do not continue if there is nothing + if (!data.rsp.length) + return; + + // Get the row containing the profile + var rowPos = findRow(profile, '#' + tableId, 1); + if (rowPos < 0) + return; + + // Update the disk info columns + var dTable = $('#' + tableId).dataTable(); + + var tmp = ""; + var pool = ""; + var eckdSize = 0; + var info = data.rsp[0].split('\n'); + for (var i in info) { + if (info[i].indexOf('diskpool') > -1) { + tmp = info[i].split('='); + pool = jQuery.trim(tmp[1]); + + dTable.fnUpdate(pool, rowPos, 2, false); + } if (info[i].indexOf('eckd_size') > -1) { + tmp = info[i].split('='); + eckdSize = jQuery.trim(tmp[1]); + + dTable.fnUpdate(eckdSize, rowPos, 3, false); + } + } + + // Adjust table styling + adjustColumnSize(tableId); +} + +/** + * Open group dialog + */ +function groupDialog() { + // Create form to add profile + var dialogId = 'zvmCreateGroup'; + var groupForm = $('
                                                              '); + + // Create info bar + var info = createInfoBar('Provide the following attributes for the group.'); + groupForm.append(info); + + var group = $('
                                                              '); + var selectable = $('
                                                              '); + var ip = $('
                                                              '); + var hostnames = $('
                                                              '); + var network = $('
                                                              '); + var comments = $('
                                                              '); + groupForm.append(group, selectable, ip, hostnames, network, comments); + + // Open dialog to add image + groupForm.dialog({ + title:'Create group', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function() { + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get group attributes + var group = $(this).find('input[name="group"]'); + var selectable = $(this).find('input[name="selectable"]'); + var ip = $(this).find('input[name="ip"]'); + var hostnames = $(this).find('input[name="hostnames"]'); + var network = $(this).find('input[name="network"]'); + var comments = $(this).find('input[name="comments"]'); + + // Check that group attributes are provided before continuing + var ready = 1; + var inputs = new Array(group, ip, hostnames, network); + for (var i in inputs) { + if (!inputs[i].val()) { + inputs[i].css('border-color', 'red'); + ready = 0; + } else + inputs[i].css('border-color', ''); + } + + // If inputs are not complete, show warning message + if (!ready) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + // Set default description + if (!comments.val()) + comments.val('No description'); + + // Create arguments to send via AJAX + var args = "updategroup;" + group.val() + ";'" + ip.val() + "';'" + hostnames.val() + "';"; + + if (selectable.attr("checked")) + args += "'description:" + comments.val() + "|network:" + network.val() + "|selectable:yes"; + else + args += "'description:" + comments.val() + "|network:" + network.val() + "|selectable:no"; + + // Add image to xCAT + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : args, + msg : dialogId + }, + + success : updatePanel + }); + } + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); +} + +/** + * Open image dialog + */ +function imageDialog() { + // Create form to add profile + var dialogId = 'zvmCreateImage'; + var imageForm = $('
                                                              '); + + // Create info bar + var info = createInfoBar('Provide the following attributes for the image. The image name will be generated based on the attributes you will give.'); + imageForm.append(info); + + var imageName = $('
                                                              '); + var selectable = $('
                                                              '); + var imageType = $('
                                                              '); + var architecture = $('
                                                              '); + var osName = $('
                                                              '); + var osVersion = $('
                                                              '); + var profile = $('
                                                              '); + var provisionMethod = $('
                                                              '); + var provisionSelect = $(''); + provisionMethod.append(provisionSelect); + var comments = $('
                                                              '); + imageForm.append(imageName, selectable, imageType, architecture, osName, osVersion, profile, provisionMethod, comments); + + // Open dialog to add image + imageForm.dialog({ + title:'Create image', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function() { + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get image attributes + var imageType = $(this).find('input[name="imagetype"]'); + var selectable = $(this).find('input[name="selectable"]'); + var architecture = $(this).find('input[name="osarch"]'); + var osName = $(this).find('input[name="osname"]'); + var osVersion = $(this).find('input[name="osvers"]'); + var profile = $(this).find('input[name="profile"]'); + var provisionMethod = $(this).find('select[name="provmethod"]'); + var comments = $(this).find('input[name="comments"]'); + + // Check that image attributes are provided before continuing + var ready = 1; + var inputs = new Array(imageType, architecture, osName, osVersion, profile, provisionMethod); + for (var i in inputs) { + if (!inputs[i].val()) { + inputs[i].css('border-color', 'red'); + ready = 0; + } else + inputs[i].css('border-color', ''); + } + + // If inputs are not complete, show warning message + if (!ready) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Override image name + $(this).find('input[name="imagename"]').val(osVersion.val() + '-' + architecture.val() + '-' + provisionMethod.val() + '-' + profile.val()); + var imageName = $(this).find('input[name="imagename"]'); + + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + // Set default description + if (!comments.val()) + comments.val('No description'); + + // Create arguments to send via AJAX + var args = 'updateosimage;' + imageName.val() + ';' + + imageType.val() + ';' + + architecture.val() + ';' + + osName.val() + ';' + + osVersion.val() + ';' + + profile.val() + ';' + + provisionMethod.val() + ';'; + + if (selectable.attr('checked')) + args += '"description:' + comments.val() + '|selectable:yes"'; + else + args += '"description:' + comments.val() + '|selectable:no"'; + + // Add image to xCAT + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : args, + msg : dialogId + }, + + success : updatePanel + }); + } + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); +} + +/** + * Open profile dialog + */ +function profileDialog() { + // Create form to add profile + var dialogId = 'zvmCreateProfile'; + var profileForm = $('
                                                              '); + + // Create info bar + var info = createInfoBar('Configure the default settings for a profile'); + profileForm.append(info); + + // Insert profiles into select + var profileSelect = $(''); + var profiles = $.cookie('profiles').split(','); + profiles.push('default'); // Add default profile + for (var i in profiles) { + if (profiles[i]) { + profileSelect.append($('')); + } + } + + profileForm.append($('
                                                              ').append(profileSelect)); + profileForm.append('
                                                              '); + profileForm.append('
                                                              '); + profileForm.append('
                                                              ').css({ - 'font-size': '10px', - 'height': '50px', - 'width': '200px', - 'background-color': '#000', - 'color': '#fff', - 'border': '0px', - 'display': 'block' - }); - - // Create links to save and cancel changes - var lnkStyle = { - 'color': '#58ACFA', - 'font-size': '10px', - 'display': 'inline-block', - 'padding': '5px', - 'float': 'right' - }; - - var saveLnk = $('Save').css(lnkStyle).hide(); - var cancelLnk = $('Cancel').css(lnkStyle).hide(); - var infoSpan = $('Click to edit').css(lnkStyle); - - // Save changes onclick - saveLnk.bind('click', function(){ - // Get node and comment - var node = $(this).parent().parent().find('img').attr('id').replace('Tip', ''); - var comments = $(this).parent().find('textarea').val(); - - // Save comment - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : '-t;node;-o;' + node + ';usercomment=' + comments, - msg : 'out=nodesTab;tgt=' + node - }, - - success: showChdefOutput - }); - - // Hide cancel and save links - $(this).hide(); - cancelLnk.hide(); - }); - - // Cancel changes onclick - cancelLnk.bind('click', function(){ - // Get original comment and put it back - var orignComments = $(this).parent().find('textarea').text(); - $(this).parent().find('textarea').val(orignComments); - - // Hide cancel and save links - $(this).hide(); - saveLnk.hide(); - infoSpan.show(); - }); - - // Show save link when comment is edited - txtArea.bind('click', function(){ - saveLnk.show(); - cancelLnk.show(); - infoSpan.hide(); - }); - - toolTip.append(txtArea); - toolTip.append(cancelLnk); - toolTip.append(saveLnk); - toolTip.append(infoSpan); - - return toolTip; + // Create tooltip container + var toolTip = $('
                                                              '); + // Create textarea to hold comment + var txtArea = $('').css({ + 'font-size': '10px', + 'height': '50px', + 'width': '200px', + 'background-color': '#000', + 'color': '#fff', + 'border': '0px', + 'display': 'block' + }); + + // Create links to save and cancel changes + var lnkStyle = { + 'color': '#58ACFA', + 'font-size': '10px', + 'display': 'inline-block', + 'padding': '5px', + 'float': 'right' + }; + + var saveLnk = $('Save').css(lnkStyle).hide(); + var cancelLnk = $('Cancel').css(lnkStyle).hide(); + var infoSpan = $('Click to edit').css(lnkStyle); + + // Save changes onclick + saveLnk.bind('click', function(){ + // Get node and comment + var node = $(this).parent().parent().find('img').attr('id').replace('Tip', ''); + var comments = $(this).parent().find('textarea').val(); + + // Save comment + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : '-t;node;-o;' + node + ';usercomment=' + comments, + msg : 'out=nodesTab;tgt=' + node + }, + + success: showChdefOutput + }); + + // Hide cancel and save links + $(this).hide(); + cancelLnk.hide(); + }); + + // Cancel changes onclick + cancelLnk.bind('click', function(){ + // Get original comment and put it back + var orignComments = $(this).parent().find('textarea').text(); + $(this).parent().find('textarea').val(orignComments); + + // Hide cancel and save links + $(this).hide(); + saveLnk.hide(); + infoSpan.show(); + }); + + // Show save link when comment is edited + txtArea.bind('click', function(){ + saveLnk.show(); + cancelLnk.show(); + infoSpan.hide(); + }); + + toolTip.append(txtArea); + toolTip.append(cancelLnk); + toolTip.append(saveLnk); + toolTip.append(infoSpan); + + return toolTip; } /** @@ -2500,45 +2399,45 @@ function createCommentsToolTip(comment) { * @return Tool tip */ function createStatusToolTip() { - // Create tooltip container - var toolTip = $('
                                                              ').css({ - 'width': '150px', - 'font-weight': 'normal' - }); - - // Create info text - var info = $('

                                                              ').css({ - 'white-space': 'normal' - }); - info.append('Click here to refresh the node status. To configure the xCAT monitor, '); - - // Create link to turn on xCAT monitoring - var monitorLnk = $('click here').css({ - 'color': '#58ACFA', - 'font-size': '10px' - }); - - // Open dialog to configure xCAT monitor - monitorLnk.bind('click', function(){ - // Check if xCAT monitor is enabled - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'monls', - tgt : '', - args : 'xcatmon', - msg : '' - }, + // Create tooltip container + var toolTip = $('
                                                              ').css({ + 'width': '150px', + 'font-weight': 'normal' + }); + + // Create info text + var info = $('

                                                              ').css({ + 'white-space': 'normal' + }); + info.append('Click here to refresh the node status. To configure the xCAT monitor, '); + + // Create link to turn on xCAT monitoring + var monitorLnk = $('click here').css({ + 'color': '#58ACFA', + 'font-size': '10px' + }); + + // Open dialog to configure xCAT monitor + monitorLnk.bind('click', function(){ + // Check if xCAT monitor is enabled + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'monls', + tgt : '', + args : 'xcatmon', + msg : '' + }, - success : openConfXcatMon - }); - }); - - info.append(monitorLnk); - toolTip.append(info); - - return toolTip; + success : openConfXcatMon + }); + }); + + info.append(monitorLnk); + toolTip.append(info); + + return toolTip; } /** @@ -2547,13 +2446,13 @@ function createStatusToolTip() { * @return Tool tip */ function createPowerToolTip() { - // Create tooltip container - var toolTip = $('
                                                              Click here to refresh the power status
                                                              ').css({ - 'width': '150px', - 'white-space': 'normal', - 'font-weight': 'normal' - }); - return toolTip; + // Create tooltip container + var toolTip = $('
                                                              Click here to refresh the power status
                                                              ').css({ + 'width': '150px', + 'white-space': 'normal', + 'font-weight': 'normal' + }); + return toolTip; } /** @@ -2562,636 +2461,620 @@ function createPowerToolTip() { * @return Tool tip */ function createMonitorToolTip() { - // Create tooltip container - var toolTip = $('
                                                              Click here to refresh the monitoring status
                                                              ').css({ - 'width': '150px', - 'white-space': 'normal', - 'font-weight': 'normal' - }); - return toolTip; + // Create tooltip container + var toolTip = $('
                                                              Click here to refresh the monitoring status
                                                              ').css({ + 'width': '150px', + 'white-space': 'normal', + 'font-weight': 'normal' + }); + return toolTip; } /** * Open dialog to configure xCAT monitor * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function openConfXcatMon(data) { - // Create info bar - var info = createInfoBar('Configure the xCAT monitor. Select to enable or disable the monitor below.'); - var dialog = $('
                                                              '); - dialog.append(info); - - // Create status area - var statusArea = $('
                                                              ').css('padding-top', '10px'); - var label = $(''); - statusArea.append(label); - - // Get xCAT monitor status - var status = data.rsp[0]; - var buttons; - // If xCAT monitor is disabled - if (status.indexOf('not-monitored') > -1) { - status = $('Disabled').css('padding', '0px 5px'); - statusArea.append(status); - - // Create enable and cancel buttons - buttons = { - "Enable": function(){ - // Enable xCAT monitor - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'monstart', - tgt : '', - args : 'xcatmon', - msg : '' - }, + // Create info bar + var info = createInfoBar('Configure the xCAT monitor. Select to enable or disable the monitor below.'); + var dialog = $('
                                                              '); + dialog.append(info); - success : function(data){ - openDialog('info', data.rsp[0]); - } - }); - $(this).dialog("close"); - }, - "Cancel": function(){ - $(this).dialog("close"); - } - }; - } else { - status = $('Enabled').css('padding', '0px 5px'); - statusArea.append(status); - - // Create disable and cancel buttons - buttons = { - "Disable": function(){ - // Disable xCAT monitor - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'monstop', - tgt : '', - args : 'xcatmon', - msg : '' - }, + // Create status area + var statusArea = $('
                                                              ').css('padding-top', '10px'); + var label = $(''); + statusArea.append(label); - success : function(data){ - openDialog('info', data.rsp[0]); - } - }); - $(this).dialog("close"); - }, - "Cancel": function(){ - $(this).dialog("close"); - } - }; - } - - dialog.append(statusArea); - - // Open dialog - dialog.dialog({ - modal: true, - width: 500, - buttons: buttons - }); + // Get xCAT monitor status + var status = data.rsp[0]; + var buttons; + // If xCAT monitor is disabled + if (status.indexOf('not-monitored') > -1) { + status = $('Disabled').css('padding', '0px 5px'); + statusArea.append(status); + + // Create enable and cancel buttons + buttons = { + "Enable": function(){ + // Enable xCAT monitor + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'monstart', + tgt : '', + args : 'xcatmon', + msg : '' + }, + + success : function(data){ + openDialog('info', data.rsp[0]); + } + }); + $(this).dialog("close"); + }, + "Cancel": function(){ + $(this).dialog("close"); + } + }; + } else { + status = $('Enabled').css('padding', '0px 5px'); + statusArea.append(status); + + // Create disable and cancel buttons + buttons = { + "Disable": function(){ + // Disable xCAT monitor + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'monstop', + tgt : '', + args : 'xcatmon', + msg : '' + }, + + success : function(data){ + openDialog('info', data.rsp[0]); + } + }); + $(this).dialog("close"); + }, + "Cancel": function(){ + $(this).dialog("close"); + } + }; + } + + dialog.append(statusArea); + + // Open dialog + dialog.dialog({ + modal: true, + width: 500, + buttons: buttons + }); } /** * Show chdef output * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function showChdefOutput(data) { - // Get output - var out = data.rsp; - var args = data.msg.split(';'); - var tabID = args[0].replace('out=', ''); - var tgt = args[1].replace('tgt=', ''); - - // Find info bar on nodes tab, if any - var info = $('#' + tabID).find('.ui-state-highlight'); - if (!info.length) { - // Create info bar if one does not exist - info = createInfoBar(''); - $('#' + tabID).append(info); - } - - // Go through output and append to paragraph - var prg = $('

                                                              '); - for (var i in out) { - prg.append(tgt + ': ' + out[i] + '
                                                              '); - } - - info.append(prg); + // Get output + var out = data.rsp; + var args = data.msg.split(';'); + var tabID = args[0].replace('out=', ''); + var tgt = args[1].replace('tgt=', ''); + + // Find info bar on nodes tab, if any + var info = $('#' + tabID).find('.ui-state-highlight'); + if (!info.length) { + // Create info bar if one does not exist + info = createInfoBar(''); + $('#' + tabID).append(info); + } + + // Go through output and append to paragraph + var prg = $('

                                                              '); + for (var i in out) { + prg.append(tgt + ': ' + out[i] + '
                                                              '); + } + + info.append(prg); } /** * Set node attributes * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function setNodeAttrs(data) { - // Clear hash table containing definable node attributes - nodeAttrs = new Array(); - - // Get definable attributes - var attrs = data.rsp[2].split(/\n/); + // Clear hash table containing definable node attributes + nodeAttrs = new Array(); + + // Get definable attributes + var attrs = data.rsp[2].split(/\n/); - // Go through each line - var attr, key, descr; - for (var i in attrs) { - attr = attrs[i]; - - // If the line is not empty - if (attr) { - // If the line has the attribute name - if (attr.indexOf(':') && attr.indexOf(' ')) { - // Get attribute name and description - key = jQuery.trim(attr.substring(0, attr.indexOf(':'))); - descr = jQuery.trim(attr.substring(attr.indexOf(':') + 1)); - - // Remove arrow brackets - descr = descr.replace(new RegExp('<|>', 'g'), ''); - - // Set hash table where key = attribute name and value = description - nodeAttrs[key] = descr; - } else { - // Remove arrow brackets - attr = attr.replace(new RegExp('<|>', 'g'), ''); - - // Append description to hash table - nodeAttrs[key] = nodeAttrs[key] + '\n' + attr; - } - } // End of if - } // End of for + // Go through each line + var attr, key, descr; + for (var i in attrs) { + attr = attrs[i]; + + // If the line is not empty + if (attr) { + // If the line has the attribute name + if (attr.indexOf(':') && attr.indexOf(' ')) { + // Get attribute name and description + key = jQuery.trim(attr.substring(0, attr.indexOf(':'))); + descr = jQuery.trim(attr.substring(attr.indexOf(':') + 1)); + + // Remove arrow brackets + descr = descr.replace(new RegExp('<|>', 'g'), ''); + + // Set hash table where key = attribute name and value = description + nodeAttrs[key] = descr; + } else { + // Remove arrow brackets + attr = attr.replace(new RegExp('<|>', 'g'), ''); + + // Append description to hash table + nodeAttrs[key] = nodeAttrs[key] + '\n' + attr; + } + } // End of if + } // End of for } /** * Load set node properties page * - * @param tgtNode - * Target node to set properties - * @return Nothing + * @param tgtNode Target node to set properties */ function editNodeProps(tgtNode) { - // Get nodes tab - var tab = getNodesTab(); + // Get nodes tab + var tab = getNodesTab(); - // Generate new tab ID - var inst = 0; - var newTabId = 'editPropsTab' + inst; - while ($('#' + newTabId).length) { - // If one already exists, generate another one - inst = inst + 1; - newTabId = 'editPropsTab' + inst; - } + // Generate new tab ID + var inst = 0; + var newTabId = 'editPropsTab' + inst; + while ($('#' + newTabId).length) { + // If one already exists, generate another one + inst = inst + 1; + newTabId = 'editPropsTab' + inst; + } - // Open new tab - // Create set properties form - var editPropsForm = $('
                                                              '); + // Open new tab + // Create set properties form + var editPropsForm = $('
                                                              '); - // Create info bar - var infoBar = createInfoBar('Choose the properties you wish to change on the node. When you are finished, click Save.'); - editPropsForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Choose the properties you wish to change on the node. When you are finished, click Save.'); + editPropsForm.append(infoBar); - // Create an input for each definable attribute - var div, label, input, descr, value; - // Set node attribute - origAttrs[tgtNode]['node'] = tgtNode; - for (var key in nodeAttrs) { - // If an attribute value exists - if (origAttrs[tgtNode][key]) { - // Set the value - value = origAttrs[tgtNode][key]; - } else { - value = ''; - } - - // Create label and input for attribute - div = $('
                                                              ').css('display', 'inline-table'); - label = $('').css('vertical-align', 'middle'); - input = $('').css('margin-top', '5px'); - - // Change border to blue onchange - input.bind('change', function(event) { - $(this).css('border-color', 'blue'); - }); - - div.append(label); - div.append(input); - editPropsForm.append(div); - } + // Create an input for each definable attribute + var div, label, input, descr, value; + // Set node attribute + origAttrs[tgtNode]['node'] = tgtNode; + for (var key in nodeAttrs) { + // If an attribute value exists + if (origAttrs[tgtNode][key]) { + // Set the value + value = origAttrs[tgtNode][key]; + } else { + value = ''; + } + + // Create label and input for attribute + div = $('
                                                              ').css('display', 'inline-table'); + label = $('').css('vertical-align', 'middle'); + input = $('').css('margin-top', '5px'); + + // Change border to blue onchange + input.bind('change', function(event) { + $(this).css('border-color', 'blue'); + }); + + div.append(label); + div.append(input); + editPropsForm.append(div); + } - // Change style for last division - div.css({ - 'display': 'block', - 'margin': '0px 0px 10px 0px' - }); - - // Generate tooltips - editPropsForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.8, - delay: 0, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - } - }); + // Change style for last division + div.css({ + 'display': 'block', + 'margin': '0px 0px 10px 0px' + }); + + // Generate tooltips + editPropsForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.8, + delay: 0, + predelay: 800, + events: { + def: "mouseover,mouseout", + input: "mouseover,mouseout", + widget: "focus mouseover,blur mouseout", + tooltip: "mouseover,mouseout" + } + }); - // Save changes - var saveBtn = createButton('Save'); - saveBtn.click(function() { - // Get all inputs - var inputs = $('#' + newTabId + ' input'); - - // Go through each input - var args = ''; - var attrName, attrVal; - inputs.each(function(){ - // If the border color is blue - if ($(this).css('border-left-color') == 'rgb(0, 0, 255)') { - // Change border color back to normal - $(this).css('border-color', ''); - - // Get attribute name and value - attrName = $(this).parent().find('label').text().replace(':', ''); - attrVal = $(this).val(); - - // Build argument string - if (args) { - // Handle subsequent arguments - args += ';' + attrName + '=' + attrVal; - } else { - // Handle the 1st argument - args += attrName + '=' + attrVal; - } - } - }); - - // Send command to change node attributes - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : '-t;node;-o;' + tgtNode + ';' + args, - msg : 'out=' + newTabId + ';tgt=' + tgtNode - }, + // Save changes + var saveBtn = createButton('Save'); + saveBtn.click(function() { + // Get all inputs + var inputs = $('#' + newTabId + ' input'); + + // Go through each input + var args = ''; + var attrName, attrVal; + inputs.each(function(){ + // If the border color is blue + if ($(this).css('border-left-color') == 'rgb(0, 0, 255)') { + // Change border color back to normal + $(this).css('border-color', ''); + + // Get attribute name and value + attrName = $(this).parent().find('label').text().replace(':', ''); + attrVal = $(this).val(); + + // Build argument string + if (args) { + // Handle subsequent arguments + args += ';' + attrName + '=' + attrVal; + } else { + // Handle the 1st argument + args += attrName + '=' + attrVal; + } + } + }); + + // Send command to change node attributes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : '-t;node;-o;' + tgtNode + ';' + args, + msg : 'out=' + newTabId + ';tgt=' + tgtNode + }, - success: showChdefOutput - }); - }); - editPropsForm.append(saveBtn); - - // Cancel changes - var cancelBtn = createButton('Cancel'); - cancelBtn.click(function() { - // Close the tab - tab.remove($(this).parent().parent().attr('id')); - }); - editPropsForm.append(cancelBtn); + success: showChdefOutput + }); + }); + editPropsForm.append(saveBtn); + + // Cancel changes + var cancelBtn = createButton('Cancel'); + cancelBtn.click(function() { + // Close the tab + tab.remove($(this).parent().parent().attr('id')); + }); + editPropsForm.append(cancelBtn); - // Append to discover tab - tab.add(newTabId, 'Edit', editPropsForm, true); + // Append to discover tab + tab.add(newTabId, 'Edit', editPropsForm, true); - // Select new tab - tab.select(newTabId); + // Select new tab + tab.select(newTabId); } /** * Open set node attributes dialog - * - * @return Nothing */ function openSetAttrsDialog() { - // Open new tab - // Create set properties form - var setPropsForm = $('
                                                              '); + // Open new tab + // Create set properties form + var setPropsForm = $('
                                                              '); - // Create info bar - var infoBar = createInfoBar('Choose the properties you wish to change on the node. When you are finished, click Save.'); - setPropsForm.append(infoBar); - - // Create an input for each definable attribute - var div, label, input, descr, value; - for (var key in nodeAttrs) { - value = ''; - - // Create label and input for attribute - div = $('
                                                              ').css('display', 'inline'); - label = $('').css('vertical-align', 'middle'); - input = $('').css('margin-top', '5px'); - - // Change border to blue onchange - input.bind('change', function(event) { - $(this).css('border-color', 'blue'); - }); - - div.append(label); - div.append(input); - setPropsForm.append(div); - } - - // Change style for last division - div.css({ - 'display': 'block', - 'margin': '0px 0px 10px 0px' - }); - - // Generate tooltips - setPropsForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.8, - delay: 0, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - }, + // Create info bar + var infoBar = createInfoBar('Choose the properties you wish to change on the node. When you are finished, click Save.'); + setPropsForm.append(infoBar); + + // Create an input for each definable attribute + var div, label, input, descr, value; + for (var key in nodeAttrs) { + value = ''; + + // Create label and input for attribute + div = $('
                                                              ').css('display', 'inline'); + label = $('').css('vertical-align', 'middle'); + input = $('').css('margin-top', '5px'); + + // Change border to blue onchange + input.bind('change', function(event) { + $(this).css('border-color', 'blue'); + }); + + div.append(label); + div.append(input); + setPropsForm.append(div); + } + + // Change style for last division + div.css({ + 'display': 'block', + 'margin': '0px 0px 10px 0px' + }); + + // Generate tooltips + setPropsForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.8, + delay: 0, + predelay: 800, + events: { + def: "mouseover,mouseout", + input: "mouseover,mouseout", + widget: "focus mouseover,blur mouseout", + tooltip: "mouseover,mouseout" + }, - // Change z index to show tooltip in front - onBeforeShow: function() { - this.getTip().css('z-index', $.topZIndex()); - } - }); - - // Enable vertical scroll - setPropsForm.css('overflow', 'auto'); - - // Open form as a dialog - setPropsForm.dialog({ - title: 'Set attributes', - modal: true, - height: 400, - width: 700, - buttons: { - "Save": function() { - // Remove any warning messages - $(this).find('.ui-state-error').remove(); - - // Get all inputs - var inputs = $(this).find('input'); - - // Go through each input - var args = ''; - var tgtNode, attrName, attrVal; - inputs.each(function(){ - // If the border color is blue - if ($(this).css('border-left-color') == 'rgb(0, 0, 255)') { - // Change border color back to normal - $(this).css('border-color', ''); - - // Get attribute name and value - attrName = $(this).parent().find('label').text().replace(':', ''); - attrVal = $(this).val(); - - // Get node name - if (attrName == 'node') { - tgtNode = attrVal; - } else { - // Build argument string - if (args) { - // Handle subsequent arguments - args += ';' + attrName + '=' + attrVal; - } else { - // Handle the 1st argument - args += attrName + '=' + attrVal; - } - } - } - }); - - // Send command to change node attributes - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : '-t;node;-o;' + tgtNode + ';' + args, - msg : 'node=' + tgtNode - }, + // Change z index to show tooltip in front + onBeforeShow: function() { + this.getTip().css('z-index', $.topZIndex()); + } + }); + + // Enable vertical scroll + setPropsForm.css('overflow', 'auto'); + + // Open form as a dialog + setPropsForm.dialog({ + title: 'Set attributes', + modal: true, + close: function(){ + $(this).remove(); + }, + height: 400, + width: 700, + buttons: { + "Save": function() { + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get all inputs + var inputs = $(this).find('input'); + + // Go through each input + var args = ''; + var tgtNode, attrName, attrVal; + inputs.each(function(){ + // If the border color is blue + if ($(this).css('border-left-color') == 'rgb(0, 0, 255)') { + // Change border color back to normal + $(this).css('border-color', ''); + + // Get attribute name and value + attrName = $(this).parent().find('label').text().replace(':', ''); + attrVal = $(this).val(); + + // Get node name + if (attrName == 'node') { + tgtNode = attrVal; + } else { + // Build argument string + if (args) { + // Handle subsequent arguments + args += ';' + attrName + '=' + attrVal; + } else { + // Handle the 1st argument + args += attrName + '=' + attrVal; + } + } + } + }); + + // Send command to change node attributes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : '-t;node;-o;' + tgtNode + ';' + args, + msg : 'node=' + tgtNode + }, - /** - * Show results - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success: function(data) { - // Get output - var out = data.rsp; - var node = data.msg.replace('node=', ''); - - // Go through output and append to paragraph - var msg = ''; - for (var i in out) { - if (!msg) { - msg = node + ': ' + out[i]; - } else { - msg += '
                                                              ' + node + ': ' + out[i]; - } - } - - openDialog('info', msg); - } - }); - - // Close dialog - $(this).dialog( "close" ); - }, - "Cancel": function(){ - $(this).dialog( "close" ); - } - } - }); + /** + * Show results + * + * @param data + * Data returned from HTTP request + * @return Nothing + */ + success: function(data) { + // Get output + var out = data.rsp; + var node = data.msg.replace('node=', ''); + + // Go through output and append to paragraph + var msg = ''; + for (var i in out) { + if (!msg) { + msg = node + ': ' + out[i]; + } else { + msg += '
                                                              ' + node + ': ' + out[i]; + } + } + + openDialog('info', msg); + } + }); + + // Close dialog + $(this).dialog( "close" ); + }, + "Cancel": function(){ + $(this).dialog( "close" ); + } + } + }); } /** * Turn on monitoring for a given node * - * @param node - * Node to monitor on or off - * @param monitor - * Monitor state, on or off - * @return Nothing + * @param node Node to monitor on or off + * @param monitor Monitor state, on or off */ function monitorNode(node, monitor) { - // Show ganglia loader - var gangliaCol = $('#' + nodesTableId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); - gangliaCol.find('img').show(); - - if (monitor == 'on') { - // Append loader to warning bar - var warningBar = $('#nodesTab').find('.ui-state-error p'); - if (warningBar.length) { - warningBar.append(createLoader('')); - } + // Show ganglia loader + var gangliaCol = $('#' + nodesTableId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); + gangliaCol.find('img').show(); + + if (monitor == 'on') { + // Append loader to warning bar + var warningBar = $('#nodesTab').find('.ui-state-error p'); + if (warningBar.length) { + warningBar.append(createLoader('')); + } - if (node) { - // Check if ganglia RPMs are installed - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliacheck;' + node, - msg : node // Node range will be passed along in data.msg - }, + if (node) { + // Check if ganglia RPMs are installed + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliacheck;' + node, + msg : node // Node range will be passed along in data.msg + }, - /** - * Start ganglia on a given node range - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success : function(data) { - // Get response - var out = data.rsp[0].split(/\n/); + /** + * Start ganglia on a given node range + * + * @param data Data returned from HTTP request + */ + success : function(data) { + // Get response + var out = data.rsp[0].split(/\n/); - // Go through each line - var warn = false; - var warningMsg = ''; - for (var i in out) { - // If an RPM is not installed - if (out[i].indexOf('not installed') > -1) { - warn = true; - - if (warningMsg) { - warningMsg += '
                                                              ' + out[i]; - } else { - warningMsg = out[i]; - } - } - } - - // If there are warnings - if (warn) { - // Create warning bar - var warningBar = createWarnBar(warningMsg); - warningBar.css('margin-bottom', '10px'); - warningBar.prependTo($('#nodesTab')); - } else { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliastart;' + data.msg + ';-r', - msg : data.msg - }, + // Go through each line + var warn = false; + var warningMsg = ''; + for (var i in out) { + // If an RPM is not installed + if (out[i].indexOf('not installed') > -1) { + warn = true; + + if (warningMsg) { + warningMsg += '
                                                              ' + out[i]; + } else { + warningMsg = out[i]; + } + } + } + + // If there are warnings + if (warn) { + // Create warning bar + var warningBar = createWarnBar(warningMsg); + warningBar.css('margin-bottom', '10px'); + warningBar.prependTo($('#nodesTab')); + } else { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliastart;' + data.msg + ';-r', + msg : data.msg + }, - success : function(data) { - // Remove any warnings - $('#nodesTab').find('.ui-state-error').remove(); - - // Update datatable - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliastatus;' + data.msg, - msg : '' - }, + success : function(data) { + // Remove any warnings + $('#nodesTab').find('.ui-state-error').remove(); + + // Update datatable + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliastatus;' + data.msg, + msg : '' + }, - success : loadGangliaStatus - }); - } - }); - } // End of if (warn) - } // End of function(data) - }); - } else { - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliastart', - msg : '' - }, + success : loadGangliaStatus + }); + } + }); + } // End of if (warn) + } // End of function(data) + }); + } else { + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliastart', + msg : '' + }, - success : function(data) { - // Remove any warnings - $('#nodesTab').find('.ui-state-error').remove(); - } - }); - } // End of if (node) - } else { - var args; - if (node) { - args = 'gangliastop;' + node + ';-r'; - } else { - args = 'gangliastop'; - } + success : function(data) { + // Remove any warnings + $('#nodesTab').find('.ui-state-error').remove(); + } + }); + } // End of if (node) + } else { + var args; + if (node) { + args = 'gangliastop;' + node + ';-r'; + } else { + args = 'gangliastop'; + } - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : args, - msg : '' - }, + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : args, + msg : '' + }, - success : function(data) { - // Hide ganglia loader - var gangliaCol = $('#' + nodesTableId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); - gangliaCol.find('img').hide(); - } - }); - } + success : function(data) { + // Hide ganglia loader + var gangliaCol = $('#' + nodesTableId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); + gangliaCol.find('img').hide(); + } + }); + } } /** * Install Ganglia on a given node * - * @param node - * Node to install Ganglia on - * @return Nothing + * @param node Node to install Ganglia on */ function installGanglia(node) { - var iframe = createIFrame('lib/cmd.php?cmd=webrun&tgt=&args=installganglia;' + node + '&msg=' + node + '&opts=flush'); - iframe.prependTo($('#nodesTab')); - - // Turn on Ganglia for node - monitorNode(node, 'on'); + var iframe = createIFrame('lib/cmd.php?cmd=webrun&tgt=&args=installganglia;' + node + '&msg=' + node + '&opts=flush'); + iframe.prependTo($('#nodesTab')); + + // Turn on Ganglia for node + monitorNode(node, 'on'); } /** * After nodes are loaded, load more information based on different hardware architectures * - * @param group - * Group name - * @return Nothing + * @param group Group name */ function advancedLoad(group){ var tempIndex = 0; @@ -3268,9 +3151,7 @@ function advancedLoad(group){ /** * Jump to provision page on-click * - * @param tgtNodes - * Target nodes - * @return Nothing + * @param tgtNodes Target nodes */ function jump2Provision(tgtNodes){ var nodeArray = tgtNodes.split(','); @@ -3321,6 +3202,9 @@ function jump2Provision(tgtNodes){ diaDiv.append(createWarnBar(errorMsg)); diaDiv.dialog({ modal: true, + close: function(){ + $(this).remove(); + }, width: 400, buttons: { 'Close': function(){ @@ -3333,16 +3217,17 @@ function jump2Provision(tgtNodes){ } if (origAttrs[nodeName]['xcatmaster']) { - master = origAttrs[nodeName]['xcatmaster']; + master = origAttrs[nodeName]['xcatmaster']; } if (origAttrs[nodeName]['tftpserver']) { - tftpserver = origAttrs[nodeName]['tftpserver']; + tftpserver = origAttrs[nodeName]['tftpserver']; } if (origAttrs[nodeName]['nfsserver']) { - nfsserver = origAttrs[nodeName]['nfsserver']; + nfsserver = origAttrs[nodeName]['nfsserver']; } + window.location.href = 'provision.php?nodes=' + tgtNodes + '&arch=' + archType + '&master=' + master + '&tftpserver=' + tftpserver + '&nfsserver=' + nfsserver; } \ No newline at end of file diff --git a/xCAT-UI/js/nodes/nodeset.js b/xCAT-UI/js/nodes/nodeset.js index 43c6428c0..d49c3871e 100644 --- a/xCAT-UI/js/nodes/nodeset.js +++ b/xCAT-UI/js/nodes/nodeset.js @@ -1,379 +1,375 @@ /** * Load nodeset page * - * @param tgtNodes - * Targets to run nodeset against - * @return Nothing + * @param tgtNodes Targets to run nodeset against */ function loadNodesetPage(tgtNodes) { - // Get OS images - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS images + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); + success : setOSImageCookies + }); - // Get nodes tab - var tab = getNodesTab(); + // Get nodes tab + var tab = getNodesTab(); - // Generate new tab ID - var inst = 0; - var tabId = 'nodesetTab' + inst; - while ($('#' + tabId).length) { - // If one already exists, generate another one - inst = inst + 1; - tabId = 'nodesetTab' + inst; - } + // Generate new tab ID + var inst = 0; + var tabId = 'nodesetTab' + inst; + while ($('#' + tabId).length) { + // If one already exists, generate another one + inst = inst + 1; + tabId = 'nodesetTab' + inst; + } - // Open new tab & create nodeset form - var nodesetForm = $('
                                                              '); + // Open new tab & create nodeset form + var nodesetForm = $('
                                                              '); - // Create status bar - var statBarId = 'nodesetStatusBar' + inst; - var statBar = createStatusBar(statBarId).hide(); - nodesetForm.append(statBar); + // Create status bar + var statBarId = 'nodesetStatusBar' + inst; + var statBar = createStatusBar(statBarId).hide(); + nodesetForm.append(statBar); - // Create loader - var loader = createLoader('nodesetLoader'); - statBar.find('div').append(loader); + // Create loader + var loader = createLoader('nodesetLoader'); + statBar.find('div').append(loader); - // Create info bar - var infoBar = createInfoBar('Set the boot state for a node range'); - nodesetForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Set the boot state for a node range'); + nodesetForm.append(infoBar); - // Create target node or group - var tgt = $('
                                                              '); - nodesetForm.append(tgt); + // Create target node or group + var tgt = $('
                                                              '); + nodesetForm.append(tgt); - // Create boot method drop down - var method = $('
                                                              '); - var methodLabel = $(''); - var methodSelect = $(''); - methodSelect.append('' - + '' - + '' - + '' - + '' - ); - method.append(methodLabel); - method.append(methodSelect); - nodesetForm.append(method); + // Create boot method drop down + var method = $('
                                                              '); + var methodLabel = $(''); + var methodSelect = $(''); + methodSelect.append('' + + '' + + '' + + '' + + '' + ); + method.append(methodLabel); + method.append(methodSelect); + nodesetForm.append(method); - // Create boot type drop down - var type = $('
                                                              '); - var typeLabel = $(''); - var typeSelect = $(''); - typeSelect.append('' - + '' - + '' - ); - type.append(typeLabel); - type.append(typeSelect); - nodesetForm.append(type); + // Create boot type drop down + var type = $('
                                                              '); + var typeLabel = $(''); + var typeSelect = $(''); + typeSelect.append('' + + '' + + '' + ); + type.append(typeLabel); + type.append(typeSelect); + nodesetForm.append(type); - // Create operating system input - var os = $('
                                                              '); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function(){ - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - nodesetForm.append(os); + // Create operating system input + var os = $('
                                                              '); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function(){ + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + nodesetForm.append(os); - // Create architecture input - var arch = $('
                                                              '); - var archLabel = $(''); - var archInput = $(''); - archInput.one('focus', function(){ - var tmp = $.cookie('osarchs'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - arch.append(archLabel); - arch.append(archInput); - nodesetForm.append(arch); + // Create architecture input + var arch = $('
                                                              '); + var archLabel = $(''); + var archInput = $(''); + archInput.one('focus', function(){ + var tmp = $.cookie('osarchs'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + arch.append(archLabel); + arch.append(archInput); + nodesetForm.append(arch); - // Create profiles input - var profile = $('
                                                              '); - var profileLabel = $(''); - var profileInput = $(''); - profileInput.one('focus', function(){ - tmp = $.cookie('profiles'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - profile.append(profileLabel); - profile.append(profileInput); - nodesetForm.append(profile); + // Create profiles input + var profile = $('
                                                              '); + var profileLabel = $(''); + var profileInput = $(''); + profileInput.one('focus', function(){ + tmp = $.cookie('profiles'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + profile.append(profileLabel); + profile.append(profileInput); + nodesetForm.append(profile); - // Generate tooltips - nodesetForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - predelay: 800, - events : { - def : "mouseover,mouseout", - input : "mouseover,mouseout", - widget : "focus mouseover,blur mouseout", - tooltip : "mouseover,mouseout" - } - }); - - /** - * Ok - */ - var okBtn = createButton('Ok'); - okBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - // Check state, OS, arch, and profile - var ready = true; - var inputs = $('#' + tabId + ' input'); - for ( var i = 0; i < inputs.length; i++) { - if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'diskPw') { - inputs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - inputs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } + // Generate tooltips + nodesetForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.7, + predelay: 800, + events : { + def : "mouseover,mouseout", + input : "mouseover,mouseout", + widget : "focus mouseover,blur mouseout", + tooltip : "mouseover,mouseout" + } + }); + + /** + * Ok + */ + var okBtn = createButton('Ok'); + okBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + // Check state, OS, arch, and profile + var ready = true; + var inputs = $('#' + tabId + ' input'); + for ( var i = 0; i < inputs.length; i++) { + if (!inputs.eq(i).val() && inputs.eq(i).attr('name') != 'diskPw') { + inputs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + inputs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } - if (ready) { - // Get nodes - var tgts = $('#' + tabId + ' input[name=target]').val(); - // Get boot method - var method = $('#' + tabId + ' select[id=bootMethod]').val(); - // Get boot type - var type = $('#' + tabId + ' select[id=bootType]').val(); + if (ready) { + // Get nodes + var tgts = $('#' + tabId + ' input[name=target]').val(); + // Get boot method + var method = $('#' + tabId + ' select[id=bootMethod]').val(); + // Get boot type + var type = $('#' + tabId + ' select[id=bootType]').val(); - // Get OS, arch, and profile - var os = $('#' + tabId + ' input[name=os]').val(); - var arch = $('#' + tabId + ' input[name=arch]').val(); - var profile = $('#' + tabId + ' input[name=profile]').val(); + // Get OS, arch, and profile + var os = $('#' + tabId + ' input[name=os]').val(); + var arch = $('#' + tabId + ' input[name=arch]').val(); + var profile = $('#' + tabId + ' input[name=profile]').val(); - // Disable all inputs, selects, and Ok button - inputs.attr('disabled', 'disabled'); - $('#' + tabId + ' select').attr('disabled', 'disabled'); - $(this).attr('disabled', 'true'); + // Disable all inputs, selects, and Ok button + inputs.attr('disabled', 'disabled'); + $('#' + tabId + ' select').attr('disabled', 'disabled'); + $(this).attr('disabled', 'true'); - /** - * (1) Set the OS, arch, and profile - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeadd', - tgt : '', - args : tgts + ';noderes.netboot=' + type - + ';nodetype.os=' + os - + ';nodetype.arch=' + arch - + ';nodetype.profile=' + profile, - msg : 'cmd=nodeadd;inst=' + inst - }, + /** + * (1) Set the OS, arch, and profile + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeadd', + tgt : '', + args : tgts + ';noderes.netboot=' + type + + ';nodetype.os=' + os + + ';nodetype.arch=' + arch + + ';nodetype.profile=' + profile, + msg : 'cmd=nodeadd;inst=' + inst + }, - success : updateNodesetStatus - }); + success : updateNodesetStatus + }); - // Show status bar - statBar.show(); - } else { - // Show warning message - var warn = createWarnBar('You are missing some values'); - warn.prependTo($(this).parent().parent()); - } - }); - nodesetForm.append(okBtn); + // Show status bar + statBar.show(); + } else { + // Show warning message + var warn = createWarnBar('You are missing some values'); + warn.prependTo($(this).parent().parent()); + } + }); + nodesetForm.append(okBtn); - // Append to discover tab - tab.add(tabId, 'Nodeset', nodesetForm, true); + // Append to discover tab + tab.add(tabId, 'Nodeset', nodesetForm, true); - // Select new tab - tab.select(tabId); + // Select new tab + tab.select(tabId); } /** * Update nodeset status * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function updateNodesetStatus(data) { - // Get ajax response - var rsp = data.rsp; - var args = data.msg.split(';'); - var cmd = args[0].replace('cmd=', ''); + // Get ajax response + var rsp = data.rsp; + var args = data.msg.split(';'); + var cmd = args[0].replace('cmd=', ''); - // Get nodeset instance - var inst = args[1].replace('inst=', ''); - // Get status bar ID - var statBarId = 'nodesetStatusBar' + inst; - // Get tab ID - var tabId = 'nodesetTab' + inst; + // Get nodeset instance + var inst = args[1].replace('inst=', ''); + // Get status bar ID + var statBarId = 'nodesetStatusBar' + inst; + // Get tab ID + var tabId = 'nodesetTab' + inst; - // Get nodes - var tgts = $('#' + tabId + ' input[name=target]').val(); - // Get boot method - var method = $('#' + tabId + ' select[id=bootMethod]').val(); + // Get nodes + var tgts = $('#' + tabId + ' input[name=target]').val(); + // Get boot method + var method = $('#' + tabId + ' select[id=bootMethod]').val(); - /** - * (2) Update /etc/hosts - */ - if (cmd == 'nodeadd') { - if (rsp.length) { - $('#' + statBarId).find('img').hide(); - $('#' + statBarId).find('div').append('
                                                              (Error) Failed to create node definition
                                                              '); - } else { - // Create target nodes string - var tgtNodesStr = ''; - var nodes = tgts.split(','); - - // Loop through each node - for ( var i in nodes) { - // If it is the 1st and only node - if (i == 0 && i == nodes.length - 1) { - tgtNodesStr += nodes[i]; - } - // If it is the 1st node of many nodes - else if (i == 0 && i != nodes.length - 1) { - // Append a comma to the string - tgtNodesStr += nodes[i] + ', '; - } else { - // If it is the last node - if (i == nodes.length - 1) { - // Append nothing to the string - tgtNodesStr += nodes[i]; - } else { - // Append a comma to the string - tgtNodesStr += nodes[i] + ', '; - } - } - } - - $('#' + statBarId).find('div').append('
                                                              Node definition created for ' + tgtNodesStr + '
                                                              '); - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makehosts', - tgt : '', - args : '', - msg : 'cmd=makehosts;inst=' + inst - }, + /** + * (2) Update /etc/hosts + */ + if (cmd == 'nodeadd') { + if (rsp.length) { + $('#' + statBarId).find('img').hide(); + $('#' + statBarId).find('div').append('
                                                              (Error) Failed to create node definition
                                                              '); + } else { + // Create target nodes string + var tgtNodesStr = ''; + var nodes = tgts.split(','); + + // Loop through each node + for ( var i in nodes) { + // If it is the 1st and only node + if (i == 0 && i == nodes.length - 1) { + tgtNodesStr += nodes[i]; + } + // If it is the 1st node of many nodes + else if (i == 0 && i != nodes.length - 1) { + // Append a comma to the string + tgtNodesStr += nodes[i] + ', '; + } else { + // If it is the last node + if (i == nodes.length - 1) { + // Append nothing to the string + tgtNodesStr += nodes[i]; + } else { + // Append a comma to the string + tgtNodesStr += nodes[i] + ', '; + } + } + } + + $('#' + statBarId).find('div').append('
                                                              Node definition created for ' + tgtNodesStr + '
                                                              '); + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makehosts', + tgt : '', + args : '', + msg : 'cmd=makehosts;inst=' + inst + }, - success : updateNodesetStatus - }); - } - } + success : updateNodesetStatus + }); + } + } - /** - * (4) Update DNS - */ - else if (cmd == 'makehosts') { - // If no output, no errors occurred - if (rsp.length) { - $('#' + statBarId).find('div').append('
                                                              (Error) Failed to update /etc/hosts
                                                              '); - } else { - $('#' + statBarId).find('div').append('
                                                              /etc/hosts updated
                                                              '); - } + /** + * (4) Update DNS + */ + else if (cmd == 'makehosts') { + // If no output, no errors occurred + if (rsp.length) { + $('#' + statBarId).find('div').append('
                                                              (Error) Failed to update /etc/hosts
                                                              '); + } else { + $('#' + statBarId).find('div').append('
                                                              /etc/hosts updated
                                                              '); + } - // Update DNS - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makedns', - tgt : '', - args : '', - msg : 'cmd=makedns;inst=' + inst - }, + // Update DNS + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makedns', + tgt : '', + args : '', + msg : 'cmd=makedns;inst=' + inst + }, - success : updateNodesetStatus - }); - } + success : updateNodesetStatus + }); + } - /** - * (5) Update DHCP - */ - else if (cmd == 'makedns') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); - - // Update DHCP - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'makedhcp', - tgt : '', - args : '-a', - msg : 'cmd=makedhcp;inst=' + inst - }, + /** + * (5) Update DHCP + */ + else if (cmd == 'makedns') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); + + // Update DHCP + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'makedhcp', + tgt : '', + args : '-a', + msg : 'cmd=makedhcp;inst=' + inst + }, - success : updateNodesetStatus - }); - } + success : updateNodesetStatus + }); + } - /** - * (6) Prepare node for boot - */ - else if (cmd == 'makedhcp') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + /** + * (6) Prepare node for boot + */ + else if (cmd == 'makedhcp') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // Prepare node for boot - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodeset', - tgt : tgts, - args : method, - msg : 'cmd=nodeset;inst=' + inst - }, + // Prepare node for boot + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodeset', + tgt : tgts, + args : method, + msg : 'cmd=nodeset;inst=' + inst + }, - success : updateNodesetStatus - }); - } + success : updateNodesetStatus + }); + } - /** - * (7) Boot node from network - */ - else if (cmd == 'nodeset') { - // Write ajax response to status bar - var prg = writeRsp(rsp, ''); - $('#' + statBarId).find('div').append(prg); + /** + * (7) Boot node from network + */ + else if (cmd == 'nodeset') { + // Write ajax response to status bar + var prg = writeRsp(rsp, ''); + $('#' + statBarId).find('div').append(prg); - // Hide loader - $('#' + statBarId).find('img').hide(); - } + // Hide loader + $('#' + statBarId).find('img').hide(); + } } \ No newline at end of file diff --git a/xCAT-UI/js/nodes/physical.js b/xCAT-UI/js/nodes/physical.js index 498ffd35c..ab8ca607c 100644 --- a/xCAT-UI/js/nodes/physical.js +++ b/xCAT-UI/js/nodes/physical.js @@ -8,95 +8,95 @@ var graphicalNodeList; var selectNode; /** - * get all nodes useful attributes from remote server. + * Get all nodes useful attributes from remote server * - * @param dataTypeIndex: the index in Array graphicalDataType, which contains attributes we need. - * attrNullNode: the target node list for this attribute - * - * @return null + * @param dataTypeIndex The index in the array which contains attributes we need. + * @param attrNullNode The target node list for this attribute */ -function initGraphicalData(){ - $('#graphTab').append(createLoader()); - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'graph', - msg : '' - }, - success: function(data){ - if(!data.rsp[0]){ - return; - } - extractGraphicalData(data.rsp[0]); - getNodesAndDraw(); - } - }); +function initGraphicalData() { + $('#graphTab').append(createLoader()); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'graph', + msg : '' + }, + success : function(data) { + if (!data.rsp[0]) { + return; + } + extractGraphicalData(data.rsp[0]); + getNodesAndDraw(); + } + }); } /** - * extract all nodes userful data into a hash, which is used for creating graphical + * Extract all nodes userful data into a hash, which will be used for creating graphical * - * @param data: the response from xcat command "nodels all nodetype.nodetype ppc.parent ..." + * @param data The response from xCAT command 'nodels all nodetype.nodetype ppc.parent ...' * @return nodes list for next time query */ -function extractGraphicalData(data){ - var nodes = data.split(';'); - var attrs; - var nodename; - //extract useful info into tempList - for (var i = 0; i < nodes.length; i++){ - attrs = nodes[i].split(':'); - nodename = attrs[0]; - if (undefined == graphicalNodeList[nodename]){ - graphicalNodeList[nodename] = new Object(); - } - graphicalNodeList[nodename]['type'] = attrs[1].toLowerCase(); - switch(attrs[1].toLowerCase()){ - case 'cec': - case 'frame': - case 'lpar': - case 'lpar,osi': - case 'osi,lpar': - graphicalNodeList[nodename]['parent'] = attrs[2]; - graphicalNodeList[nodename]['mtm'] = attrs[3]; - graphicalNodeList[nodename]['status'] = attrs[4]; - break; - case 'blade': - graphicalNodeList[nodename]['mpa'] = attrs[2]; - graphicalNodeList[nodename]['unit'] = attrs[3]; - graphicalNodeList[nodename]['status'] = attrs[4]; - break; - case 'systemx': - graphicalNodeList[nodename]['rack'] = attrs[2]; - graphicalNodeList[nodename]['unit'] = attrs[3]; - graphicalNodeList[nodename]['mtm'] = attrs[4]; - graphicalNodeList[nodename]['status'] = attrs[5]; - break; - default: - break; - } - } +function extractGraphicalData(data) { + var nodes = data.split(';'); + var attrs; + var nodeName; + + // Extract useful info into tempList + for (var i = 0; i < nodes.length; i++) { + attrs = nodes[i].split(':'); + nodeName = attrs[0]; + if (undefined == graphicalNodeList[nodeName]) { + graphicalNodeList[nodeName] = new Object(); + } + + graphicalNodeList[nodeName]['type'] = attrs[1].toLowerCase(); + switch (attrs[1].toLowerCase()) { + case 'cec': + case 'frame': + case 'lpar': + case 'lpar,osi': + case 'osi,lpar': + graphicalNodeList[nodeName]['parent'] = attrs[2]; + graphicalNodeList[nodeName]['mtm'] = attrs[3]; + graphicalNodeList[nodeName]['status'] = attrs[4]; + break; + case 'blade': + graphicalNodeList[nodeName]['mpa'] = attrs[2]; + graphicalNodeList[nodeName]['unit'] = attrs[3]; + graphicalNodeList[nodeName]['status'] = attrs[4]; + break; + case 'systemx': + graphicalNodeList[nodeName]['rack'] = attrs[2]; + graphicalNodeList[nodeName]['unit'] = attrs[3]; + graphicalNodeList[nodeName]['mtm'] = attrs[4]; + graphicalNodeList[nodeName]['status'] = attrs[5]; + break; + default: + break; + } + } } -function createPhysicalLayout(nodeList){ - var flag = false; - - //when the graphical layout is shown, do not need to redraw - if (1 < $('#graphTab').children().length){ - return; - } - - //save the new selected nodes. - if (graphicalNodeList){ - for(var i in graphicalNodeList){ - flag = true; - break; - } - } - +function createPhysicalLayout(nodeList) { + var flag = false; + + // When the graphical layout is shown, do not need to redraw + if (1 < $('#graphTab').children().length) { + return; + } + + // Save the new selected nodes + if (graphicalNodeList) { + for (var i in graphicalNodeList) { + flag = true; + break; + } + } + bpaList = new Object(); fspList = new Object(); lparList = new Object(); @@ -104,800 +104,773 @@ function createPhysicalLayout(nodeList){ selectNode = new Object(); rackList = new Object(); unknownList = new Array(); - - //there is not graphical data, get the info now - if (!flag){ - graphicalNodeList = new Object(); - initGraphicalData(); - } - else{ - getNodesAndDraw(); - } + + // There is no graphical data, get the info now + if (!flag) { + graphicalNodeList = new Object(); + initGraphicalData(); + } else { + getNodesAndDraw(); + } } -function getNodesAndDraw(){ - var groupname = $.cookie('selectgrouponnodes'); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'nodels', - tgt : groupname, - args : '', - msg : '' - }, - success : function(data){ - for (var temp in data.rsp){ - var nodeName = data.rsp[temp][0]; - if ('' == nodeName){ - continue; - } - fillList(nodeName); - } - $('#graphTab').empty(); - createGraphical(); - } - }); +function getNodesAndDraw() { + var groupName = $.cookie('selectgrouponnodes'); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'nodels', + tgt : groupName, + args : '', + msg : '' + }, + success : function(data) { + for (var temp in data.rsp) { + var nodeName = data.rsp[temp][0]; + if ('' == nodeName) { + continue; + } + fillList(nodeName); + } + $('#graphTab').empty(); + createGraphical(); + } + }); } -function fillList(nodeName, defaultnodetype){ +function fillList(nodeName, defaultnodetype) { var parentName = ''; var mtm = ''; var status = ''; - var nodetype = ''; + var nodeType = ''; var mpa = ''; var unit = ''; var rack = ''; - if (!graphicalNodeList[nodeName]){ + if (!graphicalNodeList[nodeName]) { parentName = ''; mtm = ''; status = ''; - nodetype = defaultnodetype; + nodeType = defaultnodetype; + } else { + status = graphicalNodeList[nodeName]['status']; + nodeType = graphicalNodeList[nodeName]['type']; + switch (nodeType) { + case 'frame': + case 'lpar,osi': + case 'lpar': + case 'osi': + case 'cec': + parentName = graphicalNodeList[nodeName]['parent']; + mtm = graphicalNodeList[nodeName]['mtm']; + break; + case 'blade': + mpa = graphicalNodeList[nodeName]['mpa']; + unit = graphicalNodeList[nodeName]['unit']; + break; + case 'systemx': + rack = graphicalNodeList[nodeName]['rack']; + unit = graphicalNodeList[nodeName]['unit']; + break; + default: + break; + } + } - else{ - status = graphicalNodeList[nodeName]['status']; - nodetype = graphicalNodeList[nodeName]['type']; - switch (nodetype){ - case 'frame': - case 'lpar,osi': - case 'lpar': - case 'osi': - case 'cec':{ - parentName = graphicalNodeList[nodeName]['parent']; - mtm = graphicalNodeList[nodeName]['mtm']; - } - break; - case 'blade':{ - mpa = graphicalNodeList[nodeName]['mpa']; - unit = graphicalNodeList[nodeName]['unit']; - } - break; - case 'systemx':{ - rack = graphicalNodeList[nodeName]['rack']; - unit = graphicalNodeList[nodeName]['unit']; - } - break; - default: - break; - } + + if ('' == status) { + status = 'unknown'; + } + + switch (nodeType) { + case 'frame': + if (undefined == bpaList[nodeName]) { + bpaList[nodeName] = new Array(); + } + break; + case 'lpar,osi': + case 'lpar': + case 'osi': + if ('' == parentName) { + break; + } + + if (undefined == fspList[parentName]) { + fillList(parentName, 'cec'); + } + + fspList[parentName]['children'].push(nodeName); + lparList[nodeName] = status; + + break; + case 'cec': + if (undefined != fspList[nodeName]) { + break; + } + + fspList[nodeName] = new Object(); + fspList[nodeName]['children'] = new Array(); + fspList[nodeName]['mtm'] = mtm; + + if ('' == parentName) { + break; + } + + if (undefined == bpaList[parentName]) { + fillList(parentName, 'frame'); + } + + bpaList[parentName].push(nodeName); + break; + case 'blade': + if (undefined == bladeList[mpa]) { + bladeList[mpa] = new Array(); + } + bladeList[mpa].push(nodeName + ',' + unit); + + break; + case 'systemx': + if (!rack) { + rack = '_notsupply_'; + } + + if (undefined == rackList[rack]) { + rackList[rack] = new Array(); + } + + rackList[rack].push(nodeName + ',' + unit); + + break; + default: + unknownList.push(nodeName); + break; + } +} + +function createGraphical() { + var tabArea = $('#graphTab'); + var selectNodeDiv = $('
                                                              '); + var temp = 0; + for (var i in selectNode) { + temp++; + break; + } + + // There is no selected LPAR, show the info bar + if (temp == 0) { + tabArea.append(createInfoBar('Hover over a CEC and select the LPARs to do operations against.')); + } else { + // Show selected LPARs + updateSelectNodeDiv(); + } + + // Add buttons + tabArea.append(createActionMenu()); + tabArea.append(selectNodeDiv); + createSystempGraphical(bpaList, fspList, tabArea); + createBladeGraphical(bladeList, tabArea); + createSystemxGraphical(rackList, tabArea); + addUnknownGraphical(unknownList, tabArea); +} + +/** + * Create the physical/graphical layout for System p machines + * + * @param bpa All BPA and their related FSPs + * @param fsp All FSP and their related LPARs + * @param area The element to append graphical layout + */ +function createSystempGraphical(bpa, fsp, area) { + var usedFsp = new Object(); + var graphTable = $('
                                                              '); + var elementNum = 0; + var row = null; + var showFlag = false; + + // There is a node in the BPA list, so show add the title and show all frames + for (var bpaName in bpa) { + showFlag = true; + $('#graphTab').append('system p
                                                              '); + $('#graphTab').append(graphTable); + break; + } + + for (var bpaName in bpa) { + if (0 == elementNum % 3) { + row = $(''); + graphTable.append(row); + } + + elementNum++; + + var td = $(''); + var frameDiv = $('
                                                              '); + frameDiv.append('
                                                              '); + + // For P7-IH, all the CECs are insert into the frame from bottom to up, + // so we have to show the CECs same as the physical layout + var tempBlankDiv = $('
                                                              '); + var tempHeight = 0; + for (var fspIndex in bpa[bpaName]) { + var fspName = bpa[bpaName][fspIndex]; + usedFsp[fspName] = 1; + + // This is the P7-IH, we should add the blank at the top + if ((0 == fspIndex) && ('9125-F2C' == fsp[fspName]['mtm'])) { + frameDiv.append(tempBlankDiv); + } + + frameDiv.append(createFspDiv(fspName, fsp[fspName]['mtm'], fsp)); + frameDiv.append(createFspTip(fspName, fsp[fspName]['mtm'], fsp)); + + tempHeight += calculateBlank(fsp[fspName]['mtm']); + } + + // tempHeight is the total height for all CECs, so we should minus BPA div + // height and CEC div heights + tempHeight = 428 - tempHeight; + tempBlankDiv.css('height', tempHeight); + td.append(frameDiv); + row.append(td); + } + + // Find the single FSP and sort descend by units + var singleFsp = new Array(); + for (var fspName in fsp) { + if (usedFsp[fspName]) { + continue; + } + + singleFsp.push([ fspName, fsp[fspName]['mtm'] ]); + } + + // If there is no frame, we should check if there is single CEC and show + // the title and add node area + if (!showFlag) { + for (var fspIndex in singleFsp) { + $('#graphTab').append('system p
                                                              '); + $('#graphTab').append(graphTable); + break; + } + } + + singleFsp.sort(function(a, b) { + var unitNumA = 4; + var unitNumB = 4; + if (hardwareInfo[a[1]]) { + unitNumA = hardwareInfo[a[1]][1]; + } + + if (hardwareInfo[b[1]]) { + unitNumB = hardwareInfo[b[1]][1]; + } + + return (unitNumB - unitNumA); + }); + + elementNum = 0; + for (var fspIndex in singleFsp) { + var fspName = singleFsp[fspIndex][0]; + if (0 == elementNum % 3) { + row = $(''); + graphTable.append(row); + } + elementNum++; + + var td = $(''); + td.append(createFspDiv(fspName, fsp[fspName]['mtm'], fsp)); + td.append(createFspTip(fspName, fsp[fspName]['mtm'], fsp)); + row.append(td); + } + + $('.tooltip input[type = checkbox]').bind('click', function() { + var lparName = $(this).attr('name'); + if ('' == lparName) { + return; + } + if (true == $(this).attr('checked')) { + changeNode(lparName, 'select'); + } else { + changeNode(lparName, 'unselect'); + } + + updateSelectNodeDiv(); + }); + + $('.fspDiv2, .fspDiv4, .fspDiv42').tooltip({ + position : "center right", + relative : true, + offset : [ 10, -40 ], + effect : "fade", + opacity : 0.9 + }); + + $('.tooltip a').bind('click', function() { + var lparName = $(this).html(); + $('#nodesDatatable #' + lparName).trigger('click'); + }); + + $('.fspDiv2, .fspDiv4, .fspDiv42').bind('click', function() { + var fspName = $(this).attr('value'); + var selectCount = 0; + for (var lparIndex in fspList[fspName]['children']) { + var lparName = fspList[fspName]['children'][lparIndex]; + if (selectNode[lparName]) { + selectCount++; + } + } + + // All LPARs are selected, so unselect nodes + if (selectCount == fspList[fspName]['children'].length) { + for (var lparIndex in fspList[fspName]['children']) { + var lparName = fspList[fspName]['children'][lparIndex]; + changeNode(lparName, 'unselect'); + } + } + + // No selected LPARs on the cec, so add all LPARs into selectNode hash + else { + for (var lparIndex in fspList[fspName]['children']) { + var lparName = fspList[fspName]['children'][lparIndex]; + changeNode(lparName, 'select'); + } + } + + updateSelectNodeDiv(); + }); + + $('.fspCheckbox').bind('click', function() { + var itemName = $(this).attr('name'); + name = itemName.substr(6); + + if ($(this).attr('checked')) { + selectNode[name] = 1; + } else { + delete selectNode[name]; + } + + updateSelectNodeDiv(); + }); +} + +/** + * Create the physical/graphical layout for blades + * + * @param blades The blade list in global + * @param area The element to append the graphical layout + */ +function createBladeGraphical(blades, area) { + var graphTable = $('
                                                              '); + var mpa = ''; + var bladeName = ''; + var index = 0; + var mpaNumber = 0; + var row; + var showFlag = false; + + // Only show the title and nodes when there are blade in the blade list + for (mpa in blades) { + showFlag = true; + break; + } + + if (showFlag) { + $('#graphTab').append('Blade
                                                              '); + $('#graphTab').append(graphTable); + } + // If there is no blade node, return directly + else { + return; + } + + for (mpa in blades) { + var tempArray = new Array(14); + var bladeInfo = new Array(); + var unit = 0; + if (0 == mpaNumber % 3) { + row = $(''); + graphTable.append(row); + } + + mpaNumber++; + + var td = $(''); + var chasisDiv = $('
                                                              '); + + // Fill the array with blade information, to create the empty slot + for (index in blades[mpa]) { + bladeInfo = blades[mpa][index].split(','); + unit = parseInt(bladeInfo[1]); + tempArray[unit - 1] = bladeInfo[0]; + + } + + // Draw the blades and empty slot in chasis + for (index = 0; index < 14; index++) { + if (tempArray[index]) { + bladeName = tempArray[index]; + chasisDiv.append('
                                                              '); + } else { + chasisDiv.append('
                                                              '); + } + } + + td.append(chasisDiv); + row.append(td); + } + +} + +/** + * Create the physical/graphical layout for System x machines + * + * @param xnodes The system x node list in global + * @param area The element to append graphical layout + */ +function createSystemxGraphical(xnodes, area) { + var graphTable = $('
                                                              '); + var xnodename = ''; + var index = 0; + var rack = ''; + var row; + var xNodeCount = 0; + var showflag = false; + + // Only the title and System x node when there are x nodes in the list + for (rack in rackList) { + showflag = true; + break; + } + + if (showflag) { + $('#graphTab').append('system x
                                                              '); + $('#graphTab').append(graphTable); + } + // There is nothing to show, return directly + else { + return; + } + + for (rack in rackList) { + for (index in rackList[rack]) { + var xNodeName = rackList[rack][index]; + if (0 == xNodeCount % 3) { + row = $(''); + graphTable.append(row); + } + xNodeCount++; + var td = $(''); + var xNodeDiv = '
                                                              '; + td.append(xNodeDiv); + row.append(td); + } + } +} + +function addUnknownGraphical(unknownNodes, tab) { + // Do not continue if no nodes were found + if (unknownNodes.length < 1) + return; + + var list = ""; + tab.append('
                                                              '); + for (var index in unknownNodes) { + list += unknownNodes[index] + ', '; + + } + + // Delete last comma + list = list.substr(0, list.length - 2); + tab.append(list); +} + +/** + * Update the LPARs background in CEC, LPAR area and selectNode + */ +function updateSelectNodeDiv() { + var temp = 0; + $('#selectNodeDiv').empty(); + + // Add buttons + if (selectNode.length) { + $('#selectNodeDiv').append('Nodes: '); + for (var lparName in selectNode) { + $('#selectNodeDiv').append(lparName + ' '); + temp++; + if (temp > 6) { + $('#selectNodeDiv').append('...'); + break; + } + } + } +} + +/** + * Create the action menu + */ +function createActionMenu() { + // Create action bar + var actionBar = $('
                                                              '); + + // Power on + var powerOnLnk = $('Power on'); + powerOnLnk.click(function() { + var tgtNodes = getSelectNodes(); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : tgtNodes, + args : 'on', + msg : '' + } + }); + }); + + // Power off + var powerOffLnk = $('Power off'); + powerOffLnk.click(function() { + var tgtNodes = getSelectNodes(); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : tgtNodes, + args : 'off', + msg : '' + } + }); + }); + + // Delete + var deleteLnk = $('Delete'); + deleteLnk.click(function() { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadDeletePage(tgtNodes); + } + }); + + // Unlock + var unlockLnk = $('Unlock'); + unlockLnk.click(function() { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadUnlockPage(tgtNodes); + } + }); + + // Run script + var scriptLnk = $('Run script'); + scriptLnk.click(function() { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadScriptPage(tgtNodes); + } + }); + + // Update + var updateLnk = $('Update'); + updateLnk.click(function() { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadUpdatenodePage(tgtNodes); + } + }); + + // Set boot state + var setBootStateLnk = $('Set boot state'); + setBootStateLnk.click(function() { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadNodesetPage(tgtNodes); + } + }); + + // Boot to network + var boot2NetworkLnk = $('Boot to network'); + boot2NetworkLnk.click(function() { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadNetbootPage(tgtNodes); + } + }); + + // Remote console + var rconLnk = $('Open console'); + rconLnk.bind('click', function(event) { + var tgtNodes = getSelectNodes(); + if (tgtNodes) { + loadRconsPage(tgtNodes); + } + }); + + // Edit properties + var editProps = $('Edit properties'); + editProps.bind('click', function(event) { + for (var node in selectNode) { + loadEditPropsPage(node); + } + }); + + // Actions + var actionsLnk = 'Actions'; + var actsMenu = createMenu([ deleteLnk, powerOnLnk, powerOffLnk, scriptLnk ]); + + // Configurations + var configLnk = 'Configuration'; + var configMenu = createMenu([ unlockLnk, updateLnk, editProps ]); + + // Provision + var provLnk = 'Provision'; + var provMenu = createMenu([ boot2NetworkLnk, setBootStateLnk, rconLnk ]); + + // Create an action menu + var actionsMenu = createMenu([ [ actionsLnk, actsMenu ], + [ configLnk, configMenu ], [ provLnk, provMenu ] ]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + actionBar.css('margin-top', '10px'); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + return actionBar; +} + +/** + * Create the physical/graphical layout + */ +function createFspDiv(fspName, mtm, fsp) { + // Create FSP title + var lparStatusRow = ''; + var temp = ''; + + for (var lparIndex in fsp[fspName]['children']) { + // Show 8 lpars on one cec at most. + if (lparIndex >= 8) { + break; + } + + var lparName = fsp[fspName]['children'][lparIndex]; + var color = statusMap(lparList[lparName]); + lparStatusRow += ''; + } + + // Select the backgroud + var divClass = ''; + if ('' == mtm) { + temp = '8231-E2B'; + } else { + temp = mtm; } - if ('' == status){ - status = 'unknown'; - } - - switch (nodetype){ - case 'frame': { - if (undefined == bpaList[nodeName]){ - bpaList[nodeName] = new Array(); - } - } - break; - case 'lpar,osi': - case 'lpar': - case 'osi': { - if ('' == parentName){ - break; - } - - if (undefined == fspList[parentName]){ - fillList(parentName, 'cec'); - } - - fspList[parentName]['children'].push(nodeName); - lparList[nodeName] = status; - } - break; - case 'cec': { - if (undefined != fspList[nodeName]){ - break; - } - - fspList[nodeName] = new Object(); - fspList[nodeName]['children'] = new Array(); - fspList[nodeName]['mtm'] = mtm; - - if ('' == parentName){ - break; - } - - if (undefined == bpaList[parentName]){ - fillList(parentName, 'frame'); - } - - bpaList[parentName].push(nodeName); - } - break; - case 'blade': { - if (undefined == bladeList[mpa]){ - bladeList[mpa] = new Array(); - } - bladeList[mpa].push(nodeName + ',' + unit); - } - break; - case 'systemx':{ - if (!rack){ - rack = '_notsupply_'; - } - if (undefined == rackList[rack]){ - rackList[rack] = new Array(); - } - rackList[rack].push(nodeName + ',' + unit); - } - break; - default: - unknownList.push(nodeName); - break; - } + if (hardwareInfo[temp][1]) { + divClass += 'fspDiv' + hardwareInfo[temp][1]; + } else { + divClass += 'fspDiv4'; + } + + // Create return value + var retHtml = ''; + retHtml += '
                                                              '; + retHtml += '
                                                              ' + lparStatusRow + + '
                                                              '; + return retHtml; } -function createGraphical(){ - var tabarea = $('#graphTab'); - var selectNodeDiv = $('
                                                              '); - var temp = 0; - for (var i in selectNode){ - temp ++; - break; - } - - //there is not selected lpars, show the info bar - if (temp == 0){ - tabarea.append(createInfoBar('Hover over a CEC and select the LPARs to do operations against.')); - } - //show selected lpars - else{ - updateSelectNodeDiv(); - } - - //add buttons - tabarea.append(createActionMenu()); - tabarea.append(selectNodeDiv); - createSystempGraphical(bpaList, fspList, tabarea); - createBladeGraphical(bladeList, tabarea); - createSystemxGraphical(rackList, tabarea); - addUnknownGraphical(unknownList, tabarea); -} /** - * create the physical graphical layout for system p machines - * - * @param bpa : all bpa and there related fsps - * fsp : all fsp and there related lpars - * fspinfo : all fsps' hardwareinfo - * area: the element to append graphical layout - * @return + * Create the physical/graphical FSP tooltip which is used to select the LPAR */ -function createSystempGraphical(bpa, fsp, area){ - var usedFsp = new Object(); - var graphTable = $('
                                                              '); - var elementNum = 0; - var row; - var showflag = false; - - //there is node in bpa list, so show add the title and show all frames - for (var bpaName in bpa){ - showflag = true; - $('#graphTab').append('system p
                                                              '); - $('#graphTab').append(graphTable); - break; - } - - for (var bpaName in bpa){ - if (0 == elementNum % 3){ - row = $(''); - graphTable.append(row); - } - - elementNum ++; - - var td = $(''); - var frameDiv = $('
                                                              '); - frameDiv.append('
                                                              '); - - //for P7-IH, all the cecs are insert into the frame from down to up, so we had to show the cecs same as the - //physical layout. - var tempBlankDiv = $('
                                                              '); - var tempHeight = 0; - for (var fspIndex in bpa[bpaName]){ - var fspName = bpa[bpaName][fspIndex]; - usedFsp[fspName] = 1; - - //this is the p7IH, we should add the blank at the top - if ((0 == fspIndex) && ('9125-F2C' == fsp[fspName]['mtm'])){ - frameDiv.append(tempBlankDiv); - } - frameDiv.append(createFspDiv(fspName, fsp[fspName]['mtm'], fsp)); - frameDiv.append(createFspTip(fspName, fsp[fspName]['mtm'], fsp)); - - tempHeight += coculateBlank(fsp[fspName]['mtm']); - } - - //now the tempHeight are all cecs' height, so we should minus bpa div height and cecs' div height - tempHeight = 428 - tempHeight; - tempBlankDiv.css('height', tempHeight); - td.append(frameDiv); - row.append(td); - } - - //find the single fsp and sort descend by units - var singleFsp = new Array(); - for (var fspName in fsp){ - if (usedFsp[fspName]){ - continue; - } - - singleFsp.push([fspName, fsp[fspName]['mtm']]); - } - - //if there is not frame, so we should check if there is single cec and show the title and add node area. - if (!showflag){ - for(var fspIndex in singleFsp){ - $('#graphTab').append('system p
                                                              '); - $('#graphTab').append(graphTable); - break; - } - } - - singleFsp.sort(function(a, b){ - var unitNumA = 4; - var unitNumB = 4; - if (hardwareInfo[a[1]]){ - unitNumA = hardwareInfo[a[1]][1]; - } - - if (hardwareInfo[b[1]]){ - unitNumB = hardwareInfo[b[1]][1]; - } - - return (unitNumB - unitNumA); - }); - - - elementNum = 0; - for (var fspIndex in singleFsp){ - var fspName = singleFsp[fspIndex][0]; - if (0 == elementNum % 3){ - row = $(''); - graphTable.append(row); - } - elementNum ++; +function createFspTip(fspName, mtm, fsp) { + var tip = $('
                                                              '); + var tempTable = $('
                                                              '); + var temp = ''; + if ('' == mtm) { + temp = 'unkown'; + } else { + temp = mtm; + } - var td = $(''); - td.append(createFspDiv(fspName, fsp[fspName]['mtm'], fsp)); - td.append(createFspTip(fspName, fsp[fspName]['mtm'], fsp)); - row.append(td); - } - - - $('.tooltip input[type = checkbox]').bind('click', function(){ - var lparName = $(this).attr('name'); - if ('' == lparName){ - return; - } - if (true == $(this).attr('checked')){ - changeNode(lparName, 'select'); - } - else{ - changeNode(lparName, 'unselect'); - } - - updateSelectNodeDiv(); - }); - - $('.fspDiv2, .fspDiv4, .fspDiv42').tooltip({ - position: "center right", - relative : true, - offset : [10, -40], - effect: "fade", - opacity: 0.9 - }); - - $('.tooltip a').bind('click', function(){ - var lparName = $(this).html(); - $('#nodesDatatable #' + lparName).trigger('click'); - }); - - $('.fspDiv2, .fspDiv4, .fspDiv42').bind('click', function(){ - var fspName = $(this).attr('value'); - var selectCount = 0; - for (var lparIndex in fspList[fspName]['children']){ - var lparName = fspList[fspName]['children'][lparIndex]; - if (selectNode[lparName]){ - selectCount ++; - } - } - - //all the lpars are selected, so unselect nodes - if (selectCount == fspList[fspName]['children'].length){ - for (var lparIndex in fspList[fspName]['children']){ - var lparName = fspList[fspName]['children'][lparIndex]; - changeNode(lparName, 'unselect'); - } - } - //not select all lpars on the cec, so add all lpars into selectNode Hash. - else{ - for (var lparIndex in fspList[fspName]['children']){ - var lparName = fspList[fspName]['children'][lparIndex]; - changeNode(lparName, 'select'); - } - } - - updateSelectNodeDiv(); - }); - - $('.fspcheckbox').bind('click', function(){ - var itemName = $(this).attr('name'); - name = itemName.substr(6); - - if ($(this).attr('checked')){ - selectNode[name] = 1; - } - else{ - delete selectNode[name]; - } - - updateSelectNodeDiv(); - }); + if (hardwareInfo[temp]) { + tip.append('

                                                              ' + fspName + '(' + hardwareInfo[temp][0] + ')


                                                              '); + } else { + tip.append('

                                                              ' + fspName + '


                                                              '); + } + + for (var lparIndex in fsp[fspName]['children']) { + var lparName = fsp[fspName]['children'][lparIndex]; + var color = statusMap(lparList[lparName]); + var row = ''; + row += '' + lparName + ''; + row += '' + lparList[lparName] + ''; + tempTable.append(row); + } + + tip.append(tempTable); + return tip; } - /** - * create the physical graphical layout for blades + * Map the LPAR status into a color * - * @param blades : the blade list in global - * area: the element to append graphical layout - * @return + * @param status LPAR status in nodelist table + * @return Corresponding color name */ -function createBladeGraphical(blades, area){ - var graphTable = $('
                                                              '); - var mpa = ''; - var bladename = ''; - var index = 0; - var mpaNumber = 0; - var row; - var showflag = false; - - //only show the title and nodes when there are blade in the blade list - for (mpa in blades){ - showflag = true; - break; - } - - if (showflag){ - $('#graphTab').append('Blade
                                                              '); - $('#graphTab').append(graphTable); - } - //if there is not blade nodes, return directly - else{ - return; - } - - for (mpa in blades){ - var tempArray = new Array(14); - var bladeInfo = new Array(); - var unit = 0; - if (0 == mpaNumber % 3){ - row = $(''); - graphTable.append(row); - } - - mpaNumber ++; - - var td = $(''); - var chasisDiv = $('
                                                              '); - - - //fill the array with blade information, to create the empty slot - for (index in blades[mpa]){ - bladeInfo = blades[mpa][index].split(','); - unit = parseInt(bladeInfo[1]); - tempArray[unit - 1] = bladeInfo[0]; - - } - - //draw the blades and empty slot in chasis - for (index = 0; index < 14; index++){ - if (tempArray[index]){ - bladename = tempArray[index]; - chasisDiv.append('
                                                              '); - } - else{ - chasisDiv.append('
                                                              '); - } - } - - td.append(chasisDiv); - row.append(td); - } - +function statusMap(status) { + var color = 'gainsboro'; + + switch (status) { + case 'alive': + case 'ready': + case 'pbs': + case 'sshd': + case 'booting': + case 'booted': + case 'ping': + color = 'green'; + break; + case 'noping': + case 'unreachable': + color = 'red'; + break; + default: + color = 'grey'; + break; + } + + return color; } /** - * create the physical graphical layout for system x machines - * - * @param xnodes : the system x node list in global - * area: the element to append graphical layout - * @return + * Select all LPAR checkboxes */ -function createSystemxGraphical(xnodes, area){ - var graphTable = $('
                                                              '); - var xnodename = ''; - var index = 0; - var rack = ''; - var row; - var xnodenum = 0; - var showflag = false; - - //only the title and system x node when there is x nodes in the list - for (rack in rackList){ - showflag = true; - break; - } - - if (showflag){ - $('#graphTab').append('system x
                                                              '); - $('#graphTab').append(graphTable); - } - //there is nothing to show, return directly - else{ - return; - } - - for (rack in rackList){ - for(index in rackList[rack]){ - var xnodename = rackList[rack][index]; - if (0 == xnodenum % 3){ - row = $(''); - graphTable.append(row); - } - xnodenum++; - var td = $(''); - var xnodeDiv = '
                                                              '; - td.append(xnodeDiv); - row.append(td); - } - } -} - -function addUnknownGraphical(unknownNodes, tab){ - // Do not continue if no nodes were found - if (unknownNodes.length < 1) - return; - - var list = ""; - tab.append('
                                                              '); - for (var index in unknownNodes){ - list += unknownNodes[index] + ', '; - - } - - // Delete last comma - list = list.substr(0, list.length - 2); - tab.append(list); +function selectAllLpars(checkbox) { + var temp = checkbox.attr('checked'); + $('#selectNodeTable input[type = checkbox]').attr('checked', temp); } /** - * update the lpars' background in cec, lpars area and selectNode + * Export all LPAR names from selectNode * - * @param - * @return - **/ -function updateSelectNodeDiv(){ - var temp = 0; - $('#selectNodeDiv').empty(); - - //add buttons - if (selectNode.length) { - $('#selectNodeDiv').append('Nodes: '); - for (var lparName in selectNode){ - $('#selectNodeDiv').append(lparName + ' '); - temp ++; - if (temp > 6){ - $('#selectNodeDiv').append('...'); - break; - } - } - } -} - -/** - * create the action menu - * - * @param getNodesFunction - * the function that can find selected nodes name - * @return action menu object - */ -function createActionMenu(){ - // Create action bar - var actionBar = $('
                                                              '); - - // Power on - var powerOnLnk = $('Power on'); - powerOnLnk.click(function() { - var tgtNodes = getSelectNodes(); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : tgtNodes, - args : 'on', - msg : '' - } - }); - }); - - // Power off - var powerOffLnk = $('Power off'); - powerOffLnk.click(function() { - var tgtNodes = getSelectNodes(); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : tgtNodes, - args : 'off', - msg : '' - } - }); - }); - - // Delete - var deleteLnk = $('Delete'); - deleteLnk.click(function() { - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadDeletePage(tgtNodes); - } - }); - - // Unlock - var unlockLnk = $('Unlock'); - unlockLnk.click(function() { - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadUnlockPage(tgtNodes); - } - }); - - // Run script - var scriptLnk = $('Run script'); - scriptLnk.click(function() { - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadScriptPage(tgtNodes); - } - }); - - // Update - var updateLnk = $('Update'); - updateLnk.click(function() { - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadUpdatenodePage(tgtNodes); - } - }); - - // Set boot state - var setBootStateLnk = $('Set boot state'); - setBootStateLnk.click(function() { - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadNodesetPage(tgtNodes); - } - }); - - // Boot to network - var boot2NetworkLnk = $('Boot to network'); - boot2NetworkLnk.click(function() { - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadNetbootPage(tgtNodes); - } - }); - - // Remote console - var rconLnk = $('Open console'); - rconLnk.bind('click', function(event){ - var tgtNodes = getSelectNodes(); - if (tgtNodes) { - loadRconsPage(tgtNodes); - } - }); - - // Edit properties - var editProps = $('Edit properties'); - editProps.bind('click', function(event){ - for (var node in selectNode) { - loadEditPropsPage(node); - } - }); - - // Actions - var actionsLnk = 'Actions'; - var actsMenu = createMenu([deleteLnk, powerOnLnk, powerOffLnk, scriptLnk]); - - // Configurations - var configLnk = 'Configuration'; - var configMenu = createMenu([unlockLnk, updateLnk, editProps]); - - // Provision - var provLnk = 'Provision'; - var provMenu = createMenu([boot2NetworkLnk, setBootStateLnk, rconLnk]); - - // Create an action menu - var actionsMenu = createMenu([ [ actionsLnk, actsMenu ], [ configLnk, configMenu ], [ provLnk, provMenu ] ]); - actionsMenu.superfish(); - actionsMenu.css('display', 'inline-block'); - actionBar.append(actionsMenu); - actionBar.css('margin-top', '10px'); - - // Set correct theme for action menu - actionsMenu.find('li').hover(function() { - setMenu2Theme($(this)); - }, function() { - setMenu2Normal($(this)); - }); - - return actionBar; -} - -/** - * create the physical graphical layout - * - * @param bpaName : fsp's key - * fsp : all fsp and there related lpars - * fspinfo : all fsps' hardwareinfo - * @return - */ -function createFspDiv(fspName, mtm, fsp){ - //create fsp title - var lparStatusRow = ''; - var temp = ''; - - for (var lparIndex in fsp[fspName]['children']){ - //show 8 lpars on one cec at most. - if (lparIndex >= 8){ - break; - } - var lparName = fsp[fspName]['children'][lparIndex]; - var color = statusMap(lparList[lparName]); - lparStatusRow += ''; - } - - //select the backgroud - var divClass = ''; - if ('' == mtm){ - temp = '8231-E2B'; - } - else{ - temp = mtm; - } - if (hardwareInfo[temp][1]){ - divClass += 'fspDiv' + hardwareInfo[temp][1]; - } - else{ - divClass += 'fspDiv4'; - } - - //create return value - var retHtml = ''; - retHtml += '
                                                              '; - retHtml += '
                                                              ' + lparStatusRow + '
                                                              '; - return retHtml; -} - -/** - * create the physical graphical fsps' help witch could select the lpars. - * - * @param bpaName : fsp's key - * fsp : all fsp and there related lpars - * fspinfo : all fsps' hardwareinfo - * @return - */ -function createFspTip(fspName, mtm, fsp){ - var tip = $('
                                                              '); - var tempTable = $('
                                                              '); - var temp = ''; - if ('' == mtm){ - temp = 'unkown'; - } - else{ - temp = mtm; - } - - if (hardwareInfo[temp]){ - tip.append('

                                                              ' + fspName + '(' + hardwareInfo[temp][0] + ')


                                                              '); - } - else{ - tip.append('

                                                              ' + fspName + '


                                                              '); - } - - for (var lparIndex in fsp[fspName]['children']){ - var lparName = fsp[fspName]['children'][lparIndex]; - var color = statusMap(lparList[lparName]); - var row = ''; - row += ''+ lparName + ''; - row += '' + lparList[lparName] + ''; - tempTable.append(row); - } - - tip.append(tempTable); - return tip; -} -/** - * map the lpar's status into a color - * - * @param status : lpar's status in nodelist table - * @return corresponding color name - */ -function statusMap(status){ - var color = 'gainsboro'; - - switch(status){ - case 'alive': - case 'ready': - case 'pbs': - case 'sshd': - case 'booting': - case 'booted': - case 'ping':{ - color = 'green'; - } - break; - case 'noping': - case 'unreachable':{ - color = 'red'; - } - break; - default: - color = 'grey'; - break; - } - - return color; -} - -/** - * select all lpars checkbox in the dialog - * - * @param - * @return - */ -function selectAllLpars(checkbox){ - var temp = checkbox.attr('checked'); - $('#selectNodeTable input[type = checkbox]').attr('checked', temp); -} - -/** - * export all lpars' name from selectNode - * - * @param - * @return lpars' string + * @return lpars' string */ function getSelectNodes() { var ret = ''; - for ( var lparName in selectNode) { + for (var lparName in selectNode) { ret += lparName + ','; } @@ -905,62 +878,52 @@ function getSelectNodes() { } /** - * when the node is selected or unselected, then update the area on cec, update the global - * list and update the tooltip table - * - * @param - * @return + * When the node is selected or unselected, update the area on CEC, update + * the global list, and update the tooltip table */ -function changeNode(lparName, status){ - var imgUrl = ''; - var checkFlag = true; - if ('select' == status){ - selectNode[lparName] = 1; - imgUrl = 'url(images/nodes/s-'+ statusMap(lparList[lparName]) + '.gif)'; - checkFlag = true; - } - else{ - delete selectNode[lparName]; - imgUrl = 'url(images/nodes/'+ statusMap(lparList[lparName]) + '.gif)'; - checkFlag = false; - } - $('#' + lparName + 'status').css('background-image', imgUrl); - $('.tooltip input[name="' + lparName + '"]').attr('checked', checkFlag); +function changeNode(lparName, status) { + var imgUrl = ''; + var checkFlag = true; + if ('select' == status) { + selectNode[lparName] = 1; + imgUrl = 'url(images/nodes/s-' + statusMap(lparList[lparName]) + + '.gif)'; + checkFlag = true; + } else { + delete selectNode[lparName]; + imgUrl = 'url(images/nodes/' + statusMap(lparList[lparName]) + '.gif)'; + checkFlag = false; + } + $('#' + lparName + 'status').css('background-image', imgUrl); + $('.tooltip input[name="' + lparName + '"]').attr('checked', checkFlag); } /** - * The P7-IH's cecs are insert from down to up, so we had to coculate the blank height. + * The P7-IH's CECs are insert from bottom to up, so we had to calculate the blank height * - * @param - * @return the height for the cec + * @return Height for the CEC */ -function coculateBlank(mtm){ - if ('' == mtm){ - return 24; - } - - if (!hardwareInfo[mtm]){ - return 24; - } - - switch(hardwareInfo[mtm][1]){ - case 1: - { - return 13; - } - break; - case 2: - { - return 24; - } - break; - case 4: - { - return 47; - } - break; - default: - return 0; - break; - } +function calculateBlank(mtm) { + if ('' == mtm) { + return 24; + } + + if (!hardwareInfo[mtm]) { + return 24; + } + + switch (hardwareInfo[mtm][1]) { + case 1: + return 13; + break; + case 2: + return 24; + break; + case 4: + return 47; + break; + default: + return 0; + break; + } } \ No newline at end of file diff --git a/xCAT-UI/js/nodes/rnetboot.js b/xCAT-UI/js/nodes/rnetboot.js index f97e25173..836f67637 100644 --- a/xCAT-UI/js/nodes/rnetboot.js +++ b/xCAT-UI/js/nodes/rnetboot.js @@ -1,202 +1,200 @@ /** * Load netboot page * - * @param tgtNodes - * Targets to run rnetboot against - * @return Nothing + * @param tgtNodes Targets to run rnetboot against */ function loadNetbootPage(tgtNodes) { - // Get node OS - var osHash = new Object(); - var nodes = tgtNodes.split(','); - for (var i in nodes) { - var os = getNodeAttr(nodes[i], 'os'); - var osBase = os.match(/[a-zA-Z]+/); - if (osBase) { - nodes[osBase] = 1; - } - } - - // Get nodes tab - var tab = getNodesTab(); - - // Generate new tab ID - var inst = 0; - var newTabId = 'netbootTab' + inst; - while ($('#' + newTabId).length) { - // If one already exists, generate another one - inst = inst + 1; - newTabId = 'netbootTab' + inst; - } + // Get node OS + var osHash = new Object(); + var nodes = tgtNodes.split(','); + for (var i in nodes) { + var os = getNodeAttr(nodes[i], 'os'); + var osBase = os.match(/[a-zA-Z]+/); + if (osBase) { + nodes[osBase] = 1; + } + } + + // Get nodes tab + var tab = getNodesTab(); + + // Generate new tab ID + var inst = 0; + var newTabId = 'netbootTab' + inst; + while ($('#' + newTabId).length) { + // If one already exists, generate another one + inst = inst + 1; + newTabId = 'netbootTab' + inst; + } - // Create netboot form - var netbootForm = $('
                                                              '); + // Create netboot form + var netbootForm = $('
                                                              '); - // Create status bar - var statBarId = 'netbootStatusBar' + inst; - var statusBar = createStatusBar(statBarId).hide(); - netbootForm.append(statusBar); + // Create status bar + var statBarId = 'netbootStatusBar' + inst; + var statusBar = createStatusBar(statBarId).hide(); + netbootForm.append(statusBar); - // Create loader - var loader = createLoader('netbootLoader'); - statusBar.find('div').append(loader); + // Create loader + var loader = createLoader('netbootLoader'); + statusBar.find('div').append(loader); - // Create info bar - var infoBar = createInfoBar('Cause the range of nodes to boot to network'); - netbootForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Cause the range of nodes to boot to network'); + netbootForm.append(infoBar); - // Create target node or group input - var target = $('
                                                              '); - netbootForm.append(target); + // Create target node or group input + var target = $('
                                                              '); + netbootForm.append(target); - // Create options - var optsDIV = $('
                                                              '); - var optsLabel = $(''); - var optsList = $('
                                                                '); - var opt = $('
                                                              • '); - optsList.append(opt); - optsDIV.append(optsLabel); - optsDIV.append(optsList); - netbootForm.append(optsDIV); - - // Create boot order checkbox - var bootOrderChkBox = $(''); - opt.append(bootOrderChkBox); - opt.append('Set the boot device order'); - // Create boot order input - var bootOrder = $('
                                                              • '); - bootOrder.hide(); - optsList.append(bootOrder); - - // Create force reboot checkbox - optsList.append('
                                                              • Force reboot
                                                              • '); - // Create force shutdown checkbox - optsList.append('
                                                              • Force immediate shutdown of the partition
                                                              • '); - if (osHash['AIX']) { - // Create iscsi dump checkbox - optsList.append('
                                                              • Do a iscsi dump on AIX
                                                              • '); - } - - // Show boot order when checkbox is checked - bootOrderChkBox.bind('click', function(event) { - if ($(this).is(':checked')) { - bootOrder.show(); - } else { - bootOrder.hide(); - } - }); + // Create options + var optsDIV = $('
                                                                '); + var optsLabel = $(''); + var optsList = $('
                                                                  '); + var opt = $('
                                                                • '); + optsList.append(opt); + optsDIV.append(optsLabel); + optsDIV.append(optsList); + netbootForm.append(optsDIV); + + // Create boot order checkbox + var bootOrderChkBox = $(''); + opt.append(bootOrderChkBox); + opt.append('Set the boot device order'); + // Create boot order input + var bootOrder = $('
                                                                • '); + bootOrder.hide(); + optsList.append(bootOrder); + + // Create force reboot checkbox + optsList.append('
                                                                • Force reboot
                                                                • '); + // Create force shutdown checkbox + optsList.append('
                                                                • Force immediate shutdown of the partition
                                                                • '); + if (osHash['AIX']) { + // Create iscsi dump checkbox + optsList.append('
                                                                • Do a iscsi dump on AIX
                                                                • '); + } + + // Show boot order when checkbox is checked + bootOrderChkBox.bind('click', function(event) { + if ($(this).is(':checked')) { + bootOrder.show(); + } else { + bootOrder.hide(); + } + }); - // Determine plugin - var tmp = tgtNodes.split(','); - for ( var i = 0; i < tmp.length; i++) { - var mgt = getNodeAttr(tmp[i], 'mgt'); - // If it is zvm - if (mgt == 'zvm') { - // Add IPL input - netbootForm.append('
                                                                  '); - break; - } - } + // Determine plugin + var tmp = tgtNodes.split(','); + for ( var i = 0; i < tmp.length; i++) { + var mgt = getNodeAttr(tmp[i], 'mgt'); + // If it is zvm + if (mgt == 'zvm') { + // Add IPL input + netbootForm.append('
                                                                  '); + break; + } + } - // Generate tooltips - netbootForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - predelay: 800, - events : { - def : "mouseover,mouseout", - input : "mouseover,mouseout", - widget : "focus mouseover,blur mouseout", - tooltip : "mouseover,mouseout" - } - }); - - /** - * Ok - */ - var okBtn = createButton('Ok'); - okBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - - // Check inputs - var ready = true; - var inputs = $("#" + newTabId + " input[type='text']:visible"); - for ( var i = 0; i < inputs.length; i++) { - if (!inputs.eq(i).val()) { - inputs.eq(i).css('border', 'solid #FF0000 1px'); - ready = false; - } else { - inputs.eq(i).css('border', 'solid #BDBDBD 1px'); - } - } + // Generate tooltips + netbootForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.7, + predelay: 800, + events : { + def : "mouseover,mouseout", + input : "mouseover,mouseout", + widget : "focus mouseover,blur mouseout", + tooltip : "mouseover,mouseout" + } + }); + + /** + * Ok + */ + var okBtn = createButton('Ok'); + okBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + + // Check inputs + var ready = true; + var inputs = $("#" + newTabId + " input[type='text']:visible"); + for ( var i = 0; i < inputs.length; i++) { + if (!inputs.eq(i).val()) { + inputs.eq(i).css('border', 'solid #FF0000 1px'); + ready = false; + } else { + inputs.eq(i).css('border', 'solid #BDBDBD 1px'); + } + } - // Generate arguments - var chkBoxes = $("#" + newTabId + " input[type='checkbox']:checked"); - var optStr = ''; - var opt; - for ( var i = 0; i < chkBoxes.length; i++) { - opt = chkBoxes.eq(i).attr('name'); - optStr += '-' + opt; - - // If it is the boot order - if (opt == 's') { - // Get the boot order - optStr += ';' + $('#' + newTabId + ' input[name=bootOrder]').val(); - } - - // Append ; to end of string - if (i < (chkBoxes.length - 1)) { - optStr += ';'; - } - } + // Generate arguments + var chkBoxes = $("#" + newTabId + " input[type='checkbox']:checked"); + var optStr = ''; + var opt; + for ( var i = 0; i < chkBoxes.length; i++) { + opt = chkBoxes.eq(i).attr('name'); + optStr += '-' + opt; + + // If it is the boot order + if (opt == 's') { + // Get the boot order + optStr += ';' + $('#' + newTabId + ' input[name=bootOrder]').val(); + } + + // Append ; to end of string + if (i < (chkBoxes.length - 1)) { + optStr += ';'; + } + } - // If no inputs are empty - if (ready) { - // Get nodes - var tgts = $('#' + newTabId + ' input[name=target]').val(); + // If no inputs are empty + if (ready) { + // Get nodes + var tgts = $('#' + newTabId + ' input[name=target]').val(); - // Get IPL address - var ipl = $('#' + newTabId + ' input[name=ipl]'); - if (ipl) { - optStr += 'ipl=' + ipl.val(); - } + // Get IPL address + var ipl = $('#' + newTabId + ' input[name=ipl]'); + if (ipl) { + optStr += 'ipl=' + ipl.val(); + } - // Disable all inputs and Ok button - $('#' + newTabId + ' input').attr('disabled', 'disabled'); - $(this).attr('disabled', 'true'); + // Disable all inputs and Ok button + $('#' + newTabId + ' input').attr('disabled', 'disabled'); + $(this).attr('disabled', 'true'); - /** - * (1) Boot to network - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'rnetboot', - tgt : tgts, - args : optStr, - msg : 'out=' + statBarId + ';cmd=rnetboot;tgt=' + tgts - }, + /** + * (1) Boot to network + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rnetboot', + tgt : tgts, + args : optStr, + msg : 'out=' + statBarId + ';cmd=rnetboot;tgt=' + tgts + }, - success : updateStatusBar - }); + success : updateStatusBar + }); - // Show status bar - statusBar.show(); - } else { - // Show warning message - var warn = createWarnBar('Please provide a value for each missing field.'); - warn.prependTo($(this).parent().parent()); - } - }); - netbootForm.append(okBtn); + // Show status bar + statusBar.show(); + } else { + // Show warning message + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this).parent().parent()); + } + }); + netbootForm.append(okBtn); - // Append to discover tab - tab.add(newTabId, 'Boot', netbootForm, true); + // Append to discover tab + tab.add(newTabId, 'Boot', netbootForm, true); - // Select new tab - tab.select(newTabId); + // Select new tab + tab.select(newTabId); } \ No newline at end of file diff --git a/xCAT-UI/js/nodes/updatenode.js b/xCAT-UI/js/nodes/updatenode.js index 6c06b9e88..4ee383346 100644 --- a/xCAT-UI/js/nodes/updatenode.js +++ b/xCAT-UI/js/nodes/updatenode.js @@ -1,386 +1,384 @@ /** * Load updatenode page * - * @param tgtNodes - * Targets to run updatenode against - * @return Nothing + * @param tgtNodes Targets to run updatenode against */ function loadUpdatenodePage(tgtNodes) { - // Get OS images - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS images + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); - - // Get node OS - var osHash = new Object(); - var nodes = tgtNodes.split(','); - for (var i in nodes) { - var os = getNodeAttr(nodes[i], 'os'); - var osBase = os.match(/[a-zA-Z]+/); - if (osBase) { - nodes[osBase] = 1; - } - } - - // Get nodes tab - var tab = getNodesTab(); + success : setOSImageCookies + }); + + // Get node OS + var osHash = new Object(); + var nodes = tgtNodes.split(','); + for (var i in nodes) { + var os = getNodeAttr(nodes[i], 'os'); + var osBase = os.match(/[a-zA-Z]+/); + if (osBase) { + nodes[osBase] = 1; + } + } + + // Get nodes tab + var tab = getNodesTab(); - // Generate new tab ID - var inst = 0; - var newTabId = 'updatenodeTab' + inst; - while ($('#' + newTabId).length) { - // If one already exists, generate another one - inst = inst + 1; - newTabId = 'updatenodeTab' + inst; - } - - // Create updatenode form - var updatenodeForm = $('
                                                                  '); + // Generate new tab ID + var inst = 0; + var newTabId = 'updatenodeTab' + inst; + while ($('#' + newTabId).length) { + // If one already exists, generate another one + inst = inst + 1; + newTabId = 'updatenodeTab' + inst; + } + + // Create updatenode form + var updatenodeForm = $('
                                                                  '); - // Create status bar - var statBarId = 'updatenodeStatusBar' + inst; - var statusBar = createStatusBar(statBarId).hide(); - updatenodeForm.append(statusBar); + // Create status bar + var statBarId = 'updatenodeStatusBar' + inst; + var statusBar = createStatusBar(statBarId).hide(); + updatenodeForm.append(statusBar); - // Create loader - var loader = createLoader('updatenodeLoader'); - statusBar.find('div').append(loader); + // Create loader + var loader = createLoader('updatenodeLoader'); + statusBar.find('div').append(loader); - // Create info bar - var infoBar = createInfoBar('Update nodes in an xCAT environment'); - updatenodeForm.append(infoBar); - - // Create target node or group input - var tgt = $('
                                                                  '); - updatenodeForm.append(tgt); + // Create info bar + var infoBar = createInfoBar('Update nodes in an xCAT environment'); + updatenodeForm.append(infoBar); + + // Create target node or group input + var tgt = $('
                                                                  '); + updatenodeForm.append(tgt); - // Create options - var options = $('
                                                                  '); - var optionsLabel = $(''); - var optionsList = $('
                                                                    '); - options.append(optionsLabel); - options.append(optionsList); - updatenodeForm.append(options); - - // Create update all software checkbox (only AIX) - if (osHash['AIX']) { - var updateAllOption = $('
                                                                  • '); - var updateAllChkBox = $(''); - updateAllOption.append(updateAllChkBox); - optionsList.append(updateAllOption); - updateAllOption.append('Install or update all software contained in the source directory'); - - // Create source directory input - var allSwScrDirectory = $('
                                                                  • '); - // Browse server directory and files - var allSWSrcDirBrowse = createButton('Browse'); - allSWSrcDirBrowse.serverBrowser({ - onSelect : function(path) { - $('#allSwSrcDirectory').val(path); - }, - onLoad : function() { - return $('#allSwSrcDirectory').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [ { - text : 'Install', - image : 'desktop.png', - path : '/install' - } ], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/install' // Limit user to only install directory - }); - allSwScrDirectory.append(allSWSrcDirBrowse); - allSwScrDirectory.hide(); - optionsList.append(allSwScrDirectory); + // Create options + var options = $('
                                                                    '); + var optionsLabel = $(''); + var optionsList = $('
                                                                      '); + options.append(optionsLabel); + options.append(optionsList); + updatenodeForm.append(options); + + // Create update all software checkbox (only AIX) + if (osHash['AIX']) { + var updateAllOption = $('
                                                                    • '); + var updateAllChkBox = $(''); + updateAllOption.append(updateAllChkBox); + optionsList.append(updateAllOption); + updateAllOption.append('Install or update all software contained in the source directory'); + + // Create source directory input + var allSwScrDirectory = $('
                                                                    • '); + // Browse server directory and files + var allSWSrcDirBrowse = createButton('Browse'); + allSWSrcDirBrowse.serverBrowser({ + onSelect : function(path) { + $('#allSwSrcDirectory').val(path); + }, + onLoad : function() { + return $('#allSwSrcDirectory').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [ { + text : 'Install', + image : 'desktop.png', + path : '/install' + } ], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + allSwScrDirectory.append(allSWSrcDirBrowse); + allSwScrDirectory.hide(); + optionsList.append(allSwScrDirectory); - // Show source directory when checked - updateAllChkBox.bind('click', function(event) { - if ($(this).is(':checked')) { - allSwScrDirectory.show(); - } else { - allSwScrDirectory.hide(); - } - }); - } - - // Create update software checkbox - var updateOption = $('
                                                                    • '); - var updateChkBox = $(''); - optionsList.append(updateOption); - updateOption.append(updateChkBox); - updateOption.append('Update existing software'); - - // Create source directory input - var scrDirectory = $('
                                                                    • '); - // Browse server directory and files - var srcDirBrowse = createButton('Browse'); - srcDirBrowse.serverBrowser({ - onSelect : function(path) { - $('#srcDirectory').val(path); - }, - onLoad : function() { - return $('#srcDirectory').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [ { - text : 'Install', - image : 'desktop.png', - path : '/install' - } ], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/install' // Limit user to only install directory - }); - scrDirectory.append(srcDirBrowse); - scrDirectory.hide(); - optionsList.append(scrDirectory); - - // Create other packages input - var otherPkgs = $('
                                                                    • '); - otherPkgs.hide(); - optionsList.append(otherPkgs); - - // Create RPM flags input (only AIX) - var aixRpmFlags = $('
                                                                    • '); - aixRpmFlags.hide(); - optionsList.append(aixRpmFlags); - - // Create installp flags input (only AIX) - var aixInstallPFlags = $('
                                                                    • '); - aixInstallPFlags.hide(); - optionsList.append(aixInstallPFlags); - - // Create emgr flags input (only AIX) - var aixEmgrFlags = $('
                                                                    • '); - aixEmgrFlags.hide(); - optionsList.append(aixEmgrFlags); - - // Show flags when checked - updateChkBox.bind('click', function(event) { - if ($(this).is(':checked')) { - scrDirectory.show(); - otherPkgs.show(); - if (osHash['AIX']) { - aixRpmFlags.show(); - aixInstallPFlags.show(); - aixEmgrFlags.show(); - } - } else { - scrDirectory.hide(); - otherPkgs.hide(); - if (osHash['AIX']) { - aixRpmFlags.hide(); - aixInstallPFlags.hide(); - aixEmgrFlags.hide(); - } - } - }); - - // Create postscripts input - var postOption = $('
                                                                    • '); - var postChkBox = $(''); - optionsList.append(postOption); - postOption.append(postChkBox); - postOption.append('Run postscripts'); - var postscripts = $('
                                                                    • '); - postscripts.hide(); - optionsList.append(postscripts); - - // Show alternate source directory when checked - postChkBox.bind('click', function(event) { - if ($(this).is(':checked')) { - postscripts.show(); - } else { - postscripts.hide(); - } - }); - optionsList.append('
                                                                    • Distribute and synchronize files
                                                                    • '); - optionsList.append('
                                                                    • Update the ssh keys and host keys for the service nodes and compute nodes
                                                                    • '); - - // Create update OS checkbox - if (!osHash['AIX']) { - var osOption = $('
                                                                    • '); - var osChkBox = $(''); - optionsList.append(osOption); - osOption.append(osChkBox); - osOption.append('Update the operating system'); - - var os = $('
                                                                    • ').hide(); - var osLabel = $(''); - var osInput = $(''); - osInput.one('focus', function(){ - var tmp = $.cookie('osvers'); - if (tmp) { - // Turn on auto complete - $(this).autocomplete({ - source: tmp.split(',') - }); - } - }); - os.append(osLabel); - os.append(osInput); - optionsList.append(os); - - // Show alternate source directory when checked - osChkBox.bind('click', function(event) { - if ($(this).is(':checked')) { - os.show(); - } else { - os.hide(); - } - }); - } - - // Generate tooltips - updatenodeForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - predelay: 800, - events : { - def : "mouseover,mouseout", - input : "mouseover,mouseout", - widget : "focus mouseover,blur mouseout", - tooltip : "mouseover,mouseout" - } - }); - - /** - * Ok - */ - var okBtn = createButton('Ok'); - okBtn.bind('click', function(event) { - // Remove any warning messages - $(this).parent().parent().find('.ui-state-error').remove(); - var ready = true; - - // Generate arguments - var chkBoxes = $("#" + newTabId + " input[type='checkbox']:checked"); - var optionsStr = ''; - var option; - for ( var i = 0; i < chkBoxes.length; i++) { - option = chkBoxes.eq(i).attr('name'); - optionsStr += '-' + option; - - // If update all software is checked - if (option == 'S') { - var srcDir = $('#' + newTabId + ' input[name=allSwSrcDirectory]').val(); - if (srcDir) { - optionsStr += ';-d ' + srcDir; - } - } + // Show source directory when checked + updateAllChkBox.bind('click', function(event) { + if ($(this).is(':checked')) { + allSwScrDirectory.show(); + } else { + allSwScrDirectory.hide(); + } + }); + } + + // Create update software checkbox + var updateOption = $('
                                                                    • '); + var updateChkBox = $(''); + optionsList.append(updateOption); + updateOption.append(updateChkBox); + updateOption.append('Update existing software'); + + // Create source directory input + var scrDirectory = $('
                                                                    • '); + // Browse server directory and files + var srcDirBrowse = createButton('Browse'); + srcDirBrowse.serverBrowser({ + onSelect : function(path) { + $('#srcDirectory').val(path); + }, + onLoad : function() { + return $('#srcDirectory').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [ { + text : 'Install', + image : 'desktop.png', + path : '/install' + } ], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + scrDirectory.append(srcDirBrowse); + scrDirectory.hide(); + optionsList.append(scrDirectory); + + // Create other packages input + var otherPkgs = $('
                                                                    • '); + otherPkgs.hide(); + optionsList.append(otherPkgs); + + // Create RPM flags input (only AIX) + var aixRpmFlags = $('
                                                                    • '); + aixRpmFlags.hide(); + optionsList.append(aixRpmFlags); + + // Create installp flags input (only AIX) + var aixInstallPFlags = $('
                                                                    • '); + aixInstallPFlags.hide(); + optionsList.append(aixInstallPFlags); + + // Create emgr flags input (only AIX) + var aixEmgrFlags = $('
                                                                    • '); + aixEmgrFlags.hide(); + optionsList.append(aixEmgrFlags); + + // Show flags when checked + updateChkBox.bind('click', function(event) { + if ($(this).is(':checked')) { + scrDirectory.show(); + otherPkgs.show(); + if (osHash['AIX']) { + aixRpmFlags.show(); + aixInstallPFlags.show(); + aixEmgrFlags.show(); + } + } else { + scrDirectory.hide(); + otherPkgs.hide(); + if (osHash['AIX']) { + aixRpmFlags.hide(); + aixInstallPFlags.hide(); + aixEmgrFlags.hide(); + } + } + }); + + // Create postscripts input + var postOption = $('
                                                                    • '); + var postChkBox = $(''); + optionsList.append(postOption); + postOption.append(postChkBox); + postOption.append('Run postscripts'); + var postscripts = $('
                                                                    • '); + postscripts.hide(); + optionsList.append(postscripts); + + // Show alternate source directory when checked + postChkBox.bind('click', function(event) { + if ($(this).is(':checked')) { + postscripts.show(); + } else { + postscripts.hide(); + } + }); + optionsList.append('
                                                                    • Distribute and synchronize files
                                                                    • '); + optionsList.append('
                                                                    • Update the ssh keys and host keys for the service nodes and compute nodes
                                                                    • '); + + // Create update OS checkbox + if (!osHash['AIX']) { + var osOption = $('
                                                                    • '); + var osChkBox = $(''); + optionsList.append(osOption); + osOption.append(osChkBox); + osOption.append('Update the operating system'); + + var os = $('
                                                                    • ').hide(); + var osLabel = $(''); + var osInput = $(''); + osInput.one('focus', function(){ + var tmp = $.cookie('osvers'); + if (tmp) { + // Turn on auto complete + $(this).autocomplete({ + source: tmp.split(',') + }); + } + }); + os.append(osLabel); + os.append(osInput); + optionsList.append(os); + + // Show alternate source directory when checked + osChkBox.bind('click', function(event) { + if ($(this).is(':checked')) { + os.show(); + } else { + os.hide(); + } + }); + } + + // Generate tooltips + updatenodeForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.7, + predelay: 800, + events : { + def : "mouseover,mouseout", + input : "mouseover,mouseout", + widget : "focus mouseover,blur mouseout", + tooltip : "mouseover,mouseout" + } + }); + + /** + * Ok + */ + var okBtn = createButton('Ok'); + okBtn.bind('click', function(event) { + // Remove any warning messages + $(this).parent().parent().find('.ui-state-error').remove(); + var ready = true; + + // Generate arguments + var chkBoxes = $("#" + newTabId + " input[type='checkbox']:checked"); + var optionsStr = ''; + var option; + for ( var i = 0; i < chkBoxes.length; i++) { + option = chkBoxes.eq(i).attr('name'); + optionsStr += '-' + option; + + // If update all software is checked + if (option == 'S') { + var srcDir = $('#' + newTabId + ' input[name=allSwSrcDirectory]').val(); + if (srcDir) { + optionsStr += ';-d ' + srcDir; + } + } - // If update software is checked - if (option == 'S') { - // Get source directory - var srcDirectory = $('#' + newTabId + ' input[name=srcDirectory]').val(); - if (srcDirectory) { - optionsStr += ';-d;' + srcDirectory; - } - - // Get otherpkgs - var otherpkgs = $('#' + newTabId + ' input[name=otherpkgs]').val(); - if (otherpkgs) { - optionsStr += ';otherpkgs=' + otherpkgs; - } - - // Get rpm_flags - var rpm_flags = $('#' + newTabId + ' input[name=rpm_flags]').val(); - if (rpm_flags) { - optionsStr += ';rpm_flags=' + rpm_flags; - } - - // Get installp_flags - var installp_flags = $('#' + newTabId + ' input[name=installp_flags]').val(); - if (installp_flags) { - optionsStr += ';installp_flags=' + installp_flags; - } - - // Get emgr_flags - var emgr_flags = $('#' + newTabId + ' input[name=emgr_flags]').val(); - if (emgr_flags) { - optionsStr += ';emgr_flags=' + emgr_flags; - } - } - - // If postscripts is checked - if (option == 'P') { - // Get postscripts - optionsStr += ';' + $('#' + newTabId + ' input[name=postscripts]').val(); - } - - // If operating system is checked - if (option == 'o') { - // Get the OS - optionsStr += ';' + $('#' + newTabId + ' input[name=os]').val(); - } - - // Append ; to end of string - if (i < (chkBoxes.length - 1)) { - optionsStr += ';'; - } - } - - // If no inputs are empty - if (ready) { - // Get nodes - var tgts = $('#' + newTabId + ' input[name=target]').val(); + // If update software is checked + if (option == 'S') { + // Get source directory + var srcDirectory = $('#' + newTabId + ' input[name=srcDirectory]').val(); + if (srcDirectory) { + optionsStr += ';-d;' + srcDirectory; + } + + // Get otherpkgs + var otherpkgs = $('#' + newTabId + ' input[name=otherpkgs]').val(); + if (otherpkgs) { + optionsStr += ';otherpkgs=' + otherpkgs; + } + + // Get rpm_flags + var rpm_flags = $('#' + newTabId + ' input[name=rpm_flags]').val(); + if (rpm_flags) { + optionsStr += ';rpm_flags=' + rpm_flags; + } + + // Get installp_flags + var installp_flags = $('#' + newTabId + ' input[name=installp_flags]').val(); + if (installp_flags) { + optionsStr += ';installp_flags=' + installp_flags; + } + + // Get emgr_flags + var emgr_flags = $('#' + newTabId + ' input[name=emgr_flags]').val(); + if (emgr_flags) { + optionsStr += ';emgr_flags=' + emgr_flags; + } + } + + // If postscripts is checked + if (option == 'P') { + // Get postscripts + optionsStr += ';' + $('#' + newTabId + ' input[name=postscripts]').val(); + } + + // If operating system is checked + if (option == 'o') { + // Get the OS + optionsStr += ';' + $('#' + newTabId + ' input[name=os]').val(); + } + + // Append ; to end of string + if (i < (chkBoxes.length - 1)) { + optionsStr += ';'; + } + } + + // If no inputs are empty + if (ready) { + // Get nodes + var tgts = $('#' + newTabId + ' input[name=target]').val(); - // Disable all inputs and Ok button - $('#' + newTabId + ' input').attr('disabled', 'disabled'); - $(this).attr('disabled', 'true'); - - /** - * (1) Boot to network - */ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'updatenode', - tgt : tgts, - args : optionsStr, - msg : 'out=' + statBarId + ';cmd=updatenode;tgt=' + tgts - }, + // Disable all inputs and Ok button + $('#' + newTabId + ' input').attr('disabled', 'disabled'); + $(this).attr('disabled', 'true'); + + /** + * (1) Boot to network + */ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'updatenode', + tgt : tgts, + args : optionsStr, + msg : 'out=' + statBarId + ';cmd=updatenode;tgt=' + tgts + }, - success : updateStatusBar - }); + success : updateStatusBar + }); - // Show status bar - statusBar.show(); - } else { - // Show warning message - var warn = createWarnBar('You are missing some values'); - warn.prependTo($(this).parent().parent()); - } - }); - updatenodeForm.append(okBtn); + // Show status bar + statusBar.show(); + } else { + // Show warning message + var warn = createWarnBar('You are missing some values'); + warn.prependTo($(this).parent().parent()); + } + }); + updatenodeForm.append(okBtn); - // Append to discover tab - tab.add(newTabId, 'Update', updatenodeForm, true); + // Append to discover tab + tab.add(newTabId, 'Update', updatenodeForm, true); - // Select new tab - tab.select(newTabId); + // Select new tab + tab.select(newTabId); } \ No newline at end of file diff --git a/xCAT-UI/js/provision/images.js b/xCAT-UI/js/provision/images.js index e58edf1ec..7a8ac9ac0 100644 --- a/xCAT-UI/js/provision/images.js +++ b/xCAT-UI/js/provision/images.js @@ -3,367 +3,775 @@ */ var origAttrs = new Object(); // Original image attributes var defAttrs; // Definable image attributes -var imgTableId = 'imagesDatatable'; // Images datatable ID +var imgTableId = 'imagesDatatable'; // Images datatable ID var softwareList = { - "rsct" : ["rsct.core.utils", "rsct.core", "src"], - "pe" : ["IBMJava2-142-ppc64-JRE", "ibm_lapi_ip_rh6p", "ibm_lapi_us_rh6p", "IBM_pe_license", "ibm_pe_rh6p", "ppe_pdb_ppc64_rh600", "sci_ppc_32bit_rh600", "sci_ppc_64bit_rh600", "vac.cmp", - "vac.lib", "vac.lic", "vacpp.cmp", "vacpp.help.pdf", "vacpp.lib", "vacpp.man", "vacpp.rte", "vacpp.rte.lnk", "vacpp.samples", "xlf.cmp", "xlf.help.pdf", "xlf.lib", "xlf.lic", "xlf.man", - "xlf.msg.rte", "xlf.rte", "xlf.rte.lnk", "xlf.samples", "xlmass.lib", "xlsmp.lib", "xlsmp.msg.rte", "xlsmp.rte"], - "gpfs" : ["gpfs.base", "gpfs.gpl", "gpfs.gplbin", "gpfs.msg.en_US"], - "essl" : ["essl.3232.rte", "essl.3264.rte", "essl.6464.rte", "essl.common", "essl.license", "essl.man", "essl.msg", "essl.rte", "ibm-java2", "pessl.common", "pessl.license", "pessl.man", - "pessl.msg", "pessl.rte.ppe"], - "loadl" : ["IBMJava2", "LoadL-full-license-RH6", "LoadL-resmgr-full-RH6", "LoadL-scheduler-full-RH6"], - "ganglia" : ["rrdtool", "ganglia", "ganglia-gmetad", "ganglia-gmond"], - "base" : ["createrepo"] + "rsct" : ["rsct.core.utils", "rsct.core", "src"], + "pe" : ["IBMJava2-142-ppc64-JRE", "ibm_lapi_ip_rh6p", "ibm_lapi_us_rh6p", "IBM_pe_license", "ibm_pe_rh6p", "ppe_pdb_ppc64_rh600", "sci_ppc_32bit_rh600", "sci_ppc_64bit_rh600", "vac.cmp", + "vac.lib", "vac.lic", "vacpp.cmp", "vacpp.help.pdf", "vacpp.lib", "vacpp.man", "vacpp.rte", "vacpp.rte.lnk", "vacpp.samples", "xlf.cmp", "xlf.help.pdf", "xlf.lib", "xlf.lic", "xlf.man", + "xlf.msg.rte", "xlf.rte", "xlf.rte.lnk", "xlf.samples", "xlmass.lib", "xlsmp.lib", "xlsmp.msg.rte", "xlsmp.rte"], + "gpfs" : ["gpfs.base", "gpfs.gpl", "gpfs.gplbin", "gpfs.msg.en_US"], + "essl" : ["essl.3232.rte", "essl.3264.rte", "essl.6464.rte", "essl.common", "essl.license", "essl.man", "essl.msg", "essl.rte", "ibm-java2", "pessl.common", "pessl.license", "pessl.man", + "pessl.msg", "pessl.rte.ppe"], + "loadl" : ["IBMJava2", "LoadL-full-license-RH6", "LoadL-resmgr-full-RH6", "LoadL-scheduler-full-RH6"], + "ganglia" : ["rrdtool", "ganglia", "ganglia-gmetad", "ganglia-gmond"], + "base" : ["createrepo"] }; /** * Load images page - * - * @return Nothing */ function loadImagesPage() { - // Set padding for images page - $('#imagesTab').css('padding', '20px 60px'); - - // Get images within the database - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : '-t;osimage;-l', - msg : '' - }, + // Set padding for images page + $('#imagesTab').css('padding', '20px 60px'); + + // Get images within the database + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : '-t;osimage;-l', + msg : '' + }, - success : loadImages - }); + success : loadImages + }); } /** * Load images within the database * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function loadImages(data) { - // Data returned - var rsp = data.rsp; - // Image attributes hash - var attrs = new Object(); - // Image attributes - var headers = new Object(); - - // Clear hash table containing image attributes - origAttrs = ''; + // Data returned + var rsp = data.rsp; + // Image attributes hash + var attrs = new Object(); + // Image attributes + var headers = new Object(); + + // Clear hash table containing image attributes + origAttrs = ''; - var image; - var args; - for (var i in rsp) { - // Get the image - var pos = rsp[i].indexOf('Object name:'); - if (pos > -1) { - var temp = rsp[i].split(': '); - image = jQuery.trim(temp[1]); + var image; + var args; + for (var i in rsp) { + // Get the image + var pos = rsp[i].indexOf('Object name:'); + if (pos > -1) { + var temp = rsp[i].split(': '); + image = jQuery.trim(temp[1]); - // Create a hash for the image attributes - attrs[image] = new Object(); - i++; - } + // Create a hash for the image attributes + attrs[image] = new Object(); + i++; + } - // Get key and value - args = rsp[i].split('='); - var key = jQuery.trim(args[0]); - var val = jQuery.trim(args[1]); + // Get key and value + args = rsp[i].split('='); + var key = jQuery.trim(args[0]); + var val = jQuery.trim(args[1]); - // Create a hash table - attrs[image][key] = val; - headers[key] = 1; - } - - // Save attributes in hash table - origAttrs = attrs; + // Create a hash table + attrs[image][key] = val; + headers[key] = 1; + } + + // Save attributes in hash table + origAttrs = attrs; - // Sort headers - var sorted = new Array(); - for (var key in headers) { - sorted.push(key); - } - sorted.sort(); + // Sort headers + var sorted = new Array(); + for (var key in headers) { + sorted.push(key); + } + sorted.sort(); - // Add column for check box and image name - sorted.unshift('', 'imagename'); + // Add column for check box and image name + sorted.unshift('', 'imagename'); - // Create a datatable - var dTable = new DataTable(imgTableId); - dTable.init(sorted); + // Create a datatable + var dTable = new DataTable(imgTableId); + dTable.init(sorted); - // Go through each image - for (var img in attrs) { - // Create a row - var row = new Array(); - // Create a check box - var checkBx = ''; - // Push in checkbox and image name - row.push(checkBx, img); - - // Go through each header - for (var i = 2; i < sorted.length; i++) { - // Add the node attributes to the row - var key = sorted[i]; - var val = attrs[img][key]; - if (val) { - row.push(val); - } else { - row.push(''); - } - } + // Go through each image + for (var img in attrs) { + // Create a row + var row = new Array(); + // Create a check box + var checkBx = ''; + // Push in checkbox and image name + row.push(checkBx, img); + + // Go through each header + for (var i = 2; i < sorted.length; i++) { + // Add the node attributes to the row + var key = sorted[i]; + var val = attrs[img][key]; + if (val) { + row.push(val); + } else { + row.push(''); + } + } - // Add the row to the table - dTable.add(row); - } + // Add the row to the table + dTable.add(row); + } - // Clear the tab before inserting the table - $('#imagesTab').children().remove(); - - // Create info bar for images tab - var info = createInfoBar('Click on a cell to edit. Click outside the table to save changes. Hit the Escape key to ignore changes.'); - $('#imagesTab').append(info); + // Clear the tab before inserting the table + $('#imagesTab').children().remove(); + + // Create info bar for images tab + var info = createInfoBar('Double click on a cell to edit. Click outside the table to save changes. Hit the Escape key to ignore changes.'); + $('#imagesTab').append(info); - /** - * The following actions are available for images: - * copy Linux distribution and edit image properties - */ + /** + * The following actions are available for images: + * copy Linux distribution and edit image properties + */ - // Create copy CD link - var copyCDLnk = $('Copy CD'); - copyCDLnk.click(function() { - loadCopyCdPage(); - }); - - // Create image link - var newLnk = $('Create image'); - newLnk.click(function() { - loadCreateImage(); - }); - - // Create edit link - var editBtn = $('Edit'); - editBtn.click(function() { - var tgtImages = getNodesChecked(imgTableId).split(','); - for (var i in tgtImages) { - loadEditImagePage(tgtImages[i]); - } - }); - - // Insert table - $('#imagesTab').append(dTable.object()); + // Copy CD into install directory + var copyCDLnk = $('Copy CD'); + copyCDLnk.click(function() { + openCopyCdDialog(); + }); + + // Generate stateless or statelite image + var generateLnk = $('Generate image'); + generateLnk.click(function() { + loadCreateImage(); + }); + + // Edit image attributes + var editLnk = $('Edit'); + editLnk.click(function() { + var tgtImages = getNodesChecked(imgTableId).split(','); + if (tgtImages) { + for (var i in tgtImages) { + openEditImagePage(tgtImages[i]); + } + } + }); + + // Add a row + var addLnk = $('Add'); + addLnk.click(function() { + openAddImageDialog(); + }); + + // Remove a row + var removeLnk = $('Remove'); + removeLnk.click(function() { + var images = getNodesChecked(imgTableId); + if (images) { + confirmImageDeleteDialog(images); + } + }); + + // Refresh image table + var refreshLnk = $('Refresh'); + refreshLnk.click(function() { + // Get images within the database + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : '-t;osimage;-l', + msg : '' + }, - // Turn table into a datatable - var myDataTable = $('#' + imgTableId).dataTable({ - 'iDisplayLength': 50, - 'bLengthChange': false, - "sScrollX": "100%", - "bAutoWidth": true, - "fnInitComplete": function() { - adjustColumnSize(imgTableId); - } - }); - - // Set datatable width - $('#' + imgTableId + '_wrapper').css({ - 'width': '880px' - }); - - // Actions - var actionBar = $('
                                                                      '); - var actionsLnk = 'Actions'; - var actsMenu = createMenu([copyCDLnk, newLnk, editBtn]); + success : loadImages + }); + }); + + // Insert table + $('#imagesTab').append(dTable.object()); - // Create an action menu - var actionsMenu = createMenu([ [ actionsLnk, actsMenu ] ]); - actionsMenu.superfish(); - actionsMenu.css('display', 'inline-block'); - actionBar.append(actionsMenu); - - // Set correct theme for action menu - actionsMenu.find('li').hover(function() { - setMenu2Theme($(this)); - }, function() { - setMenu2Normal($(this)); - }); - - // Create a division to hold actions menu - var menuDiv = $(''); - $('#' + imgTableId + '_wrapper').prepend(menuDiv); - menuDiv.append(actionBar); - $('#' + imgTableId + '_filter').appendTo(menuDiv); - - /** - * Enable editable columns - */ - - // Do not make 1st, 2nd, 3rd, 4th, or 5th column editable - $('#' + imgTableId + ' td:not(td:nth-child(1),td:nth-child(2))').editable( - function(value, settings) { - // Get column index - var colPos = this.cellIndex; - - // Get row index - var dTable = $('#' + imgTableId).dataTable(); - var rowPos = dTable.fnGetPosition(this.parentNode); - - // Update datatable - dTable.fnUpdate(value, rowPos, colPos); - - // Get image name - var image = $(this).parent().find('td:eq(1)').text(); - - // Get table headers - var headers = $('#' + imgTableId).parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); + // Turn table into a datatable + var myDataTable = $('#' + imgTableId).dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%", + "bAutoWidth": true, + "fnInitComplete": function() { + adjustColumnSize(imgTableId); + } + }); + + // Set datatable width + $('#' + imgTableId + '_wrapper').css({ + 'width': '880px' + }); + + // Actions + var actionBar = $('
                                                                      '); + var advancedLnk = 'Advanced'; + var advancedMenu = createMenu([copyCDLnk, generateLnk]); - // Get attribute name - var attrName = jQuery.trim(headers.eq(colPos).text()); - // Get column value - var value = $(this).text(); - // Build argument - var args = attrName + '=' + value; - - // Send command to change image attributes - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : '-t;osimage;-o;' + image + ';' + args, - msg : 'out=imagesTab;tgt=' + image - }, + // Create an action menu + var actionsMenu = createMenu([refreshLnk, addLnk, editLnk, removeLnk, [advancedLnk, advancedMenu]]); + actionsMenu.superfish(); + actionsMenu.css('display', 'inline-block'); + actionBar.append(actionsMenu); + + // Set correct theme for action menu + actionsMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + imgTableId + '_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + imgTableId + '_filter').appendTo(menuDiv); + + /** + * Enable editable columns + */ + + // Do not make 1st column editable + $('#' + imgTableId + ' td:not(td:nth-child(1))').editable( + function(value, settings) { + // Get column index + var colPos = this.cellIndex; + + // Get row index + var dTable = $('#' + imgTableId).dataTable(); + var rowPos = dTable.fnGetPosition(this.parentNode); + + // Update datatable + dTable.fnUpdate(value, rowPos, colPos); + + // Get image name + var image = $(this).parent().find('td:eq(1)').text(); + + // Get table headers + var headers = $('#' + imgTableId).parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); - success: showChdefOutput - }); + // Get attribute name + var attrName = jQuery.trim(headers.eq(colPos).text()); + // Get column value + var value = $(this).text(); + // Build argument + var args = attrName + '=' + value; + + // Send command to change image attributes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : '-t;osimage;-o;' + image + ';' + args, + msg : 'out=imagesTab;tgt=' + image + }, - return value; - }, { - onblur : 'submit', // Clicking outside editable area submits changes - type : 'textarea', // Input type to use - placeholder: ' ', - height : '30px' // The height of the text area - }); - - // Get definable node attributes - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : '-t;osimage;-h', - msg : '' - }, + success: showChdefOutput + }); - success : setImageDefAttrs - }); + return value; + }, { + onblur : 'submit', // Clicking outside editable area submits changes + type : 'textarea', // Input type to use + placeholder: ' ', + event : "dblclick", // Double click and edit + height : '30px' // The height of the text area + }); + + // Get definable node attributes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : '-t;osimage;-h', + msg : '' + }, + + success : setImageDefAttrs + }); +} + +/** + * Open dialog to confirm deleting image + * + * @param images Comma delimited image names + */ +function confirmImageDeleteDialog(images) { + // Make images list more readable + var dialogId = 'confirmImageRemove'; + var tmp = images.replace(new RegExp(',', 'g'), ', '); + var confirmDialog = $('
                                                                      ' + + '

                                                                      Are you sure you want to remove ' + tmp + '?

                                                                      ' + + '
                                                                      '); + + // Open dialog to confirm delete + confirmDialog.dialog({ + modal: true, + close: function(){ + $(this).remove(); + }, + title: 'Confirm', + width: 500, + buttons: { + "Ok": function(){ + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + // Add image to xCAT + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'rmdef', + tgt : '', + args : '-t;osimage;-o;' + images, + msg : dialogId + }, + + success : updateImageDialog + }); + }, + "Cancel": function(){ + $(this).dialog("close"); + } + } + }); +} + +/** + * Open a dialog to add an image + */ +function openAddImageDialog() { + // Create dialog to add image + var dialogId = 'addImage'; + var addImageForm = $('
                                                                      '); + + // Create info bar + var info = createInfoBar('Provide the following attributes for the image. The image name will be generated based on the attributes you will give.'); + addImageForm.append(info); + + // Create inputs for image attributes + var imageName = $('
                                                                      '); + var imageType = $('
                                                                      '); + var architecture = $('
                                                                      '); + var osName = $('
                                                                      '); + var osVersion = $('
                                                                      '); + var profile = $('
                                                                      '); + var provisionMethod = $('
                                                                      '); + var provisionSelect = $(''); + provisionMethod.append(provisionSelect); + + // Create inputs for optional attributes + var exList = $('
                                                                      '); + var exListInput = $(''); + exList.append(exListInput); + exListInput.serverBrowser({ + onSelect : function(path) { + $('#addImage input[name="exlist"]').val(path); + }, + onLoad : function() { + return $('#addImage input[name="exlist"]').val(); + }, + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + var otherpkgDirectory = $('
                                                                      '); + var otherpkgDirectoryInput = $(''); + otherpkgDirectory.append(otherpkgDirectoryInput); + otherpkgDirectoryInput.serverBrowser({ + onSelect : function(path) { + $('#addImage input[name="otherpkgdir"]').val(path); + }, + onLoad : function() { + return $('#addImage input[name="otherpkgdir"]').val(); + }, + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + var packageDirectory = $('
                                                                      '); + var packageDirectoryInput = $(''); + packageDirectory.append(packageDirectoryInput); + packageDirectoryInput.serverBrowser({ + onSelect : function(path) { + $('#addImage input[name="pkgdir"]').val(path); + }, + onLoad : function() { + return $('#addImage input[name="pkgdir"]').val(); + }, + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + var packageList = $('
                                                                      '); + var packageListInput = $(''); + packageList.append(packageListInput); + packageListInput.serverBrowser({ + onSelect : function(path) { + $('#addImage input[name="pkglist"]').val(path); + }, + onLoad : function() { + return $('#addImage input[name="pkglist"]').val(); + }, + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + var postInstall = $('
                                                                      '); + var postInstallInput = $(''); + postInstall.append(postInstallInput); + postInstallInput.serverBrowser({ + onSelect : function(path) { + $('#addImage input[name="postinstall"]').val(path); + }, + onLoad : function() { + return $('#addImage input[name="postinstall"]').val(); + }, + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + var template = $('
                                                                      '); + var templateInput = $(''); + template.append(templateInput); + templateInput.serverBrowser({ + onSelect : function(path) { + $('#addImage input[name="template"]').val(path); + }, + onLoad : function() { + return $('#addImage input[name="template"]').val(); + }, + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + + addImageForm.append(imageName, imageType, architecture, osName, osVersion, profile, provisionMethod, + exList, otherpkgDirectory, packageDirectory, packageList, postInstall, template); + + // Open dialog to add image + addImageForm.dialog({ + title:'Add image', + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + // Get image attributes + var imageType = $(this).find('input[name="imagetype"]'); + var architecture = $(this).find('input[name="osarch"]'); + var osName = $(this).find('input[name="osname"]'); + var osVersion = $(this).find('input[name="osvers"]'); + var profile = $(this).find('input[name="profile"]'); + var provisionMethod = $(this).find('select[name="provmethod"]'); + + // Get optional image attributes + var exList = $(this).find('input[name="exlist"]'); + var otherpkgDirectory = $(this).find('input[name="otherpkgdir"]'); + var pkgDirectory = $(this).find('input[name="pkgdir"]'); + var pkgList = $(this).find('input[name="pkglist"]'); + var postInstall = $(this).find('input[name="postinstall"]'); + var template = $(this).find('input[name="template"]'); + + // Check that image attributes are provided before continuing + var ready = 1; + var inputs = new Array(imageType, architecture, osName, osVersion, profile, provisionMethod); + for (var i in inputs) { + if (!inputs[i].val()) { + inputs[i].css('border-color', 'red'); + ready = 0; + } else + inputs[i].css('border-color', ''); + } + + // If inputs are not complete, show warning message + if (!ready) { + var warn = createWarnBar('Please provide a value for each missing field.'); + warn.prependTo($(this)); + } else { + // Override image name + $(this).find('input[name="imagename"]').val(osVersion.val() + '-' + architecture.val() + '-' + provisionMethod.val() + '-' + profile.val()); + var imageName = $(this).find('input[name="imagename"]'); + + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + // Create arguments to send via AJAX + var args = '-t;osimage;-o;' + imageName.val() + ';' + + 'imagetype=' + imageType.val() + ';' + + 'osarch=' + architecture.val() + ';' + + 'osname=' + osName.val() + ';' + + 'osvers=' + osVersion.val() + ';' + + 'profile=' + profile.val() + ';' + + 'provmethod=' + provisionMethod.val(); + + // Get optional attributes + if (exList.val()) + args += ';exlist=' + exList.val(); + if (otherpkgDirectory.val()) + args += ';otherpkgdir=' + otherpkgDirectory.val(); + if (pkgDirectory.val()) + args += ';pkgdir=' + pkgDirectory.val(); + if (pkgList.val()) + args += ';pkglist=' + pkgList.val(); + if (postInstall.val()) + args += ';postinstall=' + postInstall.val(); + if (template.val()) + args += ';template=' + template.val(); + + // Add image to xCAT + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : args, + msg : dialogId + }, + + success : updateImageDialog + }); + } + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); +} + +/** + * Update image dialog + * + * @param data HTTP request data + */ +function updateImageDialog(data) { + var dialogId = data.msg; + var infoMsg; + + // Delete loader if one does exist + $('.ui-dialog #' + dialogId + ' img[src="images/loader.gif"]').remove(); + + // Create info message + if (jQuery.isArray(data.rsp)) { + infoMsg = ''; + + // If the data returned is more than 10 lines, get only the last line + var i, start; + if (data.rsp.length > 10) + start = data.rsp.length - 1; + else + start = 0; + + for (i = start; i < data.rsp.length; i++) + infoMsg += data.rsp[i] + '
                                                                      '; + } else { + infoMsg = data.rsp; + } + + // Create info bar with close button + var infoBar = $('
                                                                      ').css('margin', '5px 0px'); + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px' + }); + + // Create close button to close info bar + var close = $('').css({ + 'display': 'inline-block', + 'float': 'right' + }).click(function() { + $(this).parent().remove(); + }); + + var msg = $('

                                                                      ' + infoMsg + '

                                                                      ').css({ + 'display': 'inline-block', + 'width': '90%' + }); + + infoBar.append(icon, msg, close); + infoBar.prependTo($('.ui-dialog #' + dialogId)); } /** * Set definable image attributes * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function setImageDefAttrs(data) { - // Clear hash table containing definable image attributes - defAttrs = new Array(); - - // Get definable attributes - var attrs = data.rsp[2].split(/\n/); + // Clear hash table containing definable image attributes + defAttrs = new Array(); + + // Get definable attributes + var attrs = data.rsp[2].split(/\n/); - // Go through each line - var attr, key, descr; - for (var i in attrs) { - attr = attrs[i]; - - // If the line is not empty - if (attr) { - // If the line has the attribute name - if (attr.indexOf(':') && attr.indexOf(' ')) { - // Get attribute name and description - key = jQuery.trim(attr.substring(0, attr.indexOf(':'))); - descr = jQuery.trim(attr.substring(attr.indexOf(':') + 1)); - descr = descr.replace(new RegExp('<', 'g'), '[').replace(new RegExp('>', 'g'), ']'); - - // Set hash table where key = attribute name and value = description - defAttrs[key] = descr; - } else { - // Append description to hash table - defAttrs[key] = defAttrs[key] + '\n' + attr.replace(new RegExp('<', 'g'), '[').replace(new RegExp('>', 'g'), ']'); - } - } // End of if - } // End of for + // Go through each line + var attr, key, descr; + for (var i in attrs) { + attr = attrs[i]; + + // If the line is not empty + if (attr) { + // If the line has the attribute name + if (attr.indexOf(':') && attr.indexOf(' ')) { + // Get attribute name and description + key = jQuery.trim(attr.substring(0, attr.indexOf(':'))); + descr = jQuery.trim(attr.substring(attr.indexOf(':') + 1)); + descr = descr.replace(new RegExp('<', 'g'), '[').replace(new RegExp('>', 'g'), ']'); + + // Set hash table where key = attribute name and value = description + defAttrs[key] = descr; + } else { + // Append description to hash table + defAttrs[key] = defAttrs[key] + '\n' + attr.replace(new RegExp('<', 'g'), '[').replace(new RegExp('>', 'g'), ']'); + } + } // End of if + } // End of for } /** * Load create image page */ function loadCreateImage() { - // Get nodes tab - var tab = getProvisionTab(); - var tabId = 'createImageTab'; - - // Generate new tab ID - if ($('#' + tabId).size()) { - tab.select(tabId); - return; - } + // Get nodes tab + var tab = getProvisionTab(); + var tabId = 'createImageTab'; + + // Generate new tab ID + if ($('#' + tabId).size()) { + tab.select(tabId); + return; + } - var imageOsVers = $.cookie("osvers").split(","); - var imageArch = $.cookie("osarchs").split(","); - var profiles = $.cookie("profiles").split(","); - - var createImgForm = $('
                                                                      '); - var createImgFS = $('
                                                                      ').append('Create Image'); - createImgForm.append(createImgFS); + var imageOsVers = $.cookie("osvers").split(","); + var imageArch = $.cookie("osarchs").split(","); + var profiles = $.cookie("profiles").split(","); + + var createImgForm = $('
                                                                      '); + var createImgFS = $('
                                                                      ').append('Create Image'); + createImgForm.append(createImgFS); - // Show info bar - var infoBar = createInfoBar('Specify the parameters for the image (stateless or statelite) you want to create, then click Create.'); - createImgFS.append(infoBar); + // Show info bar + var infoBar = createInfoBar('Specify the parameters for the image (stateless or statelite) you want to create, then click Create.'); + createImgFS.append(infoBar); - // Drop down for OS versions - var osVerSelect = $(''); - for (var i in imageOsVers) - osVerSelect.append(''); - createImgFS.append($('
                                                                      ').append(osVerSelect)); + // Drop down for OS versions + var osVerSelect = $(''); + for (var i in imageOsVers) + osVerSelect.append(''); + createImgFS.append($('
                                                                      ').append(osVerSelect)); - // Drop down for OS architectures - var imgSelect = $(''); - for (var i in imageArch) - imgSelect.append(''); - createImgFS.append($('
                                                                      ').append(imgSelect)); + // Drop down for OS architectures + var imgSelect = $(''); + for (var i in imageArch) + imgSelect.append(''); + createImgFS.append($('
                                                                      ').append(imgSelect)); - // Netboot interface input - createImgFS.append($('
                                                                      ')); - - // Profile selector - var profileSelect = $('' + - '' + - '' + - '
                                                                      ')); - - // Create HPC software stack fieldset - createHpcFS(createImgForm); + // Netboot interface input + createImgFS.append($('
                                                                      ')); + + // Profile selector + var profileSelect = $('' + + '' + + '' + + '
                                                                    ')); + + // Create HPC software stack fieldset + createHpcFS(createImgForm); - // The button used to create images is created here + // The button used to create images is created here var createImageBtn = createButton("Create"); createImageBtn.bind('click', function(event) { createImage(); @@ -371,725 +779,630 @@ function loadCreateImage() { createImgForm.append(createImageBtn); - // Add tab - tab.add(tabId, 'Create', createImgForm, true); - tab.select(tabId); + // Add tab + tab.add(tabId, 'Create', createImgForm, true); + tab.select(tabId); - // Check the selected OS version and OS arch for HPC stack - // If they are valid, show the HCP stack fieldset - hpcShow(); + // Check the selected OS version and OS arch for HPC stack + // If they are valid, show the HCP stack fieldset + hpcShow(); } /** * Create HPC fieldset * - * @param container - * The container to hold the HPC fieldset - * @return Nothing + * @param container The container to hold the HPC fieldset */ function createHpcFS(container) { - var hpcFieldset = $('
                                                                    '); - hpcFieldset.append('HPC Software Stack'); - - var str = 'Before selecting the software, you should have the following already completed on your xCAT cluster:

                                                                    ' - + '1. If you are using the xCAT hierarchy, your service nodes are installed and running.
                                                                    ' - + '2. Your compute nodes are defined in xCAT, and you have verified your hardware control capabilities, ' - + 'gathered MAC addresses, and done all the other necessary preparations for a diskless install.
                                                                    ' - + '3. You should have a diskless image created with the base OS installed and verified it on at least one test node.
                                                                    ' - + '4. You should install the software on the management node and copy all correponding packages into the location "/install/custom/otherpkgs/" based on ' - + 'these documents.
                                                                    '; - hpcFieldset.append(createInfoBar(str)); - - // Advanced software - str = '
                                                                    • GPFS
                                                                    • ' + - '
                                                                    • RSCT
                                                                    • ' + - '
                                                                    • PE
                                                                    • ' + - '
                                                                    • ESSl & PESSL
                                                                    • ' + - '
                                                                    ' + - '
                                                                    • Ganglia
                                                                    • ' + - '
                                                                    '; - hpcFieldset.append(str); + var hpcFieldset = $('
                                                                    '); + hpcFieldset.append('HPC Software Stack'); + + var str = 'Before selecting the software, you should have the following already completed on your xCAT cluster:

                                                                    ' + + '1. If you are using the xCAT hierarchy, your service nodes are installed and running.
                                                                    ' + + '2. Your compute nodes are defined in xCAT, and you have verified your hardware control capabilities, ' + + 'gathered MAC addresses, and done all the other necessary preparations for a diskless install.
                                                                    ' + + '3. You should have a diskless image created with the base OS installed and verified it on at least one test node.
                                                                    ' + + '4. You should install the software on the management node and copy all correponding packages into the location "/install/custom/otherpkgs/" based on ' + + 'these documents.
                                                                    '; + hpcFieldset.append(createInfoBar(str)); + + // Advanced software + str = '
                                                                    • GPFS
                                                                    • ' + + '
                                                                    • RSCT
                                                                    • ' + + '
                                                                    • PE
                                                                    • ' + + '
                                                                    • ESSl & PESSL
                                                                    • ' + + '
                                                                    ' + + '
                                                                    • Ganglia
                                                                    • ' + + '
                                                                    '; + hpcFieldset.append(str); - container.append($('
                                                                    ').append(hpcFieldset)); + container.append($('
                                                                    ').append(hpcFieldset)); } /** * Check the dependance for ESSL and start the software check for ESSL * - * @param softwareObject - * The checkbox object of ESSL - * @return nothing + * @param softwareObject The checkbox object of ESSL */ function esslCheck(softwareObject) { - var softwareName = softwareObject.name; - if (!$('#createImageTab input[name=pe]').attr('checked')) { - var warnBar = createWarnBar('You must first select the PE'); - $(':checkbox[name=essl]').attr("checked", false); - - // Clear existing warnings and append new warning - $('#hpcsoft .ui-state-error').remove(); - $('#hpcsoft').prepend(warnBar); - - return; - } else { - softwareCheck(softwareObject); - } + var softwareName = softwareObject.name; + if (!$('#createImageTab input[name=pe]').attr('checked')) { + var warnBar = createWarnBar('You must first select the PE'); + $(':checkbox[name=essl]').attr("checked", false); + + // Clear existing warnings and append new warning + $('#hpcsoft .ui-state-error').remove(); + $('#hpcsoft').prepend(warnBar); + + return; + } else { + softwareCheck(softwareObject); + } } /** * Check the parameters for the HPC software * - * @param softwareObject - * Checkbox object of the HPC software - * @return True: The checkbox is checked - * False: Error message shown on page + * @param softwareObject Checkbox object of the HPC software + * @return True if the checkbox is checked, false otherwise */ function softwareCheck(softwareObject) { - var softwareName = softwareObject.name; - $('#createImageTab #' + softwareName + 'li .ui-state-error').remove(); - $('#createImageTab #' + softwareName + 'li').append(createLoader()); - var cmdString = genRpmCmd(softwareName); - $.ajax( { - url : 'lib/systemcmd.php', - dataType : 'json', - data : { - cmd : cmdString, - msg : softwareName - }, - success : function(data) { - if (rpmCheck(data.rsp, data.msg)) { - genLsCmd(data.msg); - $.ajax( { - url : 'lib/systemcmd.php', - dataType : 'json', - data : { - cmd : genLsCmd(data.msg), - msg : data.msg - }, - success : rpmCopyCheck - }); - } - } - }); + var softwareName = softwareObject.name; + $('#createImageTab #' + softwareName + 'li .ui-state-error').remove(); + $('#createImageTab #' + softwareName + 'li').append(createLoader()); + var cmdString = genRpmCmd(softwareName); + $.ajax( { + url : 'lib/systemcmd.php', + dataType : 'json', + data : { + cmd : cmdString, + msg : softwareName + }, + success : function(data) { + if (rpmCheck(data.rsp, data.msg)) { + genLsCmd(data.msg); + $.ajax( { + url : 'lib/systemcmd.php', + dataType : 'json', + data : { + cmd : genLsCmd(data.msg), + msg : data.msg + }, + success : rpmCopyCheck + }); + } + } + }); } /** * Check if the RPMs are copied to the special location * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function rpmCopyCheck(data) { - // Remove the loading image - var errorStr = ''; - var softwareName = data.msg; - - // Check the return information - var reg = /.+:(.+): No such.*/; - var resultArray = data.rsp.split("\n"); - for ( var i in resultArray) { - var temp = reg.exec(resultArray[i]); - if (temp) { - // Find out the path and RPM name - var pos = temp[1].lastIndexOf('/'); - var path = temp[1].substring(0, pos); - var rpmName = temp[1].substring(pos + 1).replace('*', ''); - errorStr += 'copy ' + rpmName + ' to ' + path + '
                                                                    '; - } - } - $('#createImageTab #' + softwareName + 'li').find('img').remove(); - - // No error, show the check image - if (!errorStr) { - var infoPart = '
                                                                    '; - $('#createImageTab #' + softwareName + 'li').append(infoPart); - } else { - // Show the error message - errorStr = 'To install the RSCT on your compute node. You should:
                                                                    ' + errorStr + '
                                                                    '; - var warnBar = createWarnBar(errorStr); - $(':checkbox[name=' + softwareName + ']').attr("checked", false); - - // Clear existing warnings and append new warning - $('#hpcsoft .ui-state-error').remove(); - $('#hpcsoft').prepend(warnBar); - } + // Remove the loading image + var errorStr = ''; + var softwareName = data.msg; + + // Check the return information + var reg = /.+:(.+): No such.*/; + var resultArray = data.rsp.split("\n"); + for ( var i in resultArray) { + var temp = reg.exec(resultArray[i]); + if (temp) { + // Find out the path and RPM name + var pos = temp[1].lastIndexOf('/'); + var path = temp[1].substring(0, pos); + var rpmName = temp[1].substring(pos + 1).replace('*', ''); + errorStr += 'copy ' + rpmName + ' to ' + path + '
                                                                    '; + } + } + $('#createImageTab #' + softwareName + 'li').find('img').remove(); + + // No error, show the check image + if (!errorStr) { + var infoPart = '
                                                                    '; + $('#createImageTab #' + softwareName + 'li').append(infoPart); + } else { + // Show the error message + errorStr = 'To install the RSCT on your compute node. You should:
                                                                    ' + errorStr + '
                                                                    '; + var warnBar = createWarnBar(errorStr); + $(':checkbox[name=' + softwareName + ']').attr("checked", false); + + // Clear existing warnings and append new warning + $('#hpcsoft .ui-state-error').remove(); + $('#hpcsoft').prepend(warnBar); + } } /** * Generate the RPM command for rpmcheck * - * @param softwareName - * The name of the software - * @return The RPM command, e.g. 'rpm -q ***' + * @param softwareName The name of the software + * @return The RPM command */ function genRpmCmd(softwareName) { - var cmdString; - cmdString = 'rpm -q '; - for (var i in softwareList[softwareName]) { - cmdString += softwareList[softwareName][i] + ' '; - } + var cmdString; + cmdString = 'rpm -q '; + for (var i in softwareList[softwareName]) { + cmdString += softwareList[softwareName][i] + ' '; + } - for (var i in softwareList['base']) { - cmdString += softwareList['base'][i] + ' '; - } - - return cmdString; + for (var i in softwareList['base']) { + cmdString += softwareList['base'][i] + ' '; + } + + return cmdString; } /** * Check if the RPMs for the HPC software are copied to the special location * - * @param softwareName - * The name of the software - * @return True: OK - * False: Add the error message to the page + * @param softwareName The name of the software */ function genLsCmd(softwareName) { - var osvers = $('#createImageTab #osvers').val(); - var osarch = $('#createImageTab #osarch').val(); - var path = '/install/post/otherpkgs/' + osvers + '/' + osarch + '/' + softwareName; - var checkCmd = 'ls '; + var osvers = $('#createImageTab #osvers').val(); + var osarch = $('#createImageTab #osarch').val(); + var path = '/install/post/otherpkgs/' + osvers + '/' + osarch + '/' + softwareName; + var checkCmd = 'ls '; - for (var i in softwareList[softwareName]) { - checkCmd += path + '/' + softwareList[softwareName][i] + '*.rpm '; - } - checkCmd += '2>&1'; + for (var i in softwareList[softwareName]) { + checkCmd += path + '/' + softwareList[softwareName][i] + '*.rpm '; + } + checkCmd += '2>&1'; - return checkCmd; + return checkCmd; } /** * Check if all RPMs are installed * - * @param checkInfo - * 'rpm -q' output - * @return True: All RPMs are installed - * False: Some RPMs are not installed + * @param checkInfo 'rpm -q' output + * @return True if all RPMs are installed, false otherwise */ function rpmCheck(checkInfo, name) { - var errorStr = ''; + var errorStr = ''; - var checkArray = checkInfo.split('\n'); - for (var i in checkArray) { - if (checkArray[i].indexOf('not install') != -1) { - errorStr += checkArray[i] + '
                                                                    '; - } - } + var checkArray = checkInfo.split('\n'); + for (var i in checkArray) { + if (checkArray[i].indexOf('not install') != -1) { + errorStr += checkArray[i] + '
                                                                    '; + } + } - if (!errorStr) { - return true; - } + if (!errorStr) { + return true; + } - errorStr = errorStr.substr(0, errorStr.length - 1); - $(':checkbox[name=' + name + ']').attr('checked', false); - - // Add the error - var warnBar = createWarnBar(errorStr); - $('#createImageTab #' + name + 'li').find('img').remove(); + errorStr = errorStr.substr(0, errorStr.length - 1); + $(':checkbox[name=' + name + ']').attr('checked', false); + + // Add the error + var warnBar = createWarnBar(errorStr); + $('#createImageTab #' + name + 'li').find('img').remove(); - // Clear existing warnings and append new warning - $('#hpcsoft .ui-state-error').remove(); - $('#hpcsoft').prepend(warnBar); - - return; + // Clear existing warnings and append new warning + $('#hpcsoft .ui-state-error').remove(); + $('#hpcsoft').prepend(warnBar); + + return; } /** * Check the option and decide whether to show the hpcsoft or not - * - * @param Nothing - * @return Nothing */ function hpcShow() { - // The current UI only supports RHELS 6 - // If you want to support all, delete the subcheck - if ($('#createImageTab #osvers').attr('value') != "rhels6" || $('#createImageTab #osarch').attr('value') != "ppc64" || $('#createImageTab #profile').attr('value') != "compute") { - $('#createImageTab #partlysupport').hide(); - } else { - $('#createImageTab #partlysupport').show(); - } + // The current UI only supports RHELS 6 + // If you want to support all, delete the subcheck + if ($('#createImageTab #osvers').attr('value') != "rhels6" || $('#createImageTab #osarch').attr('value') != "ppc64" || $('#createImageTab #profile').attr('value') != "compute") { + $('#createImageTab #partlysupport').hide(); + } else { + $('#createImageTab #partlysupport').show(); + } } /** * Load set image properties page * - * @param tgtImage - * Target image to set properties - * @return Nothing + * @param tgtImage Target image to set properties */ -function loadEditImagePage(tgtImage) { - // Get nodes tab - var tab = getProvisionTab(); +function openEditImagePage(tgtImage) { + // Get nodes tab + var tab = getProvisionTab(); - // Generate new tab ID - var inst = 0; - var newTabId = 'editImageTab' + inst; - while ($('#' + newTabId).length) { - // If one already exists, generate another one - inst = inst + 1; - newTabId = 'editImageTab' + inst; - } + // Generate new tab ID + var inst = 0; + var newTabId = 'editImageTab' + inst; + while ($('#' + newTabId).length) { + // If one already exists, generate another one + inst = inst + 1; + newTabId = 'editImageTab' + inst; + } - // Open new tab - // Create set properties form - var setPropsForm = $('
                                                                    '); + // Open new tab + // Create set properties form + var setPropsForm = $('
                                                                    '); - // Create info bar - var infoBar = createInfoBar('Choose the properties you wish to change on the node. When you are finished, click Save.'); - setPropsForm.append(infoBar); + // Create info bar + var infoBar = createInfoBar('Choose the properties you wish to change on the node. When you are finished, click Save.'); + setPropsForm.append(infoBar); - // Create an input for each definable attribute - var div, label, input, value; - // Set node attribute - origAttrs[tgtImage]['imagename'] = tgtImage; - for (var key in defAttrs) { - // If an attribute value exists - if (origAttrs[tgtImage][key]) { - // Set the value - value = origAttrs[tgtImage][key]; - } else { - value = ''; - } - - // Create label and input for attribute - div = $('
                                                                    ').css('display', 'inline'); - label = $('').css('vertical-align', 'middle'); - input = $('').css('margin-top', '5px'); - - // Create server browser - switch (key) { - case 'pkgdir': - input.serverBrowser({ - onSelect : function(path) { - $('#pkgdir').val(path); - }, - onLoad : function() { - return $('#pkgdir').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [{ - text : 'Install', - image : 'desktop.png', - path : '/install' - }], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/install' // Limit user to only install directory - }); - break; - case 'otherpkgdir': - input.serverBrowser({ - onSelect : function(path) { - $('#otherpkgdir').val(path); - }, - onLoad : function() { - return $('#otherpkgdir').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [{ - text : 'Install', - image : 'desktop.png', - path : '/install' - }], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/install' // Limit user to only install directory - }); - break; - case 'pkglist': - input.serverBrowser({ - onSelect : function(path) { - $('#pkglist').val(path); - }, - onLoad : function() { - return $('#pkglist').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [{ - text : 'Install', - image : 'desktop.png', - path : '/install' - }], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/opt/xcat/share' // Limit user to only install directory - }); - break; - case 'otherpkglist': - input.serverBrowser({ - onSelect : function(path) { - $('#otherpkglist').val(path); - }, - onLoad : function() { - return $('#otherpkglist').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [{ - text : 'Install', - image : 'desktop.png', - path : '/install' - }], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/install' // Limit user to only install directory - }); - break; - case 'template': - input.serverBrowser({ - onSelect : function(path) { - $('#template').val(path); - }, - onLoad : function() { - return $('#template').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [{ - text : 'Install', - image : 'desktop.png', - path : '/install' - }], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/opt/xcat/share' // Limit user to only install directory - }); - break; - default: - // Do nothing - } - - // Change border to blue onchange - input.bind('change', function(event) { - $(this).css('border-color', 'blue'); - }); - - div.append(label); - div.append(input); - setPropsForm.append(div); - } - - // Change style for last division - div.css({ - 'display': 'block', - 'margin': '0px 0px 10px 0px' - }); - - // Generate tooltips - setPropsForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.8, - delay: 500, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - } - }); + // Create an input for each definable attribute + var div, label, input, value; + // Set node attribute + origAttrs[tgtImage]['imagename'] = tgtImage; + for (var key in defAttrs) { + // If an attribute value exists + if (origAttrs[tgtImage][key]) { + // Set the value + value = origAttrs[tgtImage][key]; + } else { + value = ''; + } + + // Create label and input for attribute + div = $('
                                                                    ').css('display', 'inline'); + label = $('').css('vertical-align', 'middle'); + input = $('').css('margin-top', '5px'); + + // Create server browser + switch (key) { + case 'pkgdir': + input.serverBrowser({ + onSelect : function(path) { + $('#pkgdir').val(path); + }, + onLoad : function() { + return $('#pkgdir').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + break; + case 'otherpkgdir': + input.serverBrowser({ + onSelect : function(path) { + $('#otherpkgdir').val(path); + }, + onLoad : function() { + return $('#otherpkgdir').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + break; + case 'pkglist': + input.serverBrowser({ + onSelect : function(path) { + $('#pkglist').val(path); + }, + onLoad : function() { + return $('#pkglist').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/opt/xcat/share' // Limit user to only install directory + }); + break; + case 'otherpkglist': + input.serverBrowser({ + onSelect : function(path) { + $('#otherpkglist').val(path); + }, + onLoad : function() { + return $('#otherpkglist').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + break; + case 'template': + input.serverBrowser({ + onSelect : function(path) { + $('#template').val(path); + }, + onLoad : function() { + return $('#template').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [{ + text : 'Install', + image : 'desktop.png', + path : '/install' + }], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/opt/xcat/share' // Limit user to only install directory + }); + break; + default: + // Do nothing + } + + // Change border to blue onchange + input.bind('change', function(event) { + $(this).css('border-color', 'blue'); + }); + + div.append(label); + div.append(input); + setPropsForm.append(div); + } + + // Change style for last division + div.css({ + 'display': 'block', + 'margin': '0px 0px 10px 0px' + }); + + // Generate tooltips + setPropsForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.8, + delay: 500, + predelay: 800, + events: { + def: "mouseover,mouseout", + input: "mouseover,mouseout", + widget: "focus mouseover,blur mouseout", + tooltip: "mouseover,mouseout" + } + }); - /** - * Save - */ - var saveBtn = createButton('Save'); - saveBtn.bind('click', function(event) { - // Get all inputs - var inputs = $('#' + newTabId + ' input'); - - // Go through each input - var args = ''; - var attrName, attrVal; - inputs.each(function(){ - // If the border color is blue - if ($(this).css('border-left-color') == 'rgb(0, 0, 255)') { - // Change border color back to normal - $(this).css('border-color', ''); - - // Get attribute name and value - attrName = $(this).parent().find('label').text().replace(':', ''); - attrVal = $(this).val(); - - // Build argument string - if (args) { - // Handle subsequent arguments - args += ';' + attrName + '=' + attrVal; - } else { - // Handle the 1st argument - args += attrName + '=' + attrVal; - } - } - }); - - // Send command to change image attributes - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : '-t;osimage;-o;' + tgtImage + ';' + args, - msg : 'out=' + newTabId + ';tgt=' + tgtImage - }, + /** + * Save + */ + var saveBtn = createButton('Save'); + saveBtn.bind('click', function(event) { + // Get all inputs + var inputs = $('#' + newTabId + ' input'); + + // Go through each input + var args = ''; + var attrName, attrVal; + inputs.each(function(){ + // If the border color is blue + if ($(this).css('border-left-color') == 'rgb(0, 0, 255)') { + // Change border color back to normal + $(this).css('border-color', ''); + + // Get attribute name and value + attrName = $(this).parent().find('label').text().replace(':', ''); + attrVal = $(this).val(); + + // Build argument string + if (args) { + // Handle subsequent arguments + args += ';' + attrName + '=' + attrVal; + } else { + // Handle the 1st argument + args += attrName + '=' + attrVal; + } + } + }); + + // Send command to change image attributes + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : '-t;osimage;-o;' + tgtImage + ';' + args, + msg : 'out=' + newTabId + ';tgt=' + tgtImage + }, - success: showChdefOutput - }); - }); - setPropsForm.append(saveBtn); - - /** - * Cancel - */ - var cancelBtn = createButton('Cancel'); - cancelBtn.bind('click', function(event) { - // Close the tab - tab.remove($(this).parent().parent().attr('id')); - }); - setPropsForm.append(cancelBtn); + success: showChdefOutput + }); + }); + setPropsForm.append(saveBtn); + + /** + * Cancel + */ + var cancelBtn = createButton('Cancel'); + cancelBtn.bind('click', function(event) { + // Close the tab + tab.remove($(this).parent().parent().attr('id')); + }); + setPropsForm.append(cancelBtn); - // Append to discover tab - tab.add(newTabId, 'Edit', setPropsForm, true); + // Append to discover tab + tab.add(newTabId, 'Edit', setPropsForm, true); - // Select new tab - tab.select(newTabId); + // Select new tab + tab.select(newTabId); } /** * Load copy CD page - * - * @return Nothing */ -function loadCopyCdPage() { - // Get provision tab - var tab = getProvisionTab(); +function openCopyCdDialog() { + // Create copy Linux form + var dialogId = 'imageCopyCd'; + var copyLinuxForm = $('
                                                                    '); + + // Create info bar + var infoBar = createInfoBar('Copy Linux distributions and service levels from CDs or DVDs to the install directory.'); + copyLinuxForm.append(infoBar); + + // Create Linux ISO input + var iso = $('
                                                                    '); + var isoLabel = $('').css('vertical-align', 'middle'); + var isoInput = $('').css('width', '300px'); + iso.append(isoLabel); + iso.append(isoInput); + copyLinuxForm.append(iso); + + // Create architecture input + copyLinuxForm.append('
                                                                    '); + // Create distribution input + copyLinuxForm.append('
                                                                    '); + + /** + * Browse + */ + var browseBtn = createButton('Browse'); + iso.append(browseBtn); + // Browse server directory and files + browseBtn.serverBrowser({ + onSelect : function(path) { + $('#imageCopyCd #iso').val(path); + }, + onLoad : function() { + return $('#imageCopyCd #iso').val(); + }, + knownExt : [ 'exe', 'js', 'txt' ], + knownPaths : [ { + text : 'Install', + image : 'desktop.png', + path : '/install' + } ], + imageUrl : 'images/serverbrowser/', + systemImageUrl : 'images/serverbrowser/', + handlerUrl : 'lib/getpath.php', + title : 'Browse', + requestMethod : 'POST', + width : '500', + height : '300', + basePath : '/install' // Limit user to only install directory + }); + + // Open dialog to copy CD + copyLinuxForm.dialog({ + title:'Copy CD', + close: function(){ + $(this).remove(); + }, + modal: true, + width: 600, + buttons: { + "Copy": function() { + // Show loader + $('.ui-dialog #imageCopyCd').append(createLoader('')); + + // Change dialog buttons + $(this).dialog('option', 'buttons', { + 'Close': function() {$(this).dialog("close");} + }); + + // Get image attributes + var iso = $(this).find('input[name="iso"]'); + var arch = $(this).find('input[name="arch"]'); + var distro = $(this).find('input[name="distro"]'); - // Generate new tab ID - var inst = 0; - newTabId = 'copyLinuxTab' + inst; - while ($('#' + newTabId).length) { - // If one already exists, generate another one - inst = inst + 1; - newTabId = 'copyLinuxTab' + inst; - } - - // Create copy Linux form - var copyLinuxForm = $('
                                                                    '); - - // Create status bar, hide on load - var statBarId = 'copyLinuxStatusBar' + inst; - var statBar = createStatusBar(statBarId).hide(); - copyLinuxForm.append(statBar); - - // Create loader - var loader = createLoader(''); - statBar.find('div').append(loader); - - // Create info bar - var infoBar = createInfoBar('Copy Linux distributions and service levels from CDs or DVDs to the install directory.'); - copyLinuxForm.append(infoBar); - - // Create Linux ISO input - var iso = $('
                                                                    '); - var isoLabel = $('').css('vertical-align', 'middle'); - var isoInput = $('').css('width', '300px'); - iso.append(isoLabel); - iso.append(isoInput); - copyLinuxForm.append(iso); - - // Create architecture input - copyLinuxForm.append('
                                                                    '); - // Create distribution input - copyLinuxForm.append('
                                                                    '); - - // Generate tooltips - copyLinuxForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - delay: 500, - predelay: 800, - events: { - def: "mouseover,mouseout", - input: "mouseover,mouseout", - widget: "focus mouseover,blur mouseout", - tooltip: "mouseover,mouseout" - } - }); - - /** - * Browse - */ - var browseBtn = createButton('Browse'); - iso.append(browseBtn); - // Browse server directory and files - browseBtn.serverBrowser({ - onSelect : function(path) { - $('#iso').val(path); - }, - onLoad : function() { - return $('#iso').val(); - }, - knownExt : [ 'exe', 'js', 'txt' ], - knownPaths : [ { - text : 'Install', - image : 'desktop.png', - path : '/install' - } ], - imageUrl : 'images/serverbrowser/', - systemImageUrl : 'images/serverbrowser/', - handlerUrl : 'lib/getpath.php', - title : 'Browse', - requestMethod : 'POST', - width : '500', - height : '300', - basePath : '/install' // Limit user to only install directory - }); - - /** - * Copy - */ - var copyBtn = createButton('Copy'); - copyLinuxForm.append(copyBtn); - copyBtn.bind('click', function(event) { - // Disable all inputs and buttons - $('#' + newTabId + ' input').attr('disabled', 'true'); - $('#' + newTabId + ' button').attr('disabled', 'true'); - // Show status bar and loader - $('#' + statBarId).show(); - $('#' + statBarId).find('img').show(); - - // Get Linux ISO - var iso = $('#' + newTabId + ' input[name=iso]').val(); - // Get architecture - var arch = $('#' + newTabId + ' input[name=arch]').val(); - // Get distribution - var distro = $('#' + newTabId + ' input[name=distro]').val(); - - // Send ajax request to copy ISO - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'copycds', - tgt : '', - args : '-n;' + distro + ';-a;' + arch + ';' + iso, - msg : 'out=' + statBarId - }, - - /** - * Show output - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success : function(data) { - // Get output - var out = data.rsp; - // Get status bar ID - var statBarId = data.msg.replace('out=', ''); - // Get tab ID - var tabId = statBarId.replace('copyLinuxStatusBar', 'copyLinuxTab'); - - // Go through output and append to paragraph - var prg = $('
                                                                    ');
                                                                    -				for (var i in out) {
                                                                    -					if (out[i].length > 6) {
                                                                    -						prg.append(out[i] + '
                                                                    '); - } - } - $('#' + statBarId).find('div').append(prg); - - // Hide loader - $('#' + statBarId).find('img').hide(); - // Enable inputs and buttons - $('#' + tabId + ' input').attr('disabled', ''); - $('#' + tabId + ' button').attr('disabled', ''); - } - }); - }); - - /** - * Cancel - */ - var cancelBtn = createButton('Cancel'); - copyLinuxForm.append(cancelBtn); - cancelBtn.bind('click', function(event) { - // Close the tab - tab.remove($(this).parent().parent().attr('id')); - }); - - tab.add(newTabId, 'Copy', copyLinuxForm, true); - tab.select(newTabId); + // Send ajax request to copy ISO + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'copycds', + tgt : '', + args : '-n;' + distro.val() + ';-a;' + arch.val() + ';' + iso.val(), + msg : dialogId + }, + + success : updateImageDialog + }); + }, + "Cancel": function() { + $(this).dialog( "close" ); + } + } + }); } /** - * use users' input or select to create image - * - * @param - * - * @return Nothing + * Use user input or select to create image */ function createImage() { - var osvers = $("#createImageTab #osvers").val(); - var osarch = $("#createImageTab #osarch").val(); - var profile = $("#createImageTab #profile").val(); - var bootInterface = $("#createImageTab #netbootif").val(); - var bootMethod = $("#createImageTab #bootmethod").val(); + var osvers = $("#createImageTab #osvers").val(); + var osarch = $("#createImageTab #osarch").val(); + var profile = $("#createImageTab #profile").val(); + var bootInterface = $("#createImageTab #netbootif").val(); + var bootMethod = $("#createImageTab #bootmethod").val(); - $('#createImageTab .ui-state-error').remove(); - // If there no input for the bootInterface - if (!bootInterface) { - var warnBar = createWarnBar('Please specify the netboot interface'); - $("#createImageTab").prepend(warnBar); - return; - } + $('#createImageTab .ui-state-error').remove(); + // If there no input for the bootInterface + if (!bootInterface) { + var warnBar = createWarnBar('Please specify the netboot interface'); + $("#createImageTab").prepend(warnBar); + return; + } - var createImageArgs = "createimage;" + osvers + ";" + osarch + ";" + profile + ";" + bootInterface + ";" + bootMethod + ";"; + var createImageArgs = "createimage;" + osvers + ";" + osarch + ";" + profile + ";" + bootInterface + ";" + bootMethod + ";"; - $("#createImageTab :checkbox:checked").each(function() { - createImageArgs += $(this).attr("name") + ","; - }); + $("#createImageTab :checkbox:checked").each(function() { + createImageArgs += $(this).attr("name") + ","; + }); - createImageArgs = createImageArgs.substring(0, (createImageArgs.length - 1)); - $.ajax({ - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : createImageArgs, - msg : '' - }, - success : function(data) { - - } - }); + createImageArgs = createImageArgs.substring(0, (createImageArgs.length - 1)); + $.ajax({ + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : createImageArgs, + msg : '' + }, + success : function(data) { + + } + }); } \ No newline at end of file diff --git a/xCAT-UI/js/provision/provision.js b/xCAT-UI/js/provision/provision.js index aab9e5b1b..4f7a71279 100644 --- a/xCAT-UI/js/provision/provision.js +++ b/xCAT-UI/js/provision/provision.js @@ -6,12 +6,10 @@ var provisionTabs; // Provision tabs /** * Set the provision tab * - * @param obj - * Tab object - * @return Nothing + * @param obj Tab object */ function setProvisionTab(obj) { - provisionTabs = obj; + provisionTabs = obj; } /** @@ -21,157 +19,155 @@ function setProvisionTab(obj) { * @return Tab object */ function getProvisionTab() { - return provisionTabs; + return provisionTabs; } /** * Load provision page - * - * @return Nothing */ function loadProvisionPage() { - // If the page is loaded - if ($('#content').children().length) { - // Do not load again - return; - } + // If the page is loaded + if ($('#content').children().length) { + // Do not load again + return; + } - // Get OS image names - if (!$.cookie('imagenames')){ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + // Get OS image names + if (!$.cookie('imagenames')){ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : setOSImageCookies - }); - } + success : setOSImageCookies + }); + } - // Get groups - if (!$.cookie('groups')){ - $.ajax( { - url : 'lib/cmd.php', - dataType : 'json', - data : { - cmd : 'extnoderange', - tgt : '/.*', - args : 'subgroups', - msg : '' - }, + // Get groups + if (!$.cookie('groups')){ + $.ajax( { + url : 'lib/cmd.php', + dataType : 'json', + data : { + cmd : 'extnoderange', + tgt : '/.*', + args : 'subgroups', + msg : '' + }, - success : setGroupsCookies - }); - } - - // Create info bar - var infoBar = createInfoBar('Select a platform to provision or re-provision a node on, then click Ok.'); - - // Create provision page - var provPg = $('
                                                                    '); - provPg.append(infoBar); + success : setGroupsCookies + }); + } + + // Create info bar + var infoBar = createInfoBar('Select a platform to provision or re-provision a node on, then click Ok.'); + + // Create provision page + var provPg = $('
                                                                    '); + provPg.append(infoBar); - // Create provision tab - var tab = new Tab('provisionPageTabs'); - setProvisionTab(tab); - tab.init(); - $('#content').append(tab.object()); + // Create provision tab + var tab = new Tab('provisionPageTabs'); + setProvisionTab(tab); + tab.init(); + $('#content').append(tab.object()); - // Create radio buttons for platforms - var hwList = $('
                                                                      Platforms available:
                                                                    '); - var esx = $('
                                                                  • ESX
                                                                  • '); - var kvm = $('
                                                                  • KVM
                                                                  • '); - var zvm = $('
                                                                  • z\/VM
                                                                  • '); - var ipmi = $('
                                                                  • iDataPlex
                                                                  • '); - var blade = $('
                                                                  • BladeCenter
                                                                  • '); - var hmc = $('
                                                                  • System p
                                                                  • '); - - hwList.append(esx); - hwList.append(kvm); - hwList.append(zvm); - hwList.append(blade); - hwList.append(ipmi); - hwList.append(hmc); - provPg.append(hwList); + // Create radio buttons for platforms + var hwList = $('
                                                                      Platforms available:
                                                                    '); + var esx = $('
                                                                  • ESX
                                                                  • '); + var kvm = $('
                                                                  • KVM
                                                                  • '); + var zvm = $('
                                                                  • z\/VM
                                                                  • '); + var ipmi = $('
                                                                  • iDataPlex
                                                                  • '); + var blade = $('
                                                                  • BladeCenter
                                                                  • '); + var hmc = $('
                                                                  • System p
                                                                  • '); + + hwList.append(esx); + hwList.append(kvm); + hwList.append(zvm); + hwList.append(blade); + hwList.append(ipmi); + hwList.append(hmc); + provPg.append(hwList); - /** - * Ok - */ - var okBtn = createButton('Ok'); - okBtn.bind('click', function(event) { - // Get hardware that was selected - var hw = $(this).parent().find('input[name="hw"]:checked').val(); - - var inst = 0; - var newTabId = hw + 'ProvisionTab' + inst; - while ($('#' + newTabId).length) { - // If one already exists, generate another one - inst = inst + 1; - newTabId = hw + 'ProvisionTab' + inst; - } - + /** + * Ok + */ + var okBtn = createButton('Ok'); + okBtn.bind('click', function(event) { + // Get hardware that was selected + var hw = $(this).parent().find('input[name="hw"]:checked').val(); + + var inst = 0; + var newTabId = hw + 'ProvisionTab' + inst; + while ($('#' + newTabId).length) { + // If one already exists, generate another one + inst = inst + 1; + newTabId = hw + 'ProvisionTab' + inst; + } + // Create an instance of the plugin - var title = ''; + var title = ''; var plugin; switch (hw) { - case "kvm": - plugin = new kvmPlugin(); - title = 'KVM'; - break; - case "esx": - plugin = new esxPlugin(); - title = 'ESX'; - break; - case "blade": - plugin = new bladePlugin(); - title = 'BladeCenter'; - break; - case "hmc": - plugin = new hmcPlugin(); - title = 'System p'; - break; - case "ipmi": - plugin = new ipmiPlugin(); - title = 'iDataPlex'; - break; - case "zvm": - plugin = new zvmPlugin(); - title = 'z/VM'; - break; + case "kvm": + plugin = new kvmPlugin(); + title = 'KVM'; + break; + case "esx": + plugin = new esxPlugin(); + title = 'ESX'; + break; + case "blade": + plugin = new bladePlugin(); + title = 'BladeCenter'; + break; + case "hmc": + plugin = new hmcPlugin(); + title = 'System p'; + break; + case "ipmi": + plugin = new ipmiPlugin(); + title = 'iDataPlex'; + break; + case "zvm": + plugin = new zvmPlugin(); + title = 'z/VM'; + break; } // Select tab tab.add(newTabId, title, '', true); tab.select(newTabId); plugin.loadProvisionPage(newTabId); - }); - provPg.append(okBtn); + }); + provPg.append(okBtn); - // Add provision tab - tab.add('provisionTab', 'Provision', provPg, false); - // Add image tab - tab.add('imagesTab', 'Images', '', false); - - // Load tabs onselect - $('#provisionPageTabs').bind('tabsselect', function(event, ui){ - // Load image page - if (!$('#imagesTab').children().length && ui.index == 1) { - $('#imagesTab').append($('
                                                                    ').append(createLoader(''))); - loadImagesPage(); - } - }); - - // Open the quick provision tab - if (window.location.search) { - tab.add('quickProvisionTab', 'Quick Provision', '', true); - tab.select('quickProvisionTab'); - - var provForm = $('
                                                                    '); - $('#quickProvisionTab').append(provForm); - appendProvisionSection('quick', provForm); - } + // Add provision tab + tab.add('provisionTab', 'Provision', provPg, false); + // Add image tab + tab.add('imagesTab', 'Images', '', false); + + // Load tabs onselect + $('#provisionPageTabs').bind('tabsselect', function(event, ui){ + // Load image page + if (!$('#imagesTab').children().length && ui.index == 1) { + $('#imagesTab').append($('
                                                                    ').append(createLoader(''))); + loadImagesPage(); + } + }); + + // Open the quick provision tab + if (window.location.search) { + tab.add('quickProvisionTab', 'Quick Provision', '', true); + tab.select('quickProvisionTab'); + + var provForm = $('
                                                                    '); + $('#quickProvisionTab').append(provForm); + appendProvisionSection('quick', provForm); + } } \ No newline at end of file diff --git a/xCAT-UI/js/rcons/rcons.js b/xCAT-UI/js/rcons/rcons.js index 9bb776d38..32662baea 100644 --- a/xCAT-UI/js/rcons/rcons.js +++ b/xCAT-UI/js/rcons/rcons.js @@ -1,288 +1,288 @@ rconsTerm = function(nodeName, height, width) { - var sid = nodeName; - var keyBuf = []; - var receivingFlag = false; - var sendTimeout = ""; - var errorTimeout = ""; - var queryStable = 's=' + sid + '&w=' + height + '&h=' + width + '&c=1&k='; - var maxDelay = 200; - var firstFlag = true; + var sid = nodeName; + var keyBuf = []; + var receivingFlag = false; + var sendTimeout = ""; + var errorTimeout = ""; + var queryStable = 's=' + sid + '&w=' + height + '&h=' + width + '&c=1&k='; + var maxDelay = 200; + var firstFlag = true; - var workingStatus = ""; - var termArea = ""; - var errorArea = ""; + var workingStatus = ""; + var termArea = ""; + var errorArea = ""; - var ie = 0; - if (window.ActiveXObject) { - ie = 1; - } + var ie = 0; + if (window.ActiveXObject) { + ie = 1; + } - rconsInit(); - // init - function rconsInit() { - // create status, configure the css - workingStatus = $('.'); - workingStatus.attr('class', 'off'); + rconsInit(); + // init + function rconsInit() { + // Create status, configure the css + workingStatus = $('.'); + workingStatus.attr('class', 'off'); - // create the disconnect button - var disconnectButton = $('Disconnect'); - disconnectButton.bind('click', function() { - window.close(); - }); + // Create the disconnect button + var disconnectButton = $('Disconnect'); + disconnectButton.bind('click', function() { + window.close(); + }); - // create the control panel, add to the rcons div - var controlPanel = $('
                                                                    ');
                                                                    -		$('#term').append(controlPanel);
                                                                    +        // Create the control panel, add to the rcons div
                                                                    +        var controlPanel = $('
                                                                    ');
                                                                    +        $('#term').append(controlPanel);
                                                                     
                                                                    -		// create the error erea
                                                                    -		errorArea = $('');
                                                                    +        // Create the error erea
                                                                    +        errorArea = $('');
                                                                     
                                                                    -		// add all item to controlPanel
                                                                    -		controlPanel.append(workingStatus);
                                                                    -		controlPanel.append(disconnectButton);
                                                                    -		controlPanel.append(errorArea);
                                                                    +        // Add all item to control panel
                                                                    +        controlPanel.append(workingStatus);
                                                                    +        controlPanel.append(disconnectButton);
                                                                    +        controlPanel.append(errorArea);
                                                                     
                                                                    -		// create the termArea
                                                                    -		termArea = $('
                                                                    '); - $('#term').append(termArea); + // Create the termArea + termArea = $('
                                                                    '); + $('#term').append(termArea); - // bind keypress event - document.onkeypress = rconsKeypress; - document.onkeydown = rconsKeydown; - window.onbeforeunload = function() { - rconsDisconnect(); - alert("Closing remote console"); - }; + // Bind keypress event + document.onkeypress = rconsKeypress; + document.onkeydown = rconsKeydown; + window.onbeforeunload = function() { + rconsDisconnect(); + alert("Closing remote console"); + }; - rconsSend(); - } + rconsSend(); + } - // close the connection - function rconsDisconnect() { - window.clearTimeout(sendTimeout); - window.clearTimeout(errorTimeout); + // Close the connection + function rconsDisconnect() { + window.clearTimeout(sendTimeout); + window.clearTimeout(errorTimeout); - $.ajax({ - type : "POST", - url : "lib/rcons.php", - data : queryStable + '&q=1', - dataType : 'json' - }); - } + $.ajax({ + type : "POST", + url : "lib/rcons.php", + data : queryStable + '&q=1', + dataType : 'json' + }); + } - // translate the key press - function rconsKeypress(event) { - if (!event) - var event = window.event; - var kc = ""; - var k = ""; - if (event.keyCode) - kc = event.keyCode; - if (event.which) - kc = event.which; - if (event.altKey) { - if (kc >= 65 && kc <= 90) - kc += 32; - if (kc >= 97 && kc <= 122) { - k = String.fromCharCode(27) + String.fromCharCode(kc); - } - } else if (event.ctrlKey) { - if (kc >= 65 && kc <= 90) - k = String.fromCharCode(kc - 64); // Ctrl-A..Z - else if (kc >= 97 && kc <= 122) - k = String.fromCharCode(kc - 96); // Ctrl-A..Z - else if (kc == 54) - k = String.fromCharCode(30); // Ctrl-^ - else if (kc == 109) - k = String.fromCharCode(31); // Ctrl-_ - else if (kc == 219) - k = String.fromCharCode(27); // Ctrl-[ - else if (kc == 220) - k = String.fromCharCode(28); // Ctrl-\ - else if (kc == 221) - k = String.fromCharCode(29); // Ctrl-] - else if (kc == 219) - k = String.fromCharCode(29); // Ctrl-] - else if (kc == 219) - k = String.fromCharCode(0); // Ctrl-@ - } else if (event.which == 0) { - if (kc == 9) - k = String.fromCharCode(9); // Tab - else if (kc == 8) - k = String.fromCharCode(127); // Backspace - else if (kc == 27) - k = String.fromCharCode(27); // Escape - else { - if (kc == 33) - k = "[5~"; // PgUp - else if (kc == 34) - k = "[6~"; // PgDn - else if (kc == 35) - k = "[4~"; // End - else if (kc == 36) - k = "[1~"; // Home - else if (kc == 37) - k = "[D"; // Left - else if (kc == 38) - k = "[A"; // Up - else if (kc == 39) - k = "[C"; // Right - else if (kc == 40) - k = "[B"; // Down - else if (kc == 45) - k = "[2~"; // Ins - else if (kc == 46) - k = "[3~"; // Del - else if (kc == 112) - k = "[[A"; // F1 - else if (kc == 113) - k = "[[B"; // F2 - else if (kc == 114) - k = "[[C"; // F3 - else if (kc == 115) - k = "[[D"; // F4 - else if (kc == 116) - k = "[[E"; // F5 - else if (kc == 117) - k = "[17~"; // F6 - else if (kc == 118) - k = "[18~"; // F7 - else if (kc == 119) - k = "[19~"; // F8 - else if (kc == 120) - k = "[20~"; // F9 - else if (kc == 121) - k = "[21~"; // F10 - else if (kc == 122) - k = "[23~"; // F11 - else if (kc == 123) - k = "[24~"; // F12 - if (k.length) { - k = String.fromCharCode(27) + k; - } - } - } else { - if (kc == 8) - k = String.fromCharCode(127); // Backspace - else - k = String.fromCharCode(kc); - } - if (k.length) { - if (k == "+") { - rconsQueue("%2B"); - } else { - rconsQueue(escape(k)); - } - } - event.cancelBubble = true; - if (event.stopPropagation) - event.stopPropagation(); - if (event.preventDefault) - event.preventDefault(); - return false; - } + // Translate the key press + function rconsKeypress(event) { + if (!event) + var event = window.event; + var kc = ""; + var k = ""; + if (event.keyCode) + kc = event.keyCode; + if (event.which) + kc = event.which; + if (event.altKey) { + if (kc >= 65 && kc <= 90) + kc += 32; + if (kc >= 97 && kc <= 122) { + k = String.fromCharCode(27) + String.fromCharCode(kc); + } + } else if (event.ctrlKey) { + if (kc >= 65 && kc <= 90) + k = String.fromCharCode(kc - 64); // Ctrl-A..Z + else if (kc >= 97 && kc <= 122) + k = String.fromCharCode(kc - 96); // Ctrl-A..Z + else if (kc == 54) + k = String.fromCharCode(30); // Ctrl-^ + else if (kc == 109) + k = String.fromCharCode(31); // Ctrl-_ + else if (kc == 219) + k = String.fromCharCode(27); // Ctrl-[ + else if (kc == 220) + k = String.fromCharCode(28); // Ctrl-\ + else if (kc == 221) + k = String.fromCharCode(29); // Ctrl-] + else if (kc == 219) + k = String.fromCharCode(29); // Ctrl-] + else if (kc == 219) + k = String.fromCharCode(0); // Ctrl-@ + } else if (event.which == 0) { + if (kc == 9) + k = String.fromCharCode(9); // Tab + else if (kc == 8) + k = String.fromCharCode(127); // Backspace + else if (kc == 27) + k = String.fromCharCode(27); // Escape + else { + if (kc == 33) + k = "[5~"; // PgUp + else if (kc == 34) + k = "[6~"; // PgDn + else if (kc == 35) + k = "[4~"; // End + else if (kc == 36) + k = "[1~"; // Home + else if (kc == 37) + k = "[D"; // Left + else if (kc == 38) + k = "[A"; // Up + else if (kc == 39) + k = "[C"; // Right + else if (kc == 40) + k = "[B"; // Down + else if (kc == 45) + k = "[2~"; // Ins + else if (kc == 46) + k = "[3~"; // Del + else if (kc == 112) + k = "[[A"; // F1 + else if (kc == 113) + k = "[[B"; // F2 + else if (kc == 114) + k = "[[C"; // F3 + else if (kc == 115) + k = "[[D"; // F4 + else if (kc == 116) + k = "[[E"; // F5 + else if (kc == 117) + k = "[17~"; // F6 + else if (kc == 118) + k = "[18~"; // F7 + else if (kc == 119) + k = "[19~"; // F8 + else if (kc == 120) + k = "[20~"; // F9 + else if (kc == 121) + k = "[21~"; // F10 + else if (kc == 122) + k = "[23~"; // F11 + else if (kc == 123) + k = "[24~"; // F12 + if (k.length) { + k = String.fromCharCode(27) + k; + } + } + } else { + if (kc == 8) + k = String.fromCharCode(127); // Backspace + else + k = String.fromCharCode(kc); + } + if (k.length) { + if (k == "+") { + rconsQueue("%2B"); + } else { + rconsQueue(escape(k)); + } + } + event.cancelBubble = true; + if (event.stopPropagation) + event.stopPropagation(); + if (event.preventDefault) + event.preventDefault(); + return false; + } - // translate the key press, same with rconsKeypress - function rconsKeydown(event) { - if (!event) - var event = window.event; - if (ie) { - o = { - 9 : 1, - 8 : 1, - 27 : 1, - 33 : 1, - 34 : 1, - 35 : 1, - 36 : 1, - 37 : 1, - 38 : 1, - 39 : 1, - 40 : 1, - 45 : 1, - 46 : 1, - 112 : 1, - 113 : 1, - 114 : 1, - 115 : 1, - 116 : 1, - 117 : 1, - 118 : 1, - 119 : 1, - 120 : 1, - 121 : 1, - 122 : 1, - 123 : 1 - }; - if (o[event.keyCode] || event.ctrlKey || event.altKey) { - event.which = 0; - return keypress(event); - } - } - } + // Translate the key press, same with rconsKeypress + function rconsKeydown(event) { + if (!event) + var event = window.event; + if (ie) { + o = { + 9 : 1, + 8 : 1, + 27 : 1, + 33 : 1, + 34 : 1, + 35 : 1, + 36 : 1, + 37 : 1, + 38 : 1, + 39 : 1, + 40 : 1, + 45 : 1, + 46 : 1, + 112 : 1, + 113 : 1, + 114 : 1, + 115 : 1, + 116 : 1, + 117 : 1, + 118 : 1, + 119 : 1, + 120 : 1, + 121 : 1, + 122 : 1, + 123 : 1 + }; + if (o[event.keyCode] || event.ctrlKey || event.altKey) { + event.which = 0; + return keypress(event); + } + } + } - // send the command and request to server - function rconsSend() { - var keyPressList = ''; - var requireString = ''; - if (receivingFlag) { - return; - } + // Send the command and request to server + function rconsSend() { + var keyPressList = ''; + var requireString = ''; + if (receivingFlag) { + return; + } - receivingFlag = true; - workingStatus.attr('class', 'on'); + receivingFlag = true; + workingStatus.attr('class', 'on'); - while (keyBuf.length > 0) { - keyPressList += keyBuf.pop(); - } + while (keyBuf.length > 0) { + keyPressList += keyBuf.pop(); + } - if (firstFlag) { - requireString = queryStable + keyPressList + '&f=1'; - firstFlag = false; - } else { - requireString = queryStable + keyPressList; - } + if (firstFlag) { + requireString = queryStable + keyPressList + '&f=1'; + firstFlag = false; + } else { + requireString = queryStable + keyPressList; + } - $.ajax({ - type : "POST", - url : "lib/rcons.php", - data : requireString, - dataType : 'json', - success : function(data) { - rconsUpdate(data); - } - }); + $.ajax({ + type : "POST", + url : "lib/rcons.php", + data : requireString, + dataType : 'json', + success : function(data) { + rconsUpdate(data); + } + }); - errorTimeout = window.setTimeout(rconsSendError, 15000); + errorTimeout = window.setTimeout(rconsSendError, 15000); - } + } - // when receive the response, update the term area - function rconsUpdate(data) { - window.clearTimeout(errorTimeout); - errorArea.empty(); - if (data.term) { - termArea.empty().append(data.term); - maxDelay = 200; - } else { - maxDelay = 2000; - } + // When response received, update the term area + function rconsUpdate(data) { + window.clearTimeout(errorTimeout); + errorArea.empty(); + if (data.term) { + termArea.empty().append(data.term); + maxDelay = 200; + } else { + maxDelay = 2000; + } - receivingFlag = false; - workingStatus.attr('class', 'off'); - sendTimeout = window.setTimeout(rconsSend, maxDelay); - } + receivingFlag = false; + workingStatus.attr('class', 'off'); + sendTimeout = window.setTimeout(rconsSend, maxDelay); + } - function rconsSendError() { - workingStatus.attr('class', 'off'); - errorArea.empty().append('Send require error.'); - } + function rconsSendError() { + workingStatus.attr('class', 'off'); + errorArea.empty().append('Send require error.'); + } - function rconsQueue(kc) { - keyBuf.unshift(kc); - if (false == receivingFlag) { - window.clearTimeout(sendTimeout); - sendTimeout = window.setTimeout(rconsSend, 1); - } - } + function rconsQueue(kc) { + keyBuf.unshift(kc); + if (false == receivingFlag) { + window.clearTimeout(sendTimeout); + sendTimeout = window.setTimeout(rconsSend, 1); + } + } }; \ No newline at end of file diff --git a/xCAT-UI/js/service/service.js b/xCAT-UI/js/service/service.js index b7c35e970..efb57412b 100644 --- a/xCAT-UI/js/service/service.js +++ b/xCAT-UI/js/service/service.js @@ -11,1038 +11,1049 @@ var gangliaTimer; * Initialize service page */ function initServicePage() { - // Load theme - var theme = $.cookie('xcat_theme'); - if (theme) { - switch (theme) { - case 'cupertino': - includeCss("css/themes/jquery-ui-cupertino.css"); - break; - case 'dark_hive': - includeCss("css/themes/jquery-ui-dark_hive.css"); - break; - case 'redmond': - includeCss("css/themes/jquery-ui-redmond.css"); - break; - case 'start': - includeCss("css/themes/jquery-ui-start.css"); - break; - case 'sunny': - includeCss("css/themes/jquery-ui-sunny.css"); - break; - case 'ui_dark': - includeCss("css/themes/jquery-ui-ui_darkness.css"); - break; - default: - includeCss("css/themes/jquery-ui-start.css"); - } - } else { - includeCss("css/themes/jquery-ui-start.css"); - } + // Load theme + var theme = $.cookie('xcat_theme'); + if (theme) { + switch (theme) { + case 'cupertino': + includeCss("css/themes/jquery-ui-cupertino.css"); + break; + case 'dark_hive': + includeCss("css/themes/jquery-ui-dark_hive.css"); + break; + case 'redmond': + includeCss("css/themes/jquery-ui-redmond.css"); + break; + case 'start': + includeCss("css/themes/jquery-ui-start.css"); + break; + case 'sunny': + includeCss("css/themes/jquery-ui-sunny.css"); + break; + case 'ui_dark': + includeCss("css/themes/jquery-ui-ui_darkness.css"); + break; + default: + includeCss("css/themes/jquery-ui-start.css"); + } + } else { + includeCss("css/themes/jquery-ui-start.css"); + } - // Load jQuery stylesheets - includeCss("css/jquery.dataTables.css"); - includeCss("css/superfish.css"); - includeCss("css/jstree.css"); - includeCss("css/jquery.jqplot.css"); - - // Load custom stylesheet - includeCss("css/style.css"); - - // Reuqired JQuery plugins - includeJs("js/jquery/jquery.dataTables.min.js"); - includeJs("js/jquery/jquery.cookie.min.js"); - includeJs("js/jquery/tooltip.min.js"); - includeJs("js/jquery/superfish.min.js"); - includeJs("js/jquery/jquery.jqplot.min.js"); + // Load jQuery stylesheets + includeCss("css/jquery.dataTables.css"); + includeCss("css/superfish.css"); + includeCss("css/jstree.css"); + includeCss("css/jquery.jqplot.css"); + + // Load custom stylesheet + includeCss("css/style.css"); + + // Reuqired JQuery plugins + includeJs("js/jquery/jquery.dataTables.min.js"); + includeJs("js/jquery/jquery.cookie.min.js"); + includeJs("js/jquery/tooltip.min.js"); + includeJs("js/jquery/superfish.min.js"); + includeJs("js/jquery/jquery.jqplot.min.js"); includeJs("js/jquery/jqplot.dateAxisRenderer.min.js"); // Custom plugins - includeJs("js/custom/blade.js"); - includeJs("js/custom/ipmi.js"); - includeJs("js/custom/zvm.js"); - includeJs("js/custom/hmc.js"); - - // Enable settings link - $('#xcat_settings').click(function() { - openSettings(); - }); - - // Show service page - $("#content").children().remove(); - includeJs("js/service/utils.js"); - loadServicePage(); - - // Initialize tab index history - $.cookie('tabindex_history', '0,0'); + includeJs("js/custom/esx.js"); + includeJs("js/custom/kvm.js"); + includeJs("js/custom/zvm.js"); + + // Enable settings link + $('#xcat_settings').click(function() { + openSettings(); + }); + + // Show service page + $("#content").children().remove(); + includeJs("js/service/utils.js"); + loadServicePage(); + + // Initialize tab index history + $.cookie('tabindex_history', '0,0'); } /** * Load service page */ function loadServicePage() { - // If the page is loaded - if ($('#content').children().length) { - // Do not load again - return; - } - - // Create manage and provision tabs - serviceTabs = new Tab(); - serviceTabs.init(); - $('#content').append(serviceTabs.object()); - - var manageTabId = 'manageTab'; - serviceTabs.add(manageTabId, 'Manage', '', false); - - // Get nodes owned by user - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'nodetype', - msg : '' - }, + // If the page is loaded + if ($('#content').children().length) { + // Do not load again + return; + } + + // Create manage and provision tabs + serviceTabs = new Tab(); + serviceTabs.init(); + $('#content').append(serviceTabs.object()); + + var manageTabId = 'manageTab'; + serviceTabs.add(manageTabId, 'Manage', '', false); + + // Get nodes owned by user + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'nodetype', + msg : '' + }, - success : function(data) { - setUserNodes(data); - setMaxVM(); - getUserNodesDef(); - getNodesCurrentLoad(); - loadManagePage(manageTabId); - } - }); - - var provTabId = 'provisionTab'; - serviceTabs.add(provTabId, 'Provision', '', false); - loadServiceProvisionPage(provTabId); + success : function(data) { + setUserNodes(data); + setMaxVM(); + getUserNodesDef(); + getNodesCurrentLoad(); + loadManagePage(manageTabId); + } + }); + + var provTabId = 'provisionTab'; + serviceTabs.add(provTabId, 'Provision', '', false); + loadServiceProvisionPage(provTabId); - serviceTabs.select(manageTabId); - - // Get OS image names - if (!$.cookie('srv_imagenames')){ - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'osimage', - msg : '' - }, + serviceTabs.select(manageTabId); + + // Get OS image names + if (!$.cookie('srv_imagenames')){ + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'osimage', + msg : '' + }, - success : function(data) { - setOSImageCookies(data); - } - }); - } - - // Get contents of hosts table - if (!$.cookie('srv_groups')) { - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'hosts', - msg : '' - }, + success : function(data) { + setOSImageCookies(data); + } + }); + } + + // Get contents of hosts table + if (!$.cookie('srv_groups')) { + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'hosts', + msg : '' + }, - success : function(data) { - setGroupCookies(data); - } - }); - } + success : function(data) { + setGroupCookies(data); + } + }); + } } /** * Load the service portal's provision page * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ function loadServiceProvisionPage(tabId) { - // Create info bar - var infoBar = createInfoBar('Select a platform to provision a node on, then click Ok.'); - - // Create provision page - var provPg = $('
                                                                    '); - $('#' + tabId).append(infoBar, provPg); + // Create info bar + var infoBar = createInfoBar('Select a platform to provision a node on, then click Ok.'); + + // Create provision page + var provPg = $('
                                                                    '); + $('#' + tabId).append(infoBar, provPg); - // Create radio buttons for platforms - var hwList = $('
                                                                      Platforms available:
                                                                    '); - var esx = $('
                                                                  • ESX
                                                                  • '); - var kvm = $('
                                                                  • KVM
                                                                  • '); - var zvm = $('
                                                                  • z\/VM
                                                                  • '); - - hwList.append(esx); - hwList.append(kvm); - hwList.append(zvm); - provPg.append(hwList); + // Create radio buttons for platforms + var hwList = $('
                                                                      Platforms available:
                                                                    '); + var esx = $('
                                                                  • ESX
                                                                  • '); + var kvm = $('
                                                                  • KVM
                                                                  • '); + var zvm = $('
                                                                  • z\/VM
                                                                  • '); + + hwList.append(esx); + hwList.append(kvm); + hwList.append(zvm); + provPg.append(hwList); - /** - * Ok - */ - var okBtn = createButton('Ok'); - okBtn.bind('click', function(event) { - var userName = $.cookie('xcat_username'); - var tmp = $.cookie(userName + '_usrnodes'); - - // Get maximun number for nodes from cookie - var nodes = ''; - var maxVM = 0; - if (tmp.length) { - nodes = tmp.split(','); - maxVM = parseInt($.cookie(userName + '_maxvm')); - - // Do not allow user to clone if the maximum number of VMs is reached - if (nodes.length >= maxVM) { - var warn = createWarnBar('You have reached the maximum number of virtual machines allowed (' + maxVM + '). Delete unused virtual machines or contact your system administrator request more virtual machines.'); - warn.prependTo($('#' + tabId)); - return; - } - } - - // Get hardware that was selected - var hw = $(this).parent().find('input[name="hw"]:checked').val(); - var newTabId = hw + 'ProvisionTab'; + /** + * Ok + */ + var okBtn = createButton('Ok'); + okBtn.bind('click', function(event) { + var userName = $.cookie('xcat_username'); + var tmp = $.cookie(userName + '_usrnodes'); + + // Get maximun number for nodes from cookie + var nodes = ''; + var maxVM = 0; + if (tmp.length) { + nodes = tmp.split(','); + maxVM = parseInt($.cookie(userName + '_maxvm')); + + // Do not allow user to clone if the maximum number of VMs is reached + if (nodes.length >= maxVM) { + var warn = createWarnBar('You have reached the maximum number of virtual machines allowed (' + maxVM + '). Delete unused virtual machines or contact your system administrator request more virtual machines.'); + warn.prependTo($('#' + tabId)); + return; + } + } + + // Get hardware that was selected + var hw = $(this).parent().find('input[name="hw"]:checked').val(); + var newTabId = hw + 'ProvisionTab'; - if ($('#' + newTabId).size() > 0){ - serviceTabs.select(newTabId); - } else { - var title = ''; - - // Create an instance of the plugin - var plugin; - switch (hw) { - case "kvm": - plugin = new kvmPlugin(); - title = 'KVM'; - break; - case "esx": - plugin = new esxPlugin(); - title = 'ESX'; - break; - case "blade": - plugin = new bladePlugin(); - title = 'BladeCenter'; - break; - case "hmc": - plugin = new hmcPlugin(); - title = 'System p'; - break; - case "ipmi": - plugin = new ipmiPlugin(); - title = 'iDataPlex'; - break; - case "zvm": - plugin = new zvmPlugin(); - title = 'z/VM'; - - // Get zVM host names - if (!$.cookie('srv_zvm')){ - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webportal', - tgt : '', - args : 'lszvm', - msg : '' - }, + if ($('#' + newTabId).size() > 0){ + serviceTabs.select(newTabId); + } else { + var title = ''; + + // Create an instance of the plugin + var plugin = null; + switch (hw) { + case "kvm": + plugin = new kvmPlugin(); + title = 'KVM'; + break; + case "esx": + plugin = new esxPlugin(); + title = 'ESX'; + break; + case "blade": + plugin = new bladePlugin(); + title = 'BladeCenter'; + break; + case "hmc": + plugin = new hmcPlugin(); + title = 'System p'; + break; + case "ipmi": + plugin = new ipmiPlugin(); + title = 'iDataPlex'; + break; + case "zvm": + plugin = new zvmPlugin(); + title = 'z/VM'; + + // Get zVM host names + if (!$.cookie('srv_zvm')){ + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webportal', + tgt : '', + args : 'lszvm', + msg : '' + }, - success : function(data) { - setzVMCookies(data); - } - }); - } - - break; - } + success : function(data) { + setzVMCookies(data); + } + }); + } + + break; + } - // Select tab - serviceTabs.add(newTabId, title, '', true); - serviceTabs.select(newTabId); - plugin.loadServiceProvisionPage(newTabId); - } - }); - provPg.append(okBtn); + // Select tab + serviceTabs.add(newTabId, title, '', true); + serviceTabs.select(newTabId); + plugin.loadServiceProvisionPage(newTabId); + } + }); + provPg.append(okBtn); } /** * Load manage page * - * @param tabId - * Tab ID where page will reside - * @return Nothing + * @param tabId Tab ID where page will reside */ function loadManagePage(tabId) { - // Create manage form - var manageForm = $('
                                                                    '); + // Create manage form + var manageForm = $('
                                                                    '); - // Append to manage tab - $('#' + tabId).append(manageForm); + // Append to manage tab + $('#' + tabId).append(manageForm); } /** * Get the user nodes definitions */ function getUserNodesDef() { - var userName = $.cookie('xcat_username'); - var userNodes = $.cookie(userName + '_usrnodes'); - if (userNodes) { - // Get nodes definitions - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : userNodes, - msg : '' - }, - - success : loadNodesTable - }); - } else { - // Clear the tab before inserting the table - $('#manageTab').append(createWarnBar('No nodes were found belonging to you!')); - } + var userName = $.cookie('xcat_username'); + var userNodes = $.cookie(userName + '_usrnodes'); + if (userNodes) { + // Get nodes definitions + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : userNodes, + msg : '' + }, + + success : loadNodesTable + }); + } else { + // Clear the tab before inserting the table + $('#manageTab').append(createWarnBar('No nodes were found belonging to you!')); + } } /** * Load user nodes definitions into a table * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function loadNodesTable(data) { - // Clear the tab before inserting the table - $('#manageTab').children().remove(); - - // Nodes datatable ID - var nodesDTId = 'userNodesDT'; - - // Hash of node attributes - var attrs = new Object(); - // Node attributes - var headers = new Object(); - var node, args; - // Create hash of node attributes - for (var i in data.rsp) { - // Get node name - if (data.rsp[i].indexOf('Object name:') > -1) { - var temp = data.rsp[i].split(': '); - node = jQuery.trim(temp[1]); + // Clear the tab before inserting the table + $('#manageTab').children().remove(); + + // Nodes datatable ID + var nodesDTId = 'userNodesDT'; + + // Hash of node attributes + var attrs = new Object(); + // Node attributes + var headers = new Object(); + var node = null, args; + // Create hash of node attributes + for (var i in data.rsp) { + // Get node name + if (data.rsp[i].indexOf('Object name:') > -1) { + var temp = data.rsp[i].split(': '); + node = jQuery.trim(temp[1]); - // Create a hash for the node attributes - attrs[node] = new Object(); - i++; - } + // Create a hash for the node attributes + attrs[node] = new Object(); + i++; + } - // Get key and value - args = data.rsp[i].split('=', 2); - var key = jQuery.trim(args[0]); - var val = jQuery.trim(data.rsp[i].substring(data.rsp[i].indexOf('=') + 1, data.rsp[i].length)); - - // Create a hash table - attrs[node][key] = val; - headers[key] = 1; - } + // Get key and value + args = data.rsp[i].split('=', 2); + var key = jQuery.trim(args[0]); + var val = jQuery.trim(data.rsp[i].substring(data.rsp[i].indexOf('=') + 1, data.rsp[i].length)); + + // Create a hash table + attrs[node][key] = val; + headers[key] = 1; + } - // Sort headers - var sorted = new Array(); - var attrs2hide = new Array('status', 'statustime', 'appstatus', 'appstatustime', 'usercomment'); - var attrs2show = new Array('arch', 'groups', 'hcp', 'hostnames', 'ip', 'os', 'userid', 'mgt'); - for (var key in headers) { - // Show node attributes - if (jQuery.inArray(key, attrs2show) > -1) { - sorted.push(key); - } - } - sorted.sort(); + // Sort headers + var sorted = new Array(); + var attrs2show = new Array('arch', 'groups', 'hcp', 'hostnames', 'ip', 'os', 'userid', 'mgt'); + for (var key in headers) { + // Show node attributes + if (jQuery.inArray(key, attrs2show) > -1) { + sorted.push(key); + } + } + sorted.sort(); - // Add column for check box, node, ping, power, monitor, and comments - sorted.unshift('', - 'node', - 'status', - 'power', - 'monitor', - 'comments'); + // Add column for check box, node, ping, power, monitor, and comments + sorted.unshift('', + 'node', + 'status', + 'power', + 'monitor', + 'comments'); - // Create a datatable - var nodesDT = new DataTable(nodesDTId); - nodesDT.init(sorted); - - // Go through each node - for (var node in attrs) { - // Create a row - var row = new Array(); - - // Create a check box, node link, and get node status - var checkBx = $(''); - var nodeLink = $('' + node + '').bind('click', loadNode); - - // If there is no status attribute for the node, do not try to access hash table - // Else the code will break - var status = ''; - if (attrs[node]['status']) { - status = attrs[node]['status'].replace('sshd', 'ping'); - } - - // Push in checkbox, node, status, monitor, and power - row.push(checkBx, nodeLink, status, '', ''); - - // If the node attributes are known (i.e the group is known) - if (attrs[node]['groups']) { - // Put in comments - var comments = attrs[node]['usercomment']; - // If no comments exists, show 'No comments' and set icon image source - var iconSrc; - if (!comments) { - comments = 'No comments'; - iconSrc = 'images/nodes/ui-icon-no-comment.png'; - } else { - iconSrc = 'images/nodes/ui-icon-comment.png'; - } - - // Create comments icon - var tipID = node + 'Tip'; - var icon = $('').css({ - 'width': '18px', - 'height': '18px' - }); - - // Create tooltip - var tip = createCommentsToolTip(comments); - var col = $('').append(icon); - col.append(tip); - row.push(col); - - // Generate tooltips - icon.tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.8, - relative: true, - delay: 500 - }); - } else { - // Do not put in comments if attributes are not known - row.push(''); - } - - // Go through each header - for (var i = 6; i < sorted.length; i++) { - // Add the node attributes to the row - var key = sorted[i]; - - // Do not put comments and status in twice - if (key != 'usercomment' && key != 'status' && key.indexOf('statustime') < 0) { - var val = attrs[node][key]; - if (val) { - row.push($('' + val + '')); - } else { - row.push(''); - } - } - } + // Create a datatable + var nodesDT = new DataTable(nodesDTId); + nodesDT.init(sorted); + + // Go through each node + for (var node in attrs) { + // Create a row + var row = new Array(); + + // Create a check box, node link, and get node status + var checkBx = $(''); + var nodeLink = $('' + node + '').bind('click', loadNode); + + // If there is no status attribute for the node, do not try to access hash table + // Else the code will break + var status = ''; + if (attrs[node]['status']) { + status = attrs[node]['status'].replace('sshd', 'ping'); + } + + // Push in checkbox, node, status, monitor, and power + row.push(checkBx, nodeLink, status, '', ''); + + // If the node attributes are known (i.e the group is known) + if (attrs[node]['groups']) { + // Put in comments + var comments = attrs[node]['usercomment']; + // If no comments exists, show 'No comments' and set icon image source + var iconSrc; + if (!comments) { + comments = 'No comments'; + iconSrc = 'images/nodes/ui-icon-no-comment.png'; + } else { + iconSrc = 'images/nodes/ui-icon-comment.png'; + } + + // Create comments icon + var tipID = node + 'Tip'; + var icon = $('').css({ + 'width': '18px', + 'height': '18px' + }); + + // Create tooltip + var tip = createCommentsToolTip(comments); + var col = $('').append(icon); + col.append(tip); + row.push(col); + + // Generate tooltips + icon.tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.8, + relative: true, + delay: 500 + }); + } else { + // Do not put in comments if attributes are not known + row.push(''); + } + + // Go through each header + for (var i = 6; i < sorted.length; i++) { + // Add the node attributes to the row + var key = sorted[i]; + + // Do not put comments and status in twice + if (key != 'usercomment' && key != 'status' && key.indexOf('statustime') < 0) { + var val = attrs[node][key]; + if (val) { + row.push($('' + val + '')); + } else { + row.push(''); + } + } + } - // Add the row to the table - nodesDT.add(row); - } - - // Create info bar - var infoBar = createInfoBar('Manage and monitor your virtual machines.'); - $('#manageTab').append(infoBar); - - // Insert action bar and nodes datatable - $('#manageTab').append(nodesDT.object()); - - // Turn table into a datatable - $('#' + nodesDTId).dataTable({ - 'iDisplayLength': 50, - 'bLengthChange': false, - "sScrollX": "100%" - }); - - // Set datatable header class to add color - // $('.datatable thead').attr('class', 'ui-widget-header'); - - // Do not sort ping, power, and comment column - var cols = $('#' + nodesDTId + ' thead tr th').click(function() { - getNodeAttrs(group); - }); - var checkboxCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(0)'); - var pingCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(2)'); - var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); - var monitorCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); - var commentCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(5)'); - checkboxCol.unbind('click'); - pingCol.unbind('click'); - powerCol.unbind('click'); - monitorCol.unbind('click'); - commentCol.unbind('click'); - - // Refresh the node ping, power, and monitor status on-click - var nodes = getNodesShown(nodesDTId); - pingCol.find('span a').click(function() { - refreshNodeStatus(nodes); - }); - powerCol.find('span a').click(function() { - refreshPowerStatus(nodes); - }); - monitorCol.find('span a').click(function() { - refreshGangliaStatus(nodes); - }); - - // Create actions menu - // Power on - var powerOnLnk = $('Power on'); - powerOnLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - powerNode(tgtNodes, 'on'); - } - }); - - // Power off - var powerOffLnk = $('Power off'); - powerOffLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - powerNode(tgtNodes, 'off'); - } - }); - - // Turn monitoring on - var monitorOnLnk = $('Monitor on'); - monitorOnLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - monitorNode(tgtNodes, 'on'); - } - }); + // Add the row to the table + nodesDT.add(row); + } + + // Create info bar + var infoBar = createInfoBar('Manage and monitor your virtual machines.'); + $('#manageTab').append(infoBar); + + // Insert action bar and nodes datatable + $('#manageTab').append(nodesDT.object()); + + // Turn table into a datatable + $('#' + nodesDTId).dataTable({ + 'iDisplayLength': 50, + 'bLengthChange': false, + "sScrollX": "100%" + }); + + // Set datatable header class to add color + // $('.datatable thead').attr('class', 'ui-widget-header'); + + // Do not sort ping, power, and comment column + $('#' + nodesDTId + ' thead tr th').click(function() { + getNodeAttrs(group); + }); + var checkboxCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(0)'); + var pingCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(2)'); + var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); + var monitorCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); + var commentCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(5)'); + checkboxCol.unbind('click'); + pingCol.unbind('click'); + powerCol.unbind('click'); + monitorCol.unbind('click'); + commentCol.unbind('click'); + + // Refresh the node ping, power, and monitor status on-click + var nodes = getNodesShown(nodesDTId); + pingCol.find('span a').click(function() { + refreshNodeStatus(nodes); + }); + powerCol.find('span a').click(function() { + refreshPowerStatus(nodes); + }); + monitorCol.find('span a').click(function() { + refreshGangliaStatus(nodes); + }); + + // Create actions menu + // Power on + var powerOnLnk = $('Power on'); + powerOnLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + powerNode(tgtNodes, 'on'); + } + }); + + // Power off + var powerOffLnk = $('Power off'); + powerOffLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + powerNode(tgtNodes, 'off'); + } + }); + + // Turn monitoring on + var monitorOnLnk = $('Monitor on'); + monitorOnLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + monitorNode(tgtNodes, 'on'); + } + }); - // Turn monitoring off - var monitorOffLnk = $('Monitor off'); - monitorOffLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - monitorNode(tgtNodes, 'off'); - } - }); - - // Clone - var cloneLnk = $('Clone'); - cloneLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - cloneNode(tgtNodes); - } - }); - - // Delete - var deleteLnk = $('Delete'); - deleteLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - deleteNode(tgtNodes); - } - }); + // Turn monitoring off + var monitorOffLnk = $('Monitor off'); + monitorOffLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + monitorNode(tgtNodes, 'off'); + } + }); + + // Clone + var cloneLnk = $('Clone'); + cloneLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + cloneNode(tgtNodes); + } + }); + + // Delete + var deleteLnk = $('Delete'); + deleteLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + deleteNode(tgtNodes); + } + }); - // Unlock - var unlockLnk = $('Unlock'); - unlockLnk.click(function() { - var tgtNodes = getNodesChecked(nodesDTId); - if (tgtNodes) { - unlockNode(tgtNodes); - } - }); - - // Create action bar - var actionBar = $('
                                                                    '); - - // Prepend menu to datatable - var actionsLnk = $('Actions'); - var refreshLnk = $('Refresh'); - refreshLnk.click(function() { - // Get nodes owned by user - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'nodetype', - msg : '' - }, + // Unlock + var unlockLnk = $('Unlock'); + unlockLnk.click(function() { + var tgtNodes = getNodesChecked(nodesDTId); + if (tgtNodes) { + unlockNode(tgtNodes); + } + }); + + // Create action bar + var actionBar = $('
                                                                    '); + + // Prepend menu to datatable + var actionsLnk = $('Actions'); + var refreshLnk = $('Refresh'); + refreshLnk.click(function() { + // Get nodes owned by user + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'nodetype', + msg : '' + }, - success : function(data) { - // Save nodes owned by user - setUserNodes(data); - getNodesCurrentLoad(); - - // Refresh nodes table - var userName = $.cookie('xcat_username'); - var userNodes = $.cookie(userName + '_usrnodes'); - if (userNodes) { - // Get nodes definitions - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'lsdef', - tgt : '', - args : userNodes, - msg : '' - }, - - success : loadNodesTable - }); - } else { - // Clear the tab before inserting the table - $('#manageTab').children().remove(); - $('#manageTab').append(createWarnBar('You are not managing any node. Try to provision a node.')); - } - } - }); - }); - - var actionMenu = createMenu([cloneLnk, deleteLnk, monitorOnLnk, monitorOffLnk, powerOnLnk, powerOffLnk, unlockLnk]); - var menu = createMenu([[actionsLnk, actionMenu], refreshLnk]); - menu.superfish(); - actionBar.append(menu); - - // Set correct theme for action menu - actionMenu.find('li').hover(function() { - setMenu2Theme($(this)); - }, function() { - setMenu2Normal($(this)); - }); - - // Create a division to hold actions menu - var menuDiv = $(''); - $('#' + nodesDTId + '_wrapper').prepend(menuDiv); - menuDiv.append(actionBar); - $('#' + nodesDTId + '_filter').appendTo(menuDiv); - - // Get power and monitor status - var nodes = getNodesShown(nodesDTId); - refreshPowerStatus(nodes); - refreshGangliaStatus(nodes); + success : function(data) { + // Save nodes owned by user + setUserNodes(data); + getNodesCurrentLoad(); + + // Refresh nodes table + var userName = $.cookie('xcat_username'); + var userNodes = $.cookie(userName + '_usrnodes'); + if (userNodes) { + // Get nodes definitions + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'lsdef', + tgt : '', + args : userNodes, + msg : '' + }, + + success : loadNodesTable + }); + } else { + // Clear the tab before inserting the table + $('#manageTab').children().remove(); + $('#manageTab').append(createWarnBar('You are not managing any node. Try to provision a node.')); + } + } + }); + }); + + var actionMenu = createMenu([cloneLnk, deleteLnk, monitorOnLnk, monitorOffLnk, powerOnLnk, powerOffLnk, unlockLnk]); + var menu = createMenu([[actionsLnk, actionMenu], refreshLnk]); + menu.superfish(); + actionBar.append(menu); + + // Set correct theme for action menu + actionMenu.find('li').hover(function() { + setMenu2Theme($(this)); + }, function() { + setMenu2Normal($(this)); + }); + + // Create a division to hold actions menu + var menuDiv = $(''); + $('#' + nodesDTId + '_wrapper').prepend(menuDiv); + menuDiv.append(actionBar); + $('#' + nodesDTId + '_filter').appendTo(menuDiv); + + // Get power and monitor status + var nodes = getNodesShown(nodesDTId); + refreshPowerStatus(nodes); + refreshGangliaStatus(nodes); } /** * Refresh ping status for each node * - * @param nodes - * Nodes to get ping status - * @return Nothing + * @param nodes Nodes to get ping status */ function refreshNodeStatus(nodes) { - // Show ping loader - var nodesDTId = 'userNodesDT'; - var pingCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(2)'); - pingCol.find('img').show(); - - // Get the node ping status - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'nodestat', - tgt : nodes, - args : '-u', - msg : '' - }, + // Show ping loader + var nodesDTId = 'userNodesDT'; + var pingCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(2)'); + pingCol.find('img').show(); + + // Get the node ping status + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'nodestat', + tgt : nodes, + args : '-u', + msg : '' + }, - success : loadNodePing - }); + success : loadNodePing + }); } /** * Load node ping status for each node * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function loadNodePing(data) { - var nodesDTId = 'userNodesDT'; - var datatable = $('#' + nodesDTId).dataTable(); - var rsp = data.rsp; - var args, rowPos, node, status; + var nodesDTId = 'userNodesDT'; + var datatable = $('#' + nodesDTId).dataTable(); + var rsp = data.rsp; + var args, rowPos, node, status; - // Get all nodes within datatable - for (var i in rsp) { - args = rsp[i].split(':'); - - // args[0] = node and args[1] = status - node = jQuery.trim(args[0]); - status = jQuery.trim(args[1]).replace('sshd', 'ping'); - - // Get row containing node - rowPos = findRow(node, '#' + nodesDTId, 1); + // Get all nodes within datatable + for (var i in rsp) { + args = rsp[i].split(':'); + + // args[0] = node and args[1] = status + node = jQuery.trim(args[0]); + status = jQuery.trim(args[1]).replace('sshd', 'ping'); + + // Get row containing node + rowPos = findRow(node, '#' + nodesDTId, 1); - // Update ping status column - datatable.fnUpdate(status, rowPos, 2, false); - } - - // Hide status loader - var pingCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(2)'); - pingCol.find('img').hide(); - adjustColumnSize(nodesDTId); + // Update ping status column + datatable.fnUpdate(status, rowPos, 2, false); + } + + // Hide status loader + var pingCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(2)'); + pingCol.find('img').hide(); + adjustColumnSize(nodesDTId); } /** * Refresh power status for each node * - * @param nodes - * Nodes to get power status - * @return Nothing + * @param nodes Nodes to get power status */ -function refreshPowerStatus(nodes) { - // Show power loader - var nodesDTId = 'userNodesDT'; - var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); - powerCol.find('img').show(); - - // Get power status - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : nodes, - args : 'stat', - msg : '' - }, +function refreshPowerStatus(nodes) { + // Show power loader + var nodesDTId = 'userNodesDT'; + var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); + powerCol.find('img').show(); + + // Get power status + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : nodes, + args : 'stat', + msg : '' + }, - success : loadPowerStatus - }); + success : loadPowerStatus + }); } /** * Load power status for each node * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function loadPowerStatus(data) { - var nodesDTId = 'userNodesDT'; - var datatable = $('#' + nodesDTId).dataTable(); - var power = data.rsp; - var rowPos, node, status, args; + var nodesDTId = 'userNodesDT'; + var datatable = $('#' + nodesDTId).dataTable(); + var power = data.rsp; + var rowPos, node, status, args; - for (var i in power) { - // power[0] = nodeName and power[1] = state - args = power[i].split(':'); - node = jQuery.trim(args[0]); - status = jQuery.trim(args[1]); - - // Get the row containing the node - rowPos = findRow(node, '#' + nodesDTId, 1); + for (var i in power) { + // power[0] = nodeName and power[1] = state + args = power[i].split(':'); + node = jQuery.trim(args[0]); + status = jQuery.trim(args[1]); + + // Get the row containing the node + rowPos = findRow(node, '#' + nodesDTId, 1); - // Update the power status column - datatable.fnUpdate(status, rowPos, 3, false); - } - - // Hide power loader - var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); - powerCol.find('img').hide(); - adjustColumnSize(nodesDTId); + // Update the power status column + datatable.fnUpdate(status, rowPos, 3, false); + } + + // Hide power loader + var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); + powerCol.find('img').hide(); + adjustColumnSize(nodesDTId); } /** * Refresh the status of Ganglia for each node * - * @param nodes - * Nodes to get Ganglia status - * @return Nothing + * @param nodes Nodes to get Ganglia status */ function refreshGangliaStatus(nodes) { - // Show ganglia loader - var nodesDTId = 'userNodesDT'; - var gangliaCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); - gangliaCol.find('img').show(); - - // Get the status of Ganglia - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliastatus;' + nodes, - msg : '' - }, + // Show ganglia loader + var nodesDTId = 'userNodesDT'; + var gangliaCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); + gangliaCol.find('img').show(); + + // Get the status of Ganglia + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliastatus;' + nodes, + msg : '' + }, - success : loadGangliaStatus - }); + success : loadGangliaStatus + }); } /** * Load the status of Ganglia for a given group * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function loadGangliaStatus(data) { - // Get datatable - var nodesDTId = 'userNodesDT'; - var datatable = $('#' + nodesDTId).dataTable(); - var ganglia = data.rsp; - var rowNum, node, status; + // Get datatable + var nodesDTId = 'userNodesDT'; + var datatable = $('#' + nodesDTId).dataTable(); + var ganglia = data.rsp; + var rowNum, node, status; - for ( var i in ganglia) { - // ganglia[0] = nodeName and ganglia[1] = state - node = jQuery.trim(ganglia[i][0]); - status = jQuery.trim(ganglia[i][1]); + for ( var i in ganglia) { + // ganglia[0] = nodeName and ganglia[1] = state + node = jQuery.trim(ganglia[i][0]); + status = jQuery.trim(ganglia[i][1]); - if (node) { - // Get the row containing the node - rowNum = findRow(node, '#' + nodesDTId, 1); + if (node) { + // Get the row containing the node + rowNum = findRow(node, '#' + nodesDTId, 1); - // Update the power status column - datatable.fnUpdate(status, rowNum, 4); - } - } + // Update the power status column + datatable.fnUpdate(status, rowNum, 4); + } + } - // Hide Ganglia loader - var gangliaCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); - gangliaCol.find('img').hide(); - adjustColumnSize(nodesDTId); + // Hide Ganglia loader + var gangliaCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); + gangliaCol.find('img').hide(); + adjustColumnSize(nodesDTId); } /** * Load inventory for given node * - * @param e - * Windows event - * @return Nothing + * @param e Windows event */ function loadNode(e) { - if (!e) { - e = window.event; - } - - // Get node that was clicked - var node = (e.target) ? e.target.id : e.srcElement.id; + if (!e) { + e = window.event; + } + + // Get node that was clicked + var node = (e.target) ? e.target.id : e.srcElement.id; - // Create a new tab to show inventory - var tabId = node + '_inventory'; + // Create a new tab to show inventory + var tabId = node + '_inventory'; - if(!$('#' + tabId).length) { - // Add new tab, only if one does not exist - var loader = createLoader(node + 'Loader'); - loader = $('
                                                                    ').append(loader); - serviceTabs.add(tabId, node, loader, true); - - // Get node inventory - var msg = 'out=' + tabId + ',node=' + node; - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'rinv', - tgt : node, - args : 'all', - msg : msg - }, + if(!$('#' + tabId).length) { + // Add new tab, only if one does not exist + var loader = createLoader(node + 'Loader'); + loader = $('
                                                                    ').append(loader); + serviceTabs.add(tabId, node, loader, true); + + // Get node inventory + var msg = 'out=' + tabId + ',node=' + node; + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'rinv', + tgt : node, + args : 'all', + msg : msg + }, - success : function(data) { - var args = data.msg.split(','); + success : function(data) { + var args = data.msg.split(','); - // Get node - var node = args[1].replace('node=', ''); - - // Get the management plugin - var mgt = getNodeAttr(node, 'mgt'); - - // Create an instance of the plugin - var plugin; - switch (mgt) { - case "blade": - plugin = new bladePlugin(); - break; - case "hmc": - plugin = new hmcPlugin(); - break; - case "ipmi": - plugin = new ipmiPlugin(); - break; - case "zvm": - plugin = new zvmPlugin(); - break; - } + // Get node + var node = args[1].replace('node=', ''); + + // Get the management plugin + var mgt = getNodeAttr(node, 'mgt'); + + // Create an instance of the plugin + var plugin; + switch (mgt) { + case "blade": + plugin = new bladePlugin(); + break; + case "hmc": + plugin = new hmcPlugin(); + break; + case "ipmi": + plugin = new ipmiPlugin(); + break; + case "zvm": + plugin = new zvmPlugin(); + break; + } - // Select tab - plugin.loadServiceInventory(data); - } - }); - } + // Select tab + plugin.loadServiceInventory(data); + } + }); + } - // Select new tab - serviceTabs.select(tabId); + // Select new tab + serviceTabs.select(tabId); } /** - * Set a cookie for disk pool names + * Set a cookie for group names * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function setGroupCookies(data) { - if (data.rsp) { - var groups = new Array(); - - // Index 0 is the table header - var cols, name, ip, hostname, desc, comments, tmp; - for (var i = 1; i < data.rsp.length; i++) { - // Split into columns: - // node, ip, hostnames, otherinterfaces, comments, disable - cols = data.rsp[i].split(','); - name = cols[0].replace(new RegExp('"', 'g'), ''); - ip = cols[1].replace(new RegExp('"', 'g'), ''); - hostname = cols[2].replace(new RegExp('"', 'g'), ''); - - // It should return: "description: All machines; network: 10.1.100.0/24;" - comments = cols[4].replace(new RegExp('"', 'g'), ''); - tmp = comments.split(';'); - for (var j = 0; j < tmp.length; j++) { - if (tmp[j].indexOf('description:') > -1) { - desc = tmp[j].replace('description:', ''); - desc = jQuery.trim(desc); - } - } - - groups.push(name + ':' + ip + ':' + hostname + ':' + desc); - } - - // Set cookie to expire in 60 minutes - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie('srv_groups', groups, { expires: exDate }); - } + if (data.rsp) { + var groups = new Array(); + + // Index 0 is the table header + var cols, name, ip, hostname, desc, selectable, comments, tmp; + for (var i = 1; i < data.rsp.length; i++) { + // Set default description and selectable + selectable = "no"; + desc = "No description"; + + // Split into columns: + // node, ip, hostnames, otherinterfaces, comments, disable + cols = data.rsp[i].split(','); + name = cols[0].replace(new RegExp('"', 'g'), ''); + ip = cols[1].replace(new RegExp('"', 'g'), ''); + hostname = cols[2].replace(new RegExp('"', 'g'), ''); + + // It should return: "description: All machines; network: 10.1.100.0/24;" + comments = cols[4].replace(new RegExp('"', 'g'), ''); + tmp = comments.split('|'); + for (var j = 0; j < tmp.length; j++) { + // Save description + if (tmp[j].indexOf('description:') > -1) { + desc = tmp[j].replace('description:', ''); + desc = jQuery.trim(desc); + } + + // Is the group selectable? + if (tmp[j].indexOf('selectable:') > -1) { + selectable = tmp[j].replace('selectable:', ''); + selectable = jQuery.trim(selectable); + } + } + + // Save groups that are selectable + if (selectable == "yes") + groups.push(name + ':' + ip + ':' + hostname + ':' + desc); + } + + // Set cookie to expire in 60 minutes + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie('srv_groups', groups, { expires: exDate }); + } } /** * Set a cookie for the OS images * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function setOSImageCookies(data) { - // Get response - var rsp = data.rsp; + // Get response + var rsp = data.rsp; - var imageNames = new Array; - var profilesHash = new Object(); - var osVersHash = new Object(); - var osArchsHash = new Object(); - var imagePos = 0; - var profilePos = 0; - var osversPos = 0; - var osarchPos = 0; - var provMethodPos = 0; - var comments = 0; - // Get the column value - var colNameArray = rsp[0].substr(1).split(','); - for (var i in colNameArray){ - switch (colNameArray[i]){ - case 'imagename': { - imagePos = i; - } - break; - - case 'profile':{ - profilePos = i; - } - break; - - case 'osvers':{ - osversPos = i; - } - break; - - case 'osarch':{ - osarchPos = i; - } - break; - - case 'comments':{ - comments = i; - } - break; - - case 'provmethod':{ - provMethodPos = i; - } - break; - - default : - break; - } - } - - // Go through each index - for (var i = 1; i < rsp.length; i++) { - // Get image name - var cols = rsp[i].split(','); - var osImage = cols[imagePos].replace(new RegExp('"', 'g'), ''); - var profile = cols[profilePos].replace(new RegExp('"', 'g'), ''); - var provMethod = cols[provMethodPos].replace(new RegExp('"', 'g'), ''); - var osVer = cols[osversPos].replace(new RegExp('"', 'g'), ''); - var osArch = cols[osarchPos].replace(new RegExp('"', 'g'), ''); - var osComments = cols[comments].replace(new RegExp('"', 'g'), ''); - - // Only save install boot - if (provMethod.indexOf('install') > -1) { - if (!osComments) - osComments = 'No descritption'; - imageNames.push(osImage + ':' + osComments); - profilesHash[profile] = 1; - osVersHash[osVer] = 1; - osArchsHash[osArch] = 1; - } - - - } + var imageNames = new Array(); + var profilesHash = new Object(); + var osVersHash = new Object(); + var osArchsHash = new Object(); + var imagePos = 0; + var profilePos = 0; + var osversPos = 0; + var osarchPos = 0; + var provMethodPos = 0; + var comments = 0; + var desc, selectable, tmp; + // Get column index for each attribute + var colNameArray = rsp[0].substr(1).split(','); + for (var i in colNameArray){ + switch (colNameArray[i]){ + case 'imagename': { + imagePos = i; + } + break; + + case 'profile':{ + profilePos = i; + } + break; + + case 'osvers':{ + osversPos = i; + } + break; + + case 'osarch':{ + osarchPos = i; + } + break; + + case 'comments':{ + comments = i; + } + break; + + case 'provmethod':{ + provMethodPos = i; + } + break; + + default : + break; + } + } + + // Go through each index + for (var i = 1; i < rsp.length; i++) { + // Get image name + var cols = rsp[i].split(','); + var osImage = cols[imagePos].replace(new RegExp('"', 'g'), ''); + var profile = cols[profilePos].replace(new RegExp('"', 'g'), ''); + var provMethod = cols[provMethodPos].replace(new RegExp('"', 'g'), ''); + var osVer = cols[osversPos].replace(new RegExp('"', 'g'), ''); + var osArch = cols[osarchPos].replace(new RegExp('"', 'g'), ''); + var osComments = cols[comments].replace(new RegExp('"', 'g'), ''); + + // Only save install boot + if (provMethod.indexOf('install') > -1) { + if (!osComments) { + osComments = "No descritption"; + imageNames.push(osImage + ':' + osComments); + } else { + // Set default description and selectable + selectable = "no"; + desc = "No description"; + + tmp = osComments.split('|'); + for (var j = 0; j < tmp.length; j++) { + // Save description + if (tmp[j].indexOf('description:') > -1) { + desc = tmp[j].replace('description:', ''); + desc = jQuery.trim(desc); + } + + // Is the image selectable? + if (tmp[j].indexOf('selectable:') > -1) { + selectable = tmp[j].replace('selectable:', ''); + selectable = jQuery.trim(selectable); + } + } + + // Save images that are selectable + if (selectable == "yes") + imageNames.push(osImage + ':' + desc); + } + + profilesHash[profile] = 1; + osVersHash[osVer] = 1; + osArchsHash[osArch] = 1; + } + } - // Save image names in a cookie - $.cookie('srv_imagenames', imageNames); + // Save image names in a cookie + $.cookie('srv_imagenames', imageNames); - // Save profiles in a cookie - var tmp = new Array; - for (var key in profilesHash) { - tmp.push(key); - } - $.cookie('srv_profiles', tmp); + // Save profiles in a cookie + var tmp = new Array; + for (var key in profilesHash) { + tmp.push(key); + } + $.cookie('srv_profiles', tmp); - // Save OS versions in a cookie - tmp = new Array; - for (var key in osVersHash) { - tmp.push(key); - } - $.cookie('srv_osvers', tmp); + // Save OS versions in a cookie + tmp = new Array; + for (var key in osVersHash) { + tmp.push(key); + } + $.cookie('srv_osvers', tmp); - // Save OS architectures in a cookie - tmp = new Array; - for (var key in osArchsHash) { - tmp.push(key); - } - $.cookie('srv_osarchs', tmp); + // Save OS architectures in a cookie + tmp = new Array; + for (var key in osArchsHash) { + tmp.push(key); + } + $.cookie('srv_osarchs', tmp); } @@ -1050,58 +1061,53 @@ function setOSImageCookies(data) { /** * Set a cookie for user nodes * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function setUserNodes(data) { - if (data.rsp) { - // Get user name that is logged in - var userName = $.cookie('xcat_username'); - var usrNodes = new Array(); - - // Ignore first columns because it is the header - for ( var i = 1; i < data.rsp.length; i++) { - // Go through each column - // where column names are: node, os, arch, profile, provmethod, supportedarchs, nodetype, comments, disable - var cols = data.rsp[i].split(','); - var node = cols[0].replace(new RegExp('"', 'g'), ''); - var owner = cols[7].replace(new RegExp('"', 'g'), ''); - owner = owner.replace('owner:', ''); - - if (owner == userName) { - usrNodes.push(node); - } - } // End of for - - // Set cookie to expire in 240 minutes - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie(userName + '_usrnodes', usrNodes, { expires: exDate }); - } // End of if + if (data.rsp) { + // Get user name that is logged in + var userName = $.cookie('xcat_username'); + var usrNodes = new Array(); + + // Ignore first columns because it is the header + for ( var i = 1; i < data.rsp.length; i++) { + // Go through each column + // where column names are: node, os, arch, profile, provmethod, supportedarchs, nodetype, comments, disable + var cols = data.rsp[i].split(','); + var node = cols[0].replace(new RegExp('"', 'g'), ''); + var owner = cols[7].replace(new RegExp('"', 'g'), ''); + owner = owner.replace('owner:', ''); + + if (owner == userName) { + usrNodes.push(node); + } + } // End of for + + // Set cookie to expire in 240 minutes + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie(userName + '_usrnodes', usrNodes, { expires: exDate }); + } // End of if } /** * Power on a given node * - * @param tgtNodes - * Node to power on or off - * @param power2 - * Power node to given state - * @return Nothing + * @param tgtNodes Node to power on or off + * @param power2 Power node to given state */ function powerNode(tgtNodes, power2) { - // Show power loader - var nodesDTId = 'userNodesDT'; - var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); - powerCol.find('img').show(); - - var nodes = tgtNodes.split(','); - for (var n in nodes) { - // Get hardware that was selected - var hw = getUserNodeAttr(nodes[n], 'mgt'); - - // Change to power softoff (to gracefully shutdown) + // Show power loader + var nodesDTId = 'userNodesDT'; + var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); + powerCol.find('img').show(); + + var nodes = tgtNodes.split(','); + for (var n in nodes) { + // Get hardware that was selected + var hw = getUserNodeAttr(nodes[n], 'mgt'); + + // Change to power softoff (to gracefully shutdown) switch (hw) { case "blade": break; @@ -1110,205 +1116,198 @@ function powerNode(tgtNodes, power2) { case "ipmi": break; case "zvm": - if (power2 == 'off') { - power2 = 'softoff'; - } - + if (power2 == 'off') { + power2 = 'softoff'; + } + break; } - } - - $.ajax({ - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'rpower', - tgt : tgtNodes, - args : power2, - msg : tgtNodes - }, + } + + $.ajax({ + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'rpower', + tgt : tgtNodes, + args : power2, + msg : tgtNodes + }, - success : updatePowerStatus - }); + success : updatePowerStatus + }); } /** * Update power status of a node in the datatable * - * @param data - * Data from HTTP request - * @return Nothing + * @param data Data from HTTP request */ function updatePowerStatus(data) { - // Get datatable - var nodesDTId = 'userNodesDT'; - var dTable = $('#' + nodesDTId).dataTable(); + // Get datatable + var nodesDTId = 'userNodesDT'; + var dTable = $('#' + nodesDTId).dataTable(); - // Get xCAT response - var rsp = data.rsp; - // Loop through each line - var node, status, rowPos, strPos; - for (var i in rsp) { - // Get node name - node = rsp[i].split(":")[0]; + // Get xCAT response + var rsp = data.rsp; + // Loop through each line + var node, status, rowPos, strPos; + for (var i in rsp) { + // Get node name + node = rsp[i].split(":")[0]; - // If there is no error - if (rsp[i].indexOf("Error") < 0 || rsp[i].indexOf("Failed") < 0) { - // Get the row containing the node link - rowPos = findRow(node, '#' + nodesDTId, 1); + // If there is no error + if (rsp[i].indexOf("Error") < 0 || rsp[i].indexOf("Failed") < 0) { + // Get the row containing the node link + rowPos = findRow(node, '#' + nodesDTId, 1); - // If it was power on, then the data return would contain "Starting" - strPos = rsp[i].indexOf("Starting"); - if (strPos > -1) { - status = 'on'; - } else { - status = 'off'; - } + // If it was power on, then the data return would contain "Starting" + strPos = rsp[i].indexOf("Starting"); + if (strPos > -1) { + status = 'on'; + } else { + status = 'off'; + } - // Update the power status column - dTable.fnUpdate(status, rowPos, 3, false); - } else { - // Power on/off failed - alert(rsp[i]); - } - } - - var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); - powerCol.find('img').hide(); - adjustColumnSize(nodesDTId); + // Update the power status column + dTable.fnUpdate(status, rowPos, 3, false); + } else { + // Power on/off failed + alert(rsp[i]); + } + } + + var powerCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(3)'); + powerCol.find('img').hide(); + adjustColumnSize(nodesDTId); } /** * Turn on monitoring for a given node * - * @param node - * Node to monitor on or off - * @param monitor - * Monitor state, on or off - * @return Nothing + * @param node Node to monitor on or off + * @param monitor Monitor state, on or off */ function monitorNode(node, monitor) { - // Show ganglia loader - var nodesDTId = 'userNodesDT'; - var gangliaCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); - gangliaCol.find('img').show(); - - if (monitor == 'on') { - if (node) { - // Check if ganglia RPMs are installed - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliacheck;' + node, - msg : node // Node range will be passed along in data.msg - }, + // Show ganglia loader + var nodesDTId = 'userNodesDT'; + var gangliaCol = $('#' + nodesDTId + '_wrapper .dataTables_scrollHead .datatable thead tr th:eq(4)'); + gangliaCol.find('img').show(); + + if (monitor == 'on') { + if (node) { + // Check if ganglia RPMs are installed + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliacheck;' + node, + msg : node // Node range will be passed along in data.msg + }, - /** - * Start ganglia on a given node range - * - * @param data - * Data returned from HTTP request - * @return Nothing - */ - success : function(data) { - // Get response - var out = data.rsp[0].split(/\n/); + /** + * Start ganglia on a given node range + * + * @param data + * Data returned from HTTP request + * @return Nothing + */ + success : function(data) { + // Get response + var out = data.rsp[0].split(/\n/); - // Go through each line - var warn = false; - var warningMsg = ''; - for (var i in out) { - // If an RPM is not installed - if (out[i].indexOf('not installed') > -1) { - warn = true; - - if (warningMsg) { - warningMsg += '
                                                                    ' + out[i]; - } else { - warningMsg = out[i]; - } - } - } - - // If there are warnings - if (warn) { - // Create warning bar - var warningBar = createWarnBar(warningMsg); - warningBar.css('margin-bottom', '10px'); - warningBar.prependTo($('#nodesTab')); - } else { - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'gangliastart;' + data.msg, - msg : data.msg - }, + // Go through each line + var warn = false; + var warningMsg = ''; + for (var i in out) { + // If an RPM is not installed + if (out[i].indexOf('not installed') > -1) { + warn = true; + + if (warningMsg) { + warningMsg += '
                                                                    ' + out[i]; + } else { + warningMsg = out[i]; + } + } + } + + // If there are warnings + if (warn) { + // Create warning bar + var warningBar = createWarnBar(warningMsg); + warningBar.css('margin-bottom', '10px'); + warningBar.prependTo($('#nodesTab')); + } else { + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'gangliastart;' + data.msg, + msg : data.msg + }, - success : function(data) { - // Remove any warnings - $('#nodesTab').find('.ui-state-error').remove(); - refreshGangliaStatus(data.msg); - } - }); - } // End of if (warn) - } // End of function(data) - }); - } - } else { - var args; - if (node) { - args = 'gangliastop;' + node; - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : args, - msg : node - }, + success : function(data) { + // Remove any warnings + $('#nodesTab').find('.ui-state-error').remove(); + refreshGangliaStatus(data.msg); + } + }); + } // End of if (warn) + } // End of function(data) + }); + } + } else { + var args; + if (node) { + args = 'gangliastop;' + node; + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : args, + msg : node + }, - success : function(data) { - refreshGangliaStatus(data.msg); - } - }); - } - } + success : function(data) { + refreshGangliaStatus(data.msg); + } + }); + } + } } /** * Open a dialog to clone node * - * @param tgtNodes - * Nodes to clone - * @return Nothing + * @param tgtNodes Nodes to clone */ -function cloneNode(tgtNodes) { - var userName = $.cookie('xcat_username'); - var nodes = tgtNodes.split(','); - var tmp = $.cookie(userName + '_usrnodes'); - var usrNodes = tmp.split(','); - - var maxVM = parseInt($.cookie(userName + '_maxvm')); - - // Do not allow user to clone if the maximum number of VMs is reached - if (usrNodes.length >= maxVM) { - var warn = createWarnBar('You have reached the maximum number of virtual machines allowed (' + maxVM + '). Delete un-used virtual machines or contact your system administrator request more virtual machines.'); - warn.prependTo($('#manageTab')); - return; - } - - for (var n in nodes) { - // Get hardware that was selected - var hw = getUserNodeAttr(nodes[n], 'mgt'); - - // Create an instance of the plugin +function cloneNode(tgtNodes) { + var userName = $.cookie('xcat_username'); + var nodes = tgtNodes.split(','); + var tmp = $.cookie(userName + '_usrnodes'); + var usrNodes = tmp.split(','); + + var maxVM = parseInt($.cookie(userName + '_maxvm')); + + // Do not allow user to clone if the maximum number of VMs is reached + if (usrNodes.length >= maxVM) { + var warn = createWarnBar('You have reached the maximum number of virtual machines allowed (' + maxVM + '). Delete un-used virtual machines or contact your system administrator request more virtual machines.'); + warn.prependTo($('#manageTab')); + return; + } + + for (var n in nodes) { + // Get hardware that was selected + var hw = getUserNodeAttr(nodes[n], 'mgt'); + + // Create an instance of the plugin var plugin; switch (hw) { case "blade": @@ -1321,280 +1320,282 @@ function cloneNode(tgtNodes) { plugin = new ipmiPlugin(); break; case "zvm": - plugin = new zvmPlugin(); + plugin = new zvmPlugin(); break; } // Clone node - plugin.serviceClone(nodes[n]); - } + plugin.serviceClone(nodes[n]); + } } - + /** * Open a dialog to delete node * - * @param tgtNodes - * Nodes to delete - * @return Nothing + * @param tgtNodes Nodes to delete */ function deleteNode(tgtNodes) { - var nodes = tgtNodes.split(','); - - // Loop through each node and create target nodes string - var tgtNodesStr = ''; - for (var i in nodes) { - if (i == 0 && i == nodes.length - 1) { - // If it is the 1st and only node - tgtNodesStr += nodes[i]; - } else if (i == 0 && i != nodes.length - 1) { - // If it is the 1st node of many nodes, append a comma to the string - tgtNodesStr += nodes[i] + ', '; - } else { - if (i == nodes.length - 1) { - // If it is the last node, append nothing to the string - tgtNodesStr += nodes[i]; - } else { - // Append a comma to the string - tgtNodesStr += nodes[i] + ', '; - } - } - } - - // Confirm delete - var confirmMsg = $('

                                                                    Are you sure you want to delete ' + tgtNodesStr + '?

                                                                    ').css({ - 'display': 'inline', - 'margin': '5px', - 'vertical-align': 'middle', - 'word-wrap': 'break-word' - }); - - var style = { - 'display': 'inline-block', - 'margin': '5px', - 'vertical-align': 'middle' - }; + var nodes = tgtNodes.split(','); + + // Loop through each node and create target nodes string + var tgtNodesStr = ''; + for (var i in nodes) { + if (i == 0 && i == nodes.length - 1) { + // If it is the 1st and only node + tgtNodesStr += nodes[i]; + } else if (i == 0 && i != nodes.length - 1) { + // If it is the 1st node of many nodes, append a comma to the string + tgtNodesStr += nodes[i] + ', '; + } else { + if (i == nodes.length - 1) { + // If it is the last node, append nothing to the string + tgtNodesStr += nodes[i]; + } else { + // Append a comma to the string + tgtNodesStr += nodes[i] + ', '; + } + } + } + + // Confirm delete + var confirmMsg = $('

                                                                    Are you sure you want to delete ' + tgtNodesStr + '?

                                                                    ').css({ + 'display': 'inline', + 'margin': '5px', + 'vertical-align': 'middle', + 'word-wrap': 'break-word' + }); + + var style = { + 'display': 'inline-block', + 'margin': '5px', + 'vertical-align': 'middle' + }; - var dialog = $('
                                                                    '); - var icon = $('').css(style); - dialog.append(icon); - dialog.append(confirmMsg); - - // Open dialog - dialog.dialog({ - title: "Confirm", - modal: true, - width: 400, - buttons: { - "Yes": function(){ - // Create status bar and append to tab - var instance = 0; - var statBarId = 'deleteStat' + instance; - while ($('#' + statBarId).length) { - // If one already exists, generate another one - instance = instance + 1; - statBarId = 'deleteStat' + instance; - } - - var statBar = createStatusBar(statBarId); - var loader = createLoader(''); - statBar.find('div').append(loader); - statBar.prependTo($('#manageTab')); - - // Delete the virtual server - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'rmvm', - tgt : tgtNodes, - args : '', - msg : 'out=' + statBarId + ';cmd=rmvm;tgt=' + tgtNodes - }, + var dialog = $('
                                                                    '); + var icon = $('').css(style); + dialog.append(icon); + dialog.append(confirmMsg); + + // Open dialog + dialog.dialog({ + title: "Confirm", + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Yes": function(){ + // Create status bar and append to tab + var instance = 0; + var statBarId = 'deleteStat' + instance; + while ($('#' + statBarId).length) { + // If one already exists, generate another one + instance = instance + 1; + statBarId = 'deleteStat' + instance; + } + + var statBar = createStatusBar(statBarId); + var loader = createLoader(''); + statBar.find('div').append(loader); + statBar.prependTo($('#manageTab')); + + // Delete the virtual server + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'rmvm', + tgt : tgtNodes, + args : '', + msg : 'out=' + statBarId + ';cmd=rmvm;tgt=' + tgtNodes + }, - success : function(data) { - var args = data.msg.split(';'); - var statBarId = args[0].replace('out=', ''); - var tgts = args[2].replace('tgt=', '').split(','); - - // Get data table - var nodesDTId = 'userNodesDT'; - var dTable = $('#' + nodesDTId).dataTable(); - var failed = false; + success : function(data) { + var args = data.msg.split(';'); + var statBarId = args[0].replace('out=', ''); + var tgts = args[2].replace('tgt=', '').split(','); + + // Get data table + var nodesDTId = 'userNodesDT'; + var dTable = $('#' + nodesDTId).dataTable(); + var failed = false; - // Create an info box to show output - var output = writeRsp(data.rsp, ''); - output.css('margin', '0px'); - // Remove loader and append output - $('#' + statBarId + ' img').remove(); - $('#' + statBarId + ' div').append(output); - - // If there was an error, do not continue - if (output.html().indexOf('Error') > -1) { - failed = true; - } + // Create an info box to show output + var output = writeRsp(data.rsp, ''); + output.css('margin', '0px'); + // Remove loader and append output + $('#' + statBarId + ' img').remove(); + $('#' + statBarId + ' div').append(output); + + // If there was an error, do not continue + if (output.html().indexOf('Error') > -1) { + failed = true; + } - // Update data table - var rowPos; - for (var i in tgts) { - if (!failed) { - // Get row containing the node link and delete it - rowPos = findRow(tgts[i], '#' + nodesDTId, 1); - dTable.fnDeleteRow(rowPos); - } - } - - // Refresh nodes owned by user - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'tabdump', - tgt : '', - args : 'nodetype', - msg : '' - }, + // Update data table + var rowPos; + for (var i in tgts) { + if (!failed) { + // Get row containing the node link and delete it + rowPos = findRow(tgts[i], '#' + nodesDTId, 1); + dTable.fnDeleteRow(rowPos); + } + } + + // Refresh nodes owned by user + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'tabdump', + tgt : '', + args : 'nodetype', + msg : '' + }, - success : function(data) { - setUserNodes(data); - } - }); - } - }); - - $(this).dialog("close"); - }, - "No": function() { - $(this).dialog("close"); - } - } - }); + success : function(data) { + setUserNodes(data); + } + }); + } + }); + + $(this).dialog("close"); + }, + "No": function() { + $(this).dialog("close"); + } + } + }); } /** * Unlock a node by setting the ssh keys * - * @param tgtNodes - * Nodes to unlock - * @return Nothing + * @param tgtNodes Nodes to unlock */ function unlockNode(tgtNodes) { - var nodes = tgtNodes.split(','); - - // Loop through each node and create target nodes string - var tgtNodesStr = ''; - for (var i in nodes) { - if (i == 0 && i == nodes.length - 1) { - // If it is the 1st and only node - tgtNodesStr += nodes[i]; - } else if (i == 0 && i != nodes.length - 1) { - // If it is the 1st node of many nodes, append a comma to the string - tgtNodesStr += nodes[i] + ', '; - } else { - if (i == nodes.length - 1) { - // If it is the last node, append nothing to the string - tgtNodesStr += nodes[i]; - } else { - // Append a comma to the string - tgtNodesStr += nodes[i] + ', '; - } - } - } + var nodes = tgtNodes.split(','); + + // Loop through each node and create target nodes string + var tgtNodesStr = ''; + for (var i in nodes) { + if (i == 0 && i == nodes.length - 1) { + // If it is the 1st and only node + tgtNodesStr += nodes[i]; + } else if (i == 0 && i != nodes.length - 1) { + // If it is the 1st node of many nodes, append a comma to the string + tgtNodesStr += nodes[i] + ', '; + } else { + if (i == nodes.length - 1) { + // If it is the last node, append nothing to the string + tgtNodesStr += nodes[i]; + } else { + // Append a comma to the string + tgtNodesStr += nodes[i] + ', '; + } + } + } - var dialog = $('
                                                                    '); - var infoBar = createInfoBar('Give the root password for this node range to setup its SSH keys.'); - dialog.append(infoBar); - - var unlockForm = $('
                                                                    ').css('margin', '5px'); - unlockForm.append('
                                                                    '); - unlockForm.append('
                                                                    '); - dialog.append(unlockForm); - - dialog.find('div input').css('margin', '5px'); - - // Generate tooltips - unlockForm.find('div input[title]').tooltip({ - position: "center right", - offset: [-2, 10], - effect: "fade", - opacity: 0.7, - predelay: 800, - events : { - def : "mouseover,mouseout", - input : "mouseover,mouseout", - widget : "focus mouseover,blur mouseout", - tooltip : "mouseover,mouseout" - } - }); - - // Open dialog - dialog.dialog({ - title: "Confirm", - modal: true, - width: 450, - buttons: { - "Ok": function(){ - // Create status bar and append to tab - var instance = 0; - var statBarId = 'unlockStat' + instance; - while ($('#' + statBarId).length) { - // If one already exists, generate another one - instance = instance + 1; - statBarId = 'unlockStat' + instance; - } - - var statBar = createStatusBar(statBarId); - var loader = createLoader(''); - statBar.find('div').append(loader); - statBar.prependTo($('#manageTab')); - - // If a password is given - var password = unlockForm.find('input[name=password]:eq(0)'); - if (password.val()) { - // Setup SSH keys - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'unlock;' + tgtNodes + ';' + password.val(), - msg : 'out=' + statBarId + ';cmd=unlock;tgt=' + tgtNodes - }, - - success : function(data) { - // Create an info box to show output - var output = writeRsp(data.rsp, ''); - output.css('margin', '0px'); - // Remove loader and append output - $('#' + statBarId + ' img').remove(); - $('#' + statBarId + ' div').append(output); - } - }); - - $(this).dialog("close"); - } - }, - "Cancel": function() { - $(this).dialog("close"); - } - } - }); + var dialog = $('
                                                                    '); + var infoBar = createInfoBar('Give the root password for this node range to setup its SSH keys.'); + dialog.append(infoBar); + + var unlockForm = $('
                                                                    ').css('margin', '5px'); + unlockForm.append('
                                                                    '); + unlockForm.append('
                                                                    '); + dialog.append(unlockForm); + + dialog.find('div input').css('margin', '5px'); + + // Generate tooltips + unlockForm.find('div input[title]').tooltip({ + position: "center right", + offset: [-2, 10], + effect: "fade", + opacity: 0.7, + predelay: 800, + events : { + def : "mouseover,mouseout", + input : "mouseover,mouseout", + widget : "focus mouseover,blur mouseout", + tooltip : "mouseover,mouseout" + } + }); + + // Open dialog + dialog.dialog({ + title: "Confirm", + modal: true, + close: function(){ + $(this).remove(); + }, + width: 450, + buttons: { + "Ok": function(){ + // Create status bar and append to tab + var instance = 0; + var statBarId = 'unlockStat' + instance; + while ($('#' + statBarId).length) { + // If one already exists, generate another one + instance = instance + 1; + statBarId = 'unlockStat' + instance; + } + + var statBar = createStatusBar(statBarId); + var loader = createLoader(''); + statBar.find('div').append(loader); + statBar.prependTo($('#manageTab')); + + // If a password is given + var password = unlockForm.find('input[name=password]:eq(0)'); + if (password.val()) { + // Setup SSH keys + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'unlock;' + tgtNodes + ';' + password.val(), + msg : 'out=' + statBarId + ';cmd=unlock;tgt=' + tgtNodes + }, + + success : function(data) { + // Create an info box to show output + var output = writeRsp(data.rsp, ''); + output.css('margin', '0px'); + // Remove loader and append output + $('#' + statBarId + ' img').remove(); + $('#' + statBarId + ' div').append(output); + } + }); + + $(this).dialog("close"); + } + }, + "Cancel": function() { + $(this).dialog("close"); + } + } + }); } /** * Get nodes current load information */ function getNodesCurrentLoad(){ - var userName = $.cookie('xcat_username'); - var nodes = $.cookie(userName + '_usrnodes'); - + var userName = $.cookie('xcat_username'); + var nodes = $.cookie(userName + '_usrnodes'); + // Get nodes current status $.ajax({ - url : 'lib/srv_cmd.php', + url : 'lib/srv_cmd.php', dataType : 'json', data : { - cmd : 'webrun', + cmd : 'webrun', tgt : '', args : 'gangliacurrent;node;' + nodes, msg : '' @@ -1607,15 +1608,14 @@ function getNodesCurrentLoad(){ /** * Save node load data * - * @param status - * Data returned from HTTP request + * @param status Data returned from HTTP request */ function saveNodeLoad(status){ - // Save node path and status for future use - nodePath = new Object(); - nodeStatus = new Object(); - - // Get nodes status + // Save node path and status for future use + nodePath = new Object(); + nodeStatus = new Object(); + + // Get nodes status var nodes = status.rsp[0].split(';'); var i = 0, pos = 0; @@ -1654,17 +1654,15 @@ function saveNodeLoad(status){ /** * Get monitoring metrics and load into inventory fieldset * - * @param node - * Node to collect metrics - * @return Nothing + * @param node Node to collect metrics */ function getMonitorMetrics(node) { - // Inventory tab should have this fieldset already created - // e.g.
                                                                    - $('#' + node + '_monitor').children('div').remove(); - - // Before trying to get the metrics, check if Ganglia is running - $.ajax({ + // Inventory tab should have this fieldset already created + // e.g.
                                                                    + $('#' + node + '_monitor').children('div').remove(); + + // Before trying to get the metrics, check if Ganglia is running + $.ajax({ url : 'lib/srv_cmd.php', dataType : 'json', data : { @@ -1675,18 +1673,18 @@ function getMonitorMetrics(node) { }, success: function(data) { - var ganglia = data.rsp; - var node, status; + var ganglia = data.rsp; + var node, status; - // Get the ganglia status - for ( var i in ganglia) { - // ganglia[0] = nodeName and ganglia[1] = state - node = jQuery.trim(ganglia[i][0]); - status = jQuery.trim(ganglia[i][1]); - - if (node && status == 'on') { - // Get monitoring metrics - $.ajax({ + // Get the ganglia status + for ( var i in ganglia) { + // ganglia[0] = nodeName and ganglia[1] = state + node = jQuery.trim(ganglia[i][0]); + status = jQuery.trim(ganglia[i][1]); + + if (node && status == 'on') { + // Get monitoring metrics + $.ajax({ url : 'lib/srv_cmd.php', dataType : 'json', data : { @@ -1698,27 +1696,25 @@ function getMonitorMetrics(node) { success: drawMonitoringCharts }); - } else if (node && status == 'off') { - var info = createInfoBar('Ganglia monitoring is disabled for this node'); - $('#' + node + '_monitor').append(info.css('width', '300px')); - } - } // End of for + } else if (node && status == 'off') { + var info = createInfoBar('Ganglia monitoring is disabled for this node'); + $('#' + node + '_monitor').append(info.css('width', '300px')); + } + } // End of for } // End of function - }); + }); } /** * Draw monitoring charts based on node metrics * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function drawMonitoringCharts(data){ - var nodeMetrics = new Object(); - var metricData = data.rsp[0].split(';'); - var node = data.msg; - + var nodeMetrics = new Object(); + var metricData = data.rsp[0].split(';'); + var node = data.msg; + var metricName = ''; var metricVal = ''; var pos = 0; @@ -1748,13 +1744,9 @@ function drawMonitoringCharts(data){ /** * Draw load metrics flot * - * @param node - * Node name - * @param loadpair - * Load timestamp and value pair - * @param cpupair - * CPU number and value pair - * @return Nothing + * @param node Node name + * @param loadpair Load timestamp and value pair + * @param cpupair CPU number and value pair */ function drawLoadFlot(node, loadPair, cpuPair){ var load = new Array(); @@ -1766,10 +1758,10 @@ function drawLoadFlot(node, loadPair, cpuPair){ // Append flot to node monitoring fieldset var loadFlot = $('
                                                                    ').css({ - 'float': 'left', - 'height': '150px', - 'margin': '0 0 10px', - 'width': '300px' + 'float': 'left', + 'height': '150px', + 'margin': '0 0 10px', + 'width': '300px' }); $('#' + node + '_monitor').append(loadFlot); $('#' + node + '_load').empty(); @@ -1824,21 +1816,18 @@ function drawLoadFlot(node, loadPair, cpuPair){ /** * Draw CPU usage flot * - * @param node - * Node name - * @param cpuPair - * CPU timestamp and value pair - * @return Nothing + * @param node Node name + * @param cpuPair CPU timestamp and value pair */ function drawCpuFlot(node, cpuPair){ var cpu = new Array(); - // Append flot to node monitoring fieldset + // Append flot to node monitoring fieldset var cpuFlot = $('
                                                                    ').css({ - 'float': 'left', - 'height': '150px', - 'margin': '0 0 10px', - 'width': '300px' + 'float': 'left', + 'height': '150px', + 'margin': '0 0 10px', + 'width': '300px' }); $('#' + node + '_monitor').append(cpuFlot); $('#' + node + '_cpu').empty(); @@ -1873,25 +1862,21 @@ function drawCpuFlot(node, cpuPair){ /** * Draw memory usage flot * - * @param node - * Node name - * @param freePair - * Free memory timestamp and value pair - * @param totalPair - * Total memory timestamp and value pair - * @return Nothing + * @param node Node name + * @param freePair Free memory timestamp and value pair + * @param totalPair Total memory timestamp and value pair */ function drawMemFlot(node, freePair, totalPair){ var used = new Array(); var total = new Array(); var size = 0; - // Append flot to node monitoring fieldset + // Append flot to node monitoring fieldset var memoryFlot = $('
                                                                    ').css({ - 'float': 'left', - 'height': '150px', - 'margin': '0 0 10px', - 'width': '300px' + 'float': 'left', + 'height': '150px', + 'margin': '0 0 10px', + 'width': '300px' }); $('#' + node + '_monitor').append(memoryFlot); $('#' + node + '_memory').empty(); @@ -1940,231 +1925,221 @@ function drawMemFlot(node, freePair, totalPair){ /** * Draw disk usage flot * - * @param node - * Node name - * @param freePair - * Free disk space (Ganglia only logs free data) - * @param totalPair - * Total disk space - * @return Nothing + * @param node Node name + * @param freePair Free disk space (Ganglia only logs free data) + * @param totalPair Total disk space */ function drawDiskFlot(node, freePair, totalPair) { - var used = new Array(); - var total = new Array(); - var size = 0; + var used = new Array(); + var total = new Array(); + var size = 0; - // Append flot to node monitoring fieldset - var diskFlot = $('
                                                                    ').css({ - 'float' : 'left', - 'height' : '150px', - 'margin' : '0 0 10px', - 'width' : '300px' - }); - $('#' + node + '_monitor').append(diskFlot); - $('#' + node + '_disk').empty(); + // Append flot to node monitoring fieldset + var diskFlot = $('
                                                                    ').css({ + 'float' : 'left', + 'height' : '150px', + 'margin' : '0 0 10px', + 'width' : '300px' + }); + $('#' + node + '_monitor').append(diskFlot); + $('#' + node + '_disk').empty(); - if (freePair.length < totalPair.length) { - size = freePair.length; - } else { - size = freePair.length; - } + if (freePair.length < totalPair.length) { + size = freePair.length; + } else { + size = freePair.length; + } - var tmpTotal, tmpUsed; - for ( var i = 0; i < size; i += 2) { - tmpTotal = totalPair[i + 1]; - tmpUsed = tmpTotal - freePair[i + 1]; - total.push([ totalPair[i] * 1000, tmpTotal ]); - used.push([ freePair[i] * 1000, tmpUsed ]); - } + var tmpTotal, tmpUsed; + for ( var i = 0; i < size; i += 2) { + tmpTotal = totalPair[i + 1]; + tmpUsed = tmpTotal - freePair[i + 1]; + total.push([ totalPair[i] * 1000, tmpTotal ]); + used.push([ freePair[i] * 1000, tmpUsed ]); + } - $.jqplot(node + '_disk', [ used, total ], { - title : 'Disk Use Last Hour', - axes : { - xaxis : { - renderer : $.jqplot.DateAxisRenderer, - numberTicks : 4, - tickOptions : { - formatString : '%R', - show : true - } - }, - yaxis : { - min : 0, - tickOptions : { - formatString : '%.2fG' - } - } - }, - legend : { - show : true, - location : 'nw' - }, - series : [ { - label : 'Used' - }, { - label : 'Total' - } ], - seriesDefaults : { - showMarker : false - } - }); + $.jqplot(node + '_disk', [ used, total ], { + title : 'Disk Use Last Hour', + axes : { + xaxis : { + renderer : $.jqplot.DateAxisRenderer, + numberTicks : 4, + tickOptions : { + formatString : '%R', + show : true + } + }, + yaxis : { + min : 0, + tickOptions : { + formatString : '%.2fG' + } + } + }, + legend : { + show : true, + location : 'nw' + }, + series : [ { + label : 'Used' + }, { + label : 'Total' + } ], + seriesDefaults : { + showMarker : false + } + }); } /** * Draw network usage flot * - * @param node - * Node name - * @param freePair - * Free memory timestamp and value pair - * @param totalPair - * Total memory timestamp and value pair - * @return Nothing + * @param node Node name + * @param freePair Free memory timestamp and value pair + * @param totalPair Total memory timestamp and value pair */ function drawNetworkFlot(node, inPair, outPair) { - var inArray = new Array(); - var outArray = new Array(); - var maxVal = 0; - var unitName = 'B'; - var divisor = 1; + var inArray = new Array(); + var outArray = new Array(); + var maxVal = 0; + var unitName = 'B'; + var divisor = 1; - // Append flot to node monitoring fieldset - var diskFlot = $('
                                                                    ').css({ - 'float' : 'left', - 'height' : '150px', - 'margin' : '0 0 10px', - 'width' : '300px' - }); - $('#' + node + '_monitor').append(diskFlot); - $('#' + node + '_network').empty(); - - for (var i = 0; i < inPair.length; i += 2) { - if (inPair[i + 1] > maxVal) { - maxVal = inPair[i + 1]; - } - } + // Append flot to node monitoring fieldset + var diskFlot = $('
                                                                    ').css({ + 'float' : 'left', + 'height' : '150px', + 'margin' : '0 0 10px', + 'width' : '300px' + }); + $('#' + node + '_monitor').append(diskFlot); + $('#' + node + '_network').empty(); + + for (var i = 0; i < inPair.length; i += 2) { + if (inPair[i + 1] > maxVal) { + maxVal = inPair[i + 1]; + } + } - for (var i = 0; i < outPair.length; i += 2) { - if (outPair[i + 1] > maxVal) { - maxVal = outPair[i + 1]; - } - } + for (var i = 0; i < outPair.length; i += 2) { + if (outPair[i + 1] > maxVal) { + maxVal = outPair[i + 1]; + } + } - if (maxVal > 3000000) { - divisor = 1000000; - unitName = 'GB'; - } else if (maxVal >= 3000) { - divisor = 1000; - unitName = 'MB'; - } else { - // Do nothing - } + if (maxVal > 3000000) { + divisor = 1000000; + unitName = 'GB'; + } else if (maxVal >= 3000) { + divisor = 1000; + unitName = 'MB'; + } else { + // Do nothing + } - for (i = 0; i < inPair.length; i += 2) { - inArray.push([ (inPair[i] * 1000), (inPair[i + 1] / divisor) ]); - } + for (i = 0; i < inPair.length; i += 2) { + inArray.push([ (inPair[i] * 1000), (inPair[i + 1] / divisor) ]); + } - for (i = 0; i < outPair.length; i += 2) { - outArray.push([ (outPair[i] * 1000), (outPair[i + 1] / divisor) ]); - } + for (i = 0; i < outPair.length; i += 2) { + outArray.push([ (outPair[i] * 1000), (outPair[i + 1] / divisor) ]); + } - $.jqplot(node + '_network', [ inArray, outArray ], { - title : 'Network Last Hour', - axes : { - xaxis : { - renderer : $.jqplot.DateAxisRenderer, - numberTicks : 4, - tickOptions : { - formatString : '%R', - show : true - } - }, - yaxis : { - min : 0, - tickOptions : { - formatString : '%d' + unitName - } - } - }, - legend : { - show : true, - location : 'nw' - }, - series : [ { - label : 'In' - }, { - label : 'Out' - } ], - seriesDefaults : { - showMarker : false - } - }); + $.jqplot(node + '_network', [ inArray, outArray ], { + title : 'Network Last Hour', + axes : { + xaxis : { + renderer : $.jqplot.DateAxisRenderer, + numberTicks : 4, + tickOptions : { + formatString : '%R', + show : true + } + }, + yaxis : { + min : 0, + tickOptions : { + formatString : '%d' + unitName + } + } + }, + legend : { + show : true, + location : 'nw' + }, + series : [ { + label : 'In' + }, { + label : 'Out' + } ], + seriesDefaults : { + showMarker : false + } + }); } /** * Get an attribute of a given node * - * @param node - * The node - * @param attrName - * The attribute + * @param node The node + * @param attrName The attribute * @return The attribute of the node */ function getNodeAttr(node, attrName) { - // Get the row - var row = $('[id=' + node + ']').parents('tr'); + // Get the row + var row = $('[id=' + node + ']').parents('tr'); - // Search for the column containing the attribute - var attrCol; - - var cols = row.parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); - // Loop through each column - for (var i in cols) { - // Find column that matches the attribute - if (cols.eq(i).html() == attrName) { - attrCol = cols.eq(i); - break; - } - } - - // If the column containing the attribute is found - if (attrCol) { - // Get the attribute column index - var attrIndex = attrCol.index(); + // Search for the column containing the attribute + var attrCol = null; + + var cols = row.parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); + // Loop through each column + for (var i in cols) { + // Find column that matches the attribute + if (cols.eq(i).html() == attrName) { + attrCol = cols.eq(i); + break; + } + } + + // If the column containing the attribute is found + if (attrCol) { + // Get the attribute column index + var attrIndex = attrCol.index(); - // Get the attribute for the given node - var attr = row.find('td:eq(' + attrIndex + ')'); - return attr.text(); - } else { - return ''; - } + // Get the attribute for the given node + var attr = row.find('td:eq(' + attrIndex + ')'); + return attr.text(); + } else { + return ''; + } } /** * Set the maximum number of VMs a user could have */ function setMaxVM() { - var userName = $.cookie('xcat_username'); - - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'webportal', - tgt : '', - args : 'getmaxvm;' + userName, - msg : '' - }, + var userName = $.cookie('xcat_username'); + + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'webportal', + tgt : '', + args : 'getmaxvm;' + userName, + msg : '' + }, - success : function(data) { - // Get response - var rsp = jQuery.trim(data.rsp); - rsp = rsp.replace('Max allowed:', ''); - - // Set cookie to expire in 60 minutes - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie(userName + '_maxvm', rsp, { expires: exDate }); - } - }); + success : function(data) { + // Get response + var rsp = jQuery.trim(data.rsp); + rsp = rsp.replace('Max allowed:', ''); + + // Set cookie to expire in 60 minutes + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie(userName + '_maxvm', rsp, { expires: exDate }); + } + }); } \ No newline at end of file diff --git a/xCAT-UI/js/service/utils.js b/xCAT-UI/js/service/utils.js index 62ed47c24..ac48c1f9c 100644 --- a/xCAT-UI/js/service/utils.js +++ b/xCAT-UI/js/service/utils.js @@ -6,355 +6,340 @@ * @return String of nodes shown */ function getNodesShown(tableId) { - // String of nodes shown - var shownNodes = ''; - - // Get rows of shown nodes - var nodes = $('#' + tableId + ' tbody tr'); - - // Go through each row - var cols; - for (var i = 0; i < nodes.length; i++) { - // Get second column containing node name - cols = nodes.eq(i).find('td'); - shownNodes += cols.eq(1).text() + ','; - } - - // Remove last comma - shownNodes = shownNodes.substring(0, shownNodes.length-1); - return shownNodes; + // String of nodes shown + var shownNodes = ''; + + // Get rows of shown nodes + var nodes = $('#' + tableId + ' tbody tr'); + + // Go through each row + var cols; + for (var i = 0; i < nodes.length; i++) { + // Get second column containing node name + cols = nodes.eq(i).find('td'); + shownNodes += cols.eq(1).text() + ','; + } + + // Remove last comma + shownNodes = shownNodes.substring(0, shownNodes.length-1); + return shownNodes; } /** * Find the row index containing a column with a given string * - * @param str - * String to search for - * @param table - * Table to check - * @param col - * Column to find string under + * @param str String to search for + * @param table Table to check + * @param col Column to find string under * @return The row index containing the search string */ function findRow(str, table, col){ - var dTable, rows; - - // Get datatable - dTable = $(table).dataTable(); - rows = dTable.fnGetData(); - - // Loop through each row - for (var i in rows) { - // If the column contains the search string - if (rows[i][col].indexOf(str) > -1) { - return i; - } - } - - return -1; + var dTable, rows; + + // Get datatable + dTable = $(table).dataTable(); + rows = dTable.fnGetData(); + + // Loop through each row + for (var i in rows) { + // If the column contains the search string + if (rows[i][col].indexOf(str) > -1) { + return i; + } + } + + return -1; } /** * Select all checkboxes in the datatable * - * @param event - * Event on element - * @param obj - * Object triggering event - * @return Nothing + * @param event Event on element + * @param obj Object triggering event */ function selectAll(event, obj) { - var status = obj.attr('checked'); - var checkboxes = obj.parents('.dataTables_scroll').find('.dataTables_scrollBody input:checkbox'); - if (status) { - checkboxes.attr('checked', true); - } else { - checkboxes.attr('checked', false); - } - - event.stopPropagation(); + var status = obj.attr('checked'); + var checkboxes = obj.parents('.dataTables_scroll').find('.dataTables_scrollBody input:checkbox'); + if (status) { + checkboxes.attr('checked', true); + } else { + checkboxes.attr('checked', false); + } + + event.stopPropagation(); } /** * Get node attributes from HTTP request data * - * @param propNames - * Hash table of property names - * @param keys - * Property keys - * @param data - * Data from HTTP request + * @param propNames Hash table of property names + * @param keys Property keys + * @param data Data from HTTP request * @return Hash table of property values */ function getAttrs(keys, propNames, data) { - // Create hash table for property values - var attrs = new Object(); + // Create hash table for property values + var attrs = new Object(); - // Go through inventory and separate each property out - var curKey; // Current property key - var addLine; // Add a line to the current property? - for ( var i = 1; i < data.length; i++) { - addLine = true; + // Go through inventory and separate each property out + var curKey; // Current property key + var addLine; // Add a line to the current property? + for ( var i = 1; i < data.length; i++) { + addLine = true; - // Loop through property keys - // Does this line contains one of the properties? - for ( var j = 0; j < keys.length; j++) { - // Find property name - if (data[i].indexOf(propNames[keys[j]]) > -1) { - attrs[keys[j]] = new Array(); + // Loop through property keys + // Does this line contains one of the properties? + for ( var j = 0; j < keys.length; j++) { + // Find property name + if (data[i].indexOf(propNames[keys[j]]) > -1) { + attrs[keys[j]] = new Array(); - // Get rid of property name in the line - data[i] = data[i].replace(propNames[keys[j]], ''); - // Trim the line - data[i] = jQuery.trim(data[i]); + // Get rid of property name in the line + data[i] = data[i].replace(propNames[keys[j]], ''); + // Trim the line + data[i] = jQuery.trim(data[i]); - // Do not insert empty line - if (data[i].length > 0) { - attrs[keys[j]].push(data[i]); - } + // Do not insert empty line + if (data[i].length > 0) { + attrs[keys[j]].push(data[i]); + } - curKey = keys[j]; - addLine = false; // This line belongs to a property - } - } + curKey = keys[j]; + addLine = false; // This line belongs to a property + } + } - // Line does not contain a property - // Must belong to previous property - if (addLine && data[i].length > 1) { - data[i] = jQuery.trim(data[i]); - attrs[curKey].push(data[i]); - } - } + // Line does not contain a property + // Must belong to previous property + if (addLine && data[i].length > 1) { + data[i] = jQuery.trim(data[i]); + attrs[curKey].push(data[i]); + } + } - return attrs; + return attrs; } /** * Create a tool tip for comments * - * @param comment - * Comments to be placed in a tool tip + * @param comment Comments to be placed in a tool tip * @return Tool tip */ function createCommentsToolTip(comment) { - // Create tooltip container - var toolTip = $('
                                                                    '); - // Create textarea to hold comment - var txtArea = $('').css({ - 'font-size': '10px', - 'height': '50px', - 'width': '200px', - 'background-color': '#000', - 'color': '#fff', - 'border': '0px', - 'display': 'block' - }); - - // Create links to save and cancel changes - var lnkStyle = { - 'color': '#58ACFA', - 'font-size': '10px', - 'display': 'inline-block', - 'padding': '5px', - 'float': 'right' - }; - - var saveLnk = $('Save').css(lnkStyle).hide(); - var cancelLnk = $('Cancel').css(lnkStyle).hide(); - var infoSpan = $('Click to edit').css(lnkStyle); - - // Save changes onclick - saveLnk.bind('click', function(){ - // Get node and comment - var node = $(this).parent().parent().find('img').attr('id').replace('Tip', ''); - var comments = $(this).parent().find('textarea').val(); - - // Save comment - $.ajax( { - url : 'lib/srv_cmd.php', - dataType : 'json', - data : { - cmd : 'chdef', - tgt : '', - args : '-t;node;-o;' + node + ';usercomment=' + comments, - msg : 'out=manageTab;tgt=' + node - }, - - success: showChdefOutput - }); - - // Hide cancel and save links - $(this).hide(); - cancelLnk.hide(); - }); - - // Cancel changes onclick - cancelLnk.bind('click', function(){ - // Get original comment and put it back - var orignComments = $(this).parent().find('textarea').text(); - $(this).parent().find('textarea').val(orignComments); - - // Hide cancel and save links - $(this).hide(); - saveLnk.hide(); - infoSpan.show(); - }); - - // Show save link when comment is edited - txtArea.bind('click', function(){ - saveLnk.show(); - cancelLnk.show(); - infoSpan.hide(); - }); - - toolTip.append(txtArea); - toolTip.append(cancelLnk); - toolTip.append(saveLnk); - toolTip.append(infoSpan); - - return toolTip; + // Create tooltip container + var toolTip = $('
                                                                    '); + // Create textarea to hold comment + var txtArea = $('').css({ + 'font-size': '10px', + 'height': '50px', + 'width': '200px', + 'background-color': '#000', + 'color': '#fff', + 'border': '0px', + 'display': 'block' + }); + + // Create links to save and cancel changes + var lnkStyle = { + 'color': '#58ACFA', + 'font-size': '10px', + 'display': 'inline-block', + 'padding': '5px', + 'float': 'right' + }; + + var saveLnk = $('Save').css(lnkStyle).hide(); + var cancelLnk = $('Cancel').css(lnkStyle).hide(); + var infoSpan = $('Click to edit').css(lnkStyle); + + // Save changes onclick + saveLnk.bind('click', function(){ + // Get node and comment + var node = $(this).parent().parent().find('img').attr('id').replace('Tip', ''); + var comments = $(this).parent().find('textarea').val(); + + // Save comment + $.ajax( { + url : 'lib/srv_cmd.php', + dataType : 'json', + data : { + cmd : 'chdef', + tgt : '', + args : '-t;node;-o;' + node + ';usercomment=' + comments, + msg : 'out=manageTab;tgt=' + node + }, + + success: showChdefOutput + }); + + // Hide cancel and save links + $(this).hide(); + cancelLnk.hide(); + }); + + // Cancel changes onclick + cancelLnk.bind('click', function(){ + // Get original comment and put it back + var orignComments = $(this).parent().find('textarea').text(); + $(this).parent().find('textarea').val(orignComments); + + // Hide cancel and save links + $(this).hide(); + saveLnk.hide(); + infoSpan.show(); + }); + + // Show save link when comment is edited + txtArea.bind('click', function(){ + saveLnk.show(); + cancelLnk.show(); + infoSpan.hide(); + }); + + toolTip.append(txtArea); + toolTip.append(cancelLnk); + toolTip.append(saveLnk); + toolTip.append(infoSpan); + + return toolTip; } /** * Open a dialog and show given message * - * @param type - * Type of dialog, i.e. warn or info - * @param msg - * Message to show - * @return Nothing + * @param type Type of dialog, i.e. warn or info + * @param msg Message to show */ function prompt(type, msg) { - var style = { - 'display': 'inline-block', - 'margin': '5px', - 'vertical-align': 'middle' - }; - msg.css({ - 'display': 'inline', - 'margin': '5px', - 'vertical-align': 'middle' - }); - - // Append icon - var icon; - var dialog = $('
                                                                    '); - if (type == "Warning") { - icon = $('').css(style); - } else { - icon = $('').css(style); - } - - dialog.append(icon); - dialog.append(msg); - - // Open dialog - dialog.dialog({ - title: type, - modal: true, - width: 400, - buttons: { - "Ok": function(){ - $(this).dialog("close"); - } - } - }); + var style = { + 'display': 'inline-block', + 'margin': '5px', + 'vertical-align': 'middle' + }; + msg.css({ + 'display': 'inline', + 'margin': '5px', + 'vertical-align': 'middle' + }); + + // Append icon + var icon; + var dialog = $('
                                                                    '); + if (type == "Warning") { + icon = $('').css(style); + } else { + icon = $('').css(style); + } + + dialog.append(icon); + dialog.append(msg); + + // Open dialog + dialog.dialog({ + title: type, + modal: true, + close: function(){ + $(this).remove(); + }, + width: 400, + buttons: { + "Ok": function(){ + $(this).dialog("close"); + } + } + }); } /** * Get nodes that are checked in a given datatable * - * @param dTableId - * The datatable ID + * @param dTableId The datatable ID * @return Nodes that were checked */ function getNodesChecked(dTableId) { - var tgts = ''; + var tgts = ''; - // Get nodes that were checked - var nodes = $('#' + dTableId + ' input[type=checkbox]:checked'); - for (var i in nodes) { - var tgtNode = nodes.eq(i).attr('name'); - - if (tgtNode){ - tgts += tgtNode; - - // Add a comma at the end - if (i < nodes.length - 1) { - tgts += ','; - } - } - } + // Get nodes that were checked + var nodes = $('#' + dTableId + ' input[type=checkbox]:checked'); + for (var i in nodes) { + var tgtNode = nodes.eq(i).attr('name'); + + if (tgtNode){ + tgts += tgtNode; + + // Add a comma at the end + if (i < nodes.length - 1) { + tgts += ','; + } + } + } - return tgts; + return tgts; } /** * Show chdef output * - * @param data - * Data returned from HTTP request - * @return Nothing + * @param data Data returned from HTTP request */ function showChdefOutput(data) { - // Get output - var out = data.rsp; - var args = data.msg.split(';'); - var tabID = args[0].replace('out=', ''); - var tgt = args[1].replace('tgt=', ''); - - // Find info bar on nodes tab, if any - var info = $('#' + tabID).find('.ui-state-highlight'); - if (!info.length) { - // Create info bar if one does not exist - info = createInfoBar(''); - $('#' + tabID).append(info); - } - - // Go through output and append to paragraph - var prg = $('

                                                                    '); - for (var i in out) { - prg.append(tgt + ': ' + out[i] + '
                                                                    '); - } - - info.append(prg); + // Get output + var out = data.rsp; + var args = data.msg.split(';'); + var tabID = args[0].replace('out=', ''); + var tgt = args[1].replace('tgt=', ''); + + // Find info bar on nodes tab, if any + var info = $('#' + tabID).find('.ui-state-highlight'); + if (!info.length) { + // Create info bar if one does not exist + info = createInfoBar(''); + $('#' + tabID).append(info); + } + + // Go through output and append to paragraph + var prg = $('

                                                                    '); + for (var i in out) { + prg.append(tgt + ': ' + out[i] + '
                                                                    '); + } + + info.append(prg); } /** * Get an attribute of a given node * - * @param node - * The node - * @param attrName - * The attribute + * @param node The node + * @param attrName The attribute * @return The attribute of the node */ function getUserNodeAttr(node, attrName) { - // Get the row - var row = $('[id=' + node + ']').parents('tr'); + // Get the row + var row = $('[id=' + node + ']').parents('tr'); - // Search for the column containing the attribute - var attrCol; - - var cols = row.parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); - // Loop through each column - for (var i in cols) { - // Find column that matches the attribute - if (cols.eq(i).html() == attrName) { - attrCol = cols.eq(i); - break; - } - } - - // If the column containing the attribute is found - if (attrCol) { - // Get the attribute column index - var attrIndex = attrCol.index(); + // Search for the column containing the attribute + var attrCol = null; + + var cols = row.parents('.dataTables_scroll').find('.dataTables_scrollHead thead tr:eq(0) th'); + // Loop through each column + for (var i in cols) { + // Find column that matches the attribute + if (cols.eq(i).html() == attrName) { + attrCol = cols.eq(i); + break; + } + } + + // If the column containing the attribute is found + if (attrCol) { + // Get the attribute column index + var attrIndex = attrCol.index(); - // Get the attribute for the given node - var attr = row.find('td:eq(' + attrIndex + ')'); - return attr.text(); - } else { - return ''; - } + // Get the attribute for the given node + var attr = row.find('td:eq(' + attrIndex + ')'); + return attr.text(); + } else { + return ''; + } } \ No newline at end of file diff --git a/xCAT-UI/js/srv_xcatauth.js b/xCAT-UI/js/srv_xcatauth.js index a22fc56ad..c86d56af4 100644 --- a/xCAT-UI/js/srv_xcatauth.js +++ b/xCAT-UI/js/srv_xcatauth.js @@ -13,78 +13,76 @@ $(document).ready(function() { // The window's height is to small to show the dialog var tmpHeight = 0; if ((winHeight - 50) < diagHeight){ - tmpHeight = 0; + tmpHeight = 0; } else { - tmpHeight = parseInt((winHeight - diagHeight - 50) / 2); + tmpHeight = parseInt((winHeight - diagHeight - 50) / 2); } $('#login').css('margin', tmpHeight + 'px auto'); $('button').bind('click', function(){ - authenticate(); + authenticate(); }).button(); - if (document.location.protocol == 'http:') { - $('#login_status').html('You are using an unencrypted session!'); - $('#login_status').css('color', 'red'); - } - - if (!$("#login input[name='username']").val()) { - $("#login input[name='username']").focus(); - } else { - $("#login input[name='password']").focus(); - } + if (document.location.protocol == 'http:') { + $('#login-status').html('You are using an unencrypted session!'); + $('#login-status').css('color', 'red'); + } + + if (!$("#login input[name='username']").val()) { + $("#login input[name='username']").focus(); + } else { + $("#login input[name='password']").focus(); + } - // When enter is hit while in username, advance to password - $("#login input[name='username']").keydown(function(event) { - if (event.keyCode == 13) { - $("#login input[name='password']").focus(); - } - }); + // When enter is hit while in username, advance to password + $("#login input[name='username']").keydown(function(event) { + if (event.keyCode == 13) { + $("#login input[name='password']").focus(); + } + }); - // Submit authentication if enter is pressed in password field - $("#login input[name='password']").keydown(function(event) { - if (event.keyCode == 13) { - authenticate(); - } - }); + // Submit authentication if enter is pressed in password field + $("#login input[name='password']").keydown(function(event) { + if (event.keyCode == 13) { + authenticate(); + } + }); }); /** * Update login dialog * - * @param data - * Data returned from AJAX call - * @param txtStatus - * Status of login + * @param data Data returned from AJAX call + * @param txtStatus Status of login */ function onlogin(data, txtStatus) { - // Clear password field regardless of what happens - var usrName = $("#login input[name='username']").val(); - $("#login input[name='password']").val(''); - if (data.authenticated == 'yes') { - $('#login_status').text('Login successful'); - window.location = 'service.php'; - - // Set user name cookie - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie('xcat_username', usrName, { expires: exDate }); - } else { - $('#login_status').text('Authentication failure'); - $('#login_status').css('color', '#FF0000'); - } + // Clear password field regardless of what happens + var usrName = $("#login input[name='username']").val(); + $("#login input[name='password']").val(''); + if (data.authenticated == 'yes') { + $('#login-status').text('Login successful'); + window.location = 'service.php'; + + // Set user name cookie + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie('xcat_username', usrName, { expires: exDate }); + } else { + $('#login-status').text('Authentication failure'); + $('#login-status').css('color', '#FF0000'); + } } /** * Authenticate user for new session */ function authenticate() { - $('#login_status').css('color', '#000000'); - $('#login_status').html('Authenticating...'); - - var passwd = $("#login input[name='password']").val(); - $.post('lib/srv_log.php', { - username : $("#login input[name='username']").val(), - password : passwd - }, onlogin, 'json'); + $('#login-status').css('color', '#000000'); + $('#login-status').html('Authenticating...'); + + var passwd = $("#login input[name='password']").val(); + $.post('lib/srv_log.php', { + username : $("#login input[name='username']").val(), + password : passwd + }, onlogin, 'json'); } diff --git a/xCAT-UI/js/ui.js b/xCAT-UI/js/ui.js index 74938adc2..148f016cc 100644 --- a/xCAT-UI/js/ui.js +++ b/xCAT-UI/js/ui.js @@ -8,789 +8,750 @@ * @return Nothing */ var Tab = function(tabId) { - this.tabId = tabId; - this.tabName = null; - this.tab = null; + this.tabId = tabId; + this.tabName = null; + this.tab = null; }; /** * Initialize the tab * - * @param tabName - * Tab name to initialize - * @return Nothing + * @param tabName Tab name to initialize */ Tab.prototype.init = function() { - // Create a division containing the tab - this.tab = $('
                                                                    '); - var tabList = $('
                                                                      '); - var tabItem = $('
                                                                    • Dummy tab item
                                                                    • '); - tabList.append(tabItem); - this.tab.append(tabList); + // Create a division containing the tab + this.tab = $('
                                                                      '); + var tabList = $('
                                                                        '); + var tabItem = $('
                                                                      • Dummy tab item
                                                                      • '); + tabList.append(tabItem); + this.tab.append(tabList); - // Create a template with close button - var tabs = this.tab.tabs(); + // Create a template with close button + var tabs = this.tab.tabs(); - tabs.bind('tabsselect', function(event, ui){ - // Save the order tabs were selected - var order; - if ($.cookie('tabindex_history')) { - order = $.cookie('tabindex_history').split(','); - order[1] = order[0]; // Set index 1 to last selected tab - order[0] = ui.index; // Set index 0 to currently selected tab - } else { - // Create an array to track the tab selected - order = new Array; - order[0] = ui.index; - order[1] = ui.index; - } - - $.cookie('tabindex_history', order); - }); + tabs.bind('tabsselect', function(event, ui){ + // Save the order tabs were selected + var order; + if ($.cookie('tabindex_history')) { + order = $.cookie('tabindex_history').split(','); + order[1] = order[0]; // Set index 1 to last selected tab + order[0] = ui.index; // Set index 0 to currently selected tab + } else { + // Create an array to track the tab selected + order = new Array; + order[0] = ui.index; + order[1] = ui.index; + } + + $.cookie('tabindex_history', order); + + // Find any datatable within the tab + var dTables = $(ui.panel).find('.dataTables_wrapper'); + if(dTables.length) { + // Adjust column sizes for each datatable found + for (var i = 0; i < dTables.length; i++) { + var tableId = dTables.eq(i).attr('id').replace('_wrapper', ''); + adjustColumnSize(tableId); + } + } + }); - // Remove dummy tab - this.tab.tabs("remove", 0); + // Remove dummy tab + this.tab.tabs("remove", 0); - // Hide tab - this.tab.hide(); + // Hide tab + this.tab.hide(); }; /** * Return the tab object * - * @param Nothing * @return Object representing the tab */ Tab.prototype.object = function() { - return this.tab; + return this.tab; }; /** * Add a new tab * - * @param tabId - * Tab ID - * @param tabName - * Tab name - * @param tabCont - * Tab content - * @param closeable - * Is tab closeable - * @return Nothing + * @param tabId Tab ID + * @param tabName Tab name + * @param tabCont Tab content + * @param closeable Is tab closeable */ Tab.prototype.add = function(tabId, tabName, tabCont, closeable) { - // Show tab - if (this.tab.css("display") == "none") { - this.tab.show(); - } + // Show tab + if (this.tab.css("display") == "none") { + this.tab.show(); + } - var newTab = $('
                                                                        '); - newTab.append(tabCont); - this.tab.append(newTab); - this.tab.tabs("add", "#" + tabId, tabName); - - // Append close button - if (closeable) { - var header = this.tab.find('ul.ui-tabs-nav a[href="#' + tabId +'"]').parent(); - header.append(''); - - // Get this tab - var tabs = this.tab; - var tabLink = 'a[href="\#' + tabId + '"]'; - var thisTab = $(tabLink, tabs).parent(); - - // Close tab when close button is clicked - thisTab.find('span.tab-close').bind('click', function(event) { - var tabIndex = ($('li', tabs).index(thisTab)); - - // Do not remove first tab - if (tabIndex != 0) { - // Go back to last tab if user is trying to close currently selected tab - if (tabs.tabs('option', 'selected') == tabIndex) { - // Get last selected tab from history - var order = $.cookie('tabindex_history').split(','); - if (order[1]) { - tabs.tabs('select', parseInt(order[1])); - } else { - tabs.tabs('select', 0); - } - } - - tabs.tabs('remove', tabIndex); - } - }); - } + var newTab = $('
                                                                        '); + newTab.append(tabCont); + this.tab.append(newTab); + this.tab.tabs("add", "#" + tabId, tabName); + + // Append close button + if (closeable) { + var header = this.tab.find('ul.ui-tabs-nav a[href="#' + tabId +'"]').parent(); + header.append(''); + + // Get this tab + var tabs = this.tab; + var tabLink = 'a[href="\#' + tabId + '"]'; + var thisTab = $(tabLink, tabs).parent(); + + // Close tab when close button is clicked + thisTab.find('span.tab-close').bind('click', function(event) { + var tabIndex = ($('li', tabs).index(thisTab)); + + // Do not remove first tab + if (tabIndex != 0) { + // Go back to last tab if user is trying to close currently selected tab + if (tabs.tabs('option', 'selected') == tabIndex) { + // Get last selected tab from history + var order = $.cookie('tabindex_history').split(','); + if (order[1]) { + tabs.tabs('select', parseInt(order[1])); + } else { + tabs.tabs('select', 0); + } + } + + tabs.tabs('remove', tabIndex); + } + }); + } }; /** * Select a tab * - * @param id - * Tab ID to select - * @return Nothing + * @param id Tab ID to select */ Tab.prototype.select = function(id) { - this.tab.tabs("select", "#" + id); + this.tab.tabs("select", "#" + id); }; /** * Remove a tab * - * @param id - * Tab ID to remove - * @return Nothing + * @param id Tab ID to remove */ Tab.prototype.remove = function(id) { - var selectorStr = 'a[href="\#' + id + '"]'; - var selectTab = $(selectorStr, this.tab).parent(); - var index = ($('li', this.tab).index(selectTab)); - this.tab.tabs("remove", index); + var selectorStr = 'a[href="\#' + id + '"]'; + var selectTab = $(selectorStr, this.tab).parent(); + var index = ($('li', this.tab).index(selectTab)); + this.tab.tabs("remove", index); }; /** * Table constructor * - * @param tabId - * Tab ID - * @param tabName - * Tab name - * @return Nothing + * @param tabId Tab ID + * @param tabName Tab name */ var Table = function(tableId) { - if ($('#' + tableId).length) { - this.tableId = tableId; - this.table = $('#' + tableId); - } else { - this.tableId = tableId; - this.table = null; - } + if ($('#' + tableId).length) { + this.tableId = tableId; + this.table = $('#' + tableId); + } else { + this.tableId = tableId; + this.table = null; + } }; /** * Initialize the table * - * @param Headers - * Array of table headers - * @return Nothing + * @param Headers Array of table headers */ Table.prototype.init = function(headers) { - // Create a table - this.table = $('
                                                                        '); - var thead = $(''); - var headRow = $(''); + // Create a table + this.table = $('
                                                                        '); + var thead = $(''); + var headRow = $(''); - // Append headers - for ( var i in headers) { - headRow.append('' + headers[i] + ''); - } + // Append headers + for ( var i in headers) { + headRow.append('' + headers[i] + ''); + } - thead.append(headRow); - this.table.append(thead); + thead.append(headRow); + this.table.append(thead); - // Append table body - var tableBody = $(''); - this.table.append(tableBody); + // Append table body + var tableBody = $(''); + this.table.append(tableBody); }; /** * Return the table object * - * @param Nothing * @return Object representing the table */ Table.prototype.object = function() { - return this.table; + return this.table; }; /** * Add a row to the table * - * @param rowCont - * Array of table row contents - * @return Nothing + * @param rowCont Array of table row contents */ Table.prototype.add = function(rowCont) { - // Create table row - var tableRow = $(''); + // Create table row + var tableRow = $(''); - // Create a column for each content - var tableCol; - for ( var i in rowCont) { - tableCol = $(''); - tableCol.append(rowCont[i]); - tableRow.append(tableCol); - } + // Create a column for each content + var tableCol; + for ( var i in rowCont) { + tableCol = $(''); + tableCol.append(rowCont[i]); + tableRow.append(tableCol); + } - // Append table row to table - this.table.find('tbody').append(tableRow); + // Append table row to table + this.table.find('tbody').append(tableRow); }; /** * Add a footer to the table * - * @param rowCont - * Array of table row contents - * @return Nothing + * @param rowCont Array of table row contents */ Table.prototype.addFooter = function(rowCont) { - // Create table row - var tableFoot = $(''); - tableFoot.append(rowCont); + // Create table row + var tableFoot = $(''); + tableFoot.append(rowCont); - // Append table row to table - this.table.append(tableFoot); + // Append table row to table + this.table.append(tableFoot); }; /** * Remove a row from the table - * - * @return Nothing */ Table.prototype.remove = function(id) { - // To be continued + // To be continued }; /** * Datatable class constructor * - * @param tabId - * Tab ID - * @param tabName - * Tab name - * @return Nothing + * @param tabId Tab ID + * @param tabName Tab name */ var DataTable = function(tableId) { - this.dataTableId = tableId; - this.dataTable = null; + this.dataTableId = tableId; + this.dataTable = null; }; /** * Initialize the datatable * - * @param Headers - * Array of table headers - * @return Nothing + * @param Headers Array of table headers */ DataTable.prototype.init = function(headers) { - // Create a table - this.dataTable = $('
                                                                        '); - var thead = $(''); - var headRow = $(''); + // Create a table + this.dataTable = $('
                                                                        '); + var thead = $(''); + var headRow = $(''); - // Append headers - for ( var i in headers) { - headRow.append('' + headers[i] + ''); - } + // Append headers + for ( var i in headers) { + headRow.append('' + headers[i] + ''); + } - thead.append(headRow); - this.dataTable.append(thead); + thead.append(headRow); + this.dataTable.append(thead); - // Append table body - var tableBody = $(''); - this.dataTable.append(tableBody); + // Append table body + var tableBody = $(''); + this.dataTable.append(tableBody); }; /** * Return the datatable object * - * @param Nothing * @return Object representing the table */ DataTable.prototype.object = function() { - return this.dataTable; + return this.dataTable; }; /** * Add a row to the datatable * - * @param rowCont - * Array of table row contents - * @return Nothing + * @param rowCont Array of table row contents */ DataTable.prototype.add = function(rowCont) { - // Create table row - var tableRow = $(''); + // Create table row + var tableRow = $(''); - // Create a column for each content - var tableCol; - for ( var i in rowCont) { - tableCol = $(''); - tableCol.append(rowCont[i]); - tableRow.append(tableCol); - } + // Create a column for each content + var tableCol; + for ( var i in rowCont) { + tableCol = $(''); + tableCol.append(rowCont[i]); + tableRow.append(tableCol); + } - // Append table row to table - this.dataTable.find('tbody').append(tableRow); + // Append table row to table + this.dataTable.find('tbody').append(tableRow); }; /** * Create status bar * - * @param barId - * Status bar ID - * @return Status bar + * @param barId Status bar ID */ function createStatusBar(barId) { - var statusBar = $('
                                                                        ').css({ - 'margin-bottom': '5px', - 'min-height': '30px' - }); - - // Create info icon - var icon = $('').css({ - 'display': 'inline-block', - 'margin': '10px 5px', - 'vertical-align': 'top' - }); - - // Create message section - var msg = $('
                                                                        ').css({ - 'display': 'inline-block', - 'margin': '10px 0px', - 'width': '90%' - }); - - // Create hide button - var hide = $('').css({ - 'display': 'inline-block', - 'float': 'right', - 'margin': '10px 5px', - 'cursor': 'pointer' - }).click(function() { - // Remove info box on-click - $(this).parent().hide(); - }); - - statusBar.append(icon); - statusBar.append(msg); - statusBar.append(hide); - return statusBar; + var statusBar = $('
                                                                        ').css({ + 'margin-bottom': '5px', + 'min-height': '30px' + }); + + // Create info icon + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px', + 'vertical-align': 'top' + }); + + // Create message section + var msg = $('
                                                                        ').css({ + 'display': 'inline-block', + 'margin': '10px 0px', + 'width': '90%' + }); + + // Create hide button + var hide = $('').css({ + 'display': 'inline-block', + 'float': 'right', + 'margin': '10px 5px', + 'cursor': 'pointer' + }).click(function() { + // Remove info box on-click + $(this).parent().hide(); + }); + + statusBar.append(icon); + statusBar.append(msg); + statusBar.append(hide); + return statusBar; } /** * Create info bar * - * @param msg - * Info message + * @param msg Info message * @return Info bar */ function createInfoBar(msg) { - var infoBar = $('
                                                                        ').css('margin', '5px 0px'); - var icon = $('').css({ - 'display': 'inline-block', - 'margin': '10px 5px' - }); - var msg = $('

                                                                        ' + msg + '

                                                                        ').css({ - 'display': 'inline-block', - 'width': '90%' - }); - - infoBar.append(icon); - infoBar.append(msg); - return infoBar; + var infoBar = $('
                                                                        ').css('margin', '5px 0px'); + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px' + }); + var barMsg = $('

                                                                        ' + msg + '

                                                                        ').css({ + 'display': 'inline-block', + 'width': '90%' + }); + + infoBar.append(icon); + infoBar.append(barMsg); + return infoBar; } /** * Create warning bar * - * @param msg - * Warning message + * @param msg Warning message * @return Warning bar */ function createWarnBar(msg) { - var warnBar = $('
                                                                        '); - var icon = $('').css({ - 'display': 'inline-block', - 'margin': '10px 5px' - }); - var msg = $('

                                                                        ' + msg + '

                                                                        ').css({ - 'display': 'inline-block', - 'width': '90%' - }); - - warnBar.append(icon); - warnBar.append(msg); - return warnBar; + var warnBar = $('
                                                                        '); + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px' + }); + var barMsg = $('

                                                                        ' + msg + '

                                                                        ').css({ + 'display': 'inline-block', + 'width': '90%' + }); + + warnBar.append(icon); + warnBar.append(barMsg); + return warnBar; } /** * Create a loader * - * @param loaderId - * Loader ID - * @return Loader + * @param loaderId Loader ID */ function createLoader(loaderId) { - var loader = $(''); - return loader; + var loader = $(''); + return loader; } /** * Create a button * - * @param name - * Name of the button - * @return Nothing + * @param name Name of the button */ function createButton(name) { - var button = $('').button(); - return button; + var button = $('').button(); + return button; } /** * Create a menu * - * @param items - * An array of items to go into the menu + * @param items An array of items to go into the menu * @return A division containing the menu */ function createMenu(items) { - var menu = $('
                                                                          '); + var menu = $('
                                                                            '); - // Loop through each item - for ( var i in items) { - // Append item to menu - var item = $('
                                                                          • '); + // Loop through each item + for ( var i in items) { + // Append item to menu + var item = $('
                                                                          • '); - // If it is a sub menu - if (items[i] instanceof Array) { - // 1st index = Sub menu title - item.append(items[i][0]); - // 2nd index = Sub menu - item.append(items[i][1]); - } else { - item.append(items[i]); - } - - menu.append(item); - } - - return menu; + // If it is a sub menu + if (items[i] instanceof Array) { + // 1st index = Sub menu title + item.append(items[i][0]); + // 2nd index = Sub menu + item.append(items[i][1]); + } else { + item.append(items[i]); + } + + menu.append(item); + } + + return menu; } /** * Initialize the page - * - * @return Nothing */ -function initPage() { - // Load theme - var theme = $.cookie('xcat_theme'); - if (theme) { - switch (theme) { - case 'cupertino': - includeCss("css/themes/jquery-ui-cupertino.css"); - break; - case 'dark_hive': - includeCss("css/themes/jquery-ui-dark_hive.css"); - break; - case 'redmond': - includeCss("css/themes/jquery-ui-redmond.css"); - break; - case 'start': - includeCss("css/themes/jquery-ui-start.css"); - break; - case 'sunny': - includeCss("css/themes/jquery-ui-sunny.css"); - break; - case 'ui_dark': - includeCss("css/themes/jquery-ui-ui_darkness.css"); - break; - default: - includeCss("css/themes/jquery-ui-start.css"); - } - } else { - includeCss("css/themes/jquery-ui-start.css"); - } +function initPage() { + // Load theme + var theme = $.cookie('xcat_theme'); + if (theme) { + switch (theme) { + case 'cupertino': + includeCss("css/themes/jquery-ui-cupertino.css"); + break; + case 'dark_hive': + includeCss("css/themes/jquery-ui-dark_hive.css"); + break; + case 'redmond': + includeCss("css/themes/jquery-ui-redmond.css"); + break; + case 'start': + includeCss("css/themes/jquery-ui-start.css"); + break; + case 'sunny': + includeCss("css/themes/jquery-ui-sunny.css"); + break; + case 'ui_dark': + includeCss("css/themes/jquery-ui-ui_darkness.css"); + break; + default: + includeCss("css/themes/jquery-ui-start.css"); + } + } else { + includeCss("css/themes/jquery-ui-start.css"); + } - // Load jQuery stylesheets - includeCss("css/jquery.dataTables.css"); - includeCss("css/superfish.css"); - includeCss("css/jstree.css"); - includeCss("css/jquery.jqplot.css"); - - // Load custom stylesheet - includeCss("css/style.css"); - - // JQuery plugins - includeJs("js/jquery/jquery.dataTables.min.js"); - includeJs("js/jquery/jquery.form.min.js"); - includeJs("js/jquery/jquery.jeditable.min.js"); - includeJs("js/jquery/jquery.contextmenu.min.js"); - includeJs("js/jquery/superfish.min.js"); - includeJs("js/jquery/hoverIntent.min.js"); - includeJs("js/jquery/jquery.jstree.min.js"); - includeJs("js/jquery/tooltip.min.js"); - includeJs("js/jquery/jquery.serverBrowser.min.js"); - includeJs("js/jquery/jquery.jqplot.min.js"); + // Load jQuery stylesheets + includeCss("css/jquery.dataTables.css"); + includeCss("css/superfish.css"); + includeCss("css/jstree.css"); + includeCss("css/jquery.jqplot.css"); + + // Load custom stylesheet + includeCss("css/style.css"); + + // JQuery plugins + includeJs("js/jquery/jquery.dataTables.min.js"); + includeJs("js/jquery/jquery.form.min.js"); + includeJs("js/jquery/jquery.jeditable.min.js"); + includeJs("js/jquery/jquery.contextmenu.min.js"); + includeJs("js/jquery/superfish.min.js"); + includeJs("js/jquery/hoverIntent.min.js"); + includeJs("js/jquery/jquery.jstree.min.js"); + includeJs("js/jquery/tooltip.min.js"); + includeJs("js/jquery/jquery.serverBrowser.min.js"); + includeJs("js/jquery/jquery.jqplot.min.js"); includeJs("js/jquery/jqplot.pieRenderer.min.js"); includeJs("js/jquery/jqplot.dateAxisRenderer.min.js"); - // Page plugins - includeJs("js/configure/configure.js"); - includeJs("js/monitor/monitor.js"); - includeJs("js/nodes/nodes.js"); - includeJs("js/provision/provision.js"); - - // Custom plugins - includeJs("js/custom/esx.js"); - includeJs("js/custom/kvm.js"); - includeJs("js/custom/blade.js"); - includeJs("js/custom/ipmi.js"); - includeJs("js/custom/zvm.js"); - includeJs("js/custom/hmc.js"); - includeJs("js/custom/customUtils.js"); + // Page plugins + includeJs("js/configure/configure.js"); + includeJs("js/monitor/monitor.js"); + includeJs("js/nodes/nodes.js"); + includeJs("js/provision/provision.js"); + + // Custom plugins + includeJs("js/custom/esx.js"); + includeJs("js/custom/kvm.js"); + includeJs("js/custom/blade.js"); + includeJs("js/custom/ipmi.js"); + includeJs("js/custom/zvm.js"); + includeJs("js/custom/hmc.js"); + includeJs("js/custom/customUtils.js"); - // Enable settings link - $('#xcat_settings').click(function() { - openSettings(); - }); - - // Set header to theme - var background = '', color = ''; - var theme = $.cookie('xcat_theme'); - if (theme) { - switch (theme) { - case 'cupertino': - background = '#3BAAE3'; - color = 'white'; - break; - case 'dark_hive': - background = '#0972A5'; - break; - case 'redmond': - background = '#F5F8F9'; - color = '#E17009'; - break; - case 'start': - background = '#6EAC2C'; - break; - case 'sunny': - background = 'white'; - color = '#0074C7'; - break; - case 'ui_dark': - background = '#F58400'; - break; - default: - background = '#6EAC2C'; - } - } else { - background = '#6EAC2C'; - } - - $('#header').addClass('ui-state-default'); - $('#header').css('border', '0px'); - - // Set theme to user span - $('#login_user').css('color', color); - - // Style for selected page - var style = { - 'background-color': background, - 'color': color - }; + // Enable settings link + $('#xcat_settings').click(function() { + openSettings(); + }); + + // Set header to theme + var background = '', color = ''; + var theme = $.cookie('xcat_theme'); + if (theme) { + switch (theme) { + case 'cupertino': + background = '#3BAAE3'; + color = 'white'; + break; + case 'dark_hive': + background = '#0972A5'; + break; + case 'redmond': + background = '#F5F8F9'; + color = '#E17009'; + break; + case 'start': + background = '#6EAC2C'; + break; + case 'sunny': + background = 'white'; + color = '#0074C7'; + break; + case 'ui_dark': + background = '#F58400'; + break; + default: + background = '#6EAC2C'; + } + } else { + background = '#6EAC2C'; + } + + $('#header').addClass('ui-state-default'); + $('#header').css('border', '0px'); + + // Set theme to user span + $('#login_user').css('color', color); + + // Style for selected page + var style = { + 'background-color': background, + 'color': color + }; - // Get the page being loaded - var url = window.location.pathname; - var page = url.replace('/xcat/', ''); - var headers = $('#header ul li a'); - - // Show the page - $("#content").children().remove(); - if (page == 'configure.php') { - includeJs("js/configure/update.js"); - includeJs("js/configure/discover.js"); - headers.eq(1).css(style); - loadConfigPage(); - } else if (page == 'provision.php') { - includeJs("js/provision/images.js"); - headers.eq(2).css(style); - loadProvisionPage(); - } else if (page == 'monitor.php') { - includeJs("js/monitor/xcatmon.js"); - includeJs("js/monitor/rmcmon.js"); - includeJs("js/monitor/gangliamon.js"); - headers.eq(3).css(style); - loadMonitorPage(); - } else if (page == 'help.php') { - includeJs("js/help/help.js"); - headers.eq(4).css(style); + // Get the page being loaded + var url = window.location.pathname; + var page = url.replace('/xcat/', ''); + var headers = $('#header ul li a'); + + // Show the page + $("#content").children().remove(); + if (page == 'configure.php') { + includeJs("js/configure/update.js"); + includeJs("js/configure/discover.js"); + includeJs("js/configure/service.js"); + headers.eq(1).css(style); + loadConfigPage(); + } else if (page == 'provision.php') { + includeJs("js/provision/images.js"); + headers.eq(2).css(style); + loadProvisionPage(); + } else if (page == 'monitor.php') { + includeJs("js/monitor/xcatmon.js"); + includeJs("js/monitor/rmcmon.js"); + includeJs("js/monitor/gangliamon.js"); + headers.eq(3).css(style); + loadMonitorPage(); + } else if (page == 'help.php') { + includeJs("js/help/help.js"); + headers.eq(4).css(style); loadHelpPage(); - } else { - // Load nodes page by default - includeJs("js/jquery/jquery.topzindex.min.js"); + } else { + // Load nodes page by default + includeJs("js/jquery/jquery.topzindex.min.js"); includeJs("js/nodes/nodeset.js"); includeJs("js/nodes/rnetboot.js"); includeJs("js/nodes/updatenode.js"); includeJs("js/nodes/physical.js"); includeJs("js/nodes/mtm.js"); - headers.eq(0).css(style); - loadNodesPage(); - } + headers.eq(0).css(style); + loadNodesPage(); + } } /** * Include javascript file in * - * @param file - * File to include - * @return Nothing + * @param file File to include */ function includeJs(file) { - var script = $("head script[src='" + file + "']"); + var script = $("head script[src='" + file + "']"); - // If does not contain the javascript - if (!script.length) { - // Append the javascript to - var script = $(''); - script.attr( { - type : 'text/javascript', - src : file - }); + // If does not contain the javascript + if (!script.length) { + // Append the javascript to + var script = $(''); + script.attr( { + type : 'text/javascript', + src : file + }); - $('head').append(script); - } + $('head').append(script); + } } /** * Include CSS link in * - * @param file - * File to include - * @return Nothing + * @param file File to include */ function includeCss(file) { - var link = $("head link[href='" + file + "']"); + var link = $("head link[href='" + file + "']"); - // If does not contain the link - if (!link.length) { - // Append the CSS link to - var link = $(''); - link.attr( { - type : 'text/css', - rel : 'stylesheet', - href : file - }); + // If does not contain the link + if (!link.length) { + // Append the CSS link to + var link = $(''); + link.attr( { + type : 'text/css', + rel : 'stylesheet', + href : file + }); - $('head').append(link); - } + $('head').append(link); + } } /** * Write ajax response to a paragraph * - * @param rsp - * Ajax response - * @param pattern - * Pattern to replace with a break + * @param rsp Ajax response + * @param pattern Pattern to replace with a break * @return Paragraph containing ajax response */ function writeRsp(rsp, pattern) { - // Create paragraph to hold ajax response - var prg = $('
                                                                            ');
                                                                            -	
                                                                            -	for ( var i in rsp) {
                                                                            -		if (rsp[i]) {
                                                                            -			// Create regular expression for given pattern
                                                                            -			// Replace pattern with break
                                                                            -			if (pattern) {
                                                                            -				rsp[i] = rsp[i].replace(new RegExp(pattern, 'g'), '
                                                                            '); - prg.append(rsp[i]); - } else { - prg.append(rsp[i]); - prg.append('
                                                                            '); - } - } - } + // Create paragraph to hold ajax response + var prg = $('
                                                                            ');
                                                                            +    
                                                                            +    for ( var i in rsp) {
                                                                            +        if (rsp[i]) {
                                                                            +            // Create regular expression for given pattern
                                                                            +            // Replace pattern with break
                                                                            +            if (pattern) {
                                                                            +                rsp[i] = rsp[i].replace(new RegExp(pattern, 'g'), '
                                                                            '); + prg.append(rsp[i]); + } else { + prg.append(rsp[i]); + prg.append('
                                                                            '); + } + } + } - return prg; + return prg; } /** * Open a dialog and show given message * - * @param type - * Type of dialog, i.e. warn or info - * @param msg - * Message to show - * @return Nothing + * @param type Type of dialog, i.e. warn or info + * @param msg Message to show */ function openDialog(type, msg) { - var msgDialog; - if (type == "warn") { - // Create warning message - msgDialog = $('
                                                                            ' - + '

                                                                            ' + msg + '

                                                                            ' - + '
                                                                            '); - } else { - // Create info message - msgDialog = $('
                                                                            ' - + '

                                                                            ' + msg + '

                                                                            ' - +'
                                                                            '); - } - - // Open dialog - msgDialog.dialog({ - modal: true, - width: 500, - buttons: { - "Ok": function(){ - $(this).dialog("close"); - } - } - }); + var msgDialog; + if (type == "warn") { + // Create warning message + msgDialog = $('
                                                                            ' + + '

                                                                            ' + msg + '

                                                                            ' + + '
                                                                            '); + } else { + // Create info message + msgDialog = $('
                                                                            ' + + '

                                                                            ' + msg + '

                                                                            ' + +'
                                                                            '); + } + + // Open dialog + msgDialog.dialog({ + modal: true, + close: function(){ + $(this).remove(); + }, + width: 500, + buttons: { + "Ok": function(){ + $(this).dialog("close"); + } + } + }); } /** * Create an iframe to hold the output of an xCAT command * - * @param src - * The URL of the document to show in the iframe + * @param src The URL of the document to show in the iframe * @return Info box containing the iframe */ function createIFrame(src) { - // Put an iframe inside an info box - var infoBar = $('
                                                                            ').css({ - 'margin-bottom': '5px' - }); - - // Create info and close icons - var icon = $('').css({ - 'display': 'inline-block', - 'margin': '10px 5px' - }); - var close = $('').css({ - 'display': 'inline-block', - 'float': 'right', - 'margin': '10px 5px' - }).click(function() { - // Remove info box on-click - $(this).parent().remove(); - }); - - var iframe = $('').attr('src', src).css({ - 'display': 'block', - 'border': '0px', - 'margin': '10px', - 'width': '100%' - }); - - var loader = createLoader('iLoader').css({ - 'display': 'block', - 'margin': '10px 0px' - }); - - infoBar.append(icon); - infoBar.append($('
                                                                            ').append(loader, iframe)); - infoBar.append(close); - - // Remove loader when done - iframe.load(function() { - loader.remove(); - }); - - return infoBar; + // Put an iframe inside an info box + var infoBar = $('
                                                                            ').css({ + 'margin-bottom': '5px' + }); + + // Create info and close icons + var icon = $('').css({ + 'display': 'inline-block', + 'margin': '10px 5px' + }); + var close = $('').css({ + 'display': 'inline-block', + 'float': 'right', + 'margin': '10px 5px' + }).click(function() { + // Remove info box on-click + $(this).parent().remove(); + }); + + var iframe = $('').attr('src', src).css({ + 'display': 'block', + 'border': '0px', + 'margin': '10px', + 'width': '100%' + }); + + var loader = createLoader('iLoader').css({ + 'display': 'block', + 'margin': '10px 0px' + }); + + infoBar.append(icon); + infoBar.append($('
                                                                            ').append(loader, iframe)); + infoBar.append(close); + + // Remove loader when done + iframe.load(function() { + loader.remove(); + }); + + return infoBar; } @@ -798,269 +759,292 @@ function createIFrame(src) { * Open dialog to set xCAT UI settings */ function openSettings() { - // Create form to add node range - var dialog = $('
                                                                            '); - var info = createInfoBar('Select from the following options'); - dialog.append(info); - - var style = { - 'color': 'blue', - 'cursor': 'pointer', - 'padding': '5px' - }; - - var changeThemeOption = $('').css(style); - dialog.append(changeThemeOption); - - var changePasswordOption = $('').css(style); - dialog.append(changePasswordOption); - - // Open form as a dialog - dialog.dialog({ - modal: true, - title: 'Settings', - width: 400, - buttons: { - "Cancel": function(){ - $(this).dialog("close"); - } - } - }); - - // Bind to click event - changeThemeOption.click(function() { - dialog.dialog("close"); - changeTheme(); - }); - - changePasswordOption.click(function() { - dialog.dialog("close"); - changePassword(); - }); + // Create form to add node range + var dialog = $('
                                                                            '); + var info = createInfoBar('Select from the following options'); + dialog.append(info); + + var style = { + 'color': 'blue', + 'cursor': 'pointer', + 'padding': '5px' + }; + + var changeThemeOption = $('').css(style); + dialog.append(changeThemeOption); + + var changePasswordOption = $('').css(style); + dialog.append(changePasswordOption); + + // Open form as a dialog + dialog.dialog({ + modal: true, + close: function(){ + $(this).remove(); + }, + title: 'Settings', + width: 400, + buttons: { + "Cancel": function(){ + $(this).dialog("close"); + } + } + }); + + // Bind to click event + changeThemeOption.click(function() { + dialog.dialog("close"); + changeTheme(); + }); + + changePasswordOption.click(function() { + dialog.dialog("close"); + changePassword(); + }); } /** * Open dialog to change xCAT theme */ function changeTheme() { - // Create form to add node range - var dialog = $('
                                                                            '); - var info = createInfoBar('Select the xCAT theme you desire'); - dialog.append(info); - - // Create select drop down for themes - var themeFS = $('
                                                                            '); - dialog.append(themeFS); - var legend = $('Theme'); - themeFS.append(legend); - var oList = $('
                                                                              '); - oList.append($('
                                                                            1. Cupertino
                                                                            2. ')); - oList.append($('
                                                                            3. Dark Hive
                                                                            4. ')); - oList.append($('
                                                                            5. Redmond
                                                                            6. ')); - oList.append($('
                                                                            7. Start (default)
                                                                            8. ')); - oList.append($('
                                                                            9. Sunny
                                                                            10. ')); - oList.append($('
                                                                            11. UI Darkness
                                                                            12. ')); - themeFS.append(oList); - - if ($.cookie('xcat_theme')) { - // Select theme - oList.find('input[value="' + $.cookie('xcat_theme') + '"]').attr('checked', true); - } else { - oList.find('input[value="start"]').attr('checked', true); - } + // Create form to add node range + var dialog = $('
                                                                              '); + var info = createInfoBar('Select the xCAT theme you desire'); + dialog.append(info); + + // Create select drop down for themes + var oList = $('
                                                                                '); + oList.append($('
                                                                              1. Cupertino
                                                                              2. ')); + oList.append($('
                                                                              3. Dark Hive
                                                                              4. ')); + oList.append($('
                                                                              5. Redmond
                                                                              6. ')); + oList.append($('
                                                                              7. Start (default)
                                                                              8. ')); + oList.append($('
                                                                              9. Sunny
                                                                              10. ')); + oList.append($('
                                                                              11. UI Darkness
                                                                              12. ')); + dialog.append(oList); + + if ($.cookie('xcat_theme')) { + // Select theme + oList.find('input[value="' + $.cookie('xcat_theme') + '"]').attr('checked', true); + } else { + oList.find('input[value="start"]').attr('checked', true); + } - // Open form as a dialog - dialog.dialog({ - modal: true, - title: 'xCAT Theme', - width: 400, - buttons: { - "Ok": function(){ - // Save selected theme - var theme = $(this).find('input[name="theme"]:checked').val(); - $.cookie('xcat_theme', theme); // Do not expire cookie, keep it as long as possible - - // Show instructions to apply theme - $(this).empty(); - var info = createInfoBar('You will need to reload this page in order for changes to take effect'); - $(this).append(info); - - // Only show close button - $(this).dialog("option", "buttons", { - "Close" : function() { - $(this).dialog( "close" ); - } - }); - }, - "Cancel": function(){ - $(this).dialog( "close" ); - } - } - }); + // Open form as a dialog + dialog.dialog({ + modal: true, + close: function(){ + $(this).remove(); + }, + title: 'xCAT Theme', + width: 400, + buttons: { + "Ok": function(){ + // Save selected theme + var theme = $(this).find('input[name="theme"]:checked').val(); + $.cookie('xcat_theme', theme); // Do not expire cookie, keep it as long as possible + + // Show instructions to apply theme + $(this).empty(); + var info = createInfoBar('You will need to reload this page in order for changes to take effect'); + $(this).append(info); + + // Only show close button + $(this).dialog("option", "buttons", { + "Close" : function() { + $(this).dialog( "close" ); + } + }); + }, + "Cancel": function(){ + $(this).dialog( "close" ); + } + } + }); } /** * Open dialog to change user password */ function changePassword() { - // Create form to add node range - var dialog = $('
                                                                                '); - var info = createInfoBar('Change your password'); - dialog.append(info); - - dialog.append('
                                                                                '); - dialog.append('
                                                                                '); - - // Open form as a dialog - dialog.dialog({ - modal: true, - title: 'Change Password', - width: 400, - buttons: { - "Ok": function(){ - // Remove any warning messages - $(this).find('.ui-state-error').remove(); - - var errorMessage = ""; - - // Check each input is provided - $('#changePassword input').each(function() { - if (!$(this).val()) { - errorMessage = "Please provide a value for each missing input!"; - } - }); - - // Do not continue if error found - if (errorMessage) { - dialog.prepend(createWarnBar(errorMessage)); - return; - } - - // Check new and confirm passwords match - var user = $.cookie('xcat_username'); - var newPassword = $('#changePassword input[name="newPassword"]').val(); - var confirmPassword = $('#changePassword input[name="confirmPassword"]').val(); - if (newPassword != confirmPassword) { - dialog.prepend(createWarnBar("Please confirm new password!")); - return; - } - - // Change dialog buttons - $('#changePassword').dialog('option', 'buttons', { - 'Close':function(){ - $('#changePassword').dialog('close'); - } - }); - - // Send request to change password - var url = window.location.pathname; - var page = url.replace('/xcat/', ''); - var url = 'lib/cmd.php'; - // Service portal does not have access to cmd.php - if (page == 'service.php') - url = 'lib/srv_cmd.php'; - $.ajax( { - url : url, - dataType : 'json', - data : { - cmd : 'webrun', - tgt : '', - args : 'passwd;' + user + ';' + newPassword, - msg : '' - }, - - success : function (data) { - // Show response message - var rspMessage = ""; - for (var i in data.rsp) - rspMessage += data.rsp[i] + "
                                                                                "; - - $('#changePassword').prepend(createInfoBar(rspMessage)); - } - }); - }, - "Cancel": function(){ - $(this).dialog( "close" ); - } - } - }); + // Create form to add node range + var dialog = $('
                                                                                '); + var info = createInfoBar('Change your password'); + dialog.append(info); + + dialog.append('
                                                                                '); + dialog.append('
                                                                                '); + + // Open form as a dialog + dialog.dialog({ + modal: true, + close: function(){ + $(this).remove(); + }, + title: 'Change Password', + width: 400, + buttons: { + "Ok": function(){ + // Remove any warning messages + $(this).find('.ui-state-error').remove(); + + var errorMessage = ""; + + // Check each input is provided + $('#changePassword input').each(function() { + if (!$(this).val()) { + errorMessage = "Please provide a value for each missing input!"; + } + }); + + // Do not continue if error found + if (errorMessage) { + dialog.prepend(createWarnBar(errorMessage)); + return; + } + + // Check new and confirm passwords match + var user = $.cookie('xcat_username'); + var newPassword = $('#changePassword input[name="newPassword"]').val(); + var confirmPassword = $('#changePassword input[name="confirmPassword"]').val(); + if (newPassword != confirmPassword) { + dialog.prepend(createWarnBar("Please confirm new password!")); + return; + } + + // Change dialog buttons + $('#changePassword').dialog('option', 'buttons', { + 'Close':function(){ + $('#changePassword').dialog('close'); + } + }); + + // Send request to change password + var url = window.location.pathname; + var page = url.replace('/xcat/', ''); + var url = 'lib/cmd.php'; + // Service portal does not have access to cmd.php + if (page == 'service.php') + url = 'lib/srv_cmd.php'; + $.ajax( { + url : url, + dataType : 'json', + data : { + cmd : 'webrun', + tgt : '', + args : 'passwd;' + user + ';' + newPassword, + msg : '' + }, + + success : function (data) { + // Show response message + var rspMessage = ""; + for (var i in data.rsp) + rspMessage += data.rsp[i] + "
                                                                                "; + + $('#changePassword').prepend(createInfoBar(rspMessage)); + } + }); + }, + "Cancel": function(){ + $(this).dialog( "close" ); + } + } + }); } /** * Adjust datatable column size * - * @param tableId - * Table ID - * @return Nothing + * @param tableId Table ID */ function adjustColumnSize(tableId) { - var cols = $('#' + tableId).find('tbody tr:eq(0) td'); - - // If the column size is zero, wait until table is initialized - if (!cols.eq(1).outerWidth()) { - adjustColumnSize(tableId); - } else { - for (var i in cols) { - var headers = $('#' + tableId + '_wrapper .dataTables_scrollHead .datatable thead tr th').eq(i); - headers.css('width', cols.eq(i).outerWidth()); - } - } + var cols = $('#' + tableId).find('tbody tr:eq(0) td'); + // If the column size is zero, wait until table is initialized + if (cols.eq(1).outerWidth()) { + for (var i in cols) { + var headers = $('#' + tableId + '_wrapper .dataTables_scrollHead .datatable thead tr th').eq(i); + headers.css('width', cols.eq(i).outerWidth()); + } + } } /** * Set menu theme * - * @param menu - * Menu object - * @return Nothing + * @param menu Menu object */ function setMenu2Theme(menu) { - // On hover - var background = '', color = ''; - var theme = $.cookie('xcat_theme'); - if (theme) { - switch (theme) { - case 'cupertino': - background = '#3BAAE3'; - color = 'white'; - break; - case 'dark_hive': - background = '#0972A5'; - break; - case 'redmond': - background = '#F5F8F9'; - color = '#E17009'; - break; - case 'start': - background = '#6EAC2C'; - break; - case 'sunny': - background = 'white'; - color = '#0074C7'; - break; - case 'ui_dark': - background = '#F58400'; - break; - default: - background = '#6EAC2C'; - } - } else { - background = '#6EAC2C'; - } - - menu.css('background', background); - menu.find('a:eq(0)').css('color', color); + // On hover + var background = '', color = ''; + var theme = $.cookie('xcat_theme'); + if (theme) { + switch (theme) { + case 'cupertino': + background = '#3BAAE3'; + color = 'white'; + break; + case 'dark_hive': + background = '#0972A5'; + break; + case 'redmond': + background = '#F5F8F9'; + color = '#E17009'; + break; + case 'start': + background = '#6EAC2C'; + break; + case 'sunny': + background = 'white'; + color = '#0074C7'; + break; + case 'ui_dark': + background = '#F58400'; + break; + default: + background = '#6EAC2C'; + } + } else { + background = '#6EAC2C'; + } + + menu.css('background', background); + menu.find('a:eq(0)').css('color', color); } /** * Set menu back to normal before applying theme * - * @param menu - * Menu object - * @return Nothing + * @param menu Menu object */ function setMenu2Normal(menu) { - // Change back to normal - menu.css('background', ''); - menu.find('a:eq(0)').css('color', ''); + // Change back to normal + menu.css('background', ''); + menu.find('a:eq(0)').css('color', ''); +} + +/** + * Get nodes that are checked in a given datatable + * + * @param datatableId The datatable ID + * @return Nodes that were checked + */ +function getNodesChecked(datatableId) { + var tgts = ''; + + // Get nodes that were checked + var nodes = $('#' + datatableId + ' input[type=checkbox]:checked'); + for (var i in nodes) { + var tgtNode = nodes.eq(i).attr('name'); + + if (tgtNode){ + tgts += tgtNode; + + // Add a comma at the end + if (i < nodes.length - 1) { + tgts += ','; + } + } + } + + return tgts; } \ No newline at end of file diff --git a/xCAT-UI/js/xcatauth.js b/xCAT-UI/js/xcatauth.js index 9d615b349..ef363759d 100644 --- a/xCAT-UI/js/xcatauth.js +++ b/xCAT-UI/js/xcatauth.js @@ -13,95 +13,90 @@ $(document).ready(function() { // The window's height is to small to show the dialog var tempheight = 0; if ((winheight - 50) < diaheight){ - tempheight = 0; + tempheight = 0; } else { - tempheight = parseInt((winheight - diaheight - 50) / 2); + tempheight = parseInt((winheight - diaheight - 50) / 2); } $('#login').css('margin', tempheight + 'px auto'); $('button').bind('click', function(){ - authenticate(); + authenticate(); }); $('#login button').button(); - if (document.location.protocol == "http:") { - $("#login_status").html("You are using an unencrypted session!"); - $("#login_status").css("color", "#ff0000"); - } - - if ($("#login input[name='username']").val() == "") { - $("#login input[name='username']").focus(); - } else { - $("#login input[name='password']").focus(); - } + if (document.location.protocol == "http:") { + $("#login-status").html("You are using an unencrypted session!"); + $("#login-status").css("color", "#ff0000"); + } + + if ($("#login input[name='username']").val() == "") { + $("#login input[name='username']").focus(); + } else { + $("#login input[name='password']").focus(); + } - // When enter is hit while in username, advance to password - $("#login input[name='username']").keydown(function(event) { - if (event.keyCode == 13) { - $("#login input[name='password']").focus(); - } - }); + // When enter is hit while in username, advance to password + $("#login input[name='username']").keydown(function(event) { + if (event.keyCode == 13) { + $("#login input[name='password']").focus(); + } + }); - // Submit authentication if enter is pressed in password field - $("#login input[name='password']").keydown(function(event) { - if (event.keyCode == 13) { - authenticate(); - } - }); + // Submit authentication if enter is pressed in password field + $("#login input[name='password']").keydown(function(event) { + if (event.keyCode == 13) { + authenticate(); + } + }); }); /** * Update login dialog * - * @param data - * Data returned from AJAX call - * @param txtStatus - * Status of login - * @return + * @param data Data returned from AJAX call + * @param txtStatus Status of login */ function onlogin(data, txtStatus) { - // Clear password field regardless of what happens - $("#login input[name='password']").val(""); - if (data.authenticated == "yes") { - $("#login_status").text("Login successful"); + // Clear password field regardless of what happens + $("#login input[name='password']").val(""); + if (data.authenticated == "yes") { + $("#login-status").text("Login successful"); - // Not the first time to log - if ($.cookie('logonflag')){ - // Remembered what page they were trying to go to - window.location = window.location.pathname; - } else { - window.location = 'help.php'; - } - - // Set user name cookie - var usrName = $("#login input[name='username']").val(); - var exDate = new Date(); - exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); - $.cookie('xcat_username', usrName, { expires: exDate }); - - // Set the logonflag - $.cookie('logonflag', 'yes', { - path : '/xcat', - expires : 100 - }); - - } else { - $("#login_status").text("Authentication failure").css("color", "#FF0000"); - } + // Not the first time to log + if ($.cookie('logonflag')){ + // Remembered what page they were trying to go to + window.location = window.location.pathname; + } else { + window.location = 'help.php'; + } + + // Set user name cookie + var usrName = $("#login input[name='username']").val(); + var exDate = new Date(); + exDate.setTime(exDate.getTime() + (240 * 60 * 1000)); + $.cookie('xcat_username', usrName, { expires: exDate }); + + // Set the logonflag + $.cookie('logonflag', 'yes', { + path : '/xcat', + expires : 100 + }); + + } else { + $("#login-status").text("Authentication failure").css("color", "#FF0000"); + } } /** * Authenticate user for new session - * - * @return Nothing */ function authenticate() { - $("#login_status").css("color", "#000000"); - $("#login_status").html('Authenticating...'); - var passwd = $("#login input[name='password']").val(); - $.post("lib/log.php", { - username : $("#login input[name='username']").val(), - password : passwd - }, onlogin, "json"); + $("#login-status").css("color", "#000000"); + $("#login-status").html('Authenticating...'); + var passwd = $("#login input[name='password']").val(); + $.post("lib/log.php", { + username : $("#login input[name='username']").val(), + password : passwd + }, onlogin, "json"); } diff --git a/xCAT-UI/lib/cmd.php b/xCAT-UI/lib/cmd.php index 7fde777f3..d272b9d79 100644 --- a/xCAT-UI/lib/cmd.php +++ b/xCAT-UI/lib/cmd.php @@ -6,21 +6,26 @@ require_once "$TOPDIR/lib/jsonwrapper.php"; /** * Issue a xCAT command, e.g. rinv gpok123 all - * This will handle most commands. If not, you can create your - * own .php. Look at zCmd.php for an example. + * This will handle most commands. If not, you can create your own .php. + * Look at zCmd.php for an example. * - * @param $cmd The xCAT command - * @param $tgt The target node or group - * @param $args The xCAT command arguments, separated by semicolons - * @param $opts The xCAT command options, separated by semicolons - * @return The xCAT response. Replies are in the form of JSON + * @param $cmd The xCAT command + * @param $tgt The target node or group + * @param $args The xCAT command arguments, separated by semicolons + * @param $opts The xCAT command options, separated by semicolons + * @return The xCAT response. Replies are in the form of JSON */ if (isset($_GET["cmd"])) { // HTTP GET requests $cmd = $_GET["cmd"]; $tgt = $_GET["tgt"]; $args = $_GET["args"]; - + + // File contents in case of file write + if (isset($_GET["cont"])) { + $cont = $_GET["cont"]; + } + // Special messages put here // This gets sent back to the AJAX request as is. $msg = $_GET["msg"]; @@ -29,7 +34,7 @@ if (isset($_GET["cmd"])) { if (!$tgt) { $tgt = NULL; } - + // If no $msg is given, set $msg to NULL if (!$msg) { $msg = NULL; @@ -47,12 +52,12 @@ if (isset($_GET["cmd"])) { $args_array = array($args); } } - + // If no $opts are given, set $opts_array to NULL $opts_array = array(); if (isset($_GET["opts"])) { $opts = $_GET["opts"]; - + // If $args contains multiple arguments, split it into an array if (strpos($opts,";")) { // Split the arguments into an array @@ -69,7 +74,7 @@ if (isset($_GET["cmd"])) { if (in_array("flush", $opts_array)) { return; } - + $rsp = array(); // webrun pping and gangliastatus output needs special handling @@ -86,26 +91,37 @@ if (isset($_GET["cmd"])) { else if(strncasecmp($cmd, "extnoderange", 12) == 0) { $rsp = extractExtnoderange($xml); } + // Write contents to file + else if(strncasecmp($cmd, "write", 4) == 0) { + // Directory should be /var/opt/xcat/profiles + // You can write anything to that directory + $file = "$tgt"; + $handle = fopen($file, 'w') or die("Cannot open $file"); + fwrite($handle, $cont); + fclose($handle); + + $rsp = "Directory entry written to $file"; + } // Handle the typical output else { foreach ($xml->children() as $child) { foreach ($child->children() as $data) { if($data->name) { $node = $data->name; - + if ($data->data->contents) { $cont = $data->data->contents; } else { $cont = $data->data; } - + if ($data->data->desc) { $cont = $data->data->desc . ": " . $cont; } - + $cont = str_replace(":|:", "\n", $cont); array_push($rsp, "$node: $cont"); - } else if(strlen("$data") > 2) { + } else if (strlen("$data") > 2) { $data = str_replace(":|:", "\n", $data); array_push($rsp, "$data"); } @@ -121,8 +137,8 @@ if (isset($_GET["cmd"])) { /** * Extract the output for a webrun command * - * @param $xml The XML output from docmd() - * @return An array containing the output + * @param $xml The XML output from docmd() + * @return An array containing the output */ function extractWebrun($xml) { $rsp = array(); @@ -133,7 +149,7 @@ function extractWebrun($xml) { foreach($nodes->children() as $node){ // Get the node name $name = $node->name; - + // Get the content $status = $node->data; $status = str_replace(":|:", "\n", $status); @@ -150,8 +166,8 @@ function extractWebrun($xml) { /** * Extract the output for a nodels command * - * @param $xml The XML output from docmd() - * @return An array containing the output + * @param $xml The XML output from docmd() + * @return An array containing the output */ function extractNodels($xml) { $rsp = array(); @@ -179,8 +195,8 @@ function extractNodels($xml) { /** * Extract the output for a extnoderange command * - * @param $xml The XML output from docmd() - * @return The nodes and groups + * @param $xml The XML output from docmd() + * @return The nodes and groups */ function extractExtnoderange($xml) { $rsp = array(); diff --git a/xCAT-UI/lib/functions.php b/xCAT-UI/lib/functions.php index c1e23b5eb..52935d368 100644 --- a/xCAT-UI/lib/functions.php +++ b/xCAT-UI/lib/functions.php @@ -5,22 +5,21 @@ // Retain session variables across page requests session_start(); -session_write_close(); // Do not block HTTP requests +session_write_close(); // Do not block other HTTP requests -// The settings below display error on the screen, -// instead of giving blank pages. +// The settings below display error on the screen, instead of giving blank pages. error_reporting(E_ALL); ini_set('display_errors', true); /** * Run a command using the xCAT client/server protocol * - * @param $cmd The xCAT command - * @param $nr Node range or group - * @param $args_array Command arguments - * @param $opts_array Command options - * @return A tree of SimpleXML objects. - * See perl-xCAT/xCAT/Client.pm for the format + * @param $cmd The xCAT command + * @param $nr Node range or group + * @param $args_array Command arguments + * @param $opts_array Command options + * @return A tree of SimpleXML objects. + * See perl-xCAT/xCAT/Client.pm for the format */ function docmd($cmd, $nr, $args_array, $opts_array){ // If we are not logged in, @@ -34,7 +33,9 @@ function docmd($cmd, $nr, $args_array, $opts_array){ // Add command, node range, and arguments to request $request = simplexml_load_string(''); $request->addChild('command', $cmd); - if(!empty($nr)) { $request->addChild('noderange', $nr); } + if (!empty($nr)) { + $request->addChild('noderange', $nr); + } if (!empty($args_array)) { foreach ($args_array as $a) { $request->addChild('arg',$a); @@ -53,9 +54,9 @@ function docmd($cmd, $nr, $args_array, $opts_array){ /** * Used by docmd() to submit request to xCAT * - * @param $req Tree of SimpleXML objects - * @param $opts_array Request options - * @return A tree of SimpleXML objects + * @param $req Tree of SimpleXML objects + * @param $opts_array Request options + * @return A tree of SimpleXML objects */ function submit_request($req, $skipVerify, $opts_array){ $xcathost = "localhost"; @@ -63,46 +64,46 @@ function submit_request($req, $skipVerify, $opts_array){ $rsp = FALSE; $response = ''; $cleanexit = 0; - + // Determine whether to flush output or not $flush = false; if ($opts_array && in_array("flush", $opts_array)) { $flush = true; } - + // Determine how to handle the flush output // You can specify a function name, in place of TBD, to handle the flush output $flush_format = ""; if ($opts_array && in_array("flush-format=TBD", $opts_array)) { $flush_format = "TBD"; } - - // Open syslog, include the process ID and also send - // the log to standard error, and use a user defined - // logging mechanism + + // Open syslog, include the process ID and also send the log to standard error, + // and use a user defined logging mechanism openlog("xCAT-UI", LOG_PID | LOG_PERROR, LOG_LOCAL0); // Open a socket to xcatd syslog(LOG_INFO, "Opening socket to xcatd..."); - if($fp = stream_socket_client('ssl://'.$xcathost.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT)){ + if ($fp = stream_socket_client('ssl://'.$xcathost.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT)){ $reqXML = $req->asXML(); $nr = $req->noderange; $cmd = $req->command; - + syslog(LOG_INFO, "Sending request: $cmd $nr"); - stream_set_blocking($fp, 0); // Set as non-blocking - fwrite($fp,$req->asXML()); // Send XML to xcatd - set_time_limit(900); // Set 15 minutes timeout (for long running requests) - // The default is 30 seconds which is too short for some requests - + stream_set_blocking($fp, 0); // Set as non-blocking + fwrite($fp,$req->asXML()); // Send XML to xcatd + set_time_limit(900); // Set 15 minutes timeout (for long running requests) + // The default is 30 seconds which is too short for some requests + // Turn on output buffering ob_start(); - while(!feof($fp)) { // Read until there is no more + while (!feof($fp)) { + // Read until there is no more // Remove newlines and add it to the response $str = fread($fp, 8192); if ($str) { $response .= preg_replace('/>\n\s*<', $str); - + // Flush output to browser if ($flush) { // Strip HTML tags from output @@ -117,50 +118,48 @@ function submit_request($req, $skipVerify, $opts_array){ flush(); } } - } + } } - + // Look for serverdone response $fullpattern = '/\s*\s*<\/serverdone>\s*<\/xcatresponse>/'; $mixedpattern = '/\s*<\/serverdone>.*<\/xcatresponse>/'; $recentpattern = '/<\/xcatresponse>/'; - if(preg_match($recentpattern,$str) && preg_match($mixedpattern,$response)) { - // Transaction is done, - // Package up XML and return it + if (preg_match($recentpattern,$str) && preg_match($mixedpattern,$response)) { + // Transaction is done, package up XML and return it // Remove the serverdone response and put an xcat tag around the rest $count = 0; - $response = preg_replace($fullpattern,'', $response, -1, $count); // 1st try to remove the long pattern - if (!$count) { $response = preg_replace($mixedpattern,'', $response) . '/'; } // if its not there, then remove the short pattern + $response = preg_replace($fullpattern,'', $response, -1, $count); // 1st try to remove the long pattern + if (!$count) { + $response = preg_replace($mixedpattern,'', $response) . '/'; + } $response = "$response"; - //delete the \n between '>' and '<' $response = preg_replace('/>\n\s*<', $response); - //replace the '\n' by ':|:' in the data area. $response = preg_replace('/\n/', ':|:', $response); $rsp = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); $cleanexit = 1; break; } } // End of while(!feof($fp)) - + syslog(LOG_INFO, "($cmd $nr) Sending response"); fclose($fp); } else { echo "

                                                                                xCAT submit request socket error: $errno - $errstr

                                                                                "; } - + // Flush (send) the output buffer and turn off output buffering ob_end_flush(); // Close syslog closelog(); - + if(! $cleanexit) { if (preg_match('/^\s*.*<\/xcatresponse>\s*$/',$response)) { // Probably an error message $response = "$response"; $rsp = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); - } - elseif(!$skipVerify) { + } else if(!$skipVerify) { echo "

                                                                                (Error) xCAT response ended prematurely: ", htmlentities($response), "

                                                                                "; $rsp = FALSE; } @@ -170,10 +169,6 @@ function submit_request($req, $skipVerify, $opts_array){ /** * Enable password storage to split between cookie and session variable - * - * @param $data - * @param $key - * @return */ function xorcrypt($data, $key) { $datalen = strlen($data); @@ -187,9 +182,6 @@ function xorcrypt($data, $key) { /** * Get password - * - * @param Nothing - * @return */ function getpassword() { if (isset($GLOBALS['xcatauthsecret'])) { @@ -204,13 +196,11 @@ function getpassword() { } /** - * Get the password splitting knowledge between server - * and client side persistant storage. Caller should regenerate - * session ID when contemplating a new user/password, to preclude - * session fixation, though fixation is limited without the secret. + * Get the password splitting knowledge between server and client side persistant storage. + * Caller should regenerate session ID when contemplating a new user/password, + * to preclude session fixation, though fixation is limited without the secret. * - * @param $password Password - * @return Nothing + * @param $password Password */ function setpassword($password) { $randlen = strlen($password); @@ -227,8 +217,8 @@ function setpassword($password) { /** * Get RAND characters * - * @param $length Length of characters - * @return RAND characters + * @param $length Length of characters + * @return RAND characters */ function getrandchars($length) { $charset = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*'; @@ -246,9 +236,7 @@ function getrandchars($length) { /** * Determine if a user/password session exists * - * @param Nothing - * @return True If user has a session. - * False Otherwise + * @return True if user has a session, false otherwise */ function is_logged() { if (isset($_SESSION["username"]) and !is_bool(getpassword())) { @@ -260,10 +248,8 @@ function is_logged() { /** * Determine if a user is currently logged in successfully - * - * @param Nothing - * @return True If the user is currently logged in successfully - * False Otherwise + * + * @return True if the user is currently logged in successfully, false otherwise */ function isAuthenticated() { if (is_logged()) { @@ -290,12 +276,10 @@ function isAuthenticated() { } /** -* Determine if a user has root access -* -* @param Nothing -* @return True If the user has root access -* False Otherwise -*/ + * Determine if a user has root access + * + * @return True if the user has root access, false otherwise + */ function isRootAcess() { if (is_logged() && $_SESSION["xcatpassvalid"]) { $testacc = docmd('tabdump', '', array('policy', '-w', "name==" . $_SESSION["username"]), array()); @@ -304,7 +288,7 @@ function isRootAcess() { $result = str_replace('"', '', $result); $args = array(); $args = explode(",", $result); - + // Get the comments which contains the privilege $comments = $args[8]; $args = explode(";", $comments); @@ -319,13 +303,13 @@ function isRootAcess() { $privilege = 'root'; $_SESSION["xcatpassvalid"] = 1; } - + break; - } + } } } } - + if (strcmp($_SESSION["username"], 'root') == 0) { $_SESSION["xcatpassvalid"] = 1; } @@ -338,10 +322,7 @@ function isRootAcess() { } /** - * Log out of the current user session - * - * @param Nothing - * @return Nothing + * Log out of current user session */ function logout() { // Clear the secret cookie from browser @@ -360,12 +341,9 @@ function logout() { /** * Format a given string and echo it back to the browser - * - * @param $str String - * @return Nothing */ function format_TBD($str) { - // Format a given string however you want it + // Format a given string however you want it echo $tmp . '
                                                                                '; flush(); } diff --git a/xCAT-UI/lib/rcons.php b/xCAT-UI/lib/rcons.php index 5ddc2825a..d27960aa2 100644 --- a/xCAT-UI/lib/rcons.php +++ b/xCAT-UI/lib/rcons.php @@ -77,14 +77,14 @@ function rconsSynchronise($parameter) { if (0 == strlen($line)) { continue; } - + if ('<' == substr($line, 0, 1)) { $flag = true; $return .= $line; break; } } - + if ($flag) { while (!feof($fp)) { $return .= fgets($fp, 1024); diff --git a/xCAT-UI/lib/srv_cmd.php b/xCAT-UI/lib/srv_cmd.php index 3798fab27..ae3b4878b 100644 --- a/xCAT-UI/lib/srv_cmd.php +++ b/xCAT-UI/lib/srv_cmd.php @@ -5,22 +5,21 @@ require_once "$TOPDIR/lib/srv_functions.php"; require_once "$TOPDIR/lib/jsonwrapper.php"; /** - * Issue a xCAT command, e.g. rinv gpok123 all - * This will handle most commands. If not, you can create your - * own .php. Look at zCmd.php for an example. + * Issue a xCAT command, e.g. rinv gpok123 all. This will handle most commands. + * If not, you can create your own .php. Look at zCmd.php for an example. * - * @param $cmd The xCAT command - * @param $tgt The target node or group - * @param $args The xCAT command arguments, separated by semicolons - * @param $opts The xCAT command options, separated by semicolons - * @return The xCAT response. Replies are in the form of JSON + * @param $cmd The xCAT command + * @param $tgt The target node or group + * @param $args The xCAT command arguments, separated by semicolons + * @param $opts The xCAT command options, separated by semicolons + * @return The xCAT response. Replies are in the form of JSON */ if (isset($_GET["cmd"])) { // HTTP GET requests $cmd = $_GET["cmd"]; $tgt = $_GET["tgt"]; $args = $_GET["args"]; - + // Special messages put here // This gets sent back to the AJAX request as is. $msg = $_GET["msg"]; @@ -29,7 +28,7 @@ if (isset($_GET["cmd"])) { if (!$tgt) { $tgt = NULL; } - + // If no $msg is given, set $msg to NULL if (!$msg) { $msg = NULL; @@ -47,12 +46,12 @@ if (isset($_GET["cmd"])) { $args_array = array($args); } } - + // If no $opts are given, set $opts_array to NULL $opts_array = array(); if (isset($_GET["opts"])) { $opts = $_GET["opts"]; - + // If $args contains multiple arguments, split it into an array if (strpos($opts,";")) { // Split the arguments into an array @@ -69,7 +68,7 @@ if (isset($_GET["cmd"])) { if (in_array("flush", $opts_array)) { return; } - + $rsp = array(); // webrun pping and gangliastatus output needs special handling @@ -92,17 +91,16 @@ if (isset($_GET["cmd"])) { foreach ($child->children() as $data) { if($data->name) { $node = $data->name; - + if($data->data->contents){ $cont = $data->data->contents; - } - else{ + } else { $cont = $data->data; } - + $cont = str_replace(":|:", "\n", $cont); array_push($rsp, "$node: $cont"); - } else if(strlen("$data") > 2) { + } else if (strlen("$data") > 2) { $data = str_replace(":|:", "\n", $data); array_push($rsp, "$data"); } @@ -118,8 +116,8 @@ if (isset($_GET["cmd"])) { /** * Extract the output for a webrun command * - * @param $xml The XML output from docmd() - * @return An array containing the output + * @param $xml The XML output from docmd() + * @return An array containing the output */ function extractWebrun($xml) { $rsp = array(); @@ -130,7 +128,7 @@ function extractWebrun($xml) { foreach($nodes->children() as $node){ // Get the node name $name = $node->name; - + // Get the content $status = $node->data; $status = str_replace(":|:", "\n", $status); @@ -147,8 +145,8 @@ function extractWebrun($xml) { /** * Extract the output for a nodels command * - * @param $xml The XML output from docmd() - * @return An array containing the output + * @param $xml The XML output from docmd() + * @return An array containing the output */ function extractNodels($xml) { $rsp = array(); @@ -176,8 +174,8 @@ function extractNodels($xml) { /** * Extract the output for a extnoderange command * - * @param $xml The XML output from docmd() - * @return The nodes and groups + * @param $xml The XML output from docmd() + * @return The nodes and groups */ function extractExtnoderange($xml) { $rsp = array(); diff --git a/xCAT-UI/lib/srv_functions.php b/xCAT-UI/lib/srv_functions.php index 624db7687..c18a336fb 100644 --- a/xCAT-UI/lib/srv_functions.php +++ b/xCAT-UI/lib/srv_functions.php @@ -5,7 +5,7 @@ // Retain session variables across page requests session_start(); -session_write_close(); // Do not block HTTP requests +session_write_close(); // Do not block HTTP requests // The settings below display error on the screen, // instead of giving blank pages. @@ -15,310 +15,286 @@ ini_set('display_errors', true); /** * Run a command using the xCAT client/server protocol * - * @param $cmd The xCAT command - * @param $nr Node range or group - * @param $args_array Command arguments - * @param $opts_array Command options - * @return A tree of SimpleXML objects. - * See perl-xCAT/xCAT/Client.pm for the format + * @param $cmd The xCAT command + * @param $nr Node range or group + * @param $args_array Command arguments + * @param $opts_array Command options + * @return A tree of SimpleXML objects. See perl-xCAT/xCAT/Client.pm for the format */ function docmd($cmd, $nr, $args_array, $opts_array){ - // If we are not logged in, - // do not try to communicate with xcatd - if (!is_logged()) { - echo "

                                                                                You are not logged in! Failed to run command.

                                                                                "; - return simplexml_load_string('', 'SimpleXMLElement', LIBXML_NOCDATA); - } + // If we are not logged in, + // do not try to communicate with xcatd + if (!is_logged()) { + echo "

                                                                                You are not logged in! Failed to run command.

                                                                                "; + return simplexml_load_string('', 'SimpleXMLElement', LIBXML_NOCDATA); + } - // Create xCAT request - // Add command, node range, and arguments to request - $request = simplexml_load_string(''); - $request->addChild('command', $cmd); - if(!empty($nr)) { $request->addChild('noderange', $nr); } - if (!empty($args_array)) { - foreach ($args_array as $a) { - $request->addChild('arg',$a); - } - } + // Create xCAT request + // Add command, node range, and arguments to request + $request = simplexml_load_string(''); + $request->addChild('command', $cmd); + if (!empty($nr)) { $request->addChild('noderange', $nr); } + if (!empty($args_array)) { + foreach ($args_array as $a) { + $request->addChild('arg',$a); + } + } - // Add user and password to request - $usernode=$request->addChild('becomeuser'); - $usernode->addChild('username',$_SESSION["srv_username"]); - $usernode->addChild('password',getpassword()); + // Add user and password to request + $usernode=$request->addChild('becomeuser'); + $usernode->addChild('username',$_SESSION["srv_username"]); + $usernode->addChild('password',getpassword()); - $xml = submit_request($request, 0, $opts_array); - return $xml; + $xml = submit_request($request, 0, $opts_array); + return $xml; } /** * Used by docmd() to submit request to xCAT * - * @param $req Tree of SimpleXML objects - * @param $opts_array Request options - * @return A tree of SimpleXML objects + * @param $req Tree of SimpleXML objects + * @param $opts_array Request options + * @return A tree of SimpleXML objects */ function submit_request($req, $skipVerify, $opts_array){ - $xcathost = "localhost"; - $port = "3001"; - $rsp = FALSE; - $response = ''; - $cleanexit = 0; - - // Determine whether to flush output or not - $flush = false; - if ($opts_array && in_array("flush", $opts_array)) { - $flush = true; - } - - // Determine how to handle the flush output - // You can specify a function name, in place of TBD, to handle the flush output - $flush_format = ""; - if ($opts_array && in_array("flush-format=TBD", $opts_array)) { - $flush_format = "TBD"; - } - - // Open syslog, include the process ID and also send - // the log to standard error, and use a user defined - // logging mechanism - openlog("xCAT-UI", LOG_PID | LOG_PERROR, LOG_LOCAL0); + $xcathost = "localhost"; + $port = "3001"; + $rsp = FALSE; + $response = ''; + $cleanexit = 0; + + // Determine whether to flush output or not + $flush = false; + if ($opts_array && in_array("flush", $opts_array)) { + $flush = true; + } + + // Determine how to handle the flush output + // You can specify a function name, in place of TBD, to handle the flush output + $flush_format = ""; + if ($opts_array && in_array("flush-format=TBD", $opts_array)) { + $flush_format = "TBD"; + } + + // Open syslog, include the process ID and also send + // the log to standard error, and use a user defined + // logging mechanism + openlog("xCAT-UI", LOG_PID | LOG_PERROR, LOG_LOCAL0); - // Open a socket to xcatd - syslog(LOG_INFO, "Opening socket to xcatd..."); - if($fp = stream_socket_client('ssl://'.$xcathost.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT)){ - $reqXML = $req->asXML(); - $nr = $req->noderange; - $cmd = $req->command; - - syslog(LOG_INFO, "Sending request: $cmd $nr"); - stream_set_blocking($fp, 0); // Set as non-blocking - fwrite($fp,$req->asXML()); // Send XML to xcatd - set_time_limit(900); // Set 15 minutes timeout (for long running requests) - // The default is 30 seconds which is too short for some requests - - // Turn on output buffering - ob_start(); - while(!feof($fp)) { // Read until there is no more - // Remove newlines and add it to the response - $str = fread($fp, 8192); - if ($str) { - $response .= preg_replace('/>\n\s*<', $str); - - // Flush output to browser - if ($flush) { - // Strip HTML tags from output - if ($tmp = trim(strip_tags($str))) { - // Format the output based on what was given for $flush_format - if ($flush_format == "TDB") { - format_TBD($tmp); - } else { - // Print out output by default - echo '
                                                                                ' . $tmp . '
                                                                                '; - ob_flush(); - flush(); - } - } - } - } - - // Look for serverdone response - $fullpattern = '/\s*\s*<\/serverdone>\s*<\/xcatresponse>/'; - $mixedpattern = '/\s*<\/serverdone>.*<\/xcatresponse>/'; - $recentpattern = '/<\/xcatresponse>/'; - if(preg_match($recentpattern,$str) && preg_match($mixedpattern,$response)) { - // Transaction is done, - // Package up XML and return it - // Remove the serverdone response and put an xcat tag around the rest - $count = 0; - $response = preg_replace($fullpattern,'', $response, -1, $count); // 1st try to remove the long pattern - if (!$count) { $response = preg_replace($mixedpattern,'', $response) . '/'; } // if its not there, then remove the short pattern - $response = "$response"; - //delete the \n between '>' and '<' - $response = preg_replace('/>\n\s*<', $response); - //replace the '\n' by ':|:' in the data area. - $response = preg_replace('/\n/', ':|:', $response); - $rsp = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); - $cleanexit = 1; - break; - } - } // End of while(!feof($fp)) - - syslog(LOG_INFO, "($cmd $nr) Sending response"); - fclose($fp); - } else { - echo "

                                                                                xCAT submit request socket error: $errno - $errstr

                                                                                "; - } - - // Flush (send) the output buffer and turn off output buffering - ob_end_flush(); + // Open a socket to xcatd + syslog(LOG_INFO, "Opening socket to xcatd..."); + if ($fp = stream_socket_client('ssl://'.$xcathost.':'.$port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT)){ + $reqXML = $req->asXML(); + $nr = $req->noderange; + $cmd = $req->command; + + syslog(LOG_INFO, "Sending request: $cmd $nr"); + stream_set_blocking($fp, 0); // Set as non-blocking + fwrite($fp,$req->asXML()); // Send XML to xcatd + set_time_limit(900); // Set 15 minutes timeout (for long running requests) + // The default is 30 seconds which is too short for some requests + + // Turn on output buffering + ob_start(); + while(!feof($fp)) { // Read until there is no more + // Remove newlines and add it to the response + $str = fread($fp, 8192); + if ($str) { + $response .= preg_replace('/>\n\s*<', $str); + + // Flush output to browser + if ($flush) { + // Strip HTML tags from output + if ($tmp = trim(strip_tags($str))) { + // Format the output based on what was given for $flush_format + if ($flush_format == "TDB") { + format_TBD($tmp); + } else { + // Print out output by default + echo '
                                                                                ' . $tmp . '
                                                                                '; + ob_flush(); + flush(); + } + } + } + } + + // Look for serverdone response + $fullpattern = '/\s*\s*<\/serverdone>\s*<\/xcatresponse>/'; + $mixedpattern = '/\s*<\/serverdone>.*<\/xcatresponse>/'; + $recentpattern = '/<\/xcatresponse>/'; + if(preg_match($recentpattern,$str) && preg_match($mixedpattern,$response)) { + // Transaction is done, package up XML and return it + // Remove the serverdone response and put an xcat tag around the rest + $count = 0; + $response = preg_replace($fullpattern,'', $response, -1, $count); // 1st try to remove the long pattern + if (!$count) { $response = preg_replace($mixedpattern,'', $response) . '/'; } + $response = "$response"; + $response = preg_replace('/>\n\s*<', $response); + $response = preg_replace('/\n/', ':|:', $response); + $rsp = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); + $cleanexit = 1; + break; + } + } // End of while(!feof($fp)) + + syslog(LOG_INFO, "($cmd $nr) Sending response"); + fclose($fp); + } else { + echo "

                                                                                xCAT submit request socket error: $errno - $errstr

                                                                                "; + } + + // Flush (send) the output buffer and turn off output buffering + ob_end_flush(); - // Close syslog - closelog(); - - if(! $cleanexit) { - if (preg_match('/^\s*.*<\/xcatresponse>\s*$/',$response)) { - // Probably an error message - $response = "$response"; - $rsp = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); - } - elseif(!$skipVerify) { - echo "

                                                                                (Error) xCAT response ended prematurely: ", htmlentities($response), "

                                                                                "; - $rsp = FALSE; - } - } - return $rsp; + // Close syslog + closelog(); + + if(! $cleanexit) { + if (preg_match('/^\s*.*<\/xcatresponse>\s*$/',$response)) { + // Probably an error message + $response = "$response"; + $rsp = simplexml_load_string($response,'SimpleXMLElement', LIBXML_NOCDATA); + } else if (!$skipVerify) { + echo "

                                                                                (Error) xCAT response ended prematurely: ", htmlentities($response), "

                                                                                "; + $rsp = FALSE; + } + } + return $rsp; } /** * Enable password storage to split between cookie and session variable - * - * @param $data - * @param $key - * @return */ function xorcrypt($data, $key) { - $datalen = strlen($data); - $keylen = strlen($key); - for ($i=0;$i<$datalen;$i++) { - $data[$i] = chr(ord($data[$i])^ord($key[$i])); - } + $datalen = strlen($data); + $keylen = strlen($key); + for ($i=0;$i<$datalen;$i++) { + $data[$i] = chr(ord($data[$i])^ord($key[$i])); + } - return $data; + return $data; } /** * Get RAND characters * - * @param $length Length of characters - * @return RAND characters + * @param $length Length of characters + * @return RAND characters */ function getrandchars($length) { - $charset = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*'; - $charsize = strlen($charset); - srand(); - $chars = ''; - for ($i=0;$i<$length;$i++) { - $num=rand()%$charsize; - $chars=$chars.substr($charset,$num,1); - } + $charset = '0123456789abcdefghijklmnopqrstuvwxyz!@#$%^&*'; + $charsize = strlen($charset); + srand(); + $chars = ''; + for ($i=0;$i<$length;$i++) { + $num=rand()%$charsize; + $chars=$chars.substr($charset,$num,1); + } - return $chars; + return $chars; } /** * Format a given string and echo it back to the browser - * - * @param $str String - * @return Nothing */ function format_TBD($str) { - // Format a given string however you want it - echo $tmp . '
                                                                                '; - flush(); + // Format a given string however you want it + echo $tmp . '
                                                                                '; + flush(); } /** * Get password - * - * @param Nothing - * @return */ function getpassword() { - if (isset($GLOBALS['xcatauthsecret'])) { - $cryptext = $GLOBALS['xcatauthsecret']; - } else if (isset($_COOKIE["xcatauthsecret"])) { - $cryptext = $_COOKIE["xcatauthsecret"]; - } else { - return false; - } + if (isset($GLOBALS['xcatauthsecret'])) { + $cryptext = $GLOBALS['xcatauthsecret']; + } else if (isset($_COOKIE["xcatauthsecret"])) { + $cryptext = $_COOKIE["xcatauthsecret"]; + } else { + return false; + } - return xorcrypt($_SESSION["secretkey"], base64_decode($cryptext)); + return xorcrypt($_SESSION["secretkey"], base64_decode($cryptext)); } /** - * Get the password splitting knowledge between server - * and client side persistant storage. Caller should regenerate - * session ID when contemplating a new user/password, to preclude - * session fixation, though fixation is limited without the secret. + * Get the password splitting knowledge between server and client side persistant storage. + * Caller should regenerate session ID when contemplating a new user/password, + * to preclude session fixation, though fixation is limited without the secret. * - * @param $password Password - * @return Nothing + * @param $password Password */ function setpassword($password) { - $randlen = strlen($password); - $key = getrandchars($randlen); - $cryptext = xorcrypt($password,$key); + $randlen = strlen($password); + $key = getrandchars($randlen); + $cryptext = xorcrypt($password,$key); - // Non-ascii characters, encode it in base64 - $cryptext = base64_encode($cryptext); - setcookie("xcatauthsecret",$cryptext,0,'/'); - $GLOBALS["xcatauthsecret"] = $cryptext; - $_SESSION["secretkey"] = $key; + // Non-ascii characters, encode it in base64 + $cryptext = base64_encode($cryptext); + setcookie("xcatauthsecret",$cryptext,0,'/'); + $GLOBALS["xcatauthsecret"] = $cryptext; + $_SESSION["secretkey"] = $key; } /** * Determine if a user/password session exists * - * @param Nothing - * @return True If user has a session. - * False Otherwise + * @return True if user has a session, false otherwise */ function is_logged() { - if (isset($_SESSION["srv_username"]) and !is_bool(getpassword())) { - return true; - } else { - return false; - } + if (isset($_SESSION["srv_username"]) and !is_bool(getpassword())) { + return true; + } else { + return false; + } } /** * Determine if a user is currently logged in successfully - * - * @param Nothing - * @return True If the user is currently logged in successfully - * False Otherwise + * + * @return True if the user is currently logged in successfully, false otherwise */ function isAuthenticated() { - if (is_logged()) { - if ($_SESSION["srv_xcatpassvalid"] != 1) { - $testcred = docmd("authcheck", "", NULL, NULL); - if (isset($testcred->{'xcatresponse'}->{'data'})) { - $result = "".$testcred->{'xcatresponse'}->{'data'}; - if (is_numeric(strpos("Authenticated",$result))) { - // Logged in successfully - $_SESSION["srv_xcatpassvalid"] = 1; - } else { - // Not logged in - $_SESSION["srv_xcatpassvalid"] = 0; - } - } - } - } + if (is_logged()) { + if ($_SESSION["srv_xcatpassvalid"] != 1) { + $testcred = docmd("authcheck", "", NULL, NULL); + if (isset($testcred->{'xcatresponse'}->{'data'})) { + $result = "".$testcred->{'xcatresponse'}->{'data'}; + if (is_numeric(strpos("Authenticated",$result))) { + // Logged in successfully + $_SESSION["srv_xcatpassvalid"] = 1; + } else { + // Not logged in + $_SESSION["srv_xcatpassvalid"] = 0; + } + } + } + } - if (isset($_SESSION["srv_xcatpassvalid"]) and $_SESSION["srv_xcatpassvalid"]==1) { - return true; - } else { - return false; - } + if (isset($_SESSION["srv_xcatpassvalid"]) and $_SESSION["srv_xcatpassvalid"]==1) { + return true; + } else { + return false; + } } /** * Log out of the current user session - * - * @param Nothing - * @return Nothing */ function logout() { - // Clear the secret cookie from browser - if (isset($_COOKIE["xcatauthsecret"])) { - setcookie("xcatauthsecret",'',time()-86400*7,'/'); - } + // Clear the secret cookie from browser + if (isset($_COOKIE["xcatauthsecret"])) { + setcookie("xcatauthsecret",'',time()-86400*7,'/'); + } - // Expire session cookie - if (isset($_COOKIE[session_name()])) { - setcookie(session_name(),"",time()-86400*7,"/"); - } + // Expire session cookie + if (isset($_COOKIE[session_name()])) { + setcookie(session_name(),"",time()-86400*7,"/"); + } - // Clear server store of data - $_SESSION=array(); + // Clear server store of data + $_SESSION=array(); } ?> diff --git a/xCAT-UI/lib/srv_log.php b/xCAT-UI/lib/srv_log.php index 5a9f3bccc..31106b9aa 100644 --- a/xCAT-UI/lib/srv_log.php +++ b/xCAT-UI/lib/srv_log.php @@ -11,29 +11,29 @@ header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); if (isset($_REQUEST["password"])) { - // Clear data from session - $_SESSION = array(); + // Clear data from session + $_SESSION = array(); - // Zap existing session entirely - session_regenerate_id(true); - setpassword($_REQUEST["password"]); + // Zap existing session entirely + session_regenerate_id(true); + setpassword($_REQUEST["password"]); - // Invalid password - $_SESSION["srv_xcatpassvalid"] = -1; + // Invalid password + $_SESSION["srv_xcatpassvalid"] = -1; } if (isset($_REQUEST["username"])) { - $_SESSION["srv_username"] = $_REQUEST["username"]; + $_SESSION["srv_username"] = $_REQUEST["username"]; - // Invalid user name - $_SESSION["srv_xcatpassvalid"]=-1; + // Invalid user name + $_SESSION["srv_xcatpassvalid"]=-1; } $jdata = array(); if (isAuthenticated()) { - $jdata["authenticated"]="yes"; + $jdata["authenticated"]="yes"; } else { - $jdata["authenticated"]="no"; + $jdata["authenticated"]="no"; } echo json_encode($jdata); diff --git a/xCAT-UI/lib/systemcmd.php b/xCAT-UI/lib/systemcmd.php index 469551789..7990aa035 100644 --- a/xCAT-UI/lib/systemcmd.php +++ b/xCAT-UI/lib/systemcmd.php @@ -7,30 +7,30 @@ require_once "$TOPDIR/lib/jsonwrapper.php"; /** * This will handle system commands, e.g. rpm -qa xCAT * - * @param $cmd The system command - * @return The system response. Replies are in the form of JSON + * @param $cmd The system command + * @return The system response. Replies are in the form of JSON */ if (!isAuthenticated()) { - echo ("Please login before continuing!"); - exit; + echo ("Please login before continuing!"); + exit; } if (isset($_GET["cmd"])) { - // HTTP GET requests - $cmd = $_GET["cmd"]; - $msg = NULL; - $ret = ""; + // HTTP GET requests + $cmd = $_GET["cmd"]; + $msg = NULL; + $ret = ""; - if (isset($_GET["msg"])) { - $msg = $_GET["msg"]; - } - - if ($cmd == "ostype") { - $ret = strtolower(PHP_OS); - } else { - $ret = shell_exec($cmd); - } + if (isset($_GET["msg"])) { + $msg = $_GET["msg"]; + } + + if ($cmd == "ostype") { + $ret = strtolower(PHP_OS); + } else { + $ret = shell_exec($cmd); + } - echo json_encode(array("rsp"=>$ret, "msg" => $msg)); + echo json_encode(array("rsp"=>$ret, "msg" => $msg)); } ?> \ No newline at end of file diff --git a/xCAT-UI/lib/tabRestore.php b/xCAT-UI/lib/tabRestore.php index 79fafd6b8..4d3e960dc 100644 --- a/xCAT-UI/lib/tabRestore.php +++ b/xCAT-UI/lib/tabRestore.php @@ -7,8 +7,8 @@ require_once "$TOPDIR/lib/jsonwrapper.php"; /** * Replace the contents of an xCAT table * - * @param $tab The xCAT table - * @param $cont The xCAT table contents + * @param $tab The xCAT table + * @param $cont The xCAT table contents * @return The xCAT response. Replies are in the form of JSON */ if (isset($_POST["table"])) { @@ -24,7 +24,7 @@ $request = simplexml_load_string(''); $request->addChild('command', 'tabrestore'); // Setup authentication -$usernode=$request->addChild('becomeuser'); +$usernode = $request->addChild('becomeuser'); $usernode->addChild('username', $_SESSION["username"]); $usernode->addChild('password', getpassword()); @@ -43,7 +43,7 @@ foreach($cont as $line){ } // Go through each column - foreach($line as &$col){ + foreach ($line as &$col){ // If the column does begins and end with a quote // Change quotes to " if(!empty($col) && !preg_match('/^".*"$/', $col)) { @@ -55,9 +55,11 @@ foreach($cont as $line){ ksort($line, SORT_NUMERIC); $keys = array_keys($line); $max = count($line) - 1; - if($keys[$max] != $max){ + if ($keys[$max] != $max){ for ($i = 0; $i <= $keys[$max]; $i++) { - if (!isset($line[$i])) {$line[$i]='';} + if (!isset($line[$i])) { + $line[$i]=''; + } } ksort($line, SORT_NUMERIC); } diff --git a/xCAT-UI/lib/ui.php b/xCAT-UI/lib/ui.php index 163785eb8..c45b83a26 100644 --- a/xCAT-UI/lib/ui.php +++ b/xCAT-UI/lib/ui.php @@ -1,96 +1,87 @@ - - xCAT - - - - - - - '; + // Include CSS and Javascripts + echo + ' + + xCAT + + + + + + + '; - // Header menu - echo - ' - '; + // Content + echo '
                                                                                '; - // End of page - echo - ' - '; + // End of page + echo + ' + '; } /** * Load page content - * - * @param Nothing - * @return Nothing */ function loadContent() { - // Initialize page - echo - ''; + // Initialize page + echo + ''; } /** * Login user into a new session - * - * @param Nothing - * @return Nothing */ function login() { - // xcatauth.js will open a dialog box - // asking for the user name and password - echo - ' - -
                                                                                -
                                                                                - - - - - - - - -
                                                                                eXtreme Cloud Administration Toolkit
                                                                                -
                                                                                -
                                                                                Open Source. EPL License.
                                                                                -
                                                                                '; + // xcatauth.js will open a dialog box + // asking for the user name and password + echo + ' + +
                                                                                +
                                                                                + + + + + + + + +
                                                                                eXtreme Cloud Administration Toolkit
                                                                                +
                                                                                +
                                                                                Open Source. EPL License.
                                                                                +
                                                                                '; } ?> \ No newline at end of file diff --git a/xCAT-UI/lib/upload.php b/xCAT-UI/lib/upload.php index 2f33fc940..983fa30a1 100644 --- a/xCAT-UI/lib/upload.php +++ b/xCAT-UI/lib/upload.php @@ -4,26 +4,26 @@ */ $type = $_FILES["file"]["type"]; if ($type == "text/plain" || $type == "application/octet-stream" || $type == "application/x-shellscript" || $type == "application/x-sh") { - $error = $_FILES["file"]["error"]; - if ($error) { - echo "Return Code: " . $error; - } else { - $file = $_FILES["file"]["name"]; - $path = "/var/tmp/" . $file; - move_uploaded_file($_FILES["file"]["tmp_name"], $path); + $error = $_FILES["file"]["error"]; + if ($error) { + echo "Return Code: " . $error; + } else { + $file = $_FILES["file"]["name"]; + $path = "/var/tmp/" . $file; + move_uploaded_file($_FILES["file"]["tmp_name"], $path); - // Open and read given file - $handler = fopen($path, "r"); - $data = fread($handler, filesize($path)); - fclose($handler); + // Open and read given file + $handler = fopen($path, "r"); + $data = fread($handler, filesize($path)); + fclose($handler); - // Print out file contents - echo $data; + // Print out file contents + echo $data; - // Remove this file - unlink($path); - } + // Remove this file + unlink($path); + } } else { - echo "(Error) File type $type not supported"; + echo "(Error) File type $type not supported"; } ?> \ No newline at end of file diff --git a/xCAT-UI/lib/zCmd.php b/xCAT-UI/lib/zCmd.php index 24c6dcf32..706248268 100644 --- a/xCAT-UI/lib/zCmd.php +++ b/xCAT-UI/lib/zCmd.php @@ -7,9 +7,9 @@ require_once "$TOPDIR/lib/jsonwrapper.php"; /** * Issue an xCAT command (only for z) * - * @param $cmd The xCAT command - * @param $tgt The target node or group - * @param $args The xCAT command arguments, separated by semicolons + * @param $cmd The xCAT command + * @param $tgt The target node or group + * @param $args The xCAT command arguments, separated by semicolons * @return The xCAT response. Replies are in the form of JSON */ if (isset($_GET["cmd"])) { @@ -56,7 +56,7 @@ if (isset($_GET["cmd"])) { $rsp = array(); // Replace user entry - if(strncasecmp($cmd, "chvm", 4) == 0 && strncasecmp($arr[0], "--replacevs", 11) == 0) { + if (strncasecmp($cmd, "chvm", 4) == 0 && strncasecmp($arr[0], "--replacevs", 11) == 0) { // Directory /var/tmp permissions = 777 // You can write anything to that directory $userEntry = "/var/tmp/$tgt.txt"; @@ -77,7 +77,7 @@ if (isset($_GET["cmd"])) { } // Create virtual server - else if(strncasecmp($cmd, "mkvm", 4) == 0) { + else if (strncasecmp($cmd, "mkvm", 4) == 0) { // Directory /var/tmp permissions = 777 // You can write anything to that directory $userEntry = "/var/tmp/$tgt.txt"; diff --git a/xCAT-UI/monitor.php b/xCAT-UI/monitor.php index db1637792..29010ad74 100644 --- a/xCAT-UI/monitor.php +++ b/xCAT-UI/monitor.php @@ -10,8 +10,8 @@ loadPage(); /* Login user */ if (!isAuthenticated()) { - login(); + login(); } else { - loadContent(); + loadContent(); } ?> \ No newline at end of file diff --git a/xCAT-UI/provision.php b/xCAT-UI/provision.php index 8e12c5609..ef494bee5 100644 --- a/xCAT-UI/provision.php +++ b/xCAT-UI/provision.php @@ -10,8 +10,8 @@ loadPage(); /* Login user */ if (!isAuthenticated()) { - login(); + login(); } else { - loadContent(); + loadContent(); } ?> \ No newline at end of file diff --git a/xCAT-UI/rcons.php b/xCAT-UI/rcons.php index 67877ba02..a18102ff4 100644 --- a/xCAT-UI/rcons.php +++ b/xCAT-UI/rcons.php @@ -1,21 +1,21 @@ - - {$_GET['rconsnd']} - - - - - - - -
                                                                                - + + {$_GET['rconsnd']} + + + + + + + +
                                                                                + EEE; ?> diff --git a/xCAT-UI/service.php b/xCAT-UI/service.php index 972ce6428..558d39f85 100644 --- a/xCAT-UI/service.php +++ b/xCAT-UI/service.php @@ -12,30 +12,30 @@ require_once "lib/jsonwrapper.php"; // Include CSS and Javascripts echo ' - - xCAT Service Portal - - - - - - - - '; + + xCAT Service Portal + + + + + + + + '; // Create header menu echo ' -