2
0
mirror of https://github.com/xcat2/xcat-core.git synced 2025-05-29 09:13:08 +00:00

Merge pull request #2927 from zVMopenstack/ZVM_XCAT_DEV

Merge the changes made for zVM into the xCAT development branch
This commit is contained in:
zet809 2017-10-18 17:06:31 +08:00 committed by GitHub
commit a6661f84b7
87 changed files with 64768 additions and 36638 deletions

View File

@ -26,6 +26,7 @@ Includes xCAT::Table, xCAT::NodeRange, among others.
%define zvm %(if [ "$zvm" = "1" ];then echo 1; else echo 0; fi)
%define fsm %(if [ "$fsm" = "1" ];then echo 1; else echo 0; fi)
%define builddate %(date)
%prep
%setup -q -n perl-xCAT
%build

View File

@ -3855,10 +3855,10 @@ sub usage_dsh
my $usagemsg1 = " xdsh -h \n xdsh -q \n xdsh -V \n";
my $usagemsg1a = "xdsh <noderange> [-K] [-l logonuserid]\n";
my $usagemsg2 = " [-B | --bypass ] [-c] [-e] [-E environment_file]
[--devicetype type_of_device] [-f fanout]\n";
[--devicetype type_of_device] [-f fanout] [--ip ip_addr]\n";
my $usagemsg3 = " [-l user_ID] [-L] ";
my $usagemsg4 = "[-m] [-o options][-q] [-Q] [-r remote_shell]
[-i image] [-s] [-S ksh | csh] [-t timeout]\n";
[-i image] [-s] [-S ksh | csh] [--show key|script] [-t timeout]\n";
my $usagemsg5 = " [-T] [-X environment variables] [-v] [-z] [--sudo]\n";
my $usagemsg6 = " <command_list>";
my $usagemsg .= $usagemsg1 .= $usagemsg1a .= $usagemsg2 .= $usagemsg3 .=
@ -3962,8 +3962,10 @@ sub parse_and_run_dsh
'c|cleanup' => \$options{'cleanup'},
'E|environment=s' => \$options{'environment'},
'I|ignore-sig|ignoresig=s' => \$options{'ignore-signal'},
'ip=s' => \$options{'ip'},
'K|keysetup' => \$options{'ssh-setup'},
'L|no-locale' => \$options{'no-locale'},
'show=s' => \$options{'show'},
'Q|silent' => \$options{'silent'},
'S|syntax=s' => \$options{'syntax'},
'T|trace' => \$options{'trace'},
@ -4131,7 +4133,7 @@ sub parse_and_run_dsh
# with error, if the Management Node is in the Database and in the
# noderange
my @mname = xCAT::Utils->noderangecontainsMn(@nodelist);
if (@mname) { # MN in the nodelist
if ( @mname and !$options{'ip'} ) { # MN in the nodelist and --ip not specified
my $nodes = join(',', @mname);
my $rsp = {};
$rsp->{error}->[0] =
@ -4165,7 +4167,7 @@ sub parse_and_run_dsh
# password for the key update. This was setup in xdsh client
# frontend.
if (!($ENV{'DSH_REMOTE_PASSWORD'}))
if (!($ENV{'DSH_REMOTE_PASSWORD'}) && !(defined $options{'show'}))
{
my $rsp = {};
$rsp->{error}->[0] =
@ -4239,7 +4241,22 @@ sub parse_and_run_dsh
#
# setup ssh keys on the nodes or ib switch
#
my $rc = xCAT::TableUtils->setupSSH($options{'nodes'}, $options{'timeout'});
my $rc;
# If 'show' was specified then pass the value in an environment variable.
if ( $options{'show'} ) {
$ENV{'DSH_SHOW'} = $options{'show'};
}
# Go perform the setup of the SSH keys.
if ( $options{'ip'} ) {
# If IPs were passed then use them as the target of the unlock.
$rc = xCAT::TableUtils->setupSSH($options{'ip'} );
} else {
# Unlock the nodes
$rc = xCAT::TableUtils->setupSSH($options{'nodes'}, $options{'timeout'});
}
my @results = "return code = $rc";
return (@results);
}

View File

@ -276,7 +276,7 @@ qq{ link,ro - The file is readonly, and will be placed in tmpfs on the booted no
table_descr => 'Node storage resources',
descriptions => {
node => 'The node name',
controller => 'The management address to attach/detach new volumes.
controller => 'The management address to attach/detach new volumes.
In the scenario involving multiple controllers, this data must be
passed as argument rather than by table value',
osvolume => "Specification of what storage to place the node OS image onto. Examples include:
@ -664,13 +664,13 @@ passed as argument rather than by table value',
servicenode => 'A comma separated list of node names (as known by the management node) that provides most services for this node. The first service node on the list that is accessible will be used. The 2nd node on the list is generally considered to be the backup service node for this node when running commands like snmove.',
netboot => 'The type of network booting to use for this node. Valid values:
Arch OS valid netboot options
x86, x86_64 ALL pxe, xnba
Arch OS valid netboot options
x86, x86_64 ALL pxe, xnba
ppc64 <=rhel6, <=sles11.3 yaboot
ppc64 >=rhels7, >=sles11.4 grub2,grub2-http,grub2-tftp
ppc64le NonVirtualize ALL petitboot
ppc64le PowerKVM Guest ALL grub2,grub2-http,grub2-tftp
',
tftpserver => 'The TFTP server for this node (as known by this node). If not set, it defaults to networks.tftpserver.',
tftpdir => 'The directory that roots this nodes contents from a tftp and related perspective. Used for NAS offload by using different mountpoints.',
@ -807,16 +807,16 @@ passed as argument rather than by table value',
exlist => 'The fully qualified name of the file that stores the file names and directory names that will be excluded from the image during packimage command. It is used for diskless image only.',
postinstall => 'Supported in diskless image only. The fully qualified name of the scripts running in non-chroot mode after the package installation but before initrd generation during genimage. If multiple scripts are specified, they should be seperated with comma ",". A set of osimage attributes are exported as the environment variables to be used in the postinstall scripts:
IMG_ARCH(The architecture of the osimage, such as "ppc64le","x86_64"),
IMG_NAME(The name of the osimage, such as "rhels7.3-ppc64le-netboot-compute"),
IMG_OSVER(The os release of the osimage, such as "rhels7.3","sles11.4"),
IMG_ARCH(The architecture of the osimage, such as "ppc64le","x86_64"),
IMG_NAME(The name of the osimage, such as "rhels7.3-ppc64le-netboot-compute"),
IMG_OSVER(The os release of the osimage, such as "rhels7.3","sles11.4"),
IMG_KERNELVERSION(the "kernelver" attribute of the osimage),
IMG_PROFILE(the profile of the osimage, such as "service","compute"),
IMG_PKGLIST(the "pkglist" attribute of the osimage),
IMG_PKGDIR(the "pkgdir" attribute of the osimage),
IMG_OTHERPKGLIST(the "otherpkglist" attribute of the osimage),
IMG_OTHERPKGDIR(the "otherpkgdir" attribute of the osimage),
IMG_ROOTIMGDIR(the "rootimgdir" attribute of the osimage)',
IMG_PROFILE(the profile of the osimage, such as "service","compute"),
IMG_PKGLIST(the "pkglist" attribute of the osimage),
IMG_PKGDIR(the "pkgdir" attribute of the osimage),
IMG_OTHERPKGLIST(the "otherpkglist" attribute of the osimage),
IMG_OTHERPKGDIR(the "otherpkgdir" attribute of the osimage),
IMG_ROOTIMGDIR(the "rootimgdir" attribute of the osimage)',
rootimgdir => 'The directory name where the image is stored. It is generally used for diskless image. it also can be used in sysclone environment to specify where the image captured from golden client is stored. in sysclone environment, rootimgdir is generally assigned to some default value by xcat, but you can specify your own store directory. just one thing need to be noticed, wherever you save the image, the name of last level directory must be the name of image. for example, if your image name is testimage and you want to save this image under home directoy, rootimgdir should be assigned to value /home/testimage/',
kerneldir => 'The directory name where the 3rd-party kernel is stored. It is used for diskless image only.',
nodebootif => 'The network interface the stateless/statelite node will boot over (e.g. eth0)',
@ -1069,7 +1069,7 @@ passed as argument rather than by table value',
" nodes, use a simple comma-separated list of NICs. To specify different \n" .
" NICs for different nodes, use the format: \"xcatmn|eth1,eth2;service|bond0\", \n" .
" where xcatmn is the name of the management node, and DNS should listen on\n" .
" the eth1 and eth2 interfaces. All the nods in group 'service' should \n" .
" the eth1 and eth2 interfaces. All the nods in group 'service' should \n" .
" listen on the 'bond0' interface.\n\n" .
" NOTE: If using this attribute to block certain interfaces, make sure\n" .
" the IP maps to your hostname of xCAT MN is not blocked since xCAT needs\n" .
@ -1504,8 +1504,30 @@ passed as argument rather than by table value',
},
},
zvmivp => {
cols => [qw(id ip schedule last_run type_of_run access_user orch_parms prep_parms main_ivp_parms comments disable)],
keys => [qw(id)],
table_desc => 'List of z/VM Installation Verification Procedures (IVPs) to be periodically run.',
descriptions => {
id => 'Unique identifier associated with the IVP run, e.g. 1.',
ip => 'IP address of the target system, either the IP of the OpenStack compute node or the xCAT management node.',
schedule => 'The hours (0-24) that the IVP should be run. Multiple hours are separated by a blank.',
last_run => 'The last time the IVP was run specified as a set of 3 blank delimeted words: year, Julian date, and hour (in 24 hour format).',
type_of_run => 'The type of run requested, \'fullivp\' or \'basicivp\'.',
access_user => 'User on the OpenStack node that is used to: push the IVP preparation script to the OpenStack system, '.
'drive the preparation script to validate the OpenStack configuration files, and return the created '.
'driver script to the xCAT MN system for the next part of the IVP. This user should be '.
'able to access the OpenStack configuration files that are scanned by the IVP.',
orch_parms => 'Parameters to pass to the IVP orchestrator script, verifynode.',
prep_parms => 'Parameters to pass to the phase 1 IVP preparation script.',
main_ivp_parms => 'Parameters to pass to the main IVP script.',
comments => 'Any user provided notes or description of the run.',
disable => "Set to 'yes' or '1' to disable this IVP run.",
},
},
zvm => {
cols => [qw(node hcp userid nodetype parent comments disable)],
cols => [qw(node hcp userid nodetype parent comments disable discovered status)],
keys => [qw(node)],
table_desc => 'List of z/VM virtual servers.',
descriptions => {
@ -1516,6 +1538,8 @@ passed as argument rather than by table value',
parent => 'The parent node. For LPAR, this specifies the CEC. For z/VM, this specifies the LPAR. For VM, this specifies the z/VM host operating system.',
comments => 'Any user provided notes.',
disable => "Set to 'yes' or '1' to comment out this row.",
discovered => "Set to '1' to indicate this node was discovered.",
status => "The processing status. Key value pairs (key=value) indicating status of the node. Multiple pairs are separated by semi-colons. Keys include: CLONING, CLONE_ONLY.",
},
},
@ -1551,6 +1575,7 @@ passed as argument rather than by table value',
If multiple ip addresses are associated with each NIC:
<nic1>!<ext1>|<ext2>,<nic2>!<ext1>|<ext2>,..., for example, eth0!-eth0|-eth0-ipv6,ib0!-ib0|-ib0-ipv6.
The xCAT object definition commands support to use nichostnamesuffixes.<nicname> as the sub attributes.
Note: According to DNS rules a hostname must be a text string up to 24 characters drawn from the alphabet (A-Z), digits (0-9) and minus sign (-). When you are specifying "nichostnamesuffixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention',
nichostnameprefixes => 'Comma-separated list of hostname prefixes per NIC.
If only one ip address is associated with each NIC:
@ -1869,6 +1894,7 @@ foreach my $tabname (keys(%xCAT::ExtTab::ext_tabspec)) {
osdistro => { attrs => [], attrhash => {}, objkey => 'osdistroname' },
osdistroupdate => { attrs => [], attrhash => {}, objkey => 'osupdatename' },
zone => { attrs => [], attrhash => {}, objkey => 'zonename' },
zvmivp => { attrs => [], attrhash => {}, objkey => 'id' },
firmware => { attrs => [], attrhash => {}, objkey => 'cfgfile' },
taskstate => { attrs => [], attrhash => {}, objkey => 'node' },
pdu => { attrs => [], attrhash => {}, objkey => 'node' },

View File

@ -250,13 +250,16 @@ my %usage = (
lsvm <noderange> [-a|--all]
PPC (using Direct FSP Management) specific:
lsvm <noderange> [-l|--long] --p775
lsvm <noderange>
lsvm <noderange>
zVM specific:
lsvm noderange
lsvm noderange --getnetworknames
lsvm noderange --getnetwork network_name
lsvm noderange --diskpoolnames
lsvm noderange --diskpool pool_name",
lsvm noderange --diskpool pool_name
lsvm noderange --queryalldisks
lsvm noderange --querypagevolumes
lsvm noderange --queryspoolvolumes",
"chvm" =>
"Usage:
Common:
@ -270,7 +273,7 @@ my %usage = (
chvm <noderange> [lparname=<*|name>]
chvm <noderange> [vmcpus=min/req/max] [vmmemory=min/req/max]
[vmothersetting=hugepage:N,bsr:N]
[add_physlots=drc_index1,drc_index2...]
[add_physlots=drc_index1,drc_index2...]
[add_vmnics=vlan1,vlan2] [add_vmstorage=<N|viosnode:slotid>] [--vios]
chvm <noderange> [del_physlots=drc_index1,drc_index2...]
chvm <noderange> [del_vadapter=slotid]
@ -448,7 +451,7 @@ Options:
[-f|--snsync] Performs File Syncing to the service nodes that service
the nodes in the noderange.
[-g|--genmypost] Will generate a new mypostscript file for the
[-g|--genmypost] Will generate a new mypostscript file for the
the nodes in the noderange, if site precreatemypostscripts is 1 or YES.
[-l|--user] User name to run the updatenode command. It overrides the

View File

@ -2294,11 +2294,19 @@ sub osver
$os = $id_like;
}
if (!$os ) {
$os = "unknown";
}
$verrel = $version;
if (!$verrel and $version_id) {
$verrel = $version_id;
}
if (!$verrel ) {
$verrel = "unknown";
}
if (!$name and $prettyname) {
$name = $prettyname;

File diff suppressed because it is too large Load Diff

1397
perl-xCAT/xCAT/zvmMsgs.pm Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,336 @@
/**
* Load the files page
*/
function loadFilesPage() {
var tabId = 'filesTab';
$('#' + tabId).empty();
// Set padding for page
$('#' + tabId).css('padding', '10px 30px');
// Create info bar
var info = $('#' + tabId).find('.ui-state-highlight');
// If there is no info bar
if (!info.length) {
var infoBar = createInfoBar('Below is a listing of the xCAT repository. ' +
'Upload any file or package into the repository using the Upload button. ' +
'Go into any subdirectories by specifying the directory path and clicking on Go.');
var directoryFS = $('<fieldset></fieldset>');
var dirLegend = $('<legend>Directory</legend>');
directoryFS.append(dirLegend);
// Division to hold directory actions
var actions = $('<div></div>');
directoryFS.append(actions);
// Create button to create a directory
var folderBtn = createButton('New folder');
folderBtn.click(function() {
var deleteFolderBtn = $('<span class="ui-icon ui-icon-close" style="margin-left:10px; margin-right:10px;"></span>');
var createFolderBtn = createButton('Create');
// Create a new directory
var newFolder = $('<li><span class="ui-icon ui-icon-folder-collapsed" style="margin-right: 10px;"></span><input type="text" name="new_folder"/></li>');
newFolder.prepend(deleteFolderBtn);
newFolder.append(createFolderBtn);
$('#repo_content ul').append(newFolder);
// Delete new folder on-click
deleteFolderBtn.click(function() {
$(this).parents('li').remove();
});
// Create folder on-click
createFolderBtn.click(function() {
var directory = $('#' + tabId + ' input[name="repo_directory"]');
var newFolderPath = $('#' + tabId + ' input[name="new_folder"]').val();
if (newFolderPath) {
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'webrun',
tgt : '',
args : 'createfolder;' + directory.val() + '/' + newFolderPath,
msg : ''
},
success:function(data) {
data = decodeRsp(data);
openDialog('info', data.rsp[0]);
}
});
$(this).parents('li').remove();
} else {
openDialog('warn', 'You must specify the folder name');
}
});
});
// Create button to upload files
var uploadBtn = createButton('Upload');
uploadBtn.click(function() {
var directory = $('#' + tabId + ' input[name="repo_directory"]');
openUploadDialog(directory.val());
});
// Create button to go into a directory path
var dirPath = $('<input type="text" name="repo_directory" style="width:400px;"/>');
var goBtn = createButton('Go');
goBtn.click(function() {
var directory = $('#' + tabId + ' input[name="repo_directory"]');
loadPath(directory.val());
});
goBtn.attr('id', 'go_to_path');
var space = $('<div id="repo_space"></div>');
var content = $('<div id="repo_content" class="form"></div>');
actions.append(folderBtn, uploadBtn, dirPath, goBtn);
directoryFS.append(space, content);
$('#' + tabId).append(infoBar, directoryFS);
}
// Retrieve repository space
getRepositorySpace();
// Retrieve files from /install
loadPath('/install');
}
/**
* Get the repository space
*/
function getRepositorySpace() {
// Grab repository space
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
async: false,
data : {
cmd : 'webrun',
tgt : '',
args : 'getrepospace',
msg : ''
},
success: function(data) {
data = decodeRsp(data);
$('#repo_space').children().remove();
// Data returned is: size, used, available, used %, mount
// Data could be in a different format in CMO, where it puts the directory on the line
// "rsp":["\/data\/xcat\/install 28G 6.0G 20G 24% \/install"],"msg":null}
var space = data.rsp[0].split(' ');
if (space.length == 6) {
space.splice(0,1);
}
var spaceLabel = $('<label style="margin:10px;width:300px;"><b>Total size: </b>' + space[0] +
'<b> | Available: </b>' + space[2] +
'</label>');
$('#repo_space').append(spaceLabel);
}
});
}
/**
* Open a dialog to upload files into the repository
*
* @param destDirectory The destination directory
*/
function openUploadDialog(destDirectory) {
// Create info bar
var info = createInfoBar('Select a file to upload onto ' + destDirectory + '.');
var dialog = $('<div id="upload_file_dg"></div>');
dialog.append(info);
// Upload file
var upload = $('<form id="upload_file" enctype="multipart/form-data"></form>');
var label = $('<label style="margin-right: 10px;">Remote file:</label>');
var file = $('<input type="file" name="file" id="file"/>');
var subBtn = createButton('Upload');
upload.append(label, file, subBtn);
dialog.append(upload);
upload.submit(function() {
// Create status bar, hide on load
var statBarId = 'uploadStatusBar';
var statBar = createStatusBar(statBarId);
var loader = createLoader('');
statBar.find('div').append('Do not close this dialog while the file is being uploaded ');
statBar.find('div').append(loader);
statBar.prependTo($('#upload_file_dg'));
var data = new FormData($('#upload_file')[0]);
$.ajax({
type: 'POST',
url : 'lib/uploadfile.php?destination=' + destDirectory,
data: data,
success: function(data) {
$('#uploadStatusBar').find('img').hide();
$('#uploadStatusBar').find('div').empty();
$('#uploadStatusBar').find('div').append(data);
// Refresh directory contents
$('#go_to_path').click();
getRepositorySpace();
},
cache: false,
contentType: false,
processData: false
});
return false;
});
// Create dialog
dialog.dialog({
modal: true,
title: 'Upload',
width: 500,
close: function() {$(this).remove();}
});
}
/**
* Load the directory path structure
*
* @path The directory path
*/
function loadPath(path) {
// Limit access to only /install
if (path.substring(0, 9).indexOf("install") == -1) {
openDialog('warn', 'You are not authorized to browse outside the repository');
return;
}
var tabId = 'filesTab';
var directory = $('#' + tabId + ' input[name="repo_directory"]');
directory.val(path);
// Un-ordered list containing directories and files
var contentId = 'repo_content';
$('#' + contentId).empty();
var itemsList = $('<ul></ul>');
$('#' + contentId).append(itemsList);
// Back button to go up a directory
var item = $('<li><span class="ui-icon ui-icon-folder-collapsed" style="margin-right: 10px;"></span>..</li>');
itemsList.append(item);
item.dblclick(function() {
if (path.lastIndexOf('/') > 1)
path = path.substring(0, path.lastIndexOf('/'));
loadPath(path);
});
$.ajax({
type: 'POST',
url : 'lib/getpath.php',
dataType : 'json',
data: {
action: 'browse',
path: path,
time: new Date().getTime()
},
beforeSend: function() {
// Show loading image
},
success: function(files) {
$.each(files, function(index, file) {
if (!file.path || file.path.indexOf("undefined"))
file.path = "";
var fullPath = file.path + "/" + file.name;
// Create a list showing the directories and files
var item;
if (file.isFolder) {
var deleteFolderBtn = $('<span class="ui-icon ui-icon-close" style="margin-left:10px; margin-right:10px;"></span>');
item = $('<li><span class="ui-icon ui-icon-folder-collapsed" style="margin-right: 10px;"></span>' + file.name + '</li>');
item.prepend(deleteFolderBtn);
itemsList.append(item);
item.dblclick(function() {
loadPath(directory.val() + fullPath);
});
// Delete file on click
deleteFolderBtn.click(function() {
deleteFile($(this).parents('li'), directory.val() + fullPath);
});
} else {
var icon = $('<span class="ui-icon ui-icon-document" style="margin-right: 10px;"></span>');
var deleteFileBtn = $('<span class="ui-icon ui-icon-close" style="margin-left:10px; margin-right:10px;"></span>');
item = $('<li><a href="' + directory.val() + fullPath + '">' + file.name + '</a></li>');
item.append(deleteFileBtn, icon);
// Delete file on click
deleteFileBtn.click(function() {
deleteFile($(this).parents('li'), directory.val() + fullPath);
});
itemsList.append(item);
}
});
}
});
}
/**
* Prompt user to confirm deletion of file
*
* @param container The element container
* @param file The file name to delete
*/
function deleteFile(container, file) {
// Open dialog to confirm
var confirmDialog = $('<div id="confirm_delete"></div>');
var warn = createWarnBar('Are you sure you want to delete ' + file + '?');
confirmDialog.append(warn);
confirmDialog.dialog({
title: "Confirm",
modal: true,
width: 400,
close: function() {$(this).remove();},
buttons: {
"Ok": function() {
var loader = createLoader('').css({'margin': '5px'});
$(this).append(loader);
// Change dialog buttons
$(this).dialog('option', 'buttons', {
'Close':function() {
$(this).dialog('destroy').remove();
}
});
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
async: false,
data : {
cmd : 'webrun',
tgt : '',
args : 'deletefile;' + file,
msg : ''
},
success: function(data) {
data = decodeRsp(data);
$('#confirm_delete').children().remove();
var info = createInfoBar(data.rsp[0]);
$('#confirm_delete').append(info);
getRepositorySpace();
}
});
// Delete folder from the list
container.remove();
},
"Cancel": function() {
$(this).dialog('destroy').remove();
}
}
});
}

File diff suppressed because it is too large Load Diff

View File

@ -1,310 +1,322 @@
/**
* Load update page
*/
function loadUpdatePage() {
var repositoryDiv = $('<div id="repository"></div>');
var rpmDiv = $('<div id="rpm"></div>');
var statusDiv = createStatusBar("update");
statusDiv.hide();
$('#updateTab').append(statusDiv);
$('#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);
repositoryDiv.append("<fieldset><legend>Repository</legend></fieldset>");
$.ajax( {
url : 'lib/systemcmd.php',
dataType : 'json',
data : {
cmd : 'ostype'
},
success : showRepository
});
rpmDiv.append("<fieldset></fieldset>");
$.ajax( {
url : 'lib/systemcmd.php',
dataType : 'json',
data : {
cmd : 'rpm -q xCAT-client perl-xCAT xCAT-server xCAT xCAT-rmc xCAT-UI'
},
success : showRpmInfo
});
}
/**
* Show the RPM repository (it can use the user's last choice and input)
*
* @param data Data returned from HTTP request
*/
function showRepository(data) {
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/";
}
var repoList = $('<ol></ol>');
// Display the Devel Repository, remember user's last selection
show = show + "<li><input type='radio' ";
if ($.cookie('xcat_repository') == 1) {
show = show + "checked='true'";
}
show = show + "name='reporadio' value='" + develRepository + "'>";
show = show + "<strong>Development</strong>: " + develRepository + "</li>";
repoList.append(show);
// Display the Stable Repository, remember user's last selection
show = "<li><input type='radio' ";
if ($.cookie('xcat_repository') == 2) {
show = show + "checked='true'";
}
show = show + "name='reporadio' value='" + stableRepository + "' checked='true'>";
show = show + "<strong>Stable</strong>: " + stableRepository + "</li>";
repoList.append(show);
// Display the Input Repository, remember user's last selection
if (($.cookie('xcat_repository')) && ($.cookie('xcat_repository') != 1)
&& ($.cookie('xcat_repository') != 2)) {
show = "<li><input type='radio' checked='true' name='reporadio' value=''>Other: ";
show += "<input style='width: 500px' id='repositoryaddr' value='"
+ $.cookie('xcat_repository') + "'</li>";
} else {
show = "<li><input type='radio' name='reporadio' value=''>Other: ";
show += "<input style='width: 500px' id='repositoryaddr' value=''</li>";
}
repoList.append(show);
$('#repository fieldset').append(repoList);
}
/**
* Show all xCAT RPMs
*
* @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;
}
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("<legend>xCAT RPMs</legend>");
show = "<table id=rpmtable >";
show += "<thead class='ui-widget-header'><tr>";
show += "<th><input type='checkbox' id='selectall' value='' onclick='updateSelectAll()'></th>";
show += "<th><b>Package Name</b></th><th><b>Version</b></th>";
show += "</tr></thead>";
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;
}
// Show the version in table
show += "<tr>";
show += "<td><input type='checkbox' value='" + rpmNames[temp] + "'></td>";
show += "<td>" + rpmNames[temp] + "</td><td>"
+ rpms[temp].substr(rpmNames[temp].length + 1) + "</td>";
show += "</tr>";
}
show += "</table>";
show += "<br\>";
$('#rpm fieldset').append(show);
// Add the update button
var updateButton = createButton('Update');
$('#rpm fieldset').append(updateButton);
updateButton.bind('click', function() {
updateRpm();
});
}
/**
* Select all checkboxes
*/
function updateSelectAll() {
var check_status = $('#selectall').attr('checked');
$('input:checkbox').attr('checked', check_status);
}
/**
* Update selected xCAT RPMs
*/
function updateRpm() {
// Remove any warning messages
$('#updateTab').find('.ui-state-error').remove();
var rpmPath = $('input[type=radio]:checked').val();
var rpmPathType = "0";
var rpms = "";
var temp = "";
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";
}
}
$("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 + ",";
});
if (0 < rpms.length) {
rpms = rpms.slice(0, -1);
}
// Check RPM and repository
var errMsg = '';
if (!rpms) {
errMsg = "Please select an RPM!<br>";
}
if (!rpmPath) {
errMsg += "Please select or specify a repository!";
}
if (!rpms || !rpmPath) {
// Show warning message
var warn = createWarnBar(errMsg);
warn.prependTo($('#updateTab'));
return;
}
// Remember users' choice and input
$.cookie('xcat_repository', rpmPathType, {
path : '/xcat',
secure : true,
expires : 10
});
$('#update').show();
$('#update div').empty();
$('#update div').append("<p>Updating <b>" + rpms + "</b> from <b>" + rpmPath + "</b></p>");
$('#update div').append("<img id='loadingpic' src='images/loader.gif'>");
$('#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 : ''
},
success : showUpdateResult
});
}
/**
* Show the results of the RPM update
*
* @param data Data returned from HTTP request
*/
function showUpdateResult(data) {
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('<pre>' + resArray[resArray.length - 2] + '</pre>');
} else {
$('#update div').append('<pre>' + resArray[resArray.length - 1] + '</pre>');
}
// Create link to show details
$('#update div').append('<br/><a>Show details</a>');
$('#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 = $('<pre id="resDetail"></pre>');
resDetail.hide();
$('#update div').append(resDetail);
for (temp = 0; temp < resArray.length; temp++) {
resDetail.append(resArray[temp] + '<br/>');
}
}
// 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
});
$('#rpm button').attr('disabled', '');
/**
* Load update page
*/
function loadUpdatePage() {
var repositoryDiv = $('<div id="repository"></div>');
var rpmDiv = $('<div id="rpm"></div>');
var statusDiv = createStatusBar("update");
statusDiv.hide();
$('#updateTab').append(statusDiv);
$('#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);
repositoryDiv.append("<fieldset><legend>Repository</legend></fieldset>");
$.ajax( {
url : 'lib/systemcmd.php',
dataType : 'json',
data : {
cmd : 'ostype'
},
success : function(data) {
data = decodeRsp(data);
showRepository(data);
}
});
rpmDiv.append("<fieldset></fieldset>");
$.ajax( {
url : 'lib/systemcmd.php',
dataType : 'json',
data : {
cmd : 'rpm -q xCAT-client perl-xCAT xCAT-server xCAT xCAT-rmc xCAT-UI'
},
success : function(data) {
data = decodeRsp(data);
showRpmInfo(data);
}
});
}
/**
* Show the RPM repository (it can use the user's last choice and input)
*
* @param data Data returned from HTTP request
*/
function showRepository(data) {
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/";
}
var repoList = $('<ol></ol>');
// Display the Devel Repository, remember user's last selection
show = show + "<li><input type='radio' ";
if ($.cookie('xcat_repository') == 1) {
show = show + "checked='true'";
}
show = show + "name='reporadio' value='" + develRepository + "'>";
show = show + "<strong>Development</strong>: " + develRepository + "</li>";
repoList.append(show);
// Display the Stable Repository, remember user's last selection
show = "<li><input type='radio' ";
if ($.cookie('xcat_repository') == 2) {
show = show + "checked='true'";
}
show = show + "name='reporadio' value='" + stableRepository + "' checked='true'>";
show = show + "<strong>Stable</strong>: " + stableRepository + "</li>";
repoList.append(show);
// Display the Input Repository, remember user's last selection
if (($.cookie('xcat_repository')) && ($.cookie('xcat_repository') != 1)
&& ($.cookie('xcat_repository') != 2)) {
show = "<li><input type='radio' checked='true' name='reporadio' value=''>Other: ";
show += "<input style='width: 500px' id='repositoryaddr' value='"
+ $.cookie('xcat_repository') + "'</li>";
} else {
show = "<li><input type='radio' name='reporadio' value=''>Other: ";
show += "<input style='width: 500px' id='repositoryaddr' value=''</li>";
}
repoList.append(show);
$('#repository fieldset').append(repoList);
}
/**
* Show all xCAT RPMs
*
* @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;
}
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("<legend>xCAT RPMs</legend>");
show = "<table id=rpmtable >";
show += "<thead class='ui-widget-header'><tr>";
show += "<th><input type='checkbox' id='selectall' value='' onclick='updateSelectAll()'></th>";
show += "<th><b>Package Name</b></th><th><b>Version</b></th>";
show += "</tr></thead>";
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;
}
// Show the version in table
show += "<tr>";
show += "<td><input type='checkbox' value='" + rpmNames[temp] + "'></td>";
show += "<td>" + rpmNames[temp] + "</td><td>"
+ rpms[temp].substr(rpmNames[temp].length + 1) + "</td>";
show += "</tr>";
}
show += "</table>";
show += "<br\>";
$('#rpm fieldset').append(show);
// Add the update button
var updateButton = createButton('Update');
$('#rpm fieldset').append(updateButton);
updateButton.bind('click', function() {
updateRpm();
});
}
/**
* Select all checkboxes
*/
function updateSelectAll() {
var check_status = $('#selectall').attr('checked');
$('input:checkbox').attr('checked', check_status);
}
/**
* Update selected xCAT RPMs
*/
function updateRpm() {
// Remove any warning messages
$('#updateTab').find('.ui-state-error').remove();
var rpmPath = $('input[type=radio]:checked').val();
var rpmPathType = "0";
var rpms = "";
var temp = "";
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";
}
}
$("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 + ",";
});
if (0 < rpms.length) {
rpms = rpms.slice(0, -1);
}
// Check RPM and repository
var errMsg = '';
if (!rpms) {
errMsg = "Please select an RPM!<br>";
}
if (!rpmPath) {
errMsg += "Please select or specify a repository!";
}
if (!rpms || !rpmPath) {
// Show warning message
var warn = createWarnBar(errMsg);
warn.prependTo($('#updateTab'));
return;
}
// Remember users' choice and input
$.cookie('xcat_repository', rpmPathType, {
path : '/xcat',
secure : true,
expires : 10
});
$('#update').show();
$('#update div').empty();
$('#update div').append("<p>Updating <b>" + rpms + "</b> from <b>" + rpmPath + "</b></p>");
$('#update div').append("<img id='loadingpic' src='images/loader.gif'>");
$('#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 : ''
},
success : function(data) {
data = decodeRsp(data);
showUpdateResult(data);
}
});
}
/**
* Show the results of the RPM update
*
* @param data Data returned from HTTP request
*/
function showUpdateResult(data) {
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('<pre>' + resArray[resArray.length - 2] + '</pre>');
} else {
$('#update div').append('<pre>' + resArray[resArray.length - 1] + '</pre>');
}
// Create link to show details
$('#update div').append('<br/><a>Show details</a>');
$('#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 = $('<pre id="resDetail"></pre>');
resDetail.hide();
$('#update div').append(resDetail);
for (temp = 0; temp < resArray.length; temp++) {
resDetail.append(resArray[temp] + '<br/>');
}
}
// 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 : function(data) {
data = decodeRsp(data);
showRpmInfo(data);
}
});
$('#rpm button').attr('disabled', '');
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,276 +1,281 @@
/**
* Global variables
*/
var monitorTabs; // Monitor tabs
/**
* Set the monitor tab
*
* @param o
* Tab object
* @return Nothing
*/
function setMonitorTab(o) {
monitorTabs = o;
}
/**
* Get the monitor tab
*
* @return Tab object
*/
function getMonitorTab() {
return monitorTabs;
}
/**
* Load the monitor page
*/
function loadMonitorPage() {
// If the page is already loaded
if ($('#monitor_page').children().length) {
// Do not reload the monitor page
return;
}
// Create monitor tab
var tab = new Tab();
setMonitorTab(tab);
tab.init();
$('#content').append(tab.object());
var monitorForm = $('<div class="form"></div>');
monitorForm.append('Getting monitoring status ').append(createLoader());
tab.add('monitorTab', 'Monitor', monitorForm, false);
// Get monitoring status of each tool
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'webrun',
tgt : '',
args : 'monls',
msg : ''
},
/**
* Load monitoring status
*
* @param data Data returned from HTTP request
*/
success : function(data){
// Initialize status for each tool
var statusHash = new Object();
statusHash['xcatmon'] = 'Off';
statusHash['rmcmon'] = 'Off';
statusHash['rmcevent'] = 'Off';
statusHash['gangliamon'] = 'Off';
if (data.rsp[0]) {
var tempArray = data.rsp[0].split(';');
var position = 0;
var name = '';
var status = '';
for ( var i in tempArray) {
position = tempArray[i].indexOf(':');
if (position == -1) {
continue;
}
name = tempArray[i].substr(0, position);
status = tempArray[i].substr(position + 1);
statusHash[name] = status;
}
}
// Create a status buttonset for each monitoring tool
var statusButtonHash = new Object();
for ( var name in statusHash) {
var statusButton = $('<div></div>').css({
'width': '100px',
'text-align': 'center'
});
statusButtonHash[name] = statusButton;
// Set button to correct status
if (statusHash[name] == 'On') {
statusButton.append($('<input type="radio" id="' + name + 'On" name="' + name + '" value="On" checked="checked"/><label for="' + name + 'On">On</label>'));
statusButton.append($('<input type="radio" id="' + name + 'Off" name="' + name + '" value="Off"/><label for="' + name + 'Off">Off</label>'));
} else {
statusButton.append($('<input type="radio" id="' + name + 'On" name="' + name + '" value="On"/><label for="' + name + 'On">On</label>'));
statusButton.append($('<input type="radio" id="' + name + 'Off" name="' + name + '" value="Off" checked="checked"/><label for="' + name + 'Off">Off</label>'));
}
statusButton.find('label').css({
'margin': '0px',
'padding': '0px',
'font-size': '10px',
'width': 'auto'
});
statusButton.buttonset();
// Turn on or off monitoring tool when clicked
statusButton.find('input["' + name + '"]:radio').change(toggleMonitor);
}
var monTable = $('<table></table>');
monTable.append($('<thead class="ui-widget-header"><tr><th><b>Tool</b></th><th><b>Status</b></th><th><b>Description</b></th></tr></thead>'));
var monTableBody = $('<tbody></tbody>');
monTable.append(monTableBody);
var xcatMon = $('<tr></tr>');
xcatMon.append($('<td><a href="#" name="xcatmon">xCAT</a></td>'));
xcatMon.append($('<td></td>').append(statusButtonHash['xcatmon']));
xcatMon.append($('<td>xCAT provides node status monitoring using fping on AIX and nmapon Linux. It also provides application status monitoring. The status and the appstatus columns of the nodelist table will be updated periodically with the latest status values for the nodes.</td>'));
monTableBody.append(xcatMon);
var rmcMon = $('<tr></tr>');
rmcMon.append($('<td><a href="#" name="rmcmon">RMC</a></td>'));
rmcMon.append($('<td></td>').append(statusButtonHash['rmcmon']));
rmcMon.append($('<td>Resource Monitoring and Control (RMC) is a generalized framework for managing, monitoring and manipulating resources, such as physical or logical system entities. RMC is utilized as a communication mechanism for reporting service events to the Hardware Management Console (HMC).</td>'));
monTableBody.append(rmcMon);
var rmcEvent = $('<tr></tr>');
rmcEvent.append($('<td><a href="#" name="rmcevent">RMC Event</a></td>'));
rmcEvent.append($('<td></td>').append(statusButtonHash['rmcevent']));
rmcEvent.append($('<td>Shows a list of events recorded by the RSCT Event Response resource manager in the audit log.</td>'));
monTableBody.append(rmcEvent);
var gangliaMon = $('<tr></tr>');
gangliaMon.append($('<td><a href="#" name="gangliamon">Ganglia</a></td>'));
gangliaMon.append($('<td></td>').append(statusButtonHash['gangliamon']));
gangliaMon.append($('<td>Ganglia is a scalable distributed monitoring system for high-performance computing systems such as clusters and Grids.</td>'));
monTableBody.append(gangliaMon);
// Do not word wrap
monTableBody.find('td:nth-child(1)').css('white-space', 'nowrap');
monTableBody.find('td:nth-child(3)').css({
'white-space': 'normal',
'text-align': 'left'
});
// Append info bar
$('#monitorTab div').empty().append(createInfoBar('Select a monitoring tool to use'));
$('#monitorTab .form').append(monTable);
// Open monitoring tool onclick
$('#monitorTab .form a').bind('click', function() {
loadMonitorTab($(this).attr('name'));
});
}
});
}
/**
* Load monitoring tool in a new tab
*
* @param name Name of monitoring tool
*/
function loadMonitorTab(name) {
// If the tab exist, then we only need to select it
var tab = getMonitorTab();
if ($("#" + name).length) {
tab.select(name);
return;
}
switch (name) {
case 'xcatmon':
tab.add(name, 'xCAT', '', true);
loadXcatMon();
break;
case 'rmcmon':
tab.add(name, 'RMC Monitor', '', true);
loadRmcMon();
break;
case 'gangliamon':
tab.add(name, 'Ganglia', '', true);
loadGangliaMon();
break;
case 'rmcevent':
tab.add(name, 'RMC Event', '', true);
loadRmcEvent();
break;
}
tab.select(name);
}
/**
* Load tab showing 'Under contruction'
*
* @param monitorName Name of monitoring tool
* @param tab Tab area
*/
function loadUnfinish(monitorName, tab) {
var unfinishPage = $('<div></div>');
unfinishPage.append(createInfoBar('Not yet supported'));
tab.add(monitorName, 'Unfinished', unfinishPage, true);
}
/**
* Turn on or off monitoring tool
*
* @return Nothing
*/
function toggleMonitor() {
// Get the name of the monitoring tool
var name = $(this).attr('name');
// Get the status to toggle to, either on or off
var status = $(this).val();
// Start or stop monitoring plugin
var command = 'monstart';
if (status == 'Off') {
command = 'monstop' ;
}
// Start or stop monitoring on xCAT
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : command,
tgt : '',
args : name + '',
msg : ''
},
success : function(data) {
// Start or stop monitoring on remote nodes
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : command,
tgt : '',
args : name + ';-r',
msg : name + ' switched ' + status
},
success : updateMonStatus
});
}
});
}
/**
* Update the monitoring status on Monitor tab
*
* @param data Data returned from HTTP request
*/
function updateMonStatus(data) {
var rsp = data.rsp[data.rsp.length-1];
var msg = data.msg;
// Create appropriate info or warning bar
var bar = '';
if (rsp.indexOf('started') > -1 || rsp.indexOf('stopped') > -1) {
bar = createInfoBar(msg);
} else {
bar = createWarnBar('Failed to ' + msg + '. ' + rsp);
}
// Prepend info or warning bar to tab
bar.prependTo($('#monitorTab .form'));
bar.delay(4000).slideUp();
/**
* Global variables
*/
var monitorTabs; // Monitor tabs
/**
* Set the monitor tab
*
* @param o
* Tab object
* @return Nothing
*/
function setMonitorTab(o) {
monitorTabs = o;
}
/**
* Get the monitor tab
*
* @return Tab object
*/
function getMonitorTab() {
return monitorTabs;
}
/**
* Load the monitor page
*/
function loadMonitorPage() {
// If the page is already loaded
if ($('#monitor_page').children().length) {
// Do not reload the monitor page
return;
}
// Create monitor tab
var tab = new Tab();
setMonitorTab(tab);
tab.init();
$('#content').append(tab.object());
var monitorForm = $('<div class="form"></div>');
monitorForm.append('Getting monitoring status ').append(createLoader());
tab.add('monitorTab', 'Monitor', monitorForm, false);
// Get monitoring status of each tool
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'webrun',
tgt : '',
args : 'monls',
msg : ''
},
/**
* Load monitoring status
*
* @param data Data returned from HTTP request
*/
success : function(data){
data = decodeRsp(data);
// Initialize status for each tool
var statusHash = new Object();
statusHash['xcatmon'] = 'Off';
statusHash['rmcmon'] = 'Off';
statusHash['rmcevent'] = 'Off';
statusHash['gangliamon'] = 'Off';
if (data.rsp[0]) {
var tempArray = data.rsp[0].split(';');
var position = 0;
var name = '';
var status = '';
for ( var i in tempArray) {
position = tempArray[i].indexOf(':');
if (position == -1) {
continue;
}
name = tempArray[i].substr(0, position);
status = tempArray[i].substr(position + 1);
statusHash[name] = status;
}
}
// Create a status buttonset for each monitoring tool
var statusButtonHash = new Object();
for ( var name in statusHash) {
var statusButton = $('<div></div>').css({
'width': '100px',
'text-align': 'center'
});
statusButtonHash[name] = statusButton;
// Set button to correct status
if (statusHash[name] == 'On') {
statusButton.append($('<input type="radio" id="' + name + 'On" name="' + name + '" value="On" checked="checked"/><label for="' + name + 'On">On</label>'));
statusButton.append($('<input type="radio" id="' + name + 'Off" name="' + name + '" value="Off"/><label for="' + name + 'Off">Off</label>'));
} else {
statusButton.append($('<input type="radio" id="' + name + 'On" name="' + name + '" value="On"/><label for="' + name + 'On">On</label>'));
statusButton.append($('<input type="radio" id="' + name + 'Off" name="' + name + '" value="Off" checked="checked"/><label for="' + name + 'Off">Off</label>'));
}
statusButton.find('label').css({
'margin': '0px',
'padding': '0px',
'font-size': '10px',
'width': 'auto'
});
statusButton.buttonset();
// Turn on or off monitoring tool when clicked
statusButton.find('input["' + name + '"]:radio').change(toggleMonitor);
}
var monTable = $('<table></table>');
monTable.append($('<thead class="ui-widget-header"><tr><th><b>Tool</b></th><th><b>Status</b></th><th><b>Description</b></th></tr></thead>'));
var monTableBody = $('<tbody></tbody>');
monTable.append(monTableBody);
var xcatMon = $('<tr></tr>');
xcatMon.append($('<td><a href="#" name="xcatmon">xCAT</a></td>'));
xcatMon.append($('<td></td>').append(statusButtonHash['xcatmon']));
xcatMon.append($('<td>xCAT provides node status monitoring using fping on AIX and nmapon Linux. It also provides application status monitoring. The status and the appstatus columns of the nodelist table will be updated periodically with the latest status values for the nodes.</td>'));
monTableBody.append(xcatMon);
var rmcMon = $('<tr></tr>');
rmcMon.append($('<td><a href="#" name="rmcmon">RMC</a></td>'));
rmcMon.append($('<td></td>').append(statusButtonHash['rmcmon']));
rmcMon.append($('<td>Resource Monitoring and Control (RMC) is a generalized framework for managing, monitoring and manipulating resources, such as physical or logical system entities. RMC is utilized as a communication mechanism for reporting service events to the Hardware Management Console (HMC).</td>'));
monTableBody.append(rmcMon);
var rmcEvent = $('<tr></tr>');
rmcEvent.append($('<td><a href="#" name="rmcevent">RMC Event</a></td>'));
rmcEvent.append($('<td></td>').append(statusButtonHash['rmcevent']));
rmcEvent.append($('<td>Shows a list of events recorded by the RSCT Event Response resource manager in the audit log.</td>'));
monTableBody.append(rmcEvent);
var gangliaMon = $('<tr></tr>');
gangliaMon.append($('<td><a href="#" name="gangliamon">Ganglia</a></td>'));
gangliaMon.append($('<td></td>').append(statusButtonHash['gangliamon']));
gangliaMon.append($('<td>Ganglia is a scalable distributed monitoring system for high-performance computing systems such as clusters and Grids.</td>'));
monTableBody.append(gangliaMon);
// Do not word wrap
monTableBody.find('td:nth-child(1)').css('white-space', 'nowrap');
monTableBody.find('td:nth-child(3)').css({
'white-space': 'normal',
'text-align': 'left'
});
// Append info bar
$('#monitorTab div').empty().append(createInfoBar('Select a monitoring tool to use'));
$('#monitorTab .form').append(monTable);
// Open monitoring tool onclick
$('#monitorTab .form a').bind('click', function() {
loadMonitorTab($(this).attr('name'));
});
}
});
}
/**
* Load monitoring tool in a new tab
*
* @param name Name of monitoring tool
*/
function loadMonitorTab(name) {
// If the tab exist, then we only need to select it
var tab = getMonitorTab();
if ($("#" + name).length) {
tab.select(name);
return;
}
switch (name) {
case 'xcatmon':
tab.add(name, 'xCAT', '', true);
loadXcatMon();
break;
case 'rmcmon':
tab.add(name, 'RMC Monitor', '', true);
loadRmcMon();
break;
case 'gangliamon':
tab.add(name, 'Ganglia', '', true);
loadGangliaMon();
break;
case 'rmcevent':
tab.add(name, 'RMC Event', '', true);
loadRmcEvent();
break;
}
tab.select(name);
}
/**
* Load tab showing 'Under contruction'
*
* @param monitorName Name of monitoring tool
* @param tab Tab area
*/
function loadUnfinish(monitorName, tab) {
var unfinishPage = $('<div></div>');
unfinishPage.append(createInfoBar('Not yet supported'));
tab.add(monitorName, 'Unfinished', unfinishPage, true);
}
/**
* Turn on or off monitoring tool
*
* @return Nothing
*/
function toggleMonitor() {
// Get the name of the monitoring tool
var name = $(this).attr('name');
// Get the status to toggle to, either on or off
var status = $(this).val();
// Start or stop monitoring plugin
var command = 'monstart';
if (status == 'Off') {
command = 'monstop' ;
}
// Start or stop monitoring on xCAT
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : command,
tgt : '',
args : name + '',
msg : ''
},
success : function(data) {
data = decodeRsp(data);
// Start or stop monitoring on remote nodes
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : command,
tgt : '',
args : name + ';-r',
msg : name + ' switched ' + status
},
success : function(data) {
data = decodeRsp(data);
updateMonStatus(data);
}
});
}
});
}
/**
* Update the monitoring status on Monitor tab
*
* @param data Data returned from HTTP request
*/
function updateMonStatus(data) {
var rsp = data.rsp[data.rsp.length-1];
var msg = data.msg;
// Create appropriate info or warning bar
var bar = '';
if (rsp.indexOf('started') > -1 || rsp.indexOf('stopped') > -1) {
bar = createInfoBar(msg);
} else {
bar = createWarnBar('Failed to ' + msg + '. ' + rsp);
}
// Prepend info or warning bar to tab
bar.prependTo($('#monitorTab .form'));
bar.delay(4000).slideUp();
}

File diff suppressed because it is too large Load Diff

View File

@ -1,419 +1,423 @@
/**
* Global variables
*/
var xcatMonTableId = "xcatMonSettingTable";
/**
* Load xCAT monitoring
*/
function loadXcatMon() {
// Find xCAT monitoring tab
var xcatMonTab = $('#xcatmon');
xcatMonTab.append("<div id= xcatmonTable></div>");
// Show content of monsetting table
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'tabdump',
tgt : '',
args : 'monsetting',
msg : ''
},
success : loadXcatMonSetting
});
}
function loadXcatMonSetting(data) {
var apps = ""; // Contains the xcatmon config
var rsp = data.rsp;
if (!rsp.length)
return;
var apps_flag = 0;
var ping; // xcatmon ping interval
var ping_flag = 0;
// Create an info bar
var infoBar = createInfoBar('Click on a cell to edit. Click outside the table to write to the cell. Once you are finished configuring the xCAT monitor, click on Apply.');
$('#xcatmonTable').append(infoBar);
// Create xcatmon table
var xcatmonTable = new DataTable(xcatMonTableId);
// Create datatable
var dTable;
// Create table header
var header = rsp[0].split(",");
header.splice(3, 2);
header.splice(0, 1);
header[0] = "App Name";
header[1] = "Configure";
header.push('<input type="checkbox" onclick="selectAllCheckbox(event,$(this))">');
header.unshift('');
xcatmonTable.init(header);
// Create container for original table contents
var origCont = new Array();
origCont[0] = header; // Table headers
// Create container for new contents to use later updating monsetting table
var newCont = new Object();
newCont[0] = rsp[0].split(","); // Table headers
// Create container for other monsetting lines
var otherCont = new Array();
$('#xcatmonTable').append(xcatmonTable.object());
var m = 1; // Count for origCont
var n = 0;
for ( var i = 1; i < rsp.length; i++) {
var pos = rsp[i].indexOf("xcatmon"); // Only check xcatmon setting
if (pos == 1) {
if ((rsp[i].indexOf("apps") == -1) && (rsp[i].indexOf("ping") == -1)) {
var cols = rsp[i].split(',');
for ( var j = 0; j < cols.length; j++) {
if (cols[j].count('"') % 2 == 1) {
while (cols[j].count('"') % 2 == 1) {
cols[j] = cols[j] + "," + cols[j + 1];
cols.splice(j + 1, 1);
}
}
cols[j] = cols[j].replace(new RegExp('"', 'g'), '');
}
cols.splice(3, 2);
cols.splice(0, 1);
cols.push('<input type="checkbox" name="' + cols[0] + '" title="Checking this box will add/remove the app from the configured app value"/>');
cols.unshift('<span class="ui-icon ui-icon-close" onclick="deleteXcatMonRow(this)"></span>');
// Add column to table
xcatmonTable.add(cols);
origCont[m++] = cols;
} else {
if (!apps_flag) { // Check the apps setting
if (rsp[i].indexOf("apps") > -1) {
apps = rsp[i].split(',');
for ( var j = 0; j < apps.length; j++) {
if (apps[j].count('"') % 2 == 1) {
while (apps[j].count('"') % 2 == 1) {
apps[j] = apps[j] + "," + apps[j + 1];
apps.splice(j + 1, 1);
}
}
apps[j] = apps[j].replace(new RegExp('"', 'g'), '');
}
apps_flag = 1; // Set the flag to 1 to avoid this subroute
}
}
// Get into the ping settings
if (!ping_flag) {
// Check the ping interval
if (rsp[i].indexOf("ping-interval") > -1) {
ping = rsp[i].split(',');
for ( var j = 0; j < ping.length; j++) {
if (ping[j].count('"') % 2 == 1) {
while (ping[j].count('"') % 2 == 1) {
ping[j] = ping[j] + "," + ping[j + 1];
ping.splice(j + 1, 1);
}
}
ping[j] = ping[j].replace((new RegExp('"', 'g')),
'');
}
ping_flag = 1;
}
}
}
} else if (pos != 1) {
// The other monitor in the monsetting table
var otherCols = rsp[i].split(',');
for ( var k = 0; k < otherCols.length; k++) {
if (otherCols[k].count('"') % 2 == 1) {
while (otherCols[k].count('"') % 2 == 1) {
otherCols[k] = otherCols[k] + "," + otherCols[k + 1];
otherCols.splice(k + 1, 1);
}
}
otherCols[k] = otherCols[k].replace(new RegExp('"', 'g'), '');
}
otherCont[n++] = otherCols;
}
}
// If app is not in the monsetting table, then create default apps row
if (!apps_flag) {
apps = rsp[0].split(',');
apps[0] = "xcatmon";
apps[1] = "apps";
apps[2] = "";
apps[3] = "";
apps[4] = "";
}
// If the ping interval is not in the monsetting table, then create the
// default ping-interval
if (!ping_flag) {
ping = rsp[0].split(',');
ping[0] = "xcatmon";
ping[1] = "ping-interval";
// Set default ping-interval setting to 5
ping[2] = "5";
ping[3] = "";
ping[4] = "";
}
// Set checkbox to be true
var checked = apps[2].split(',');
for ( var i = 0; i < checked.length; i++) {
$("input:checkbox[name=" + checked[i] + "]").attr('checked', true);
for ( var j = 0; j < origCont.length; j++) {
if (origCont[j][1] == checked[i]) {
origCont[j].splice(3, 1);
origCont[j].push('<input type="checkbox" name="' + origCont[j][1] + '" title="Check this checkbox to add/remove the app from the configured app value." checked=true/>');
}
}
}
$(":checkbox").tooltip();
// Make the table editable
$('#' + xcatMonTableId + ' td:not(td:nth-child(1),td:last-child)').editable(function(value, settings) {
var colPos = this.cellIndex;
var rowPos = dTable.fnGetPosition(this.parentNode);
dTable.fnUpdate(value, rowPos, colPos);
return (value);
}, {
onblur : 'submit',
type : 'textarea',
placeholder : ' ',
height : '30px'
});
// Save datatable
dTable = $('#' + xcatMonTableId).dataTable({
'iDisplayLength': 50,
'bLengthChange': false,
"bScrollCollapse": true,
"sScrollY": "400px",
"sScrollX": "110%",
"bAutoWidth": true,
"oLanguage": {
"oPaginate": {
"sNext": "",
"sPrevious": ""
}
}
});
// Create action bar
var actionBar = $('<div class="actionBar"></div>');
var addRowLnk = $('<a>Add row</a>');
addRowLnk.bind('click', function(event) {
// Create container for new row
var row = new Array();
// Add delete button to row
row.push('<span class="ui-icon ui-icon-close" onclick="deleteXcatMonRow(this)"></span>');
for ( var i = 0; i < header.length - 2; i++)
row.push('');
// Add checkbox
row.push('<input type="checkbox" name="' + row[2] + '" title="Checking this checkbox will add/remove the app from the configured apps value"/>');
// Get the datatable of the table
var dTable = $('#' + xcatMonTableId).dataTable();
// Add the new row to the datatable
dTable.fnAddData(row);
// make the datatable editable
$(":checkbox[title]").tooltip();
$('#' + xcatMonTableId + ' td:not(td:nth-child(1),td:last-child)').editable(function(value, settings) {
var colPos = this.cellIndex;
var rowPos = dTable
.fnGetPosition(this.parentNode);
dTable.fnUpdate(value, rowPos,
colPos);
return (value);
}, {
onblur : 'submit',
type : 'textarea',
placeholder : ' ',
height : '30px'
});
});
// Create apply button to store the contents of the table to the monsetting table
var applyLnk = $('<a>Apply</a>');
applyLnk.bind('click', function(event) {
// Get the datatable
var dTable = $('#' + xcatMonTableId).dataTable();
// Get datatable rows
var dRows = dTable.fnGetNodes();
var count = 0;
// Create a new container for the apps value
var appValue = '';
var tableName = 'monsetting';
var closeBtn = createButton('close');
// Get the row contents
for ( var i = 0; i < dRows.length; i++) {
if (dRows[i]) {
// Get the row columns
var cols = dRows[i].childNodes;
// Create a container for the new columns
var vals = new Array();
for ( var j = 1; j < cols.length - 1; j++) {
var val = cols.item(j).firstChild.nodeValue;
if (val == ' ')
vals[j - 1] = '';
else
vals[j - 1] = val;
}
var vals_orig = new Array();
// Copy data from vals to vals_orig
for ( var p = 0; p < 2; p++) {
var val = vals[p];
vals_orig[p] = val;
}
vals.push('');
vals.push('');
vals.unshift('xcatmon');
// Stored new column to newCont
newCont[i + 1] = vals;
if (cols.item(cols.length - 1).firstChild.checked) {
vals_orig.push('<input type="checkbox" name="' + vals_orig[0] + '" title="Checking this checkbox will add/remove the app from the configured apps value" checked=true/>');
} else {
vals_orig.push('<input type="checkbox" name="' + vals_orig[0] + '" title="Checking this checkbox will add/remove the app from the configured apps value"/>');
}
// Add delete button to row
vals_orig.unshift('<span class="ui-icon ui-icon-close" onclick="deleteXcatMonRow(this)"></span>');
// Add row to origCont
origCont[i + 1] = vals_orig;
count = i + 1;
// Check checkbox for every row when merging the app name with the apps values
if (cols.item(cols.length - 1).firstChild.checked)
appValue = appValue.concat(cols.item(2).firstChild.nodeValue + ",");
}
}
count++;
// Delete the last comma of the apps value
appValue = appValue.substring(0, (appValue.length - 1));
apps[2] = appValue;
newCont[count++] = apps;
newCont[count++] = ping;
// Add to other monitor settings
for ( var j = 0; j < otherCont.length; j++) {
newCont[count++] = otherCont[j];
}
// Create save dialog
var dialogSave = $('<div id="saveDialog" align="center">Saving configuration</div>');
dialogSave.append(createLoader());
$('#xcatmon').append(dialogSave);
$("#saveDialog").dialog({
modal : true
});
$('.ui-dialog-titlebar-close').hide();
$.ajax({
type : 'POST',
url : 'lib/tabRestore.php',
dataType : 'json',
data : {
table : tableName,
cont : newCont
},
success : function(data) {
// empty the dialog.add the close button
$("#saveDialog").empty().append('<p>Configuration saved!</p>');
$("#saveDialog").append(closeBtn);
}
});
// Close button
closeBtn.bind('click', function(event) {
$("#saveDialog").dialog("destroy");
$("#saveDialog").remove();
});
// Clear the newCont
newCont = null;
newCont = new Object();
newCont[0] = rsp[0].split(",");
});
var cancelLnk = $('<a>Cancel</a>');
cancelLnk.bind('click', function(event) {
// Get the datatable for the page
var dTable = $('#' + xcatMonTableId).dataTable();
// Clear the datatable
dTable.fnClearTable();
// Add the contents of origCont to the datatable
for ( var i = 1; i < origCont.length; i++)
dTable.fnAddData(origCont[i], true);
$(":checkbox[title]").tooltip();
$('#' + xcatMonTableId + ' td:not(td:nth-child(1),td:last-child)').editable(function(value, settings) {
var colPos = this.cellIndex;
var rowPos = dTable.fnGetPosition(this.parentNode);
dTable.fnUpdate(value, rowPos, colPos);
return (value);
}, {
onblur : 'submit',
type : 'textarea',
placeholder : ' ',
height : '30px'
});
});
// Create actions menu
var actionsLnk = '<a>Actions</a>';
var actsMenu = createMenu([ addRowLnk, applyLnk, cancelLnk ]);
var actionsMenu = createMenu([ [ actionsLnk, actsMenu ] ]);
actionsMenu.superfish();
actionsMenu.css('display', 'inline-block');
actionBar.append(actionsMenu);
// Create a division to hold actions menu
var menuDiv = $('<div id="' + xcatMonTableId + '_menuDiv" class="menuDiv"></div>');
$('#' + xcatMonTableId + '_wrapper').prepend(menuDiv);
menuDiv.append(actionBar);
$('#' + xcatMonTableId + '_filter').appendTo(menuDiv);
}
/**
* Delete a row from the table
*/
function deleteXcatMonRow(obj) {
var dTable = $('#' + xcatMonTableId).dataTable();
var rows = dTable.fnGetNodes();
var tgtRow = $(obj).parent().parent().get(0);
for ( var i in rows) {
if (rows[i] == tgtRow) {
dTable.fnDeleteRow(i, null, true);
break;
}
}
/**
* Global variables
*/
var xcatMonTableId = "xcatMonSettingTable";
/**
* Load xCAT monitoring
*/
function loadXcatMon() {
// Find xCAT monitoring tab
var xcatMonTab = $('#xcatmon');
xcatMonTab.append("<div id= xcatmonTable></div>");
// Show content of monsetting table
$.ajax({
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'tabdump',
tgt : '',
args : 'monsetting',
msg : ''
},
success : function(data) {
data = decodeRsp(data);
loadXcatMonSetting(data);
}
});
}
function loadXcatMonSetting(data) {
var apps = ""; // Contains the xcatmon config
var rsp = data.rsp;
if (!rsp.length)
return;
var apps_flag = 0;
var ping; // xcatmon ping interval
var ping_flag = 0;
// Create an info bar
var infoBar = createInfoBar('Click on a cell to edit. Click outside the table to write to the cell. Once you are finished configuring the xCAT monitor, click on Apply.');
$('#xcatmonTable').append(infoBar);
// Create xcatmon table
var xcatmonTable = new DataTable(xcatMonTableId);
// Create datatable
var dTable;
// Create table header
var header = rsp[0].split(",");
header.splice(3, 2);
header.splice(0, 1);
header[0] = "App Name";
header[1] = "Configure";
header.push('<input type="checkbox" onclick="selectAllCheckbox(event,$(this))">');
header.unshift('');
xcatmonTable.init(header);
// Create container for original table contents
var origCont = new Array();
origCont[0] = header; // Table headers
// Create container for new contents to use later updating monsetting table
var newCont = new Object();
newCont[0] = rsp[0].split(","); // Table headers
// Create container for other monsetting lines
var otherCont = new Array();
$('#xcatmonTable').append(xcatmonTable.object());
var m = 1; // Count for origCont
var n = 0;
for ( var i = 1; i < rsp.length; i++) {
var pos = rsp[i].indexOf("xcatmon"); // Only check xcatmon setting
if (pos == 1) {
if ((rsp[i].indexOf("apps") == -1) && (rsp[i].indexOf("ping") == -1)) {
var cols = rsp[i].split(',');
for ( var j = 0; j < cols.length; j++) {
if (cols[j].count('"') % 2 == 1) {
while (cols[j].count('"') % 2 == 1) {
cols[j] = cols[j] + "," + cols[j + 1];
cols.splice(j + 1, 1);
}
}
cols[j] = cols[j].replace(new RegExp('"', 'g'), '');
}
cols.splice(3, 2);
cols.splice(0, 1);
cols.push('<input type="checkbox" name="' + cols[0] + '" title="Checking this box will add/remove the app from the configured app value"/>');
cols.unshift('<span class="ui-icon ui-icon-close" onclick="deleteXcatMonRow(this)"></span>');
// Add column to table
xcatmonTable.add(cols);
origCont[m++] = cols;
} else {
if (!apps_flag) { // Check the apps setting
if (rsp[i].indexOf("apps") > -1) {
apps = rsp[i].split(',');
for ( var j = 0; j < apps.length; j++) {
if (apps[j].count('"') % 2 == 1) {
while (apps[j].count('"') % 2 == 1) {
apps[j] = apps[j] + "," + apps[j + 1];
apps.splice(j + 1, 1);
}
}
apps[j] = apps[j].replace(new RegExp('"', 'g'), '');
}
apps_flag = 1; // Set the flag to 1 to avoid this subroute
}
}
// Get into the ping settings
if (!ping_flag) {
// Check the ping interval
if (rsp[i].indexOf("ping-interval") > -1) {
ping = rsp[i].split(',');
for ( var j = 0; j < ping.length; j++) {
if (ping[j].count('"') % 2 == 1) {
while (ping[j].count('"') % 2 == 1) {
ping[j] = ping[j] + "," + ping[j + 1];
ping.splice(j + 1, 1);
}
}
ping[j] = ping[j].replace((new RegExp('"', 'g')),
'');
}
ping_flag = 1;
}
}
}
} else if (pos != 1) {
// The other monitor in the monsetting table
var otherCols = rsp[i].split(',');
for ( var k = 0; k < otherCols.length; k++) {
if (otherCols[k].count('"') % 2 == 1) {
while (otherCols[k].count('"') % 2 == 1) {
otherCols[k] = otherCols[k] + "," + otherCols[k + 1];
otherCols.splice(k + 1, 1);
}
}
otherCols[k] = otherCols[k].replace(new RegExp('"', 'g'), '');
}
otherCont[n++] = otherCols;
}
}
// If app is not in the monsetting table, then create default apps row
if (!apps_flag) {
apps = rsp[0].split(',');
apps[0] = "xcatmon";
apps[1] = "apps";
apps[2] = "";
apps[3] = "";
apps[4] = "";
}
// If the ping interval is not in the monsetting table, then create the
// default ping-interval
if (!ping_flag) {
ping = rsp[0].split(',');
ping[0] = "xcatmon";
ping[1] = "ping-interval";
// Set default ping-interval setting to 5
ping[2] = "5";
ping[3] = "";
ping[4] = "";
}
// Set checkbox to be true
var checked = apps[2].split(',');
for ( var i = 0; i < checked.length; i++) {
$("input:checkbox[name=" + checked[i] + "]").attr('checked', true);
for ( var j = 0; j < origCont.length; j++) {
if (origCont[j][1] == checked[i]) {
origCont[j].splice(3, 1);
origCont[j].push('<input type="checkbox" name="' + origCont[j][1] + '" title="Check this checkbox to add/remove the app from the configured app value." checked=true/>');
}
}
}
$(":checkbox").tooltip();
// Make the table editable
$('#' + xcatMonTableId + ' td:not(td:nth-child(1),td:last-child)').editable(function(value, settings) {
var colPos = this.cellIndex;
var rowPos = dTable.fnGetPosition(this.parentNode);
dTable.fnUpdate(value, rowPos, colPos);
return (value);
}, {
onblur : 'submit',
type : 'textarea',
placeholder : ' ',
height : '30px'
});
// Save datatable
dTable = $('#' + xcatMonTableId).dataTable({
'iDisplayLength': 50,
'bLengthChange': false,
"bScrollCollapse": true,
"sScrollY": "400px",
"sScrollX": "110%",
"bAutoWidth": true,
"oLanguage": {
"oPaginate": {
"sNext": "",
"sPrevious": ""
}
}
});
// Create action bar
var actionBar = $('<div class="actionBar"></div>');
var addRowLnk = $('<a>Add row</a>');
addRowLnk.bind('click', function(event) {
// Create container for new row
var row = new Array();
// Add delete button to row
row.push('<span class="ui-icon ui-icon-close" onclick="deleteXcatMonRow(this)"></span>');
for ( var i = 0; i < header.length - 2; i++)
row.push('');
// Add checkbox
row.push('<input type="checkbox" name="' + row[2] + '" title="Checking this checkbox will add/remove the app from the configured apps value"/>');
// Get the datatable of the table
var dTable = $('#' + xcatMonTableId).dataTable();
// Add the new row to the datatable
dTable.fnAddData(row);
// make the datatable editable
$(":checkbox[title]").tooltip();
$('#' + xcatMonTableId + ' td:not(td:nth-child(1),td:last-child)').editable(function(value, settings) {
var colPos = this.cellIndex;
var rowPos = dTable
.fnGetPosition(this.parentNode);
dTable.fnUpdate(value, rowPos,
colPos);
return (value);
}, {
onblur : 'submit',
type : 'textarea',
placeholder : ' ',
height : '30px'
});
});
// Create apply button to store the contents of the table to the monsetting table
var applyLnk = $('<a>Apply</a>');
applyLnk.bind('click', function(event) {
// Get the datatable
var dTable = $('#' + xcatMonTableId).dataTable();
// Get datatable rows
var dRows = dTable.fnGetNodes();
var count = 0;
// Create a new container for the apps value
var appValue = '';
var tableName = 'monsetting';
var closeBtn = createButton('close');
// Get the row contents
for ( var i = 0; i < dRows.length; i++) {
if (dRows[i]) {
// Get the row columns
var cols = dRows[i].childNodes;
// Create a container for the new columns
var vals = new Array();
for ( var j = 1; j < cols.length - 1; j++) {
var val = cols.item(j).firstChild.nodeValue;
if (val == ' ')
vals[j - 1] = '';
else
vals[j - 1] = val;
}
var vals_orig = new Array();
// Copy data from vals to vals_orig
for ( var p = 0; p < 2; p++) {
var val = vals[p];
vals_orig[p] = val;
}
vals.push('');
vals.push('');
vals.unshift('xcatmon');
// Stored new column to newCont
newCont[i + 1] = vals;
if (cols.item(cols.length - 1).firstChild.checked) {
vals_orig.push('<input type="checkbox" name="' + vals_orig[0] + '" title="Checking this checkbox will add/remove the app from the configured apps value" checked=true/>');
} else {
vals_orig.push('<input type="checkbox" name="' + vals_orig[0] + '" title="Checking this checkbox will add/remove the app from the configured apps value"/>');
}
// Add delete button to row
vals_orig.unshift('<span class="ui-icon ui-icon-close" onclick="deleteXcatMonRow(this)"></span>');
// Add row to origCont
origCont[i + 1] = vals_orig;
count = i + 1;
// Check checkbox for every row when merging the app name with the apps values
if (cols.item(cols.length - 1).firstChild.checked)
appValue = appValue.concat(cols.item(2).firstChild.nodeValue + ",");
}
}
count++;
// Delete the last comma of the apps value
appValue = appValue.substring(0, (appValue.length - 1));
apps[2] = appValue;
newCont[count++] = apps;
newCont[count++] = ping;
// Add to other monitor settings
for ( var j = 0; j < otherCont.length; j++) {
newCont[count++] = otherCont[j];
}
// Create save dialog
var dialogSave = $('<div id="saveDialog" align="center">Saving configuration</div>');
dialogSave.append(createLoader());
$('#xcatmon').append(dialogSave);
$("#saveDialog").dialog({
modal : true
});
$('.ui-dialog-titlebar-close').hide();
$.ajax({
type : 'POST',
url : 'lib/tabRestore.php',
dataType : 'json',
data : {
table : tableName,
cont : newCont
},
success : function(data) {
// do not put in until tabRestore.php has been updated: data = decodeRsp(data);
// empty the dialog.add the close button
$("#saveDialog").empty().append('<p>Configuration saved!</p>');
$("#saveDialog").append(closeBtn);
}
});
// Close button
closeBtn.bind('click', function(event) {
$("#saveDialog").dialog("destroy");
$("#saveDialog").remove();
});
// Clear the newCont
newCont = null;
newCont = new Object();
newCont[0] = rsp[0].split(",");
});
var cancelLnk = $('<a>Cancel</a>');
cancelLnk.bind('click', function(event) {
// Get the datatable for the page
var dTable = $('#' + xcatMonTableId).dataTable();
// Clear the datatable
dTable.fnClearTable();
// Add the contents of origCont to the datatable
for ( var i = 1; i < origCont.length; i++)
dTable.fnAddData(origCont[i], true);
$(":checkbox[title]").tooltip();
$('#' + xcatMonTableId + ' td:not(td:nth-child(1),td:last-child)').editable(function(value, settings) {
var colPos = this.cellIndex;
var rowPos = dTable.fnGetPosition(this.parentNode);
dTable.fnUpdate(value, rowPos, colPos);
return (value);
}, {
onblur : 'submit',
type : 'textarea',
placeholder : ' ',
height : '30px'
});
});
// Create actions menu
var actionsLnk = '<a>Actions</a>';
var actsMenu = createMenu([ addRowLnk, applyLnk, cancelLnk ]);
var actionsMenu = createMenu([ [ actionsLnk, actsMenu ] ]);
actionsMenu.superfish();
actionsMenu.css('display', 'inline-block');
actionBar.append(actionsMenu);
// Create a division to hold actions menu
var menuDiv = $('<div id="' + xcatMonTableId + '_menuDiv" class="menuDiv"></div>');
$('#' + xcatMonTableId + '_wrapper').prepend(menuDiv);
menuDiv.append(actionBar);
$('#' + xcatMonTableId + '_filter').appendTo(menuDiv);
}
/**
* Delete a row from the table
*/
function deleteXcatMonRow(obj) {
var dTable = $('#' + xcatMonTableId).dataTable();
var rows = dTable.fnGetNodes();
var tgtRow = $(obj).parent().parent().get(0);
for ( var i in rows) {
if (rows[i] == tgtRow) {
dTable.fnDeleteRow(i, null, true);
break;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,296 +1,308 @@
/**
* Load nodeset page
*
* @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 : ''
},
success : setOSImageCookies
});
// 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;
}
// Create nodeset form
var nodesetForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'nodesetStatusBar' + inst;
var statBar = createStatusBar(statBarId).hide();
// 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(statBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
nodesetForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var imageFS = $('<fieldset></fieldset>');
var imageLegend = $('<legend>Image</legend>');
imageFS.append(imageLegend);
nodesetForm.append(imageFS);
var imageAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
imageFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
imageFS.append(imageAttr);
// Create target node or group
var tgt = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to set the boot state for"/></div>');
vmAttr.append(tgt);
// Create boot type drop down
var type = $('<div></div>');
var typeLabel = $('<label>Boot type:</label>');
var typeSelect = $('<select id="bootType" name="bootType" title="The type of network booting to use for this node"></select>');
typeSelect.append('<option value="zvm">zvm</option>'
+ '<option value="install">pxe</option>'
+ '<option value="iscsiboot">yaboot</option>'
);
type.append(typeLabel);
type.append(typeSelect);
imageAttr.append(type);
// Create operating system image input
var os = $('<div></div>');
var osLabel = $('<label>Operating system image:</label>');
var osSelect = $('<select name="os" title="The operating system image to be installed on this node"></select>');
osSelect.append($('<option value=""></option>'));
var imageNames = $.cookie('xcat_imagenames').split(',');
if (imageNames) {
imageNames.sort();
for (var i in imageNames) {
osSelect.append($('<option value="' + imageNames[i] + '">' + imageNames[i] + '</option>'));
}
}
os.append(osLabel);
os.append(osSelect);
imageAttr.append(os);
// Generate tooltips
nodesetForm.find('div input[title],select').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.css({
'width': '80px',
'display': 'block'
});
okBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').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 type
var type = $('#' + tabId + ' select[id=bootType]').val();
// Get operating system image
var os = $('#' + tabId + ' select[name=os]').val();
// 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,
msg : 'cmd=nodeadd;inst=' + inst
},
success : updateNodesetStatus
});
// Show status bar
statBar.show();
} else {
// Show warning message
var warn = createWarnBar('You are missing some values!');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
nodesetForm.append(okBtn);
// Append to discover tab
tab.add(tabId, 'Nodeset', nodesetForm, true);
// Select new tab
tab.select(tabId);
}
/**
* Update nodeset status
*
* @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 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 operating system image
var os = $('#' + tabId + ' select[name=os]').val();
/**
* (2) Update /etc/hosts
*/
if (cmd == 'nodeadd') {
if (rsp.length) {
$('#' + statBarId).find('img').hide();
$('#' + statBarId).find('div').append('<pre>(Error) Failed to create node definition</pre>');
} 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('<pre>Node definition created for ' + tgtNodesStr + '</pre>');
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'makehosts',
tgt : '',
args : '',
msg : 'cmd=makehosts;inst=' + inst
},
success : updateNodesetStatus
});
}
}
/**
* (4) Update DNS
*/
else if (cmd == 'makehosts') {
// If no output, no errors occurred
if (rsp.length) {
$('#' + statBarId).find('div').append('<pre>(Error) Failed to update /etc/hosts</pre>');
} else {
$('#' + statBarId).find('div').append('<pre>/etc/hosts updated</pre>');
}
// Go straight to prepare node for boot
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'nodeset',
tgt : tgts,
args : 'osimage=' + os,
msg : 'cmd=nodeset;inst=' + inst
},
success : updateNodesetStatus
});
}
/**
* (5) 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();
}
/**
* Load nodeset page
*
* @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 : ''
},
success : function(data) {
data = decodeRsp(data);
setOSImageCookies(data);
}
});
// 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;
}
// Create nodeset form
var nodesetForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'nodesetStatusBar' + inst;
var statBar = createStatusBar(statBarId).hide();
// 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(statBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
nodesetForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var imageFS = $('<fieldset></fieldset>');
var imageLegend = $('<legend>Image</legend>');
imageFS.append(imageLegend);
nodesetForm.append(imageFS);
var imageAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
imageFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
imageFS.append(imageAttr);
// Create target node or group
var tgt = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to set the boot state for"/></div>');
vmAttr.append(tgt);
// Create boot type drop down
var type = $('<div></div>');
var typeLabel = $('<label>Boot type:</label>');
var typeSelect = $('<select id="bootType" name="bootType" title="The type of network booting to use for this node"></select>');
typeSelect.append('<option value="zvm">zvm</option>'
+ '<option value="install">pxe</option>'
+ '<option value="iscsiboot">yaboot</option>'
);
type.append(typeLabel);
type.append(typeSelect);
imageAttr.append(type);
// Create operating system image input
var os = $('<div></div>');
var osLabel = $('<label>Operating system image:</label>');
var osSelect = $('<select name="os" title="The operating system image to be installed on this node"></select>');
osSelect.append($('<option value=""></option>'));
var imageNames = $.cookie('xcat_imagenames').split(',');
if (imageNames) {
imageNames.sort();
for (var i in imageNames) {
osSelect.append($('<option value="' + imageNames[i] + '">' + imageNames[i] + '</option>'));
}
}
os.append(osLabel);
os.append(osSelect);
imageAttr.append(os);
// Generate tooltips
nodesetForm.find('div input[title],select').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.css({
'width': '80px',
'display': 'block'
});
okBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').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 type
var type = $('#' + tabId + ' select[id=bootType]').val();
// Get operating system image
var os = $('#' + tabId + ' select[name=os]').val();
// 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,
msg : 'cmd=nodeadd;inst=' + inst
},
success : function(data) {
data = decodeRsp(data);
updateNodesetStatus(data);
}
});
// Show status bar
statBar.show();
} else {
// Show warning message
var warn = createWarnBar('You are missing some values!');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
nodesetForm.append(okBtn);
// Append to discover tab
tab.add(tabId, 'Nodeset', nodesetForm, true);
// Select new tab
tab.select(tabId);
}
/**
* Update nodeset status
*
* @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 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 operating system image
var os = $('#' + tabId + ' select[name=os]').val();
/**
* (2) Update /etc/hosts
*/
if (cmd == 'nodeadd') {
if (rsp.length) {
$('#' + statBarId).find('img').hide();
$('#' + statBarId).find('div').append('<pre>(Error) Failed to create node definition</pre>');
} 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('<pre>Node definition created for ' + tgtNodesStr + '</pre>');
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'makehosts',
tgt : '',
args : '',
msg : 'cmd=makehosts;inst=' + inst
},
success : function(data) {
data = decodeRsp(data);
updateNodesetStatus(data);
}
});
}
}
/**
* (4) Update DNS
*/
else if (cmd == 'makehosts') {
// If no output, no errors occurred
if (rsp.length) {
$('#' + statBarId).find('div').append('<pre>(Error) Failed to update /etc/hosts</pre>');
} else {
$('#' + statBarId).find('div').append('<pre>/etc/hosts updated</pre>');
}
// Go straight to prepare node for boot
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'nodeset',
tgt : tgts,
args : 'osimage=' + os,
msg : 'cmd=nodeset;inst=' + inst
},
success : function(data) {
data = decodeRsp(data);
updateNodesetStatus(data);
}
});
}
/**
* (5) 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();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,220 +1,223 @@
/**
* Load netboot page
*
* @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;
}
// Create netboot form
var netbootForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'netbootStatusBar' + inst;
var statusBar = createStatusBar(statBarId).hide();
// 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(statusBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
netbootForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var optionsFS = $('<fieldset></fieldset>');
var optionsLegend = $('<legend>Options</legend>');
optionsFS.append(optionsLegend);
netbootForm.append(optionsFS);
var optionsAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
optionsFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
optionsFS.append(optionsAttr);
// Create target node or group input
var target = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to boot to network"/></div>');
vmAttr.append(target);
// Create options
var optsLabel = $('<label>Options:</label>');
var optsList = $('<ul></ul>');
optionsAttr.append(optsList);
// Create boot order checkbox
var opt = $('<li></li>');
var bootOrderChkBox = $('<input type="checkbox" id="s" name="s"/>');
opt.append(bootOrderChkBox);
opt.append('Set the boot device order');
optsList.append(opt);
// Create boot order input
var bootOrder = $('<li><label>Boot order:</label><input type="text" name="bootOrder"/></li>');
bootOrder.hide();
optsList.append(bootOrder);
// Create force reboot checkbox
optsList.append('<li><input type="checkbox" id="F" name="F"/>Force reboot</li>');
// Create force shutdown checkbox
optsList.append('<li><input type="checkbox" id="f" name="f"/>Force immediate shutdown of the partition</li>');
if (osHash['AIX']) {
// Create iscsi dump checkbox
optsList.append('<li><input type="checkbox" id="I" name="I"/>Do a iscsi dump on AIX</li>');
}
// 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
optsList.append('<div><label style="width: 40px;">IPL:</label><input type="text" name="ipl" title="The virtual address to IPL"/></div>');
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.css({
'width': '80px',
'display': 'block'
});
okBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').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 += ';';
}
}
// 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();
}
// 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
},
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).parents('.ui-tabs-panel'));
}
});
netbootForm.append(okBtn);
// Append to discover tab
tab.add(newTabId, 'Boot', netbootForm, true);
// Select new tab
tab.select(newTabId);
/**
* Load netboot page
*
* @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;
}
// Create netboot form
var netbootForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'netbootStatusBar' + inst;
var statusBar = createStatusBar(statBarId).hide();
// 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(statusBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
netbootForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var optionsFS = $('<fieldset></fieldset>');
var optionsLegend = $('<legend>Options</legend>');
optionsFS.append(optionsLegend);
netbootForm.append(optionsFS);
var optionsAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
optionsFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
optionsFS.append(optionsAttr);
// Create target node or group input
var target = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to boot to network"/></div>');
vmAttr.append(target);
// Create options
var optsLabel = $('<label>Options:</label>');
var optsList = $('<ul></ul>');
optionsAttr.append(optsList);
// Create boot order checkbox
var opt = $('<li></li>');
var bootOrderChkBox = $('<input type="checkbox" id="s" name="s"/>');
opt.append(bootOrderChkBox);
opt.append('Set the boot device order');
optsList.append(opt);
// Create boot order input
var bootOrder = $('<li><label>Boot order:</label><input type="text" name="bootOrder"/></li>');
bootOrder.hide();
optsList.append(bootOrder);
// Create force reboot checkbox
optsList.append('<li><input type="checkbox" id="F" name="F"/>Force reboot</li>');
// Create force shutdown checkbox
optsList.append('<li><input type="checkbox" id="f" name="f"/>Force immediate shutdown of the partition</li>');
if (osHash['AIX']) {
// Create iscsi dump checkbox
optsList.append('<li><input type="checkbox" id="I" name="I"/>Do a iscsi dump on AIX</li>');
}
// 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
optsList.append('<div><label style="width: 40px;">IPL:</label><input type="text" name="ipl" title="The virtual address to IPL"/></div>');
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.css({
'width': '80px',
'display': 'block'
});
okBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').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 += ';';
}
}
// 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();
}
// 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
},
success : function(data) {
data = decodeRsp(data);
updateStatusBar(data);
}
});
// Show status bar
statusBar.show();
} else {
// Show warning message
var warn = createWarnBar('Please provide a value for each missing field.');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
netbootForm.append(okBtn);
// Append to discover tab
tab.add(newTabId, 'Boot', netbootForm, true);
// Select new tab
tab.select(newTabId);
}

View File

@ -1,171 +1,174 @@
/**
* Load rscan page
*
* @param tgtNodes Targets to run rscan against
*/
function loadRscanPage(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 = 'rscanTab' + inst;
while ($('#' + newTabId).length) {
// If one already exists, generate another one
inst = inst + 1;
newTabId = 'rscanTab' + inst;
}
// Create rscan form
var rscanForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'rscanStatusBar' + inst;
var statBar = createStatusBar(statBarId).hide();
// Create loader
var loader = createLoader('rscanLoader');
statBar.find('div').append(loader);
// Create info bar
var infoBar = createInfoBar('Collects node information from one or more hardware control points');
rscanForm.append(statBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
rscanForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var optionsFS = $('<fieldset></fieldset>');
var optionsLegend = $('<legend>Options</legend>');
optionsFS.append(optionsLegend);
rscanForm.append(optionsFS);
var optionsAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
optionsFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
optionsFS.append(optionsAttr);
// Create target node or group input
var target = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to scan"/></div>');
vmAttr.append(target);
// Create options
var optsList = $('<ul></ul>');
optionsAttr.append(optsList);
optsList.append('<li><input type="checkbox" name="u"/>Updates and then prints out node definitions in the xCAT database for CEC/BPA</li>');
optsList.append('<li><input type="checkbox" name="w"/>Writes output to xCAT database</li>');
optsList.append('<li><input type="checkbox" name="x"/>XML format</li>');
optsList.append('<li><input type="checkbox" name="z"/>Stanza formated output</li>');
// Generate tooltips
rscanForm.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.css({
'width': '80px',
'display': 'block'
});
okBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').find('.ui-state-error').remove();
// Check inputs
var ready = true;
var inputs = $("#" + newTabId + " input[type='text']");
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;
// 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();
// Disable all inputs and Ok button
$('#' + newTabId + ' input').attr('disabled', 'disabled');
$(this).attr('disabled', 'true');
/**
* (1) Scan
*/
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'rscan',
tgt : tgts,
args : optStr,
msg : 'out=' + statBarId + ';cmd=rscan;tgt=' + tgts
},
success : updateStatusBar
});
// Show status bar
statBar.show();
} else {
// Show warning message
var warn = createWarnBar('Please provide a value for each missing field.');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
rscanForm.append(okBtn);
// Append to discover tab
tab.add(newTabId, 'Scan', rscanForm, true);
// Select new tab
tab.select(newTabId);
/**
* Load rscan page
*
* @param tgtNodes Targets to run rscan against
*/
function loadRscanPage(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 = 'rscanTab' + inst;
while ($('#' + newTabId).length) {
// If one already exists, generate another one
inst = inst + 1;
newTabId = 'rscanTab' + inst;
}
// Create rscan form
var rscanForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'rscanStatusBar' + inst;
var statBar = createStatusBar(statBarId).hide();
// Create loader
var loader = createLoader('rscanLoader');
statBar.find('div').append(loader);
// Create info bar
var infoBar = createInfoBar('Collects node information from one or more hardware control points');
rscanForm.append(statBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
rscanForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var optionsFS = $('<fieldset></fieldset>');
var optionsLegend = $('<legend>Options</legend>');
optionsFS.append(optionsLegend);
rscanForm.append(optionsFS);
var optionsAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
optionsFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
optionsFS.append(optionsAttr);
// Create target node or group input
var target = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to scan"/></div>');
vmAttr.append(target);
// Create options
var optsList = $('<ul></ul>');
optionsAttr.append(optsList);
optsList.append('<li><input type="checkbox" name="u"/>Updates and then prints out node definitions in the xCAT database for CEC/BPA</li>');
optsList.append('<li><input type="checkbox" name="w"/>Writes output to xCAT database</li>');
optsList.append('<li><input type="checkbox" name="x"/>XML format</li>');
optsList.append('<li><input type="checkbox" name="z"/>Stanza formated output</li>');
// Generate tooltips
rscanForm.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.css({
'width': '80px',
'display': 'block'
});
okBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').find('.ui-state-error').remove();
// Check inputs
var ready = true;
var inputs = $("#" + newTabId + " input[type='text']");
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;
// 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();
// Disable all inputs and Ok button
$('#' + newTabId + ' input').attr('disabled', 'disabled');
$(this).attr('disabled', 'true');
/**
* (1) Scan
*/
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'rscan',
tgt : tgts,
args : optStr,
msg : 'out=' + statBarId + ';cmd=rscan;tgt=' + tgts
},
success : function(data) {
data = decodeRsp(data);
updateStatusBar(data);
}
});
// Show status bar
statBar.show();
} else {
// Show warning message
var warn = createWarnBar('Please provide a value for each missing field.');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
rscanForm.append(okBtn);
// Append to discover tab
tab.add(newTabId, 'Scan', rscanForm, true);
// Select new tab
tab.select(newTabId);
}

View File

@ -1,403 +1,409 @@
/**
* Load updatenode page
*
* @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 : ''
},
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 rscan form
var updatenodeForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'updatenodeStatusBar' + inst;
var statusBar = createStatusBar(statBarId).hide();
// 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(statusBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
updatenodeForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var optionsFS = $('<fieldset></fieldset>');
var optionsLegend = $('<legend>Options</legend>');
optionsFS.append(optionsLegend);
updatenodeForm.append(optionsFS);
var optionsAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
optionsFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
optionsFS.append(optionsAttr);
// Create target node or group input
var tgt = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to update"/></div>');
vmAttr.append(tgt);
// Create options
var optionsList = $('<ul></ul>');
optionsAttr.append(optionsList);
// Create update all software checkbox (only AIX)
if (osHash['AIX']) {
var updateAllOption = $('<li></li>');
var updateAllChkBox = $('<input type="checkbox" id="A" name="A"/>');
updateAllOption.append(updateAllChkBox);
optionsList.append(updateAllOption);
updateAllOption.append('Install or update all software contained in the source directory');
// Create source directory input
var allSwScrDirectory = $('<li><label style="vertical-align: middle">Source directory:</label><input type="text" id="allSwSrcDirectory" name="allSwSrcDirectory"/></li>');
// 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 = $('<li></li>');
var updateChkBox = $('<input type="checkbox" id="S" name="S"/>');
optionsList.append(updateOption);
updateOption.append(updateChkBox);
updateOption.append('Update existing software');
// Create source directory input
var scrDirectory = $('<li><label style="vertical-align: middle">Source directory:</label><input type="text" id="srcDirectory" name="srcDirectory" title="You must give the source directory containing the updated software packages"/></li>');
// 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 = $('<li><label style="vertical-align: middle">otherpkgs:</label><input type="text" id="otherpkgs" name="otherpkgs"/></li>');
otherPkgs.hide();
optionsList.append(otherPkgs);
// Create RPM flags input (only AIX)
var aixRpmFlags = $('<li><label>rpm_flags:</label><input type="text" name="rpm_flags"/></li>');
aixRpmFlags.hide();
optionsList.append(aixRpmFlags);
// Create installp flags input (only AIX)
var aixInstallPFlags = $('<li><label>installp_flags:</label><input type="text" name="installp_flags"/></li>');
aixInstallPFlags.hide();
optionsList.append(aixInstallPFlags);
// Create emgr flags input (only AIX)
var aixEmgrFlags = $('<li><label>emgr_flags:</label><input type="text" name="emgr_flags"/></li>');
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 = $('<li></li>');
var postChkBox = $('<input type="checkbox" id="P" name="P"/>');
optionsList.append(postOption);
postOption.append(postChkBox);
postOption.append('Run postscripts');
var postscripts = $('<li><label style="vertical-align: middle">Postscripts:</label><input type="text" id="postscripts" name="postscripts" title="You must give the postscript(s) to run"/></li>');
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('<li><input type="checkbox" id="F" name="F"/>Distribute and synchronize files</li>');
optionsList.append('<li><input type="checkbox" id="k" name="k"/>Update the ssh keys and host keys for the service nodes and compute nodes</li>');
// Create update OS checkbox
if (!osHash['AIX']) {
var osOption = $('<li></li>');
var osChkBox = $('<input type="checkbox" id="o" name="o"/>');
optionsList.append(osOption);
osOption.append(osChkBox);
osOption.append('Update the operating system');
var os = $('<li></li>').hide();
var osLabel = $('<label>Operating system:</label>');
var osInput = $('<input type="text" name="os" title="You must give the operating system to upgrade to, e.g. rhel5.5"/>');
osInput.one('focus', function(){
var tmp = $.cookie('xcat_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 updateBtn = createButton('Update');
updateBtn.css({
'width': '80px',
'display': 'block'
});
updateBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').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();
// 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
});
// Show status bar
statusBar.show();
} else {
// Show warning message
var warn = createWarnBar('You are missing some values');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
updatenodeForm.append(updateBtn);
// Append to discover tab
tab.add(newTabId, 'Update', updatenodeForm, true);
// Select new tab
tab.select(newTabId);
/**
* Load updatenode page
*
* @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 : ''
},
success : function(data) {
data = decodeRsp(data);
setOSImageCookies(data);
}
});
// 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 rscan form
var updatenodeForm = $('<div class="form"></div>');
// Create status bar
var statBarId = 'updatenodeStatusBar' + inst;
var statusBar = createStatusBar(statBarId).hide();
// 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(statusBar, infoBar);
// Create VM fieldset
var vmFS = $('<fieldset></fieldset>');
var vmLegend = $('<legend>Virtual Machine</legend>');
vmFS.append(vmLegend);
updatenodeForm.append(vmFS);
var vmAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
vmFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/computer.png"></img></div>'));
vmFS.append(vmAttr);
// Create options fieldset
var optionsFS = $('<fieldset></fieldset>');
var optionsLegend = $('<legend>Options</legend>');
optionsFS.append(optionsLegend);
updatenodeForm.append(optionsFS);
var optionsAttr = $('<div style="display: inline-table; vertical-align: middle;"></div>');
optionsFS.append($('<div style="display: inline-table; vertical-align: middle;"><img src="images/provision/setting.png" style="width: 70px;"></img></div>'));
optionsFS.append(optionsAttr);
// Create target node or group input
var tgt = $('<div><label>Target node range:</label><input type="text" name="target" value="' + tgtNodes + '" title="The node or node range to update"/></div>');
vmAttr.append(tgt);
// Create options
var optionsList = $('<ul></ul>');
optionsAttr.append(optionsList);
// Create update all software checkbox (only AIX)
if (osHash['AIX']) {
var updateAllOption = $('<li></li>');
var updateAllChkBox = $('<input type="checkbox" id="A" name="A"/>');
updateAllOption.append(updateAllChkBox);
optionsList.append(updateAllOption);
updateAllOption.append('Install or update all software contained in the source directory');
// Create source directory input
var allSwScrDirectory = $('<li><label style="vertical-align: middle">Source directory:</label><input type="text" id="allSwSrcDirectory" name="allSwSrcDirectory"/></li>');
// 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 = $('<li></li>');
var updateChkBox = $('<input type="checkbox" id="S" name="S"/>');
optionsList.append(updateOption);
updateOption.append(updateChkBox);
updateOption.append('Update existing software');
// Create source directory input
var scrDirectory = $('<li><label style="vertical-align: middle">Source directory:</label><input type="text" id="srcDirectory" name="srcDirectory" title="You must give the source directory containing the updated software packages"/></li>');
// 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 = $('<li><label style="vertical-align: middle">otherpkgs:</label><input type="text" id="otherpkgs" name="otherpkgs"/></li>');
otherPkgs.hide();
optionsList.append(otherPkgs);
// Create RPM flags input (only AIX)
var aixRpmFlags = $('<li><label>rpm_flags:</label><input type="text" name="rpm_flags"/></li>');
aixRpmFlags.hide();
optionsList.append(aixRpmFlags);
// Create installp flags input (only AIX)
var aixInstallPFlags = $('<li><label>installp_flags:</label><input type="text" name="installp_flags"/></li>');
aixInstallPFlags.hide();
optionsList.append(aixInstallPFlags);
// Create emgr flags input (only AIX)
var aixEmgrFlags = $('<li><label>emgr_flags:</label><input type="text" name="emgr_flags"/></li>');
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 = $('<li></li>');
var postChkBox = $('<input type="checkbox" id="P" name="P"/>');
optionsList.append(postOption);
postOption.append(postChkBox);
postOption.append('Run postscripts');
var postscripts = $('<li><label style="vertical-align: middle">Postscripts:</label><input type="text" id="postscripts" name="postscripts" title="You must give the postscript(s) to run"/></li>');
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('<li><input type="checkbox" id="F" name="F"/>Distribute and synchronize files</li>');
optionsList.append('<li><input type="checkbox" id="k" name="k"/>Update the ssh keys and host keys for the service nodes and compute nodes</li>');
// Create update OS checkbox
if (!osHash['AIX']) {
var osOption = $('<li></li>');
var osChkBox = $('<input type="checkbox" id="o" name="o"/>');
optionsList.append(osOption);
osOption.append(osChkBox);
osOption.append('Update the operating system');
var os = $('<li></li>').hide();
var osLabel = $('<label>Operating system:</label>');
var osInput = $('<input type="text" name="os" title="You must give the operating system to upgrade to, e.g. rhel5.5"/>');
osInput.one('focus', function(){
var tmp = $.cookie('xcat_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 updateBtn = createButton('Update');
updateBtn.css({
'width': '80px',
'display': 'block'
});
updateBtn.bind('click', function(event) {
// Remove any warning messages
$(this).parents('.ui-tabs-panel').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();
// 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 : function(data) {
data = decodeRsp(data);
updateStatusBar(data);
}
});
// Show status bar
statusBar.show();
} else {
// Show warning message
var warn = createWarnBar('You are missing some values');
warn.prependTo($(this).parents('.ui-tabs-panel'));
}
});
updatenodeForm.append(updateBtn);
// Append to discover tab
tab.add(newTabId, 'Update', updatenodeForm, true);
// Select new tab
tab.select(newTabId);
}

File diff suppressed because it is too large Load Diff

View File

@ -1,252 +1,258 @@
/**
* Global variables
*/
var provisionTabs; // Provision tabs
/**
* Set the provision tab
*
* @param obj Tab object
*/
function setProvisionTab(obj) {
provisionTabs = obj;
}
/**
* Get the provision tab
*
* @param Nothing
* @return Tab object
*/
function getProvisionTab() {
return provisionTabs;
}
/**
* Load provision page
*/
function loadProvisionPage() {
// If the page is loaded
if ($('#content').children().length) {
// Do not load again
return;
}
// Get OS image names
if (!$.cookie('xcat_imagenames')){
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'tabdump',
tgt : '',
args : 'osimage',
msg : ''
},
success : setOSImageCookies
});
}
// Get groups
if (!$.cookie('xcat_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 = $('<div class="form"></div>');
provPg.append(infoBar);
// Create provision tab
var tab = new Tab('provisionPageTabs');
setProvisionTab(tab);
tab.init();
$('#content').append(tab.object());
// Create radio buttons for platforms
var hwList = $('<ol>Platforms available:</ol>');
var esx = $('<li><input type="radio" name="hw" value="esx" disabled/>ESX</li>');
var kvm = $('<li><input type="radio" name="hw" value="kvm" disabled/>KVM</li>');
var zvm = $('<li><input type="radio" name="hw" value="zvm" checked/>z\/VM</li>');
var ipmi = $('<li><input type="radio" name="hw" value="ipmi" disabled/>iDataPlex</li>');
var blade = $('<li><input type="radio" name="hw" value="blade" disabled/>BladeCenter</li>');
var hmc = $('<li><input type="radio" name="hw" value="hmc" disabled/>System p</li>');
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;
}
// Create an instance of the plugin
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;
}
// Select tab
tab.add(newTabId, title, '', true);
tab.select(newTabId);
plugin.loadProvisionPage(newTabId);
});
provPg.append(okBtn);
// Create resources tab
var resrcPg = $('<div class="form"></div>');
// Create info bar
var resrcInfoBar = createInfoBar('Select a platform to view its current resources.');
resrcPg.append(resrcInfoBar);
// Create radio buttons for platforms
var rsrcHwList = $('<ol>Platforms available:</ol>');
esx = $('<li><input type="radio" name="rsrcHw" value="esx" disabled/>ESX</li>');
kvm = $('<li><input type="radio" name="rsrcHw" value="kvm" disabled/>KVM</li>');
zvm = $('<li><input type="radio" name="rsrcHw" value="zvm" checked/>z\/VM</li>');
ipmi = $('<li><input type="radio" name="rsrcHw" value="ipmi" disabled/>iDataPlex</li>');
blade = $('<li><input type="radio" name="rsrcHw" value="blade" disabled/>BladeCenter</li>');
hmc = $('<li><input type="radio" name="rsrcHw" value="hmc" disabled/>System p</li>');
rsrcHwList.append(esx);
rsrcHwList.append(kvm);
rsrcHwList.append(zvm);
rsrcHwList.append(blade);
rsrcHwList.append(ipmi);
rsrcHwList.append(hmc);
resrcPg.append(rsrcHwList);
var okBtn = createButton('Ok');
okBtn.bind('click', function(event) {
// Get hardware that was selected
var hw = $(this).parent().find('input[name="rsrcHw"]:checked').val();
// Generate new tab ID
var newTabId = hw + 'ResourceTab';
if (!$('#' + newTabId).length) {
// Create loader
var loader = $('<center></center>').append(createLoader(hw + 'ResourceLoader'));
// Create an instance of the plugin
var plugin = null;
var displayName = "";
switch (hw) {
case "kvm":
plugin = new kvmPlugin();
displayName = "KVM";
break;
case "esx":
plugin = new esxPlugin();
displayName = "ESX";
break;
case "blade":
plugin = new bladePlugin();
displayName = "BladeCenter";
break;
case "hmc":
plugin = new hmcPlugin();
displayName = "System p";
break;
case "ipmi":
plugin = new ipmiPlugin();
displayName = "iDataPlex";
break;
case "zvm":
plugin = new zvmPlugin();
displayName = "z\/VM";
break;
}
// Add resource tab and load resources
tab.add(newTabId, displayName, loader, true);
plugin.loadResources();
}
// Select tab
tab.select(newTabId);
});
resrcPg.append(okBtn);
// Add provision tab
tab.add('provisionTab', 'Provision', provPg, false);
// Add image tab
tab.add('imagesTab', 'Images', '', false);
// Add resource tab
tab.add('resourceTab', 'Resources', resrcPg, false);
// Load tabs onselect
$('#provisionPageTabs').bind('tabsselect', function(event, ui){
// Load image page
if (!$('#imagesTab').children().length && ui.index == 1) {
$('#imagesTab').append($('<center></center>').append(createLoader('')));
loadImagesPage();
}
});
// Open the quick provision tab
if (window.location.search) {
tab.add('quickProvisionTab', 'Quick Provision', '', true);
tab.select('quickProvisionTab');
var provForm = $('<div class="form"></div>');
$('#quickProvisionTab').append(provForm);
appendProvisionSection('quick', provForm);
}
/**
* Global variables
*/
var provisionTabs; // Provision tabs
/**
* Set the provision tab
*
* @param obj Tab object
*/
function setProvisionTab(obj) {
provisionTabs = obj;
}
/**
* Get the provision tab
*
* @param Nothing
* @return Tab object
*/
function getProvisionTab() {
return provisionTabs;
}
/**
* Load provision page
*/
function loadProvisionPage() {
// If the page is loaded
if ($('#content').children().length) {
// Do not load again
return;
}
// Get OS image names
if (!$.cookie('xcat_imagenames')){
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'tabdump',
tgt : '',
args : 'osimage',
msg : ''
},
success : function(data) {
data = decodeRsp(data);
setOSImageCookies(data);
}
});
}
// Get groups
if (!$.cookie('xcat_groups')){
$.ajax( {
url : 'lib/cmd.php',
dataType : 'json',
data : {
cmd : 'extnoderange',
tgt : '/.*',
args : 'subgroups',
msg : ''
},
success : function(data) {
data = decodeRsp(data);
setGroupsCookies(data);
}
});
}
// 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 = $('<div class="form"></div>');
provPg.append(infoBar);
// Create provision tab
var tab = new Tab('provisionPageTabs');
setProvisionTab(tab);
tab.init();
$('#content').append(tab.object());
// Create radio buttons for platforms
var hwList = $('<ol>Platforms available:</ol>');
var esx = $('<li><input type="radio" name="hw" value="esx" disabled/>ESX</li>');
var kvm = $('<li><input type="radio" name="hw" value="kvm" disabled/>KVM</li>');
var zvm = $('<li><input type="radio" name="hw" value="zvm" checked/>z\/VM</li>');
var ipmi = $('<li><input type="radio" name="hw" value="ipmi" disabled/>iDataPlex</li>');
var blade = $('<li><input type="radio" name="hw" value="blade" disabled/>BladeCenter</li>');
var hmc = $('<li><input type="radio" name="hw" value="hmc" disabled/>System p</li>');
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;
}
// Create an instance of the plugin
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;
}
// Select tab
tab.add(newTabId, title, '', true);
tab.select(newTabId);
plugin.loadProvisionPage(newTabId);
});
provPg.append(okBtn);
// Create resources tab
var resrcPg = $('<div class="form"></div>');
// Create info bar
var resrcInfoBar = createInfoBar('Select a platform to view its current resources.');
resrcPg.append(resrcInfoBar);
// Create radio buttons for platforms
var rsrcHwList = $('<ol>Platforms available:</ol>');
esx = $('<li><input type="radio" name="rsrcHw" value="esx" disabled/>ESX</li>');
kvm = $('<li><input type="radio" name="rsrcHw" value="kvm" disabled/>KVM</li>');
zvm = $('<li><input type="radio" name="rsrcHw" value="zvm" checked/>z\/VM</li>');
ipmi = $('<li><input type="radio" name="rsrcHw" value="ipmi" disabled/>iDataPlex</li>');
blade = $('<li><input type="radio" name="rsrcHw" value="blade" disabled/>BladeCenter</li>');
hmc = $('<li><input type="radio" name="rsrcHw" value="hmc" disabled/>System p</li>');
rsrcHwList.append(esx);
rsrcHwList.append(kvm);
rsrcHwList.append(zvm);
rsrcHwList.append(blade);
rsrcHwList.append(ipmi);
rsrcHwList.append(hmc);
resrcPg.append(rsrcHwList);
var okBtn = createButton('Ok');
okBtn.bind('click', function(event) {
// Get hardware that was selected
var hw = $(this).parent().find('input[name="rsrcHw"]:checked').val();
// Generate new tab ID
var newTabId = hw + 'ResourceTab';
if (!$('#' + newTabId).length) {
// Create loader
var loader = $('<center></center>').append(createLoader(hw + 'ResourceLoader'));
// Create an instance of the plugin
var plugin = null;
var displayName = "";
switch (hw) {
case "kvm":
plugin = new kvmPlugin();
displayName = "KVM";
break;
case "esx":
plugin = new esxPlugin();
displayName = "ESX";
break;
case "blade":
plugin = new bladePlugin();
displayName = "BladeCenter";
break;
case "hmc":
plugin = new hmcPlugin();
displayName = "System p";
break;
case "ipmi":
plugin = new ipmiPlugin();
displayName = "iDataPlex";
break;
case "zvm":
plugin = new zvmPlugin();
displayName = "z\/VM";
break;
}
// Add resource tab and load resources
tab.add(newTabId, displayName, loader, true);
plugin.loadResources();
}
// Select tab
tab.select(newTabId);
});
resrcPg.append(okBtn);
// Add provision tab
tab.add('provisionTab', 'Provision', provPg, false);
// Add image tab
tab.add('imagesTab', 'Images', '', false);
// Add resource tab
tab.add('resourceTab', 'Resources', resrcPg, false);
// Load tabs onselect
$('#provisionPageTabs').bind('tabsselect', function(event, ui){
// Load image page
if (!$('#imagesTab').children().length && ui.index == 1) {
$('#imagesTab').append($('<center></center>').append(createLoader('')));
loadImagesPage();
}
});
// Open the quick provision tab
if (window.location.search) {
tab.add('quickProvisionTab', 'Quick Provision', '', true);
tab.select('quickProvisionTab');
var provForm = $('<div class="form"></div>');
$('#quickProvisionTab').append(provForm);
appendProvisionSection('quick', provForm);
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,225 +1,241 @@
<?php
/* Required libraries */
$TOPDIR = '..';
require_once "$TOPDIR/lib/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.
*
* @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"];
// If no $tgt is given, set $tgt to NULL
if (!$tgt) {
$tgt = NULL;
}
// If no $msg is given, set $msg to NULL
if (!$msg) {
$msg = NULL;
}
// If no $args are given, set $args_array to NULL
// Separators used are: || or ;
$args_array = array();
if ($args) {
// If $args contains multiple arguments, split it into an array
if (strpos($args, "||")) {
// Split the arguments into an array
$args_array = array();
$args_array = explode("||", $args);
} else if (strpos($args, ";")) {
// Split the arguments into an array
$args_array = array();
$args_array = explode(";", $args);
} else {
$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
$opts_array = array();
$opts_array = explode("|", $opts);
} if (strpos($opts, ";")) {
// Split the arguments into an array
$opts_array = array();
$opts_array = explode(";", $opts);
} else {
$opts_array = array($opts);
}
}
// Time needed to update /etc/hosts
if (strncasecmp($cmd, "makehosts", 9) == 0) {
sleep(5);
}
// Submit request and get response
$xml = docmd($cmd, $tgt, $args_array, $opts_array);
// If the output is flushed, do not return output in JSON
if (in_array("flush", $opts_array)) {
return;
}
$rsp = array();
// webrun pping and gangliastatus output needs special handling
if (strncasecmp($cmd, "webrun", 6) == 0 && (stristr($args, "pping") || stristr($args, "gangliastatus") || stristr($args, "chtab"))) {
$rsp = extractWebrun($xml);
}
// nodels output needs special handling
else if (strncasecmp($cmd, "nodels", 6) == 0) {
// Handle the output the same way as webrun
$rsp = extractNodels($xml);
}
// extnoderange output needs special handling
// This command gets the nodes and groups
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) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
}
// Reply in the form of JSON
$rtn = array("rsp" => $rsp, "msg" => $msg);
echo json_encode($rtn);
}
/**
* Extract the output for a webrun command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractWebrun($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data;
$status = str_replace(":|:", "\n", $status);
// Add to return array
$rsp[$i] = array("$name", "$status");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a nodels command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractNodels($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data->contents;
$status = str_replace(":|:", "\n", $status);
$description = $node->data->desc;
// Add to return array
$rsp[$i] = array("$name", "$status", "$description");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a extnoderange command
*
* @param $xml The XML output from docmd()
* @return The nodes and groups
*/
function extractExtnoderange($xml) {
$rsp = array();
// Extract data returned
foreach ($xml->xcatresponse->intersectinggroups as $group) {
array_push($rsp, "$group");
}
return $rsp;
}
<?php
/* Required libraries */
$TOPDIR = '..';
require_once "$TOPDIR/lib/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.
*
* @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"];
// If no $tgt is given, set $tgt to NULL
if (!$tgt) {
$tgt = NULL;
}
// If no $msg is given, set $msg to NULL
if (!$msg) {
$msg = NULL;
}
// If no $args are given, set $args_array to NULL
// Separators used are: || or ;
$args_array = array();
if ($args) {
// If $args contains multiple arguments, split it into an array
if (strpos($args, "||")) {
// Split the arguments into an array
$args_array = array();
$args_array = explode("||", $args);
} else if (strpos($args, ";")) {
// Split the arguments into an array
$args_array = array();
$args_array = explode(";", $args);
} else {
$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
$opts_array = array();
$opts_array = explode("|", $opts);
} if (strpos($opts, ";")) {
// Split the arguments into an array
$opts_array = array();
$opts_array = explode(";", $opts);
} else {
$opts_array = array($opts);
}
}
// Time needed to update /etc/hosts
if (strncasecmp($cmd, "makehosts", 9) == 0) {
sleep(5);
}
// Submit request and get response
$xml = docmd($cmd, $tgt, $args_array, $opts_array);
// If the output is flushed, do not return output in JSON
if (in_array("flush", $opts_array)) {
return;
}
$rsp = array();
// webrun pping and gangliastatus output needs special handling
if (strncasecmp($cmd, "webrun", 6) == 0 && (stristr($args, "pping") || stristr($args, "gangliastatus") || stristr($args, "chtab"))) {
$rsp = extractWebrun($xml);
}
// nodels output needs special handling
else if (strncasecmp($cmd, "nodels", 6) == 0) {
// Handle the output the same way as webrun
$rsp = extractNodels($xml);
}
// extnoderange output needs special handling
// This command gets the nodes and groups
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) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
}
// Remove any HTML that could be used for XSS attacks
foreach ($rsp as $key => &$value) {
$whatami = gettype($value);
if ("string" != $whatami) {
//echo "found a non string in rsp array \n";
foreach ($value as $key2 => $value2){
//echo "Key2:$key2 Value2 type:",gettype($value2)," value2 data: $value2 \n";
$value[$key2] = htmlentities($value2, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
} else {
//echo "Key:$key Value type:",gettype($value)," value data: $value \n";
$rsp[$key] = htmlentities($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
//echo "New value: $rsp[$key] \n";
}
}
$msg = htmlentities($msg, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Reply in the form of JSON
$rtn = array("rsp" => $rsp, "msg" => $msg);
echo json_encode($rtn);
}
/**
* Extract the output for a webrun command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractWebrun($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data;
$status = str_replace(":|:", "\n", $status);
// Add to return array
$rsp[$i] = array("$name", "$status");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a nodels command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractNodels($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data->contents;
$status = str_replace(":|:", "\n", $status);
$description = $node->data->desc;
// Add to return array
$rsp[$i] = array("$name", "$status", "$description");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a extnoderange command
*
* @param $xml The XML output from docmd()
* @return The nodes and groups
*/
function extractExtnoderange($xml) {
$rsp = array();
// Extract data returned
foreach ($xml->xcatresponse->intersectinggroups as $group) {
array_push($rsp, "$group");
}
return $rsp;
}
?>

View File

@ -299,7 +299,7 @@ function isAuthenticated() {
*/
function isRootAcess() {
if (is_logged() && $_SESSION["xcatpassvalid"]) {
$testacc = docmd('tabdump', '', array('policy', '-w', "name==" . $_SESSION["username"]), array());
$testacc = docmd('tabdump', '', array('-w', "name==" . $_SESSION["username"],'policy' ), array());
if (isset($testacc->{'xcatresponse'}->{'data'}->{1})) {
$result = $testacc->{'xcatresponse'}->{'data'}->{1};
$result = str_replace('"', '', $result);

View File

@ -1,190 +1,206 @@
<?php
/* Required libraries */
$TOPDIR = '..';
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.
*
* @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"];
// If no $tgt is given, set $tgt to NULL
if (!$tgt) {
$tgt = NULL;
}
// If no $msg is given, set $msg to NULL
if (!$msg) {
$msg = NULL;
}
// If no $args are given, set $args_array to NULL
$args_array = array();
if ($args) {
// If $args contains multiple arguments, split it into an array
if (strpos($args,";")) {
// Split the arguments into an array
$args_array = array();
$args_array = explode(";", $args);
} else {
$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
$opts_array = array();
$opts_array = explode(";", $opts);
} else {
$opts_array = array($opts);
}
}
// Submit request and get response
$xml = docmd($cmd, $tgt, $args_array, $opts_array);
// If the output is flushed, do not return output in JSON
if (in_array("flush", $opts_array)) {
return;
}
$rsp = array();
// webrun pping and gangliastatus output needs special handling
if(strncasecmp($cmd, "webrun", 6) == 0 && (stristr($args, "pping") || stristr($args, "gangliastatus") || stristr($args, "chtab"))) {
$rsp = extractWebrun($xml);
}
// nodels output needs special handling
else if(strncasecmp($cmd, "nodels", 6) == 0) {
// Handle the output the same way as webrun
$rsp = extractNodels($xml);
}
// extnoderange output needs special handling
// This command gets the nodes and groups
else if(strncasecmp($cmd, "extnoderange", 12) == 0) {
$rsp = extractExtnoderange($xml);
}
// 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;
}
$cont = str_replace(":|:", "\n", $cont);
array_push($rsp, "$node: $cont");
} else if (strlen("$data") > 2) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
}
// Reply in the form of JSON
$rtn = array("rsp" => $rsp, "msg" => $msg);
echo json_encode($rtn);
}
/**
* Extract the output for a webrun command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractWebrun($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data;
$status = str_replace(":|:", "\n", $status);
// Add to return array
$rsp[$i] = array("$name", "$status");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a nodels command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractNodels($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data->contents;
$status = str_replace(":|:", "\n", $status);
$description = $node->data->desc;
// Add to return array
$rsp[$i] = array("$name", "$status", "$description");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a extnoderange command
*
* @param $xml The XML output from docmd()
* @return The nodes and groups
*/
function extractExtnoderange($xml) {
$rsp = array();
// Extract data returned
foreach ($xml->xcatresponse->intersectinggroups as $group) {
array_push($rsp, "$group");
}
return $rsp;
}
<?php
/* Required libraries */
$TOPDIR = '..';
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.
*
* @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"];
// If no $tgt is given, set $tgt to NULL
if (!$tgt) {
$tgt = NULL;
}
// If no $msg is given, set $msg to NULL
if (!$msg) {
$msg = NULL;
}
// If no $args are given, set $args_array to NULL
$args_array = array();
if ($args) {
// If $args contains multiple arguments, split it into an array
if (strpos($args,";")) {
// Split the arguments into an array
$args_array = array();
$args_array = explode(";", $args);
} else {
$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
$opts_array = array();
$opts_array = explode(";", $opts);
} else {
$opts_array = array($opts);
}
}
// Submit request and get response
$xml = docmd($cmd, $tgt, $args_array, $opts_array);
// If the output is flushed, do not return output in JSON
if (in_array("flush", $opts_array)) {
return;
}
$rsp = array();
// webrun pping and gangliastatus output needs special handling
if(strncasecmp($cmd, "webrun", 6) == 0 && (stristr($args, "pping") || stristr($args, "gangliastatus") || stristr($args, "chtab"))) {
$rsp = extractWebrun($xml);
}
// nodels output needs special handling
else if(strncasecmp($cmd, "nodels", 6) == 0) {
// Handle the output the same way as webrun
$rsp = extractNodels($xml);
}
// extnoderange output needs special handling
// This command gets the nodes and groups
else if(strncasecmp($cmd, "extnoderange", 12) == 0) {
$rsp = extractExtnoderange($xml);
}
// 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;
}
$cont = str_replace(":|:", "\n", $cont);
array_push($rsp, "$node: $cont");
} else if (strlen("$data") > 2) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
}
// Remove any HTML that could be used for XSS attacks
foreach ($rsp as $key => &$value) {
$whatami = gettype($value);
if ("string" != $whatami) {
//echo "found a non string in rsp array \n";
foreach ($value as $key2 => $value2){
//echo "Key2:$key2 Value2 type:",gettype($value2)," value2 data: $value2 \n";
$value[$key2] = htmlentities($value2, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
} else {
//echo "Key:$key Value type:",gettype($value)," value data: $value \n";
$rsp[$key] = htmlentities($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
//echo "New value: $rsp[$key] \n";
}
}
$msg = htmlentities($msg, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Reply in the form of JSON
$rtn = array("rsp" => $rsp, "msg" => $msg);
echo json_encode($rtn);
}
/**
* Extract the output for a webrun command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractWebrun($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data;
$status = str_replace(":|:", "\n", $status);
// Add to return array
$rsp[$i] = array("$name", "$status");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a nodels command
*
* @param $xml The XML output from docmd()
* @return An array containing the output
*/
function extractNodels($xml) {
$rsp = array();
$i = 0;
// Extract data returned
foreach($xml->children() as $nodes){
foreach($nodes->children() as $node){
// Get the node name
$name = $node->name;
// Get the content
$status = $node->data->contents;
$status = str_replace(":|:", "\n", $status);
$description = $node->data->desc;
// Add to return array
$rsp[$i] = array("$name", "$status", "$description");
$i++;
}
}
return $rsp;
}
/**
* Extract the output for a extnoderange command
*
* @param $xml The XML output from docmd()
* @return The nodes and groups
*/
function extractExtnoderange($xml) {
$rsp = array();
// Extract data returned
foreach ($xml->xcatresponse->intersectinggroups as $group) {
array_push($rsp, "$group");
}
return $rsp;
}
?>

View File

@ -1,36 +1,39 @@
<?php
/* Required libraries */
$TOPDIR = '..';
require_once "$TOPDIR/lib/functions.php";
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
*/
if (!isAuthenticated()) {
echo ("<b>Please login before continuing!</b>");
exit;
}
if (isset($_GET["cmd"])) {
// 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);
}
echo json_encode(array("rsp"=>$ret, "msg" => $msg));
}
<?php
/* Required libraries */
$TOPDIR = '..';
require_once "$TOPDIR/lib/functions.php";
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
*/
if (!isAuthenticated()) {
echo ("<b>Please login before continuing!</b>");
exit;
}
if (isset($_GET["cmd"])) {
// 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);
}
// Remove any HTML that could be used for XSS attacks
$ret = htmlentities($ret, ENT_QUOTES | ENT_HTML5, 'UTF-8');
$msg = htmlentities($msg, ENT_QUOTES | ENT_HTML5, 'UTF-8');
echo json_encode(array("rsp"=>$ret, "msg" => $msg));
}
?>

View File

@ -0,0 +1,63 @@
<?php
/**
* Upload a given file into /var/tmp
*/
$TOPDIR = '..';
require_once "$TOPDIR/lib/functions.php";
require_once "$TOPDIR/lib/jsonwrapper.php";
session_start();
if (!is_logged()) {
echo "You are not logged in!";
return;
}
// Set the file upload size limit (not sure if this actually works)
ini_set('upload_max_filesize', '4096M');
ini_set('post_max_size', '4096M');
ini_set('max_input_time', -1);
// Set time limit on how long this can run
set_time_limit(1200);
// Grab the target destination and file type
$dest = $_GET["destination"];
// Only allow uploads onto /install
if (strcmp(substr($dest, 0, 9), "/install/") != 0) {
echo "You are only authorized to upload onto /install subdirectories";
return;
}
$file = $_FILES["file"]["name"];
$path = $dest . "/" . $file;
if (move_uploaded_file($_FILES["file"]["tmp_name"], $path)) {
echo "File successfully uploaded";
chmod($path, 0755); // Change file to be executable
} else {
echo "Failed to upload file to $path. ";
// Obtain the reason for failure
$reason = "";
switch ($_FILES["file"]["error"]) {
case 1:
$reason = "The file is bigger than the PHP installation allows.";
break;
case 2:
$reason = "The file is bigger than this form allows.";
break;
case 3:
$reason = "Only part of the file was uploaded.";
break;
case 4:
$reason = "No file was uploaded.";
break;
default:
$reason = "Unknown error.";
}
echo $reason;
}
?>

View File

@ -1,142 +1,159 @@
<?php
/* Required libraries */
$TOPDIR = '..';
require_once "$TOPDIR/lib/functions.php";
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
* @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"];
// Attachments are put here
$att = $_GET["att"];
// Special messages put here
$msg = $_GET["msg"];
// If no $tgt is given, set $tgt to NULL
if (!$tgt) {
$tgt = NULL;
}
// If no $args is given, set $args to NULL
if (!$args) {
$args = NULL;
}
// If no $msg is given, set $msg to NULL
if (!$msg) {
$msg = NULL;
}
// If no $att is given, set $att to NULL
if (!$att) {
$att = NULL;
}
// If $args contains multiple arguments, split it into an array
// Separators used are: || or ;
if (strpos($args, "||")) {
// Split the arguments into an array
$arr = array();
$arr = explode("||", $args);
} else if (strpos($args, ";")) {
// Split the arguments into an array
$arr = array();
$arr = explode(";", $args);
} else {
$arr = array($args);
}
$rsp = array();
// Replace user entry
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";
$handle = fopen($userEntry, 'w') or die("Cannot open $userEntry");
fwrite($handle, $att);
fclose($handle);
// CLI command: chvm gpok249 --replacevs /tmp/dirEntry.txt
// Replace user entry
array_push($arr, $userEntry);
$xml = docmd($cmd, $tgt, $arr, NULL);
foreach ($xml->children() as $child) {
foreach ($child->children() as $data) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
// Create virtual server
else if (strncasecmp($cmd, "mkvm", 4) == 0) {
// Directory /var/tmp permissions = 777
// You can write anything to that directory
$userEntry = "/var/tmp/$tgt.txt";
$handle = fopen($userEntry, 'w') or die("Cannot open $userEntry");
fwrite($handle, $att);
fclose($handle);
// CLI command: mkvm gpok3 /tmp/gpok3.txt
// Create user entry
array_unshift($arr, $userEntry);
$xml = docmd($cmd, $tgt, $arr, NULL);
foreach ($xml->children() as $child) {
foreach ($child->children() as $data) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
// Run shell script
// This is a typical command used by all platforms. It is put here because
// most of the code needed are already here
else if (strncasecmp($cmd, "xdsh", 4) == 0) {
// Directory /var/tmp permissions = 777
// You can write anything to that directory
$msgArgs = explode(";", $msg);
$inst = str_replace("out=scriptStatusBar", "", $msgArgs[0]);
$script = "/var/tmp/script$inst.sh";
// Write to file
$handle = fopen($script, 'w') or die("Cannot open $script");
fwrite($handle, $att);
fclose($handle);
// Change it to executable
chmod($script, 0777);
// CLI command: xdsh gpok3 -e /var/tmp/gpok3.sh
// Create user entry
array_push($arr, $script);
$xml = docmd($cmd, $tgt, $arr, NULL);
foreach ($xml->children() as $child) {
foreach ($child->children() as $data) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
// Remove this file
unlink($script);
}
// Reply in the form of JSON
$rtn = array("rsp" => $rsp, "msg" => $msg);
echo json_encode($rtn);
}
<?php
/* Required libraries */
$TOPDIR = '..';
require_once "$TOPDIR/lib/functions.php";
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
* @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"];
// Attachments are put here
$att = $_GET["att"];
// Special messages put here
$msg = $_GET["msg"];
// If no $tgt is given, set $tgt to NULL
if (!$tgt) {
$tgt = NULL;
}
// If no $args is given, set $args to NULL
if (!$args) {
$args = NULL;
}
// If no $msg is given, set $msg to NULL
if (!$msg) {
$msg = NULL;
}
// If no $att is given, set $att to NULL
if (!$att) {
$att = NULL;
}
// If $args contains multiple arguments, split it into an array
// Separators used are: || or ;
if (strpos($args, "||")) {
// Split the arguments into an array
$arr = array();
$arr = explode("||", $args);
} else if (strpos($args, ";")) {
// Split the arguments into an array
$arr = array();
$arr = explode(";", $args);
} else {
$arr = array($args);
}
$rsp = array();
// Replace user entry
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";
$handle = fopen($userEntry, 'w') or die("Cannot open $userEntry");
fwrite($handle, $att);
fclose($handle);
// CLI command: chvm gpok249 --replacevs /tmp/dirEntry.txt
// Replace user entry
array_push($arr, $userEntry);
$xml = docmd($cmd, $tgt, $arr, NULL);
foreach ($xml->children() as $child) {
foreach ($child->children() as $data) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
// Create virtual server
else if (strncasecmp($cmd, "mkvm", 4) == 0) {
// Directory /var/tmp permissions = 777
// You can write anything to that directory
$userEntry = "/var/tmp/$tgt.txt";
$handle = fopen($userEntry, 'w') or die("Cannot open $userEntry");
fwrite($handle, $att);
fclose($handle);
// CLI command: mkvm gpok3 /tmp/gpok3.txt
// Create user entry
array_unshift($arr, $userEntry);
$xml = docmd($cmd, $tgt, $arr, NULL);
foreach ($xml->children() as $child) {
foreach ($child->children() as $data) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
}
// Run shell script
// This is a typical command used by all platforms. It is put here because
// most of the code needed are already here
else if (strncasecmp($cmd, "xdsh", 4) == 0) {
// Directory /var/tmp permissions = 777
// You can write anything to that directory
$msgArgs = explode(";", $msg);
$inst = str_replace("out=scriptStatusBar", "", $msgArgs[0]);
$script = "/var/tmp/script$inst.sh";
// Write to file
$handle = fopen($script, 'w') or die("Cannot open $script");
fwrite($handle, $att);
fclose($handle);
// Change it to executable
chmod($script, 0777);
// CLI command: xdsh gpok3 -e /var/tmp/gpok3.sh
// Create user entry
array_push($arr, $script);
$xml = docmd($cmd, $tgt, $arr, NULL);
foreach ($xml->children() as $child) {
foreach ($child->children() as $data) {
$data = str_replace(":|:", "\n", $data);
array_push($rsp, "$data");
}
}
// Remove this file
unlink($script);
}
// Remove any HTML that could be used for XSS attacks
foreach ($rsp as $key => &$value) {
$whatami = gettype($value);
if ("string" != $whatami) {
//echo "found a non string in rsp array \n";
foreach ($value as $key2 => $value2){
//echo "Key2:$key2 Value2 type:",gettype($value2)," value2 data: $value2 \n";
$value[$key2] = htmlentities($value2, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
} else {
//echo "Key:$key Value type:",gettype($value)," value data: $value \n";
$rsp[$key] = htmlentities($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
//echo "New value: $rsp[$key] \n";
}
}
$msg = htmlentities($msg, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// Reply in the form of JSON
$rtn = array("rsp" => $rsp, "msg" => $msg);
echo json_encode($rtn);
}
?>

View File

@ -83,7 +83,8 @@ sub process_request {
'cecsetup' => \&web_cecsetup,
'deletefile' => \&web_deletefile,
'createfolder' => \&web_createfolder,
'getrepospace' => \&web_getrepospace
'getrepospace' => \&web_getrepospace,
'verifynode' => \&web_verifynode,
);
# Check whether the request is authorized or not
@ -1982,8 +1983,8 @@ sub web_summary {
while (my ($key, $value) = each(%{$attrs})) {
web_attrcount($value->[0]->{'os'}, \%oshash);
web_attrcount($value->[0]->{'arch'}, \%archhash);
web_attrcount($value->[0]->{'provmethod'}, \%provhash);
web_attrcount($value->[0]->{'nodetype'}, \%typehash);
web_attrcount($value->[0]->{'provmethod'},, \%provhash);
web_attrcount($value->[0]->{'nodetype'},, \%typehash);
}
$attrs = $nodelistTab->getNodesAttribs(\@nodes, ['status']);
@ -2716,4 +2717,27 @@ sub web_getrepospace() {
$callback->({ info => $space });
}
sub web_verifynode() {
my ( $request, $callback, $sub_req ) = @_;
my $cmdOpts = '';
my $out;
# Loop to handle all options passed. We don't know how many they will pass
# so we look for 'end' to signify the end. We set a loop variable to 500 which
# we know is much larger than the expected number of arguments. This prevents
# the loop from going on forever should there be an error on the javascript side
# an the 'end' was not passed.
for ( my $i = 0 ; $i < 500 ; $i++ ) {
if ( $request->{arg}->[$i] ne 'end' ) {
$cmdOpts = "$cmdOpts $request->{arg}->[$i]";
} else {
last;
}
}
$out = `/opt/xcat/bin/verifynode $cmdOpts`;
$callback->( { info => $out });
}
1;

View File

@ -0,0 +1,286 @@
#!/usr/bin/perl
###############################################################################
# IBM(c) 2015 EPL license http://www.eclipse.org/legal/epl-v10.html
###############################################################################
# COMPONENT: mkdummyimage
#
# This script creates a dummy image.
###############################################################################
use strict;
use warnings;
use File::Basename;
use File::Path;
use File::Spec;
use File::Temp;
use Getopt::Long;
use MIME::Base64;
use Sys::Hostname;
use Socket;
my $version = "1.0";
my $defaultName = 'dummy.img'; # Default image file name
my $dest = ''; # Target destination (filespec)
my $displayHelp = 0; # Display help information
my $eckdImage = 0; # ECKD image is wanted
my $fbaImage = 0; # FBA image is wanted
my $remoteHost = ''; # Remote host transfer information
my $remoteUser = ''; # Remote user transfer information
my $verbose = 0; # Verbose flag - 0: quiet, 1: verbose
my $versionOpt = 0; # Show version information flag
# set the usage message
my $usage_string = "Usage:\n
$0 [ --eckd | --fba ] [ -V | --verbose ]
[ -d | --destination <dest> ] [-R | --remotehost <host> ]\n
or\n
$0 -v | --version\n
or\n
$0 -h | --help\n
The following options are supported:\n
-d | --destination <dest>
File specification of the image file to be created.
Either the filename only or a fully qualified name.
If the destination is within the xCAT MN then
it must be within the directory specified by
the installdir property in the xCAT site table.
The default file name is $defaultName.\n
--eckd Create an empty ECKD disk image. This is the
default image type if neither --eckd or --fba
is specifed.\n
--fba Create an empty FBA disk image\n
-h | --help Display help information\n
-R | --remotehost <host>
Indicates that the destination specified on the
command invocation is the file specification on a
host other than the management node.
The 'host' operand is the IP address or DNS host
name of the target server. A user may be specified
in a similar way as it is specified with the SCP
command using the format 'user\@host' where 'user'
is the name of the user on the remote system and
'host' operand is as previously stated. The image
is created in the directory specified by the
tmpdir property in the site table and then moved
to the remote host using SCP. After moving the
image off the xCAT MN, the image is removed
from the xCAT MN. Prior to specifying the command,
the keystore on the remote host must be set up with
the public key of the xCAT MN.\n
-v | --version Display the version of this script.\n
-V | --verbose Display verbose processing messages.\n";
#-------------------------------------------------------
=head3 createImage
Description : Create the dummy image file.
Arguments : None
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = createImage();
=cut
#-------------------------------------------------------
sub createImage{
my $rc = 0;
my $buildDir = '';
my $header;
# Create a temporary directory in which to create the image.
my $tmpDir = `/opt/xcat/sbin/tabdump site| grep '^"tmpdir",' | sed s/'^"tmpdir","'//g| sed s/'".*'//g`;
chomp $tmpDir;
if ( $tmpDir eq '' ) {
print "Error: The 'tmpdir' value is missing from the site table.\n";
$rc = 11;
goto FINISH_createImage;
}
$buildDir = mkdtemp( "$tmpDir/image.$$.XXXXXX" );
# Create the image
my $imageFile = $defaultName;
open( my $fh, '>', "$buildDir/$imageFile" ) or die "Could not open file '$buildDir/$imageFile'";
if ( $verbose ) {
print "Creating the image in $buildDir as $imageFile.\n";
}
if ( $eckdImage ) {
$header = "xCAT CKD Disk Image:";
$header = "$header 0 CYL";
}
elsif ( $fbaImage ) {
$header = "xCAT FBA Disk Image:";
$header = "$header 0 BLK";
}
$header = "$header HLen: 0055"; # Header size increased by x from 0055
$header = "$header GZIP: 0";
printf $fh "%-512s", "$header";
close( $fh );
# Move the image to the target location.
if ( $remoteHost ne '' ) {
# Do a remote transfer
my $remoteTarget = $remoteHost . ':' . $dest;
if ( $remoteUser ne '' ) {
$remoteTarget = "$remoteUser\@$remoteTarget";
}
my $scpVerbose = '';
if ( $verbose ) {
print "Moving the image $imageFile to the remote system $remoteHost as $dest.\n";
$scpVerbose = '-v'
}
$rc = system( "/usr/bin/scp $scpVerbose -B $buildDir/$imageFile $remoteTarget" );
if ( $rc ) {
$rc = $rc >> 8;
print "Error: Unable to copy the image $buildDir/$imageFile to the remote host: $remoteHost, rc: $rc\n";
$rc = 30;
goto FINISH_createImage;
}
} else {
# Move the file to a local directory
$rc = system( "cp $buildDir/$imageFile $dest" );
if ( $rc ) {
$rc = $rc >> 8;
print "Error: Unable to copy the image $buildDir/$imageFile to the destination: $dest, rc: $rc\n";
$rc = 40;
goto FINISH_createImage;
}
}
if ( $remoteHost ne '' ) {
print "Image created on $remoteHost: $dest\n";
} else {
print "Image created: $dest\n";
}
FINISH_createImage:
if ( -d $buildDir ) {
rmtree $buildDir;
}
return $rc;
}
#-------------------------------------------------------
=head3 showHelp
Description : Show the help inforamtion.
Arguments : None.
Returns : None.
Example : showHelp();
=cut
#-------------------------------------------------------
sub showHelp{
print "$0 prepares a special image file that contains no disk\ncontents.\n\n";
print $usage_string;
return;
}
#*****************************************************************************
# Main routine
#*****************************************************************************
my $rc = 0;
my $out;
# Parse the arguments
$Getopt::Long::ignorecase = 0;
Getopt::Long::Configure( "bundling" );
if (!GetOptions(
'eckd' => \$eckdImage,
'd|destination=s' => \$dest,
'fba' => \$fbaImage,
'h|help' => \$displayHelp,
'R|remotehost=s' => \$remoteHost,
'v|version' => \$versionOpt,
'V|verbose' => \$verbose )) {
print $usage_string;
goto FINISH_main;
}
if ( $versionOpt ) {
print "Version: $version\n";
}
if ( $displayHelp ) {
showHelp();
}
if ( $displayHelp or $versionOpt ) {
goto FINISH_main;
}
if ( !$eckdImage and !$fbaImage ) {
$eckdImage = 1;
}
if ( $remoteHost ne '' ) {
$remoteHost =~ s/^\s+|\s+$//g; # trim blanks from both ends of the value
my $spaceCnt = scalar( () = $remoteHost =~ /\s+/g );
if ( $spaceCnt != 0 ) {
print "Error: Remote host value is not a single word.\n";
$rc = 1;
goto FINISH_main;
}
if ( $remoteHost =~ /@/ ) {
my @parts = split( /@/, $remoteHost );
if ( substr( $remoteHost, -1) eq '@' or
@parts > 2 or
!defined $parts[0] or $parts[0] eq '' or
!defined $parts[1] or $parts[1] eq '' ) {
print "Error: Remote host value is not valid.\n" .
" It should be in the form of 'hostname' or 'user\@hostname'.\n";
$rc = 2;
goto FINISH_main;
}
$remoteUser = $parts[0];
$remoteHost = $parts[1];
} else {
$remoteUser = 'root';
}
}
# Determine the destination and make certain it is valid.
my $installDir = `/opt/xcat/sbin/tabdump site| grep '^"installdir",' | sed s/'^"installdir","'//g| sed s/'".*'//g`;
chomp $installDir;
if ( $installDir eq '' ) {
print "Error: The 'installDir' value is missing from the site table.\n";
$rc = 10;
goto FINISH_main;
}
if ( $dest eq '' ){
# Set default destination for either a local or remote location.
if ( $remoteHost eq '' ) {
$dest = "$installDir/$defaultName";
} else {
$dest = "$defaultName";
}
} else {
# Can only verify local destination here. SCP will verify the remote destination.
if ( $remoteHost eq '' ) {
if ( $dest !~ /\// ) {
$dest = "$installDir/$dest";
} else {
if ( $dest !~ /^$installDir/ ) {
print "Error: The destination is not within the install directory specified in the site table.\n";
$rc = 20;
goto FINISH_main;
}
}
}
}
# Create the image file.
createImage();
FINISH_main:
exit $rc;

3007
xCAT-client/bin/verifynode Normal file

File diff suppressed because it is too large Load Diff

113
xCAT-client/bin/zvmMsg Normal file
View File

@ -0,0 +1,113 @@
#!/usr/bin/perl
# IBM(c) 2016 EPL license http://www.eclipse.org/legal/epl-v10.html
#-------------------------------------------------------
=head1
Provides more information related to an xCAT message
for z/VM. These are messages which are similar to the
following:
Warning (ZXCATIVP:VN01) Network VSW3 was not found as a network.
These message were originally added for the z/VM IVP and
are in the form:
<message type> (group:msgId) <msgText>
The information provided consists of:
Explanation of the message,
System Action, and
User Action.
=cut
#-------------------------------------------------------
package xCAT::zvmMsgs;
BEGIN
{
$::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat';
}
$XML::Simple::PREFERRED_PARSER='XML::Parser';
use Getopt::Long;
use lib "$::XCATROOT/lib/perl";
use Text::Wrap;
use xCAT::zvmMsgs;
use strict;
use warnings;
1;
# set the usage message
my $usage_string = "Usage:\n
$0 -h
$0 --help
$0 --group <group id> --id <msg id>\n
Use this script to display extra information for messages related
to z/VM that have the format:
<msgType> (<group>:<msgId>) <msgText>
for example:
Warning (ZXCATIVP:VN01) Network VSW3 was not found.\n
The following options are supported:
--group <group id>
specified the identifier of the group to which the message belongs.
The group id is the first part of the identifer, e.g.
'Warning (ZXCATIVP:VDS01)' belongs to the 'ZXCATIVP' group.
The group id is case sensitive. This operand should be specified
along with the --id operand.
-h | --help
Displays usage information.
--id <msg id>
specifies the message identifier. The message id is the second part
of the identifier, e.g. 'Warning (ZXCATIVP:VDS01)' where 'VDS01'
is the message id. The message identifier is case sensitive. This
operand should be specified along with the --group operand to fully
identify the message.\n";
#*****************************************************************************
# Main routine
#*****************************************************************************
# Parse the arguments
my $displayHelp = 0;
my $group = '';
my $msgId = '';
$Getopt::Long::ignorecase = 0;
Getopt::Long::Configure( 'bundling' );
if ( !GetOptions(
'h|help' => \$displayHelp,
'group=s' => \$group,
'id=s' => \$msgId,
)) {
print $usage_string;
goto FINISH;
}
if ( $displayHelp ) {
print $usage_string;
goto FINISH;
}
if ( $group eq '' ) {
print "--group operand was not specified.\n";
print $usage_string;
} elsif ( $msgId eq '' ) {
print "--id operand was not specified.\n";
print $usage_string;
} else {
my $extraInfo;
my $msg;
my $recAction;
my $sev;
( $recAction, $sev, $msg, $extraInfo ) = xCAT::zvmMsgs->buildMsg( $group, $msgId );
if ( $msg =~ ': Message was not found!' ) {
# Oops, we could not find the message.
print "$msg\n";
} else {
if ( $extraInfo ne '' ) {
print "Additional information for message $msgId in group $group:\n";
print "$extraInfo\n";
}
}
}
FINISH:
exit;

View File

@ -0,0 +1,353 @@
#!/usr/bin/perl
###############################################################################
# IBM (C) Copyright 2015, 2016 Eclipse Public License
# http://www.eclipse.org/org/documents/epl-v10.html
###############################################################################
# COMPONENT: zxcatCopyCloneList.pl
#
# This is a program to copy the "DOCLONE COPY" file from the 193 disk to
# /opt/xcat/doclone.txt
###############################################################################
use strict;
#use warnings;
use Capture::Tiny ':all';
use Getopt::Long;
my $file_location = '/var/opt/xcat/';
my $source_file = 'DOCLONE.COPY';
my $file_name = 'doclone.txt';
my $tempPattern = 'doclone.XXXXXXXX';
my $source_vdev = '193';
my $version = "1.0";
my $out;
my $err;
my $returnvalue;
my $displayHelp = 0; # Display help information
my $versionOpt = 0; # Show version information flag
my $usage_string = "This script copies the DOCLONE COPY from the MAINT 193
to the $file_location$file_name\n\n
Usage:\n
$0 [ -v ]
$0 [ -h | --help ]\n
The following options are supported:\n
-h | --help Display help information\n
-v Display the version of this script.\n";
# Copied this routine from sspmodload.pl
# This will get the Linux address of the vdev
sub get_disk($)
{
my ($id_user) = @_;
my $id = hex $id_user;
my $hex_id = sprintf '%x', $id;
my $completed = 1;
my $dev_path = sprintf '/sys/bus/ccw/drivers/dasd-eckd/0.0.%04x', $id;
if (!-d $dev_path) {
$dev_path = sprintf '/sys/bus/ccw/drivers/dasd-fba/0.0.%04x', $id;
}
if (!-d $dev_path) {
print "(Error) Unable to find a path to the $source_vdev in /sys/bus/ccw/drivers/\n";
}
-d $dev_path or return undef;
#offline the disk so that a new online will pick up the current file
my @sleepTimes = ( 1, 2, 3, 5, 8, 15, 22, 34, 60);
system("echo 0 > $dev_path/online");
my $dev_block = "$dev_path/block";
#wait if the disk directory is still there
if (-d $dev_block) {
$completed = 0;
foreach (@sleepTimes) {
system("echo 0 > $dev_path/online");
sleep $_;
if (!-d $dev_block) {
$completed = 1;
last;
}
}
}
if (!$completed) {
print "(Error) The 193 disk failed to complete the offline!\n";
return undef;
}
system("echo 1 > $dev_path/online");
# Bring the device online if offline
if (!-d $dev_block) {
$completed = 0;
foreach (@sleepTimes) {
system("echo 1 > $dev_path/online");
sleep $_;
if (-d $dev_block) {
$completed = 1;
last;
}
}
if (!$completed) {
print "(Error) The 193 disk failed to come online!\n";
return undef;
}
}
if (opendir(my $dir, $dev_block)) {
my $dev;
while ($dev = readdir $dir) {
last if (!( $dev eq '.' || $dev eq '..' ) );
}
closedir $dir;
if (!defined $dev) {
print "(Error) undefined $dev\n";
}
defined $dev ? "/dev/$dev" : undef;
} else {
print "(Error) Unable to opendir $dev_block\n";
return undef;
}
}
# ***********************************************************
# Mainline. Parse any arguments, usually no arguments
$Getopt::Long::ignorecase = 0;
Getopt::Long::Configure( "bundling" );
GetOptions(
'h|help' => \$displayHelp,
'v' => \$versionOpt );
if ( $versionOpt ) {
print "Version: $version\n";
exit 0;
}
if ( $displayHelp ) {
print $usage_string;
exit 0;
}
my $tempFileName = '';
my $rc = 0;
my $oldFileExists = 0;
my $dev = get_disk($source_vdev);
if (defined($dev)) {
# make sure directory exists
if (!-d $file_location) {
$returnvalue = mkdir "$file_location", 0755;
if (!$returnvalue) {
print "(Error) mkdir $file_location failed with errno:$!";
$rc = 1;
goto MAIN_EXIT;
}
}
my $oldFiletime;
# Create a temp file name to use while validating
$tempFileName = `/bin/mktemp -p $file_location $tempPattern`;
chomp($tempFileName);
# if we are overwriting an existing file, save time stamp
if (-e "$file_location$file_name") {
# stat will return results in $returnvalue
( $out, $err, $returnvalue ) = eval { capture { `stat \'-c%y\' $file_location$file_name` } };
chomp($out);
chomp($err);
chomp($returnvalue);
if (length($err) > 0) {
print "(Error) Cannot stat the $file_location$file_name\n$err\n";
$rc = 1;
goto MAIN_EXIT;
}
$oldFileExists = 1;
$oldFiletime = $returnvalue;
}
( $out, $err, $returnvalue ) = eval { capture { `/sbin/cmsfscp -d $dev -a $source_file $tempFileName` } };
chomp($out);
chomp($err);
chomp($returnvalue);
if (length($err) > 0) {
# skip any blksize message for other blksize
if ($err =~ 'does not match device blksize') {
} else {
print "(Error) Cannot copy $source_file\n$err\n";
$rc = 1;
goto MAIN_EXIT;
}
}
if ($oldFileExists == 1) {
( $out, $err, $returnvalue ) = eval { capture { `stat \'-c%y\' $tempFileName` } };
chomp($out);
chomp($err);
chomp($returnvalue);
if (length($err) > 0) {
print "(Error) Cannot stat the $tempFileName\n$err\n";
$rc = 1;
goto MAIN_EXIT;
}
if ($oldFiletime eq $returnvalue) {
print "The $source_file copied to temporary file $tempFileName is the same time stamp as original.\n";
} else {
print "$source_file copied to temporary file $tempFileName successfully\n";
}
} else {
print "$source_file copied to temporary file $tempFileName successfully\n";
}
print "Validating $tempFileName contents for proper syntax...\n";
if (-f "$tempFileName") {
$out = `cat $tempFileName`;
} else {
print "(Error) Missing temporary file: $tempFileName\n";
$rc = 1;
goto MAIN_EXIT;
}
my @lines = split('\n',$out);
my %hash = ();
my %imagenames = ();
my $count = @lines;
if ($count < 1) {
print "(Error) $tempFileName does not have any data.\n";
( $out, $err, $returnvalue ) = eval { capture { `rm $tempFileName` } };
chomp($out);
chomp($err);
chomp($returnvalue);
if (length($err) > 0) {
print "(Error) Cannot erase temporary file $tempFileName $err\n";
}
$rc = 1;
goto MAIN_EXIT;
}
# loop for any lines found
for (my $i=0; $i < $count; $i++) {
# skip comment lines, * or /*
if ( $lines[$i] =~ '^\s*[\*]') {
next;
}
if ( $lines[$i] =~ '^\s*/[*]') {
next;
}
# is this a blank line? if so skip it
if ($lines[$i] =~/^\s*$/) {
next;
}
my $semicolons = $lines[$i] =~ tr/\;//;
if ($semicolons < 3) {
print "(Error) Semicolons need to end each key=value on line ".($i+1)."\n";
$rc = 1;
}
%hash = ('IMAGE_NAME' => 0,'CLONE_FROM' => 0,'ECKD_POOL' => 0, 'FBA_POOL' => 0 );
# IMAGE_NAME=imgBoth; CLONE_FROM=testFBA; ECKD_POOL=POOLECKD; FBA_POOL=POOLFBA
my @parms = split( ';', $lines[$i]);
my $parmcount = @parms;
# get the key and value for this item, store in hash
for (my $j=0; $j < $parmcount; $j++) {
# if this token is all blanks skip it. Could be reading blanks at the end of the line
if ($parms[$j] =~ /^\s*$/) {
next;
}
my $parmlength = length($parms[$j]);
my @keyvalue = split('=', $parms[$j]);
my $key = $keyvalue[0];
$key =~ s/^\s+|\s+$//g; # get rid of leading and trailing blanks
if ( length( $key ) == 0 ) {
print "(Error) Missing keyword on line ".($i+1)."\n";
$rc = 1;
next;
}
my $value = $keyvalue[1];
$value =~ s/^\s+|\s+$//g;
if ( length( $value ) == 0 ) {
print "(Error) Missing value for key $key on line ".($i+1)."\n";
$rc = 1;
next
}
#uppercase both key and value;
my $UCkey = uc $key;
my $UCvalue = uc $value;
$hash{$UCkey} = $hash{$UCkey} + 1;
if ($UCkey eq "IMAGE_NAME") {
if (exists $imagenames{$UCvalue}) {
print "(Error) Duplicate IMAGE_NAME found on line ".($i+1)." with value: $value\n";
$rc = 1;
} else {
$imagenames{$UCvalue} = 1;
}
}
if ($UCkey ne "IMAGE_NAME" && $UCkey ne "CLONE_FROM" && $UCkey ne "ECKD_POOL" && $UCkey ne "FBA_POOL") {
print "(Error) Unknown keyword $key found on line ".($i+1)."\n";
$rc = 1;
}
}
# Check to make sure they have at least an image name, from and one pool
if ($hash{IMAGE_NAME} == 1 && $hash{CLONE_FROM} == 1 && ($hash{ECKD_POOL} ==1 || $hash{FBA_POOL} ==1 )) {
next;
} else {
if ($hash{IMAGE_NAME} == 0) {
print "(Error) Missing IMAGE_NAME key=value on line ".($i+1)."\n";
$rc = 1;
}
if ($hash{IMAGE_NAME} > 1) {
print "(Error) Multiple IMAGE_NAME keys found on line ".($i+1)."\n";
$rc = 1;
}
if ($hash{CLONE_FROM} == 0) {
print "(Error) Missing CLONE_FROM key=value on line ".($i+1)."\n";
$rc = 1;
}
if ($hash{CLONE_FROM} > 1) {
print "(Error) Multiple CLONE_FROM keys found on line ".($i+1)."\n";
$rc = 1;
}
if ($hash{ECKD_POOL} == 0 && $hash{FBA_POOL} == 0) {
print "(Error) Missing ECKD_POOL or FBA_POOL on line ".($i+1)."\n";
$rc = 1;
}
if ($hash{ECKD_POOL} > 1) {
print "(Error) Multiple ECKD_POOL keys found on line ".($i+1)."\n";
$rc = 1;
}
if ($hash{FBA_POOL} > 1) {
print "(Error) Multiple FBA_POOL keys found on line ".($i+1)."\n";
$rc = 1;
}
}
}
} else {
print "(Error) Unable to access the $source_vdev disk.\n";
$rc = 1;
}
# Main exit for this routine. Handles any necessary clean up.
MAIN_EXIT:
if (length($tempFileName) > 0 ) {
# If a good rc, Copy the temp file to the correct file
if ($rc == 0) {
( $out, $err, $returnvalue ) = eval { capture { `/bin/cp -f $tempFileName $file_location$file_name` } };
print $out;
print $err;
print $returnvalue;
chomp($out);
chomp($err);
chomp($returnvalue);
if (length($err) > 0) {
print "(Error) Cannot copy the temporary file $tempFileName to $file_location$file_name \n $err\n";
$rc = 1;
} else {
print "Validation completed. Temporary file copied to $file_location$file_name.\nIt is ready to use\n";
}
}
( $out, $err, $returnvalue ) = eval { capture { `rm $tempFileName` } };
chomp($out);
chomp($err);
chomp($returnvalue);
if (length($err) > 0) {
print "(Error) Cannot erase temporary file $tempFileName\n$err\n";
$rc = 1;
}
}
exit $rc;

2607
xCAT-client/bin/zxcatIVP.pl Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,333 @@
#!/usr/bin/perl
###############################################################################
# IBM (C) Copyright 2015, 2016 Eclipse Public License
# http://www.eclipse.org/org/documents/epl-v10.html
###############################################################################
# COMPONENT: zxcatExport
#
# This is a program to save the xCAT tables to the /install/xcatmigrate directory;
# then close and export the /install LVM
#
# The reverse process on the other system can be done if the LVM disks are
# writeable and online. The zxcatmigrate script can be used for that.
# It will issue pvscan, vgimport, vgchange -ay, mkdir, then mount commands.
#
###############################################################################
use strict;
use warnings;
use Capture::Tiny ':all';
use Getopt::Long;
use lib '/opt/xcat/lib/perl/';
use xCAT::TableUtils;
use xCAT::zvmUtils;
$| = 1; # turn off STDOUT buffering
my $lvmPath = "/dev/xcat/repo";
my $mountPoint = "/install";
my $exportDir = "/install/xcatmigrate";
my $exportTablesDir = "/install/xcatmigrate/xcattables";
my $exportFcpConfigsDir = "/install/xcatmigrate/fcpconfigs";
my $exportFcpOtherFilesDir = "/install/xcatmigrate/fcpotherfiles";
my $exportDocloneFilesDir = "/install/xcatmigrate/doclone";
my $lvmInfoFile = "lvminformation";
my $lsdasdInfoFile = "lsdasdinformation";
my $zvmVirtualDasdInfoFile = "zvmvirtualdasdinformation";
my $vgName = "xcat";
# xCAT table information to be filled in
my $masterIP;
my $xcatNode;
my $hcp;
my $zhcpNode;
my $version = "1.1";
my $targetIP = ""; # IP address to get data from
my $skipInstallFiles = 0; # Skip copying any install files
my $skipTables = 0; # Skip copying and installing xcat tables
my $displayHelp = 0; # Display help information
my $versionOpt = 0; # Show version information flag
my @entries;
my @propNames;
my $propVals;
my $usage_string = "This script saves the xcat tables in /install/xcatmigrate and\n
then exports the LVM mounted at /install. This should only be used to migrate\n
the /install LVM to a new userid.\n\n
Usage:\n
$0 [ -v ]\n
$0 [ -h | --help ]\n
The following options are supported:\n
-h | --help Display help information\n
-v Display the version of this script.\n";
#-------------------------------------------------------
=head3 chompall
Description : Issue chomp on all three input parms (pass by reference)
Arguments : arg1, arg2, arg3
Returns : nothing
Example : chompall(\$out, \$err, \$returnvalue);
=cut
#-------------------------------------------------------
sub chompall{
my ( $arg1, $arg2, $arg3 ) = @_;
chomp($$arg1);
chomp($$arg2);
chomp($$arg3);
}
# ***********************************************************
# Mainline. Parse any arguments, usually no arguments
$Getopt::Long::ignorecase = 0;
Getopt::Long::Configure( "bundling" );
GetOptions(
'h|help' => \$displayHelp,
'v' => \$versionOpt );
if ( $versionOpt ) {
print "Version: $version\n";
exit;
}
if ( $displayHelp ) {
print $usage_string;
exit;
}
my $out = '';
my $err = '';
my $returnvalue = 0;
# This looks in the passwd table for a key = sudoer
($::SUDOER, $::SUDO) = xCAT::zvmUtils->getSudoer();
# Scan the xCAT tables to get the zhcp node name
# Print out a message and stop if any errors found
@entries = xCAT::TableUtils->get_site_attribute("master");
$masterIP = $entries[0];
if ( !$masterIP ) {
print "xCAT site table is missing a master with ip address\n";
exit;
}
# Get xcat node name from 'hosts' table using IP as key
@propNames = ( 'node');
$propVals = xCAT::zvmUtils->getTabPropsByKey('hosts', 'ip', $masterIP, @propNames);
$xcatNode = $propVals->{'node'};
if ( !$xcatNode ) {
print "xCAT hosts table is missing a node with ip address of $masterIP\n";
exit;
}
# Get hcp for xcat from the zvm table using xcat node name
@propNames = ( 'hcp');
$propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $xcatNode, @propNames );
$hcp = $propVals->{'hcp'};
if ( !$hcp ) {
print "xCAT zvm table is missing hcp value for $xcatNode\n";
exit;
}
# Get zhcp node name from 'hosts' table using hostname as key
@propNames = ( 'node');
$propVals = xCAT::zvmUtils->getTabPropsByKey('hosts', 'hostnames', $hcp, @propNames);
$zhcpNode = $propVals->{'node'};
if ( !$zhcpNode ) {
print "xCAT hosts table is missing a zhcp node with hostname of $hcp\n";
exit;
}
#Create the migrate directory and the xcat tables directory. This should not get error even if it exists
print "Creating directory $exportDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "mkdir -p -m 0755 $exportDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to create $exportDir:\n";
print "$err\n";
exit;
}
print "Creating directory $exportTablesDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "mkdir -p -m 0755 $exportTablesDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to create $exportTablesDir:\n";
print "$err\n";
exit;
}
print "Creating directory $exportFcpConfigsDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "mkdir -p -m 0755 $exportFcpConfigsDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to create $exportFcpConfigsDir:\n";
print "$err\n";
exit;
}
print "Creating directory $exportFcpOtherFilesDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "mkdir -p -m 0755 $exportFcpOtherFilesDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to create $exportFcpOtherFilesDir:\n";
print "$err\n";
exit;
}
print "Creating directory $exportDocloneFilesDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "mkdir -p -m 0755 $exportDocloneFilesDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to create $exportDocloneFilesDir:\n";
print "$err\n";
exit;
}
#Save the current LVM information
print "Saving current LVM information at $exportDir/$lvmInfoFile \n";
( $out, $err, $returnvalue ) = eval { capture { system( "vgdisplay '-v' 2>&1 > $exportDir/$lvmInfoFile"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to display LVM information:\n";
print "$err\n";
exit;
}
#Save the current Linux DASD list information
print "Saving current Linux DASD list information at $exportDir/$lsdasdInfoFile \n";
( $out, $err, $returnvalue ) = eval { capture { system( "lsdasd 2>&1 > $exportDir/$lsdasdInfoFile"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to display Linux DASD list information:\n";
print "$err\n";
exit;
}
#Save the current zVM virtual DASD list information
print "Saving current zVM virtual DASD list information at $exportDir/$zvmVirtualDasdInfoFile \n";
( $out, $err, $returnvalue ) = eval { capture { system( "vmcp q v dasd 2>&1 > $exportDir/$zvmVirtualDasdInfoFile"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to display zVM virtual DASD list information:\n";
print "$err\n";
exit;
}
#save the xcat tables
print "Dumping xCAT tables to $exportTablesDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( ". /etc/profile.d/xcat.sh; /opt/xcat/sbin/dumpxCATdb -p $exportTablesDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to dump the xcat tables to $exportTablesDir:\n";
print "$err\n";
exit;
}
#Check for and save any zhcp FCP configuration files
print "Checking zhcp for any FCP configuration files\n";
( $out, $err, $returnvalue ) = eval { capture { system( "ssh $zhcpNode ls /var/opt/zhcp/zfcp/*.conf"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue == 0) {
# Save any *.conf files
print "Copying /var/opt/zhcp/zfcp/*.conf files to $exportFcpConfigsDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "scp $::SUDOER\@$zhcpNode:/var/opt/zhcp/zfcp/*.conf $exportFcpConfigsDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to use scp to copy files from $zhcpNode\n";
print "$err\n";
exit;
}
} else {
# If file not found, that is an OK error, if others then display error and exit
if (index($err, "No such file or directory")== -1) {
print "Error rv:$returnvalue trying to use ssh to list files on $zhcpNode\n";
print "$err\n";
exit;
}
}
# Check for any other zhcp FCP files
( $out, $err, $returnvalue ) = eval { capture { system( "ssh $zhcpNode ls /opt/zhcp/conf/*"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue == 0) {
# Save any files found
print "Copying /opt/zhcp/conf/*.conf files to $exportFcpOtherFilesDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "scp $::SUDOER\@$zhcpNode:/opt/zhcp/conf/* $exportFcpOtherFilesDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to use scp to copy /opt/zhcp/conf/* files from $zhcpNode\n";
print "$err\n";
exit;
}
} else {
# If file not found, that is an OK error, if others then display error and exit
if (index($err, "No such file or directory")== -1) {
print "Error rv:$returnvalue trying to use ssh to list files on $zhcpNode\n";
print "$err\n";
exit;
}
}
# Check for any doclone.txt file
( $out, $err, $returnvalue ) = eval { capture { system( "ls /var/opt/xcat/doclone.txt"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue == 0) {
# Save any file found
print "Copying /var/opt/xcat/doclone.txt file to $exportDocloneFilesDir\n";
( $out, $err, $returnvalue ) = eval { capture { system( "cp /var/opt/xcat/doclone.txt $exportDocloneFilesDir"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to copy /var/opt/xcat/doclone.txt file\n";
print "$err\n";
exit;
}
} else {
# If file not found, that is an OK error, if others then display error and exit
if (index($err, "No such file or directory")== -1) {
print "Error rv:$returnvalue trying to copy /var/opt/xcat/doclone.txt file\n";
print "$err\n";
exit;
}
}
#unmount the /install
print "Unmounting $lvmPath\n";
( $out, $err, $returnvalue ) = eval { capture { system( "umount $lvmPath"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to umount $lvmPath:\n";
print "$err\n";
exit;
}
#mark the lvm inactive
print "Making the LVM $vgName inactive\n";
( $out, $err, $returnvalue ) = eval { capture { system( "vgchange '-an' $vgName"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to inactivate volume group $vgName:\n";
print "$err\n";
exit;
}
#export the volume group
print "Exporting the volume group $vgName\n";
( $out, $err, $returnvalue ) = eval { capture { system( "vgexport $vgName"); } };
chompall(\$out, \$err, \$returnvalue);
if ($returnvalue) {
print "Error rv:$returnvalue trying to export volume group $vgName:\n";
print "$err\n";
exit;
}
print "\nVolume group $vgName is exported, you can now signal shutdown xcat and\n";
print "have the xcat lvm disks linked RW in the new appliance.";
exit 0;

View File

@ -0,0 +1,758 @@
#!/usr/bin/perl
###############################################################################
# IBM (C) Copyright 2015, 2016 Eclipse Public License
# http://www.eclipse.org/org/documents/epl-v10.html
###############################################################################
# COMPONENT: zxcatimport
#
# This is a program to copy the xCAT /install files and the xCAT tables from
# an old XCAT userid to the new appliance
# See usage string below for parameters.
# return code = 0 successful; else error.
#
###############################################################################
use strict;
use warnings;
use Capture::Tiny ':all';
use Getopt::Long;
use lib '/opt/xcat/lib/perl/';
use xCAT::TableUtils;
use xCAT::Table;
use xCAT::zvmUtils;
use xCAT::MsgUtils;
my $lvmPath = "/dev/xcat/repo";
my $lvmMountPoint = "/install2";
my $lvmImportDir = "/install2/xcatmigrate";
my $lvmImportTablesDir = "/install2/xcatmigrate/xcattables";
my $lvmImportFcpConfigsDir = "/install2/xcatmigrate/fcpconfigs";
my $lvmImportFcpOtherFilesDir = "/install2/xcatmigrate/fcpotherfiles";
my $lvmImportDocloneFilesDir = "/install2/xcatmigrate/doclone";
my $lvmInfoFile = "lvminformation";
my $lsdasdInfoFile = "lsdasdinformation";
my $zvmVirtualDasdInfoFile = "zvmvirtualdasdinformation";
my $vgName = "xcat";
my $persistentMountPoint = "/persistent2";
my @defaultTables = ("hosts", "hypervisor", "linuximage", "mac", "networks", "nodelist",
"nodetype", "policy", "zvm");
my $version = "1.0";
my $out;
my $err;
my $returnValue;
my $copyLvmFiles = 0; # Copy files under old /install to new /install
my $replaceAllXcatTables = 0; # Copy one or all xcat tables
my $addTableData = '*none*'; # Add node data to one table or default tables
my $copyFcpConfigs = 0; # copy old zhcp fcp *.conf files
my $copyDoclone = 0; # copy old doclone.txt file
my $replaceSshKeys = 0; # replace SSH keys with old xCAT SSH keys
my $displayHelp = 0; # Display help information
my $versionOpt = 0; # Show version information flag
my $rc = 0;
my $usage_string = "This script will mount or copy the old xcat lvm and old persistent disk\n
to this appliance. The old xCAT LVM volumes and the persistent disk on XCAT userid must \n
be linked in write mode by this appliance. The LVM will be mounted at '/install2' and \n
the persistent disk will be mounted at '/persistent2'.\n
\n
The default is to just mount the persistent and LVM disks.\n
They will be mounted as /install2 and /persistent2\n\n
Usage:\n
$0 [--addtabledata [tablename]] [--installfiles ] [--doclonefile]\n
[--fcppoolconfigs] [--replacealltables] [--replaceSSHkeys] \n
$0 [ -v ]\n
$0 [ -h | --help ]\n
The following options are supported:\n
--addtabledata [tablename] | ['tablename1 tablename2 ..']\n
Add old xCAT data to specific table(s) or\n
default to the following xCAT tables:\n
hosts, hypervisor, linuximage, mac, networks, nodelist,\n
nodetype, policy, zvm/n
--installfiles Copy any files from old /install to appliance /install\n
--doclonefile Copy any doclone.txt to appliance\n
--fcppoolconfigs Copy any zhcp FCP pool configuration files\n
--replacealltables Replace all xCAT tables with old xCAT tables\n
--replaceSSHkeys Replaces the current xCAT SSH keys with the old xCAT SSH keys\n
-h | --help Display help information\n
-v Display the version of this script.\n";
#-------------------------------------------------------
=head3 chompall
Description : Issue chomp on all three input parms (pass by reference)
Arguments : arg1, arg2, arg3
Returns : nothing
Example : chompall(\$out, \$err, \$returnValue);
=cut
#-------------------------------------------------------
sub chompall{
my ( $arg1, $arg2, $arg3 ) = @_;
chomp($$arg1);
chomp($$arg2);
chomp($$arg3);
}
# =======unit test/debugging routine ==========
# print the return data from tiny capture return
# data for: out, err, return value
sub printreturndata{
my ( $arg1, $arg2, $arg3 ) = @_;
print "=============================\n";
print "Return value ($$arg3)\n";
print "out ($$arg1)\n";
print "err ($$arg2)\n\n";
}
## ---------------------------------------------- ##
## Subroutine to find device name from address
sub get_disk($)
{
my ($id_user) = @_;
my $id = hex $id_user;
my $hex_id = sprintf '%x', $id;
my $dev_path = sprintf '/sys/bus/ccw/drivers/dasd-eckd/0.0.%04x', $id;
unless (-d $dev_path) {
$dev_path = sprintf '/sys/bus/ccw/drivers/dasd-fba/0.0.%04x', $id;
}
-d $dev_path or return undef;
my $dev_block = "$dev_path/block";
unless (-d $dev_block) {
# Try bringing the device online
for (1..5) {
system("echo 1 > $dev_path/online");
last if -d $dev_block;
sleep(10);
}
}
opendir(my $dir, $dev_block) or return undef;
my $dev;
while ($dev = readdir $dir) {
last unless $dev eq '.' || $dev eq '..';
}
closedir $dir;
defined $dev ? "/dev/$dev" : undef;
}
#-------------------------------------------------------
=head3 mountOldLVM
Description : This routine will import the old LVM and mount
it at /install2
Arguments : none
Returns : 0 - LVM mounted or already mounted
non-zero - Error detected.
Example : $rc = mountOldLVM;
=cut
#-------------------------------------------------------
sub mountOldLVM{
my $saveMsg;
my $saveErr;
my $saveReturnValue;
#Check for /install2 If already mounted should get a return value(8192) and $err output
#Check $err for "is already mounted on", if found we are done.
print "Checking for $lvmMountPoint.\n";
( $out, $err, $returnValue ) = eval { capture { system( "mount $lvmMountPoint"); } };
chompall(\$out, \$err, \$returnValue);
if (index($err, "already mounted on $lvmMountPoint") > -1) {
print "Old xCAT LVM is already mounted at $lvmMountPoint\n";
return 0;
}
print "Importing $vgName\n";
( $out, $err, $returnValue ) = eval { capture { system( "/sbin/vgimport $vgName"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
# There could be a case where the LVM has been imported already
# Save this error information and do the next step (vgchange)
$saveMsg = "Error rv:$returnValue trying to vgimport $vgName";
$saveErr = "$err";
$saveReturnValue = $returnValue;
}
print "Activating LVM $vgName\n";
( $out, $err, $returnValue ) = eval { capture { system( "/sbin/vgchange -a y $vgName"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
# If the import failed previously, put out that message instead.
if (!defined $saveMsg) {
print "$saveMsg\n";
print "$saveErr\n";
return $saveReturnValue;
} else {
print "Error rv:$returnValue trying to vgchange -a y $vgName\n";
print "$err\n";
retun $returnValue;
}
}
print "Making $lvmMountPoint directory\n";
( $out, $err, $returnValue ) = eval { capture { system( "mkdir -p $lvmMountPoint"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to mkdir -p $lvmMountPoint\n";
print "$err\n";
return $returnValue;
}
print "Mounting LVM $lvmPath at $lvmMountPoint\n";
( $out, $err, $returnValue ) = eval { capture { system( "mount -t ext3 $lvmPath $lvmMountPoint"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to mkdir -p $lvmMountPoint\n";
print "$err\n";
return $returnValue;
}
print "Old xCAT LVM is now mounted at $lvmMountPoint\n";
return 0;
}
#-------------------------------------------------------
=head3 mountOldPersistent
Description : This routine will look for the old persistent disk and mount
it at /persistent2
Arguments : none
Returns : 0 - /persistent2 mounted or already mounted
non-zero - Error detected.
Example : $rc = mountOldPersistent;
=cut
#-------------------------------------------------------
sub mountOldPersistent{
#Check for /persistent2 If already mounted should get a return value(8192) and $err output
#Check $err for "is already mounted on", if found we are done.
print "Checking for $persistentMountPoint.\n";
( $out, $err, $returnValue ) = eval { capture { system( "mount $persistentMountPoint"); } };
chompall(\$out, \$err, \$returnValue);
if (index($err, "already mounted on $persistentMountPoint") > -1) {
print "The old xCAT /persistent disk already mounted at $persistentMountPoint\n";
return 0;
}
# search the exported Linux lsdasd file to get the vdev for vdev 100 (dasda)
# should look like: 0.0.0100 active dasda 94:0 ECKD 4096 2341MB 599400
my $dasda = `cat "$lvmImportDir/$lsdasdInfoFile" | egrep -i "dasda"`;
if (length($dasda) <= 50) {
print "Unable to find dasda information in $lvmImportDir/$lsdasdInfoFile\n";
return 1;
}
my @tokens = split(/\s+/, $dasda);
my @vdevparts = split (/\./, $tokens[0]);
my $vdev = $vdevparts[2];
if (!(length($vdev))) {
print "Unable to find a vdev value for dasda\n";
return 1;
}
# search the exported zVM virtual dasd list to get the volume id of the disk
# should look like: DASD 0100 3390 QVCD69 R/W 3330 CYL ON DASD CD69 SUBCHANNEL = 000B
my $voliddata = `cat "$lvmImportDir/$zvmVirtualDasdInfoFile" | egrep -i "DASD $vdev"`;
if (length($voliddata) <= 50) {
print "Unable to find volid information for $vdev in $lvmImportDir/$zvmVirtualDasdInfoFile\n";
return 1;
}
@tokens = split(/\s+/, $voliddata);
my $volid = $tokens[3];
if (!(length($volid))) {
print "Unable to find a volume id for vdev $vdev\n";
return 1;
}
# Now display the current zVM query v dasd to see if they have the volid listed
# and what vdev it is mounted on
( $out, $err, $returnValue ) = eval { capture { system( "vmcp q v dasd 2>&1"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to vmcp q v dasd\n";
print "$err\n";
return $returnValue;
}
# get the current VDEV the old volid is now using
# If not they they did not update the directory to link to the old classic disk
( $out, $err, $returnValue ) = eval { capture { system( "echo \"$out\" | egrep -i $volid"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to echo $out\n";
print "$err\n";
return $returnValue;
}
if (!(length($out))) {
print "Unable to find a current vdev value for volume id $volid\n";
return 1;
}
@tokens = split(/\s+/, $out);
my $currentvdev = $tokens[1];
if (!(length($currentvdev))) {
print "Unable to find a current vdev value for volume id $volid\n";
return 1;
}
# Now get the Linux disk name that is being used for this vdev (/dev/dasdx)
my $devname = get_disk($currentvdev);
#print "Devname found: $devname\n";
if (!(defined $devname)) {
print "Unable to find a Linux disk for address $currentvdev volume id $volid\n";
return 1;
}
# Create the directory for the mount of old persistent disk
( $out, $err, $returnValue ) = eval { capture { system( "mkdir -p -m 0755 $persistentMountPoint"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to create $persistentMountPoint:\n";
print "$err\n";
return $returnValue;
}
# Mount the old persistent disk, must be partition 1
my $partition = 1;
( $out, $err, $returnValue ) = eval { capture { system( "mount -t ext3 $devname$partition $persistentMountPoint"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to mount -t ext3 $devname$partition $persistentMountPoint\n";
print "$err\n";
return $returnValue;
}
print "The old xCAT /persistent disk is mounted at $persistentMountPoint\n";
return 0;
}
# ***********************************************************
# Mainline. Parse any arguments
$Getopt::Long::ignorecase = 0;
Getopt::Long::Configure( "bundling" );
GetOptions(
'installfiles' => \$copyLvmFiles,
'replacealltables' => \$replaceAllXcatTables,
'addtabledata:s' => \$addTableData,
'fcppoolconfigs' => \$copyFcpConfigs,
'doclonefile' => \$copyDoclone,
'replaceSSHkeys' => \$replaceSshKeys,
'h|help' => \$displayHelp,
'v' => \$versionOpt );
if ( $versionOpt ) {
print "Version: $version\n";
exit 0;
}
if ( $displayHelp ) {
print $usage_string;
exit 0;
}
# Use sudo or not
# This looks in the passwd table for a key = sudoer
($::SUDOER, $::SUDO) = xCAT::zvmUtils->getSudoer();
$rc = mountOldLVM();
if ($rc != 0) {
exit 1;
}
$rc = mountOldPersistent();
if ($rc != 0) {
exit 1;
}
# *****************************************************************************
# **** Copy the LVM files from old xCAT LVM to current LVM
if ( $copyLvmFiles ) {
$rc = chdir("$lvmMountPoint");
if (!$rc) {
print "Error rv:$rc trying to chdir $lvmMountPoint\n";
exit 1;
}
$out = `cp -a * /install 2>&1`;
if ($?) {
print "Error rv:$? trying to copy from $lvmMountPoint to /install. $out\n";
exit $?;
}
print "Old LVM Files copied from $lvmMountPoint to /install\n" ;
}
# *****************************************************************************
# **** Replace all the current xCAT tables with the old xCAT tables
if ( $replaceAllXcatTables ) {
print "Restoring old xCAT tables from $lvmImportTablesDir\n";
# restorexCATdb - restores the xCAT db tables from the directory -p path
( $out, $err, $returnValue ) = eval { capture { system( ". /etc/profile.d/xcat.sh; /opt/xcat/sbin/restorexCATdb -p $lvmImportTablesDir"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to restore the xcat tables from $lvmImportTablesDir:\n";
print "$err\n";
exit 1;
}
# There is a chance the return value is 0, and the $out says "Restore of Database Complete.";
# Yet some of the tables had failures. That information is in $err
if (length($err)) {
print "Some tables did not restore. Error output:\n$err\n ";
exit 1;
}
}
# *****************************************************************************
# **** Copy the zhcp FCP config files
if ($copyFcpConfigs) {
# Check if there are any FCP config files to copy
( $out, $err, $returnValue ) = eval { capture { system( "ls $lvmImportFcpConfigsDir/*.conf"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue == 0) {
# Save any *.conf files
print "Copying $lvmImportFcpConfigsDir/*.conf files to /var/opt/zhcp/zfcp\n";
( $out, $err, $returnValue ) = eval { capture { system( "mkdir -p /var/opt/zhcp/zfcp && cp -R $lvmImportFcpConfigsDir/*.conf /var/opt/zhcp/zfcp/"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy files from $lvmImportFcpConfigsDir\n";
print "$err\n";
exit 1;
}
} else {
print "There were not any zhcp FCP *.conf files to copy\n";
}
# Check if there are any other FCP files to copy
( $out, $err, $returnValue ) = eval { capture { system( "ls $lvmImportFcpOtherFilesDir/*"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue == 0) {
# Save any files
print "Copying $lvmImportFcpOtherFilesDir/* files to /opt/zhcp/conf\n";
( $out, $err, $returnValue ) = eval { capture { system( "mkdir -p /opt/zhcp/conf && cp -R $lvmImportFcpOtherFilesDir/* /opt/zhcp/conf/"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy files from $lvmImportFcpOtherFilesDir\n";
print "$err\n";
exit 1;
}
} else {
print "There were not any zhcp files from /opt/zhcp/conf to copy\n";
}
}
# *****************************************************************************
# **** Copy the doclone.txt file if it exists
if ($copyDoclone) {
# Check if there is a doclone.txt to copy
( $out, $err, $returnValue ) = eval { capture { system( "ls $lvmImportDocloneFilesDir/doclone.txt"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue == 0) {
# Save this file in correct location
print "Copying $lvmImportDocloneFilesDir/doclone.txt file to /var/opt/xcat/doclone.txt\n";
( $out, $err, $returnValue ) = eval { capture { system( "cp -R $lvmImportDocloneFilesDir/doclone.txt /var/opt/xcat/"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy doclone.txt file from $lvmImportDocloneFilesDir\n";
print "$err\n";
exit 1;
}
} else {
print "There was not any doclone.txt file to copy\n";
}
}
# *****************************************************************************
# **** Add old xCAT table data to a table
my $test = length($addTableData);
# Add old xCAT data to an existing table. Admin may need to delete out duplicates using the GUI
if ((length($addTableData)==0) || $addTableData ne "*none*") {
#defaultTables = ("hosts", "hypervisor", "linuximage", "mac", "networks", "nodelist",
# "nodetype", "policy", "zvm");
my @tables = @defaultTables;
if (length($addTableData)>1 ) {
# use the table specified
@tables = ();
@tables = split(' ',$addTableData);
}
foreach my $atable (@tables) {
print "Adding data to table $atable\n";
# the current xCAT code we have does not support the -a option
# use xCAT::Table functions
my $tabledata = `cat "$lvmImportTablesDir\/$atable\.csv"`;
if (length($tabledata) <= 10) {
print "Unable to find table information for $atable in $lvmImportTablesDir\n";
return 1;
}
# remove the hash tag from front
$tabledata =~ s/\#//;
my @rows = split('\n', $tabledata);
my @keys;
my @values;
my $tab;
# loop through all the csv rows, first are the header keys, rest is data
foreach my $i (0 .. $#rows) {
my %record;
#print "row $i data($rows[$i])\n";
if ($i == 0) {
@keys = split(',', $rows[0]);
#print "Keys found:(@keys)\n";
} else {
# now that we know we have data, lets create table
if (!defined $tab) {
$tab = xCAT::Table->new($atable, -create => 1, -autocommit => 0);
}
# put the data into the new table.
@values = split(',', $rows[$i]);
foreach my $v (0 .. $#values) {
# Strip off any leading and trailing double quotes
$values[$v] =~ s/"(.*?)"\z/$1/s;
$record{$keys[$v]} = $values[$v];
#print "Row $i matches key $keys[$v] Value found:($values[$v])\n";
}
}
# write out the row if any keys added to the hash
if (%record) {
my @dbrc = $tab->setAttribs(\%record, \%record);
if (!defined($dbrc[0])) {
print "Error ($dbrc[1]) setting database for table $atable";
$tab->rollback();
$tab->close;
exit 1;
}
}
}
# if we made it here and $tab is defined, commit it.
if (defined $tab) {
$tab->commit;
print "Data successfully added and committed to $atable.\n*****! Remember to check the table and remove any rows not needed\n";
}
}#end for each table
}
# *****************************************************************************
# **** Replace the xCAT SSH key with the old xCAT SSH key
# First copy the current keys and copy the old xCAT keys into unique file names
if ($replaceSshKeys) {
# Make temp file names to hold the current and old ssh public and private key
my $copySshKey= `/bin/mktemp -p /root/.ssh/ id_rsa.pub_XXXXXXXX`;
chomp($copySshKey);
my $copySshPrivateKey= `/bin/mktemp -p /root/.ssh/ id_rsa_XXXXXXXX`;
chomp($copySshPrivateKey);
# Make temp files for the RSA backup keys in appliance
my $copyHostSshKey= `/bin/mktemp -p /etc/ssh/ ssh_host_rsa_key.pub_XXXXXXXX`;
chomp($copyHostSshKey);
my $copyHostSshPrivateKey= `/bin/mktemp -p /etc/ssh/ ssh_host_rsa_key_XXXXXXXX`;
chomp($copyHostSshPrivateKey);
# Save old keys in unique names
my $oldSshKey= `/bin/mktemp -p /root/.ssh/ id_rsa.pub_OldMachineXXXXXXXX`;
chomp($oldSshKey);
my $oldSshPrivateKey= `/bin/mktemp -p /root/.ssh/ id_rsa_OldMachineXXXXXXXX`;
chomp($oldSshPrivateKey);
print "Making backup copies of current xCAT SSH keys\n";
( $out, $err, $returnValue ) = eval { capture { system( "cp \-p /root/.ssh/id_rsa.pub $copySshKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy /root/.ssh/id_rsa.pub to $copySshKey\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "cp \-p /root/.ssh/id_rsa $copySshPrivateKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy /root/.ssh/id_rsa to $copySshPrivateKey\n";
print "$err\n";
exit 1;
}
# Save appliance backup keys
( $out, $err, $returnValue ) = eval { capture { system( "cp \-p /etc/ssh/ssh_host_rsa_key.pub $copyHostSshKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy /etc/ssh/ssh_host_rsa_key.pub to $copyHostSshKey\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "cp \-p /etc/ssh/ssh_host_rsa_key $copyHostSshPrivateKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy /etc/ssh/ssh_host_rsa_key to $copyHostSshPrivateKey\n";
print "$err\n";
exit 1;
}
# Copy the old public key and make sure the permissions are 644
print "Copying old xCAT SSH keys (renamed) from /persistent2 to /root/.ssh\n";
( $out, $err, $returnValue ) = eval { capture { system( "cp /persistent2/root/.ssh/id_rsa.pub $oldSshKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy /persistent2/root/.ssh/id_rsa.pub to $oldSshKey\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "chmod 644 $oldSshKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to chmod 644 $oldSshKey\n";
print "$err\n";
exit 1;
}
# Copy the private key and make sure the permissions are 600
( $out, $err, $returnValue ) = eval { capture { system( "cp /persistent2/root/.ssh/id_rsa $oldSshPrivateKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use cp to copy /persistent2/root/.ssh/id_rsa to $oldSshPrivateKey\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "chmod 600 $oldSshPrivateKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to chmod 600 $oldSshPrivateKey\n";
print "$err\n";
exit 1;
}
# Now compare the IP of xCAT to zHCP .
# If they are the same, then only the private and public key in xCAT needs to be changed.
# If zhcp is on a different machine, then the first thing to be done is add the old xCAT key
# to the zhcp authorized_keys files, then do the switch on xcat of public and private keys
my $xcatIp;
my $zhcpIp;
my $zhcpHostName;
my $zhcpNode;
my $xcatNodeName;
my @propNames;
my $propVals;
my @entries;
my $rc = 0;
# Scan the xCAT tables to get the zhcp node name
# Print out a message and stop if any errors found
@entries = xCAT::TableUtils->get_site_attribute("master");
$xcatIp = $entries[0];
if ( !$xcatIp ) {
print "xCAT site table is missing a master with ip address\n";
exit 1;
}
# Get xcat node name from 'hosts' table using IP as key
@propNames = ( 'node');
$propVals = xCAT::zvmUtils->getTabPropsByKey('hosts', 'ip', $xcatIp, @propNames);
$xcatNodeName = $propVals->{'node'};
if ( !$xcatNodeName ) {
print "xCAT hosts table is missing a node with ip address of $xcatIp\n";
exit 1;
}
# Get hcp hostname for xcat from the zvm table using xcat node name
@propNames = ( 'hcp');
$propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $xcatNodeName, @propNames );
$zhcpHostName = $propVals->{'hcp'};
if ( !$zhcpHostName ) {
print "xCAT zvm table is missing hcp value for $xcatNodeName\n";
exit 1;
}
# Get zhcp IP and node from 'hosts' table using hostname as key
@propNames = ( 'ip', 'node');
$propVals = xCAT::zvmUtils->getTabPropsByKey('hosts', 'hostnames', $zhcpHostName, @propNames);
$zhcpIp = $propVals->{'ip'};
if ( !$zhcpIp ) {
print "xCAT hosts table is missing a zhcp node IP with hostname of $zhcpHostName\n";
exit 1;
}
$zhcpNode = $propVals->{'node'};
if ( !$zhcpNode ) {
print "xCAT hosts table is missing a zhcp node with hostname of $zhcpHostName\n";
exit 1;
}
if ($zhcpIp eq $xcatIp) {
print "xCAt and zhcp are on same IP, only need to update public and private keys\n";
} else {
# Need to append the old SSH key to zhcp authorized_keys file
my $target = "$::SUDOER\@$zhcpHostName";
print "Copying old SSH key to zhcp\n";
( $out, $err, $returnValue ) = eval { capture { system( "scp $oldSshKey $target:$oldSshKey"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to use scp to copy $oldSshKey to zhcp $oldSshKey\n";
print "$err\n";
exit 1;
}
# Adding the old SSH key to the authorized_keys file
# Make a copy of the old authorized_users file
my $suffix = '_' . substr($oldSshKey, -8);
( $out, $err, $returnValue ) = eval { capture { system( "ssh $target cp \"/root/.ssh/authorized_keys /root/.ssh/authorized_keys$suffix\""); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to make a copy of the /root/.ssh/authorized_keys file\n";
print "$err\n";
exit 1;
}
# Add the key to zhcp authorized_keys file
( $out, $err, $returnValue ) = eval { capture { system( "ssh $target cat \"$oldSshKey >> /root/.ssh/authorized_keys\""); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to append zhcp $oldSshKey to /root/.ssh/authorized_keys\n";
print "$err\n";
exit 1;
}
}
# We need to replace the xCAT public and private key with the old keys
# and add the old key to the authorized_keys on xCAT
( $out, $err, $returnValue ) = eval { capture { system( "cat $oldSshKey >> /root/.ssh/authorized_keys"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to append xcat $oldSshKey to /root/.ssh/authorized_keys\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "cp \-f $oldSshKey /root/.ssh/id_rsa.pub"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to replace the /root/.ssh/id_rsa.pub with the $oldSshKey\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "cp \-f $oldSshPrivateKey /root/.ssh/id_rsa"); } };
chompall(\$out, \$err, \$returnValue);
#printreturndata(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to replace the /root/.ssh/id_rsa with the $oldSshPrivateKey\n";
print "$err\n";
exit 1;
}
# Copy old keys into appliance saved key locations
( $out, $err, $returnValue ) = eval { capture { system( "cp \-f $oldSshKey /etc/ssh/ssh_host_rsa_key.pub"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to replace the /etc/ssh/ssh_host_rsa_key.pub with the $oldSshKey\n";
print "$err\n";
exit 1;
}
( $out, $err, $returnValue ) = eval { capture { system( "cp \-f $oldSshPrivateKey /etc/ssh/ssh_host_rsa_key"); } };
chompall(\$out, \$err, \$returnValue);
if ($returnValue) {
print "Error rv:$returnValue trying to replace the /etc/ssh/ssh_host_rsa_key with the $oldSshPrivateKey\n";
print "$err\n";
exit 1;
}
print "Old xCAT SSH keys have replaced current SSH keys. Previous key data saved in unique names.\n";
}
exit 0;

View File

@ -0,0 +1,9 @@
# This file maps the OpenStack version numbers to their OpenStack release name.
15. OCATA
14. NEWTON
13. MIKATA
12. LIBERTY
2015. KILO
2014.2. JUNO
2014.1. ICEHOUSE
2013.2. HAVANA

View File

@ -16,6 +16,9 @@ BuildRoot: /var/tmp/%{name}-%{version}-%{release}-root
%define pcm %(if [ "$pcm" = "1" ];then echo 1; else echo 0; fi)
%define notpcm %(if [ "$pcm" = "1" ];then echo 0; else echo 1; fi)
%define s390x %(if [ "$s390x" = "1" ];then echo 1; else echo 0; fi)
%define nots390x %(if [ "$s390x" = "1" ];then echo 0; else echo 1; fi)
# AIX will build with an arch of "ppc"
%ifos linux
BuildArch: noarch
@ -69,6 +72,10 @@ cp share/xcat/rvid/* $RPM_BUILD_ROOT/%{prefix}/share/xcat/rvid/
chmod 755 $RPM_BUILD_ROOT/%{prefix}/share/xcat/rvid/*
%endif
%if %s390x
cp openstack.versions $RPM_BUILD_ROOT/%{prefix}
chmod 644 $RPM_BUILD_ROOT/%{prefix}/openstack.versions
%endif
cp bin/* $RPM_BUILD_ROOT/%{prefix}/bin
chmod 755 $RPM_BUILD_ROOT/%{prefix}/bin/*
cp sbin/* $RPM_BUILD_ROOT/%{prefix}/sbin
@ -123,6 +130,17 @@ rm -f $RPM_BUILD_ROOT/%{prefix}/share/doc/man1/getxcatdocs.1.html
rm -f $RPM_BUILD_ROOT/%{prefix}/share/man/man1/getxcatdocs.1
%endif
# Only zVM needs scripts below. These scripts also need Capture::Tiny
%if %nots390x
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/zxcatCopyCloneList.pl
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/zxcatexport.pl
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/zxcatimport.pl
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/mkdummyimage
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/verifynode
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/zvmMsg
rm -f $RPM_BUILD_ROOT/%{prefix}/bin/zxcatIVP.pl
%endif
# These links get made in the RPM_BUILD_ROOT/prefix area
ln -sf xcatclient $RPM_BUILD_ROOT/%{prefix}/bin/rpower
ln -sf xcatclient $RPM_BUILD_ROOT/%{prefix}/bin/rscan

View File

@ -31,7 +31,7 @@ This program module file, is a set of utilities used by xCAT daemon.
Here is where we check if $peername is allowed to do $request in policy tbl.
$peername, if set signifies client has a cert that the xCAT CA accepted.
Logs to syslog and auditlog table all user commands, see site.auditskipcmds
attribute and auditnosyslog attribute.
attribute and auditnosyslog attribute.
Arguments:
@ -94,7 +94,7 @@ sub validate {
$req_noderange_info{leftnodes} = \@tmpn;
}
}
RULE: foreach $rule (@sortedpolicies) {
if ($rule->{name} and $rule->{name} ne '*') {
@ -163,7 +163,7 @@ sub validate {
push @non_hit_nodes, $_;
}
}
if($hitnum == 0){
next RULE;
}elsif($hitnum && $hitnum != $req_noderange_info{leftnodenum}){
@ -224,10 +224,33 @@ sub validate {
my $args = $request->{arg};
my $arglist;
foreach my $argument (@$args) {
$arglist .= " " . $argument;
}
if ($arglist) { $logst .= $arglist; }
my $saveArglist = $arglist;
# If this is mkvm check for --password or -w
if ($request->{command}->[0] eq "mkvm") {
my $first;
my $restcommand;
my $passw = index ($saveArglist, '--password');
if ($passw > -1) {
$passw = $passw + 11;
my $first = substr($saveArglist,0,$passw). "******** ";
my $restcommand = substr($saveArglist,$passw);
$restcommand =~ s/^\S+\s*//;
$saveArglist = "$first$restcommand";
}
# now check for -w with password
$passw = index ($saveArglist, '-w');
if ($passw > -1) {
$passw = $passw + 3;
$first = substr($saveArglist,0,$passw). "******** ";
$restcommand = substr($saveArglist,$passw);
$restcommand =~ s/^\S+\s*//;
$saveArglist = "$first$restcommand";
}
}
if ($arglist) { $logst .= $saveArglist; }
if ($peername) { $logst .= " for " . $request->{username}->[0] }
if ($peerhost) { $logst .= " from " . $peerhost }
@ -319,7 +342,7 @@ sub validate {
if($req_noderange_info{leftnodenum}){
my $leftnodes = join(",", @{$req_noderange_info{leftnodes}});
xCAT::MsgUtils->message("S", "Request matched no policy rule: peername=$peername, peerhost=$peerhost $request->{command}->[0] to $leftnodes");
xCAT::MsgUtils->message("S", "Request matched no policy rule: peername=$peername, peerhost=$peerhost $request->{command}->[0] to $leftnodes");
}else{
xCAT::MsgUtils->message("S", "Request matched no policy rule: peername=$peername, peerhost=$peerhost " . $request->{command}->[0]);
}

View File

@ -46,10 +46,16 @@ sub process_request {
@ARGV = @{ $request->{arg} } if (defined $request->{arg});
my $argc = scalar @ARGV;
my $usage = "Usage:\n imgcapture <node> -t|--type {diskless|sysclone} -o|--osimage <osimage> [-i <nodebootif>] [-n <nodebootif>] [-V | --verbose] \n imgcapture [-h|--help] \n imgcapture [-v|--version]";
my $usage = "Usage: imgcapture <node> -t|--type {diskless|sysclone} [-p | --profile <profile>] " .
"[-o|--osimage <osimage>] [-i <nodebootif>] [-n <nodenetdrivers>] " .
"[-d | --device <devicesToCapture>] [-c | --compress <compressionLevel>] [-V | --verbose] \n\n" .
"imgcapture <node> -t|--type sysclone -o|--osimage <osimage> [-V | --verbose] \n" .
"imgcapture [-h|--help] \n" .
"imgcapture [-v|--version]";
my $os;
my $arch;
my $compression; # Supported by the s390x architecture
my $device;
my $profile;
my $bootif;
@ -65,6 +71,7 @@ sub process_request {
'n=s' => \$netdriver,
'osimage|o=s' => \$osimg,
"device|d=s" => \$device,
"compress|c=s" => \$compression,
"help|h" => \$help,
"version|v" => \$version,
"verbose|V" => \$verbose,
@ -123,7 +130,7 @@ sub process_request {
# Handle image capture separately for s390x
if ($arch eq 's390x') {
eval { require xCAT_plugin::zvm; }; # Load z/VM plugin dynamically
xCAT_plugin::zvm->imageCapture($callback, $node, $os, $arch, $profile, $osimg, $device);
xCAT_plugin::zvm->imageCapture($callback, $node, $os, $arch, $type, $profile, $osimg, $device, $compression);
return;
}

View File

@ -99,13 +99,14 @@ sub ximport {
my $nodes;
my $new_profile;
my $remoteHost;
my $nozip = 0;
my $xusage = sub {
my $ec = shift;
push @{ $rsp{data} }, "imgimport: Takes in an xCAT image bundle and defines it to xCAT so you can use it";
push @{ $rsp{data} }, "Usage: ";
push @{ $rsp{data} }, "\timgimport [-h|--help]";
push @{ $rsp{data} }, "\timgimport <bundle_file_name> [-p|--postscripts <nodelist>] [-f|--profile <new_profile>] [-R|--remotehost <userid\@host>] [-v]";
push @{ $rsp{data} }, "\timgimport <bundle_file_name> [-p|--postscripts <nodelist>] [-f|--profile <new_profile>] [-R|--remotehost <userid\@host>] [-n|--nozip] [-v]";
if ($ec) { $rsp{errorcode} = $ec; }
$callback->(\%rsp);
};
@ -122,6 +123,7 @@ sub ximport {
'R|remotehost=s' => \$remoteHost,
'p|postscripts=s' => \$nodes,
'f|profile=s' => \$new_profile,
'n|nozip' => \$nozip
);
if ($help) {
@ -130,7 +132,7 @@ sub ximport {
}
# first extract the bundle
extract_bundle($request, $callback, $nodes, $new_profile, $remoteHost);
extract_bundle($request, $callback, $nodes, $new_profile, $remoteHost, $nozip );
}
@ -608,7 +610,7 @@ sub get_files {
if (-f "$rootimgdir/kernel") {
$kernel = "$rootimgdir/kernel";
}
my $compressedrootimg=xCAT::SvrUtils->searchcompressedrootimg("$rootimgdir");
$rootimg = "$rootimgdir/$compressedrootimg";
@ -1115,6 +1117,7 @@ sub extract_bundle {
my $nodes = shift;
my $new_profile = shift;
my $remoteHost = shift;
my $nozip = shift;
@ARGV = @{ $request->{arg} };
my $xml;
@ -1188,12 +1191,21 @@ sub extract_bundle {
$callback->({ data => ["Unbundling image..."] });
my $rc;
if ($::VERBOSE) {
if ($nozip) {
if ($::VERBOSE) {
$callback->({data=>["tar xvf $bundle -C $tpath"]});
$rc = system("tar xvf $bundle -C $tpath");
} else {
$rc = system("tar xf $bundle -C $tpath");
}
} else {
if ($::VERBOSE) {
$callback->({ data => ["tar zxvf $bundle -C $tpath"] });
$rc = system("tar zxvf $bundle -C $tpath");
} else {
$rc = system("tar zxf $bundle -C $tpath");
}
}
if ($rc) {
$callback->({ error => ["Failed to extract bundle $bundle"], errorcode => [1] });

View File

@ -55,6 +55,7 @@ sub findme {
my @SEQdiscover = xCAT::TableUtils->get_site_attribute("__SEQDiscover");
my @PCMdiscover = xCAT::TableUtils->get_site_attribute("__PCMDiscover");
my @ZVMDiscover = xCAT::TableUtils->get_site_attribute("__ZVMDiscover");
if (defined($request->{discoverymethod}) and defined($request->{discoverymethod}->[0]) and ($request->{discoverymethod}->[0] ne 'undef')) {
@ -62,7 +63,7 @@ sub findme {
return;
}
unless ($SEQdiscover[0]) {
return;
return;
}
# Get the parameters for the sequential discovery
@ -444,20 +445,25 @@ sub nodediscoverstart {
xCAT::MsgUtils->message("E", $rsp, $cb, 1);
}
my $usageinfo = "nodediscoverstart: Start a discovery process: Sequential or Profile.
my $usageinfo = "nodediscoverstart: Start a discovery process: Sequential, Profile or z/VM.
Usage:
Common:
nodediscoverstart [-h|--help|-v|--version|-V|--verbose]
Sequential Discovery:
nodediscoverstart noderange=<noderange> [hostiprange=<hostiprange>] [bmciprange=<bmciprange>] [groups=<groups>] [rack=<rack>] [chassis=<chassis>] [height=<height>] [unit=<unit>] [osimage=<osimagename>] [-n|--dns] [-s|--skipbmcsetup] [-V|--verbose]
Profile Discovery:
nodediscoverstart networkprofile=<networkprofile> imageprofile=<imageprofile> hostnameformat=<hostnameformat> [hardwareprofile=<hardwareprofile>] [groups=<groups>] [rack=<rack>] [chassis=<chassis>] [height=<height>] [unit=<unit>] [rank=rank-num]";
nodediscoverstart networkprofile=<networkprofile> imageprofile=<imageprofile> hostnameformat=<hostnameformat> [hardwareprofile=<hardwareprofile>] [groups=<groups>] [rack=<rack>] [chassis=<chassis>] [height=<height>] [unit=<unit>] [rank=rank-num]
z/VM Discovery:
nodediscoverstart zvmhost=<noderange> [defineto=both] [groups=<groups>] [ipfilter=<filter>] [openstackoperands=<operands>] [useridfilter=<filter>]
nodediscoverstart zvmhost=<noderange> defineto=xcatonly [groups=<groups>] [ipfilter=<filter>] [nodenameformat=<nodenameformat>] [useridfilter=<filter>]
nodediscoverstart zvmhost=<noderange> defineto=openstackonly [openstackoperands=<operands>]";
$rsp = ();
push @{ $rsp->{data} }, $usageinfo;
xCAT::MsgUtils->message("I", $rsp, $cb);
};
# valid attributes for deqdiscovery
# valid attributes for seqdiscovery
my %validargs = (
'noderange' => 1,
'hostiprange' => 1,
@ -500,7 +506,13 @@ Usage:
$orgargs{$name} = $value;
}
# Check the noderage=has been specified which is the flag that this is for sequential discovery
# Check the zvmhost= has been specified which is the flag that this is for z/VM discovery.
# Otherwise, fall thru to handle either sequential or profile discovery.
if ( defined( $orgargs{zvmhost} ) ) {
return;
}
# Check the noderange= has been specified which is the flag that this is for sequential discovery
# Otherwise try to check the whether the networkprofile || hardwareprofile || imageprofile
# has been passed, if yes, return to profile discovery
unless (defined($orgargs{noderange})) {
@ -510,6 +522,7 @@ Usage:
return;
} else {
$usage->($callback, "For sequential discovery, the \'noderange\' option must be specified.");
$usage->($callback, "For z/VM discovery, the \'zvmhost\' option must be specified.");
return;
}
}
@ -575,7 +588,7 @@ Usage:
$sitetab->setAttribs({ "key" => "__SEQDiscover" }, { "value" => "$textparam" });
$sitetab->close();
# Clean the entries which discovery method is 'sequential' from the discoverdata table
# Clean the entries which discovery method is 'sequential' from the discoverydata table
my $distab = xCAT::Table->new("discoverydata");
$distab->delEntries({ method => 'sequential' });
$distab->commit();
@ -697,9 +710,12 @@ sub nodediscoverstop {
xCAT::MsgUtils->message("E", $rsp, $cb, 1);
}
my $usageinfo = "nodediscoverstop: Stop the running discovery: Sequential and Profile.
my $usageinfo = "nodediscoverstop: Stop the running discovery: Profile, Sequential and z/VM.
Usage:
nodediscoverstop [-h|--help|-v|--version] ";
Common:
nodediscoverstop [-h|--help|-v|--version]
z/VM discovery:
nodediscoverstop [-z|--zvmhost <noderange>]";
$rsp = ();
push @{ $rsp->{data} }, $usageinfo;
xCAT::MsgUtils->message("I", $rsp, $cb);
@ -729,9 +745,10 @@ Usage:
# Check the running of sequential discovery
my @SEQDiscover = xCAT::TableUtils->get_site_attribute("__SEQDiscover");
my @PCMDiscover = xCAT::TableUtils->get_site_attribute("__PCMDiscover");
if ($PCMDiscover[0]) {
my @ZVMDiscover = xCAT::TableUtils->get_site_attribute("__ZVMDiscover");
if ($PCMDiscover[0] or $ZVMDiscover[0]) {
# return directly that profile discover will cover it
# return directly that the other discovery will handle the stop function.
return;
} elsif (!$SEQDiscover[0]) {
@ -739,12 +756,13 @@ Usage:
my $rsp;
push @{ $rsp->{data} }, "Sequential Discovery is stopped.";
push @{ $rsp->{data} }, "Profile Discovery is stopped.";
push @{$rsp->{data}}, "z/VM Discovery is stopped.";
xCAT::MsgUtils->message("E", $rsp, $callback, 1);
return;
}
my $DBname = xCAT::Utils->get_DBName; # support for DB2
# Go thought discoverydata table and display the sequential disocvery entries
# Go through discoverydata table and display the sequential discovery entries
my $distab = xCAT::Table->new('discoverydata');
unless ($distab) {
my $rsp;
@ -787,7 +805,7 @@ Usage:
}
=head3 nodediscoverls
Display the discovered nodes
Display the discovered nodes. This supports sequential and z/VM and partially Profile discovery.
=cut
sub nodediscoverls {
@ -805,12 +823,14 @@ sub nodediscoverls {
}
my $usageinfo = "nodediscoverls: list the discovered nodes.
Usage:
Usage:
Common:
nodediscoverls
nodediscoverls [-h|--help|-v|--version]
nodediscoverls [-t seq|profile|switch|blade|manual|mtms|undef|all] [-l]
nodediscoverls [-t seq|profile|switch|blade|manual|mtms|undef|zvm|all] [-l]
nodediscoverls [-u uuid] [-l]
";
z/VM:
nodediscoverls [-t zvm][-z|--zvmhost <noderange>] [-l]";
$rsp = ();
push @{ $rsp->{data} }, $usageinfo;
xCAT::MsgUtils->message("I", $rsp, $cb);
@ -819,14 +839,15 @@ Usage:
if ($args) {
@ARGV = @$args;
}
my ($type, $uuid, $long, $help, $ver);
my ($type, $uuid, $long, $help, $ver, $zvmHost );
if (!GetOptions(
't=s' => \$type,
'u=s' => \$uuid,
'l' => \$long,
'h|help' => \$help,
'V|verbose' => \$::VERBOSE,
'v|version' => \$ver)) {
't=s' => \$type,
'u=s' => \$uuid,
'l' => \$long,
'h|help' => \$help,
'V|verbose' => \$::VERBOSE,
'v|version' => \$ver,
'z|zvmhost=s' => \$zvmHost )) {
$usage->($callback);
return;
}
@ -841,9 +862,9 @@ Usage:
}
# If the type is specified, display the corresponding type of nodes
my @SEQDiscover;
my ( @SEQDiscover, @ZVMDiscover );
if ($type) {
if ($type !~ /^(seq|profile|switch|blade|manual|mtms|undef|all)$/) {
if ($type !~ /^(seq|profile|switch|blade|manual|mtms|undef|zvm|all)$/) {
$usage->($callback, "The discovery type \'$type\' is not supported.");
return;
}
@ -852,24 +873,31 @@ Usage:
# Check the running of sequential discovery
@SEQDiscover = xCAT::TableUtils->get_site_attribute("__SEQDiscover");
@ZVMDiscover = xCAT::TableUtils->get_site_attribute("__ZVMDiscover");
my @PCMDiscover = xCAT::TableUtils->get_site_attribute("__PCMDiscover");
if ($SEQDiscover[0]) {
$type = "seq";
} else {
my @PCMDiscover = xCAT::TableUtils->get_site_attribute("__PCMDiscover");
if ($PCMDiscover[0]) {
#return directly if my type of discover is not running.
} elsif ($PCMDiscover[0]) {
#return directly if profile discovery is running.
return;
} elsif ( $ZVMDiscover[0] ) {
# zvmdiscovery handles requests for a running z/VM discovery.
return;
} else {
# no type, no seq and no profile, then just diaplay all
$type = "all";
}
} else {
# no type, no seq and no profile, then just display all
$type = "all";
}
}
# If a zvmHost was specified then let zvmdiscovery handle it.
# Specifying '-u' will keep processing within seqdiscovery.
if ( !$uuid && ( $zvmHost || ( $type && $type eq 'zvm' )) ) {
# zvmdiscovery handles request specific to z/VM.
return;
}
my $DBname = xCAT::Utils->get_DBName; # support for DB2
# Go thought discoverydata table and display the disocvery entries
# Go through discoverydata table and display the discovery entries
my $distab = xCAT::Table->new('discoverydata');
unless ($distab) {
my $rsp;
@ -922,7 +950,8 @@ Usage:
}
my $rsp;
if ($SEQDiscover[0] && $type eq "sequential") {
if (($SEQDiscover[0] && $type eq "sequential" ) or
( $type && $type eq "all" )) {
push @{ $rsp->{data} }, "Discovered $discoverednum node.";
}
if (@discoverednodes) {
@ -957,8 +986,11 @@ sub nodediscoverstatus {
}
my $usageinfo = "nodediscoverstatus: Display the discovery process status.
Usage:
nodediscoverstatus [-h|--help|-v|--version] ";
Usage:
Common:
nodediscoverstatus [-h|--help|-v|--version]
z/VM
nodediscoverstatus [-z|--zvmhost <noderange>]";
$rsp = ();
push @{ $rsp->{data} }, $usageinfo;
xCAT::MsgUtils->message("I", $rsp, $cb);
@ -988,6 +1020,7 @@ Usage:
# Check the running of sequential discovery
my @SEQDiscover = xCAT::TableUtils->get_site_attribute("__SEQDiscover");
my @PCMDiscover = xCAT::TableUtils->get_site_attribute("__PCMDiscover");
my @ZVMDiscover = xCAT::TableUtils->get_site_attribute("__ZVMDiscover");
if ($SEQDiscover[0]) {
my $rsp;
push @{ $rsp->{data} }, "Sequential discovery is running.";
@ -997,10 +1030,13 @@ Usage:
my $rsp;
push @{ $rsp->{data} }, "Node discovery for all nodes using profiles is running";
xCAT::MsgUtils->message("I", $rsp, $callback);
} elsif ( $ZVMDiscover[0] ) {
# z/VM discovery is a more complex response so we let its handler return the response.
} else {
my $rsp;
push @{ $rsp->{data} }, "Sequential Discovery is stopped.";
push @{ $rsp->{data} }, "Profile Discovery is stopped.";
push @{$rsp->{data}}, "z/VM Discovery is stopped.";
xCAT::MsgUtils->message("I", $rsp, $callback);
}
@ -1016,6 +1052,9 @@ sub nodediscoverdef {
my $subreq = shift;
my $args = shift;
my @inputZvmHosts; # Input list of z/VM host nodes to stop
my $zvmHost; # Small scope variable to temporarily hold a z/VM host node value
# The subroutine used to display the usage message
my $usage = sub {
my $cb = shift;
@ -1029,10 +1068,13 @@ sub nodediscoverdef {
my $usageinfo = "nodediscoverdef: Define the undefined discovery request, or clean the discovery entries in the discoverydata table (Which can be displayed by nodediscoverls command).
Usage:
Common:
nodediscoverdef -u uuid -n node
nodediscoverdef -r -u uuid
nodediscoverdef -r -t {seq|profile|switch|blade|manual|undef|all}
nodediscoverdef [-h|--help|-v|--version]";
nodediscoverdef -r -t {seq|profile|switch|blade|manual|undef|zvm|all}
nodediscoverdef [-h|--help|-v|--version]
z/VM:
nodediscoverdef -r -t zvm [-z|--zvmhost noderange]";
$rsp = ();
push @{ $rsp->{data} }, $usageinfo;
xCAT::MsgUtils->message("I", $rsp, $cb);
@ -1050,7 +1092,8 @@ Usage:
'r' => \$remove,
'h|help' => \$help,
'V|verbose' => \$::VERBOSE,
'v|version' => \$ver)) {
'v|version' => \$ver,
'z|zvmhost=s' => \$zvmHost )) {
$usage->($callback);
return;
}
@ -1065,6 +1108,29 @@ Usage:
}
my $DBname = xCAT::Utils->get_DBName; # support for DB2
# Put any specified zvmhosts into an array for later use.
if ( $zvmHost ) {
$type = 'zvm' if ( !$type );
if ( $type ne 'zvm' ) {
xCAT::MsgUtils->message("E", {data=>["Discovery Error: Type must be 'zvm' when '-z' or '--zvmhost' is specified."]}, $callback);
return;
}
if ( index( $zvmHost, ',' ) != -1 ) {
# Must have specified multiple host node names
my @hosts = split( /,/, $zvmHost );
foreach $zvmHost ( @hosts ) {
if ( !$zvmHost ) {
# Tolerate zvmhost value beginning with a comma.
# It is wrong but not worth an error message.
next;
}
push( @inputZvmHosts, $zvmHost );
}
} else {
push( @inputZvmHosts, $zvmHost );
}
}
# open the discoverydata table for the subsequent using
my $distab = xCAT::Table->new("discoverydata");
unless ($distab) {
@ -1103,7 +1169,7 @@ Usage:
} elsif ($type) {
# handle the -r -t <...>
if ($type !~ /^(seq|profile|switch|blade|manual|undef|all)$/) {
if ($type !~ /^(seq|profile|switch|blade|manual|undef|zvm|all)$/) {
$usage->($callback, "The discovery type \'$type\' is not supported.");
return;
}
@ -1139,9 +1205,24 @@ Usage:
if ($type =~ /^seq/) {
$type = "sequential";
}
# If a noderange of z/VM hosts was specified then delete
# all z/VM discovered systems for those hosts. 'zvm' type
# must be used when z/VM hosts are specified.
if ( @inputZvmHosts ) {
my %keyhash;
$keyhash{'method'} = 'zvm';
foreach $zvmHost ( @inputZvmHosts ) {
$keyhash{'otherdata'} = "zvmhost." . $zvmHost;
$distab->delEntries( \%keyhash );
}
$distab->commit();
} else {
# Otherwise, Delete all systems discovered using the specified method.
$distab->delEntries({ method => $type });
$distab->commit();
}
}
}
xCAT::MsgUtils->message("I", { data => ["Removing discovery entries finished."] }, $callback);
} elsif ($uuid) {

View File

@ -303,6 +303,8 @@ sub parse_xdcp_cmd
'F|File=s' => \$options{'File'},
'h|help' => \$options{'help'},
'i|rootimg=s' => \$options{'rootimg'},
'ip=s' => \$options{'ip'},
'show=s' => \$options{'show'},
'l|user=s' => \$options{'user'},
'n|nodes=s' => \$options{'nodes'},
'o|node-options=s' => \$options{'node-options'},
@ -459,6 +461,8 @@ sub parse_xdsh_cmd
'q|show-config' => \$options{'show-config'},
'r|node-rsh=s' => \$options{'node-rsh'},
'i|rootimg=s' => \$options{'rootimg'},
'ip=s' => \$options{'ip'},
'show=s' => \$options{'show'},
's|stream' => \$options{'streaming'},
't|timeout=i' => \$options{'timeout'},
'v|verify' => \$options{'verify'},
@ -1070,11 +1074,11 @@ sub process_nodes
#-------------------------------------------------------
=head3 syncSNZoneKeys
Build the xdcp command to send the zone keys to the service nodes
Return an array of servicenodes that do not have errors
Build the xdcp command to send the zone keys to the service nodes
Return an array of servicenodes that do not have errors
Returns error code:
if = 0, good return continue to process the
nodes.
nodes.
if = 1, global error need to quit
=cut

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,306 @@
# IBM(c) 2016 EPL license http://www.eclipse.org/legal/epl-v10.html
#-------------------------------------------------------
=head1
xCAT plugin to support z/VM (s390x) diagnostics command
=cut
#-------------------------------------------------------
package xCAT_plugin::zvmdiagnostics;
#use xCAT::Client;
use xCAT::zvmUtils;
#use xCAT::zvmCPUtils;
#use xCAT::MsgUtils;
use Sys::Hostname;
#use xCAT::Table;
#use xCAT::Utils;
#use xCAT::TableUtils;
#use xCAT::ServiceNodeUtils;
#use xCAT::NetworkUtils;
#use XML::Simple;
#use File::Basename;
#use File::Copy;
#use File::Path;
#use File::Temp;
use Time::HiRes;
use POSIX;
use Getopt::Long;
use strict;
use warnings;
#use Cwd;
# Set $DEBUGGING = 1 to get extra message logging
my $DEBUGGING = 0;
# Common prefix for log messages
my $ROUTINE = "zvmdiagnostics";
my $COMMAND = "diagnostics";
my $NOTIFY_FILENAME = "/var/lib/sspmod/appliance_system_role";
my $NOTIFY_KEYWORD = "notify";
my $NOTIFY_KEYWORD_DELIMITER = "=";
# If the following line ("1;") is not included, you get:
# /opt/xcat/lib/perl/xCAT_plugin/... did not return a true value
# where ... is the name of this file
1;
#-------------------------------------------------------
=head3 handled_commands
Return list of commands handled by this plugin
=cut
#-------------------------------------------------------
sub handled_commands {
return { $COMMAND => $ROUTINE, };
}
#-------------------------------------------------------
=head3 preprocess_request
Check and setup for hierarchy
=cut
#-------------------------------------------------------
sub preprocess_request {
my $req = shift;
my $callback = shift;
my $SUBROUTINE = "preprocess_request";
# Hash array
my %sn;
# Scalar variable
my $sn;
# Array
my @requests;
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE entry");
}
# If already preprocessed, go straight to request
if ( $req->{_xcatpreprocessed}->[0] == 1 ) {
return [$req];
}
my $nodes = $req->{node};
my $service = "xcat";
# Find service nodes for requested nodes
# Build an individual request for each service node
if ($nodes) {
$sn = xCAT::ServiceNodeUtils->get_ServiceNode( $nodes, $service, "MN" );
# Build each request for each service node
foreach my $snkey ( keys %$sn ) {
my $n = $sn->{$snkey};
print "snkey=$snkey, nodes=@$n\n";
my $reqcopy = {%$req};
$reqcopy->{node} = $sn->{$snkey};
$reqcopy->{'_xcatdest'} = $snkey;
$reqcopy->{_xcatpreprocessed}->[0] = 1;
push @requests, $reqcopy;
}
return \@requests;
}
else {
# Input error
my %rsp;
my $rsp;
$rsp->{data}->[0] =
"Input noderange missing. Usage: $ROUTINE <noderange> \n";
xCAT::MsgUtils->message( "I", $rsp, $callback, 0 );
return 1;
}
}
#-------------------------------------------------------
=head3 process_request
Process the command. This is the main call.
=cut
#-------------------------------------------------------
sub process_request {
my $SUBROUTINE = "process_request";
my $request = shift;
my $callback = shift;
my $nodes = $request->{node};
my $command = $request->{command}->[0];
my $args = $request->{arg};
my $envs = $request->{env};
$::STDIN = $request->{stdin}->[0];
my %rsp;
my $rsp;
my @nodes = @$nodes;
my $host = hostname();
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE entry");
}
# Process ID for xfork()
my $pid;
# Child process IDs
my @children = ();
#*** Collect or manage diagnostics***
if ( $command eq $COMMAND ) {
foreach (@nodes) {
$pid = xCAT::Utils->xfork();
# Parent process
if ($pid) {
push( @children, $pid );
}
# Child process
elsif ( $pid == 0 ) {
if ( xCAT::zvmUtils->isHypervisor($_) ) {
#TODO should this be handled inside the subroutine, ala rmvm?
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE for hypervisor - semantically coherent?");
}
}
else {
collectDiags( $callback, $_, $args );
}
# Exit process
exit(0);
}
else {
# Ran out of resources
die "Error: Could not fork\n";
}
} # End of foreach
} # End of case
# Wait for all processes to end
foreach (@children) {
waitpid( $_, 0 );
}
return;
}
#-------------------------------------------------------
=head3 collectDiags
Description : Collect diagnostics
Arguments : Node to collect diagnostics about
Returns : Nothing
Example : collectDiags($callback, $node);
=cut
#-------------------------------------------------------
sub collectDiags {
my $SUBROUTINE = "collectDiags";
# Get inputs
my ( $callback, $node, $args ) = @_;
my $rc;
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE entry");
}
# Get node properties from 'zvm' table
my @propNames = ( 'hcp', 'userid', 'discovered' );
my $propVals = xCAT::zvmUtils->getNodeProps( 'zvm', $node, @propNames );
# Get zHCP
my $hcp = $propVals->{'hcp'};
if ( !$hcp ) {
xCAT::zvmUtils->printLn( $callback, "$node: (Error) Missing node HCP" );
return;
}
# Get node user ID
my $userId = $propVals->{'userid'};
if ( !$userId ) {
xCAT::zvmUtils->printLn( $callback, "$node: (Error) Missing user ID" );
return;
}
# Capitalize user ID
$userId =~ tr/a-z/A-Z/;
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE sudoer:$::SUDOER zHCP:$hcp sudo:$::SUDO userid:$::userId");
}
my $out;
my $requestId = "NoUpstreamRequestID";
my $objectId = "NoUpstreamObjectID";
my $projectName = "NoUpstreamProjectName";
my $userUuid = "NoUpstreamUserUuid";
if ($args) {
@ARGV = @$args;
xCAT::zvmUtils->printSyslog(
"$ROUTINE $SUBROUTINE for node:$node on zhcp:$hcp args @$args");
# Parse options
GetOptions(
'requestid=s' => \$requestId # Optional
, 'objectid=s' => \$objectId # Optional
);
}
my $xcatnotify = "OPERATOR"; # Default value
my $xcatnotify_found = 0; # Not found yet
my (@array, $varname);
open( FILE, "<$NOTIFY_FILENAME" );
#TODO If file not found ("should never happen"), log error but continue
while (<FILE>) {
# Find record in file with NOTIFY=something on it, optionally delimited with whitespace
next unless ( /^[\s]*$NOTIFY_KEYWORD[\s]*$NOTIFY_KEYWORD_DELIMITER[\s]*(\S+)[\s]*$/i );
$xcatnotify_found = 1;
$xcatnotify = $1; # First parenthesized expression in regex above, that is: \S+
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE xCAT will notify $xcatnotify.");
}
last; # Ignore anything past the first matching record. Absent a bug elsewhere, there is only one value to find.
}
close(FILE);
if (not $xcatnotify_found) {
xCAT::zvmUtils->printSyslog(
"$ROUTINE $SUBROUTINE error: failed to parse $NOTIFY_KEYWORD$NOTIFY_KEYWORD_DELIMITER " .
"from $NOTIFY_FILENAME, defaulting to notify $xcatnotify");
}
#TODO add COZ... message ID
my $msg = "vmcp MSG $xcatnotify deployment failed: node $node userid $userId on zHCP $hcp";
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE $msg");
system($msg);
#TODO check system()'s rc
#TODO Capture diagnostic files
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE ... rest of implementation stubbed out ");
if ( $DEBUGGING == 1 ) {
xCAT::zvmUtils->printSyslog("$ROUTINE $SUBROUTINE exit");
}
return;
}

File diff suppressed because it is too large Load Diff

View File

@ -4,7 +4,7 @@ install
url --url replace_url
key --skip
lang en_US.UTF-8
network --bootproto dhcp
network --bootproto=static --ip=replace_ip --netmask=replace_netmask --gateway=replace_gateway --nameserver=replace_nameserver --hostname=replace_hostname
rootpw replace_rootpw
firewall --disabled
authconfig --enableshadow --enablemd5
@ -18,7 +18,7 @@ key --skip
# here so unless you clear all partitions first, this is
# not guaranteed to work
zerombr yes
clearpart --initlabel --drives=dasda
clearpart --all --initlabel --drives=dasda
part / --fstype ext3 --size=100 --grow --ondisk=dasda
part swap --size=512 --ondisk=dasda

View File

@ -4,7 +4,7 @@ install
url --url replace_url
key --skip
lang en_US.UTF-8
network --bootproto dhcp
network --bootproto=static --ip=replace_ip --netmask=replace_netmask --gateway=replace_gateway --nameserver=replace_nameserver --hostname=replace_hostname
rootpw replace_rootpw
firewall --disabled
authconfig --enableshadow --enablemd5
@ -18,7 +18,7 @@ key --skip
# here so unless you clear all partitions first, this is
# not guaranteed to work
zerombr
clearpart --initlabel --drives=dasda
clearpart --all --initlabel --drives=dasda
part / --fstype ext3 --size=100 --grow --ondisk=dasda
part swap --size=512 --ondisk=dasda

View File

@ -4,7 +4,7 @@ install
url --url replace_url
key --skip
lang en_US.UTF-8
network --bootproto dhcp
network --bootproto=static --ip=replace_ip --netmask=replace_netmask --gateway=replace_gateway --nameserver=replace_nameserver --hostname=replace_hostname
rootpw replace_rootpw
firewall --disabled
authconfig --enableshadow --enablemd5

View File

@ -4,7 +4,7 @@ install
url --url replace_url
key --skip
lang en_US.UTF-8
network --bootproto dhcp
network --bootproto=static --ip=replace_ip --netmask=replace_netmask --gateway=replace_gateway --nameserver=replace_nameserver --hostname=replace_hostname
rootpw replace_rootpw
firewall --disabled
authconfig --enableshadow --enablemd5

View File

@ -1,4 +1,3 @@
echo ARP=no >> /etc/sysconfig/network-scripts/ifcfg-eth0
# Get hostname
export HOSTNAME=$(host $IP 2>/dev/null | awk '{print $5}' | awk -F. '{print $1}')
@ -93,34 +92,26 @@ cd /xcatpost
export PATH=$PATH:/xcatpost
# Use the run_ps subroutine to run the postscripts
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps postscript \1/;s/run_ps postscript\s*#/#/;s/run_ps postscript\s*$//" /xcatpost/mypostscript`
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /xcatpost/mypostscript`
echo "
# Subroutine used to run postscripts
# \$1 argument is the script type
# rest argument is the script name and arguments
run_ps () {
logdir=\"/var/log/xcat\"
mkdir -p \$logdir
logfile=\"/var/log/xcat/xcat.log\"
scriptype=\$1
shift;
if [ -z \"\$scriptype\" ]; then
scriptype=\"postscript\"
fi
if [ -f \$1 ]; then
echo \"Running \$scriptype: \$1\" | tee -a \$logfile
./\$@ 2>&1 | tee -a \$logfile
echo \"Running postscript: \$@\" | tee -a \$logfile
./\$@ 2>&1 | tee -a $logfile
else
echo \"\$scriptype \$1 does NOT exist.\" | tee -a \$logfile
echo \"Postscript \$1 does NOT exist.\" | tee -a \$logfile
fi
}
# Subroutine end
" > /xcatpost/mypostscript
echo "$TMP" >> /xcatpost/mypostscript
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps postbootscript \1/;s/run_ps postbootscript\s*#/#/;s/run_ps postbootscript\s*$//" /xcatpost/mypostscript`
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /xcatpost/mypostscript`
echo "$TMP" > /xcatpost/mypostscript

View File

@ -1,4 +1,3 @@
echo ARP=no >> /etc/sysconfig/network-scripts/ifcfg-eth0
# Get hostname
export HOSTNAME=$(host $IP 2>/dev/null | awk '{print $5}' | awk -F. '{print $1}')
@ -92,34 +91,26 @@ cd /xcatpost
export PATH=$PATH:/xcatpost
# Use the run_ps subroutine to run the postscripts
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps postscript \1/;s/run_ps postscript\s*#/#/;s/run_ps postscript\s*$//" /xcatpost/mypostscript`
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /xcatpost/mypostscript`
echo "
# Subroutine used to run postscripts
# \$1 argument is the script type
# rest argument is the script name and arguments
run_ps () {
logdir=\"/var/log/xcat\"
mkdir -p \$logdir
logfile=\"/var/log/xcat/xcat.log\"
scriptype=\$1
shift;
if [ -z \"\$scriptype\" ]; then
scriptype=\"postscript\"
fi
if [ -f \$1 ]; then
echo \"Running \$scriptype: \$1\" | tee -a \$logfile
./\$@ 2>&1 | tee -a \$logfile
echo \"Running postscript: \$@\" | tee -a \$logfile
./\$@ 2>&1 | tee -a $logfile
else
echo \"\$scriptype \$1 does NOT exist.\" | tee -a \$logfile
echo \"Postscript \$1 does NOT exist.\" | tee -a \$logfile
fi
}
# Subroutine end
" > /xcatpost/mypostscript
echo "$TMP" >> /xcatpost/mypostscript
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps postbootscript \1/;s/run_ps postbootscript\s*#/#/;s/run_ps postbootscript\s*$//" /xcatpost/mypostscript`
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /xcatpost/mypostscript`
echo "$TMP" > /xcatpost/mypostscript

View File

@ -100,28 +100,20 @@ PATH=$PATH:/xcatpost
export PATH
# use the run_ps subroutine to run the postscripts
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps postscript \1/;s/run_ps postscript\s*#/#/;s/run_ps postscript\s*$//" /tmp/mypostscript`
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /tmp/mypostscript`
echo "
# subroutine used to run postscripts
# \$1 argument is the script type
# rest argument is the script name and arguments
run_ps () {
logdir=\"/var/log/xcat\"
mkdir -p \$logdir
logfile=\"/var/log/xcat/xcat.log\"
scriptype=\$1
shift;
if [ -z \"\$scriptype\" ]; then
scriptype=\"postscript\"
fi
if [ -f \$1 ]; then
echo \"Running \$scriptype: \$1\" | tee -a \$logfile
echo \"Running postscript: \$@\" | tee -a \$logfile
./\$@ 2>&1 1> /tmp/tmp4xcatlog
cat /tmp/tmp4xcatlog | tee -a \$logfile
else
echo \"\$scriptype \$1 does NOT exist.\" | tee -a \$logfile
echo \"Postscript \$1 does NOT exist.\" | tee -a \$logfile
fi
}
# subroutine end
@ -129,7 +121,7 @@ run_ps () {
" > /tmp/mypostscript
echo "cd /xcatpost" >> /tmp/mypostscript
echo "$TMP" >> /tmp/mypostscript
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps postbootscript \1/;s/run_ps postbootscript\s*#/#/;s/run_ps postbootscript\s*$//" /tmp/mypostscript`
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /tmp/mypostscript`
echo "$TMP" > /tmp/mypostscript

View File

@ -101,28 +101,20 @@ PATH=$PATH:/xcatpost
export PATH
# use the run_ps subroutine to run the postscripts
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps postscript \1/;s/run_ps postscript\s*#/#/;s/run_ps postscript\s*$//" /tmp/mypostscript`
TMP=`sed "/postscripts-start-here/,/postscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /tmp/mypostscript`
echo "
# subroutine used to run postscripts
# \$1 argument is the script type
# rest argument is the script name and arguments
run_ps () {
logdir=\"/var/log/xcat\"
mkdir -p \$logdir
logfile=\"/var/log/xcat/xcat.log\"
scriptype=\$1
shift;
if [ -z \"\$scriptype\" ]; then
scriptype=\"postscript\"
fi
if [ -f \$1 ]; then
echo \"Running \$scriptype: \$1\" | tee -a \$logfile
echo \"Running postscript: \$@\" | tee -a \$logfile
./\$@ 2>&1 1> /tmp/tmp4xcatlog
cat /tmp/tmp4xcatlog | tee -a \$logfile
else
echo \"\$scriptype \$1 does NOT exist.\" | tee -a \$logfile
echo \"Postscript \$1 does NOT exist.\" | tee -a \$logfile
fi
}
# subroutine end
@ -130,7 +122,7 @@ run_ps () {
" > /tmp/mypostscript
echo "cd /xcatpost" >> /tmp/mypostscript
echo "$TMP" >> /tmp/mypostscript
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps postbootscript \1/;s/run_ps postbootscript\s*#/#/;s/run_ps postbootscript\s*$//" /tmp/mypostscript`
TMP=`sed "/postbootscripts-start-here/,/postbootscripts-end-here/ s/\(.*\)/run_ps \1/;s/run_ps\s*#/#/;s/run_ps\s*$//" /tmp/mypostscript`
echo "$TMP" > /tmp/mypostscript

View File

@ -284,8 +284,7 @@
<dhclient_hostname_option>AUTO</dhclient_hostname_option>
</dhcp_options>
<dns>
<dhcp_hostname config:type="boolean">true</dhcp_hostname>
<dhcp_resolv config:type="boolean">true</dhcp_resolv>
<dhcp_hostname config:type="boolean">false</dhcp_hostname>
<domain>replace_domain</domain>
<hostname>replace_hostname</hostname>
<nameservers config:type="list">
@ -294,11 +293,14 @@
</dns>
<interfaces config:type="list">
<interface>
<bootproto>dhcp</bootproto>
<bootproto>static</bootproto>
<broadcast>replace_broadcast</broadcast>
<device>replace_device</device>
<ipaddr>replace_ipaddr</ipaddr>
<lladdr>replace_lladdr</lladdr>
<netmask>replace_netmask</netmask>
<network>replace_network</network>
<startmode>auto</startmode>
<usercontrol>no</usercontrol>
</interface>
</interfaces>
<managed config:type="boolean">false</managed>

View File

@ -284,8 +284,7 @@
<dhclient_hostname_option>AUTO</dhclient_hostname_option>
</dhcp_options>
<dns>
<dhcp_hostname config:type="boolean">true</dhcp_hostname>
<dhcp_resolv config:type="boolean">true</dhcp_resolv>
<dhcp_hostname config:type="boolean">false</dhcp_hostname>
<domain>replace_domain</domain>
<hostname>replace_hostname</hostname>
<nameservers config:type="list">
@ -294,11 +293,14 @@
</dns>
<interfaces config:type="list">
<interface>
<bootproto>dhcp</bootproto>
<bootproto>static</bootproto>
<broadcast>replace_broadcast</broadcast>
<device>replace_device</device>
<ipaddr>replace_ipaddr</ipaddr>
<lladdr>replace_lladdr</lladdr>
<netmask>replace_netmask</netmask>
<network>replace_network</network>
<startmode>auto</startmode>
<usercontrol>no</usercontrol>
</interface>
</interfaces>
<managed config:type="boolean">false</managed>

View File

@ -238,7 +238,7 @@
<dhclient_hostname_option>AUTO</dhclient_hostname_option>
</dhcp_options>
<dns>
<dhcp_hostname config:type="boolean">true</dhcp_hostname>
<dhcp_hostname config:type="boolean">false</dhcp_hostname>
<dhcp_resolv config:type="boolean">true</dhcp_resolv>
<domain>replace_domain</domain>
<hostname>replace_hostname</hostname>
@ -248,11 +248,14 @@
</dns>
<interfaces config:type="list">
<interface>
<bootproto>dhcp</bootproto>
<bootproto>static</bootproto>
<broadcast>replace_broadcast</broadcast>
<device>replace_device</device>
<ipaddr>replace_ipaddr</ipaddr>
<lladdr>replace_lladdr</lladdr>
<netmask>replace_netmask</netmask>
<network>replace_network</network>
<startmode>auto</startmode>
<usercontrol>no</usercontrol>
</interface>
</interfaces>
<managed config:type="boolean">false</managed>

View File

@ -238,7 +238,7 @@
<dhclient_hostname_option>AUTO</dhclient_hostname_option>
</dhcp_options>
<dns>
<dhcp_hostname config:type="boolean">true</dhcp_hostname>
<dhcp_hostname config:type="boolean">false</dhcp_hostname>
<dhcp_resolv config:type="boolean">true</dhcp_resolv>
<domain>replace_domain</domain>
<hostname>replace_hostname</hostname>
@ -248,11 +248,14 @@
</dns>
<interfaces config:type="list">
<interface>
<bootproto>dhcp</bootproto>
<bootproto>static</bootproto>
<broadcast>replace_broadcast</broadcast>
<device>replace_device</device>
<ipaddr>replace_ipaddr</ipaddr>
<lladdr>replace_lladdr</lladdr>
<netmask>replace_netmask</netmask>
<network>replace_network</network>
<startmode>auto</startmode>
<usercontrol>no</usercontrol>
</interface>
</interfaces>
<managed config:type="boolean">false</managed>

View File

@ -15,6 +15,3 @@ rpm
rsync
udev
s390utils
tar
gzip
xz

View File

@ -14,6 +14,3 @@ rsync
rsyslog
udev
s390utils
tar
gzip
xz

View File

@ -0,0 +1,579 @@
#!/bin/bash
# IBM(c) 2013, 2015 EPL license http://www.eclipse.org/legal/epl-v10.html
###############################################################################
# This script is used to handle xCAT disk initialization and configuration(eg.
# attach/detach a SCSI volume, add an additional ephemeral disk when vm is in
# inactive status). It will be invoked and executed when vm start up.
###############################################################################
version=3.0
function getOsVersion {
# @Description:
# Returns the Linux distro version in an easy to parse format.
# @Input:
# None
# @Output:
# os - Variable set with OS and version information. For example:
# "rhel62" or "sles11sp2"
# @Code:
if [[ -e "/etc/os-release" ]]; then
os=`cat /etc/os-release | grep "^ID=" | sed \
-e 's/ID=//' \
-e 's/"//g'`
version=`cat /etc/os-release | grep "^VERSION_ID=" | sed \
-e 's/VERSION_ID=//' \
-e 's/"//g' \
-e 's/\.//'`
os=$os$version
#The /etc/SuSE-release file will be deprecated in sles11.4 and later release
elif [[ -e "/etc/SuSE-release" ]]; then
os='sles'
version=`cat /etc/SuSE-release | grep "VERSION =" | sed \
-e 's/^.*VERSION =//' \
-e 's/\s*$//' \
-e 's/.//' \
-e 's/[^0-9]*([0-9]+).*/$1/'`
os=$os$version
# Append service level
level=`echo "/etc/SuSE-release" | grep "LEVEL =" | sed \
-e 's/^.*LEVEL =//' \
-e 's/\s*$//' \
-e 's/.//' \
-e 's/[^0-9]*([0-9]+).*/$1/'`
os=$os'sp'$level
#The /etc/redhat-release file will be deprecated in rhel7 and later release
elif [[ -e "/etc/redhat-release" ]]; then
os='rhel'
version=`cat /etc/redhat-release | grep -i "Red Hat Enterprise Linux Server" | sed \
-e 's/[A-Za-z\/\.\(\)]//g' \
-e 's/^ *//g' \
-e 's/ *$//g' \
-e 's/\s.*$//'`
os=$os$version
fi
return
}
function onlineDevice {
# @Description:
# Brings a Linux device online.
# @Input:
# Device number, e.g. "0.0.000c"
# @Output:
# Return code indicates success or failure
# @Code:
device=$1
local funcName="onlineDevice"
rc=$(/sbin/chccwdev -e $device > /dev/null; echo $?)
if (( rc != 0 )); then
if [[ -e /sbin/cio_ignore ]]; then
rc=$(/sbin/cio_ignore -r 0.0.$device > /dev/null; echo $?)
which udevadm &> /dev/null && udevadm settle || udevsettle
fi
rc=$(/sbin/chccwdev -e $device > /dev/null; echo $?)
if (( rc != 0 )); then
echo "$funcName (Error) Could not activate the virtual device $device"
return 1
fi
fi
which udevadm &> /dev/null && udevadm settle || udevsettle
return 0
}
function setupDisk {
# @Description:
# Processes a disk file for the following functions:
# Create a file system node
# Remove a file system node
# Setup a SCSI volume
# Removes a SCSI volume
# Add a mdisk based ephemeral disk
# @Input:
# Disk handling parameters
# @Output:
# None
# @Code:
local funcName="setupDisk"
# Parse the parameter from parameter list
for parameter in $@; do
keyName=${parameter%\=*}
value=${parameter#*\=}
value=$(echo ${value} | sed -e 's/^ *//g')
newKey='xcat_'$keyName
eval $newKey=$value
done
# Remove the invokeScript.sh file after we have read it
rm -f invokeScript.sh
##########################################################################
# Handle creating a file system node
# Disk handler input parameters:
# action - "createfilesysnode"
# srcFile - location/name of the source file for the mknod command
# xcat_tgtFile - location/name of the target file for the mknod command
##########################################################################
if [[ $xcat_action == "createfilesysnode" ]]; then
echo "Creating a file system node, source: $xcat_srcFile, target: $xcat_tgtFile"
if [[ ! -n $xcat_srcFile ]]; then
echo "$funcName (Error) Source file for creating a file system node was not specified"
return
fi
if [[ ! -n $xcat_tgtFile ]]; then
echo "$funcName (Error) Target file for creating a file system node was not specified"
return
fi
if [[ -e $xcat_tgtFile ]]; then
echo "$funcName (Error) Target file for creating a file system node already exists"
return
fi
configFile='/etc/udev/rules.d/56-zfcp.rules'
# Create udev config file if not exist
if [[ ! -e $configFile ]]; then
touch $configFile
if [[ $os == rhel* ]]; then
echo "KERNEL==\"zfcp\", RUN+=\"/sbin/zfcpconf.sh\"" >> ${configFile}
echo "KERNEL==\"zfcp\", RUN+=\"/sbin/multipath -r\"" >> ${configFile}
fi
fi
tgtNode=$(echo ${xcat_tgtFile} | sed -e 's/^\/dev\///')
if [[ $os == sles* || $os == rhel* ]]; then
wwpn_lun=$(echo ${xcat_srcFile} | sed -e 's/^\/dev.*-zfcp-//')
wwpn=$(echo ${wwpn_lun} | sed -e 's/:0x.*//')
lun=$(echo ${wwpn_lun} | sed -e 's/^0x.*://')
else
wwpn_lun=$(echo ${xcat_srcFile} | sed -e 's/^\/dev.*-fc-//')
wwpn=$(echo ${wwpn_lun} | sed -e 's/-lun-.*//')
lun=$(echo ${wwpn_lun} | sed -e 's/^0x.*-lun-//')
fi
multipath=0
out=`echo $wwpn | grep ","`
if [[ -n "$out" ]]; then
multipath=1
fi
if [[ $os == sles* || $os == rhel* ]]; then
fcp=$(echo ${xcat_srcFile} | sed -e 's/^\/dev.*ccw-0.0.//' | sed -e 's/-zfcp-.*$//')
else
fcp=$(echo ${xcat_srcFile} | sed -e 's/^\/dev.*ccw-0.0.//' | sed -e 's/-fc-.*$//')
fi
oldIFS=$IFS
IFS=","
fcpList=($fcp)
for fcp in ${fcpList[@]}
do
if [[ $multipath == 1 ]]; then
# Find the name of the multipath device by arbitrary one path in the set
wwpnList=($wwpn)
for wwpn in ${wwpnList[@]}
do
if [[ ${wwpn:0:2} -ne "0x" ]]; then
wwpn="0x$wwpn"
fi
if [[ $os == sles* || $os == rhel* ]]; then
cur_wwpn_lun=${wwpn}:${lun}
srcFile=$(echo ${xcat_srcFile} | sed -e 's/-zfcp-.*//')"-zfcp-"$cur_wwpn_lun
srcFile=$(echo ${srcFile} | sed -e 's/ccw-.*-zfcp/ccw-0.0.'$fcp'-zfcp/')
else
cur_wwpn_lun=${wwpn}-lun-${lun}
srcFile=$(echo ${xcat_srcFile} | sed -e 's/-fc-.*//')"-fc-"$cur_wwpn_lun
srcFile=$(echo ${srcFile} | sed -e 's/ccw-.*-fc/ccw-0.0.'$fcp'-fc/')
fi
out=`/usr/bin/stat --printf=%n ${srcFile}`
if (( $? != 0 )); then
echo "$funcName (Error) Unable to stat the source file: $srcFile"
continue
fi
out=`/sbin/udevadm info --query=all --name=$srcFile | grep ID_SERIAL=`
devName=$(echo ${out} | sed -e 's/^E:\s//')
multipathUuid=$(echo $devName | sed -e 's/ID_SERIAL=//')
if [[ -n "$multipathUuid" ]]; then
break
fi
done
if [[ -z "$multipathUuid" ]]; then
echo "$funcName (Error) Building up multipath failed!"
return
fi
else
if [[ $os == sles* || $os == rhel* ]]; then
srcFile=$(echo ${xcat_srcFile} | sed -e 's/ccw-.*-zfcp/ccw-0.0.'$fcp'-zfcp/')
else
srcFile=$(echo ${xcat_srcFile} | sed -e 's/ccw-.*-zfcp/ccw-0.0.'$fcp'-fc/')
fi
out=`/usr/bin/stat --printf=%n ${srcFile}`
if (( $? != 0 )); then
echo "$funcName (Error) Unable to stat the source file: $xcat_srcFile"
return
fi
fi
done
IFS=$oldIFS
# Add the entry into udev config file
if [[ $multipath == 1 ]]; then
echo "KERNEL==\"dm*\", ENV{DM_UUID}==\"mpath-${multipathUuid}\", SYMLINK+=\"${tgtNode}\"" >> ${configFile}
udevadm control --reload
udevadm trigger --sysname-match=dm-*
else
echo "KERNEL==\"sd*\", ATTRS{wwpn}==\"${wwpn}\", ATTRS{fcp_lun}==\"${lun}\", SYMLINK+=\"${tgtNode}%n\"" >> ${configFile}
udevadm control --reload
udevadm trigger --sysname-match=sd*
fi
echo "$funcName successfully create the file system node ${xcat_tgtFile}"
##########################################################################
# Handle removing a file system node
# Disk file input parameters:
# action - "removefilesysnode"
# tgtFile - location/name of the target file for the mknod command
##########################################################################
elif [[ $xcat_action == "removefilesysnode" ]]; then
echo "Removing a file system node, target: $xcat_tgtFile"
if [[ ! -n $xcat_tgtFile ]]; then
echo "$funcName (Error) Target file for creating a file system node was not specified"
return
fi
configFile='/etc/udev/rules.d/56-zfcp.rules'
tgtNode=$(echo ${xcat_tgtFile} | sed -e 's/^\/dev\///')
sed -i -e /SYMLINK+=\"${tgtNode}%n\"/d ${configFile}
sed -i -e /SYMLINK+=\"${tgtNode}\"/d ${configFile}
udevadm control --reload
udevadm trigger --sysname-match=sd*
udevadm trigger --sysname-match=dm-*
echo "$funcName successfully remove the file system node ${xcat_tgtFile}"
##########################################################################
# Handle adding a SCSI volume
# Disk file input parameters:
# action - "addScsiVolume"
# fcpAddr - FCP device address
# wwpn - WWPN number
# lun - LUN number
##########################################################################
elif [[ $xcat_action == "addScsiVolume" ]]; then
echo "Adding a SCSI Volume, FCP addr: $xcat_fcpAddr, WWPN: $xcat_wwpn, LUN: $xcat_lun"
# Validate the input
if [[ ! -n $xcat_fcpAddr ]]; then
echo "$funcName (Error) FCP address was not specified"
return
fi
xcat_fcpAddr=`echo $xcat_fcpAddr | tr '[A-Z]' '[a-z]'`
if [[ ! -n $xcat_wwpn ]]; then
echo "$funcName (Error) WWPN was not specified"
return
fi
xcat_wwpn=`echo $xcat_wwpn | tr '[A-Z]' '[a-z]'`
if [[ ! -n $xcat_lun ]]; then
echo "$funcName (Error) LUN was not specified"
return
fi
xcat_lun=`echo $xcat_lun | tr '[A-Z]' '[a-z]'`
decimal_lun=$((16#${xcat_lun:0:4}))
# Online the device
oldIFS=$IFS
IFS=","
fcp_list=($xcat_fcpAddr)
for fcp in ${fcp_list[@]}
do
rc= onlineDevice $fcp
if (( rc != 0 )); then
return
fi
if [[ $os == sles12* ]]; then
out=`cat /boot/zipl/active_devices.txt | grep -i "0.0.$fcp"`
if [[ -z $out ]]; then
/sbin/zfcp_host_configure 0.0.$fcp 1
fi
elif [[ $os == sles11* ]]; then
/sbin/zfcp_host_configure 0.0.$fcp 1
elif [[ $os == ubuntu* ]]; then
/sbin/chzdev zfcp-host $fcp -e
fi
done
multipath=0
out=`echo $xcat_wwpn | grep ","`
if [[ -n "$out" ]]; then
multipath=1
fi
# Start multipathd service
if [[ $multipath == 1 ]]; then
if [[ $os == sles* ]]; then
insserv multipathd
elif [[ $os == rhel6* ]]; then
chkconfig multipathd on
else
systemctl enable multipathd
fi
modprobe dm-multipath
fi
for fcp in ${fcp_list[@]}
do
wwpn_list=($xcat_wwpn)
for wwpn in ${wwpn_list[@]}
do
# Set WWPN and LUN in sysfs
echo 0x$xcat_lun > /sys/bus/ccw/drivers/zfcp/0.0.$fcp/0x$wwpn/unit_add
# Set WWPN and LUN in configuration files
if [[ $os == sles* ]]; then
# SLES: /etc/udev/rules.d/51-zfcp*
/sbin/zfcp_disk_configure 0.0.$fcp $wwpn $xcat_lun 1
# Configure zFCP device to be persistent
touch /etc/udev/rules.d/51-zfcp-0.0.$fcp.rules
# Check if the file already contains the zFCP channel
out=`cat "/etc/udev/rules.d/51-zfcp-0.0.$fcp.rules" | egrep -i "ccw/0.0.$fcp]online"`
if [[ ! $out ]]; then
echo "ACTION==\"add\", SUBSYSTEM==\"ccw\", KERNEL==\"0.0.$fcp\", IMPORT{program}=\"collect 0.0.$fcp %k 0.0.$fcp zfcp\"" \
| tee -a /etc/udev/rules.d/51-zfcp-0.0.$fcp.rules
echo "ACTION==\"add\", SUBSYSTEM==\"drivers\", KERNEL==\"zfcp\", IMPORT{program}=\"collect 0.0.$fcp %k 0.0.$fcp zfcp\"" \
| tee -a /etc/udev/rules.d/51-zfcp-0.0.$fcp.rules
echo "ACTION==\"add\", ENV{COLLECT_0.0.$fcp}==\"0\", ATTR{[ccw/0.0.$fcp]online}=\"1\"" \
| tee -a /etc/udev/rules.d/51-zfcp-0.0.$fcp.rules
fi
echo "ACTION==\"add\", KERNEL==\"rport-*\", ATTR{port_name}==\"0x$wwpn\", SUBSYSTEMS==\"ccw\", KERNELS==\"0.0.$fcp\", ATTR{[ccw/0.0.$fcp]0x$wwpn/unit_add}=\"0x$xcat_lun\"" \
| tee -a /etc/udev/rules.d/51-zfcp-0.0.$fcp.rules
elif [[ $os == rhel* ]]; then
# RHEL: /etc/zfcp.conf
echo "0.0.$fcp 0x$wwpn 0x$xcat_lun" >> /etc/zfcp.conf
echo "add" > /sys/bus/ccw/devices/0.0.$fcp/uevent
elif [[ $os == ubuntu* ]]; then
# Ubuntu: chzdev zfcp-lun 0.0.$device:0x$wwpn:0x$lun -e
/sbin/chzdev zfcp-lun 0.0.$fcp:0x$wwpn:0x$xcat_lun -e
fi
# Settle the file system so when we are done the device is fully available
if [[ $(which udevadm 2> /dev/null) != '' ]]; then
udevadm settle
else
udevsettle
fi
if [[ $os == rhel* || $os == sles* ]]; then
if [[ ! -e "/dev/disk/by-path/ccw-0.0.${fcp}-zfcp-0x${wwpn}:0x${xcat_lun}" ]]; then
# Sometimes the file takes longer to appear. We will wait up to 3 minutes.
maxTime=0
for time in 1 2 2 5 10 10 30 60 60
do
if [[ -e "/dev/disk/by-path/ccw-0.0.${fcp}-zfcp-0x${wwpn}:0x${xcat_lun}" ]]; then
# Leave the loop now that the file exists
break
fi
maxTime=$maxTime+$time
echo "Sleeping for $time seconds to allow /dev/disk/by-path/ccw-0.0.${fcp}-zfcp-0x${wwpn}:0x${xcat_lun} to be created"
sleep $time
done
fi
if [[ ! -e "/dev/disk/by-path/ccw-0.0.${fcp}-zfcp-0x${wwpn}:0x${xcat_lun}" ]]; then
echo "/dev/disk/by-path/ccw-0.0.${fcp}-zfcp-0x${wwpn}:0x${xcat_lun} did not appear in $maxTime seconds, continuing."
fi
elif [[ $os == ubuntu* ]]; then
if [[ ! -e "/dev/disk/by-path/ccw-0.0.${fcp}-fc-0x${wwpn}-lun-${decimal_lun}" ]]; then
# Sometimes the file takes longer to appear. We will wait up to 3 minutes.
maxTime=0
for time in 1 2 2 5 10 10 30 60 60
do
if [[ -e "/dev/disk/by-path/ccw-0.0.${fcp}-fc-0x${wwpn}-lun-${decimal_lun}" ]]; then
# Leave the loop now that the file exists
break
fi
maxTime=$maxTime+$time
echo "Sleeping for $time seconds to allow /dev/disk/by-path/ccw-0.0.${fcp}-fc-0x${wwpn}-lun-${decimal_lun} to be created"
sleep $time
done
fi
if [[ ! -e "/dev/disk/by-path/ccw-0.0.${fcp}-fc-0x${wwpn}-lun-${decimal_lun}" ]]; then
echo "/dev/disk/by-path/ccw-0.0.${fcp}-fc-0x${wwpn}-lun-${decimal_lun} did not appear in $maxTime seconds, continuing."
fi
fi
done
done
IFS=$oldIFS
/sbin/multipath -r
echo "$funcName successfully create the SCSI volume"
##########################################################################
# Handle removing a SCSI volume
# Disk file input parameters:
# action - "removeScsiVolume"
# fcpAddr - FCP device address
# wwpn - WWPN number
# lun - LUN number
##########################################################################
elif [[ $xcat_action == "removeScsiVolume" ]]; then
echo "Removing a SCSI Volume, FCP addr: $xcat_fcpAddr, WWPN: $xcat_wwpn, LUN: $xcat_lun"
# Validate the input
if [[ ! -n $xcat_fcpAddr ]]; then
echo "$funcName (Error) FCP address was not specified"
return
fi
xcat_fcpAddr=`echo $xcat_fcpAddr | tr '[A-Z]' '[a-z]'`
if [[ ! -n $xcat_wwpn ]]; then
echo "$funcName (Error) WWPN was not specified"
return
fi
xcat_wwpn=`echo $xcat_wwpn | tr '[A-Z]' '[a-z]'`
if [[ ! -n $xcat_lun ]]; then
echo "$funcName (Error) LUN was not specified"
return
fi
xcat_lun=`echo $xcat_lun | tr '[A-Z]' '[a-z]'`
oldIFS=$IFS
IFS=","
fcp_list=($xcat_fcpAddr)
for fcp in ${fcp_list[@]}
do
wwpn_list=($xcat_wwpn)
for wwpn in ${wwpn_list[@]}
do
# Delete the SCSI device
scsiDevice=`lszfcp -l 0x$xcat_lun | grep 0x$wwpn | cut -d " " -f2`
if [[ -n $scsiDevice ]]; then
echo 1 > "/sys/bus/scsi/devices/$scsiDevice/delete"
fi
# Delete WWPN and LUN from sysfs
if [[ -e /sys/bus/ccw/drivers/zfcp/0.0.$fcp/0x$wwpn/unit_remove ]]; then
if [[ $(which udevadm 2> /dev/null) != '' ]]; then
udevadm settle
else
udevsettle
fi
echo 0x$xcat_lun > /sys/bus/ccw/drivers/zfcp/0.0.$fcp/0x$wwpn/unit_remove
fi
# Delete WWPN and LUN from configuration files
if [[ $os == sles11* || $os == sles12* ]]; then
# SLES: /etc/udev/rules.d/51-zfcp*
expression="/$xcat_lun/d"
sed --in-place -e $expression /etc/udev/rules.d/51-zfcp-0.0.$fcp.rules
elif [[ $os == rhel* ]]; then
# RHEL: /etc/zfcp.conf
expression="/$xcat_lun/d"
sed --in-place -e $expression /etc/zfcp.conf
elif [[ $os == ubuntu* ]]; then
# Ubuntu: chzdev zfcp-lun 0.0.$device:0x$wwpn:0x$lun -d
/sbin/chzdev zfcp-lun 0.0.$fcp:0x$wwpn:0x$xcat_lun -d
fi
done
done
IFS=$oldIFS
/sbin/multipath -W
/sbin/multipath -r
echo "$funcName successfully remove the SCSI volume"
###########################################################################
# Handle adding a mdisk based ephemeral disk.
# Disk file input parameters:
# action - "addMdisk"
# vaddr - virtual address of the minidisk
# filesys - Filesystem type
# mntdir - The directory that mount the mdisk to
##########################################################################
elif [[ $xcat_action == "addMdisk" ]]; then
echo "Adding a minidisk based ephemeral disk, Vaddr: $xcat_vaddr, Filesystem: $xcat_filesys mountpoint:$xcat_mntdir"
# Validate the input
if [[ ! -n $xcat_vaddr ]]; then
echo "$funcName (Error) Virtual address was not specified"
return
fi
xcat_vaddr=`echo $xcat_vaddr | tr '[A-Z]' '[a-z]'`
# Online the device
rc= onlineDevice $xcat_vaddr
if (( rc != 0 )); then
echo "$funcName (Error) fail to online the disk $xcat_vaddr"
return
fi
# Configure the added dasd to be persistent
echo "Permanently online the ephemeral disk"
if [[ $os == rhel* ]]; then
out=`cat "/etc/dasd.conf" | egrep -i $xcat_vaddr`
if [[ ! $out ]]; then
echo "0.0.$xcat_vaddr" >> /etc/dasd.conf
fi
elif [[ $os == sles* ]]; then
/sbin/dasd_configure 0.0.$xcat_vaddr 1
elif [[ $os == ubuntu16* ]]; then
touch /etc/sysconfig/hardware/config-ccw-0.0.$xcat_vaddr
else
echo "$funcName (Error) failed to permanently online the disk:$xcat_vaddr on os: $os, please check if $os is in the supported distribution list"
return
fi
# Mount the mdisk to the specified mount point
echo "Mounting the ephemeral disk $xcat_vaddr to directory $xcat_mntdir"
if [[ -d $xcat_mntdir ]]; then
rm -rf $xcat_mntdir
fi
mkdir -p $xcat_mntdir
cp /etc/fstab /etc/fstab.bak
out=`cat "/etc/fstab" | egrep -i "ccw-0.0.$xcat_vaddr"`
if [[ $out ]]; then
sed -i '/ccw-0.0.'"$xcat_vaddr"'/d' /etc/fstab
fi
if [[ $os == sles12* ]]; then
echo "/dev/disk/by-path/ccw-0.0.${xcat_vaddr}-part1 $xcat_mntdir $xcat_filesys defaults,nofail 0 0" >> /etc/fstab
else
echo "/dev/disk/by-path/ccw-0.0.${xcat_vaddr}-part1 $xcat_mntdir $xcat_filesys defaults 0 0" >> /etc/fstab
fi
out=`mount -a 2>&1`
if [[ "$out" ]]; then
echo "Fail to mount the disk $xcat_vaddr with reason $out"
mv /etc/fstab.bak /etc/fstab
mount -a
else
echo "The disk $xcat_vaddr has been mounted to $xcat_mntdir in format $xcat_filesys successfully"
fi
fi
return
}
############################################################################
# Main Code Section
############################################################################
# Get Linux version
getOsVersion
setupDisk $@
rm -f setupDisk

View File

@ -1,4 +1,5 @@
#!/bin/sh
#!/bin/bash
# IBM(c) 2013, 2015 EPL license http://www.eclipse.org/legal/epl-v10.html
### BEGIN INIT INFO
# Provides: xcatconf4z
@ -7,10 +8,11 @@
# Required-Start: $syslog
# Should-Start:
# Required-Stop:
# Short-Description: xCAT disk initialization and configuration
# Short-Description: A basic active engine used to initialize and configure vm.
# Description: Reads class x files from the reader and acts based on the type of file.
# Files of filetype "disk" cause SCSI disks be configured.
# Other files are used to generate an ISO9660 disk for transporting xCAT configurations.
# Generate an ISO9660 disk for cloud-init to handle openstack configurations.
# Files of filetype "disk" cause disks be configured. (deprecated)
# Other files are used to configure vm when it start up.
### END INIT INFO
###############################################################################
@ -20,6 +22,7 @@
# If nothing is specified then this function will not process any
# configuration files in the reader.
###############################################################################
version=3.0
authorizedSenders=''
function getOsVersion {
@ -80,7 +83,7 @@ function onlineDevice {
fi
rc=$(/sbin/chccwdev -e $device > /dev/null; echo $?)
if (( rc != 0 )); then
echo "xcatconf4z $funcName (Error) Could not activate the virtual reader"
echo "xcatconf4z $funcName (Error) Could not activate the virtual device $device"
return 1
fi
fi
@ -94,7 +97,8 @@ function pullReader {
# Drives special processing functions for files of a specific type.
# Files with a filetype of:
# tgz are unpacked into the transport directory
# disk files are read and cause the setupDisk function to be driven
# disk files are read and cause the setupDisk function to be driven (deprecated)
# doscript that contains a invokeScript.sh which will call the other script in it to do the speicial work
# all other files are unpacked into the transport directory
# @Input:
# None
@ -145,14 +149,26 @@ function pullReader {
# Receive the spool file
echo "Downloading record $spoolid: $file"
if [[ $type == "txt" ]] || [[ $type == "sh" ]]; then
if [[ $type == "txt" ]]; then
# Receiving text
rc=$(/usr/sbin/vmur re -t $spoolid $file)
rc=$(/usr/sbin/vmur re -f $spoolid $file)
elif [[ $type == "sh" ]]; then
# Receiving shell
rc=$(/usr/sbin/vmur re -f $spoolid $file)
/bin/bash $file
rm $file
elif [[ $type == "tgz" ]]; then
rc=$(/usr/sbin/vmur re $spoolid $file)
/bin/tar xzf $file -C $transportdir
rm $file
injectFiles
elif [[ $type == "doscript" ]]; then
rc=$(/usr/sbin/vmur re $spoolid $file)
/bin/tar xf $file -C $transportdir
rm $file
/bin/bash invokeScript.sh
elif [[ $type == "disk" ]]; then
echo 'disk file encountered and will be handled by the deprecated setupDisk function'
rc=$(/usr/sbin/vmur re $spoolid $file)
if (( rc == 0 )); then
setupDisk $transportdir'/'$file
@ -180,11 +196,15 @@ function setupIso {
# @Output:
# None
# @Code:
local funcName="setupIso"
iso="/var/opt/xcat/transport.iso"
# If there are files in the transport directory then create an ISO system.
if [ "$(ls -A .)" ]; then
/usr/bin/mkisofs -l -o $iso $transportdir
/usr/bin/mkisofs -l -V 'config-2' -o $iso $transportdir
if [ -e /tmp/znetconfig.sh ]; then
/bin/bash /tmp/znetconfig.sh
fi
fi
# If the ISO filesystem exists then create loop back device pointing
@ -350,7 +370,7 @@ function setupDisk {
/sbin/zfcp_host_configure 0.0.$xcat_fcpAddr 1
/sbin/zfcp_disk_configure 0.0.$xcat_fcpAddr $xcat_wwpn $xcat_lun 1
echo "0x$xcat_wwpn:0x$xcat_lun" >> /etc/sysconfig/hardware/hwcfg-zfcp-bus-ccw-0.0.$xcat_fcpAddr
elif [[ $os == sles* ]]; then
elif [[ $os == sles11* ]]; then
/sbin/zfcp_host_configure 0.0.$xcat_fcpAddr 1
/sbin/zfcp_disk_configure 0.0.$xcat_fcpAddr $xcat_wwpn $xcat_lun 1
@ -455,18 +475,115 @@ function setupDisk {
if [[ $os == sles10* ]]; then
expression="/$xcat_lun/d"
sed --in-place -e $expression /etc/sysconfig/hardware/hwcfg-zfcp-bus-ccw-0.0.$xcat_fcpAddr
elif [[ $os == sles* ]]; then
elif [[ $os == sles11* ]]; then
expression="/$xcat_lun/d"
sed --in-place -e $expression /etc/udev/rules.d/51-zfcp-0.0.$xcat_fcpAddr.rules
elif [[ $os == rhel* ]]; then
expression="/$xcat_lun/d"
sed --in-place -e $expression /etc/zfcp.conf
fi
fi
###########################################################################
# Handle adding a mdisk based ephemeral disk.
# Disk file input parameters:
# action - "addMdisk"
# vaddr - virtual address of the minidisk
# filesys - Filesystem type
# mntdir - The directory that mount the mdisk to
##########################################################################
elif [[ $xcat_action == "addMdisk" ]]; then
echo "Adding a minidisk based ephemeral disk, Vaddr: $xcat_vaddr, Filesystem: $xcat_filesys mountpoint:$xcat_mntdir"
# Validate the input
if [[ ! -n $xcat_vaddr ]]; then
echo "xcatconf4z $funcName (Error) Virtual address was not specified"
return
fi
xcat_vaddr=`echo $xcat_vaddr | tr '[A-Z]' '[a-z]'`
# Online the device
rc= onlineDevice $xcat_vaddr
if (( rc != 0 )); then
echo "xcatconf4z $funcName (Error) fail to online the disk $xcat_vaddr"
return
fi
# Configure the added dasd to be persistent
echo "Permenently online the ephemeral disk"
if [[ $os == rhel* ]]; then
out=`cat "/etc/dasd.conf" | egrep -i $xcat_vaddr`
if [[ ! $out ]]; then
echo "0.0.$xcat_vaddr" >> /etc/dasd.conf
fi
else
/sbin/dasd_configure 0.0.$xcat_vaddr 1
fi
# Mount the mdisk to the specified mount point
echo "Mounting the ephemeral disk $xcat_vaddr to directory $xcat_mntdir"
if [[ -d $xcat_mntdir ]]; then
rm -rf $xcat_mntdir
fi
mkdir -p $xcat_mntdir
cp /etc/fstab /etc/fstab.bak
out=`cat "/etc/fstab" | egrep -i "ccw-0.0.$xcat_vaddr"`
if [[ $out ]]; then
sed -i '/ccw-0.0.'"$xcat_vaddr"'/d' /etc/fstab
fi
echo "/dev/disk/by-path/ccw-0.0.${xcat_vaddr}-part1 $xcat_mntdir $xcat_filesys defaults 0 0" >> /etc/fstab
out=`mount -a 2>&1`
if [[ "$out" ]]; then
echo "Fail to mount the disk $xcat_vaddr with reason $out"
mv /etc/fstab.bak /etc/fstab
mount -a
else
echo "The disk $xcat_vaddr has been mounted to $xcat_mntdir in format $xcat_filesys successfully"
fi
fi
return
}
function injectFiles {
# @Description:
# Inject network files and scripts
# @Input:
# None
# @Output:
# None
# @Code:
local funcName="injectFiles"
if [[ ! -e $transportdir/openstack/latest/meta_data.json ]]; then
echo "Can not inject files, because no meta_data.json"
return
fi
echo "File injecting ...."
awk '{
#get inject files info
split($0 ,res1,/"files": \[/)
split(res1[2], res2, /\]/)
n=split(res2[1], res, /}, /)
for(m=1;m<=n;m++)
{
split(res[m], temp1, /{"path": "/)
k=split(temp1[2], temp2, /", "content_path": "/)
sub(/"}*$/, "", temp2[2])
#print temp2[1] " : " temp2[2]
des = dir "/openstack" temp2[2]
cmd = "cp " des " " temp2[1]
#print cmd
system(cmd)
}
}' dir=$transportdir <$transportdir/openstack/latest/meta_data.json
return
}
############################################################################
# Main Code Section
############################################################################
@ -483,13 +600,27 @@ case "$1" in
if [[ -n "$authorizedSenders" ]]; then
pullReader
echo "xcatconf4z has successfully processed the reader files."
else
echo "xcatconf4z is disabled from accepting configuration reader files."
fi
setupIso
;;
stop|status|restart|reload|force-reload)
;;
status)
if [[ -n "$authorizedSenders" ]]; then
echo "xcatconf4z is enabled to accept configuration reader files from: $authorizedSenders"
else
echo "xcatconf4z is disabled from accepting configuration reader files."
fi
;;
version)
echo "xcatconf4z version:" $version
;;
stop|restart|reload|force-reload)
# Do nothing
;;
esac

View File

@ -0,0 +1,14 @@
[Unit]
Description=Activation engine for configuring vm when it start up
Wants=local-fs.target NetworkManager.service
After=local-fs.target
Before=NetworkManager.service cloud-init-local.service
[Service]
Type=oneshot
ExecStart=/usr/bin/xcatconf4z start
StandardOutput=journal+console
[Install]
WantedBy=multi-user.target

View File

@ -0,0 +1,13 @@
z/VM Toolkit
The list of resources related:
Files:
prep_zxcatIVP_*.pl
The prep_zxcatIVP_*.pl files are provided for each supported OpenStack release
that interacts with xCAT. These scripts end contain the name of the OpenStack
release that they support. The scripts scan the OpenStack configuration files
and produce a driver script which is used to validate the installation of the
OpenStack code with xCAT. For more information on the scripts, invoke the
help function for the individual script (operand --help).

View File

@ -0,0 +1,938 @@
#!/usr/bin/perl
###############################################################################
# (c) Copyright International Business Machines Corporation 2014.
# All Rights Reserved.
###############################################################################
# COMPONENT: prep_zxcatIVP_HAVANA.pl
#
# This is a preparation script for Installation Verification Program for xCAT
# on z/VM. It prepares the driver script by gathering information from
# OpenStack configuration files on the compute node.
###############################################################################
use strict;
#use warnings;
use Getopt::Long;
use Sys::Hostname;
use Socket;
my %cinderConf;
my %novaConf;
my %neutronConf;
my %ovsNeutronPluginIni;
my %neutronZvmPluginIni;
my $version = "1.1";
my $supportString = "Supports code based on the OpenStack Havana release.";
my $driver; # Name of driver file to be created less the ".pl"
my $driverLocation = "/opt/xcat/bin/"; # Location of the IVP program in xCAT MN.
my $driverPrefix = "zxcatIVPDriver_"; # Prefix used in naming the driver program.
my $displayHelp = 0; # Display help information.
my $ivp = "zxcatIVP.pl"; # z/VM xCAT IVP script name
my $obfuscatePw; # Obfuscate the PW in the driver file that is built
my $scan; # Type of scan to be performed
my $verbose; # Verbose flag - 0: quiet, 1: verbose
my $versionOpt = 0; # Shov version information.
my $localIpAddress; # Local IP address of system where we are prepping
# set the usage message
my $usage_string = "Usage:\n
$0\n
or\n
$0 -s serviceToScan -d driverProgramName\n
or\n
$0 --scan serviceToScan -driver driverProgramName\n
-s | --scan Services to scan ('all', 'nova' or 'neutron').\n
-d | --driver Name of driver program to construct.\n
--help Display help information.\n
-v Display script version information.\n
-V Display the verbose message\n";
#-------------------------------------------------------
=head3 buildDriverProgram
Description : Build or update the driver program with the
data obtained by the scans.
Arguments : None
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = buildDriverProgram();
=cut
#-------------------------------------------------------
sub buildDriverProgram{
my $rc;
my @driverText;
if ( $verbose ) {
print "Building the IVP driver program.\n";
}
# Erase any existing driver program.
if ( -e $driver and ! -z $driver ) {
# Make certain the file is one of our driver files.
my $found = `grep 'Function: z/VM xCAT IVP driver program' $driver`;
if ( ! $found ) {
print "$driver is not a z/VM xCAT IVP driver program\n";
print "File will not be changed.\n";
return 251;
} else {
# Rename the existing driver file.
print "Existing driver file is being saved as $driver.old\n";
rename $driver,"$driver.old";
}
}
# Open the driver program for output.
$rc = open( my $fileHandle, '>', $driver ) or die;
if ( $rc != 1 ) {
print "Unable to open $driver for output: $!\n";
return ( 200 + $rc );
}
# Construct the file in an array.
push( @driverText, "#!/bin/bash" );
push( @driverText, "# IBM(c) 2014 EPL license http://www.eclipse.org/legal/epl-v10.html" );
push( @driverText, "" );
push( @driverText, "# Function: z/VM xCAT IVP driver program" );
push( @driverText, "# Built by $0 version $version." );
push( @driverText, "# $supportString" );
push( @driverText, "" );
push( @driverText, "############## Start of Nova Config Properties" );
if ( exists $novaConf{'DEFAULT'}{'my_ip'} ) {
push( @driverText, "" );
push( @driverText, "# IP address or hostname of the compute node that is accessing this xCAT MN." );
push( @driverText, "# From \'my_ip\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_cNAddress=\"$novaConf{'DEFAULT'}{'my_ip'}\"" );
} else {
push( @driverText, "" );
push( @driverText, "# IP address or hostname of the compute node that is accessing this xCAT MN." );
push( @driverText, "# From the local IP address of this system." );
push( @driverText, "export zxcatIVP_cNAddress=\"$localIpAddress\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_user_profile'} ) {
push( @driverText, "" );
push( @driverText, "# Default profile used in creation of server instances." );
push( @driverText, "# From \'zvm_user_profile\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_defaultUserProfile=\"$novaConf{'DEFAULT'}{'zvm_user_profile'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_diskpool'} ) {
push( @driverText, "" );
push( @driverText, "# Array of disk pools that are expected to exist." );
push( @driverText, "# From \'zvm_diskpool\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_diskpools=\"$novaConf{'DEFAULT'}{'zvm_diskpool'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_fcp_list'} ) {
push( @driverText, "" );
push( @driverText, "# The list of FCPs used by instances." );
push( @driverText, "# From \'zvm_fcp_list\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_instFCPList=\"$novaConf{'DEFAULT'}{'zvm_fcp_list'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_host'} ) {
push( @driverText, "" );
push( @driverText, "# Node of host being managed. If blank, IVP will search for the host node." );
push( @driverText, "# From \'zvm_host\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_hostNode=\"$novaConf{'DEFAULT'}{'zvm_host'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_xcat_master'} ) {
push( @driverText, "" );
push( @driverText, "# Node name for xCAT MN (optional)." );
push( @driverText, "# From \'zvm_xcat_master\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_mnNode=\"$novaConf{'DEFAULT'}{'zvm_xcat_master'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_xcat_password'} ) {
push( @driverText, "" );
if ( $obfuscatePw ) {
# Obfuscate the password so that it is not easily read.
# Currently not used due to GUI restrictions that modify the obfuscated password.
push( @driverText, "# User password defined to communicate with xCAT MN. Note: Password is hidden." );
push( @driverText, "export zxcatIVP_pw_obfuscated=1" );
push( @driverText, "# From \'zvm_xcat_password\' in /etc/nova/nova.conf." );
my @chars = split( //, $novaConf{'DEFAULT'}{'zvm_xcat_password'} );
my @newChars;
foreach my $char ( @chars ) {
$char = ~$char;
push( @newChars, $char );
}
my $hiddenPw = join( "", @newChars );
push( @driverText, "export zxcatIVP_xcatUserPw=\"$hiddenPw\"" );
} else {
push( @driverText, "# User password defined to communicate with xCAT MN." );
push( @driverText, "# From \'zvm_xcat_password\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_xcatUserPw=\"$novaConf{'DEFAULT'}{'zvm_xcat_password'}\"" );
}
}
if ( exists $novaConf{'DEFAULT'}{'zvm_xcat_server'} ) {
push( @driverText, "" );
push( @driverText, "# Expected IP address of the xcat MN" );
push( @driverText, "# From \'zvm_xcat_server\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_xcatMNIp=\"$novaConf{'DEFAULT'}{'zvm_xcat_server'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_xcat_username'} ) {
push( @driverText, "" );
push( @driverText, "# User defined to communicate with xCAT MN" );
push( @driverText, "# From \'zvm_xcat_username\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_xcatUser=\"$novaConf{'DEFAULT'}{'zvm_xcat_username'}\"" );
}
if ( exists $novaConf{'DEFAULT'}{'zvm_zhcp_fcp_list'} ) {
push( @driverText, "" );
push( @driverText, "# The list of FCPs used by zHCP." );
push( @driverText, "# From \'zvm_zhcp_fcp_list\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_zhcpFCPList=\"$novaConf{'DEFAULT'}{'zvm_zhcp_fcp_list'}\"" );
}
push( @driverText, "" );
push( @driverText, "# Expected space available in the xCAT MN image repository" );
push( @driverText, "# From \'xcat_free_space_threshold\' in /etc/nova/nova.conf." );
push( @driverText, "export zxcatIVP_expectedReposSpace=\"$novaConf{'DEFAULT'}{'xcat_free_space_threshold'}G\"" );
push( @driverText, "" );
push( @driverText, "############## End of Nova Config Properties" );
push( @driverText, "" );
push( @driverText, "############## Start of Neutron Config Properties" );
if ( exists $neutronConf{'DEFAULT'}{'base_mac'} ) {
my $prefix = $neutronConf{'DEFAULT'}{'base_mac'};
$prefix =~ tr/://d;
$prefix = substr( $prefix, 0, 6 );
push( @driverText, "" );
push( @driverText, "# User prefix for MAC Addresses of Linux level 2 interfaces" );
push( @driverText, "# From \'base_mac\' in /etc/neutron/neutron.conf." );
push( @driverText, "export zxcatIVP_macPrefix=\"$prefix\"" );
}
if ( exists $neutronZvmPluginIni{'agent'}{'xcat_mgt_ip'} ) {
push( @driverText, "" );
push( @driverText, "# xCat MN's address on the xCAT management network" );
push( @driverText, "# From \'xcat_mgt_ip\' in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini." );
push( @driverText, "export zxcatIVP_xcatMgtIp=\"$neutronZvmPluginIni{'agent'}{'xcat_mgt_ip'}\"" );
}
if ( exists $neutronZvmPluginIni{'agent'}{'xcat_mgt_mask'} ) {
push( @driverText, "" );
push( @driverText, "# xCat management interface netmask" );
push( @driverText, "# From \'xcat_mgt_mask\' in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini." );
push( @driverText, "export zxcatIVP_mgtNetmask=\"$neutronZvmPluginIni{'agent'}{'xcat_mgt_mask'}\"" );
}
if ( exists $ovsNeutronPluginIni{'ovs'}{'network_vlan_ranges'} ) {
push( @driverText, "" );
push( @driverText, "# Array of networks and possible VLAN ranges" );
push( @driverText, "# From \'network_vlan_ranges\' in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini." );
push( @driverText, "export zxcatIVP_networks=\"$ovsNeutronPluginIni{'ovs'}{'network_vlan_ranges'}\"" );
}
if ( exists $neutronZvmPluginIni{'agent'}{'xcat_zhcp_nodename'} ) {
push( @driverText, "" );
push( @driverText, "# Node name for xCAT zHCP server" );
push( @driverText, "# From \'xcat_zhcp_nodename\' in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini." );
push( @driverText, "export zxcatIVP_zhcpNode=\"$neutronZvmPluginIni{'agent'}{'xcat_zhcp_nodename'}\"" );
}
# Create the zxcatIVP_vswitchOSAs variable for any networks specified with an rdev list.
my $vswitchOSAs = '';
foreach my $section (sort keys %neutronZvmPluginIni) {
next if ( $section eq 'agent');
foreach my $property ( keys %{ $neutronZvmPluginIni{$section} } ) {
next if ( $property ne "rdev_list" );
my $list = $neutronZvmPluginIni{$section}{$property};
$list =~ s/^\s+|\s+$//g; # trim blanks from both ends of the list
next if ( $list eq '' );
$list =~ s/\s+/\,/g; # insert comma between words
$vswitchOSAs = "$section $list $vswitchOSAs";
}
}
if ( defined $vswitchOSAs ) {
push( @driverText, "" );
push( @driverText, "# Vswitches and their related OSAs" );
push( @driverText, "# From \'rdev_list\' in vswitch sections of /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini." );
push( @driverText, "export zxcatIVP_vswitchOSAs=\"$vswitchOSAs\"" );
}
push( @driverText, "" );
push( @driverText, "############## End of Neutron Config Properties" );
push( @driverText, "" );
push( @driverText, "# Name of user under which nova runs, default is nova." );
push( @driverText, "# If you system is different then change this property." );
push( @driverText, "export zxcatIVP_expUser=\"nova\"" );
push( @driverText, "" );
push( @driverText, "# Controls whether Warnings/Errors detected by the IVP are" );
push( @driverText, "# logged in the xCAT MN syslog, 0: do not log, 1: log to syslog." );
push( @driverText, "export zxcatIVP_syslogErrors=1" );
push( @driverText, "" );
push( @driverText, "perl $driverLocation$ivp" );
# Write the array to the driver file.
foreach (@driverText) {
#print "$_\n";
print $fileHandle "$_\n"; # Print each entry in our array to the file
}
close $fileHandle;
print "$driver was built.\n";
}
#-------------------------------------------------------
=head3 hashFile
Description : Read a file with equal signs designating
key value pairs and create a hash from it.
Arguments : File to read
Reference to hash that should be constructed.
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = hashFile( $file, \%novaConf, 1 );
=cut
#-------------------------------------------------------
sub hashFile{
my ( $file, $hash, $required ) = @_;
my $section = "null";
my $caseInsensitive = 1; # assume section/properties are case insensitive
my @parts;
if ( !-e $file ) {
if ( $required ) {
print "Warning: $file does not exist.\n";
} else {
print "Info: $file does not exist.\n";
}
return 601;
}
if ( $file =~ /.conf$/ ) {
# File is case sensitive, translate sections and property names to uppercase.
$caseInsensitive = 0;
}
# Read the configuration file and construct the hash of values.
my $out = `egrep -v '(^#|^\\s*\\t*#)' $file`;
my @lines = split( "\n", $out );
foreach my $line ( @lines ) {
if ( $line =~ /^\[/ ) {
# Section header line
$line =~ s/^\s+|\s+$//g; # trim blanks from both ends of the line
$line =~ s/^\[+|\]+$//g; # trim [] from ends of the line
if ( $caseInsensitive ) {
$section = lc( $line );
} else {
$section = $line;
}
} else {
# Property line
@parts = split( "=", $line );
next if ( ! exists $parts[0] );
$parts[0] =~ s/^\s+|\s+$//g; # trim both ends of the string
next if ( length( $parts[0] ) == 0 );
if ( $caseInsensitive ) {
$parts[0] = lc( $parts[0] );
}
if ( exists $parts[1] ) {
chomp( $parts[1] );
$parts[1] =~ s/^\s+|\s+$//g; # trim both ends of the string
} else {
$parts[1] = '';
}
$$hash{$section}{$parts[0]} = $parts[1];
#print "$section $parts[0]" . ": " . $parts[1]. "\n";
#print $parts[0] . ": " . $$hash{$section}{$parts[0]}. "\n";
}
}
return 0;
}
#-------------------------------------------------------
=head3 scanCinder
Description : Scan the cinder configuration files.
Arguments : None
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = scanCinder();
=cut
#-------------------------------------------------------
sub scanCinder{
my $rc;
if ( $verbose ) {
print "Scanning the Cinder configuration files.\n";
}
# Read the configuration file and construct the hash of values.
my $file = '/etc/cinder/cinder.conf';
$rc = hashFile( $file, \%cinderConf, 0 );
return $rc;
}
#-------------------------------------------------------
=head3 scanNeutron
Description : Scan the neutron configuration files.
Arguments : None
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = scanNeutron();
=cut
#-------------------------------------------------------
sub scanNeutron{
my $rc;
if ( $verbose ) {
print "Scanning the Neutron configuration files.\n";
}
# Read the configuration file and construct the hash of values.
my $file = '/etc/neutron/neutron.conf';
$rc = hashFile( $file, \%neutronConf, 1 );
# Read the configuration file and construct the hash of values.
$file = '/etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini';
$rc = hashFile( $file, \%ovsNeutronPluginIni, 1 );
# Read the configuration file and construct the hash of values.
$file = '/etc/neutron/plugins/zvm/neutron_zvm_plugin.ini';
$rc = hashFile( $file, \%neutronZvmPluginIni, 1 );
return $rc;
}
#-------------------------------------------------------
=head3 scanNova
Description : Scan the Nova configuration files.
Arguments : None.
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = scanNova();
=cut
#-------------------------------------------------------
sub scanNova{
my $rc;
if ( $verbose ) {
print "Scanning the Nova configuration files.\n";
}
# Verify the /etc/nova/nova.conf exists.
my $file = '/etc/nova/nova.conf';
$rc = hashFile( $file, \%novaConf, 1 );
return $rc;
}
#-------------------------------------------------------
=head3 showHelp
Description : Show the help inforamtion.
Arguments : None.
Returns : None.
Example : showHelp();
=cut
#-------------------------------------------------------
sub showHelp{
print "$0 prepares and builds a z/VM xCAT IVP driver program
using the information from the configuration files in the
compute node. The default name of the driver program is
'$driverPrefix' following by the IP address of the
system where the driver is being prepared and ending with
'.sh'.
$supportString
The following files are scanned for input:
/etc/cinder/cinder.conf
/etc/nova/nova.conf
/etc/neutron/neutron.conf
/etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini
/etc/neutron/plugins/zvm/neutron_zvm_plugin.ini
The constructed driver program can then be uploaded to
the xCAT MN and used to validate the configuration between
the compute node and xCAT.\n\n";
print $usage_string;
return;
}
#-------------------------------------------------------
=head3 validateConfigs
Description : Compare and validate the configuration
values obtained by the scans.
Arguments : None.
Returns : 0 - No error
non-zero - Error detected.
Example : $rc = validateConfigs();
=cut
#-------------------------------------------------------
sub validateConfigs{
my $rc = 0;
my $option;
if ( $verbose ) {
print "Performing a local validation of the configuration files.\n";
}
#*******************************************************
# Verify required configuration options were specified.
#*******************************************************
if ( keys %cinderConf ) {
my @requiredCinderOpts = ();
foreach $option ( @requiredCinderOpts ) {
if ( !exists $cinderConf{'DEFAULT'}{$option} ) {
#print "option:$option.\nvalue:$cinderConf{$option}\n";
print "Warning: \'$option\' is missing from section \'DEFAULT\'\n" .
" in /etc/cinder/cinder.conf.\n";
}
}
}
my @requiredNovaOpts = (
"compute_driver",
"config_drive_format",
"force_config_drive",
"host",
'instance_name_template',
'zvm_diskpool',
'zvm_host',
'zvm_user_profile',
'zvm_xcat_master',
'zvm_xcat_server',
'zvm_xcat_username',
'zvm_xcat_password',
);
foreach $option ( @requiredNovaOpts ) {
if ( !exists $novaConf{'DEFAULT'}{$option} ) {
#print "option:$option.\nvalue:$novaConf{$option}\n";
print "Warning: \'$option\' is missing from section \'DEFAULT\'\n" .
" in /etc/nova/nova.conf.\n";
}
}
my @requiredNeutronConfOpts = (
'base_mac',
'core_plugin',
);
foreach $option ( @requiredNeutronConfOpts ) {
if ( !exists $neutronConf{'DEFAULT'}{$option} ) {
print "Warning: \'$option\' is missing from section \'DEFAULT\'\n" .
" in /etc/neutron/neutron.conf.\n";
}
}
my @requiredOvsNeutronPluginIniOpts = (
'network_vlan_ranges',
'tenant_network_type',
);
foreach $option ( @requiredOvsNeutronPluginIniOpts ) {
if ( !exists $ovsNeutronPluginIni{'ovs'}{$option} ) {
print "Warning: \'$option\' is missing from section \'ovs\'\n" .
" in /etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini.\n";
}
}
my @requiredNeutronZvmPluginIniOpts = (
"zvm_xcat_server",
);
foreach $option ( @requiredNeutronZvmPluginIniOpts ) {
if ( !exists $neutronZvmPluginIni{'agent'}{$option} ) {
print "Warning: \'$option\' is missing from section \'agent\'\n" .
" in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
}
}
#******************************************
# Verify optional operands were specified.
#******************************************
if ( keys %cinderConf ) {
if ( !exists $cinderConf{'DEFAULT'}{'san_ip'} and
!exists $cinderConf{'DEFAULT'}{'san_private_key'} and
!exists $cinderConf{'DEFAULT'}{'storwize_svc_connection_protocol'} and
!exists $cinderConf{'DEFAULT'}{'storwize_svc_volpool_name'} and
!exists $cinderConf{'DEFAULT'}{'storwize_svc_vol_iogrp'} and
!exists $cinderConf{'DEFAULT'}{'volume_driver'} ) {
print "Info: z/VM specific Cinder keys are not defined in section \'DEFAULT\'\n" .
" in /etc/cinder/cinder.conf. Cinder support for creation of persistent\n" .
" disks for z/VM is not enabled. Further testing of these options will\n" .
" not occur in this script.\n"
} else {
my %optionalCinderConfOpts = (
"san_ip" => "This property is necessary when using persistent disks obtained\n" .
" from the Cinder service.",
"san_private_key" => "This property is necessary when using persistent disks obtained\n" .
" from the Cinder service.",
"storwize_svc_connection_protocol" => "This property is necessary when using persistent disks obtained\n" .
" from the Cinder service.",
"storwize_svc_volpool_name" => "This property is necessary when using persistent disks obtained\n" .
" from the Cinder service.",
'storwize_svc_vol_iogrp' => "This property is necessary when using persistent disks obtained\n" .
" from the Cinder service.",
'volume_driver' => "This property is necessary when using persistent disks obtained\n" .
" from the Cinder service.",
);
my %defaultCinderConfOpts = ();
foreach my $key ( keys %optionalCinderConfOpts ) {
if ( !exists $cinderConf{'DEFAULT'}{$key} ) {
print "Info: \'$key\' is missing from section \'DEFAULT\'\n" .
" in /etc/cinder/cinder.conf.\n";
if ( $optionalCinderConfOpts{$key} ne '' ) {
print " " . $optionalCinderConfOpts{$key} . "\n";
}
if ( exists $defaultCinderConfOpts{$key} ) {
$cinderConf{'DEFAULT'}{$key} = $defaultCinderConfOpts{$key};
}
}
}
}
}
my %optionalNovaConfOpts = (
"image_cache_manager_interval" => "Default of 2400 (seconds) will be used.",
"ram_allocation_ratio" => "",
"rpc_response_timeout" => "zVM Live migration may timeout with the default " .
"value (60 seconds).\n The recommended value for z/VM is 180 to allow " .
"zVM live migration\n to succeed.",
"xcat_free_space_threshold" => "Default of 50 (G) will be used.",
"xcat_image_clean_period" => "Default of 30 (days) will be used.",
"zvm_config_drive_inject_password" => "This value will default to 'FALSE'.",
'zvm_diskpool_type' => "This value will default to \'ECKD\'.",
"zvm_fcp_list" => "Persistent disks cannot be attached to server instances.",
"zvm_zhcp_fcp_list" => "",
"zvm_image_tmp_path" => "Defaults to '/var/lib/nova/images'.",
"zvm_reachable_timeout" => "Default of 300 (seconds) will be used.",
"zvm_scsi_pool" => "Default of \'xcatzfcp\' will be used.",
"zvm_vmrelocate_force" => "",
"zvm_xcat_connection_timeout" => "Default of 3600 seconds will be used.",
);
my %defaultNovaConfOpts = (
"xcat_free_space_threshold" => 50,
"xcat_image_clean_period" => 30,
'zvm_diskpool_type' => 'ECKD',
"zvm_scsi_pool" => "xcatzfcp",
);
foreach my $key ( keys %optionalNovaConfOpts ) {
if ( !exists $novaConf{'DEFAULT'}{$key} ) {
print "Info: \'$key\' is missing from section \'DEFAULT\'\n" .
" in /etc/nova/nova.conf.\n";
if ( $optionalNovaConfOpts{$key} ne '' ) {
print " " . $optionalNovaConfOpts{$key} . "\n";
}
if ( exists $defaultNovaConfOpts{$key} ) {
$novaConf{'DEFAULT'}{$key} = $defaultNovaConfOpts{$key};
}
}
}
my %optionalNeutronConfOpts = ();
my %defaultNeutronConfOpts = ();
foreach my $key ( keys %optionalNeutronConfOpts ) {
if ( !exists $neutronConf{'DEFAULT'}{$key} ) {
print "Info: \'$key\' is missing from section \'DEFAULT\'\n" .
" in /etc/neutron/neutron.conf.\n";
if ( $optionalNeutronConfOpts{$key} ne '' ) {
print " " . $optionalNeutronConfOpts{$key} . "\n";
}
if ( exists $defaultNeutronConfOpts{$key} ) {
$neutronConf{'DEFAULT'}{$key} = $defaultNeutronConfOpts{$key};
}
}
}
my %optionalOvsNeutronPluginIniOpts = ();
my %defaultOvsNeutronPluginIniOpts = ();
foreach my $key ( keys %optionalOvsNeutronPluginIniOpts ) {
if ( !exists $ovsNeutronPluginIni{'agent'}{$key} ) {
print "Info: \'$key\' is missing from section \'agent\'\n" .
" in /etc/neutron/plugins/openvswitch/ovs_neutron_plugin.ini.\n";
if ( $optionalOvsNeutronPluginIniOpts{$key} ne '' ) {
print " " . $optionalOvsNeutronPluginIniOpts{$key} . "\n";
}
if ( exists $defaultOvsNeutronPluginIniOpts{'agent'}{$key} ) {
$ovsNeutronPluginIni{'agent'}{$key} = $defaultOvsNeutronPluginIniOpts{$key};
}
}
}
my %optionalNeutronZvmPluginIniOpts = (
"xcat_mgt_ip" => "This property is necessary when deploying virtual server " .
"instances that\n do NOT have public IP addresses.",
"xcat_mgt_mask" => "This property is necessary when deploying virtual server " .
"instances that\n do NOT have public IP addresses.",
"polling_interval" => "A default value of \'2\' will be used.",
"xcat_zhcp_nodename" => "A default value of \'zhcp\' will be used.",
"zvm_xcat_password" => "A default value of \'admin\' is used.",
"zvm_xcat_timeout" => "A default value of 300 seconds is used.",
"zvm_xcat_username" => "A default value of \'admin\' is used.",
);
my %defaultNeutronZvmPluginIniOpts = (
"polling_interval" => 2,
"xcat_zhcp_nodename" => "zhcp",
"zvm_xcat_password" => "admin",
"zvm_xcat_timeout" => 300,
"zvm_xcat_username" => "admin",
);
foreach my $key ( keys %optionalNeutronZvmPluginIniOpts ) {
if ( !exists $neutronZvmPluginIni{'agent'}{$key} ) {
print "Info: \'$key\' is missing from section \'agent\'\n" .
" in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
if ( $optionalNeutronZvmPluginIniOpts{$key} ne '' ) {
print " " . $optionalNeutronZvmPluginIniOpts{$key} . "\n";
}
if ( exists $defaultNeutronZvmPluginIniOpts{'agent'}{$key} ) {
$neutronZvmPluginIni{'agent'}{$key} = $defaultNeutronZvmPluginIniOpts{$key};
}
}
}
# Verify xCAT users are the same.
if ( !exists $novaConf{'DEFAULT'}{'zvm_xcat_username'} ) {
print "Info: Bypassing validation of 'zvm_xcat_username'.\n" .
" It is not specified in /etc/nova/nova.conf.\n";
} elsif ( !exists $neutronZvmPluginIni{'agent'}{'zvm_xcat_username'} ) {
print "Info: Bypassing validation of 'zvm_xcat_username'.\n" .
" It is not specified in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
} else {
if ( $novaConf{'DEFAULT'}{'zvm_xcat_username'} ne $neutronZvmPluginIni{'agent'}{'zvm_xcat_username'} ) {
print "Warning: xCAT user names mismatch; review 'zvm_xcat_username':\n" .
" \'$novaConf{'DEFAULT'}{'zvm_xcat_username'}\' in /etc/nova/nova.conf.\n" .
" \'$neutronZvmPluginIni{'agent'}{'zvm_xcat_username'}\' in\n" .
" /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
}
}
# Verify xCAT user passwords are the same.
if ( !exists $novaConf{'DEFAULT'}{'zvm_xcat_password'} ) {
print "Info: Bypassing validation of 'zvm_xcat_password'.\n" .
" It is not specified in /etc/nova/nova.conf.\n";
} elsif ( !exists $neutronZvmPluginIni{'agent'}{'zvm_xcat_password'} ) {
print "Info: Bypassing validation of 'zvm_xcat_password'. It is not specified\n" .
" in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
} else {
if ( $novaConf{'DEFAULT'}{'zvm_xcat_password'} ne $neutronZvmPluginIni{'agent'}{'zvm_xcat_password'} ) {
print "Warning: xCAT user passwords are not the same:\n" .
" Please review 'zvm_xcat_password' in /etc/nova/nova.conf and\n" .
" /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
}
}
# Verify the xcat server IP addresses are the same.
if ( !exists $novaConf{'DEFAULT'}{'zvm_xcat_server'} ) {
print "Info: Bypassing validation of 'zvm_xcat_server'.\n" .
" It is not specified in /etc/nova/nova.conf.\n";
} elsif ( !exists $neutronZvmPluginIni{'agent'}{'zvm_xcat_server'} ) {
print "Info: Bypassing validation of 'zvm_xcat_server'.\n" .
" It is not specified in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
} else {
if ( $novaConf{'DEFAULT'}{'zvm_xcat_server'} ne $neutronZvmPluginIni{'agent'}{'zvm_xcat_server'} ) {
print "Warning: xCAT server addresses mismatch; review 'zvm_xcat_server':\n" .
" \'$novaConf{'DEFAULT'}{'zvm_xcat_server'}\' in /etc/nova/nova.conf.\n" .
" \'$neutronZvmPluginIni{'agent'}{'zvm_xcat_server'}\' in /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini.\n";
}
}
# Verify the instance name template is valid
if ( exists $novaConf{'DEFAULT'}{'instance_name_template'} ) {
# Use sprintf which is close enough to the python % support for formatting to construct a sample.
my $base_name = sprintf( $novaConf{'DEFAULT'}{'instance_name_template'}, 1 );
if ( length( $base_name ) > 8 ) {
print "Warning: In /etc/nova/nova.conf, section \`DEFAULT\`, instance_name_template would\n" .
" construct a value greater than 8 in length: \'$novaConf{'DEFAULT'}{'instance_name_template'}\'.\n";
}
if ( $novaConf{'DEFAULT'}{'instance_name_template'} =~ /(^RSZ)/ or $novaConf{'DEFAULT'}{'instance_name_template'} =~ /(^rsz)/ ) {
print "Warning: In /etc/nova/nova.conf, instance_name_template begins\n" .
" with 'RSZ' or 'rsz': \'$novaConf{'DEFAULT'}{'instance_name_template'}\'\n";
}
}
# Verify the compute_driver is for z/VM
if ( exists $novaConf{'DEFAULT'}{'compute_driver'} ) {
if ( $novaConf{'DEFAULT'}{'compute_driver'} ne "nova.virt.zvm.ZVMDriver" and
$novaConf{'DEFAULT'}{'compute_driver'} ne "zvm.ZVMDriver") {
print "Warning: In /etc/nova/nova.conf, compute_driver does not contain the\n" .
" expected value of \'zvm.ZVMDriver\' and instead contains:\n" .
" \'$novaConf{'DEFAULT'}{'compute_driver'}\'\n";
}
}
# Check whether the rpc timeout is too small for z/VM
if ( exists $novaConf{'DEFAULT'}{'rpc_response_timeout'} ) {
if ( $novaConf{'DEFAULT'}{'rpc_response_timeout'} < 180 ) {
print "Warning: In /etc/nova/nova.conf, section \'DEFAULT\', rpc_response_timeout\n" .
" specifies a value, \'$novaConf{'DEFAULT'}{'rpc_response_timeout'}\', which is " .
"less than the recommended value\n of \'180\'.\n";
}
}
# Verify all SCSI disk operands are specified, if one exists.
if ( exists $novaConf{'DEFAULT'}{'zvm_fcp_list'} or exists $novaConf{'DEFAULT'}{'zvm_zhcp_fcp_list'} ) {
if ( !exists $novaConf{'DEFAULT'}{'zvm_fcp_list'} ) {
print "Warning: In /etc/nova/nova.conf, \'zvm_fcp_list\' does not exist but\n" .
" but other SCSI disk related operands exist. Both should be \'\n" .
" specified: \'zvm_fcp_list\' and \'zvm_zhcp_fcp_list\'\n";
}
if ( !exists $novaConf{'DEFAULT'}{'zvm_zhcp_fcp_list'} ) {
print "Warning: In /etc/nova/nova.conf, \'zvm_zhcp_fcp_list\' does not exist but\n" .
" but other SCSI disk related operands exist. Both should be \'\n" .
" specified: \'zvm_fcp_list\' and \'zvm_zhcp_fcp_list\'\n";
}
}
# Verify any rdev_list in Neutron z/VM Plugin ini file contains a single value and/or not a comma
foreach my $section (sort keys %neutronZvmPluginIni) {
next if ( $section eq 'agent');
foreach my $property ( keys %{ $neutronZvmPluginIni{$section} } ) {
next if ( $property ne "rdev_list" );
my $list = $neutronZvmPluginIni{$section}{$property};
$list =~ s/^\s+|\s+$//g; # trim blanks from both ends of the list
if ( $list eq '' ) {
print "Warning: In /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini, section \'$section\',\n" .
" \'rdev_list\' is specified but has no value.\n";
} else {
my @vals = split ( /\s/, $list );
if ( $#vals > 0 ) {
# $#vals is array size - 1.
print "Warning: In /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini, section \'$section\',\n" .
" \'rdev_list\' contains too many values.\n";
}
foreach my $op ( @vals ) {
if ( $op =~ m/[^0-9a-fA-F]+/ ) {
print "Warning: In /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini, section \'$section\',\n" .
" \'rdev_list\' contains non-hexadecimal characters: \'$op\'.\n";
} elsif ( length($op) > 4 ) {
print "Warning: In /etc/neutron/plugins/zvm/neutron_zvm_plugin.ini, section \'$section\',\n" .
" \'rdev_list\' contains a value that is not 1-4 characters in\n" .
" length: \'$op\'.\n";
}
}
}
}
}
# Check whether the storwize_svc_connection_protocol is not 'FC' for z/VM
if ( exists $cinderConf{'DEFAULT'}{'storwize_svc_connection_protocol'} ) {
if ( $cinderConf{'DEFAULT'}{'storwize_svc_connection_protocol'} ne 'FC' ) {
print "Warning: In /etc/cinder/cinder.conf, section \'DEFAULT\',\n" .
" storwize_svc_connection_protocol specifies a value, " .
"\'$cinderConf{'DEFAULT'}{'storwize_svc_connection_protocol'}\',\n" .
" which is not the required value of \'FC\'.\n";
}
}
# Check whether the storwize_svc_connection_protocol is not 'FC' for z/VM
if ( exists $cinderConf{'DEFAULT'}{'volume_driver'} ) {
if ( $cinderConf{'DEFAULT'}{'volume_driver'} ne 'cinder.volume.drivers.zvm.storwize_svc.StorwizeSVCZVMDriver' ) {
print "Warning: In /etc/cinder/cinder.conf, section \'DEFAULT\', volume_driver specifies\n" .
" a value, \'$cinderConf{'DEFAULT'}{'volume_driver'}\',\n which is " .
"not the required value of\n \'cinder.volume.drivers.zvm.storwize_svc.StorwizeSVCZVMDriver\'.\n";
}
}
return;
}
#*****************************************************************************
# Main routine
#*****************************************************************************
my $rc = 0;
my $clearPwOpt;
my $obfuscateOpt;
# Parse the arguments
$Getopt::Long::ignorecase = 0;
Getopt::Long::Configure( "bundling" );
if (!GetOptions( 's|scan=s' => \$scan,
'd|driver=s' => \$driver,
'h|help' => \$displayHelp,
#'c' => \$clearPwOpt,
#'o' => \$obfuscateOpt,
'v' => \$versionOpt,
'V' => \$verbose )) {
print $usage_string;
goto FINISH;
}
if ( $versionOpt ) {
print "Version: $version\n";
print "$supportString\n";
}
if ( $displayHelp ) {
showHelp();
}
if ( $displayHelp or $versionOpt ) {
goto FINISH;
}
$localIpAddress = inet_ntoa((gethostbyname(hostname))[4]);
if ( defined( $scan ) ) {
if ( $verbose ) {
print "Operand --scan: $scan\n";
}
if ( 'all nova neutron' !~ $scan ) {
print "--scan operand($scan) is not all, nova or neutron\n";
$rc = 400;
goto FINISH;
}
} else {
$scan = 'all';
}
if ( defined( $driver ) ) {
if ( $verbose ) {
print "Operand --driver: $driver\n";
}
$driver = "$driver.sh";
} else {
$driver = "$driverPrefix$localIpAddress.sh";
}
if ( $scan =~ 'all' or $scan =~ 'nova' ) {
!( $rc = scanNova() ) or goto FINISH;
}
if ( $scan =~ 'all' or $scan =~ 'cinder' ) {
scanCinder();
}
if ( $scan =~ 'all' or $scan =~ 'neutron' ) {
!( $rc = scanNeutron() ) or goto FINISH;
}
#if ( $obfuscateOpt ) {
# print "obfuscateOpt: $obfuscateOpt\n";
# $obfuscatePw = 1;
#} elsif ( $clearPwOpt ) {
# $obfuscatePw = 0;
#}
!( $rc = validateConfigs() ) or goto FINISH;
!( $rc = buildDriverProgram() ) or goto FINISH;
FINISH:
exit $rc;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -18,23 +18,37 @@ AutoReqProv: no
%define fsm %(if [ "$fsm" = "1" ];then echo 1; else echo 0; fi)
# Define local variable from environment variable
%define pcm %(if [ "$pcm" = "1" ];then echo 1; else echo 0; fi)
%define notpcm %(if [ "$pcm" = "1" ];then echo 0; else echo 1; fi)
%define s390x %(if [ "$s390x" = "1" ];then echo 1; else echo 0; fi)
%define nots390x %(if [ "$s390x" = "1" ];then echo 0; else echo 1; fi)
# Define a different location for various httpd configs in s390x mode
%define httpconfigdir %(if [ "$s390x" = "1" ];then echo "xcathttpdsave"; else echo "xcat"; fi)
# AIX will build with an arch of "ppc"
# also need to fix Requires for AIX
%ifos linux
BuildArch: noarch
# Note: ifarch/ifnarch does not work for noarch package, use environment variable instead
%if %s390x
Requires: perl-IO-Socket-SSL perl-XML-Simple perl-XML-Parser
%else
Requires: perl-IO-Socket-SSL perl-XML-Simple perl-XML-Parser perl-Digest-SHA1 perl(LWP::Protocol::https)
%endif
Obsoletes: atftp-xcat
%endif
# The aix rpm cmd forces us to do this outside of ifos type stmts
%if %notpcm
%ifos linux
#
# PCM does not use or ship grub2-xcat
%if %nots390x
Requires: grub2-xcat perl-Net-HTTPS-NB perl-HTTP-Async
#%endif
%endif
%endif
%endif
@ -313,7 +327,7 @@ mkdir -p $RPM_BUILD_ROOT/etc/init.d
cp etc/init.d/xcatd $RPM_BUILD_ROOT/etc/init.d
%endif
#TODO: the next has to me moved to postscript, to detect /etc/xcat vs /etc/opt/xcat
mkdir -p $RPM_BUILD_ROOT/etc/xcat
mkdir -p $RPM_BUILD_ROOT/etc/%httpconfigdir
mkdir -p $RPM_BUILD_ROOT/%{prefix}/share/doc/packages/xCAT-server
cp LICENSE.html $RPM_BUILD_ROOT/%{prefix}/share/doc/packages/xCAT-server
@ -324,7 +338,7 @@ chmod 644 $RPM_BUILD_ROOT/%{prefix}/share/doc/packages/xCAT-server/*
mkdir -p $RPM_BUILD_ROOT/%{prefix}/ws
mkdir -p $RPM_BUILD_ROOT/etc/apache2/conf.d
mkdir -p $RPM_BUILD_ROOT/etc/httpd/conf.d
mkdir -p $RPM_BUILD_ROOT/etc/xcat/conf.orig
mkdir -p $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig
cp xCAT-wsapi/* $RPM_BUILD_ROOT/%{prefix}/ws
@ -334,20 +348,32 @@ cp xCAT-wsapi/* $RPM_BUILD_ROOT/%{prefix}/ws
rm -f $RPM_BUILD_ROOT/%{prefix}/ws/xcatws.cgi
%endif
%if %fsm
%else
echo "ScriptAlias /xcatrhevh %{prefix}/ws/xcatrhevh.cgi" > $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache22
echo "ScriptAlias /xcatrhevh %{prefix}/ws/xcatrhevh.cgi" > $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache24
%if %notpcm
echo "ScriptAlias /xcatws %{prefix}/ws/xcatws.cgi" >> $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache22
echo "ScriptAlias /xcatws %{prefix}/ws/xcatws.cgi" >> $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache24
%if %nots390x
rm -f $RPM_BUILD_ROOT/%{prefix}/ws/zvmxcatws.cgi
%endif
cat $RPM_BUILD_ROOT/%{prefix}/ws/xcat-ws.conf.apache22 >> $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache22
cat $RPM_BUILD_ROOT/%{prefix}/ws/xcat-ws.conf.apache24 >> $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache24
%if %fsm
%else
echo "ScriptAlias /xcatrhevh %{prefix}/ws/xcatrhevh.cgi" > $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22
echo "ScriptAlias /xcatrhevh %{prefix}/ws/xcatrhevh.cgi" > $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24
%if %notpcm
%if %nots390x
echo "ScriptAlias /xcatws %{prefix}/ws/xcatws.cgi" >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22
echo "ScriptAlias /xcatws %{prefix}/ws/xcatws.cgi" >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24
%else
# Add in old version 1 REST-API and version 2 REST-API to z/VM, default to version 1
echo "ScriptAlias /xcatwsv2 %{prefix}/ws/xcatws.cgi" >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22
echo "ScriptAlias /xcatwsv2 %{prefix}/ws/xcatws.cgi" >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24
echo "ScriptAlias /xcatws %{prefix}/ws/zvmxcatws.cgi" >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22
echo "ScriptAlias /xcatws %{prefix}/ws/zvmxcatws.cgi" >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24
%endif
%endif
cat $RPM_BUILD_ROOT/%{prefix}/ws/xcat-ws.conf.apache22 >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22
cat $RPM_BUILD_ROOT/%{prefix}/ws/xcat-ws.conf.apache24 >> $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24
#install lower version(<2.4) apache/httpd conf files by default
cp $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache22 $RPM_BUILD_ROOT/etc/apache2/conf.d/xcat-ws.conf
cp $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat-ws.conf.apache22 $RPM_BUILD_ROOT/etc/httpd/conf.d/xcat-ws.conf
cp $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22 $RPM_BUILD_ROOT/etc/apache2/conf.d/xcat-ws.conf
cp $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22 $RPM_BUILD_ROOT/etc/httpd/conf.d/xcat-ws.conf
%endif
@ -362,12 +388,12 @@ rm -rf $RPM_BUILD_ROOT
%defattr(-,root,root)
#%doc LICENSE.html
%{prefix}
/etc/xcat
/etc/%httpconfigdir
%if %fsm
%else
/etc/init.d/xcatd
#/etc/xcat/conf.orig/xcat-ws.conf.apache24
#/etc/xcat/conf.orig/xcat-ws.conf.apache22
#/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24
#/etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache22
/etc/apache2/conf.d/xcat-ws.conf
/etc/httpd/conf.d/xcat-ws.conf
%endif
@ -434,19 +460,19 @@ fi
if [ -n "$(httpd -v 2>&1 |grep -e '^Server version\s*:.*\/2.4')" ]
then
rm -rf /etc/httpd/conf.d/xcat-ws.conf
cp /etc/xcat/conf.orig/xcat-ws.conf.apache24 /etc/httpd/conf.d/xcat-ws.conf
cp /etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24 /etc/httpd/conf.d/xcat-ws.conf
fi
if [ -n "$(apachectl -v 2>&1 |grep -e '^Server version\s*:.*\/2.4')" ]
then
rm -rf /etc/apache2/conf.d/xcat-ws.conf
cp /etc/xcat/conf.orig/xcat-ws.conf.apache24 /etc/apache2/conf.d/xcat-ws.conf
cp /etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24 /etc/apache2/conf.d/xcat-ws.conf
fi
if [ -n "$(apache2ctl -v 2>&1 |grep -e '^Server version\s*:.*\/2.4')" ]
then
rm -rf /etc/apache2/conf.d/xcat-ws.conf
cp /etc/xcat/conf.orig/xcat-ws.conf.apache24 /etc/apache2/conf.d/xcat-ws.conf
cp /etc/%httpconfigdir/conf.orig/xcat-ws.conf.apache24 /etc/apache2/conf.d/xcat-ws.conf
fi
exit 0

View File

@ -1,10 +1,13 @@
LoadModule rewrite_module /usr/lib64/apache2-prefork/mod_rewrite.so
# Redirect all http request to https
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} xcatws
RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [R,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^/?xcatws/(.*) https://%{SERVER_NAME}/xcatws/$1 [R,L]
RewriteRule ^/?xcatwsv2/(.*) https://%{SERVER_NAME}/xcatwsv2/$1 [R,L]
<Files xcatws.cgi>
<Files (xcatws.cgi|zvmxcatws.cgi)>
Order allow,deny
Allow from all
</Files>

View File

@ -1,10 +1,11 @@
LoadModule rewrite_module /usr/lib64/apache2-prefork/mod_rewrite.so
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} xcatws
RewriteRule ^(.*)$ https://%{SERVER_NAME}$1 [R,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^/?xcatws/(.*) https://%{SERVER_NAME}/xcatws/$1 [R,L]
RewriteRule ^/?xcatwsv2/(.*) https://%{SERVER_NAME}/xcatwsv2/$1 [R,L]
<Files xcatws.cgi>
<Files (xcatws.cgi|zvmxcatws.cgi)>
Require all granted
</Files>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -28,14 +28,24 @@ Conflicts: xCATsn
Requires: perl-DBD-SQLite
Requires: xCAT-client = 4:%{version}-%{release}
Requires: xCAT-server = 4:%{version}-%{release}
Requires: xCAT-probe = 4:%{version}-%{release}
Requires: xCAT-genesis-scripts-x86_64 = 1:%{version}-%{release}
Requires: xCAT-genesis-scripts-ppc64 = 1:%{version}-%{release}
Requires: rsync
%define pcm %(if [ "$pcm" = "1" ];then echo 1; else echo 0; fi)
%define notpcm %(if [ "$pcm" = "1" ];then echo 0; else echo 1; fi)
%define s390x %(if [ "$s390x" = "1" ];then echo 1; else echo 0; fi)
%define nots390x %(if [ "$s390x" = "1" ];then echo 0; else echo 1; fi)
# Define a different location for various httpd configs in s390x mode
%define httpconfigdir %(if [ "$s390x" = "1" ];then echo "xcathttpdsave"; else echo "xcat"; fi)
%if %nots390x
Requires: xCAT-probe = 4:%{version}-%{release}
Requires: xCAT-genesis-scripts-x86_64 = 1:%{version}-%{release}
Requires: xCAT-genesis-scripts-ppc64 = 1:%{version}-%{release}
%endif
Requires: rsync
%ifos linux
Requires: httpd nfs-utils nmap bind perl(CGI)
# on RHEL7, need to specify it explicitly
@ -45,7 +55,7 @@ Requires: /usr/bin/killall
Requires: /usr/sbin/dhcpd
# On RHEL this pulls in openssh-server, on SLES it pulls in openssh
Requires: /usr/bin/ssh
%ifnarch s390x
%if %nots390x
Requires: /etc/xinetd.d/tftp
Requires: xCAT-buildkit
# Stty is only needed for rcons on ppc64 nodes, but for mixed clusters require it on both x and p
@ -56,7 +66,7 @@ Requires: perl-IO-Stty
# The aix rpm cmd forces us to do this outside of ifos type stmts
%if %notpcm
%ifos linux
%ifnarch s390x
%if %nots390x
# PCM does not use or ship conserver
Requires: conserver-xcat
%endif
@ -64,7 +74,9 @@ Requires: conserver-xcat
%endif
#support mixed cluster
%if %nots390x
Requires: elilo-xcat xnba-undi
%endif
%ifarch i386 i586 i686 x86 x86_64
Requires: syslinux
@ -79,8 +91,10 @@ Requires: ipmitool-xcat >= 1.8.17-1
%if %notpcm
# PCM does not need or ship syslinux-xcat
%if %nots390x
Requires: syslinux-xcat
%endif
%endif
%description
xCAT is a server management package intended for at-scale management, including
@ -128,7 +142,7 @@ fi
%install
mkdir -p $RPM_BUILD_ROOT/etc/xcat/conf.orig
mkdir -p $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig
mkdir -p $RPM_BUILD_ROOT/etc/apache2/conf.d
mkdir -p $RPM_BUILD_ROOT/etc/httpd/conf.d
mkdir -p $RPM_BUILD_ROOT/etc/logrotate.d
@ -176,8 +190,8 @@ mkdir -p postscripts/hostkeys
cd -
cp %{SOURCE1} $RPM_BUILD_ROOT/etc/httpd/conf.d/xcat.conf
cp %{SOURCE1} $RPM_BUILD_ROOT/etc/apache2/conf.d/xcat.conf
cp %{SOURCE7} $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat.conf.apach24
cp %{SOURCE1} $RPM_BUILD_ROOT/etc/xcat/conf.orig/xcat.conf.apach22
cp %{SOURCE7} $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat.conf.apach24
cp %{SOURCE1} $RPM_BUILD_ROOT/etc/%httpconfigdir/conf.orig/xcat.conf.apach22
cp %{SOURCE5} $RPM_BUILD_ROOT/etc/xCATMN
mkdir -p $RPM_BUILD_ROOT/%{prefix}/share/doc/packages/xCAT
@ -190,19 +204,19 @@ cp LICENSE.html $RPM_BUILD_ROOT/%{prefix}/share/doc/packages/xCAT
if [ -n "$(httpd -v 2>&1 |grep -e '^Server version\s*:.*\/2.4')" ]
then
rm -rf /etc/httpd/conf.d/xcat.conf
cp /etc/xcat/conf.orig/xcat.conf.apach24 /etc/httpd/conf.d/xcat.conf
cp /etc/%httpconfigdir/conf.orig/xcat.conf.apach24 /etc/httpd/conf.d/xcat.conf
fi
if [ -n "$(apachectl -v 2>&1 |grep -e '^Server version\s*:.*\/2.4')" ]
then
rm -rf /etc/apache2/conf.d/xcat.conf
cp /etc/xcat/conf.orig/xcat.conf.apach24 /etc/apache2/conf.d/xcat.conf
cp /etc/%httpconfigdir/conf.orig/xcat.conf.apach24 /etc/apache2/conf.d/xcat.conf
fi
if [ -n "$(apache2ctl -v 2>&1 |grep -e '^Server version\s*:.*\/2.4')" ]
then
rm -rf /etc/apache2/conf.d/xcat.conf
cp /etc/xcat/conf.orig/xcat.conf.apach24 /etc/apache2/conf.d/xcat.conf
cp /etc/%httpconfigdir/conf.orig/xcat.conf.apach24 /etc/apache2/conf.d/xcat.conf
fi
# Let rsyslogd perform close of any open files
@ -244,8 +258,8 @@ exit 0
%files
%{prefix}
# one for sles, one for rhel. yes, it's ugly...
/etc/xcat/conf.orig/xcat.conf.apach24
/etc/xcat/conf.orig/xcat.conf.apach22
/etc/%httpconfigdir/conf.orig/xcat.conf.apach24
/etc/%httpconfigdir/conf.orig/xcat.conf.apach22
/etc/httpd/conf.d/xcat.conf
/etc/apache2/conf.d/xcat.conf
/etc/xCATMN

View File

@ -24,4 +24,3 @@ Alias /xcat-doc "/opt/xcat/share/doc"
AllowOverride None
Require all granted
</Directory>

View File

@ -57,7 +57,9 @@ Requires: conserver-xcat
%endif
#support mixed cluster
%ifnarch s390x
Requires: elilo-xcat xnba-undi
%endif
%ifarch i386 i586 i686 x86 x86_64
Requires: syslinux