diff --git a/Version b/Version index 3cf561c0b..371a952d6 100644 --- a/Version +++ b/Version @@ -1 +1 @@ -2.12.1 +2.12.2 diff --git a/build-debs-all b/build-debs-all deleted file mode 100755 index 70f71933a..000000000 --- a/build-debs-all +++ /dev/null @@ -1,88 +0,0 @@ -#!/bin/bash -########### -# -# This script call makedeb and create the deb packages -# for xCAT -# -# Author: Leonardo Tonetto -# Revisor: Adalberto Medeiros -# Revisor2: Arif Ali -# -# Input: -# -# $1 is the build type/location -# $2 is the string added to the debian/changelog of each package -# -############ - -############## -# Get input -############## - -PKG_LOCATION=$1 # local | snap | alpha -if [ -z $PKG_LOCATION ]; then - PKG_LOCATION="local" -fi -BUILD_STRING=$2 -if [ -z $BUILD_STRING ]; then - BUILD_STRING="Personal Build" -fi -XCAT_VERSION=`cat Version` -TRUNK_REVISION=`svnversion | cut -d ":" -f1` -CUR_DATE=`date +%Y%m%d` -VERSION="${XCAT_VERSION}-${PKG_LOCATION}${CUR_DATE}" - -function makedeb { - SRC_ROOT=$1 - PKG_LOCATION=$2 - BUILD_STRING=$3 - VERSION=$4 - - # - # Make DEBs - # - # build perl-xCAT - deps are libsoap-lite-perl, libdigest-sha1-perl, libdbi-perl - # - - find $SRC_ROOT -maxdepth 2 -name debian -type d | while read DEBIAN_DIR - do - DIR=`echo ${DEBIAN_DIR} | sed -e 's/[/]debian$//'` - cd ${DIR} - dch -v $VERSION -b -c debian/changelog "$BUILD_STRING" - dpkg-buildpackage - cd - - RC=$? - if [ ${RC} -gt 0 ] - then - echo "Warning: ${DEBIAN_DIR} failed exit code ${RC}" - fi - done - - # - # Clean up - # - # Eliminate unnecessary directories and debian/files made by dpkg-buildpackage - - find $SRC_ROOT -maxdepth 3 -type d -name "xcat-*" | grep debian | xargs rm -rf - find $SRC_ROOT -maxdepth 3 -type f -name "files" | grep debian | xargs rm -f -} - -# build all debian packages -packages="xCAT-client xCAT-nbroot xCAT-nbroot2 perl-xCAT xCAT-server xCAT-UI xCAT xCATsn xCAT-test xCAT-IBMhpc xCAT-rmc xCAT-vlan xCAT-confluent" - -for file in `echo $packages` -do - makedeb $file $PKG_LOCATION "$BUILD_STRING" $VERSION -done - -if [ -d debs ]; then - rm -rf debs -fi - -mkdir debs -mv xcat* debs/ -mv perl-xcat* debs/ - -echo $VERSION > latest_version - -exit 0 diff --git a/build-ubunturepo b/build-ubunturepo index 3678dc71e..275a95347 100755 --- a/build-ubunturepo +++ b/build-ubunturepo @@ -35,8 +35,8 @@ printusage() { printf "Usage: %s {-c | -d} \n" $(basename $0) >&2 - echo " -c : Build the xcat core packages and create the repo" - echo " -d : Create the xcat dep repo. Building the xcat dep packages can refer \"build-debs-all\" from svn" + echo " -c : Build the xcat-core packages and create the repo" + echo " -d : Create the xcat-dep repo." } # For the purpose of getting the distribution name if [[ ! -f /etc/lsb-release ]]; then @@ -223,7 +223,7 @@ then if [ ! -d ../../$package_dir_name ];then mkdir -p "../../$package_dir_name" fi - packages="xCAT-client xCAT-genesis-scripts perl-xCAT xCAT-server xCAT xCATsn xCAT-test xCAT-buildkit xCAT-vlan xCAT-confluent" + packages="xCAT-client xCAT-genesis-scripts perl-xCAT xCAT-server xCAT xCATsn xCAT-test xCAT-buildkit xCAT-vlan xCAT-confluent xCAT-probe" target_archs=(amd64 ppc64el) for file in `echo $packages` do @@ -242,9 +242,29 @@ then cd $file dch -v $pkg_version -b -c debian/changelog $build_string if [ "$target_arch" = "all" ]; then + #xcat probe use some functions shipped by xCAT, for below reasons we need to copy files to xCAT-probe directory + #1 make xcat probe code to be self-contained + #2 don't maintain two files for each script + #3 symbolic link can't work during package + if [ $file_low = "xcat-probe" ]; then + CURDIR=$(pwd) + mkdir -p ${CURDIR}/xCAT-probe/lib/perl/xCAT/ + cp -f ${CURDIR}/perl-xCAT/xCAT/NetworkUtils.pm ${CURDIR}/xCAT-probe/lib/perl/xCAT/ + cp -f ${CURDIR}/perl-xCAT/xCAT/GlobalDef.pm ${CURDIR}/xCAT-probe/lib/perl/xCAT/ + fi dpkg-buildpackage -uc -us else + if [ "$file" = "xCAT-genesis-scripts" ]; then + CURDIR=$(pwd) + echo "Rename control file to build pkg: mv ${CURDIR}/debian/control-${target_arch} ${CURDIR}/debian/control" + mv ${CURDIR}/debian/control-${target_arch} ${CURDIR}/debian/control + fi dpkg-buildpackage -uc -us -a$target_arch + if [ "$file" = "xCAT-genesis-scripts" ]; then + CURDIR=$(pwd) + echo "Move control file back: mv ${CURDIR}/debian/control ${CURDIR}/debian/control-${target_arch}" + mv ${CURDIR}/debian/control ${CURDIR}/debian/control-${target_arch} + fi fi rc=$? if [ $rc -gt 0 ]; then diff --git a/buildcore.sh b/buildcore.sh index 13494774c..a2422ce7f 100755 --- a/buildcore.sh +++ b/buildcore.sh @@ -67,7 +67,7 @@ if [ -z "$UP" ]; then fi # These are the rpms that should be built for each kind of xcat build -ALLBUILD="perl-xCAT xCAT-client xCAT-server xCAT-test xCAT-buildkit xCAT xCATsn xCAT-genesis-scripts xCAT-SoftLayer xCAT-vlan xCAT-confluent" +ALLBUILD="perl-xCAT xCAT-client xCAT-server xCAT-test xCAT-buildkit xCAT xCATsn xCAT-genesis-scripts xCAT-SoftLayer xCAT-vlan xCAT-confluent xCAT-probe" ZVMBUILD="perl-xCAT xCAT-server xCAT-UI" ZVMLINK="xCAT-client xCAT xCATsn" # xCAT and xCATsn have PCM specific configuration - conserver-xcat, syslinux-xcat @@ -175,6 +175,9 @@ function setversionvars { VER=`cat Version` SHORTVER=`cat Version|cut -d. -f 1,2` SHORTSHORTVER=`cat Version|cut -d. -f 1` + BUILD_TIME=`date` + BUILD_MACHINE=`hostname` + COMMIT_ID=`git rev-parse --short HEAD` } @@ -288,7 +291,7 @@ if [ "$OSNAME" = "AIX" ]; then fi # Build the rest of the noarch rpms -for rpmname in xCAT-client xCAT-server xCAT-IBMhpc xCAT-rmc xCAT-UI xCAT-test xCAT-buildkit xCAT-SoftLayer xCAT-vlan xCAT-confluent; do +for rpmname in xCAT-client xCAT-server xCAT-IBMhpc xCAT-rmc xCAT-UI xCAT-test xCAT-buildkit xCAT-SoftLayer xCAT-vlan xCAT-confluent xCAT-probe; do if [[ " $EMBEDBUILD " != *\ $rpmname\ * ]]; then continue; fi if [ "$OSNAME" = "AIX" -a "$rpmname" = "xCAT-buildkit" ]; then continue; fi # do not build xCAT-buildkit on aix if [ "$OSNAME" = "AIX" -a "$rpmname" = "xCAT-SoftLayer" ]; then continue; fi # do not build xCAT-softlayer on aix @@ -504,6 +507,16 @@ if [ -n "$VERBOSEMODE" ]; then else verboseflag="" fi + +# +# Add a VERSION file into the tar.bz2 file to track information about the build +# +BUILDINFO=$XCATCORE/buildinfo +echo "VERSION=$VER" > $BUILDINFO +echo "BUILD_TIME=$BUILD_TIME" >> $BUILDINFO +echo "BUILD_MACHINE=$BUILD_MACHINE" >> $BUILDINFO +echo "COMMIT_ID=$COMMIT_ID" >> $BUILDINFO + echo "Creating $(dirname $DESTDIR)/$TARNAME ..." if [[ -e $TARNAME ]]; then mkdir -p previous diff --git a/create_man_pages.py b/create_man_pages.py index 3002f2d20..2a5ff368a 100755 --- a/create_man_pages.py +++ b/create_man_pages.py @@ -130,7 +130,7 @@ for component in COMPONENTS: cmd = "perl -I %s/share/perl5 %s/bin/%s " %(prefix_path, prefix_path, POD2RST) cmd += " --infile=%s --outfile=%s --title=%s.%s" %(pod_input, rst_output, title, man_ver) - print cmd + # print cmd os.system(cmd) if man_ver == '1' or man_ver == '8': fix_vertical_bar(rst_output) diff --git a/docs/README.md b/docs/README.md index 05e277f85..175295970 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,10 +13,19 @@ The documentation project is written in restructured text (.rst) using Sphinx an * Clone the project -* Using pip, install sphinx (See: http://pip.readthedocs.org/) +* Using pip, install or update sphinx (See: http://pip.readthedocs.org/) ``` pip install sphinx ``` + or + ``` + pip install sphinx --upgrade + ``` + +* Using pip, install ReadTheDocs theme + ``` + pip install sphinx_rtd_theme + ``` * Build the Docs ``` diff --git a/docs/source/advanced/cluster_maintenance/compute_node/changing_hostname_ip.rst b/docs/source/advanced/cluster_maintenance/compute_node/changing_hostname_ip.rst index 04ea388d7..544f577cd 100644 --- a/docs/source/advanced/cluster_maintenance/compute_node/changing_hostname_ip.rst +++ b/docs/source/advanced/cluster_maintenance/compute_node/changing_hostname_ip.rst @@ -1,2 +1,81 @@ -Changing the hostname/IP address +Changing the Hostname/IP address ================================ + +Background +---------- + +If the hostname or IP address has already been modified on compute nodes, +follow the steps to change the configuration in xcat. + +Remove Old Provision Environment +-------------------------------- + +#. Remove the nodes from DNS configuration :: + + makedns -d + +#. Remove the nodes from the DHCP configuration :: + + makedhcp -d + +#. Remove the nodes from the conserver configuration :: + + makeconservercf -d + +Change Definition +----------------- + +#. Change netwoks table definitions :: + + lsdef -t network -l + + The output may be like :: + + 10_0_0_0-255_0_0_0 (network) + 192_168_122_0-255_255_255_0 (network) + + Change the networks table definitions, For example ``192_168_122_0-255_255_255_0`` + is a original network configuration which should be modified to + ``192_168_123_0-255_255_255_0``:: + + rmdef -t network 192_168_122_0-255_255_255_0 + mkdef -t network 192_168_123_0-255_255_255_0 net=192.168.123.0 mask=255.255.255.0 + +#. Change the hostname in the xCAT database (This command only supports one node + at a time). For many nodes you will have to write a script. :: + + # changes node1 to node2 in the database + chdef -t node -o node1 -n node2 + +#. Change the hostname and IP address in the ``/etc/hosts`` file + + - If you do not use the hosts table in xCAT to create the ``/etc/hosts`` file, + edit the ``/etc/hosts`` file and change your hostname and IP address entries + directly. + - If you use the xCAT hosts table, and your nodes are defined by name in the + hosts table, the hosts table must be updated with the new names when + we changed the node name using ``chdef`` command. If the hosts tables contains + regular expression, you have to rewrite the regular expression to + match your new hostname and IP address. + - If these is no regular expression in the hosts table, you can run :: + + # change the IP address for the new hostname in the hosts table. + nodech hosts.ip="x.xx.xx.xx" + # add hostname/IP records in /etc/hosts from the definition in the xCAT hosts + # table for the + makehosts + +Update The Provision Environment +-------------------------------- + +#. Configure the new names in DNS :: + + makedns -n + +#. Configure the new names in DHCP :: + + makedhcp -a + +#. Configure the new names in conserver :: + + makeconservercf diff --git a/docs/source/advanced/cluster_maintenance/index.rst b/docs/source/advanced/cluster_maintenance/index.rst index 6419d475e..e4fcb7ff7 100644 --- a/docs/source/advanced/cluster_maintenance/index.rst +++ b/docs/source/advanced/cluster_maintenance/index.rst @@ -6,4 +6,5 @@ Cluster Maintenance compute_node/index.rst mgmt_node/index.rst + service_node/index.rst sw_fw_inventory.rst diff --git a/docs/source/advanced/cluster_maintenance/mgmt_node/changing_hostname_ip.rst b/docs/source/advanced/cluster_maintenance/mgmt_node/changing_hostname_ip.rst index 0716dc9e1..fda96e1ad 100644 --- a/docs/source/advanced/cluster_maintenance/mgmt_node/changing_hostname_ip.rst +++ b/docs/source/advanced/cluster_maintenance/mgmt_node/changing_hostname_ip.rst @@ -1,4 +1,277 @@ Changing the hostname/IP address ================================ -There may be times when it is required to change the hostname or IP address of the xCAT management nodes. This document helps to outline the steps required to ensure successfully changing this attribute on the management node. +Overview +-------- + +This document is intended to describe the steps that must be taken if you need +to change your Linux Management Node's hostname and/or IP address +after the cluster is installed and configured by xCAT. This documentation will +only cover the changes by xCAT and will not try to cover any other changes by +any other tools. + +Backup your xCAT data +--------------------- + +Clean up the database by running ``tabprune`` command: :: + + tabprune -a auditlog + tabprune -a eventlog + +Now take a snapshot of the Management Node. This will also create a database +backup. You can use this data as reference if needed. :: + + xcatsnap -d + +Stop xCAT +--------- + +You need to stop the xcat daemon and any other applications that are using the +xCAT database on the Management Node and the Service Nodes. To determine your +database, run :: + + lsxcatd -a | grep dbengine + +To stop xCAT: :: + + service xcatd stop + +Stop The Database +----------------- + +For all databases except SQlite, you should stop the database. +For example :: + + service postgresql stop + service mysqld stop + +Change the Management Hostname +------------------------------- + +* hostname command :: + + hostname + +* Edit hostname configuration file + + | Add hostname in ``/etc/hostname`` + | Add HOSTNAME attribute in ``/etc/sysconfig/network`` (only for [RHEL]) + +Update Database Files +--------------------- + +You need to update the new MN hostname or IP address in several database +configuration files. + +SQLite +^^^^^^ + +Nothing to do. + +Postgresql +^^^^^^^^^^ + +- Edit ``/etc/xcat/cfgloc`` file, replace ``Pg:dbname=xcatdb;host=|xcatadm|xcat20`` + with ``Pg:dbname=xcatdb;host=|xcatadm|xcat20``. + +- Edit config database config file ``/var/lib/pgsql/data/pg_hba.conf``, + replace ``host all all /32 md5`` + with ``host all all /32 md5``. + +Mysql +^^^^^ + +Edit ``/etc/xcat/cfglooc``, replace ``mysql:dbname=xcatdb;host=|xcatadmin|xcat20`` +with ``mysql:dbname=xcatdb;host=|xcatadmin|xcat20``. + +Start the database +------------------ + +:: + + service postgresql start + service mysqld start + +Start xCAT + +:: + + service xcatd start + +Verify your new database setup :: + + lsxcatd -a | grep dbengine + tabdump site # if output exists + +Change The Definition In xCAT Database +-------------------------------------- + +Change the site table master attribute +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + chdef -t site master= + +Change all IP address attribute relevant to the MN IP address +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For example, old address was "10.6.0.1" + +* Query the attributes with old address :: + + lsdef -t node -l | grep "10.6.0.1" + # the output may looks like + conserver=10.6.0.1 + conserver=10.6.0.1 + conserver=10.6.0.1 + conserver=10.6.0.1 + nfsserver=10.6.0.1 + servicenode=10.6.0.1 + xcatmaster=10.6.0.1 + kcmdline=quiet repo=http://10.6.0.1/install/rhels6/ppc64/ ks=http://10.6.0.1/install/autoinst + /slessn ksdevice=d6:92:39:bf:71:05 + nfsserver=10.6.0.1 + servicenode=10.6.0.1 + tftpserver=10.6.0.1 + xcatmaster=10.6.0.1 + servicenode=10.6.0.1 + xcatmaster=10.6.0.1 + +* As the attribute with the old IP address is list above, take conserver as + a example, query the nodes with ``conserver=10.6.0.1``. + + :: + + lsdef -t node -w conserver="10.6.0.1" + # the output looks like + cn1 (node) + cn2 (node) + cn3 (node) + cn4 (node) + +* Change the conserver address for cn1,cn2,cn3,cn4 :: + + chdef -t node cn1-cn4 conserver= + +Repeat the same process for the other attributes. + +Change networks table +^^^^^^^^^^^^^^^^^^^^^^ + +Check your networks table to see if the network definitions are still correct, +if not edit accordingly :: + + lsdef -t network -l + chdef -t network + +Check Result +^^^^^^^^^^^^^ + +You can check whether all the old address has been changed using :: + + dumpxCATdb -P + cd + fgrep "10.6.0.1" *.csv + +If the old address still exists in the ``*.csv` file, you can edit this file, +then use the following command to restore the records :: + + tabrestore + +Generate SSL credentials(optional) +---------------------------------- + +If you do not generate new credentials, skip this section. +If you decide generate new credentials, then you will use the following +command. + +* Generate new credentials :: + + xcatconfig -c + +* Update the policy table with new MN name, + replace ``"1.4","old_MN_name",,,,,,"trusted",,`` with + ``"1.4","new_MN_name",,,,,,"trusted",,`` + +* Setup up conserver with new credentials :: + + makeconservercf + +External DNS Server Changed +--------------------------- + +* Update nameserver entries in ``/etc/resolv.conf`` +* Update nameserver attribute in ``site`` table :: + + chdef -t site -o clustersite nameservers="new_ip_address1,new_ip_address2" + +* Update site forwarders in DB :: + + chdef -t site -o clustersite forwarders="new_ip_address1,new_ip_address2" + +* Run command ``makedns -n`` + +Domain Name Changed +------------------- + +Change the entries in ``/etc/hosts``. + +Change the ``/etc/resolv.conf``, forwarders attribute in site table. :: + + lsdef -t site -o clustersite -i forwarders + chdef -t site -o clustersite forwarders + +Change the domain name in the xCAT database site table. :: + + chdef -t site -o clustersite domain= + +From xCAT 2.8, multiple domains is supported in the cluster. Update the +networks table definition. :: + + lsdef -t network -l + chdef -t network -o ddnsdomain= + +Update the Provision Environment +-------------------------------- + +Determine if the Management node is defined in the database, assuming it was +done correctly using xcatconfig -m, by running: :: + + lsdef __mgmtnode + +If it exists, then use the return name and do the following: + + - Remove the MN from DNS configuration :: + + makedns -d + + - Remove the MN from the DHCP configuration :: + + makedns -d + + - Remove the MN from the conserver configuration :: + + makedns -d + + - Change the MN name in the xCAT database :: + + chdef -t node -o -n + + - Add the new MN to DNS :: + + makedns -n + + - Add the MN to dhcp :: + + makedhcp -a + + - Add the MN to conserver :: + + makeconservercf + +Update the genesis packages +--------------------------- + +Run ``mknb `` after changing the ip of MN. + diff --git a/docs/source/advanced/cluster_maintenance/service_node/changing_hostname_ip.rst b/docs/source/advanced/cluster_maintenance/service_node/changing_hostname_ip.rst new file mode 100644 index 000000000..faffe3cbe --- /dev/null +++ b/docs/source/advanced/cluster_maintenance/service_node/changing_hostname_ip.rst @@ -0,0 +1,60 @@ +Changing the Hostname/IP address +================================ + +Change compute node definition relevant to the service node +----------------------------------------------------------- + +Change the settings in database. Below shows a method to find out where the old +IP address settings (take 10.6.0.1 as a example) are used in Hierarchy +environment. + +* Query the old attribute :: + + lsdef -t node -l | grep "10.6.0.1" + # below is output of the above command. We can find out that nfsserver + # and servicenode are using the old IP address setting. + nfsserver=10.6.0.1 + servicenode=10.6.0.1 + + +* Query the nodes whose nfsserver is 10.6.0.1 :: + + lsdef -w nfsserver==10.6.0.1 + # below is output of the above command + cn1 (node) + cn2 (node) + cn3 (node) + cn4 (node) + +* Change the nfsserver address for cn1,cn2,cn3,cn4 by running the following + command: :: + + chdef -t node cn1-cn4 nfsserver= + +Database Connection Changes +--------------------------- + +Granting or revoking access privilege in the database for the service node. + +* For mysql, please refer to :ref:`grante_revoke_mysql_access_label`. +.. There is no procedure in old document on sourceforge for postgress to + grant or revoke the access privilege for service node. + +* For postgress, please refer to `TODO `_. + +Update Provision Environment on Service Node +-------------------------------------------- + +If you are using service nodes to install the nodes and using ``/etc/hosts`` +for hostname resolution, you need to copy the new ``/etc/hosts`` from the +management node to the service nodes, then run ``makedns -n`` on the service +nodes. For example: :: + + xdcp /etc/hosts /etc/hosts + xdsh makedns -n + +Reinstall the nodes to pick up all changes :: + + nodeset osimage= + +Then use your normal command to install the nodes like rinstall, rnetboot, etc. diff --git a/docs/source/advanced/cluster_maintenance/service_node/index.rst b/docs/source/advanced/cluster_maintenance/service_node/index.rst new file mode 100644 index 000000000..bf5a4e05d --- /dev/null +++ b/docs/source/advanced/cluster_maintenance/service_node/index.rst @@ -0,0 +1,7 @@ +Service Node +============ + +.. toctree:: + :maxdepth: 2 + + changing_hostname_ip.rst diff --git a/docs/source/advanced/docker/dockerized_xcat/run_xcat_in_docker_compose.rst b/docs/source/advanced/docker/dockerized_xcat/run_xcat_in_docker_compose.rst index b934a0ce8..5a21e83d8 100644 --- a/docs/source/advanced/docker/dockerized_xcat/run_xcat_in_docker_compose.rst +++ b/docs/source/advanced/docker/dockerized_xcat/run_xcat_in_docker_compose.rst @@ -147,9 +147,10 @@ Known Issues ------------ .. [1] -When you start up xCAT Docker container, you might see an error message at the end of the output like: :: - Couldn't connect to Docker daemon at http+unix://var/run/docker.sock - is it running? If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.` +When you start up xCAT Docker container, you might see an error message at the end of the output like :: + + Couldn't connect to Docker daemon at http+unix://var/run/docker.sock - is it running? If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable. You can ignore it, the container has already been running. It is a Docker bug `#1214 `_ diff --git a/docs/source/advanced/docker/lifecycle_management.rst b/docs/source/advanced/docker/lifecycle_management.rst index 100c71969..2943bd75f 100644 --- a/docs/source/advanced/docker/lifecycle_management.rst +++ b/docs/source/advanced/docker/lifecycle_management.rst @@ -56,17 +56,20 @@ The otherpkglist file should contain the following: At the time of this writing (February 2016), docker package is not available for **ppc64el** architecture from docker.org. You can follow instructions below on how to manually download and install it. -* Download docker engine for ppc64el +* Download docker engine for ppc64el: + :: wget http://launchpadlibrarian.net/251622081/docker.io_1.10.3-0ubuntu4_ppc64el.deb -O /install/docker_ppc64el/docker.io_1.10.3-0ubuntu4_ppc64el.deb -* Configure **otherpkgdir** like this +* Configure **otherpkgdir** like this: + :: otherpkgdir=/install/docker_ppc64el -* The **otherpkglist** file should be +* The **otherpkglist** file should be: + :: # cat /install/custom/ubuntu/ubuntu_docker.pkglist @@ -226,16 +229,19 @@ If things go wrong: * After dockerhost node boots, check contents of **/var/log/xcat/xcat.log** file on the dockerhost for errors. * Verify **nicname** specified in **Preparing setup trust connection for docker service and create docker network object** section exists on the docker host. Depending on the version of Ubuntu OS and host architecture, it could be **eth0**, or **em1**, or **eno1**, or **enp0s1**. Verify by running on the dockerhost + :: ip addr show dev -* Run **ps -ef | grep docker** to verify docker engine is running with configured options. It should look something like +* Run **ps -ef | grep docker** to verify docker engine is running with configured options. It should look something like + :: root 3703 1 0 Apr15 ? 00:12:28 /usr/bin/docker daemon -H unix:///var/run/docker.sock -H tcp://host01:2375 --tls --tlscacert=/root/.docker/ca-cert.pem --tlscert=/root/.docker/dockerhost-cert.pem --tlskey=/root/.docker/dockerhost-cert.pem --tlsverify=true --raw-logs -If the output is missing some options, verify that file **/lib/systemd/system/docker.service** contains the following lines +If the output is missing some options, verify that file **/lib/systemd/system/docker.service** contains the following lines + :: EnvironmentFile=-/etc/default/docker diff --git a/docs/source/advanced/domain_name_resolution/domain_name_resolution.rst b/docs/source/advanced/domain_name_resolution/domain_name_resolution.rst index e5b9ddd12..acf30517d 100644 --- a/docs/source/advanced/domain_name_resolution/domain_name_resolution.rst +++ b/docs/source/advanced/domain_name_resolution/domain_name_resolution.rst @@ -193,7 +193,7 @@ Once **/etc/hosts** is populated with all of the nodes' hostnames and IP address makedns -n -When the **/etc/resolv.conf** files for the compute nodes are created the value of the **nameserver** in /etc/resolv.conf is gotten from **site.nameservers** or **networks.nameservers** if it's specified. :: +When the **/etc/resolv.conf** files for the compute nodes are created the value of the **nameserver** in /etc/resolv.conf is gotten from **site.nameservers** or **networks.nameservers** if it's specified. For example: :: diff --git a/docs/source/advanced/hamn/high_available_management_node.rst b/docs/source/advanced/hamn/high_available_management_node.rst index e6bb3c383..4375d553b 100644 --- a/docs/source/advanced/hamn/high_available_management_node.rst +++ b/docs/source/advanced/hamn/high_available_management_node.rst @@ -55,7 +55,7 @@ The combinations of data synchronization mechanism and manual/automatic failover |Automatic Failover | 4 | **5** | **6** | +-------------------+-------------------------+-----------------+--------------+ -Option 1, :ref:`setup_ha_mgmt_node_with_raid1_and disks_move` +Option 1, :ref:`setup_ha_mgmt_node_with_raid1_and_disks_move` Option 2, :ref:`setup_ha_mgmt_node_with_shared_data` diff --git a/docs/source/advanced/hamn/setup_ha_mgmt_node_with_raid1_and_disks_move.rst b/docs/source/advanced/hamn/setup_ha_mgmt_node_with_raid1_and_disks_move.rst index 806712b30..895775f5e 100644 --- a/docs/source/advanced/hamn/setup_ha_mgmt_node_with_raid1_and_disks_move.rst +++ b/docs/source/advanced/hamn/setup_ha_mgmt_node_with_raid1_and_disks_move.rst @@ -1,4 +1,4 @@ -.. _setup_ha_mgmt_node_with_raid1_and disks_move: +.. _setup_ha_mgmt_node_with_raid1_and_disks_move: Setup HA Mgmt Node With RAID1 and disks move ============================================ diff --git a/docs/source/advanced/hierarchy/databases/mysql_configure.rst b/docs/source/advanced/hierarchy/databases/mysql_configure.rst index b830760b4..a7404c2b6 100644 --- a/docs/source/advanced/hierarchy/databases/mysql_configure.rst +++ b/docs/source/advanced/hierarchy/databases/mysql_configure.rst @@ -24,6 +24,8 @@ where the /tmp/servicenodes contains a host per line: :: **While not recommended**, if you wish to manually migrate your xCAT database, see the following documentation: `Manually set up MySQL `_ +.. _grante_revoke_mysql_access_label: + Granting/Revoking access to the database for Service Node Clients ----------------------------------------------------------------- diff --git a/docs/source/advanced/hierarchy/databases/mysql_remove.rst b/docs/source/advanced/hierarchy/databases/mysql_remove.rst index f00fbad56..53cc15e71 100644 --- a/docs/source/advanced/hierarchy/databases/mysql_remove.rst +++ b/docs/source/advanced/hierarchy/databases/mysql_remove.rst @@ -12,7 +12,7 @@ If you no longer want to use MySQL/MariaDB to maintain ``xcatdb``, and like to s XCATBYPASS=1 restorexCATdb -p ~/xcat-dbback -* Change to PostgreSQL, please following documentation: :doc:`/guides/admin-guides/large_clusters/databases/postgres_install` +* Change to PostgreSQL, please following documentation: :doc:`/advanced/hierarchy/databases/postgres_install` * Change back to default xCAT database, SQLite (**Note**: xCAT Hierarchy cluster will no longer work) diff --git a/docs/source/advanced/hierarchy/provision/diskful_sn.rst b/docs/source/advanced/hierarchy/provision/diskful_sn.rst index 924298c33..20813fd38 100644 --- a/docs/source/advanced/hierarchy/provision/diskful_sn.rst +++ b/docs/source/advanced/hierarchy/provision/diskful_sn.rst @@ -1,3 +1,6 @@ + +.. _setup_service_node_stateful_label: + Diskful (Stateful) Installation =============================== @@ -103,8 +106,8 @@ the build with fixes from RHEL6 team, once meet this problem, you need to manually select the SAS disk to be the first boot device and boots from the SAS disk. -Update Service Node Diskfull Image ----------------------------------- +Update Service Node Diskful Image +--------------------------------- To update the xCAT software on the Service Node: diff --git a/docs/source/advanced/index.rst b/docs/source/advanced/index.rst index 851788614..dacf235d0 100755 --- a/docs/source/advanced/index.rst +++ b/docs/source/advanced/index.rst @@ -22,5 +22,4 @@ Advanced Topics softlayer/index.rst switches/index.rst sysclone/index.rst - webservices/index.rst zones/index.rst diff --git a/docs/source/advanced/mixed_cluster/power/diskful.rst b/docs/source/advanced/mixed_cluster/power/diskful.rst index 423c0ceba..40f9d4cb3 100644 --- a/docs/source/advanced/mixed_cluster/power/diskful.rst +++ b/docs/source/advanced/mixed_cluster/power/diskful.rst @@ -44,6 +44,15 @@ Create a node definition for the x86_64 compute node, here is a sample: :: serialport=0 serialspeed=115200 +Verify the genesis packages: + +* **[RHEL/SLES]**: ``rpm -qa | grep -i genesis`` + +* **[Ubuntu]**: ``dpkg -l | grep -i genesis`` + +If missing, install the packages ``xCAT-genesis-base`` and ``xCAT-genesis-scripts`` from ``xcat-deps`` repository and run ``mknb `` to create the genesis network boot root image. + + Provision the node using the following commands: :: # The following prepares the boot files in /install and /tftpboot diff --git a/docs/source/advanced/mixed_cluster/support_matrix.rst b/docs/source/advanced/mixed_cluster/support_matrix.rst index 5e94e1c05..aa895ab0f 100644 --- a/docs/source/advanced/mixed_cluster/support_matrix.rst +++ b/docs/source/advanced/mixed_cluster/support_matrix.rst @@ -46,7 +46,7 @@ Notes: * The support statements refers to hardware control, operating system (os) provisioning, and general purpose system management where we do not see any obvious problems with the indicated combination. -* For diskless mixed cluster support, the initial diskless image must be created on a node running the target operating system version and architecture. see :ref:`Building_a_Stateless_Image_of_a_Different_Architecture_or_OS` for more details. +* For diskless mixed cluster support, the initial diskless image must be created on a node running the target operating system version and architecture. see :doc:`/advanced/mixed_cluster/building_stateless_images` for more details. .. rubric:: Footnotes diff --git a/docs/source/advanced/networks/infiniband/mlnxofed_ib_known_issue.rst b/docs/source/advanced/networks/infiniband/mlnxofed_ib_known_issue.rst index ef0ee44c6..c523de4fa 100644 --- a/docs/source/advanced/networks/infiniband/mlnxofed_ib_known_issue.rst +++ b/docs/source/advanced/networks/infiniband/mlnxofed_ib_known_issue.rst @@ -13,7 +13,7 @@ After you install mellanox derives in rhels7.2 successfully by xCAT, maybe you h Known Issue 2 ------------- -If you want to use ``--add-kernel-support`` attribute in sles12.1 and ppc64le scenario, you will find some dependency packages are not shipped by SLES Server DVDs, such like ``python-devel``, it's shipped in SDK DVDs. xCAT doesn't ship specific pkglist to support such scenario. If you have such requirement, please used ``otherpkglist`` and ``otherpkgs`` attributes to prepare dependency packages repository ahead. If you need help about ``otherpkglist`` and ``otherpkgs``attributes, please refer to :doc:`Add Additional Software Packages `. +If you want to use ``--add-kernel-support`` attribute in sles12.1 and ppc64le scenario, you will find some dependency packages are not shipped by SLES Server DVDs, such like ``python-devel``, it's shipped in SDK DVDs. xCAT doesn't ship specific pkglist to support such scenario. If you have such requirement, please used ``otherpkglist`` and ``otherpkgs`` attributes to prepare dependency packages repository ahead. If you need help about ``otherpkglist`` and ``otherpkgs`` attributes, please refer to :doc:`Add Additional Software Packages `. diff --git a/docs/source/advanced/networks/infiniband/switch_configuration.rst b/docs/source/advanced/networks/infiniband/switch_configuration.rst index b84d4a138..b1c6824bf 100644 --- a/docs/source/advanced/networks/infiniband/switch_configuration.rst +++ b/docs/source/advanced/networks/infiniband/switch_configuration.rst @@ -74,7 +74,7 @@ Configure xdsh for Mellanox Switch ---------------------------------- To run xdsh commands to the Mellanox Switch, you must use the --devicetype input flag to xdsh. In addition, for xCAT versions less than 2.8, you must add a configuration file, please see `Setup ssh connection to the Mellanox Switch`_ section. -For the Mellanox Switch the ``--devicetype`` is ``IBSwitch::Mellanox``. See :doc:`xdsh man page <../../../guides/admin-guides/references/man/xdsh.1.html>` for details. +For the Mellanox Switch the ``--devicetype`` is ``IBSwitch::Mellanox``. See :doc:`xdsh man page ` for details. Now you can run the switch commands from the mn using xdsh. For example: :: diff --git a/docs/source/advanced/restapi/restapi_resource/restapi_reference.rst b/docs/source/advanced/restapi/restapi_resource/restapi_reference.rst index aacfc0cf6..1953a18ba 100644 --- a/docs/source/advanced/restapi/restapi_resource/restapi_reference.rst +++ b/docs/source/advanced/restapi/restapi_resource/restapi_reference.rst @@ -1533,6 +1533,7 @@ Set the name attribute for policy 3. :: #curl -X PUT -k 'https://127.0.0.1/xcatws/policy/3?userName=root&userPW=cluster&pretty=1' -H Content-Type:application/json --data '{"name":"root"}' + POST - Create the policy {policyname}. DataBody: {attr1:v1,att2:v2...}. ``````````````````````````````````````````````````````````````````````` diff --git a/docs/source/advanced/restapi/restapi_setup/restapi_setup.rst b/docs/source/advanced/restapi/restapi_setup/restapi_setup.rst index da560ffd9..a2abb4498 100644 --- a/docs/source/advanced/restapi/restapi_setup/restapi_setup.rst +++ b/docs/source/advanced/restapi/restapi_setup/restapi_setup.rst @@ -3,7 +3,7 @@ Enable the HTTPS service for REST API To improve the security between the REST API client and server, enabling the HTTPS service on the xCAT MN is recommended. And the REST API client should use the 'https' to access web server instead of the 'http'. -* **[RHEL6 (x86_64/ppc64) and RHEL5 (x86_64)]** :: +* **[RHEL6/7 (x86_64/ppc64) and RHEL5 (x86_64)]** :: yum install mod_ssl service httpd restart @@ -16,7 +16,7 @@ To improve the security between the REST API client and server, enabling the HTT rpm -e --nodeps httpd.ppc64 rpm -i httpd.ppc mod_ssl.ppc -* **[SLES10/11 (x86_64/ppc64)]** :: +* **[SLES10/11/12 (x86_64/ppc64)]** :: a2enmod ssl a2enflag SSL diff --git a/docs/source/advanced/sysclone/sysclone.rst b/docs/source/advanced/sysclone/sysclone.rst index 8801fd7a1..5aa301f80 100644 --- a/docs/source/advanced/sysclone/sysclone.rst +++ b/docs/source/advanced/sysclone/sysclone.rst @@ -40,7 +40,7 @@ This document describes how to install and configure a template node (called gol Prepare the xCAT Management Node for Support Sysclone ````````````````````````````````````````````````````` -How to configure xCAT management node please refer to section :ref:`Install Guides ` +How to configure xCAT management node please refer to section :ref:`install_guides` For support Sysclone, we need to install some extra rpms on management node and the golden client. diff --git a/docs/source/conf.py b/docs/source/conf.py index 3e3d82ae7..b5b6350b3 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -76,7 +76,42 @@ language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = [] +# +# Adding a pattern or a file on this list will still make file available in the documentation, +# but will eliminate the warning message "document isn't included in any toctree" +# However, some files that generate such warning contain labels being referred to from other files, +# if put on the exclude_patters list, such labels are not visible. The commented out files in the +# exclude_patters list below, are such files. They generate a warning, but contain reference labels. +exclude_patterns = ['guides/install-guides/common_sections.rst', + '**manage_clusters/common/deployment/*.rst', + '**manage_clusters/common/discover/**', + '**manage_clusters/common/management/**', + '**manage_clusters/common/parallel_cmd.rst', + '**manage_clusters/common/updatenode.rst', + '**manage_clusters/common/kvm/manage_vm.rst', + '**manage_clusters/common/management.rst', + '**ppc64le/discovery/config_environment.rst', + '**ppc64le/discovery/pbmc_discovery.rst', + '**ppc64le/discovery/pbmc_discovery_with_bmcdiscover.rst', + '**ppc64le/discovery/pbmc_discovery_with_lsslp.rst', + '**ppc64le/discovery/schedule_environment.rst', + '**ppc64le/discovery/standard_cn_definition.rst', + '**ppc64le/diskless/customize_image/cfg_partition.rst', + '**ppc64le/diskless/customize_image/raid_cfg.rst', + #'**chain/create_image_for_runimage.rst' + #'**hamn/setup_ha_mgmt_node_with_drbd_pacemaker_corosync.rst' + #'**hamn/setup_ha_mgmt_node_with_raid1_and_disks_move.rst' + #'**hamn/setup_ha_mgmt_node_with_shared_data.rst', + #'**hamn/setup_xcat_high_available_management_node_in_softlayer.rst', + '**hierarchy/databases/postgres_tips.rst', + '**hierarchy/define_and_install_compute_node.rst', + #'**hierarchy/define_service_node.rst', + '**networks/getadapter.rst' + #'**networks/vlan/index.rst', + #'**networks/vlan/vlan.rst', + #'**license/xcat_corporate_contributor_license_agreement.rst', + #'**license/xcat_individual_contributor_license_agreement.rst' + ] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -145,7 +180,7 @@ else: # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ['_static'] +#html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied diff --git a/docs/source/developers/doc_guidelines.rst b/docs/source/developers/doc_guidelines.rst deleted file mode 100644 index a91d0f23e..000000000 --- a/docs/source/developers/doc_guidelines.rst +++ /dev/null @@ -1,255 +0,0 @@ -Guidelines for xCAT Documentation -================================= -The following guidelines should be followed when making changes to the xCAT documentation to help create consistency in the documentation. - -Document Structure ------------------- - -Section Structure -````````````````` - -xCAT doc page may have 4 levels of title at most: :: - - The First Title - =============== - - The Second Title - ---------------- - - The Third Title - ``````````````` - - The Forth Title - ''''''''''''''' - -List Structure -`````````````` - -Bullet Lists -'''''''''''' - -* Bullet one - - The Content. -* Bullet Two - - The Content. - -:: - - * Bullet one - The Content. - * Bullet Two - The Content. - -Enumerated List -''''''''''''''' - -1. Item 1 - - a) item a - b) item b - -2. Item 2 - - a) item a - -:: - - 1. Item 1 - a) item a - b) item b - 2. Item 2 - a) item a - -Hyperlinks -> Internal Links -> External Links ----------------------------------------------- - -Add links to refer other web page is a very common way in writting document, it's very helpful to reduce the doc duplication and make doc to be easy to understand. Following are several ways to add a link in the xCAT documentation. - -* **Add an Internal Link to ``Customized Link Target``** - - ``Customized Link Target`` means a user defined **Link Target**. - -.. _my_link_target: - - Define a **Link Target** named ``my_link_target``: :: - - .. _my_link_target: - - **Customized Link Target** - - This part of content is a link target which can be linked by other content. - -.. - - Link to the customized link target ``my_link_target`` :ref:`my link `: :: - - Link to the customized link target ``my_link_target`` :ref:`my link ` - -.. - - ``Usage:`` This method is used to add a **Link Target** in any page that can be referred by any other pages. - -* **Add an Internal Link to Current Page** - - Link to an internal section in current page: `Guidelines for xCAT Documentation`_: :: - - Link to an internal section in current page: `Guidelines for xCAT Documentation`_ - -.. - - ``Usage:`` Every title of a section is an auto-generated 'link target', so you can use it directly. But it's only available inside the current page. - -* **Add an Internal Link to Other Page via File Path** - - Link to page ``http://server/overview/suport_list.html`` with **absolute file path** :doc:`support list `: :: - - Link to page ``http://server/overview/suport_list.html`` with **absolute file path** :doc:`support list ` - -.. - - Link to page ``http://server/overview/suport_list.html`` with **relative file path** :doc:`support list <../overview/support_list>`: :: - - Link to page ``http://server/overview/suport_list.html`` with **relative file path** :doc:`support list <../overview/support_list>` - -.. - - ``Usage:`` When you want to link to another whole page but don't want to make a ``Customized Link Target`` in that source page, you can use the file path to link it directly. - -* **Add an External Link** - - Link to an external web page: `google `_: :: - - Link to an external web page: `google `_ - -.. - - ``Usage:`` When you want to link to a page which does not belong to xCAT documentation. - - ``Note:`` The ``https://`` keyword must be added before the web page URL. - -* **Add a Link with Explicit URL Displayed** - - Link to http://www.google.com: :: - - Link to http://www.google.com - -.. - - ``Usage:`` Make a link and display the URL. - - -Add OS or ARCH Specific Contents --------------------------------- - -When writing a common xCAT doc, we always encounter the case that certain small part of content needs to be OS or ARCH specific. In this case, please use the following format to add specific branches. - -The keyword in the **[]** can be an OS name or ARCH name, or any name which can distinguish the content from other part. - -The valid keyword includes: **RHEL**, **SLES**, **UBUNTU**, **CENTOS**, **X86_64**, **PPC64**, **PPC64LE**. If the keyword is an OS, it can be postfixed with an OS version e.g. RHEL7. - -* **[RHEL7]** - - This part of description is for [rh7] specific. - -* **[SLES]** - - This part of description is for [sles] specific. - -* **[PPC64LE]** - - This part of description is for [ppc64le] specific. - -:: - - * **[RHEL7]** - - This part of description is for [rh7] specific. - - -Miscellaneous -------------- - -Add a Comment -````````````` - -.. Try the comment - -The sentence started with ``..`` will be a comment that won't be displayed in the doc. :: - - .. This is a comment - -Add Literal Block -````````````````` - -If you want to add a paragraph of code or something that don't want to be interpreted by browser: :: - - If you want to add a paragraph of code or something that don't want to be interpreted by browser: :: - #lsdef node1 - #tabdump - -Decorate Word -````````````` - -If you want to display one or several words to be ``Literal Word``: :: - - If you want to display one or several words to be ``Literal Word`` - -If you want to make a **strong emphasis** of the word: :: - - If you want to make a **strong emphasis** of the word: - -Add a Table -``````````` - -Add a table in the doc: - -+------------+------------+-----------+ -| Header 1 | Header 2 | Header 3 | -+============+============+===========+ -| body row 1 | column 2 | column 3 | -+------------+------------+-----------+ -| body row 2 | Cells may span columns.| -+------------+------------+-----------+ -| body row 3 | Cells may | - Cells | -+------------+ span rows. | - contain | -| body row 4 | | - blocks. | -+------------+------------+-----------+ - -:: - - +------------+------------+-----------+ - | Header 1 | Header 2 | Header 3 | - +============+============+===========+ - | body row 1 | column 2 | column 3 | - +------------+------------+-----------+ - | body row 2 | Cells may span columns.| - +------------+------------+-----------+ - | body row 3 | Cells may | - Cells | - +------------+ span rows. | - contain | - | body row 4 | | - blocks. | - +------------+------------+-----------+ - -Add Footnotes -````````````` - -This is the first example of footnotes [1]_. - -This is the second example of footnotes [2]_. - -:: - - This is the first example of footnotes [1]_. - This is the second example of footnotes [2]_. - - .. [1] First footnote - .. [2] Second footnote - ------------------------- - -.. [1] First footnote -.. [2] Second footnote - - - diff --git a/docs/source/developers/guides/docs/doc_guidelines.rst b/docs/source/developers/guides/docs/doc_guidelines.rst index a91d0f23e..3fe458d0c 100644 --- a/docs/source/developers/guides/docs/doc_guidelines.rst +++ b/docs/source/developers/guides/docs/doc_guidelines.rst @@ -62,10 +62,28 @@ Enumerated List 2. Item 2 a) item a +Include another file +-------------------- + +To add contents of a document file inside another file, use ``.. include::``. This is usefull when a common information needs to be displayed in multiple files, whithout the use of a hyperlink. +:: + + .. include:: config_common.rst + + +``Note:`` Do not put customized link targets, such as ``.. _my_link_taget:`` inside the file to be included. If you do, a warning for a duplicate label will be displayed during the documentation build process. + +Index file +---------- + +Index.rst files contain the ``.. toctree::`` tag. Files listed under that tag will have links to them displayed in the left side navigation area. If a documentation file does not wish to be accessbile from the navigation area, do not list it under the ``.. toctree::``. + +``Note:`` If a file is not listed under the ``.. toctree::`` it might generate a warning during the documentation build ``WARNING: document isn't included in any toctree``. To eliminate such warning, add the file to the ``exclude_patterns`` list in the ``docs/source/conf.py`` file. However, do not add a file to the ``exclude_patterns`` list if it contains a customized link target, such as ``.. _my_link_taget:``. This link target will not be visible to other files and a ``WARNING: undefined label:`` will be displayed during the documentation build. + Hyperlinks -> Internal Links -> External Links ---------------------------------------------- -Add links to refer other web page is a very common way in writting document, it's very helpful to reduce the doc duplication and make doc to be easy to understand. Following are several ways to add a link in the xCAT documentation. +Add links to refer other web page is a very common way in writting document, it's very helpful to reduce the doc duplication and make docs easy to understand. Following are several ways to add a link in the xCAT documentation. * **Add an Internal Link to ``Customized Link Target``** @@ -85,7 +103,7 @@ Add links to refer other web page is a very common way in writting document, it Link to the customized link target ``my_link_target`` :ref:`my link `: :: - Link to the customized link target ``my_link_target`` :ref:`my link ` + :ref:`my link ` .. @@ -95,7 +113,7 @@ Add links to refer other web page is a very common way in writting document, it Link to an internal section in current page: `Guidelines for xCAT Documentation`_: :: - Link to an internal section in current page: `Guidelines for xCAT Documentation`_ + `Guidelines for xCAT Documentation`_ .. @@ -103,15 +121,15 @@ Add links to refer other web page is a very common way in writting document, it * **Add an Internal Link to Other Page via File Path** - Link to page ``http://server/overview/suport_list.html`` with **absolute file path** :doc:`support list `: :: + Link to page `http://server/overview/suport_list.html` with **absolute file path** :: - Link to page ``http://server/overview/suport_list.html`` with **absolute file path** :doc:`support list ` + :doc:`support list ` .. - Link to page ``http://server/overview/suport_list.html`` with **relative file path** :doc:`support list <../overview/support_list>`: :: + Link to page `http://server/overview/suport_list.html` with **relative file path** :: - Link to page ``http://server/overview/suport_list.html`` with **relative file path** :doc:`support list <../overview/support_list>` + :doc:`support list <../overview/support_list>` .. @@ -121,7 +139,7 @@ Add links to refer other web page is a very common way in writting document, it Link to an external web page: `google `_: :: - Link to an external web page: `google `_ + `google `_ .. @@ -133,7 +151,7 @@ Add links to refer other web page is a very common way in writting document, it Link to http://www.google.com: :: - Link to http://www.google.com + http://www.google.com .. diff --git a/docs/source/guides/admin-guides/basic_concepts/global_cfg/index.rst b/docs/source/guides/admin-guides/basic_concepts/global_cfg/index.rst index 37c209201..052836083 100644 --- a/docs/source/guides/admin-guides/basic_concepts/global_cfg/index.rst +++ b/docs/source/guides/admin-guides/basic_concepts/global_cfg/index.rst @@ -10,7 +10,7 @@ Database Attributes ------------------- * excludenodes: - A set of comma separated nodes and/or groups that would automatically be subtracted from any noderange, it can be used for excluding some failed nodes from any xCAT command. See :doc:`noderange ` for details on supported formats. + A set of comma separated nodes and/or groups that would automatically be subtracted from any noderange, it can be used for excluding some failed nodes from any xCAT command. See :doc:`noderange ` for details on supported formats. * nodestatus: If set to ``n``, the ``nodelist.status`` column will not be updated during the node deployment, node discovery and power operations. The default is to update. diff --git a/docs/source/guides/admin-guides/manage_clusters/common/deployment/create_img.rst b/docs/source/guides/admin-guides/manage_clusters/common/deployment/create_img.rst index 24b57eed3..c07b65f78 100644 --- a/docs/source/guides/admin-guides/manage_clusters/common/deployment/create_img.rst +++ b/docs/source/guides/admin-guides/manage_clusters/common/deployment/create_img.rst @@ -87,7 +87,7 @@ You can create/modify an osimage definition easily based on the default osimage For example, if you need to change the osimage name to your favorite name, this command may be helpful: :: - lsdef -t osimage -z rhels6.2-x86_64-install-compute | sed 's/^[^ ]\+:/mycomputeimage:/' | mkdef -z + chdef -t osimage rhels6.2-x86_64-install-compute -n rhels6.2_myimage diff --git a/docs/source/guides/admin-guides/manage_clusters/common/deployment/deploy_os.rst b/docs/source/guides/admin-guides/manage_clusters/common/deployment/deploy_os.rst index 2fca4b8de..bd7567600 100644 --- a/docs/source/guides/admin-guides/manage_clusters/common/deployment/deploy_os.rst +++ b/docs/source/guides/admin-guides/manage_clusters/common/deployment/deploy_os.rst @@ -1,5 +1,3 @@ -.. _deploy_os: - Initialize the Compute for Deployment ===================================== @@ -34,5 +32,3 @@ For **x86_64 servers**, those two operations need two independent commands. rpower reset - - diff --git a/docs/source/guides/admin-guides/manage_clusters/common/deployment/install_new_kernel.rst b/docs/source/guides/admin-guides/manage_clusters/common/deployment/install_new_kernel.rst index 535ecb613..cd1df8fc3 100644 --- a/docs/source/guides/admin-guides/manage_clusters/common/deployment/install_new_kernel.rst +++ b/docs/source/guides/admin-guides/manage_clusters/common/deployment/install_new_kernel.rst @@ -79,4 +79,4 @@ The default driver list: :: Note: With this approach, xCAT will search for the drivers in the rootimage. You need to make sure the drivers have been included in the rootimage before generating the initrd. You can install the drivers manually in an existing rootimage (using chroot) and run genimage again, or you can use a postinstall script to install drivers to the rootimage during your initial genimage run. -Use the driver rpm package to add new drivers from rpm packages to the diskless initrd.Refer to the :doc:`cfg_second_adapter.rst` for details. +Use the driver rpm package to add new drivers from rpm packages to the diskless initrd. Refer to the :doc:`/guides/admin-guides/manage_clusters/ppc64le/diskless/customize_image/cfg_second_adapter` for details. diff --git a/docs/source/guides/admin-guides/manage_clusters/common/deployment/prepostscripts/post_script.rst b/docs/source/guides/admin-guides/manage_clusters/common/deployment/prepostscripts/post_script.rst index fbe5f7af3..05f1c432b 100644 --- a/docs/source/guides/admin-guides/manage_clusters/common/deployment/prepostscripts/post_script.rst +++ b/docs/source/guides/admin-guides/manage_clusters/common/deployment/prepostscripts/post_script.rst @@ -218,6 +218,8 @@ Example of mypostscript :: The mypostscript file is generated according to the mypostscript.tmpl file. +.. _Using-the-mypostscript-template-label: + Using the mypostscript template ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/source/guides/admin-guides/manage_clusters/common/deployment/syncfile/syncfile_synclist_file.rst b/docs/source/guides/admin-guides/manage_clusters/common/deployment/syncfile/syncfile_synclist_file.rst index e3c13a2d4..6ce471eb3 100644 --- a/docs/source/guides/admin-guides/manage_clusters/common/deployment/syncfile/syncfile_synclist_file.rst +++ b/docs/source/guides/admin-guides/manage_clusters/common/deployment/syncfile/syncfile_synclist_file.rst @@ -91,7 +91,7 @@ If the above syncfile is performed by the **updatenode/xdcp** commands, or perfo Support nodes in synclist file -~~~~~~~~~~~~~~~~~ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Note: From xCAT 2.9.2 on AIX and from xCAT 2.12 on Linux, xCAT support a new format for syncfile. The new format is :: diff --git a/docs/source/guides/admin-guides/manage_clusters/common/updatenode.rst b/docs/source/guides/admin-guides/manage_clusters/common/updatenode.rst index 4eeb32798..d9bcd36fd 100644 --- a/docs/source/guides/admin-guides/manage_clusters/common/updatenode.rst +++ b/docs/source/guides/admin-guides/manage_clusters/common/updatenode.rst @@ -94,7 +94,7 @@ If you need to, you can also pass arguments to your scripts: :: mypostscript template for ``updatenode`` -You can customize what attributes you want made available to the post*script, using the shipped mypostscript.tmpl file :ref:`Using-the-mypostscript-template`. +You can customize what attributes you want made available to the postscript, using the shipped mypostscript.tmpl file :ref:`Using-the-mypostscript-template-label`. Synchronize new/updated configuration files ------------------------------------------- diff --git a/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/config_environment.rst b/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/config_environment.rst index 95c71c100..79791d155 100644 --- a/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/config_environment.rst +++ b/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/config_environment.rst @@ -1,3 +1,4 @@ + Configure xCAT -------------- @@ -15,8 +16,6 @@ Run the following command to add networks in ``networks`` table if there are no makenetworks -.. _Setup-dhcp: - Setup DHCP `````````` diff --git a/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/switch_discovery.rst b/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/switch_discovery.rst index adc63b226..ad2c60a31 100644 --- a/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/switch_discovery.rst +++ b/docs/source/guides/admin-guides/manage_clusters/ppc64le/discovery/switch_discovery.rst @@ -12,6 +12,8 @@ Switch info:: Switch IP Address: 10.0.201.1 Switch port for Compute Node: port0 +.. _Setup-dhcp: + .. include:: config_environment.rst Predefined Nodes @@ -19,8 +21,8 @@ Predefined Nodes In order to differentiate one node from another, the admin needs to predefine node in xCAT database based on the switches information. This consists of two parts: -#. :ref:`predefined_switches_label` -#. :ref:`predefined_server_nodes_label` +#. :ref:`Predefine Switches ` +#. :ref:`Predefine Server Node ` .. _predefined_switches_label: diff --git a/docs/source/guides/admin-guides/manage_clusters/ppc64le/diskful/deploy_os.rst b/docs/source/guides/admin-guides/manage_clusters/ppc64le/diskful/deploy_os.rst index be4ba945c..129e60c13 100644 --- a/docs/source/guides/admin-guides/manage_clusters/ppc64le/diskful/deploy_os.rst +++ b/docs/source/guides/admin-guides/manage_clusters/ppc64le/diskful/deploy_os.rst @@ -1,2 +1,3 @@ +.. _deploy_os: .. include:: ../../common/deployment/deploy_os.rst diff --git a/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/FAQ.rst b/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/FAQ.rst index f11b0a282..32686df62 100644 --- a/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/FAQ.rst +++ b/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/FAQ.rst @@ -45,6 +45,31 @@ rpower fails with "Error: internal error: process exited while connecting to mon Then reboot the hypervisor... +rmigrate fails with "Error: libvirt error code: 38, message: unable to connect to server at 'c910f05c35:49152': No route to host." +---------------------------------------------------------------------------------------------------------------------------------- + + **Issue**: :: + + #rmigrate vm1 kvmhost2 + vm1: Error: libvirt error code: 38, message: unable to connect to server at 'kvmhost2:49152': No route to host: Failed migration of vm1 from kvmhost1 to kvmhost2 + + **Solution**: + Usually caused by active firewall. To disable the firewall issue: :: + + systemctl disable firewalld + +rmigrate fails with "Error: 38, message: failed to create directory '': File exists: Unknown issue libvirt error code." +--------------------------------------------------------------------------------------------------------------------------------- + + **Issue**: :: + + #rmigrate vm1 kvmhost2 + vm1: Error: 38, message: failed to create directory '': File exists: Unknown issue libvirt error code. + + **Solution**: + Ususally happens when `nfs:` is specified for vmstorage attribute but that NFS directory is no longer mounted. Make sure the directory /var/lib/xcat/pools is empty on the destination kvmhost. + + Error: Cannot communicate via libvirt to kvmhost1 ------------------------------------------------- diff --git a/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/powerKVM.rst b/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/powerKVM.rst index a98c199f4..239b69b08 100644 --- a/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/powerKVM.rst +++ b/docs/source/guides/admin-guides/manage_clusters/ppc64le/virtual_machines/powerKVM.rst @@ -6,7 +6,7 @@ Provision Hypervisor with PowerKVM ---------------------------------- -Please follow the ``Diskful Installation Documentation`` :ref:`Diskful Installation ` to provision kvm hypervisor with PowerKVM, several customization steps should be taken into consideration. +Please follow the :ref:`Diskful Installation ` to provision kvm hypervisor with PowerKVM, several customization steps should be taken into consideration. To demonstrate the brief steps on hypervisor provision, take **ibm-powerkvm-3.1.0.0-39.0-ppc64le-gold-201511041419.iso** for example here: diff --git a/docs/source/guides/admin-guides/references/man1/buildkit.1.rst b/docs/source/guides/admin-guides/references/man1/buildkit.1.rst index 0594537d0..20dd710e6 100644 --- a/docs/source/guides/admin-guides/references/man1/buildkit.1.rst +++ b/docs/source/guides/admin-guides/references/man1/buildkit.1.rst @@ -23,7 +23,7 @@ SYNOPSIS To build a new Kit -\ **buildkit**\ [\ **-V | -**\ **-verbose]**\ \ *subcommand*\ [\ *kit_name*\ ] [\ *repo_name*\ |\ **all**\ ] [\ **-l | -**\ **-kitloc**\ \ *kit_location*\ ] +\ **buildkit**\ [\ **-V | -**\ **-verbose]**\ \ *subcommand*\ [\ *kit_name*\ ] [\ *repo_name*\ | \ **all**\ ] [\ **-l | -**\ **-kitloc**\ \ *kit_location*\ ] To add packages to an existing Kit. @@ -314,7 +314,7 @@ EXAMPLES \ **buildkit listrepo**\ - \ **buildkit buildrepo all **\ + \ **buildkit buildrepo all**\ \ **buildkit buildtar**\ diff --git a/docs/source/guides/admin-guides/references/man1/geninitrd.1.rst b/docs/source/guides/admin-guides/references/man1/geninitrd.1.rst index b3c98d0e6..ffac5dd95 100644 --- a/docs/source/guides/admin-guides/references/man1/geninitrd.1.rst +++ b/docs/source/guides/admin-guides/references/man1/geninitrd.1.rst @@ -31,7 +31,7 @@ DESCRIPTION Generate the initrd for the osimage: \ **imagename**\ which is an xCAT object of \ *osimage*\ type. -\ **Diskfull Osimage**\ +\ **Diskful Osimage**\ If the \ **imagename**\ is a stateful one (The provmethod attribute for the osimage is 'install'), diff --git a/docs/source/guides/admin-guides/references/man1/getadapter.1.rst b/docs/source/guides/admin-guides/references/man1/getadapter.1.rst index 147d30426..d1046d6ca 100644 --- a/docs/source/guides/admin-guides/references/man1/getadapter.1.rst +++ b/docs/source/guides/admin-guides/references/man1/getadapter.1.rst @@ -29,7 +29,7 @@ DESCRIPTION *********** -Traditionally, network interfaces in Linux are enumerated as eth[0123…], but these names do not necessarily correspond to actual labels on the chassis. \ **getadapter**\ help customer to get predictable network device name and some other network adapter information before provision or network configuration. +Traditionally, network interfaces in Linux are enumerated as eth[0123...], but these names do not necessarily correspond to actual labels on the chassis. \ **getadapter**\ help customer to get predictable network device name and some other network adapter information before provision or network configuration. \ **getadapter**\ use genesis to collect network adapters information, so that mean it need to restart the target node. diff --git a/docs/source/guides/admin-guides/references/man1/getmacs.1.rst b/docs/source/guides/admin-guides/references/man1/getmacs.1.rst index 647b277f7..68c38c47b 100644 --- a/docs/source/guides/admin-guides/references/man1/getmacs.1.rst +++ b/docs/source/guides/admin-guides/references/man1/getmacs.1.rst @@ -41,7 +41,7 @@ blade specific: =============== -\ **getmacs**\ \ *noderange*\ [\ **-V**\ | \ **-**\ **-verbose**\ ] [\ **-d**\ ] [\ **-**\ **-arp**\ ] [\ **-i**\ \ *ethN*\ |\ *enN*\ ] +\ **getmacs**\ \ *noderange*\ [\ **-V**\ | \ **-**\ **-verbose**\ ] [\ **-d**\ ] [\ **-**\ **-arp**\ ] [\ **-i**\ \ *ethN*\ | \ *enN*\ ] diff --git a/docs/source/guides/admin-guides/references/man1/lsdef.1.rst b/docs/source/guides/admin-guides/references/man1/lsdef.1.rst index 2f4edb8ac..5e4bbe84d 100644 --- a/docs/source/guides/admin-guides/references/man1/lsdef.1.rst +++ b/docs/source/guides/admin-guides/references/man1/lsdef.1.rst @@ -26,6 +26,9 @@ SYNOPSIS [\ **-c | -**\ **-compress**\ ] [\ **-**\ **-osimage**\ ] [\ **-**\ **-nics**\ ] [[\ **-w**\ \ *attr*\ ==\ *val*\ ] [\ **-w**\ \ *attr*\ =~\ *val*\ ] ...] [\ *noderange*\ ] +\ **lsdef**\ [\ **-l | -**\ **-long**\ ] [\ **-a | -**\ **-all**\ ] [\ **-t**\ \ *object-types*\ ] [\ **-z | -**\ **-stanza**\ ] +[\ **-i**\ \ *attr-list*\ ] [\ **-**\ **-template**\ [\ *template-object-name*\ ]] + *********** DESCRIPTION @@ -33,7 +36,7 @@ DESCRIPTION This command is used to display xCAT object definitions which are stored -in the xCAT database. +in the xCAT database and xCAT object definition templates shipped in xCAT. ******* @@ -101,6 +104,12 @@ OPTIONS +\ **-**\ **-template**\ [\ *template-object-name*\ ] + + Show the object definition templates \ *template-object-name*\ shipped in xCAT. If no \ *template-object-name*\ is specified, all the object definition templates of the specified type \ **-t**\ \ *object-types*\ will be listed. Use \ **-a|-**\ **-all**\ option to list all the object definition templates. + + + \ **-**\ **-osimage**\ Show all the osimage information for the node. @@ -376,6 +385,42 @@ EXAMPLES +18. + + To list all the object definition templates shipped in xCAT. + + + .. code-block:: perl + + lsdef --template -a + + + + +19. + + To display the details of "node" object definition template "ppc64le-template" shipped in xCAT. + + + .. code-block:: perl + + lsdef -t node --template ppc64le-template + + + + +20. + + To list all the "node" object definition templates shipped in xCAT. + + + .. code-block:: perl + + lsdef -t node --template + + + + ***** FILES diff --git a/docs/source/guides/admin-guides/references/man1/lsve.1.rst b/docs/source/guides/admin-guides/references/man1/lsve.1.rst index bf71f3ac5..59c351f2b 100644 --- a/docs/source/guides/admin-guides/references/man1/lsve.1.rst +++ b/docs/source/guides/admin-guides/references/man1/lsve.1.rst @@ -66,13 +66,16 @@ OPTIONS \ **-t**\ Specify the \ **type**\ of the target object. Supported types: - \ **dc**\ - Data Center (For type of 'dc', all the elements belongs to the data - center will be listed.) - \ **cl**\ - Cluster - \ **sd**\ - Storage Domain (To get the status of Storage Doamin, show it from - \ *data center*\ it attached to. - \ **nw**\ - Network - \ **tpl**\ - Template + + + .. code-block:: perl + + B - Data Center (For type of 'dc', all the elements belongs to the data center will be listed.) + B - Cluster + B - Storage Domain (To get the status of Storage Doamin, show it from I it attached to. + B - Network + B - Template + diff --git a/docs/source/guides/admin-guides/references/man1/makentp.1.rst b/docs/source/guides/admin-guides/references/man1/makentp.1.rst index b67c1af83..34f143dc1 100644 --- a/docs/source/guides/admin-guides/references/man1/makentp.1.rst +++ b/docs/source/guides/admin-guides/references/man1/makentp.1.rst @@ -97,7 +97,7 @@ EXAMPLES .. code-block:: perl - setupntp -a + makentp -a @@ -108,7 +108,7 @@ FILES ***** -/opt/xcat/bin/setupntp +/opt/xcat/bin/makentp ******** diff --git a/docs/source/guides/admin-guides/references/man1/mkdef.1.rst b/docs/source/guides/admin-guides/references/man1/mkdef.1.rst index 353da0498..41084a288 100644 --- a/docs/source/guides/admin-guides/references/man1/mkdef.1.rst +++ b/docs/source/guides/admin-guides/references/man1/mkdef.1.rst @@ -21,7 +21,7 @@ SYNOPSIS \ **mkdef**\ [\ **-h | -**\ **-help**\ ] [\ **-t**\ \ *object-types*\ ] -\ **mkdef**\ [\ **-V | -**\ **-verbose**\ ] [\ **-t**\ \ *object-types*\ ] [\ **-o**\ \ *object-names*\ ] [\ **-z | -**\ **-stanza**\ ] [\ **-d | -**\ **-dynamic**\ ] [\ **-f | -**\ **-force**\ ] [[\ **-w**\ \ *attr*\ ==\ *val*\ ] [\ **-w**\ \ *attr*\ =~\ *val*\ ] ...] [\ *noderange*\ ] [\ *attr*\ =\ *val*\ [\ *attr*\ =\ *val...*\ ]] [\ **-u**\ \ **provmethod**\ ={\ **install**\ | \ **netboot**\ | \ **statelite**\ } \ **profile=**\ \ *xxx*\ [\ **osvers=**\ \ *value*\ ] [\ **osarch=**\ \ *value*\ ]] +\ **mkdef**\ [\ **-V | -**\ **-verbose**\ ] [\ **-t**\ \ *object-types*\ ] [\ **-**\ **-template**\ \ *template-object-name*\ ] [\ **-o**\ \ *object-names*\ ] [\ **-z | -**\ **-stanza**\ ] [\ **-d | -**\ **-dynamic**\ ] [\ **-f | -**\ **-force**\ ] [[\ **-w**\ \ *attr*\ ==\ *val*\ ] [\ **-w**\ \ *attr*\ =~\ *val*\ ] ...] [\ *noderange*\ ] [\ *attr*\ =\ *val*\ [\ *attr*\ =\ *val...*\ ]] [\ **-u**\ \ **provmethod**\ ={\ **install**\ | \ **netboot**\ | \ **statelite**\ } \ **profile=**\ \ *xxx*\ [\ **osvers=**\ \ *value*\ ] [\ **osarch=**\ \ *value*\ ]] *********** @@ -82,6 +82,12 @@ OPTIONS +\ **-**\ **-template**\ \ *template-object-name*\ + + Name of the xCAT shipped object definition template or an existing object, from which the new object definition will be created. The newly created object will inherit the attributes of the template definition unless the attribute is specified in the arguments of \ **mkdef**\ command. If there are a template and an existing object with the same name \ *template-object-name*\ , the tempalte object takes precedence over the existing object. For the details of xCAT shipped object definition templates, refer to the manpage of \ **-**\ **-template**\ option in lsdef(1)|lsdef.1. + + + \ **-V|-**\ **-verbose**\ Verbose mode. @@ -280,6 +286,30 @@ EXAMPLES +13. + + To create a PowerLE kvm node definition with the xCAT shipped template "ppc64lekvmguest-template". + + + .. code-block:: perl + + mkdef -t node cn1 --template ppc64lekvmguest-template ip=1.1.1.1 mac=42:3d:0a:05:27:0b vmhost=1.1.0.1 vmnics=br0 + + + + +14. + + To create a node definition from an existing node definition "cn1" + + + .. code-block:: perl + + mkdef -t node cn2 --template cn1 ip=1.1.1.2 mac=42:3d:0a:05:27:0c + + + + ***** FILES diff --git a/docs/source/guides/admin-guides/references/man1/packimage.1.rst b/docs/source/guides/admin-guides/references/man1/packimage.1.rst index 705880797..13510d4b1 100644 --- a/docs/source/guides/admin-guides/references/man1/packimage.1.rst +++ b/docs/source/guides/admin-guides/references/man1/packimage.1.rst @@ -62,7 +62,7 @@ OPTIONS \ **-a**\ Architecture (ppc64,x86_64,etc) -\ **-m**\ Method (default cpio) +\ **-m**\ Method (cpio,txc,squashfs, default is cpio) ************ diff --git a/docs/source/guides/admin-guides/references/man1/rmigrate.1.rst b/docs/source/guides/admin-guides/references/man1/rmigrate.1.rst index f119cf28d..d6b67dfcb 100644 --- a/docs/source/guides/admin-guides/references/man1/rmigrate.1.rst +++ b/docs/source/guides/admin-guides/references/man1/rmigrate.1.rst @@ -36,6 +36,8 @@ For zVM: \ **rmigrate**\ requests that a guest VM to be moved from the current hypervisor to another. It will request a live migration if possible. The vmstorage directory should be shared between the source and destination hypervisors. +Note: Make sure SELINUX is disabled and firewall is turned off on source and destination hypervisors. + For zVM: ======== @@ -97,17 +99,29 @@ This is used to determine the current host to migrate from. 1. To migrate kvm guest "kvm1" from hypervisor "hyp01" to hypervisor "hyp02", run: -\ **rmigrate**\ \ *kvm1*\ \ *hyp02*\ + +.. code-block:: perl + + rmigrate kvm1 hyp02 + 2. To migrate kvm guest "kvm1" to hypervisor "hyp02", which is already on host "hyp02", enter: -\ **rmigrate**\ \ *kvm1*\ \ *hyp02*\ + +.. code-block:: perl + + rmigrate kvm1 hyp02 + zVM specific: ============= -\ **rmigrate**\ \ *ihost123*\ destination=\ *pokdev62*\ + +.. code-block:: perl + + rmigrate ihost123 destination=pokdev62 + diff --git a/docs/source/guides/admin-guides/references/man1/rmkitcomp.1.rst b/docs/source/guides/admin-guides/references/man1/rmkitcomp.1.rst index 3c4ec9d47..675774440 100644 --- a/docs/source/guides/admin-guides/references/man1/rmkitcomp.1.rst +++ b/docs/source/guides/admin-guides/references/man1/rmkitcomp.1.rst @@ -29,7 +29,7 @@ DESCRIPTION *********** -The \ **rmkitcomp**\ command removes kit components from an xCAT osimage. All the kit component attribute values that are contained in the osimage will be removed, and the kit comoponent meta rpm and package rpm could be uninstalled by <-u|-**\ **-uninstall> option. +The \ **rmkitcomp**\ command removes kit components from an xCAT osimage. All the kit component attribute values that are contained in the osimage will be removed, and the kit comoponent meta rpm and package rpm could be uninstalled by \ **-u|-**\ **-uninstall**\ option. Note: The xCAT support for Kits is only available for Linux operating systems. diff --git a/docs/source/guides/admin-guides/references/man1/rscan.1.rst b/docs/source/guides/admin-guides/references/man1/rscan.1.rst index a3b615e53..9d6ff5082 100644 --- a/docs/source/guides/admin-guides/references/man1/rscan.1.rst +++ b/docs/source/guides/admin-guides/references/man1/rscan.1.rst @@ -35,7 +35,7 @@ The rscan command lists hardware information for each node managed by the hardwa For the management module of blade, if the blade server is a Flex system P node, the fsp belongs to the blade server also will be scanned. -For the KVM host, all the KVM guests on the specified KVM host will be scanned. Note: currently rscan can only get the information of the "disk" device on the kvm guest with the underlying source as a "file" on the KVM host. +For the KVM host, all the KVM guests on the specified KVM host will be scanned. Note: The first line of the output always contains information about the hardware control point. When using the rscan command to generate output for HMC or IVM hardware control points, it provides the FSPs and BPAs as part of the output. The only exception is the rscan -u flag which provides updates made hardware control point in the xCAT database. @@ -55,7 +55,7 @@ OPTIONS For the Flex system manager, both the blade server and fsp object of xCAT will be updated if the mpa and slot id are matched to the object which has been defined in the xCAT database. -For the KVM host, the information of the KVM guests which have been defined in xCAT database will be updated. +For KVM host, the information of the KVM guests which have been defined in xCAT database will be updated. Note: only the matched object will be updated. @@ -69,6 +69,8 @@ For KVM host, updates the information of the KVM guests which have been defined \ **-z**\ Stanza formated output. +Note: For KVM host, -z is not a valid option for rscan. + ************ RETURN VALUE @@ -311,39 +313,12 @@ Output is similar to: blade [SN#YL10JH184079] Matched To =>[cmm01node03] -8. To scan the KVM host "hyp01", list all the KVM guest information on the KVM host in stanza format and write the KVM guest information into xCAT database: +8. To scan the KVM host "hyp01", write the KVM guest information into xCAT database: .. code-block:: perl - rscan hyp01 -z -w - - -Output is similar to: - - -.. code-block:: perl - - kvm1 - arch=x86_64 - mac= - mgt=kvm - vmcpus=1 - vmhost=hyp01 - vmmemory=1024 - vmnicnicmodel=virtio - vmnics=virbr0 - vmstorage=/install/vms/kvm1.hda.qcow2 - kvm2 - arch=x86_64 - mac= - mgt=kvm - vmcpus=2 - vmhost=hyp01 - vmmemory=1024 - vmnicnicmodel=virtio - vmnics=virbr0 - vmstorage=/install/vms/kvm2.hda.qcow2 + rscan hyp01 -w 9. To update definitions of kvm guest, which is managed by hypervisor hyp01, enter: diff --git a/docs/source/guides/admin-guides/references/man1/unregnotif.1.rst b/docs/source/guides/admin-guides/references/man1/unregnotif.1.rst index b1ff299ca..a61c02d17 100644 --- a/docs/source/guides/admin-guides/references/man1/unregnotif.1.rst +++ b/docs/source/guides/admin-guides/references/man1/unregnotif.1.rst @@ -49,7 +49,7 @@ OPTIONS \ **-h | -help**\ Display usage message. -\ **-v | -version **\ Command Version. +\ **-v | -version**\ Command Version. \ **-V | -verbose**\ Verbose output. diff --git a/docs/source/guides/admin-guides/references/man1/updatenode.1.rst b/docs/source/guides/admin-guides/references/man1/updatenode.1.rst index 56a5c8b8a..55043ad8d 100644 --- a/docs/source/guides/admin-guides/references/man1/updatenode.1.rst +++ b/docs/source/guides/admin-guides/references/man1/updatenode.1.rst @@ -159,14 +159,18 @@ file. ospkgs postscript will normally remove all the existing rpm repositories before adding server:/install// /etc/passwd - /custom/mygroups -> /etc/group - /custom/myshadow -> /etc/shadow + /custom/mypasswd -> /etc/passwd + /custom/mygroups -> /etc/group + /custom/myshadow -> /etc/shadow Note: no order can be assumed by the order that the EXECUTE,EXECUTEALWAYS and APPEND clause fall in the synclist file. diff --git a/docs/source/guides/admin-guides/references/man5/auditlog.5.rst b/docs/source/guides/admin-guides/references/man5/auditlog.5.rst index 142d68d3a..d177660f8 100644 --- a/docs/source/guides/admin-guides/references/man5/auditlog.5.rst +++ b/docs/source/guides/admin-guides/references/man5/auditlog.5.rst @@ -27,11 +27,7 @@ DESCRIPTION *********** - -.. code-block:: perl - - Audit Data log. - +Audit Data log. ******************** diff --git a/docs/source/guides/admin-guides/references/man5/deps.5.rst b/docs/source/guides/admin-guides/references/man5/deps.5.rst index 4c61b66b7..1da97c43c 100644 --- a/docs/source/guides/admin-guides/references/man5/deps.5.rst +++ b/docs/source/guides/admin-guides/references/man5/deps.5.rst @@ -56,7 +56,7 @@ deps Attributes: \ **cmd**\ - Comma-seperated list of which operation this dependency applies to. + Comma-separated list of which operation this dependency applies to. diff --git a/docs/source/guides/admin-guides/references/man5/domain.5.rst b/docs/source/guides/admin-guides/references/man5/domain.5.rst index 90af85987..73cc78ebb 100644 --- a/docs/source/guides/admin-guides/references/man5/domain.5.rst +++ b/docs/source/guides/admin-guides/references/man5/domain.5.rst @@ -44,7 +44,7 @@ domain Attributes: \ **ou**\ - For an LDAP described machine account (i.e. Active Directory), the orginaztional unit to place the system. If not set, defaults to cn=Computers,dc=your,dc=domain + For an LDAP described machine account (i.e. Active Directory), the organizational unit to place the system. If not set, defaults to cn=Computers,dc=your,dc=domain diff --git a/docs/source/guides/admin-guides/references/man5/eventlog.5.rst b/docs/source/guides/admin-guides/references/man5/eventlog.5.rst index 8387bb43c..f75afb9de 100644 --- a/docs/source/guides/admin-guides/references/man5/eventlog.5.rst +++ b/docs/source/guides/admin-guides/references/man5/eventlog.5.rst @@ -104,11 +104,7 @@ eventlog Attributes: \ **rawdata**\ - - .. code-block:: perl - - The data that associated with the event. - + The data that associated with the event. diff --git a/docs/source/guides/admin-guides/references/man5/ipmi.5.rst b/docs/source/guides/admin-guides/references/man5/ipmi.5.rst index 5122a442c..88fe0488c 100644 --- a/docs/source/guides/admin-guides/references/man5/ipmi.5.rst +++ b/docs/source/guides/admin-guides/references/man5/ipmi.5.rst @@ -44,20 +44,17 @@ ipmi Attributes: \ **bmc**\ - The hostname of the BMC adapater. + The hostname of the BMC adapter. \ **bmcport**\ + In systems with selectable shared/dedicated ethernet ports, this parameter can be used to specify the preferred port. 0 means use the shared port, 1 means dedicated, blank is to not assign. + .. code-block:: perl - In systems with selectable shared/dedicated ethernet ports, - this parameter can be used to specify the preferred port. 0 - means use the shared port, 1 means dedicated, blank is to not - assign. - The following special cases exist for IBM System x servers: For x3755 M3 systems, 0 means use the dedicated port, 1 means diff --git a/docs/source/guides/admin-guides/references/man5/kvm_masterdata.5.rst b/docs/source/guides/admin-guides/references/man5/kvm_masterdata.5.rst index c22dd1b82..7ac2d011a 100644 --- a/docs/source/guides/admin-guides/references/man5/kvm_masterdata.5.rst +++ b/docs/source/guides/admin-guides/references/man5/kvm_masterdata.5.rst @@ -27,7 +27,7 @@ DESCRIPTION *********** -Persistant store for KVM plugin for masters +Persistent store for KVM plugin for masters ************************** diff --git a/docs/source/guides/admin-guides/references/man5/kvm_nodedata.5.rst b/docs/source/guides/admin-guides/references/man5/kvm_nodedata.5.rst index 81054cabc..c2286a413 100644 --- a/docs/source/guides/admin-guides/references/man5/kvm_nodedata.5.rst +++ b/docs/source/guides/admin-guides/references/man5/kvm_nodedata.5.rst @@ -27,7 +27,7 @@ DESCRIPTION *********** -Persistant store for KVM plugin, not intended for manual modification. +Persistent store for KVM plugin, not intended for manual modification. ************************ diff --git a/docs/source/guides/admin-guides/references/man5/linuximage.5.rst b/docs/source/guides/admin-guides/references/man5/linuximage.5.rst index 1028e48ac..662d6b48b 100644 --- a/docs/source/guides/admin-guides/references/man5/linuximage.5.rst +++ b/docs/source/guides/admin-guides/references/man5/linuximage.5.rst @@ -68,13 +68,13 @@ linuximage Attributes: \ **pkgdir**\ - The name of the directory where the distro packages are stored. It could be set multiple paths.The multiple paths must be seperated by ",". The first path in the value of osimage.pkgdir must be the OS base pkg dir path, such as pkgdir=/install/rhels6.2/x86_64,/install/updates . In the os base pkg path, there are default repository data. And in the other pkg path(s), the users should make sure there are repository data. If not, use "createrepo" command to create them. For ubuntu, multiple mirrors can be specified in the pkgdir attribute, the mirrors must be prefixed by the protocol(http/ssh) and delimited with "," between each other. + The name of the directory where the distro packages are stored. It could be set to multiple paths. The multiple paths must be separated by ",". The first path in the value of osimage.pkgdir must be the OS base pkg dir path, such as pkgdir=/install/rhels6.2/x86_64,/install/updates . In the os base pkg path, there are default repository data. And in the other pkg path(s), the users should make sure there are repository data. If not, use "createrepo" command to create them. For ubuntu, multiple mirrors can be specified in the pkgdir attribute, the mirrors must be prefixed by the protocol(http/ssh) and delimited with "," between each other. \ **otherpkglist**\ - The fully qualified name of the file that stores non-distro package lists that will be included in the image. It could be set multiple paths.The multiple paths must be seperated by ",". + The fully qualified name of the file that stores non-distro package lists that will be included in the image. It could be set to multiple paths. The multiple paths must be separated by ",". @@ -92,7 +92,7 @@ linuximage Attributes: \ **postinstall**\ - The fully qualified name of the script file that will be run at the end of the genimage command. It could be set multiple paths.The multiple paths must be seperated by ",". It is used for diskless image only. + The fully qualified name of the script file that will be run at the end of the genimage command. It could be set to multiple paths. The multiple paths must be separated by ",". It is used for diskless image only. @@ -158,7 +158,7 @@ linuximage Attributes: \ **partitionfile**\ - The path of the configuration file which will be used to partition the disk for the node. For stateful osimages,two types of files are supported: "" which contains a partitioning definition that will be inserted directly into the generated autoinst configuration file and must be formatted for the corresponding OS installer (e.g. kickstart for RedHat, autoyast for SLES, pressed for Ubuntu). "s:" which specifies a shell script that will be run from the OS installer configuration file %pre section; the script must write the correct partitioning definition into the file /tmp/partitionfile on the node which will be included into the configuration file during the install process. For statelite osimages, partitionfile should specify ""; see the xCAT Statelite documentation for the xCAT defined format of this configuration file.For Ubuntu, besides "" or "s:", the disk name(s) to partition must be specified in traditional, non-devfs format, delimited with space, it can be specified in 2 forms: "d:" which contains the disk name(s) to partition and "s:d:" which runs in pressed/early_command and writes the disk names into the "/tmp/install_disk" . To support other specific partition methods such as RAID or LVM in Ubuntu, some additional preseed values should be specified, these values can be specified with "c:" which contains the additional pressed entries in "d-i ..." form and "s:c:" which runs in pressed/early_command and set the preseed values with "debconf-set". The multiple values should be delimited with comma "," + The path of the configuration file which will be used to partition the disk for the node. For stateful osimages,two types of files are supported: "" which contains a partitioning definition that will be inserted directly into the generated autoinst configuration file and must be formatted for the corresponding OS installer (e.g. kickstart for RedHat, autoyast for SLES, pressed for Ubuntu). "s:" which specifies a shell script that will be run from the OS installer configuration file %pre section; the script must write the correct partitioning definition into the file /tmp/partitionfile on the node which will be included into the configuration file during the install process. For statelite osimages, partitionfile should specify ""; see the xCAT Statelite documentation for the xCAT defined format of this configuration file.For Ubuntu, besides "" or "s:", the disk name(s) to partition must be specified in traditional, non-devfs format, delimited with space, it can be specified in 2 forms: "d:" which contains the disk name(s) to partition and "s:d:" which runs in pressed/early_command and writes the disk names into the "/tmp/xcat.install_disk" . To support other specific partition methods such as RAID or LVM in Ubuntu, some additional preseed values should be specified, these values can be specified with "c:" which contains the additional pressed entries in "d-i ..." form and "s:c:" which runs in pressed/early_command and set the preseed values with "debconf-set". The multiple values should be delimited with comma "," diff --git a/docs/source/guides/admin-guides/references/man5/mic.5.rst b/docs/source/guides/admin-guides/references/man5/mic.5.rst index f2c30831e..896113110 100644 --- a/docs/source/guides/admin-guides/references/man5/mic.5.rst +++ b/docs/source/guides/admin-guides/references/man5/mic.5.rst @@ -27,7 +27,7 @@ DESCRIPTION *********** -The host, slot id and configuraton of the mic (Many Integrated Core). +The host, slot id and configuration of the mic (Many Integrated Core). *************** diff --git a/docs/source/guides/admin-guides/references/man5/monitoring.5.rst b/docs/source/guides/admin-guides/references/man5/monitoring.5.rst index 8419697d1..1f8176938 100644 --- a/docs/source/guides/admin-guides/references/man5/monitoring.5.rst +++ b/docs/source/guides/admin-guides/references/man5/monitoring.5.rst @@ -38,7 +38,7 @@ monitoring Attributes: \ **name**\ - The name of the mornitoring plug-in module. The plug-in must be put in /lib/perl/xCAT_monitoring/. See the man page for monstart for details. + The name of the monitoring plug-in module. The plug-in must be put in /opt/xcat/lib/perl/xCAT_monitoring/. See the man page for monstart for details. diff --git a/docs/source/guides/admin-guides/references/man5/monsetting.5.rst b/docs/source/guides/admin-guides/references/man5/monsetting.5.rst index 5718e62e6..6200b8925 100644 --- a/docs/source/guides/admin-guides/references/man5/monsetting.5.rst +++ b/docs/source/guides/admin-guides/references/man5/monsetting.5.rst @@ -38,7 +38,7 @@ monsetting Attributes: \ **name**\ - The name of the mornitoring plug-in module. The plug-in must be put in /lib/perl/xCAT_monitoring/. See the man page for monstart for details. + The name of the monitoring plug-in module. The plug-in must be put in /opt/xcat/lib/perl/xCAT_monitoring/. See the man page for monstart for details. diff --git a/docs/source/guides/admin-guides/references/man5/mp.5.rst b/docs/source/guides/admin-guides/references/man5/mp.5.rst index 94ae534e0..ee046aee4 100644 --- a/docs/source/guides/admin-guides/references/man5/mp.5.rst +++ b/docs/source/guides/admin-guides/references/man5/mp.5.rst @@ -44,7 +44,7 @@ mp Attributes: \ **mpa**\ - The managment module used to control this blade. + The management module used to control this blade. diff --git a/docs/source/guides/admin-guides/references/man5/mpa.5.rst b/docs/source/guides/admin-guides/references/man5/mpa.5.rst index e44e0f87d..4b03e9d12 100644 --- a/docs/source/guides/admin-guides/references/man5/mpa.5.rst +++ b/docs/source/guides/admin-guides/references/man5/mpa.5.rst @@ -63,9 +63,14 @@ mpa Attributes: \ **slots**\ The number of available slots in the chassis. For PCM, this attribute is used to store the number of slots in the following format: ,, Where: - = number of rows of slots in chassis - = number of columns of slots in chassis - = set to 0 if slots are vertical, and set to 1 if slots of horizontal + + + .. code-block:: perl + + = number of rows of slots in chassis + = number of columns of slots in chassis + = set to 0 if slots are vertical, and set to 1 if slots of horizontal + diff --git a/docs/source/guides/admin-guides/references/man5/nics.5.rst b/docs/source/guides/admin-guides/references/man5/nics.5.rst index 4855c0a56..cf4aab58c 100644 --- a/docs/source/guides/admin-guides/references/man5/nics.5.rst +++ b/docs/source/guides/admin-guides/references/man5/nics.5.rst @@ -44,7 +44,8 @@ nics Attributes: \ **nicips**\ - Comma-separated list of IP addresses per NIC. To specify one ip address per NIC: + Comma-separated list of IP addresses per NIC. + To specify one ip address per NIC: !,!,..., for example, eth0!10.0.0.100,ib0!11.0.0.100 To specify multiple ip addresses per NIC: !|,!|,..., for example, eth0!10.0.0.100|fd55::214:5eff:fe15:849b,ib0!11.0.0.100|2001::214:5eff:fe15:849a. The xCAT object definition commands support to use nicips. as the sub attributes. @@ -57,7 +58,7 @@ nics Attributes: Comma-separated list of hostname suffixes per NIC. If only one ip address is associated with each NIC: !,!,..., for example, eth0!-eth0,ib0!-ib0 - If multiple ip addresses are associcated with each NIC: + If multiple ip addresses are associated with each NIC: !|,!|,..., for example, eth0!-eth0|-eth0-ipv6,ib0!-ib0|-ib0-ipv6. The xCAT object definition commands support to use nichostnamesuffixes. 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), minus sign (-),and period (.). When you are specifying "nichostnamesuffixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention @@ -69,7 +70,7 @@ nics Attributes: Comma-separated list of hostname prefixes per NIC. If only one ip address is associated with each NIC: !,!,..., for example, eth0!eth0-,ib0!ib- - If multiple ip addresses are associcated with each NIC: + If multiple ip addresses are associated with each NIC: !|,!|,..., for example, eth0!eth0-|eth0-ipv6i-,ib0!ib-|ib-ipv6-. The xCAT object definition commands support to use nichostnameprefixes. 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), minus sign (-),and period (.). When you are specifying "nichostnameprefixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention @@ -102,9 +103,9 @@ nics Attributes: \ **nicaliases**\ Comma-separated list of hostname aliases for each NIC. - Format: eth0!,eth1!| - For multiple aliases per nic use a space-separated list. - For example: eth0!moe larry curly,eth1!tom|jerry + Format: eth0!,eth1!| + For multiple aliases per nic use a space-separated list. + For example: eth0!moe larry curly,eth1!tom|jerry @@ -121,7 +122,7 @@ nics Attributes: \ **nicdevices**\ - Comma-separated list of NIC device per NIC, multiple ethernet devices can be bonded as bond device, these ethernet devices are separated by |. !|,!, e.g. bond0!eth0|eth2,br0!bond0. The xCAT object definition commands support to use nicdevices. as the sub attributes. + Comma-separated list of NIC device per NIC, multiple ethernet devices can be bonded as bond device, these ethernet devices are separated by | . !|,!, e.g. bond0!eth0|eth2,br0!bond0. The xCAT object definition commands support to use nicdevices. as the sub attributes. diff --git a/docs/source/guides/admin-guides/references/man5/nodelist.5.rst b/docs/source/guides/admin-guides/references/man5/nodelist.5.rst index 8c81ea740..25bf8c377 100644 --- a/docs/source/guides/admin-guides/references/man5/nodelist.5.rst +++ b/docs/source/guides/admin-guides/references/man5/nodelist.5.rst @@ -50,7 +50,7 @@ nodelist Attributes: \ **status**\ - The current status of this node. This attribute will be set by xCAT software. Valid values: defined, booting, netbooting, booted, discovering, configuring, installing, alive, standingby, powering-off, unreachable. If blank, defined is assumed. The possible status change sequenses are: For installaton: defined->[discovering]->[configuring]->[standingby]->installing->booting->booted->[alive], For diskless deployment: defined->[discovering]->[configuring]->[standingby]->netbooting->booted->[alive], For booting: [alive/unreachable]->booting->[alive], For powering off: [alive]->powering-off->[unreachable], For monitoring: alive->unreachable. Discovering and configuring are for x Series dicovery process. Alive and unreachable are set only when there is a monitoring plug-in start monitor the node status for xCAT. Please note that the status values will not reflect the real node status if you change the state of the node from outside of xCAT (i.e. power off the node using HMC GUI). + The current status of this node. This attribute will be set by xCAT software. Valid values: defined, booting, netbooting, booted, discovering, configuring, installing, alive, standingby, powering-off, unreachable. If blank, defined is assumed. The possible status change sequences are: For installation: defined->[discovering]->[configuring]->[standingby]->installing->booting->booted->[alive], For diskless deployment: defined->[discovering]->[configuring]->[standingby]->netbooting->booted->[alive], For booting: [alive/unreachable]->booting->[alive], For powering off: [alive]->powering-off->[unreachable], For monitoring: alive->unreachable. Discovering and configuring are for x Series discovery process. Alive and unreachable are set only when there is a monitoring plug-in start monitor the node status for xCAT. Please note that the status values will not reflect the real node status if you change the state of the node from outside of xCAT (i.e. power off the node using HMC GUI). diff --git a/docs/source/guides/admin-guides/references/man5/noderes.5.rst b/docs/source/guides/admin-guides/references/man5/noderes.5.rst index 36c9fb575..8d2bae399 100644 --- a/docs/source/guides/admin-guides/references/man5/noderes.5.rst +++ b/docs/source/guides/admin-guides/references/man5/noderes.5.rst @@ -51,12 +51,17 @@ noderes Attributes: \ **netboot**\ The type of network booting to use for this node. Valid values: - 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 + + + .. code-block:: perl + + 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 + diff --git a/docs/source/guides/admin-guides/references/man5/osimage.5.rst b/docs/source/guides/admin-guides/references/man5/osimage.5.rst index 283c0c0eb..968b2f443 100644 --- a/docs/source/guides/admin-guides/references/man5/osimage.5.rst +++ b/docs/source/guides/admin-guides/references/man5/osimage.5.rst @@ -122,7 +122,7 @@ osimage Attributes: \ **postscripts**\ - Comma separated list of scripts that should be run on this image after diskful installation or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. See the site table runbootscripts attribute. Support will be added in the future for the postscripts attribute to run the scripts before the reboot in AIX. + Comma separated list of scripts that should be run on this image after diskful installation or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. See the site table runbootscripts attribute. diff --git a/docs/source/guides/admin-guides/references/man5/postscripts.5.rst b/docs/source/guides/admin-guides/references/man5/postscripts.5.rst index ed667890d..a87cd902c 100644 --- a/docs/source/guides/admin-guides/references/man5/postscripts.5.rst +++ b/docs/source/guides/admin-guides/references/man5/postscripts.5.rst @@ -44,7 +44,7 @@ postscripts Attributes: \ **postscripts**\ - Comma separated list of scripts that should be run on this node after diskful installation or diskless boot. Each script can take zero or more parameters. For example: "script1 p1 p2,script2,...". xCAT automatically adds the postscripts from the xcatdefaults.postscripts attribute of the table to run first on the nodes after install or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. Support will be added in the future for the postscripts attribute to run the scripts before the reboot in AIX. + Comma separated list of scripts that should be run on this node after diskful installation or diskless boot. Each script can take zero or more parameters. For example: "script1 p1 p2,script2,...". xCAT automatically adds the postscripts from the xcatdefaults.postscripts attribute of the table to run first on the nodes after install or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. diff --git a/docs/source/guides/admin-guides/references/man5/prescripts.5.rst b/docs/source/guides/admin-guides/references/man5/prescripts.5.rst index 6b8b0ebc6..13f42e25c 100644 --- a/docs/source/guides/admin-guides/references/man5/prescripts.5.rst +++ b/docs/source/guides/admin-guides/references/man5/prescripts.5.rst @@ -44,10 +44,9 @@ prescripts Attributes: \ **begin**\ - The scripts to be run at the beginning of the nodeset(Linux), - nimnodeset(AIX) or mkdsklsnode(AIX) command. + The scripts to be run at the beginning of the nodeset(Linux), nimnodeset(AIX) or mkdsklsnode(AIX) command. The format is: - [action1:]s1,s2...[|action2:s3,s4,s5...] + [action1:]s1,s2...[| action2:s3,s4,s5...] where: - action1 and action2 for Linux are the nodeset actions specified in the command. For AIX, action1 and action1 can be 'diskless' for mkdsklsnode command' @@ -59,28 +58,20 @@ prescripts Attributes: myscript1,myscript2 (all actions) diskless:myscript1,myscript2 (AIX) install:myscript1,myscript2|netboot:myscript3 (Linux) - - - .. code-block:: perl - - All the scripts should be copied to /install/prescripts directory. - The following two environment variables will be passed to each script: - NODES a coma separated list of node names that need to run the script for - ACTION current nodeset action. - - If '#xCAT setting:MAX_INSTANCE=number' is specified in the script, the script - will get invoked for each node in parallel, but no more than number of instances - will be invoked at at a time. If it is not specified, the script will be invoked - once for all the nodes. - + All the scripts should be copied to /install/prescripts directory. + The following two environment variables will be passed to each script: + NODES a coma separated list of node names that need to run the script for + ACTION current nodeset action. + If '#xCAT setting:MAX_INSTANCE=number' is specified in the script, the script + will get invoked for each node in parallel, but no more than number of instances + will be invoked at at a time. If it is not specified, the script will be invoked + once for all the nodes. \ **end**\ - The scripts to be run at the end of the nodeset(Linux), - nimnodeset(AIX),or mkdsklsnode(AIX) command. - The format is the same as the 'begin' column. + The scripts to be run at the end of the nodeset(Linux), nimnodeset(AIX),or mkdsklsnode(AIX) command. The format is the same as the 'begin' column. diff --git a/docs/source/guides/admin-guides/references/man5/routes.5.rst b/docs/source/guides/admin-guides/references/man5/routes.5.rst index 755c35322..b84fa965a 100644 --- a/docs/source/guides/admin-guides/references/man5/routes.5.rst +++ b/docs/source/guides/admin-guides/references/man5/routes.5.rst @@ -27,7 +27,7 @@ DESCRIPTION *********** -Describes the additional routes needed to be setup in the os routing table. These routes usually are used to connect the management node to the compute node using the servie node as gateway. +Describes the additional routes needed to be setup in the os routing table. These routes usually are used to connect the management node to the compute node using the service node as gateway. ****************** diff --git a/docs/source/guides/admin-guides/references/man5/site.5.rst b/docs/source/guides/admin-guides/references/man5/site.5.rst index 6c0495904..35c59d2b7 100644 --- a/docs/source/guides/admin-guides/references/man5/site.5.rst +++ b/docs/source/guides/admin-guides/references/man5/site.5.rst @@ -307,7 +307,7 @@ site Attributes: currently supported values: '0': disable debug mode '1': enable basic debug mode - '2': enalbe expert debug mode + '2': enable expert debug mode For the details on 'basic debug mode' and 'expert debug mode', please refer to xCAT documentation. diff --git a/docs/source/guides/admin-guides/references/man5/statelite.5.rst b/docs/source/guides/admin-guides/references/man5/statelite.5.rst index 35559be56..3b9f6e1b0 100644 --- a/docs/source/guides/admin-guides/references/man5/statelite.5.rst +++ b/docs/source/guides/admin-guides/references/man5/statelite.5.rst @@ -50,7 +50,7 @@ statelite Attributes: \ **statemnt**\ - The persistant read/write area where a node's persistent files will be written to, e.g: 10.0.0.1/state/. The node name will be automatically added to the pathname, so 10.0.0.1:/state, will become 10.0.0.1:/state/. + The persistent read/write area where a node's persistent files will be written to, e.g: 10.0.0.1/state/. The node name will be automatically added to the pathname, so 10.0.0.1:/state, will become 10.0.0.1:/state/. diff --git a/docs/source/guides/admin-guides/references/man5/storage.5.rst b/docs/source/guides/admin-guides/references/man5/storage.5.rst index a2183e3ef..5182c1c82 100644 --- a/docs/source/guides/admin-guides/references/man5/storage.5.rst +++ b/docs/source/guides/admin-guides/references/man5/storage.5.rst @@ -43,9 +43,14 @@ storage Attributes: \ **osvolume**\ Specification of what storage to place the node OS image onto. Examples include: - localdisk (Install to first non-FC attached disk) - usbdisk (Install to first USB mass storage device seen) - wwn=0x50000393c813840c (Install to storage device with given WWN) + + + .. code-block:: perl + + localdisk (Install to first non-FC attached disk) + usbdisk (Install to first USB mass storage device seen) + wwn=0x50000393c813840c (Install to storage device with given WWN) + @@ -93,9 +98,9 @@ storage Attributes: \ **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 + 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 diff --git a/docs/source/guides/admin-guides/references/man5/switches.5.rst b/docs/source/guides/admin-guides/references/man5/switches.5.rst index 7dc675fef..5cdb6d33e 100644 --- a/docs/source/guides/admin-guides/references/man5/switches.5.rst +++ b/docs/source/guides/admin-guides/references/man5/switches.5.rst @@ -56,7 +56,7 @@ switches Attributes: \ **password**\ - The password strinng for SNMPv3 or community string for SNMPv1/SNMPv2. Falls back to passwd table, and site snmpc value if using SNMPv1/SNMPv2. + The password string for SNMPv3 or community string for SNMPv1/SNMPv2. Falls back to passwd table, and site snmpc value if using SNMPv1/SNMPv2. @@ -92,13 +92,13 @@ switches Attributes: \ **protocol**\ - Prorocol for running remote commands for the switch. The valid values are: ssh, telnet. ssh is the default. If the sshusername is blank, the username, password and protocol will be retrieved from the passwd table with "switch" as the key. The passwd.comments attribute is used for protocol. + Protocol for running remote commands for the switch. The valid values are: ssh, telnet. ssh is the default. If the sshusername is blank, the username, password and protocol will be retrieved from the passwd table with "switch" as the key. The passwd.comments attribute is used for protocol. \ **switchtype**\ - The type of switch. It is used to identify the file name that implements the functions for this swithc. The valid values are: Mellanox, Cisco, BNT and Juniper. + The type of switch. It is used to identify the file name that implements the functions for this switch. The valid values are: Mellanox, Cisco, BNT and Juniper. diff --git a/docs/source/guides/admin-guides/references/man5/taskstate.5.rst b/docs/source/guides/admin-guides/references/man5/taskstate.5.rst index 44fb0ee01..1d7fc2e4f 100644 --- a/docs/source/guides/admin-guides/references/man5/taskstate.5.rst +++ b/docs/source/guides/admin-guides/references/man5/taskstate.5.rst @@ -19,7 +19,7 @@ SYNOPSIS ******** -\ **taskstate Attributes:**\ \ *node*\ , \ *command*\ , \ *state*\ , \ *pid*\ , \ *reserve*\ +\ **taskstate Attributes:**\ \ *node*\ , \ *command*\ , \ *state*\ , \ *pid*\ , \ *reserve*\ , \ *disable*\ *********** @@ -66,6 +66,12 @@ taskstate Attributes: +\ **disable**\ + + Set to 'yes' or '1' to comment out this row. + + + ******** SEE ALSO diff --git a/docs/source/guides/admin-guides/references/man5/vm.5.rst b/docs/source/guides/admin-guides/references/man5/vm.5.rst index ece3064cc..f16c9f3d2 100644 --- a/docs/source/guides/admin-guides/references/man5/vm.5.rst +++ b/docs/source/guides/admin-guides/references/man5/vm.5.rst @@ -86,7 +86,7 @@ vm Attributes: \ **cfgstore**\ - Optional location for persistant storage separate of emulated hard drives for virtualization solutions that require persistant store to place configuration data + Optional location for persistent storage separate of emulated hard drives for virtualization solutions that require persistant store to place configuration data @@ -128,7 +128,8 @@ vm Attributes: \ **virtflags**\ - General flags used by the virtualization method. For example, in Xen it could, among other things, specify paravirtualized setup, or direct kernel boot. For a hypervisor/dom0 entry, it is the virtualization method (i.e. "xen"). For KVM, the following flag=value pairs are recognized: + General flags used by the virtualization method. + For example, in Xen it could, among other things, specify paravirtualized setup, or direct kernel boot. For a hypervisor/dom0 entry, it is the virtualization method (i.e. "xen"). For KVM, the following flag=value pairs are recognized: imageformat=[raw|fullraw|qcow2] raw is a generic sparse file that allocates storage on demand fullraw is a generic, non-sparse file that preallocates all space @@ -190,7 +191,7 @@ vm Attributes: \ **othersettings**\ - This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively,the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. + This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively, the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. diff --git a/docs/source/guides/admin-guides/references/man5/vpd.5.rst b/docs/source/guides/admin-guides/references/man5/vpd.5.rst index b4ee11883..eabf05441 100644 --- a/docs/source/guides/admin-guides/references/man5/vpd.5.rst +++ b/docs/source/guides/admin-guides/references/man5/vpd.5.rst @@ -62,7 +62,7 @@ vpd Attributes: \ **asset**\ - A field for administators to use to correlate inventory numbers they may have to accomodate + A field for administrators to use to correlate inventory numbers they may have to accommodate diff --git a/docs/source/guides/admin-guides/references/man5/xcatdb.5.rst b/docs/source/guides/admin-guides/references/man5/xcatdb.5.rst index 86806e6ae..2e15caff4 100644 --- a/docs/source/guides/admin-guides/references/man5/xcatdb.5.rst +++ b/docs/source/guides/admin-guides/references/man5/xcatdb.5.rst @@ -329,11 +329,7 @@ The tables are: auditlog(5)|auditlog.5 - - .. code-block:: perl - - Audit Data log. - + Audit Data log. @@ -441,13 +437,13 @@ kitrepo(5)|kitrepo.5 kvm_masterdata(5)|kvm_masterdata.5 - Persistant store for KVM plugin for masters + Persistent store for KVM plugin for masters kvm_nodedata(5)|kvm_nodedata.5 - Persistant store for KVM plugin, not intended for manual modification. + Persistent store for KVM plugin, not intended for manual modification. @@ -477,7 +473,7 @@ mac(5)|mac.5 mic(5)|mic.5 - The host, slot id and configuraton of the mic (Many Integrated Core). + The host, slot id and configuration of the mic (Many Integrated Core). @@ -645,7 +641,7 @@ rack(5)|rack.5 routes(5)|routes.5 - Describes the additional routes needed to be setup in the os routing table. These routes usually are used to connect the management node to the compute node using the servie node as gateway. + Describes the additional routes needed to be setup in the os routing table. These routes usually are used to connect the management node to the compute node using the service node as gateway. diff --git a/docs/source/guides/admin-guides/references/man7/boottarget.7.rst b/docs/source/guides/admin-guides/references/man7/boottarget.7.rst index fa8729eb7..be767a2fc 100644 --- a/docs/source/guides/admin-guides/references/man7/boottarget.7.rst +++ b/docs/source/guides/admin-guides/references/man7/boottarget.7.rst @@ -19,7 +19,7 @@ SYNOPSIS ******** -\ **boottarget Attributes:**\ \ **\ +\ **boottarget Attributes:**\ \ *bprofile*\ , \ *comments*\ , \ *initrd*\ , \ *kcmdline*\ , \ *kernel*\ *********** @@ -39,6 +39,36 @@ boottarget Attributes: +\ **bprofile**\ (boottarget.bprofile) + + All nodes with a nodetype.profile value equal to this value and nodetype.os set to "boottarget", will use the associated kernel, initrd, and kcmdline. + + + +\ **comments**\ (boottarget.comments) + + Any user-written notes. + + + +\ **initrd**\ (boottarget.initrd) + + The initial ramdisk image that network boot actions should use (could be a DOS floppy or hard drive image if using memdisk as kernel) + + + +\ **kcmdline**\ (boottarget.kcmdline) + + Arguments to be passed to the kernel + + + +\ **kernel**\ (boottarget.kernel) + + The kernel that network boot actions should currently acquire and use. Note this could be a chained boot loader such as memdisk or a non-linux boot loader + + + ******** SEE ALSO diff --git a/docs/source/guides/admin-guides/references/man7/eventlog.7.rst b/docs/source/guides/admin-guides/references/man7/eventlog.7.rst index 7837a6c39..ff31cbe01 100644 --- a/docs/source/guides/admin-guides/references/man7/eventlog.7.rst +++ b/docs/source/guides/admin-guides/references/man7/eventlog.7.rst @@ -107,11 +107,7 @@ eventlog Attributes: \ **rawdata**\ (eventlog.rawdata) - - .. code-block:: perl - - The data that associated with the event. - + The data that associated with the event. diff --git a/docs/source/guides/admin-guides/references/man7/group.7.rst b/docs/source/guides/admin-guides/references/man7/group.7.rst index 0e76c6a07..f2d407860 100644 --- a/docs/source/guides/admin-guides/references/man7/group.7.rst +++ b/docs/source/guides/admin-guides/references/man7/group.7.rst @@ -59,7 +59,7 @@ group Attributes: \ **bmc**\ (ipmi.bmc) - The hostname of the BMC adapater. + The hostname of the BMC adapter. @@ -71,87 +71,45 @@ group Attributes: \ **bmcport**\ (ipmi.bmcport) + In systems with selectable shared/dedicated ethernet ports, this parameter can be used to specify the preferred port. 0 means use the shared port, 1 means dedicated, blank is to not assign. + .. code-block:: perl - In systems with selectable shared/dedicated ethernet ports, - - this parameter can be used to specify the preferred port. 0 - - means use the shared port, 1 means dedicated, blank is to not - - assign. - - - The following special cases exist for IBM System x servers: - - For x3755 M3 systems, 0 means use the dedicated port, 1 means - shared, blank is to not assign. - - For certain systems which have a mezzaine or ML2 adapter, there is a second - value to include: - - - For x3750 M4 (Model 8722): - - - 0 2 1st 1Gbps interface for LOM - - 0 0 1st 10Gbps interface for LOM - - 0 3 2nd 1Gbps interface for LOM - - 0 1 2nd 10Gbps interface for LOM - - - For x3750 M4 (Model 8752), x3850/3950 X6, dx360 M4, x3550 M4, and x3650 M4: - - - 0 Shared (1st onboard interface) - - 1 Dedicated - - 2 0 First interface on ML2 or mezzanine adapter - - 2 1 Second interface on ML2 or mezzanine adapter - - 2 2 Third interface on ML2 or mezzanine adapter - - 2 3 Fourth interface on ML2 or mezzanine adapter @@ -267,7 +225,7 @@ group Attributes: \ **dockerflag**\ (vm.othersettings) - This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively,the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. + This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively, the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. @@ -545,7 +503,7 @@ group Attributes: \ **mpa**\ (mp.mpa) - The managment module used to control this blade. + The management module used to control this blade. @@ -568,17 +526,12 @@ group Attributes: .. code-block:: perl - 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 + 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 @@ -598,142 +551,85 @@ group Attributes: \ **nicaliases**\ (nics.nicaliases) Comma-separated list of hostname aliases for each NIC. - - - .. code-block:: perl - - Format: eth0!,eth1!| - - For multiple aliases per nic use a space-separated list. - - For example: eth0!moe larry curly,eth1!tom|jerry - + Format: eth0!,eth1!| + For multiple aliases per nic use a space-separated list. + For example: eth0!moe larry curly,eth1!tom|jerry \ **niccustomscripts**\ (nics.niccustomscripts) Comma-separated list of custom scripts per NIC. !,!, e.g. eth0!configeth eth0, ib0!configib ib0. The xCAT object definition commands support to use niccustomscripts. as the sub attribute - . \ **nicdevices**\ (nics.nicdevices) - Comma-separated list of NIC device per NIC, multiple ethernet devices can be bonded as bond device, these ethernet devices are separated by |. !|,!, e.g. bond0!eth0|eth2,br0!bond0. The xCAT object definition commands support to use nicdevices. as the sub attributes. + Comma-separated list of NIC device per NIC, multiple ethernet devices can be bonded as bond device, these ethernet devices are separated by | . !|,!, e.g. bond0!eth0|eth2,br0!bond0. The xCAT object definition commands support to use nicdevices. as the sub attributes. \ **nicextraparams**\ (nics.nicextraparams) Comma-separated list of extra parameters that will be used for each NIC configuration. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!, for example, eth0!MTU=1500,ib0!MTU=65520 CONNECTED_MODE=yes. - - If multiple ip addresses are associated with each NIC: - - !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. - - The xCAT object definition commands support to use nicextraparams. as the sub attributes. - + If only one ip address is associated with each NIC: + !,!, for example, eth0!MTU=1500,ib0!MTU=65520 CONNECTED_MODE=yes. + If multiple ip addresses are associated with each NIC: + !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. + The xCAT object definition commands support to use nicextraparams. as the sub attributes. \ **nichostnameprefixes**\ (nics.nichostnameprefixes) - Comma-separated list of hostname prefixes per NIC. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!,..., for example, eth0!eth0-,ib0!ib- - - If multiple ip addresses are associcated with each NIC: - - !|,!|,..., for example, eth0!eth0-|eth0-ipv6i-,ib0!ib-|ib-ipv6-. - - The xCAT object definition commands support to use nichostnameprefixes. 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), minus sign (-),and period (.). When you are specifying "nichostnameprefixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention - + Comma-separated list of hostname prefixes per NIC. + If only one ip address is associated with each NIC: + !,!,..., for example, eth0!eth0-,ib0!ib- + If multiple ip addresses are associated with each NIC: + !|,!|,..., for example, eth0!eth0-|eth0-ipv6i-,ib0!ib-|ib-ipv6-. + The xCAT object definition commands support to use nichostnameprefixes. 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), minus sign (-),and period (.). When you are specifying "nichostnameprefixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention \ **nichostnamesuffixes**\ (nics.nichostnamesuffixes) - Comma-separated list of hostname suffixes per NIC. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!,..., for example, eth0!-eth0,ib0!-ib0 - - If multiple ip addresses are associcated with each NIC: - - !|,!|,..., for example, eth0!-eth0|-eth0-ipv6,ib0!-ib0|-ib0-ipv6. - - The xCAT object definition commands support to use nichostnamesuffixes. 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), minus sign (-),and period (.). When you are specifying "nichostnamesuffixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention - + Comma-separated list of hostname suffixes per NIC. + If only one ip address is associated with each NIC: + !,!,..., for example, eth0!-eth0,ib0!-ib0 + If multiple ip addresses are associated with each NIC: + !|,!|,..., for example, eth0!-eth0|-eth0-ipv6,ib0!-ib0|-ib0-ipv6. + The xCAT object definition commands support to use nichostnamesuffixes. 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), minus sign (-),and period (.). When you are specifying "nichostnamesuffixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention \ **nicips**\ (nics.nicips) - Comma-separated list of IP addresses per NIC. To specify one ip address per NIC: - - - .. code-block:: perl - - !,!,..., for example, eth0!10.0.0.100,ib0!11.0.0.100 - - To specify multiple ip addresses per NIC: - - !|,!|,..., for example, eth0!10.0.0.100|fd55::214:5eff:fe15:849b,ib0!11.0.0.100|2001::214:5eff:fe15:849a. The xCAT object definition commands support to use nicips. as the sub attributes. - - Note: The primary IP address must also be stored in the hosts.ip attribute. The nichostnamesuffixes should specify one hostname suffix for each ip address. - + Comma-separated list of IP addresses per NIC. + To specify one ip address per NIC: + !,!,..., for example, eth0!10.0.0.100,ib0!11.0.0.100 + To specify multiple ip addresses per NIC: + !|,!|,..., for example, eth0!10.0.0.100|fd55::214:5eff:fe15:849b,ib0!11.0.0.100|2001::214:5eff:fe15:849a. The xCAT object definition commands support to use nicips. as the sub attributes. + Note: The primary IP address must also be stored in the hosts.ip attribute. The nichostnamesuffixes should specify one hostname suffix for each ip address. \ **nicnetworks**\ (nics.nicnetworks) Comma-separated list of networks connected to each NIC. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!, for example, eth0!10_0_0_0-255_255_0_0, ib0!11_0_0_0-255_255_0_0 - - If multiple ip addresses are associated with each NIC: - - !|,!|, for example, eth0!10_0_0_0-255_255_0_0|fd55:faaf:e1ab:336::/64,ib0!11_0_0_0-255_255_0_0|2001:db8:1:0::/64. The xCAT object definition commands support to use nicnetworks. as the sub attributes. - + If only one ip address is associated with each NIC: + !,!, for example, eth0!10_0_0_0-255_255_0_0, ib0!11_0_0_0-255_255_0_0 + If multiple ip addresses are associated with each NIC: + !|,!|, for example, eth0!10_0_0_0-255_255_0_0|fd55:faaf:e1ab:336::/64,ib0!11_0_0_0-255_255_0_0|2001:db8:1:0::/64. The xCAT object definition commands support to use nicnetworks. as the sub attributes. \ **nicsadapter**\ (nics.nicsadapter) Comma-separated list of extra parameters that will be used for each NIC configuration. - - - .. code-block:: perl - - !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. - + !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. @@ -775,9 +671,7 @@ group Attributes: .. code-block:: perl localdisk (Install to first non-FC attached disk) - usbdisk (Install to first USB mass storage device seen) - wwn=0x50000393c813840c (Install to storage device with given WWN) @@ -791,7 +685,7 @@ group Attributes: \ **ou**\ (domain.ou) - For an LDAP described machine account (i.e. Active Directory), the orginaztional unit to place the system. If not set, defaults to cn=Computers,dc=your,dc=domain + For an LDAP described machine account (i.e. Active Directory), the organizational unit to place the system. If not set, defaults to cn=Computers,dc=your,dc=domain @@ -857,7 +751,7 @@ group Attributes: \ **postscripts**\ (postscripts.postscripts) - Comma separated list of scripts that should be run on this node after diskful installation or diskless boot. Each script can take zero or more parameters. For example: "script1 p1 p2,script2,...". xCAT automatically adds the postscripts from the xcatdefaults.postscripts attribute of the table to run first on the nodes after install or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. Support will be added in the future for the postscripts attribute to run the scripts before the reboot in AIX. + Comma separated list of scripts that should be run on this node after diskful installation or diskless boot. Each script can take zero or more parameters. For example: "script1 p1 p2,script2,...". xCAT automatically adds the postscripts from the xcatdefaults.postscripts attribute of the table to run first on the nodes after install or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. @@ -875,73 +769,34 @@ group Attributes: \ **prescripts-begin**\ (prescripts.begin) - The scripts to be run at the beginning of the nodeset(Linux), - - - .. code-block:: perl - - nimnodeset(AIX) or mkdsklsnode(AIX) command. - - The format is: - - [action1:]s1,s2...[|action2:s3,s4,s5...] - - where: - - - action1 and action2 for Linux are the nodeset actions specified in the command. - - For AIX, action1 and action1 can be 'diskless' for mkdsklsnode command' - - and 'standalone for nimnodeset command. - - - s1 and s2 are the scripts to run for action1 in order. - - - s3, s4, and s5 are the scripts to run for actions2. - - If actions are omitted, the scripts apply to all actions. - - Examples: - - myscript1,myscript2 (all actions) - - diskless:myscript1,myscript2 (AIX) - - install:myscript1,myscript2|netboot:myscript3 (Linux) - - - - All the scripts should be copied to /install/prescripts directory. - - The following two environment variables will be passed to each script: - - NODES a coma separated list of node names that need to run the script for - - ACTION current nodeset action. - - - - If '#xCAT setting:MAX_INSTANCE=number' is specified in the script, the script - - will get invoked for each node in parallel, but no more than number of instances - - will be invoked at at a time. If it is not specified, the script will be invoked - - once for all the nodes. - + The scripts to be run at the beginning of the nodeset(Linux), nimnodeset(AIX) or mkdsklsnode(AIX) command. + The format is: + [action1:]s1,s2...[| action2:s3,s4,s5...] + where: + - action1 and action2 for Linux are the nodeset actions specified in the command. + For AIX, action1 and action1 can be 'diskless' for mkdsklsnode command' + and 'standalone for nimnodeset command. + - s1 and s2 are the scripts to run for action1 in order. + - s3, s4, and s5 are the scripts to run for actions2. + If actions are omitted, the scripts apply to all actions. + Examples: + myscript1,myscript2 (all actions) + diskless:myscript1,myscript2 (AIX) + install:myscript1,myscript2|netboot:myscript3 (Linux) + All the scripts should be copied to /install/prescripts directory. + The following two environment variables will be passed to each script: + NODES a coma separated list of node names that need to run the script for + ACTION current nodeset action. + If '#xCAT setting:MAX_INSTANCE=number' is specified in the script, the script + will get invoked for each node in parallel, but no more than number of instances + will be invoked at at a time. If it is not specified, the script will be invoked + once for all the nodes. \ **prescripts-end**\ (prescripts.end) - The scripts to be run at the end of the nodeset(Linux), - - - .. code-block:: perl - - nimnodeset(AIX),or mkdsklsnode(AIX) command. - - The format is the same as the 'begin' column. - + The scripts to be run at the end of the nodeset(Linux), nimnodeset(AIX),or mkdsklsnode(AIX) command. The format is the same as the 'begin' column. @@ -965,7 +820,7 @@ group Attributes: \ **protocol**\ (switches.protocol) - Prorocol for running remote commands for the switch. The valid values are: ssh, telnet. ssh is the default. If the sshusername is blank, the username, password and protocol will be retrieved from the passwd table with "switch" as the key. The passwd.comments attribute is used for protocol. + Protocol for running remote commands for the switch. The valid values are: ssh, telnet. ssh is the default. If the sshusername is blank, the username, password and protocol will be retrieved from the passwd table with "switch" as the key. The passwd.comments attribute is used for protocol. @@ -1121,9 +976,7 @@ group Attributes: .. code-block:: perl = number of rows of slots in chassis - = number of columns of slots in chassis - = set to 0 if slots are vertical, and set to 1 if slots of horizontal @@ -1137,7 +990,7 @@ group Attributes: \ **snmppassword**\ (switches.password) - The password strinng for SNMPv3 or community string for SNMPv1/SNMPv2. Falls back to passwd table, and site snmpc value if using SNMPv1/SNMPv2. + The password string for SNMPv3 or community string for SNMPv1/SNMPv2. Falls back to passwd table, and site snmpc value if using SNMPv1/SNMPv2. @@ -1161,15 +1014,9 @@ group Attributes: \ **storagcontroller**\ (storage.controller) - The management address to attach/detach new volumes. - - - .. code-block:: perl - - In the scenario involving multiple controllers, this data must be - - passed as argument rather than by table value - + 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 @@ -1217,7 +1064,7 @@ group Attributes: \ **switchtype**\ (switches.switchtype) - The type of switch. It is used to identify the file name that implements the functions for this swithc. The valid values are: Mellanox, Cisco, BNT and Juniper. + The type of switch. It is used to identify the file name that implements the functions for this switch. The valid values are: Mellanox, Cisco, BNT and Juniper. @@ -1313,7 +1160,7 @@ group Attributes: \ **vmcfgstore**\ (vm.cfgstore) - Optional location for persistant storage separate of emulated hard drives for virtualization solutions that require persistant store to place configuration data + Optional location for persistent storage separate of emulated hard drives for virtualization solutions that require persistant store to place configuration data @@ -1367,7 +1214,7 @@ group Attributes: \ **vmothersetting**\ (vm.othersettings) - This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively,the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. + This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively, the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. @@ -1409,27 +1256,16 @@ group Attributes: \ **vmvirtflags**\ (vm.virtflags) - General flags used by the virtualization method. For example, in Xen it could, among other things, specify paravirtualized setup, or direct kernel boot. For a hypervisor/dom0 entry, it is the virtualization method (i.e. "xen"). For KVM, the following flag=value pairs are recognized: - - - .. code-block:: perl - - imageformat=[raw|fullraw|qcow2] - - raw is a generic sparse file that allocates storage on demand - - fullraw is a generic, non-sparse file that preallocates all space - - qcow2 is a sparse, copy-on-write capable format implemented at the virtualization layer rather than the filesystem level - - clonemethod=[qemu-img|reflink] - - qemu-img allows use of qcow2 to generate virtualization layer copy-on-write - - reflink uses a generic filesystem facility to clone the files on your behalf, but requires filesystem support such as btrfs - - placement_affinity=[migratable|user_migratable|pinned] - + General flags used by the virtualization method. + For example, in Xen it could, among other things, specify paravirtualized setup, or direct kernel boot. For a hypervisor/dom0 entry, it is the virtualization method (i.e. "xen"). For KVM, the following flag=value pairs are recognized: + imageformat=[raw|fullraw|qcow2] + raw is a generic sparse file that allocates storage on demand + fullraw is a generic, non-sparse file that preallocates all space + qcow2 is a sparse, copy-on-write capable format implemented at the virtualization layer rather than the filesystem level + clonemethod=[qemu-img|reflink] + qemu-img allows use of qcow2 to generate virtualization layer copy-on-write + reflink uses a generic filesystem facility to clone the files on your behalf, but requires filesystem support such as btrfs + placement_affinity=[migratable|user_migratable|pinned] diff --git a/docs/source/guides/admin-guides/references/man7/monitoring.7.rst b/docs/source/guides/admin-guides/references/man7/monitoring.7.rst index b77bae541..8f74ca22c 100644 --- a/docs/source/guides/admin-guides/references/man7/monitoring.7.rst +++ b/docs/source/guides/admin-guides/references/man7/monitoring.7.rst @@ -53,7 +53,7 @@ monitoring Attributes: \ **name**\ (monitoring.name) - The name of the mornitoring plug-in module. The plug-in must be put in /lib/perl/xCAT_monitoring/. See the man page for monstart for details. + The name of the monitoring plug-in module. The plug-in must be put in /opt/xcat/lib/perl/xCAT_monitoring/. See the man page for monstart for details. diff --git a/docs/source/guides/admin-guides/references/man7/node.7.rst b/docs/source/guides/admin-guides/references/man7/node.7.rst index 0d871ee82..19171544f 100644 --- a/docs/source/guides/admin-guides/references/man7/node.7.rst +++ b/docs/source/guides/admin-guides/references/man7/node.7.rst @@ -71,7 +71,7 @@ node Attributes: \ **bmc**\ (ipmi.bmc) - The hostname of the BMC adapater. + The hostname of the BMC adapter. @@ -83,87 +83,45 @@ node Attributes: \ **bmcport**\ (ipmi.bmcport) + In systems with selectable shared/dedicated ethernet ports, this parameter can be used to specify the preferred port. 0 means use the shared port, 1 means dedicated, blank is to not assign. + .. code-block:: perl - In systems with selectable shared/dedicated ethernet ports, - - this parameter can be used to specify the preferred port. 0 - - means use the shared port, 1 means dedicated, blank is to not - - assign. - - - The following special cases exist for IBM System x servers: - - For x3755 M3 systems, 0 means use the dedicated port, 1 means - shared, blank is to not assign. - - For certain systems which have a mezzaine or ML2 adapter, there is a second - value to include: - - - For x3750 M4 (Model 8722): - - - 0 2 1st 1Gbps interface for LOM - - 0 0 1st 10Gbps interface for LOM - - 0 3 2nd 1Gbps interface for LOM - - 0 1 2nd 10Gbps interface for LOM - - - For x3750 M4 (Model 8752), x3850/3950 X6, dx360 M4, x3550 M4, and x3650 M4: - - - 0 Shared (1st onboard interface) - - 1 Dedicated - - 2 0 First interface on ML2 or mezzanine adapter - - 2 1 Second interface on ML2 or mezzanine adapter - - 2 2 Third interface on ML2 or mezzanine adapter - - 2 3 Fourth interface on ML2 or mezzanine adapter @@ -279,7 +237,7 @@ node Attributes: \ **dockerflag**\ (vm.othersettings) - This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively,the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. + This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively, the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. @@ -545,7 +503,7 @@ node Attributes: \ **mpa**\ (mp.mpa) - The managment module used to control this blade. + The management module used to control this blade. @@ -568,17 +526,12 @@ node Attributes: .. code-block:: perl - 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 + 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 @@ -598,142 +551,85 @@ node Attributes: \ **nicaliases**\ (nics.nicaliases) Comma-separated list of hostname aliases for each NIC. - - - .. code-block:: perl - - Format: eth0!,eth1!| - - For multiple aliases per nic use a space-separated list. - - For example: eth0!moe larry curly,eth1!tom|jerry - + Format: eth0!,eth1!| + For multiple aliases per nic use a space-separated list. + For example: eth0!moe larry curly,eth1!tom|jerry \ **niccustomscripts**\ (nics.niccustomscripts) Comma-separated list of custom scripts per NIC. !,!, e.g. eth0!configeth eth0, ib0!configib ib0. The xCAT object definition commands support to use niccustomscripts. as the sub attribute - . \ **nicdevices**\ (nics.nicdevices) - Comma-separated list of NIC device per NIC, multiple ethernet devices can be bonded as bond device, these ethernet devices are separated by |. !|,!, e.g. bond0!eth0|eth2,br0!bond0. The xCAT object definition commands support to use nicdevices. as the sub attributes. + Comma-separated list of NIC device per NIC, multiple ethernet devices can be bonded as bond device, these ethernet devices are separated by | . !|,!, e.g. bond0!eth0|eth2,br0!bond0. The xCAT object definition commands support to use nicdevices. as the sub attributes. \ **nicextraparams**\ (nics.nicextraparams) Comma-separated list of extra parameters that will be used for each NIC configuration. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!, for example, eth0!MTU=1500,ib0!MTU=65520 CONNECTED_MODE=yes. - - If multiple ip addresses are associated with each NIC: - - !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. - - The xCAT object definition commands support to use nicextraparams. as the sub attributes. - + If only one ip address is associated with each NIC: + !,!, for example, eth0!MTU=1500,ib0!MTU=65520 CONNECTED_MODE=yes. + If multiple ip addresses are associated with each NIC: + !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. + The xCAT object definition commands support to use nicextraparams. as the sub attributes. \ **nichostnameprefixes**\ (nics.nichostnameprefixes) - Comma-separated list of hostname prefixes per NIC. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!,..., for example, eth0!eth0-,ib0!ib- - - If multiple ip addresses are associcated with each NIC: - - !|,!|,..., for example, eth0!eth0-|eth0-ipv6i-,ib0!ib-|ib-ipv6-. - - The xCAT object definition commands support to use nichostnameprefixes. 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), minus sign (-),and period (.). When you are specifying "nichostnameprefixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention - + Comma-separated list of hostname prefixes per NIC. + If only one ip address is associated with each NIC: + !,!,..., for example, eth0!eth0-,ib0!ib- + If multiple ip addresses are associated with each NIC: + !|,!|,..., for example, eth0!eth0-|eth0-ipv6i-,ib0!ib-|ib-ipv6-. + The xCAT object definition commands support to use nichostnameprefixes. 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), minus sign (-),and period (.). When you are specifying "nichostnameprefixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention \ **nichostnamesuffixes**\ (nics.nichostnamesuffixes) - Comma-separated list of hostname suffixes per NIC. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!,..., for example, eth0!-eth0,ib0!-ib0 - - If multiple ip addresses are associcated with each NIC: - - !|,!|,..., for example, eth0!-eth0|-eth0-ipv6,ib0!-ib0|-ib0-ipv6. - - The xCAT object definition commands support to use nichostnamesuffixes. 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), minus sign (-),and period (.). When you are specifying "nichostnamesuffixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention - + Comma-separated list of hostname suffixes per NIC. + If only one ip address is associated with each NIC: + !,!,..., for example, eth0!-eth0,ib0!-ib0 + If multiple ip addresses are associated with each NIC: + !|,!|,..., for example, eth0!-eth0|-eth0-ipv6,ib0!-ib0|-ib0-ipv6. + The xCAT object definition commands support to use nichostnamesuffixes. 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), minus sign (-),and period (.). When you are specifying "nichostnamesuffixes" or "nicaliases" make sure the resulting hostnames will conform to this naming convention \ **nicips**\ (nics.nicips) - Comma-separated list of IP addresses per NIC. To specify one ip address per NIC: - - - .. code-block:: perl - - !,!,..., for example, eth0!10.0.0.100,ib0!11.0.0.100 - - To specify multiple ip addresses per NIC: - - !|,!|,..., for example, eth0!10.0.0.100|fd55::214:5eff:fe15:849b,ib0!11.0.0.100|2001::214:5eff:fe15:849a. The xCAT object definition commands support to use nicips. as the sub attributes. - - Note: The primary IP address must also be stored in the hosts.ip attribute. The nichostnamesuffixes should specify one hostname suffix for each ip address. - + Comma-separated list of IP addresses per NIC. + To specify one ip address per NIC: + !,!,..., for example, eth0!10.0.0.100,ib0!11.0.0.100 + To specify multiple ip addresses per NIC: + !|,!|,..., for example, eth0!10.0.0.100|fd55::214:5eff:fe15:849b,ib0!11.0.0.100|2001::214:5eff:fe15:849a. The xCAT object definition commands support to use nicips. as the sub attributes. + Note: The primary IP address must also be stored in the hosts.ip attribute. The nichostnamesuffixes should specify one hostname suffix for each ip address. \ **nicnetworks**\ (nics.nicnetworks) Comma-separated list of networks connected to each NIC. - - - .. code-block:: perl - - If only one ip address is associated with each NIC: - - !,!, for example, eth0!10_0_0_0-255_255_0_0, ib0!11_0_0_0-255_255_0_0 - - If multiple ip addresses are associated with each NIC: - - !|,!|, for example, eth0!10_0_0_0-255_255_0_0|fd55:faaf:e1ab:336::/64,ib0!11_0_0_0-255_255_0_0|2001:db8:1:0::/64. The xCAT object definition commands support to use nicnetworks. as the sub attributes. - + If only one ip address is associated with each NIC: + !,!, for example, eth0!10_0_0_0-255_255_0_0, ib0!11_0_0_0-255_255_0_0 + If multiple ip addresses are associated with each NIC: + !|,!|, for example, eth0!10_0_0_0-255_255_0_0|fd55:faaf:e1ab:336::/64,ib0!11_0_0_0-255_255_0_0|2001:db8:1:0::/64. The xCAT object definition commands support to use nicnetworks. as the sub attributes. \ **nicsadapter**\ (nics.nicsadapter) Comma-separated list of extra parameters that will be used for each NIC configuration. - - - .. code-block:: perl - - !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. - + !|,!|, for example, eth0!MTU=1500|MTU=1460,ib0!MTU=65520 CONNECTED_MODE=yes. @@ -781,9 +677,7 @@ node Attributes: .. code-block:: perl localdisk (Install to first non-FC attached disk) - usbdisk (Install to first USB mass storage device seen) - wwn=0x50000393c813840c (Install to storage device with given WWN) @@ -797,7 +691,7 @@ node Attributes: \ **ou**\ (domain.ou) - For an LDAP described machine account (i.e. Active Directory), the orginaztional unit to place the system. If not set, defaults to cn=Computers,dc=your,dc=domain + For an LDAP described machine account (i.e. Active Directory), the organizational unit to place the system. If not set, defaults to cn=Computers,dc=your,dc=domain @@ -863,7 +757,7 @@ node Attributes: \ **postscripts**\ (postscripts.postscripts) - Comma separated list of scripts that should be run on this node after diskful installation or diskless boot. Each script can take zero or more parameters. For example: "script1 p1 p2,script2,...". xCAT automatically adds the postscripts from the xcatdefaults.postscripts attribute of the table to run first on the nodes after install or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. Support will be added in the future for the postscripts attribute to run the scripts before the reboot in AIX. + Comma separated list of scripts that should be run on this node after diskful installation or diskless boot. Each script can take zero or more parameters. For example: "script1 p1 p2,script2,...". xCAT automatically adds the postscripts from the xcatdefaults.postscripts attribute of the table to run first on the nodes after install or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. @@ -881,73 +775,34 @@ node Attributes: \ **prescripts-begin**\ (prescripts.begin) - The scripts to be run at the beginning of the nodeset(Linux), - - - .. code-block:: perl - - nimnodeset(AIX) or mkdsklsnode(AIX) command. - - The format is: - - [action1:]s1,s2...[|action2:s3,s4,s5...] - - where: - - - action1 and action2 for Linux are the nodeset actions specified in the command. - - For AIX, action1 and action1 can be 'diskless' for mkdsklsnode command' - - and 'standalone for nimnodeset command. - - - s1 and s2 are the scripts to run for action1 in order. - - - s3, s4, and s5 are the scripts to run for actions2. - - If actions are omitted, the scripts apply to all actions. - - Examples: - - myscript1,myscript2 (all actions) - - diskless:myscript1,myscript2 (AIX) - - install:myscript1,myscript2|netboot:myscript3 (Linux) - - - - All the scripts should be copied to /install/prescripts directory. - - The following two environment variables will be passed to each script: - - NODES a coma separated list of node names that need to run the script for - - ACTION current nodeset action. - - - - If '#xCAT setting:MAX_INSTANCE=number' is specified in the script, the script - - will get invoked for each node in parallel, but no more than number of instances - - will be invoked at at a time. If it is not specified, the script will be invoked - - once for all the nodes. - + The scripts to be run at the beginning of the nodeset(Linux), nimnodeset(AIX) or mkdsklsnode(AIX) command. + The format is: + [action1:]s1,s2...[| action2:s3,s4,s5...] + where: + - action1 and action2 for Linux are the nodeset actions specified in the command. + For AIX, action1 and action1 can be 'diskless' for mkdsklsnode command' + and 'standalone for nimnodeset command. + - s1 and s2 are the scripts to run for action1 in order. + - s3, s4, and s5 are the scripts to run for actions2. + If actions are omitted, the scripts apply to all actions. + Examples: + myscript1,myscript2 (all actions) + diskless:myscript1,myscript2 (AIX) + install:myscript1,myscript2|netboot:myscript3 (Linux) + All the scripts should be copied to /install/prescripts directory. + The following two environment variables will be passed to each script: + NODES a coma separated list of node names that need to run the script for + ACTION current nodeset action. + If '#xCAT setting:MAX_INSTANCE=number' is specified in the script, the script + will get invoked for each node in parallel, but no more than number of instances + will be invoked at at a time. If it is not specified, the script will be invoked + once for all the nodes. \ **prescripts-end**\ (prescripts.end) - The scripts to be run at the end of the nodeset(Linux), - - - .. code-block:: perl - - nimnodeset(AIX),or mkdsklsnode(AIX) command. - - The format is the same as the 'begin' column. - + The scripts to be run at the end of the nodeset(Linux), nimnodeset(AIX),or mkdsklsnode(AIX) command. The format is the same as the 'begin' column. @@ -977,7 +832,7 @@ node Attributes: \ **protocol**\ (switches.protocol) - Prorocol for running remote commands for the switch. The valid values are: ssh, telnet. ssh is the default. If the sshusername is blank, the username, password and protocol will be retrieved from the passwd table with "switch" as the key. The passwd.comments attribute is used for protocol. + Protocol for running remote commands for the switch. The valid values are: ssh, telnet. ssh is the default. If the sshusername is blank, the username, password and protocol will be retrieved from the passwd table with "switch" as the key. The passwd.comments attribute is used for protocol. @@ -1133,9 +988,7 @@ node Attributes: .. code-block:: perl = number of rows of slots in chassis - = number of columns of slots in chassis - = set to 0 if slots are vertical, and set to 1 if slots of horizontal @@ -1149,7 +1002,7 @@ node Attributes: \ **snmppassword**\ (switches.password) - The password strinng for SNMPv3 or community string for SNMPv1/SNMPv2. Falls back to passwd table, and site snmpc value if using SNMPv1/SNMPv2. + The password string for SNMPv3 or community string for SNMPv1/SNMPv2. Falls back to passwd table, and site snmpc value if using SNMPv1/SNMPv2. @@ -1173,7 +1026,7 @@ node Attributes: \ **status**\ (nodelist.status) - The current status of this node. This attribute will be set by xCAT software. Valid values: defined, booting, netbooting, booted, discovering, configuring, installing, alive, standingby, powering-off, unreachable. If blank, defined is assumed. The possible status change sequenses are: For installaton: defined->[discovering]->[configuring]->[standingby]->installing->booting->booted->[alive], For diskless deployment: defined->[discovering]->[configuring]->[standingby]->netbooting->booted->[alive], For booting: [alive/unreachable]->booting->[alive], For powering off: [alive]->powering-off->[unreachable], For monitoring: alive->unreachable. Discovering and configuring are for x Series dicovery process. Alive and unreachable are set only when there is a monitoring plug-in start monitor the node status for xCAT. Please note that the status values will not reflect the real node status if you change the state of the node from outside of xCAT (i.e. power off the node using HMC GUI). + The current status of this node. This attribute will be set by xCAT software. Valid values: defined, booting, netbooting, booted, discovering, configuring, installing, alive, standingby, powering-off, unreachable. If blank, defined is assumed. The possible status change sequences are: For installation: defined->[discovering]->[configuring]->[standingby]->installing->booting->booted->[alive], For diskless deployment: defined->[discovering]->[configuring]->[standingby]->netbooting->booted->[alive], For booting: [alive/unreachable]->booting->[alive], For powering off: [alive]->powering-off->[unreachable], For monitoring: alive->unreachable. Discovering and configuring are for x Series discovery process. Alive and unreachable are set only when there is a monitoring plug-in start monitor the node status for xCAT. Please note that the status values will not reflect the real node status if you change the state of the node from outside of xCAT (i.e. power off the node using HMC GUI). @@ -1185,15 +1038,9 @@ node Attributes: \ **storagcontroller**\ (storage.controller) - The management address to attach/detach new volumes. - - - .. code-block:: perl - - In the scenario involving multiple controllers, this data must be - - passed as argument rather than by table value - + 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 @@ -1241,7 +1088,7 @@ node Attributes: \ **switchtype**\ (switches.switchtype) - The type of switch. It is used to identify the file name that implements the functions for this swithc. The valid values are: Mellanox, Cisco, BNT and Juniper. + The type of switch. It is used to identify the file name that implements the functions for this switch. The valid values are: Mellanox, Cisco, BNT and Juniper. @@ -1349,7 +1196,7 @@ node Attributes: \ **vmcfgstore**\ (vm.cfgstore) - Optional location for persistant storage separate of emulated hard drives for virtualization solutions that require persistant store to place configuration data + Optional location for persistent storage separate of emulated hard drives for virtualization solutions that require persistant store to place configuration data @@ -1403,7 +1250,7 @@ node Attributes: \ **vmothersetting**\ (vm.othersettings) - This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively,the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. + This allows specifying a semicolon delimited list of key->value pairs to include in a vmx file of VMware or KVM. For partitioning on normal power machines, this option is used to specify the hugepage and/or bsr information, the value is like:'hugepage:1,bsr=2'. For KVM cpu pinning, this option is used to specify the physical cpu set on the host, the value is like:"vcpupin:'0-15,^8'",Its syntax is a comma separated list and a special markup using '-' and '^' (ex. '0-4', '0-3,^2') can also be allowed, the '-' denotes the range and the '^' denotes exclusive. For KVM memory binding, the value is like:'membind:0', restrict a guest to allocate memory from the specified set of NUMA nodes. For PCI passthrough, the value is like:'devpassthrough:pci_0001_01_00_0,pci_0000_03_00_0',the PCI devices are assigned to a virtual machine, and the virtual machine can use this I/O exclusively, the devices list are a list of PCI device names delimited with comma, the PCI device names can be obtained by running \ **virsh nodedev-list**\ on the host. @@ -1445,27 +1292,16 @@ node Attributes: \ **vmvirtflags**\ (vm.virtflags) - General flags used by the virtualization method. For example, in Xen it could, among other things, specify paravirtualized setup, or direct kernel boot. For a hypervisor/dom0 entry, it is the virtualization method (i.e. "xen"). For KVM, the following flag=value pairs are recognized: - - - .. code-block:: perl - - imageformat=[raw|fullraw|qcow2] - - raw is a generic sparse file that allocates storage on demand - - fullraw is a generic, non-sparse file that preallocates all space - - qcow2 is a sparse, copy-on-write capable format implemented at the virtualization layer rather than the filesystem level - - clonemethod=[qemu-img|reflink] - - qemu-img allows use of qcow2 to generate virtualization layer copy-on-write - - reflink uses a generic filesystem facility to clone the files on your behalf, but requires filesystem support such as btrfs - - placement_affinity=[migratable|user_migratable|pinned] - + General flags used by the virtualization method. + For example, in Xen it could, among other things, specify paravirtualized setup, or direct kernel boot. For a hypervisor/dom0 entry, it is the virtualization method (i.e. "xen"). For KVM, the following flag=value pairs are recognized: + imageformat=[raw|fullraw|qcow2] + raw is a generic sparse file that allocates storage on demand + fullraw is a generic, non-sparse file that preallocates all space + qcow2 is a sparse, copy-on-write capable format implemented at the virtualization layer rather than the filesystem level + clonemethod=[qemu-img|reflink] + qemu-img allows use of qcow2 to generate virtualization layer copy-on-write + reflink uses a generic filesystem facility to clone the files on your behalf, but requires filesystem support such as btrfs + placement_affinity=[migratable|user_migratable|pinned] diff --git a/docs/source/guides/admin-guides/references/man7/osimage.7.rst b/docs/source/guides/admin-guides/references/man7/osimage.7.rst index 23ac6bd49..a88927474 100644 --- a/docs/source/guides/admin-guides/references/man7/osimage.7.rst +++ b/docs/source/guides/admin-guides/references/man7/osimage.7.rst @@ -261,7 +261,7 @@ osimage Attributes: \ **otherpkglist**\ (linuximage.otherpkglist) - The fully qualified name of the file that stores non-distro package lists that will be included in the image. It could be set multiple paths.The multiple paths must be seperated by ",". + The fully qualified name of the file that stores non-distro package lists that will be included in the image. It could be set to multiple paths. The multiple paths must be separated by ",". @@ -279,7 +279,7 @@ osimage Attributes: \ **partitionfile**\ (linuximage.partitionfile, winimage.partitionfile) - The path of the configuration file which will be used to partition the disk for the node. For stateful osimages,two types of files are supported: "" which contains a partitioning definition that will be inserted directly into the generated autoinst configuration file and must be formatted for the corresponding OS installer (e.g. kickstart for RedHat, autoyast for SLES, pressed for Ubuntu). "s:" which specifies a shell script that will be run from the OS installer configuration file %pre section; the script must write the correct partitioning definition into the file /tmp/partitionfile on the node which will be included into the configuration file during the install process. For statelite osimages, partitionfile should specify ""; see the xCAT Statelite documentation for the xCAT defined format of this configuration file.For Ubuntu, besides "" or "s:", the disk name(s) to partition must be specified in traditional, non-devfs format, delimited with space, it can be specified in 2 forms: "d:" which contains the disk name(s) to partition and "s:d:" which runs in pressed/early_command and writes the disk names into the "/tmp/install_disk" . To support other specific partition methods such as RAID or LVM in Ubuntu, some additional preseed values should be specified, these values can be specified with "c:" which contains the additional pressed entries in "d-i ..." form and "s:c:" which runs in pressed/early_command and set the preseed values with "debconf-set". The multiple values should be delimited with comma "," + The path of the configuration file which will be used to partition the disk for the node. For stateful osimages,two types of files are supported: "" which contains a partitioning definition that will be inserted directly into the generated autoinst configuration file and must be formatted for the corresponding OS installer (e.g. kickstart for RedHat, autoyast for SLES, pressed for Ubuntu). "s:" which specifies a shell script that will be run from the OS installer configuration file %pre section; the script must write the correct partitioning definition into the file /tmp/partitionfile on the node which will be included into the configuration file during the install process. For statelite osimages, partitionfile should specify ""; see the xCAT Statelite documentation for the xCAT defined format of this configuration file.For Ubuntu, besides "" or "s:", the disk name(s) to partition must be specified in traditional, non-devfs format, delimited with space, it can be specified in 2 forms: "d:" which contains the disk name(s) to partition and "s:d:" which runs in pressed/early_command and writes the disk names into the "/tmp/xcat.install_disk" . To support other specific partition methods such as RAID or LVM in Ubuntu, some additional preseed values should be specified, these values can be specified with "c:" which contains the additional pressed entries in "d-i ..." form and "s:c:" which runs in pressed/early_command and set the preseed values with "debconf-set". The multiple values should be delimited with comma "," or @@ -295,7 +295,7 @@ osimage Attributes: \ **pkgdir**\ (linuximage.pkgdir) - The name of the directory where the distro packages are stored. It could be set multiple paths.The multiple paths must be seperated by ",". The first path in the value of osimage.pkgdir must be the OS base pkg dir path, such as pkgdir=/install/rhels6.2/x86_64,/install/updates . In the os base pkg path, there are default repository data. And in the other pkg path(s), the users should make sure there are repository data. If not, use "createrepo" command to create them. For ubuntu, multiple mirrors can be specified in the pkgdir attribute, the mirrors must be prefixed by the protocol(http/ssh) and delimited with "," between each other. + The name of the directory where the distro packages are stored. It could be set to multiple paths. The multiple paths must be separated by ",". The first path in the value of osimage.pkgdir must be the OS base pkg dir path, such as pkgdir=/install/rhels6.2/x86_64,/install/updates . In the os base pkg path, there are default repository data. And in the other pkg path(s), the users should make sure there are repository data. If not, use "createrepo" command to create them. For ubuntu, multiple mirrors can be specified in the pkgdir attribute, the mirrors must be prefixed by the protocol(http/ssh) and delimited with "," between each other. @@ -313,13 +313,13 @@ osimage Attributes: \ **postinstall**\ (linuximage.postinstall) - The fully qualified name of the script file that will be run at the end of the genimage command. It could be set multiple paths.The multiple paths must be seperated by ",". It is used for diskless image only. + The fully qualified name of the script file that will be run at the end of the genimage command. It could be set to multiple paths. The multiple paths must be separated by ",". It is used for diskless image only. \ **postscripts**\ (osimage.postscripts) - Comma separated list of scripts that should be run on this image after diskful installation or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. See the site table runbootscripts attribute. Support will be added in the future for the postscripts attribute to run the scripts before the reboot in AIX. + Comma separated list of scripts that should be run on this image after diskful installation or diskless boot. For installation of RedHat, CentOS, Fedora, the scripts will be run before the reboot. For installation of SLES, the scripts will be run after the reboot but before the init.d process. For diskless deployment, the scripts will be run at the init.d time, and xCAT will automatically add the list of scripts from the postbootscripts attribute to run after postscripts list. For installation of AIX, the scripts will run after the reboot and acts the same as the postbootscripts attribute. For AIX, use the postbootscripts attribute. See the site table runbootscripts attribute. diff --git a/docs/source/guides/admin-guides/references/man8/mknb.8.rst b/docs/source/guides/admin-guides/references/man8/mknb.8.rst index e7753beb2..119a369ef 100644 --- a/docs/source/guides/admin-guides/references/man8/mknb.8.rst +++ b/docs/source/guides/admin-guides/references/man8/mknb.8.rst @@ -27,14 +27,14 @@ DESCRIPTION *********** -The \ **mknb**\ command is run by xCAT automatically, when xCAT is installed on the management node. +The \ **mknb**\ command is run by xCAT automatically when xCAT is installed on the management node. It creates a network boot root image (used for node discovery, BMC programming, and flashing) -for the same architecture that the management node is. So you normally do not need to run the \ **mknb**\ -command yourself. +for the same architecture that the management node is. So you normally do not need to run the +\ **mknb**\ command yourself. -If you do run \ **mknb**\ to add custom utilities to your boot root image, and you have an xCAT Hierarchical Cluster with service nodes that each have a local /tftpboot directory (site sharedtftp=0), you will also need to copy the generated root image to each service node. +If you make custom changes to the network boot root image, you will need to run \ **mknb**\ again to regenerate the diskless image to include your changes. If you have an xCAT Hierarchical Cluster with Service Nodes having local /tftpboot directories (site.sharedtftp=0), you will need to copy the generated root image to each Service Node. -Presently, only the arch x86_64 is supported. +Presently, the architectures x86_64 and ppc64 are supported. For ppc64le, use the ppc64 architecture. ******* @@ -45,7 +45,7 @@ OPTIONS \ *arch*\ - The hardware architecture for which to build the boot image: x86_64 + The hardware architecture for which to build the boot image. diff --git a/docs/source/guides/admin-guides/references/man8/nodeset.8.rst b/docs/source/guides/admin-guides/references/man8/nodeset.8.rst index d8c0be67f..23ec24e23 100644 --- a/docs/source/guides/admin-guides/references/man8/nodeset.8.rst +++ b/docs/source/guides/admin-guides/references/man8/nodeset.8.rst @@ -19,7 +19,7 @@ Name **************** -\ **nodeset**\ \ *noderange*\ [\ **boot**\ | \ **stat**\ | \ **iscsiboot**\ | \ **offline**\ | \ **runcmd=bmcsetup**\ | \ **osimage**\ [=\ *imagename*\ ] | \ **shell**\ | \ **shutdown**\ ] +\ **nodeset**\ \ *noderange*\ [\ **boot**\ | \ **stat**\ | \ **offline**\ | \ **runcmd=bmcsetup**\ | \ **osimage**\ [=\ *imagename*\ ] | \ **shell**\ | \ **shutdown**\ ] \ **nodeset**\ \ *noderange*\ \ **osimage**\ [=\ *imagename*\ ] [\ **-**\ **-noupdateinitrd**\ ] [\ **-**\ **-ignorekernelchk**\ ] @@ -50,7 +50,7 @@ Assume that /tftpboot is the root for tftpd (set in site(5)|site.5). \ **nodeset**\ only sets the next boot state, but does not reboot. -\ **nodeset**\ is called by rinstall and winstall and is also called by the +\ **nodeset**\ is called by \ **rinstall**\ and \ **winstall**\ and is also called by the installation process remotely to set the boot state back to "boot". A user can supply their own scripts to be run on the mn or on the service node (if a hierarchical cluster) for a node when the nodeset command is run. Such scripts are called \ **prescripts**\ . They should be copied to /install/prescripts dirctory. A table called \ *prescripts*\ is used to specify the scripts and their associated actions. The scripts to be run at the beginning of the nodeset command are stored in the 'begin' column of \ *prescripts*\ table. The scripts to be run at the end of the nodeset command are stored in the 'end' column of \ *prescripts*\ table. You can run 'tabdump -d prescripts' command for details. The following two environment variables will be passed to each script: NODES contains all the names of the nodes that need to run the script for and ACTION contains the current nodeset action. If \ *#xCAT setting:MAX_INSTANCE=number*\ is specified in the script, the script will get invoked for each node in parallel, but no more than \ *number*\ of instances will be invoked at at a time. If it is not specified, the script will be invoked once for all the nodes. @@ -82,8 +82,8 @@ A user can supply their own scripts to be run on the mn or on the service node ( \ **-**\ **-noupdateinitrd**\ - Skip the rebuilding of initrd when the 'netdrivers', 'drvierupdatesrc' or 'osupdatename' were set for injecting new drviers to initrd. But, the geninitrd command - should be run to rebuild the initrd for new drivers injecting. This is used to improve the performance of nodeset command. + Skip the rebuilding of initrd when the 'netdrivers', 'drvierupdatesrc' or 'osupdatename' were set for injecting new drivers to initrd. But, the \ **geninitrd**\ command + should be run to rebuild the initrd for new drivers injecting. This is used to improve the performance of \ **nodeset**\ command. diff --git a/docs/source/guides/admin-guides/references/man8/rinstall.8.rst b/docs/source/guides/admin-guides/references/man8/rinstall.8.rst index 73ffc705d..0e06cd9e6 100644 --- a/docs/source/guides/admin-guides/references/man8/rinstall.8.rst +++ b/docs/source/guides/admin-guides/references/man8/rinstall.8.rst @@ -19,7 +19,11 @@ Name **************** -\ **rinstall**\ [\ **-O | -**\ **-osimage**\ ] [\ **-c | -**\ **-console**\ ] [\ *noderange*\ ] +\ **rinstall**\ \ *noderange*\ \ **boot**\ | \ **shell**\ | \ **runcmd=bmcsetup**\ [\ **-c | -**\ **-console**\ ] [\ **-V | -**\ **-verbose**\ ] + +\ **rinstall**\ \ *noderange*\ \ **osimage**\ =\ *imagename*\ | [\ **-O**\ ] \ *imagename*\ [\ **-**\ **-ignorekernelchk**\ ] [\ **-c | -**\ **-console**\ ] [\ **-u | -**\ **-uefimode**\ ] [\ **-V | -**\ **-verbose**\ ] + +\ **rinstall**\ [\ **-h | -**\ **-help | -v | -**\ **-version**\ ] ******************* @@ -27,9 +31,9 @@ Name ******************* -\ **rinstall**\ is a convenience command that will change tables as requested for operating system version, profile, and architecture, call \ **nodeset**\ to modify the network boot configuration, call \ **rsetboot**\ net to set the next boot over network (only support nodes with "nodetype.mgt=ipmi", for other nodes, make sure the correct boot order has been set before \ **rinstall**\ ), and \ **rpower**\ to begin a boot cycle. +\ **rinstall**\ is a convenience command to begin OS provision on a noderange(support nodes with "nodetype.mgt=ipmi,blade,hmc,ivm,fsp,kvm,esx,rhevm"). -If [\ **-O | -**\ **-osimage**\ ] is specified or nodetype.provmethod=\ **osimage**\ is set, provision the noderange with the osimage specified/configured, ignore the table change options if specified. +If \ **osimage**\ =\ *imagename*\ | \ **-O**\ \ *imagename*\ is specified or nodetype.provmethod=\ **osimage**\ is set, provision the noderange with the osimage specified/configured. If -c is specified, it will then run rcons on the node. This is allowed only if one node in the noderange. If need consoles on multiple nodes , see winstall(8)|winstall.8. @@ -40,6 +44,44 @@ If -c is specified, it will then run rcons on the node. This is allowed only if +\ **boot**\ + + Instruct network boot loader to be skipped, generally meaning boot to hard disk + + + +\ **osimage | osimage=**\ \ *imagename*\ |\ **-O**\ \ *imagename*\ + + Prepare server for installing a node using the specified os image. The os image is defined in the \ *osimage*\ table and \ *linuximage*\ table. If the is omitted, the os image name will be obtained from \ *nodetype.provmethod*\ for the node. + + + +\ **-**\ **-ignorekernelchk**\ + + Skip the kernel version checking when injecting drivers from osimage.driverupdatesrc. That means all drivers from osimage.driverupdatesrc will be injected to initrd for the specific target kernel. + + + +\ **runimage**\ =\ *task*\ + + If you would like to run a task after deployment, you can define that task with this attribute. + + + +\ **runcmd=bmcsetup**\ + + This instructs the node to boot to the xCAT nbfs environment and proceed to configure BMC + for basic remote access. This causes the IP, netmask, gateway, username, and password to be programmed according to the configuration table. + + + +\ **shell**\ + + This instructs tho node to boot to the xCAT genesis environment, and present a shell prompt on console. + The node will also be able to be sshed into and have utilities such as wget, tftp, scp, nfs, and cifs. It will have storage drivers available for many common systems. + + + \ **-h | -**\ **-help**\ Display usage message. @@ -52,15 +94,21 @@ If -c is specified, it will then run rcons on the node. This is allowed only if -\ **-O | -**\ **-osimage**\ +\ **-u | -**\ **-uefimode**\ - Specifies the osimage to provision. + For BMC-based servers, to specify the next boot mode to be "UEFI Mode". + + + +\ **-V | -**\ **-Verbose**\ + + Verbose output. \ **-c | -**\ **-console**\ - Requests that rinstall runs rcons once the provision starts. This will only work if there is only one node in the noderange. See winstall(8)|winstall.8 for starting nsoles on multiple nodes. + Requests that rinstall runs rcons once the provision starts. This will only work if there is only one node in the noderange. See winstall(8)|winstall.8 for starting consoles on multiple nodes. @@ -86,7 +134,7 @@ If -c is specified, it will then run rcons on the node. This is allowed only if .. code-block:: perl - rinstall node1-node20 -O rhels6.4-ppc64-netboot-compute + rinstall node1-node20 osimage=rhels6.4-ppc64-netboot-compute diff --git a/docs/source/guides/admin-guides/references/man8/tabprune.8.rst b/docs/source/guides/admin-guides/references/man8/tabprune.8.rst index aa0a5a78a..58c489334 100644 --- a/docs/source/guides/admin-guides/references/man8/tabprune.8.rst +++ b/docs/source/guides/admin-guides/references/man8/tabprune.8.rst @@ -19,7 +19,7 @@ SYNOPSIS ******** -\ **tabprune**\ [\ **eventlog | auditlog**\ ] [\ **-V**\ ] [\ **-i**\ \ *recid*\ |\ **-n**\ \ *number of records*\ | \ **-p**\ \ *percentage*\ | \ **-d**\ \ *number of days*\ | \ **-a**\ ] +\ **tabprune**\ [\ **eventlog | auditlog**\ ] [\ **-V**\ ] [\ **-i**\ \ *recid*\ | \ **-n**\ \ *number of records*\ | \ **-p**\ \ *percentage*\ | \ **-d**\ \ *number of days*\ | \ **-a**\ ] \ **tabprune**\ \ *tablename*\ \ **-a**\ diff --git a/docs/source/guides/admin-guides/references/man8/winstall.8.rst b/docs/source/guides/admin-guides/references/man8/winstall.8.rst index 2830397dd..cfe21170c 100644 --- a/docs/source/guides/admin-guides/references/man8/winstall.8.rst +++ b/docs/source/guides/admin-guides/references/man8/winstall.8.rst @@ -19,9 +19,11 @@ Name **************** -\ **winstall**\ [\ **-o | -**\ **-osver**\ ] [\ **-p | -**\ **-profile**\ ] [\ **-a | -**\ **-arch**\ ] [\ *noderange*\ ] +\ **rinstall**\ \ *noderange*\ \ **boot**\ | \ **shell**\ | \ **runcmd=bmcsetup**\ [\ **-c | -**\ **-console**\ ] [\ **-V | -**\ **-verbose**\ ] -\ **winstall**\ [\ **-O | -**\ **-osimage**\ ] [\ *noderange*\ ] +\ **rinstall**\ \ *noderange*\ \ **osimage**\ =\ *imagename*\ | [\ **-O**\ ] \ *imagename*\ [\ **-**\ **-ignorekernelchk**\ ] [\ **-c | -**\ **-console**\ ] [\ **-u | -**\ **-uefimode**\ ] [\ **-V | -**\ **-verbose**\ ] + +\ **rinstall**\ [\ **-h | -**\ **-help | -v | -**\ **-version**\ ] ******************* @@ -29,10 +31,9 @@ Name ******************* -\ **winstall**\ is a convenience tool that will change attributes as requested for operating system version, profile, and architecture, call \ **nodeset**\ to modify the network boot configuration, call \ **rsetboot**\ net to set the next boot over network (only support nodes -with "nodetype.mgt=ipmi", for other nodes, make sure the correct boot order has been set before \ **winstall**\ ), and \ **rpower**\ to begin a boot cycle. +\ **winstall**\ is a convenience command to begin OS provision on a noderange(support nodes with "nodetype.mgt=ipmi,blade,hmc,ivm,fsp,kvm,esx,rhevm"). -If [\ **-O | -**\ **-osimage**\ ] is specified or nodetype.provmethod=\ *osimage*\ is set, provision the noderange with the osimage specified/configured, ignore the table change options if specified. +If \ **osimage**\ =\ *imagename*\ | \ **-O**\ \ *imagename*\ is specified or nodetype.provmethod=\ **osimage**\ is set, provision the noderange with the osimage specified/configured. It will then run wcons on the nodes. @@ -43,6 +44,44 @@ It will then run wcons on the nodes. +\ **boot**\ + + Instruct network boot loader to be skipped, generally meaning boot to hard disk + + + +\ **osimage | osimage=**\ \ *imagename*\ |\ **-O**\ \ *imagename*\ + + Prepare server for installing a node using the specified os image. The os image is defined in the \ *osimage*\ table and \ *linuximage*\ table. If the is omitted, the os image name will be obtained from \ *nodetype.provmethod*\ for the node. + + + +\ **-**\ **-ignorekernelchk**\ + + Skip the kernel version checking when injecting drivers from osimage.driverupdatesrc. That means all drivers from osimage.driverupdatesrc will be injected to initrd for the specific target kernel. + + + +\ **runimage**\ =\ *task*\ + + If you would like to run a task after deployment, you can define that task with this attribute. + + + +\ **runcmd=bmcsetup**\ + + This instructs the node to boot to the xCAT nbfs environment and proceed to configure BMC + for basic remote access. This causes the IP, netmask, gateway, username, and password to be programmed according to the configuration table. + + + +\ **shell**\ + + This instructs tho node to boot to the xCAT genesis environment, and present a shell prompt on console. + The node will also be able to be sshed into and have utilities such as wget, tftp, scp, nfs, and cifs. It will have storage drivers available for many common systems. + + + \ **-h | -**\ **-help**\ Display usage message. @@ -55,27 +94,21 @@ It will then run wcons on the nodes. -\ **-o | -**\ **-osver**\ +\ **-u | -**\ **-uefimode**\ - Specifies which os version to provision. If unspecified, the current node os setting is used. Will be ignored if [\ *-O*\ |\ *--osimage*\ ] is specified or nodetype.provmethod=\ *osimage*\ . + For BMC-based servers, to specify the next boot mode to be "UEFI Mode". -\ **-p | -**\ **-profile**\ +\ **-V | -**\ **-Verbose**\ - Specifies what profile should be used of the operating system. If not specified the current node profile setting is used. Will be ignored if [\ *-O*\ |\ *--osimage*\ ] is specified or nodetype.provmethod=\ *osimage*\ . + Verbose output. -\ **-a | -**\ **-arch**\ +\ **-c | -**\ **-console**\ - Specifies what architecture of the OS to provision. Typically this is unneeded, but if provisioning between x86_64 and x86 frequently, this may be a useful flag. Will be ignored if [\ *-O*\ |\ *--osimage*\ ] is specified or nodetype.provmethod=\ *osimage*\ . - - - -\ **-O | -**\ **-osimage**\ - - Specifies the osimage to provision. + Requests that rinstall runs rcons once the provision starts. This will only work if there is only one node in the noderange. See winstall(8)|winstall.8 for starting consoles on multiple nodes. @@ -96,17 +129,7 @@ It will then run wcons on the nodes. -2. Provision nodes 1 through 20, forcing rhels5.1 and compute profile. - - - .. code-block:: perl - - winstall node1-node20 -o rhels5.1 -p compute - - - - -3. Provision nodes 1 through 20 with the osimage rhels6.4-ppc64-netboot-compute. +2. Provision nodes 1 through 20 with the osimage rhels6.4-ppc64-netboot-compute. .. code-block:: perl diff --git a/docs/source/guides/admin-guides/references/man8/xcatdebug.8.rst b/docs/source/guides/admin-guides/references/man8/xcatdebug.8.rst index 9b786f0be..6a32f61e7 100644 --- a/docs/source/guides/admin-guides/references/man8/xcatdebug.8.rst +++ b/docs/source/guides/admin-guides/references/man8/xcatdebug.8.rst @@ -38,7 +38,7 @@ The trace message includes: The name of the called subroutine; The arguments whi The flag \ **-c**\ is used to specify the subroutine list for \ **subroutine calling trace**\ , it can only work with \ **-f**\ . The value of \ **-c**\ can be a configuration file or a subroutine list. \ **configuration file**\ : a file contains multiple lines of \ **SUBROUTINE_DEFINITION**\ - \ **subroutine list**\ : \ **SUBROUTINE_DEFINITION | SUBROUTINE_DEFINITION**\ |... + \ **subroutine list**\ : \ **SUBROUTINE_DEFINITION | SUBROUTINE_DEFINITION|...**\ \ **SUBROUTINE_DEFINITION**\ : is the element for the \ **-c**\ to specify the subroutine list. @@ -109,7 +109,7 @@ OPTIONS xCAT_plugin::DBobjectdefs(defls,process_request) xCAT::DBobjUtils(getobjdefs) - \ **subroutine list**\ : a string like \ **SUBROUTINE_DEFINITION | SUBROUTINE_DEFINITION**\ |... + \ **subroutine list**\ : a string like \ **SUBROUTINE_DEFINITION | SUBROUTINE_DEFINITION|...**\ e.g. "(plugin_command)|xCAT_plugin::DBobjectdefs(defls,process_request)|xCAT::DBobjUtils(getobjdefs)" @@ -131,32 +131,62 @@ EXAMPLES 1. Enable the \ **subroutine calling trace**\ for all the subroutines in the xcatd and plugin modules. - xcatdebug -f enable - + + + .. code-block:: perl + + xcatdebug -f enable + + 2. Enable the \ **subroutine calling trace**\ for the subroutines configured in the /opt/xcat/share/xcat/samples/tracelevel0 - xcatdebug -f enable -c /opt/xcat/share/xcat/samples/tracelevel0 - + + + .. code-block:: perl + + xcatdebug -f enable -c /opt/xcat/share/xcat/samples/tracelevel0 + + 3. Enable the \ **subroutine calling trace**\ for the plugin_command in xcatd and defls,process_request in the xCAT_plugin::DBobjectdefs module. - xcatdebug -f enable -c "xCAT_plugin::DBobjectdefs(defls,process_request)|(plugin_command)" - + + + .. code-block:: perl + + xcatdebug -f enable -c "xCAT_plugin::DBobjectdefs(defls,process_request)|(plugin_command)" + + 4. Disable the \ **subroutine calling trace**\ for all the subroutines which have been enabled by \ **xcatdebug -f enable**\ . - xcatdebug -f disable - + + + .. code-block:: perl + + xcatdebug -f disable + + 5. Enable the \ **commented trace log**\ - xcatdebug -d enable - + + + .. code-block:: perl + + xcatdebug -d enable + + 6. Enable both the \ **subroutine calling trace**\ and \ **commented trace log**\ - xcatdebug -f enable -c /opt/xcat/share/xcat/samples/tracelevel0 -d enable - + + + .. code-block:: perl + + xcatdebug -f enable -c /opt/xcat/share/xcat/samples/tracelevel0 -d enable + + diff --git a/docs/source/guides/install-guides/apt/update_xcat.rst b/docs/source/guides/install-guides/apt/update_xcat.rst index 44412b88b..dfa08f6f5 100644 --- a/docs/source/guides/install-guides/apt/update_xcat.rst +++ b/docs/source/guides/install-guides/apt/update_xcat.rst @@ -3,6 +3,6 @@ Updating xCAT If at a later date you want to update xCAT, first, update the software repositories and then run: :: apt-get update - apt-get upgrade xcat + apt-get --only-upgrade install xcat* diff --git a/docs/source/guides/install-guides/common/uninstall_xcat.rst b/docs/source/guides/install-guides/common/uninstall_xcat.rst deleted file mode 100644 index 6e04ddb6b..000000000 --- a/docs/source/guides/install-guides/common/uninstall_xcat.rst +++ /dev/null @@ -1,238 +0,0 @@ -Remove xCAT -=========== - -Backup xCAT User Data ---------------------- - -Before removing xCAT, recommend to backup xCAT database. It's convenient to restore xCAT management environment in the future if needed. :: - - dumpxCATdb -p - -For more information of ``dumpxCATdb``, please refer to :doc:`command dumpxCATdb `. For how to restore xcat DB, please refer to `Restore xCAT User Data`_. - -Clean Up xCAT Related Configuration ------------------------------------ - -1. To clean up the node information from dhcp :: - - makedhcp -d -a - -2. To clean up the node information in tftpboot :: - - nodeset all offline - -3. To clean up the node information from ``/etc/hosts`` (optional) - - Keep xCAT nodes information in ``/etc/hosts`` is harmless. But if really need to remove them from ``/etc/hosts``, you can edit ``/etc/hosts`` by 'vi' directly, or using xCAT command ``makehosts``. :: - - makehosts -d all - -4. To clean up the node information from DNS (optional) - - After removing all the nodes from ``/etc/hosts``, run below command to clean up the node information from DNS. :: - - makedns -n - -Stop xCAT Service ------------------ - -1. Stop xCAT service :: - - service xcatd stop - -2. Stop xCAT related services(Optional) - - XCAT uses various network services on the management node and service nodes, the network services setup by xCAT may need to be cleaned up on the management node and service nodes before uninstalling xCAT. - -* **NFS** : Stop nfs service, unexport all the file systems exported by xCAT, and remove the xCAT file systems from ``/etc/exports``. -* **HTTP**: Stop http service, remove the xcat.conf in the http configuration directory. -* **TFTP**: Stop tftp service, remove the tftp files created by xCAT in tftp directory. -* **DHCP**: Stop dhcp service, remove the configuration made by xCAT in dhcp configuration files. -* **DNS** : Stop the named service, remove the named entries created by xCAT from the named database. - -Remove xCAT Files ------------------ - -1. Remove the xCAT RPMs - - There is no easy way to distinct all the packages depending by xCAT. For packages shipped by xCAT, you can remove them by the commands below. - - [RHEL and SLES] :: - - rpm -qa |grep -i xcat - - [Ubuntu] :: - - dpkg -l | awk '/xcat/ { print $2 }' - - If you want to remove more cleanly. below list maybe helpful for you. They are the packages list of xcat installation tarball. These list are the whole RPMs list, it's possible for some RPMs not to be installed due to them are not suitable for your environment. Please do judgment by yourself. - - * XCAT Core Packages list (xcat-core): - - [RHEL and SLES] :: - - perl-xCAT - xCAT - xCAT-buildkit - xCAT-client - xCAT-confluent - xCAT-genesis-scripts-ppc64 - xCAT-genesis-scripts-x86_64 - xCAT-server - xCATsn - xCAT-SoftLayer - xCAT-test - xCAT-vlan - - [Ubuntu] :: - - perl-xcat - xcat - xcat-buildkit - xcat-client - xcat-confluent - xcat-genesis-scripts - xcat-server - xcatsn - xcat-test - xcat-vlan - - * XCAT Dependency Packages (xcat-dep): - - [RHEL and SLES] :: - - conserver-xcat - cpio - cpio-lang - elilo-xcat - esxboot-xcat - fping - ganglia-devel - ganglia-gmetad - ganglia-gmond - ganglia-gmond-modules-python - ganglia-web - grub2-xcat - ipmitool-xcat - libconfuse - libconfuse-devel - libganglia - lldpd - net-snmp-perl - perl-AppConfig - perl-Compress-Raw-Zlib - perl-Crypt-Blowfish - perl-Crypt-CBC - perl-Crypt-Rijndael - perl-Crypt-SSLeay - perl-DBD-DB2 - perl-DBD-DB2Lite - perl-DBD-Pg - perl-DBD-SQLite - perl-Expect - perl-HTML-Form - perl-IO-Compress-Base - perl-IO-Compress-Zlib - perl-IO-Socket-SSL - perl-IO-Stty - perl-IO-Tty - perl-JSON - perl-Net-DNS - perl-Net-Telnet - perl-SOAP-Lite - perl-Test-Manifest - perl-version - perl-XML-Simple - pyodbc - rrdtool - scsi-target-utils - stunnel - syslinux-xcat - systemconfigurator - systemimager-client - systemimager-common - systemimager-server - xCAT-genesis-base-ppc64 - xCAT-genesis-base-x86_64 - xCAT-genesis-x86_64 - xCAT-UI-deps - xnba-kvm - xnba-undi - yaboot-xcat - zhcp - - [Ubuntu] :: - - conserver-xcat - elilo-xcat - grub2-xcat - ipmitool-xcat - syslinux - syslinux-extlinux - syslinux-xcat - xcat-genesis-base-amd64 - xcat-genesis-base-ppc64 - xnba-undi - - Along with xCAT development, above list maybe change, you can get the latest list through below links: - - - * XCAT Core Packages List (xcat-core) - - [RHEL and SLES] :: - - http://xcat.org/files/xcat/repos/yum//xcat-core/ - - [Ubuntu] :: - - http://xcat.org/files/xcat/repos/apt//xcat-core/ - - * XCAT Dependency Packages (xcat-dep) - - `RPM Packages List (RHEL and SLES) `_ - - `Debian Packages List (Ubuntu) `_ - - - Generally, we use ``yum install xCAT`` to install xCAT, so these are some RPMs shipped by operating system are installed during xCAT installation. We don't have an easy way to find out all of them, but keep these RPMs are harmless. - - -2. Remove xCAT certificate file :: - - rm -rf /root/.xcat - -3. Remove xCAT data file - - By default, xCAT use SQLite, remove SQLite data file under ``/etc/xcat/``. :: - - rm -rf /etc/xcat - -4. Remove xCAT related file(Optional) - - XCAT has ever operated below directory when it was running. Do judgment by yourself before removing these directory, to avoid removing some directories used for other purpose in your environment. :: - - /install - /tftpboot - /etc/yum.repos.d/xCAT-* - /etc/sysconfig/xcat - /etc/apache2/conf.d/xCAT-* - /etc/logrotate.d/xCAT-* - /etc/rsyslogd.d/xCAT-* - /var/log/xcat - /opt/xcat/ - /mnt/xcat - -Remove Databases ----------------- - -* For PostgreSQL: See :doc:`Removing xCAT DB from PostgreSQL `. -* For MySQL/MariaDB: See :doc:`Removing xCAT DB from MySQL/MariaDB `. - -Restore xCAT User Data ----------------------- - -If need to restore xCAT environment, after :doc:`xCAT software installation `, you can restore xCAT DB by data files dumped in the past. :: - - restorexCATdb -p - -For more information of ``restorexCATdb``, please refer to :doc:`command restorexCATdb `. diff --git a/docs/source/guides/install-guides/common_sections.rst b/docs/source/guides/install-guides/common_sections.rst index b4646a0cb..840532675 100644 --- a/docs/source/guides/install-guides/common_sections.rst +++ b/docs/source/guides/install-guides/common_sections.rst @@ -188,22 +188,22 @@ xCAT is started automatically after the installation, but the following commands * start xCAT: :: service xcatd start - [systemd] systemctl xcatd.service start + [systemd] systemctl start xcatd.service * stop xCAT: :: service xcatd stop - [systemd] systemctl xcatd.service stop + [systemd] systemctl stop xcatd.service * restart xCAT: :: service xcatd restart - [systemd] systemctl xcatd.service restart + [systemd] systemctl restart xcatd.service * check xCAT status: :: service xcatd status - [systemd] systemctl xcatd.service status + [systemd] systemctl status xcatd.service .. END_verifying_xcat diff --git a/docs/source/guides/install-guides/index.rst b/docs/source/guides/install-guides/index.rst index 07a08b77d..09a92b510 100644 --- a/docs/source/guides/install-guides/index.rst +++ b/docs/source/guides/install-guides/index.rst @@ -1,3 +1,5 @@ +.. _install_guides: + Install Guides ============== diff --git a/docs/source/overview/xcat2_release.rst b/docs/source/overview/xcat2_release.rst index 7ed15f5b3..1f128f855 100644 --- a/docs/source/overview/xcat2_release.rst +++ b/docs/source/overview/xcat2_release.rst @@ -7,6 +7,33 @@ The following table is a summary of the new operating system (OS), hardware, and * **SLES** - Suse Linux Enterprise Server * **UBT** - Ubuntu +xCAT 2.12.x +----------- + ++---------------------------------+---------------+-------------+----------------------------------+ +|xCAT |New OS |New |New Feature | +|Version | |Hardware | | ++=================================+===============+=============+==================================+ +|| xCAT 2.12.1 | | |- New xCAT install tool: go-xcat | +|| 2016/07/08 | | |- New opt: mkdef/lsdef --template | +|| | | |- Support rinstall for all OS/ARCH| +| `2.12.1 Release Notes `_ | | |- rscan | +| | | |- New: xcatprobe (experimental) | ++---------------------------------+---------------+-------------+----------------------------------+ +|| xCAT 2.12 |- RHEL 6.8 | |- Docker: xCAT in Docker | +|| 2016/5/20 |- UBT 14.4.4 LE| |- Docker: container life cycle mgt| +|| |- UBT 16.04 | |- Docker: Set up Docker Registry | +| `2.12 Release Notes `_ | | |- Add site.xcatdebugmode | +| | | |- Add switchdiscover -s snmp | +| | | |- Disable auditlog by default | +| | | |- Add site.hierarchicalattrs | ++---------------------------------+---------------+-------------+----------------------------------+ + + xCAT 2.11.x ----------- @@ -14,6 +41,13 @@ xCAT 2.11.x |xCAT |New OS |New |New Feature | |Version | |Hardware | | +=================================+===============+=============+==================================+ +|| xCAT 2.11.1 | | |- Bug fix | +|| 2016/04/22 | | | | +|| | | | | +| `2.11.1 Release Notes `_ | | | | ++---------------------------------+---------------+-------------+----------------------------------+ || xCAT 2.11 |- RHEL 7.2 LE |- S822LC(GCA)|- NVIDIA GPU for OpenPOWER | || 2015/12/11 |- UBT 14.4.3 LE|- S822LC(GTA)|- Infiniband for OpenPOWER | || |- UBT 15.10 LE |- S812LC |- SW KIT support for OpenPOWER | diff --git a/docs/source/security/index.rst b/docs/source/security/index.rst index 4f9535ac9..9952ab44f 100644 --- a/docs/source/security/index.rst +++ b/docs/source/security/index.rst @@ -5,4 +5,3 @@ Security Notices :maxdepth: 2 2016/index.rst - 2015/index.rst diff --git a/docs/source/troubleshooting/index.rst b/docs/source/troubleshooting/index.rst index 5d1f1124c..d8f69a11b 100644 --- a/docs/source/troubleshooting/index.rst +++ b/docs/source/troubleshooting/index.rst @@ -1,7 +1,7 @@ Troubleshooting =============== -This chapter introduces the methods of how to troubleshoot a real cluster. Basically, it includes the following parts. +This chapter introduces the methods of troubleshooting a xCAT cluster. It includes the following parts. .. toctree:: :maxdepth: 2 diff --git a/docs/source/troubleshooting/os_installation/debug_port.rst b/docs/source/troubleshooting/os_installation/debug_port.rst index c80d891be..f5d043892 100644 --- a/docs/source/troubleshooting/os_installation/debug_port.rst +++ b/docs/source/troubleshooting/os_installation/debug_port.rst @@ -1,21 +1,15 @@ -Enable Debug Port: Running commands in the installer from MN ------------------------------------------------------------- +Enabling Debug Port: Running commands in the installer from MN +-------------------------------------------------------------- -**This mode is only supported with debug level set to 1 or 2** +**This mode is supported with debug level set to 1 or 2** -xCAT creates a server in the **installer** listening on port ``3001``. It executes commands sent to it from the xCAT MN and returns the response output. +xCAT creates a server in the **installer**, listening on port ``3001``. It executes commands sent to it from the xCAT MN and returns the response output. -The command ``runcmdinstaller`` can be used to send request to installer: :: +The command ``runcmdinstaller`` can be used to send request to installer: - Usage: +Usage: ``runcmdinstaller ""`` - runcmdinstaller "" - - make sure all the commands are quoted by "" - - Example: - - To list all the items under the /etc directory in the installer - - runcmdinstaller c910f03c01p03 "ls /etc" +Note: Make sure all the commands are quoted by ``""`` +To list all the items under the /etc directory in the installer: ``runcmdinstaller c910f03c01p03 "ls /etc"`` + diff --git a/docs/source/troubleshooting/os_installation/index.rst b/docs/source/troubleshooting/os_installation/index.rst index dfdff4a0c..6a263c5f3 100644 --- a/docs/source/troubleshooting/os_installation/index.rst +++ b/docs/source/troubleshooting/os_installation/index.rst @@ -3,19 +3,19 @@ Operating System Installation The ability to access the installer or to collect logs during the installation process can be helpful when debugging installation problems. -A new attribute is provided in the site table called ``xcatdebugmode``. :: +A new attribute is provided in the **site** table called ``xcatdebugmode``. - xcatdebugmode=0: Only diagnose Log will be show in corresponding files. - xcatdebugmode=1: Diagnose Log will be show in corresponding files and debug port will be opened. - xcatdebugmode=2: SSH is supported while installing also with diagnose log show and debug port enable. +* xcatdebugmode=0: Diagnostic entries will be shown in corresponding log files. +* xcatdebugmode=1: Diagnostic entries will be shown in corresponding log files and debug port will be opened. +* xcatdebugmode=2: Diagnostic entries will be shown in corresponding log files, debug port will be opened and SSH access is enabled. -List of Supported OS. :: +Supported OS: - RHEL: 6.7 and above - SLES: 11.4 and above - UBT: 14.04.3 and above +* RHEL: 6.7 and above +* SLES: 11.4 and above +* UBT: 14.04.3 and above -The following behavior is observed during OS install: +The following behavior is supported during OS installation: +-----------------+--------------+--------------+--------------+ |**xcatdebugmode**| 0 | 1 | 2 | @@ -29,11 +29,11 @@ The following behavior is observed during OS install: | SSH Access | N | N | N | N | N | N | Y | Y | Y | +-----------------+----+----+----+----+----+----+----+----+----+ -Y means the behavior is supported by OS at current xcatdebugmode. +* Y - the behavior is supported by OS at specified **xcatdebugmode** level. -N means the opposite meaning. +* N - the behavior is not supported. -This chapter introduces the procedures of how to troubleshoot operating system installation. Basically, it includes the following parts. +Next chapter introduces the procedures on how to troubleshoot operating system installation. .. toctree:: :maxdepth: 2 diff --git a/docs/source/troubleshooting/os_installation/log_to_mn_cn.rst b/docs/source/troubleshooting/os_installation/log_to_mn_cn.rst index 8b19712b3..007142084 100644 --- a/docs/source/troubleshooting/os_installation/log_to_mn_cn.rst +++ b/docs/source/troubleshooting/os_installation/log_to_mn_cn.rst @@ -1,51 +1,87 @@ -Log Collecting: Collecting logs of the whole installation process +Log Collection: Collecting logs of the whole installation process ----------------------------------------------------------------- -The ability to collect logs during the installation process can be helpful when debugging installation problems. +The ability to collect logs during the installation (diskful and diskless) can be enabled by setting the "site.xcatdebugmode" to different levels (0,1,2), which is quite helpful when debugging installation problems. -Pre-Install: the logs of pre-installation scripts, the pre-installation scripts include "%pre" section in anaconda, "" section for SUSE and "partman/early_command" and "preseed/early_command" sections for ubuntu. The logs include the STDOUT and STDERR of the scripts as well as the debug trace output of bash scripts with "set -x" +The diskful provision logs: +`````````````````````````````````` ++---------------------+--------------+--------------+--------------+ +| **xcatdebugmode** | 0 | 1 | 2 | ++---------------------+----+----+----+----+----+----+----+----+----+ +| OS Distribution |RHEL|SLES|UBT |RHEL|SLES|UBT |RHEL|SLES|UBT | ++================+====+====+====+====+====+====+====+====+====+====+ +| Pre-Install | MN | N | N | N | ++ logs +----+----+----+----+----+----+----+----+----+----+ +| | CN | C1 | C1 C2 | C1 C2 | ++----------------+----+----+----+----+----+----+----+----+----+----+ +| Installer | MN | N | N | N | M1 | M1 | M1 | M1 | M1 | M1 | ++ logs +----+----+----+----+----+----+----+----+----+----+ +| | CN | C3 | C3 | C3 | C3 | C3 | C3 | C3 | C3 | C3 | ++----------------+----+----+----+----+----+----+----+----+----+----+ +| Post-Install | MN | M2 | M3 | M3 | ++ logs +----+----+----+----+----+----+----+----+----+----+ +| | CN | C1 | C1 C2 | C1 C2 | ++----------------+----+----+----+----+----+----+----+----+----+----+ +| PostBootScript | MN | M2 | M3 | M3 | ++ logs +----+----+----+----+----+----+----+----+----+----+ +| | CN | C1 | C1 C2 | C1 C2 | ++----------------+----+----+----+----+----+----+----+----+----+----+ -Installer: the logs from the os installer itself, i.e, the logs of installation program(anaconda, autoyast and preseed,etc.) +The diskless provision logs: +``````````````````````````````````` ++---------------------+--------------+--------------+--------------+ +| **xcatdebugmode** | 0 | 1 | 2 | ++---------------------+----+----+----+----+----+----+----+----+----+ +| OS Distribution |RHEL|SLES|UBT |RHEL|SLES|UBT |RHEL|SLES|UBT | ++================+====+====+====+====+====+====+====+====+====+====+ +| Provision | MN | N | M3 | M3 | ++ logs +----+----+----+----+----+----+----+----+----+----+ +| | CN | N | N | N | ++----------------+----+----+----+----+----+----+----+----+----+----+ +| PostBootScript | MN | M3 | M3 M4 | M3 M4 | ++ logs +----+----+----+----+----+----+----+----+----+----+ +| | CN | C1 | C1 C2 | C1 C2 | ++----------------+----+----+----+----+----+----+----+----+----+----+ -Post-Install: the logs of post-installation scripts, the post-installation scripts include "%post" section in anaconda, "" and "" sections for SUSE and "preseed/late_command" section for ubuntu. The logs include the STDOUT and STDERR of the scripts as well as the debug trace output of bash scripts with "set -x" +* **Pre-Install** logs: the logs of pre-installation scripts, including: -Post-Script: This section is useful for functions such as updating node status. This section contains the postbootscripts. + * ``%pre`` section in anaconda, + * ```` section for SUSE and ``partman/early_command`` and ``preseed/early_command`` sections for ubuntu. + * STDOUT and STDERR of the scripts + * debug trace output of bash scripts with ``set -x`` -The following behavior is observed during OS install: +* **Installer** logs: the logs from the os installer itself, i.e, the logs of installation program (anaconda, autoyast and preseed,etc.) -+------------------+--------------+--------------+--------------+ -|**xcatdebugmode** | 0 | 1 | 2 | -+------------------+----+----+----+----+----+----+----+----+----+ -| |RHEL|SLES|UBT |RHEL|SLES|UBT |RHEL|SLES|UBT | -+=============+====+====+====+====+====+====+====+====+====+====+ -| Pre-Install | MN | N | N | N | -+ log +----+----+----+----+----+----+----+----+----+----+ -| | CN | Y1 | Y2 | Y2 | -+-------------+----+----+----+----+----+----+----+----+----+----+ -| Installer | MN | N | N | N | Y6 | Y6 | N | Y6 | Y6 | N | -+ log +----+----+----+----+----+----+----+----+----+----+ -| | CN | Y5 | Y5 | Y5 | Y5 | Y5 | Y5 | Y5 | Y5 | Y5 | -+-------------+----+----+----+----+----+----+----+----+----+----+ -| Post-Install| MN | Y4 | Y3 | Y3 | -+ log +----+----+----+----+----+----+----+----+----+----+ -| | CN | Y1 | Y2 | Y2 | -+-------------+----+----+----+----+----+----+----+----+----+----+ -| Post-Script | MN | Y4 | Y3 | Y3 | -+ log +----+----+----+----+----+----+----+----+----+----+ -| | CN | Y1 | Y2 | Y2 | -+-------------+----+----+----+----+----+----+----+----+----+----+ +* **Post-Install** logs: the logs of post-installation scripts, including -Y1 means the installation logs can be saved to ``/var/log/xcat/xcat.log`` file on CN. + * ``%post`` section in anaconda, + * ```` and ```` sections for SUSE and ``preseed/late_command`` section for ubuntu. + * STDOUT and STDERR of the scripts + * debug trace output of bash scripts with ``set -x`` -Y2 means the installation logs and debug trace("set -x" or "-o xtrace") of bash scripts can be saved to ``/var/log/xcat/xcat.log`` file on CN. +* **Provision** logs: the logs during the diskless provision. -Y3 means the installation logs can be forwarded to ``/var/log/xcat/computes.log`` file on MN. +* **PostBootScript** logs: the logs during the post boot scripts execution, which are specified in ``postbootscripts`` attribute of node and osimage definition and run during the 1st reboot after installation. -Y4 means the error messages can be forwarded to ``/var/log/xcat/computes.log`` file on MN only when critical error happens. +MN: the logs forwarded to management node: -Y5 means the installer log can be saved to the CN in ``/var/log/anaconda`` for RHEL, ``/var/log/YaST2`` for SLES, ``/var/log/installer`` for UBT. +* M1: the installer logs will be forwarded to the MN in ``/var/log/xcat/computes.log`` file. -Y6 means the installer log can be forwarded to the MN in ``/var/log/xcat/computes.log`` file. +* M2: the error messages will be forwarded to ``/var/log/xcat/computes.log`` file on MN only when critical error happens. -N means the logs can not be forwarded or saved. +* M3: the installation logs will be forwarded to ``/var/log/xcat/computes.log`` file on MN. + +* M4: the debug trace(``set -x`` or ``-o xtrace``) of bash scripts enabled. + +* N: the logs will not be forwarded to MN. + +CN: the logs on compute node: + +* C1 - the installation logs will be saved to ``/var/log/xcat/xcat.log`` file on CN. + +* C2 - the debug trace(``set -x`` or ``-o xtrace``) of bash scripts enabled. + +* C3 - the installer logs will be saved to the CN in ``/var/log/anaconda`` for RHEL, ``/var/log/YaST2`` for SLES, ``/var/log/installer`` for UBT. + +* N - the logs will not be saved to CN. diff --git a/docs/source/troubleshooting/os_installation/ssh_enable.rst b/docs/source/troubleshooting/os_installation/ssh_enable.rst index 5d1bebd3a..8f2e94b80 100644 --- a/docs/source/troubleshooting/os_installation/ssh_enable.rst +++ b/docs/source/troubleshooting/os_installation/ssh_enable.rst @@ -1,9 +1,9 @@ SSH Access: Accessing the installer via "ssh" --------------------------------------------- -**This mode is only supported with debug level set to 2** +**This mode is supported with debug level set to 2** -The ssh access to the installer is enabled, the admin can login into the installer through: +When ssh access to the installer is enabled, the admin can login into the installer through: #. For RHEL, the installation won't halt, just login into the installer with ``ssh root@``. @@ -28,7 +28,7 @@ The ssh access to the installer is enabled, the admin can login into the install SYSTEMCTL_OPTIONS=--ignore-dependencies yast.ssh -#. For UBT, the installation will halt on the following similar message in the console: :: +#. For UBT, the installation will halt on the message in the console similar to: :: ┌───────────┤ [!!] Continue installation remotely using SSH ├───────────┠│ │ @@ -49,7 +49,7 @@ The ssh access to the installer is enabled, the admin can login into the install │ │ └───────────────────────────────────────────────────────────────────────┘ - Just as the message show, the admin can run ``ssh installer@`` with the password "cluster" to login into the installer, the following message shows on login: :: + Just as the message above suggests, the admin can run ``ssh installer@`` with the password "cluster" to login into the installer, the following message shows on login: :: ┌────────────────────┤ [!!] Configuring d-i ├─────────────────────┠│ │ diff --git a/makerpm b/makerpm index 355e236bf..c3cd442df 100755 --- a/makerpm +++ b/makerpm @@ -40,6 +40,18 @@ function makenoarch { fi fi fi + + #xcat probe use some functions shipped by xCAT, for below reasons we need to copy files to xCAT-probe directory + #1 make xcat probe code to be self-contained + #2 don't maintain two files for each script + #3 symbolic link can't work during package + if [ $RPMNAME = "xCAT-probe" ]; then + CURDIR=$(pwd) + mkdir -p ${CURDIR}/xCAT-probe/lib/perl/xCAT/ + cp -f ${CURDIR}/perl-xCAT/xCAT/NetworkUtils.pm ${CURDIR}/xCAT-probe/lib/perl/xCAT/ + cp -f ${CURDIR}/perl-xCAT/xCAT/GlobalDef.pm ${CURDIR}/xCAT-probe/lib/perl/xCAT/ + fi + tar --exclude .svn -czf $RPMROOT/SOURCES/$RPMNAME-$VER.tar.gz $RPMNAME rm -f $RPMROOT/SRPMS/$RPMNAME-$VER*rpm $RPMROOT/RPMS/noarch/$RPMNAME-$VER*rpm rpmbuild $QUIET -ta $RPMROOT/SOURCES/$RPMNAME-$VER.tar.gz @@ -146,30 +158,6 @@ function makeironic { rm -rf /tmp/ironic_baremetal } - -# Make the xCAT-nbroot-core rpm -function makenbroot { - if [ -z "$2" ]; then - echo 'Usage: makerpm xCAT-nbroot-core []' - exit 1 - fi - - DIR="xCAT-nbroot" - ARCH="$2" - RPMNAME="xCAT-nbroot-core-$ARCH" - SPEC="xcat-core-nbroot" - cd `dirname $0`/$DIR - tar --exclude .svn -czf $RPMROOT/SOURCES/xcat-nbrootoverlay.tar.gz -C overlay/ . - cp LICENSE.html $RPMROOT/BUILD - cp $SPEC.spec $RPMROOT/SOURCES - cd - >/dev/null - rm -f $RPMROOT/SRPMS/$RPMNAME-$VER*rpm $RPMROOT/RPMS/noarch/$RPMNAME-$VER*rpm - echo "Building $RPMROOT/RPMS/noarch/$RPMNAME-$VER-snap*.noarch.rpm $EMBEDTXT..." - rpmbuild $QUIET -ba $DIR/$SPEC.spec --target $ARCH -} - - - # Make the xCAT-genesis rpm function makegenesis { DIR="xCAT-genesis-builder" @@ -183,6 +171,7 @@ function makegenesis { echo "Building $RPMROOT/RPMS/noarch/$RPMNAME-$VER-snap*.noarch.rpm $EMBEDTXT..." rpmbuild $QUIET -ba $DIR/$RPMNAME.spec } + function makegenesisscripts { DIR="xCAT-genesis-scripts" if [ -z "$2" ]; then @@ -248,9 +237,6 @@ fi if [ "$1" = "xCAT" -o "$1" = "xCATsn" -o "$1" = "xCAT-buildkit" -o "$1" = "xCAT-OpenStack" ]; then exportEmbed $3 makexcat $1 $2 -elif [ "$1" = "xCAT-nbroot" -o "$1" = "xCAT-nbroot-core" ]; then - exportEmbed $3 - makenbroot xCAT-nbroot-core $2 elif [ "$1" = "xCAT-genesis-builder" ]; then exportEmbed $2 makegenesis $1 diff --git a/perl-xCAT/db2man b/perl-xCAT/db2man index 55d738ce9..da35965e9 100755 --- a/perl-xCAT/db2man +++ b/perl-xCAT/db2man @@ -16,12 +16,12 @@ use xCAT::Table; use Pod::Man; use Pod::Html; -my $poddir = 'pods'; -my $mandir = 'share/man'; -my $htmldir = 'share/doc'; +my $poddir = 'pods'; +my $mandir = 'share/man'; +my $htmldir = 'share/doc'; my $cachedir = "$ENV{'HOME'}/tmp"; if (system("mkdir -p $cachedir")) { die "Error: could not create $cachedir.\n"; } -my $isaix = ($^O =~ /^aix/i); +my $isaix = ($^O =~ /^aix/i); my $skiponaix = 'route|group'; my $poddir5 = 'pods/man5'; @@ -36,51 +36,53 @@ writesummarypage("$poddir5/xcatdb.5.pod", xCAT::Table->getDescriptions(), \%{xCA # Build the pod man page for each object definition my $defspecref = \%{xCAT::Schema::defspec}; foreach my $defkey (keys %$defspecref) { - my $def = $defspecref->{$defkey}; - my $attrs = $def->{'attrs'}; + my $def = $defspecref->{$defkey}; + my $attrs = $def->{'attrs'}; writedefmanpage("$poddir7/$defkey.7.pod", $defkey, $attrs); } # Build the pod man page for each table. my $tabspecref = \%xCAT::Schema::tabspec; foreach my $tablekey (keys %$tabspecref) { - my $table = $tabspecref->{$tablekey}; - my $summary = $table->{table_desc}; - my $colorder = $table->{cols}; + my $table = $tabspecref->{$tablekey}; + my $summary = $table->{table_desc}; + my $colorder = $table->{cols}; my $descriptions = $table->{descriptions}; writepodmanpage("$poddir5/$tablekey.5.pod", $tablekey, $summary, $colorder, $descriptions); } my @pods = getPodList($poddir); + #foreach (@pods) { print "$_\n"; } exit; # Build the man page for each pod. #mkdir($mandir) or die "Error: could not create $mandir.\n"; print "Converting PODs to man pages...\n"; foreach my $podfile (@pods) { - if ($isaix && grep(/\/($skiponaix)\.\d\.pod$/, $podfile)) { print "Skipping $podfile\n"; next; } + if ($isaix && grep(/\/($skiponaix)\.\d\.pod$/, $podfile)) { print "Skipping $podfile\n"; next; } my $manfile = $podfile; - $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path - $manfile =~ s/\.pod$//; # change the ending + $manfile =~ s/^$poddir/$mandir/; # change the beginning of the path + $manfile =~ s/\.pod$//; # change the ending my $mdir = $manfile; - $mdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } - my ($section) = $podfile =~ /\.(\d+)\.pod$/; + $mdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $mdir")) { die "Error: could not create $mdir.\n"; } + my ($section) = $podfile =~ /\.(\d+)\.pod$/; convertpod2man($podfile, $manfile, $section); } # Build the html page for each pod. #mkdir($htmldir) or die "Error: could not create $htmldir.\n"; print "Converting PODs to HTML pages...\n"; + # have to clear the cache, because old entries can cause a problem unlink("$cachedir/pod2htmd.tmp", "$cachedir/pod2htmi.tmp"); foreach my $podfile (@pods) { my $htmlfile = $podfile; - $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path - $htmlfile =~ s/\.pod$/\.html/; # change the ending + $htmlfile =~ s/^$poddir/$htmldir/; # change the beginning of the path + $htmlfile =~ s/\.pod$/\.html/; # change the ending my $hdir = $htmlfile; - $hdir =~ s|/[^/]*$||; # get rid of the basename part - if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } + $hdir =~ s|/[^/]*$||; # get rid of the basename part + if (system("mkdir -p $hdir")) { die "Error: could not create $hdir.\n"; } convertpod2html($podfile, $htmlfile, $poddir, $htmldir); } @@ -89,62 +91,62 @@ exit; # Recursively get the list of pod man page files. sub getPodList { - my $poddir = shift; - my @files; + my $poddir = shift; + my @files; - # 1st get toplevel dir listing - opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; - my @topdir = grep !/^\./, readdir(DIR); # / - close(DIR); + # 1st get toplevel dir listing + opendir(DIR, $poddir) or die "Error: could not read $poddir.\n"; + my @topdir = grep !/^\./, readdir(DIR); # / + close(DIR); - # Now go thru each subdir (these are man1, man3, etc.) - foreach my $mandir (@topdir) { - opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; - my @dir = grep !/^\./, readdir(DIR); # / - close(DIR); - foreach my $file (@dir) { - push @files, "$poddir/$mandir/$file"; - } - } - return sort @files; + # Now go thru each subdir (these are man1, man3, etc.) + foreach my $mandir (@topdir) { + opendir(DIR, "$poddir/$mandir") or die "Error: could not read $poddir/$mandir.\n"; + my @dir = grep !/^\./, readdir(DIR); # / + close(DIR); + foreach my $file (@dir) { + push @files, "$poddir/$mandir/$file"; + } + } + return sort @files; } # Create the html page for one pod. sub convertpod2html { - my ($podfile, $htmlfile, $poddir, $htmldir) = @_; + my ($podfile, $htmlfile, $poddir, $htmldir) = @_; - #TODO: use --css= and --title= to make the pages look better - pod2html($podfile, - "--outfile=$htmlfile", - "--podpath=man5:man7", - "--podroot=$poddir", - "--htmldir=$htmldir", - "--recurse", - "--cachedir=$cachedir", - ); + #TODO: use --css= and --title= to make the pages look better + pod2html($podfile, + "--outfile=$htmlfile", + "--podpath=man5:man7", + "--podroot=$poddir", + "--htmldir=$htmldir", + "--recurse", + "--cachedir=$cachedir", + ); } # Create the man page for one pod. sub convertpod2man { - my ($podfile, $manfile, $section) = @_; + my ($podfile, $manfile, $section) = @_; - my $parser = Pod::Man->new(section => $section); + my $parser = Pod::Man->new(section => $section); $parser->parse_from_file($podfile, $manfile); } # Create the xcatdb man page that gives a summary description of each table. sub writesummarypage { - my $file = shift; # relative path file name of the man page - my $descriptions = shift; # a hash containing the description of each table - my $defdescriptions = shift; # a hash containing the description of each object definition + my $file = shift; # relative path file name of the man page + my $descriptions = shift; # a hash containing the description of each table + my $defdescriptions = shift; # a hash containing the description of each object definition - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<'EOS1'; + print FILE <<'EOS1'; =head1 NAME An overview of the xCAT database. @@ -316,11 +318,11 @@ The object types are: =over 2 EOS1 -foreach my $def (sort keys %$defdescriptions) { - print FILE "\n=item L<$def(7)|$def.7>\n"; -} + foreach my $def (sort keys %$defdescriptions) { + print FILE "\n=item L<$def(7)|$def.7>\n"; + } - print FILE <<"EOS2"; + print FILE <<"EOS2"; =back @@ -336,11 +338,11 @@ The tables are: =over 2 EOS2 -foreach my $table (sort keys %$descriptions) { - print FILE "\n=item L<$table(5)|$table.5>\n\n".$descriptions->{$table}."\n"; -} + foreach my $table (sort keys %$descriptions) { + print FILE "\n=item L<$table(5)|$table.5>\n\n" . $descriptions->{$table} . "\n"; + } - print FILE <<"EOS3"; + print FILE <<"EOS3"; =back @@ -349,47 +351,49 @@ foreach my $table (sort keys %$descriptions) { B, B, B, B, B, B, B, B EOS3 - close FILE; + close FILE; } # Create the man page for one object definition. sub writedefmanpage { - my $file = shift; # relative path file name of the man page - my $defname = shift; # name of object - my $attrs = shift; # reference to the array of attributes + my $file = shift; # relative path file name of the man page + my $defname = shift; # name of object + my $attrs = shift; # reference to the array of attributes - # Go thru the attributes, collecting the descriptions - # Note: this logic is loosely taken from DBobjectdefs.pm - my %attrlist; # holds the attr name as the key, and the description & tables as value - foreach my $this_attr (@$attrs) { + # Go thru the attributes, collecting the descriptions + # Note: this logic is loosely taken from DBobjectdefs.pm + my %attrlist; # holds the attr name as the key, and the description & tables as value + foreach my $this_attr (@$attrs) { my $attr = $this_attr->{attr_name}; my $desc = $this_attr->{description}; my ($table, $at) = split(/\./, $this_attr->{tabentry}); if (!defined($desc)) { - # description key not there, so go to the corresponding - # entry in tabspec to get the description + + # description key not there, so go to the corresponding + # entry in tabspec to get the description my $schema = xCAT::Table->getTableSchema($table); $desc = $schema->{descriptions}->{$at}; } - # Attr names can appear more than once, if they are in multiple tables. - # We will keep track of that based on the table attribute, because that can be duplicated too - if (!defined($attrlist{$attr})) { - $attrlist{$attr}->{'tables'} = []; # initialize the array, so we can check it below - } - my $tableattr = "$table.$at"; - if (!grep(/^$tableattr$/, @{$attrlist{$attr}->{'tables'}})) { - # there can be multiple entries that refer to the same table attribute - # if this is a new table attribute, then save the attr name and description - push @{$attrlist{$attr}->{'tables'}}, $tableattr; - push @{$attrlist{$attr}->{'descriptions'}}, $desc; - } - } + # Attr names can appear more than once, if they are in multiple tables. + # We will keep track of that based on the table attribute, because that can be duplicated too + if (!defined($attrlist{$attr})) { + $attrlist{$attr}->{'tables'} = []; # initialize the array, so we can check it below + } + my $tableattr = "$table.$at"; + if (!grep(/^$tableattr$/, @{ $attrlist{$attr}->{'tables'} })) { - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + # there can be multiple entries that refer to the same table attribute + # if this is a new table attribute, then save the attr name and description + push @{ $attrlist{$attr}->{'tables'} }, $tableattr; + push @{ $attrlist{$attr}->{'descriptions'} }, $desc; + } + } - print FILE <<"EOS1"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + + print FILE <<"EOS1"; =head1 NAME B<$defname> - a logical object definition in the xCAT database. @@ -398,9 +402,9 @@ B<$defname> - a logical object definition in the xCAT database. EOS1 - print FILE "B<$defname Attributes:> I<" . join('>, I<',sort(keys(%attrlist))) . ">\n"; + print FILE "B<$defname Attributes:> I<" . join('>, I<', sort(keys(%attrlist))) . ">\n"; - print FILE <<"EOS2"; + print FILE <<"EOS2"; =head1 DESCRIPTION @@ -415,15 +419,17 @@ parentheses, what tables each attribute is stored in. EOS2 -foreach my $a (sort keys %attrlist) { - my $d = join("\nor\n", @{$attrlist{$a}->{'descriptions'}}); - $d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them - my $t = '(' . join(', ',@{$attrlist{$a}->{'tables'}}) . ')'; - #print FILE "\nB<$a> - $d\n"; - print FILE "\n=item B<$a> $t\n\n$d\n"; -} + foreach my $a (sort keys %attrlist) { + my $d = join("\n\nor\n\n", @{ $attrlist{$a}->{'descriptions'} }); - print FILE <<"EOS3"; + #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them + my $t = '(' . join(', ', @{ $attrlist{$a}->{'tables'} }) . ')'; + + #print FILE "\nB<$a> - $d\n"; + print FILE "\n=item B<$a> $t\n\n$d\n"; + } + + print FILE <<"EOS3"; =back @@ -432,21 +438,21 @@ foreach my $a (sort keys %attrlist) { B, B, B, B EOS3 - close FILE; + close FILE; } # Create the man page for one table. sub writepodmanpage { - my $file = shift; # relative path file name of the man page - my $tablename = shift; # name of table - my $summary = shift; # description of table - my $colorder = shift; # the order in which the table attributes should be presented in - my $descriptions = shift; # a hash containing the description of each attribute + my $file = shift; # relative path file name of the man page + my $tablename = shift; # name of table + my $summary = shift; # description of table + my $colorder = shift; # the order in which the table attributes should be presented in + my $descriptions = shift; # a hash containing the description of each attribute - open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; + open(FILE, ">$file") or die "Error: could not open $file for writing.\n"; - print FILE <<"EOS1"; + print FILE <<"EOS1"; =head1 NAME B<$tablename> - a table in the xCAT database. @@ -455,9 +461,9 @@ B<$tablename> - a table in the xCAT database. EOS1 - print FILE "B<$tablename Attributes:> I<" . join('>, I<',@$colorder) . ">\n"; + print FILE "B<$tablename Attributes:> I<" . join('>, I<', @$colorder) . ">\n"; - print FILE <<"EOS2"; + print FILE <<"EOS2"; =head1 DESCRIPTION @@ -469,14 +475,15 @@ $summary EOS2 -foreach my $a (@$colorder) { - my $d = $descriptions->{$a}; - #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them - #print FILE "\nB<$a> - $d\n"; - print FILE "\n=item B<$a>\n\n$d\n"; -} + foreach my $a (@$colorder) { + my $d = $descriptions->{$a}; - print FILE <<"EOS3"; + #$d =~ s/\n/\n\n/sg; # if there are newlines, double them so pod sees a blank line, otherwise pod will ignore them + #print FILE "\nB<$a> - $d\n"; + print FILE "\n=item B<$a>\n\n$d\n"; + } + + print FILE <<"EOS3"; =back @@ -485,5 +492,5 @@ foreach my $a (@$colorder) { B, B, B, B EOS3 - close FILE; + close FILE; } diff --git a/perl-xCAT/xCAT/CFMUtils.pm b/perl-xCAT/xCAT/CFMUtils.pm index 2c66e0004..e2563cfa4 100644 --- a/perl-xCAT/xCAT/CFMUtils.pm +++ b/perl-xCAT/xCAT/CFMUtils.pm @@ -4,7 +4,7 @@ package xCAT::CFMUtils; BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; @@ -58,11 +58,11 @@ sub initCFMdir # below system files will be synced to all compute nodes my @sysfiles = ("/etc/hosts"); - # the /etc/passwd, shadow, group files will be merged + # the /etc/passwd, shadow, group files will be merged my @userfiles = ("/etc/passwd", "/etc/shadow", "/etc/group"); # create the cfmdir - if (! -d $cfmdir) + if (!-d $cfmdir) { mkpath $cfmdir; } @@ -70,20 +70,20 @@ sub initCFMdir # backup the OS files and create links under cfmdir foreach my $file (@userfiles) { - my $backup = $file.".OS"; - if (! -e $backup) + my $backup = $file . ".OS"; + if (!-e $backup) { copy($file, $backup); } - if (! -e "$cfmdir/".basename($backup)) + if (!-e "$cfmdir/" . basename($backup)) { - symlink($backup, "$cfmdir/".basename($backup)); + symlink($backup, "$cfmdir/" . basename($backup)); } } # Initialize CFM directory and related files - if (! -d "$cfmdir/etc") + if (!-d "$cfmdir/etc") { mkpath "$cfmdir/etc"; } @@ -93,16 +93,17 @@ sub initCFMdir { symlink($file, "$cfmdir/$file"); } + # touch and link the merge files for /etc/passwd, shadow, group foreach my $file (@userfiles) { - my $merge = $file.".merge"; - if (! -e "$merge") + my $merge = $file . ".merge"; + if (!-e "$merge") { xCAT::Utils->runcmd("touch $merge", -1); } - if (! -e "$cfmdir/$merge") + if (!-e "$cfmdir/$merge") { symlink($merge, "$cfmdir/$merge"); } @@ -143,18 +144,18 @@ sub updateUserInfo { $rsp->{data}->[0] = "Skiping the update of the /etc/passwd, shadow, group merge files under the CFM directory."; xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } - return 0; + return 0; } foreach my $file (@userfiles) { my @oldrecords = (); my @newrecords = (); - my $backup = basename($file).".OS"; + my $backup = basename($file) . ".OS"; # get the records from /etc/passwd, shadow, group file and backup files(.OS files) - # and all the files from /install/osimages/$imgname/cfmdir directory - foreach my $userinfo ($file, "$cfmdir/$backup") + # and all the files from /install/osimages/$imgname/cfmdir directory + foreach my $userinfo ($file, "$cfmdir/$backup") { my $fp; open($fp, $userinfo); @@ -162,18 +163,18 @@ sub updateUserInfo { while (<$fp>) { my $line = xCAT::CFMUtils->trim($_); - if (($line =~ /^#/) || ($line =~ /^\s*$/ )) - { #comment line or blank line + if (($line =~ /^#/) || ($line =~ /^\s*$/)) + { #comment line or blank line next; } else - { + { push @records, $line; - } + } } close($fp); # check the records from /etc/passwd, shadow, group file or backup - if ($userinfo =~ /^\/etc/ ) + if ($userinfo =~ /^\/etc/) { @newrecords = @records; } else { @@ -182,8 +183,9 @@ sub updateUserInfo { } # update the merge file - my $mergefile = $cfmdir."/".$file.".merge"; + my $mergefile = $cfmdir . "/" . $file . ".merge"; my @diff = xCAT::CFMUtils->arrayops("D", \@newrecords, \@oldrecords); + # output the diff to merge files my $fp; open($fp, '>', $mergefile); @@ -199,8 +201,8 @@ sub updateUserInfo { print $fp "$record\n"; } } - close ($fp); - + close($fp); + } return 0; @@ -208,6 +210,7 @@ sub updateUserInfo { #----------------------------------------------------------------------------- + =head3 setCFMSynclistFile Set osimage synclists attribute for CFM function, the CMF synclist file is: /install/osimages//synclist.cfm @@ -224,6 +227,7 @@ sub updateUserInfo { my $cfmdir = xCAT::CFMUtils->setCFMSynclistFile($imagename); if ($cfmdir) { # update the CFM synclist file } =cut + #----------------------------------------------------------------------------- sub setCFMSynclistFile { my ($class, $img) = @_; @@ -234,18 +238,19 @@ sub setCFMSynclistFile { # get the cfmdir and synclists attributes my $osimage_t = xCAT::Table->new('osimage'); - my $records = $osimage_t->getAttribs({imagename=>$img}, 'cfmdir', 'synclists'); - if (defined ($records->{'cfmdir'})) + my $records = $osimage_t->getAttribs({ imagename => $img }, 'cfmdir', 'synclists'); + if (defined($records->{'cfmdir'})) { $cfmdir = $records->{'cfmdir'}; - if (defined ($records->{'synclists'})) {$synclists = $records->{'synclists'}} + if (defined($records->{'synclists'})) { $synclists = $records->{'synclists'} } } else { + # no cfmdir defined, return directly return 0; } my $found = 0; - my $index = 0; + my $index = 0; if ($synclists) { # the synclists is a comma separated list @@ -253,7 +258,7 @@ sub setCFMSynclistFile { foreach my $synclist (@lists) { # find the synclist configuration for CFM - if ($synclist eq $cfmsynclist) + if ($synclist eq $cfmsynclist) { $found = 1; last; @@ -263,17 +268,19 @@ sub setCFMSynclistFile { if ($found == 0) { # the CFM synclist is not defined, append it to $synclists - $synclists = "$synclists,$cfmsynclist"; - # set the synclists attribute - $osimage_t->setAttribs({imagename=>$img}, {'synclists' => $synclists}); + $synclists = "$synclists,$cfmsynclist"; + + # set the synclists attribute + $osimage_t->setAttribs({ imagename => $img }, { 'synclists' => $synclists }); } } else { + # no synclists defined, set it to CFM synclist file if ($cfmdir) { $synclists = $cfmsynclist; } - $osimage_t->setAttribs({imagename=>$img}, {'synclists' => $synclists}); + $osimage_t->setAttribs({ imagename => $img }, { 'synclists' => $synclists }); } - return $cfmdir; + return $cfmdir; } @@ -335,60 +342,62 @@ sub updateCFMSynclistFile { { my $cfmdir; $cfmdir = xCAT::CFMUtils->setCFMSynclistFile($osimg); - if ($cfmdir) # check for /install/osiamges/$osimg/cfmdir + if ($cfmdir) # check for /install/osiamges/$osimg/cfmdir { my $cfmsynclist = "/install/osimages/$osimg/synclist.cfm"; - if (! -d $cfmdir) + if (!-d $cfmdir) { - # skip this one go on to the next image, nothing to do for + # skip this one go on to the next image, nothing to do for # CFMUtils in this image next; } + # create the parent directory of CFM synclist file - if (! -d dirname($cfmsynclist)) + if (!-d dirname($cfmsynclist)) { mkpath dirname($cfmsynclist); } # update /etc/passwd, shadow, group merge files my $ret = xCAT::CFMUtils->updateUserInfo($cfmdir); - if ($ret !=0 ) + if ($ret != 0) { my $rsp = {}; - $rsp->{error}->[0] = - "Update /etc/passwd, shadow, group merge files failed."; + $rsp->{error}->[0] = + "Update /etc/passwd, shadow, group merge files failed."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return 1; } - # recursively list the files under cfm directory + # recursively list the files under cfm directory my @files = (); - find ( { wanted => sub { push @files, $File::Find::name if -f }, follow => 1 }, $cfmdir); - if (!@files) # not files under cfm directory, skip to next loop + find({ wanted => sub { push @files, $File::Find::name if -f }, follow => 1 }, $cfmdir); + if (!@files) # not files under cfm directory, skip to next loop { next; } my $fp; open($fp, '>', $cfmsynclist); - my @mergefiles = (); + my @mergefiles = (); my @appendfiles = (); foreach my $file (@files) { my $name = basename($file); - #TODO: find a better way to get the suffix + + #TODO: find a better way to get the suffix my $suffix = ($name =~ m/([^.]+)$/)[0]; my $dest = substr($file, length($cfmdir)); - if ($suffix eq "OS") # skip the backup files + if ($suffix eq "OS") # skip the backup files { next; - } elsif ($suffix eq "merge") # merge file + } elsif ($suffix eq "merge") # merge file { push(@mergefiles, $file); - } elsif ($suffix eq "append") { # append file - push(@appendfiles, $file); - } else { # output the syncing files maintained by CFM + } elsif ($suffix eq "append") { # append file + push(@appendfiles, $file); + } else { # output the syncing files maintained by CFM print $fp "$file -> $dest\n"; } } @@ -398,7 +407,7 @@ sub updateCFMSynclistFile { print $fp "APPEND:\n"; } foreach my $file (@appendfiles) - { + { my $dest = substr($file, length($cfmdir), length($file) - length(".append") - length($cfmdir)); print $fp "$file -> $dest\n"; } @@ -411,21 +420,23 @@ sub updateCFMSynclistFile { { my @userfiles = ("/etc/passwd", "/etc/shadow", "/etc/group"); my $dest = substr($file, length($cfmdir), length($file) - length(".merge") - length($cfmdir)); + # only /etc/passwd, /etc/shadow, /etc/groups merging is supported - if (grep(/$dest/, @userfiles)) { + if (grep(/$dest/, @userfiles)) { print $fp "$file -> $dest\n"; } } - - # close the file - close($fp); + + # close the file + close($fp); } } - + return 0; } #----------------------------------------------------------------------------- + =head3 setCFMPkglistFile Set the pkglist attribute of linuximage object for CFM function @@ -441,20 +452,21 @@ sub updateCFMSynclistFile { Example: my $ret = xCAT::CFMUtils->setCFMPkglistFile($imagename); =cut + #----------------------------------------------------------------------------- sub setCFMPkglistFile { my ($class, $img) = @_; - my $pkglists = ""; + my $pkglists = ""; my $cfmpkglist = "/install/osimages/$img/pkglist.cfm"; # get the pkglist files my $linuximage_t = xCAT::Table->new('linuximage'); - my $records = $linuximage_t->getAttribs({imagename => $img}, 'pkglist'); + my $records = $linuximage_t->getAttribs({ imagename => $img }, 'pkglist'); if ($records) { if ($records->{'pkglist'}) { $pkglists = $records->{'pkglist'}; } - } else + } else { if ($::VERBOSE) { @@ -469,27 +481,29 @@ sub setCFMPkglistFile { { foreach my $pkglist (split(/,/, $pkglists)) { - if ($pkglist eq $cfmpkglist) # the pkglist file for CFM is found, exit the loop + if ($pkglist eq $cfmpkglist) # the pkglist file for CFM is found, exit the loop { $found = 1; last; } } - # the pkglist file for CFM is not found, append it to $pkglits - if (!$found) + + # the pkglist file for CFM is not found, append it to $pkglits + if (!$found) { - $pkglists = "$pkglists,$cfmpkglist"; + $pkglists = "$pkglists,$cfmpkglist"; + # set the pkglist attribute for linuximage - $linuximage_t->setAttribs({imagename => $img}, {'pkglist' => $pkglists}); - } - } else + $linuximage_t->setAttribs({ imagename => $img }, { 'pkglist' => $pkglists }); + } + } else { # the pkglist file for linuximage is not defined, set it to $cfmpkglist $pkglists = $cfmpkglist; - $linuximage_t->setAttribs({imagename => $img}, {'pkglist' => $pkglists}); + $linuximage_t->setAttribs({ imagename => $img }, { 'pkglist' => $pkglists }); } - return 0; + return 0; } #----------------------------------------------------------------------------- @@ -517,17 +531,19 @@ sub setCFMPkglistFile { #----------------------------------------------------------------------------- sub updateCFMPkglistFile { my ($class, $img, $ospkgs, $mode) = @_; - - if(defined($mode)){ + + if (defined($mode)) { + # Exact Matching $mode = 1; - }else { + } else { + # Fuzzy Matching $mode = 0; } - + my @cur_selected = @$ospkgs; - my $cfmpkglist = "/install/osimages/$img/pkglist.cfm"; + my $cfmpkglist = "/install/osimages/$img/pkglist.cfm"; my $ret = xCAT::CFMUtils->setCFMPkglistFile($img); if ($ret) @@ -539,7 +555,7 @@ sub updateCFMPkglistFile { } # check the parent directory of cfmpkglist file - if (! -d dirname($cfmpkglist)) + if (!-d dirname($cfmpkglist)) { mkpath dirname($cfmpkglist); } @@ -547,10 +563,11 @@ sub updateCFMPkglistFile { # get previous selected and removed OS packages list from pkglist file my ($pre_selected_ref, $pre_removed_ref) = xCAT::CFMUtils->getPreOSpkgsList($cfmpkglist); my @pre_selected = @$pre_selected_ref; - my @pre_removed = @$pre_removed_ref; + my @pre_removed = @$pre_removed_ref; # get the #INCLUDE file from cfmpkglist file my @incfiles = xCAT::CFMUtils->getIncludefiles($cfmpkglist); + # get the packages list in the #INCLUDE files my @basepkgs = (); foreach my $inc (@incfiles) @@ -559,18 +576,18 @@ sub updateCFMPkglistFile { my @selected = @$selected_ref; @basepkgs = xCAT::CFMUtils->arrayops("U", \@basepkgs, \@selected); } - + # Fuzzy Matching - if (not $mode){ + if (not $mode) { my ($ref1, $ref2, $ref3) = xCAT::CFMUtils->updateSelectedPkgs(\@pre_selected, \@pre_removed, \@cur_selected); @pre_selected = @$ref1; - @pre_removed = @$ref2; + @pre_removed = @$ref2; @cur_selected = @$ref3; } - # get diff between previous and current selected OS packages lists + # get diff between previous and current selected OS packages lists my @diff = xCAT::CFMUtils->getPkgsDiff(\@pre_selected, \@cur_selected); - + # merge the diff to previous removed OS packages list my @all_removed = xCAT::CFMUtils->arrayops("U", \@pre_removed, \@diff); @@ -590,6 +607,7 @@ sub updateCFMPkglistFile { { print $fp "#INCLUDE:$inc#\n"; } + # the pacakges be installed if (@cur_selected) { @@ -598,6 +616,7 @@ sub updateCFMPkglistFile { print $fp "$pkg\n"; } } + # the packages be removed if (@cur_removed) { @@ -606,6 +625,7 @@ sub updateCFMPkglistFile { print $fp "-$pkg\n"; } } + # close the file close($fp); @@ -635,8 +655,8 @@ sub updateCFMPkglistFile { #----------------------------------------------------------------------------- sub getPreOSpkgsList { my ($class, $pkglist) = @_; - my @selected = (); - my @removed = (); + my @selected = (); + my @removed = (); my @pkglistfiles = (); # get the #INCLUDE file from cfmpkglist file @@ -645,6 +665,7 @@ sub getPreOSpkgsList { { push @pkglistfiles, $inc; } + # assume the #INCLUDE file includes the BASE packages push @pkglistfiles, $pkglist; @@ -655,20 +676,20 @@ sub getPreOSpkgsList { while (<$pkglistfp>) { my $line = xCAT::CFMUtils->trim($_); - if (($line =~ /^#/) || ($line =~ /^\s*$/ ) || ($line =~ /^@/)) - { #comment line or blank line + if (($line =~ /^#/) || ($line =~ /^\s*$/) || ($line =~ /^@/)) + { #comment line or blank line next; } else { if ($line =~ /^-/) - { # the package be removed + { # the package be removed push @removed, substr($line, 1); } else - { # the package be installed + { # the package be installed push @selected, $line; - } + } } - } + } close($pkglistfp); } @@ -700,21 +721,21 @@ sub getPreOSpkgsList { #----------------------------------------------------------------------------- sub getPreBaseOSpkgsList { my ($class, $pkglist) = @_; - - my ($pre_selected_ref, $pre_removed_ref) = xCAT::CFMUtils->getPreOSpkgsList($pkglist); - + + my ($pre_selected_ref, $pre_removed_ref) = xCAT::CFMUtils->getPreOSpkgsList($pkglist); + my %pre_selected_hash = (); foreach (@$pre_selected_ref) { my @names = split(/\./, $_); my $basename = $names[0]; - + if ($_ =~ /^$basename\.([^\.]+)$/) { $pre_selected_hash{$basename} = 1; - }else { + } else { $pre_selected_hash{$_} = 1; } } - + my @pre_selected = keys %pre_selected_hash; return \@pre_selected; @@ -749,6 +770,7 @@ sub getPkgsDiff { # get the difference my @diff = xCAT::CFMUtils->arrayops("D", \@$pre, \@tmp); + #print Dumper(@diff); return @diff; @@ -783,14 +805,15 @@ sub getIncludefiles { { my $line = xCAT::CFMUtils->trim($_); if ($line =~ /^\s*$/) - { # blank line + { # blank line next; } + # find the #INCLUDE line if ($line =~ /^\s*#INCLUDE:[^#^\n]+#/) { #print "The line is: [$line]\n"; - my $incfile = substr($line, length("#INCLUDE:"), length($line)-length("#INCLUDE:")-1); + my $incfile = substr($line, length("#INCLUDE:"), length($line) - length("#INCLUDE:") - 1); push @files, $incfile; } } @@ -857,13 +880,13 @@ sub trim { sub arrayops { my ($class, $ops, $array1, $array2) = @_; - my @union = (); + my @union = (); my @intersection = (); - my @difference = (); - my %count = (); - foreach my $element (@$array1, @$array2) - { - $count{$element}++ + my @difference = (); + my %count = (); + foreach my $element (@$array1, @$array2) + { + $count{$element}++ } foreach my $element (keys %count) { @@ -872,7 +895,7 @@ sub arrayops { } if ($ops eq "U") { return @union; } - + if ($ops eq "I") { return @intersection; } if ($ops eq "D") { return @difference; } @@ -903,19 +926,19 @@ sub arrayops { #----------------------------------------------------------------------------- sub updateSelectedPkgs() { - my ($class, $pre_selected_ref, $pre_removed_ref, $cur_selected_ref) = @_; - - my %pre_selected_hash = map{$_ => 1} @$pre_selected_ref; - my %pre_removed_hash = map{$_ => 1} @$pre_removed_ref; - my %cur_selected_hash = map{$_ => 1} @$cur_selected_ref; - + my ($class, $pre_selected_ref, $pre_removed_ref, $cur_selected_ref) = @_; + + my %pre_selected_hash = map { $_ => 1 } @$pre_selected_ref; + my %pre_removed_hash = map { $_ => 1 } @$pre_removed_ref; + my %cur_selected_hash = map { $_ => 1 } @$cur_selected_ref; + my %new_pre_selected_hash = %pre_selected_hash; - my %new_pre_removed_hash = %pre_removed_hash; + my %new_pre_removed_hash = %pre_removed_hash; my %new_cur_selected_hash = %cur_selected_hash; - + foreach (keys %cur_selected_hash) { my $father = $_; - my $flag = 0; + my $flag = 0; foreach (keys %pre_selected_hash) { my $child = $_; if ($child =~ /^$father\.([^\.]+)$/) { @@ -923,10 +946,10 @@ sub updateSelectedPkgs() { $flag = 1; } } - if ($flag and not exists $pre_selected_hash{$father}){ + if ($flag and not exists $pre_selected_hash{$father}) { delete $new_cur_selected_hash{$father} if exists $new_cur_selected_hash{$father}; } - + foreach (keys %pre_removed_hash) { my $child = $_; if ($child =~ /^$father\.([^\.]+)$/) { @@ -934,11 +957,11 @@ sub updateSelectedPkgs() { } } } - + my @new_cur_selected = keys %new_cur_selected_hash; my @new_pre_selected = keys %new_pre_selected_hash; - my @new_pre_removed = keys %new_pre_removed_hash; - - - return (\@new_pre_selected, \@new_pre_removed, \@new_cur_selected); + my @new_pre_removed = keys %new_pre_removed_hash; + + + return (\@new_pre_selected, \@new_pre_removed, \@new_cur_selected); } diff --git a/perl-xCAT/xCAT/CIMUtils.pm b/perl-xCAT/xCAT/CIMUtils.pm index 1c49f0102..d13a2e93a 100644 --- a/perl-xCAT/xCAT/CIMUtils.pm +++ b/perl-xCAT/xCAT/CIMUtils.pm @@ -63,74 +63,74 @@ sub enum_instance unless (ref($http_params)) { $http_params = shift; } - + my $cim_params = shift; - # This is a mandatory parameter + # This is a mandatory parameter unless ($cim_params->{classname}) { - return ({rc => 1, msg => "Missed the classname"}); + return ({ rc => 1, msg => "Missed the classname" }); } unless ($cim_params->{namespace}) { $cim_params->{namespace} = "ibmsd"; } - + # prepare the CIM payload my $tmpnode; # create a new doc - my $doc = XML::LibXML->createDocument('1.0','UTF-8'); - + my $doc = XML::LibXML->createDocument('1.0', 'UTF-8'); + # create and add the root element my $root = $doc->createElement("CIM"); $root->setAttribute("CIMVERSION", "2.0"); $root->setAttribute("DTDVERSION", "2.0"); - + $doc->setDocumentElement($root); - + # create and add the MESSAGE element my $message = $doc->createElement("MESSAGE"); - $message->setAttribute("ID", "1000"); + $message->setAttribute("ID", "1000"); $message->setAttribute("PROTOCOLVERSION", "1.0"); - + $root->addChild($message); - + # add a SIMPLE REQUEST my $simple_request = $doc->createElement("SIMPLEREQ"); $message->addChild($simple_request); - + # add an IMETHOD CALL my $imethod_call = $doc->createElement("IMETHODCALL"); $imethod_call->setAttribute("NAME", "EnumerateInstances"); - + $simple_request->addChild($imethod_call); - + # add the local name space path my $localnamespacepath = $doc->createElement("LOCALNAMESPACEPATH"); $tmpnode = $doc->createElement("NAMESPACE"); $tmpnode->setAttribute("NAME", "root"); $localnamespacepath->addChild($tmpnode); - + $tmpnode = $doc->createElement("NAMESPACE"); $tmpnode->setAttribute("NAME", $cim_params->{namespace}); $localnamespacepath->addChild($tmpnode); - + $imethod_call->addChild($localnamespacepath); - + # add the target class name my $param_classname = $doc->createElement("IPARAMVALUE"); $param_classname->setAttribute("NAME", "ClassName"); $imethod_call->addChild($param_classname); - + my $classname = $doc->createElement("CLASSNAME"); $classname->setAttribute("NAME", $cim_params->{classname}); $param_classname->addChild($classname); - + # add several common parameters $imethod_call->appendWellBalancedChunk('TRUEFALSEFALSETRUE'); - + my $payload = $doc->toString(); - + # generate http request my $ret = gen_http_request($http_params, $payload); @@ -146,15 +146,15 @@ sub enum_instance # parse the http response my $ret_value; - my $parser = XML::LibXML->new(); + my $parser = XML::LibXML->new(); my $resp_doc = $parser->parse_string($ret->{payload}); # check the error message from CIM my $error_node = $resp_doc->getElementsByTagName("ERROR"); if ($error_node) { - my $msg = $error_node->[0]->getAttribute("DESCRIPTION"); + my $msg = $error_node->[0]->getAttribute("DESCRIPTION"); my $errorcode = $error_node->[0]->getAttribute("CODE"); - return ({rc => 1, cim_rc => $errorcode, msg => $error_node->[0]->getAttribute("DESCRIPTION")." [cim return code: $errorcode]"}); + return ({ rc => 1, cim_rc => $errorcode, msg => $error_node->[0]->getAttribute("DESCRIPTION") . " [cim return code: $errorcode]" }); } # get the name path of the instance, which is used to set property @@ -167,6 +167,7 @@ sub enum_instance # get all the instance elements my @instances = $resp_doc->getElementsByTagName("VALUE.NAMEDINSTANCE"); foreach my $instance (@instances) { + # get all the property element for each instance my @properties = $instance->getElementsByTagName("PROPERTY"); if (my @property_arrays = $instance->getElementsByTagName("PROPERTY.ARRAY")) { @@ -174,18 +175,19 @@ sub enum_instance } my $ins_value; foreach my $property (@properties) { + # get name, vlaue and type for each property. (only the one which has value) if (my $pname = $property->getAttribute("NAME")) { if (my $pvalue = $property->getAttribute("TYPE")) { $ins_value->{property}->{$pname}->{type} = $pvalue; } if ($property->getElementsByTagName("VALUE.ARRAY")) { - my @nodelist = $property->getElementsByTagName("VALUE"); + my @nodelist = $property->getElementsByTagName("VALUE"); my @value_array = (); foreach my $n (@nodelist) { push @value_array, $n->textContent; } - $ins_value->{property}->{$pname}->{value} = join(',',@value_array); + $ins_value->{property}->{$pname}->{value} = join(',', @value_array); } elsif (my $node = $property->getElementsByTagName("VALUE")) { $ins_value->{property}->{$pname}->{value} = $node->[0]->textContent; } @@ -193,8 +195,8 @@ sub enum_instance } push @{$ret_value}, $ins_value; } - - return ({rc =>0}, $ret_value, $namepath_string); + + return ({ rc => 0 }, $ret_value, $namepath_string); } =head1 set_property () @@ -213,71 +215,72 @@ sub enum_instance cim_rc - The return code from CIM server. msg - Output message. =cut + sub set_property { my $http_params = shift; unless (ref($http_params)) { $http_params = shift; } - + my $cim_params = shift; # This is a mandatory parameter unless ($cim_params->{namepath}) { - return ({rc => 1, msg => "Missed the name path for the instance"}); + return ({ rc => 1, msg => "Missed the name path for the instance" }); } unless ($cim_params->{namespace}) { $cim_params->{namespace} = "ibmsd"; } - + # prepare the CIM payload my $tmpnode; # create a new doc - my $doc = XML::LibXML->createDocument('1.0','UTF-8'); - + my $doc = XML::LibXML->createDocument('1.0', 'UTF-8'); + # create and add the root element my $root = $doc->createElement("CIM"); $root->setAttribute("CIMVERSION", "2.0"); $root->setAttribute("DTDVERSION", "2.0"); - + $doc->setDocumentElement($root); - + # create and add the MESSAGE element my $message = $doc->createElement("MESSAGE"); - $message->setAttribute("ID", "1000"); + $message->setAttribute("ID", "1000"); $message->setAttribute("PROTOCOLVERSION", "1.0"); - + $root->addChild($message); - + # add a SIMPLE REQUEST my $simple_request = $doc->createElement("SIMPLEREQ"); $message->addChild($simple_request); - + # add an IMETHOD CALL my $imethod_call = $doc->createElement("IMETHODCALL"); $imethod_call->setAttribute("NAME", "SetProperty"); - + $simple_request->addChild($imethod_call); - + # add the local name space path my $localnamespacepath = $doc->createElement("LOCALNAMESPACEPATH"); $tmpnode = $doc->createElement("NAMESPACE"); $tmpnode->setAttribute("NAME", "root"); $localnamespacepath->addChild($tmpnode); - + $tmpnode = $doc->createElement("NAMESPACE"); $tmpnode->setAttribute("NAME", $cim_params->{namespace}); $localnamespacepath->addChild($tmpnode); - + $imethod_call->addChild($localnamespacepath); - + # add the target property name my $param_propertyname = $doc->createElement("IPARAMVALUE"); $param_propertyname->setAttribute("NAME", "PropertyName"); $imethod_call->addChild($param_propertyname); - + $tmpnode = $doc->createElement("VALUE"); $tmpnode->appendTextNode($cim_params->{propertyname}); $param_propertyname->addChild($tmpnode); @@ -286,19 +289,19 @@ sub set_property my $param_newvaluename = $doc->createElement("IPARAMVALUE"); $param_newvaluename->setAttribute("NAME", "NewValue"); $imethod_call->addChild($param_newvaluename); - + $tmpnode = $doc->createElement("VALUE"); $tmpnode->appendTextNode($cim_params->{propertyvalue}); $param_newvaluename->addChild($tmpnode); - + # add parameters of instance name path my $param_namepath = $doc->createElement("IPARAMVALUE"); $param_namepath->setAttribute("NAME", "InstanceName"); $param_namepath->appendWellBalancedChunk($cim_params->{namepath}); $imethod_call->addChild($param_namepath); - + my $payload = $doc->toString(); - + # generate http request my $ret = gen_http_request($http_params, $payload); @@ -314,15 +317,15 @@ sub set_property # parse the http response my $ret_value; - my $parser = XML::LibXML->new(); + my $parser = XML::LibXML->new(); my $resp_doc = $parser->parse_string($ret->{payload}); # check the error message from CIM my $error_node = $resp_doc->getElementsByTagName("ERROR"); if ($error_node) { - my $msg = $error_node->[0]->getAttribute("DESCRIPTION"); + my $msg = $error_node->[0]->getAttribute("DESCRIPTION"); my $errorcode = $error_node->[0]->getAttribute("CODE"); - return ({rc => 1, cim_rc => $errorcode, msg => $error_node->[0]->getAttribute("DESCRIPTION")." [cim return code: $errorcode]"}); + return ({ rc => 1, cim_rc => $errorcode, msg => $error_node->[0]->getAttribute("DESCRIPTION") . " [cim return code: $errorcode]" }); } @@ -347,40 +350,40 @@ sub set_property sub gen_http_request { - my $http_params = shift; + my $http_params = shift; my $http_payload = shift; - + # check the mandatory parameters - unless (defined ($http_params->{ip}) && defined ($http_params->{port}) && defined($http_params->{user}) && defined($http_params->{password})) { - return ({rc => 1, msg => "Missed the mandatory parameters: ip, port, user or password"}); + unless (defined($http_params->{ip}) && defined($http_params->{port}) && defined($http_params->{user}) && defined($http_params->{password})) { + return ({ rc => 1, msg => "Missed the mandatory parameters: ip, port, user or password" }); } # set the default value for parameters - unless (defined ($http_params->{protocol})) { + unless (defined($http_params->{protocol})) { $http_params->{protocol} = 'https'; } - unless (defined ($http_params->{format})) { + unless (defined($http_params->{format})) { $http_params->{format} = 'xml'; } - unless (defined ($http_params->{method})) { + unless (defined($http_params->{method})) { $http_params->{method} = 'GET'; } my $payload = ''; - if (defined ($http_params->{payload})) { + if (defined($http_params->{payload})) { $payload = $http_params->{payload}; } - if (defined ($http_payload)) { - unless (ref($http_payload)) { #Todo: support payloasd to be a hash + if (defined($http_payload)) { + unless (ref($http_payload)) { #Todo: support payloasd to be a hash $payload = $http_payload; } } # create the http head my $header = HTTP::Headers->new('content-type' => "application/$http_params->{format}", - 'Accept' => "application/$http_params->{format}", - 'User-Agent' => "xCAT/2", - 'Host' => "$http_params->{ip}:$http_params->{port}"); + 'Accept' => "application/$http_params->{format}", + 'User-Agent' => "xCAT/2", + 'Host' => "$http_params->{ip}:$http_params->{port}"); # set the user & password $header->authorization_basic($http_params->{user}, $http_params->{password}); @@ -396,7 +399,7 @@ sub gen_http_request # set the http version $request->protocol('HTTP/1.1'); - return ({rc => 0, request => $request}); + return ({ rc => 0, request => $request }); } @@ -418,44 +421,44 @@ sub gen_http_request sub send_http_request { - my $http_params = shift; + my $http_params = shift; my $http_request = shift; # Load the library LWP::Protocol::https for https support if ($http_params->{protocol} eq 'https') { - eval { require LWP::Protocol::https}; + eval { require LWP::Protocol::https }; if ($@) { - return ({rc => 1, msg => "Failed to load perl library LWP::Protocol::https"}); + return ({ rc => 1, msg => "Failed to load perl library LWP::Protocol::https" }); } } # create a new HTTP User Agent Object - my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0}); + my $ua = LWP::UserAgent->new(ssl_opts => { verify_hostname => 0, SSL_verify_mode => 0 }); if ($http_params->{timeout}) { $ua->timeout($http_params->{timeout}); } else { - $ua->timeout(10); # the default timeout is 10s + $ua->timeout(10); # the default timeout is 10s } - if (defined($http_params->{verbose}) && defined ($http_params->{callback})) { - $http_params->{callback}({data => ["\n========CIM Request Start========", $http_request->as_string(), "=======CIM Request End======="]}); + if (defined($http_params->{verbose}) && defined($http_params->{callback})) { + $http_params->{callback}({ data => [ "\n========CIM Request Start========", $http_request->as_string(), "=======CIM Request End=======" ] }); } # send request and receive the response my $response = $ua->request($http_request); - if (defined($http_params->{verbose}) && defined ($http_params->{callback}) && defined ($response->{_content})) { - $http_params->{callback}({data => ["\n========CIM Response Start========", $response->{_content}, "=======CIM Response End======="]}); + if (defined($http_params->{verbose}) && defined($http_params->{callback}) && defined($response->{_content})) { + $http_params->{callback}({ data => [ "\n========CIM Response Start========", $response->{_content}, "=======CIM Response End=======" ] }); } # check the http response - if (defined ($response) && defined ($response->{_rc}) && defined ($response->{_msg})) { + if (defined($response) && defined($response->{_rc}) && defined($response->{_msg})) { if ($response->{_rc} eq "200" && $response->{_msg} eq "OK") { - return ({rc => 0, http_rc => $response->{_rc}, msg => "$response->{_msg} [http return code: $response->{_rc}]", payload => $response->{_content}}); + return ({ rc => 0, http_rc => $response->{_rc}, msg => "$response->{_msg} [http return code: $response->{_rc}]", payload => $response->{_content} }); } } - - return ({rc => 1, http_rc => $response->{_rc}, msg => $response->{_msg}}); + + return ({ rc => 1, http_rc => $response->{_rc}, msg => $response->{_msg} }); } diff --git a/perl-xCAT/xCAT/Client.pm b/perl-xCAT/xCAT/Client.pm index c6966e978..b460d5f38 100644 --- a/perl-xCAT/xCAT/Client.pm +++ b/perl-xCAT/xCAT/Client.pm @@ -1,35 +1,37 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html package xCAT::Client; + BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. use Storable qw/nstore_fd fd_retrieve/; if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use IO::Handle; use MIME::Base64 qw(decode_base64); use IO::Socket::SSL; my $inet6support; -if ($^O =~ /^aix/i) { # disable AIX IPV6 TODO fix - $inet6support = 0; +if ($^O =~ /^aix/i) { # disable AIX IPV6 TODO fix + $inet6support = 0; } else { - $inet6support=eval { require Socket6; 1; }; + $inet6support = eval { require Socket6; 1; }; } if ($inet6support) { - $inet6support = eval { require IO::Socket::INET6; 1; }; + $inet6support = eval { require IO::Socket::INET6; 1; }; } if ($inet6support) { - $inet6support = eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet6'); 1;}; + $inet6support = eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet6'); 1; }; } if ($^O =~ /^linux/i) { + # Is IPv6 enabled on the MN or xcat client node at all? my $ipv6enabled = `ip addr 2> /dev/null | grep inet6`; if (!$ipv6enabled) { @@ -38,63 +40,66 @@ if ($^O =~ /^linux/i) { } unless ($inet6support) { - eval { require Socket }; - eval { require IO::Socket::INET }; - eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet4') }; + eval { require Socket }; + eval { require IO::Socket::INET }; + eval { require IO::Socket::SSL; IO::Socket::SSL->import('inet4') }; } -use XML::Simple; #smaller than libxml.... +use XML::Simple; #smaller than libxml.... use Fcntl; use POSIX qw/:errno_h/; use IO::Select; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; + #require Data::Dumper; -my $xcathost='localhost:3001'; +my $xcathost = 'localhost:3001'; my $plugins_dir; my %resps; -my $EXITCODE; # save the bitmask of all exit codes returned by calls to handle_response() +my $EXITCODE; # save the bitmask of all exit codes returned by calls to handle_response() 1; sub rspclean { - my $response = shift; - my $callback = shift; - my $rsps = XMLin($response,SuppressEmpty=>undef,ForceArray=>1); - foreach my $rsp (@{$rsps->{xcatresponse}}) { - #add ESC back - foreach my $key (keys %$rsp) { - if (ref($rsp->{$key}) eq 'ARRAY') { - foreach my $text (@{$rsp->{$key}}) { - next unless defined $text; - $text =~ s/xxxxESCxxxx/\e/g; - } - } - else { - $rsp->{$key} =~ s/xxxxESCxxxx/\e/g; - } - } - $callback->($rsp); - if ($rsp->{serverdone}) { - return 1; - } - } - return 0; + my $response = shift; + my $callback = shift; + my $rsps = XMLin($response, SuppressEmpty => undef, ForceArray => 1); + foreach my $rsp (@{ $rsps->{xcatresponse} }) { + + #add ESC back + foreach my $key (keys %$rsp) { + if (ref($rsp->{$key}) eq 'ARRAY') { + foreach my $text (@{ $rsp->{$key} }) { + next unless defined $text; + $text =~ s/xxxxESCxxxx/\e/g; + } + } + else { + $rsp->{$key} =~ s/xxxxESCxxxx/\e/g; + } + } + $callback->($rsp); + if ($rsp->{serverdone}) { + return 1; + } + } + return 0; } + sub send_request { my $request = shift; - my $sock = shift; - my $encode = shift; + my $sock = shift; + my $encode = shift; if ($encode eq "xml") { - my $msg=XMLout($request,RootName=>'xcatrequest',NoAttr=>1,KeyAttr=>[]); + my $msg = XMLout($request, RootName => 'xcatrequest', NoAttr => 1, KeyAttr => []); if ($ENV{XCATXMLTRACE}) { print $msg; } - if($ENV{XCATXMLWARNING}) { + if ($ENV{XCATXMLWARNING}) { validateXML($msg); } print $sock $msg; $sock->flush(); } else { - nstore_fd($request,$sock); + nstore_fd($request, $sock); $sock->flush(); } } @@ -133,845 +138,881 @@ sub send_request { # always create hashes with array values. ################################# sub submit_request { - my $request = shift; - my $callback = shift; - my $keyfile = shift; - my $certfile = shift; - my $cafile = shift; - # get home directory - my @user = getpwuid($>); - my $homedir=$user[7]; - unless ($keyfile) { $keyfile = $homedir."/.xcat/client-cred.pem"; } - unless ($certfile) { $certfile = $homedir."/.xcat/client-cred.pem"; } - unless ($cafile) { $cafile = $homedir."/.xcat/ca.pem"; } - $xCAT::Client::EXITCODE = 0; # clear out exit code before invoking the plugin -if (ref($request) eq 'HASH') { # the request is an array, not pure XML - $request->{clienttype}->[0] = "cli"; # setup clienttype for auditlog -} -# If XCATBYPASS is set, invoke the plugin process_request method directly -# without going through the socket connection to the xcatd daemon - if ($ENV{XCATBYPASS}) { - #add current userid to the request - if (ref($request) eq 'HASH') { # the request is an array, not pure XML - if (!(defined($request->{username}))) { - $request->{username}->[0] = getpwuid($>); - } + my $request = shift; + my $callback = shift; + my $keyfile = shift; + my $certfile = shift; + my $cafile = shift; - # only allow root to run - unless ($request->{username}->[0] =~ /root/) { - print ("WARNING: Only allow root to run XCATBYPASS mode, your current user ID is $request->{username}->[0].\n"); - return 0; - } - } - # Load plugins from either specified or default dir - require xCAT::Table; - my %cmd_handlers; - my @plugins_dirs = split('\:',$ENV{XCATBYPASS}); - if (-d $plugins_dirs[0]) { - foreach (@plugins_dirs) { - $plugins_dir = $_; - scan_plugins(); - } + # get home directory + my @user = getpwuid($>); + my $homedir = $user[7]; + unless ($keyfile) { $keyfile = $homedir . "/.xcat/client-cred.pem"; } + unless ($certfile) { $certfile = $homedir . "/.xcat/client-cred.pem"; } + unless ($cafile) { $cafile = $homedir . "/.xcat/ca.pem"; } + $xCAT::Client::EXITCODE = 0; # clear out exit code before invoking the plugin + if (ref($request) eq 'HASH') { # the request is an array, not pure XML + $request->{clienttype}->[0] = "cli"; # setup clienttype for auditlog + } + + # If XCATBYPASS is set, invoke the plugin process_request method directly + # without going through the socket connection to the xcatd daemon + if ($ENV{XCATBYPASS}) { + + #add current userid to the request + if (ref($request) eq 'HASH') { # the request is an array, not pure XML + if (!(defined($request->{username}))) { + $request->{username}->[0] = getpwuid($>); + } + + # only allow root to run + unless ($request->{username}->[0] =~ /root/) { + print("WARNING: Only allow root to run XCATBYPASS mode, your current user ID is $request->{username}->[0].\n"); + return 0; + } + } + + # Load plugins from either specified or default dir + require xCAT::Table; + my %cmd_handlers; + my @plugins_dirs = split('\:', $ENV{XCATBYPASS}); + if (-d $plugins_dirs[0]) { + foreach (@plugins_dirs) { + $plugins_dir = $_; + scan_plugins(); + } + } else { + + # figure out default plugins dir + #my $sitetab=xCAT::Table->new('site'); + #unless ($sitetab) { + # print ("ERROR: Unable to open basic site table for configuration\n"); + #} + $plugins_dir = $::XCATROOT . '/lib/perl/xCAT_plugin'; + scan_plugins(); + } + + populate_site_hash(); + + # don't do XML transformation -- assume request is well-formed + # my $xmlreq=XMLout($request,RootName=>xcatrequest,NoAttr=>1,KeyAttr=>[]); + # $request = XMLin($xmlreq,SuppressEmpty=>undef,ForceArray=>1) ; + + + # Call the plugin directly + # ${"xCAT_plugin::".$modname."::"}{process_request}->($request,$callback); + plugin_command($request, undef, $callback); + return 0; + } + + # No XCATBYPASS, so establish a socket connection with the xcatd daemon + # and submit the request + if ($ENV{XCATHOST}) { + $xcathost = $ENV{XCATHOST}; + } + my %connargs = (); + if ($xcathost =~ s/%([^\]|:]*)//) { + $connargs{PeerScope} = $1; + } + $connargs{PeerAddr} = $xcathost; + $connargs{Timeout} = 15; + if ($connargs{PeerScope} and $connargs{PeerScope} =~ /[a-zA-Z]/) { #non-numeric, need to translate... + my @ipdata = `ip link`; + @ipdata = grep(/[^@]$connargs{PeerScope}(:|@)/, @ipdata); + if (scalar(@ipdata) != 1) { + print STDERR "Unable to identify scope " . $connargs{PeerScope} . "\n"; + exit(1); + } + $connargs{PeerScope} = $ipdata[0]; + $connargs{PeerScope} =~ s/:.*//; + } + + + my $pclient; + if ($inet6support) { + $pclient = IO::Socket::INET6->new( + %connargs, + ); } else { - # figure out default plugins dir - #my $sitetab=xCAT::Table->new('site'); - #unless ($sitetab) { - # print ("ERROR: Unable to open basic site table for configuration\n"); - #} - $plugins_dir=$::XCATROOT.'/lib/perl/xCAT_plugin'; - scan_plugins(); + $pclient = IO::Socket::INET->new( + PeerAddr => $xcathost, + Timeout => 15, + ); + } + unless ($pclient) { + print "Unable to open socket connection to xcatd daemon on $xcathost.\n"; + print "Verify that the xcatd daemon is running and that your SSL setup is correct.\n"; + if ($@ =~ /SSL Timeout/) { + die "Connection failure: SSL Timeout or incorrect certificates in ~/.xcat"; + } else { + die "Connection failure: $@" + } + } + my $client; + my %sslargs; + if (defined($ENV{'XCATSSLVER'})) { + $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; + } + if (-r $keyfile and -r $certfile and -r $cafile) { + $client = IO::Socket::SSL->start_SSL($pclient, + SSL_key_file => $keyfile, + SSL_cert_file => $certfile, + SSL_ca_file => $cafile, + SSL_verify_mode => SSL_VERIFY_PEER, + SSL_verifycn_scheme => "none", + SSL_use_cert => 1, + Timeout => 0, + %sslargs, + ); + } else { + $client = IO::Socket::SSL->start_SSL($pclient, + Timeout => 0, + ); + } + unless ($client) { + print "Unable to open socket connection to xcatd daemon on $xcathost.\n"; + print "Verify that the xcatd daemon is running and that your SSL setup is correct.\n"; + if ($@ =~ /SSL Timeout/) { + die "Connection failure: SSL Timeout or incorrect certificates in ~/.xcat"; + } else { + die "Connection failure: $@" + } } - populate_site_hash(); + my $msg; + my $encode = "xml"; - # don't do XML transformation -- assume request is well-formed - # my $xmlreq=XMLout($request,RootName=>xcatrequest,NoAttr=>1,KeyAttr=>[]); - # $request = XMLin($xmlreq,SuppressEmpty=>undef,ForceArray=>1) ; - - - # Call the plugin directly - # ${"xCAT_plugin::".$modname."::"}{process_request}->($request,$callback); - plugin_command($request,undef,$callback); - return 0; - } - -# No XCATBYPASS, so establish a socket connection with the xcatd daemon -# and submit the request - if ($ENV{XCATHOST}) { - $xcathost=$ENV{XCATHOST}; - } - my %connargs=(); - if ($xcathost =~ s/%([^\]|:]*)//) { - $connargs{PeerScope} = $1; - } - $connargs{PeerAddr} = $xcathost; - $connargs{Timeout} = 15; - if ($connargs{PeerScope} and $connargs{PeerScope} =~ /[a-zA-Z]/) { #non-numeric, need to translate... - my @ipdata = `ip link`; - @ipdata = grep(/[^@]$connargs{PeerScope}(:|@)/,@ipdata); - if (scalar(@ipdata) != 1) { - print STDERR "Unable to identify scope ".$connargs{PeerScope}."\n"; - exit(1); - } - $connargs{PeerScope} = $ipdata[0]; - $connargs{PeerScope} =~ s/:.*//; - } - - - my $pclient; - if ($inet6support) { - $pclient = IO::Socket::INET6->new( - %connargs, - ); - } else { - $pclient = IO::Socket::INET->new( - PeerAddr => $xcathost, - Timeout => 15, - ); - } - unless ($pclient) { - print "Unable to open socket connection to xcatd daemon on $xcathost.\n"; - print "Verify that the xcatd daemon is running and that your SSL setup is correct.\n"; - if ($@ =~ /SSL Timeout/) { - die "Connection failure: SSL Timeout or incorrect certificates in ~/.xcat"; - } else { - die "Connection failure: $@" - } - } - my $client; - my %sslargs; - if (defined($ENV{'XCATSSLVER'})) { - $sslargs{SSL_version} = $ENV{'XCATSSLVER'}; - } - if (-r $keyfile and -r $certfile and -r $cafile) { - $client = IO::Socket::SSL->start_SSL($pclient, - SSL_key_file => $keyfile, - SSL_cert_file => $certfile, - SSL_ca_file => $cafile, - SSL_verify_mode => SSL_VERIFY_PEER, - SSL_use_cert => 1, - Timeout => 0, - %sslargs, - ); - } else { - $client = IO::Socket::SSL->start_SSL($pclient, - Timeout => 0, - ); - } - unless ($client) { - print "Unable to open socket connection to xcatd daemon on $xcathost.\n"; - print "Verify that the xcatd daemon is running and that your SSL setup is correct.\n"; - if ($@ =~ /SSL Timeout/) { - die "Connection failure: SSL Timeout or incorrect certificates in ~/.xcat"; - } else { - die "Connection failure: $@" - } - } - - my $msg; - my $encode = "xml"; - #storable encoding is unsafe, carry on with the unsafe xml scheme - #perhaps one day will support faster schemes - #my $encode = "storable"; - #my $straightprint=0; - #if ($ENV{XCATXMLTRACE} or $ENV{XCATXMLWARNING}) { $encode="xml"; } - if (ref($request) eq 'HASH') { # the request is an array, not pure XML - #print $client "xcatencoding: $encode\n"; - #my $encok=<$client>; - send_request($request,$client,$encode); - } else { #XML - $straightprint=1; - $msg=$request; - print $client $msg; - } - # when receive TERM or INT (ctrl^c) from user, sleep 2s before exit to make - # sure the server (xcatd) has recevied 'abortcommand' command - $SIG{TERM} = $SIG{INT} = sub { send_request({abortcommand=>[1]},$client,$encode); sleep 2; exit 0; }; - my $response; - my $rsp; - my $cleanexit=0; - if ($encode eq 'xml') { - my $massresponse=""; - my $nextcoalescetime=time()+1; - my $coalescenow=0; - my $flags=fcntl($client,F_GETFL,0); - $flags |= O_NONBLOCK; #select can be a bit.. fickle, make sysread work more easily... - fcntl($client,F_SETFL,$flags); - my $clientsel = new IO::Select; - $clientsel->add($client); - my $line; - my $newdata=0; - while (1) { - my $shouldexit; - if ($newdata and ($coalescenow or time() > $nextcoalescetime)) { - $coalescenow=0; - $newdata=0; - $nextcoalescetime=time()+1; - $massresponse .= ""; - $shouldexit = rspclean($massresponse,$callback); - $massresponse=""; - } - - if ($shouldexit) { - $cleanexit=1; - last; - } - $line = ""; - $clientsel->can_read(0.5); - my $readbytes; - do { $readbytes=sysread($client,$line,65535,length($line)); } while ($readbytes); - unless (length($line)) { - if (not defined $readbytes and $! == EAGAIN) { next; } - last; + #storable encoding is unsafe, carry on with the unsafe xml scheme + #perhaps one day will support faster schemes + #my $encode = "storable"; + #my $straightprint=0; + #if ($ENV{XCATXMLTRACE} or $ENV{XCATXMLWARNING}) { $encode="xml"; } + if (ref($request) eq 'HASH') { # the request is an array, not pure XML + #print $client "xcatencoding: $encode\n"; + #my $encok=<$client>; + send_request($request, $client, $encode); + } else { #XML + $straightprint = 1; + $msg = $request; + print $client $msg; } - $newdata=1; - $response .= $line; - if ($line =~ m/<\/xcatresponse>\s*\z/) { - if ($line =~ /serverdone/) { $coalescenow=1; } #if serverdone was detected, hint at coalesce code to flush things out now - #this means that coalesce can be triggered by stray words in the output prematurely, but that's harmless - #replace ESC with xxxxESCxxx because XMLin cannot handle it - $response =~ s/\e/xxxxESCxxxx/g; - if ($ENV{XCATXMLTRACE}) { print $response; } - $massresponse.=$response; - $response=''; - if($ENV{XCATXMLWARNING}) { - validateXML($response); - } - } - } - if (not $cleanexit and $massresponse ne "") { - $massresponse .= ""; - $cleanexit = rspclean($massresponse,$callback); - } - } else { #storable encode + # when receive TERM or INT (ctrl^c) from user, sleep 2s before exit to make + # sure the server (xcatd) has recevied 'abortcommand' command + $SIG{TERM} = $SIG{INT} = sub { send_request({ abortcommand => [1] }, $client, $encode); sleep 2; exit 0; }; + my $response; my $rsp; - eval { $rsp = fd_retrieve($client); }; - SERVERINPUT: while ($rsp) { - my @rsps; - if (ref $rsp eq 'ARRAY') { - @rsps = @$rsp; - } else { - @rsps = ($rsp); - } - foreach (@rsps) { - $callback->($_); - if ($_->{serverdone}) { - $cleanexit=1; - last SERVERINPUT; - } - } - $rsp = undef; - eval { $rsp = fd_retrieve($client); }; - } - } - $massresponse=""; - unless ($cleanexit) { - print STDERR "ERROR/WARNING: communication with the xCAT server seems to have been ended prematurely\n"; - $xCAT::Client::EXITCODE = 1; - } + my $cleanexit = 0; + if ($encode eq 'xml') { + my $massresponse = ""; + my $nextcoalescetime = time() + 1; + my $coalescenow = 0; + my $flags = fcntl($client, F_GETFL, 0); + $flags |= O_NONBLOCK; #select can be a bit.. fickle, make sysread work more easily... + fcntl($client, F_SETFL, $flags); + my $clientsel = new IO::Select; + $clientsel->add($client); + my $line; + my $newdata = 0; -sub validateXML { - my $xml = shift; - my @lines = split /\n/, $xml; - my $invalidNewline = 0; - my $contentsColon = 0; - my $contentsLine; - - foreach (@lines) { - if(!$invalidNewline) { - if( ($_ =~ // && $_ !~ /<\/contents>/) || - ($_ =~ // && $_ !~ /<\/desc>/)) { - $invalidNewline = 1; - print "Possible invalid XML using newlines found: \n$xml\n"; - } - } - if($_ =~ /.+:.+<\/contents>/) { - $contentsColon = 1; - $contentsLine = $_; - } - if($_ =~ /.+<\/desc>/) { - $contentsColon = 0; - } - if($contentsColon && $_ =~ /<\/desc>/) { - print "Possible invalid XML found(data contents using colon and blank description): \n$contentsLine\n$_\n"; - $contentsColon = 0; - } - } -} - -################################### -# scan_plugins -# will load all plugin perl modules and build a list of supported -# commands -# -# NOTE: This is copied from xcatd (last merge 11/23/09). -# TODO: Will eventually move to using common source.... -################################### -sub scan_plugins { - my @plugins=glob($plugins_dir."/*.pm"); - foreach (@plugins) { - /.*\/([^\/]*).pm$/; - my $modname = $1; - unless ( eval { require "$_" }) { -# xCAT::MsgUtils->message("S","Error loading module ".$_." ...skipping"); - print "Error loading module $_ ...skipping\n"; - next; - } - no strict 'refs'; - my $cmd_adds=${"xCAT_plugin::".$modname."::"}{handled_commands}->(); - foreach (keys %$cmd_adds) { - my $value = $_; - if (defined($cmd_handlers{$_})) { - push @{$cmd_handlers{$_}},[$modname,$cmd_adds->{$_}]; - } else { - $cmd_handlers{$_} = [ [$modname,$cmd_adds->{$_}] ]; - } - } - } - foreach (@plugins) { - no strict 'refs'; - /.*\/([^\/]*).pm$/; - my $modname = $1; - unless (defined(${"xCAT_plugin::".$modname."::"}{init_plugin})) { - next; - } - ${"xCAT_plugin::".$modname."::"}{init_plugin}->(\&do_request); - } -} - - - - -################################### -# plugin_command -# will invoke the correct plugin -# -# NOTE: This is copied from xcatd (last merge 11/23/09). -# TODO: Will eventually move to using common source.... -################################### -sub plugin_command { - my $req = shift; - my $sock = shift; - my $callback = shift; - my %handler_hash; - my $usesiteglobal = 0; - # We require these only in bypass mode to reduce start up time for the normal case - #use lib "$::XCATROOT/lib/perl"; - #use xCAT::NodeRange; - require lib; - lib->import("$::XCATROOT/lib/perl"); - require xCAT::NodeRange; - require xCAT::Table; - - $Main::resps={}; - my $xmlreq; - if (ref($req) ne 'HASH') { # the request XML, get an array - $xmlreq=$req; # save the original XML - $req = XMLin($xmlreq,SuppressEmpty=>undef,ForceArray=>1) ; - - } - my @nodes; - if ($req->{node}) { - @nodes = @{$req->{node}}; - } elsif ($req->{noderange} and $req->{noderange}->[0]) { - @nodes = xCAT::NodeRange::noderange($req->{noderange}->[0]); - if (xCAT::NodeRange::nodesmissed()) { -# my $rsp = {errorcode=>1,error=>"Invalid nodes in noderange:".join(',',xCAT::NodeRange::nodesmissed)}; -# my $rsp->{serverdone} = {}; - print "Invalid nodes in noderange:".join(',',xCAT::NodeRange::nodesmissed())."\n"; -# if ($sock) { -# print $sock XMLout($rsp,RootName=>'xcatresponse' ,NoAttr=>1); -# } -# return ($rsp); - return 1; - } - unless (@nodes) { - $req->{emptynoderange} = [1]; - } - } - if (@nodes) { $req->{node} = \@nodes; } - my %unhandled_nodes; - foreach (@nodes) { - $unhandled_nodes{$_}=1; - } - my $useunhandled=0; - if (defined($cmd_handlers{$req->{command}->[0]})) { - my $hdlspec; - my @globalhandlers=(); - my $useglobals=1; #If it stays 1, then use globals normally, if 0, use only for 'unhandled_nodes, if -1, don't do at all - foreach (@{$cmd_handlers{$req->{command}->[0]}}) { - $hdlspec =$_->[1]; - my $ownmod = $_->[0]; - if ($hdlspec =~ /^site:/) { #A site entry specifies a plugin - my $sitekey = $hdlspec; - $sitekey =~ s/^site://; - #$sitetab = xCAT::Table->new('site'); - #my $sent = $sitetab->getAttribs({key=>$sitekey},['value']); - #if ($sent and $sent->{value}) { #A site style plugin specification is just like - if ($::XCATSITEVALS{$sitekey}) { #A site style plugin specification is just like - #a static global, it grabs all nodes rather than some - $useglobals = -1; #If they tried to specify anything, don't use the default global handlers at all - unless (@nodes) { - $handler_hash{$::XCATSITEVALS{$sitekey}} = 1; - $usesiteglobal = 1; + while (1) { + my $shouldexit; + if ($newdata and ($coalescenow or time() > $nextcoalescetime)) { + $coalescenow = 0; + $newdata = 0; + $nextcoalescetime = time() + 1; + $massresponse .= ""; + $shouldexit = rspclean($massresponse, $callback); + $massresponse = ""; } - foreach (@nodes) { #Specified a specific plugin, not a table lookup - $handler_hash{$::XCATSITEVALS{$sitekey}}->{$_} = 1; + + if ($shouldexit) { + $cleanexit = 1; + last; } - } - } elsif ($hdlspec =~ /:/) { #Specificed a table lookup path for plugin name - if (@nodes) { # only use table lookup plugin if nodelist exists - # Usage will be handled in common AAAhelp plugin - - $useglobals = 0; #Only contemplate nodes that aren't caught through searching below in the global handler - $useunhandled=1; - my $table; - my $cols; - ($table,$cols) = split(/:/,$hdlspec); - my @colmns=split(/,/,$cols); - my @columns; - my $hdlrtable=xCAT::Table->new($table); - unless ($hdlrtable) { - #TODO: proper error handling - } - my $node; - my $colvals = {}; - foreach my $colu (@colmns) { - if ($colu =~ /=/) { #a value redirect to a pattern/specific name - my $coln; my $colv; - ($coln,$colv) = split(/=/,$colu,2); - $colvals->{$coln} = $colv; - push (@columns,$coln); - } else { - push (@columns,$colu); + $line = ""; + $clientsel->can_read(0.5); + my $readbytes; + do { $readbytes = sysread($client, $line, 65535, length($line)); } while ($readbytes); + unless (length($line)) { + if (not defined $readbytes and $! == EAGAIN) { next; } + last; } - } + $newdata = 1; + $response .= $line; + if ($line =~ m/<\/xcatresponse>\s*\z/) { + if ($line =~ /serverdone/) { $coalescenow = 1; } #if serverdone was detected, hint at coalesce code to flush things out now + #this means that coalesce can be triggered by stray words in the output prematurely, but that's harmless + #replace ESC with xxxxESCxxx because XMLin cannot handle it + $response =~ s/\e/xxxxESCxxxx/g; - - unless (@nodes) { #register the plugin in the event of usage - $handler_hash{$ownmod} = 1; - $useglobals = 1; - } - my $hdlrcache; - if ($hdlrtable) { - $hdlrcache = $hdlrtable->getNodesAttribs(\@nodes,\@columns); - } - foreach $node (@nodes) { - unless ($hdlrcache) { next; } - my $attribs = $hdlrcache->{$node}->[0]; #$hdlrtable->getNodeAttribs($node,\@columns); - unless (defined($attribs)) { next; } - foreach (@columns) { - my $col=$_; - if (defined($attribs->{$col})) { - if ($colvals->{$col}) { #A pattern match style request. - if ($attribs->{$col} =~ /$colvals->{$col}/) { - $handler_hash{$ownmod}->{$node} = 1; - delete $unhandled_nodes{$node}; - last; - } - } else { - # call the plugin that matches the table value for that node - if ($attribs->{$col} =~ /$ownmod/) { - $handler_hash{$attribs->{$col}}->{$node} = 1; - delete $unhandled_nodes{$node}; - last; - } + if ($ENV{XCATXMLTRACE}) { print $response; } + $massresponse .= $response; + $response = ''; + if ($ENV{XCATXMLWARNING}) { + validateXML($response); } - } } - } - $hdlrtable->close; - } # end if (@nodes) - - } else { - push @globalhandlers,$hdlspec; - } + } + if (not $cleanexit and $massresponse ne "") { + $massresponse .= ""; + $cleanexit = rspclean($massresponse, $callback); + } + } else { #storable encode + my $rsp; + eval { $rsp = fd_retrieve($client); }; + SERVERINPUT: while ($rsp) { + my @rsps; + if (ref $rsp eq 'ARRAY') { + @rsps = @$rsp; + } else { + @rsps = ($rsp); + } + foreach (@rsps) { + $callback->($_); + if ($_->{serverdone}) { + $cleanexit = 1; + last SERVERINPUT; + } + } + $rsp = undef; + eval { $rsp = fd_retrieve($client); }; + } } - if ($useglobals == 1) { #Behavior when globals have not been overriden - my $hdlspec; - foreach $hdlspec (@globalhandlers) { + $massresponse = ""; + unless ($cleanexit) { + print STDERR "ERROR/WARNING: communication with the xCAT server seems to have been ended prematurely\n"; + $xCAT::Client::EXITCODE = 1; + } + + sub validateXML { + my $xml = shift; + my @lines = split /\n/, $xml; + my $invalidNewline = 0; + my $contentsColon = 0; + my $contentsLine; + + foreach (@lines) { + if (!$invalidNewline) { + if (($_ =~ // && $_ !~ /<\/contents>/) || + ($_ =~ // && $_ !~ /<\/desc>/)) { + $invalidNewline = 1; + print "Possible invalid XML using newlines found: \n$xml\n"; + } + } + if ($_ =~ /.+:.+<\/contents>/) { + $contentsColon = 1; + $contentsLine = $_; + } + if ($_ =~ /.+<\/desc>/) { + $contentsColon = 0; + } + if ($contentsColon && $_ =~ /<\/desc>/) { + print "Possible invalid XML found(data contents using colon and blank description): \n$contentsLine\n$_\n"; + $contentsColon = 0; + } + } + } + +################################### + # scan_plugins + # will load all plugin perl modules and build a list of supported + # commands + # + # NOTE: This is copied from xcatd (last merge 11/23/09). + # TODO: Will eventually move to using common source.... +################################### + sub scan_plugins { + my @plugins = glob($plugins_dir . "/*.pm"); + foreach (@plugins) { + /.*\/([^\/]*).pm$/; + my $modname = $1; + unless (eval { require "$_" }) { + + # xCAT::MsgUtils->message("S","Error loading module ".$_." ...skipping"); + print "Error loading module $_ ...skipping\n"; + next; + } + no strict 'refs'; + my $cmd_adds = ${ "xCAT_plugin::" . $modname . "::" }{handled_commands}->(); + foreach (keys %$cmd_adds) { + my $value = $_; + if (defined($cmd_handlers{$_})) { + push @{ $cmd_handlers{$_} }, [ $modname, $cmd_adds->{$_} ]; + } else { + $cmd_handlers{$_} = [ [ $modname, $cmd_adds->{$_} ] ]; + } + } + } + foreach (@plugins) { + no strict 'refs'; + /.*\/([^\/]*).pm$/; + my $modname = $1; + unless (defined(${ "xCAT_plugin::" . $modname . "::" }{init_plugin})) { + next; + } + ${ "xCAT_plugin::" . $modname . "::" }{init_plugin}->(\&do_request); + } + } + + + + +################################### + # plugin_command + # will invoke the correct plugin + # + # NOTE: This is copied from xcatd (last merge 11/23/09). + # TODO: Will eventually move to using common source.... +################################### + sub plugin_command { + my $req = shift; + my $sock = shift; + my $callback = shift; + my %handler_hash; + my $usesiteglobal = 0; + + # We require these only in bypass mode to reduce start up time for the normal case + #use lib "$::XCATROOT/lib/perl"; + #use xCAT::NodeRange; + require lib; + lib->import("$::XCATROOT/lib/perl"); + require xCAT::NodeRange; + require xCAT::Table; + + $Main::resps = {}; + my $xmlreq; + if (ref($req) ne 'HASH') { # the request XML, get an array + $xmlreq = $req; # save the original XML + $req = XMLin($xmlreq, SuppressEmpty => undef, ForceArray => 1); + + } + my @nodes; + if ($req->{node}) { + @nodes = @{ $req->{node} }; + } elsif ($req->{noderange} and $req->{noderange}->[0]) { + @nodes = xCAT::NodeRange::noderange($req->{noderange}->[0]); + if (xCAT::NodeRange::nodesmissed()) { + + # my $rsp = {errorcode=>1,error=>"Invalid nodes in noderange:".join(',',xCAT::NodeRange::nodesmissed)}; + # my $rsp->{serverdone} = {}; + print "Invalid nodes in noderange:" . join(',', xCAT::NodeRange::nodesmissed()) . "\n"; + + # if ($sock) { + # print $sock XMLout($rsp,RootName=>'xcatresponse' ,NoAttr=>1); + # } + # return ($rsp); + return 1; + } unless (@nodes) { - $handler_hash{$hdlspec} = 1; + $req->{emptynoderange} = [1]; } - foreach (@nodes) { #Specified a specific plugin, not a table lookup - $handler_hash{$hdlspec}->{$_} = 1; + } + if (@nodes) { $req->{node} = \@nodes; } + my %unhandled_nodes; + foreach (@nodes) { + $unhandled_nodes{$_} = 1; + } + my $useunhandled = 0; + if (defined($cmd_handlers{ $req->{command}->[0] })) { + my $hdlspec; + my @globalhandlers = (); + my $useglobals = 1; #If it stays 1, then use globals normally, if 0, use only for 'unhandled_nodes, if -1, don't do at all + foreach (@{ $cmd_handlers{ $req->{command}->[0] } }) { + $hdlspec = $_->[1]; + my $ownmod = $_->[0]; + if ($hdlspec =~ /^site:/) { #A site entry specifies a plugin + my $sitekey = $hdlspec; + $sitekey =~ s/^site://; + + #$sitetab = xCAT::Table->new('site'); + #my $sent = $sitetab->getAttribs({key=>$sitekey},['value']); + #if ($sent and $sent->{value}) { #A site style plugin specification is just like + if ($::XCATSITEVALS{$sitekey}) { #A site style plugin specification is just like + #a static global, it grabs all nodes rather than some + $useglobals = -1; #If they tried to specify anything, don't use the default global handlers at all + unless (@nodes) { + $handler_hash{ $::XCATSITEVALS{$sitekey} } = 1; + $usesiteglobal = 1; + } + foreach (@nodes) { #Specified a specific plugin, not a table lookup + $handler_hash{ $::XCATSITEVALS{$sitekey} }->{$_} = 1; + } + } + } elsif ($hdlspec =~ /:/) { #Specificed a table lookup path for plugin name + if (@nodes) { # only use table lookup plugin if nodelist exists + # Usage will be handled in common AAAhelp plugin + + $useglobals = 0; #Only contemplate nodes that aren't caught through searching below in the global handler + $useunhandled = 1; + my $table; + my $cols; + ($table, $cols) = split(/:/, $hdlspec); + my @colmns = split(/,/, $cols); + my @columns; + my $hdlrtable = xCAT::Table->new($table); + unless ($hdlrtable) { + + #TODO: proper error handling + } + my $node; + my $colvals = {}; + foreach my $colu (@colmns) { + if ($colu =~ /=/) { #a value redirect to a pattern/specific name + my $coln; my $colv; + ($coln, $colv) = split(/=/, $colu, 2); + $colvals->{$coln} = $colv; + push(@columns, $coln); + } else { + push(@columns, $colu); + } + } + + + unless (@nodes) { #register the plugin in the event of usage + $handler_hash{$ownmod} = 1; + $useglobals = 1; + } + my $hdlrcache; + if ($hdlrtable) { + $hdlrcache = $hdlrtable->getNodesAttribs(\@nodes, \@columns); + } + foreach $node (@nodes) { + unless ($hdlrcache) { next; } + my $attribs = $hdlrcache->{$node}->[0]; #$hdlrtable->getNodeAttribs($node,\@columns); + unless (defined($attribs)) { next; } + foreach (@columns) { + my $col = $_; + if (defined($attribs->{$col})) { + if ($colvals->{$col}) { #A pattern match style request. + if ($attribs->{$col} =~ /$colvals->{$col}/) { + $handler_hash{$ownmod}->{$node} = 1; + delete $unhandled_nodes{$node}; + last; + } + } else { + + # call the plugin that matches the table value for that node + if ($attribs->{$col} =~ /$ownmod/) { + $handler_hash{ $attribs->{$col} }->{$node} = 1; + delete $unhandled_nodes{$node}; + last; + } + } + } + } + } + $hdlrtable->close; + } # end if (@nodes) + + } else { + push @globalhandlers, $hdlspec; + } } - } - } elsif ($useglobals == 0) { - unless (@nodes or $usesiteglobal) { #if something like 'makedhcp -n', - foreach (keys %handler_hash) { - if ($handler_hash{$_} == 1) { - delete ($handler_hash{$_}) - } - } - } - foreach $hdlspec (@globalhandlers) { - unless (@nodes or $usesiteglobal) { - $handler_hash{$hdlspec} = 1; + if ($useglobals == 1) { #Behavior when globals have not been overriden + my $hdlspec; + foreach $hdlspec (@globalhandlers) { + unless (@nodes) { + $handler_hash{$hdlspec} = 1; + } + foreach (@nodes) { #Specified a specific plugin, not a table lookup + $handler_hash{$hdlspec}->{$_} = 1; + } + } + } elsif ($useglobals == 0) { + unless (@nodes or $usesiteglobal) { #if something like 'makedhcp -n', + foreach (keys %handler_hash) { + if ($handler_hash{$_} == 1) { + delete($handler_hash{$_}) + } + } + } + foreach $hdlspec (@globalhandlers) { + unless (@nodes or $usesiteglobal) { + $handler_hash{$hdlspec} = 1; + } + foreach (keys %unhandled_nodes) { #Specified a specific plugin, not a table lookup + $handler_hash{$hdlspec}->{$_} = 1; + } + } + } #Otherwise, global handler is implicitly disabled + } else { + print "Error request: $req->{command}->[0] has no known plugin for it.\n"; + return 1; + } + if ($useunhandled) { + my $queuelist; + foreach (@{ $cmd_handlers{ $req->{command}->[0] } }) { + my $queueitem = $_->[1]; + if (($queueitem =~ /:/) and !($queuelist =~ /($queueitem)/)) { + $queuelist .= "$_->[1];"; + } } - foreach (keys %unhandled_nodes) { #Specified a specific plugin, not a table lookup - $handler_hash{$hdlspec}->{$_} = 1; + $queuelist =~ s/;$//; + $queuelist =~ s/:/./g; + foreach (keys %unhandled_nodes) { + + # if ($sock) { + # print $sock XMLout({node=>[{name=>[$_],data=>["Unable to identify plugin for this command, check relevant tables: $queuelist"],errorcode=>[1]}]},NoAttr=>1,RootName=>'xcatresponse'); + # } else { + my $tabdesc = $queuelist; + $tabdesc =~ s/=.*$//; + $callback->({ node => [ { name => [$_], error => [ 'Unable to identify plugin for this command, check relevant tables: ' . $tabdesc ], errorcode => [1] } ] }); + + # } } - } - } #Otherwise, global handler is implicitly disabled - } else { - print "Error request: $req->{command}->[0] has no known plugin for it.\n"; - return 1; - } - if ($useunhandled) { - my $queuelist; - foreach (@{$cmd_handlers{$req->{command}->[0]}}) { - my $queueitem = $_->[1]; - if (($queueitem =~ /:/) and !($queuelist =~ /($queueitem)/)) { - $queuelist .= "$_->[1];"; - } - } - $queuelist =~ s/;$//; - $queuelist =~ s/:/./g; - foreach (keys %unhandled_nodes) { -# if ($sock) { -# print $sock XMLout({node=>[{name=>[$_],data=>["Unable to identify plugin for this command, check relevant tables: $queuelist"],errorcode=>[1]}]},NoAttr=>1,RootName=>'xcatresponse'); -# } else { - my $tabdesc = $queuelist; - $tabdesc =~ s/=.*$//; - $callback->({node=>[{name=>[$_],error=>['Unable to identify plugin for this command, check relevant tables: '.$tabdesc],errorcode=>[1]}]}); -# } - } - } + } ## FOR NOW, DON'T FORK CHILD PROCESS TO MAKE BYPASS SIMPLER AND EASIER TO DEBUG -# $plugin_numchildren=0; -# %plugin_children=(); -# $SIG{CHLD} = \&plugin_reaper; #sub {my $plugpid; while (($plugpid = waitpid(-1, WNOHANG)) > 0) { if ($plugin_children{$plugpid}) { delete $plugin_children{$plugpid}; $plugin_numchildren--; } } }; -# my $check_fds; -# if ($sock) { -# $check_fds = new IO::Select; -# } - foreach (keys %handler_hash) { - my $modname = $_; -# my $shouldbealivepid=$$; - if (-r $plugins_dir."/".$modname.".pm") { - require $plugins_dir."/".$modname.".pm"; -# $plugin_numchildren++; -# my $pfd; #will be referenced for inter-process messaging. -# my $parfd; #not causing a problem that I discern yet, but theoretically -# my $child; -# if ($sock) { #If $sock not passed in, don't fork.. -# socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair: $!"; -# #pipe($pfd,$cfd); -# $parfd->autoflush(1); -# $pfd->autoflush(1); -# $child = xCAT::Utils->xfork; -# } else { -# $child = 0; -# } -# unless (defined $child) { die "Fork failed"; } -# if ($child == 0) { -# if ($parfd) { #If xCAT is doing multiple requests in same communication PID, things would get unfortunate otherwise -# $parent_fd = $parfd; -# } - my $oldprogname=$$progname; - $$progname=$oldprogname.": $modname instance"; -# if ($sock) { close $pfd; } - unless ($handler_hash{$_} == 1) { - my @nodes = sort {($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] || $a cmp $b } (keys %{$handler_hash{$_}}); - $req->{node}=\@nodes; + # $plugin_numchildren=0; + # %plugin_children=(); + # $SIG{CHLD} = \&plugin_reaper; #sub {my $plugpid; while (($plugpid = waitpid(-1, WNOHANG)) > 0) { if ($plugin_children{$plugpid}) { delete $plugin_children{$plugpid}; $plugin_numchildren--; } } }; + # my $check_fds; + # if ($sock) { + # $check_fds = new IO::Select; + # } + foreach (keys %handler_hash) { + my $modname = $_; + + # my $shouldbealivepid=$$; + if (-r $plugins_dir . "/" . $modname . ".pm") { + require $plugins_dir . "/" . $modname . ".pm"; + + # $plugin_numchildren++; + # my $pfd; #will be referenced for inter-process messaging. + # my $parfd; #not causing a problem that I discern yet, but theoretically + # my $child; + # if ($sock) { #If $sock not passed in, don't fork.. + # socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair: $!"; + # #pipe($pfd,$cfd); + # $parfd->autoflush(1); + # $pfd->autoflush(1); + # $child = xCAT::Utils->xfork; + # } else { + # $child = 0; + # } + # unless (defined $child) { die "Fork failed"; } + # if ($child == 0) { + # if ($parfd) { #If xCAT is doing multiple requests in same communication PID, things would get unfortunate otherwise + # $parent_fd = $parfd; + # } + my $oldprogname = $$progname; + $$progname = $oldprogname . ": $modname instance"; + + # if ($sock) { close $pfd; } + unless ($handler_hash{$_} == 1) { + my @nodes = sort { ($a =~ /(\d+)/)[0] <=> ($b =~ /(\d+)/)[0] || $a cmp $b } (keys %{ $handler_hash{$_} }); + $req->{node} = \@nodes; + } + no strict "refs"; + + # eval { #REMOVEEVALFORDEBUG + # if ($dispatch_requests) { + # backup the original req and recover it after the a run + my $org_req = {%$req}; + dispatch_request($req, $callback, $modname); + $req = {%$org_req}; + + # } else { + # $SIG{CHLD}='DEFAULT'; + # ${"xCAT_plugin::".$modname."::"}{process_request}->($req,$callback,\&do_request); + # } + $$progname = $oldprogname; + + # if ($sock) { + # close($parent_fd); + # xexit(0); + # } + # }; #REMOVEEVALFORDEBUG + # if ($sock or $shouldbealivepid != $$) { #We shouldn't still be alive, try to send as much detail to parent as possible as to why + # my $error= "$modname plugin bug, pid $$, process description: '$$progname'"; + # if ($@) { + # $error .= " with error '$@'"; + # } else { #Sys::Virt and perhaps Net::SNMP sometimes crashes in a way $@ won't catch.. + # $error .= " with missing eval error, probably due to special manipulation of $@ or strange circumstances in an XS library, remove evals in xcatd marked 'REMOVEEVALFORDEBUG and run xcatd -f for more info"; + # } + # if (scalar (@nodes)) { #Don't know which of the nodes, so one error message warning about the possibliity.. + # $error .= " while trying to fulfill request for the following nodes: ".join(",",@nodes); + # } + # xCAT::MsgUtils->message("S","xcatd: $error"); + # $callback->({error=>[$error],errorcode=>[1]}); + # xexit(0); #Die like we should have done + # } elsif ($@) { #We are still alive, should be alive, but yet we have an error. This means we are in the case of 'do_request' or something similar. Forward up the death since our communication channel is intact.. + # die $@; + # } + # } else { + # $plugin_children{$child}=1; + # close $parfd; + # $check_fds->add($pfd); + # } + } else { + my $pm_name = $plugins_dir . "/" . $modname . ".pm"; + foreach my $node (keys %{ $handler_hash{$_} }) { + if ($sock) { + print $sock XMLout({ node => [ { name => [$node], data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] } ] }, NoAttr => 1, RootName => 'xcatresponse'); + } else { + $callback->({ node => [ { name => [$node], data => ["Cannot find the perl module to complete the operation: $pm_name"], errorcode => [1] } ] }); + } + } + } } - no strict "refs"; -# eval { #REMOVEEVALFORDEBUG -# if ($dispatch_requests) { - # backup the original req and recover it after the a run - my $org_req = {%$req}; - dispatch_request($req,$callback,$modname); - $req = {%$org_req}; -# } else { -# $SIG{CHLD}='DEFAULT'; -# ${"xCAT_plugin::".$modname."::"}{process_request}->($req,$callback,\&do_request); -# } - $$progname=$oldprogname; -# if ($sock) { -# close($parent_fd); -# xexit(0); -# } -# }; #REMOVEEVALFORDEBUG -# if ($sock or $shouldbealivepid != $$) { #We shouldn't still be alive, try to send as much detail to parent as possible as to why -# my $error= "$modname plugin bug, pid $$, process description: '$$progname'"; -# if ($@) { -# $error .= " with error '$@'"; -# } else { #Sys::Virt and perhaps Net::SNMP sometimes crashes in a way $@ won't catch.. -# $error .= " with missing eval error, probably due to special manipulation of $@ or strange circumstances in an XS library, remove evals in xcatd marked 'REMOVEEVALFORDEBUG and run xcatd -f for more info"; -# } -# if (scalar (@nodes)) { #Don't know which of the nodes, so one error message warning about the possibliity.. -# $error .= " while trying to fulfill request for the following nodes: ".join(",",@nodes); -# } -# xCAT::MsgUtils->message("S","xcatd: $error"); -# $callback->({error=>[$error],errorcode=>[1]}); -# xexit(0); #Die like we should have done -# } elsif ($@) { #We are still alive, should be alive, but yet we have an error. This means we are in the case of 'do_request' or something similar. Forward up the death since our communication channel is intact.. -# die $@; -# } -# } else { -# $plugin_children{$child}=1; -# close $parfd; -# $check_fds->add($pfd); -# } - } else { - my $pm_name = $plugins_dir."/".$modname.".pm"; - foreach my $node (keys %{$handler_hash{$_}}) { - if ($sock) { - print $sock XMLout({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]},NoAttr=>1,RootName=>'xcatresponse'); + unless ($sock) { return $Main::resps } + + # while (($plugin_numchildren > 0) and ($check_fds->count > 0)) { #this tracks end of useful data from children much more closely + # relay_fds($check_fds,$sock); + # } + # #while (relay_fds($check_fds,$sock)) {} + # my %done; + # $done{serverdone} = {}; + # if ($req->{transid}) { + # $done{transid}=$req->{transid}->[0]; + # } + # if ($sock) { + # my $clientpresence = new IO::Select; #The client may have gone away without confirmation, don't PIPE over this trivial thing + # $clientpresence->add($sock); + # if ($clientpresence->can_write(5)) { + # print $sock XMLout(\%done,RootName => 'xcatresponse',NoAttr=>1); + # } + # } + } + + + + +################################### + # dispatch_request + # dispatch the requested command + # + # NOTE: This is copied from xcatd (last merge 11/23/09). + # All we really need from this subroutine is to call preprocess_request + # and to only run the command for nodes handled by the local server + # Will eventually move to using common source.... +################################### + sub dispatch_request { + + # %dispatched_children=(); + require xCAT::Utils; + my $req = shift; + $dispatch_cb = shift; + + my $modname = shift; + my $reqs = []; + + # my $child_fdset = new IO::Select; + no strict "refs"; + + #Hierarchy support. Originally, the default scope for noderange commands was + #going to be the servicenode associated unless overriden. + #However, assume for example that you have blades and a blade is the service node + #rpower being executed by the servicenode for one of its subnodes would have to + #reach it's own management module. This has the potential to be non-trivial for some quite possible network configurations. + #Since plugins may commonly experience this, a preprocess_request implementation + #will for now be required for a command to be scaled through service nodes + #If the plugin offers a preprocess method, use it to set the request array + if (defined(${ "xCAT_plugin::" . $modname . "::" }{preprocess_request})) { + $SIG{CHLD} = 'DEFAULT'; + $reqs = ${ "xCAT_plugin::" . $modname . "::" }{preprocess_request}->($req, $dispatch_cb, \&do_request); + } else { #otherwise, pass it in without hierarchy support + $reqs = [$req]; + } + + # $dispatch_children=0; + # $SIG{CHLD} = \&dispatch_reaper; #sub {my $cpid; while (($cpid =waitpid(-1, WNOHANG)) > 0) { if ($dispatched_children{$cpid}) { delete $dispatched_children{$cpid}; $dispatch_children--; } } }; + my $onlyone = 0; + if (defined $reqs and (scalar(@{$reqs}) == 1)) { + $onlyone = 1; + } + + foreach (@{$reqs}) { + + # my $pfd; + # my $parfd; #use a private variable so it won't trounce itself recursively + # my $child; + delete $_->{noderange}; + + #----- added to Client.pm -----# + if ($_->{node}) { + $_->{noderange}->[0] = join(',', @{ $_->{node} }); + } + + #----- end added to Client.pm -----# + + if (ref $_->{'_xcatdest'} and (ref $_->{'_xcatdest'}) eq 'ARRAY') { + _->{'_xcatdest'} = $_->{'_xcatdest'}->[0]; + } + if ($onlyone and not($_->{'_xcatdest'} and xCAT::NetworkUtils->thishostisnot($_->{'_xcatdest'}))) { + $SIG{CHLD} = 'DEFAULT'; + ${ "xCAT_plugin::" . $modname . "::" }{process_request}->($_, $dispatch_cb, \&do_request); + return; + } + + # socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair: $!"; + # $parfd->autoflush(1); + # $pfd->autoflush(1); + # $child = xCAT::Utils->xfork; + # if ($child) { + # $dispatch_children++; + # $dispatched_children{$child}=1; + # $child_fdset->add($pfd); + # next; + # } + # unless (defined $child) { + # $dispatch_cb->({error=>['Fork failure dispatching request'],errorcode=>[1]}); + # } + # undef $SIG{CHLD}; + # $dispatch_parentfd = $parfd; + my @prexcatdests = (); + my @xcatdests = (); + if (ref($_->{'_xcatdest'}) eq 'ARRAY') { #If array, consider it an 'anycast' operation, broadcast done through dupe + #requests, or an alternative join '&' maybe? + @prexcatdests = @{ $_->{'_xcatdest'} }; + } else { + @prexcatdests = ($_->{'_xcatdest'}); + } + foreach (@prexcatdests) { + if ($_ and /,/) { + push @xcatdests, split /,/, $_; + } else { + push @xcatdests, $_; + } + } + my $xcatdest; + my $numdests = scalar(@xcatdests); + my $request_satisfied = 0; + foreach $xcatdest (@xcatdests) { + my $dlock; + if ($xcatdest and xCAT::NetworkUtils->thishostisnot($xcatdest)) { + + #----- added to Client.pm -----# + $dispatch_cb->({ warning => [ 'XCATBYPASS is set, skipping hierarchy call to ' . $_->{'_xcatdest'} . '' ] }); + + #----- end added to Client.pm -----# + + # #mkpath("/var/lock/xcat/"); #For now, limit intra-xCAT requests to one at a time, to mitigate DB handle usage + # #open($dlock,">","/var/lock/xcat/dispatchto_$xcatdest"); + # #flock($dlock,LOCK_EX); + # $ENV{XCATHOST} = ($xcatdest =~ /:/ ? $xcatdest : $xcatdest.":3001" ); + # $$progname.=": connection to ".$ENV{XCATHOST}; + # my $errstr; + # eval { + # undef $_->{'_xcatdest'}; + # xCAT::Client::submit_request($_,\&dispatch_callback,$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/ca.pem"); + # }; + # if ($@) { + # $errstr=$@; + # } + # #unlink("/var/lock/xcat/dispatchto_$xcatdest"); + # #flock($dlock,LOCK_UN); + # if ($errstr) { + # if ($numdests == 1) { + # dispatch_callback({error=>["Unable to dispatch command to ".$ENV{XCATHOST}.", command will not make changes to that server ($errstr)"],errorcode=>[1]}); + # xCAT::MsgUtils->message("S","Error dispatching request to ".$ENV{XCATHOST}.": ".$errstr); + # } else { + # xCAT::MsgUtils->message("S","Error dispatching request to ".$ENV{XCATHOST}.", trying other service nodes: ".$errstr); + # } + # next; + # } else { + # $request_satisfied=1; + # last; + # } + } else { + $$progname .= ": locally executing"; + $SIG{CHLD} = 'DEFAULT'; + + # ${"xCAT_plugin::".$modname."::"}{process_request}->($_,\&dispatch_callback,\&do_request); + #----- changed in Client.pm -----# + ${ "xCAT_plugin::" . $modname . "::" }{process_request}->($_, $dispatch_cb, \&do_request); + + #----- end changed in Client.pm -----# + last; + } + } + + # if ($numdests > 1 and not $request_satisfied) { + # xCAT::MsgUtils->message("S","Error dispatching a request to all possible service nodes for request"); + # dispatch_callback({error=>["Failed to dispatch command to any of the following service nodes: ".join(",",@xcatdests)],errorcode=>[1]}); + # } + + # xexit; + } + + #while (($dispatch_children > 0) and ($child_fdset->count > 0)) { relay_dispatch($child_fdset) } + #while (relay_dispatch($child_fdset)) { } #Potentially useless drain. + } + + + +################################### + # do_request + # called from a plugin to execute another xCAT plugin command internally + # + # NOTE: This is copied from xcatd (last merge 11/23/09). + # Will eventually move to using common source.... +################################### + sub do_request { + my $req = shift; + my $second = shift; + my $rsphandler = \&build_response; + my $sock = undef; + if ($second) { + if (ref($second) eq "CODE") { + $rsphandler = $second; + } elsif (ref($second) eq "GLOB") { + $sock = $second; + } + } + + #my $sock = shift; #If no sock, will return a response hash + if ($cmd_handlers{ $req->{command}->[0] }) { + return plugin_command($req, $sock, $rsphandler); + } elsif ($req->{command}->[0] eq "noderange" and $req->{noderange}) { + my @nodes = xCAT::NodeRange::noderange($req->{noderange}->[0]); + my %resp; + if (xCAT::NodeRange::nodesmissed()) { + $resp{warning} = "Invalid nodes in noderange:" . join ',', xCAT::NodeRange::nodesmissed() . "\n"; + } + $resp{serverdone} = {}; + @{ $resp{node} } = @nodes; + if ($req->{transid}) { + $resp{transid} = $req->{transid}->[0]; + } + if ($sock) { + print $sock XMLout(\%resp, RootName => 'xcatresponse', NoAttr => 1); + } else { + return (\%resp); + } } else { - $callback->({node=>[{name=>[$node],data=>["Cannot find the perl module to complete the operation: $pm_name"],errorcode=>[1]}]}); + my %resp = (error => "Unsupported request"); + $resp{serverdone} = {}; + if ($req->{transid}) { + $resp{transid} = $req->{transid}->[0]; + } + if ($sock) { + print $sock XMLout(\%resp, RootName => 'xcatresponse', NoAttr => 1); + } else { + return (\%resp); + } } - } } - } - unless ($sock) { return $Main::resps }; -# while (($plugin_numchildren > 0) and ($check_fds->count > 0)) { #this tracks end of useful data from children much more closely -# relay_fds($check_fds,$sock); -# } -# #while (relay_fds($check_fds,$sock)) {} -# my %done; -# $done{serverdone} = {}; -# if ($req->{transid}) { -# $done{transid}=$req->{transid}->[0]; -# } -# if ($sock) { -# my $clientpresence = new IO::Select; #The client may have gone away without confirmation, don't PIPE over this trivial thing -# $clientpresence->add($sock); -# if ($clientpresence->can_write(5)) { -# print $sock XMLout(\%done,RootName => 'xcatresponse',NoAttr=>1); -# } -# } -} - - ################################### -# dispatch_request -# dispatch the requested command -# -# NOTE: This is copied from xcatd (last merge 11/23/09). -# All we really need from this subroutine is to call preprocess_request -# and to only run the command for nodes handled by the local server -# Will eventually move to using common source.... + # build_response + # This callback handles responses from nested level plugin calls. + # It builds a merged hash of all responses that gets passed back + # to the calling plugin. + # Note: Need to create a "deep clone" of this response to add to the + # return, otherwise next time through the referenced data is overwritten + # ################################### -sub dispatch_request { -# %dispatched_children=(); - require xCAT::Utils; - my $req = shift; - $dispatch_cb = shift; - - my $modname = shift; - my $reqs = []; -# my $child_fdset = new IO::Select; - no strict "refs"; - - #Hierarchy support. Originally, the default scope for noderange commands was - #going to be the servicenode associated unless overriden. - #However, assume for example that you have blades and a blade is the service node - #rpower being executed by the servicenode for one of its subnodes would have to - #reach it's own management module. This has the potential to be non-trivial for some quite possible network configurations. - #Since plugins may commonly experience this, a preprocess_request implementation - #will for now be required for a command to be scaled through service nodes - #If the plugin offers a preprocess method, use it to set the request array - if (defined(${"xCAT_plugin::".$modname."::"}{preprocess_request})) { - $SIG{CHLD}='DEFAULT'; - $reqs = ${"xCAT_plugin::".$modname."::"}{preprocess_request}->($req,$dispatch_cb,\&do_request); - } else { #otherwise, pass it in without hierarchy support - $reqs = [$req]; - } - -# $dispatch_children=0; -# $SIG{CHLD} = \&dispatch_reaper; #sub {my $cpid; while (($cpid =waitpid(-1, WNOHANG)) > 0) { if ($dispatched_children{$cpid}) { delete $dispatched_children{$cpid}; $dispatch_children--; } } }; - my $onlyone=0; - if (defined $reqs and (scalar(@{$reqs}) == 1)) { - $onlyone=1; - } - - foreach (@{$reqs}) { -# my $pfd; -# my $parfd; #use a private variable so it won't trounce itself recursively -# my $child; - delete $_->{noderange}; -#----- added to Client.pm -----# - if ($_->{node}) { - $_->{noderange}->[0]=join(',',@{$_->{node}}); - } -#----- end added to Client.pm -----# - - if (ref $_->{'_xcatdest'} and (ref $_->{'_xcatdest'}) eq 'ARRAY') { - _->{'_xcatdest'} = $_->{'_xcatdest'}->[0]; - } - if ($onlyone and not ($_->{'_xcatdest'} and xCAT::NetworkUtils->thishostisnot($_->{'_xcatdest'}))) { - $SIG{CHLD}='DEFAULT'; - ${"xCAT_plugin::".$modname."::"}{process_request}->($_,$dispatch_cb,\&do_request); - return; - } - -# socketpair($pfd, $parfd,AF_UNIX,SOCK_STREAM,PF_UNSPEC) or die "socketpair: $!"; -# $parfd->autoflush(1); -# $pfd->autoflush(1); -# $child = xCAT::Utils->xfork; -# if ($child) { -# $dispatch_children++; -# $dispatched_children{$child}=1; -# $child_fdset->add($pfd); -# next; -# } -# unless (defined $child) { -# $dispatch_cb->({error=>['Fork failure dispatching request'],errorcode=>[1]}); -# } -# undef $SIG{CHLD}; -# $dispatch_parentfd = $parfd; - my @prexcatdests=(); - my @xcatdests=(); - if (ref($_->{'_xcatdest'}) eq 'ARRAY') { #If array, consider it an 'anycast' operation, broadcast done through dupe - #requests, or an alternative join '&' maybe? - @prexcatdests=@{$_->{'_xcatdest'}}; - } else { - @prexcatdests=($_->{'_xcatdest'}); - } - foreach (@prexcatdests) { - if ($_ and /,/) { - push @xcatdests,split /,/,$_; - } else { - push @xcatdests,$_; - } - } - my $xcatdest; - my $numdests=scalar(@xcatdests); - my $request_satisfied=0; - foreach $xcatdest (@xcatdests) { - my $dlock; - if ($xcatdest and xCAT::NetworkUtils->thishostisnot($xcatdest)) { -#----- added to Client.pm -----# - $dispatch_cb->({warning=>['XCATBYPASS is set, skipping hierarchy call to '.$_->{'_xcatdest'}.'']}); -#----- end added to Client.pm -----# - -# #mkpath("/var/lock/xcat/"); #For now, limit intra-xCAT requests to one at a time, to mitigate DB handle usage -# #open($dlock,">","/var/lock/xcat/dispatchto_$xcatdest"); -# #flock($dlock,LOCK_EX); -# $ENV{XCATHOST} = ($xcatdest =~ /:/ ? $xcatdest : $xcatdest.":3001" ); -# $$progname.=": connection to ".$ENV{XCATHOST}; -# my $errstr; -# eval { -# undef $_->{'_xcatdest'}; -# xCAT::Client::submit_request($_,\&dispatch_callback,$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/server-cred.pem",$xcatdir."/cert/ca.pem"); -# }; -# if ($@) { -# $errstr=$@; -# } -# #unlink("/var/lock/xcat/dispatchto_$xcatdest"); -# #flock($dlock,LOCK_UN); -# if ($errstr) { -# if ($numdests == 1) { -# dispatch_callback({error=>["Unable to dispatch command to ".$ENV{XCATHOST}.", command will not make changes to that server ($errstr)"],errorcode=>[1]}); -# xCAT::MsgUtils->message("S","Error dispatching request to ".$ENV{XCATHOST}.": ".$errstr); -# } else { -# xCAT::MsgUtils->message("S","Error dispatching request to ".$ENV{XCATHOST}.", trying other service nodes: ".$errstr); -# } -# next; -# } else { -# $request_satisfied=1; -# last; -# } - } else { - $$progname.=": locally executing"; - $SIG{CHLD}='DEFAULT'; -# ${"xCAT_plugin::".$modname."::"}{process_request}->($_,\&dispatch_callback,\&do_request); -#----- changed in Client.pm -----# - ${"xCAT_plugin::".$modname."::"}{process_request}->($_,$dispatch_cb,\&do_request); -#----- end changed in Client.pm -----# - last; + sub build_response { + my $rsp = shift; + require Storable; + foreach (keys %$rsp) { + my $subresp = Storable::dclone($rsp->{$_}); + push(@{ $Main::resps->{$_} }, @{$subresp}); } - } -# if ($numdests > 1 and not $request_satisfied) { -# xCAT::MsgUtils->message("S","Error dispatching a request to all possible service nodes for request"); -# dispatch_callback({error=>["Failed to dispatch command to any of the following service nodes: ".join(",",@xcatdests)],errorcode=>[1]}); -# } - -# xexit; - } -#while (($dispatch_children > 0) and ($child_fdset->count > 0)) { relay_dispatch($child_fdset) } -#while (relay_dispatch($child_fdset)) { } #Potentially useless drain. -} - - - -################################### -# do_request -# called from a plugin to execute another xCAT plugin command internally -# -# NOTE: This is copied from xcatd (last merge 11/23/09). -# Will eventually move to using common source.... -################################### -sub do_request { - my $req = shift; - my $second = shift; - my $rsphandler = \&build_response; - my $sock = undef; - if ($second) { - if (ref($second) eq "CODE") { - $rsphandler = $second; - } elsif (ref($second) eq "GLOB") { - $sock = $second; } - } - - #my $sock = shift; #If no sock, will return a response hash - if ($cmd_handlers{$req->{command}->[0]}) { - return plugin_command($req,$sock,$rsphandler); - } elsif ($req->{command}->[0] eq "noderange" and $req->{noderange}) { - my @nodes = xCAT::NodeRange::noderange($req->{noderange}->[0]); - my %resp; - if (xCAT::NodeRange::nodesmissed()) { - $resp{warning}="Invalid nodes in noderange:".join ',',xCAT::NodeRange::nodesmissed() ."\n"; - } - $resp{serverdone} = {}; - @{$resp{node}}=@nodes; - if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; - } - if ($sock) { - print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1); - } else { - return (\%resp); - } - } else { - my %resp=(error=>"Unsupported request"); - $resp{serverdone} = {}; - if ($req->{transid}) { - $resp{transid}=$req->{transid}->[0]; - } - if ($sock) { - print $sock XMLout(\%resp,RootName => 'xcatresponse',NoAttr=>1); - } else { - return (\%resp); - } - } -} - - -################################### -# build_response -# This callback handles responses from nested level plugin calls. -# It builds a merged hash of all responses that gets passed back -# to the calling plugin. -# Note: Need to create a "deep clone" of this response to add to the -# return, otherwise next time through the referenced data is overwritten -# -################################### -sub build_response { - my $rsp = shift; - require Storable; - foreach (keys %$rsp) { - my $subresp = Storable::dclone($rsp->{$_}); - push (@{$Main::resps->{$_}}, @{$subresp}); - } -} @@ -982,15 +1023,15 @@ sub build_response { # This is used with XCATBYPASS=1 ################################### sub populate_site_hash { - %::XCATSITEVALS=(); - my $sitetab = xCAT::Table->new('site',-create=>0); - unless ($sitetab) { - print ("ERROR: Unable to open basic site table for configuration\n"); - return; + %::XCATSITEVALS = (); + my $sitetab = xCAT::Table->new('site', -create => 0); + unless ($sitetab) { + print("ERROR: Unable to open basic site table for configuration\n"); + return; } my @records = $sitetab->getAllAttribs(qw/key value/); foreach (@records) { - $::XCATSITEVALS{$_->{key}}=$_->{value}; + $::XCATSITEVALS{ $_->{key} } = $_->{value}; } } @@ -1077,188 +1118,194 @@ sub populate_site_hash { # node_name: desc: contents ########################################## sub handle_response { - my $rsp = shift; - if ($ENV{'XCATSHOWXML'}) { - my $xmlrec=XMLout($rsp,RootName=>'xcatresponse',NoAttr=>1,KeyAttr=>[]); - print "$xmlrec\n"; - return; - } -#print "in handle_response\n"; - # Handle errors - if (defined($rsp->{errorcode})) { - if (ref($rsp->{errorcode}) eq 'ARRAY') { - foreach my $ecode (@{$rsp->{errorcode}}) { - $xCAT::Client::EXITCODE |= $ecode; - } + my $rsp = shift; + if ($ENV{'XCATSHOWXML'}) { + my $xmlrec = XMLout($rsp, RootName => 'xcatresponse', NoAttr => 1, KeyAttr => []); + print "$xmlrec\n"; + return; } - else { - $xCAT::Client::EXITCODE |= $rsp->{errorcode}; - } # assume it is a non-reference scalar - } - if ($rsp->{error}) { -#print "printing error\n"; - if (ref($rsp->{error}) eq 'ARRAY') { - foreach my $text (@{$rsp->{error}}) { - if ($rsp->{NoErrorPrefix}) { - print STDERR "$text\n"; - } else { - print STDERR "Error: $text\n"; - } - } - } - else { - if ($rsp->{NoErrorPrefix}) { - print STDERR ($rsp->{error}."\n"); - } else { - print STDERR ("Error: ".$rsp->{error}."\n"); - } - } - } - if ($rsp->{warning}) { -#print "printing warning\n"; - if (ref($rsp->{warning}) eq 'ARRAY') { - foreach my $text (@{$rsp->{warning}}) { - if ($rsp->{NoWarnPrefix}) { - print STDERR "$text\n"; - } else { - print STDERR "Warning: $text\n"; - } - } - } - else { - if ($rsp->{NoWarnPrefix}) { - print STDERR ($rsp->{warning}."\n"); - } else { - print STDERR ("Warning: ".$rsp->{warning}."\n"); - } - } - } - if ($rsp->{info}) { -#print "printing info\n"; - if (ref($rsp->{info}) eq 'ARRAY') { - foreach my $text (@{$rsp->{info}}) { - print "$text\n"; - } - } - else { - print ($rsp->{info}."\n"); - } - } - if ($rsp->{sinfo}) { - if (ref($rsp->{sinfo}) eq 'ARRAY') { - foreach my $text (@{$rsp->{sinfo}}) { - print "$text\r"; $|++; - } - } - else { - print ($rsp->{sinfo}."\r"); $|++; - } - } - - - - # Handle {node} structure - my $errflg=0; - my $nodes=($rsp->{node}); - unless (ref $nodes eq 'ARRAY') { - $nodes = [$nodes]; - } - if (scalar @{$nodes}) { -#print "printing node\n"; - my $node; - foreach $node (@$nodes) { - my $desc; - if (ref($node->{name}) eq 'ARRAY') { - $desc=$node->{name}->[0]; - } else { - $desc=$node->{name}; - } - if ($node->{errorcode}) { - if (ref($node->{errorcode}) eq 'ARRAY') { - foreach my $ecode (@{$node->{errorcode}}) { - $xCAT::Client::EXITCODE |= $ecode; - } - } - else { - $xCAT::Client::EXITCODE |= $node->{errorcode}; - } # assume it is a non-reference scalar - } - if ($node->{error}) { - $desc.=": Error: ".$node->{error}->[0]; - $errflg=1; - } - if ($node->{warning}) { - $desc.=": Warning: ".$node->{warning}->[0]; - $errflg=1; - } - if ($node->{data}) { - if (ref(\($node->{data})) eq 'SCALAR') { - $desc=$desc.": ".$node->{data}; - } elsif (ref($node->{data}) eq 'HASH') { - if ($node->{data}->{desc}) { - if (ref($node->{data}->{desc}) eq 'ARRAY') { - $desc=$desc.": ".$node->{data}->{desc}->[0]; - } else { - $desc=$desc.": ".$node->{data}->{desc}; - } + #print "in handle_response\n"; + # Handle errors + if (defined($rsp->{errorcode})) { + if (ref($rsp->{errorcode}) eq 'ARRAY') { + foreach my $ecode (@{ $rsp->{errorcode} }) { + $xCAT::Client::EXITCODE |= $ecode; } - if ($node->{data}->{contents}) { - if (ref($node->{data}->{contents}) eq 'ARRAY') { - $desc="$desc: ".$node->{data}->{contents}->[0]; + } + else { + $xCAT::Client::EXITCODE |= $rsp->{errorcode}; + } # assume it is a non-reference scalar + } + if ($rsp->{error}) { + + #print "printing error\n"; + if (ref($rsp->{error}) eq 'ARRAY') { + foreach my $text (@{ $rsp->{error} }) { + if ($rsp->{NoErrorPrefix}) { + print STDERR "$text\n"; } else { - $desc="$desc: ".$node->{data}->{contents}; + print STDERR "Error: $text\n"; } } - } elsif (ref(\($node->{data}->[0])) eq 'SCALAR') { - $desc=$desc.": ".$node->{data}->[0]; - } else { - if ($node->{data}->[0]->{desc}) { - $desc=$desc.": ".$node->{data}->[0]->{desc}->[0]; - } - if ($node->{data}->[0]->{contents}) { - $desc="$desc: ".$node->{data}->[0]->{contents}->[0]; - } - } - } - if ($node->{base64_data}) { - $desc = $desc . ": " . decode_base64($node->{base64_data}->[0]); - } - if ($desc) { - if ($errflg == 1) { - print STDERR ("$desc\n"); - } else { - print "$desc\n"; } - } - } - } - - # Handle {data} structure with no nodes - if ($rsp->{data}) { -#print "printing data\n"; - my $data=($rsp->{data}); - my $data_entry; - foreach $data_entry (@$data) { - my $desc; - if (ref(\($data_entry)) eq 'SCALAR') { - $desc=$data_entry; - } else { - if ($data_entry->{desc}) { - $desc=$data_entry->{desc}->[0]; + else { + if ($rsp->{NoErrorPrefix}) { + print STDERR ($rsp->{error} . "\n"); + } else { + print STDERR ("Error: " . $rsp->{error} . "\n"); } - if ($data_entry->{contents}) { - if ($desc) { - $desc="$desc: ".$data_entry->{contents}->[0]; - } else { - $desc=$data_entry->{contents}->[0]; - } - } - } - if ($desc) { print "$desc\n"; } + } } - } -} # end of handle_response + if ($rsp->{warning}) { + + #print "printing warning\n"; + if (ref($rsp->{warning}) eq 'ARRAY') { + foreach my $text (@{ $rsp->{warning} }) { + if ($rsp->{NoWarnPrefix}) { + print STDERR "$text\n"; + } else { + print STDERR "Warning: $text\n"; + } + } + } + else { + if ($rsp->{NoWarnPrefix}) { + print STDERR ($rsp->{warning} . "\n"); + } else { + print STDERR ("Warning: " . $rsp->{warning} . "\n"); + } + } + } + if ($rsp->{info}) { + + #print "printing info\n"; + if (ref($rsp->{info}) eq 'ARRAY') { + foreach my $text (@{ $rsp->{info} }) { + print "$text\n"; + } + } + else { + print($rsp->{info} . "\n"); + } + } + + if ($rsp->{sinfo}) { + if (ref($rsp->{sinfo}) eq 'ARRAY') { + foreach my $text (@{ $rsp->{sinfo} }) { + print "$text\r"; $|++; + } + } + else { + print($rsp->{sinfo} . "\r"); $|++; + } + } + + + + # Handle {node} structure + my $errflg = 0; + my $nodes = ($rsp->{node}); + unless (ref $nodes eq 'ARRAY') { + $nodes = [$nodes]; + } + if (scalar @{$nodes}) { + + #print "printing node\n"; + my $node; + foreach $node (@$nodes) { + my $desc; + if (ref($node->{name}) eq 'ARRAY') { + $desc = $node->{name}->[0]; + } else { + $desc = $node->{name}; + } + if ($node->{errorcode}) { + if (ref($node->{errorcode}) eq 'ARRAY') { + foreach my $ecode (@{ $node->{errorcode} }) { + $xCAT::Client::EXITCODE |= $ecode; + } + } + else { + $xCAT::Client::EXITCODE |= $node->{errorcode}; + } # assume it is a non-reference scalar + } + if ($node->{error}) { + $desc .= ": Error: " . $node->{error}->[0]; + $errflg = 1; + } + if ($node->{warning}) { + $desc .= ": Warning: " . $node->{warning}->[0]; + $errflg = 1; + } + if ($node->{data}) { + if (ref(\($node->{data})) eq 'SCALAR') { + $desc = $desc . ": " . $node->{data}; + } elsif (ref($node->{data}) eq 'HASH') { + if ($node->{data}->{desc}) { + if (ref($node->{data}->{desc}) eq 'ARRAY') { + $desc = $desc . ": " . $node->{data}->{desc}->[0]; + } else { + $desc = $desc . ": " . $node->{data}->{desc}; + } + } + if ($node->{data}->{contents}) { + if (ref($node->{data}->{contents}) eq 'ARRAY') { + $desc = "$desc: " . $node->{data}->{contents}->[0]; + } else { + $desc = "$desc: " . $node->{data}->{contents}; + } + } + } elsif (ref(\($node->{data}->[0])) eq 'SCALAR') { + $desc = $desc . ": " . $node->{data}->[0]; + } else { + if ($node->{data}->[0]->{desc}) { + $desc = $desc . ": " . $node->{data}->[0]->{desc}->[0]; + } + if ($node->{data}->[0]->{contents}) { + $desc = "$desc: " . $node->{data}->[0]->{contents}->[0]; + } + } + } + if ($node->{base64_data}) { + $desc = $desc . ": " . decode_base64($node->{base64_data}->[0]); + } + if ($desc) { + if ($errflg == 1) { + print STDERR ("$desc\n"); + } else { + print "$desc\n"; + } + } + } + } + + # Handle {data} structure with no nodes + if ($rsp->{data}) { + + #print "printing data\n"; + my $data = ($rsp->{data}); + my $data_entry; + foreach $data_entry (@$data) { + my $desc; + if (ref(\($data_entry)) eq 'SCALAR') { + $desc = $data_entry; + } else { + if ($data_entry->{desc}) { + $desc = $data_entry->{desc}->[0]; + } + if ($data_entry->{contents}) { + if ($desc) { + $desc = "$desc: " . $data_entry->{contents}->[0]; + } else { + $desc = $data_entry->{contents}->[0]; + } + } + } + if ($desc) { print "$desc\n"; } + } + } +} # end of handle_response diff --git a/perl-xCAT/xCAT/Common.pm b/perl-xCAT/xCAT/Common.pm index 0ec8ac046..fedb1ebf1 100644 --- a/perl-xCAT/xCAT/Common.pm +++ b/perl-xCAT/xCAT/Common.pm @@ -12,40 +12,40 @@ use Storable qw/store_fd fd_retrieve/; BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } -# forward_data is a function used to aggregate output passed up from a set of -# children. This is commonly used due to make absolutely certain multiple +# forward_data is a function used to aggregate output passed up from a set of +# children. This is commonly used due to make absolutely certain multiple # writers trying to use a common file descriptor wouldn't corrupt each other. -# So instead, each child is given a dedicated filehandle and the parent +# So instead, each child is given a dedicated filehandle and the parent # uses this function to organize child data and send it up. # locking might be a more straightforward approach, but locking experiments # weren't as successful. sub forward_data { - my $callback = shift; - my $fds = shift; - my @ready_fds = $fds->can_read(1); - my $rfh; - my $rc = @ready_fds; - foreach $rfh (@ready_fds) { - my $responses; - eval { - $responses = fd_retrieve($rfh); - }; - if ($@ and $@ =~ /^Magic number checking on storable file/) { #this most likely means we ran over the end of available input - $fds->remove($rfh); - close($rfh); - } else { - eval { print $rfh "ACK\n"; }; #Ignore ack loss due to child giving up and exiting, we don't actually explicitly care about the acks - foreach (@$responses) { - $callback->($_); - } + my $callback = shift; + my $fds = shift; + my @ready_fds = $fds->can_read(1); + my $rfh; + my $rc = @ready_fds; + foreach $rfh (@ready_fds) { + my $responses; + eval { + $responses = fd_retrieve($rfh); + }; + if ($@ and $@ =~ /^Magic number checking on storable file/) { #this most likely means we ran over the end of available input + $fds->remove($rfh); + close($rfh); + } else { + eval { print $rfh "ACK\n"; }; #Ignore ack loss due to child giving up and exiting, we don't actually explicitly care about the acks + foreach (@$responses) { + $callback->($_); + } + } } - } - yield(); #Try to avoid useless iterations as much as possible - return $rc; + yield(); #Try to avoid useless iterations as much as possible + return $rc; } #This function pairs with the above. @@ -59,100 +59,100 @@ sub send_data { if (not ref $_[0]) { $node = shift; } - foreach(@_) { - my %output; - if (ref($_) eq HASH) { - store_fd([$_],$out); - yield(); - waitforack($out); - next; - } - my $line; - my $rc; - if (ref($_) eq ARRAY) { - $rc = $_->[0]; - $line = $_->[1]; - } else { - $line = $_; - } - - - (my $desc,my $text) = split (/:/,$line,2); - unless ($text) { - $text=$desc; - } else { - $desc =~ s/^\s+//; - $desc =~ s/\s+$//; - if ($desc) { - $output{node}->[0]->{data}->[0]->{desc}->[0]=$desc; + foreach (@_) { + my %output; + if (ref($_) eq HASH) { + store_fd([$_], $out); + yield(); + waitforack($out); + next; } - } - $text =~ s/^\s+//; - $text =~ s/\s+$//; - $output{node}->[0]->{name}->[0]=$node; - if ($rc) { - $output{node}->[0]->{errorcode} = $rc; - $output{node}->[0]->{error}->[0]->{contents}->[0]=$text; - } else { - $output{node}->[0]->{data}->[0]->{contents}->[0]=$text; - } - store_fd([\%output],$out); - yield(); - waitforack($out); + my $line; + my $rc; + if (ref($_) eq ARRAY) { + $rc = $_->[0]; + $line = $_->[1]; + } else { + $line = $_; + } + + + (my $desc, my $text) = split(/:/, $line, 2); + unless ($text) { + $text = $desc; + } else { + $desc =~ s/^\s+//; + $desc =~ s/\s+$//; + if ($desc) { + $output{node}->[0]->{data}->[0]->{desc}->[0] = $desc; + } + } + $text =~ s/^\s+//; + $text =~ s/\s+$//; + $output{node}->[0]->{name}->[0] = $node; + if ($rc) { + $output{node}->[0]->{errorcode} = $rc; + $output{node}->[0]->{error}->[0]->{contents}->[0] = $text; + } else { + $output{node}->[0]->{data}->[0]->{contents}->[0] = $text; + } + store_fd([ \%output ], $out); + yield(); + waitforack($out); } } #This function is intended to be used to process a request through the usage #module. -sub usage_noderange { - my $request = shift; - my $callback=shift; +sub usage_noderange { + my $request = shift; + my $callback = shift; - #display usage statement if -h is present or no noderage is specified - my $noderange = $request->{node}; #Should be arrayref - my $command = $request->{command}->[0]; - my $extrargs = $request->{arg}; - my @exargs=($request->{arg}); - if (ref($extrargs)) { - @exargs=@$extrargs; - } + #display usage statement if -h is present or no noderage is specified + my $noderange = $request->{node}; #Should be arrayref + my $command = $request->{command}->[0]; + my $extrargs = $request->{arg}; + my @exargs = ($request->{arg}); + if (ref($extrargs)) { + @exargs = @$extrargs; + } - my $usage_string=xCAT::Usage->parseCommand($command, @exargs); - if ($usage_string) { - $callback->({data=>$usage_string}); - $request = {}; - return; - } + my $usage_string = xCAT::Usage->parseCommand($command, @exargs); + if ($usage_string) { + $callback->({ data => $usage_string }); + $request = {}; + return; + } - if (!$noderange) { - $usage_string="Missing Noderange\n"; - $usage_string .=xCAT::Usage->getUsage($command); - $callback->({error=>[$usage_string],errorcode=>[1]}); - $request = {}; - return; - } + if (!$noderange) { + $usage_string = "Missing Noderange\n"; + $usage_string .= xCAT::Usage->getUsage($command); + $callback->({ error => [$usage_string], errorcode => [1] }); + $request = {}; + return; + } } # copy, overwriting only if the source file is newer sub copy_if_newer { - my ($source, $dest) = @_; + my ($source, $dest) = @_; - die "ERROR: source file doesn't exist\n" unless (-e $source); + die "ERROR: source file doesn't exist\n" unless (-e $source); - # resolve destination path - if ($dest =~ m/\/$/ || -d $dest) { - $dest .= '/' if ($dest !~ m/\/$/); - $dest .= $1 if $source =~ m/([^\/]+)$/; - } + # resolve destination path + if ($dest =~ m/\/$/ || -d $dest) { + $dest .= '/' if ($dest !~ m/\/$/); + $dest .= $1 if $source =~ m/([^\/]+)$/; + } - if (-e $dest) { - my $smtime = stat($source)->mtime; - my $dmtime = stat($dest)->mtime; + if (-e $dest) { + my $smtime = stat($source)->mtime; + my $dmtime = stat($dest)->mtime; - return if ($smtime < $dmtime); - } + return if ($smtime < $dmtime); + } - copy($source, $dest); + copy($source, $dest); } 1; diff --git a/perl-xCAT/xCAT/DBobjUtils.pm b/perl-xCAT/xCAT/DBobjUtils.pm index 1cbaeac1d..6f9c9e3f5 100755 --- a/perl-xCAT/xCAT/DBobjUtils.pm +++ b/perl-xCAT/xCAT/DBobjUtils.pm @@ -57,7 +57,7 @@ sub getObjectsOfType # The database may be changed between getObjectsOfType calls # do not use cache %::saveObjList if --nocache is specified if ($::saveObjList{$type} && !$::opt_nc) { - @objlist = @{$::saveObjList{$type}}; + @objlist = @{ $::saveObjList{$type} }; } else { # get the key for this type object @@ -71,9 +71,10 @@ sub getObjectsOfType my $table; my $tabkey; - foreach my $this_attr (@{$datatype->{'attrs'}}) { + foreach my $this_attr (@{ $datatype->{'attrs'} }) { my $attr = $this_attr->{attr_name}; if ($attr eq $objkey) { + # get the table & key for to lookup # get the actual attr name to use in the table # - may be different then the attr name used for the object. @@ -91,22 +92,22 @@ sub getObjectsOfType } # if this is type "group" we need to check the nodelist table - my @nodeGroupList=(); + my @nodeGroupList = (); if ($type eq 'group') { - my $table = "nodelist"; + my $table = "nodelist"; my @TableRowArray = xCAT::DBobjUtils->getDBtable($table); foreach (@TableRowArray) { my @tmplist = split(',', $_->{'groups'}); push(@nodeGroupList, @tmplist); } foreach my $n (@nodeGroupList) { - if (!grep(/^$n$/, @objlist) ) { + if (!grep(/^$n$/, @objlist)) { push(@objlist, $n); } } } - @{$::saveObjList{$type}} = @objlist; + @{ $::saveObjList{$type} } = @objlist; } return @objlist; @@ -138,12 +139,13 @@ sub getObjectsOfType #----------------------------------------------------------------------------- sub getobjattrs { - my $class = shift; + my $class = shift; my $ref_hash = shift; my @attrs; + # The $attrs is an optional argument if (ref $_[0]) { - @attrs = @{shift()}; + @attrs = @{ shift() }; } my %typehash = %$ref_hash; @@ -153,9 +155,10 @@ sub getobjattrs # get a list of object names for each type my %objtypelist; foreach my $objname (sort (keys %typehash)) { + # get list of objects for each type # $objtypelist{$typehash{$objname}}=$objname; - push @{$objtypelist{$typehash{$objname}}}, $objname; + push @{ $objtypelist{ $typehash{$objname} } }, $objname; } # go through each object type and look up all the info for each object @@ -163,15 +166,16 @@ sub getobjattrs # only do node type for now if ($objtype eq 'node') { + # find the list of tables and corresponding attrs # - for this object type # get the object type decription from Schema.pm my $datatype = $xCAT::Schema::defspec{$objtype}; - foreach my $this_attr (@{$datatype->{'attrs'}}) { + foreach my $this_attr (@{ $datatype->{'attrs'} }) { my $attr = $this_attr->{attr_name}; - if (scalar(@attrs) > 0) { # Only query specific attributes + if (scalar(@attrs) > 0) { # Only query specific attributes if (!grep(/^$attr$/, @attrs)) { - next; # This attribute is not needed + next; # This attribute is not needed } } @@ -180,14 +184,15 @@ sub getobjattrs # used in the node def # ex. 'nodetype.arch' my ($lookup_table, $table_attr) = split('\.', $this_attr->{tabentry}); - if (!grep(/^$table_attr$/, @{$tableattrs{$lookup_table}})) { - push @{$tableattrs{$lookup_table}}, $table_attr; + if (!grep(/^$table_attr$/, @{ $tableattrs{$lookup_table} })) { + push @{ $tableattrs{$lookup_table} }, $table_attr; } } # foreach table look up the list of attrs for this # list of object names foreach my $table (keys %tableattrs) { + # open the table # with autocommit => 0, it does not work on Ubuntu running mysql my $thistable = xCAT::Table->new($table, -create => 1, -autocommit => 1); @@ -198,23 +203,26 @@ sub getobjattrs next; } - my @objlist = @{$objtypelist{$objtype}}; + my @objlist = @{ $objtypelist{$objtype} }; - my $rec = $thistable->getNodesAttribs(\@objlist, @{$tableattrs{$table}}); + my $rec = $thistable->getNodesAttribs(\@objlist, @{ $tableattrs{$table} }); # fill in %tabhash with any values that are set foreach my $n (@objlist) { - my $tmp1=$rec->{$n}->[0]; - foreach $a (@{$tableattrs{$table}}) { + my $tmp1 = $rec->{$n}->[0]; + foreach $a (@{ $tableattrs{$table} }) { if (defined($tmp1->{$a})) { $tabhash{$table}{$n}{$a} = $tmp1->{$a}; + #print "obj = $n, table = $table, attr =$a, val = $tabhash{$table}{$n}{$a}\n"; } else { + # Add a has been searched flag to improve the performance - $tabhash{$table}{$n}{"$a"."_hassearched"} = 1; + $tabhash{$table}{$n}{ "$a" . "_hassearched" } = 1; } } } + #$thistable->commit; } } @@ -266,6 +274,7 @@ sub getobjdefs @::foundTableList = (); if ($::ATTRLIST eq "none") { + # just return the list of obj names foreach my $objname (sort (keys %typehash)) { my $type = $typehash{$objname}; @@ -275,10 +284,10 @@ sub getobjdefs } # see if we need to get any objects of type 'node' - my $getnodes=0; + my $getnodes = 0; foreach my $objname (keys %typehash) { if ($typehash{$objname} eq 'node') { - $getnodes=1; + $getnodes = 1; } } @@ -288,10 +297,10 @@ sub getobjdefs # values from when using 'only_if' - see below # - but this saves lots of time if ($getnodes) { - if (scalar(@attrs) > 0) { # Only get specific attributes of the node - # find the onlyif key for the attributes - REDO: my $datatype = $xCAT::Schema::defspec{'node'}; - foreach my $this_attr (@{$datatype->{'attrs'}}) { + if (scalar(@attrs) > 0) { # Only get specific attributes of the node + # find the onlyif key for the attributes + REDO: my $datatype = $xCAT::Schema::defspec{'node'}; + foreach my $this_attr (@{ $datatype->{'attrs'} }) { my $attr = $this_attr->{attr_name}; if (exists($this_attr->{only_if})) { my ($onlyif_key, $onlyif_value) = split('\=', $this_attr->{only_if}); @@ -310,23 +319,23 @@ sub getobjdefs # Classify the nodes with type my %type_obj = (); foreach my $objname (keys %typehash) { - push @{$type_obj{$typehash{$objname}}}, $objname; + push @{ $type_obj{ $typehash{$objname} } }, $objname; } foreach my $objtype (sort (keys %type_obj)) { if ($objtype eq 'site') { my @TableRowArray = xCAT::DBobjUtils->getDBtable('site'); - foreach my $objname (sort @{$type_obj{$objtype}}) { + foreach my $objname (sort @{ $type_obj{$objtype} }) { if (@TableRowArray) { my $foundinfo = 0; foreach (@TableRowArray) { if ($_->{key}) { - if (defined($_->{value}) ) { + if (defined($_->{value})) { $foundinfo++; if ($verbose == 1) { - $objhash{$objname}{$_->{key}} = "$_->{value}\t(Table:site - Key:$_->{key})"; + $objhash{$objname}{ $_->{key} } = "$_->{value}\t(Table:site - Key:$_->{key})"; } else { - $objhash{$objname}{$_->{key}} = $_->{value}; + $objhash{$objname}{ $_->{key} } = $_->{value}; } } } @@ -336,27 +345,28 @@ sub getobjdefs } } else { my $rsp; - $rsp->{data}->[0] ="Could not read the \'$objname\' object from the \'site\' table."; + $rsp->{data}->[0] = "Could not read the \'$objname\' object from the \'site\' table."; xCAT::MsgUtils->message("E", $rsp, $::callback); } } } elsif ($objtype eq 'monitoring') { + # need a special case for the monitoring table # - need to check the monsetting table for entries that contain # the same name as the monitoring table entry. my @TableRowArray = xCAT::DBobjUtils->getDBtable('monsetting'); - foreach my $objname (sort @{$type_obj{$objtype}}) { + foreach my $objname (sort @{ $type_obj{$objtype} }) { if (@TableRowArray) { my $foundinfo = 0; foreach (@TableRowArray) { - if ($_->{name} eq $objname ) { + if ($_->{name} eq $objname) { if ($_->{key}) { - if (defined($_->{value}) ) { + if (defined($_->{value})) { $foundinfo++; if ($verbose == 1) { - $objhash{$objname}{$_->{key}} = "$_->{value}\t(Table:monsetting)"; + $objhash{$objname}{ $_->{key} } = "$_->{value}\t(Table:monsetting)"; } else { - $objhash{$objname}{$_->{key}} = $_->{value}; + $objhash{$objname}{ $_->{key} } = $_->{value}; } } } @@ -367,26 +377,28 @@ sub getobjdefs } } else { my $rsp; - $rsp->{data}->[0] ="Could not read the \'$objname\' object from the \'monsetting\' table."; + $rsp->{data}->[0] = "Could not read the \'$objname\' object from the \'monsetting\' table."; xCAT::MsgUtils->message("E", $rsp, $::callback); } } } elsif (($objtype eq 'auditlog') || ($objtype eq 'eventlog')) { + # Special case for auditlog/eventlog # All the auditlog/eventlog attributes are in auditlog/eventlog table, # Do not need to read the table multiple times for each attribute. # The auditlog/eventlog is likely be very big over time, # performance is a big concern with the general logic my @TableRowArray = xCAT::DBobjUtils->getDBtable($objtype); - foreach my $objname (sort @{$type_obj{$objtype}}) { + foreach my $objname (sort @{ $type_obj{$objtype} }) { if (@TableRowArray) { my $foundinfo = 0; foreach my $entry (@TableRowArray) { if ($entry->{recid} eq $objname) { foreach my $k (keys %{$entry}) { + # recid is the object name, do not need to be in the attributes list if ($k eq 'recid') { next; } - if (defined($entry->{$k}) ) { + if (defined($entry->{$k})) { $foundinfo++; if ($verbose == 1) { $objhash{$objname}{$k} = "$entry->{$k}\t(Table:$objtype - Key:$k)"; @@ -398,20 +410,23 @@ sub getobjdefs if ($foundinfo) { $objhash{$objname}{'objtype'} = $objtype; } + # There should not be multiple entries with the same recid last; - } # end if($entry-> - } # end foreach my $entry - } # end if(@TableTowArray - } # end foreach my $objname + } # end if($entry-> + } # end foreach my $entry + } # end if(@TableTowArray + } # end foreach my $objname } else { + # get the object type decription from Schema.pm my $datatype = $xCAT::Schema::defspec{$objtype}; + # get the key to look for, for this object type my $objkey = $datatype->{'objkey'}; # go through the list of valid attrs - foreach my $this_attr (@{$datatype->{'attrs'}}) { + foreach my $this_attr (@{ $datatype->{'attrs'} }) { my $ent; my $attr = $this_attr->{attr_name}; @@ -419,6 +434,7 @@ sub getobjdefs if ($attr eq $objkey) { next; } + # skip the attributes that does not needed for node type if ($getnodes) { if (scalar(@attrs) > 0 && !grep(/^$attr$/, @attrs)) { @@ -434,7 +450,8 @@ sub getobjdefs # ex. noderes.nfsdir my ($tab, $tabattr) = split('\.', $this_attr->{tabentry}); - foreach my $objname (sort @{$type_obj{$objtype}}) { + foreach my $objname (sort @{ $type_obj{$objtype} }) { + # get table lookup info from Schema.pm # !!!! some tables depend on the value of certain attrs # we need to look up attrs in the correct order or we will @@ -442,22 +459,24 @@ sub getobjdefs # in for some attrs. if (exists($this_attr->{only_if})) { my ($check_attr, $check_value) = split('\=', $this_attr->{only_if}); + # if the object value is not the value we need # to match then try the next only_if value - next if ( !($objhash{$objname}{$check_attr} =~ /\b$check_value\b/) ); + next if (!($objhash{$objname}{$check_attr} =~ /\b$check_value\b/)); } $objhash{$objname}{'objtype'} = $objtype; my %tabentry = (); + # def commands need to support multiple keys in one table # the subroutine parse_access_tabentry is used for supporting multiple keys my $rc = xCAT::DBobjUtils->parse_access_tabentry($objname, - $this_attr->{access_tabentry}, \%tabentry); + $this_attr->{access_tabentry}, \%tabentry); if ($rc != 0) { my $rsp; $rsp->{data}->[0] = - "access_tabentry \'$this_attr->{access_tabentry}\' is not valid."; +"access_tabentry \'$this_attr->{access_tabentry}\' is not valid."; xCAT::MsgUtils->message("E", $rsp, $::callback); next; } @@ -465,12 +484,13 @@ sub getobjdefs # Only allow one table in the access_tabentry # use multiple tables to look up tabentry does not make any sense my $lookup_table = $tabentry{'lookup_table'}; - my $intabhash = 0; - my $notsearched = 0; - foreach my $lookup_attr (keys %{$tabentry{'lookup_attrs'}}) { + my $intabhash = 0; + my $notsearched = 0; + foreach my $lookup_attr (keys %{ $tabentry{'lookup_attrs'} }) { + # Check whether the attribute is already in %tabhash # The %tabhash is for performance considerations - if ( ($lookup_attr eq 'node') && ($objtype eq 'node') ) { + if (($lookup_attr eq 'node') && ($objtype eq 'node')) { if (defined($tabhash{$lookup_table}{$objname}{$tabattr})) { if ($verbose == 1) { $objhash{$objname}{$attr} = "$tabhash{$lookup_table}{$objname}{$tabattr}\t(Table:$lookup_table - Key:$lookup_attr - Column:$tabattr)"; @@ -478,11 +498,11 @@ sub getobjdefs $objhash{$objname}{$attr} = $tabhash{$lookup_table}{$objname}{$tabattr}; } if (defined $chname_ref) { - push @{$chname_ref->{$lookup_table}}, ($tabentry{'lookup_attrs'}, $lookup_attr); + push @{ $chname_ref->{$lookup_table} }, ($tabentry{'lookup_attrs'}, $lookup_attr); } $intabhash = 1; last; - } elsif (! defined($tabhash{$lookup_table}{$objname}{"$tabattr"."_hassearched"})) { + } elsif (!defined($tabhash{$lookup_table}{$objname}{ "$tabattr" . "_hassearched" })) { $notsearched = 1; } } else { @@ -493,14 +513,16 @@ sub getobjdefs # Not in tabhash, # Need to lookup the table if ($intabhash == 0 && $notsearched == 1) { + # look up attr values my @rows = xCAT::DBobjUtils->getDBtable($lookup_table); if (@rows) { foreach my $rowent (@rows) { my $match = 1; my $matchedattr; + # Again, multiple keys support needs the "foreach" - foreach my $lookup_attr (keys %{$tabentry{'lookup_attrs'}}) { + foreach my $lookup_attr (keys %{ $tabentry{'lookup_attrs'} }) { if ($rowent->{$lookup_attr} ne $tabentry{'lookup_attrs'}{$lookup_attr}) { $match = 0; last; @@ -508,24 +530,24 @@ sub getobjdefs } if ($match == 1) { if ($verbose == 1) { - my @lookup_attrs = keys %{$tabentry{'lookup_attrs'}}; + my @lookup_attrs = keys %{ $tabentry{'lookup_attrs'} }; $objhash{$objname}{$attr} = "$rowent->{$tabattr}\t(Table:$lookup_table - Key: @lookup_attrs - Column:$tabattr)"; } else { $objhash{$objname}{$attr} = $rowent->{$tabattr}; } if (defined $chname_ref) { - push @{$chname_ref->{$lookup_table}}, ($tabentry{'lookup_attrs'}, (keys %{$tabentry{'lookup_attrs'}}) [0]); + push @{ $chname_ref->{$lookup_table} }, ($tabentry{'lookup_attrs'}, (keys %{ $tabentry{'lookup_attrs'} })[0]); } - } #end if ($match... - } #end foreach - } # end if (defined... - } #end if ($intabhash... + } #end if ($match... + } #end foreach + } # end if (defined... + } #end if ($intabhash... } } } - } #foreach my $objtype + } #foreach my $objtype return %objhash; } @@ -562,7 +584,7 @@ sub getDBtable if (grep(/^$table$/, @::foundTableList) && !$::opt_nc) { # already have this - @rows = @{$::TableHash{$table}}; + @rows = @{ $::TableHash{$table} }; } else { @@ -573,7 +595,7 @@ sub getDBtable } #@rows = $thistable->getTable; - @rows = @{$thistable->getAllEntries()}; + @rows = @{ $thistable->getAllEntries() }; # !!!! this routine returns rows even if the table is empty!!!!!! @@ -581,11 +603,11 @@ sub getDBtable # - even if it's empty! push(@::foundTableList, $thistable->{tabname}); - @{$::TableHash{$table}} = @rows; + @{ $::TableHash{$table} } = @rows; #$thistable->commit; - } # end if not cached + } # end if not cached if (@rows) { return @rows; @@ -628,7 +650,7 @@ sub setobjdefs my %settableref; my $ret = 0; my %allupdates; - my $setattrs=0; + my $setattrs = 0; # get the attr=vals for these objects from the DB - if any # - so we can figure out where to put additional attrs @@ -641,7 +663,7 @@ sub setobjdefs foreach my $objname (keys %objhash) { my $type = $objhash{$objname}{objtype}; $DBhash{$objname} = $type; - @attrs = keys %{$objhash{$objname}}; + @attrs = keys %{ $objhash{$objname} }; } my %DBattrvals; @@ -667,7 +689,7 @@ sub setobjdefs # get a list of valid attr names # for this type object my @attrlist; - foreach my $entry (@{$datatype->{'attrs'}}) { + foreach my $entry (@{ $datatype->{'attrs'} }) { push(@attrlist, $entry->{'attr_name'}); } @@ -679,6 +701,7 @@ sub setobjdefs xCAT::MsgUtils->message("E", $rsp, $::callback); return 1; } + # open the table my $monsettable = xCAT::Table->new('monsetting', -create => 1, -autocommit => 0); if (!$monsettable) { @@ -691,7 +714,7 @@ sub setobjdefs my %keyhash; my %updates; - foreach my $attr (keys %{$objhash{$objname}}) { + foreach my $attr (keys %{ $objhash{$objname} }) { my $val; if ($attr eq 'objtype') { next; @@ -699,6 +722,7 @@ sub setobjdefs # determine the value if we have plus or minus if ($::plus_option) { + # add new to existing - at the end - comma separated if (defined($DBattrvals{$objname}{$attr})) { $val = "$DBattrvals{$objname}{$attr},$objhash{$objname}{$attr}"; @@ -706,12 +730,14 @@ sub setobjdefs $val = "$objhash{$objname}{$attr}"; } } elsif ($::minus_option) { + # remove the specified list of values from the current # attr values. if ($DBattrvals{$objname}{$attr}) { + # get the list of attrs to remove my @currentList = split(/,/, $DBattrvals{$objname}{$attr}); - my @minusList = split(/,/, $objhash{$objname}{$attr}); + my @minusList = split(/,/, $objhash{$objname}{$attr}); # make a new list without the one specified my $first = 1; @@ -719,6 +745,7 @@ sub setobjdefs foreach my $i (@currentList) { chomp $i; if (!grep(/^$i$/, @minusList)) { + # set new groups list for node if (!$first) { $newlist .= ","; @@ -730,19 +757,22 @@ sub setobjdefs $val = $newlist; } } else { + #just set the attr to what was provided! - replace $val = $objhash{$objname}{$attr}; } if (grep(/^$attr$/, @attrlist)) { + # if the attr belong in the monitoring tabel - %keyhash=(name=>$objname); - %updates=($attr=>$val); + %keyhash = (name => $objname); + %updates = ($attr => $val); $montable->setAttribs(\%keyhash, \%updates); } else { + # else it belongs in the monsetting table - $keyhash{name} = $objname; - $keyhash{key} = $attr; + $keyhash{name} = $objname; + $keyhash{key} = $attr; $updates{value} = $val; $monsettable->setAttribs(\%keyhash, \%updates); } @@ -751,13 +781,14 @@ sub setobjdefs $montable->commit; $monsettable->commit; next; - } #if ($type eq 'monitoring') + } #if ($type eq 'monitoring') # handle the site table as a special case !!!!! if ($type eq 'site') { + # open the table my $thistable = - xCAT::Table->new('site', -create => 1, -autocommit => 0); + xCAT::Table->new('site', -create => 1, -autocommit => 0); if (!$thistable) { my $rsp; $rsp->{data}->[0] = "Could not set the \'$thistable\' table."; @@ -765,7 +796,7 @@ sub setobjdefs return 1; } - foreach my $attr (keys %{$objhash{$objname}}) { + foreach my $attr (keys %{ $objhash{$objname} }) { if ($attr eq 'objtype') { next; } @@ -775,20 +806,23 @@ sub setobjdefs my $val; if ($::plus_option) { + # add new to existing - at the end - comma separated if (defined($DBattrvals{$objname}{$attr})) { $val = - "$DBattrvals{$objname}{$attr},$objhash{$objname}{$attr}"; +"$DBattrvals{$objname}{$attr},$objhash{$objname}{$attr}"; } else { $val = "$objhash{$objname}{$attr}"; } } elsif ($::minus_option) { + # remove the specified list of values from the current # attr values. if ($DBattrvals{$objname}{$attr}) { + # get the list of attrs to remove my @currentList = split(/,/, $DBattrvals{$objname}{$attr}); - my @minusList = split(/,/, $objhash{$objname}{$attr}); + my @minusList = split(/,/, $objhash{$objname}{$attr}); # make a new list without the one specified my $first = 1; @@ -796,6 +830,7 @@ sub setobjdefs foreach my $i (@currentList) { chomp $i; if (!grep(/^$i$/, @minusList)) { + # set new groups list for node if (!$first) { $newlist .= ","; @@ -813,9 +848,9 @@ sub setobjdefs } - if ( $val eq "") { # delete the line + if ($val eq "") { # delete the line $thistable->delEntries(\%keyhash); - } else { # change the attr + } else { # change the attr my %updates; $updates{value} = $val; @@ -825,9 +860,9 @@ sub setobjdefs if ($::verbose) { my $rsp; $rsp->{data}->[0] = - "Could not set the \'$attr\' attribute of the \'$objname\' object in the xCAT database."; +"Could not set the \'$attr\' attribute of the \'$objname\' object in the xCAT database."; $rsp->{data}->[1] = - "Error returned is \'$str->errstr\'."; + "Error returned is \'$str->errstr\'."; xCAT::MsgUtils->message("I", $rsp, $::callback); } $ret = 1; @@ -839,7 +874,7 @@ sub setobjdefs $thistable->commit; next; - } #if ($type eq 'site') + } #if ($type eq 'site') @@ -856,21 +891,23 @@ sub setobjdefs # get a list of valid attr names # for this type object my %attrlist; - foreach my $entry (@{$datatype->{'attrs'}}) { + foreach my $entry (@{ $datatype->{'attrs'} }) { + #push(@{$attrlist{$type}}, $entry->{'attr_name'}); - $attrlist{$type}{$entry->{'attr_name'}} = 1; + $attrlist{$type}{ $entry->{'attr_name'} } = 1; } - my @attrprovided=(); + my @attrprovided = (); # check FINALATTRS to see if all the attrs are valid - foreach my $attr (keys %{$objhash{$objname}}) { + foreach my $attr (keys %{ $objhash{$objname} }) { if ($attr eq $objkey) { next; } if ($attr eq "objtype") { + # objtype not stored in object definition next; } @@ -892,11 +929,11 @@ sub setobjdefs # store each attr # And we must do this in the order given in defspec!! - my @setattrlist=(); + my @setattrlist = (); my %checkedattrs; my $invalidattr; - foreach my $this_attr (@{$datatype->{'attrs'}}) { + foreach my $this_attr (@{ $datatype->{'attrs'} }) { my %keyhash; my %updates; my %tabentry; @@ -910,6 +947,7 @@ sub setobjdefs # if we have a value for this attribute then process it # - otherwise go to the next attr if (defined($objhash{$objname}{$attr_name})) { + # check the defspec to see where this attr goes # the table for this attr might depend on the @@ -933,25 +971,26 @@ sub setobjdefs # as well as the attrs for this object that may be # already set in DB - if ( !($objhash{$objname}{$check_attr}) && !($DBattrvals{$objname}{$check_attr}) ) { + if (!($objhash{$objname}{$check_attr}) && !($DBattrvals{$objname}{$check_attr})) { + # if I didn't already check for this attr my $rsp; if (!defined($checkedattrs{$attr_name})) { - push @{$rsp->{data}}, "Cannot set the \'$attr_name\' attribute unless a value is provided for \'$check_attr\'."; + push @{ $rsp->{data} }, "Cannot set the \'$attr_name\' attribute unless a value is provided for \'$check_attr\'."; - foreach my $tmp_attr (@{$datatype->{'attrs'}}) { + foreach my $tmp_attr (@{ $datatype->{'attrs'} }) { my $attr = $tmp_attr->{attr_name}; if ($attr eq $check_attr) { my ($tab, $at) = split(/\./, $tmp_attr->{tabentry}); my $schema = xCAT::Table->getTableSchema($tab); my $desc = $schema->{descriptions}->{$at}; - push @{$rsp->{data}}, "$check_attr => $desc"; + push @{ $rsp->{data} }, "$check_attr => $desc"; } } } xCAT::MsgUtils->message("I", $rsp, $::callback); $checkedattrs{$attr_name} = 1; - if ( $invalidattr->{$attr_name}->{valid} ne 1 ) { + if ($invalidattr->{$attr_name}->{valid} ne 1) { $invalidattr->{$attr_name}->{valid} = 0; $invalidattr->{$attr_name}->{condition} = "\'$check_attr=$check_value\'"; } @@ -959,8 +998,8 @@ sub setobjdefs next; } - if ( !($objhash{$objname}{$check_attr} =~ /\b$check_value\b/) && !($DBattrvals{$objname}{$check_attr} =~ /\b$check_value\b/) ) { - if ( $invalidattr->{$attr_name}->{valid} ne 1 ) { + if (!($objhash{$objname}{$check_attr} =~ /\b$check_value\b/) && !($DBattrvals{$objname}{$check_attr} =~ /\b$check_value\b/)) { + if ($invalidattr->{$attr_name}->{valid} ne 1) { $invalidattr->{$attr_name}->{valid} = 0; $invalidattr->{$attr_name}->{condition} = "\'$check_attr=$check_value\'"; @@ -979,20 +1018,21 @@ sub setobjdefs ($ntab, $::tabattr) = split('\.', $this_attr->{tabentry}); my $rc = xCAT::DBobjUtils->parse_access_tabentry($objname, - $this_attr->{access_tabentry}, \%tabentry); + $this_attr->{access_tabentry}, \%tabentry); if ($rc != 0) { my $rsp; $rsp->{data}->[0] = - "access_tabentry \'$this_attr->{access_tabentry}\' is not valid."; +"access_tabentry \'$this_attr->{access_tabentry}\' is not valid."; xCAT::MsgUtils->message("E", $rsp, $::callback); next; } $lookup_table = $tabentry{'lookup_table'}; + # Set the lookup criteria for this attribute into %allupdates # the key is 'lookup_attrs' - foreach my $lookup_attr (keys %{$tabentry{'lookup_attrs'}}) { + foreach my $lookup_attr (keys %{ $tabentry{'lookup_attrs'} }) { $allupdates{$lookup_table}{$objname}{$attr_name}{'lookup_attrs'}{$lookup_attr} - =$tabentry{'lookup_attrs'}{$lookup_attr}; + = $tabentry{'lookup_attrs'}{$lookup_attr}; } } else { next; @@ -1000,7 +1040,8 @@ sub setobjdefs my $val; my $delim = ','; - if(($type eq 'group') && ($DBattrvals{$objname}{'grouptype'} eq 'dynamic')) { + if (($type eq 'group') && ($DBattrvals{$objname}{'grouptype'} eq 'dynamic')) { + # dynamic node group selection string use "::" as delimiter $delim = '::'; } @@ -1009,6 +1050,7 @@ sub setobjdefs # add new to existing - at the end - comma separated if (defined($DBattrvals{$objname}{$attr_name})) { + # add the attr into the list if it's not already in the list! # and avoid the duplicate values my @DBattrarray = split(/$delim/, $DBattrvals{$objname}{$attr_name}); @@ -1035,7 +1077,7 @@ sub setobjdefs my @minusList = split(/$delim/, $objhash{$objname}{$attr_name}); foreach my $em (@minusList) { - if (!(grep {$_ eq $em} @currentList)) { + if (!(grep { $_ eq $em } @currentList)) { if (($::opt_t eq 'group') && ($DBattrvals{$objname}{'grouptype'} ne 'dynamic')) { my $rsp; $rsp->{data}->[0] = "$objname is not a member of \'$em\'."; @@ -1047,6 +1089,7 @@ sub setobjdefs } } } + # make a new list without the one specified my $first = 1; my $newlist; @@ -1075,7 +1118,7 @@ sub setobjdefs # Set the values into %allupdates # the key is 'tabattrs' $allupdates{$lookup_table}{$objname}{$attr_name}{'tabattrs'}{$::tabattr} = $val; - $setattrs=1; + $setattrs = 1; push(@setattrlist, $attr_name); @@ -1083,9 +1126,9 @@ sub setobjdefs my $rsp; foreach my $att (keys %$invalidattr) { - if ( $invalidattr->{$att}->{valid} ne 1) { -my $tt = $invalidattr->{$att}->{valid}; - push @{$rsp->{data}}, "Cannot set the attr=\'$att\' attribute unless $invalidattr->{$att}->{condition}."; + if ($invalidattr->{$att}->{valid} ne 1) { + my $tt = $invalidattr->{$att}->{valid}; + push @{ $rsp->{data} }, "Cannot set the attr=\'$att\' attribute unless $invalidattr->{$att}->{condition}."; xCAT::MsgUtils->message("E", $rsp, $::callback); } } @@ -1099,6 +1142,7 @@ my $tt = $invalidattr->{$att}->{valid}; my @errlist; foreach $a (@attrprovided) { + # is this attr was not set then add it to the error list if (!grep(/^$a$/, @setattrlist)) { push(@errlist, $a); @@ -1115,55 +1159,56 @@ my $tt = $invalidattr->{$att}->{valid}; } } # end - foreach object -#==========================================================# -#%allupdates structure: -# for command: chdef -t node -o node1 groups=all -# usercomment=ddee passwd.HMC=HMC -# passwd.admin=cluster passwd.general=abc123 -# the %allupdates will be: -#0 'ppcdirect' -#1 HASH(0x12783d30) -# 'node1' => HASH(0x12783cc4) -# 'passwd.HMC' => HASH(0x12783ed4) -# 'lookup_attrs' => HASH(0x12783f70) -# 'hcp' => 'node1' -# 'username' => 'HMC' -# 'tabattrs' => HASH(0x12783e8c) -# 'password' => 'HMC' -# 'passwd.admin' => HASH(0x12783c64) -# 'lookup_attrs' => HASH(0x12784000) -# 'hcp' => 'node1' -# 'username' => 'admin' -# 'tabattrs' => HASH(0x12783f64) -# 'password' => 'cluster' -# 'passwd.general' => HASH(0x12783a6c) -# 'lookup_attrs' => HASH(0x12784198) -# 'hcp' => 'node1' -# 'username' => 'general' -# 'tabattrs' => HASH(0x12783aa8) -# 'password' => 'abc123' -#2 'nodelist' -#3 HASH(0x127842b8) -# 'node1' => HASH(0x12784378) -# 'groups' => HASH(0x12784090) -# 'lookup_attrs' => HASH(0x127844bc) -# 'node' => 'node1' -# 'tabattrs' => HASH(0x1277fd34) -# 'groups' => 'all' -# 'usercomment' => HASH(0x12784318) -# 'lookup_attrs' => HASH(0x12780550) -# 'node' => 'node1' -# 'tabattrs' => HASH(0x127842f4) -# 'comments' => 'ddee' -#=================================================================# + + #==========================================================# + #%allupdates structure: + # for command: chdef -t node -o node1 groups=all + # usercomment=ddee passwd.HMC=HMC + # passwd.admin=cluster passwd.general=abc123 + # the %allupdates will be: + #0 'ppcdirect' + #1 HASH(0x12783d30) + # 'node1' => HASH(0x12783cc4) + # 'passwd.HMC' => HASH(0x12783ed4) + # 'lookup_attrs' => HASH(0x12783f70) + # 'hcp' => 'node1' + # 'username' => 'HMC' + # 'tabattrs' => HASH(0x12783e8c) + # 'password' => 'HMC' + # 'passwd.admin' => HASH(0x12783c64) + # 'lookup_attrs' => HASH(0x12784000) + # 'hcp' => 'node1' + # 'username' => 'admin' + # 'tabattrs' => HASH(0x12783f64) + # 'password' => 'cluster' + # 'passwd.general' => HASH(0x12783a6c) + # 'lookup_attrs' => HASH(0x12784198) + # 'hcp' => 'node1' + # 'username' => 'general' + # 'tabattrs' => HASH(0x12783aa8) + # 'password' => 'abc123' + #2 'nodelist' + #3 HASH(0x127842b8) + # 'node1' => HASH(0x12784378) + # 'groups' => HASH(0x12784090) + # 'lookup_attrs' => HASH(0x127844bc) + # 'node' => 'node1' + # 'tabattrs' => HASH(0x1277fd34) + # 'groups' => 'all' + # 'usercomment' => HASH(0x12784318) + # 'lookup_attrs' => HASH(0x12780550) + # 'node' => 'node1' + # 'tabattrs' => HASH(0x127842f4) + # 'comments' => 'ddee' + #=================================================================# # now set the attribute values in the tables # - handles all except site, monitoring & monsetting for now if ($setattrs) { foreach my $table (keys %allupdates) { - # get the keys for this table + # get the keys for this table my $schema = xCAT::Table->getTableSchema($table); - my $keys = $schema->{keys}; + my $keys = $schema->{keys}; # open the table my $thistable = xCAT::Table->new($table, -create => 1, -autocommit => 0); @@ -1186,23 +1231,24 @@ my $tt = $invalidattr->{$att}->{valid}; my @TableRowArray = xCAT::DBobjUtils->getDBtable('postscripts'); if (@TableRowArray) { foreach my $tablerow (@TableRowArray) { - if(($tablerow->{node} eq 'xcatdefaults') && !($tablerow->{disable})) { - $xcatdefaultsps = $tablerow->{postscripts}; + if (($tablerow->{node} eq 'xcatdefaults') && !($tablerow->{disable})) { + $xcatdefaultsps = $tablerow->{postscripts}; $xcatdefaultspbs = $tablerow->{postbootscripts}; last; } } } - my @xcatdefps = split(/,/, $xcatdefaultsps); + my @xcatdefps = split(/,/, $xcatdefaultsps); my @xcatdefpbs = split(/,/, $xcatdefaultspbs); - foreach my $obj(keys %{$allupdates{$table}}) { + foreach my $obj (keys %{ $allupdates{$table} }) { if ($obj eq 'xcatdefaults') { + #xcatdefaults can be treated as a node? next; } my @newps; if (defined($allupdates{$table}{$obj}{'postscripts'}) - && defined($allupdates{$table}{$obj}{'postscripts'}{'tabattrs'}{'postscripts'})) { + && defined($allupdates{$table}{$obj}{'postscripts'}{'tabattrs'}{'postscripts'})) { foreach my $tempps (split(/,/, $allupdates{$table}{$obj}{'postscripts'}{'tabattrs'}{'postscripts'})) { if (grep(/^$tempps$/, @xcatdefps)) { my $rsp; @@ -1216,7 +1262,7 @@ my $tt = $invalidattr->{$att}->{valid}; } my @newpbs; if (defined($allupdates{$table}{$obj}{'postbootscripts'}) - && defined($allupdates{$table}{$obj}{'postbootscripts'}{'tabattrs'}{'postbootscripts'})) { + && defined($allupdates{$table}{$obj}{'postbootscripts'}{'tabattrs'}{'postbootscripts'})) { foreach my $temppbs (split(/,/, $allupdates{$table}{$obj}{'postbootscripts'}{'tabattrs'}{'postbootscripts'})) { if (grep(/^$temppbs$/, @xcatdefpbs)) { my $rsp; @@ -1233,11 +1279,12 @@ my $tt = $invalidattr->{$att}->{valid}; my $commit_manually = 0; my %node_updates; - OBJ: foreach my $obj (keys %{$allupdates{$table}}) { + OBJ: foreach my $obj (keys %{ $allupdates{$table} }) { my %keyhash; my %updates; my $firsttime = 1; - ROW: foreach my $row (keys %{$allupdates{$table}{$obj}}) { + ROW: foreach my $row (keys %{ $allupdates{$table}{$obj} }) { + # make sure we have a value for each key foreach my $k (@$keys) { if (!$allupdates{$table}{$obj}{$row}{'lookup_attrs'}) { @@ -1250,26 +1297,30 @@ my $tt = $invalidattr->{$att}->{valid}; } if ($firsttime) { + # lookup keys in %hashkey # ex. $keyhash{'hcp'} = node1 - foreach my $key (keys %{$allupdates{$table}{$obj}{$row}{'lookup_attrs'}}) { + foreach my $key (keys %{ $allupdates{$table}{$obj}{$row}{'lookup_attrs'} }) { $keyhash{$key} = $allupdates{$table}{$obj}{$row}{'lookup_attrs'}{$key}; } $firsttime = 0; } else { + # check if the look_attrs is the same as the %keyhash - foreach my $key (keys %{$allupdates{$table}{$obj}{$row}{'lookup_attrs'}}) { + foreach my $key (keys %{ $allupdates{$table}{$obj}{$row}{'lookup_attrs'} }) { + # The lookup_attrs can be different for tables with more than one keys such as ppcdirect - if ((scalar(keys %keyhash) != scalar(keys %{$allupdates{$table}{$obj}{$row}{'lookup_attrs'}})) - || !defined($keyhash{$key}) - ||($keyhash{$key} ne $allupdates{$table}{$obj}{$row}{'lookup_attrs'}{$key})) { + if ((scalar(keys %keyhash) != scalar(keys %{ $allupdates{$table}{$obj}{$row}{'lookup_attrs'} })) + || !defined($keyhash{$key}) + || ($keyhash{$key} ne $allupdates{$table}{$obj}{$row}{'lookup_attrs'}{$key})) { + # different keys, set the existing attributes into database # update the %keyhash and clean up the %updates hash if (%updates) { $commit_manually = 1; my ($rc, $str) = $thistable->setAttribs(\%keyhash, \%updates); } - foreach my $key (keys %{$allupdates{$table}{$obj}{$row}{'lookup_attrs'}}) { + foreach my $key (keys %{ $allupdates{$table}{$obj}{$row}{'lookup_attrs'} }) { $keyhash{$key} = $allupdates{$table}{$obj}{$row}{'lookup_attrs'}{$key}; } %updates = (); @@ -1279,7 +1330,7 @@ my $tt = $invalidattr->{$att}->{valid}; # set values in %updates # ex. $updates{'groups'} = 'all,lpar' - foreach my $attr (keys %{$allupdates{$table}{$obj}{$row}{'tabattrs'}}) { + foreach my $attr (keys %{ $allupdates{$table}{$obj}{$row}{'tabattrs'} }) { if (scalar(keys %keyhash) == 0 && $keyhash{'node'} && $keyhash{'node'} eq "node") { $node_updates{$obj}{$attr} = $allupdates{$table}{$obj}{$row}{'tabattrs'}{$attr}; } else { @@ -1287,20 +1338,20 @@ my $tt = $invalidattr->{$att}->{valid}; } } - } #end foreach my $row - # only uses the setAttribs to set attribute one by one when the obj type is NOT 'node' + } #end foreach my $row + # only uses the setAttribs to set attribute one by one when the obj type is NOT 'node' if (%updates) { $commit_manually = 1; my ($rc, $str) = $thistable->setAttribs(\%keyhash, \%updates); } - } #end foreach my $obj + } #end foreach my $obj if ($commit_manually) { $thistable->commit; } if (%node_updates) { $thistable->setNodesAttribs(\%node_updates); } - } #end forach my $table + } #end forach my $table } return $ret; } @@ -1349,7 +1400,7 @@ sub rmobjdefs my $thistable = xCAT::Table->new('site', -create => 1, -autocommit => 0); my %keyhash; - foreach my $attr (keys %{$DBattrvals{$objname}}) { + foreach my $attr (keys %{ $DBattrvals{$objname} }) { # ex. key = attr $keyhash{key} = $attr; @@ -1367,7 +1418,7 @@ sub rmobjdefs # go through the list of valid attrs # - need to delete the row with a $key value of $objname from $table # - make a hash containing $delhash{$table}{$key}= $objname - foreach my $this_attr (@{$datatype->{'attrs'}}) { + foreach my $this_attr (@{ $datatype->{'attrs'} }) { my $attr = $this_attr->{attr_name}; # get table lookup info from Schema.pm @@ -1378,7 +1429,7 @@ sub rmobjdefs if ($rc != 0) { my $rsp; $rsp->{data}->[0] = - "access_tabentry \'$this_attr->{access_tabentry}\' is not valid."; +"access_tabentry \'$this_attr->{access_tabentry}\' is not valid."; xCAT::MsgUtils->message("E", $rsp, $::callback); next; } @@ -1386,64 +1437,67 @@ sub rmobjdefs # Only allow one table in the access_tabentry # use multiple tables to look up tabentry does not make any sense my $lookup_table = $tabentry{'lookup_table'}; + # The attr_name is the *def attribute name instead of db column my $attr_name = $this_attr->{'attr_name'}; + # we'll need table name, object name, attribute name and the lookup entries # put this info in a hash - we'll process it later - below - foreach my $lookup_attr (keys %{$tabentry{'lookup_attrs'}}) { + foreach my $lookup_attr (keys %{ $tabentry{'lookup_attrs'} }) { $tablehash{$lookup_table}{$objname}{$attr_name}{$lookup_attr} - = $tabentry{'lookup_attrs'}{$lookup_attr}; + = $tabentry{'lookup_attrs'}{$lookup_attr}; } } } -#=============================================# -# The tablehash looks like this - # DB<5> x %tablehash - # 'bootparams' - # HASH(0x1280828c) - # 'node1' => HASH(0x127bca50) - # 'addkcmdline' => HASH(0x127fb114) - # 'node' => 'node1' - # 'initrd' => HASH(0x127bcb40) - # 'node' => 'node1' - # 'kcmdline' => HASH(0x127fb24c) - # 'node' => 'node1' - # 'kernel' => HASH(0x127b2e80) - # 'node' => 'node1' - # 'testfsp' => HASH(0x1280e71c) - # 'addkcmdline' => HASH(0x1280e7a0) - # 'node' => 'testfsp' - # 'initrd' => HASH(0x1280e740) - # 'node' => 'testfsp' - # 'kcmdline' => HASH(0x1280e77c) - # 'node' => 'testfsp' - # 'kernel' => HASH(0x1280e758) - # 'node' => 'testfsp' - #... - # 'ppcdirect' - # HASH(0x1278fe1c) - # 'node1' => HASH(0x12808370) - # 'passwd.HMC' => HASH(0x128083e8) - # 'hcp' => 'node1' - # 'username' => 'HMC' - # 'passwd.admin' => HASH(0x128081c0) - # 'hcp' => 'node1' - # 'username' => 'admin' - # 'passwd.general' => HASH(0x128075d8) - # 'hcp' => 'node1' - # 'username' => 'general' - # 'testfsp' => HASH(0x12790620) - # 'passwd.HMC' => HASH(0x1280ee84) - # 'hcp' => 'testfsp' - # 'username' => 'HMC' - # 'passwd.admin' => HASH(0x128082f8) - # 'hcp' => 'testfsp' - # 'username' => 'admin' - # 'passwd.general' => HASH(0x1280843c) - # 'hcp' => 'testfsp' - # 'username' => 'general' - #... + + #=============================================# + # The tablehash looks like this + # DB<5> x %tablehash + # 'bootparams' + # HASH(0x1280828c) + # 'node1' => HASH(0x127bca50) + # 'addkcmdline' => HASH(0x127fb114) + # 'node' => 'node1' + # 'initrd' => HASH(0x127bcb40) + # 'node' => 'node1' + # 'kcmdline' => HASH(0x127fb24c) + # 'node' => 'node1' + # 'kernel' => HASH(0x127b2e80) + # 'node' => 'node1' + # 'testfsp' => HASH(0x1280e71c) + # 'addkcmdline' => HASH(0x1280e7a0) + # 'node' => 'testfsp' + # 'initrd' => HASH(0x1280e740) + # 'node' => 'testfsp' + # 'kcmdline' => HASH(0x1280e77c) + # 'node' => 'testfsp' + # 'kernel' => HASH(0x1280e758) + # 'node' => 'testfsp' + #... + # 'ppcdirect' + # HASH(0x1278fe1c) + # 'node1' => HASH(0x12808370) + # 'passwd.HMC' => HASH(0x128083e8) + # 'hcp' => 'node1' + # 'username' => 'HMC' + # 'passwd.admin' => HASH(0x128081c0) + # 'hcp' => 'node1' + # 'username' => 'admin' + # 'passwd.general' => HASH(0x128075d8) + # 'hcp' => 'node1' + # 'username' => 'general' + # 'testfsp' => HASH(0x12790620) + # 'passwd.HMC' => HASH(0x1280ee84) + # 'hcp' => 'testfsp' + # 'username' => 'HMC' + # 'passwd.admin' => HASH(0x128082f8) + # 'hcp' => 'testfsp' + # 'username' => 'admin' + # 'passwd.general' => HASH(0x1280843c) + # 'hcp' => 'testfsp' + # 'username' => 'general' + #... ##=========================================================# # now for each table - clear the entry foreach my $table (keys %tablehash) { @@ -1452,27 +1506,31 @@ sub rmobjdefs my $thistable = xCAT::Table->new($table, -create => 1, -autocommit => 0); - foreach my $obj (keys %{$tablehash{$table}}) { + foreach my $obj (keys %{ $tablehash{$table} }) { my %keyhash; - foreach my $attr (keys %{$tablehash{$table}{$obj}}) { - foreach my $key (keys %{$tablehash{$table}{$obj}{$attr}}) { + foreach my $attr (keys %{ $tablehash{$table}{$obj} }) { + foreach my $key (keys %{ $tablehash{$table}{$obj}{$attr} }) { #multiple keys support if (defined($keyhash{$key}) && ($keyhash{$key} ne $tablehash{$table}{$obj}{$attr}{$key})) { my %tmpkeyhash; + # copy hash foreach my $hashkey (keys %keyhash) { $tmpkeyhash{$hashkey} = $keyhash{$hashkey}; } push @all_keyhash, \%tmpkeyhash; + #$thistable->delEntries(\@all_keyhash); } + # ex. $keyhash{node}=c68m3hvp01 $keyhash{$key} = $tablehash{$table}{$obj}{$attr}{$key}; } } push @all_keyhash, \%keyhash; } + # ex. delete the c68m3hvp01 entry of the node column in the # nodelist table $thistable->delEntries(\@all_keyhash); @@ -1578,8 +1636,8 @@ sub readFileInput my $val = $2; $attr =~ s/^\s*//; # Remove any leading whitespace $attr =~ s/\s*$//; # Remove any trailing whitespace - $val =~ s/^\s*//; - $val =~ s/\s*$//; + $val =~ s/^\s*//; + $val =~ s/\s*$//; # remove spaces and quotes so createnode won't get upset $val =~ s/^\s*"\s*//; @@ -1604,7 +1662,7 @@ sub readFileInput push(@::fileobjtypes, $val); # $val will be the object type ex. site, node etc. - foreach my $a (keys %{$::defAttrs{$val}}) { + foreach my $a (keys %{ $::defAttrs{$val} }) { # set the default values for this object hash $::FILEATTRS{$objectname}{$a} = $::defAttrs{$val}{$a}; @@ -1662,7 +1720,7 @@ sub getGroupMembers # set 'static' as the dafault of nodetype if (!defined($objhash{$objectname}{'grouptype'}) || - $objhash{$objectname}{'grouptype'} eq "") { + $objhash{$objectname}{'grouptype'} eq "") { $objhash{$objectname}{'grouptype'} = 'static'; } @@ -1769,21 +1827,21 @@ sub getGroupMembers sub getNetwkInfo { my ($class, $ref_nodes) = @_; - my @nodelist = @$ref_nodes; + my @nodelist = @$ref_nodes; my %nethash; my @attrnames; # get the current list of network attrs (networks table columns) my $datatype = $xCAT::Schema::defspec{'network'}; - foreach my $a (@{$datatype->{'attrs'}}) { + foreach my $a (@{ $datatype->{'attrs'} }) { my $attr = $a->{attr_name}; push(@attrnames, $attr); } # read the networks table my @TableRowArray = xCAT::DBobjUtils->getDBtable('networks'); - if (! @TableRowArray) { + if (!@TableRowArray) { return undef; } @@ -1802,34 +1860,38 @@ sub getNetwkInfo # - if the bitwise AND of the IP and the netmask gives you # the "net" name then that is the entry you want. foreach (@TableRowArray) { - my $NM = $_->{'mask'}; - my $net=$_->{'net'}; + my $NM = $_->{'mask'}; + my $net = $_->{'net'}; chomp $NM; chomp $net; - if(xCAT::NetworkUtils->ishostinsubnet($IP, $NM, $net)) { + if (xCAT::NetworkUtils->ishostinsubnet($IP, $NM, $net)) { + # fill in the hash - foreach my $attr (@attrnames) { - if ( defined($_->{$attr}) ) { + if (defined($_->{$attr})) { $nethash{$node}{$attr} = $_->{$attr}; } } - if($nethash{$node}{'gateway'} eq '') { - if(xCAT::NetworkUtils->ip_forwarding_enabled()) { + if ($nethash{$node}{'gateway'} eq '') { + if (xCAT::NetworkUtils->ip_forwarding_enabled()) { $nethash{$node}{'gateway'} = xCAT::NetworkUtils->my_ip_in_subnet($net, $NM); } else { $nethash{$node}{'gateway'} = ''; } $nethash{$node}{'myselfgw'} = 1; + # For hwctrl commands, it is possible that this subroutine is called # on MN instead of SN, if the hcp SN is not set if (xCAT::Utils->isMN() && !$nethash{$node}{'gateway'}) { + # does not have ip address in this subnet, # use the node attribute 'xcatmaster' or site.master my @nodes = ("$node"); - my $sn = xCAT::ServiceNodeUtils->get_ServiceNode(\@nodes,"xcat","Node"); + my $sn = xCAT::ServiceNodeUtils->get_ServiceNode(\@nodes, "xcat", "Node"); my $snkey = (keys %{$sn})[0]; - my $gw = xCAT::NetworkUtils->getipaddr($snkey); + my $gw = xCAT::NetworkUtils->getipaddr($snkey); + # two possible cases when this code is run: # 1. flat cluster: ip forwarding is not enabled on MN # 2. hw ctrl in hierarchy cluster, in which HCP SN is not set @@ -1845,10 +1907,11 @@ sub getNetwkInfo } - } #end - for each node + } #end - for each node return %nethash; } + #---------------------------------------------------------------------------- =head3 parse_access_tabentry @@ -1891,6 +1954,7 @@ sub parse_access_tabentry() # ex. 'nodelist.node', 'attr:node' foreach my $ent (split('::', $access_tabentry)) { + # ex. 'nodelist.node', 'attr:node' my ($lookup_key, $lookup_value) = split('\=', $ent); @@ -1910,12 +1974,13 @@ sub parse_access_tabentry() if ($lookup_table ne $tabentry_ref->{'lookup_table'}) { my $rsp; $rsp->{data}->[0] = - "The access_tabentry \"$access_tabentry\" is not valid, can not specify more than one tables to look up."; +"The access_tabentry \"$access_tabentry\" is not valid, can not specify more than one tables to look up."; xCAT::MsgUtils->message("E", $rsp, $::callback); return 1; } if ($lookup_type eq 'attr') { + # TODO: may need to update in the future # for now, the "val" in attr:val in # Schema.pm can only be the object name @@ -1928,13 +1993,14 @@ sub parse_access_tabentry() } else { my $rsp; $rsp->{data}->[0] = - "The access_tabentry \"$access_tabentry\" is not valid, the lookup type can only be 'attr' or 'str'."; +"The access_tabentry \"$access_tabentry\" is not valid, the lookup type can only be 'attr' or 'str'."; xCAT::MsgUtils->message("E", $rsp, $::callback); return 1; } } return 0; } + #------------------------------------------------------------------------------- =head3 getchildren @@ -1960,6 +2026,7 @@ sub parse_access_tabentry() #------------------------------------------------------------------------------- my %PPCHASH; + sub getchildren { my $parent = shift; @@ -1967,65 +2034,69 @@ sub getchildren $parent = shift; } $::RUNCMD_RC = 0; - my $port = shift; - my @tabletype = qw(ppc zvm); - my @children = (); + my $port = shift; + my @tabletype = qw(ppc zvm); + my @children = (); my @children_port = (); if (!%PPCHASH) { - my $ppctab = xCAT::Table->new( 'ppc' ); - unless ($ppctab) { # cannot open the table return with error + my $ppctab = xCAT::Table->new('ppc'); + unless ($ppctab) { # cannot open the table return with error xCAT::MsgUtils->message('S', "getchildren:Unable to open ppc table.\n"); $::RUNCMD_RC = 1; return undef; } - my @ps = $ppctab->getAllNodeAttribs(['node','parent','nodetype','hcp']); - foreach my $entry ( @ps ) { + my @ps = $ppctab->getAllNodeAttribs([ 'node', 'parent', 'nodetype', 'hcp' ]); + foreach my $entry (@ps) { my $p = $entry->{parent}; my $c = $entry->{node}; my $t = $entry->{nodetype}; - if ( $p and $c) { - if ($t) { # the nodetype exists in the ppc table, use it - if ( $t eq 'fsp' or $t eq 'bpa') { + if ($p and $c) { + if ($t) { # the nodetype exists in the ppc table, use it + if ($t eq 'fsp' or $t eq 'bpa') { + # build hash of ppc.parent -> ppc.node - push @{$PPCHASH{$p}}, $c; + push @{ $PPCHASH{$p} }, $c; } elsif ($t eq 'blade') { - push @{$PPCHASH{$c}}, $entry->{hcp}; + push @{ $PPCHASH{$c} }, $entry->{hcp}; } - } else { # go look in the nodetype table to find nodetype + } else { # go look in the nodetype table to find nodetype my $type = getnodetype($c, "ppc"); - if ( $type eq 'fsp' or $type eq 'bpa') { + if ($type eq 'fsp' or $type eq 'bpa') { + # build hash of ppc.parent -> ppc.node - push @{$PPCHASH{$p}}, $c; + push @{ $PPCHASH{$p} }, $c; } elsif ($type eq "blade") { - push @{$PPCHASH{$c}}, $entry->{hcp}; + push @{ $PPCHASH{$c} }, $entry->{hcp}; } } - } # not $p and $c + } # not $p and $c } + # Find parent in the hash and build return values - foreach (@{$PPCHASH{$parent}}) { + foreach (@{ $PPCHASH{$parent} }) { push @children, $_; } } else { if (exists($PPCHASH{$parent})) { - foreach (@{$PPCHASH{$parent}}) { + foreach (@{ $PPCHASH{$parent} }) { push @children, $_; } } } + # if port not input - if ( !defined($port )) { + if (!defined($port)) { return \@children; } else { if (@children) { - my $vpdtab = xCAT::Table->new( 'vpd' ); - unless ($vpdtab) { # cannot open the table return with error + my $vpdtab = xCAT::Table->new('vpd'); + unless ($vpdtab) { # cannot open the table return with error xCAT::MsgUtils->message('S', "getchildren:Unable to open vpd table.\n"); $::RUNCMD_RC = 1; return undef; } my $sides = $vpdtab->getNodesAttribs(\@children, ['side']); - if(!$sides) { + if (!$sides) { return undef; } foreach my $n (@children) { @@ -2035,11 +2106,12 @@ sub getchildren } } return \@children_port; - } else { # no children + } else { # no children return undef; } } } + #------------------------------------------------------------------------------- =head3 getnodetype @@ -2067,6 +2139,7 @@ sub getchildren #------------------------------------------------------------------------------- my %NODETYPEHASH; + sub getnodetype { my $nodes = shift; @@ -2087,11 +2160,11 @@ sub getnodetype # if can't get anything from the specified table, go to nodetype table ###################################################################### if ($table) { - my $nodetypetab = xCAT::Table->new( $table ); + my $nodetypetab = xCAT::Table->new($table); unless ($nodetypetab) { xCAT::MsgUtils->message('S', "getnodetype:Unable to open $table table.\n"); $::RUNCMD_RC = 1; - if ( $nodes =~ /^ARRAY/) { + if ($nodes =~ /^ARRAY/) { foreach my $tn (@$nodes) { $typehash{$tn} = undef; } @@ -2104,13 +2177,13 @@ sub getnodetype # if the input node arg is an array, # query table and don't use the global hash ############################################ - if ( $nodes =~ /^ARRAY/) { + if ($nodes =~ /^ARRAY/) { my $nodetypes = $nodetypetab->getNodesAttribs($nodes, ['nodetype']); foreach my $tn (@$nodes) { my $gottype = $nodetypes->{$tn}->[0]->{'nodetype'}; - if ( $gottype ) { + if ($gottype) { $NODETYPEHASH{$tn} = $gottype; - $typehash{$tn} = $gottype; + $typehash{$tn} = $gottype; } else { push @failnodes, $tn; } @@ -2118,9 +2191,9 @@ sub getnodetype ################################################ # for the failed nodes, go to nodetype table ################################################ - if ( @failnodes ) { - my $typetable = xCAT::Table->new( 'nodetype' ); - unless ($typetable) { # cannot open the table return with error + if (@failnodes) { + my $typetable = xCAT::Table->new('nodetype'); + unless ($typetable) { # cannot open the table return with error xCAT::MsgUtils->message('S', "getnodetype:Unable to open nodetype table.\n"); $::RUNCMD_RC = 1; foreach my $tn (@failnodes) { @@ -2128,8 +2201,8 @@ sub getnodetype } } else { my $nodetypes = $nodetypetab->getNodesAttribs(\@failnodes, ['nodetype']); - foreach my $tn ( @failnodes ) { - if ( $nodetypes->{$tn}->[0] ) { + foreach my $tn (@failnodes) { + if ($nodetypes->{$tn}->[0]) { $NODETYPEHASH{$tn} = $nodetypes->{$tn}->[0]->{'nodetype'}; $typehash{$tn} = $nodetypes->{$tn}->[0]->{'nodetype'}; } else { @@ -2140,8 +2213,8 @@ sub getnodetype # give error msg for the nodes can't get nodetype ################################################## } - if ( @failnodes1 ) { - my $nodelist = join(",", @failnodes1); + if (@failnodes1) { + my $nodelist = join(",", @failnodes1); xCAT::MsgUtils->message('S', "getnodetype:Can't find these nodes' type: $nodelist.\n"); } } @@ -2152,28 +2225,28 @@ sub getnodetype return \%typehash; } else { - ############################################ - # if the input node arg is not an array, - # query table and use the global hash first - ############################################ - if ( $NODETYPEHASH{$nodes} ) { + ############################################ + # if the input node arg is not an array, + # query table and use the global hash first + ############################################ + if ($NODETYPEHASH{$nodes}) { return $NODETYPEHASH{$nodes}; } else { my $typep = $nodetypetab->getNodeAttribs($nodes, ['nodetype']); - if ( $typep->{nodetype} ) { + if ($typep->{nodetype}) { $NODETYPEHASH{$nodes} = $typep->{nodetype}; return $typep->{nodetype}; } else { #if not find in the specified table, go to nodetype table - my $typetable = xCAT::Table->new( 'nodetype' ); - unless ($typetable) { # cannot open the table return with error + my $typetable = xCAT::Table->new('nodetype'); + unless ($typetable) { # cannot open the table return with error xCAT::MsgUtils->message('S', "getnodetype:Unable to open nodetype table.\n"); $::RUNCMD_RC = 1; return undef; } - my $typep = $typetable->getNodeAttribs($nodes, ['nodetype']); - if ( $typep->{nodetype} ) { + my $typep = $typetable->getNodeAttribs($nodes, ['nodetype']); + if ($typep->{nodetype}) { $NODETYPEHASH{$nodes} = $typep->{nodetype}; - return $typep->{nodetype}; + return $typep->{nodetype}; } else { return undef; } @@ -2181,15 +2254,15 @@ sub getnodetype } } } else { - ###################################################################### - # if the table arg is not set, go to the nodetype table first - # if can't get anything from the specified table, go to nodetype table - ###################################################################### - my $nodetypetab = xCAT::Table->new( 'nodetype' ); + ###################################################################### + # if the table arg is not set, go to the nodetype table first + # if can't get anything from the specified table, go to nodetype table + ###################################################################### + my $nodetypetab = xCAT::Table->new('nodetype'); unless ($nodetypetab) { xCAT::MsgUtils->message('S', "getnodetype:Unable to open $table table.\n"); $::RUNCMD_RC = 1; - if ( $nodes =~ /^ARRAY/) { + if ($nodes =~ /^ARRAY/) { foreach my $tn (@$nodes) { $typehash{$tn} = undef; } @@ -2202,33 +2275,33 @@ sub getnodetype # if the input node arg is an array, # query table and don't use the global hash ############################################ - if ( $nodes =~ /^ARRAY/) { + if ($nodes =~ /^ARRAY/) { my $nodetypes = $nodetypetab->getNodesAttribs($nodes, ['nodetype']); foreach my $tn (@$nodes) { my $gottype = $nodetypes->{$tn}->[0]->{'nodetype'}; - if ( $gottype) { - if ($gottype =~ /,/) { #if find ppc,osi + if ($gottype) { + if ($gottype =~ /,/) { #if find ppc,osi my @tbty = split /,/, $gottype; - foreach my $ttable (@tbty){ - if (grep(/$ttable/, @tabletype)){ - $tablehash{ $tn } = $ttable; - last; + foreach my $ttable (@tbty) { + if (grep(/$ttable/, @tabletype)) { + $tablehash{$tn} = $ttable; + last; } } - } elsif (grep(/$gottype/, @tabletype)){ #if find ppc or zvm - $tablehash{ $tn } = $gottype; + } elsif (grep(/$gottype/, @tabletype)) { #if find ppc or zvm + $tablehash{$tn} = $gottype; } else { - $NODETYPEHASH{ $tn } = $gottype; - $typehash{ $tn } = $gottype; + $NODETYPEHASH{$tn} = $gottype; + $typehash{$tn} = $gottype; } } else { - $typehash{ $tn } = undef; + $typehash{$tn} = undef; } } ################################################ # for the failed nodes, go to related tables ################################################ - if ( %tablehash ) { + if (%tablehash) { foreach my $ttable (@tabletype) { my @nodegroup; foreach my $fnode (keys %tablehash) { @@ -2237,7 +2310,7 @@ sub getnodetype } } next unless (@nodegroup); - my $typetable = xCAT::Table->new( $ttable); + my $typetable = xCAT::Table->new($ttable); unless ($typetable) { my $failnodes = join(",", @nodegroup); xCAT::MsgUtils->message('S', "getnodetype:Unable to open $ttable table, can't find $failnodes type.\n"); @@ -2246,9 +2319,9 @@ sub getnodetype $typehash{$_} = undef; } } else { - my $typep = $typetable->getNodesAttribs(\@nodegroup, ['nodetype']); + my $typep = $typetable->getNodesAttribs(\@nodegroup, ['nodetype']); foreach my $fn (@nodegroup) { - if ( $typep->{$fn}->[0]->{'nodetype'} ) { + if ($typep->{$fn}->[0]->{'nodetype'}) { $typehash{$fn} = $typep->{$fn}->[0]->{'nodetype'}; $NODETYPEHASH{$fn} = $typep->{$fn}->[0]->{'nodetype'}; } else { @@ -2259,23 +2332,23 @@ sub getnodetype } } return \%typehash; - } else { # if not an array - if ( $NODETYPEHASH{$nodes} ) { + } else { # if not an array + if ($NODETYPEHASH{$nodes}) { return $NODETYPEHASH{$nodes}; } else { my $typep = $nodetypetab->getNodeAttribs($nodes, ["nodetype"]); - if ( $typep->{nodetype} and !(grep(/$typep->{nodetype}/, @tabletype))) { + if ($typep->{nodetype} and !(grep(/$typep->{nodetype}/, @tabletype))) { $NODETYPEHASH{$nodes} = $typep->{nodetype}; return $typep->{nodetype}; - } elsif ( grep(/$typep->{nodetype}/, @tabletype) ) { - my $typetable = xCAT::Table->new( $typep->{nodetype} ); + } elsif (grep(/$typep->{nodetype}/, @tabletype)) { + my $typetable = xCAT::Table->new($typep->{nodetype}); unless ($typetable) { xCAT::MsgUtils->message('S', "getnodetype:Unable to open nodetype table.\n"); $::RUNCMD_RC = 1; return undef; } my $typep = $typetable->getNodeAttribs($nodes, ["nodetype"]); - if ( $typep->{nodetype} ) { + if ($typep->{nodetype}) { $NODETYPEHASH{$nodes} = $typep->{nodetype}; return $typep->{nodetype}; } else { @@ -2286,6 +2359,7 @@ sub getnodetype } } } + #------------------------------------------------------------------------------- =head3 getcecchildren @@ -2306,6 +2380,7 @@ sub getnodetype #------------------------------------------------------------------------------- my %PARENT_CHILDREN_CEC; + sub getcecchildren { my $parent = shift; @@ -2314,41 +2389,43 @@ sub getcecchildren } my @children = (); if (!%PARENT_CHILDREN_CEC) { - my $ppctab = xCAT::Table->new( 'ppc' ); - unless ($ppctab) { # cannot open the table return with error + my $ppctab = xCAT::Table->new('ppc'); + unless ($ppctab) { # cannot open the table return with error xCAT::MsgUtils->message('S', "getcecchildren:Unable to open ppc table.\n"); $::RUNCMD_RC = 1; return undef; } if ($ppctab) { - my @ps = $ppctab->getAllNodeAttribs(['node','parent','nodetype']); - foreach my $entry ( @ps ) { + my @ps = $ppctab->getAllNodeAttribs([ 'node', 'parent', 'nodetype' ]); + foreach my $entry (@ps) { my $p = $entry->{parent}; my $c = $entry->{node}; my $t = $entry->{nodetype}; - if ( $p and $c) { - if ($t) { # the nodetype exists in the ppc table, use it - if ( $t eq 'cec') { + if ($p and $c) { + if ($t) { # the nodetype exists in the ppc table, use it + if ($t eq 'cec') { + # build hash of ppc.parent -> ppc.node - push @{$PARENT_CHILDREN_CEC{$p}}, $c; + push @{ $PARENT_CHILDREN_CEC{$p} }, $c; } - } else { # go look in the nodetype table to find nodetype + } else { # go look in the nodetype table to find nodetype my $type = getnodetype($c); - if ( $type eq 'cec') { - push @{$PARENT_CHILDREN_CEC{$p}}, $c; + if ($type eq 'cec') { + push @{ $PARENT_CHILDREN_CEC{$p} }, $c; } } } } + # find a match for the parent and build the return array - foreach (@{$PARENT_CHILDREN_CEC{$parent}}) { + foreach (@{ $PARENT_CHILDREN_CEC{$parent} }) { push @children, $_; } return \@children; } - } else { # already built the HASH + } else { # already built the HASH if (exists($PARENT_CHILDREN_CEC{$parent})) { - foreach (@{$PARENT_CHILDREN_CEC{$parent}}) { + foreach (@{ $PARENT_CHILDREN_CEC{$parent} }) { push @children, $_; } return \@children; @@ -2356,6 +2433,7 @@ sub getcecchildren } return undef; } + #------------------------------------------------------------------------------- =head3 judge_node @@ -2385,8 +2463,8 @@ sub judge_node my $flag = 0; my $parenttype; my $nodeparent; - my $ppctab = xCAT::Table->new( 'ppc' ); - if ( $ppctab ) { + my $ppctab = xCAT::Table->new('ppc'); + if ($ppctab) { $nodeparent = $ppctab->getNodeAttribs($node, ["parent"]); if ($nodeparent and $nodeparent->{parent}) { $parenttype = getnodetype($nodeparent->{parent}); @@ -2456,13 +2534,31 @@ sub expandnicsattr() my $nicattr = $1; # Value: eth0!1.1.1.1|2.1.1.1,eth1!3.1.1.1|4.1.1.1 - my $nicval=$2; + my $nicval = $2; + + #if there is regrex in nicips + if (($nicval) && ($nicval =~ /^\|(.*?)\|$/)) { + + #$nicval Value: |node(d+)|eth0!192.1.1.($1+10)| or + # |eth0!192.1.1.($1+10),bond0!10.28.41.($1+10)| + #In the lsdef, remove the ^| and |$ before displaying + $nicval =~ s/(^\||\|$)//g; + + #$nicval Value: node(d+)|eth0!192.1.1.($1+10) + if (($nicval) && ($nicval =~ /\|/)) { + my ($str1, $str2) = split('\|', $nicval); + + #$nivval Value: eth0!192.1.1.($1+10) + $nicval = $str2; + } + } # $nicarr[0]: eth0!1.1.1.1|2.1.1.1 # $nicarr[1]: eth1!3.1.1.1|4.1.1.1 my @nicarr = split(/,/, $nicval); foreach my $nicentry (@nicarr) { + #nicentry: eth0!1.1.1.1|2.1.1.1 # $nicv[0]: eth0 # $nicv[1]: 1.1.1.1|2.1.1.1 @@ -2472,6 +2568,7 @@ sub expandnicsattr() if ($nicnames) { my @nics = split(/,/, $nicnames); if ($nicv[0]) { + # Do not need to return the nic attr for this nic if (!grep(/^$nicv[0]$/, @nics)) { next; @@ -2534,31 +2631,36 @@ sub collapsenicsattr() my %nicattrs = (); foreach my $nodeattr (keys %{$nodeattrhash}) { + # e.g nicips.eth0 # do not need to handle nic attributes without the postfix .ethx, # it will be overwritten by the attributes with the postfix .ethx, if ($nodeattr =~ /^(nic\w+)\.(.*)$/) { if ($1 && $2) { + # chdef nicips.eth2= to remove the definition for eth2 # in this case, the $nodeattrhash->{'nicips.eth0'} is blank - if ($nodeattrhash->{$nodeattr}) { - # $nicattrs{nicips}{eth0} = "1.1.1.1|1.2.1.1" - $nicattrs{$1}{$2} = $nodeattrhash->{$nodeattr}; - } + # $nicattrs{nicips}{eth0} = "1.1.1.1|1.2.1.1" + $nicattrs{$1}{$2} = $nodeattrhash->{$nodeattr}; # remove nicips.eth0 from the %::FILEATTRS delete $nodeattrhash->{$nodeattr}; } } } + # $nicattrs{'nicips'}{'eth0'} = "1.1.1.1|1.2.1.1" # $nicattrs{'nicips'}{'eth1'} = "2.1.1.1|2.2.1.1" foreach my $nicattr (keys %nicattrs) { my @tmparray = (); - foreach my $nicname (keys %{$nicattrs{$nicattr}}) { + foreach my $nicname (keys %{ $nicattrs{$nicattr} }) { + # eth0!1.1.1.1|1.2.1.1 - push @tmparray, "$nicname!$nicattrs{$nicattr}{$nicname}"; + if ($nicattrs{$nicattr}{$nicname}) { + push @tmparray, "$nicname!$nicattrs{$nicattr}{$nicname}"; + } } + # eth0!1.1.1.1|1.2.1.1,eth1!2.1.1.1|2.2.1.1 $nodeattrhash->{$nicattr} = join(',', @tmparray); } diff --git a/perl-xCAT/xCAT/DSHCLI.pm b/perl-xCAT/xCAT/DSHCLI.pm index 8dc10874b..a0b5788c9 100644 --- a/perl-xCAT/xCAT/DSHCLI.pm +++ b/perl-xCAT/xCAT/DSHCLI.pm @@ -2,6 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html package xCAT::DSHCLI; + BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; @@ -39,18 +40,18 @@ $::CONTEXT_DIR = "/opt/xcat/xdsh/Context/"; $::__DCP_DELIM = 'Xcat,DELIMITER,Xcat'; our @dsh_valid_env = ( - 'DCP_NODE_OPTS', 'DCP_NODE_RCP', - 'DSH_ENVIRONMENT', 'DSH_FANOUT', - 'DSH_LOG', 'DSH_NODEGROUP_PATH', - 'DSH_NODE_LIST', 'DSH_NODE_OPTS', - 'DSH_NODE_RCP', 'DSH_NODE_RSH', - 'DSH_OUTPUT', 'DSH_PATH', - 'DSH_SYNTAX', 'DSH_TIMEOUT', - 'DSH_REMOTE_PASSWORD', 'DSH_TO_USERID', - 'DSH_FROM_USERID', 'DEVICETYPE', - 'RSYNCSN', 'DSH_RSYNC_FILE', - 'RSYNCSNONLY', - ); + 'DCP_NODE_OPTS', 'DCP_NODE_RCP', + 'DSH_ENVIRONMENT', 'DSH_FANOUT', + 'DSH_LOG', 'DSH_NODEGROUP_PATH', + 'DSH_NODE_LIST', 'DSH_NODE_OPTS', + 'DSH_NODE_RCP', 'DSH_NODE_RSH', + 'DSH_OUTPUT', 'DSH_PATH', + 'DSH_SYNTAX', 'DSH_TIMEOUT', + 'DSH_REMOTE_PASSWORD', 'DSH_TO_USERID', + 'DSH_FROM_USERID', 'DEVICETYPE', + 'RSYNCSN', 'DSH_RSYNC_FILE', + 'RSYNCSNONLY', +); select(STDERR); $| = 1; select(STDOUT); @@ -101,7 +102,7 @@ sub execute_dcp my %unresolved_targets = (); my %context_targets = (); xCAT::DSHCLI->resolve_targets($options, \%resolved_targets, - \%unresolved_targets, \%context_targets); + \%unresolved_targets, \%context_targets); if (!scalar(%resolved_targets)) { @@ -147,11 +148,11 @@ sub execute_dcp !$$options{'silent'} && push @error_files, *STDERR; xCAT::DSHCLI->fork_fanout_dcp( - $options, \%resolved_targets, - \%forked_process, \%pid_targets, - \%outfh_targets, \%errfh_targets, - \@targets_waiting, \%targets_active - ); + $options, \%resolved_targets, + \%forked_process, \%pid_targets, + \%outfh_targets, \%errfh_targets, + \@targets_waiting, \%targets_active + ); while (keys(%targets_active)) { @@ -165,7 +166,7 @@ sub execute_dcp my @active_list = keys(%targets_active); my $rsp = {}; $rsp->{error}->[0] = - " Timed out waiting for response from child processes for the following nodes."; +" Timed out waiting for response from child processes for the following nodes."; $rsp->{error}->[1] = " @active_list"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); kill 'INT', keys(%pid_targets); @@ -178,26 +179,26 @@ sub execute_dcp (@select_out_fhs) && xCAT::DSHCLI->buffer_output( - $options, \%resolved_targets, \%targets_active, - \@targets_finished, \@targets_failed, \%targets_buffered, - \%pid_targets, \%forked_process, \%outfh_targets, - \%output_buffers, \%error_buffers, \@output_files, - \@error_files, \@select_out_fhs - ); + $options, \%resolved_targets, \%targets_active, + \@targets_finished, \@targets_failed, \%targets_buffered, + \%pid_targets, \%forked_process, \%outfh_targets, + \%output_buffers, \%error_buffers, \@output_files, + \@error_files, \@select_out_fhs + ); my @select_err_fhs = xCAT::DSHCLI->util_bit_indexes($rout & $errfh_targets{'bitmap'}, 1); (@select_err_fhs) && xCAT::DSHCLI->buffer_error( - $options, \%resolved_targets, - \%targets_active, \@targets_finished, - \@targets_failed, \%targets_buffered, - \%pid_targets, \%forked_process, - \%errfh_targets, \%output_buffers, - \%error_buffers, \@output_files, - \@error_files, \@select_err_fhs - ); + $options, \%resolved_targets, + \%targets_active, \@targets_finished, + \@targets_failed, \%targets_buffered, + \%pid_targets, \%forked_process, + \%errfh_targets, \%output_buffers, + \%error_buffers, \@output_files, + \@error_files, \@select_err_fhs + ); my @targets_buffered_keys = sort keys(%targets_buffered); @@ -210,13 +211,13 @@ sub execute_dcp if ($::DCP_API) { $::DCP_API_MESSAGE .= - join("", @{$output_buffers{$user_target}}) - . join("", @{$error_buffers{$user_target}}); + join("", @{ $output_buffers{$user_target} }) + . join("", @{ $error_buffers{$user_target} }); } else { - print STDOUT @{$output_buffers{$user_target}}; - print STDERR @{$error_buffers{$user_target}}; + print STDOUT @{ $output_buffers{$user_target} }; + print STDERR @{ $error_buffers{$user_target} }; } } @@ -224,65 +225,65 @@ sub execute_dcp delete $error_buffers{$user_target}; my $exit_code = $targets_buffered{$user_target}{'exit-code'}; - + if ($exit_code != 0) { # report error status --nodestatus # Note the message below for node status must - # not be NLS translated. Code depends on the English. + # not be NLS translated. Code depends on the English. if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$exit_code"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$exit_code"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } push @targets_failed, $user_target; - push @{$dsh_target_status{'failed'}}, $user_target; + push @{ $dsh_target_status{'failed'} }, $user_target; } else { # Note the message below for node status must - # not be NLS translated. Code depends on the English. + # not be NLS translated. Code depends on the English. if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_successful"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + my $rsp = {}; + $rsp->{data}->[0] = + "$user_target: Remote_command_successful"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } push @targets_finished, $user_target; } - + # return list of badnodes and goodnodes if ($$options{'monitor'}) { - foreach my $badnode (@targets_failed) { - my $rsp={}; - $rsp->{data}->[0] = - "dsh> Remote_command_failed $badnode"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } - foreach my $goodnode (@targets_finished) { - my $rsp={}; - $rsp->{data}->[0] = - "dsh> Remote_command_successful $goodnode"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + foreach my $badnode (@targets_failed) { + my $rsp = {}; + $rsp->{data}->[0] = + "dsh> Remote_command_failed $badnode"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } + foreach my $goodnode (@targets_finished) { + my $rsp = {}; + $rsp->{data}->[0] = + "dsh> Remote_command_successful $goodnode"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } } delete $targets_buffered{$user_target}; } (@targets_waiting) && xCAT::DSHCLI->fork_fanout_dcp( - $options, \%resolved_targets, \%forked_process, - \%pid_targets, \%outfh_targets, \%errfh_targets, - \@targets_waiting, \%targets_active - ); + $options, \%resolved_targets, \%forked_process, + \%pid_targets, \%outfh_targets, \%errfh_targets, + \@targets_waiting, \%targets_active + ); } if (scalar(@targets_failed) > 0) { - #$::DCP_NODES_FAILED = join ",", @targets_failed; - @::DCP_NODES_FAILED = @targets_failed; + #$::DCP_NODES_FAILED = join ",", @targets_failed; + @::DCP_NODES_FAILED = @targets_failed; } return (scalar(@targets_failed) + scalar(keys(%unresolved_targets))); @@ -345,7 +346,7 @@ sub execute_dsh $dsh_unresolved_targets = \%unresolved_targets; my %context_targets = (); xCAT::DSHCLI->resolve_targets($options, \%resolved_targets, - \%unresolved_targets, \%context_targets); + \%unresolved_targets, \%context_targets); my @canceled_targets = (); $dsh_target_status{'canceled'} = \@canceled_targets; my $rsp = {}; @@ -395,11 +396,11 @@ sub execute_dsh $dsh_target_status{'failed'} = \@targets_failed; @targets_failed = xCAT::DSHCLI->_execute_dsh($options, \%resolved_targets, - \%unresolved_targets, \%context_targets); + \%unresolved_targets, \%context_targets); if (scalar(@targets_failed) > 0) { - # $::DSH_NODES_FAILED = join ",", @targets_failed; - @::DSH_NODES_FAILED = @targets_failed; + # $::DSH_NODES_FAILED = join ",", @targets_failed; + @::DSH_NODES_FAILED = @targets_failed; } return (scalar(@targets_failed) + scalar(keys(%unresolved_targets))); @@ -473,11 +474,11 @@ sub _execute_dsh $dsh_exec_state++; xCAT::DSHCLI->fork_fanout_dsh( - $options, $resolved_targets, - \%forked_process, \%pid_targets, - \%outfh_targets, \%errfh_targets, - \@targets_waiting, \%targets_active - ); + $options, $resolved_targets, + \%forked_process, \%pid_targets, + \%outfh_targets, \%errfh_targets, + \@targets_waiting, \%targets_active + ); while (keys(%targets_active)) { @@ -490,9 +491,9 @@ sub _execute_dsh if ($fh_count == 0) { my @active_list = keys(%targets_active); - my $rsp = {}; + my $rsp = {}; $rsp->{error}->[0] = - " Timed out waiting for response from child processes for the following nodes. Terminating the child processes. "; +" Timed out waiting for response from child processes for the following nodes. Terminating the child processes. "; $rsp->{error}->[1] = " @active_list"; xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); @targets_failed = keys(%targets_active); @@ -511,22 +512,22 @@ sub _execute_dsh if ($$options{'streaming'}) { xCAT::DSHCLI->stream_output( - $options, $resolved_targets, \%targets_active, - \@targets_finished, \@targets_failed, \%pid_targets, - \%forked_process, \%outfh_targets, \%output_buffers, - \@output_files, \@select_out_fhs - ); + $options, $resolved_targets, \%targets_active, + \@targets_finished, \@targets_failed, \%pid_targets, + \%forked_process, \%outfh_targets, \%output_buffers, + \@output_files, \@select_out_fhs + ); } else { xCAT::DSHCLI->buffer_output( - $options, $resolved_targets, \%targets_active, - \@targets_finished, \@targets_failed, \%targets_buffered, - \%pid_targets, \%forked_process, \%outfh_targets, - \%output_buffers, \%error_buffers, \@output_files, - \@error_files, \@select_out_fhs - ); + $options, $resolved_targets, \%targets_active, + \@targets_finished, \@targets_failed, \%targets_buffered, + \%pid_targets, \%forked_process, \%outfh_targets, + \%output_buffers, \%error_buffers, \@output_files, + \@error_files, \@select_out_fhs + ); } } @@ -538,24 +539,25 @@ sub _execute_dsh if ($$options{'streaming'}) { xCAT::DSHCLI->stream_error( - $options, $resolved_targets, \%targets_active, - \@targets_finished, \@targets_failed, \%pid_targets, - \%forked_process, \%errfh_targets, \%error_buffers, - \@error_files, \@select_err_fhs - ); + $options, $resolved_targets, \%targets_active, + \@targets_finished, \@targets_failed, \%pid_targets, + \%forked_process, \%errfh_targets, \%error_buffers, + \@error_files, \@select_err_fhs + ); } else { xCAT::DSHCLI->buffer_error( - $options, $resolved_targets, \%targets_active, - \@targets_finished, \@targets_failed, \%targets_buffered, - \%pid_targets, \%forked_process, \%errfh_targets, - \%output_buffers, \%error_buffers, \@output_files, - \@error_files, \@select_err_fhs - ); + $options, $resolved_targets, \%targets_active, + \@targets_finished, \@targets_failed, \%targets_buffered, + \%pid_targets, \%forked_process, \%errfh_targets, + \%output_buffers, \%error_buffers, \@output_files, + \@error_files, \@select_err_fhs + ); } } + # This is only if you are not streaming ( -s) my @targets_buffered_keys = sort keys(%targets_buffered); @@ -573,24 +575,24 @@ sub _execute_dsh if ($::DSH_API) { $::DSH_API_MESSAGE = - $::DSH_API_MESSAGE - . join("", @{$output_buffers{$user_target}}) - . join("", @{$error_buffers{$user_target}}); + $::DSH_API_MESSAGE + . join("", @{ $output_buffers{$user_target} }) + . join("", @{ $error_buffers{$user_target} }); } else { # HERE: This is where the output shows up #print STDOUT @{$output_buffers{$user_target}}; #print STDERR @{$error_buffers{$user_target}}; - chomp(@{$output_buffers{$user_target}}); - chomp(@{$error_buffers{$user_target}}); + chomp(@{ $output_buffers{$user_target} }); + chomp(@{ $error_buffers{$user_target} }); my $rsp = {}; - push @{$rsp->{data}}, @{$output_buffers{$user_target}}; + push @{ $rsp->{data} }, @{ $output_buffers{$user_target} }; xCAT::MsgUtils->message("D", $rsp, $::CALLBACK); $rsp = {}; - push @{$rsp->{error}}, @{$error_buffers{$user_target}}; + push @{ $rsp->{error} }, @{ $error_buffers{$user_target} }; $rsp->{NoErrorPrefix} = 1; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK,0); + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 0); } } @@ -606,14 +608,15 @@ sub _execute_dsh { # Note the message below for node status must - # not be NLS translated. Code depends on the English. + # not be NLS translated. Code depends on the English. # report error status --nodestatus if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$exit_code"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$exit_code"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } + # for monitoring -m my $rsp = {}; $rsp->{error}->[0] = "dsh> Remote_command_failed $user_target"; @@ -624,7 +627,7 @@ sub _execute_dsh push @targets_failed, $user_target; } - push @{$dsh_target_status{'failed'}}, $user_target + push @{ $dsh_target_status{'failed'} }, $user_target if !$signal_interrupt_flag; } @@ -633,42 +636,43 @@ sub _execute_dsh { if ($target_rc != 0) { - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - # report error status --nodestatus - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$target_rc"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + # report error status --nodestatus + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$target_rc"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } + # if monitoring - $rsp={}; + $rsp = {}; $rsp->{data}->[0] = "dsh> Remote_command_failed $user_target"; $$options{'monitor'} && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK, 1); push @targets_failed, $user_target; - push @{$dsh_target_status{'failed'}}, $user_target + push @{ $dsh_target_status{'failed'} }, $user_target if !$signal_interrupt_flag; } - elsif (!defined($target_rc) && !$dsh_cmd_background && ($::DSH_MELLANOX_SWITCH==0) && ($$options{'devicetype'}!~ /EthSwitch/)) + elsif (!defined($target_rc) && !$dsh_cmd_background && ($::DSH_MELLANOX_SWITCH == 0) && ($$options{'devicetype'} !~ /EthSwitch/)) { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=???"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = + "$user_target: Remote_command_failed, error_code=???"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } - $rsp={}; + $rsp = {}; $rsp->{error}->[0] = - " A return code for the command run on the host $user_target was not received."; +" A return code for the command run on the host $user_target was not received."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); my $rsp = {}; @@ -678,21 +682,21 @@ sub _execute_dsh && xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); push @targets_failed, $user_target; - push @{$dsh_target_status{'failed'}}, $user_target + push @{ $dsh_target_status{'failed'} }, $user_target if !$signal_interrupt_flag; } - else # it worked + else # it worked { - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_successful"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = + "$user_target: Remote_command_successful"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } - $rsp={}; + $rsp = {}; $rsp->{data}->[0] = "dsh> Remote_command_successful $user_target"; $$options{'monitor'} @@ -707,10 +711,10 @@ sub _execute_dsh (@targets_waiting) && xCAT::DSHCLI->fork_fanout_dsh( - $options, $resolved_targets, \%forked_process, - \%pid_targets, \%outfh_targets, \%errfh_targets, - \@targets_waiting, \%targets_active - ); + $options, $resolved_targets, \%forked_process, + \%pid_targets, \%outfh_targets, \%errfh_targets, + \@targets_waiting, \%targets_active + ); } @@ -724,7 +728,7 @@ sub _execute_dsh && ($dsh_stats{'successful-targets'} = \@targets_finished); if (scalar(@targets_failed)) { - if (scalar(@{$dsh_target_status{'failed'}})) + if (scalar(@{ $dsh_target_status{'failed'} })) { $dsh_stats{'failed-targets'} = $dsh_target_status{'failed'}; } @@ -733,7 +737,7 @@ sub _execute_dsh $dsh_stats{'failed-targets'} = \@targets_failed; } } - scalar(@{$dsh_target_status{'canceled'}}) + scalar(@{ $dsh_target_status{'canceled'} }) && ($dsh_stats{'canceled-targets'} = $dsh_target_status{'canceled'}); } my $rsp = {}; @@ -790,7 +794,7 @@ sub fork_fanout_dcp = @_; while (@$targets_waiting - && (keys(%$targets_active) < $$options{'fanout'})) + && (keys(%$targets_active) < $$options{'fanout'})) { my $user_target = shift @$targets_waiting; my $target_properties = $$resolved_targets{$user_target}; @@ -798,7 +802,7 @@ sub fork_fanout_dcp my @dcp_command; my $rsyncfile; - if (!$$target_properties{'localhost'}) # this is to a remote host + if (!$$target_properties{'localhost'}) # this is to a remote host { my $target_type = $$target_properties{'type'}; @@ -810,17 +814,17 @@ sub fork_fanout_dcp if ($target_type eq 'node') { $remote_copy = - $$options{'node-rcp'}{$$target_properties{'context'}} + $$options{'node-rcp'}{ $$target_properties{'context'} } || $$target_properties{'remote-copy'}; ($remote_copy =~ /\/scp$/) && ($rsh_extension = 'SSH'); ($remote_copy =~ /\/rsync$/) && ($rsh_extension = 'RSYNC'); $rcp_config{'options'} = - $$options{'node-options'}{$$target_properties{'context'}}; + $$options{'node-options'}{ $$target_properties{'context'} }; } $rcp_config{'preserve'} = $$options{'preserve'}; $rcp_config{'recursive'} = $$options{'recursive'}; - $rcp_config{'sudo'} = $$options{'sudo'}; + $rcp_config{'sudo'} = $$options{'sudo'}; if ($$options{'pull'}) { @@ -831,7 +835,7 @@ sub fork_fanout_dcp my @target_file = split '/', $$options{'source'}; $rcp_config{'dest-file'} = - "$$options{'target'}/$target_file[$#target_file]._$$target_properties{'hostname'}"; +"$$options{'target'}/$target_file[$#target_file]._$$target_properties{'hostname'}"; } @@ -849,63 +853,66 @@ sub fork_fanout_dcp #eval "require RemoteShell::$rsh_extension"; eval "require xCAT::$rsh_extension"; my $remoteshell = "xCAT::$rsh_extension"; + # HERE: Build the dcp command based on the arguments - my $localhost=0; # this is from the MN to another node + my $localhost = 0; # this is from the MN to another node @dcp_command = $remoteshell->remote_copy_command(\%rcp_config, $remote_copy); + # add sudo for non-root users if ($$options{'sudo'}) { - unshift (@dcp_command,'sudo'); + unshift(@dcp_command, 'sudo'); } } - else # this is the local host ( running on the Management Node) + else # this is the local host ( running on the Management Node) { if ($$options{'destDir_srcFile'}{$user_target}) { - my $target_type = $$target_properties{'type'}; + my $target_type = $$target_properties{'type'}; - my %rcp_config = (); + my %rcp_config = (); - my $remote_copy; - my $rsh_extension = 'RSH'; + my $remote_copy; + my $rsh_extension = 'RSH'; - if ($target_type eq 'node') - { - $remote_copy = - $$options{'node-rcp'}{$$target_properties{'context'}} - || $$target_properties{'remote-copy'}; - ($remote_copy =~ /\/scp$/) && ($rsh_extension = 'SSH'); - ($remote_copy =~ /\/rsync$/) && ($rsh_extension = 'RSYNC'); - $rcp_config{'options'} = - $$options{'node-options'}{$$target_properties{'context'}}; - } + if ($target_type eq 'node') + { + $remote_copy = + $$options{'node-rcp'}{ $$target_properties{'context'} } + || $$target_properties{'remote-copy'}; + ($remote_copy =~ /\/scp$/) && ($rsh_extension = 'SSH'); + ($remote_copy =~ /\/rsync$/) && ($rsh_extension = 'RSYNC'); + $rcp_config{'options'} = + $$options{'node-options'}{ $$target_properties{'context'} }; + } - $rcp_config{'preserve'} = $$options{'preserve'}; - $rcp_config{'recursive'} = $$options{'recursive'}; + $rcp_config{'preserve'} = $$options{'preserve'}; + $rcp_config{'recursive'} = $$options{'recursive'}; - $rcp_config{'src-file'} = $$options{'source'}; - $rcp_config{'dest-host'} = $$target_properties{'hostname'}; - $rcp_config{'dest-file'} = $$options{'target'}; - $rcp_config{'dest-user'} = $$target_properties{'user'} + $rcp_config{'src-file'} = $$options{'source'}; + $rcp_config{'dest-host'} = $$target_properties{'hostname'}; + $rcp_config{'dest-file'} = $$options{'target'}; + $rcp_config{'dest-user'} = $$target_properties{'user'} || $$options{'user'}; - $rcp_config{'destDir_srcFile'} = + $rcp_config{'destDir_srcFile'} = $$options{'destDir_srcFile'}{$user_target}; - eval "require xCAT::$rsh_extension"; - my $remoteshell = "xCAT::$rsh_extension"; - # HERE: Build the dcp command based on the arguments - my $localhost=1; # this is on the MN to the MN - @dcp_command = - $remoteshell->remote_copy_command(\%rcp_config, $remote_copy,$localhost); - - } - else # just a copy not a sync - { + eval "require xCAT::$rsh_extension"; + my $remoteshell = "xCAT::$rsh_extension"; + + # HERE: Build the dcp command based on the arguments + my $localhost = 1; # this is on the MN to the MN + @dcp_command = + $remoteshell->remote_copy_command(\%rcp_config, $remote_copy, $localhost); + + } + else # just a copy not a sync + { @dcp_command = ('/bin/cp', '-r', $$options{'source'}, $$options{'target'}); - } + } } my $rsp = {}; @@ -917,12 +924,12 @@ sub fork_fanout_dcp xCAT::DSHCore->fork_output($user_target, @dcp_command); vec($$outfh_targets{'bitmap'}, fileno($process_info[1]), 1) = 1; vec($$errfh_targets{'bitmap'}, fileno($process_info[2]), 1) = 1; - $$outfh_targets{fileno($process_info[1])} = $user_target; - $$errfh_targets{fileno($process_info[2])} = $user_target; + $$outfh_targets{ fileno($process_info[1]) } = $user_target; + $$errfh_targets{ fileno($process_info[2]) } = $user_target; $$forked_process{$user_target} = \@process_info; $$targets_active{$user_target}++; - $$pid_targets{$process_info[0]} = $user_target; + $$pid_targets{ $process_info[0] } = $user_target; } } @@ -977,73 +984,77 @@ sub fork_fanout_dsh if (@$targets_waiting > 0) { if ($ENV{'DSH_REMOTE_PASSWORD'}) { foreach my $t (keys(%$resolved_targets)) { - $resolved_targets->{$t}->{'password'}=$ENV{'DSH_REMOTE_PASSWORD'}; - $resolved_targets->{$t}->{'user'}=$$options{'user'}; + $resolved_targets->{$t}->{'password'} = $ENV{'DSH_REMOTE_PASSWORD'}; + $resolved_targets->{$t}->{'user'} = $$options{'user'}; } } else { + #get user name and password from the switches table - my $passwdtab=xCAT::Table->new('passwd',-create=>1); - my @passwd_ent = $passwdtab->getAttribs({key => "switch"}, ['username', 'password', 'comments']); - my $switchestab=xCAT::Table->new('switches',-create=>0); - my $switchents = $switchestab->getNodesAttribs($targets_waiting,[qw/switch sshusername sshpassword protocol/]); - foreach my $entry (values %$switchents) { - my $switch=$entry->[0]->{switch}; - my $username; - my $password; + my $passwdtab = xCAT::Table->new('passwd', -create => 1); + my @passwd_ent = $passwdtab->getAttribs({ key => "switch" }, [ 'username', 'password', 'comments' ]); + my $switchestab = xCAT::Table->new('switches', -create => 0); + my $switchents = $switchestab->getNodesAttribs($targets_waiting, [qw/switch sshusername sshpassword protocol/]); + foreach my $entry (values %$switchents) { + my $switch = $entry->[0]->{switch}; + my $username; + my $password; my $protocol; - + # use switches table first - if (defined($entry->[0]->{sshusername})) { - $username = $entry->[0]->{sshusername}; + if (defined($entry->[0]->{sshusername})) { + $username = $entry->[0]->{sshusername}; } - if (defined($entry->[0]->{sshpassword})) { - $password = $entry->[0]->{sshpassword}; - } - if (defined($entry->[0]->{protocol})) { - $protocol = $entry->[0]->{protocol}; - } - if ((!$username) && (!$password) && (!$protocol)) { #use passwd table as default - if (defined($passwd_ent[0]->{username})) { - $username=$passwd_ent[0]->{username}; + if (defined($entry->[0]->{sshpassword})) { + $password = $entry->[0]->{sshpassword}; + } + if (defined($entry->[0]->{protocol})) { + $protocol = $entry->[0]->{protocol}; + } + if ((!$username) && (!$password) && (!$protocol)) { #use passwd table as default + if (defined($passwd_ent[0]->{username})) { + $username = $passwd_ent[0]->{username}; } - if (defined($passwd_ent[0]->{password})) { - $password = $passwd_ent[0]->{password}; - } - if (defined($passwd_ent[0]->{comments}) && ($passwd_ent[0]->{comments} eq "telnet")) { - $protocol = $passwd_ent[0]->{comments}; - } - } - - if ($username) { - $resolved_targets->{$switch}->{'user'} = $username; - } - if ($password) { - $resolved_targets->{$switch}->{'password'} = $password; - } - if ($protocol) { - $resolved_targets->{$switch}->{'remotecmdproto'} = $protocol; - } - #print "username=$username, password=$password, protocol=$protocol\n"; - } + if (defined($passwd_ent[0]->{password})) { + $password = $passwd_ent[0]->{password}; + } + if (defined($passwd_ent[0]->{comments}) && ($passwd_ent[0]->{comments} eq "telnet")) { + $protocol = $passwd_ent[0]->{comments}; + } + } + + if ($username) { + $resolved_targets->{$switch}->{'user'} = $username; + } + if ($password) { + $resolved_targets->{$switch}->{'password'} = $password; + } + if ($protocol) { + $resolved_targets->{$switch}->{'remotecmdproto'} = $protocol; + } + + #print "username=$username, password=$password, protocol=$protocol\n"; + } } } } + # save the original exports, we are going to add the unique node name below - my $firstpass=0; + my $firstpass = 0; while (@$targets_waiting - && (keys(%$targets_active) < $$options{'fanout'})) + && (keys(%$targets_active) < $$options{'fanout'})) { - my $user_target = shift @$targets_waiting; + my $user_target = shift @$targets_waiting; + # now add export NODE=nodename to the pre-command, if not a device; my $exportnode; if (($$options{'devicetype'})) { - $exportnode=""; - } else{ - $exportnode="export NODE=$user_target; "; + $exportnode = ""; + } else { + $exportnode = "export NODE=$user_target; "; } my $target_properties = $$resolved_targets{$user_target}; my @commands; - my $localShell = + my $localShell = ($$options{'syntax'} eq 'csh') ? '/bin/csh' : '/bin/sh'; my @dsh_command = ($localShell, '-c'); $$options{'command'} =~ s/\s*$//; @@ -1056,40 +1067,41 @@ sub fork_fanout_dsh } if ($$options{'environment'}) { - if ($firstpass ==0) { # do the servicenode stuff only once - # if we are on a servicenode need to get the environment file - # from the SNsyncfiledir, not local - if (xCAT::Utils->isServiceNode()) { - my $newenvfile; - my $synfiledir = "/var/xcat/syncfiles"; #default + if ($firstpass == 0) { # do the servicenode stuff only once + # if we are on a servicenode need to get the environment file + # from the SNsyncfiledir, not local + if (xCAT::Utils->isServiceNode()) { + my $newenvfile; + my $synfiledir = "/var/xcat/syncfiles"; #default - # get the directory on the servicenode to and add to filepath - my @syndir= xCAT::TableUtils->get_site_attribute("SNsyncfiledir"); - if ($syndir[0]) - { - $synfiledir = $syndir[0]; - } - $newenvfile = $synfiledir; - $newenvfile .= $$options{'environment'}; - $$options{'environment'} = $newenvfile; + # get the directory on the servicenode to and add to filepath + my @syndir = xCAT::TableUtils->get_site_attribute("SNsyncfiledir"); + if ($syndir[0]) + { + $synfiledir = $syndir[0]; + } + $newenvfile = $synfiledir; + $newenvfile .= $$options{'environment'}; + $$options{'environment'} = $newenvfile; + } + if (!(-e $$options{'environment'})) + { + my $rsp = {}; + $rsp->{error}->[0] = "File $$options{'environment'} does not exist"; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + } + $firstpass = 1; } - if (!(-e $$options{'environment'})) - { - my $rsp={}; - $rsp->{error}->[0] = "File $$options{'environment'} does not exist"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - } - $firstpass=1; - } - # build the xdsh command - push @dsh_command, - "$exportnode$$options{'pre-command'} . $$options{'environment'} ; $$options{'command'}$$options{'post-command'}"; + + # build the xdsh command + push @dsh_command, +"$exportnode$$options{'pre-command'} . $$options{'environment'} ; $$options{'command'}$$options{'post-command'}"; } else { push @dsh_command, - "$exportnode$$options{'pre-command'}$$options{'command'}$$options{'post-command'}"; +"$exportnode$$options{'pre-command'}$$options{'command'}$$options{'post-command'}"; } if ($$target_properties{'localhost'}) @@ -1122,22 +1134,22 @@ sub fork_fanout_dsh if ($target_type eq 'node') { my $context = $$target_properties{'context'}; - $remote_shell = $$options{'node-rsh'}{$context} + $remote_shell = $$options{'node-rsh'}{$context} || $$options{'node-rsh'}{'none'} || $$target_properties{'remote-shell'} || $$options{'node-rsh-defaults'}{$context}; ($remote_shell =~ /\/ssh$/) && ($rsh_extension = 'SSH'); if ($$options{'devicetype'} =~ /EthSwitch/) { - $remote_shell = "$::XCATROOT/sbin/rshell_api"; - $rsh_extension='RShellAPI'; - $rsh_config{'password'}=$$target_properties{'password'}; - if ($$target_properties{'remotecmdproto'}) { - $rsh_config{'remotecmdproto'}=$$target_properties{'remotecmdproto'}; - } - if ($$options{'trace'}) { - $rsh_config{'trace'}=1; - } + $remote_shell = "$::XCATROOT/sbin/rshell_api"; + $rsh_extension = 'RShellAPI'; + $rsh_config{'password'} = $$target_properties{'password'}; + if ($$target_properties{'remotecmdproto'}) { + $rsh_config{'remotecmdproto'} = $$target_properties{'remotecmdproto'}; + } + if ($$options{'trace'}) { + $rsh_config{'trace'} = 1; + } } # will not set -n for any command, causing problems @@ -1146,7 +1158,7 @@ sub fork_fanout_dsh #if (($$options{'devicetype'})) { $rsh_config{'options'} = - $$options{'node-options'}{$$target_properties{'context'}}; + $$options{'node-options'}{ $$target_properties{'context'} }; #} else { # not a device # $rsh_config{'options'} = "-n " @@ -1159,11 +1171,12 @@ sub fork_fanout_dsh $rsh_config{'command'} = "$exportnode$$options{'pre-command'}"; my $tmp_env_file; + # for the -E flag here we build and copy the -E env variable # file to the nodes if ($$options{'environment'}) { - + my $rsp = {}; $rsp->{data}->[0] = "TRACE: Environment option specified"; $dsh_trace && (xCAT::MsgUtils->message("I", $rsp, $::CALLBACK)); @@ -1193,7 +1206,7 @@ sub fork_fanout_dsh #eval "require RemoteShell::$env_rcp_extension"; eval "require xCAT::$env_rcp_extension"; - my $rcp = "xCAT::$env_rcp_extension"; + my $rcp = "xCAT::$env_rcp_extension"; my @env_rcp_command = $rcp->remote_copy_command(\%env_rcp_config); @@ -1201,31 +1214,34 @@ sub fork_fanout_dsh $rsp->{data}->[0] = "TRACE:Environment: Exporting File.@env_rcp_command "; $dsh_trace && (xCAT::MsgUtils->message("I", $rsp, $::CALLBACK)); + # copy the Env Variable input file to the nodes my @env_rcp_process = xCAT::DSHCore->fork_no_output($user_target, @env_rcp_command); waitpid($env_rcp_process[0], undef); + #push @commands, \@env_rcp_command; } my $tmp_cmd_file; if ($$options{'execute'}) { # first build the scp command to copy the file to execute - # down to the node into /tmp/*.dsh + # down to the node into /tmp/*.dsh my $rsp = {}; $rsp->{data}->[0] = "TRACE: Execute option specified."; $dsh_trace && (xCAT::MsgUtils->message("I", $rsp, $::CALLBACK)); my %exe_rcp_config = (); - $tmp_cmd_file = POSIX::tmpnam . ".dsh"; + $tmp_cmd_file = POSIX::tmpnam . ".dsh"; - my ($exe_cmd, @args) = @{$$options{'execute'}}; + my ($exe_cmd, @args) = @{ $$options{'execute'} }; my $chmod_cmd = ""; + # now build the xdsh of the file buffer # add sudo for non-root users if ($$options{'sudo'}) { - $rsh_config{'command'} .= "sudo "; - $rsh_config{'sudo'} = "sudo "; + $rsh_config{'command'} .= "sudo "; + $rsh_config{'sudo'} = "sudo "; } $rsh_config{'command'} .= "$chmod_cmd $tmp_cmd_file @args$$options{'post-command'}"; @@ -1251,7 +1267,7 @@ sub fork_fanout_dsh #eval "require RemoteShell::$exe_rcp_extension"; eval "require xCAT::$exe_rcp_extension"; - my $rcp = "xCAT::$exe_rcp_extension"; + my $rcp = "xCAT::$exe_rcp_extension"; my @exe_rcp_command = $rcp->remote_copy_command(\%exe_rcp_config); @@ -1259,6 +1275,7 @@ sub fork_fanout_dsh $rsp->{data}->[0] = "TRACE:Execute: Exporting File:@exe_rcp_command"; $dsh_trace && (xCAT::MsgUtils->message("I", $rsp, $::CALLBACK)); + #my @exe_rcp_process = # xCAT::DSHCore->fork_no_output($user_target, @exe_rcp_command); #waitpid($exe_rcp_process[0], undef); @@ -1268,10 +1285,10 @@ sub fork_fanout_dsh else { # add sudo for non-root users - if ($$options{'sudo'}) { - $rsh_config{'command'} .= "sudo "; - $rsh_config{'sudo'} = "sudo "; - } + if ($$options{'sudo'}) { + $rsh_config{'command'} .= "sudo "; + $rsh_config{'sudo'} = "sudo "; + } $rsh_config{'command'} .= "$$options{'command'}$$options{'post-command'}"; } @@ -1281,7 +1298,7 @@ sub fork_fanout_dsh } if ($$options{'execute'}) { - $rsh_config{'command'} .= ";rm $tmp_cmd_file"; + $rsh_config{'command'} .= ";rm $tmp_cmd_file"; } #eval "require RemoteShell::$rsh_extension"; @@ -1301,19 +1318,19 @@ sub fork_fanout_dsh my $rsp = {}; $rsp->{data}->[0] = "dsh> Remote_command_started $user_target"; $$options{'monitor'} && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - + # execute and remove the /tmp file build which is a copy of the # input -E file #print "Command=@dsh_command\n"; #@process_info = xCAT::DSHCore->fork_output($user_target, @dsh_command); - push (@commands, \@dsh_command); #print Dumper(\@commands); - @process_info = xCAT::DSHCore->fork_output_for_commands($user_target, @commands); + push(@commands, \@dsh_command); #print Dumper(\@commands); + @process_info = xCAT::DSHCore->fork_output_for_commands($user_target, @commands); if ($process_info[0] == -2) { my $rsp = {}; $rsp->{error}->[0] = - "$user_target could not execute this command $dsh_command[0] - $$options{'command'} , $! "; +"$user_target could not execute this command $dsh_command[0] - $$options{'command'} , $! "; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } @@ -1337,12 +1354,12 @@ sub fork_fanout_dsh vec($$outfh_targets{'bitmap'}, fileno($process_info[1]), 1) = 1; vec($$errfh_targets{'bitmap'}, fileno($process_info[2]), 1) = 1; - $$outfh_targets{fileno($process_info[1])} = $user_target; - $$errfh_targets{fileno($process_info[2])} = $user_target; + $$outfh_targets{ fileno($process_info[1]) } = $user_target; + $$errfh_targets{ fileno($process_info[2]) } = $user_target; $$forked_process{$user_target} = \@process_info; $$targets_active{$user_target}++; - $$pid_targets{$process_info[0]} = $user_target; + $$pid_targets{ $process_info[0] } = $user_target; } } @@ -1420,11 +1437,11 @@ sub buffer_output my $eof_output = xCAT::DSHCore->pipe_handler_buffer( - $target_properties, $output_fh, 4096, - "$user_target: ", - $$output_buffers{"${user_target}_tmp"}, - $$output_buffers{$user_target} - ); + $target_properties, $output_fh, 4096, + "$user_target: ", + $$output_buffers{"${user_target}_tmp"}, + $$output_buffers{$user_target} + ); if ($eof_output) { @@ -1447,26 +1464,26 @@ sub buffer_output { # check return code $exit_code = $? >> 8; } - if (scalar(@{$$output_buffers{$user_target}}) == 1) + if (scalar(@{ $$output_buffers{$user_target} }) == 1) { ($$output_buffers{$user_target}[0] eq '') - && (@{$$output_buffers{$user_target}} = ()); + && (@{ $$output_buffers{$user_target} } = ()); } - if (scalar(@{$$error_buffers{$user_target}}) == 1) + if (scalar(@{ $$error_buffers{$user_target} }) == 1) { ($$error_buffers{$user_target}[0] eq '') - && (@{$$error_buffers{$user_target}} = ()); + && (@{ $$error_buffers{$user_target} } = ()); } my %exit_status = ( - 'exit-code' => $exit_code, - 'target-rc' => $$target_properties{'target-rc'} - ); + 'exit-code' => $exit_code, + 'target-rc' => $$target_properties{'target-rc'} + ); $$targets_buffered{$user_target} = \%exit_status; delete $$targets_active{$user_target}; - delete $$pid_targets{$$forked_process{$user_target}[0]}; + delete $$pid_targets{ $$forked_process{$user_target}[0] }; close $output_fh; close $error_fh; @@ -1549,11 +1566,11 @@ sub buffer_error my $eof_error = xCAT::DSHCore->pipe_handler_buffer( - $target_properties, $error_fh, 4096, - "$user_target: ", - $$error_buffers{"${user_target}_tmp"}, - $$error_buffers{$user_target} - ); + $target_properties, $error_fh, 4096, + "$user_target: ", + $$error_buffers{"${user_target}_tmp"}, + $$error_buffers{$user_target} + ); if ($eof_error) { @@ -1576,26 +1593,26 @@ sub buffer_error $exit_code = $? >> 8; } - if (scalar(@{$$output_buffers{$user_target}}) == 1) + if (scalar(@{ $$output_buffers{$user_target} }) == 1) { ($$output_buffers{$user_target}[0] eq '') - && (@{$$output_buffers{$user_target}} = ()); + && (@{ $$output_buffers{$user_target} } = ()); } - if (scalar(@{$$error_buffers{$user_target}}) == 1) + if (scalar(@{ $$error_buffers{$user_target} }) == 1) { ($$error_buffers{$user_target}[0] eq '') - && (@{$$error_buffers{$user_target}} = ()); + && (@{ $$error_buffers{$user_target} } = ()); } my %exit_status = ( - 'exit-code' => $exit_code, - 'target-rc' => $$target_properties{'target-rc'} - ); + 'exit-code' => $exit_code, + 'target-rc' => $$target_properties{'target-rc'} + ); $$targets_buffered{$user_target} = \%exit_status; delete $$targets_active{$user_target}; - delete $$pid_targets{$$forked_process{$user_target}[0]}; + delete $$pid_targets{ $$forked_process{$user_target}[0] }; close $output_fh; close $error_fh; @@ -1668,14 +1685,14 @@ sub stream_output my $eof_output = xCAT::DSHCore->pipe_handler( - $options, - $target_properties, - $output_fh, - 4096, - "$user_target: ", - $$output_buffers{$user_target}, - @$output_files - ); + $options, + $target_properties, + $output_fh, + 4096, + "$user_target: ", + $$output_buffers{$user_target}, + @$output_files + ); if ($eof_output) { @@ -1704,12 +1721,12 @@ sub stream_output { # report error status --nodestatus # Note the message below for node status must - # not be NLS translated. Code depends on the English. + # not be NLS translated. Code depends on the English. if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$exit_code"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$exit_code"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } my $rsp = {}; $rsp->{error}->[0] = @@ -1724,7 +1741,7 @@ sub stream_output && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); push @$targets_failed, $user_target; - push @{$dsh_target_status{'failed'}}, $user_target + push @{ $dsh_target_status{'failed'} }, $user_target if !$signal_interrupt_flag; } @@ -1733,19 +1750,19 @@ sub stream_output { if ($target_rc != 0) { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$$target_properties{'target-rc'}"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$$target_properties{'target-rc'}"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } my $rsp = {}; $rsp->{error}->[0] = - " $user_target remote Command had return code: $$target_properties{'target-rc'} "; +" $user_target remote Command had return code: $$target_properties{'target-rc'} "; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); my $rsp = {}; @@ -1759,20 +1776,20 @@ sub stream_output elsif (!defined($target_rc)) { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=???"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=???"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } my $rsp = {}; $rsp->{error}->[0] = - " $user_target a return code run on this host was not received. "; +" $user_target a return code run on this host was not received. "; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); my $rsp = {}; @@ -1784,17 +1801,17 @@ sub stream_output push @$targets_failed, $user_target; } - else # xdsh -s worked + else # xdsh -s worked { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_successful"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = + "$user_target: Remote_command_successful"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } my $rsp = {}; @@ -1808,7 +1825,7 @@ sub stream_output } delete $$targets_active{$user_target}; - delete $$pid_targets{$$forked_process{$user_target}[0]}; + delete $$pid_targets{ $$forked_process{$user_target}[0] }; } close $output_fh; @@ -1880,14 +1897,14 @@ sub stream_error my $eof_error = xCAT::DSHCore->pipe_handler( - $options, - $target_properties, - $error_fh, - 4096, - "$user_target: ", - $$error_buffers{$user_target}, - @$error_files - ); + $options, + $target_properties, + $error_fh, + 4096, + "$user_target: ", + $$error_buffers{$user_target}, + @$error_files + ); if ($eof_error) { @@ -1914,14 +1931,14 @@ sub stream_error if ($exit_code != 0) { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$exit_code"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$exit_code"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } my $rsp = {}; $rsp->{error}->[0] = @@ -1936,7 +1953,7 @@ sub stream_error && xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); push @$targets_failed, $user_target; - push @{$dsh_target_status{'failed'}}, $user_target + push @{ $dsh_target_status{'failed'} }, $user_target if !$signal_interrupt_flag; } @@ -1945,15 +1962,15 @@ sub stream_error { if ($target_rc != 0) { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=$$target_properties{'target-rc'}"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=$$target_properties{'target-rc'}"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } #my $rsp = {}; #$rsp->{error}->[0] = @@ -1969,22 +1986,22 @@ sub stream_error push @$targets_failed, $user_target; } - elsif (!defined($target_rc) && ($::DSH_MELLANOX_SWITCH==0)) + elsif (!defined($target_rc) && ($::DSH_MELLANOX_SWITCH == 0)) { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed, error_code=???}"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = +"$user_target: Remote_command_failed, error_code=???}"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } my $rsp = {}; $rsp->{data}->[0] = - "A return code for the command run on $user_target was not received."; +"A return code for the command run on $user_target was not received."; xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); my $rsp = {}; @@ -1998,15 +2015,15 @@ sub stream_error else { - # report error status --nodestatus - # Note the message below for node status must - # not be NLS translated. Code depends on the English. - if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_successful"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + # report error status --nodestatus + # Note the message below for node status must + # not be NLS translated. Code depends on the English. + if ($$options{'nodestatus'}) { + my $rsp = {}; + $rsp->{data}->[0] = + "$user_target: Remote_command_successful"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } my $rsp = {}; @@ -2020,7 +2037,7 @@ sub stream_error } delete $$targets_active{$user_target}; - delete $$pid_targets{$$forked_process{$user_target}[0]}; + delete $$pid_targets{ $$forked_process{$user_target}[0] }; } close $error_fh; @@ -2123,13 +2140,13 @@ sub config_dcp && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); !$$options{'node-rcp'} - && ( $$options{'node-rcp'} = $ENV{'DCP_NODE_RCP'} - || $ENV{'DCP_COPY_CMD'} - || undef); + && ($$options{'node-rcp'} = $ENV{'DCP_NODE_RCP'} + || $ENV{'DCP_COPY_CMD'} + || undef); if ($$options{'node-rcp'}) { - my %node_rcp = (); + my %node_rcp = (); my @remotecopy_list = split ',', $$options{'node-rcp'}; foreach my $context_remotecopy (@remotecopy_list) @@ -2171,7 +2188,7 @@ sub config_dcp $dsh_trace && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - if ( (!$$options{'nodes'}) + if ((!$$options{'nodes'}) && ($ENV{'DSH_NODE_LIST'} || $ENV{'DSH_LIST'})) { require Context::DSH; @@ -2198,7 +2215,7 @@ sub config_dcp if ($$options{'node-options'}) { - my %node_options = (); + my %node_options = (); my @remoteopts_list = split ',', $$options{'node-options'}; foreach my $context_remoteopts (@remoteopts_list) @@ -2230,7 +2247,7 @@ sub config_dcp { my $rsp = {}; $rsp->{error}->[0] = - "Cannot copy to target $$options{'target'}. Directory does not exist."; +"Cannot copy to target $$options{'target'}. Directory does not exist."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return ++$result; } @@ -2285,7 +2302,7 @@ sub config_dsh $dsh_stats{'report-status-messages'} = (); $dsh_stats{'specified-targets'} = (); scalar(@dsh_valid_contexts) || xCAT::DSHCLI->get_valid_contexts; - push @{$dsh_stats{'valid-contexts'}}, @dsh_valid_contexts; + push @{ $dsh_stats{'valid-contexts'} }, @dsh_valid_contexts; foreach my $context (@dsh_valid_contexts) { @@ -2320,7 +2337,7 @@ sub config_dsh $dsh_trace && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - # Check devicetype attr and build command based on type + # Check devicetype attr and build command based on type $$options{'devicetype'} = $$options{'devicetype'} || $ENV{'DEVICETYPE'} || undef; @@ -2336,43 +2353,44 @@ sub config_dsh # process the config file. check /var/opt/xcat/... first, if the config # file is not found, goto /opt/xcat/share/devicetype - my $devicepath = "/var/opt/xcat/" . $devicename . "/config"; - if (! -e $devicepath) { - $devicepath="$::XCATROOT/share/xcat/devicetype/" . $devicename . "/config"; - } - # Get configuration from $::XCATDEVCFGDIR - # used for QLogic and Mellanox - if (-e $devicepath) - { - my $deviceconf = get_config($devicepath); - - # Get all dsh section configuration - foreach my $entry (keys %{$$deviceconf{'xdsh'}}) - { + my $devicepath = "/var/opt/xcat/" . $devicename . "/config"; + if (!-e $devicepath) { + $devicepath = "$::XCATROOT/share/xcat/devicetype/" . $devicename . "/config"; + } + + # Get configuration from $::XCATDEVCFGDIR + # used for QLogic and Mellanox + if (-e $devicepath) + { + my $deviceconf = get_config($devicepath); + + # Get all dsh section configuration + foreach my $entry (keys %{ $$deviceconf{'xdsh'} }) + { my $value = $$deviceconf{'xdsh'}{$entry}; if ($value) { $$options{$entry} = $value; } - - } - } - else - { - # if not Mellanox, it does not need a config file - if (!($$options{'devicetype'} =~ /IBSwitch::Mellanox/i)) { - my $rsp = {}; - $rsp->{error}->[0] = "The config file: $devicepath is missing"; - xCAT::MsgUtils->message('E', $rsp, $::CALLBACK); - } - } + } + } + else + + { + # if not Mellanox, it does not need a config file + if (!($$options{'devicetype'} =~ /IBSwitch::Mellanox/i)) { + my $rsp = {}; + $rsp->{error}->[0] = "The config file: $devicepath is missing"; + xCAT::MsgUtils->message('E', $rsp, $::CALLBACK); + } + } } !$$options{'node-rsh'} - && ( $$options{'node-rsh'} = $ENV{'DSH_NODE_RSH'} - || $ENV{'DSH_REMOTE_CMD'} - || undef); + && ($$options{'node-rsh'} = $ENV{'DSH_NODE_RSH'} + || $ENV{'DSH_REMOTE_CMD'} + || undef); my $rsp = {}; $rsp->{data}->[0] = "TRACE:Node RSH is $$options{'node-rsh'}"; @@ -2432,7 +2450,7 @@ sub config_dsh } $$options{'fanout'} = $$options{'fanout'} || $ENV{'DSH_FANOUT'} || 64; - $rsp={}; + $rsp = {}; $rsp->{data}->[0] = "TRACE: Fanout value is $$options{'fanout'}."; $dsh_trace && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); @@ -2441,7 +2459,7 @@ sub config_dsh if ( defined($$options{'syntax'}) - && ( ($$options{'syntax'} ne 'csh') + && (($$options{'syntax'} ne 'csh') && ($$options{'syntax'} ne 'ksh')) ) { @@ -2520,12 +2538,12 @@ sub config_dsh } else { - # if entry NULL then remove - if ($$options{'pre-command'} =~ /NULL/i) { - $$options{'pre-command'} = ''; - } else { #add space between pre-command and command - $$options{'pre-command'} .=" "; - } + # if entry NULL then remove + if ($$options{'pre-command'} =~ /NULL/i) { + $$options{'pre-command'} = ''; + } else { #add space between pre-command and command + $$options{'pre-command'} .= " "; + } } # Check if $$options{'post-command'} has been overwritten. @@ -2534,18 +2552,18 @@ sub config_dsh if ($$options{'syntax'} eq 'csh') { $$options{'post-command'} = - "; $env_set DSH_TARGET_RC$env_assign\$status; echo \":DSH_TARGET_RC=\${DSH_TARGET_RC}:\""; +"; $env_set DSH_TARGET_RC$env_assign\$status; echo \":DSH_TARGET_RC=\${DSH_TARGET_RC}:\""; } else { $$options{'post-command'} = - "; $env_set DSH_TARGET_RC$env_assign\$?; echo \":DSH_TARGET_RC=\${DSH_TARGET_RC}:\""; +"; $env_set DSH_TARGET_RC$env_assign\$?; echo \":DSH_TARGET_RC=\${DSH_TARGET_RC}:\""; } $$options{'exit-status'} && ($$options{'post-command'} .= - ' ; echo "Remote_command_rc = $DSH_TARGET_RC"'); + ' ; echo "Remote_command_rc = $DSH_TARGET_RC"'); } else { @@ -2572,7 +2590,7 @@ sub config_dsh if ( !$$options{'nodes'} - && ( $ENV{'DSH_NODE_LIST'} + && ($ENV{'DSH_NODE_LIST'} || $ENV{'DSH_LIST'}) ) { @@ -2600,7 +2618,7 @@ sub config_dsh if ($$options{'node-options'}) { - my %node_options = (); + my %node_options = (); my @remoteopts_list = split ',', $$options{'node-options'}; foreach my $context_remoteopts (@remoteopts_list) @@ -2635,7 +2653,7 @@ sub config_dsh if (!(-e $exe_command[0])) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "File $exe_command[0] does not exist"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return ++$result; @@ -2644,7 +2662,7 @@ sub config_dsh if (-z $exe_command[0]) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "File $exe_command[0] is empty."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return ++$result; @@ -2653,7 +2671,7 @@ sub config_dsh if (!(-x $exe_command[0])) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "File $exe_command[0] is not executable."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return ++$result; @@ -2719,7 +2737,7 @@ sub config_signals_dsh foreach my $signal (@ignore_signals) { - if ( ($signal ne 'STOP') + if (($signal ne 'STOP') && ($signal ne 'CONT') && ($signal ne 'TSTP')) { @@ -2774,7 +2792,7 @@ sub handle_signal_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Command execution ended prematurely due to a previous error or stop request from the user."; +"Command execution ended prematurely due to a previous error or stop request from the user."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); exit(1); } @@ -2783,7 +2801,7 @@ sub handle_signal_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Command execution ended prematurely due to a previous error or stop request from the user."; +"Command execution ended prematurely due to a previous error or stop request from the user."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); exit(1); @@ -2797,16 +2815,16 @@ sub handle_signal_dsh $dsh_stats{'end-time'} = localtime(); } - if (@{$dsh_target_status{'waiting'}}) + if (@{ $dsh_target_status{'waiting'} }) { - foreach my $user_target (@{$dsh_target_status{'waiting'}}) + foreach my $user_target (@{ $dsh_target_status{'waiting'} }) { if ($fatal_error) { my $rsp = {}; $rsp->{error}->[0] = - "Running the command on $user_target has been cancelled due to unrecoverable error. The command was never sent to the host."; +"Running the command on $user_target has been cancelled due to unrecoverable error. The command was never sent to the host."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } @@ -2820,13 +2838,13 @@ sub handle_signal_dsh && xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } - push @{$dsh_target_status{'canceled'}}, $user_target; + push @{ $dsh_target_status{'canceled'} }, $user_target; } } my $rsp = {}; $rsp->{error}->[0] = - "Running commands have been cancelled due to unrecoverable error or stop request by user."; +"Running commands have been cancelled due to unrecoverable error or stop request by user."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); if ($$dsh_options{'stats'}) @@ -2855,16 +2873,16 @@ sub handle_signal_dsh $dsh_stats{'end-time'} = localtime(); } - if (@{$dsh_target_status{'waiting'}}) + if (@{ $dsh_target_status{'waiting'} }) { - foreach my $user_target (@{$dsh_target_status{'waiting'}}) + foreach my $user_target (@{ $dsh_target_status{'waiting'} }) { if ($fatal_error) { my $rsp = {}; $rsp->{error}->[0] = - "$user_target: running of the command on this host has been cancelled due to unrecoverable error.\n The command was never sent to the host."; +"$user_target: running of the command on this host has been cancelled due to unrecoverable error.\n The command was never sent to the host."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } @@ -2873,7 +2891,7 @@ sub handle_signal_dsh my $rsp = {}; $rsp->{error}->[0] = - "$user_target: running of the command on this host has been cancelled due to unrecoverable error or stop request by user.\n The command was never sent to the host."; +"$user_target: running of the command on this host has been cancelled due to unrecoverable error or stop request by user.\n The command was never sent to the host."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); my $rsp = {}; @@ -2883,15 +2901,15 @@ sub handle_signal_dsh && xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } - push @{$dsh_target_status{'canceled'}}, $user_target; + push @{ $dsh_target_status{'canceled'} }, $user_target; } } - @{$dsh_target_status{'waiting'}} = (); + @{ $dsh_target_status{'waiting'} } = (); my $rsp = {}; $rsp->{data}->[0] = - "Command execution ended prematurely due to a previous unrecoverable error or stop by user.\n No commands were executed on any host."; +"Command execution ended prematurely due to a previous unrecoverable error or stop by user.\n No commands were executed on any host."; if ($$dsh_options{'stats'}) { @@ -2949,7 +2967,7 @@ sub handle_signal_dsh my $rsp = {}; $rsp->{error}->[0] = - "Running the command on $user_target has been interrupted due to unrecoverable error. The command may not have completed successfully."; +"Running the command on $user_target has been interrupted due to unrecoverable error. The command may not have completed successfully."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } @@ -2958,14 +2976,14 @@ sub handle_signal_dsh my $rsp = {}; $rsp->{error}->[0] = - "Running the command on $user_target has been interrupted due to unrecoverable error or stop request by the user. The command may not have completed successfully."; +"Running the command on $user_target has been interrupted due to unrecoverable error or stop request by the user. The command may not have completed successfully."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } } my $target_pid = $$dsh_forked_process{$user_target}[0]; kill $target_signal, $target_pid; - push @{$dsh_target_status{'failed'}}, $user_target; + push @{ $dsh_target_status{'failed'} }, $user_target; $signal_interrupt_flag = 1; } @@ -2976,16 +2994,16 @@ sub handle_signal_dsh # not want to remove all the rest if ($fatal_error != 2) { # remove the waiting processes - if (@{$dsh_target_status{'waiting'}}) + if (@{ $dsh_target_status{'waiting'} }) { - foreach my $user_target (@{$dsh_target_status{'waiting'}}) + foreach my $user_target (@{ $dsh_target_status{'waiting'} }) { if ($fatal_error) { my $rsp = {}; $rsp->{error}->[0] = - "Running the command on $user_target has been cancelled due to unrecoverable error. The command was never sent to the host."; +"Running the command on $user_target has been cancelled due to unrecoverable error. The command was never sent to the host."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } @@ -2994,7 +3012,7 @@ sub handle_signal_dsh my $rsp = {}; $rsp->{error}->[0] = - "Running the command on $user_target has been cancelled due to unrecoverable error or stop request by the user. The command was never sent to the host."; +"Running the command on $user_target has been cancelled due to unrecoverable error or stop request by the user. The command was never sent to the host."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); my $rsp = {}; @@ -3004,15 +3022,15 @@ sub handle_signal_dsh && xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } - push @{$dsh_target_status{'canceled'}}, $user_target; + push @{ $dsh_target_status{'canceled'} }, $user_target; } } - @{$dsh_target_status{'waiting'}} = (); + @{ $dsh_target_status{'waiting'} } = (); my $rsp = {}; $rsp->{error}->[0] = - "Command execution ended prematurely due to a previous unrecoverable error or stop request by the user."; +"Command execution ended prematurely due to a previous unrecoverable error or stop request by the user."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } #end fatal_error != 2 if ($$dsh_options{'stats'}) @@ -3037,7 +3055,7 @@ sub handle_signal_dsh my $rsp = {}; $rsp->{error}->[0] = - "Running the command stopped due to unrecoverable error or stop request by the user."; +"Running the command stopped due to unrecoverable error or stop request by the user."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return; @@ -3047,7 +3065,7 @@ sub handle_signal_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Running the command stopped due to unrecoverable error or stop request by the user."; +"Running the command stopped due to unrecoverable error or stop request by the user."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); exit(1); } @@ -3092,8 +3110,8 @@ sub resolve_targets = @_; $$options{'nodes'} - && xCAT::DSHCLI->resolve_nodes($options, $resolved_targets, - $unresolved_targets, $context_targets); + && xCAT::DSHCLI->resolve_nodes($options, $resolved_targets, + $unresolved_targets, $context_targets); } #---------------------------------------------------------------------------- @@ -3141,12 +3159,12 @@ sub resolve_nodes !$node && (($node = $context) && ($context = $$options{'context'})); - push @{$dsh_stats{'specified-targets'}{$context}{'nodes'}}, $node; + push @{ $dsh_stats{'specified-targets'}{$context}{'nodes'} }, $node; } xCAT::DSHCLI->_resolve_nodes($options, $resolved_targets, - $unresolved_targets, $context_targets, - @node_list); + $unresolved_targets, $context_targets, + @node_list); } #---------------------------------------------------------------------------- @@ -3251,16 +3269,16 @@ sub bld_resolve_nodes_hash # find out if we have an MN in the list, local cp and sh will be used # not remote shell # find out the names for the Management Node - my @MNnodeinfo = xCAT::NetworkUtils->determinehostname; - my $mname = pop @MNnodeinfo; # hostname - my $cmd="hostname"; - my $localhostname = xCAT::Utils->runcmd($cmd,0); + my @MNnodeinfo = xCAT::NetworkUtils->determinehostname; + my $mname = pop @MNnodeinfo; # hostname + my $cmd = "hostname"; + my $localhostname = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { - my $rsp = {}; - $rsp->{info}->[0] = "Command: $cmd failed. Continuing..."; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); - } + my $rsp = {}; + $rsp->{info}->[0] = "Command: $cmd failed. Continuing..."; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + } foreach my $target (@target_list) { @@ -3269,18 +3287,19 @@ sub bld_resolve_nodes_hash my $localhost; my $user; my $context = "XCAT"; + # check to see if this node is the Management Node we are on, can run local commands (sh,cp) - if (($mname eq $target) || ($localhostname eq $target)){ - $localhost=$target; + if (($mname eq $target) || ($localhostname eq $target)) { + $localhost = $target; } my %properties = ( - 'hostname' => $hostname, - 'ip-address' => $ip_address, - 'localhost' => $localhost, - 'user' => $user, - 'context' => $context, - 'unresolved' => $target - ); + 'hostname' => $hostname, + 'ip-address' => $ip_address, + 'localhost' => $localhost, + 'user' => $user, + 'context' => $context, + 'unresolved' => $target + ); $$resolved_targets{"$target"} = \%properties; } @@ -3345,16 +3364,17 @@ sub verify_targets { my $rsp = {}; $rsp->{error}->[0] = - "$user_target is not responding. No command will be issued to this host."; +"$user_target is not responding. No command will be issued to this host."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + # report error status --nodestatus # Note the message below for node status must # not be NLS translated. Code depends on the English. if ($$options{'nodestatus'}) { - my $rsp={}; - $rsp->{data}->[0] = - "$user_target: Remote_command_failed"; - xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); + my $rsp = {}; + $rsp->{data}->[0] = + "$user_target: Remote_command_failed"; + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } my $rsp = {}; @@ -3363,7 +3383,7 @@ sub verify_targets $$dsh_options{'monitor'} && xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - push @{$dsh_target_status{'canceled'}}, $user_target; + push @{ $dsh_target_status{'canceled'} }, $user_target; $$dsh_unresolved_targets{$user_target} = $$resolved_targets{$user_target}; delete $$resolved_targets{$user_target}; @@ -3567,7 +3587,7 @@ sub util_bit_indexes my ($class, $vector, $bit) = @_; my @bit_indexes = (); - my @bits = split(//, unpack("b*", $vector)); + my @bits = split(//, unpack("b*", $vector)); my $index = 0; while (@bits) @@ -3608,23 +3628,23 @@ sub check_valid_options { my @invalid_opts; my @valid_longnames = ( - "continue", "execute", - "fanout", "help", - "user", "monitor", - "nodes", "node-options", - "node-rsh", "stream", - "timeout", "verify", - "exit-status", "context", - "environment", "ignore-sig", - "ignoresig", "no-locale", - "nodegroups", "silent", - "syntax", "trace", - "version", "command-name", - "commandName", "command-description", - "commandDescription", "noFileWriting", - "preserve", "node-rcp", - "pull", "recursive" - ); + "continue", "execute", + "fanout", "help", + "user", "monitor", + "nodes", "node-options", + "node-rsh", "stream", + "timeout", "verify", + "exit-status", "context", + "environment", "ignore-sig", + "ignoresig", "no-locale", + "nodegroups", "silent", + "syntax", "trace", + "version", "command-name", + "commandName", "command-description", + "commandDescription", "noFileWriting", + "preserve", "node-rcp", + "pull", "recursive" + ); foreach my $opt (@$options) { @@ -3941,8 +3961,8 @@ sub parse_and_run_dsh 'V|version' => \$options{'version'}, 'devicetype|devicetype=s' => \$options{'devicetype'}, - 'nodestatus|nodestatus' => \$options{'nodestatus'}, - 'sudo|sudo' => \$options{'sudo'}, + 'nodestatus|nodestatus' => \$options{'nodestatus'}, + 'sudo|sudo' => \$options{'sudo'}, 'command-name|commandName=s' => \$options{'command-name'}, 'command-description|commandDescription=s' => \$options{'command-description'}, @@ -3983,7 +4003,7 @@ sub parse_and_run_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Remote command: $remotecommand should be used with the dcp command. "; +"Remote command: $remotecommand should be used with the dcp command. "; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); return; } @@ -3996,25 +4016,27 @@ sub parse_and_run_dsh # this was determined in the xdsh client code, because non-root user # actions must be taken there. For those calling xdsh plugin, default # is root - if (!($ENV{'DSH_TO_USERID'})) # env first + if (!($ENV{'DSH_TO_USERID'})) # env first { - if (!($options{'user'})) { # -l second - $options{'user'} = "root"; # default - } + if (!($options{'user'})) { # -l second + $options{'user'} = "root"; # default + } } else { $options{'user'} = $ENV{'DSH_TO_USERID'}; } if ((!(defined($nodes))) && (!(defined($options{'rootimg'})))) - { # no nodes and not -i option, error + { # no nodes and not -i option, error my $rsp = (); $rsp->{error}->[0] = "Unless using -i option, noderange is required."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } + # Determine switch type, processing Mellanox not the same as QLogic my $switchtype = $options{'devicetype'}; + #$switchtype =~ s/::/\//g; # @@ -4024,16 +4046,16 @@ sub parse_and_run_dsh if (defined($options{'rootimg'})) { # running against local host # diskless image - # need directory for Linux, just osimage name for AIX + # need directory for Linux, just osimage name for AIX if (xCAT::Utils->isLinux()) { - if (!(-e ($options{'rootimg'}))) - { # directory does not exist - my $rsp = {}; - $rsp->{error}->[0] = - "Input image directory $options{'rootimg'} does not exist."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return; - } + if (!(-e ($options{'rootimg'}))) + { # directory does not exist + my $rsp = {}; + $rsp->{error}->[0] = + "Input image directory $options{'rootimg'} does not exist."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return; + } } # since we have no input nodes for running xdsh against the image @@ -4049,7 +4071,7 @@ sub parse_and_run_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Input noderange:@$nodes and any other xdsh flags or environment variables are not valid with -i flag."; +"Input noderange:@$nodes and any other xdsh flags or environment variables are not valid with -i flag."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4066,29 +4088,29 @@ sub parse_and_run_dsh # get the actual xdsh command from the argument list $options{'command'} = join ' ', @ARGV; - + # if a Mellanox switch command we have to build - # the command xdsh will send special + # the command xdsh will send special # input will look something like this # xdsh mswitch -l admin --devicetype IBSwitch::Mellanox # enable;configure terminal;show ssh server host-keys # We will build # ssh admin@mswitch cli - # "enable" "configure terminal" "show ssh server host-keys" + # "enable" "configure terminal" "show ssh server host-keys" my @melcmds; if ($switchtype =~ /IBSwitch::Mellanox/i) { - $::DSH_MELLANOX_SWITCH=1; - @melcmds = split (/;/, $options{'command'}); - my $newcmd; - foreach my $cmd (@melcmds) { - $newcmd .= "\""; - $newcmd .= $cmd; - $newcmd .= "\" "; - } - $options{'command'} = $newcmd; + $::DSH_MELLANOX_SWITCH = 1; + @melcmds = split(/;/, $options{'command'}); + my $newcmd; + foreach my $cmd (@melcmds) { + $newcmd .= "\""; + $newcmd .= $cmd; + $newcmd .= "\" "; + } + $options{'command'} = $newcmd; } else { - $::DSH_MELLANOX_SWITCH=0; + $::DSH_MELLANOX_SWITCH = 0; } # # -K option just sets up the ssh keys on the nodes and exits @@ -4096,23 +4118,24 @@ sub parse_and_run_dsh if (defined $options{'ssh-setup'}) { - # check if any node in the noderange is the Management Node and exit + # check if any node in the noderange is the Management Node and exit # 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 - my $nodes=join(',', @mname); + my @mname = xCAT::Utils->noderangecontainsMn(@nodelist); + if (@mname) { # MN in the nodelist + my $nodes = join(',', @mname); my $rsp = {}; $rsp->{error}->[0] = "You must not run -K option against the Management Node:$nodes."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; - } + } + # if devicetype=Mellanox, xdsh does not setup ssh, rspconfig does if ($switchtype =~ /IBSwitch::Mellanox/i) { - my $rsp = {}; - $rsp->{error}->[0] = - "You do not use xdsh -K to setup the Mellanox switch ssh keys. Use rspconfig. See man page for rspconfig option sshcfg={enable|disable}."; + my $rsp = {}; + $rsp->{error}->[0] = +"You do not use xdsh -K to setup the Mellanox switch ssh keys. Use rspconfig. See man page for rspconfig option sshcfg={enable|disable}."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4131,13 +4154,13 @@ sub parse_and_run_dsh # This is checked for in the client code. # DSH_REMOTE_PASSWORD env variable must be set to the correct # password for the key update. This was setup in xdsh client - # frontend. + # frontend. if (!($ENV{'DSH_REMOTE_PASSWORD'})) { my $rsp = {}; $rsp->{error}->[0] = - "User password for ssh key exchange has not been supplied.\n Cannot complete the -K command\n"; +"User password for ssh key exchange has not been supplied.\n Cannot complete the -K command\n"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4147,7 +4170,7 @@ sub parse_and_run_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Current Userid has not been supplied.\n Cannot complete the -K command.\n"; +"Current Userid has not been supplied.\n Cannot complete the -K command.\n"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4158,7 +4181,7 @@ sub parse_and_run_dsh { my $rsp = {}; $rsp->{error}->[0] = - "Logon Userid has not been supplied.\n Cannot complete the -K command.\n"; +"Logon Userid has not been supplied.\n Cannot complete the -K command.\n"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4169,12 +4192,12 @@ sub parse_and_run_dsh # if current_userid ne touserid then current_userid # must be root - if ( ($current_userid ne $to_userid) + if (($current_userid ne $to_userid) && ($current_userid ne "root")) { my $rsp = {}; $rsp->{error}->[0] = - "When touserid:$to_userid is not the same as the current user:$current_userid. The command must be run by root id."; +"When touserid:$to_userid is not the same as the current user:$current_userid. The command must be run by root id."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4188,12 +4211,13 @@ sub parse_and_run_dsh my $devicename = $options{'devicetype'}; $devicename =~ s/::/\//g; my $devicepath = "/var/opt/xcat/" . $devicename . "/config"; - # go to backup directory if the config file + + # go to backup directory if the config file # cannot be found under /var/opt/xcat/... - if (! -e $devicepath) { - $devicepath="$::XCATROOT/share/xcat/devicetype/" . $devicename . "/config"; - } - if (-e $devicepath) + if (!-e $devicepath) { + $devicepath = "$::XCATROOT/share/xcat/devicetype/" . $devicename . "/config"; + } + if (-e $devicepath) { my $deviceconf = get_config($devicepath); @@ -4206,7 +4230,7 @@ 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 = xCAT::TableUtils->setupSSH($options{'nodes'}, $options{'timeout'}); my @results = "return code = $rc"; return (@results); } @@ -4287,7 +4311,7 @@ sub usage_dcp my $usagemsg5c = " xdcp <-i imagepath> -F "; my $usagemsg5d = "[-o options]"; - my $usagemsg .= $usagemsg1 .= $usagemsg2 .= $usagemsg3 .= $usagemsg4 .= + my $usagemsg .= $usagemsg1 .= $usagemsg2 .= $usagemsg3 .= $usagemsg4 .= $usagemsg5 .= $usagemsg5a .= $usagemsg5b .= $usagemsg5c .= $usagemsg5d; if ($::CALLBACK) @@ -4365,29 +4389,29 @@ sub parse_and_run_dcp } if ( !GetOptions( - 'f|fanout=i' => \$options{'fanout'}, - 'F|File=s' => \$options{'File'}, - 'h|help' => \$options{'help'}, - 'l|user=s' => \$options{'user'}, - 'm|monitor' => \$options{'monitor'}, - 'o|node-options=s' => \$options{'node-options'}, - 'q|show-config' => \$options{'show-config'}, - 'p|preserve' => \$options{'preserve'}, - 'r|c|node-rcp=s' => \$options{'node-rcp'}, - 'i|rootimg=s' => \$options{'rootimg'}, - 's' => \$options{'rsyncSN'}, - 't|timeout=i' => \$options{'timeout'}, - 'v|verify' => \$options{'verify'}, - 'B|bypass' => \$options{'bypass'}, - 'Q|silent' => \$options{'silent'}, - 'P|pull' => \$options{'pull'}, - 'R|recursive' => \$options{'recursive'}, - 'T|trace' => \$options{'trace'}, - 'V|version' => \$options{'version'}, - 'devicetype=s' => \$options{'devicetype'}, - 'nodestatus|nodestatus' => \$options{'nodestatus'}, - 'sudo|sudo' => \$options{'sudo'}, - 'X:s' => \$options{'ignore_env'} + 'f|fanout=i' => \$options{'fanout'}, + 'F|File=s' => \$options{'File'}, + 'h|help' => \$options{'help'}, + 'l|user=s' => \$options{'user'}, + 'm|monitor' => \$options{'monitor'}, + 'o|node-options=s' => \$options{'node-options'}, + 'q|show-config' => \$options{'show-config'}, + 'p|preserve' => \$options{'preserve'}, + 'r|c|node-rcp=s' => \$options{'node-rcp'}, + 'i|rootimg=s' => \$options{'rootimg'}, + 's' => \$options{'rsyncSN'}, + 't|timeout=i' => \$options{'timeout'}, + 'v|verify' => \$options{'verify'}, + 'B|bypass' => \$options{'bypass'}, + 'Q|silent' => \$options{'silent'}, + 'P|pull' => \$options{'pull'}, + 'R|recursive' => \$options{'recursive'}, + 'T|trace' => \$options{'trace'}, + 'V|version' => \$options{'version'}, + 'devicetype=s' => \$options{'devicetype'}, + 'nodestatus|nodestatus' => \$options{'nodestatus'}, + 'sudo|sudo' => \$options{'sudo'}, + 'X:s' => \$options{'ignore_env'} ) ) { @@ -4420,7 +4444,7 @@ sub parse_and_run_dcp { my $rsp = {}; $rsp->{error}->[0] = - "Input noderange:@$nodes and any other xdsh flags or environment variables are not valid with -i flag."; +"Input noderange:@$nodes and any other xdsh flags or environment variables are not valid with -i flag."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4436,7 +4460,7 @@ sub parse_and_run_dcp if ($options{'version'}) { my $version = xCAT::Utils->Version(); - my $rsp = {}; + my $rsp = {}; $rsp->{data}->[0] = "$version"; xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); return (0); @@ -4462,7 +4486,7 @@ sub parse_and_run_dcp { # File not given my $rsp = {}; $rsp->{error}->[0] = - "If -i option is use, then the -F option must input the file list.\nThe file will contain the list of files to rsync to the image."; +"If -i option is use, then the -F option must input the file list.\nThe file will contain the list of files to rsync to the image."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4473,7 +4497,7 @@ sub parse_and_run_dcp { my $rsp = {}; $rsp->{error}->[0] = - "If -F option is use, then -r is invalid. The command will always the rsync using ssh."; +"If -F option is use, then -r is invalid. The command will always the rsync using ssh."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4511,10 +4535,10 @@ sub parse_and_run_dcp my $remotecopycommand = $options{'node-rcp'}; if ($options{'node-rcp'} && (!-f $options{'node-rcp'} || !-x $options{'node-rcp'})) - { - my $rsp={}; + { + my $rsp = {}; $rsp->{error}->[0] = - "Remote command: $remotecopycommand does not exist or is not executable."; +"Remote command: $remotecopycommand does not exist or is not executable."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; } @@ -4566,36 +4590,38 @@ sub parse_and_run_dcp } my $synfiledir; my $nodesyncfiledir; + # set default sync dir on service node and node # right now setting the nodes and sn syncfiledir the same, leaving - # the possibility that one day we may want them to be different - $synfiledir = "/var/xcat/syncfiles"; + # the possibility that one day we may want them to be different + $synfiledir = "/var/xcat/syncfiles"; $nodesyncfiledir = "/var/xcat/node/syncfiles"; # get the directory on the servicenode to put the rsync files in my @syndir = xCAT::TableUtils->get_site_attribute("SNsyncfiledir"); if ($syndir[0]) { - $synfiledir = $syndir[0]; + $synfiledir = $syndir[0]; } + # get the directory on the node to put the rsync files in my @syndir = xCAT::TableUtils->get_site_attribute("nodesyncfiledir"); if ($syndir[0]) { - $nodesyncfiledir = $syndir[0]; + $nodesyncfiledir = $syndir[0]; } my $rc; my $syncfile; if ($options{'File'}) { - $syncfile = $options{'File'}; - if (!-f $options{'File'}) - { + $syncfile = $options{'File'}; + if (!-f $options{'File'}) + { my $rsp = (); $rsp->{error}->[0] = "File:$syncfile does not exist."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; - } + } } # if rsyncing the nodes or service nodes @@ -4609,38 +4635,41 @@ sub parse_and_run_dcp $::SYNCSN = 1; } - # the parsing of the file will fill in an array of postscripts + # the parsing of the file will fill in an array of postscripts # need to be run if the associated file is updated - @::postscripts=(); - @::alwayspostscripts=(); - @::appendlines=(); - @::mergelines=(); + @::postscripts = (); + @::alwayspostscripts = (); + @::appendlines = (); + @::mergelines = (); if (xCAT::Utils->isServiceNode()) { # running on service node $rc = &parse_rsync_input_file_on_SN(\@nodelist, \%options, $syncfile, - $synfiledir,$nodesyncfiledir); + $synfiledir, $nodesyncfiledir); } else { # running on MN $rc = &parse_rsync_input_file_on_MN(\@nodelist, \%options, $syncfile, - $::SYNCSN, $synfiledir,$nodesyncfiledir); - # build a temporary syncfile for the node's synclist - if ($::SYNCSN ==1) { # syncing a servicenode - # we need to make sure the latest is on the servicenode - # for running of the syncfiles postscript, which only pulls - # from the service node - my $tmpsyncfile="/tmp/xdcpsynclist.$$"; - my $syncline = "$syncfile -> $syncfile"; + $::SYNCSN, $synfiledir, $nodesyncfiledir); + + # build a temporary syncfile for the node's synclist + if ($::SYNCSN == 1) { # syncing a servicenode + # we need to make sure the latest is on the servicenode + # for running of the syncfiles postscript, which only pulls + # from the service node + my $tmpsyncfile = "/tmp/xdcpsynclist.$$"; + my $syncline = "$syncfile -> $syncfile"; open(FILE, ">$tmpsyncfile") or die "cannot open file $tmpsyncfile\n"; print FILE " $syncline"; close FILE; + # now put the original syncfile on the queue to sync to the SN's $rc = - &parse_rsync_input_file_on_MN(\@nodelist, \%options,$tmpsyncfile, - $::SYNCSN, $synfiledir,$nodesyncfiledir); + &parse_rsync_input_file_on_MN(\@nodelist, \%options, $tmpsyncfile, + $::SYNCSN, $synfiledir, $nodesyncfiledir); + # cleanup my $cmd = "rm $tmpsyncfile"; my @output = xCAT::Utils->runcmd($cmd, 0); @@ -4650,12 +4679,12 @@ sub parse_and_run_dcp $rsp->{error}->[0] = "Command: $cmd failed."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } - } + } } if ($rc == 1) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "Error parsing the rsync file:$syncfile."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4666,7 +4695,7 @@ sub parse_and_run_dcp { if (@ARGV < 1) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "Missing file arguments"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4676,7 +4705,7 @@ sub parse_and_run_dcp { if ($options{'pull'}) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "Missing target_path"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4687,7 +4716,7 @@ sub parse_and_run_dcp # HERE:only one line of input source and target in that line # such as xdcp -R " /test/* /test" my $tmparg = pop @ARGV; - my ($src,$tgt) = split " ", $tmparg; + my ($src, $tgt) = split " ", $tmparg; $options{'target'} = $tgt; $options{'source'} = join $::__DCP_DELIM, $src; } @@ -4695,7 +4724,7 @@ sub parse_and_run_dcp elsif ($options{'pull'} && (@ARGV > 2)) { - my $rsp={}; + my $rsp = {}; $rsp->{error}->[0] = "Cannot pull more than one file from targets."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); return; @@ -4703,7 +4732,7 @@ sub parse_and_run_dcp else { - # Get the source and the target + # Get the source and the target $options{'target'} = pop @ARGV; $options{'source'} = join $::__DCP_DELIM, @ARGV; } @@ -4714,49 +4743,51 @@ sub parse_and_run_dcp # HERE: Run xdcp LKV @results = xCAT::DSHCLI->runDcp_api(\%options, 0); $::FAILED_NODES = $::RUNCMD_RC; - + # if not just syncing the service node SNsyncfiledir directory, # @::postscripts should be empty in this case anyway - # if postscripts to run after rsync, process the output and + # if postscripts to run after rsync, process the output and # create the xdsh command to run the ones needed - my @results2; - my @results3; - my @results4; - my @results5; + my @results2; + my @results3; + my @results4; + my @results5; my $ranpostscripts; my $ranappendscripts; my $ranmergescripts; # if we were called with runxcmd, like by updatenode - # need to save the runxcmd buffer + # need to save the runxcmd buffer # $::xcmd_outref my $save_xcmd_outref; - if ($::xcmd_outref) { # this means we were called with runxcmd - $save_xcmd_outref = $::xcmd_outref; + if ($::xcmd_outref) { # this means we were called with runxcmd + $save_xcmd_outref = $::xcmd_outref; } if ((@::postscripts) && ($::SYNCSN == 0)) { - @results2 = &run_rsync_postscripts(\@results,$synfiledir,\%options); - $ranpostscripts=1; + @results2 = &run_rsync_postscripts(\@results, $synfiledir, \%options); + $ranpostscripts = 1; } if ((@::alwayspostscripts) && ($::SYNCSN == 0)) { - @results3 = &run_always_rsync_postscripts(\@nodelist,$synfiledir,\%options); + @results3 = &run_always_rsync_postscripts(\@nodelist, $synfiledir, \%options); } if (($::appendscript) && ($::SYNCSN == 0)) { - @results4 = &bld_and_run_append(\@nodelist,\@results,$synfiledir,$nodesyncfiledir,\%options); - $ranappendscripts=1; + @results4 = &bld_and_run_append(\@nodelist, \@results, $synfiledir, $nodesyncfiledir, \%options); + $ranappendscripts = 1; } if (($::mergescript) && ($::SYNCSN == 0)) { - @results5 = &bld_and_run_merge(\@nodelist,\@results,$synfiledir,$nodesyncfiledir,\%options); - $ranmergescripts=1; + @results5 = &bld_and_run_merge(\@nodelist, \@results, $synfiledir, $nodesyncfiledir, \%options); + $ranmergescripts = 1; } + # restore the runxcmd buffer - if ($save_xcmd_outref) { # this means we were called with runxcmd - $::xcmd_outref = $save_xcmd_outref; + if ($save_xcmd_outref) { # this means we were called with runxcmd + $::xcmd_outref = $save_xcmd_outref; } + # TODO, will we ever need to merge # if we ran a postscript and we were run - # using runxcmd, and there was previous output in the + # using runxcmd, and there was previous output in the # runxcmd buffer and we have output from the postscript # then we have to merge the outputs #if (($ranaps == 1) && ($save_xcmd_outref) && ($::xcmd_outref) ) { @@ -4764,32 +4795,33 @@ sub parse_and_run_dcp #} my @newresults; if (@results2) { - @newresults = (@results2); + @newresults = (@results2); } if (@results3) { - @newresults = (@newresults,@results3); + @newresults = (@newresults, @results3); } if (@results4) { - @newresults = (@newresults,@results3,@results4); + @newresults = (@newresults, @results3, @results4); } if (@results5) { - @newresults = (@newresults,@results3,@results4,@results5); + @newresults = (@newresults, @results3, @results4, @results5); } if (@newresults) { - if ($save_xcmd_outref) { # this means we were called with runxcmd - foreach my $line (@newresults) { - push @$::xcmd_outref,$line; + if ($save_xcmd_outref) { # this means we were called with runxcmd + foreach my $line (@newresults) { + push @$::xcmd_outref, $line; + } } - } - return (@newresults); + return (@newresults); } else { - # don't report other results for postscripts,appendscripts,mergescripts because - # you get all the rsync returned lines - if (($ranpostscripts == 0 ) && ($ranappendscripts == 0) - && ($ranmergescripts == 0)) { - return (@results); - } - } + + # don't report other results for postscripts,appendscripts,mergescripts because + # you get all the rsync returned lines + if (($ranpostscripts == 0) && ($ranappendscripts == 0) + && ($ranmergescripts == 0)) { + return (@results); + } + } } #------------------------------------------------------------------------------- @@ -4848,12 +4880,12 @@ sub rsync_to_image } # process no more lines, do not exec - # do not execute postscripts when syncing images - if (($line =~ /EXECUTE:/) || ($line =~ /EXECUTEALWAYS:/) - || ($line =~ /APPEND:/) || ($line =~ /MERGE:/)) - { # process no more lines - last; - } + # do not execute postscripts when syncing images + if (($line =~ /EXECUTE:/) || ($line =~ /EXECUTEALWAYS:/) + || ($line =~ /APPEND:/) || ($line =~ /MERGE:/)) + { # process no more lines + last; + } if ($line =~ /(.+) -> (.+)/) { my $imageupdatedir = $image; @@ -4987,203 +5019,212 @@ sub rsync_to_image sub parse_rsync_input_file_on_MN { use File::Basename; - my ($nodes, $options, $input_file, $rsyncSN, $syncdir,$nodesyncfiledir) = @_; - my @dest_host = @$nodes; + my ($nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir) = @_; + my @dest_host = @$nodes; $::process_line = 0; my $destfileisdir; - my $clause=0; - my $addmergescript =0; - my $addappendscript =0; + my $clause = 0; + my $addmergescript = 0; + my $addappendscript = 0; open(INPUTFILE, "< $input_file") || die "File $input_file does not exist\n"; + while (my $line = ) { chomp $line; - if (($line =~ /^#/) || ( $line =~ /^\s*$/ )) - # skip commments and blanks + if (($line =~ /^#/) || ($line =~ /^\s*$/)) + + # skip commments and blanks { next; } - # Determine if processing a clause or the synclist + + # Determine if processing a clause or the synclist if (($line =~ /EXECUTE:/) || ($line =~ /EXECUTEALWAYS:/) - || ($line =~ /APPEND:/) || ($line =~ /MERGE:/)) { - $clause=$line; - next; # get the content of the clause + || ($line =~ /APPEND:/) || ($line =~ /MERGE:/)) { + $clause = $line; + next; # get the content of the clause } + # processing a clause if (($clause =~ /APPEND:/) || ($clause =~ /EXECUTEALWAYS:/) || ($clause =~ /EXECUTE:/) || ($clause =~ /MERGE:/)) { if (($::SYNCSN == 1) && (($clause =~ /EXECUTEALWAYS:/) || - ($clause =~ /EXECUTE:/))) { - # for EXECUTE and EXECUTEALWAYS skip, if syncing SN only - next; - } else { # process the clause - if ($clause =~ /EXECUTE:/) { - push @::postscripts,$line; - } - if ($clause =~ /EXECUTEALWAYS:/) { - push @::alwayspostscripts,$line; - } - if ($clause =~ /APPEND:/) { - # location of the base append script - # for APPEND we have to sync the appendscript and the - # append file to the SN - my $onServiceNode=0; - my $syncappendscript=0; - &build_append_rsync($line,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncappendscript); - if ($::SYNCSN == 0) { - # this triggers the running of the appendscript - $::appendscript ="/opt/xcat/share/xcat/scripts/xdcpappend.sh"; + ($clause =~ /EXECUTE:/))) { + + # for EXECUTE and EXECUTEALWAYS skip, if syncing SN only + next; + } else { # process the clause + if ($clause =~ /EXECUTE:/) { + push @::postscripts, $line; + } + if ($clause =~ /EXECUTEALWAYS:/) { + push @::alwayspostscripts, $line; + } + if ($clause =~ /APPEND:/) { + + # location of the base append script + # for APPEND we have to sync the appendscript and the + # append file to the SN + my $onServiceNode = 0; + my $syncappendscript = 0; + &build_append_rsync($line, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncappendscript); + if ($::SYNCSN == 0) { + + # this triggers the running of the appendscript + $::appendscript = "/opt/xcat/share/xcat/scripts/xdcpappend.sh"; + } + + # add the append script to the sync + if ($addappendscript == 0) { # only add once + my $appscript = "/opt/xcat/share/xcat/scripts/xdcpappend.sh"; + my $appendscriptline = "$appscript -> $appscript"; + $syncappendscript = 1; # syncing the xdcpappend.sh script + &build_append_rsync($appendscriptline, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncappendscript); + $addappendscript = 1; + } + } # end APPEND clause + if ($clause =~ /MERGE:/) { + + # location of the base merge script + # for MERGE we have to sync the mergescript and the + # merge file to the SN + my $onServiceNode = 0; + my $syncmergescript = 0; + &build_merge_rsync($line, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncmergescript); + if ($::SYNCSN == 0) { + + # this triggers the running of the mergescript + $::mergescript = "/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; + } + + # add the merge script to the sync + if ($addmergescript == 0) { # only add once + my $mergescript = "/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; + my $mergescriptline = "$mergescript -> $mergescript"; + $syncmergescript = 1; # syncing the xdcpmerge.sh script + &build_merge_rsync($mergescriptline, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncmergescript); + $addmergescript = 1; + } + } # end MERGE clause + + } + } else { # not processing EXECUTE, EXECUTEALWAYS or APPEND + # otherwise it is just the synclist + # xCAT supports the syncfile format: + # file -> file + # file -> (noderange for permitted nodes) file + if ($line =~ /(.+) -> (.+)/ || $line =~ /(.+) -> +\((.+)\) +(.+)/) { + $::process_line = 1; + my $src_file; + my $dest_file; + my $dest_node; + my @dest_nodes; + if ($line =~ /(.+) -> +\((.+)\) +(.+)/) { + $src_file = $1; + $dest_node = $2; + $dest_file = $3; + } elsif ($line =~ /(.+) -> (.+)/) { + $src_file = $1; + $dest_file = $2; } - # add the append script to the sync - if ($addappendscript == 0) { # only add once - my $appscript ="/opt/xcat/share/xcat/scripts/xdcpappend.sh"; - my $appendscriptline = "$appscript -> $appscript"; - $syncappendscript=1; # syncing the xdcpappend.sh script - &build_append_rsync($appendscriptline,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncappendscript); - $addappendscript=1; - } - } # end APPEND clause - if ($clause =~ /MERGE:/) { - # location of the base merge script - # for MERGE we have to sync the mergescript and the - # merge file to the SN - my $onServiceNode=0; - my $syncmergescript=0; - &build_merge_rsync($line,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncmergescript); - if ($::SYNCSN == 0) { - # this triggers the running of the mergescript - $::mergescript ="/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; + # get all the permitted nodes for the line + $dest_node =~ s/\s//g; + if ($dest_node) { + @dest_nodes = noderange($dest_node); } - - # add the merge script to the sync - if ($addmergescript == 0) { # only add once - my $mergescript ="/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; - my $mergescriptline = "$mergescript -> $mergescript"; - $syncmergescript=1; # syncing the xdcpmerge.sh script - &build_merge_rsync($mergescriptline,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncmergescript); - $addmergescript=1; + $dest_file =~ s/[\s;]//g; + my @srcfiles = (split ' ', $src_file); + my $arraysize = scalar @srcfiles; # of source files on the line + my $dest_dir; + $destfileisdir = 0; + if ($dest_file =~ /\/$/) + { # ends in / + $destfileisdir = 1; } - } # end MERGE clause - - } - } else { # not processing EXECUTE, EXECUTEALWAYS or APPEND - # otherwise it is just the synclist - # xCAT supports the syncfile format: - # file -> file - # file -> (noderange for permitted nodes) file - if ($line =~ /(.+) -> (.+)/ || $line =~ /(.+) -> +\((.+)\) +(.+)/) { - $::process_line = 1; - my $src_file; - my $dest_file; - my $dest_node; - my @dest_nodes; - if ($line =~ /(.+) -> +\((.+)\) +(.+)/) { - $src_file = $1; - $dest_node = $2; - $dest_file = $3; - } elsif ($line =~ /(.+) -> (.+)/) { - $src_file = $1; - $dest_file = $2; - } - # get all the permitted nodes for the line - $dest_node =~ s/\s//g; - if ($dest_node) { - @dest_nodes = noderange($dest_node); - } - $dest_file =~ s/[\s;]//g; - my @srcfiles = (split ' ', $src_file); - my $arraysize = scalar @srcfiles; # of source files on the line - my $dest_dir; - $destfileisdir = 0; - if ($dest_file =~ /\/$/) - { # ends in / - $destfileisdir = 1; - } - - # if more than one file on the line then - # or the destination file ends in / - # /tmp/file1 -> /tmp/ - # the destination is a directory - # else assume a file - if (($arraysize > 1) || ($destfileisdir == 1)) - { - $dest_dir = $dest_file; - $destfileisdir = 1; - } - else # get the directory name - { # strip off the file - $dest_dir = dirname($dest_file); - } - $dest_dir =~ s/\s*//g; #remove blanks - - foreach my $target_node (@dest_host) - { - # skip the node if it's NOT in the permitted list - if ($dest_node && ! grep /^$target_node$/, @dest_nodes) { - next; - } - $$options{'destDir_srcFile'}{$target_node} ||= {}; - - # for each file on the line - foreach my $srcfile (@srcfiles) + # if more than one file on the line then + # or the destination file ends in / + # /tmp/file1 -> /tmp/ + # the destination is a directory + # else assume a file + if (($arraysize > 1) || ($destfileisdir == 1)) { + $dest_dir = $dest_file; + $destfileisdir = 1; + } + else # get the directory name + { # strip off the file + $dest_dir = dirname($dest_file); + } + $dest_dir =~ s/\s*//g; #remove blanks - # if syncing the Service Node, file goes to the same place - # where it was on the MN off the syncdir on the service - # node - if ($rsyncSN == 1) - { # syncing the SN - $dest_dir = $syncdir; # the SN sync dir - $dest_dir .= dirname($srcfile); - $dest_dir =~ s/\s*//g; #remove blanks + foreach my $target_node (@dest_host) + { + # skip the node if it's NOT in the permitted list + if ($dest_node && !grep /^$target_node$/, @dest_nodes) { + next; } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - {}; + $$options{'destDir_srcFile'}{$target_node} ||= {}; - # can be full file name for destination or just the - # directory name - my $src_basename = basename($srcfile); # get file name - - my $dest_basename; # destination file name - # determine path to the file - if ($destfileisdir == 1) # if a directory + # for each file on the line + foreach my $srcfile (@srcfiles) { - $dest_basename = $src_basename; - } - else - { - $dest_basename = basename($dest_file); - } - if ($rsyncSN == 1) # dest file will be the same as src - { # syncing the SN - $dest_basename = $src_basename; - } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - $dest_basename =~ s/[\s;]//g; - # if the filename will be the same at the destination - if ($src_basename eq $dest_basename) - { - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'same_dest_name'} ||= []; - push @{$$options{'destDir_srcFile'}{$target_node} - {$dest_dir}{'same_dest_name'}}, $srcfile; - } - else # changing file names - { - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'diff_dest_name'} ||= {}; - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'diff_dest_name'}{$srcfile} = $dest_basename; - } + # if syncing the Service Node, file goes to the same place + # where it was on the MN off the syncdir on the service + # node + if ($rsyncSN == 1) + { # syncing the SN + $dest_dir = $syncdir; # the SN sync dir + $dest_dir .= dirname($srcfile); + $dest_dir =~ s/\s*//g; #remove blanks + } + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + {}; - } # end of each srcfile - } # end of each node - } # if synclist line - } # end processing clauses EXECUTE, APPEND, etc - } #end while processing file + # can be full file name for destination or just the + # directory name + my $src_basename = basename($srcfile); # get file name + + my $dest_basename; # destination file name + # determine path to the file + if ($destfileisdir == 1) # if a directory + { + $dest_basename = $src_basename; + } + else + { + $dest_basename = basename($dest_file); + } + if ($rsyncSN == 1) # dest file will be the same as src + { # syncing the SN + $dest_basename = $src_basename; + } + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + $dest_basename =~ s/[\s;]//g; + + # if the filename will be the same at the destination + if ($src_basename eq $dest_basename) + { + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'same_dest_name'} ||= []; + push @{ $$options{'destDir_srcFile'}{$target_node} + {$dest_dir}{'same_dest_name'} }, $srcfile; + } + else # changing file names + { + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'diff_dest_name'} ||= {}; + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'diff_dest_name'}{$srcfile} = $dest_basename; + } + + } # end of each srcfile + } # end of each node + } # if synclist line + } # end processing clauses EXECUTE, APPEND, etc + } #end while processing file close INPUTFILE; if ($::process_line == 0) { # no valid lines in the file @@ -5194,10 +5235,11 @@ sub parse_rsync_input_file_on_MN } else { - $$options{'nodes'} = join ',', keys %{$$options{'destDir_srcFile'}}; + $$options{'nodes'} = join ',', keys %{ $$options{'destDir_srcFile'} }; } return 0; } + #------------------------------------------------------------------------------- =head3 @@ -5231,72 +5273,74 @@ sub parse_rsync_input_file_on_MN #------------------------------------------------------------------------------- -sub build_append_rsync +sub build_append_rsync { use File::Basename; - my ($line,$nodes, $options,$input_file, $rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncappendscript) = @_; + my ($line, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncappendscript) = @_; my @dest_host = @$nodes; my $process_line = 0; my $destfileisdir; + # add append directory to the base nodesyncfiledir $nodesyncfiledir .= "/append"; - + if ($line =~ /(.+) -> (.+)/) { - $::process_line = 1; - if ($syncappendscript == 0) { # don't add the xdcpappend.sh line - push @::appendlines,$line; + $::process_line = 1; + if ($syncappendscript == 0) { # don't add the xdcpappend.sh line + push @::appendlines, $line; + } + my $src_file = $1; # append file left of arror + my $orig_src_file = $1; # append file left of arror + # it will be sync'd to $nodesyncfiledir/$append_file + my $dest_file = $nodesyncfiledir; + $dest_file .= $src_file; + $dest_file =~ s/[\s;]//g; + my $dest_dir = dirname($dest_file); + $dest_dir =~ s/\s*//g; #remove blanks + + foreach my $target_node (@dest_host) + { + $$options{'destDir_srcFile'}{$target_node} ||= {}; + + # if syncing the Service Node, file goes to the same place + # where it was on the MN off the syncdir on the service + # node + if ($rsyncSN == 1) + { # syncing the SN + $dest_dir = $syncdir; # the SN sync dir + $dest_dir .= dirname($src_file); + $dest_dir =~ s/\s*//g; #remove blanks } - my $src_file = $1; # append file left of arror - my $orig_src_file = $1; # append file left of arror - # it will be sync'd to $nodesyncfiledir/$append_file - my $dest_file = $nodesyncfiledir; - $dest_file .= $src_file; - $dest_file =~ s/[\s;]//g; - my $dest_dir = dirname($dest_file); - $dest_dir =~ s/\s*//g; #remove blanks + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + {}; - foreach my $target_node (@dest_host) - { - $$options{'destDir_srcFile'}{$target_node} ||= {}; + my $src_basename = basename($src_file); # get file name + # if this is syncing from the Service Node then we have + # to pick up files from /var/xcat/syncfiles... + if ($onServiceNode == 1) { + my $newsrcfile = $syncdir; # add SN syndir on front + $newsrcfile .= $orig_src_file; + $src_file = $newsrcfile; + } - # if syncing the Service Node, file goes to the same place - # where it was on the MN off the syncdir on the service - # node - if ($rsyncSN == 1) - { # syncing the SN - $dest_dir = $syncdir; # the SN sync dir - $dest_dir .= dirname($src_file); - $dest_dir =~ s/\s*//g; #remove blanks - } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - {}; + # destination file name + my $dest_basename = basename($dest_file); + if ($rsyncSN == 1) # dest file will be the same as src + { # syncing the SN + $dest_basename = $src_basename; + } + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + $dest_basename =~ s/[\s;]//g; - my $src_basename = basename($src_file); # get file name - # if this is syncing from the Service Node then we have - # to pick up files from /var/xcat/syncfiles... - if ($onServiceNode == 1) { - my $newsrcfile = $syncdir; # add SN syndir on front - $newsrcfile .= $orig_src_file; - $src_file=$newsrcfile; - } - # destination file name - my $dest_basename = basename($dest_file); - if ($rsyncSN == 1) # dest file will be the same as src - { # syncing the SN - $dest_basename = $src_basename; - } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - $dest_basename =~ s/[\s;]//g; + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'same_dest_name'} ||= []; + push @{ $$options{'destDir_srcFile'}{$target_node} + {$dest_dir}{'same_dest_name'} }, $src_file; - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'same_dest_name'} ||= []; - push @{$$options{'destDir_srcFile'}{$target_node} - {$dest_dir}{'same_dest_name'}}, $src_file; - - } # end of each node - } # if synclist line + } # end of each node + } # if synclist line if ($::process_line == 0) { # no valid lines in the file my $rsp = {}; @@ -5306,10 +5350,11 @@ sub build_append_rsync } else { - $$options{'nodes'} = join ',', keys %{$$options{'destDir_srcFile'}}; + $$options{'nodes'} = join ',', keys %{ $$options{'destDir_srcFile'} }; } return 0; } + #------------------------------------------------------------------------------- =head3 @@ -5341,75 +5386,78 @@ sub build_append_rsync #------------------------------------------------------------------------------- -sub build_merge_rsync +sub build_merge_rsync { use File::Basename; - my ($line,$nodes, $options,$input_file, $rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncmergescript) = @_; + my ($line, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncmergescript) = @_; my @dest_host = @$nodes; my $process_line = 0; my $destfileisdir; + # add merge directory to the base nodesyncfiledir - if ($syncmergescript == 1) { # syncing the xdcpmerge.sh - $nodesyncfiledir .= "/merge"; - } else { # all the other merge scripts - $nodesyncfiledir .= "/merge/mergefiles"; + if ($syncmergescript == 1) { # syncing the xdcpmerge.sh + $nodesyncfiledir .= "/merge"; + } else { # all the other merge scripts + $nodesyncfiledir .= "/merge/mergefiles"; } if ($line =~ /(.+) -> (.+)/) { - $::process_line = 1; - if ($syncmergescript == 0) { # don't add the xdcpmerge.sh line - push @::mergelines,$line; + $::process_line = 1; + if ($syncmergescript == 0) { # don't add the xdcpmerge.sh line + push @::mergelines, $line; + } + my $src_file = $1; # merge file left of arrow + my $orig_src_file = $1; + + # it will be sync'd to $nodesyncfiledir/$merge_file + my $dest_file = $nodesyncfiledir; + $dest_file .= $src_file; + $dest_file =~ s/[\s;]//g; + my $dest_dir = dirname($dest_file); + $dest_dir =~ s/\s*//g; #remove blanks + + foreach my $target_node (@dest_host) + { + $$options{'destDir_srcFile'}{$target_node} ||= {}; + + # if syncing the Service Node, file goes to the same place + # where it was on the MN off the syncdir on the service + # node + if ($rsyncSN == 1) + { # syncing the SN + $dest_dir = $syncdir; # the SN sync dir + $dest_dir .= dirname($src_file); + $dest_dir =~ s/\s*//g; #remove blanks } - my $src_file = $1; # merge file left of arrow - my $orig_src_file = $1; - # it will be sync'd to $nodesyncfiledir/$merge_file - my $dest_file = $nodesyncfiledir; - $dest_file .= $src_file; - $dest_file =~ s/[\s;]//g; - my $dest_dir = dirname($dest_file); - $dest_dir =~ s/\s*//g; #remove blanks + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + {}; - foreach my $target_node (@dest_host) - { - $$options{'destDir_srcFile'}{$target_node} ||= {}; + my $src_basename = basename($src_file); # get file name + # if this is syncing from the Service Node then we have + # to pick up files from /var/xcat/syncfiles... + if ($onServiceNode == 1) { + my $newsrcfile = $syncdir; # add SN syndir on front + $newsrcfile .= $orig_src_file; + $src_file = $newsrcfile; + } - # if syncing the Service Node, file goes to the same place - # where it was on the MN off the syncdir on the service - # node - if ($rsyncSN == 1) - { # syncing the SN - $dest_dir = $syncdir; # the SN sync dir - $dest_dir .= dirname($src_file); - $dest_dir =~ s/\s*//g; #remove blanks - } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - {}; + # destination file name + my $dest_basename = basename($dest_file); + if ($rsyncSN == 1) # dest file will be the same as src + { # syncing the SN + $dest_basename = $src_basename; + } + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + $dest_basename =~ s/[\s;]//g; - my $src_basename = basename($src_file); # get file name - # if this is syncing from the Service Node then we have - # to pick up files from /var/xcat/syncfiles... - if ($onServiceNode == 1) { - my $newsrcfile = $syncdir; # add SN syndir on front - $newsrcfile .= $orig_src_file; - $src_file=$newsrcfile; - } - # destination file name - my $dest_basename = basename($dest_file); - if ($rsyncSN == 1) # dest file will be the same as src - { # syncing the SN - $dest_basename = $src_basename; - } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - $dest_basename =~ s/[\s;]//g; + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'same_dest_name'} ||= []; + push @{ $$options{'destDir_srcFile'}{$target_node} + {$dest_dir}{'same_dest_name'} }, $src_file; - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'same_dest_name'} ||= []; - push @{$$options{'destDir_srcFile'}{$target_node} - {$dest_dir}{'same_dest_name'}}, $src_file; - - } # end of each node - } # if synclist line + } # end of each node + } # if synclist line if ($::process_line == 0) { # no valid lines in the file my $rsp = {}; @@ -5419,10 +5467,11 @@ sub build_merge_rsync } else { - $$options{'nodes'} = join ',', keys %{$$options{'destDir_srcFile'}}; + $$options{'nodes'} = join ',', keys %{ $$options{'destDir_srcFile'} }; } return 0; } + #------------------------------------------------------------------------------- =head3 @@ -5491,156 +5540,164 @@ sub build_merge_rsync sub parse_rsync_input_file_on_SN { use File::Basename; - my ($nodes, $options, $input_file, $syncdir,$nodesyncfiledir) = @_; + my ($nodes, $options, $input_file, $syncdir, $nodesyncfiledir) = @_; my @dest_host = @$nodes; my $process_line = 0; my $destfileisdir; my $rsyncSN; - my $clause=0; + my $clause = 0; open(INPUTFILE, "< $input_file") || die "File $input_file does not exist\n"; + while (my $line = ) { chomp $line; - if (($line =~ /^#/) || ( $line =~ /^\s*$/ )) - # skip commments and blanks + if (($line =~ /^#/) || ($line =~ /^\s*$/)) + + # skip commments and blanks { next; } + # Determine if processing a clause or the synclist if (($line =~ /EXECUTE:/) || ($line =~ /EXECUTEALWAYS:/) - || ($line =~ /APPEND:/) || ($line =~ /MERGE:/)) { - $clause=$line; - next; # get the content of the clause + || ($line =~ /APPEND:/) || ($line =~ /MERGE:/)) { + $clause = $line; + next; # get the content of the clause } + # processing a clause if (($clause =~ /APPEND:/) || ($clause =~ /MERGE:/) || ($clause =~ /EXECUTEALWAYS:/) || ($clause =~ /EXECUTE:/)) { if (($::SYNCSN == 1) && (($clause =~ /EXECUTEALWAYS:/) || - ($clause =~ /EXECUTE:/))) { # skip, if syncing SN only - next; - } else { # process the clause - if ($clause =~ /EXECUTE:/) { - push @::postscripts,$line; - } - if ($clause =~ /EXECUTEALWAYS:/) { - push @::alwayspostscripts,$line; - } - if ($clause =~ /APPEND:/) { - $process_line = 1; - my $onServiceNode=1; - my $syncappendscript=0; - &build_append_rsync($line,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncappendscript); - if ($::SYNCSN == 0) { - # this triggers the running of the appendscript - $::appendscript ="/opt/xcat/share/xcat/scripts/xdcpappend.sh"; + ($clause =~ /EXECUTE:/))) { # skip, if syncing SN only + next; + } else { # process the clause + if ($clause =~ /EXECUTE:/) { + push @::postscripts, $line; } - # add the append script to the sync - my $appscript ="/opt/xcat/share/xcat/scripts/xdcpappend.sh"; - my $appendscriptline = "$appscript -> $appscript"; - $syncappendscript=1; # syncing the xdcpappend.sh script - &build_append_rsync($appendscriptline,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncappendscript); - } - if ($clause =~ /MERGE:/) { - $process_line = 1; - my $onServiceNode=1; - my $syncmergescript=0; - &build_merge_rsync($line,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncmergescript); - if ($::SYNCSN == 0) { - # this triggers the running of the mergescript - $::mergescript ="/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; + if ($clause =~ /EXECUTEALWAYS:/) { + push @::alwayspostscripts, $line; } - # add the merge script to the sync - my $appscript ="/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; - my $mergescriptline = "$appscript -> $appscript"; - $syncmergescript=1; # syncing the xdcpmerge.sh script - &build_merge_rsync($mergescriptline,$nodes, $options, $input_file,$rsyncSN, $syncdir,$nodesyncfiledir,$onServiceNode,$syncmergescript); - } - - } - } else { # not processing EXECUTE, EXECUTEALWAYS or APPEND - # otherwise it is just the synclist + if ($clause =~ /APPEND:/) { + $process_line = 1; + my $onServiceNode = 1; + my $syncappendscript = 0; + &build_append_rsync($line, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncappendscript); + if ($::SYNCSN == 0) { - if ($line =~ /(.+) -> (.+)/) - { - $process_line = 1; - my $src_file = $1; - my $dest_file = $2; - $dest_file =~ s/[\s;]//g; # remove blanks + # this triggers the running of the appendscript + $::appendscript = "/opt/xcat/share/xcat/scripts/xdcpappend.sh"; + } + + # add the append script to the sync + my $appscript = "/opt/xcat/share/xcat/scripts/xdcpappend.sh"; + my $appendscriptline = "$appscript -> $appscript"; + $syncappendscript = 1; # syncing the xdcpappend.sh script + &build_append_rsync($appendscriptline, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncappendscript); + } + if ($clause =~ /MERGE:/) { + $process_line = 1; + my $onServiceNode = 1; + my $syncmergescript = 0; + &build_merge_rsync($line, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncmergescript); + if ($::SYNCSN == 0) { + + # this triggers the running of the mergescript + $::mergescript = "/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; + } + + # add the merge script to the sync + my $appscript = "/opt/xcat/share/xcat/scripts/xdcpmerge.sh"; + my $mergescriptline = "$appscript -> $appscript"; + $syncmergescript = 1; # syncing the xdcpmerge.sh script + &build_merge_rsync($mergescriptline, $nodes, $options, $input_file, $rsyncSN, $syncdir, $nodesyncfiledir, $onServiceNode, $syncmergescript); + } - # see if destination is a directory - $destfileisdir = 0; - if ($dest_file =~ /\/$/) - { # ends in / - $destfileisdir = 1; } - my @srcfiles = (split ' ', $src_file); - my $arraysize = scalar @srcfiles; # of source files on the line - my $dest_dir; + } else { # not processing EXECUTE, EXECUTEALWAYS or APPEND + # otherwise it is just the synclist - # if only more than one file on the line or ends in / - # then the destination is a directory - # else a file, - if (($arraysize > 1) || ($destfileisdir == 1)) + if ($line =~ /(.+) -> (.+)/) { - $dest_dir = $dest_file; - $destfileisdir = 1; - } - else # a file path - { - $dest_dir = dirname($dest_file); - } - $dest_dir =~ s/\s*//g; #remove blanks + $process_line = 1; + my $src_file = $1; + my $dest_file = $2; + $dest_file =~ s/[\s;]//g; # remove blanks - foreach my $target_node (@dest_host) - { - $$options{'destDir_srcFile'}{$target_node} ||= {}; + # see if destination is a directory + $destfileisdir = 0; + if ($dest_file =~ /\/$/) + { # ends in / + $destfileisdir = 1; + } + my @srcfiles = (split ' ', $src_file); + my $arraysize = scalar @srcfiles; # of source files on the line + my $dest_dir; - # for each file on the line - foreach my $srcfile (@srcfiles) + # if only more than one file on the line or ends in / + # then the destination is a directory + # else a file, + if (($arraysize > 1) || ($destfileisdir == 1)) { - my $newsrcfile = $syncdir; # add syndir on front - $newsrcfile .= $srcfile; - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - {}; + $dest_dir = $dest_file; + $destfileisdir = 1; + } + else # a file path + { + $dest_dir = dirname($dest_file); + } + $dest_dir =~ s/\s*//g; #remove blanks - # can be full file name for destination or just the - # directory name. For source must be full path - my $src_basename = basename($newsrcfile); # get file name + foreach my $target_node (@dest_host) + { + $$options{'destDir_srcFile'}{$target_node} ||= {}; - my $dest_basename; # destination file name - if ($destfileisdir == 1) # is a directory + # for each file on the line + foreach my $srcfile (@srcfiles) { - $dest_basename = $src_basename; - } - else - { - $dest_basename = basename($dest_file); - } - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= - $dest_basename =~ s/[\s;]//g; + my $newsrcfile = $syncdir; # add syndir on front + $newsrcfile .= $srcfile; + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + {}; - # if the filename will be the same at the destination - if ($src_basename eq $dest_basename) - { - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'same_dest_name'} ||= []; - push @{$$options{'destDir_srcFile'}{$target_node} - {$dest_dir}{'same_dest_name'}}, $newsrcfile; - } - else # changing file names - { - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'diff_dest_name'} ||= {}; - $$options{'destDir_srcFile'}{$target_node}{$dest_dir} - {'diff_dest_name'}{$newsrcfile} = $dest_basename; - } + # can be full file name for destination or just the + # directory name. For source must be full path + my $src_basename = basename($newsrcfile); # get file name - } # end of srcfile - } # end of each node - } # end of synclist - }# end processing clauses EXECUTE, APPEND, etc - } #end of processing file + my $dest_basename; # destination file name + if ($destfileisdir == 1) # is a directory + { + $dest_basename = $src_basename; + } + else + { + $dest_basename = basename($dest_file); + } + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} ||= + $dest_basename =~ s/[\s;]//g; + + # if the filename will be the same at the destination + if ($src_basename eq $dest_basename) + { + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'same_dest_name'} ||= []; + push @{ $$options{'destDir_srcFile'}{$target_node} + {$dest_dir}{'same_dest_name'} }, $newsrcfile; + } + else # changing file names + { + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'diff_dest_name'} ||= {}; + $$options{'destDir_srcFile'}{$target_node}{$dest_dir} + {'diff_dest_name'}{$newsrcfile} = $dest_basename; + } + + } # end of srcfile + } # end of each node + } # end of synclist + } # end processing clauses EXECUTE, APPEND, etc + } #end of processing file close INPUTFILE; if ($process_line == 0) { # no valid lines in the file @@ -5651,10 +5708,11 @@ sub parse_rsync_input_file_on_SN } else { - $$options{'nodes'} = join ',', keys %{$$options{'destDir_srcFile'}}; + $$options{'nodes'} = join ',', keys %{ $$options{'destDir_srcFile'} }; } return 0; } + #------------------------------------------------------------------------------- =head3 @@ -5688,75 +5746,79 @@ sub parse_rsync_input_file_on_SN #------------------------------------------------------------------------------- -sub run_rsync_postscripts +sub run_rsync_postscripts { - my ($rsyncoutput,$syncdir,$options) = @_; - my @rsync_output = @$rsyncoutput; - my @newoutput= (); - my $dshparms; - my $firstpass=1; + my ($rsyncoutput, $syncdir, $options) = @_; + my @rsync_output = @$rsyncoutput; + my @newoutput = (); + my $dshparms; + my $firstpass = 1; foreach my $postsfile (@::postscripts) { - my $tmppostfile = $postsfile ; + my $tmppostfile = $postsfile; # if service node need to add the SNsyncfiledir to the path if (xCAT::Utils->isServiceNode()) { - my $tmpp=$syncdir . $tmppostfile; + my $tmpp = $syncdir . $tmppostfile; $tmppostfile = $tmpp; } + # remove first character for the compare, we have to do this because the # return from rsync is tmp/file1 not /tmp/file1 - substr($tmppostfile,0,1)=""; + substr($tmppostfile, 0, 1) = ""; foreach my $line (@rsync_output) { - my($hostname,$ps) = split(/: /, $line); + my ($hostname, $ps) = split(/: /, $line); chomp $ps; chomp $hostname; - if ($ps eq "rsync") { # this is a line that is not an update - # save output , if firstpass through output + if ($ps eq "rsync") { # this is a line that is not an update + # save output , if firstpass through output if ($firstpass == 1) { push @newoutput, $line; $firstpass = 0; } next; } - if ($tmppostfile eq $ps) { - # build xdsh queue + if ($tmppostfile eq $ps) { + + # build xdsh queue # build host and all scripts to execute - push (@{$dshparms->{'postscripts'} {$postsfile}}, $hostname); + push(@{ $dshparms->{'postscripts'}{$postsfile} }, $hostname); } } } + # now if we have postscripts to run, run xdsh my $out; # my $ranaps=0; # did we run a postscript - foreach my $ps ( keys %{$$dshparms{'postscripts'}}) { + foreach my $ps (keys %{ $$dshparms{'postscripts'} }) { my @nodes; - push (@nodes, @{$$dshparms{'postscripts'}{$ps}}); - my @args=(); + push(@nodes, @{ $$dshparms{'postscripts'}{$ps} }); + my @args = (); if ($$options{'nodestatus'}) { - push @args,"--nodestatus" ; + push @args, "--nodestatus"; } - push @args,"-e"; + push @args, "-e"; # # if on the service node need to add the $syncdir directory to the path # if (xCAT::Utils->isServiceNode()) { - my $tmpp=$syncdir . $ps; - $ps=$tmpp; + my $tmpp = $syncdir . $ps; + $ps = $tmpp; } - push @args,$ps; - $out=xCAT::Utils->runxcmd( { command => ['xdsh'], - node => \@nodes, - arg => \@args, - }, $::SUBREQ, 0,1); + push @args, $ps; + $out = xCAT::Utils->runxcmd({ command => ['xdsh'], + node => \@nodes, + arg => \@args, + }, $::SUBREQ, 0, 1); foreach my $r (@$out) { push(@newoutput, $r); } } return @newoutput; } + #------------------------------------------------------------------------------- =head3 @@ -5792,100 +5854,110 @@ sub run_rsync_postscripts sub bld_and_run_append { - my ($hostnames,$rsyncoutput,$syncdir,$nodesyncfiledir,$options) = @_; - my @hosts = @$hostnames; - my @rsync_output = @$rsyncoutput; - my @newoutput= (); - my $dshparms; - my $firstpass=1; - my $headeradded=0; - my $processappend=0; - + my ($hostnames, $rsyncoutput, $syncdir, $nodesyncfiledir, $options) = @_; + my @hosts = @$hostnames; + my @rsync_output = @$rsyncoutput; + my @newoutput = (); + my $dshparms; + my $firstpass = 1; + my $headeradded = 0; + my $processappend = 0; + $::xdcpappendparms = "$nodesyncfiledir "; # directory to save the original file to append - my $nodesaveorgfiledir=$nodesyncfiledir; - $nodesaveorgfiledir .="/org"; + my $nodesaveorgfiledir = $nodesyncfiledir; + $nodesaveorgfiledir .= "/org"; + # add append directory to the base nodesyncfiledir $nodesyncfiledir .= "/append"; + # build the input appendfile:orgfile parsm foreach my $appendline (@::appendlines) { - if ($appendline =~ /(.+) -> (.+)/) - { - my $appendfile = $1; # append file left of arrow - my $filetoappend = $2; # file to append right of arrow - my $tmpappendfile = $appendfile; - # if service node need to add the syncdir to the path - # for the match - if (xCAT::Utils->isServiceNode()) { - my $tmpp=$syncdir . $tmpappendfile; - $tmpappendfile = $tmpp; - } - # remove first char for the compare, we have to do this because the - # return from rsync is tmp/file1 not /tmp/file1 - substr($tmpappendfile,0,1)=""; - # check to see if this file was rsync'd and to which hosts - foreach my $line (@rsync_output) { - my($hostname,$ps) = split(/: /, $line); - chomp $ps; - chomp $hostname; - if ($ps eq "rsync") { # this is a line that is not an update - # save output , if firstpass through output - if ($firstpass == 1) { - push @newoutput, $line; - $firstpass = 0; - } - next; - } - # build the append script (xdcpappend.sh) parameter list, - # based on all the append files - # that were rsyn'd to at least one node - if ($tmpappendfile eq $ps) { - my $parm="$appendfile:$filetoappend "; - # check to see if the parameter is already in the list - if (!($::xdcpappendparms =~ /$parm/)) { - $::xdcpappendparms .= $parm; - } - $processappend=1; + if ($appendline =~ /(.+) -> (.+)/) + { + my $appendfile = $1; # append file left of arrow + my $filetoappend = $2; # file to append right of arrow + my $tmpappendfile = $appendfile; + # if service node need to add the syncdir to the path + # for the match + if (xCAT::Utils->isServiceNode()) { + my $tmpp = $syncdir . $tmpappendfile; + $tmpappendfile = $tmpp; } - } - } - - } # end for each append line - # add append script to each host to execute. - if ($::appendscript && ($processappend==1)) { - # the append script has been sync'd to the site.nodesynfiledir - my $nodeappendscript = $nodesyncfiledir; - $nodeappendscript .= $::appendscript; - foreach my $host (@hosts) { - push (@{$dshparms->{'appendscripts'} {$nodeappendscript}}, $host); - } - # now run xdsh - my $out; - foreach my $ps ( keys %{$$dshparms{'appendscripts'}}) { - my @nodes; - push (@nodes, @{$$dshparms{'appendscripts'}{$ps}}); - my @args=(); - if ($$options{'nodestatus'}) { - push @args,"--nodestatus" ; - } - push @args,$ps; - push @args,$::xdcpappendparms; - - $out=xCAT::Utils->runxcmd( { command => ['xdsh'], - node => \@nodes, - arg => \@args, - }, $::SUBREQ, 0,1); - foreach my $r (@$out){ + + # remove first char for the compare, we have to do this because the + # return from rsync is tmp/file1 not /tmp/file1 + substr($tmpappendfile, 0, 1) = ""; + + # check to see if this file was rsync'd and to which hosts + foreach my $line (@rsync_output) { + my ($hostname, $ps) = split(/: /, $line); + chomp $ps; + chomp $hostname; + if ($ps eq "rsync") { # this is a line that is not an update + # save output , if firstpass through output + if ($firstpass == 1) { + push @newoutput, $line; + $firstpass = 0; + } + next; + } + + # build the append script (xdcpappend.sh) parameter list, + # based on all the append files + # that were rsyn'd to at least one node + if ($tmpappendfile eq $ps) { + my $parm = "$appendfile:$filetoappend "; + + # check to see if the parameter is already in the list + if (!($::xdcpappendparms =~ /$parm/)) { + $::xdcpappendparms .= $parm; + } + $processappend = 1; + + } + } + } + + } # end for each append line + # add append script to each host to execute. + if ($::appendscript && ($processappend == 1)) { + + # the append script has been sync'd to the site.nodesynfiledir + my $nodeappendscript = $nodesyncfiledir; + $nodeappendscript .= $::appendscript; + foreach my $host (@hosts) { + push(@{ $dshparms->{'appendscripts'}{$nodeappendscript} }, $host); + } + + # now run xdsh + my $out; + foreach my $ps (keys %{ $$dshparms{'appendscripts'} }) { + my @nodes; + push(@nodes, @{ $$dshparms{'appendscripts'}{$ps} }); + my @args = (); + if ($$options{'nodestatus'}) { + push @args, "--nodestatus"; + } + push @args, $ps; + push @args, $::xdcpappendparms; + + $out = xCAT::Utils->runxcmd({ command => ['xdsh'], + node => \@nodes, + arg => \@args, + }, $::SUBREQ, 0, 1); + foreach my $r (@$out) { push(@newoutput, $r); - } - } + } + } } return @newoutput; } + #------------------------------------------------------------------------------- =head3 @@ -5922,111 +5994,121 @@ sub bld_and_run_append sub bld_and_run_merge { - my ($hostnames,$rsyncoutput,$syncdir,$nodesyncfiledir,$options) = @_; - my @hosts = @$hostnames; - my @rsync_output = @$rsyncoutput; - my @newoutput= (); - my $dshparms; - my $firstpass=1; - my $headeradded=0; - my $processmerge=0; - + my ($hostnames, $rsyncoutput, $syncdir, $nodesyncfiledir, $options) = @_; + my @hosts = @$hostnames; + my @rsync_output = @$rsyncoutput; + my @newoutput = (); + my $dshparms; + my $firstpass = 1; + my $headeradded = 0; + my $processmerge = 0; + $::xdcpmergeparms = "$nodesyncfiledir "; - # directory to save the original file to merge - my $nodesaveorgfiledir=$nodesyncfiledir; - $nodesaveorgfiledir .="/org"; + # directory to save the original file to merge + my $nodesaveorgfiledir = $nodesyncfiledir; + $nodesaveorgfiledir .= "/org"; + # add merge directory to the base nodesyncfiledir $nodesyncfiledir .= "/merge"; + # build the input mergefile:orgfile parsm foreach my $mergeline (@::mergelines) { - if ($mergeline =~ /(.+) -> (.+)/) - { - my $mergefile = $1; # merge file left of arrow - my $filetomerge = $2; # file to merge right of arrow - if (($filetomerge ne "/etc/passwd") - && ($filetomerge ne "/etc/group") - && ($filetomerge ne "/etc/shadow")) { + if ($mergeline =~ /(.+) -> (.+)/) + { + my $mergefile = $1; # merge file left of arrow + my $filetomerge = $2; # file to merge right of arrow + if (($filetomerge ne "/etc/passwd") + && ($filetomerge ne "/etc/group") + && ($filetomerge ne "/etc/shadow")) { my $rsp = {}; $rsp->{error}->[0] = "$filetomerge is not either /etc/passwd, /etc/group or /etc/shadow. Those are the only supported files for MERGE"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 1; - - } - my $tmpmergefile = $mergefile; - # if service node need to add the syncdir to the path - # for the match - if (xCAT::Utils->isServiceNode()) { - my $tmpp=$syncdir . $tmpmergefile; - $tmpmergefile = $tmpp; - } - # remove first char for the compare, we have to do this because the - # return from rsync is tmp/file1 not /tmp/file1 - substr($tmpmergefile,0,1)=""; - # check to see if this file was rsync'd and to which hosts - foreach my $line (@rsync_output) { - my($hostname,$ps) = split(/: /, $line); - chomp $ps; - chomp $hostname; - if ($ps eq "rsync") { # this is a line that is not an update - # save output , if firstpass through output - if ($firstpass == 1) { - push @newoutput, $line; - $firstpass = 0; - } - next; - } - # build the merge script (xdcpmerge.sh) parameter list, - # based on all the merge files - # that were rsyn'd to at least one node - if ($tmpmergefile eq $ps) { - my $parm="$mergefile:$filetomerge "; - # check to see if the parameter is already in the list - if (!($::xdcpmergeparms =~ /$parm/)) { - $::xdcpmergeparms .= $parm; - } - $processmerge=1; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 1; } - } - } - - } # end for each merge line - # add merge script to each host to execute. If we need to run anything - if ($::mergescript && ($processmerge==1)) { - # the merge script has been sync'd to the site.nodesynfiledir - my $nodemergescript = $nodesyncfiledir; - $nodemergescript .= $::mergescript; - foreach my $host (@hosts) { - push (@{$dshparms->{'mergescripts'} {$nodemergescript}}, $host); - } - # now run xdsh - my $out; - foreach my $ps ( keys %{$$dshparms{'mergescripts'}}) { - my @nodes; - push (@nodes, @{$$dshparms{'mergescripts'}{$ps}}); - - # build the argument list - my @args=(); - - if ($$options{'nodestatus'}) { - push @args,"--nodestatus" ; - } - push @args, $ps; - push @args, $::xdcpmergeparms; - $out=xCAT::Utils->runxcmd( { command => ['xdsh'], - node => \@nodes, - arg => \@args, - }, $::SUBREQ, 0,1); - foreach my $r (@$out){ + my $tmpmergefile = $mergefile; + + # if service node need to add the syncdir to the path + # for the match + if (xCAT::Utils->isServiceNode()) { + my $tmpp = $syncdir . $tmpmergefile; + $tmpmergefile = $tmpp; + } + + # remove first char for the compare, we have to do this because the + # return from rsync is tmp/file1 not /tmp/file1 + substr($tmpmergefile, 0, 1) = ""; + + # check to see if this file was rsync'd and to which hosts + foreach my $line (@rsync_output) { + my ($hostname, $ps) = split(/: /, $line); + chomp $ps; + chomp $hostname; + if ($ps eq "rsync") { # this is a line that is not an update + # save output , if firstpass through output + if ($firstpass == 1) { + push @newoutput, $line; + $firstpass = 0; + } + next; + } + + # build the merge script (xdcpmerge.sh) parameter list, + # based on all the merge files + # that were rsyn'd to at least one node + if ($tmpmergefile eq $ps) { + my $parm = "$mergefile:$filetomerge "; + + # check to see if the parameter is already in the list + if (!($::xdcpmergeparms =~ /$parm/)) { + $::xdcpmergeparms .= $parm; + } + $processmerge = 1; + + } + } + } + + } # end for each merge line + # add merge script to each host to execute. If we need to run anything + if ($::mergescript && ($processmerge == 1)) { + + # the merge script has been sync'd to the site.nodesynfiledir + my $nodemergescript = $nodesyncfiledir; + $nodemergescript .= $::mergescript; + foreach my $host (@hosts) { + push(@{ $dshparms->{'mergescripts'}{$nodemergescript} }, $host); + } + + # now run xdsh + my $out; + foreach my $ps (keys %{ $$dshparms{'mergescripts'} }) { + my @nodes; + push(@nodes, @{ $$dshparms{'mergescripts'}{$ps} }); + + # build the argument list + my @args = (); + + if ($$options{'nodestatus'}) { + push @args, "--nodestatus"; + } + push @args, $ps; + push @args, $::xdcpmergeparms; + $out = xCAT::Utils->runxcmd({ command => ['xdsh'], + node => \@nodes, + arg => \@args, + }, $::SUBREQ, 0, 1); + foreach my $r (@$out) { push(@newoutput, $r); - } - } + } + } } return @newoutput; } + #------------------------------------------------------------------------------- =head3 @@ -6040,55 +6122,59 @@ sub bld_and_run_merge #------------------------------------------------------------------------------- -sub run_always_rsync_postscripts +sub run_always_rsync_postscripts { - my ($hostnames,$syncdir,$options) = @_; - my @hosts = @$hostnames; - my @newoutput= (); - my $dshparms; + my ($hostnames, $syncdir, $options) = @_; + my @hosts = @$hostnames; + my @newoutput = (); + my $dshparms; foreach my $postsfile (@::alwayspostscripts) { - my $tmppostfile = $postsfile ; - - # if service node need to add the SNsyncfiledir to the path - if (xCAT::Utils->isServiceNode()) { - my $tmpp=$syncdir . $tmppostfile; - $tmppostfile = $tmpp; - } + my $tmppostfile = $postsfile; - foreach my $host (@hosts) { - # build xdsh queue - # build host and all scripts to execute - push (@{$dshparms->{'postscripts'} {$postsfile}}, $host); - } + # if service node need to add the SNsyncfiledir to the path + if (xCAT::Utils->isServiceNode()) { + my $tmpp = $syncdir . $tmppostfile; + $tmppostfile = $tmpp; + } + + foreach my $host (@hosts) { + + # build xdsh queue + # build host and all scripts to execute + push(@{ $dshparms->{'postscripts'}{$postsfile} }, $host); + } } + # now if we have postscripts to run, run xdsh my $out; - foreach my $ps ( keys %{$$dshparms{'postscripts'}}) { + foreach my $ps (keys %{ $$dshparms{'postscripts'} }) { my @nodes; + # build the argument list - my @args=(); + my @args = (); if ($$options{'nodestatus'}) { - push @args,"--nodestatus" ; + push @args, "--nodestatus"; } - push @args,"-e"; - # if on the service node need to add the $syncdir directory + push @args, "-e"; + + # if on the service node need to add the $syncdir directory # to the path if (xCAT::Utils->isServiceNode()) { - my $tmps=$syncdir . $ps; - push @args, $tmps; - } else{ - push @args, $ps; + my $tmps = $syncdir . $ps; + push @args, $tmps; + } else { + push @args, $ps; } - push (@nodes, @{$$dshparms{'postscripts'}{$ps}}); - - $out=xCAT::Utils->runxcmd( { command => ['xdsh'], - node => \@nodes, - arg => \@args, - }, $::SUBREQ, 0,1); - foreach my $r (@$out){ - push(@newoutput, $r); + push(@nodes, @{ $$dshparms{'postscripts'}{$ps} }); + + $out = xCAT::Utils->runxcmd({ command => ['xdsh'], + node => \@nodes, + arg => \@args, + }, $::SUBREQ, 0, 1); + foreach my $r (@$out) { + push(@newoutput, $r); } @@ -6096,6 +6182,7 @@ sub run_always_rsync_postscripts } return @newoutput; } + #------------------------------------------------------------------------------- =head3 @@ -6120,10 +6207,10 @@ sub runlocal_on_rootimg { my ($class, $options, $imagename) = @_; my $cmd; - if (xCAT::Utils->isAIX()) { # use xcatchroot - $cmd = "$::XCATROOT/bin/xcatchroot -i $$options{'rootimg'} \"$$options{'command'}\""; + if (xCAT::Utils->isAIX()) { # use xcatchroot + $cmd = "$::XCATROOT/bin/xcatchroot -i $$options{'rootimg'} \"$$options{'command'}\""; } else { - $cmd = "chroot $$options{'rootimg'} $$options{'command'}"; + $cmd = "chroot $$options{'rootimg'} $$options{'command'}"; } my @output = xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) @@ -6237,8 +6324,8 @@ sub runDsh_api { xCAT::MsgUtils->message( "E", - "xdsh command: $$optionsRef{'command'} failed on nodes:$::DSH_API_NODES_FAILED." - ); +"xdsh command: $$optionsRef{'command'} failed on nodes:$::DSH_API_NODES_FAILED." + ); } } @@ -6316,7 +6403,7 @@ sub runDcp_api elsif (ref($optionsRef->{'source'} eq "ARRAY")) { $optionsRef->{'source'} = join $::__DCP_DELIM, - @{$optionsRef->{'source'}}; + @{ $optionsRef->{'source'} }; } $::RUNCMD_RC = xCAT::DSHCLI->execute_dcp($optionsRef); @@ -6359,7 +6446,7 @@ sub runDcp_api if (!$DSHCLI::NO_MESSAGES) { xCAT::MsgUtils->message("E", - "dcp command failed, Return code=$::RUNCMD_RC."); + "dcp command failed, Return code=$::RUNCMD_RC."); } } diff --git a/perl-xCAT/xCAT/DSHContext.pm b/perl-xCAT/xCAT/DSHContext.pm index 41b22cd0a..c1fbdc37f 100644 --- a/perl-xCAT/xCAT/DSHContext.pm +++ b/perl-xCAT/xCAT/DSHContext.pm @@ -8,64 +8,64 @@ use strict; require xCAT::DSHCore; sub valid_context { - return 1; + return 1; } sub context_defaults { - my %defaults = (); + my %defaults = (); - $defaults{'NodeRemoteShell'} = '/usr/bin/rsh'; - return \%defaults; + $defaults{'NodeRemoteShell'} = '/usr/bin/rsh'; + return \%defaults; } sub context_properties { - return; + return; } sub all_devices { - return undef; + return undef; } sub all_devicegroups { - return undef; + return undef; } sub all_nodes { - return undef; + return undef; } sub all_nodegroups { - return undef; + return undef; } sub devicegroup_members { - return undef; + return undef; } sub nodegroup_members { - return undef; + return undef; } sub resolve_device { - return undef; + return undef; } sub resolve_node { - return 1; + return 1; } sub verify_target { - return 127; + return 127; } sub verify_mode { - return "NOXCAT"; + return "NOXCAT"; } sub resolve_hostnames { - my ( $class, $resolved_targets, $unresolved_targets, @target_list ) = @_; - xCAT::DSHCore->resolve_hostnames( undef, $resolved_targets, $unresolved_targets, - undef, @target_list ); + my ($class, $resolved_targets, $unresolved_targets, @target_list) = @_; + xCAT::DSHCore->resolve_hostnames(undef, $resolved_targets, $unresolved_targets, + undef, @target_list); } 1; diff --git a/perl-xCAT/xCAT/DSHCore.pm b/perl-xCAT/xCAT/DSHCore.pm index 9e940ca01..4ac392bdf 100644 --- a/perl-xCAT/xCAT/DSHCore.pm +++ b/perl-xCAT/xCAT/DSHCore.pm @@ -65,7 +65,7 @@ sub fork_no_output select(STDERR); $| = 1; - if (!(exec {$command[0]} @command)) + if (!(exec { $command[0] } @command)) { return (-4, undef); } @@ -113,7 +113,7 @@ sub fork_no_output sub fork_output { my ($class, $fork_id, @command) = @_; -no strict; + no strict; my $pid; my %pipes = (); @@ -144,7 +144,7 @@ no strict; select(STDERR); $| = 1; - if (!(exec {$command[0]} @command)) + if (!(exec { $command[0] } @command)) { return (-4, undef); } @@ -156,7 +156,7 @@ no strict; } return ($pid, *$rout_fh, *$rerr_fh, *$wout_fh, *$werr_fh); -use strict; + use strict; } @@ -197,7 +197,7 @@ use strict; sub fork_output_for_commands { my ($class, $fork_id, @commands) = @_; -no strict; + no strict; my $pid; my %pipes = (); @@ -227,15 +227,15 @@ no strict; $| = 1; select(STDERR); $| = 1; - if ( @commands > 1 ) { - my $command0 = shift(@commands); - my @exe_command0_process = xCAT::DSHCore->fork_no_output($fork_id, @$command0); + if (@commands > 1) { + my $command0 = shift(@commands); + my @exe_command0_process = xCAT::DSHCore->fork_no_output($fork_id, @$command0); waitpid($exe_command0_process[0], undef); } - + my $t_command = shift(@commands); - my @command = @$t_command; - if (!(exec {$command[0]} @command)) + my @command = @$t_command; + if (!(exec { $command[0] } @command)) { return (-4, undef); } @@ -247,7 +247,7 @@ no strict; } return ($pid, *$rout_fh, *$rerr_fh, *$wout_fh, *$werr_fh); -use strict; + use strict; } @@ -289,7 +289,8 @@ use strict; #--------------------------------------------------------------------------- # NOTE: global environment $::__DSH_LAST_LINE} only can be used in DSHCore::pipe_handler and DSHCore::pipe_handler_buffer -$::__DSH_LAST_LINE = undef; +$::__DSH_LAST_LINE = undef; + sub pipe_handler { my ($class, $options, $target_properties, $read_fh, $buffer_size, $label, @@ -298,8 +299,8 @@ sub pipe_handler my $line; my $target_hostname; - my $eof_reached = undef; - my $cust_rc_deal =0; + my $eof_reached = undef; + my $cust_rc_deal = 0; if ($::USER_POST_CMD) { @@ -316,7 +317,7 @@ sub pipe_handler } while (sysread($read_fh, $line, $buffer_size) != 0 - || ($eof_reached = 1)) + || ($eof_reached = 1)) { last if ($eof_reached && (!defined($::__DSH_LAST_LINE->{$label}))); @@ -349,13 +350,15 @@ sub pipe_handler # Dump the last line at the beginning of current buffer if ($::__DSH_LAST_LINE->{$label}) { - unshift @lines, "$::__DSH_LAST_LINE->{$label}" ; + unshift @lines, "$::__DSH_LAST_LINE->{$label}"; } + # Pop current buffer to $::__DSH_LAST_LINE->{$label} - if($line) + if ($line) { - $::__DSH_LAST_LINE->{$label} = $lines[scalar @lines - 1]; + $::__DSH_LAST_LINE->{$label} = $lines[ scalar @lines - 1 ]; pop @lines; + # Skip this loop if array @lines is empty. if (scalar @lines == 0) { @@ -377,20 +380,24 @@ sub pipe_handler $line =~ s/:DSH_TARGET_RC=$target_rc:\n//g; $$target_properties{'target-rc'} = $target_rc; } - if ( $::__DSH_LAST_LINE->{$label} =~ /DSH_RC/ && $cust_rc_deal) { + if ($::__DSH_LAST_LINE->{$label} =~ /DSH_RC/ && $cust_rc_deal) { my $target_rc = undef; + # Get the number in the last line - $line =~ /[\D]*([0-9]+)\s*$/ ; + $line =~ /[\D]*([0-9]+)\s*$/; $target_rc = $1; $$target_properties{'target-rc'} = $target_rc; + # Remove the last line $line =~ s/$target_rc\s*\n$//g; + #$line = $line . "## ret=$target_rc"; # Clean up $::__DSH_LAST_LINE->{$label} - undef $::__DSH_LAST_LINE->{$label} ; + undef $::__DSH_LAST_LINE->{$label}; + # when '-z' is specified, display return code $::DSH_EXIT_STATUS && - ($line .="Remote_command_rc = $target_rc"); + ($line .= "Remote_command_rc = $target_rc"); } if ($line ne '') @@ -417,9 +424,10 @@ sub pipe_handler $line =~ s/$label//g; } - my $rsp={}; + my $rsp = {}; $rsp->{data}->[0] = $line; xCAT::MsgUtils->message("D", $rsp, $::CALLBACK); + #print $write_fh $line; } @@ -430,10 +438,10 @@ sub pipe_handler pop @write_fhs; close $output_file || print STDOUT - "dsh> Error_file_closed $$target_properties{hostname} $output_file\n"; - my $rsp={}; +"dsh> Error_file_closed $$target_properties{hostname} $output_file\n"; + my $rsp = {}; $rsp->{error}->[0] = - "Error_file_closed $$target_properties{hostname $output_file}.\n"; +"Error_file_closed $$target_properties{hostname $output_file}.\n"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); ($output_file == $$target_properties{'output-fh'}) && delete $$target_properties{'output-fh'}; @@ -496,7 +504,7 @@ sub pipe_handler_buffer my $line; my $eof_reached = undef; - my $cust_rc_deal =0; + my $cust_rc_deal = 0; if ($::USER_POST_CMD) { # If user provide post-command to display return code, @@ -511,8 +519,8 @@ sub pipe_handler_buffer $cust_rc_deal = 1; } - while ( (sysread($read_fh, $line, $buffer_size) != 0) - || ($eof_reached = 1)) + while ((sysread($read_fh, $line, $buffer_size) != 0) + || ($eof_reached = 1)) { last if ($eof_reached && (!defined($::__DSH_LAST_LINE->{$label}))); if ($line =~ /^\n$/ && scalar(@$write_buffer) == 0) @@ -544,13 +552,15 @@ sub pipe_handler_buffer # Dump the last line at the beginning of current buffer if ($::__DSH_LAST_LINE->{$label}) { - unshift @lines, "$::__DSH_LAST_LINE->{$label}" ; + unshift @lines, "$::__DSH_LAST_LINE->{$label}"; undef $::__DSH_LAST_LINE->{$label} } if ($line) { + # Pop current buffer to $::__DSH_LAST_LINE->{$label} - $::__DSH_LAST_LINE->{$label} = $lines[scalar @lines - 1]; + $::__DSH_LAST_LINE->{$label} = $lines[ scalar @lines - 1 ]; pop @lines; + # Skip this loop if array @lines is empty. if (scalar @lines == 0) { @@ -572,20 +582,24 @@ sub pipe_handler_buffer $line =~ s/:DSH_TARGET_RC=$target_rc:\n//g; $$target_properties{'target-rc'} = $target_rc; } - if ( $::__DSH_LAST_LINE->{$label} =~ /DSH_RC/ && $cust_rc_deal) { + if ($::__DSH_LAST_LINE->{$label} =~ /DSH_RC/ && $cust_rc_deal) { my $target_rc = undef; + # Get the number in the last line - $line =~ /[\D]*([0-9]+)\s*$/ ; + $line =~ /[\D]*([0-9]+)\s*$/; $target_rc = $1; $$target_properties{'target-rc'} = $target_rc; + # Remove the last line $line =~ s/$target_rc\s*\n$//g; + #$line = $line . "## ret=$target_rc"; # Clean up $::__DSH_LAST_LINE->{$label} - undef $::__DSH_LAST_LINE->{$label} ; + undef $::__DSH_LAST_LINE->{$label}; + # when '-z' is specified, display return code $::DSH_EXIT_STATUS && - ($line .="Remote_command_rc = $target_rc"); + ($line .= "Remote_command_rc = $target_rc"); } if ($line ne '') @@ -696,35 +710,37 @@ sub pping_hostnames my ($class, @hostnames) = @_; my $hostname_list = join ",", @hostnames; + # read site table, usefping attribute # if set then run pping -f to use fping # this fixes a broken nmap in Redhat 6.2 with ip alias (3512) - my $cmd="$::XCATROOT/bin/pping $hostname_list"; # default - my @usefping=xCAT::TableUtils->get_site_attribute("usefping"); + my $cmd = "$::XCATROOT/bin/pping $hostname_list"; # default + my @usefping = xCAT::TableUtils->get_site_attribute("usefping"); if ((defined($usefping[0])) && ($usefping[0] eq "1")) { - $cmd = "$::XCATROOT/bin/pping -f $hostname_list"; + $cmd = "$::XCATROOT/bin/pping -f $hostname_list"; } + #my $rsp={}; #$rsp->{data}->[0] = "running command $cmd"; #xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); my @output = xCAT::Utils->runcmd($cmd, -1); - if ($::RUNCMD_RC !=0) { - my $rsp={}; + if ($::RUNCMD_RC != 0) { + my $rsp = {}; $rsp->{error}->[0] = "Error from pping"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - } - $::RUNCMD_RC =0; # reset + } + $::RUNCMD_RC = 0; # reset my @no_response = (); foreach my $line (@output) { my ($hostname, $result) = split ':', $line; my ($token, $status) = split ' ', $result; chomp($token); - if ($token ne 'ping') { - push @no_response, $hostname; - } + if ($token ne 'ping') { + push @no_response, $hostname; + } } return @no_response; diff --git a/perl-xCAT/xCAT/DSHRemoteShell.pm b/perl-xCAT/xCAT/DSHRemoteShell.pm index b114a55c7..64523c32f 100644 --- a/perl-xCAT/xCAT/DSHRemoteShell.pm +++ b/perl-xCAT/xCAT/DSHRemoteShell.pm @@ -3,14 +3,15 @@ package xCAT::DSHRemoteShell; use strict; + sub remote_shell_command { - return undef; + return undef; } sub remote_copy_command { - return undef; + return undef; } 1; diff --git a/perl-xCAT/xCAT/DiscoveryUtils.pm b/perl-xCAT/xCAT/DiscoveryUtils.pm index 1e89fcd9d..874387517 100644 --- a/perl-xCAT/xCAT/DiscoveryUtils.pm +++ b/perl-xCAT/xCAT/DiscoveryUtils.pm @@ -5,7 +5,7 @@ package xCAT::DiscoveryUtils; use strict; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; use xCAT::MsgUtils; @@ -16,9 +16,9 @@ use xCAT::MsgUtils; =cut sub update_discovery_data { - my $class = shift; + my $class = shift; my $request = shift; - + my %disdata; my %otherdata; @@ -33,9 +33,9 @@ sub update_discovery_data { } #discoverytime - my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time); + my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime(time); my $currtime = sprintf("%02d-%02d-%04d %02d:%02d:%02d", - $mon + 1, $mday, $year + 1900, $hour, $min, $sec); + $mon + 1, $mday, $year + 1900, $hour, $min, $sec); $disdata{'discoverytime'} = $currtime; foreach my $attr (keys %$request) { @@ -44,9 +44,10 @@ sub update_discovery_data { } elsif ($attr =~ /^(node|uuid|arch|cpucount|cputype|memory|mtm|serial)$/) { $disdata{$attr} = $request->{$attr}->[0]; } elsif ($attr eq 'nic') { + # Set the nics attributes - foreach my $nic (@{$request->{nic}}) { - my $nicname = $nic->{'devname'}->[0]; + foreach my $nic (@{ $request->{nic} }) { + my $nicname = $nic->{'devname'}->[0]; foreach my $nicattr (keys %$nic) { my $tbattr; if ($nicattr eq 'driver') { @@ -69,27 +70,28 @@ sub update_discovery_data { if ($tbattr) { if ($disdata{$tbattr}) { - $disdata{$tbattr} .= ','.$nicname.'!'.$nic->{$nicattr}->[0]; + $disdata{$tbattr} .= ',' . $nicname . '!' . $nic->{$nicattr}->[0]; } else { - $disdata{$tbattr} = $nicname.'!'.$nic->{$nicattr}->[0]; + $disdata{$tbattr} = $nicname . '!' . $nic->{$nicattr}->[0]; } } } } } else { + # store to otherdata for the not parsed attributes $otherdata{$attr} = $request->{$attr}; } } if (keys %otherdata) { - $disdata{'otherdata'} = XMLout(\%otherdata,RootName=>'discoveryotherdata' ,NoAttr=>1); + $disdata{'otherdata'} = XMLout(\%otherdata, RootName => 'discoveryotherdata', NoAttr => 1); } my $distab = xCAT::Table->new('discoverydata'); if ($distab) { - $distab->setAttribs({uuid=>$request->{'uuid'}->[0]},\%disdata); - $distab->close(); + $distab->setAttribs({ uuid => $request->{'uuid'}->[0] }, \%disdata); + $distab->close(); } } diff --git a/perl-xCAT/xCAT/Enabletrace.pm b/perl-xCAT/xCAT/Enabletrace.pm index ad75a8280..3730f7cfe 100644 --- a/perl-xCAT/xCAT/Enabletrace.pm +++ b/perl-xCAT/xCAT/Enabletrace.pm @@ -7,47 +7,49 @@ use Filter::Util::Call; our @ISA = qw(Exporter); our @EXPORT_OK = qw(loadtrace filter); -sub loadtrace{ - my (undef, $filename) = caller(); - my (%args) = ( - filename => $filename, - inside => 0, - lineno => 0, - ); +sub loadtrace { + my (undef, $filename) = caller(); + my (%args) = ( + filename => $filename, + inside => 0, + lineno => 0, + ); - filter_add(bless \%args); + filter_add(bless \%args); } sub filter { - my ($self) = @_; - my $line= filter_read(); - $self->{lineno}++; - # deal with EOF/error first - if ($line<= 0) { + my ($self) = @_; + my $line = filter_read(); + $self->{lineno}++; + + # deal with EOF/error first + if ($line <= 0) { + if ($self->{inside}) { + die "Do not find the END of the trace block. [$self->{filename}:$self->{lineno}]"; + } + return $line; + } if ($self->{inside}) { - die "Do not find the END of the trace block. [$self->{filename}:$self->{lineno}]"; - } - return $line; - } - if ($self->{inside}) { - if (/^\s*##\s*TRACE_BEGIN/ ) { - die "The trace block is nested. [$self->{filename}:$self->{lineno}]"; + if (/^\s*##\s*TRACE_BEGIN/) { + die "The trace block is nested. [$self->{filename}:$self->{lineno}]"; + } elsif (/^\s*##\s*TRACE_END/) { + $self->{inside} = 0; + } else { + + # remove the #.. at the begin of the line + s/^\s*#+//; + } + } elsif (/^\s*##\s*TRACE_BEGIN/) { + $self->{inside} = 1; } elsif (/^\s*##\s*TRACE_END/) { - $self->{inside} = 0; - } else { - # remove the #.. at the begin of the line - s/^\s*#+//; + die "Do not see the BEGIN of the trace block. [$self->{filename}:$self->{lineno}]"; + } elsif (/^\s*##\s*TRACE_LINE/) { + s/^\s*##\s*TRACE_LINE//; } - } elsif ( /^\s*##\s*TRACE_BEGIN/ ) { - $self->{inside} = 1; - } elsif ( /^\s*##\s*TRACE_END/ ) { - die "Do not see the BEGIN of the trace block. [$self->{filename}:$self->{lineno}]"; - } elsif ( /^\s*##\s*TRACE_LINE/ ) { - s/^\s*##\s*TRACE_LINE//; - } return $line; - } +} 1; diff --git a/perl-xCAT/xCAT/ExtTab.pm b/perl-xCAT/xCAT/ExtTab.pm index bc0f05c9d..f97312e13 100644 --- a/perl-xCAT/xCAT/ExtTab.pm +++ b/perl-xCAT/xCAT/ExtTab.pm @@ -2,93 +2,100 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html #------------------------------------------------------- package xCAT::ExtTab; + BEGIN { -$::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } -# + +# #NO xCAT perl library routines should be used in this begin block -#(i.e. MsgUtils,Utils, etc) -# +#(i.e. MsgUtils,Utils, etc) +# #use lib "$::XCATROOT/lib/perl"; use File::Path; -%ext_tabspec=(); -%ext_defspec=(); +%ext_tabspec = (); +%ext_defspec = (); # loads user defined table spec. They are stored under /opt/xcat/lib/perl/xCAT_schema directory -my $path="$::XCATROOT/lib/perl/xCAT_schema"; -my $filelist; # no specific files -my @extSchema = &get_filelist($path, $filelist,"pm"); +my $path = "$::XCATROOT/lib/perl/xCAT_schema"; +my $filelist; # no specific files +my @extSchema = &get_filelist($path, $filelist, "pm"); + # print "\nextSchema=@extSchema\n"; foreach (@extSchema) { /.*\/([^\/]*).pm$/; - my $file=$_; + my $file = $_; my $modname = $1; no strict 'refs'; my $warning; - # `logger -t xcat processing $_`; - eval {require($_)}; - if ($@) { - $warning ="Warning: The user defined database table schema file $file cannot be located or has compiling errors.\n"; + + # `logger -t xcat processing $_`; + eval { require($_) }; + if ($@) { + $warning = "Warning: The user defined database table schema file $file cannot be located or has compiling errors.\n"; print $warning; - `logger -p local4.warning -t xcat $warning`; - next; - } - if (${"xCAT_schema::" . "$modname" . "::"}{tabspec}) { - my %tabspec=%{${"xCAT_schema::" . "$modname" . "::"}{tabspec}}; - foreach my $tabname (keys(%tabspec)) { - if (exists($ext_tabspec{$tabname})) { - $warning = "Warning: File $file: the table name $tabname is used by other applications. Please rename the table.\n"; - print $warning; - `logger -p local4.warning -t xcat $warning`; - } else { - $ext_tabspec{$tabname}=$tabspec{$tabname}; - } - } - } else { - $warning ="\n Warning: Cannot find \%tabspec variable in the user defined database table schema file $file\n"; - print $warning; - `logger -p local4.warning -t xcat $warning`; + `logger -p local4.warning -t xcat $warning`; + next; } - + if (${ "xCAT_schema::" . "$modname" . "::" }{tabspec}) { + my %tabspec = %{ ${ "xCAT_schema::" . "$modname" . "::" }{tabspec} }; + foreach my $tabname (keys(%tabspec)) { + if (exists($ext_tabspec{$tabname})) { + $warning = "Warning: File $file: the table name $tabname is used by other applications. Please rename the table.\n"; + print $warning; + `logger -p local4.warning -t xcat $warning`; + } else { + $ext_tabspec{$tabname} = $tabspec{$tabname}; + } + } + } else { + $warning = "\n Warning: Cannot find \%tabspec variable in the user defined database table schema file $file\n"; + print $warning; + `logger -p local4.warning -t xcat $warning`; + } + #get the defspec from each file and merge them into %ext_defspec - if (${"xCAT_schema::" . "$modname" . "::"}{defspec}) { - my %defspec=%{${"xCAT_schema::" . "$modname" . "::"}{defspec}}; - foreach my $objname (keys(%defspec)) { - if (exists($defspec{$objname}->{'attrs'})) { - if (exists($ext_defspec{$objname})) { + if (${ "xCAT_schema::" . "$modname" . "::" }{defspec}) { + my %defspec = %{ ${ "xCAT_schema::" . "$modname" . "::" }{defspec} }; + foreach my $objname (keys(%defspec)) { + if (exists($defspec{$objname}->{'attrs'})) { + if (exists($ext_defspec{$objname})) { + #print "insert\n"; - my @attr_new=@{$defspec{$objname}->{'attrs'}}; - my @attr=@{$ext_defspec{$objname}->{'attrs'}}; - my %tmp_hash=(); - foreach my $orig (@attr) { - my $attrname=$orig->{attr_name}; - $tmp_hash{$attrname}=1; - } - foreach my $h (@attr_new) { - my $attrname=$h->{attr_name}; - if (exists($tmp_hash{$attrname})) { - $warning= " Warning: Conflict when adding user defined defspec from file $file. Attribute name $attrname is already defined in object $objname. \n"; + my @attr_new = @{ $defspec{$objname}->{'attrs'} }; + my @attr = @{ $ext_defspec{$objname}->{'attrs'} }; + my %tmp_hash = (); + foreach my $orig (@attr) { + my $attrname = $orig->{attr_name}; + $tmp_hash{$attrname} = 1; + } + foreach my $h (@attr_new) { + my $attrname = $h->{attr_name}; + if (exists($tmp_hash{$attrname})) { + $warning = " Warning: Conflict when adding user defined defspec from file $file. Attribute name $attrname is already defined in object $objname. \n"; print $warning; - `logger -p local4.warning -t xcat $warning`; - } else { - #print "\ngot here objname=$objname, attrname=" . $h->{attr_name} . "\n"; - push(@{$ext_defspec{$objname}->{'attrs'}}, $h); - } - } - } else { - #print "\ngot here objname=$objname, file=$file\n"; - $ext_defspec{$objname}=$defspec{$objname}; - } - } - } - } - -} #foreach + `logger -p local4.warning -t xcat $warning`; + } else { + + #print "\ngot here objname=$objname, attrname=" . $h->{attr_name} . "\n"; + push(@{ $ext_defspec{$objname}->{'attrs'} }, $h); + } + } + } else { + + #print "\ngot here objname=$objname, file=$file\n"; + $ext_defspec{$objname} = $defspec{$objname}; + } + } + } + } + +} #foreach #print out the defspec #print "\nexternal defspec:\n"; @@ -98,9 +105,10 @@ foreach (@extSchema) { # foreach my $h (@attr) { # print " " . $h->{attr_name} . "\n"; # } -#} +#} #------------------------------------------------------- + =head1 xCAT::ExtTab Handles user defined database tables. @@ -117,6 +125,7 @@ foreach (@extSchema) { =cut + #------------------------------------------------------- sub updateTables @@ -124,11 +133,12 @@ sub updateTables #print "\nupdateTables\n"; #print "\n"; foreach (keys %ext_tabspec) { - my $table= xCAT::Table->new($_,-create=>1); - my $rc=$table->updateschema(); + my $table = xCAT::Table->new($_, -create => 1); + my $rc = $table->updateschema(); $table->close(); } } + #-------------------------------------------------------------------------- =head3 @@ -159,7 +169,7 @@ sub updateTables sub get_filelist { - use File::Basename; + use File::Basename; my $directory = shift; my $files = shift; my $ext = shift; @@ -191,30 +201,31 @@ sub get_filelist my @list = glob($directory . "*.$ext"); # all files foreach my $file (@list) { - my $filename= basename($file); # strip filename - my($name,$ext1) = split '\.', $filename; - my($tmpname,$ext2) = split '\_', $name; - if ($ext2 eq $dbname) # matches the database + my $filename = basename($file); # strip filename + my ($name, $ext1) = split '\.', $filename; + my ($tmpname, $ext2) = split '\_', $name; + if ($ext2 eq $dbname) # matches the database { push @filelist, $file; } else { - if ($ext2 eq "") # no database designated + if ($ext2 eq "") # no database designated { push @filelist, $file; - } else { # if not one of the databases, they just have _ in - # the file name - if ($ext2 ne "db2" && $ext2 ne "mysql" && $ext2 ne "pgsql" && $ext2 ne "sqlite" ) { + } else { # if not one of the databases, they just have _ in + # the file name + if ($ext2 ne "db2" && $ext2 ne "mysql" && $ext2 ne "pgsql" && $ext2 ne "sqlite") { push @filelist, $file; - } + } } - } - $ext2 = ""; - $ext1 = ""; + } + $ext2 = ""; + $ext1 = ""; } return @filelist; } + #-------------------------------------------------------------------------- =head3 @@ -245,12 +256,12 @@ sub get_xcatcfg my $xcatcfg = (defined $ENV{'XCATCFG'} ? $ENV{'XCATCFG'} : ''); unless ($xcatcfg) { if (-r "/etc/xcat/cfgloc") { - my $cfgl; - open($cfgl,"<","/etc/xcat/cfgloc"); - $xcatcfg = <$cfgl>; - close($cfgl); - chomp($xcatcfg); - $ENV{'XCATCFG'}=$xcatcfg; #Store it in env to avoid many file reads + my $cfgl; + open($cfgl, "<", "/etc/xcat/cfgloc"); + $xcatcfg = <$cfgl>; + close($cfgl); + chomp($xcatcfg); + $ENV{'XCATCFG'} = $xcatcfg; #Store it in env to avoid many file reads } } if ($xcatcfg =~ /^$/) diff --git a/perl-xCAT/xCAT/FSPUtils.pm b/perl-xCAT/xCAT/FSPUtils.pm index 6072f6a25..5320078b6 100644 --- a/perl-xCAT/xCAT/FSPUtils.pm +++ b/perl-xCAT/xCAT/FSPUtils.pm @@ -10,7 +10,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -24,12 +24,13 @@ require xCAT::NetworkUtils; require xCAT::Schema; require xCAT::Utils; require xCAT::TableUtils; + #use Data::Dumper; require xCAT::NodeRange; use xCAT::MsgUtils qw(verbose_message); - - #------------------------------------------------------------------------------- + +#------------------------------------------------------------------------------- =head3 getHcpAttribs Description: @@ -50,58 +51,59 @@ use xCAT::MsgUtils qw(verbose_message); =cut #------------------------------------------------------------------------------- - -sub getHcpAttribs + +sub getHcpAttribs { my $request = shift; - my $tabs = shift; - my %ppchash ; - my %vpd ; - - my @vs = $tabs->{vpd}->getAllNodeAttribs(['node', 'side']); - for my $entry ( @vs ) { + my $tabs = shift; + my %ppchash; + my %vpd; + + my @vs = $tabs->{vpd}->getAllNodeAttribs([ 'node', 'side' ]); + for my $entry (@vs) { my $tmp_node = $entry->{node}; my $tmp_side = $entry->{side}; - if(defined($tmp_node) && defined($tmp_side)) { - $vpd{$tmp_node} = $tmp_side ; - } + if (defined($tmp_node) && defined($tmp_side)) { + $vpd{$tmp_node} = $tmp_side; + } } - - my @ps = $tabs->{ppc}->getAllNodeAttribs(['node','parent','nodetype','hcp','id']); - for my $entry ( @ps ) { + + my @ps = $tabs->{ppc}->getAllNodeAttribs([ 'node', 'parent', 'nodetype', 'hcp', 'id' ]); + for my $entry (@ps) { my $tmp_parent = $entry->{parent}; - my $tmp_node = $entry->{node}; - my $tmp_type = $entry->{nodetype}; - if(defined($tmp_node) && defined($tmp_type) && ($tmp_type =~ /^(fsp|bpa)$/ && $tmp_parent) ) { - push @{$ppchash{$tmp_parent}{children}}, $tmp_node; - #push @{$ppchash{$tmp_parent}}, $tmp_node; + my $tmp_node = $entry->{node}; + my $tmp_type = $entry->{nodetype}; + if (defined($tmp_node) && defined($tmp_type) && ($tmp_type =~ /^(fsp|bpa)$/ && $tmp_parent)) { + push @{ $ppchash{$tmp_parent}{children} }, $tmp_node; + + #push @{$ppchash{$tmp_parent}}, $tmp_node; } if (defined($tmp_node) && defined($tmp_type) && ($tmp_type eq "blade") && defined($entry->{hcp})) { - push @{$ppchash{$tmp_node}{children}}, $entry->{hcp}; + push @{ $ppchash{$tmp_node}{children} }, $entry->{hcp}; } if (defined($tmp_node) && defined($entry->{id}) && defined($tmp_parent) && defined($tmp_type) && ($tmp_type eq "lpar")) { $ppchash{$tmp_parent}{mapping}{$tmp_node} = $entry->{id}; } - #if(exists($ppchash{$tmp_node})) { - # if( defined($tmp_type) ) { - # #push @{$ppchash{$tmp_node}{type}}, $tmp_type; - # } else { - # my %output; - # my $msg = "no type for $tmp_type in the ppc table."; - # $output{errorcode} = 1; - # $output{data} = $msg; - # $request->{callback}->( \%output ); - # } - #} - } - - $request->{ppc}=\%ppchash ; - $request->{vpd}=\%vpd ; - + #if(exists($ppchash{$tmp_node})) { + # if( defined($tmp_type) ) { + # #push @{$ppchash{$tmp_node}{type}}, $tmp_type; + # } else { + # my %output; + # my $msg = "no type for $tmp_type in the ppc table."; + # $output{errorcode} = 1; + # $output{data} = $msg; + # $request->{callback}->( \%output ); + # } + #} + } + + $request->{ppc} = \%ppchash; + $request->{vpd} = \%vpd; + } - - #------------------------------------------------------------------------------- + +#------------------------------------------------------------------------------- =head3 getIPaddress Description: @@ -129,12 +131,12 @@ sub getHcpAttribs =cut #------------------------------------------------------------------------------- - -sub getIPaddress + +sub getIPaddress { -# require xCAT::Table; + # require xCAT::Table; my $request = shift; - my $type = shift; + my $type = shift; my $nodetocheck = shift; my $port = shift; if (xCAT::NetworkUtils::isIpaddr($nodetocheck)) { @@ -144,82 +146,85 @@ sub getIPaddress if (!defined($port)) { $port = "[0|1]"; } - + my $ppc = $request->{ppc}; my $vpd = $request->{vpd}; - -# only need to parse IP addresses for Frame/CEC/BPA/FSP + + # only need to parse IP addresses for Frame/CEC/BPA/FSP #my $type = xCAT::DBobjUtils->getnodetype($nodetocheck); - #my $type = $$attrs[4]; + #my $type = $$attrs[4]; if ($type) { my @children; my %node_side_pairs = (); - my $children_num = 0; + my $children_num = 0; my $parent; if ($type eq "bpa" or $type eq "fsp") { - + push @children, $nodetocheck; - - #my $tmp_s = $vpdtab->getNodeAttribs($nodetocheck, ['side']); - my $tmp_s = $vpd->{$nodetocheck}; + + #my $tmp_s = $vpdtab->getNodeAttribs($nodetocheck, ['side']); + my $tmp_s = $vpd->{$nodetocheck}; if ($tmp_s and $tmp_s =~ /(A|B)-\d/i) { - $side = $1; # get side for the fsp - + $side = $1; # get side for the fsp + } else { return -3; } } elsif ($type eq "frame" or $type eq "cec" or ($type =~ /lpar/i)) { + #In DFM - #1. when the node type is frame, its hcp( $nodetocheck ) is frame, - #and it will get the BPAs IPs for the Frame. - #2. when the node type is CEC, its hcp( $nodetocheck ) is CEC, - #and it will get the FSPs IPs for the CEC. - #3. when the node type is lpar, its hcp is the CEC. - #the $nodetocheck is its' hcp. So set $nodetocheck to $parent variable. - #And then get the FSPs IPs for the CEC. + #1. when the node type is frame, its hcp( $nodetocheck ) is frame, + #and it will get the BPAs IPs for the Frame. + #2. when the node type is CEC, its hcp( $nodetocheck ) is CEC, + #and it will get the FSPs IPs for the CEC. + #3. when the node type is lpar, its hcp is the CEC. + #the $nodetocheck is its' hcp. So set $nodetocheck to $parent variable. + #And then get the FSPs IPs for the CEC. $parent = $nodetocheck; } elsif ($type eq "blade") { return $ppc->{$nodetocheck}->{children}->[0]; } else { return undef; } - if( @children == 0 ) { - if( exists($ppc->{$parent} ) ) { - #for cec/frame, get the FSPs/BPAs from the hash we built in getHcpAttribs() before. - @children = @{$ppc->{$parent}->{children}}; + if (@children == 0) { + if (exists($ppc->{$parent})) { + + #for cec/frame, get the FSPs/BPAs from the hash we built in getHcpAttribs() before. + @children = @{ $ppc->{$parent}->{children} }; } else { - return undef; - } - } - foreach my $tmp_n( @children) { + return undef; + } + } + foreach my $tmp_n (@children) { my $tmp_s = $vpd->{$tmp_n}; if ($tmp_s and $tmp_s =~ /^$side-$port$/i) { $tmp_s =~ s/a/A/; $tmp_s =~ s/b/B/; if (xCAT::NetworkUtils::isIpaddr($tmp_n)) { - $node_side_pairs{$tmp_s} = $tmp_n; + $node_side_pairs{$tmp_s} = $tmp_n; $children_num++; } else { my $tmpip = xCAT::NetworkUtils->getipaddr($tmp_n); if (!$tmpip) { - #my $hoststab = xCAT::Table->new( 'hosts' ); - #my $tmp = $hoststab->getNodeAttribs($tmp_n, ['ip']); - #if ($tmp->{ip}) { - # $tmpip = $tmp->{ip}; - #} + + #my $hoststab = xCAT::Table->new( 'hosts' ); + #my $tmp = $hoststab->getNodeAttribs($tmp_n, ['ip']); + #if ($tmp->{ip}) { + # $tmpip = $tmp->{ip}; + #} } if ($tmpip) { $node_side_pairs{$tmp_s} = $tmpip; $children_num++; } - } # end of parse IP address for a fsp/bpa - } # end of parse a child's side - } #end of loop for children + } # end of parse IP address for a fsp/bpa + } # end of parse a child's side + } #end of loop for children if ($children_num == 0) { - return undef; #no children or brothers for this node. + return undef; #no children or brothers for this node. } - my @keys = qw(A-0 A-1 B-0 B-1); + my @keys = qw(A-0 A-1 B-0 B-1); my $out_strings = undef; foreach my $tmp (@keys) { if (!$node_side_pairs{$tmp}) { @@ -227,14 +232,14 @@ sub getIPaddress } } - $out_strings = $node_side_pairs{"A-0"}.','.$node_side_pairs{"A-1"}.','.$node_side_pairs{"B-0"}.','.$node_side_pairs{"B-1"}; + $out_strings = $node_side_pairs{"A-0"} . ',' . $node_side_pairs{"A-1"} . ',' . $node_side_pairs{"B-0"} . ',' . $node_side_pairs{"B-1"}; return $out_strings; } else { return undef; } } - + @@ -264,111 +269,115 @@ sub getIPaddress #------------------------------------------------------------------------------- sub fsp_api_action { - my $request = shift; - my $node_name = shift; - my $attrs = shift; - my $action = shift; - my $tooltype = shift; - my $parameter = shift; -# my $user = "HMC"; -# my $password = "abc123"; - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; - my $id = 1; - my $fsp_name = (); - my $fsp_ip = (); - my $target_list=(); - my $type = (); # fsp|lpar -- 0. BPA -- 1 + my $request = shift; + my $node_name = shift; + my $attrs = shift; + my $action = shift; + my $tooltype = shift; + my $parameter = shift; + + # my $user = "HMC"; + # my $password = "abc123"; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + my $id = 1; + my $fsp_name = (); + my $fsp_ip = (); + my $target_list = (); + my $type = (); # fsp|lpar -- 0. BPA -- 1 my @result; - my $Rc = 0 ; + my $Rc = 0; my %outhash = (); - my $res; + my $res; my $user; my $password; my $fsp_bpa_type; - - if( !defined($tooltype) ) { - $tooltype = 0; + + if (!defined($tooltype)) { + $tooltype = 0; } - $id = $$attrs[0]; - $fsp_name = $$attrs[3]; + $id = $$attrs[0]; + $fsp_name = $$attrs[3]; xCAT::MsgUtils->verbose_message($request, "fsp_api_action START node:$node_name,type:$$attrs[4]."); - if($$attrs[4] =~ /^fsp$/ || $$attrs[4] =~ /^lpar$/ || $$attrs[4] =~ /^cec$/) { - $type = 0; - $fsp_bpa_type="fsp"; - } elsif($$attrs[4] =~ /^bpa$/ || $$attrs[4] =~ /^frame$/) { - $type = 1; - $fsp_bpa_type="bpa"; - } elsif($$attrs[4] =~ /^blade$/) { - $type = 0; + if ($$attrs[4] =~ /^fsp$/ || $$attrs[4] =~ /^lpar$/ || $$attrs[4] =~ /^cec$/) { + $type = 0; + $fsp_bpa_type = "fsp"; + } elsif ($$attrs[4] =~ /^bpa$/ || $$attrs[4] =~ /^frame$/) { + $type = 1; + $fsp_bpa_type = "bpa"; + } elsif ($$attrs[4] =~ /^blade$/) { + $type = 0; $fsp_bpa_type = "blade"; - } else { + } else { $res = "$fsp_name\'s type is $$attrs[4]. Not support for $$attrs[4]"; - return ([$node_name, $res, -1]); - } - if( $action =~ /^add_connection$/) { + return ([ $node_name, $res, -1 ]); + } + if ($action =~ /^add_connection$/) { ############################ # Get IP address ############################ - $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name, $parameter ); - undef($parameter); + $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name, $parameter); + undef($parameter); } else { - $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name ); + $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name); } xCAT::MsgUtils->verbose_message($request, "fsp_api_action getIPaddress:$fsp_ip."); - if(!defined($fsp_ip)) { + if (!defined($fsp_ip)) { $res = "Failed to get IP address for $fsp_name or the related FSPs/BPAs."; - return ([$node_name, $res, -1]); + return ([ $node_name, $res, -1 ]); } - if($fsp_ip eq "-1") { + if ($fsp_ip eq "-1") { $res = "Cannot open vpd table"; - return ([$node_name, $res, -1]); - } elsif( $fsp_ip eq "-3") { + return ([ $node_name, $res, -1 ]); + } elsif ($fsp_ip eq "-3") { $res = "It doesn't have the FSPs or BPAs whose side is the value as specified or by default."; - return ([$node_name, $res, -1]); - } + return ([ $node_name, $res, -1 ]); + } #print "fsp name: $fsp_name\n"; #print "fsp ip: $fsp_ip\n"; - + #In DFM, only the add_connection action need the userid/password to create the connection - #between hdwr_svr and FSPs or BPAs. - if( $action =~ /^add_connection$/) { - my $tmp_node; - if( $$attrs[4] =~ /^cec$/ || $$attrs[4] =~ /^frame$/ ) { - $tmp_node = $node_name; - } elsif ($$attrs[4] =~ /^blade$/) { - $tmp_node = $$attrs[5]; - } else { - $tmp_node = $fsp_name; - } - - my $cred = $request->{$tmp_node}{cred}; - ($user, $password) = @$cred ; - #($user, $password) = xCAT::PPCdb::credentials( $tmp_node, $fsp_bpa_type,'HMC'); - if ( !$password) { - $res = "Cannot get password of userid 'HMC'. Please check table 'passwd' or 'ppcdirect'."; - return ([$node_name, $res, -1]); - } + #between hdwr_svr and FSPs or BPAs. + if ($action =~ /^add_connection$/) { + my $tmp_node; + if ($$attrs[4] =~ /^cec$/ || $$attrs[4] =~ /^frame$/) { + $tmp_node = $node_name; + } elsif ($$attrs[4] =~ /^blade$/) { + $tmp_node = $$attrs[5]; + } else { + $tmp_node = $fsp_name; + } + + my $cred = $request->{$tmp_node}{cred}; + ($user, $password) = @$cred; + + #($user, $password) = xCAT::PPCdb::credentials( $tmp_node, $fsp_bpa_type,'HMC'); + if (!$password) { + $res = "Cannot get password of userid 'HMC'. Please check table 'passwd' or 'ppcdirect'."; + return ([ $node_name, $res, -1 ]); + } + # The userid for creating connection only is "HMC". $user = 'HMC'; } my $cmd; my $install_dir = xCAT::TableUtils->getInstallDir(); - if( $action =~ /^(code_update|get_compatible_version_from_rpm)$/) { + if ($action =~ /^(code_update|get_compatible_version_from_rpm)$/) { $cmd = "$fsp_api -a $action -T $tooltype -t $type:$fsp_ip:$id:$node_name:$parameter -d $install_dir/packages_fw/"; - } elsif($action =~ /^code_updateD$/) { + } elsif ($action =~ /^code_updateD$/) { $cmd = "$fsp_api -a code_update -D -T $tooltype -t $type:$fsp_ip:$id:$node_name:$parameter -d $install_dir/packages_fw/"; - } elsif($action =~ /^add_connection$/) { - $cmd = "$fsp_api -a $action -u $user -p $password -T $tooltype -t $type:$fsp_ip:$id:$node_name:"; - } elsif ($action =~ /^set_frame_number$/) { - $cmd = "$fsp_api -a $action -T $tooltype -f $parameter -t $type:$fsp_ip:$id:$node_name:"; + } elsif ($action =~ /^add_connection$/) { + $cmd = "$fsp_api -a $action -u $user -p $password -T $tooltype -t $type:$fsp_ip:$id:$node_name:"; + } elsif ($action =~ /^set_frame_number$/) { + $cmd = "$fsp_api -a $action -T $tooltype -f $parameter -t $type:$fsp_ip:$id:$node_name:"; } else { - if( defined($parameter) ) { + if (defined($parameter)) { if ($action =~ /^set_(frame|cec|lpar)_name$/) { $cmd = "$fsp_api -a $action -n $parameter -T $tooltype -t $type:$fsp_ip:$id:$node_name:"; - } elsif( $parameter !=0 && $action =~ /^(on|reset)$/ ) { + } elsif ($parameter != 0 && $action =~ /^(on|reset)$/) { + #powerinterval for lpars power on $cmd = "$fsp_api -a $action -i $parameter -T $tooltype -t $type:$fsp_ip:$id:$node_name:"; } elsif ($action =~ /^part_set_lpar_def_state$/) { @@ -387,29 +396,32 @@ sub fsp_api_action { } } xCAT::MsgUtils->verbose_message($request, "fsp_api_action cmd:$cmd."); - #print "cmd: $cmd\n"; - $SIG{CHLD} = 'DEFAULT'; + + #print "cmd: $cmd\n"; + $SIG{CHLD} = 'DEFAULT'; + # secure passwords in verbose mode my $tmpv = $::VERBOSE; - if($action =~ /^add_connection$/) + if ($action =~ /^add_connection$/) { # password involved $::VERBOSE = 0; } $res = xCAT::Utils->runcmd($cmd, -1); - #$res = "good"; - $Rc = $::RUNCMD_RC; + + #$res = "good"; + $Rc = $::RUNCMD_RC; $::VERBOSE = $tmpv; - + ################## # output the prompt ################# #$outhash{ $node_name } = $res; - if(defined($res)) { + if (defined($res)) { $res =~ s/$node_name: //g; } xCAT::MsgUtils->verbose_message($request, "fsp_api_action return:$Rc."); - return( [$node_name,$res, $Rc] ); + return ([ $node_name, $res, $Rc ]); } #------------------------------------------------------------------------------- @@ -437,67 +449,72 @@ sub fsp_api_action { #------------------------------------------------------------------------------- sub fsp_state_action { - my $request = shift; - my $node_name = shift; - my $attrs = shift; - my $action = shift; - my $tooltype = shift; - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; - my $id = 0; - my $fsp_name = (); - my $fsp_ip = (); - my $target_list=(); - my $type = (); # fsp|lpar -- 0. BPA -- 1 + my $request = shift; + my $node_name = shift; + my $attrs = shift; + my $action = shift; + my $tooltype = shift; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + my $id = 0; + my $fsp_name = (); + my $fsp_ip = (); + my $target_list = (); + my $type = (); # fsp|lpar -- 0. BPA -- 1 my @result; - my $Rc = 0 ; + my $Rc = 0; my %outhash = (); - my @res; - - if( !defined($tooltype) ) { - $tooltype = 0; + my @res; + + if (!defined($tooltype)) { + $tooltype = 0; } - $fsp_name = $node_name; + $fsp_name = $node_name; + - xCAT::MsgUtils->verbose_message($request, "fsp_state_action START node:$node_name,type:$$attrs[4]."); - if( $$attrs[4] =~ /^(fsp|lpar|cec|blade)$/) { + if ($$attrs[4] =~ /^(fsp|lpar|cec|blade)$/) { $type = 0; - } else { - $type = 1; - } + } else { + $type = 1; + } ############################ # Get IP address ############################ - $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name ); - if(!defined($fsp_ip) or ($fsp_ip == -3)) { + $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name); + if (!defined($fsp_ip) or ($fsp_ip == -3)) { $res[0] = "Failed to get IP address for $fsp_name or the related FSPs/BPAs."; - return ([-1, $res[0]]); + return ([ -1, $res[0] ]); } - + xCAT::MsgUtils->verbose_message($request, "fsp_state_action getIPaddress:$fsp_ip."); + #print "fsp name: $fsp_name\n"; #print "fsp ip: $fsp_ip\n"; my $cmd; + #$cmd = "$fsp_api -a $action -u $user -p $password -T $tooltype -t $type:$fsp_ip:$id:$node_name:"; $cmd = "$fsp_api -a $action -T $tooltype -t $type:$fsp_ip:$id:$node_name:"; xCAT::MsgUtils->verbose_message($request, "fsp_state_action cmd:$cmd."); - #print "cmd: $cmd\n"; - $SIG{CHLD} = 'DEFAULT'; + + #print "cmd: $cmd\n"; + $SIG{CHLD} = 'DEFAULT'; @res = xCAT::Utils->runcmd($cmd, -1); - #$res = "good"; + + #$res = "good"; $Rc = $::RUNCMD_RC; + #$Rc = -1; ################## # output the prompt ################# #$outhash{ $node_name } = $res; - if( @res ) { + if (@res) { $res[0] =~ s/$node_name: //g; } xCAT::MsgUtils->verbose_message($request, "fsp_state_action return:$Rc."); - return( [$Rc,@res] ); + return ([ $Rc, @res ]); } @@ -526,99 +543,102 @@ sub fsp_state_action { #------------------------------------------------------------------------------- sub fsp_api_create_partition { - my $request = shift; - my $starting_lpar_id = shift; - my $octant_cfg = shift; - my $node_number = shift; - my $attrs = shift; - my $action = shift; - my $tooltype = shift; -# my $user = "HMC"; -# my $password = "abc123"; - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; - my $id = 0; - my $fsp_name = (); - my $fsp_ip = (); - my $target_list=(); - my $type = (); # fsp|lpar -- 0. BPA -- 1 + my $request = shift; + my $starting_lpar_id = shift; + my $octant_cfg = shift; + my $node_number = shift; + my $attrs = shift; + my $action = shift; + my $tooltype = shift; + + # my $user = "HMC"; + # my $password = "abc123"; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + my $id = 0; + my $fsp_name = (); + my $fsp_ip = (); + my $target_list = (); + my $type = (); # fsp|lpar -- 0. BPA -- 1 my @result; - my $Rc = 0 ; + my $Rc = 0; my %outhash = (); - my $res; + my $res; my $number_of_lpars_per_octant; my $octant_num_needed; my $starting_octant_id; my $octant_conf_value; - my $octant_cfg_value = $octant_cfg->{octant_cfg_value}; + my $octant_cfg_value = $octant_cfg->{octant_cfg_value}; my $new_pending_interleave_mode = $octant_cfg->{memory_interleave}; - - if( !defined($tooltype) ) { - $tooltype = 0; + + if (!defined($tooltype)) { + $tooltype = 0; } - - #use Data::Dumper; + + #use Data::Dumper; #print Dumper($attrs); - $fsp_name = $$attrs[3]; - $type = 0; + $fsp_name = $$attrs[3]; + $type = 0; ############################ # Get IP address ############################ - $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name ); - if(!defined($fsp_ip) or ($fsp_ip == -3)) { + $fsp_ip = getIPaddress($request, $$attrs[4], $fsp_name); + if (!defined($fsp_ip) or ($fsp_ip == -3)) { $res = "Failed to get IP address for $fsp_name."; - return ([$fsp_name, $res, -1]); + return ([ $fsp_name, $res, -1 ]); } - + #print "fsp name: $fsp_name\n"; #print "fsp ip: $fsp_ip\n"; - $starting_octant_id = int($starting_lpar_id/4); - my $lparnum_from_octant = 0; + $starting_octant_id = int($starting_lpar_id / 4); + my $lparnum_from_octant = 0; my $new_pending_pump_mode = $octant_cfg->{pendingpumpmode}; my $parameters; + #my $parameters = "$new_pending_pump_mode:$octant_num_needed"; - my $octant_id = $starting_octant_id ; - my $i = 0; - for($i=$starting_octant_id; $i < (keys %$octant_cfg_value) ; $i++) { - if(! exists($octant_cfg_value->{$i})) { - $res = "starting LPAR id is $starting_lpar_id, starting octant id is $starting_octant_id, octant configuration value isn't provided. Wrong plan."; - return ([$fsp_name, $res, -1]); + my $octant_id = $starting_octant_id; + my $i = 0; + for ($i = $starting_octant_id ; $i < (keys %$octant_cfg_value) ; $i++) { + if (!exists($octant_cfg_value->{$i})) { + $res = "starting LPAR id is $starting_lpar_id, starting octant id is $starting_octant_id, octant configuration value isn't provided. Wrong plan."; + return ([ $fsp_name, $res, -1 ]); } - my $octant_conf_value = $octant_cfg_value->{$i}; + my $octant_conf_value = $octant_cfg_value->{$i}; + #octant configuration values could be 1,2,3,4,5 ; AS following: # 1 - 1 partition with all cpus and memory of the octant # 2 - 2 partitions with a 50/50 split of cpus and memory # 3 - 3 partitions with a 25/25/50 split of cpus and memory # 4 - 4 partitions with a 25/25/25/25 split of cpus and memory # 5 - 2 partitions with a 25/75 split of cpus and memory - if($octant_conf_value == 1) { - $number_of_lpars_per_octant = 1; - } elsif($octant_conf_value == 2 ) { - $number_of_lpars_per_octant = 2; - } elsif($octant_conf_value == 3 ) { - $number_of_lpars_per_octant = 3; - } elsif($octant_conf_value == 4 ) { - $number_of_lpars_per_octant = 4; - } elsif($octant_conf_value == 5 ) { - $number_of_lpars_per_octant = 2; + if ($octant_conf_value == 1) { + $number_of_lpars_per_octant = 1; + } elsif ($octant_conf_value == 2) { + $number_of_lpars_per_octant = 2; + } elsif ($octant_conf_value == 3) { + $number_of_lpars_per_octant = 3; + } elsif ($octant_conf_value == 4) { + $number_of_lpars_per_octant = 4; + } elsif ($octant_conf_value == 5) { + $number_of_lpars_per_octant = 2; } else { $res = "octant $i, configuration values: $octant_conf_value. Wrong octant configuration values!\n"; - return ([$fsp_name, $res, -1]); - } + return ([ $fsp_name, $res, -1 ]); + } + + $lparnum_from_octant += $number_of_lpars_per_octant; + $octant_num_needed++; + $parameters .= ":$octant_id:$octant_conf_value:$new_pending_interleave_mode"; + - $lparnum_from_octant += $number_of_lpars_per_octant; - $octant_num_needed++; - $parameters .= ":$octant_id:$octant_conf_value:$new_pending_interleave_mode"; - - - } - $parameters = "$new_pending_pump_mode:$octant_num_needed".$parameters; - if($node_number != $lparnum_from_octant ) { - $res = "According to the partition split rule and the starting LPAR id, $lparnum_from_octant LPARs will be gotten. But the noderange has $node_number node. Wrong plan.\n"; - return ([$fsp_name, $res, -1]); } - + $parameters = "$new_pending_pump_mode:$octant_num_needed" . $parameters; + if ($node_number != $lparnum_from_octant) { + $res = "According to the partition split rule and the starting LPAR id, $lparnum_from_octant LPARs will be gotten. But the noderange has $node_number node. Wrong plan.\n"; + return ([ $fsp_name, $res, -1 ]); + } + #my $new_pending_pump_mode = 1; #my $parameters = "$new_pending_pump_mode:$octant_num_needed"; #my $octant_id = $starting_octant_id ; @@ -631,21 +651,24 @@ sub fsp_api_create_partition { my $cmd; $cmd = "$fsp_api -a $action -T $tooltype -t $type:$fsp_ip:0:$fsp_name:$parameters"; + #fsp-api -a set_octant_cfg -t 0:40.7.5.1:0:M019:1:1:7:4:2 - #print "cmd: $cmd\n"; - $SIG{CHLD} = 'DEFAULT'; + #print "cmd: $cmd\n"; + $SIG{CHLD} = 'DEFAULT'; $res = xCAT::Utils->runcmd($cmd, -1); - #$res = "good"; + + #$res = "good"; $Rc = $::RUNCMD_RC; + #$Rc = -1; ################## # output the prompt ################# #$outhash{ $node_name } = $res; - if( defined($res) ) { + if (defined($res)) { $res =~ s/$fsp_name: //; } - return( [$fsp_name,$res, $Rc] ); + return ([ $fsp_name, $res, $Rc ]); } diff --git a/perl-xCAT/xCAT/FSPboot.pm b/perl-xCAT/xCAT/FSPboot.pm index eaa4dd85f..fd9843611 100644 --- a/perl-xCAT/xCAT/FSPboot.pm +++ b/perl-xCAT/xCAT/FSPboot.pm @@ -11,7 +11,7 @@ use xCAT::PPCboot; use xCAT::LparNetbootExp; ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { xCAT::PPCboot::parse_args(@_); @@ -19,7 +19,7 @@ sub parse_args { ########################################################################## -# Netboot the lpar +# Netboot the lpar ########################################################################## sub do_rnetboot { @@ -36,14 +36,14 @@ sub do_rnetboot { my $Rc = SUCCESS; my $cmd; my %optarg; - + ####################################### # Disconnect Expect session ####################################### #xCAT::PPCcli::disconnect( $exp ); - + ####################################### - # Get node data + # Get node data ####################################### my $id = @$d[0]; my $pprofile = @$d[1]; @@ -51,10 +51,10 @@ sub do_rnetboot { my $hcp = @$d[3]; ######################################## - ## Find Expect script + ## Find Expect script ######################################## #$cmd = ($::XCATROOT) ? "$::XCATROOT/sbin/" : "/opt/xcat/sbin/"; - #$cmd .= "lpar_netboot.expect"; + #$cmd .= "lpar_netboot.expect"; # ######################################## ## Check command installed @@ -65,7 +65,7 @@ sub do_rnetboot { ####################################### # Save user name and passwd of hcp to # environment variables. - # lpar_netboot.expect depends on it + # lpar_netboot.expect depends on it ####################################### $ENV{HCP_USERID} = $userid; $ENV{HCP_PASSWD} = $pw; @@ -73,34 +73,40 @@ sub do_rnetboot { ####################################### # Turn on verbose and debugging ####################################### - if ( ${$request->{arg}}[0] eq '-V' ) { + if (${ $request->{arg} }[0] eq '-V') { + #$cmd.= " -v -x"; - $optarg{'v'} = 1; #for verbose - $optarg{'x'} = 1; #for debug + $optarg{'v'} = 1; #for verbose + $optarg{'x'} = 1; #for debug } ####################################### # Force LPAR shutdown ####################################### - if ( exists( $opt->{f} ) || !xCAT::Utils->isAIX() ) { + if (exists($opt->{f}) || !xCAT::Utils->isAIX()) { + #$cmd.= " -i"; $optarg{'i'} = 1; - } + } ####################################### # Write boot order ####################################### - if ( exists( $opt->{s} )) { + if (exists($opt->{s})) { foreach ($opt->{s}) { - if ( /^net$/ ) { + if (/^net$/) { + #$cmd.= " -w 1"; $optarg{'w'} = 1; - } elsif ( /^net,hd$/ ) { + } elsif (/^net,hd$/) { + #$cmd.= " -w 2"; $optarg{'w'} = 2; - } elsif ( /^hd,net$/ ) { + } elsif (/^hd,net$/) { + #$cmd.= " -w 3"; $optarg{'w'} = 3; - } elsif ( /^hd$/ ) { + } elsif (/^hd$/) { + #$cmd.= " -w 4"; $optarg{'w'} = 4; } @@ -108,7 +114,7 @@ sub do_rnetboot { } my @macs = split /\|/, $opt->{m}; - foreach my $mac ( @macs ) { + foreach my $mac (@macs) { $mac = lc($mac); ####################################### # Network specified @@ -121,20 +127,23 @@ sub do_rnetboot { $optarg{'C'} = $opt->{C}; $optarg{'N'} = $opt->{N}; $optarg{'G'} = $opt->{G}; - if ( exists( $opt->{o} )) { + if (exists($opt->{o})) { + #$cmd.= " -o"; $optarg{'o'} = 1; } - my %client_nethash = xCAT::DBobjUtils->getNetwkInfo( [$node] ); - if ( grep /hf/, $client_nethash{$node}{mgtifname} ) { + my %client_nethash = xCAT::DBobjUtils->getNetwkInfo([$node]); + if (grep /hf/, $client_nethash{$node}{mgtifname}) { + #$cmd.= " -t hfi-ent"; $optarg{'t'} = "hfi-ent"; } else { + #$cmd.= " -t ent"; $optarg{'t'} = "ent"; } - + $pprofile = "not_use"; #lpar_netboot.expect need pprofile for p5 & p6, but for p7 ih, we don't use this attribute. ####################################### @@ -142,21 +151,22 @@ sub do_rnetboot { ####################################### #$cmd.= " -f \"$name\" \"$pprofile\" \"$fsp\" $id $hcp \"$node\""; #print "cmd: $cmd\n"; - $optarg{'f'} = 1; - $optarg{'name'} = $name; + $optarg{'f'} = 1; + $optarg{'name'} = $name; $optarg{'pprofile'} = $pprofile; - $optarg{'fsp'} = $fsp; - $optarg{'id'} = $id; - $optarg{'hcp'} = $hcp; - $optarg{'node'} = $node; + $optarg{'fsp'} = $fsp; + $optarg{'id'} = $id; + $optarg{'hcp'} = $hcp; + $optarg{'node'} = $node; my $done = 0; - while ( $done < 2 ) { + + while ($done < 2) { $result = ""; - $Rc = SUCCESS; + $Rc = SUCCESS; ######################################## ## Execute command ######################################## - #print "cmd:$cmd\n"; + #print "cmd:$cmd\n"; #my $pid = open( OUTPUT, "$cmd 2>&1 |"); #$SIG{INT} = $SIG{TERM} = sub { #prepare to process job termination and propogate it down # kill 9, $pid; @@ -172,7 +182,7 @@ sub do_rnetboot { # $result.=$_; #} #close OUTPUT; - + ######################################## ## Get command exit code ######################################## @@ -188,7 +198,7 @@ sub do_rnetboot { ####################################### $result = xCAT::LparNetbootExp->lparnetbootexp(\%optarg, $request); $Rc = @$result[0]; - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { $done = 2; } else { $done = $done + 1; @@ -196,7 +206,7 @@ sub do_rnetboot { } } - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { last; } } @@ -215,20 +225,20 @@ sub rnetboot { my $options = $request->{opt}; my $hwtype = @$exp[2]; my $result; - my $name = $request->{node}; + my $name = $request->{node}; my $callback = $request->{callback}; ##################################### - # Get node data + # Get node data ##################################### my $lparid = @$d[0]; my $mtms = @$d[2]; my $type = @$d[4]; my $node = @$d[6]; - my $o = @$d[7]; + my $o = @$d[7]; ##################################### - # Gateway (-G) - # Server (-S) + # Gateway (-G) + # Server (-S) # Client (-C) # mac (-m) ##################################### @@ -246,31 +256,31 @@ sub rnetboot { } ##################################### - # Strip colons from mac address + # Strip colons from mac address ##################################### $opt{m} =~ s/://g; ##################################### - # Force LPAR shutdown + # Force LPAR shutdown ##################################### - if ( exists( $options->{f} )) { + if (exists($options->{f})) { $opt{f} = 1; } ##################################### # Write boot device order ##################################### - if ( exists( $options->{s} )) { + if (exists($options->{s})) { $opt{s} = $options->{s}; } - if ( exists( $options->{o} )) { + if (exists($options->{o})) { $opt{o} = $options->{o}; } ##################################### - # Invalid target hardware + # Invalid target hardware ##################################### - if ( $type !~ /^lpar$/ ) { - return( [[$name,"Not supported",RC_ERROR]] ); + if ($type !~ /^lpar$/) { + return ([ [ $name, "Not supported", RC_ERROR ] ]); } ######################################### # Get name known by HCP @@ -306,78 +316,82 @@ sub rnetboot { # It is not allowed to rinitialize node # if it is in boot state ######################################### - if ( !exists( $options->{F} ) && !xCAT::Utils->isAIX() ) { + if (!exists($options->{F}) && !xCAT::Utils->isAIX()) { my $chaintab = xCAT::Table->new('chain'); - my $vcon = $chaintab->getAttribs({ node => "$node"}, 'currstate'); - if ( $vcon and $vcon->{"currstate"} and $vcon->{"currstate"} eq "boot" ) { - return( [[$node,"Node is in boot state. Use nodeset command before rnetboot or use -F option with rnetboot",RC_ERROR]] ); + my $vcon = $chaintab->getAttribs({ node => "$node" }, 'currstate'); + if ($vcon and $vcon->{"currstate"} and $vcon->{"currstate"} eq "boot") { + return ([ [ $node, "Node is in boot state. Use nodeset command before rnetboot or use -F option with rnetboot", RC_ERROR ] ]); } } #my $sitetab = xCAT::Table->new('site'); #my $vcon = $sitetab->getAttribs({key => "conserverondemand"}, 'value'); #if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { - # $result = xCAT::PPCcli::lpar_netboot( - # $exp, - # $request->{verbose}, - # $name, - # $d, - # \%opt ); + # $result = xCAT::PPCcli::lpar_netboot( + # $exp, + # $request->{verbose}, + # $name, + # $d, + # \%opt ); # return( [[$node,"Not support conserverondemand's value is yes",RC_ERROR]] ); #} else { - ######################################### - # Manually perform boot. - ######################################### - $result = do_rnetboot( $request, $d, $exp, $name, $node, \%opt ); + ######################################### + # Manually perform boot. + ######################################### + $result = do_rnetboot($request, $d, $exp, $name, $node, \%opt); + #} #$sitetab->close; if (defined($request->{opt}->{m})) { - - my $retries = 0; + + my $retries = 0; my @monnodes = ($name); my $monsettings = xCAT::Utils->generate_monsettings($request, \@monnodes); - xCAT::Utils->monitor_installation($request, $monsettings);; - while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{$monsettings->{'nodes'}}) > 0) { + xCAT::Utils->monitor_installation($request, $monsettings); + while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{ $monsettings->{'nodes'} }) > 0) { ####lparnetboot can not support multiple nodes in one invocation ####for now, does not know how the $d and \%opt will be changed if ####support mulitiple nodes in one invocation, ####so just use the original node name and node attribute array and hash - - my $rsp={}; - $rsp->{data}->[0] = "$node: Reinitializing the installation: $retries retry"; - xCAT::MsgUtils->message("I", $rsp, $callback); - #if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { - # $result = xCAT::PPCcli::lpar_netboot( - # $exp, - # $request->{verbose}, - # $name, - # $d, - # \%opt ); + + my $rsp = {}; + $rsp->{data}->[0] = "$node: Reinitializing the installation: $retries retry"; + xCAT::MsgUtils->message("I", $rsp, $callback); + + #if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { + # $result = xCAT::PPCcli::lpar_netboot( + # $exp, + # $request->{verbose}, + # $name, + # $d, + # \%opt ); #return( [[$node,"Not support conserverondemand's value is yes",RC_ERROR]] ); #} else { - $result = do_rnetboot( $request, $d, $exp, $name, $node, \%opt ); + $result = do_rnetboot($request, $d, $exp, $name, $node, \%opt); + #} xCAT::Utils->monitor_installation($request, $monsettings); - + } + #failed after retries - if (scalar(keys %{$monsettings->{'nodes'}}) > 0) { - foreach my $node (keys %{$monsettings->{'nodes'}}) { - my $rsp={}; + if (scalar(keys %{ $monsettings->{'nodes'} }) > 0) { + foreach my $node (keys %{ $monsettings->{'nodes'} }) { + my $rsp = {}; $rsp->{data}->[0] = "The node \"$node\" can not reach the expected status after $monsettings->{'retrycount'} retries, the installation for this done failed"; xCAT::MsgUtils->message("E", $rsp, $callback); } - } + } } $Rc = shift(@$result); - + ################################## # Form string from array results ################################## - if ( exists($request->{verbose}) ) { - return( [[$node,join( '', @$result ),$Rc]] ); + if (exists($request->{verbose})) { + return ([ [ $node, join('', @$result), $Rc ] ]); } ################################## # Return error @@ -393,18 +407,18 @@ sub rnetboot { # lpar_netboot: can not find mac address 42DAB. # ################################## - if ( $Rc != SUCCESS ) { - if ( @$result[0] =~ /lpar_netboot (.*)/ ) { - return( [[$node,$1,$Rc]] ); + if ($Rc != SUCCESS) { + if (@$result[0] =~ /lpar_netboot (.*)/) { + return ([ [ $node, $1, $Rc ] ]); } - return( [[$node,join( '', @$result ),$Rc]] ); + return ([ [ $node, join('', @$result), $Rc ] ]); } ################################## # Split array into string ################################## my $data = @$result[0]; - if ( $hwtype eq "hmc" ) { - $data = join( '', @$result ); + if ($hwtype eq "hmc") { + $data = join('', @$result); } ################################## # lpar_netboot returns: @@ -419,8 +433,8 @@ sub rnetboot { # # Finished. # ##################################### - if ( $data =~ /Finished/) { - return( [[$node,"Success",$Rc]] ); + if ($data =~ /Finished/) { + return ([ [ $node, "Success", $Rc ] ]); } ##################################### # Can still be error w/ Rc=0: @@ -434,12 +448,12 @@ sub rnetboot { # lpar_netboot: bootp operation failed. # ##################################### - if ( $data =~ /lpar_netboot (.*)/ ) { - return( [[$node,$1,RC_ERROR]] ); + if ($data =~ /lpar_netboot (.*)/) { + return ([ [ $node, $1, RC_ERROR ] ]); } - return( [[$node,$data,RC_ERROR]] ); + return ([ [ $node, $data, RC_ERROR ] ]); } - + 1; diff --git a/perl-xCAT/xCAT/FSPbootseq.pm b/perl-xCAT/xCAT/FSPbootseq.pm index 98f3da0a6..8f6ba2e75 100644 --- a/perl-xCAT/xCAT/FSPbootseq.pm +++ b/perl-xCAT/xCAT/FSPbootseq.pm @@ -8,10 +8,11 @@ use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::NetworkUtils; use xCAT::FSPUtils; use xCAT::MsgUtils qw(verbose_message); + #use Data::Dumper; ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { @@ -20,22 +21,22 @@ sub parse_args { my $cmd = $request->{command}; my $args = $request->{arg}; my $node = $request->{node}; - my $vers = - my @VERSION = qw( 2.6 ); - my @dev = qw(hfi net); - + my $vers = + my @VERSION = qw( 2.6 ); + my @dev = qw(hfi net); + ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "Missing command with rbootseq in DFM, net or hfi ?" )); + if (!defined($args)) { + return (usage("Missing command with rbootseq in DFM, net or hfi ?")); } ############################################# @@ -43,12 +44,12 @@ sub parse_args { # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt,qw(h|help V|verbose v|version ))) { - return( usage() ); + if (!GetOptions(\%opt, qw(h|help V|verbose v|version ))) { + return (usage()); } #################################### # Option -h for Help @@ -59,8 +60,8 @@ sub parse_args { #################################### # Option -v for version #################################### - if ( exists( $opt{v} )) { - return( \@VERSION ); + if (exists($opt{v})) { + return (\@VERSION); } #################################### # Check for "-" with no option @@ -76,39 +77,39 @@ sub parse_args { # return(usage( "Invalid Argument: $ARGV[0]" )); #} - my $command = grep(/^$ARGV[0]$/, @dev ); - if ( !defined( $command )) { - return(usage( "Invalid command: $ARGV[0]" )); + my $command = grep(/^$ARGV[0]$/, @dev); + if (!defined($command)) { + return (usage("Invalid command: $ARGV[0]")); } - if( $ARGV[0] =~/^hfi$/) { + if ($ARGV[0] =~ /^hfi$/) { $opt{hfi} = 1; - } elsif ( $ARGV[0] =~/^net$/) { + } elsif ($ARGV[0] =~ /^net$/) { $opt{net} = 1; } else { - return(usage( "Invalid Argument: $ARGV[0]" )); + return (usage("Invalid Argument: $ARGV[0]")); } shift @ARGV; - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } - - + + #print "in parse_args:\n"; #print $command; - #print Dumper(\%opt); - + #print Dumper(\%opt); + my $nodetype = xCAT::DBobjUtils->getnodetype($$node[0], "ppc"); - if( $nodetype =~ /^blade$/) { - $request->{callback}->({data =>[ "After running rebootseq on the nodes successfully, it's required to run to make the setting be permanent"]}); - } + if ($nodetype =~ /^blade$/) { + $request->{callback}->({ data => ["After running rebootseq on the nodes successfully, it's required to run to make the setting be permanent"] }); + } #################################### - # Set method to invoke + # Set method to invoke #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } @@ -120,32 +121,33 @@ sub rbootseq { my $request = shift; my $d = shift; my $opt = $request->{opt}; - my @output ; - my $tooltype = 0; + my @output; + my $tooltype = 0; my $parameter; my $bootp_retries = 5; my $tftp_retries = 5; my $blksize = 512; my $hash; - my $node_name = @$d[6]; - my $o = @$d[7]; - + my $node_name = @$d[6]; + my $o = @$d[7]; + #print "in setbootseq:\n"; #print "request\n"; #print Dumper($request); - #print "d"; + #print "d"; #print Dumper($d); - - xCAT::MsgUtils->verbose_message($request, "rbootseq START for node:$node_name, type=$$d[4]."); - if (!($$d[4] =~ /^(lpar|blade)$/)) { - push @output, [$node_name, "\'boot\' command not supported for CEC or BPA", -1 ]; + + xCAT::MsgUtils->verbose_message($request, "rbootseq START for node:$node_name, type=$$d[4]."); + if (!($$d[4] =~ /^(lpar|blade)$/)) { + push @output, [ $node_name, "\'boot\' command not supported for CEC or BPA", -1 ]; return (\@output); } - # add checking the power state of the cec - xCAT::MsgUtils->verbose_message($request, "rbootseq check machine state for node:$node_name."); - my $power_state = xCAT::FSPUtils::fsp_api_action ($request, $node_name, $d, "cec_state", $tooltype); - if ( @$power_state[2] != 0 ) { - push @output, [$node_name, @$power_state[1], -1 ]; + + # add checking the power state of the cec + xCAT::MsgUtils->verbose_message($request, "rbootseq check machine state for node:$node_name."); + my $power_state = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "cec_state", $tooltype); + if (@$power_state[2] != 0) { + push @output, [ $node_name, @$power_state[1], -1 ]; return (\@output); } unless (@$power_state[1] and @$power_state[1] =~ /operating|standby/) { @@ -153,88 +155,90 @@ sub rbootseq { my $state; if ($$d[4] eq 'blade') { $machine = "blade"; - $state = "on"; + $state = "on"; } else { $machine = "CEC"; - $state = "power on"; + $state = "power on"; } - push @output, [$node_name, "\'boot\' command can only support while the $machine is in the \'$state\' state", -1]; + push @output, [ $node_name, "\'boot\' command can only support while the $machine is in the \'$state\' state", -1 ]; return (\@output); - } - if( $opt->{net} ) { - my $mactab = xCAT::Table->new( 'mac'); - unless($mactab) { - push @output, [$node_name, "Cannot open mac table", -1 ]; - return (\@output); - } - - my $mac_hash = $mactab->getNodeAttribs( $node_name,[qw(mac)]); - my $mac = $mac_hash->{mac}; - if( !defined($mac) ) { - push @output, [$node_name, "No mac address in mac table", -1 ]; - } - $mactab->close(); + } + if ($opt->{net}) { + my $mactab = xCAT::Table->new('mac'); + unless ($mactab) { + push @output, [ $node_name, "Cannot open mac table", -1 ]; + return (\@output); + } - if( $mac =~ /\| /) { - #01:02:03:04:05:0E!node5|01:02:03:05:0F!node6-eth1 - my @mac_t = split(/\|/,$mac); - my $m; - my $m_t; - foreach $m (@mac_t) { - if(($m =~ /([\w:]{12})!$node_name/) || ($m =~ /([\w:]{17})!$node_name/)) { - $m_t = $1; - last; - } + my $mac_hash = $mactab->getNodeAttribs($node_name, [qw(mac)]); + my $mac = $mac_hash->{mac}; + if (!defined($mac)) { + push @output, [ $node_name, "No mac address in mac table", -1 ]; + } + $mactab->close(); + + if ($mac =~ /\| /) { + + #01:02:03:04:05:0E!node5|01:02:03:05:0F!node6-eth1 + my @mac_t = split(/\|/, $mac); + my $m; + my $m_t; + foreach $m (@mac_t) { + if (($m =~ /([\w:]{12})!$node_name/) || ($m =~ /([\w:]{17})!$node_name/)) { + $m_t = $1; + last; + } } - if( !defined($m_t)) { - $mac = $mac_t[0]; - } else { - $mac = $m_t; - } - } - - if( $mac =~ /\:/) { - $mac =~ s/\://g; - } - - if($mac =~/^(\w{12})$/) { - - $parameter = "mac=$mac:speed=auto,duplex=auto,$o->{server},,$o->{client},$o->{gateway},$bootp_retries,$tftp_retries,$o->{netmask},$blksize"; - } else { - push @output, [$node_name, "The mac address in mac table could NOT be used for rbootseq with -net. HFI mac , or other wrong format?", -1 ]; - return( \@output ); - } - xCAT::MsgUtils->verbose_message($request, "rbootseq <$node_name> net=$parameter"); - } - - if( $opt->{hfi}) { - - $parameter = "/hfi-iohub/hfi-ethernet:$o->{server},,$o->{client},$o->{gateway},$bootp_retries,$tftp_retries,$o->{netmask},$blksize"; - - xCAT::MsgUtils->verbose_message($request, "rbootseq <$node_name> hfi=$parameter"); - } - - xCAT::MsgUtils->verbose_message($request, "rbootseq set_lpar_bootstring for node:$node_name."); - my $res = xCAT::FSPUtils::fsp_api_action ($request, $node_name, $d, "set_lpar_bootstring", $tooltype, $parameter); - #print "In boot, state\n"; - #print Dumper($res); - my $Rc = @$res[2]; - my $data = @$res[1]; - - ################################## - # Output error - ################################## - xCAT::MsgUtils->verbose_message($request, "rbootseq return:$Rc."); - if ( $Rc != SUCCESS ) { - push @output, [$node_name,$data,$Rc]; - } else { - push @output,[$node_name, "Success", 0]; + if (!defined($m_t)) { + $mac = $mac_t[0]; + } else { + $mac = $m_t; + } } - return( \@output ); + if ($mac =~ /\:/) { + $mac =~ s/\://g; + } + + if ($mac =~ /^(\w{12})$/) { + + $parameter = "mac=$mac:speed=auto,duplex=auto,$o->{server},,$o->{client},$o->{gateway},$bootp_retries,$tftp_retries,$o->{netmask},$blksize"; + } else { + push @output, [ $node_name, "The mac address in mac table could NOT be used for rbootseq with -net. HFI mac , or other wrong format?", -1 ]; + return (\@output); + } + xCAT::MsgUtils->verbose_message($request, "rbootseq <$node_name> net=$parameter"); + } + + if ($opt->{hfi}) { + + $parameter = "/hfi-iohub/hfi-ethernet:$o->{server},,$o->{client},$o->{gateway},$bootp_retries,$tftp_retries,$o->{netmask},$blksize"; + + xCAT::MsgUtils->verbose_message($request, "rbootseq <$node_name> hfi=$parameter"); + } + + xCAT::MsgUtils->verbose_message($request, "rbootseq set_lpar_bootstring for node:$node_name."); + my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "set_lpar_bootstring", $tooltype, $parameter); + + #print "In boot, state\n"; + #print Dumper($res); + my $Rc = @$res[2]; + my $data = @$res[1]; + + ################################## + # Output error + ################################## + xCAT::MsgUtils->verbose_message($request, "rbootseq return:$Rc."); + if ($Rc != SUCCESS) { + push @output, [ $node_name, $data, $Rc ]; + } else { + push @output, [ $node_name, "Success", 0 ]; + } + + return (\@output); } diff --git a/perl-xCAT/xCAT/FSPcfg.pm b/perl-xCAT/xCAT/FSPcfg.pm index dbefb0831..3d2a3bef3 100644 --- a/perl-xCAT/xCAT/FSPcfg.pm +++ b/perl-xCAT/xCAT/FSPcfg.pm @@ -8,6 +8,7 @@ use xCAT::Utils; use xCAT::FSPUtils; use xCAT::TableUtils; use xCAT::PPCcfg; + #use Data::Dumper; #use xCAT::PPCcli; use xCAT::MsgUtils qw(verbose_message); @@ -15,13 +16,13 @@ use xCAT::MsgUtils qw(verbose_message); ########################################## # Globals ########################################## -my %rspconfig = ( - frame => \&frame, - cec_off_policy => \&cec_off_policy, +my %rspconfig = ( + frame => \&frame, + cec_off_policy => \&cec_off_policy, ); -my %default_passwd = ( - HMC => "", +my %default_passwd = ( + HMC => "", admin => "admin", general => "general", ); @@ -30,14 +31,14 @@ my %default_passwd = ( # Parse the command line for options and operands ########################################################################## sub array_to_string { - my $array = shift; + my $array = shift; my $string = ""; - my $i = 0; + my $i = 0; if (!scalar(@$array)) { return undef; } $string .= "\'$array->[0]\'"; - for ($i = 1; $i < scalar(@$array) - 1; $i++) { + for ($i = 1 ; $i < scalar(@$array) - 1 ; $i++) { $string .= ", "; $string .= "\'$array->[$i]\'"; } @@ -48,18 +49,18 @@ sub array_to_string { } sub check_command { - my $cmd = shift; - my $rsp = shift; + my $cmd = shift; + my $rsp = shift; my @type = (); foreach my $tmp_type (keys %$rsp) { - if (grep (/^$cmd$/, @{$rsp->{$tmp_type}})) { + if (grep (/^$cmd$/, @{ $rsp->{$tmp_type} })) { push @type, $tmp_type; - } + } } if (!scalar(@type)) { return undef; } else { - return &array_to_string(\@type); + return &array_to_string(\@type); } } @@ -70,7 +71,7 @@ sub parse_args { my $args = $request->{arg}; my %opt = (); my %cmds = (); - my @fsp = ( + my @fsp = ( "HMC_passwd", "admin_passwd", "general_passwd", @@ -79,7 +80,7 @@ sub parse_args { "cec_off_policy" ); my @bpa = ( - "frame", + "frame", "HMC_passwd", "admin_passwd", "general_passwd", @@ -101,7 +102,7 @@ sub parse_args { "huge_page" ); my @frame = ( - "frame", + "frame", "HMC_passwd", "admin_passwd", "general_passwd", @@ -116,13 +117,13 @@ sub parse_args { "pending_power_on_side" ); - - + + my %rsp = ( fsp => \@fsp, bpa => \@bpa, cec => \@cec, - blade => \@blade, + blade => \@blade, frame => \@frame, ); ############################################# @@ -131,7 +132,7 @@ sub parse_args { #my $typetab = xCAT::Table->new( 'nodetype' ); #my $nodes = $request->{node}; #foreach (@$nodes) { - # if ( defined( $typetab )) { + # if ( defined( $typetab )) { # my ($ent) = $typetab->getAttribs({ node=>$_},'nodetype'); # if ( defined($ent) ) { # $request->{hwtype} = $ent->{nodetype}; @@ -141,117 +142,117 @@ sub parse_args { # } # #} - + my $nodes = $request->{node}; my $typehash = xCAT::DBobjUtils->getnodetype($nodes, "ppc"); foreach my $nn (@$nodes) { - $request->{hwtype} =$$typehash{$nn}; + $request->{hwtype} = $$typehash{$nn}; last if ($request->{hwtype}); } - - my $supported = $rsp{$request->{hwtype}}; - + + my $supported = $rsp{ $request->{hwtype} }; + ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [$_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); $request->{method} = undef; - if ( !GetOptions( \%opt, qw(V|verbose resetnet))) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose resetnet))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### - # Check for "=" with no argument + # Check for "=" with no argument #################################### - if (my ($c) = grep(/=$/, @ARGV )) { - return(usage( "Missing argument: $c" )); + if (my ($c) = grep(/=$/, @ARGV)) { + return (usage("Missing argument: $c")); } #################################### # Check for unsupported commands #################################### my @arg_array = @ARGV; - my @fsp_cmds = (); - my @ppc_cmds = (); - foreach my $arg ( @arg_array ) { - my ($command,$value) = split( /=/, $arg ); - if ( !grep( /^$command$/, @$supported) and !$opt{resetnet}) { + my @fsp_cmds = (); + my @ppc_cmds = (); + foreach my $arg (@arg_array) { + my ($command, $value) = split(/=/, $arg); + if (!grep(/^$command$/, @$supported) and !$opt{resetnet}) { $request->{arg} = [$arg]; - my $res = xCAT::PPCcfg::parse_args($request, @_); + my $res = xCAT::PPCcfg::parse_args($request, @_); if (ref($res) eq 'ARRAY') { - my $check_cmd = &check_command($command, \%rsp); - if (!defined($check_cmd)) { + my $check_cmd = &check_command($command, \%rsp); + if (!defined($check_cmd)) { return $res; - } else { - return ([$_[0], "'$command' is only supported by type $check_cmd."]); + } else { + return ([ $_[0], "'$command' is only supported by type $check_cmd." ]); } } else { push @ppc_cmds, $command; - } + } } else { push @fsp_cmds, $command; } - if ( exists( $cmds{$command} )) { - return(usage( "Command multiple times: $command" )); + if (exists($cmds{$command})) { + return (usage("Command multiple times: $command")); } $cmds{$command} = $value; } - + $request->{arg} = \@arg_array; if (scalar(@fsp_cmds) && scalar(@ppc_cmds)) { my $fsp_cmds_string = &array_to_string(\@fsp_cmds); my $ppc_cmds_string = &array_to_string(\@ppc_cmds); return (usage("Invalid command array: $fsp_cmds_string can not execute with $ppc_cmds_string.")); - } elsif(scalar(@ppc_cmds)) { + } elsif (scalar(@ppc_cmds)) { my @enableASMI = xCAT::TableUtils->get_site_attribute("enableASMI"); if (defined($enableASMI[0])) { $enableASMI[0] =~ tr/a-z/A-Z/; # convert to upper if (($enableASMI[0] eq "1") || ($enableASMI[0] eq "YES")) { $request->{enableASMI} = 1; - } - } + } + } if ($request->{enableASMI} ne '1') { - return (usage( "You should enable \"ASMI\" first for \'$command\'.")); + return (usage("You should enable \"ASMI\" first for \'$command\'.")); } } #################################### - # Check command arguments + # Check command arguments #################################### - foreach ( keys %cmds ) { - if ( $cmds{$_} ) { - my $result = parse_option( $request, $_, $cmds{$_} ); - if ( $result ) { - return( usage($result) ); + foreach (keys %cmds) { + if ($cmds{$_}) { + my $result = parse_option($request, $_, $cmds{$_}); + if ($result) { + return (usage($result)); } } elsif ($_ =~ /_passwd$/) { - return( usage("No argument specified for '$_'")); - } + return (usage("No argument specified for '$_'")); + } } - + #################################### - # Return method to invoke + # Return method to invoke #################################### #if ( $request->{hwtype} =~ /(^hmc|ivm)$/ ) { # $request->{method} = "cfg"; @@ -260,41 +261,41 @@ sub parse_args { #################################### # Return method to invoke #################################### - if ( exists($cmds{frame}) or exists($cmds{cec_off_policy})) { + if (exists($cmds{frame}) or exists($cmds{cec_off_policy})) { $request->{hcp} = (exists($cmds{frame})) ? "bpa" : "fsp"; - $request->{method} = "cfg"; - return( \%opt ); + $request->{method} = "cfg"; + return (\%opt); } #################################### # Return method to invoke #################################### - if ( $opt{resetnet} ) { - $request->{hcp} = "fsp"; + if ($opt{resetnet}) { + $request->{hcp} = "fsp"; $request->{method} = "resetnet"; - return( \%opt ); + return (\%opt); } - if(exists($cmds{sysname}) or exists($cmds{pending_power_on_side}) or exists($cmds{BSR}) - or exists($cmds{setup_failover}) or exists($cmds{force_failover}) or exists ($cmds{huge_page})) { - $request->{hcp} = $request->{hwtype} eq 'frame' ? "bpa":"fsp"; + if (exists($cmds{sysname}) or exists($cmds{pending_power_on_side}) or exists($cmds{BSR}) + or exists($cmds{setup_failover}) or exists($cmds{force_failover}) or exists($cmds{huge_page})) { + $request->{hcp} = $request->{hwtype} eq 'frame' ? "bpa" : "fsp"; $request->{method} = "do_fspapi_function"; return (\%opt); } #################################### # Return method to invoke #################################### - if ( exists($cmds{HMC_passwd}) or exists($cmds{general_passwd}) or exists($cmds{admin_passwd}) or exists($cmds{"*_passwd"}) ) { - $request->{hcp} = "fsp"; + if (exists($cmds{HMC_passwd}) or exists($cmds{general_passwd}) or exists($cmds{admin_passwd}) or exists($cmds{"*_passwd"})) { + $request->{hcp} = "fsp"; $request->{method} = "passwd"; - return( \%opt ); + return (\%opt); } $request->{method} = \%cmds; - return( \%opt ); + return (\%opt); } ########################################################################## -# Parse the command line optional arguments +# Parse the command line optional arguments ########################################################################## sub parse_option { @@ -302,7 +303,7 @@ sub parse_option { my $command = shift; my $value = shift; - + #################################### # Password #################################### @@ -313,32 +314,32 @@ sub parse_option { # } #} - if ( $command eq 'HMC_passwd' or $command eq 'admin_passwd' or $command eq 'general_passwd' or $command eq "*_passwd" ) { - my ($passwd,$newpasswd) = split /,/, $value; - if ( !$newpasswd ) { - return( "New password couldn't be empty for user 'HMC', 'admin' or 'general'" ); + if ($command eq 'HMC_passwd' or $command eq 'admin_passwd' or $command eq 'general_passwd' or $command eq "*_passwd") { + my ($passwd, $newpasswd) = split /,/, $value; + if (!$newpasswd) { + return ("New password couldn't be empty for user 'HMC', 'admin' or 'general'"); } } - if ( $command eq 'frame' ){ - if ( $value !~ /^\d+$/i && $value ne '*' ) { - return( "Invalid frame number '$value'" ); + if ($command eq 'frame') { + if ($value !~ /^\d+$/i && $value ne '*') { + return ("Invalid frame number '$value'"); } } - if ( $command eq 'cec_off_policy' ){ - if ( $value !~ /^poweroff$/i && $value !~ /^stayon$/i ) { - return( "Invalid cec_off_policy '$value'" ); + if ($command eq 'cec_off_policy') { + if ($value !~ /^poweroff$/i && $value !~ /^stayon$/i) { + return ("Invalid cec_off_policy '$value'"); } } if ($command eq 'sysname') { if ($value ne '*') { if ($value !~ /^[a-zA-Z0-9-_]+$/) { - return( "Invalid sysname param '$value'" ); - } elsif (scalar(@{$request->{node}}) gt '1') { - return( "Invalid sysname param '$value'" ); + return ("Invalid sysname param '$value'"); + } elsif (scalar(@{ $request->{node} }) gt '1') { + return ("Invalid sysname param '$value'"); } - my $len = rindex $value."\$", "\$"; + my $len = rindex $value . "\$", "\$"; if ($len > '31') { return ("Invalid sysname param '$value', name is too long, max 31 characters"); } @@ -354,85 +355,87 @@ sub parse_option { return ("Invalid setup_failover param '$value'"); } } - if ($command =~ /^(BSR|force_failover)$/ ) { + if ($command =~ /^(BSR|force_failover)$/) { return ("BSR value can not be set"); } if ($command =~ /^huge_page$/) { - if ($value !~ /^[0-9]+$/) { - return ("Invalid huge page param '$value'"); - } + if ($value !~ /^[0-9]+$/) { + return ("Invalid huge page param '$value'"); + } } return undef; } + sub check_node_info { - my $hash = shift; - my $invalid_node = undef; - while (my ($mtsm, $h) = each (%$hash)) { - while (my ($name, $d) = each(%$h)) { - if (@$d[4] !~ /^(cec|frame|blade)$/) { - $invalid_node = $name; - last; - } - } - } - return $invalid_node; + my $hash = shift; + my $invalid_node = undef; + while (my ($mtsm, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { + if (@$d[4] !~ /^(cec|frame|blade)$/) { + $invalid_node = $name; + last; + } + } + } + return $invalid_node; } my %fspapi_action = ( - sysname => { - query => { - cec => "get_cec_name", - frame => "get_frame_name" - }, - set => { - cec => "set_cec_name", - frame => "set_frame_name" - } + sysname => { + query => { + cec => "get_cec_name", + frame => "get_frame_name" }, - pending_power_on_side => { - query => { - cec => "list_firmware_level", - blade => "list_firmware_level", - frame => "list_firmware_level" - }, - set => { - cec => "set_ipl_param", - blade => "set_ipl_param", - frame => "set_ipl_param" - } + set => { + cec => "set_cec_name", + frame => "set_frame_name" + } + }, + pending_power_on_side => { + query => { + cec => "list_firmware_level", + blade => "list_firmware_level", + frame => "list_firmware_level" }, - BSR => { - query => { - cec => "get_cec_bsr" - } + set => { + cec => "set_ipl_param", + blade => "set_ipl_param", + frame => "set_ipl_param" + } + }, + BSR => { + query => { + cec => "get_cec_bsr" + } + }, + setup_failover => { + query => { + cec => "cec_setup_failover" }, - setup_failover => { - query => { - cec => "cec_setup_failover" - }, - set => { - cec => "cec_setup_failover" - } + set => { + cec => "cec_setup_failover" + } + }, + force_failover => { + query => { + cec => "cec_force_failover" + } + }, + huge_page => { + query => { + cec => "get_huge_page" }, - force_failover => { - query => { - cec => "cec_force_failover" - } - }, - huge_page => { - query => { - cec => "get_huge_page" - }, - set => { - cec => "set_huge_page" - } - } + set => { + cec => "set_huge_page" + } + } ); + sub do_process_query_res { - my $name = shift; - my $cmd = shift; + my $name = shift; + my $cmd = shift; my $result = shift; - my $res = shift; + my $res = shift; if (@$res[2] != 0) { push @$result, $res; return "Error"; @@ -443,33 +446,35 @@ sub do_process_query_res { my @values = split(/\n/, @$res[1]); foreach my $v (@values) { if ($v =~ /pend_power_on_side_(\w+)=(temp|perm),/) { - push @$result, [$name, "Pending Power On Side \L\u$1: $2", '0']; + push @$result, [ $name, "Pending Power On Side \L\u$1: $2", '0' ]; } else { - push @$result, [$name, $v, '1']; + push @$result, [ $name, $v, '1' ]; return "Error"; } } } elsif ($cmd =~ /^(BSR|huge_page)$/) { my @values = split(/\n/, @$res[1]); foreach my $v (@values) { - push @$result, [$name, $v, '0']; + push @$result, [ $name, $v, '0' ]; } } else { push @$result, $res; } return undef; } + sub do_query { my $request = shift; - my $hash = shift; - my $cmd = shift; - my @result = (); + my $hash = shift; + my $cmd = shift; + my @result = (); while (my ($mtms, $h) = each(%$hash)) { - while (my($name, $d) = each(%$h)) { - my $action = $fspapi_action{$cmd}{query}{@$d[4]}; - xCAT::MsgUtils->verbose_message($request, "rspconfig :$action for node:$name."); + while (my ($name, $d) = each(%$h)) { + my $action = $fspapi_action{$cmd}{query}{ @$d[4] }; + xCAT::MsgUtils->verbose_message($request, "rspconfig :$action for node:$name."); my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action); &do_process_query_res($name, $cmd, \@result, $values); + #my $res = &do_process_query_res($name, $cmd, \@result, $values); #if (defined($res)) { # last; @@ -478,47 +483,51 @@ sub do_query { } return (\@result); } + sub do_set_get_para { my $node_name = shift; - my $cmd = shift; - my $value = shift; + my $cmd = shift; + my $value = shift; if ($cmd =~ /^sysname$/) { return (($value eq '*') ? $node_name : $value); - } elsif ($cmd =~ /^pending_power_on_side$/){ + } elsif ($cmd =~ /^pending_power_on_side$/) { return ($value =~ /^perm$/) ? '0' : '1'; } elsif ($cmd =~ /^setup_failover$/) { return ($value =~ /^enable$/) ? '1' : '0'; } else { - return $value; + return $value; } } sub do_process_set_res { - my $name = shift; - my $cmd = shift; + my $name = shift; + my $cmd = shift; my $result = shift; - my $res = shift; + my $res = shift; if (@$res[1] && @$res[1] !~ /success/i) { push @$result, $res; return "Error"; } else { - push @$result, [$name, "Success", 0]; + push @$result, [ $name, "Success", 0 ]; } } + sub do_set { my $request = shift; - my $hash = shift; - my $cmd = shift; - my $value = shift; - my @result = (); + my $hash = shift; + my $cmd = shift; + my $value = shift; + my @result = (); while (my ($mtms, $h) = each(%$hash)) { - while (my($name, $d) = each(%$h)) { - my $action = $fspapi_action{$cmd}{set}{@$d[4]}; - xCAT::MsgUtils->verbose_message($request, "rspconfig :$action for node:$name, param:$value."); + while (my ($name, $d) = each(%$h)) { + my $action = $fspapi_action{$cmd}{set}{ @$d[4] }; + xCAT::MsgUtils->verbose_message($request, "rspconfig :$action for node:$name, param:$value."); my $para = &do_set_get_para($name, $cmd, $value); my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action, 0, $para); -# print Dumper($values); + + # print Dumper($values); &do_process_set_res($name, $cmd, \@result, $values); + #my $res = &do_process_set_res($name, $cmd, \@result, $values); #if (defined($res)) { # last; @@ -527,24 +536,26 @@ sub do_set { } return (\@result); } + sub do_fspapi_function { my $request = shift; - my $hash = shift; - my $exp = shift; - my @ret = (); + my $hash = shift; + my $exp = shift; + my @ret = (); my $res; my $args = $request->{arg}; my @fspapi_array = qw/sysname pending_power_on_side BSR setup_failover force_failover huge_page/; my $invalid_node = &check_node_info($hash); + if (defined($invalid_node)) { - return ([[$invalid_node, "Node must be CEC or Frame", '1']]); + return ([ [ $invalid_node, "Node must be CEC or Frame", '1' ] ]); } foreach my $arg (@$args) { my ($cmd, $value) = split /=/, $arg; - if (!grep(/^$cmd$/, @fspapi_array)) { + if (!grep(/^$cmd$/, @fspapi_array)) { my $fspapi_array_string = &array_to_string(\@fspapi_array); - return ([["Error", "'$cmd' can not execute with $fspapi_array_string", '1']]); - } + return ([ [ "Error", "'$cmd' can not execute with $fspapi_array_string", '1' ] ]); + } if ($value) { $res = &do_set($request, $hash, $cmd, $value) } else { @@ -568,20 +579,21 @@ sub passwd { my @output = (); my $default; - foreach my $arg ( @$args ) { - my ($user,$value) = split /=/, $arg; - if ($user !~ /_passwd$/) { - return ([["Error", "'$user' can not execute with '*_passwd' commands", '1']]); - } - my ($passwd,$newpasswd) = split /,/, $value; - $user =~ s/_passwd$//; - #$user =~ s/^HMC$/access/g; - - if( !$passwd) { - $default = 1; + foreach my $arg (@$args) { + my ($user, $value) = split /=/, $arg; + if ($user !~ /_passwd$/) { + return ([ [ "Error", "'$user' can not execute with '*_passwd' commands", '1' ] ]); } - - if ( $user eq "*" ) { + my ($passwd, $newpasswd) = split /,/, $value; + $user =~ s/_passwd$//; + + #$user =~ s/^HMC$/access/g; + + if (!$passwd) { + $default = 1; + } + + if ($user eq "*") { push @$users, "HMC"; push @$users, "admin"; push @$users, "general"; @@ -589,37 +601,37 @@ sub passwd { push @$users, $user; } - foreach my $usr ( @$users ) { - if( $default == 1 ) { - $passwd = $default_passwd{$usr}; - } - - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($node,$d) = each(%$h) ) { - my $type = @$d[4]; - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; - xCAT::MsgUtils->verbose_message($request, "rspconfig :modify password of $usr for node:$node."); - my $cmd = xCAT::FSPcfg::fsp_api_passwd ($request, $node, $d, $usr, $passwd, $newpasswd); - my $Rc = @$cmd[2]; - my $data = @$cmd[1]; - my $usr_back = $usr; - $usr_back =~ s/^access$/HMC/g; - push @output,[$node,"$usr_back: $data",$Rc]; + foreach my $usr (@$users) { + if ($default == 1) { + $passwd = $default_passwd{$usr}; + } + + while (my ($cec, $h) = each(%$hash)) { + while (my ($node, $d) = each(%$h)) { + my $type = @$d[4]; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + xCAT::MsgUtils->verbose_message($request, "rspconfig :modify password of $usr for node:$node."); + my $cmd = xCAT::FSPcfg::fsp_api_passwd($request, $node, $d, $usr, $passwd, $newpasswd); + my $Rc = @$cmd[2]; + my $data = @$cmd[1]; + my $usr_back = $usr; + $usr_back =~ s/^access$/HMC/g; + push @output, [ $node, "$usr_back: $data", $Rc ]; - ################################## - # Write the new password to table - ################################## - if ( $Rc == 0 ) { - xCAT::MsgUtils->verbose_message($request, "rspconfig :update xCATdb for node:$node,ID:$usr."); - xCAT::PPCdb::update_credentials( $node, $type, $usr, $newpasswd ); - } - } - } - } - } - - return( \@output ); + ################################## + # Write the new password to table + ################################## + if ($Rc == 0) { + xCAT::MsgUtils->verbose_message($request, "rspconfig :update xCATdb for node:$node,ID:$usr."); + xCAT::PPCdb::update_credentials($node, $type, $usr, $newpasswd); + } + } + } + } + } + + return (\@output); } ########################################################################## @@ -633,22 +645,22 @@ sub cfg { my $args = $request->{arg}; my $result; - foreach ( @$args ) { + foreach (@$args) { ################################## # Ignore switches in command-line ################################## - unless ( /^-/ ) { - my ($cmd,$value) = split /=/; - if ($cmd !~ /(frame|cec_off_policy)/) { - return ([["Error", "'$cmd' can not execute with 'frame' or 'cec_off_policy'", '1']]); - } + unless (/^-/) { + my ($cmd, $value) = split /=/; + if ($cmd !~ /(frame|cec_off_policy)/) { + return ([ [ "Error", "'$cmd' can not execute with 'frame' or 'cec_off_policy'", '1' ] ]); + } no strict 'refs'; - $result = $rspconfig{$cmd}( $request, $value, $hash ); + $result = $rspconfig{$cmd}($request, $value, $hash); use strict; } } - return( $result ); + return ($result); } sub frame { @@ -657,14 +669,14 @@ sub frame { my $hash = shift; my $arg = $request->{arg}; - foreach ( @$arg ) { + foreach (@$arg) { my $result; my $Rc; my $data; my ($cmd, $value) = split /=/, $_; - if ( $cmd ne "frame" ) { - return( [["Error","Multiple option $cmd and frame is not accepted", -1]] ); + if ($cmd ne "frame") { + return ([ [ "Error", "Multiple option $cmd and frame is not accepted", -1 ] ]); } ################################# @@ -672,91 +684,92 @@ sub frame { # the frame number between hcp # and database ################################# - my $tab = xCAT::Table->new( "ppc" ); - - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($node,$d) = each(%$h) ) { - if ( !defined($value) ) { + my $tab = xCAT::Table->new("ppc"); + + while (my ($cec, $h) = each(%$hash)) { + while (my ($node, $d) = each(%$h)) { + if (!defined($value)) { ################################# # Get frame number ################################# - #$data = xCAT::PPCcli::lssyscfg( $exp, @$d[4], @$d[2], 'frame_num' ); + #$data = xCAT::PPCcli::lssyscfg( $exp, @$d[4], @$d[2], 'frame_num' ); xCAT::MsgUtils->verbose_message($request, "rspconfig :get_frame_number for node:$node."); - $data = xCAT::FSPUtils::fsp_api_action( $request, $node, $d, "get_frame_number"); + $data = xCAT::FSPUtils::fsp_api_action($request, $node, $d, "get_frame_number"); $Rc = pop(@$data); ################################# # Return error ################################# - if ( $Rc != 0 || @$data[1] =~ /Error/ ) { - return( [[$node,"@$data[1]. If just set the frame number, please wait for 5-10 minutes. Otherwise, maybe other problems cause this failure.",$Rc]] ); + if ($Rc != 0 || @$data[1] =~ /Error/) { + return ([ [ $node, "@$data[1]. If just set the frame number, please wait for 5-10 minutes. Otherwise, maybe other problems cause this failure.", $Rc ] ]); } - push @$result, [$node,@$data[1], 0]; + push @$result, [ $node, @$data[1], 0 ]; ################################# # Set frame number to database ################################# - $tab->setNodeAttribs( $node, { id=>@$data[1] } ); + $tab->setNodeAttribs($node, { id => @$data[1] }); - } elsif ( $value eq '*' ) { + } elsif ($value eq '*') { ################################# # Set frame number - # Read the settings from database + # Read the settings from database ################################# - my $ent=$tab->getNodeAttribs( $node,['id'] ); + my $ent = $tab->getNodeAttribs($node, ['id']); ################################# # Return error ################################# - if ( !defined($ent) or !defined($ent->{id}) ) { - return( [[$node,"Cannot find frame num in database", -1]] ); + if (!defined($ent) or !defined($ent->{id})) { + return ([ [ $node, "Cannot find frame num in database", -1 ] ]); } - #$data = xCAT::PPCcli::chsyscfg( $exp, "bpa", $d, "frame_num=".$ent->{id} ); + + #$data = xCAT::PPCcli::chsyscfg( $exp, "bpa", $d, "frame_num=".$ent->{id} ); xCAT::MsgUtils->verbose_message($request, "rspconfig :set_frame_number for node:$node,id:$ent->{id}."); - $data = xCAT::FSPUtils::fsp_api_action( $request, $node, $d, "set_frame_number", 0, $ent->{id}); + $data = xCAT::FSPUtils::fsp_api_action($request, $node, $d, "set_frame_number", 0, $ent->{id}); $Rc = pop(@$data); ################################# # Return error ################################# - if ( $Rc != 0 ) { - return( [[$node,@$data[1],$Rc]] ); + if ($Rc != 0) { + return ([ [ $node, @$data[1], $Rc ] ]); } - push @$result, [$node,@$data[1], 0]; - push @$result, [$node,"It will take several minutes to complete. So please wait for 5-10 minutes, then the other operations could be done. Otherwise, the other operation will fail.", 0]; + push @$result, [ $node, @$data[1], 0 ]; + push @$result, [ $node, "It will take several minutes to complete. So please wait for 5-10 minutes, then the other operations could be done. Otherwise, the other operation will fail.", 0 ]; } else { ################################# # Set frame number # Read the frame number from opt ################################# - #$data = xCAT::PPCcli::chsyscfg( $exp, "bpa", $d, "frame_num=$value" ); + #$data = xCAT::PPCcli::chsyscfg( $exp, "bpa", $d, "frame_num=$value" ); xCAT::MsgUtils->verbose_message($request, "rspconfig :set_frame_number for node:$node,id:$value."); - $data = xCAT::FSPUtils::fsp_api_action( $request, $node, $d, "set_frame_number", 0, $value); - $Rc = pop(@$data); + $data = xCAT::FSPUtils::fsp_api_action($request, $node, $d, "set_frame_number", 0, $value); + $Rc = pop(@$data); ################################# # Return error ################################# - if ( $Rc != 0 ) { - return( [[$node,@$data[1],$Rc]] ); + if ($Rc != 0) { + return ([ [ $node, @$data[1], $Rc ] ]); } - push @$result, [$node,@$data[1],0]; - push @$result, [$node,"It will take several minutes to complete. So please wait for several minutes, then the other operations could be done. Otherwise, the other operation will fail.", 0]; + push @$result, [ $node, @$data[1], 0 ]; + push @$result, [ $node, "It will take several minutes to complete. So please wait for several minutes, then the other operations could be done. Otherwise, the other operation will fail.", 0 ]; ################################# # Set frame number to database ################################# - $tab->setNodeAttribs( $node, { id=>$value } ); + $tab->setNodeAttribs($node, { id => $value }); } } - return( [@$result] ); - } + return ([@$result]); + } } } @@ -765,67 +778,67 @@ sub cec_off_policy { my $value = shift; my $hash = shift; my $arg = $request->{arg}; - - foreach ( @$arg ) { + + foreach (@$arg) { my $result; my $Rc; my $data; my ($cmd, $value) = split /=/, $_; - if ( $cmd ne "cec_off_policy" ) { - return( [["Error","Multiple option $cmd and cec is not accepted", -1]] ); + if ($cmd ne "cec_off_policy") { + return ([ [ "Error", "Multiple option $cmd and cec is not accepted", -1 ] ]); } - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($node,$d) = each(%$h) ) { - if ( !defined($value) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($node, $d) = each(%$h)) { + if (!defined($value)) { ################################# - # Get platform IPL parameters + # Get platform IPL parameters ################################# xCAT::MsgUtils->verbose_message($request, "rspconfig :get_phyp_cfg_power_off_policy for node:$node."); - $data = xCAT::FSPUtils::fsp_api_action( $request, $node, $d, "get_phyp_cfg_power_off_policy"); + $data = xCAT::FSPUtils::fsp_api_action($request, $node, $d, "get_phyp_cfg_power_off_policy"); $Rc = pop(@$data); ################################# # Return error ################################# - if ( $Rc != 0 ) { - return( [[$node,@$data[1],$Rc]] ); + if ($Rc != 0) { + return ([ [ $node, @$data[1], $Rc ] ]); } - - @$data[1] =~ /cec_off_policy=(\w*);/; - push @$result, [$node, $1, 0]; + @$data[1] =~ /cec_off_policy=(\w*);/; + + push @$result, [ $node, $1, 0 ]; - } else { + } else { ################################# - # Set cec off policy + # Set cec off policy ################################# xCAT::MsgUtils->verbose_message($request, "rspconfig :set power_off_policy for node:$node,policy:$value."); - if( $value eq "poweroff") { - $value = "cec_off_policy_poweroff"; - } else { - $value = "cec_off_policy_stayon"; - } - $data = xCAT::FSPUtils::fsp_api_action( $request, $node, $d, $value); - $Rc = pop(@$data); + if ($value eq "poweroff") { + $value = "cec_off_policy_poweroff"; + } else { + $value = "cec_off_policy_stayon"; + } + $data = xCAT::FSPUtils::fsp_api_action($request, $node, $d, $value); + $Rc = pop(@$data); ################################# # Return error ################################# - if ( $Rc != 0 ) { - return( [[$node,@$data[1],$Rc]] ); + if ($Rc != 0) { + return ([ [ $node, @$data[1], $Rc ] ]); } - push @$result, [$node,"Success",0]; + push @$result, [ $node, "Success", 0 ]; } } - return( [@$result] ); - } + return ([@$result]); + } } } @@ -841,29 +854,29 @@ sub cec_off_policy { # Invoke fsp_api to change the passwords and store updated passwd in db ########################################################################## sub fsp_api_passwd { - my $request = shift; - my $node_name = shift; - my $attrs = shift; - my $user = shift; - my $passwd = shift; - my $newpasswd = shift; - my $id = 1; - my $fsp_name = (); - my $fsp_ip = (); - my $type = (); # fsp|lpar -- 0. BPA -- 1 + my $request = shift; + my $node_name = shift; + my $attrs = shift; + my $user = shift; + my $passwd = shift; + my $newpasswd = shift; + my $id = 1; + my $fsp_name = (); + my $fsp_ip = (); + my $type = (); # fsp|lpar -- 0. BPA -- 1 my @result; - my $Rc = 0 ; + my $Rc = 0; my %outhash = (); - my $res = 0 ; - my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; + my $res = 0; + my $fsp_api = ($::XCATROOT) ? "$::XCATROOT/sbin/fsp-api" : "/opt/xcat/sbin/fsp-api"; - $id = $$attrs[0]; + $id = $$attrs[0]; $fsp_name = $$attrs[3]; ############################ # Set type for FSP or BPA ############################ - if($$attrs[4] =~ /^fsp$/ || $$attrs[4] =~ /^lpar$/ || $$attrs[4] =~ /^cec$/) { + if ($$attrs[4] =~ /^fsp$/ || $$attrs[4] =~ /^lpar$/ || $$attrs[4] =~ /^cec$/) { $type = 0; } else { $type = 1; @@ -875,26 +888,26 @@ sub fsp_api_passwd { #$fsp_ip = xCAT::NetworkUtils::get_hdwr_ip($fsp_name); #$fsp_ip = xCAT::NetworkUtils::getNodeIPaddress($fsp_name); #$fsp_ip = xCAT::Utils::getIPaddress($fsp_name); - $fsp_ip = xCAT::FSPUtils::getIPaddress($request, $$attrs[4], $fsp_name ); - if(!defined($fsp_ip) or ($fsp_ip == -3)) { + $fsp_ip = xCAT::FSPUtils::getIPaddress($request, $$attrs[4], $fsp_name); + if (!defined($fsp_ip) or ($fsp_ip == -3)) { $res = "Failed to get IP address for $fsp_name."; - return ([$node_name, $res, -1]); + return ([ $node_name, $res, -1 ]); } ################################# # Create command and run command ################################# my $cmd; - if( $passwd ne "" ) { + if ($passwd ne "") { $cmd = "$fsp_api -a set_fsp_pw -u $user -p $passwd -P $newpasswd -t $type:$fsp_ip:$id:$node_name: "; } else { - $cmd = "$fsp_api -a set_fsp_pw -u $user -P $newpasswd -t $type:$fsp_ip:$id:$node_name: "; + $cmd = "$fsp_api -a set_fsp_pw -u $user -P $newpasswd -t $type:$fsp_ip:$id:$node_name: "; } $SIG{CHLD} = (); $res = xCAT::Utils->runcmd($cmd, -1); $Rc = $::RUNCMD_RC; - if($Rc == 0) { + if ($Rc == 0) { $res = "Success"; } @@ -904,13 +917,13 @@ sub fsp_api_passwd { ################## #$outhash{ $node_name } = $res; - return( [$node_name,$res, $Rc] ); + return ([ $node_name, $res, $Rc ]); } ########################################################################## -# Do resetnet +# Do resetnet ########################################################################## sub resetnet { my $request = shift; diff --git a/perl-xCAT/xCAT/FSPconn.pm b/perl-xCAT/xCAT/FSPconn.pm index a62a5a83f..48f0e1326 100644 --- a/perl-xCAT/xCAT/FSPconn.pm +++ b/perl-xCAT/xCAT/FSPconn.pm @@ -5,6 +5,7 @@ use strict; use Getopt::Long; use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::Usage; + #use Data::Dumper; use xCAT::FSPUtils; use xCAT::PPCconn; @@ -24,13 +25,13 @@ my %method = ( sub parse_args { my $request = shift; - my $cmd = $request->{command}; + my $cmd = $request->{command}; ############################### # Invoke correct parse_args ############################### - my $result = $method{$cmd}( $request, $request->{arg}); - return( $result ); + my $result = $method{$cmd}($request, $request->{arg}); + return ($result); } ########################################################################## @@ -40,57 +41,58 @@ sub mkhwconn_parse_args { my $request = shift; my $args = shift; - my %opt = (); + my %opt = (); local *usage = sub { my $usage_string = xCAT::Usage->getUsage("mkhwconn"); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } - local @ARGV = ref($args) eq 'ARRAY'? @$args:(); + local @ARGV = ref($args) eq 'ARRAY' ? @$args : (); $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose h|help t s:s T=s p=s P=s port=s ) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose h|help t s:s T=s p=s P=s port=s ))) { + return (usage()); } - if ( exists $opt{s} ) + if (exists $opt{s}) { my $opttmp = xCAT::PPCconn::mkhwconn_parse_args($request, $args); return $opttmp; } - return usage() if ( exists $opt{h}); + return usage() if (exists $opt{h}); - if ( !exists $opt{t} and !exists $opt{p}) { - return ( usage('Flag -t or -p must be used.')); + if (!exists $opt{t} and !exists $opt{p}) { + return (usage('Flag -t or -p must be used.')); } - if ( exists $opt{t} and exists $opt{p}) + if (exists $opt{t} and exists $opt{p}) { - return( usage('Flags -t and -p cannot be used together.')); + return (usage('Flags -t and -p cannot be used together.')); } - if ( (exists $opt{P} or grep(/^(-P)$/, @$args)) and !exists $opt{p}) + if ((exists $opt{P} or grep(/^(-P)$/, @$args)) and !exists $opt{p}) { - return( usage('Flags -P can only be used when flag -p is specified.')); + return (usage('Flags -P can only be used when flag -p is specified.')); } - + ########################################## # Check if CECs are controlled by a frame ########################################## - my $nodes = $request->{node}; - my $ppctab = xCAT::Table->new( 'ppc' ); + my $nodes = $request->{node}; + my $ppctab = xCAT::Table->new('ppc'); + #my $nodetypetab = xCAT::Table->new( 'nodetype'); - my $vpdtab = xCAT::Table->new( 'vpd'); + my $vpdtab = xCAT::Table->new('vpd'); my @bpa_ctrled_nodes = (); my @no_type_nodes = (); my @error_type_nodes = (); @@ -99,89 +101,91 @@ sub mkhwconn_parse_args ########################################### # mgt=fsp/bpa for PPCconn.pm ########################################## - if ( exists $opt{p} ) + if (exists $opt{p}) { #my $nodetype_hash = $nodetypetab->getNodeAttribs( $opt{p},[qw(nodetype)]); #my $nodetype = $nodetype_hash->{nodetype}; my $nodetype = xCAT::DBobjUtils->getnodetype($opt{p}, "ppc"); - if( !defined($nodetype) ) { - return(usage("Something wrong with the specified HMC (-p Option). The HMC type doesn't exist.")); + if (!defined($nodetype)) { + return (usage("Something wrong with the specified HMC (-p Option). The HMC type doesn't exist.")); } - if ( $nodetype eq 'hmc' ) + if ($nodetype eq 'hmc') { - $request->{ 'hwtype'} = 'hmc'; - } + $request->{'hwtype'} = 'hmc'; + } } - if ( $ppctab) + if ($ppctab) { my $hcp_nodetype = undef; my $typehash = xCAT::DBobjUtils->getnodetype($nodes, "ppc"); for my $node (@$nodes) { - my $node_parent = undef; - my $nodetype = undef; - my $node_hcp_nodetype = undef; + my $node_parent = undef; + my $nodetype = undef; + my $node_hcp_nodetype = undef; + #my $nodetype_hash = $nodetypetab->getNodeAttribs( $node,[qw(nodetype)]); - my $node_parent_hash = $ppctab->getNodeAttribs( $node,[qw(parent)]); - if ( exists $opt{t} ) + my $node_parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); + if (exists $opt{t}) { - my $node_hcp_hash = $ppctab->getNodeAttribs( $node,[qw(hcp)]); - if ( $node_hcp_hash->{hcp} ) + my $node_hcp_hash = $ppctab->getNodeAttribs($node, [qw(hcp)]); + if ($node_hcp_hash->{hcp}) { #my $node_hcp_nodetype_hash = $nodetypetab->getNodeAttribs($node_hcp_hash->{hcp},[qw(nodetype)]); #$node_hcp_nodetype = $node_hcp_nodetype_hash->{nodetype}; $node_hcp_nodetype = xCAT::DBobjUtils->getnodetype($node_hcp_hash->{hcp}, "ppc"); } - if ( defined $hcp_nodetype ) + if (defined $hcp_nodetype) { - if ( $hcp_nodetype ne $node_hcp_nodetype ) - { - return( usage("Nodetype for all the nodes' hcp must be the same.") ); + if ($hcp_nodetype ne $node_hcp_nodetype) + { + return (usage("Nodetype for all the nodes' hcp must be the same.")); } } else { $hcp_nodetype = $node_hcp_nodetype; - if ( $hcp_nodetype eq 'hmc' ) - { - $request->{ 'hwtype'} = 'hmc'; + if ($hcp_nodetype eq 'hmc') + { + $request->{'hwtype'} = 'hmc'; } } - + } + #$nodetype = $nodetype_hash->{nodetype}; - $nodetype = $$typehash{$node}; + $nodetype = $$typehash{$node}; $node_parent = $node_parent_hash->{parent}; - if ( !$nodetype ) + if (!$nodetype) { push @no_type_nodes, $node; next; } else { - unless ( $nodetype =~ /^(fsp|bpa|frame|cec|hmc|blade)$/) + unless ($nodetype =~ /^(fsp|bpa|frame|cec|hmc|blade)$/) { - push @error_type_nodes, $node; - next; + push @error_type_nodes, $node; + next; } } - - if (( $nodetype eq 'fsp' or $nodetype eq 'cec') and - $node_parent and + + if (($nodetype eq 'fsp' or $nodetype eq 'cec') and + $node_parent and $node_parent ne $node) { push @bpa_ctrled_nodes, $node; } - - if ( $nodetype eq 'bpa') + + if ($nodetype eq 'bpa') { - my $my_frame_bpa_cec = getFrameMembers( $node, $vpdtab, $ppctab); + my $my_frame_bpa_cec = getFrameMembers($node, $vpdtab, $ppctab); push @frame_members, @$my_frame_bpa_cec; } - if ( $nodetype eq 'frame') + if ($nodetype eq 'frame') { - my $my_frame_bpa_cec = xCAT::DBobjUtils::getcecchildren( $node) ; - push @frame_members, @$my_frame_bpa_cec if($my_frame_bpa_cec); + my $my_frame_bpa_cec = xCAT::DBobjUtils::getcecchildren($node); + push @frame_members, @$my_frame_bpa_cec if ($my_frame_bpa_cec); push @frame_members, $node; } @@ -191,63 +195,66 @@ sub mkhwconn_parse_args if (scalar(@no_type_nodes)) { my $tmp_nodelist = join ',', @no_type_nodes; - return ( usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.\n")); + return (usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.\n")); } if (scalar(@error_type_nodes)) { my $tmp_nodelist = join ',', @error_type_nodes; - return ( usage("Incorrect nodetype for nodes(s): $tmp_nodelist. Please modify first and try again.\n")); + return (usage("Incorrect nodetype for nodes(s): $tmp_nodelist. Please modify first and try again.\n")); } + #if (scalar(@bpa_ctrled_nodes)) #{ # my $tmp_nodelist = join ',', @bpa_ctrled_nodes; # return ( usage("Node(s) $tmp_nodelist is(are) controlled by BPA.")); #} - - if ( scalar( @frame_members)) + + if (scalar(@frame_members)) { - my @all_nodes = xCAT::Utils::get_unique_members( @$nodes, @frame_members); + my @all_nodes = xCAT::Utils::get_unique_members(@$nodes, @frame_members); $request->{node} = \@all_nodes; } - # Set HW type to 'hmc' anyway, so that this command will not going to + + # Set HW type to 'hmc' anyway, so that this command will not going to # PPCfsp.pm # $request->{ 'hwtype'} = 'hmc'; - if( ! exists $opt{T} ) + if (!exists $opt{T}) { - $opt{T} = "lpar"; #defaut value is lpar. - #return( usage('Missing -T option. The value can be lpar or fnm.')); + $opt{T} = "lpar"; #defaut value is lpar. + #return( usage('Missing -T option. The value can be lpar or fnm.')); } - - if( $opt{T} eq "lpar") { - $opt{T} = 0; - } elsif($opt{T} eq "fnm") { - $opt{T} = 1; + + if ($opt{T} eq "lpar") { + $opt{T} = 0; + } elsif ($opt{T} eq "fnm") { + $opt{T} = 1; } else { - return( usage('Wrong value of -T option. The value can be lpar or fnm. The defaut value is lpar.')); + return (usage('Wrong value of -T option. The value can be lpar or fnm. The defaut value is lpar.')); } - - if( ! exists $opt{port} ) + + if (!exists $opt{port}) { $opt{port} = "[0|1]"; - } elsif( $opt{port} ne "0" and $opt{port} ne "1") + } elsif ($opt{port} ne "0" and $opt{port} ne "1") { if ($opt{port} eq "0,1") { - return ([0, "The option --port only be used to specify special port value, please don't specify this value if you want to use all ports."]); + return ([ 0, "The option --port only be used to specify special port value, please don't specify this value if you want to use all ports." ]); } else { - return( usage('Wrong value of --port option. The value can only be 0 or 1.')); + return (usage('Wrong value of --port option. The value can only be 0 or 1.')); } } - + $ppctab->close(); + #$nodetypetab->close(); $vpdtab->close(); - if ( scalar( @ARGV)) { - return(usage( "No additional flag is support by this command" )); + if (scalar(@ARGV)) { + return (usage("No additional flag is support by this command")); } $request->{method} = 'mkhwconn'; - return( \%opt); + return (\%opt); } #################################################### @@ -256,38 +263,39 @@ sub mkhwconn_parse_args #ppc/vpd nodes cache my @all_ppc_nodes; my @all_vpd_nodes; + sub getFrameMembers { - my $node = shift; #this a BPA node - my $vpdtab = shift; - my $ppctab = shift; + my $node = shift; #this a BPA node + my $vpdtab = shift; + my $ppctab = shift; my @frame_members = (); my @bpa_nodes = (); - my $vpdhash = $vpdtab->getNodeAttribs( $node, [qw(mtm serial)]); - my $mtm = $vpdhash->{mtm}; - my $serial = $vpdhash->{serial}; - if ( scalar( @all_vpd_nodes) == 0) + my $vpdhash = $vpdtab->getNodeAttribs($node, [qw(mtm serial)]); + my $mtm = $vpdhash->{mtm}; + my $serial = $vpdhash->{serial}; + if (scalar(@all_vpd_nodes) == 0) { - @all_vpd_nodes = $vpdtab->getAllNodeAttribs( ['node', 'mtm', 'serial']); + @all_vpd_nodes = $vpdtab->getAllNodeAttribs([ 'node', 'mtm', 'serial' ]); } for my $vpd_node (@all_vpd_nodes) { - if ( $vpd_node->{'mtm'} eq $mtm and $vpd_node->{'serial'} eq $serial) + if ($vpd_node->{'mtm'} eq $mtm and $vpd_node->{'serial'} eq $serial) { push @frame_members, $vpd_node->{'node'}; - push @bpa_nodes, $vpd_node->{'node'}; + push @bpa_nodes, $vpd_node->{'node'}; } } - if ( scalar( @all_ppc_nodes) == 0) + if (scalar(@all_ppc_nodes) == 0) { - @all_ppc_nodes = $ppctab->getAllNodeAttribs( ['node', 'parent']); + @all_ppc_nodes = $ppctab->getAllNodeAttribs([ 'node', 'parent' ]); } for my $bpa_node (@bpa_nodes) { for my $ppc_node (@all_ppc_nodes) { - if ( $ppc_node->{parent} eq $bpa_node) + if ($ppc_node->{parent} eq $bpa_node) { push @frame_members, $ppc_node->{'node'}; } @@ -303,120 +311,122 @@ sub lshwconn_parse_args { my $request = shift; my $args = shift; - my %opt = (); + my %opt = (); local *usage = sub { my $usage_string = xCAT::Usage->getUsage("lshwconn"); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# -# Get options in command line + # Get options in command line ############################################# - local @ARGV = ref($args) eq 'ARRAY'? @$args:(); + local @ARGV = ref($args) eq 'ARRAY' ? @$args : (); $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( exists $opt{s} ) + if (exists $opt{s}) { my $opttmp = xCAT::PPCconn::lshwconn_parse_args($request, $args); return $opttmp; } - - if ( !GetOptions( \%opt, qw(V|verbose h|help T=s s) )) { - return( usage() ); + + if (!GetOptions(\%opt, qw(V|verbose h|help T=s s))) { + return (usage()); } - return usage() if ( exists $opt{h}); - - if( ! exists $opt{T} ) + return usage() if (exists $opt{h}); + + if (!exists $opt{T}) { - $opt{T} = "lpar"; #defaut value is lpar. - #return( usage('Missing -T option. The value can be lpar or fnm.')); + $opt{T} = "lpar"; #defaut value is lpar. + #return( usage('Missing -T option. The value can be lpar or fnm.')); } - - if( $opt{T} eq "lpar") { - $opt{T} = 0; - } elsif($opt{T} eq "fnm") { - $opt{T} = 1; + + if ($opt{T} eq "lpar") { + $opt{T} = 0; + } elsif ($opt{T} eq "fnm") { + $opt{T} = 1; } else { - return( usage('Wrong value of -T option. The value can be lpar or fnm. The defaut value is lpar.')); + return (usage('Wrong value of -T option. The value can be lpar or fnm. The defaut value is lpar.')); } - + ############################################# # Process command-line arguments ############################################# - if ( scalar( @ARGV)) { - return(usage( "No additional flag is support by this command" )); + if (scalar(@ARGV)) { + return (usage("No additional flag is support by this command")); } + #my $nodetypetab = xCAT::Table->new('nodetype'); #if (! $nodetypetab) #{ # return( ["Failed to open table 'nodetype'.\n"]); #} my $nodehmtab = xCAT::Table->new('nodehm'); - if (! $nodehmtab) + if (!$nodehmtab) { - return( ["Failed to open table 'nodehm'.\n"]); + return (["Failed to open table 'nodehm'.\n"]); } - + my $nodetype; - my @no_typenodes = (); - my @no_mgt_nodes = (); + my @no_typenodes = (); + my @no_mgt_nodes = (); my @error_type_nodes = (); - my $typehash = xCAT::DBobjUtils->getnodetype(\@{$request->{node}}, "ppc"); - for my $node ( @{$request->{node}}) + my $typehash = xCAT::DBobjUtils->getnodetype(\@{ $request->{node} }, "ppc"); + for my $node (@{ $request->{node} }) { #my $ent = $nodetypetab->getNodeAttribs( $node, [qw(nodetype)]); - my $nodehm = $nodehmtab->getNodeAttribs( $node, [qw(mgt)]); - if ( ! $nodehm) + my $nodehm = $nodehmtab->getNodeAttribs($node, [qw(mgt)]); + if (!$nodehm) { push @no_mgt_nodes, $node; - next; + next; } my $ttype = $$typehash{$node}; - if ( !$ttype) + if (!$ttype) { push @no_typenodes, $node; next; } - if ( $ttype ne 'fsp' and $ttype ne 'cec' - and $ttype ne 'bpa' and $ttype ne 'frame' and $ttype ne 'blade') + if ($ttype ne 'fsp' and $ttype ne 'cec' + and $ttype ne 'bpa' and $ttype ne 'frame' and $ttype ne 'blade') { push @error_type_nodes, $node; next; } - if ( ! $nodetype) + if (!$nodetype) { - $nodetype = $ttype; #$ent->{nodetype}; + $nodetype = $ttype; #$ent->{nodetype}; } else { - if ( $nodetype ne $ttype) #$ent->{nodetype}) + if ($nodetype ne $ttype) #$ent->{nodetype}) { - return( ["Cannot support multiple node types in this command line.\n"]); + return (["Cannot support multiple node types in this command line.\n"]); } } } if (scalar(@no_typenodes)) { my $tmp_nodelist = join ',', @no_typenodes; - return ( ["Attribute nodetype.nodetype cannot be found for node(s): $tmp_nodelist. Please define first and try again.\n"]); + return (["Attribute nodetype.nodetype cannot be found for node(s): $tmp_nodelist. Please define first and try again.\n"]); } if (scalar(@no_mgt_nodes)) { my $tmp_nodelist = join ',', @no_mgt_nodes; - return( ["Failed to get nodehm.mgt value for node(s) $tmp_nodelist. Please define first and try again.\n"]); + return (["Failed to get nodehm.mgt value for node(s) $tmp_nodelist. Please define first and try again.\n"]); } if (scalar(@error_type_nodes)) { my $tmp_nodelist = join ',', @error_type_nodes; - my $link = (scalar(@error_type_nodes) eq '1')? 'is':'are'; - return( ["Node type of node(s) $tmp_nodelist $link not supported for this command in FSPAPI.\n"]); + my $link = (scalar(@error_type_nodes) eq '1') ? 'is' : 'are'; + return (["Node type of node(s) $tmp_nodelist $link not supported for this command in FSPAPI.\n"]); } + #$nodetypetab->close(); $nodehmtab->close(); - + $request->{nodetype} = $nodetype; $request->{method} = 'lshwconn'; - return( \%opt); + return (\%opt); } ########################################################################## @@ -426,101 +436,102 @@ sub rmhwconn_parse_args { my $request = shift; my $args = shift; - my %opt = (); + my %opt = (); local *usage = sub { my $usage_string = xCAT::Usage->getUsage("rmhwconn"); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Get options in command line ############################################# - local @ARGV = ref($args) eq 'ARRAY'? @$args:(); + local @ARGV = ref($args) eq 'ARRAY' ? @$args : (); $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose h|help T=s s) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose h|help T=s s))) { + return (usage()); } - return usage() if ( exists $opt{h}); + return usage() if (exists $opt{h}); - if ( $opt{s} ) + if ($opt{s}) { my $opttmp = xCAT::PPCconn::rmhwconn_parse_args($request, $args); return $opttmp; - } - - if( ! exists $opt{T} ) + } + + if (!exists $opt{T}) { - $opt{T} = "lpar"; #defaut value is lpar. - #return( usage('Missing -T option. The value can be lpar or fnm.')); + $opt{T} = "lpar"; #defaut value is lpar. + #return( usage('Missing -T option. The value can be lpar or fnm.')); } - - if( $opt{T} eq "lpar") { - $opt{T} = 0; - } elsif($opt{T} eq "fnm") { - $opt{T} = 1; + + if ($opt{T} eq "lpar") { + $opt{T} = 0; + } elsif ($opt{T} eq "fnm") { + $opt{T} = 1; } else { - return( usage('Wrong value of -T option. The value can be lpar or fnm. The default value is lpar.')); + return (usage('Wrong value of -T option. The value can be lpar or fnm. The default value is lpar.')); } - + ############################################# # Process command-line arguments ############################################# - if ( scalar (@ARGV)) { - return(usage( "No additional flag is support by this command" )); + if (scalar(@ARGV)) { + return (usage("No additional flag is support by this command")); } ########################################## # Check if CECs are controlled by a frame ########################################## - my $nodes = $request->{node}; - my $ppctab = xCAT::Table->new( 'ppc' ); - return( ["Failed to open table 'ppc'.\n"]) if ( ! $ppctab); + my $nodes = $request->{node}; + my $ppctab = xCAT::Table->new('ppc'); + return (["Failed to open table 'ppc'.\n"]) if (!$ppctab); + #my $nodetypetab = xCAT::Table->new( 'nodetype'); #return( ["Failed to open table 'nodetype'.\n"]) if ( ! $nodetypetab); - my $vpdtab = xCAT::Table->new( 'vpd'); - return( ["Failed to open table 'vpd'.\n"]) if ( ! $vpdtab); + my $vpdtab = xCAT::Table->new('vpd'); + return (["Failed to open table 'vpd'.\n"]) if (!$vpdtab); my $nodehmtab = xCAT::Table->new('nodehm'); - return( ["Failed to open table 'nodehm'.\n"]) if (! $nodehmtab); + return (["Failed to open table 'nodehm'.\n"]) if (!$nodehmtab); my @bpa_ctrled_nodes = (); my @no_type_nodes = (); - my @no_mgt_nodes = (); + my @no_mgt_nodes = (); my @frame_members = (); - my $nodetype_hash = xCAT::DBobjUtils->getnodetype($nodes, "ppc"); - for my $node ( @$nodes) + my $nodetype_hash = xCAT::DBobjUtils->getnodetype($nodes, "ppc"); + for my $node (@$nodes) { - my $nodehm = $nodehmtab->getNodeAttribs( $node, [qw(mgt)]); - if ( ! $nodehm) + my $nodehm = $nodehmtab->getNodeAttribs($node, [qw(mgt)]); + if (!$nodehm) { push @no_mgt_nodes, $node; next; } - - my $node_parent = undef; - my $nodetype = undef; - my $node_parent_hash = $ppctab->getNodeAttribs($node,[qw(parent)]); - $nodetype = $$nodetype_hash{$node}; + + my $node_parent = undef; + my $nodetype = undef; + my $node_parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); + $nodetype = $$nodetype_hash{$node}; $node_parent = $node_parent_hash->{parent}; - if ( !$nodetype) + if (!$nodetype) { push @no_type_nodes, $node; next; } - if ( ($nodetype eq 'fsp' or $nodetype eq 'cec') and - $node_parent and - $node_parent ne $node) + if (($nodetype eq 'fsp' or $nodetype eq 'cec') and + $node_parent and + $node_parent ne $node) { push @bpa_ctrled_nodes, $node; } - if ( $nodetype eq 'bpa') + if ($nodetype eq 'bpa') { - my $my_frame_bpa_cec = getFrameMembers( $node, $vpdtab, $ppctab); + my $my_frame_bpa_cec = getFrameMembers($node, $vpdtab, $ppctab); push @frame_members, @$my_frame_bpa_cec; } - if ( $nodetype eq 'frame') + if ($nodetype eq 'frame') { my $my_frame_bpa_cec = xCAT::DBobjUtils::getcecchildren($node); push @frame_members, @$my_frame_bpa_cec; @@ -531,13 +542,14 @@ sub rmhwconn_parse_args if (scalar(@no_type_nodes)) { my $tmp_nodelist = join ',', @no_type_nodes; - return ( usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.\n")); + return (usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.\n")); } if (scalar(@no_mgt_nodes)) { my $tmp_nodelist = join ',', @no_mgt_nodes; - return( ["Failed to get nodehm.mgt value for node(s) $tmp_nodelist. Please define first and try again.\n"]); + return (["Failed to get nodehm.mgt value for node(s) $tmp_nodelist. Please define first and try again.\n"]); } $ppctab->close(); + #$nodetypetab->close(); $vpdtab->close(); $nodehmtab->close(); @@ -547,14 +559,14 @@ sub rmhwconn_parse_args # my $tmp_nodelist = join ',', @bpa_ctrled_nodes; # return ( usage("Node(s) $tmp_nodelist is(are) controlled by BPA.")); #} - - if ( scalar( @frame_members)) + + if (scalar(@frame_members)) { - my @all_nodes = xCAT::Utils::get_unique_members( @$nodes, @frame_members); + my @all_nodes = xCAT::Utils::get_unique_members(@$nodes, @frame_members); $request->{node} = \@all_nodes; } $request->{method} = 'rmhwconn'; - return( \%opt); + return (\%opt); } @@ -565,18 +577,19 @@ sub mkhwconn { my $request = shift; my $hash = shift; + #my $exp = shift; #my $hwtype = @$exp[2]; - my $opt = $request->{opt}; - my @value = (); - my $Rc = undef; - my $tooltype= $opt->{T}; - - xCAT::MsgUtils->verbose_message($request, "mkhwconn START."); - for my $cec_bpa ( keys %$hash) + my $opt = $request->{opt}; + my @value = (); + my $Rc = undef; + my $tooltype = $opt->{T}; + + xCAT::MsgUtils->verbose_message($request, "mkhwconn START."); + for my $cec_bpa (keys %$hash) { my $node_hash = $hash->{$cec_bpa}; - for my $node_name ( keys %$node_hash) + for my $node_name (keys %$node_hash) { my $d = $node_hash->{$node_name}; @@ -597,79 +610,81 @@ sub mkhwconn #} - xCAT::MsgUtils->verbose_message($request, "mkhwconn :add_connection for node:$node_name."); - my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "add_connection", $tooltype, $opt->{port} ); + xCAT::MsgUtils->verbose_message($request, "mkhwconn :add_connection for node:$node_name."); + my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "add_connection", $tooltype, $opt->{port}); $Rc = @$res[2]; - if( @$res[1] ne "") { - push @value, [$node_name, @$res[1], $Rc]; + if (@$res[1] ne "") { + push @value, [ $node_name, @$res[1], $Rc ]; } } } - xCAT::MsgUtils->verbose_message($request, "mkhwconn END."); + xCAT::MsgUtils->verbose_message($request, "mkhwconn END."); return \@value; } ########################################################################## -# List connection status for CECs/BPAs through FSPAPI +# List connection status for CECs/BPAs through FSPAPI ########################################################################## sub lshwconn { - my $request = shift; - my $hash = shift; - my $exp = shift; - my $hwtype = @$exp[2]; - my $opt = $request->{opt}; - my @value = (); - my $Rc = undef; - my $res = undef; + my $request = shift; + my $hash = shift; + my $exp = shift; + my $hwtype = @$exp[2]; + my $opt = $request->{opt}; + my @value = (); + my $Rc = undef; + my $res = undef; my $tooltype = $opt->{T}; - for my $cec_bpa ( keys %$hash) + for my $cec_bpa (keys %$hash) { - my $node_hash = $hash->{$cec_bpa}; - for my $node_name (keys %$node_hash) - { - my $d = $node_hash->{$node_name}; - my $action = "query_connection"; - my $res = xCAT::FSPUtils::fsp_api_action ($request, $node_name, $d, $action, $tooltype); - #print "in lshwconn:\n"; - #print Dumper($res); - my $Rc = @$res[2]; - my $values = @$res[1]; - - ############################################ - # If lssysconn failed, put error into all - # nodes' return values - ############################################ - #if ( $Rc ) - # { - # push @value, [$node_name, $values, $Rc]; - # next; - # } - my %rec = (); - my @data_a = split("\n", $values); - foreach my $data(@data_a) { - if( $data =~ /state/) { - $data =~ /state=([\w\s\,]+), type=([\w-]+), MTMS=([\w-\*\#]+), ([\w=]+), slot=([\w]+), ipadd=([\w.]+), alt_ipadd=([\w.]+)/ ; - #$data =~ /state=([\w\s]+),\(type=([\w-]+)\),\(serial-number=([\w]+)\),\(machinetype-model=([\w-]+)\),sp=([\w]+),\(ip-address=([\w.]+),([\w.]+)\)/ ; - print "parsing: $1,$2,$3,$4,$5,$6,$7\n"; - my $state = $1; - my $type = $2; - my $mtms = $3; - my $sp = $4; - my $slot = $5; - my $ipadd = $6; - my $alt_ipaddr = $7; - if (exists($rec{$slot})) { - next; - } - $rec{$slot} = 1; - $data = "$sp,ipadd=$ipadd,alt_ipadd=$alt_ipaddr,state=$state"; + my $node_hash = $hash->{$cec_bpa}; + for my $node_name (keys %$node_hash) + { + my $d = $node_hash->{$node_name}; + my $action = "query_connection"; + my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, $action, $tooltype); + + #print "in lshwconn:\n"; + #print Dumper($res); + my $Rc = @$res[2]; + my $values = @$res[1]; + + ############################################ + # If lssysconn failed, put error into all + # nodes' return values + ############################################ + #if ( $Rc ) + # { + # push @value, [$node_name, $values, $Rc]; + # next; + # } + my %rec = (); + my @data_a = split("\n", $values); + foreach my $data (@data_a) { + if ($data =~ /state/) { + $data =~ /state=([\w\s\,]+), type=([\w-]+), MTMS=([\w-\*\#]+), ([\w=]+), slot=([\w]+), ipadd=([\w.]+), alt_ipadd=([\w.]+)/; + + #$data =~ /state=([\w\s]+),\(type=([\w-]+)\),\(serial-number=([\w]+)\),\(machinetype-model=([\w-]+)\),sp=([\w]+),\(ip-address=([\w.]+),([\w.]+)\)/ ; + print "parsing: $1,$2,$3,$4,$5,$6,$7\n"; + my $state = $1; + my $type = $2; + my $mtms = $3; + my $sp = $4; + my $slot = $5; + my $ipadd = $6; + my $alt_ipaddr = $7; + if (exists($rec{$slot})) { + next; + } + $rec{$slot} = 1; + $data = "$sp,ipadd=$ipadd,alt_ipadd=$alt_ipaddr,state=$state"; } - push @value, [$node_name, $data, $Rc]; - } - } - } + push @value, [ $node_name, $data, $Rc ]; + } + } + } return \@value; @@ -684,28 +699,29 @@ sub rmhwconn { my $request = shift; my $hash = shift; + #my $exp = shift; #my $hwtype = @$exp[2]; - my $opt = $request->{opt}; - my @value = (); - my $Rc = undef; + my $opt = $request->{opt}; + my @value = (); + my $Rc = undef; my $tooltype = $opt->{T}; - for my $cec_bpa ( keys %$hash) + for my $cec_bpa (keys %$hash) { my $node_hash = $hash->{$cec_bpa}; for my $node_name (keys %$node_hash) { my $d = $node_hash->{$node_name}; - my ( undef,undef,undef,undef,$type) = @$d; + my (undef, undef, undef, undef, $type) = @$d; - my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "rm_connection", $tooltype ); + my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "rm_connection", $tooltype); $Rc = @$res[2]; - if( @$res[1] ne "") { - push @value, [$node_name, @$res[1], $Rc]; + if (@$res[1] ne "") { + push @value, [ $node_name, @$res[1], $Rc ]; } - + } } return \@value; diff --git a/perl-xCAT/xCAT/FSPflash.pm b/perl-xCAT/xCAT/FSPflash.pm index 44c4b7ec0..aeea4d9d9 100644 --- a/perl-xCAT/xCAT/FSPflash.pm +++ b/perl-xCAT/xCAT/FSPflash.pm @@ -12,12 +12,13 @@ use xCAT::Table; use Getopt::Long; use File::Spec; use xCAT::PPCrflash; + #use Data::Dumper; use xCAT::FSPUtils; -my $packages_dir= (); -my $activate = (); -my $verbose = 0; +my $packages_dir = (); +my $activate = (); +my $verbose = 0; my $release_level; my $active_level; my @dirlist; @@ -32,19 +33,19 @@ my $housekeeping = undef; #For -V|--verbose,put the $msg into @value ################################### sub dpush { - my $value = shift; - my $msg = shift; + my $value = shift; + my $msg = shift; - if($verbose == 1) { - push(@$value,$msg); - } + if ($verbose == 1) { + push(@$value, $msg); + } } ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { - my $req = shift; + my $req = shift; $req->{mgt} = __PACKAGE__; my $opt = xCAT::PPCrflash::parse_args($req); delete($req->{mgt}); @@ -52,7 +53,7 @@ sub parse_args { } ########################################################################## -# Invokes the callback with the specified message +# Invokes the callback with the specified message ########################################################################## sub send_msg { @@ -63,23 +64,23 @@ sub send_msg { ################################################# # Called from child process - send to parent ################################################# - if ( exists( $request->{pipe} )) { + if (exists($request->{pipe})) { my $out = $request->{pipe}; $output{errorcode} = $ecode; - $output{data} = \@_; - print $out freeze( [\%output] ); + $output{data} = \@_; + print $out freeze([ \%output ]); print $out "\nENDOFFREEZE6sK4ci\n"; } ################################################# # Called from parent - invoke callback directly ################################################# - elsif ( exists( $request->{callback} )) { + elsif (exists($request->{callback})) { my $callback = $request->{callback}; $output{errorcode} = $ecode; - $output{data} = \@_; - $callback->( \%output ); + $output{data} = \@_; + $callback->(\%output); } } @@ -90,84 +91,88 @@ sub send_msg { #-------------------------------------------------------------------------# # sub get_lic_filenames { - my $mtms = shift; - my $upgrade_required = 0; - my $msg = undef; - my $filename; + my $mtms = shift; + my $upgrade_required = 0; + my $msg = undef; + my $filename; - if(! -d $packages_dir) { - $msg = "The directory $packages_dir doesn't exist!"; - return ("","","", $msg, -1); + if (!-d $packages_dir) { + $msg = "The directory $packages_dir doesn't exist!"; + return ("", "", "", $msg, -1); + } + + #print "opening directory and reading names\n"; + opendir DIRHANDLE, $packages_dir; + @dirlist = readdir DIRHANDLE; + closedir DIRHANDLE; + + @dirlist = File::Spec->no_upwards(@dirlist); + + # Make sure we have some files to process + # + if (!scalar(@dirlist)) { + $msg = "directory $packages_dir is empty"; + return ("", "", "", $msg, -1); + } + + $release_level =~ /(\w{4})(\d{3})/; + my $pns = $1; + my $fff = $2; + + #Find the latest version lic file + @dirlist = grep /\.rpm$/, @dirlist; + @dirlist = grep /$1/, @dirlist; + if (!scalar(@dirlist)) { + $msg = "There isn't a package suitable for $mtms"; + return ("", "", "", $msg, -1); + } + if (scalar(@dirlist) > 1) { + + # Need to find the latest version package. + @dirlist = reverse sort(@dirlist); + my $t = "\n"; + foreach $t (@dirlist) { + $msg = $msg . "$t\t"; } - - #print "opening directory and reading names\n"; - opendir DIRHANDLE, $packages_dir; - @dirlist= readdir DIRHANDLE; - closedir DIRHANDLE; + } - @dirlist = File::Spec->no_upwards( @dirlist ); + $filename = File::Spec->catfile($packages_dir, $dirlist[0]); + $dirlist[0] =~ /(\w{4})(\d{3})_(\w{3})_(\d{3}).rpm$/; + ############## + #If the release levels are different, it will be upgrade_required. + ############# + if ($fff ne $2) { + $upgrade_required = 1; + } else { - # Make sure we have some files to process - # - if( !scalar( @dirlist ) ) { - $msg = "directory $packages_dir is empty"; - return ("","","",$msg, -1); + if (($pns eq $1) && ($4 <= $active_level)) { + $msg = $msg . "Upgrade $mtms $activate!"; + + # if($activate ne "concurrent") { + # $msg = "Option --actviate's value should be disruptive"; + # return ("", "","", $msg, -1); + # } + } else { + $msg = $msg . "Upgrade $mtms!"; + if ($activate !~ /^(disruptive|deferred)$/) { + $msg = "Option --activate's value shouldn't be $activate, and it must be disruptive or deferred"; + return ("", "", "", $msg, -1); + } } + } - $release_level =~/(\w{4})(\d{3})/; - my $pns = $1; - my $fff = $2; - - #Find the latest version lic file - @dirlist = grep /\.rpm$/, @dirlist; - @dirlist = grep /$1/, @dirlist; - if( !scalar( @dirlist ) ) { - $msg = "There isn't a package suitable for $mtms"; - return ("","","",$msg, -1); - } - if( scalar(@dirlist) > 1) { - # Need to find the latest version package. - @dirlist =reverse sort(@dirlist); - my $t = "\n"; - foreach $t(@dirlist) { - $msg =$msg."$t\t"; - } - } + #print "filename is $filename\n"; + my $xml_file_name = $filename; + $xml_file_name =~ s/(.+\.)rpm/\1xml/; - $filename = File::Spec->catfile( $packages_dir, $dirlist[0] ); - $dirlist[0] =~ /(\w{4})(\d{3})_(\w{3})_(\d{3}).rpm$/; - ############## - #If the release levels are different, it will be upgrade_required. - ############# - if($fff ne $2) { - $upgrade_required = 1; - } else { + #print "check_licdd_update: source xml file is $xml_file_name\n"; - if(($pns eq $1) && ($4 <= $active_level)) { - $msg = $msg. "Upgrade $mtms $activate!"; - # if($activate ne "concurrent") { - # $msg = "Option --actviate's value should be disruptive"; - # return ("", "","", $msg, -1); - # } - } else { - $msg = $msg . "Upgrade $mtms!"; - if($activate !~ /^(disruptive|deferred)$/) { - $msg = "Option --activate's value shouldn't be $activate, and it must be disruptive or deferred"; - return ("", "","", $msg, -1); - } - } - } - #print "filename is $filename\n"; - my $xml_file_name = $filename; - $xml_file_name =~ s/(.+\.)rpm/\1xml/; - #print "check_licdd_update: source xml file is $xml_file_name\n"; + if ((-z $filename) || (-z $xml_file_name)) { + $msg = "The package $filename or xml $xml_file_name is empty"; + return ("", "", "", $msg, -1); + } - if( ( -z $filename)|| ( -z $xml_file_name) ) { - $msg = "The package $filename or xml $xml_file_name is empty" ; - return ("", "", "", $msg, -1); - } - - return ($filename, $xml_file_name ,$upgrade_required, $msg, 0); + return ($filename, $xml_file_name, $upgrade_required, $msg, 0); } @@ -184,38 +189,38 @@ sub rflash { my $subreq = $request->{subreq}; my $hwtype = @$exp[2]; my @result; - my $timeout = $request->{ppctimeout}; + my $timeout = $request->{ppctimeout}; my $housekeeping = $request->{housekeeping}; $packages_dir = $request->{opt}->{p}; - $activate = $request->{opt}->{activate}; + $activate = $request->{opt}->{activate}; print "housekeeping:$housekeeping\n"; my $mtms; my $h; my $user; my $action; - my $tmp_file; #the file handle of the stanza + my $tmp_file; #the file handle of the stanza my $rpm_file; my $xml_file; my @rpm_files; my @xml_files; my $upgrade_required; my $stanza = undef; - my $mtms_t; + my $mtms_t; my @value; my %infor; - my $role ; #0x01: BPC A, BPC B; 0x01: Primary or only FSP, 0x02: Backup FSP - + my $role; #0x01: BPC A, BPC B; 0x01: Primary or only FSP, 0x02: Backup FSP + #print "in Directflash \n"; #print Dumper($request); #print Dumper($hash); #################################### # Power commands are grouped by hardware control point - # In Direct attach support, the hcp is the related fsp. + # In Direct attach support, the hcp is the related fsp. #################################### - - # Example of $hash. + + # Example of $hash. #VAR1 = { # '9110-51A*1075ECF' => { # 'Server-9110-51A-SN1075ECF' => [ @@ -228,145 +233,148 @@ sub rflash { # ] # } # }; - my $flag = 0; + my $flag = 0; my $flag2 = 0; - while (my ($mtms,$h) = each(%$hash) ) { - # - #For one mtms, it just needs to do the operation one time. - # + while (my ($mtms, $h) = each(%$hash)) { + # + #For one mtms, it just needs to do the operation one time. + # $flag += 1; - if($flag > 1) { - last; - } - - $mtms =~ /(\w+)-(\w+)\*(\w+)/; - my $mtm = "$1-$2"; - my $serial = $3; - - - while (my ($name,$d) = each(%$h) ) { - $flag2 += 1; - if($flag2 > 1) { - last; - } + if ($flag > 1) { + last; + } - if( !defined($housekeeping) && ($$d[4] =~ /^fsp$/ || $$d[4] =~ /^lpar$/ || $$d[4] =~ /^cec$/)) { - $action = "get_compatible_version_from_rpm"; - my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action, 0, $request->{opt}->{d} ); - my $Rc = @$values[2]; - my $v = @$values[1]; - if ($Rc != 0) { - push @value, [$name, $v, -1]; - return (\@value); - } - - #if( $v !~ "nocheckversion") { - my @levels = split(/,/, $v); - - my $frame = $$d[5]; - my $type = xCAT::DBobjUtils->getnodetype($frame); - if ( ( $frame ne $name ) && ( $type eq "frame" ) && $activate !~ /^deferred$/){ - - my @frame_d = (0, 0, 0, $frame, "frame", 0); - $action = "list_firmware_level"; - $values = xCAT::FSPUtils::fsp_api_action($request, $frame, \@frame_d, $action ); - $Rc = @$values[2]; - my $frame_firmware_level = @$values[1]; - if ($Rc != 0) { - push @value, [$frame, $frame_firmware_level, -1]; - return (\@value); - } - - my $level_a; - my $level_b; - if( $frame_firmware_level =~ /curr_level_a=(\d{3}),curr_ecnumber_a=02(\w{5})/) { - $level_a = "$2_$1"; - } - - if( $frame_firmware_level =~ /curr_level_b=(\d{3}),curr_ecnumber_b=02(\w{5})/) { - $level_b = "$2_$1"; - } - - #print "frame_firmware_level=$frame_firmware_level,level_a=$level_a,level_b=$level_b\n"; - foreach my $l (@levels) { - #print "rpm requires: $l\n" ; - if( (defined($level_a) && ( $l gt $level_a )) || (defined($level_b) && ( $l gt $level_b )) ) { - my $res = "New Managed System level for $name is not compatible with current Power Subsystem level 02$level_a on $frame.\nPower Subsystem level 02$l or later is required."; - - push @value, [$name, $res, -1]; - return (\@value); - } - - } - } - #} - + $mtms =~ /(\w+)-(\w+)\*(\w+)/; + my $mtm = "$1-$2"; + my $serial = $3; + + + while (my ($name, $d) = each(%$h)) { + $flag2 += 1; + if ($flag2 > 1) { + last; } - if(!defined($housekeeping)) { - my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "list_firmware_level"); - my $Rc = @$values[2]; - my $level = @$values[1]; - ##################################### - # Return error - ##################################### - if ( $Rc != SUCCESS ) { - push @value, [$name,$level,$Rc]; - next; - } - - if ( $level =~ /ecnumber=(\w+)/ ) { - $release_level = $1; - &dpush( \@value, [$name,"$mtms :release level:$1"]); - } - - if ( $level =~ /activated_level=(\w+)/ ) { - $active_level = $1; - &dpush( \@value, [$name,"$mtms :activated level:$1"]); - } + if (!defined($housekeeping) && ($$d[4] =~ /^fsp$/ || $$d[4] =~ /^lpar$/ || $$d[4] =~ /^cec$/)) { + $action = "get_compatible_version_from_rpm"; + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action, 0, $request->{opt}->{d}); + my $Rc = @$values[2]; + my $v = @$values[1]; + if ($Rc != 0) { + push @value, [ $name, $v, -1 ]; + return (\@value); + } - } - - - - if($housekeeping =~ /^commit$/) { $action = "code_commit"} - if($housekeeping =~ /^recover$/) { $action = "code_reject"} - if($housekeeping =~ /^bpa_acdl$/) { $action = "acdl"} - if($activate eq "disruptive") { - $action = "code_update"; - } elsif ($activate eq "deferred") { - $action = "code_updateD"; - } elsif (defined($activate)){ - #if($activate =~ /^concurrent$/) { - my $res = "\'$activate\' option not supported in FSPflash. Please use disruptive or deferred mode"; - push @value, [$name, $res, -1]; - next; - } - - my $msg; - if(!defined($housekeeping)) { - my $flag = 0; - ($rpm_file, $xml_file, $upgrade_required,$msg, $flag) = &get_lic_filenames($mtms); - if( $flag == -1) { - push (@value, [$name,"$mtms: $msg"]); - push (@value, [$name,"Failed to upgrade the firmware of $name"]); - return (\@value); - } - dpush ( \@value, [$name, $msg]); - } + #if( $v !~ "nocheckversion") { + my @levels = split(/,/, $v); + + my $frame = $$d[5]; + my $type = xCAT::DBobjUtils->getnodetype($frame); + if (($frame ne $name) && ($type eq "frame") && $activate !~ /^deferred$/) { + + my @frame_d = (0, 0, 0, $frame, "frame", 0); + $action = "list_firmware_level"; + $values = xCAT::FSPUtils::fsp_api_action($request, $frame, \@frame_d, $action); + $Rc = @$values[2]; + my $frame_firmware_level = @$values[1]; + if ($Rc != 0) { + push @value, [ $frame, $frame_firmware_level, -1 ]; + return (\@value); + } + + my $level_a; + my $level_b; + if ($frame_firmware_level =~ /curr_level_a=(\d{3}),curr_ecnumber_a=02(\w{5})/) { + $level_a = "$2_$1"; + } + + if ($frame_firmware_level =~ /curr_level_b=(\d{3}),curr_ecnumber_b=02(\w{5})/) { + $level_b = "$2_$1"; + } + + #print "frame_firmware_level=$frame_firmware_level,level_a=$level_a,level_b=$level_b\n"; + foreach my $l (@levels) { + + #print "rpm requires: $l\n" ; + if ((defined($level_a) && ($l gt $level_a)) || (defined($level_b) && ($l gt $level_b))) { + my $res = "New Managed System level for $name is not compatible with current Power Subsystem level 02$level_a on $frame.\nPower Subsystem level 02$l or later is required."; + + push @value, [ $name, $res, -1 ]; + return (\@value); + } + + } + } + + #} + + } + + if (!defined($housekeeping)) { + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "list_firmware_level"); + my $Rc = @$values[2]; + my $level = @$values[1]; + ##################################### + # Return error + ##################################### + if ($Rc != SUCCESS) { + push @value, [ $name, $level, $Rc ]; + next; + } + + if ($level =~ /ecnumber=(\w+)/) { + $release_level = $1; + &dpush(\@value, [ $name, "$mtms :release level:$1" ]); + } + + if ($level =~ /activated_level=(\w+)/) { + $active_level = $1; + &dpush(\@value, [ $name, "$mtms :activated level:$1" ]); + } + + } + + + + if ($housekeeping =~ /^commit$/) { $action = "code_commit" } + if ($housekeeping =~ /^recover$/) { $action = "code_reject" } + if ($housekeeping =~ /^bpa_acdl$/) { $action = "acdl" } + if ($activate eq "disruptive") { + $action = "code_update"; + } elsif ($activate eq "deferred") { + $action = "code_updateD"; + } elsif (defined($activate)) { + + #if($activate =~ /^concurrent$/) { + my $res = "\'$activate\' option not supported in FSPflash. Please use disruptive or deferred mode"; + push @value, [ $name, $res, -1 ]; + next; + } + + my $msg; + if (!defined($housekeeping)) { + my $flag = 0; + ($rpm_file, $xml_file, $upgrade_required, $msg, $flag) = &get_lic_filenames($mtms); + if ($flag == -1) { + push(@value, [ $name, "$mtms: $msg" ]); + push(@value, [ $name, "Failed to upgrade the firmware of $name" ]); + return (\@value); + } + dpush(\@value, [ $name, $msg ]); + } + + my $res = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action, 0, $request->{opt}->{d}); + if ($action eq "acdl" && @$res[2] eq '0') { + push(@value, [ $name, "Success", '0' ]); + } else { + push(@value, [ $name, @$res[1], @$res[2] ]); + } + return (\@value); - my $res = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action, 0, $request->{opt}->{d} ); - if ($action eq "acdl" && @$res[2] eq '0') { - push(@value, [$name, "Success", '0']); - } else { - push(@value,[$name, @$res[1], @$res[2]]); - } - return (\@value); - } } push(@value, @result); - return (\@value); + return (\@value); } diff --git a/perl-xCAT/xCAT/FSPinv.pm b/perl-xCAT/xCAT/FSPinv.pm index 2825c19a1..6ab7dbd38 100644 --- a/perl-xCAT/xCAT/FSPinv.pm +++ b/perl-xCAT/xCAT/FSPinv.pm @@ -8,95 +8,98 @@ require xCAT::Usage; require xCAT::PPCinv; require xCAT::FSPUtils; use XML::Simple; + #use Data::Dumper; ########################################## # Maps fsp-api attributes to text ########################################## my @licmap = ( - ["ecnumber", "Release Level "], - ["activated_level", "Active Level "], - ["installed_level", "Installed Level"], - ["accepted_level", "Accepted Level "], - ["curr_ecnumber_a", "Release Level A"], - ["curr_level_a", "Level A "], - ["curr_power_on_side_a", "Current Power on side A"], - ["curr_ecnumber_b", "Release Level B"], - ["curr_level_b", "Level B "], - ["curr_power_on_side_b", "Current Power on side B"], - ["curr_ecnumber_primary", "Release Level Primary"], - ["curr_level_primary", "Level Primary "], - ["curr_power_on_side_primary", "Current Power on side Primary"], - ["curr_ecnumber_secondary","Release Level Secondary"], - ["curr_level_secondary", "Level Secondary"], - ["curr_power_on_side_secondary","Current Power on side Secondary"] + [ "ecnumber", "Release Level " ], + [ "activated_level", "Active Level " ], + [ "installed_level", "Installed Level" ], + [ "accepted_level", "Accepted Level " ], + [ "curr_ecnumber_a", "Release Level A" ], + [ "curr_level_a", "Level A " ], + [ "curr_power_on_side_a", "Current Power on side A" ], + [ "curr_ecnumber_b", "Release Level B" ], + [ "curr_level_b", "Level B " ], + [ "curr_power_on_side_b", "Current Power on side B" ], + [ "curr_ecnumber_primary", "Release Level Primary" ], + [ "curr_level_primary", "Level Primary " ], + [ "curr_power_on_side_primary", "Current Power on side Primary" ], + [ "curr_ecnumber_secondary", "Release Level Secondary" ], + [ "curr_level_secondary", "Level Secondary" ], + [ "curr_power_on_side_secondary", "Current Power on side Secondary" ] ); ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { -# xCAT::PPCinv::parse_args(@_); + + # xCAT::PPCinv::parse_args(@_); my $request = shift; my $command = $request->{command}; my $args = $request->{arg}; my %opt = (); -# my @rinv = qw(bus config model serial firm all); - my @rinv = qw( deconfig firm ); + + # my @rinv = qw(bus config model serial firm all); + my @rinv = qw( deconfig firm ); ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose x) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose x))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Unsupported command #################################### - my ($cmd) = grep(/^$ARGV[0]$/, @rinv ); - if ( !defined( $cmd )) { - return(usage( "Invalid command: $ARGV[0]" )); + my ($cmd) = grep(/^$ARGV[0]$/, @rinv); + if (!defined($cmd)) { + return (usage("Invalid command: $ARGV[0]")); } #################################### # Check for an extra argument #################################### shift @ARGV; - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } if (exists($opt{x}) and $cmd !~ /^deconfig$/) { return (usage("Option '-x' can't work with '$cmd'")); } #################################### - # Set method to invoke + # Set method to invoke #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } @@ -112,17 +115,17 @@ sub firmware { my $request = shift; my $hash = shift; my @result; - + # print "in FSPinv \n"; #print Dumper($request); #print Dumper($hash); #################################### # FSPinv with firm command is grouped by hardware control point - # In FSPinv, the hcp is the related fsp. + # In FSPinv, the hcp is the related fsp. #################################### - - # Example of $hash. + + # Example of $hash. #VAR1 = { # '9110-51A*1075ECF' => { # 'Server-9110-51A-SN1075ECF' => [ @@ -136,57 +139,58 @@ sub firmware { # } # }; - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { ##################################### - # Command only supported on FSP/BPA/LPARs + # Command only supported on FSP/BPA/LPARs ##################################### - if ( @$d[4] !~ /^(cec|frame|fsp|bpa|lpar|blade)$/ ) { - push @result, - [$name,"Information only available for CEC/FSP/Frame/BPA/LPAR",RC_ERROR]; - next; + if (@$d[4] !~ /^(cec|frame|fsp|bpa|lpar|blade)$/) { + push @result, + [ $name, "Information only available for CEC/FSP/Frame/BPA/LPAR", RC_ERROR ]; + next; } - ################# - #For support on Lpars, the flag need to be changed. - ########## - if(@$d[4] eq "lpar") { - @$d[4] = "fsp"; - @$d[0] = 0; - } - my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "list_firmware_level"); - my $Rc = @$values[2]; - my $data = @$values[1]; - #print "values"; - #print Dumper($values); - ##################################### - # Return error - ##################################### - if ( $Rc != SUCCESS ) { - push @result, [$name,$data,$Rc]; - next; + ################# + #For support on Lpars, the flag need to be changed. + ########## + if (@$d[4] eq "lpar") { + @$d[4] = "fsp"; + @$d[0] = 0; } - - ##################################### + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "list_firmware_level"); + my $Rc = @$values[2]; + my $data = @$values[1]; + + #print "values"; + #print Dumper($values); + ##################################### + # Return error + ##################################### + if ($Rc != SUCCESS) { + push @result, [ $name, $data, $Rc ]; + next; + } + + ##################################### # Format fsp-api results ##################################### my $val; - foreach $val ( @licmap ) { - if ( $data =~ /@$val[0]=(\w+)/ ) { - push @result, [$name,"@$val[1]: $1",$Rc]; + foreach $val (@licmap) { + if ($data =~ /@$val[0]=(\w+)/) { + push @result, [ $name, "@$val[1]: $1", $Rc ]; } } } } - return( \@result ); + return (\@result); } ########################################################################## -# Returns firmware version +# Returns firmware version ########################################################################## sub firm { - return( firmware(@_) ); + return (firmware(@_)); } ########################################################################## @@ -206,17 +210,17 @@ sub deconfig { my $request = shift; my $hash = shift; my @result; - + # print "in FSPinv \n"; #print Dumper($request); #print Dumper($hash); #################################### # FSPinv with deconfig command is grouped by hardware control point - # In FSPinv, the hcp is the related fsp. + # In FSPinv, the hcp is the related fsp. #################################### - - # Example of $hash. + + # Example of $hash. #VAR1 = { # '9110-51A*1075ECF' => { # 'Server-9110-51A-SN1075ECF' => [ @@ -230,114 +234,116 @@ sub deconfig { # } # }; - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { ##################################### - # Command only supported on FSP/BPA/LPARs + # Command only supported on FSP/BPA/LPARs ##################################### - if ( @$d[4] !~ /^(cec|fsp)$/ ) { - push @result, - [$name,"Deconfigured resource information only available for CEC/FSP",RC_ERROR]; - next; + if (@$d[4] !~ /^(cec|fsp)$/) { + push @result, + [ $name, "Deconfigured resource information only available for CEC/FSP", RC_ERROR ]; + next; } - ################# - #For support on Lpars, the flag need to be changed. - ########## - #if(@$d[4] eq "lpar") { - # @$d[4] = "fsp"; - # @$d[0] = 0; - #} - my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "get_cec_deconfigured"); - my $Rc = @$values[2]; - my $data = @$values[1]; - #print "values"; - #print Dumper($values); + ################# + #For support on Lpars, the flag need to be changed. + ########## + #if(@$d[4] eq "lpar") { + # @$d[4] = "fsp"; + # @$d[0] = 0; + #} + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "get_cec_deconfigured"); + my $Rc = @$values[2]; + my $data = @$values[1]; + + #print "values"; + #print Dumper($values); ##################################### # Return error ##################################### - if ( $Rc != SUCCESS ) { - push @result, [$name,$data,$Rc]; - next; - } - - - ##################################### - # Format fsp-api results - ##################################### - #my $decfg = XMLin($data); - my $decfg; - eval { - $decfg = XMLin($data); - }; - if( $@ ) { - push @result,[$name, "Error: there are some unreadable XML data from the firmware. It can't be parsed by 'xcatd'.", -1]; - return (\@result); - } - if( exists($request->{opt}->{x})) { - push @result, [$name, "\n".$data, -1]; - next; - } - #print "decfg"; - #print Dumper($decfg); - my $node = $decfg->{NODE}; - if( defined($node) && exists($node->{Location_code}) ) { - my $Call_Out_Hardware_State ; - my $Call_Out_Method; - my $Location_code; - my $RID; - my $TYPE; - my $dres; - if (ref($node->{GARDRECORD}) eq "ARRAY") { - $dres = $node->{GARDRECORD}; - } elsif (ref($node->{GARDRECORD}) eq "HASH") { - push @$dres, $node->{GARDRECORD}; - } else { - push @result,[$name,"NO Deconfigured resources", 0]; - return( \@result ); - } - push @result,[$name,"Deconfigured resources", 0]; - push @result,[$name,"Location_code RID Call_Out_Method Call_Out_Hardware_State TYPE", 0]; - push @result,[$name,"$node->{Location_code} $node->{RID}", 0]; - - #foreach my $unit(@{$node->{GARDRECORD}}) { - foreach my $unit(@$dres) { - while (my ($key, $unit3) = each(%$unit) ) { - - if($key eq "GARDUNIT") { - if (ref($unit3) eq "HASH") { - $Call_Out_Hardware_State = $unit3->{Call_Out_Hardware_State}; - $Call_Out_Method = $unit3->{Call_Out_Method}; - $Location_code = $unit3->{Location_code}; - $RID = $unit3->{RID}; - $TYPE = $unit3->{TYPE}; - - push @result,[$name,"$Location_code $RID $Call_Out_Method $Call_Out_Hardware_State $TYPE",0]; - } elsif(ref($unit3) eq "ARRAY") { - - foreach my $unit4(@$unit3) { - $Call_Out_Hardware_State = $unit4->{Call_Out_Hardware_State}; - $Call_Out_Method = $unit4->{Call_Out_Method}; - $Location_code = $unit4->{Location_code}; - $RID = $unit4->{RID}; - $TYPE = $unit4->{TYPE}; - push @result,[$name,"$Location_code $RID $Call_Out_Method $Call_Out_Hardware_State $TYPE",0]; - } - } - } - } + if ($Rc != SUCCESS) { + push @result, [ $name, $data, $Rc ]; + next; + } - } + ##################################### + # Format fsp-api results + ##################################### + #my $decfg = XMLin($data); + my $decfg; + eval { + $decfg = XMLin($data); + }; + if ($@) { + push @result, [ $name, "Error: there are some unreadable XML data from the firmware. It can't be parsed by 'xcatd'.", -1 ]; + return (\@result); + } + if (exists($request->{opt}->{x})) { + push @result, [ $name, "\n" . $data, -1 ]; + next; + } + + #print "decfg"; + #print Dumper($decfg); + my $node = $decfg->{NODE}; + if (defined($node) && exists($node->{Location_code})) { + my $Call_Out_Hardware_State; + my $Call_Out_Method; + my $Location_code; + my $RID; + my $TYPE; + my $dres; + if (ref($node->{GARDRECORD}) eq "ARRAY") { + $dres = $node->{GARDRECORD}; + } elsif (ref($node->{GARDRECORD}) eq "HASH") { + push @$dres, $node->{GARDRECORD}; + } else { + push @result, [ $name, "NO Deconfigured resources", 0 ]; + return (\@result); + } + push @result, [ $name, "Deconfigured resources", 0 ]; + push @result, [ $name, "Location_code RID Call_Out_Method Call_Out_Hardware_State TYPE", 0 ]; + push @result, [ $name, "$node->{Location_code} $node->{RID}", 0 ]; + + #foreach my $unit(@{$node->{GARDRECORD}}) { + foreach my $unit (@$dres) { + while (my ($key, $unit3) = each(%$unit)) { + + if ($key eq "GARDUNIT") { + if (ref($unit3) eq "HASH") { + $Call_Out_Hardware_State = $unit3->{Call_Out_Hardware_State}; + $Call_Out_Method = $unit3->{Call_Out_Method}; + $Location_code = $unit3->{Location_code}; + $RID = $unit3->{RID}; + $TYPE = $unit3->{TYPE}; + + push @result, [ $name, "$Location_code $RID $Call_Out_Method $Call_Out_Hardware_State $TYPE", 0 ]; + } elsif (ref($unit3) eq "ARRAY") { + + foreach my $unit4 (@$unit3) { + $Call_Out_Hardware_State = $unit4->{Call_Out_Hardware_State}; + $Call_Out_Method = $unit4->{Call_Out_Method}; + $Location_code = $unit4->{Location_code}; + $RID = $unit4->{RID}; + $TYPE = $unit4->{TYPE}; + push @result, [ $name, "$Location_code $RID $Call_Out_Method $Call_Out_Hardware_State $TYPE", 0 ]; + } + } + } + } + + + } + + } else { + push @result, [ $name, "NO Deconfigured resources", 0 ]; + } - } else { - push @result,[$name,"NO Deconfigured resources", 0]; - } - } } - return( \@result ); + return (\@result); } @@ -353,11 +359,11 @@ sub model { ########################################################################## sub all { - my @result = ( - @{deconfig(@_)}, - @{firmware(@_)} - ); - return( \@result ); + my @result = ( + @{ deconfig(@_) }, + @{ firmware(@_) } + ); + return (\@result); } diff --git a/perl-xCAT/xCAT/FSPmac.pm b/perl-xCAT/xCAT/FSPmac.pm index 9651363cb..b8d355203 100644 --- a/perl-xCAT/xCAT/FSPmac.pm +++ b/perl-xCAT/xCAT/FSPmac.pm @@ -9,7 +9,7 @@ use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::MsgUtils qw(verbose_message); use xCAT::LparNetbootExp; ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { xCAT::PPCmac::parse_args(@_); @@ -21,21 +21,21 @@ sub parse_args { ########################################################################## sub do_getmacs { - my $request = shift; - my $d = shift; - my $exp = shift; - my $name = shift; - my $node = shift; - my $opt = $request->{opt}; - my $ssh = @$exp[0]; - my $userid = @$exp[4]; - my $pw = @$exp[5]; + my $request = shift; + my $d = shift; + my $exp = shift; + my $name = shift; + my $node = shift; + my $opt = $request->{opt}; + my $ssh = @$exp[0]; + my $userid = @$exp[4]; + my $pw = @$exp[5]; my %optarg; my $cmd; my $result; ####################################### - # Disconnect Expect session + # Disconnect Expect session ####################################### #xCAT::PPCcli::disconnect( $exp ); @@ -60,7 +60,7 @@ sub do_getmacs { # return( [RC_ERROR,"Command not installed: $cmd"] ); #} ####################################### - # Save user name and passwd of hcp to + # Save user name and passwd of hcp to # environment variables. # lpar_netboot.expect depends on this ####################################### @@ -68,17 +68,19 @@ sub do_getmacs { $ENV{HCP_PASSWD} = $pw; ####################################### - # Turn on verbose and debugging + # Turn on verbose and debugging ####################################### - if ( exists($request->{verbose}) ) { + if (exists($request->{verbose})) { + #$cmd.= " -v -x"; - $optarg{'v'} = 1; #for verbose - $optarg{'x'} = 1; #for debug + $optarg{'v'} = 1; #for verbose + $optarg{'x'} = 1; #for debug } ####################################### # Force LPAR shutdown ####################################### - if ( exists( $opt->{f} )) { + if (exists($opt->{f})) { + #$cmd.= " -i"; $optarg{'i'} = 1; } else { @@ -86,16 +88,17 @@ sub do_getmacs { # Force LPAR shutdown if LPAR is # running Linux ################################# - my $table = "nodetype"; - my $intable = 0; + my $table = "nodetype"; + my $intable = 0; my @TableRowArray = xCAT::DBobjUtils->getDBtable($table); - if ( @TableRowArray ) { - foreach ( @TableRowArray ) { + if (@TableRowArray) { + foreach (@TableRowArray) { my @nodelist = split(',', $_->{'node'}); - my @oslist = split(',', $_->{'os'}); - my $osname = "AIX"; - if ( grep(/^$node$/, @nodelist) ) { - if ( !grep(/^$osname$/, @oslist) ) { + my @oslist = split(',', $_->{'os'}); + my $osname = "AIX"; + if (grep(/^$node$/, @nodelist)) { + if (!grep(/^$osname$/, @oslist)) { + #$cmd.= " -i"; $optarg{'i'} = 1; } @@ -109,17 +112,20 @@ sub do_getmacs { # type is not assigned in table # but mnt node is running Linux ################################# - if ( xCAT::Utils->isLinux() && $intable == 0 ) { - #$cmd.= " -i"; - $optarg{'i'} = 1; + if (xCAT::Utils->isLinux() && $intable == 0) { + + #$cmd.= " -i"; + $optarg{'i'} = 1; } } - my %client_nethash = xCAT::DBobjUtils->getNetwkInfo( [$node] ); - if ( grep /hf/, $client_nethash{$node}{mgtifname} ) { + my %client_nethash = xCAT::DBobjUtils->getNetwkInfo([$node]); + if (grep /hf/, $client_nethash{$node}{mgtifname}) { + #$cmd.= " -t hfi-ent"; $optarg{'t'} = "hfi-ent"; } else { + #$cmd.= " -t ent"; $optarg{'t'} = "ent"; } @@ -127,17 +133,19 @@ sub do_getmacs { ####################################### # Network specified (-D ping test) ####################################### - if ( exists( $opt->{noping} )) { - $optarg{'D'} = 1; + if (exists($opt->{noping})) { + $optarg{'D'} = 1; $optarg{'noping'} = 1; $optarg{'pprofile'} = "not_use"; #lpar_netboot.expect need pprofile for p5 & p6, but for p7 ih, we don't use this attribute. } - if ( exists( $opt->{S} )) { - if ( exists( $opt->{o} )) { + if (exists($opt->{S})) { + if (exists($opt->{o})) { + #$cmd .=" -o"; - $optarg{'o'} = 1; + $optarg{'o'} = 1; } + #$cmd.= " -D -s auto -d auto -S $opt->{S} -G $opt->{G} -C $opt->{C}"; $optarg{'D'} = 1; $optarg{'s'} = 'auto'; @@ -146,19 +154,20 @@ sub do_getmacs { $optarg{'C'} = $opt->{C}; $optarg{'G'} = $opt->{G}; $optarg{'pprofile'} = "not_use"; #lpar_netboot.expect need pprofile for p5 & p6, but for p7 ih, we don't use this attribute. - } + } ####################################### - # Add command options + # Add command options ####################################### #$cmd.= " -f -M -A -n \"$name\" \"$pprofile\" \"$fsp\" $id $hcp \"$node\""; $optarg{'f'} = 1; $optarg{'M'} = 1; $optarg{'A'} = 1; $optarg{'n'} = $name; + #$optarg{'pprofile'} = $pprofile; - $optarg{'fsp'} = $fsp; - $optarg{'id'} = $id; - $optarg{'hcp'} = $hcp; + $optarg{'fsp'} = $fsp; + $optarg{'id'} = $id; + $optarg{'hcp'} = $hcp; $optarg{'node'} = $node; ######################################## @@ -213,238 +222,243 @@ sub getmacs { my $name; my @emptynode; my $res; - - if ( $par =~ /^HASH/ ) { - #my $t = $request->{node}; - #foreach my $n (@$t) { - # return( [[$n,"Please use -D -f options to getmacs through FSP directly",RC_ERROR]] ); - # } + + if ($par =~ /^HASH/) { + + #my $t = $request->{node}; + #foreach my $n (@$t) { + # return( [[$n,"Please use -D -f options to getmacs through FSP directly",RC_ERROR]] ); + # } ######################################### # Parse the filters specified by user ######################################### my $filter; - if ( $opt->{F} ) { - my @filters = split /,/,$opt->{F}; - foreach ( @filters ) { - my @value = split /=/,$_; - $filter->{@value[0]} = @value[1]; + if ($opt->{F}) { + my @filters = split /,/, $opt->{F}; + foreach (@filters) { + my @value = split /=/, $_; + $filter->{ @value[0] } = @value[1]; } } - ######################################### + ######################################### # A hash to save lpar attributes - ######################################### + ######################################### my %nodeatt = (); ######################################### # Cleanup old data ######################################### - my $result = (); + my $result = (); ######################################### # No ping test performed, call lshwres # to achieve the MAC address ######################################### - foreach my $hcp ( keys %$par ) { + foreach my $hcp (keys %$par) { my $hash = $par->{$hcp}; - my $cmd; + my $cmd; my @lpar_name = keys(%$hash); - $name = $lpar_name[0]; - my $d = $$hash{$name}; + $name = $lpar_name[0]; + my $d = $$hash{$name}; ######################################### # Achieve virtual ethernet MAC address ######################################### - #@$cmd[0] = ["lpar","virtualio","","eth"]; - #@$cmd[1] = ["port","hea","","logical"]; - #@$cmd[2] = ["port","hea","","phys"]; - my @cmd = ("lpar_veth_mac","lpar_lhea_mac","lpar_hfi_mac"); + #@$cmd[0] = ["lpar","virtualio","","eth"]; + #@$cmd[1] = ["port","hea","","logical"]; + #@$cmd[2] = ["port","hea","","phys"]; + my @cmd = ("lpar_veth_mac", "lpar_lhea_mac", "lpar_hfi_mac"); ######################################### # Parse the output of lshwres command ######################################### - for ( my $stat = 0; $stat < 3; $stat++ ) { - #my $output = xCAT::PPCcli::lshwres( $exp, @$cmd[$stat], $hcp); - my $output = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $cmd[$stat]); - my $macs; + for (my $stat = 0 ; $stat < 3 ; $stat++) { + + #my $output = xCAT::PPCcli::lshwres( $exp, @$cmd[$stat], $hcp); + my $output = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $cmd[$stat]); + my $macs; my $res = $$output[1]; - chomp($res); - my @op = split("\n", $res); - #print Dumper(\@op); - foreach my $line ( @op ) { - if ( $line =~ /^.*lpar\_id=(\d+),.*$/ ) { + chomp($res); + my @op = split("\n", $res); + + #print Dumper(\@op); + foreach my $line (@op) { + if ($line =~ /^.*lpar\_id=(\d+),.*$/) { ######################################### # For the first two commands ######################################### my $lparid = $1; $nodeatt{$hcp}{$lparid}{'num'}++; - $macs = $nodeatt{$hcp}{$lparid}{'num'}; - my @attrs = split /,/, $line; - foreach ( @attrs ) { + $macs = $nodeatt{$hcp}{$lparid}{'num'}; + my @attrs = split /,/, $line; + foreach (@attrs) { my @attr = split /=/, $_; - $nodeatt{$hcp}{$lparid}{$macs}{@attr[0]} = @attr[1]; + $nodeatt{$hcp}{$lparid}{$macs}{ @attr[0] } = @attr[1]; } - } elsif ( ($line =~ /^(.*)port\_group=(\d+),(.*),"log\_port\_ids=(.*)"/) || ($line =~ /^(.*)port\_group=(\d+),(.*),log\_port\_ids=(.*)/) ) { + } elsif (($line =~ /^(.*)port\_group=(\d+),(.*),"log\_port\_ids=(.*)"/) || ($line =~ /^(.*)port\_group=(\d+),(.*),log\_port\_ids=(.*)/)) { ######################################### # For the third command ######################################### my $port_group = $2; - if ( $4 !~ /^none$/ ) { - my @ids = split /,/, $4; - my @attrs = split /,/, $1; + if ($4 !~ /^none$/) { + my @ids = split /,/, $4; + my @attrs = split /,/, $1; foreach (@attrs) { - my @attr = split /=/,$_; + my @attr = split /=/, $_; foreach (@ids) { - $nodeatt{$hcp}{$port_group}{$_}{@attr[0]} = @attr[1]; - } - } - my @attrs = split /,/, $3; - foreach (@attrs) { - my @attr = split /=/,$_; - foreach (@ids) { - $nodeatt{$hcp}{$port_group}{$_}{@attr[0]} = @attr[1]; + $nodeatt{$hcp}{$port_group}{$_}{ @attr[0] } = @attr[1]; } } - } + my @attrs = split /,/, $3; + foreach (@attrs) { + my @attr = split /=/, $_; + foreach (@ids) { + $nodeatt{$hcp}{$port_group}{$_}{ @attr[0] } = @attr[1]; + } + } + } } } } - - foreach ( keys %$hash ) { - my $node = $_; - my $d = $hash->{$_}; - my $mtms = @$d[2]; - my $id = @$d[0]; - my $nodetype = @$d[4]; - my $mac_count = $nodeatt{$mtms}{$id}{'num'}; - my $value = (); - my $data = (); + foreach (keys %$hash) { + my $node = $_; + my $d = $hash->{$_}; + my $mtms = @$d[2]; + my $id = @$d[0]; + my $nodetype = @$d[4]; + + my $mac_count = $nodeatt{$mtms}{$id}{'num'}; + my $value = (); + my $data = (); my $type; ######################################### # Invalid target hardware ######################################### - if ( $nodetype ne "lpar" ) { - return( [[$node,"Node must be LPAR",RC_ERROR]] ); + if ($nodetype ne "lpar") { + return ([ [ $node, "Node must be LPAR", RC_ERROR ] ]); } ######################################### # Put all the attributes required # together ######################################### - push @$value,"\n#Type Phys_Port_Loc MAC_Address Adapter Port_Group Phys_Port Logical_Port VLan VSwitch Curr_Conn_Speed\n"; + push @$value, "\n#Type Phys_Port_Loc MAC_Address Adapter Port_Group Phys_Port Logical_Port VLan VSwitch Curr_Conn_Speed\n"; - for ( my $num = 1; $num <= $mac_count; $num++ ) { - my $mac_addr = $nodeatt{$mtms}{$id}{$num}{'mac_addr'}; - my $adapter_id = $nodeatt{$mtms}{$id}{$num}{'adapter_id'}; - my $port_group = $nodeatt{$mtms}{$id}{$num}{'port_group'}; - my $phys_port_id = $nodeatt{$mtms}{$id}{$num}{'phys_port_id'}; + for (my $num = 1 ; $num <= $mac_count ; $num++) { + my $mac_addr = $nodeatt{$mtms}{$id}{$num}{'mac_addr'}; + my $adapter_id = $nodeatt{$mtms}{$id}{$num}{'adapter_id'}; + my $port_group = $nodeatt{$mtms}{$id}{$num}{'port_group'}; + my $phys_port_id = $nodeatt{$mtms}{$id}{$num}{'phys_port_id'}; my $logical_port_id = $nodeatt{$mtms}{$id}{$num}{'logical_port_id'}; - my $vlan_id = $nodeatt{$mtms}{$id}{$num}{'port_vlan_id'}; - my $vswitch = $nodeatt{$mtms}{$id}{$num}{'vswitch'}; - my $phys_port_loc = $nodeatt{$mtms}{$port_group}{$logical_port_id}{'phys_port_loc'}; + my $vlan_id = $nodeatt{$mtms}{$id}{$num}{'port_vlan_id'}; + my $vswitch = $nodeatt{$mtms}{$id}{$num}{'vswitch'}; + my $phys_port_loc = $nodeatt{$mtms}{$port_group}{$logical_port_id}{'phys_port_loc'}; my $curr_conn_speed = $nodeatt{$mtms}{$port_group}{$logical_port_id}{'curr_conn_speed'}; - if ( $phys_port_loc ) { - $type = "hea"; + if ($phys_port_loc) { + $type = "hea"; } else { $type = "virtualio"; } - my $type = $nodeatt{$mtms}{$id}{$num}{'type'}; - my %att = (); - if( $mac_addr ) { - $mac_addr = format_mac($mac_addr); - } - if ( !exists( $opt->{M} )) { + my $type = $nodeatt{$mtms}{$id}{$num}{'type'}; + my %att = (); + if ($mac_addr) { + $mac_addr = format_mac($mac_addr); + } + if (!exists($opt->{M})) { my @mac_addrs = split /\|/, $mac_addr; $mac_addr = @mac_addrs[0]; } - $att{'MAC_Address'} = ($mac_addr) ? $mac_addr : "N/A"; - $att{'Adapter'} = ($adapter_id) ? $adapter_id : "N/A"; - $att{'Port_Group'} = ($port_group) ? $port_group : "N/A"; - $att{'Phys_Port'} = ($phys_port_id) ? $phys_port_id : "N/A"; - $att{'Logical_Port'} = ($logical_port_id) ? $logical_port_id : "N/A"; - $att{'VLan'} = ($vlan_id) ? $vlan_id : "N/A"; - $att{'VSwitch'} = ($vswitch) ? $vswitch : "N/A"; - $att{'Phys_Port_Loc'} = ($phys_port_loc) ? $phys_port_loc : "N/A"; - $att{'Curr_Conn_Speed'} = ($curr_conn_speed) ? $curr_conn_speed : "N/A"; - $att{'Type'} = $type; + $att{'MAC_Address'} = ($mac_addr) ? $mac_addr : "N/A"; + $att{'Adapter'} = ($adapter_id) ? $adapter_id : "N/A"; + $att{'Port_Group'} = ($port_group) ? $port_group : "N/A"; + $att{'Phys_Port'} = ($phys_port_id) ? $phys_port_id : "N/A"; + $att{'Logical_Port'} = ($logical_port_id) ? $logical_port_id : "N/A"; + $att{'VLan'} = ($vlan_id) ? $vlan_id : "N/A"; + $att{'VSwitch'} = ($vswitch) ? $vswitch : "N/A"; + $att{'Phys_Port_Loc'} = ($phys_port_loc) ? $phys_port_loc : "N/A"; + $att{'Curr_Conn_Speed'} = ($curr_conn_speed) ? $curr_conn_speed : "N/A"; + $att{'Type'} = $type; ######################################### # Parse the adapter with the filters # specified ######################################### - if ( defined($filter) ) { + if (defined($filter)) { my $matched = 0; - foreach my $key ( keys %$filter ) { - if ( $key eq "MAC_Address" ) { - my $mac = lc($att{$key}); + foreach my $key (keys %$filter) { + if ($key eq "MAC_Address") { + my $mac = lc($att{$key}); my $filter_mac = lc($filter->{$key}); $mac =~ s/://g; $filter_mac =~ s/://g; - if ( grep(/$filter_mac/, $mac) ) { + if (grep(/$filter_mac/, $mac)) { $matched = 1; last; } - } elsif ( grep(/$filter->{$key}/, $att{$key}) ) { + } elsif (grep(/$filter->{$key}/, $att{$key})) { $matched = 1; last; } } - if ( $matched ) { - push @$value,"$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}\n"; + if ($matched) { + push @$value, "$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}\n"; } } else { - push @$value,"$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}\n"; + push @$value, "$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}\n"; } } ######################################### # Write MAC address to database ######################################### - if ( !exists( $opt->{d} )) { - writemac( $node, $value ); + if (!exists($opt->{d})) { + writemac($node, $value); } - if ( scalar(@$value) < 2 ) { - #my $filter = "lpar_id,curr_profile"; - #my $prof = xCAT::PPCcli::lssyscfg( $exp, "node", $mtms, $filter, $id ); - #my $Rc = shift(@$prof); + if (scalar(@$value) < 2) { + + #my $filter = "lpar_id,curr_profile"; + #my $prof = xCAT::PPCcli::lssyscfg( $exp, "node", $mtms, $filter, $id ); + #my $Rc = shift(@$prof); ######################################### # Return error ######################################### - #if ( $Rc != SUCCESS ) { - # return( [[$node,@$prof[0],$Rc]] ); - #} + #if ( $Rc != SUCCESS ) { + # return( [[$node,@$prof[0],$Rc]] ); + #} - #foreach my $val ( @$prof ) { - # my ($lpar_id,$curr_profile) = split /,/, $val; - # if ( !length($curr_profile) || ($curr_profile =~ /^none$/) ) { - # push @emptynode,$node; - # } - #} - return( [[$node,"get NO mac address from PHYP for $node",-1]]); + #foreach my $val ( @$prof ) { + # my ($lpar_id,$curr_profile) = split /,/, $val; + # if ( !length($curr_profile) || ($curr_profile =~ /^none$/) ) { + # push @emptynode,$node; + # } + #} + return ([ [ $node, "get NO mac address from PHYP for $node", -1 ] ]); } - foreach ( @$value ) { - if ( /^#\s?Type/ ) { - $data.= "\n$_\n"; + foreach (@$value) { + if (/^#\s?Type/) { + $data .= "\n$_\n"; } else { - #$data.= format_mac( $_ ); - $data .= $_; + + #$data.= format_mac( $_ ); + $data .= $_; } } - push @$result,[$node,$data,0]; + push @$result, [ $node, $data, 0 ]; } } - if ( scalar(@emptynode) > 0 ) { - return([[join(",", @emptynode),"\nThese nodes have no active profiles. Please active the nodes to enable the default profiles",RC_ERROR]]); - } - return([@$result]); + if (scalar(@emptynode) > 0) { + return ([ [ join(",", @emptynode), "\nThese nodes have no active profiles. Please active the nodes to enable the default profiles", RC_ERROR ] ]); + } + return ([@$result]); } else { ######################################### # Connect to fsp to achieve MAC address @@ -453,108 +467,112 @@ sub getmacs { my $d = $par; ######################################### - # Get node data + # Get node data ######################################### - my $lparid = @$d[0]; - my $mtms = @$d[2]; - my $type = @$d[4]; - my $node = @$d[6]; + my $lparid = @$d[0]; + my $mtms = @$d[2]; + my $type = @$d[4]; + my $node = @$d[6]; ######################################### - # Invalid target hardware + # Invalid target hardware ######################################### - if ( $type ne "lpar" ) { - return( [[$node,"Node must be LPAR",RC_ERROR]] ); + if ($type ne "lpar") { + return ([ [ $node, "Node must be LPAR", RC_ERROR ] ]); } ######################################### # Get name known by HCP ######################################### my $filter = "name,lpar_id"; - # my $values = xCAT::PPCcli::lssyscfg( $exp, $type, $mtms, $filter ); - #my $Rc = shift(@$values); + + # my $values = xCAT::PPCcli::lssyscfg( $exp, $type, $mtms, $filter ); + #my $Rc = shift(@$values); ######################################### # Return error ######################################### - #if ( $Rc != SUCCESS ) { - # return( [[$node,@$values[0],$Rc]] ); - # } + #if ( $Rc != SUCCESS ) { + # return( [[$node,@$values[0],$Rc]] ); + # } ######################################### # Find LPARs by lpar_id ######################################### - # foreach ( @$values ) { - # if ( /^(.*),$lparid$/ ) { - # $name = $1; - # last; - # } - # } + # foreach ( @$values ) { + # if ( /^(.*),$lparid$/ ) { + # $name = $1; + # last; + # } + # } ######################################### - # Node not found by lpar_id + # Node not found by lpar_id ######################################### - # if ( !defined( $name )) { - # return( [[$node,"Node not found, lparid=$lparid",RC_ERROR]] ); + # if ( !defined( $name )) { + # return( [[$node,"Node not found, lparid=$lparid",RC_ERROR]] ); # } my $Rc; + #my $sitetab = xCAT::Table->new('site'); #my $vcon = $sitetab->getAttribs({key => "conserverondemand"}, 'value'); #if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { - # $result = xCAT::PPCcli::lpar_netboot( - # $exp, - # $request->{verbose}, - # $name, - # $d, - # $opt ); + # $result = xCAT::PPCcli::lpar_netboot( + # $exp, + # $request->{verbose}, + # $name, + # $d, + # $opt ); # return( [[$node,"Not support conserverondemand's value is yes",RC_ERROR]] ); #} else { - ######################################### - # Manually collect MAC addresses. - ######################################### - xCAT::MsgUtils->verbose_message($request, "getmacs :do_getmacs for node:$node."); - $result = do_getmacs( $request, $d, $exp, $name, $node ); + ######################################### + # Manually collect MAC addresses. + ######################################### + xCAT::MsgUtils->verbose_message($request, "getmacs :do_getmacs for node:$node."); + $result = do_getmacs($request, $d, $exp, $name, $node); + #} #$sitetab->close; $Rc = shift(@$result); - + my $data; - my $value; - if ( $Rc == SUCCESS ) { - foreach ( @$result ) { - if ( /^#\s?Type/ ) { - $data.= "\n$_\n"; - push @$value, "\n$_\n"; - } elsif ( /^ent\s+/ || /^hfi-ent\s+/ ) { - #my @fields = split /\s+/, $_; - #my $mac = $fields[2]; - #$mac = format_mac( $mac ); - #$fields[2] = $mac; - #$data .= join(" ",@fields)."\n"; - #push @$value, join(" ",@fields)."\n"; - $data .= "$_\n"; - push @$value, "$_\n"; - } - } - push @$res,[$node,$data,0]; - } - - ################################## - # Form string from array results - ################################## - if ( exists($request->{verbose}) ) { - if ( $Rc == SUCCESS ) { - if ( !exists( $opt->{d} )) { - writemac( $node, $value ); + my $value; + if ($Rc == SUCCESS) { + foreach (@$result) { + if (/^#\s?Type/) { + $data .= "\n$_\n"; + push @$value, "\n$_\n"; + } elsif (/^ent\s+/ || /^hfi-ent\s+/) { + + #my @fields = split /\s+/, $_; + #my $mac = $fields[2]; + #$mac = format_mac( $mac ); + #$fields[2] = $mac; + #$data .= join(" ",@fields)."\n"; + #push @$value, join(" ",@fields)."\n"; + $data .= "$_\n"; + push @$value, "$_\n"; } } - return( [[$node,join( '', @$result ),$Rc]] ); + push @$res, [ $node, $data, 0 ]; + } + + ################################## + # Form string from array results + ################################## + if (exists($request->{verbose})) { + if ($Rc == SUCCESS) { + if (!exists($opt->{d})) { + writemac($node, $value); + } + } + return ([ [ $node, join('', @$result), $Rc ] ]); } ################################## # Return error ################################## - if ( $Rc != SUCCESS ) { - if ( @$result[0] =~ /lpar_netboot (.*)/ ) { - return( [[$node,$1,$Rc]] ); + if ($Rc != SUCCESS) { + if (@$result[0] =~ /lpar_netboot (.*)/) { + return ([ [ $node, $1, $Rc ] ]); } - return( [[$node,join( '', @$result ),$Rc]] ); + return ([ [ $node, join('', @$result), $Rc ] ]); } ##################################### # lpar_netboot returns: @@ -570,24 +588,25 @@ sub getmacs { # ent U9117.MMA.10F6F3D-V5-C3-T1 1e0e122a930d /vdevice/l-lan@30000003 # ##################################### - #my $data; + #my $data; - #foreach ( @$result ) { - # if ( /^#\s?Type/ ) { - # $data.= "\n$_\n"; - # } elsif ( /^ent\s+/ or /^hfi-ent\s+/) { - # $data.= format_mac( $_ ); - # } - #} + #foreach ( @$result ) { + # if ( /^#\s?Type/ ) { + # $data.= "\n$_\n"; + # } elsif ( /^ent\s+/ or /^hfi-ent\s+/) { + # $data.= format_mac( $_ ); + # } + #} ##################################### # Write first valid adapter MAC to database ##################################### - if ( !exists( $opt->{d} )) { - writemac( $node, $value ); + if (!exists($opt->{d})) { + writemac($node, $value); } - #return( [[$node,$data,$Rc]] ); + + #return( [[$node,$data,$Rc]] ); xCAT::MsgUtils->verbose_message($request, "getmacs END."); - return $res; + return $res; } } @@ -600,11 +619,11 @@ sub cal_mac { my $mac = shift; $mac =~ s/://g; - $mac =~ /(.........)(.)(..)/; - my ($basemac, $mac_h, $mac_l) = ($1,$2, $3); + $mac =~ /(.........)(.)(..)/; + my ($basemac, $mac_h, $mac_l) = ($1, $2, $3); my $macnum_l = hex($mac_l); my $macnum_h = hex($mac_h); - $macnum_l += 1; + $macnum_l += 1; if ($macnum_l > 0xFF) { $macnum_h += 1; } @@ -612,9 +631,9 @@ sub cal_mac { $newmac_l =~ /(..)$/; $newmac_l = $1; my $newmac_h = sprintf("%01X", $macnum_h); - my $newmac = $basemac.$newmac_h.$newmac_l; + my $newmac = $basemac . $newmac_h . $newmac_l; - return( $newmac ); + return ($newmac); } ########################################################################## @@ -623,6 +642,7 @@ sub cal_mac { sub format_mac { my $mac = shift; + #my $data = shift; ##################################### @@ -632,8 +652,8 @@ sub format_mac { my $newmac = $mac; my @macs = split /\|/, $mac; - if ( !xCAT::Utils->isAIX() ) { - foreach my $mac_a ( @macs ) { + if (!xCAT::Utils->isAIX()) { + foreach my $mac_a (@macs) { ################################# # Delineate MAC with colons ################################# @@ -642,11 +662,11 @@ sub format_mac { $mac_a =~ s/:$//; push @newmacs, $mac_a; } - $newmac = join("|",@newmacs); + $newmac = join("|", @newmacs); } - return( "$newmac" ); + return ("$newmac"); } @@ -656,7 +676,7 @@ sub format_mac { sub checkmac { my $mac = shift; - if ( !xCAT::Utils->isAIX()) { + if (!xCAT::Utils->isAIX()) { if ($mac =~ /\w{2}:\w{2}:\w{2}:\w{2}:\w{2}:\w{2}/) { return 1; } else { @@ -668,12 +688,12 @@ sub checkmac { } ########################################################################## -# Write first valid adapter MAC to database +# Write first valid adapter MAC to database ########################################################################## sub writemac { - my $name = shift; - my $data = shift; + my $name = shift; + my $data = shift; my $value; my $pingret; my $ping_test; @@ -683,18 +703,18 @@ sub writemac { ##################################### # Find first valid adapter ##################################### - foreach ( @$data ) { - if ( /^ent\s+/ or /^hfi-ent\s+/ ) { + foreach (@$data) { + if (/^ent\s+/ or /^hfi-ent\s+/) { $value = $_; ##################################### # MAC not found in output ##################################### - if ( !defined( $value )) { + if (!defined($value)) { return; } @fields = split /\s+/, $value; $pingret = $fields[4]; - if ( $pingret eq "successful" ) { + if ($pingret eq "successful") { $ping_test = 0; last; } @@ -704,17 +724,17 @@ sub writemac { ##################################### # If no valid adapter, find the first one ##################################### - if ( $pingret ne "successful" ) { - foreach ( @$data ) { + if ($pingret ne "successful") { + foreach (@$data) { unless (&checkmac($_)) { next; } - if ( /^ent\s+/ or /^hfi-ent\s+/ ) { - $value = $_; + if (/^ent\s+/ or /^hfi-ent\s+/) { + $value = $_; $ping_test = 0; last; - } elsif ( /^hea\s+/ || /^virtualio\s+/ || /^HFI\s+/ ) { - $value = $_; + } elsif (/^hea\s+/ || /^virtualio\s+/ || /^HFI\s+/) { + $value = $_; $ping_test = 1; last; } @@ -724,24 +744,24 @@ sub writemac { ##################################### # MAC not found in output ##################################### - if ( !defined( $value )) { + if (!defined($value)) { return; } ##################################### # Get adapter mac ##################################### - #$value = format_mac( $value ); + #$value = format_mac( $value ); @fields = split /\s+/, $value; - $mac = $fields[2]; + $mac = $fields[2]; ##################################### # Write adapter mac to database ##################################### - my $mactab = xCAT::Table->new( "mac", -create=>1, -autocommit=>1 ); - if ( !$mactab ) { - return( [[$name,"Error opening 'mac'",RC_ERROR]] ); + my $mactab = xCAT::Table->new("mac", -create => 1, -autocommit => 1); + if (!$mactab) { + return ([ [ $name, "Error opening 'mac'", RC_ERROR ] ]); } - $mactab->setNodeAttribs( $name,{mac=>$mac} ); + $mactab->setNodeAttribs($name, { mac => $mac }); $mactab->close(); } diff --git a/perl-xCAT/xCAT/FSPpower.pm b/perl-xCAT/xCAT/FSPpower.pm index c5be978a4..972c22791 100644 --- a/perl-xCAT/xCAT/FSPpower.pm +++ b/perl-xCAT/xCAT/FSPpower.pm @@ -2,17 +2,21 @@ package xCAT::FSPpower; use strict; + #use Getopt::Long; use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::PPCpower; use xCAT::FSPUtils; +use xCAT::GlobalDef; +use xCAT_monitoring::monitorctrl; + #use Data::Dumper; ########################################################################## # Parse the command line for options and operands ########################################################################## sub parse_args { - xCAT::PPCpower::parse_args(@_); + xCAT::PPCpower::parse_args(@_); } @@ -21,58 +25,60 @@ sub parse_args { ########################################################################## sub enumerate { - my $request = shift; - my $h = shift; - my $mtms = shift; + my $request = shift; + my $h = shift; + my $mtms = shift; my $tooltype = shift; - my %outhash = (); - my %cmds = (); - my $type = (); - my $cec_bpa = (); + my %outhash = (); + my %cmds = (); + my $type = (); + my $cec_bpa = (); my $tmp_d; my $tmp_name; - + ###################################### # Check for CEC/LPAR/BPAs in list ###################################### - while (my ($name,$d) = each(%$h) ) { - $cec_bpa = @$d[3]; - $type = @$d[4]; - $tmp_d = $d; + while (my ($name, $d) = each(%$h)) { + $cec_bpa = @$d[3]; + $type = @$d[4]; + $tmp_d = $d; $tmp_name = $name; + #$cmds{$type} = ($type=~/^lpar$/) ? "all_lpars_state" : "cec_state"; - if( $type=~/^lpar$/ ) { + if ($type =~ /^lpar$/) { $cmds{$type} = "all_lpars_state"; - } elsif ($type=~/^(fsp|cec|blade)$/) { - $cmds{$type} = "cec_state"; + } elsif ($type =~ /^(fsp|cec|blade)$/) { + $cmds{$type} = "cec_state"; } else { $cmds{$type} = "bpa_state"; } } - foreach my $type ( keys %cmds ) { + foreach my $type (keys %cmds) { my $action = $cmds{$type}; - #my $values = xCAT::FSPUtils::fsp_state_action ($request, $cec_bpa, $type, $action, $tooltype); - my $values = xCAT::FSPUtils::fsp_state_action ($request, $cec_bpa, $tmp_d, $action, $tooltype); + + #my $values = xCAT::FSPUtils::fsp_state_action ($request, $cec_bpa, $type, $action, $tooltype); + my $values = xCAT::FSPUtils::fsp_state_action($request, $cec_bpa, $tmp_d, $action, $tooltype); my $Rc = shift(@$values); ################################## - # Return error + # Return error ################################## - if ( $Rc != 0 ) { - return( [$Rc,@$values[0]] ); + if ($Rc != 0) { + return ([ $Rc, @$values[0] ]); } ################################## - # Save LPARs by id + # Save LPARs by id ################################## - foreach ( @$values ) { - my ($state,$lparid) = split /,/; + foreach (@$values) { + my ($state, $lparid) = split /,/; ############################## - # No lparid for fsp/bpa + # No lparid for fsp/bpa ############################## - if ( $type =~ /^(fsp|bpa|cec|frame|blade)$/ ) { + if ($type =~ /^(fsp|bpa|cec|frame|blade)$/) { if ($type eq 'blade') { if ($state eq 'operating') { - my $res = xCAT::FSPUtils::fsp_api_action($request, $tmp_name,$tmp_d,'state',$tooltype); + my $res = xCAT::FSPUtils::fsp_api_action($request, $tmp_name, $tmp_d, 'state', $tooltype); if (@$res[2] == 0 and @$res[1] =~ /open-firmware/i) { $state = @$res[1]; } @@ -83,17 +89,12 @@ sub enumerate { } $lparid = $type; } - $outhash{ $lparid } = $state; + $outhash{$lparid} = $state; } } - return( [0,\%outhash] ); + return ([ 0, \%outhash ]); } - - - - - ########################################################################## # Performs boot operation (Off->On, On->Reset) ########################################################################## @@ -101,14 +102,15 @@ sub powercmd_boot { my $request = shift; my $hash = shift; - my @output = (); - - + my @output = (); + + my $newstat; + my %newnodestatus = (); ###################################### - # Power commands are grouped by CEC + # Power commands are grouped by CEC # not Hardware Control Point ###################################### - + #Example of $hash # $VAR1 = { # 'Server-9110-51A-SN1075ECF' => [ @@ -120,59 +122,70 @@ sub powercmd_boot { # 0 # ] # } - foreach my $node_name ( keys %$hash) + foreach my $node_name (keys %$hash) { - - my $d = $hash->{$node_name}; - if (!($$d[4] =~ /^lpar$/)) { - push @output, [$node_name, "\'boot\' command not supported for CEC or BPA", -1 ]; - #return (\@output); - next; - } - - my $res = xCAT::FSPUtils::fsp_api_action ($request,$node_name, $d, "state"); - #print "In boot, state\n"; - #print Dumper($res); - my $Rc = @$res[2]; - my $data = @$res[1]; - #my $type = @$d[4]; - #my $id = ($type=~/^(fsp|bpa)$/) ? $type : @$d[0]; - - ################################## - # Output error - ################################## - if ( $Rc != SUCCESS ) { - push @output, [$node_name,$data,$Rc]; - next; - } - - ################################## - # Convert state to on/off - ################################## - my $state = power_status($data); - #print "boot:state:$state\n"; - my $op = ($state =~ /^off$/) ? "on" : "reset"; - # Attribute powerinterval in site table, - # to control the rpower speed - if( defined($request->{'powerinterval'}) ) { - Time::HiRes::sleep($request->{'powerinterval'}); - } + my $d = $hash->{$node_name}; + if (!($$d[4] =~ /^lpar$/)) { + push @output, [ $node_name, "\'boot\' command not supported for CEC or BPA", -1 ]; + #return (\@output); + next; + } - $res = xCAT::FSPUtils::fsp_api_action ($request,$node_name, $d, $op); - - # @output ... - $Rc = @$res[2]; - $data = @$res[1]; - if ( $Rc != SUCCESS ) { - push @output, [$node_name,$data,$Rc]; - next; - } - push @output,[$node_name, "Success", 0]; + my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "state"); + #print "In boot, state\n"; + #print Dumper($res); + my $Rc = @$res[2]; + my $data = @$res[1]; + + #my $type = @$d[4]; + #my $id = ($type=~/^(fsp|bpa)$/) ? $type : @$d[0]; + + ################################## + # Output error + ################################## + if ($Rc != SUCCESS) { + push @output, [ $node_name, $data, $Rc ]; + next; + } + + ################################## + # Convert state to on/off + ################################## + my $state = power_status($data); + + #print "boot:state:$state\n"; + my $op = ($state =~ /^off$/) ? "on" : "reset"; + + $newstat = $::STATUS_POWERING_ON; + + # Attribute powerinterval in site table, + # to control the rpower speed + if (defined($request->{'powerinterval'})) { + Time::HiRes::sleep($request->{'powerinterval'}); + } + + $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, $op); + + # @output ... + $Rc = @$res[2]; + $data = @$res[1]; + if ($Rc != SUCCESS) { + push @output, [ $node_name, $data, $Rc ]; + next; + } + + push @output, [ $node_name, "Success", 0 ]; + if ($newstat) { + push @{ $newnodestatus{$newstat} }, $node_name; + } } - return( \@output ); + if (%newnodestatus) { + xCAT_monitoring::monitorctrl::setNodeStatusAttributes(\%newnodestatus, 1); + } + return (\@output); } @@ -182,29 +195,29 @@ sub powercmd_boot { ########################################################################## sub powercmd { - my $request = shift; - my $hash = shift; - my $tooltype = $request->{opt}->{T}; - my @result = (); + my $request = shift; + my $hash = shift; + my $tooltype = $request->{opt}->{T}; + my @result = (); my @output; my $action; my $node_name; my $newids; my $newnames; my $newd; - my $lpar_flag = 0; - my $cec_flag = 0; + my $lpar_flag = 0; + my $cec_flag = 0; my $frame_flag = 0; - #print "++++in powercmd++++\n"; + #print "++++in powercmd++++\n"; #print Dumper($hash); - + #################################### - # Power commands are grouped by cec or lpar + # Power commands are grouped by cec or lpar # not Hardware Control Point #################################### - - #Example of $hash. + + #Example of $hash. #$VAR1 = { # 'lpar01' => [ # '1', @@ -215,113 +228,145 @@ sub powercmd { # 0 # ] # }; - - foreach $node_name ( keys %$hash) + my $newstat; + my @updatenode; + my %newnodestatus = (); + foreach $node_name (keys %$hash) { - $action = $request->{'op'}; + $action = $request->{'op'}; my $d = $hash->{$node_name}; - if ($$d[4] =~ /^lpar$/) { - if( !($action =~ /^(on|off|of|reset|sms)$/)) { - push @output, [$node_name, "\'$action\' command not supported for LPAR", -1 ]; - return (\@output); - } - $newids .= "$$d[0],"; - $newnames .="$node_name,"; - $newd = $d; - $lpar_flag = 1; - } elsif ($$d[4] =~ /^(fsp|cec|blade)$/) { - if($action =~ /^on$/) { $action = "cec_on_autostart"; } - if($action =~ /^off$/) { $action = "cec_off"; } - if($action =~ /^resetsp$/) { $action = "reboot_service_processor"; } - if($action =~ /^lowpower$/) { $action = "cec_on_low_power"; } - #if($action =~ /^cycle$/) {$action = "cec_reboot";} - if($action =~ /^cycle$/) {$action = "reset";} - if($action !~ /^cec_on_autostart$/ && $action !~ /^cec_off$/ && $action !~ /^cec_on_low_power$/ && $action !~ /^onstandby$/ && $action !~ /^reboot_service_processor$/ && $action !~ /^reset$/ && $action !~ /^sms$/) { - push @output, [$node_name, "\'$action\' command not supported for $$d[4]", -1 ]; - return (\@output); - } - $newids = $$d[0]; + if ($$d[4] =~ /^lpar$/) { + if (!($action =~ /^(on|off|of|reset|sms)$/)) { + push @output, [ $node_name, "\'$action\' command not supported for LPAR", -1 ]; + return (\@output); + } + $newids .= "$$d[0],"; + $newnames .= "$node_name,"; + $newd = $d; + $lpar_flag = 1; + if ($action =~ /^on$/) { + $newstat = $::STATUS_POWERING_ON; + push @updatenode, $node_name; + } + if ($action =~ /^(off|of$)/) { + $newstat = $::STATUS_POWERING_OFF; + push @updatenode, $node_name; + } + if ($action =~ /^reset$/) { + my $res = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "state"); + my $Rc = @$res[2]; + my $data = @$res[1]; + if ($Rc != SUCCESS) { next; } + my $state = power_status($data); + if ($state =~ /^off$/) { next; } + $newstat = $::STATUS_POWERING_ON; + push @updatenode, $node_name; + } + } elsif ($$d[4] =~ /^(fsp|cec|blade)$/) { + if ($action =~ /^on$/) { $action = "cec_on_autostart"; } + if ($action =~ /^off$/) { $action = "cec_off"; } + if ($action =~ /^resetsp$/) { $action = "reboot_service_processor"; } + if ($action =~ /^lowpower$/) { $action = "cec_on_low_power"; } + + #if($action =~ /^cycle$/) {$action = "cec_reboot";} + if ($action =~ /^cycle$/) { $action = "reset"; } + if ($action !~ /^cec_on_autostart$/ && $action !~ /^cec_off$/ && $action !~ /^cec_on_low_power$/ && $action !~ /^onstandby$/ && $action !~ /^reboot_service_processor$/ && $action !~ /^reset$/ && $action !~ /^sms$/) { + push @output, [ $node_name, "\'$action\' command not supported for $$d[4]", -1 ]; + return (\@output); + } + $newids = $$d[0]; $newnames = $node_name; - $newd = $d; - $cec_flag = 1; + $newd = $d; + $cec_flag = 1; } else { - if ( $action =~ /^rackstandby$/) { - $action = "enter_rack_standby"; - } elsif ( $action=~/^exit_rackstandby$/) { - $action = "exit_rack_standby"; - } elsif ($action =~ /^resetsp$/) { - $action = "reboot_service_processor"; - } else { - push @output, [$node_name, "$node_name\'s type isn't fsp or lpar. Not allow doing this operation", -1 ]; - return (\@output); - } - $newids = $$d[0]; - $newnames = $node_name; - $newd = $d; - $frame_flag = 1; - } + if ($action =~ /^rackstandby$/) { + $action = "enter_rack_standby"; + } elsif ($action =~ /^exit_rackstandby$/) { + $action = "exit_rack_standby"; + } elsif ($action =~ /^resetsp$/) { + $action = "reboot_service_processor"; + } else { + push @output, [ $node_name, "$node_name\'s type isn't fsp or lpar. Not allow doing this operation", -1 ]; + return (\@output); + } + $newids = $$d[0]; + $newnames = $node_name; + $newd = $d; + $frame_flag = 1; + } - if( $lpar_flag && $cec_flag) { - push @output, [$node_name," $node_name\'s type is different from the last node. The noderange of power control operation could NOT be lpar/cec mixed" , -1 ]; - return (\@output); - - } + if ($lpar_flag && $cec_flag) { + push @output, [ $node_name, " $node_name\'s type is different from the last node. The noderange of power control operation could NOT be lpar/cec mixed", -1 ]; + return (\@output); - if( $lpar_flag && $frame_flag) { - push @output, [$node_name," $node_name\'s type is different from the last node. The noderange of power control operation could NOT be lpar/frame mixed" , -1 ]; - return (\@output); - - } + } - if( $cec_flag && $frame_flag) { - push @output, [$node_name," $node_name\'s type is different from the last node. The noderange of power control operation could NOT be cec/frame mixed" , -1 ]; - return (\@output); - - } + if ($lpar_flag && $frame_flag) { + push @output, [ $node_name, " $node_name\'s type is different from the last node. The noderange of power control operation could NOT be lpar/frame mixed", -1 ]; + return (\@output); + + } + + if ($cec_flag && $frame_flag) { + push @output, [ $node_name, " $node_name\'s type is different from the last node. The noderange of power control operation could NOT be cec/frame mixed", -1 ]; + return (\@output); + + } } $$newd[0] = $newids; - + #print Dumper($newd); - my $res = xCAT::FSPUtils::fsp_api_action($request, $newnames, $newd, $action, $tooltype, $request->{'powerinterval'} ); + my $res = xCAT::FSPUtils::fsp_api_action($request, $newnames, $newd, $action, $tooltype, $request->{'powerinterval'}); + # print "In boot, state\n"; # print Dumper($res); - my $Rc = @$res[2]; + my $Rc = @$res[2]; my $data = @$res[1]; - foreach $node_name ( keys %$hash) + foreach $node_name (keys %$hash) { my $d = $hash->{$node_name}; - - if( $data =~ /Error/) { - if( $data =~ /Power interval/) { + + if ($data =~ /Error/) { + if ($data =~ /Power interval/) { $data = "Error: Invalid powerinterval value in the site table. The valid powerinerval value could be 0 to 300 ."; - push @output, [$node_name, $data, -1]; + push @output, [ $node_name, $data, -1 ]; next; - } elsif ( $data =~ /$node_name/) { - push @output, [$node_name, $data, -1]; + } elsif ($data =~ /$node_name/) { + push @output, [ $node_name, $data, -1 ]; next; } } if ((scalar(keys %$hash) == 1) and $Rc) { - push @output, [$node_name, $data, $Rc]; + push @output, [ $node_name, $data, $Rc ]; } else { - # check the state of the blade or CEC after cec_reboot in order to let HWS realize the destination CEC had been powerd off # - #my $msg = "success"; - if ($action eq 'cec_reboot') { - sleep 0.1; - xCAT::FSPUtils::fsp_state_action ($request, @$d[3], $d, "cec_state"); - #my $state_res = xCAT::FSPUtils::fsp_state_action (@$d[3], @$d[4], "cec_state"); - #my @state_state = @$state_res[1]; - #$msg = @state_state[0]; - } - push @output, [$node_name,"Success", 0]; - #push @output, [$node_name,$msg, 0]; + + # check the state of the blade or CEC after cec_reboot in order to let HWS realize the destination CEC had been powerd off # + #my $msg = "success"; + if ($action eq 'cec_reboot') { + sleep 0.1; + xCAT::FSPUtils::fsp_state_action($request, @$d[3], $d, "cec_state"); + + #my $state_res = xCAT::FSPUtils::fsp_state_action (@$d[3], @$d[4], "cec_state"); + #my @state_state = @$state_res[1]; + #$msg = @state_state[0]; + } + push @output, [ $node_name, "Success", 0 ]; + + #push @output, [$node_name,$msg, 0]; + if (($newstat) and (grep { $_ eq $node_name } @updatenode)) { + push @{ $newnodestatus{$newstat} }, $node_name; + } } - } - return( \@output ); + } + + if (%newnodestatus) { + xCAT_monitoring::monitorctrl::setNodeStatusAttributes(\%newnodestatus, 1); + } + return (\@output); } @@ -329,44 +374,44 @@ sub powercmd { # Queries CEC/LPAR power status (On or Off) for powercmd_boot ########################################################################## sub power_status { - my $value = shift; + my $value = shift; my @states = ( "Operating|operating|on", "Running|running", "standby", "Open Firmware|open-firmware" ); - foreach my $s ( @states ) { - if ($value =~ /$s/ ) { - return("on"); + foreach my $s (@states) { + if ($value =~ /$s/) { + return ("on"); } - } - return("off"); + } + return ("off"); } ########################################################################## -# Queries CEC/LPAR power status +# Queries CEC/LPAR power status ########################################################################## sub state { - my $request = shift; - my $hash = shift; - my $exp = shift; # NOt use - my $prefix = shift; - my $convert = shift; - my @output = (); - my $tooltype = $request->{opt}->{T}; - - - #print "------in state--------\n"; - #print Dumper($request); - #print Dumper($hash); + my $request = shift; + my $hash = shift; + my $exp = shift; # NOt use + my $prefix = shift; + my $convert = shift; + my @output = (); + my $tooltype = $request->{opt}->{T}; + + + #print "------in state--------\n"; + #print Dumper($request); + #print Dumper($hash); #################################### # Power commands are grouped by hardware control point - # In FSPpower, the hcp is the related fsp. + # In FSPpower, the hcp is the related fsp. #################################### - - # Example of $hash. + + # Example of $hash. #VAR1 = { # '9110-51A*1075ECF' => { # 'Server-9110-51A-SN1075ECF' => [ @@ -377,58 +422,61 @@ sub state { # 'fsp', # 0 # ] - # } + # } # }; - my @result = (); + my @result = (); - if ( !defined( $prefix )) { + if (!defined($prefix)) { $prefix = ""; } - while (my ($mtms,$h) = each(%$hash) ) { + while (my ($mtms, $h) = each(%$hash)) { ###################################### # Build CEC/LPAR information hash ###################################### my $stat = enumerate($request, $h, $mtms, $tooltype); - my $Rc = shift(@$stat); + my $Rc = shift(@$stat); my $data = @$stat[0]; + #if($Rc != 0) { # push @result,[$mtms ,$$data[0],$Rc]; # return(\@result); #} - while (my ($name,$d) = each(%$h) ) { + while (my ($name, $d) = each(%$h)) { ################################## - # Look up by lparid + # Look up by lparid ################################## my $type = @$d[4]; - my $id = ($type=~/^(fsp|bpa|cec|frame|blade)$/) ? $type : @$d[0]; - + my $id = ($type =~ /^(fsp|bpa|cec|frame|blade)$/) ? $type : @$d[0]; + ################################## # Output error ################################## - if ( $Rc != SUCCESS ) { - push @result, [$name, "$prefix$data",$Rc]; + if ($Rc != SUCCESS) { + push @result, [ $name, "$prefix$data", $Rc ]; next; } - #print Dumper($data); - my @k = keys(%$data); - if( grep(/all/, @k) == 1 ) { - $data->{$id} = $data->{all}; + + #print Dumper($data); + my @k = keys(%$data); + if (grep(/all/, @k) == 1) { + $data->{$id} = $data->{all}; } ################################## - # Node not found + # Node not found ################################## - if ($type !~ /^blade$/ and !exists( $data->{$id} )) { - my $res = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "state", $tooltype); - my $rc = @$res[2]; + if ($type !~ /^blade$/ and !exists($data->{$id})) { + my $res = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "state", $tooltype); + my $rc = @$res[2]; my $val = @$res[1]; - if( $rc != 0) { + if ($rc != 0) { + #push @result, [$name, $prefix.$val,1]; } - - if( !defined($val) || $val =~ /^error$/ ) { - push @result, [$name, $prefix."Node not found",1]; + + if (!defined($val) || $val =~ /^error$/) { + push @result, [ $name, $prefix . "Node not found", 1 ]; next; } else { $data->{$id} = $val; @@ -441,19 +489,19 @@ sub state { my $value = $data->{$id}; ############################## - # Convert state to on/off + # Convert state to on/off ############################## - if ( defined( $convert )) { - $value = power_status( $value ); + if (defined($convert)) { + $value = power_status($value); } - push @result, [$name,"$prefix$value",$Rc]; + push @result, [ $name, "$prefix$value", $Rc ]; } } - return( \@result ); - - + return (\@result); + + } @@ -461,28 +509,28 @@ sub state { ########################################################################## -# Queries CEC/LPAR power status +# Queries CEC/LPAR power status ########################################################################## sub state1 { my $request = shift; my $hash = shift; - my $exp = shift; # NOt use + my $exp = shift; # NOt use my $prefix = shift; my $convert = shift; my @output = (); - my $action = "state"; - - - #print "------in state--------\n"; - #print Dumper($request); - #print Dumper($hash); + my $action = "state"; + + + #print "------in state--------\n"; + #print Dumper($request); + #print Dumper($hash); #################################### # Power commands are grouped by hardware control point - # In FSPpower, the hcp is the related fsp. + # In FSPpower, the hcp is the related fsp. #################################### - - # Example of $hash. + + # Example of $hash. #VAR1 = { # '9110-51A*1075ECF' => { # 'Server-9110-51A-SN1075ECF' => [ @@ -493,55 +541,56 @@ sub state1 { # 'fsp', # 0 # ] - # } + # } # }; - - foreach my $cec_bpa ( keys %$hash) + + foreach my $cec_bpa (keys %$hash) { - + my $node_hash = $hash->{$cec_bpa}; - for my $node_name ( keys %$node_hash) + for my $node_name (keys %$node_hash) { my $d = $node_hash->{$node_name}; - if($$d[4] =~ /^fsp$/ || $$d[4] =~ /^bpa$/) { - $action = "cec_state"; - } - my $stat = xCAT::FSPUtils::fsp_api_action ($request, $node_name, $d, $action); - my $Rc = @$stat[2]; - my $data = @$stat[1]; + if ($$d[4] =~ /^fsp$/ || $$d[4] =~ /^bpa$/) { + $action = "cec_state"; + } + my $stat = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, $action); + my $Rc = @$stat[2]; + my $data = @$stat[1]; my $type = @$d[4]; - #my $id = ($type=~/^(fsp|bpa)$/) ? $type : @$d[0]; - ################################## + + #my $id = ($type=~/^(fsp|bpa)$/) ? $type : @$d[0]; + ################################## # Output error ################################## - if ( $Rc != SUCCESS ) { - push @output, [$node_name,$data,$Rc]; + if ($Rc != SUCCESS) { + push @output, [ $node_name, $data, $Rc ]; next; } - ############################## - # Convert state to on/off ############################## - if ( defined( $convert )) { - $data = power_status( $data ); + # Convert state to on/off + ############################## + if (defined($convert)) { + $data = power_status($data); } - #print Dumper($prefix); + #print Dumper($prefix); ################## - # state cec_state - ################# - if ( defined($prefix) ) { + # state cec_state + ################# + if (defined($prefix)) { $data = "$prefix $data"; } - - push @output,[$node_name, $data, $Rc]; - } + + push @output, [ $node_name, $data, $Rc ]; + } } - return( \@output ); - + return (\@output); + } diff --git a/perl-xCAT/xCAT/FSPscan.pm b/perl-xCAT/xCAT/FSPscan.pm index 1dacbeeb9..68f753674 100644 --- a/perl-xCAT/xCAT/FSPscan.pm +++ b/perl-xCAT/xCAT/FSPscan.pm @@ -5,7 +5,7 @@ use strict; use Getopt::Long; use Socket; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::PPCdb; use xCAT::PPCscan; @@ -14,35 +14,37 @@ use xCAT::Usage; use xCAT::NetworkUtils; use xCAT::FSPUtils; require xCAT::data::ibmhwtypes; + #use Data::Dumper; ############################################## # Globals ############################################## -my @header = ( - ["type", "%-8s" ], - ["name", "placeholder" ], - ["id", "%-8s" ], - ["type-model", "%-12s" ], - ["serial-number", "%-15s\n" ]); +my @header = ( + [ "type", "%-8s" ], + [ "name", "placeholder" ], + [ "id", "%-8s" ], + [ "type-model", "%-12s" ], + [ "serial-number", "%-15s\n" ]); + #, # ["side", "%-8s" ], # ["address", "%-20s\n" ]); my @attribs = qw(nodetype node id mtm serial side hcp pprofile parent groups mgt cons hwtype); my %globalnodetype = ( - fsp => $::NODETYPE_PPC, - bpa => $::NODETYPE_PPC, - cec => $::NODETYPE_PPC, - frame=> $::NODETYPE_PPC, - lpar =>"$::NODETYPE_PPC,$::NODETYPE_OSI" + fsp => $::NODETYPE_PPC, + bpa => $::NODETYPE_PPC, + cec => $::NODETYPE_PPC, + frame => $::NODETYPE_PPC, + lpar => "$::NODETYPE_PPC,$::NODETYPE_OSI" ); my %globalhwtype = ( - fsp => $::NODETYPE_FSP, - bpa => $::NODETYPE_BPA, - lpar => $::NODETYPE_LPAR, - cec => $::NODETYPE_CEC, - frame=> $::NODETYPE_FRAME, + fsp => $::NODETYPE_FSP, + bpa => $::NODETYPE_BPA, + lpar => $::NODETYPE_LPAR, + cec => $::NODETYPE_CEC, + frame => $::NODETYPE_FRAME, ); @@ -56,19 +58,19 @@ sub parse_args { ########################################################################## -# Returns short-hostname given an IP +# Returns short-hostname given an IP ########################################################################## sub getshorthost { my $ip = shift; my $host = xCAT::NetworkUtils->gethostname($ip); - if ( $host and !$! ) { + if ($host and !$!) { ############################## # Get short-hostname ############################## - if ( $host =~ /([^\.]+)\./ ) { - return($1); + if ($host =~ /([^\.]+)\./) { + return ($1); } } ################################## @@ -83,12 +85,12 @@ sub getshorthost { ########################################################################## sub enumerate { - my $request = shift; - my $hash = shift; - my $exp = shift; - my $hwtype = (); - my $server ; - my @values = (); + my $request = shift; + my $hash = shift; + my $exp = shift; + my $hwtype = (); + my $server; + my @values = (); my $cageid; my $server; my $prof; @@ -101,131 +103,141 @@ sub enumerate { my @output; my $ips; my $fsp; - my $model ; + my $model; my $serial; - my $side; + my $side; my $ips; - my $line; - - foreach my $cec_bpa ( keys %$hash) - { + my $line; + + foreach my $cec_bpa (keys %$hash) + { my $node_hash = $hash->{$cec_bpa}; - for my $node_name ( keys %$node_hash) + for my $node_name (keys %$node_hash) { my $d = $node_hash->{$node_name}; - if($$d[4] =~ /^lpar$/ || $$d[4] =~ /^bpa$/ || $$d[4] =~ /^frame$/ ) { - $data = "please check the $node_name; the noderange of rscan couldn't be LPAR or BPA, or frame. "; - #push @output, [$node_name,$data,$Rc]; + if ($$d[4] =~ /^lpar$/ || $$d[4] =~ /^bpa$/ || $$d[4] =~ /^frame$/) { + $data = "please check the $node_name; the noderange of rscan couldn't be LPAR or BPA, or frame. "; + + #push @output, [$node_name,$data,$Rc]; push @values, $data; next; - } - my $stat = xCAT::FSPUtils::fsp_api_action ($request, $node_name, $d, "query_connection"); - my $Rc = @$stat[2]; - my $data = @$stat[1]; - + } + my $stat = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "query_connection"); + my $Rc = @$stat[2]; + my $data = @$stat[1]; + ################################## # Output error ################################## - if ( $Rc != SUCCESS ) { - #push @output, [$node_name,$data,$Rc]; + if ($Rc != SUCCESS) { + + #push @output, [$node_name,$data,$Rc]; push @values, $data; next; } my @data_a = split("\n", $data); - foreach $line(@data_a) { - if($line !~ "Connected" && $line !~ "LINE UP" ) { + foreach $line (@data_a) { + if ($line !~ "Connected" && $line !~ "LINE UP") { next; - } - + } + ######################################### # GET CEC's information ######################################### - #$data =~ /state=([\w\s]+),\(type=([\w-]+)\),\(serial-number=([\w]+)\),\(machinetype-model=([\w-]+)\),sp=([\w]+),\(ip-address=([\w.]+),([\w.]+)\)/ ; - $line =~ /state=([\w\s]+), type=([\w-]+), MTMS=([\w-]+)\*([\w-]+), sp=([\w=]+), slot=([\w]+), ipadd=([\w.]+), alt_ipadd=([\w.]+)/ ; - #print "parsing: $1,$2,$3,$4,$5,$6,$7,$8\n"; - - $fsp=$node_name; - $model = $3; - $serial = $4; - $side = $6; - $server = $fsp; - $fname = $fsp; - my $ip = $7; + #$data =~ /state=([\w\s]+),\(type=([\w-]+)\),\(serial-number=([\w]+)\),\(machinetype-model=([\w-]+)\),sp=([\w]+),\(ip-address=([\w.]+),([\w.]+)\)/ ; + $line =~ /state=([\w\s]+), type=([\w-]+), MTMS=([\w-]+)\*([\w-]+), sp=([\w=]+), slot=([\w]+), ipadd=([\w.]+), alt_ipadd=([\w.]+)/; + + #print "parsing: $1,$2,$3,$4,$5,$6,$7,$8\n"; + + $fsp = $node_name; + $model = $3; + $serial = $4; + $side = $6; + $server = $fsp; + $fname = $fsp; + my $ip = $7; my $ip_s = $8; - if(! defined( $ips)) { - if( $ip_s =~ /unavailable/ ) { - $ips ="$ip"; - } else { - $ips ="$ip;$ip_s"; - } + if (!defined($ips)) { + + if ($ip_s =~ /unavailable/) { + $ips = "$ip"; + } else { + $ips = "$ip;$ip_s"; + } } else { - if( $ip_s =~ /unavailable/ ) { - $ips .=";$ip"; - } else { - $ips .=";$ip;$ip_s"; - } + if ($ip_s =~ /unavailable/) { + $ips .= ";$ip"; + } else { + $ips .= ";$ip;$ip_s"; + } } } - if(!defined($fsp)) { - my $msg = "please check if the $node_name is coneected to the hardware server"; + if (!defined($fsp)) { + my $msg = "please check if the $node_name is coneected to the hardware server"; push @values, $msg; next; } - if($$d[4] =~ /^cec$/) { - $side=""; + if ($$d[4] =~ /^cec$/) { + $side = ""; } - push @values, join( ",", - $$d[4],$node_name,$cageid,$model,$serial,$side, $server,$prof,$fname); + push @values, join(",", + $$d[4], $node_name, $cageid, $model, $serial, $side, $server, $prof, $fname); + #$$d[4],$node_name,$cageid,$model,$serial,$side, $server,$prof,$fname, $ips, $$d[4]); - # $$d[4],$node_name,$cageid,$model,$serial,$side, $server,$prof,$fname, $7); + # $$d[4],$node_name,$cageid,$model,$serial,$side, $server,$prof,$fname, $7); # "fsp",$node_name,$cageid,$model,$serial,$side, $server,$prof,$fname, $7); #"fsp",$fsp,$cageid,$model,$serial,$side,$server,$prof,$fname,$ips ); - - ##################################### - # Enumerate LPARs + ##################################### - $stat = xCAT::FSPUtils::fsp_api_action ($request, $node_name, $d, "get_lpar_info"); - $Rc = @$stat[2]; - $data = @$stat[1]; - + # Enumerate LPARs + ##################################### + $stat = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "get_lpar_info"); + $Rc = @$stat[2]; + $data = @$stat[1]; + ################################## # Output error ################################## - if ( $Rc != SUCCESS ) { - #push @output, [$node_name,$data,$Rc]; + if ($Rc != SUCCESS) { + + #push @output, [$node_name,$data,$Rc]; push @values, $data; next; } - my @list = split(/\n/,$data); - #print "list\n"; - #print Dumper(\@list); - foreach my $lpar (@list) { - $lpar =~ /lparname:\s+([\w\-]+),\s+lparid:\s+(\d+),\s+state:/; - my $name = $1; - my $lparid = $2; - my $prof = ""; # No profile for Power 775 - my $server = $fsp; - my $ips = ""; - my $port = ""; -# $name =~ s/\-//g; -# $name =~ tr/A-Z/a-z/; - - ##################################### - # Save LPAR information - ##################################### - push @values, join( ",", - "lpar",$name,$lparid,$model,$serial,$port,$server,$prof,$fsp ); - #"lpar",$name,$lparid,$model,$serial,$port,$server,$prof,$fsp,$ips,"lpar" ); - - } + my @list = split(/\n/, $data); - } - #return(\@values); + #print "list\n"; + #print Dumper(\@list); + foreach my $lpar (@list) { + $lpar =~ /lparname:\s+([\w\-]+),\s+lparid:\s+(\d+),\s+state:/; + my $name = $1; + my $lparid = $2; + my $prof = ""; # No profile for Power 775 + my $server = $fsp; + my $ips = ""; + my $port = ""; + + # $name =~ s/\-//g; + # $name =~ tr/A-Z/a-z/; + + ##################################### + # Save LPAR information + ##################################### + push @values, join(",", +"lpar", $name, $lparid, $model, $serial, $port, $server, $prof, $fsp); + + #"lpar",$name,$lparid,$model,$serial,$port,$server,$prof,$fsp,$ips,"lpar" ); + + } + + } + + #return(\@values); } - - return( \@values ); + + return (\@values); } @@ -235,23 +247,23 @@ sub enumerate { ########################################################################## sub format_output { - my $request = shift; - my $exp = shift; - my $values = shift; - my $opt = $request->{opt}; - my %output = (); - my $hwtype = "fsp"; + my $request = shift; + my $exp = shift; + my $values = shift; + my $opt = $request->{opt}; + my %output = (); + my $hwtype = "fsp"; my $max_length = 0; my $result; - + #print "In format output\n"; - #print Dumper($request); - #print Dumper($exp); - #print Dumper($values); + #print Dumper($request); + #print Dumper($exp); + #print Dumper($values); ########################################### # -w flag for write to xCat database ########################################### - if ( exists( $opt->{w} )) { + if (exists($opt->{w})) { my $server = @$exp[3]; my $uid = @$exp[4]; my $pw = @$exp[5]; @@ -259,22 +271,24 @@ sub format_output { ####################################### # Strip errors for results ####################################### - my @val = grep( !/^#.*: ERROR /, @$values ); + my @val = grep(!/^#.*: ERROR /, @$values); + #xCAT::PPCdb::add_ppc( $hwtype, \@val ); - $values = xCAT::PPCdb::update_lpar( $hwtype, \@val, "write"); + $values = xCAT::PPCdb::update_lpar($hwtype, \@val, "write"); } ########################################### # -u flag for write to xCat database ########################################### - if ( exists( $opt->{u} )) { + if (exists($opt->{u})) { ####################################### # Strip errors for results ####################################### - my @val = grep( !/^#.*: ERROR /, @$values ); + my @val = grep(!/^#.*: ERROR /, @$values); + #$values = xCAT::PPCdb::update_ppc( $hwtype, \@val ); - $values = xCAT::PPCdb::update_lpar( $hwtype, \@val ); - if ( exists( $opt->{x} ) or exists( $opt->{z} )) + $values = xCAT::PPCdb::update_lpar($hwtype, \@val); + if (exists($opt->{x}) or exists($opt->{z})) { unshift @$values, "hmc"; } @@ -283,79 +297,79 @@ sub format_output { ########################################### # -x flag for xml format ########################################### - if ( exists( $opt->{x} )) { - $result .= format_xml( $hwtype, $values ); + if (exists($opt->{x})) { + $result .= format_xml($hwtype, $values); } ########################################### # -z flag for stanza format ########################################### - elsif ( exists( $opt->{z} )) { - $result .= format_stanza( $hwtype, $values ); + elsif (exists($opt->{z})) { + $result .= format_stanza($hwtype, $values); } else { - $result = sprintf( "#Updated following nodes:\n") if ( exists( $opt->{u})); + $result = sprintf("#Updated following nodes:\n") if (exists($opt->{u})); ####################################### # Get longest name for formatting ####################################### - foreach ( @$values ) { + foreach (@$values) { ################################### # Skip error message ################################### - if ( /^#.*: ERROR / ) { + if (/^#.*: ERROR /) { next; } /[^\,]+,([^\,]+),/; - my $length = length( $1 ); + my $length = length($1); $max_length = ($length > $max_length) ? $length : $max_length; } - my $format = sprintf( "%%-%ds", ($max_length + 2 )); + my $format = sprintf("%%-%ds", ($max_length + 2)); $header[1][1] = $format; ####################################### # Add header ####################################### - foreach ( @header ) { - $result .= sprintf( @$_[1], @$_[0] ); + foreach (@header) { + $result .= sprintf(@$_[1], @$_[0]); } ####################################### # Add node information ####################################### my @errmsg; - foreach ( @$values ) { + foreach (@$values) { my @data = split /,/; - my $i = 0; + my $i = 0; ################################### # Save error messages for last ################################### - if ( /^#.*: ERROR / ) { + if (/^#.*: ERROR /) { push @errmsg, $_; next; } - foreach ( @header ) { - my $d = $data[$i++]; + foreach (@header) { + my $d = $data[ $i++ ]; ############################### - # Use IPs instead of - # hardware control address + # Use IPs instead of + # hardware control address ############################### - if ( @$_[0] eq "address" ) { - if ( $data[0] !~ /^(hmc|ivm)$/ ) { - $d = $data[9]; - } + if (@$_[0] eq "address") { + if ($data[0] !~ /^(hmc|ivm)$/) { + $d = $data[9]; + } } - $result .= sprintf( @$_[1], $d ); + $result .= sprintf(@$_[1], $d); } } ####################################### - # Add any error messages + # Add any error messages ####################################### - foreach ( @errmsg ) { - $result.= "\n$_"; + foreach (@errmsg) { + $result .= "\n$_"; } } $output{data} = [$result]; - return( [\%output] ); + return ([ \%output ]); } @@ -367,23 +381,23 @@ sub format_stanza { my $hwtype = shift; my $values = shift; - + my $result; ##################################### - # Skip hardware control point + # Skip hardware control point ##################################### shift(@$values); - foreach ( sort @$values ) { + foreach (sort @$values) { my @data = split /,/; my $type = $data[0]; - my $i = 0; + my $i = 0; ################################# - # Skip error message + # Skip error message ################################# - if ( /^#.*: ERROR / ) { + if (/^#.*: ERROR /) { next; } ################################# @@ -395,35 +409,36 @@ sub format_stanza { # Add each attribute ################################# my $mtm = undef; - foreach ( @attribs ) { - my $d = $data[$i++]; + foreach (@attribs) { + my $d = $data[ $i++ ]; - if ( /^node$/ ) { + if (/^node$/) { next; - } elsif ( /^nodetype$/ ) { + } elsif (/^nodetype$/) { $d = $globalnodetype{$type}; - } elsif ( /^hwtype$/ ) { + } elsif (/^hwtype$/) { $d = $globalhwtype{$type}; - } elsif ( /^groups$/ ) { + } elsif (/^groups$/) { next; + #$d = "$type,all"; - } elsif ( /^mgt$/ ) { + } elsif (/^mgt$/) { $d = $hwtype; - } elsif ( /^cons$/ ) { - if ( $type eq "lpar" ) { + } elsif (/^cons$/) { + if ($type eq "lpar") { $d = $hwtype; } else { $d = undef; } - - } elsif ( /^(mtm|serial)$/ ) { - if ( $type eq "lpar" ) { - $d = undef; + + } elsif (/^(mtm|serial)$/) { + if ($type eq "lpar") { + $d = undef; } elsif (/^mtm$/) { $mtm = $d; - } + } } elsif (/^side$/) { - unless ( $type =~ /^fsp|bpa$/ ) { + unless ($type =~ /^fsp|bpa$/) { next; } } @@ -434,12 +449,12 @@ sub format_stanza { my $tmp_pre = xCAT::data::ibmhwtypes::parse_group($mtm); if (defined($tmp_pre)) { $tmp_groups .= ",$tmp_pre"; - } + } } $result .= "\tgroups=$tmp_groups\n"; } - return( $result ); + return ($result); } @@ -453,60 +468,61 @@ sub format_xml { my $xml; ##################################### - # Skip hardware control point + # Skip hardware control point ##################################### #shift(@$values); ##################################### # Create XML formatted attributes ##################################### - foreach ( @$values ) { + foreach (@$values) { my @data = split /,/; my $type = $data[0]; - my $i = 0; + my $i = 0; ################################# # Skip error message ################################# - if ( /^#.*: ERROR / ) { + if (/^#.*: ERROR /) { next; } ################################# # Initialize hash reference ################################# my $href = { - Node => { } + Node => {} }; ################################# - # Add each attribute + # Add each attribute ################################# my $mtm = undef; - foreach ( @attribs ) { - my $d = $data[$i++]; + foreach (@attribs) { + my $d = $data[ $i++ ]; - if ( /^nodetype$/ ) { + if (/^nodetype$/) { $d = $globalnodetype{$type}; - } elsif ( /^hwtype$/ ) { + } elsif (/^hwtype$/) { $d = $globalhwtype{$type}; - } elsif ( /^groups$/ ) { + } elsif (/^groups$/) { next; + #$d = "$type,all"; - } elsif ( /^mgt$/ ) { + } elsif (/^mgt$/) { $d = $hwtype; - } elsif ( /^cons$/ ) { - if ( $type eq "lpar" ) { + } elsif (/^cons$/) { + if ($type eq "lpar") { $d = $hwtype; } else { $d = undef; } - } elsif ( /^(mtm|serial)$/ ) { - if ( $type eq "lpar" ) { + } elsif (/^(mtm|serial)$/) { + if ($type eq "lpar") { $d = undef; } elsif (/^mtm$/) { $mtm = $d; } } elsif (/^side$/) { - unless ( $type =~ /^fsp|bpa$/ ) { + unless ($type =~ /^fsp|bpa$/) { next; } } @@ -517,20 +533,20 @@ sub format_xml { my $tmp_pre = xCAT::data::ibmhwtypes::parse_group($mtm); if (defined($tmp_pre)) { $tmp_groups .= ",$tmp_pre"; - } + } } - $href->{Node}->{groups}=$tmp_groups; + $href->{Node}->{groups} = $tmp_groups; #print Dumper($href); ################################# # XML encoding ################################# - $xml.= XMLout($href, - NoAttr => 1, - KeyAttr => [], - RootName => undef ); + $xml .= XMLout($href, + NoAttr => 1, + KeyAttr => [], + RootName => undef); } - return( $xml ); + return ($xml); } @@ -541,7 +557,7 @@ sub format_xml { sub rscan { my $request = shift; - my $hash = shift; + my $hash = shift; my $exp = shift; my $args = $request->{arg}; my $server = @$exp[3]; @@ -550,22 +566,23 @@ sub rscan { #print Dumper($request); #print Dumper($hash); #print Dumper($exp); - + ################################### # Enumerate all the hardware ################################### - my $values = enumerate($request, $hash ); + my $values = enumerate($request, $hash); + #print "In rscan:\n"; #print Dumper($values); - if ( ref($values) ne 'ARRAY' ) { - return( [[$server,$values,1]] ); + if (ref($values) ne 'ARRAY') { + return ([ [ $server, $values, 1 ] ]); } ################################### - # Success + # Success ################################### - my $result = format_output( $request, $exp, $values ); + my $result = format_output($request, $exp, $values); unshift @$result, "FORMATDATA6sK4ci"; - return( $result ); + return ($result); } diff --git a/perl-xCAT/xCAT/FSPvitals.pm b/perl-xCAT/xCAT/FSPvitals.pm index 44549fc80..3f31bf31c 100644 --- a/perl-xCAT/xCAT/FSPvitals.pm +++ b/perl-xCAT/xCAT/FSPvitals.pm @@ -8,6 +8,7 @@ use xCAT::FSPpower; use xCAT::Usage; use xCAT::PPCvitals; use xCAT::FSPUtils; + #use Data::Dumper; @@ -27,6 +28,7 @@ sub enumerate_volt { my $d = shift; my $mtms = @$d[2]; + #my $volt = xCAT::PPCcli::lshwinfo( $exp, "frame", $mtms ); #my $Rc = shift(@$volt); my $value = "Not supported by FSPvitals"; @@ -37,16 +39,16 @@ sub enumerate_volt { # return( [RC_ERROR, $value] ); #} #################################### - # Success - return voltages + # Success - return voltages #################################### - return( [SUCCESS, $value] ); + return ([ SUCCESS, $value ]); } ########################################################################## -# Returns cage temperatures +# Returns cage temperatures ########################################################################## sub enumerate_temp { @@ -60,62 +62,63 @@ sub enumerate_temp { ########################################################################## sub enumerate_lcds { - my $request= shift; - my $name= shift; - my $d = shift; - my $action = shift; - my $only_lcds = shift; - my $prefix = "Current LCD:"; + my $request = shift; + my $name = shift; + my $d = shift; + my $action = shift; + my $only_lcds = shift; + my $prefix = "Current LCD:"; my $power_status_prefix = "Current Power Status:"; my $Rc; my @refcode; my $c = 0; - - my $values = xCAT::FSPUtils::fsp_api_action ($request, $name, $d, $action); - $Rc = @$values[2]; + + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action); + $Rc = @$values[2]; my $data = @$values[1]; - my $t_n = @$values[0]; - if( $Rc != 0 ) { - my @names = split(/,/, $t_n); - my @t_data = split(/\n/, $data); + my $t_n = @$values[0]; + if ($Rc != 0) { + my @names = split(/,/, $t_n); + my @t_data = split(/\n/, $data); foreach my $n (@names) { - if( $data =~ /$n/ ) { + if ($data =~ /$n/) { chomp $t_data[$c]; + #push @refcode,[$n, "$prefix $t_data[$c]", $Rc]; - if($t_data[$c] =~ /Error/ ) { - if( $only_lcds == 0) { - push @refcode,[$n, "$power_status_prefix $t_data[$c]", $Rc]; + if ($t_data[$c] =~ /Error/) { + if ($only_lcds == 0) { + push @refcode, [ $n, "$power_status_prefix $t_data[$c]", $Rc ]; } - push @refcode,[$n, "$prefix $t_data[$c]", $Rc]; + push @refcode, [ $n, "$prefix $t_data[$c]", $Rc ]; } else { - if( $only_lcds == 0) { + if ($only_lcds == 0) { # get power status - if( $data =~ /1\|/) { - push @refcode, [$n, "$power_status_prefix on", $Rc] ; + if ($data =~ /1\|/) { + push @refcode, [ $n, "$power_status_prefix on", $Rc ]; } else { - push @refcode, [$n, "$power_status_prefix off", $Rc]; + push @refcode, [ $n, "$power_status_prefix off", $Rc ]; } } # get lcd value - if( $t_data[$c] =~ /1\|(\w[\w\s]*)/) { - push @refcode, [$n, "$prefix $1", $Rc] ; + if ($t_data[$c] =~ /1\|(\w[\w\s]*)/) { + push @refcode, [ $n, "$prefix $1", $Rc ]; } else { - push @refcode, [$n, "$prefix blank", $Rc]; + push @refcode, [ $n, "$prefix blank", $Rc ]; } - } + } $c++; } else { - push @refcode, [$n, "$prefix $data", $Rc]; - if( $only_lcds == 0) { - push @refcode, [$n, "$power_status_prefix $data", $Rc]; + push @refcode, [ $n, "$prefix $data", $Rc ]; + if ($only_lcds == 0) { + push @refcode, [ $n, "$power_status_prefix $data", $Rc ]; } } } } else { - my @array = split(/\n/, $data); - foreach my $a (@array) { + my @array = split(/\n/, $data); + foreach my $a (@array) { if ($a !~ /:\s?[^\s]*\s?[0|1]/) { next; } @@ -125,20 +128,21 @@ sub enumerate_lcds { ## it will not parse the power status if only lcds. # $only_lcds = 0, it will get the power status # $only_lcds = 0, not get the power status. - if( $only_lcds == 0) { + if ($only_lcds == 0) { + # get power status - if( $data =~ /1\|/) { - push @refcode, [$name, "$power_status_prefix on", $Rc] ; + if ($data =~ /1\|/) { + push @refcode, [ $name, "$power_status_prefix on", $Rc ]; } else { - push @refcode, [$name, "$power_status_prefix off", $Rc]; + push @refcode, [ $name, "$power_status_prefix off", $Rc ]; } } # get lcd value - if( $data =~ /1\|(\w[\w\s]*)/) { - push @refcode, [$name, "$prefix $1", $Rc] ; + if ($data =~ /1\|(\w[\w\s]*)/) { + push @refcode, [ $name, "$prefix $1", $Rc ]; } else { - push @refcode, [$name, "$prefix blank", $Rc]; + push @refcode, [ $name, "$prefix blank", $Rc ]; } } } @@ -146,43 +150,44 @@ sub enumerate_lcds { } ########################################################################## -# Returns rack environmentals +# Returns rack environmentals ########################################################################## sub enumerate_rackenv { - my $request= shift; - my $name= shift; - my $d = shift; + my $request = shift; + my $name = shift; + my $d = shift; + #my $mtms = @$d[2]; my $Rc; my $attr; my $value; my %outhash = (); - my $action = "get_rack_env"; - - my $values = xCAT::FSPUtils::fsp_api_action ($request, $name, $d, $action); - $Rc = @$values[2]; + my $action = "get_rack_env"; + + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action); + $Rc = @$values[2]; my $data = @$values[1]; - if ( $Rc != 0 ) { - return( [$Rc,@$values[1]] ); + if ($Rc != 0) { + return ([ $Rc, @$values[1] ]); } - + my $i = 0; - my @t = split(/\n/, $data); - foreach my $td ( @t ) { - my ($attr,$value) = split (/:/, $td); - $outhash{ $attr } = $value; - $outhash{$i}{ $attr } = $value; - $i++; + my @t = split(/\n/, $data); + foreach my $td (@t) { + my ($attr, $value) = split(/:/, $td); + $outhash{$attr} = $value; + $outhash{$i}{$attr} = $value; + $i++; } - - return ( [0,\%outhash] ); + + return ([ 0, \%outhash ]); } ########################################################################## -# Returns voltages/currents +# Returns voltages/currents ########################################################################## sub voltage { @@ -192,7 +197,7 @@ sub voltage { my $hwtype = @$exp[2]; my @result = (); my $text = "Frame Voltages: "; - my @prefix = ( + my @prefix = ( "Frame Voltage (Vab): %sV", "Frame Voltage (Vbc): %sV", "Frame Voltage (Vca): %sV", @@ -201,40 +206,40 @@ sub voltage { "Frame Current (Ic): %sA", ); - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { - - ################################# + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { + + ################################# # Voltages available in frame - ################################# + ################################# #if ( @$d[4] ne "bpa" && @$d[4] ne "frame") { # push @result, [$name,"$text Only available for BPA/Frame",1]; # next; #} - #my $volt = enumerate_volt( $exp, $d ); - #my $Rc = shift(@$volt); + #my $volt = enumerate_volt( $exp, $d ); + #my $Rc = shift(@$volt); - ################################# - # Output error ################################# - #if ( $Rc != SUCCESS ) { - # push @result, [$name,"$text @$volt[0]",$Rc]; - # next; - #} + # Output error + ################################# + #if ( $Rc != SUCCESS ) { + # push @result, [$name,"$text @$volt[0]",$Rc]; + # next; + #} ################################# # Output value ################################# - #my @values = split /,/, @$volt[0]; - #my $i = 0; + #my @values = split /,/, @$volt[0]; + #my $i = 0; - #foreach ( @prefix ) { - # my $value = sprintf($_, $values[$i++]); - # push @result, [$name,$value,$Rc]; - #} - push @result, [$name,"$text: Not supported in Direct FSP Management", 1]; + #foreach ( @prefix ) { + # my $value = sprintf($_, $values[$i++]); + # push @result, [$name,$value,$Rc]; + #} + push @result, [ $name, "$text: Not supported in Direct FSP Management", 1 ]; } } - return( \@result ); + return (\@result); } @@ -251,69 +256,69 @@ sub temp { my %frame = (); my $prefix = "System Temperature:"; - ######################################### + ######################################### # Group by frame - ######################################### - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { + ######################################### + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { my $mtms = @$d[5]; - - push @result, [$name,"System Temperature Not support in Direct FSP Management",-1]; + + push @result, [ $name, "System Temperature Not support in Direct FSP Management", -1 ]; ################################# - # No frame commands for IVM - ################################# - if ( $hwtype eq "ivm" ) { - push @result, [$name,"$prefix Not available (No BPA)",0]; + # No frame commands for IVM + ################################# + if ($hwtype eq "ivm") { + push @result, [ $name, "$prefix Not available (No BPA)", 0 ]; next; } - ################################# - # Temperatures not available - ################################# - if ( @$d[4] !~ /^(fsp|lpar|cec)$/ ) { + ################################# + # Temperatures not available + ################################# + if (@$d[4] !~ /^(fsp|lpar|cec)$/) { my $text = "$prefix Only available for CEC/LPAR"; - push @result, [$name,$text,0]; - next; - } - ################################# - # Error - No frame - ################################# - if ( $mtms eq "0" ) { - push @result, [$name,"$prefix Not available (No BPA)",0]; + push @result, [ $name, $text, 0 ]; next; } ################################# - # Save node - ################################# + # Error - No frame + ################################# + if ($mtms eq "0") { + push @result, [ $name, "$prefix Not available (No BPA)", 0 ]; + next; + } + ################################# + # Save node + ################################# $frame{$mtms}{$name} = $d; } } - return( \@result ); + return (\@result); - while (my ($mtms,$h) = each(%frame) ) { - ################################# - # Get temperatures this frame - ################################# - my $temp = enumerate_temp( $exp, $mtms ); - my $Rc = shift(@$temp); + while (my ($mtms, $h) = each(%frame)) { + ################################# + # Get temperatures this frame + ################################# + my $temp = enumerate_temp($exp, $mtms); + my $Rc = shift(@$temp); my $data = @$temp[0]; - while (my ($name,$d) = each(%$h) ) { + while (my ($name, $d) = each(%$h)) { my $mtms = @$d[2]; ############################# # Output error ############################# - if ( $Rc != SUCCESS ) { - push @result, [$name,"$prefix $data",$Rc]; + if ($Rc != SUCCESS) { + push @result, [ $name, "$prefix $data", $Rc ]; next; } ############################# - # CEC not in frame + # CEC not in frame ############################# - if ( !exists( $data->{$mtms} )) { - push @result, [$name,"$prefix CEC '$mtms' not found",1]; + if (!exists($data->{$mtms})) { + push @result, [ $name, "$prefix CEC '$mtms' not found", 1 ]; next; } ############################# @@ -322,10 +327,10 @@ sub temp { my $cel = $data->{$mtms}; my $fah = ($cel * 1.8) + 32; my $value = "$prefix $cel C ($fah F)"; - push @result, [$name,$value,$Rc]; + push @result, [ $name, $value, $Rc ]; } } - return( \@result ); + return (\@result); } ########################################################################## @@ -339,47 +344,48 @@ sub rackenv { my %frame = (); my $prefix = "Rack Environmentals:"; - ######################################### + ######################################### # Group by frame - ######################################### - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { + ######################################### + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { my $mtms = @$d[5]; - - ################################# - # Temperatures not available - ################################# - if ( @$d[4] !~ /^(bpa|frame)$/ ) { + + ################################# + # Temperatures not available + ################################# + if (@$d[4] !~ /^(bpa|frame)$/) { my $text = "$prefix Only available for BPA/Frame"; - push @result, [$name,$text,0]; + push @result, [ $name, $text, 0 ]; next; } - + my $action = "get_rack_env"; - my $values = xCAT::FSPUtils::fsp_api_action ($request, $name, $d, $action); - my $Rc = @$values[2]; + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, $action); + my $Rc = @$values[2]; my $data = @$values[1]; - if ( $Rc != 0 ) { - push @result, [$name,$data, $Rc]; + if ($Rc != 0) { + push @result, [ $name, $data, $Rc ]; next; } my @t = split(/\n/, $data); - foreach my $td ( @t ) { - push @result, [$name,$td, $Rc]; - if ( !exists($request->{verbose}) ) { + foreach my $td (@t) { + push @result, [ $name, $td, $Rc ]; + if (!exists($request->{verbose})) { + #if( $td =~ /^Rack altitude in meters/ ) { - if( $td =~ /^BPA-B total output in watts/ ) { + if ($td =~ /^BPA-B total output in watts/) { last; } - } + } } } } - return( \@result ); + return (\@result); } @@ -388,19 +394,19 @@ sub rackenv { ########################################################################## -# Returns system power status (on or off) +# Returns system power status (on or off) # This subroutine will not be used in DFM # And the power status will be returned with lcds ########################################################################## sub power { - return( xCAT::FSPpower::state(@_,"Current Power Status: ",1)); + return (xCAT::FSPpower::state(@_, "Current Power Status: ", 1)); } ########################################################################## -# Returns system state +# Returns system state ########################################################################## sub state { - return( xCAT::FSPpower::state(@_,"System State: ")); + return (xCAT::FSPpower::state(@_, "System State: ")); } ########################################################################### # Returns system LCD status and the power status @@ -416,60 +422,61 @@ sub lcds { my $action; my $type; my $only_lcds; - if( $request->{method} =~ /^lcds$/ ) { + + if ($request->{method} =~ /^lcds$/) { $only_lcds = 1; } - while (my ($mtms,$h) = each(%$hash) ) { - while(my ($name, $d) = each(%$h) ){ - $newids .="$$d[0],"; - $newnames .="$name,"; + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { + $newids .= "$$d[0],"; + $newnames .= "$name,"; $newd = $d; - if( defined( $type) && $type ne $$d[4] ) { - push @$result, [$name, "$name\'s type is $$d[4]. Please get the lcds for $type and $$d[4] seperately", -1 ]; + if (defined($type) && $type ne $$d[4]) { + push @$result, [ $name, "$name\'s type is $$d[4]. Please get the lcds for $type and $$d[4] seperately", -1 ]; return $result; - } + } $type = $$d[4]; - } + } } - - if( $type eq "lpar" ) { + + if ($type eq "lpar") { $action = "query_lcds"; } elsif ($type eq "blade") { - $action = "pblade_query_lcds"; + $action = "pblade_query_lcds"; } else { $action = "cec_query_lcds"; - } - + } + $$newd[0] = $newids; $result = enumerate_lcds($request, $newnames, $newd, $action, $only_lcds); - + return $result; } sub lcds_orig { - my $request = shift; - my $hash = shift; - my $exp = shift; - my $hwtype = @$exp[2]; - my @result = (); - my $text = "Current LCD:"; - my $prefix = "Current LCD%d: %s"; - my $rcode = undef; + my $request = shift; + my $hash = shift; + my $exp = shift; + my $hwtype = @$exp[2]; + my @result = (); + my $text = "Current LCD:"; + my $prefix = "Current LCD%d: %s"; + my $rcode = undef; my $refcodes = undef; - my $Rc = undef; - my $num = undef; - my $value = undef; + my $Rc = undef; + my $num = undef; + my $value = undef; - while (my ($mtms,$h) = each(%$hash) ) { - while(my ($name, $d) = each(%$h) ){ + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { $refcodes = enumerate_lcds($request, $name, $d); $num = 1; - foreach $rcode (@$refcodes){ + foreach $rcode (@$refcodes) { $Rc = shift(@$rcode); $value = sprintf($prefix, $num, @$rcode[0]); - push @result, [$name, $value, $Rc]; + push @result, [ $name, $value, $Rc ]; $num = $num + 1; - } + } } } return \@result; @@ -480,14 +487,14 @@ sub lcds_orig { ########################################################################## sub all { - my @values = ( - @{rackenv(@_)}, - @{state(@_)}, - @{lcds(@_)}, - ); + my @values = ( + @{ rackenv(@_) }, + @{ state(@_) }, + @{ lcds(@_) }, + ); - my @sorted_values = sort {$a->[0] cmp $b->[0]} @values; - return( \@sorted_values ); + my @sorted_values = sort { $a->[0] cmp $b->[0] } @values; + return (\@sorted_values); } diff --git a/perl-xCAT/xCAT/FSPvm.pm b/perl-xCAT/xCAT/FSPvm.pm index 16d310bac..c935b488b 100644 --- a/perl-xCAT/xCAT/FSPvm.pm +++ b/perl-xCAT/xCAT/FSPvm.pm @@ -2,7 +2,7 @@ BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } @@ -24,8 +24,8 @@ use xCAT::MsgUtils qw(verbose_message); my %method = ( mkvm => \&mkvm_parse_args, lsvm => \&lsvm_parse_args, - rmvm => \&rmvm_parse_args, - chvm => \&chvm_parse_args + rmvm => \&rmvm_parse_args, + chvm => \&chvm_parse_args ); @@ -38,56 +38,58 @@ sub parse_args { my $cmd = $request->{command}; ############################### - # Invoke correct parse_args + # Invoke correct parse_args ############################### - my $result = $method{$cmd}( $request ); - return( $result ); + my $result = $method{$cmd}($request); + return ($result); } ########################################################################## # Parse the chvm command line for options and operands ########################################################################## -my @query_array = (); +my @query_array = (); my %param_list_map = ( - 'vmcpus' => 'part_get_lpar_processing', - 'vmmemory' => 'part_get_lpar_memory', - 'add_physlots' => 'part_get_all_io_bus_info', - 'del_physlots' => 'part_get_all_io_bus_info', - 'add_vmnics' => 'part_get_all_vio_info', + 'vmcpus' => 'part_get_lpar_processing', + 'vmmemory' => 'part_get_lpar_memory', + 'add_physlots' => 'part_get_all_io_bus_info', + 'del_physlots' => 'part_get_all_io_bus_info', + 'add_vmnics' => 'part_get_all_vio_info', 'add_vmstorage' => 'part_get_all_vio_info', - 'del_vadapter' => 'part_get_all_vio_info' + 'del_vadapter' => 'part_get_all_vio_info' ); sub chvm_parse_extra_options { - my $args = shift; - my $opt = shift; + my $args = shift; + my $opt = shift; + # Partition used attributes # my @support_ops = qw(vmcpus vmmemory add_physlots vmothersetting add_vmstorage add_vmnics del_vadapter del_physlots); - if (ref($args) ne 'ARRAY') { - return "$args"; - } + if (ref($args) ne 'ARRAY') { + return "$args"; + } my %tmp_hash = (); - foreach (@$args) { - my ($cmd, $value) = split (/\=/, $_); - if (!defined($value)) { - return "no value specified"; - } - if ($cmd =~ /^lparname$/) { - if ($value ne '*' && $value !~ /^[a-zA-Z0-9-_]+$/) { - return "'$value' invalid"; - } - my $len = rindex $value."\$", "\$"; + foreach (@$args) { + my ($cmd, $value) = split(/\=/, $_); + if (!defined($value)) { + return "no value specified"; + } + if ($cmd =~ /^lparname$/) { + if ($value ne '*' && $value !~ /^[a-zA-Z0-9-_]+$/) { + return "'$value' invalid"; + } + my $len = rindex $value . "\$", "\$"; if ($len > '47') { return "'$value' is too long, max 47 characters"; } -# } elsif ($cmd =~ /^huge_page$/) { -# if ($value !~ /^\d+\/\d+\/\d+$/) { -# return "'$value' invalid"; -# } + + # } elsif ($cmd =~ /^huge_page$/) { + # if ($value !~ /^\d+\/\d+\/\d+$/) { + # return "'$value' invalid"; + # } } elsif (grep(/^$cmd$/, @support_ops)) { if (exists($param_list_map{$cmd})) { - $tmp_hash{$param_list_map{$cmd}} = 1; + $tmp_hash{ $param_list_map{$cmd} } = 1; } if (exists($opt->{p775})) { return "'$cmd' doesn't work for Power 775 machines."; @@ -96,7 +98,7 @@ sub chvm_parse_extra_options { return "Invalid param '$value', only one slot id can be specified"; } } elsif ($cmd eq "del_physlots") { - my @tmp_array = split ",",$value; + my @tmp_array = split ",", $value; foreach (@tmp_array) { unless (/(0x\w{8})/) { return "'$_' is invalid"; @@ -118,7 +120,7 @@ sub chvm_parse_extra_options { return "'$value' is invalid, must be numbers"; } else { my @array = (); - for (1..$value) { + for (1 .. $value) { push @array, 0; } $value = \@array; @@ -143,7 +145,7 @@ sub chvm_parse_extra_options { my ($mmin, $mcur, $mmax); if ($2 eq "G" or $2 eq '') { $mmin = $1 * 1024; - } + } if ($4 eq "G" or $4 eq '') { $mcur = $3 * 1024; } @@ -157,7 +159,7 @@ sub chvm_parse_extra_options { return "'$value' is invalid"; } } elsif ($cmd eq "add_physlots") { - my @tmp_array = split ",",$value; + my @tmp_array = split ",", $value; foreach (@tmp_array) { unless (/(0x\w{8})/) { return "'$_' is invalid"; @@ -180,12 +182,12 @@ sub chvm_parse_extra_options { } } else { - return "'$cmd' not support"; - } - $opt->{$cmd} = $value; - } + return "'$cmd' not support"; + } + $opt->{$cmd} = $value; + } @query_array = keys(%tmp_hash); - return undef; + return undef; } sub chvm_parse_args { @@ -200,243 +202,245 @@ sub chvm_parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { + #$request->{method} = $cmd; #return( \%opt ); - return ( usage() ); + return (usage()); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose p=s i=s m=s r=s p775 vios) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose p=s i=s m=s r=s p775 vios))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### - # Configuration file required + # Configuration file required #################################### - #if ( !exists( $opt{p}) ) { - # if ( !defined( $request->{stdin} )) { + #if ( !exists( $opt{p}) ) { + # if ( !defined( $request->{stdin} )) { # return(usage( "Configuration file or attributes not specified" )); # } #} - if (exists($opt{p775})) { - my @cfgdata ; - if ((exists ($opt{p}) || defined($request->{stdin})) && !exists($opt{p775}) ) { - return(usage("Profile just work for Power 775")); - } - if ( exists( $opt{p})) { - - if ( exists( $opt{i} ) || exists( $opt{r}) || exists( $opt{m} ) ) { - return(usage("-p should NOT be used with -i, -r or -m.")); + if (exists($opt{p775})) { + my @cfgdata; + if ((exists($opt{p}) || defined($request->{stdin})) && !exists($opt{p775})) { + return (usage("Profile just work for Power 775")); } - - $opt{p} = $request->{cwd}->[0] . '/' . $opt{p} if ( $opt{p} !~ /^\//); - return ( usage( "Profile $opt{p} cannot be found")) if ( ! -f $opt{p}); - open (PROFFILE, "<$opt{p}") or return ( usage( "Cannot open profile $opt{p}")); - while( ) { - chomp; - if( $_ =~ /(\d+):(\s+)(\d+)\/([\w\.\-]+)\/(\w+)\//) { - push @cfgdata, $_; + if (exists($opt{p})) { + + if (exists($opt{i}) || exists($opt{r}) || exists($opt{m})) { + return (usage("-p should NOT be used with -i, -r or -m.")); + } + + $opt{p} = $request->{cwd}->[0] . '/' . $opt{p} if ($opt{p} !~ /^\//); + return (usage("Profile $opt{p} cannot be found")) if (!-f $opt{p}); + open(PROFFILE, "<$opt{p}") or return (usage("Cannot open profile $opt{p}")); + while () { + chomp; + if ($_ =~ /(\d+):(\s+)(\d+)\/([\w\.\-]+)\/(\w+)\//) { + push @cfgdata, $_; + } else { + return (usage("Invalid line in profile: $_")); + } + } + $opt{profile} = \@cfgdata; + } + + if (defined($request->{stdin})) { + $opt{p} = 1; + if (exists($opt{i}) || exists($opt{r}) || exists($opt{m})) { + return (usage("When the profile is piped into the chvm command, the -i, -r and -m could NOT be used.")); + } + } + + #if (defined( $request->{stdin} )) { + # my $p = $request->{stdin}; + # my @io = split(/\n/, $p) ; + # foreach (@io) { + # chomp; + # if( $_ =~ /(\d+):(\s+)(\d+),([\w\.\-]+),(\w+),/) { + # push @cfgdata, $_; + # } else { + # return ( usage( "Invalid line in profile: $_")); + # } + + # } + + # $opt{profile} = \@cfgdata; + #} + #print "in parse args:\n"; + #print Dumper(\%opt); + + + + if (exists($opt{i})) { + if (!exists($opt{r})) { + return (usage("Option -i should be used with option -r .")); + } + + if ($opt{i} !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/) { + return (usage("Invalid entry: $opt{i}")); + } + my @id = (1, 5, 9, 13, 17, 21, 25, 29); + my @found = grep(/^$opt{i}$/, @id); + if (@found != 1) { + return (usage("Invalid entry: $opt{i}.\n For Power 775, starting numeric id of the newly created partitions only could be 1, 5, 9, 13, 17, 21, 25 and 29.")); + } + + #if ( !exists($opt{o}) ) { + # return(usage("For Power 775, -i should be used with -o")); + #} + + #my @value = (1, 2, 3, 4, 5); + #if ( grep(/^$opt{i}$/, @id ) != 1) { + # return(usage( "Invalid entry: $opt{o}.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm." )); + #} + + + } + + + # pending memory interleaving mode (1- interleaved, 2- non-interleaved) + # non-interleaved mode means the memory cannot be shared across the processors in an octant. + # interleaved means the memory can be shared. + if (exists($opt{m})) { + if ($opt{m} =~ /^interleaved$/ || $opt{m} =~ /^1$/) { + $opt{m} = 1; + } elsif ($opt{m} =~ /^non-interleaved$/ || $opt{m} =~ /^2$/) { + $opt{m} = 2; } else { - return ( usage( "Invalid line in profile: $_")); + return (usage("Invalid entry: $opt{m}.\n For Power 775, the pending memory interleaving mode only could be interleaved(or 1), or non-interleaved(or 2).")); } + } else { + $opt{m} = 1; # interleaved, which is the default } - $opt{profile} = \@cfgdata; - } - if (defined( $request->{stdin} )) { - $opt{p} = 1; - if ( exists( $opt{i} ) || exists( $opt{r} ) || exists( $opt{m} ) ) { - return(usage("When the profile is piped into the chvm command, the -i, -r and -m could NOT be used.")); - } - } - #if (defined( $request->{stdin} )) { - # my $p = $request->{stdin}; - # my @io = split(/\n/, $p) ; - # foreach (@io) { - # chomp; - # if( $_ =~ /(\d+):(\s+)(\d+),([\w\.\-]+),(\w+),/) { - # push @cfgdata, $_; - # } else { - # return ( usage( "Invalid line in profile: $_")); - # } - - # } - - # $opt{profile} = \@cfgdata; - #} - #print "in parse args:\n"; - #print Dumper(\%opt); + my @ratio = (1, 2, 3, 4, 5); + my %octant_cfg = (); + if (exists($opt{r})) { - - - if ( exists( $opt{i} ) ) { - if( !exists( $opt{r} ) ) { - return(usage( "Option -i should be used with option -r ." )); - } - - if ( $opt{i} !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/ ) { - return(usage( "Invalid entry: $opt{i}" )); - } - my @id = (1, 5, 9, 13, 17, 21, 25, 29); - my @found = grep(/^$opt{i}$/, @id ); - if ( @found != 1) { - return(usage( "Invalid entry: $opt{i}.\n For Power 775, starting numeric id of the newly created partitions only could be 1, 5, 9, 13, 17, 21, 25 and 29." )); - } - - #if ( !exists($opt{o}) ) { - # return(usage("For Power 775, -i should be used with -o")); - #} - - #my @value = (1, 2, 3, 4, 5); - #if ( grep(/^$opt{i}$/, @id ) != 1) { - # return(usage( "Invalid entry: $opt{o}.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm." )); - #} - - - } - - - # pending memory interleaving mode (1- interleaved, 2- non-interleaved) - # non-interleaved mode means the memory cannot be shared across the processors in an octant. - # interleaved means the memory can be shared. - if( exists($opt{m}) ) { - if( $opt{m} =~ /^interleaved$/ || $opt{m} =~ /^1$/ ) { - $opt{m} = 1; - } elsif( $opt{m} =~ /^non-interleaved$/ || $opt{m} =~ /^2$/ ) { - $opt{m} = 2; - } else { - return(usage( "Invalid entry: $opt{m}.\n For Power 775, the pending memory interleaving mode only could be interleaved(or 1), or non-interleaved(or 2)." )); - } - } else { - $opt{m} = 1 ;# interleaved, which is the default - } - - my @ratio = (1, 2, 3, 4, 5); - my %octant_cfg = (); - if ( exists( $opt{r} ) ) { - - if( !exists( $opt{i} ) ) { - return(usage( "Option -r should be used with option -i ." )); - } - - my @elems = split(/\,/,$opt{r}); - my $range=""; - while (my $elem = shift @elems) { - if ($elem !~ /\:/) { - return (usage("Invalid argument $elem.\n The input format for 'r' should be like this: \"-r Octant_id:Value\".")) + if (!exists($opt{i})) { + return (usage("Option -r should be used with option -i .")); } - if($elem !~ /\-/) { - my @subelems = split(/\:/, $elem); - if( $subelems[0] < 0 || $subelems[0] > 7) { - return(usage("Octant ID only could be 0 to 7 in the octant configuration value $elem")); - } - if( grep(/^$subelems[1]$/, @ratio ) != 1) { - return(usage( "Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of chvm." )); - } - if( exists($octant_cfg{$subelems[0]}) && $octant_cfg{$subelems[0]} == $subelems[1] ) { - return(usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); - } - $octant_cfg{$subelems[0]} = $subelems[1]; - $range .= "$elem,"; - } else { - my @subelems = split(/\:/, $elem); - my ($left,$right) = split(/\-/, $subelems[0]); - if( $left < 0 || $left > 7 || $right < 0 || $right > 7) { - return(usage("Octant ID only could be 0 to 7 in the octant configuration rule $elem")); - } - if($left == $right) { - if( grep(/^$subelems[1]$/, @ratio ) != 1) { - return(usage( "Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of chvm." )); - } - if( exists($octant_cfg{$left}) || $octant_cfg{$left} == $subelems[1] ) { - return(usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); - } - $octant_cfg{$left} = $subelems[1]; - $range .="$left:$subelems[1]," - } elsif($left < $right ) { - my $i = $left; - for( $i; $i <=$right ; $i ++) { - if( exists($octant_cfg{$i}) || $octant_cfg{$i} == $subelems[1] ) { - return(usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); - } - $octant_cfg{$i} = $subelems[1]; - $range .= "$i:$subelems[1],"; - } - } else { - return(usage("In the octant configuration rule $elem, the left octant ID could NOT be bigger than the right octant ID")); - } - } # end of "if .. else.." - } # end of while - } #end of if - - if ( exists( $opt{i} ) && exists( $opt{r} ) ) { - $opt{octant_cfg}{octant_cfg_value} = (\%octant_cfg); - $opt{octant_cfg}{memory_interleave} = $opt{m}; - - $opt{target} = \@{$request->{node}}; - my $ppctab = xCAT::Table->new( 'ppc'); - unless($ppctab) { - return(usage("Cannot open ppc table")); + my @elems = split(/\,/, $opt{r}); + my $range = ""; + while (my $elem = shift @elems) { + if ($elem !~ /\:/) { + return (usage("Invalid argument $elem.\n The input format for 'r' should be like this: \"-r Octant_id:Value\".")) + } + if ($elem !~ /\-/) { + my @subelems = split(/\:/, $elem); + if ($subelems[0] < 0 || $subelems[0] > 7) { + return (usage("Octant ID only could be 0 to 7 in the octant configuration value $elem")); + } + if (grep(/^$subelems[1]$/, @ratio) != 1) { + return (usage("Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of chvm.")); + } + if (exists($octant_cfg{ $subelems[0] }) && $octant_cfg{ $subelems[0] } == $subelems[1]) { + return (usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); + } + $octant_cfg{ $subelems[0] } = $subelems[1]; + $range .= "$elem,"; + } else { + my @subelems = split(/\:/, $elem); + my ($left, $right) = split(/\-/, $subelems[0]); + if ($left < 0 || $left > 7 || $right < 0 || $right > 7) { + return (usage("Octant ID only could be 0 to 7 in the octant configuration rule $elem")); + } + if ($left == $right) { + if (grep(/^$subelems[1]$/, @ratio) != 1) { + return (usage("Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of chvm.")); + } + if (exists($octant_cfg{$left}) || $octant_cfg{$left} == $subelems[1]) { + return (usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); + } + $octant_cfg{$left} = $subelems[1]; + $range .= "$left:$subelems[1]," + } elsif ($left < $right) { + my $i = $left; + for ($i ; $i <= $right ; $i++) { + if (exists($octant_cfg{$i}) || $octant_cfg{$i} == $subelems[1]) { + return (usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); + } + $octant_cfg{$i} = $subelems[1]; + + $range .= "$i:$subelems[1],"; + } + } else { + return (usage("In the octant configuration rule $elem, the left octant ID could NOT be bigger than the right octant ID")); + } + } # end of "if .. else.." + } # end of while + } #end of if + + if (exists($opt{i}) && exists($opt{r})) { + $opt{octant_cfg}{octant_cfg_value} = (\%octant_cfg); + $opt{octant_cfg}{memory_interleave} = $opt{m}; + + $opt{target} = \@{ $request->{node} }; + my $ppctab = xCAT::Table->new('ppc'); + unless ($ppctab) { + return (usage("Cannot open ppc table")); + } + + my $other_p; + foreach my $node (@{ $request->{node} }) { + my $parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); + my $p = $parent_hash->{parent}; + if (!$p) { + return (usage("Not found the parent of $node")); + } + if (!defined($other_p)) { + $other_p = $p; + } + if ($other_p ne $p) { + return (usage("For Power 775, please make sure the noderange are in one CEC ")); + } + } + $request->{node} = [$other_p]; + $request->{noderange} = $other_p; } - - my $other_p; - foreach my $node( @{$request->{node}} ) { - my $parent_hash = $ppctab->getNodeAttribs( $node,[qw(parent)]); - my $p = $parent_hash->{parent}; - if ( !$p) { - return(usage("Not found the parent of $node")); - } - if(! defined( $other_p)) { - $other_p = $p; - } - if ($other_p ne $p) { - return(usage("For Power 775, please make sure the noderange are in one CEC ")); - } - } - $request->{node} = [$other_p]; - $request->{noderange} = $other_p; - } } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { + if (defined($ARGV[0])) { my $check_chvm_arg = chvm_parse_extra_options(\@ARGV, \%opt); if (defined($check_chvm_arg)) { return (usage("Invalid argument: $check_chvm_arg")); - } elsif (($opt{lparname}) && ($opt{lparname} ne '*') && (scalar(@{$request->{node}}) > '1')){ - return(usage( "Invalid argument: must specify '*' for more than one node" )); + } elsif (($opt{lparname}) && ($opt{lparname} ne '*') && (scalar(@{ $request->{node} }) > '1')) { + return (usage("Invalid argument: must specify '*' for more than one node")); } - if ((exists($opt{lparname}) ||exists($opt{huge_page})) && - (exists($opt{p}) || exists($opt{i}) || exists($opt{r}))) { + if ((exists($opt{lparname}) || exists($opt{huge_page})) && + (exists($opt{p}) || exists($opt{i}) || exists($opt{r}))) { return (usage("lparname should NOT be used with -p, -i or -r.")); } } #################################### - # No operands - add command name + # No operands - add command name #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } @@ -447,44 +451,45 @@ sub mkvm_parse_args { my $request = shift; - my %opt = (); - my $cmd = $request->{command}; - my $args = $request->{arg}; + my %opt = (); + my $cmd = $request->{command}; + my $args = $request->{arg}; ############################################# -# Responds with usage statement + # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# -# Process command-line arguments + # Process command-line arguments ############################################# #if ( !defined( $args )) { # return(usage( "No command specified" )); #} ############################################# -# Checks case in GetOptions, allows opts -# to be grouped (e.g. -vx), and terminates -# at the first unrecognized option. + # Checks case in GetOptions, allows opts + # to be grouped (e.g. -vx), and terminates + # at the first unrecognized option. ############################################# if (defined($args)) { @ARGV = @$args; } $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); -# if ( !GetOptions( \%opt, qw(V|verbose ibautocfg ibacap=s i=s l=s c=s p=s m=s r=s full) )) { -# return( usage() ); -# } - if ( !GetOptions( \%opt, qw(V|verbose full vios) )) { - return( usage() ); + Getopt::Long::Configure("bundling"); + + # if ( !GetOptions( \%opt, qw(V|verbose ibautocfg ibacap=s i=s l=s c=s p=s m=s r=s full) )) { + # return( usage() ); + # } + if (!GetOptions(\%opt, qw(V|verbose full vios))) { + return (usage()); } #################################### -# Check for "-" with no option + # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } if (!exists($opt{p775})) { my @unsupport_ops = (); @@ -495,14 +500,14 @@ sub mkvm_parse_args { } my @support_ops = qw(vmcpus vmmemory vmphyslots vmothersetting vmnics vmstorage); if (defined(@ARGV[0]) and defined($opt{full})) { - return(usage("Option 'full' shall be used alone.")); + return (usage("Option 'full' shall be used alone.")); } elsif (defined(@ARGV[0])) { foreach my $arg (@ARGV) { - my ($cmd,$val) = split (/=/,$arg); - if (!grep(/^$cmd$/, @support_ops)) { + my ($cmd, $val) = split(/=/, $arg); + if (!grep(/^$cmd$/, @support_ops)) { push @unsupport_ops, $cmd; } elsif (!defined($val)) { - return(usage("The option $cmd need specific parameters.")); + return (usage("The option $cmd need specific parameters.")); } else { $opt{$cmd} = $val; } @@ -510,147 +515,149 @@ sub mkvm_parse_args { } if (@unsupport_ops) { - my $tmpops = join(",",@unsupport_ops); - return(usage( "The options $tmpops can only work(s) with Power 775 machines.")); + my $tmpops = join(",", @unsupport_ops); + return (usage("The options $tmpops can only work(s) with Power 775 machines.")); } } else { if (exists($opt{full}) or exists($opt{vios})) { - return(usage( "Option 'p775' only works for Power 775 machines.")); + return (usage("Option 'p775' only works for Power 775 machines.")); } #################################### -# Check for non-zero integer + # Check for non-zero integer #################################### - if ( exists( $opt{i} ) ) { - if ( $opt{i} !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/ ) { - return(usage( "Invalid entry: $opt{i}" )); - } - my @id = (1, 5, 9, 13, 17, 21, 25, 29); - my @found = grep(/^$opt{i}$/, @id ); - if ( @found != 1) { - return(usage( "Invalid entry: $opt{i}.\n For Power 775, starting numeric id of the newly created partitions only could be 1, 5, 9, 13, 17, 21, 25 and 29." )); - } - - #if ( !exists($opt{o}) ) { - # return(usage("For Power 775, -i should be used with -o")); - #} - - #my @value = (1, 2, 3, 4, 5); - #if ( grep(/^$opt{i}$/, @id ) != 1) { - # return(usage( "Invalid entry: $opt{o}.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm." )); - #} - - - } - - - # pending memory interleaving mode (1- interleaved, 2- non-interleaved) - # non-interleaved mode means the memory cannot be shared across the processors in an octant. - # interleaved means the memory can be shared. - if( exists($opt{m}) ) { - if( $opt{m} =~ /^interleaved$/ || $opt{m} =~ /^1$/ ) { - $opt{m} = 1; - } elsif( $opt{m} =~ /^non-interleaved$/ || $opt{m} =~ /^2$/ ) { - $opt{m} = 2; - } else { - return(usage( "Invalid entry: $opt{m}.\n For Power 775, the pending memory interleaving mode only could be interleaved(or 1), or non-interleaved(or 2)." )); - } - } elsif (exists($opt{p775})){ - $opt{m} = 2 ;# non-interleaved, which is the default - } - - if ( exists( $opt{r} ) ) { - my @ratio = (1, 2, 3, 4, 5); - my %octant_cfg = (); + if (exists($opt{i})) { + if ($opt{i} !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/) { + return (usage("Invalid entry: $opt{i}")); + } + my @id = (1, 5, 9, 13, 17, 21, 25, 29); + my @found = grep(/^$opt{i}$/, @id); + if (@found != 1) { + return (usage("Invalid entry: $opt{i}.\n For Power 775, starting numeric id of the newly created partitions only could be 1, 5, 9, 13, 17, 21, 25 and 29.")); + } + + #if ( !exists($opt{o}) ) { + # return(usage("For Power 775, -i should be used with -o")); + #} + + #my @value = (1, 2, 3, 4, 5); + #if ( grep(/^$opt{i}$/, @id ) != 1) { + # return(usage( "Invalid entry: $opt{o}.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm." )); + #} - my @elems = split(/\,/,$opt{r}); - my $range=""; - while (my $elem = shift @elems) { - if($elem !~ /\-/) { - my @subelems = split(/\:/, $elem); - if( $subelems[0] < 0 || $subelems[0] > 7) { - return(usage("Octant ID only could be 0 to 7 in the octant configuration value $elem")); - } - if( grep(/^$subelems[1]$/, @ratio ) != 1) { - return(usage( "Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm." )); - } - if( exists($octant_cfg{$subelems[0]}) && $octant_cfg{$subelems[0]} == $subelems[1] ) { - return(usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); - } - $octant_cfg{$subelems[0]} = $subelems[1]; - $range .= "$elem,"; - } else { - my @subelems = split(/\:/, $elem); - my ($left,$right) = split(/\-/, $subelems[0]); - if( $left < 0 || $left > 7 || $right < 0 || $right > 7) { - return(usage("Octant ID only could be 0 to 7 in the octant configuration rule $elem")); - } - if($left == $right) { - if( grep(/^$subelems[1]$/, @ratio ) != 1) { - return(usage( "Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm." )); - } - if( exists($octant_cfg{$left}) || $octant_cfg{$left} == $subelems[1] ) { - return(usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); - } - $octant_cfg{$left} = $subelems[1]; - $range .="$left:$subelems[1]," - } elsif($left < $right ) { - my $i = $left; - for( $i; $i <=$right ; $i ++) { - if( exists($octant_cfg{$i}) || $octant_cfg{$i} == $subelems[1] ) { - return(usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); - } - $octant_cfg{$i} = $subelems[1]; - $range .= "$i:$subelems[1],"; - } - } else { - return(usage("In the octant configuration rule $elem, the left octant ID could NOT be bigger than the right octant ID")); - } - } # end of "if .. else.." - } # end of while - $opt{octant_cfg}{octant_cfg_value} = (\%octant_cfg); - $opt{octant_cfg}{memory_interleave} = $opt{m}; - } #end of if - - - if ( (!exists( $opt{i} ) || !exists( $opt{r} )) ) { - return(usage()); - } - $opt{target} = \@{$request->{node}}; - my $ppctab = xCAT::Table->new( 'ppc'); - unless($ppctab) { - return(usage("Cannot open ppc table")); - } - - my $other_p; - foreach my $node( @{$request->{node}} ) { - my $parent_hash = $ppctab->getNodeAttribs( $node,[qw(parent)]); - my $p = $parent_hash->{parent}; - if ( !$p) { - return(usage("Not found the parent of $node")); - } - if (exists($opt{full}) and defined($other_p) and $other_p eq $p){ - return(usage("Only one full partition can be created in one CEC")); } - if(! defined( $other_p)) { - $other_p = $p; - } - if ($other_p ne $p) { - return(usage("For Power 775, please make sure the noderange are in one CEC ")); + + # pending memory interleaving mode (1- interleaved, 2- non-interleaved) + # non-interleaved mode means the memory cannot be shared across the processors in an octant. + # interleaved means the memory can be shared. + if (exists($opt{m})) { + if ($opt{m} =~ /^interleaved$/ || $opt{m} =~ /^1$/) { + $opt{m} = 1; + } elsif ($opt{m} =~ /^non-interleaved$/ || $opt{m} =~ /^2$/) { + $opt{m} = 2; + } else { + return (usage("Invalid entry: $opt{m}.\n For Power 775, the pending memory interleaving mode only could be interleaved(or 1), or non-interleaved(or 2).")); + } + } elsif (exists($opt{p775})) { + $opt{m} = 2; # non-interleaved, which is the default } - } - #if (exists($opt{p775})) { - $request->{node} = [$other_p]; - $request->{noderange} = $other_p; - #} + + if (exists($opt{r})) { + my @ratio = (1, 2, 3, 4, 5); + my %octant_cfg = (); + + my @elems = split(/\,/, $opt{r}); + my $range = ""; + while (my $elem = shift @elems) { + if ($elem !~ /\-/) { + my @subelems = split(/\:/, $elem); + if ($subelems[0] < 0 || $subelems[0] > 7) { + return (usage("Octant ID only could be 0 to 7 in the octant configuration value $elem")); + } + if (grep(/^$subelems[1]$/, @ratio) != 1) { + return (usage("Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm.")); + } + if (exists($octant_cfg{ $subelems[0] }) && $octant_cfg{ $subelems[0] } == $subelems[1]) { + return (usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); + } + $octant_cfg{ $subelems[0] } = $subelems[1]; + $range .= "$elem,"; + } else { + my @subelems = split(/\:/, $elem); + my ($left, $right) = split(/\-/, $subelems[0]); + if ($left < 0 || $left > 7 || $right < 0 || $right > 7) { + return (usage("Octant ID only could be 0 to 7 in the octant configuration rule $elem")); + } + if ($left == $right) { + if (grep(/^$subelems[1]$/, @ratio) != 1) { + return (usage("Invalid octant configuration value in $elem.\n For Power 775, octant configuration values only could be 1, 2, 3, 4, 5. Please see the details in manpage of mkvm.")); + } + if (exists($octant_cfg{$left}) || $octant_cfg{$left} == $subelems[1]) { + return (usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); + } + $octant_cfg{$left} = $subelems[1]; + $range .= "$left:$subelems[1]," + } elsif ($left < $right) { + my $i = $left; + for ($i ; $i <= $right ; $i++) { + if (exists($octant_cfg{$i}) || $octant_cfg{$i} == $subelems[1]) { + return (usage("In the octant configuration rule, same octant with different octant configuration value. Error!")); + } + $octant_cfg{$i} = $subelems[1]; + + $range .= "$i:$subelems[1],"; + } + } else { + return (usage("In the octant configuration rule $elem, the left octant ID could NOT be bigger than the right octant ID")); + } + } # end of "if .. else.." + } # end of while + $opt{octant_cfg}{octant_cfg_value} = (\%octant_cfg); + $opt{octant_cfg}{memory_interleave} = $opt{m}; + } #end of if + + + if ((!exists($opt{i}) || !exists($opt{r}))) { + return (usage()); + } + $opt{target} = \@{ $request->{node} }; + my $ppctab = xCAT::Table->new('ppc'); + unless ($ppctab) { + return (usage("Cannot open ppc table")); + } + + my $other_p; + foreach my $node (@{ $request->{node} }) { + my $parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); + my $p = $parent_hash->{parent}; + if (!$p) { + return (usage("Not found the parent of $node")); + } + if (exists($opt{full}) and defined($other_p) and $other_p eq $p) { + return (usage("Only one full partition can be created in one CEC")); + } + + if (!defined($other_p)) { + $other_p = $p; + } + if ($other_p ne $p) { + return (usage("For Power 775, please make sure the noderange are in one CEC ")); + } + } + + #if (exists($opt{p775})) { + $request->{node} = [$other_p]; + $request->{noderange} = $other_p; + + #} } #################################### - # No operands - add command name + # No operands - add command name #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } @@ -668,51 +675,51 @@ sub rmvm_parse_args { ############################################# # Responds with usage statement ############################################# - local *usage = sub { + local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose service r p775) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose service r p775))) { + return (usage()); } if (exists($opt{p775})) { - return(usage( "rmvm doesn't support for Power 775." )); + return (usage("rmvm doesn't support for Power 775.")); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # No operands - add command name + # No operands - add command name #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } @@ -731,114 +738,114 @@ sub lsvm_parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose l|long p775 updatedb) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose l|long p775 updatedb))) { + return (usage()); } if (exists($opt{l}) && !exists($opt{p775})) { - return(usage( "option 'l' only works for Power 775")); + return (usage("option 'l' only works for Power 775")); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # No operands - add command name + # No operands - add command name #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } ########################################################################## -# Changes the configuration of an existing partition +# Changes the configuration of an existing partition ########################################################################## sub modify { - my $request = shift; - my $hash = shift; + my $request = shift; + my $hash = shift; my $usage_string = xCAT::Usage->getUsage($request->{command}); - return modify_by_prof( $request, $hash) if ( exists($request->{opt}->{p775}) and ($request->{opt}->{p} || $request->{stdin})); - return create( $request, $hash) if ( exists($request->{opt}->{p775}) and $request->{opt}->{i}); - return op_extra_cmds ($request, $hash) if (!exists($request->{opt}->{p775})); - return op_extra_cmds ($request, $hash) if ($request->{opt}->{lparname} || $request->{opt}->{huge_page}); - return ([["Error", "Miss argument\n".$usage_string, 1]]); + return modify_by_prof($request, $hash) if (exists($request->{opt}->{p775}) and ($request->{opt}->{p} || $request->{stdin})); + return create($request, $hash) if (exists($request->{opt}->{p775}) and $request->{opt}->{i}); + return op_extra_cmds($request, $hash) if (!exists($request->{opt}->{p775})); + return op_extra_cmds($request, $hash) if ($request->{opt}->{lparname} || $request->{opt}->{huge_page}); + return ([ [ "Error", "Miss argument\n" . $usage_string, 1 ] ]); } sub do_op_extra_cmds { - my $request = shift; - my $hash = shift; - my @values = (); + my $request = shift; + my $hash = shift; + my @values = (); my %lpar_hash = (); while (my ($mtms, $h) = each(%$hash)) { my $memhash; - while (my($name, $d) = each(%$h)) { - foreach my $op (keys %{$request->{opt}}) { - my $action; - my $param = $request->{opt}->{$op}; - if ($op eq "lparname") { - $action = "set_lpar_name"; - } elsif ($op eq "huge_page") { + while (my ($name, $d) = each(%$h)) { + foreach my $op (keys %{ $request->{opt} }) { + my $action; + my $param = $request->{opt}->{$op}; + if ($op eq "lparname") { + $action = "set_lpar_name"; + } elsif ($op eq "huge_page") { my @td = @$d; @td[0] = 0; my $tmphash = &query_cec_info_actions($request, $name, \@td, 1, ["get_huge_page"]); if ($tmphash->{huge_page_avail}) { if ($param > $tmphash->{huge_page_avail}) { - push @values, [$name, "No enough huge pages, only $tmphash->{huge_page_avail} pages available", 0]; + push @values, [ $name, "No enough huge pages, only $tmphash->{huge_page_avail} pages available", 0 ]; $param = $tmphash->{huge_page_avail}; } $param = "1/$param/$param"; } else { - push @values, [$name, "No huge page available to configure", 0]; + push @values, [ $name, "No huge page available to configure", 0 ]; next; } - $action = "set_huge_page"; - } elsif ($op eq "vmcpus") { + $action = "set_huge_page"; + } elsif ($op eq "vmcpus") { $action = "part_set_lpar_pending_proc"; } elsif ($op eq "add_physlots" or $op eq "del_physlots") { $action = "set_io_slot_owner_uber"; } elsif ($op eq "del_vadapter") { $action = "part_clear_vslot_config"; } elsif ($op eq "add_vmnics") { - my @vlans = split /,/,$param; + my @vlans = split /,/, $param; foreach (@vlans) { if (/vlan(\d+)/i) { my $vlanid = $1; - my $mac = lc(xCAT::VMCommon::genMac($name)); + my $mac = lc(xCAT::VMCommon::genMac($name)); if ($mac =~ /(..):(..):(..):(..):(..):(..)/) { - my $tail = hex($6)+$vlanid; - $mac = sprintf("$1$2$3$4$5%02x",$tail); + my $tail = hex($6) + $vlanid; + $mac = sprintf("$1$2$3$4$5%02x", $tail); } - my $value = xCAT::FSPUtils::fsp_api_action($request,$name, $d, "part_set_veth_slot_config",0,"0,$vlanid,$mac"); + my $value = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_veth_slot_config", 0, "0,$vlanid,$mac"); if (@$value[1] && ((@$value[1] =~ /Error/i) && (@$value[2] ne '0'))) { - return ([[$name, @$value[1], '1']]) ; + return ([ [ $name, @$value[1], '1' ] ]); } else { - push @values, [$name, "Success", '0']; - } + push @values, [ $name, "Success", '0' ]; + } } } next; @@ -848,16 +855,16 @@ sub do_op_extra_cmds { my $vios = &find_lpar_id($request, @$d[3], $2); my $r_slotid = $3; if (!defined($vios)) { - return ([[$name, "Cannot find lparid for Server lpar:$1", '1']]); + return ([ [ $name, "Cannot find lparid for Server lpar:$1", '1' ] ]); } $v_info = "$1,$vios,$r_slotid"; } - my $value = xCAT::FSPUtils::fsp_api_action($request,$name, $d, "part_set_vscsi_slot_config",0,$v_info); + my $value = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_vscsi_slot_config", 0, $v_info); if (@$value[1] && ((@$value[1] =~ /Error/i) && (@$value[2] ne '0'))) { - return ([[$name, @$value[1], '1']]) ; + return ([ [ $name, @$value[1], '1' ] ]); } else { - push @values, [$name, "Success", '0']; - } + push @values, [ $name, "Success", '0' ]; + } } next; } elsif ($op eq "vmmemory") { @@ -865,224 +872,235 @@ sub do_op_extra_cmds { @td[0] = 0; $memhash = &query_cec_info_actions($request, $name, \@td, 1, ["part_get_hyp_process_and_mem"]); unless (scalar keys(%$memhash)) { - push @values, [$mtms, "Can not get hypervisor information", 1]; + push @values, [ $mtms, "Can not get hypervisor information", 1 ]; next; } if (!exists($memhash->{run})) { if ($param =~ /(\d+)([G|M]?)\/(\d+)([G|M]?)\/(\d+)([G|M]?)/i) { my $memsize = $memhash->{mem_region_size}; - my $min = $1; + my $min = $1; if ($2 eq "G" or $2 eq '') { $min = $min * 1024; - } - $min = int($min/$memsize); + } + $min = int($min / $memsize); my $cur = $3; if ($4 eq "G" or $4 eq '') { $cur = $cur * 1024; } - $cur = int($cur/$memsize); + $cur = int($cur / $memsize); my $max = $5; if ($6 eq "G" or $6 eq '') { $max = $max * 1024; } - $max = int($max/$memsize); - $request->{opt}->{$op} ="$min/$cur/$max"; - $param = $request->{opt}->{$op}; + $max = int($max / $memsize); + $request->{opt}->{$op} = "$min/$cur/$max"; + $param = $request->{opt}->{$op}; } else { - return([[$name, "The format of param:$param is incorrect.", 1]]); + return ([ [ $name, "The format of param:$param is incorrect.", 1 ] ]); } $memhash->{run} = 1; } - $memhash->{memory} = $param; + $memhash->{memory} = $param; $memhash->{lpar_used_regions} = 0; my $ret = &deal_with_avail_mem($request, $name, $d, $memhash); if (ref($ret) eq "ARRAY") { if (@$ret[2]) { - return ([[@$ret]]); - } else { + return ([ [@$ret] ]); + } else { push @values, $ret; } } - $param = $memhash->{memory}; + $param = $memhash->{memory}; $action = "part_set_lpar_pending_mem"; } elsif ($op eq "bsr") { $action = "set_lpar_bsr"; } elsif ($op eq "vios") { - print __LINE__."=========>op=vios===\n"; + print __LINE__. "=========>op=vios===\n"; next; } else { last; } my $tmp_value = ($param eq '*') ? $name : $param; - xCAT::MsgUtils->verbose_message($request, "$request->{command} $action for node:$name, parm:$tmp_value."); + xCAT::MsgUtils->verbose_message($request, "$request->{command} $action for node:$name, parm:$tmp_value."); my @tmpd = @$d; if ($op eq "del_physlots") { @tmpd[0] = "-1"; } my $value = xCAT::FSPUtils::fsp_api_action($request, $name, \@tmpd, $action, 0, $tmp_value); if (@$value[1] && ((@$value[1] =~ /Error/i) && (@$value[2] ne '0'))) { - return ([[$name, @$value[1], '1']]) ; + return ([ [ $name, @$value[1], '1' ] ]); } else { - push @values, [$name, "Success", '0']; - } + push @values, [ $name, "Success", '0' ]; + } } if (@query_array) { my $rethash = query_cec_info_actions($request, $name, $d, 1, \@query_array); unless (scalar keys(%$rethash)) { - push @values, [$mtms, "Can not get hypervisor information", 1]; + push @values, [ $mtms, "Can not get hypervisor information", 1 ]; next; } - # need to add update db here - $lpar_hash{$name} = $rethash; + + # need to add update db here + $lpar_hash{$name} = $rethash; $lpar_hash{$name}->{parent} = @$d[3]; } } - } + } if (%lpar_hash) { update_vm_db($request, \%lpar_hash); } return \@values; } + sub check_node_info { - my $hash = shift; + my $hash = shift; my $not_lpar = undef; while (my ($mtms, $h) = each(%$hash)) { - while (my($name, $d) = each(%$h)) { + while (my ($name, $d) = each(%$h)) { my $node_type = @$d[4]; if ($node_type !~ /^lpar$/) { $not_lpar = $name; - last; + last; } - } + } } return $not_lpar; } sub op_extra_cmds { - my $request = shift; - my $hash = shift; - my $node = $request->{node}; + my $request = shift; + my $hash = shift; + my $node = $request->{node}; my $lpar_flag = &check_node_info($hash); if (defined($lpar_flag)) { - return ([[$lpar_flag,"Node must be LPAR", 1]]); + return ([ [ $lpar_flag, "Node must be LPAR", 1 ] ]); } return &do_op_extra_cmds($request, $hash); } ########################################################################## -# Changes the configuration of an existing +# Changes the configuration of an existing # partition based on the profile specified ########################################################################## sub modify_by_prof { my $request = shift; my $hash = shift; - my $name = @{$request->{node}}[0]; + my $name = @{ $request->{node} }[0]; my $opt = $request->{opt}; my @values; my $cfgdata = $opt->{profile}; my $profile; - my $cec_name; - my $td; - my %io = (); + my $cec_name; + my $td; + my %io = (); my %lpar_state = (); - my @result; - xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); - if (defined( $request->{stdin} )) { - my $p = $request->{stdin}; - my @io = split(/\n/, $p) ; - foreach (@io) { - chomp; - if( $_ =~ /(\d+):(\s+)(\d+)\/([\w\.\-]+)\/(\w+)\//) { + my @result; + xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); + + if (defined($request->{stdin})) { + my $p = $request->{stdin}; + my @io = split(/\n/, $p); + foreach (@io) { + chomp; + if ($_ =~ /(\d+):(\s+)(\d+)\/([\w\.\-]+)\/(\w+)\//) { push @$cfgdata, $_; - } else { - return (\["Error", "Invalid line in profile: $_", -1]); - } - - } + } else { + return (\[ "Error", "Invalid line in profile: $_", -1 ]); + } + + } } + #print Dumper($cfgdata); - while (my ($cec,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { $td = $d; + #@$td[4] = "fsp"; - $cec_name = @$d[3]; + $cec_name = @$d[3]; } $td->[4] = "cec"; + #get the current I/O slot information - xCAT::MsgUtils->verbose_message($request, "$request->{command} :get_io_slot_info for node:$cec_name."); + xCAT::MsgUtils->verbose_message($request, "$request->{command} :get_io_slot_info for node:$cec_name."); my $action = "get_io_slot_info"; - my $values = xCAT::FSPUtils::fsp_api_action ($request, $cec_name, $td, $action); + my $values = xCAT::FSPUtils::fsp_api_action($request, $cec_name, $td, $action); my $Rc = $$values[2]; - if ( $Rc != 0 ) { - push @result, [$cec_name, $$values[1], $Rc]; + if ($Rc != 0) { + push @result, [ $cec_name, $$values[1], $Rc ]; return (\@result); } my @data = split(/\n/, $$values[1]); foreach my $v (@data) { my ($lparid, $busid, $location, $drc_index, $owner_type, $owner, $descr) = split(/,/, $v); - $io{$drc_index}{lparid} = $lparid; + $io{$drc_index}{lparid} = $lparid; $io{$drc_index}{owner_type} = $owner_type; - $io{$drc_index}{owner} = $owner; - } - + $io{$drc_index}{owner} = $owner; + } + #get all the nodes state in the same cec - xCAT::MsgUtils->verbose_message($request, "$request->{command} :get all the nodes state for CEC:$cec_name."); + xCAT::MsgUtils->verbose_message($request, "$request->{command} :get all the nodes state for CEC:$cec_name."); $action = "all_lpars_state"; undef($values); - my $values = xCAT::FSPUtils::fsp_state_action ($request, $cec_name, $td, $action); + my $values = xCAT::FSPUtils::fsp_state_action($request, $cec_name, $td, $action); $Rc = shift(@$values); - if ( $Rc != 0 ) { - push @result, [$cec_name, $$values[0], $Rc]; + if ($Rc != 0) { + push @result, [ $cec_name, $$values[0], $Rc ]; return (\@result); } - foreach ( @$values ) { - my ($state,$lparid) = split /,/; - $lpar_state{$lparid} = $state; - } - } - ################################## - # Check if LPAR profile exists - ################################### - while (my ($cec,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { - my $id = @$d[0]; - #print Dumper($cfgdata); - my @found = grep(/^$id:/, @$cfgdata ); - #print Dumper(\@found); - my $action = "set_io_slot_owner"; - my $tooltype = 0; - foreach my $f (@found) { - #'1: 514/U78A9.001.0123456-P1-C17/0x21010202/2/1' - my ($bus,$location,$drc_index,@t) = split(/\//, $f); - my $orig_id = $io{$drc_index}{lparid}; - # the current owning lpar and the new owning lpar must be in power off state - if (($lpar_state{$orig_id} ne "Not Activated") || ($lpar_state{$id} ne "Not Activated" )){ - push @result, [$lpar, "For the I/O $location, the current owning lpar(id=$orig_id) of the I/O and the new owning lpar(id=$id) must be in Not Activated state at first. And then run chvm again", -1]; - return ( \@result ); - } - - xCAT::MsgUtils->verbose_message($request, "$request->{command} :set_io_slot_owner io_slot_info:$f,owner:$lpar."); - my $values = xCAT::FSPUtils::fsp_api_action ($request, $lpar, $d, $action, $tooltype, $drc_index); - #my $Rc = shift(@$values); - my $Rc = pop(@$values); - if ( $Rc != 0 ) { - push @result, [$lpar, $$values[1],$Rc]; - next; - } - } - + foreach (@$values) { + my ($state, $lparid) = split /,/; + $lpar_state{$lparid} = $state; } } - xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); - return( \@result ); + ################################## + # Check if LPAR profile exists + ################################### + while (my ($cec, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { + my $id = @$d[0]; + + #print Dumper($cfgdata); + my @found = grep(/^$id:/, @$cfgdata); + + #print Dumper(\@found); + my $action = "set_io_slot_owner"; + my $tooltype = 0; + foreach my $f (@found) { + + #'1: 514/U78A9.001.0123456-P1-C17/0x21010202/2/1' + my ($bus, $location, $drc_index, @t) = split(/\//, $f); + my $orig_id = $io{$drc_index}{lparid}; + + # the current owning lpar and the new owning lpar must be in power off state + if (($lpar_state{$orig_id} ne "Not Activated") || ($lpar_state{$id} ne "Not Activated")) { + push @result, [ $lpar, "For the I/O $location, the current owning lpar(id=$orig_id) of the I/O and the new owning lpar(id=$id) must be in Not Activated state at first. And then run chvm again", -1 ]; + return (\@result); + } + + xCAT::MsgUtils->verbose_message($request, "$request->{command} :set_io_slot_owner io_slot_info:$f,owner:$lpar."); + my $values = xCAT::FSPUtils::fsp_api_action($request, $lpar, $d, $action, $tooltype, $drc_index); + + #my $Rc = shift(@$values); + my $Rc = pop(@$values); + if ($Rc != 0) { + push @result, [ $lpar, $$values[1], $Rc ]; + next; + } + } + + } + } + xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); + return (\@result); } sub enumerate { - my $request = shift; - my $h = shift; + my $request = shift; + my $h = shift; my $mtms = shift; my %outhash = (); my $cec; @@ -1090,180 +1108,186 @@ sub enumerate { my @td; xCAT::MsgUtils->verbose_message($request, "lsvm :enumerate START for mtms:$mtms."); - while (my ($name,$d) = each(%$h) ) { - $cec = @$d[3]; + while (my ($name, $d) = each(%$h)) { + $cec = @$d[3]; $type = @$d[4]; - @td = @$d; + @td = @$d; } - - $td[4]="cec"; + + $td[4] = "cec"; xCAT::MsgUtils->verbose_message($request, "lsvm :enumerate get_io_slot_info for node:$cec."); my $action = "get_io_slot_info"; - my $values = xCAT::FSPUtils::fsp_api_action ($request, $cec, \@td, $action); + my $values = xCAT::FSPUtils::fsp_api_action($request, $cec, \@td, $action); + #my $Rc = shift(@$values); my $Rc = $$values[2]; - if ( $Rc != 0 ) { - $outhash{ 1 } = "The LPARs' I/O slots information could NOT be listed because the cec is in power off state"; + if ($Rc != 0) { + $outhash{1} = "The LPARs' I/O slots information could NOT be listed because the cec is in power off state"; } else { - $outhash{ 0 } = $$values[1]; - } - #my @t; + $outhash{0} = $$values[1]; + } + + #my @t; #foreach my $value ( @$values ) { # my ($lparid, $busid, $slot_location_code, $drc_index,@t ) = split (/,/, $value); # push (@{$outhash{$lparid}}, $value); #} - - if( $type =~ /^(fsp|cec)$/ ) { + + if ($type =~ /^(fsp|cec)$/) { xCAT::MsgUtils->verbose_message($request, "lsvm :enumerate query_octant_cfg for node:$cec."); - $action = "query_octant_cfg"; - my $values = xCAT::FSPUtils::fsp_api_action ($request, $cec, \@td, $action); - my $Rc = pop(@$values); - if ( $Rc != 0 ) { - return( [$Rc,$$values[1]] ); - } + $action = "query_octant_cfg"; + my $values = xCAT::FSPUtils::fsp_api_action($request, $cec, \@td, $action); + my $Rc = pop(@$values); + if ($Rc != 0) { + return ([ $Rc, $$values[1] ]); + } + #$outhash{ $cec } = @$values[0]; - my $data = $$values[1]; - my @value = split(/:/, $data); - my $pendingpumpmode = $value[0]; - my $currentpumpMode = $value[1]; - my $octantcount = $value[2]; - my $j = 3; - my $res = "PendingPumpMode=$pendingpumpmode,CurrentPumpMode=$currentpumpMode,OctantCount=$octantcount:\n"; - for(my $i=0; $i < $octantcount; $i++) { - $res = $res."OctantID=".$value[$j++].",PendingOctCfg=".$value[$j++].",CurrentOctCfg=".$value[$j++].",PendingMemoryInterleaveMode=".$value[$j++].",CurrentMemoryInterleaveMode=".$value[$j++].";\n"; - } - $outhash{ $cec } = $res; - } - + my $data = $$values[1]; + my @value = split(/:/, $data); + my $pendingpumpmode = $value[0]; + my $currentpumpMode = $value[1]; + my $octantcount = $value[2]; + my $j = 3; + my $res = "PendingPumpMode=$pendingpumpmode,CurrentPumpMode=$currentpumpMode,OctantCount=$octantcount:\n"; + for (my $i = 0 ; $i < $octantcount ; $i++) { + $res = $res . "OctantID=" . $value[ $j++ ] . ",PendingOctCfg=" . $value[ $j++ ] . ",CurrentOctCfg=" . $value[ $j++ ] . ",PendingMemoryInterleaveMode=" . $value[ $j++ ] . ",CurrentMemoryInterleaveMode=" . $value[ $j++ ] . ";\n"; + } + $outhash{$cec} = $res; + } + xCAT::MsgUtils->verbose_message($request, "lsvm :enumerate END for mtms:$mtms."); - return( [0,\%outhash] ); + return ([ 0, \%outhash ]); } sub get_cec_attr_info { - my $request = shift; - my $name = shift; - my $attr = shift; - my $op = shift; - my %op_hash = ( - lpar_info => "get_lpar_info", - bsr => "get_cec_bsr", - huge_page => "get_huge_page" - ); - my $action = $op_hash{$op}; - my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $attr, $action); + my $request = shift; + my $name = shift; + my $attr = shift; + my $op = shift; + my %op_hash = ( + lpar_info => "get_lpar_info", + bsr => "get_cec_bsr", + huge_page => "get_huge_page" + ); + my $action = $op_hash{$op}; + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $attr, $action); if (@$values[1] && ((@$values[1] =~ /Error/i) && @$values[2] ne '0')) { - return ([[$name, @$values[1], '1']]); + return ([ [ $name, @$values[1], '1' ] ]); } return @$values[1]; } sub get_cec_lpar_hugepage { - my $name = shift; - my $huge_info = shift; - my $lparid = shift; - my $lparname = shift; - my @value = split(/\n/, $huge_info); + my $name = shift; + my $huge_info = shift; + my $lparid = shift; + my $lparname = shift; + my @value = split(/\n/, $huge_info); foreach my $v (@value) { - if($v =~ /\s*([^\s]+)\s*:\s*([\d|\/]+)/) { - my $tmp_name = $1; - my $tmp_num = $2; - if($tmp_name =~ /^$lparname$/) { + if ($v =~ /\s*([^\s]+)\s*:\s*([\d|\/]+)/) { + my $tmp_name = $1; + my $tmp_num = $2; + if ($tmp_name =~ /^$lparname$/) { return $tmp_num; } } } - return ([[$name, "can not get huge page info for lpar id $lparid", '1']]); + return ([ [ $name, "can not get huge page info for lpar id $lparid", '1' ] ]); } sub get_cec_lpar_name { - my $name = shift; + my $name = shift; my $lpar_info = shift; - my $lparid = shift; - my @value = split(/\n/, $lpar_info); + my $lparid = shift; + my @value = split(/\n/, $lpar_info); foreach my $v (@value) { - if($v =~ /lparname:\s*([^\,]*),\s*lparid:\s*([\d]+),/) { - if($2 eq $lparid) { + if ($v =~ /lparname:\s*([^\,]*),\s*lparid:\s*([\d]+),/) { + if ($2 eq $lparid) { return $1; } } } - return ([[$name, "can not get lparname for lpar id $lparid", '1']]); + return ([ [ $name, "can not get lparname for lpar id $lparid", '1' ] ]); } + sub get_cec_lpar_bsr { - my $name = shift; + my $name = shift; my $lpar_info = shift; - my $lparid = shift; - my $lparname = shift; - my @value = split(/\n/, $lpar_info); + my $lparid = shift; + my $lparname = shift; + my @value = split(/\n/, $lpar_info); foreach my $v (@value) { - if($v =~ /\s*([^\s]+)\s*:\s*([\d]+)/) { - my $tmp_name = $1; - my $tmp_num = $2; - if($tmp_name =~ /^$lparname$/) { + if ($v =~ /\s*([^\s]+)\s*:\s*([\d]+)/) { + my $tmp_name = $1; + my $tmp_num = $2; + if ($tmp_name =~ /^$lparname$/) { return $tmp_num; } } } - return ([[$name, "can not get BSR info for lpar id $lparid", '1']]); + return ([ [ $name, "can not get BSR info for lpar id $lparid", '1' ] ]); } + sub get_cec_cec_bsr { - my $name = shift; + my $name = shift; my $lpar_info = shift; - my $index = 0; - my @value = split(/\n/, $lpar_info); - my $cec_bsr = ""; + my $index = 0; + my @value = split(/\n/, $lpar_info); + my $cec_bsr = ""; foreach my $v (@value) { - if ($v =~ /(Number of BSR arrays:)\s*(\d+)/i) { - $cec_bsr .= "$1 $2,"; - $index++; - } elsif ($v =~ /(Bytes per BSR array:)\s*(\d+)/i) { - $cec_bsr .= "$1 $2,"; - $index++; - } elsif ($v =~ /(Available BSR array:)\s*(\d+)/i) { - $cec_bsr .= "$1 $2;\n"; - $index++; - } + if ($v =~ /(Number of BSR arrays:)\s*(\d+)/i) { + $cec_bsr .= "$1 $2,"; + $index++; + } elsif ($v =~ /(Bytes per BSR array:)\s*(\d+)/i) { + $cec_bsr .= "$1 $2,"; + $index++; + } elsif ($v =~ /(Available BSR array:)\s*(\d+)/i) { + $cec_bsr .= "$1 $2;\n"; + $index++; + } } if ($index != 3) { - return undef; + return undef; } else { - return $cec_bsr; + return $cec_bsr; } } + sub get_cec_cec_hugepage { - my $name = shift; - my $huge_info = shift; - my $index = 0; - my @value = split (/\n/, $huge_info); - my $cec_hugepage = ""; - foreach my $v (@value) { - if ($v =~ /(Available huge page memory\(in pages\):)\s*(\d+)/i) { - my $tmp = sprintf "%-40s %s;\n", $1, $2; - $cec_hugepage .= $tmp; - $index++; - } elsif($v =~ /(Configurable huge page memory\(in pages\):)\s*(\d+)/i){ - my $tmp = sprintf "%-40s %s;\n", $1, $2; - $cec_hugepage .= $tmp; - $index++; - } elsif($v =~ /(Page Size\(in GB\):)\s*(\d+)/i) { - my $tmp = sprintf "%-40s %s;\n", $1, $2; - $cec_hugepage .= $tmp; - $index++; - } elsif($v =~ /(Maximum huge page memory\(in pages\):)\s*(\d+)/i) { - my $tmp = sprintf "%-40s %s;\n", $1, $2; - $cec_hugepage .= $tmp; - $index++; - } elsif($v =~ /(Requested huge page memory\(in pages\):)\s*(\d+)/i) { - my $tmp = sprintf "%-40s %s;\n", $1, $2; - $cec_hugepage .= $tmp; - $index++; - } - } - if ($index != 5) { - return undef; - } - return $cec_hugepage; + my $name = shift; + my $huge_info = shift; + my $index = 0; + my @value = split(/\n/, $huge_info); + my $cec_hugepage = ""; + foreach my $v (@value) { + if ($v =~ /(Available huge page memory\(in pages\):)\s*(\d+)/i) { + my $tmp = sprintf "%-40s %s;\n", $1, $2; + $cec_hugepage .= $tmp; + $index++; + } elsif ($v =~ /(Configurable huge page memory\(in pages\):)\s*(\d+)/i) { + my $tmp = sprintf "%-40s %s;\n", $1, $2; + $cec_hugepage .= $tmp; + $index++; + } elsif ($v =~ /(Page Size\(in GB\):)\s*(\d+)/i) { + my $tmp = sprintf "%-40s %s;\n", $1, $2; + $cec_hugepage .= $tmp; + $index++; + } elsif ($v =~ /(Maximum huge page memory\(in pages\):)\s*(\d+)/i) { + my $tmp = sprintf "%-40s %s;\n", $1, $2; + $cec_hugepage .= $tmp; + $index++; + } elsif ($v =~ /(Requested huge page memory\(in pages\):)\s*(\d+)/i) { + my $tmp = sprintf "%-40s %s;\n", $1, $2; + $cec_hugepage .= $tmp; + $index++; + } + } + if ($index != 5) { + return undef; + } + return $cec_hugepage; } ########################################################################## @@ -1275,50 +1299,52 @@ sub list { my $args = $request->{opt}; my $values = (); my @value = (); - my $node_name; + my $node_name; my $d; my @result; my $lpar_infos; my $bsr_infos; my $huge_infos; my %lpar_huges = (); - my $l_string = "\n"; - #print Dumper($hash); + my $l_string = "\n"; + + #print Dumper($hash); xCAT::MsgUtils->verbose_message($request, "lsvm START"); - while (my ($mtms,$h) = each(%$hash) ) { - my $info = enumerate($request, $h, $mtms ); - my $Rc = shift(@$info); - my $data = @$info[0]; - - while (($node_name,$d) = each(%$h) ) { - my $cec = @$d[3]; - my $type = @$d[4]; - + while (my ($mtms, $h) = each(%$hash)) { + my $info = enumerate($request, $h, $mtms); + my $Rc = shift(@$info); + my $data = @$info[0]; + + while (($node_name, $d) = each(%$h)) { + my $cec = @$d[3]; + my $type = @$d[4]; + my $id = @$d[0]; - - if ( $Rc != SUCCESS ) { - push @result, [$node_name, $data,$Rc]; - next; - } + + if ($Rc != SUCCESS) { + push @result, [ $node_name, $data, $Rc ]; + next; + } my $values = $data->{0}; - my $msg = $data->{1}; - - # if ( !exists( $data->{$id} )) { - # push @result, [$node_name, "Node not found",1]; - # next; - # } - xCAT::MsgUtils->verbose_message($request, "lsvm :parse io info for node:$node_name."); - if( defined($msg)) { - push @result,[$node_name, $msg, 0]; + my $msg = $data->{1}; + + # if ( !exists( $data->{$id} )) { + # push @result, [$node_name, "Node not found",1]; + # next; + # } + xCAT::MsgUtils->verbose_message($request, "lsvm :parse io info for node:$node_name."); + if (defined($msg)) { + push @result, [ $node_name, $msg, 0 ]; } else { - # get the I/O slot information - if($request->{opt}->{l}) { - if ($type =~ /^(fsp|cec)$/) { - $bsr_infos = get_cec_attr_info($request, $node_name, $d, "bsr"); - if (ref($bsr_infos) eq 'ARRAY') { - return $bsr_infos; - } - $huge_infos = get_cec_attr_info($request,$node_name, $d, "huge_page"); + + # get the I/O slot information + if ($request->{opt}->{l}) { + if ($type =~ /^(fsp|cec)$/) { + $bsr_infos = get_cec_attr_info($request, $node_name, $d, "bsr"); + if (ref($bsr_infos) eq 'ARRAY') { + return $bsr_infos; + } + $huge_infos = get_cec_attr_info($request, $node_name, $d, "huge_page"); if (ref($huge_infos) eq 'ARRAY') { return $huge_infos; } @@ -1327,30 +1353,30 @@ sub list { if (ref($lpar_infos) eq 'ARRAY') { return $lpar_infos; } - } + } my $v; - my @t; + my @t; my @value = split(/\n/, $values); foreach my $v (@value) { - my ($lparid, @t ) = split (/,/, $v); - my $ios = join('/', @t); + my ($lparid, @t) = split(/,/, $v); + my $ios = join('/', @t); if ($request->{opt}->{l}) { my $lparname = get_cec_lpar_name($node_name, $lpar_infos, $lparid); my $hugepage; if ($type =~ /^(fsp|cec)$/) { - my $lpar_bsr = get_cec_lpar_bsr($node_name, $bsr_infos, $lparid, $lparname); - if (ref($lpar_bsr) eq 'ARRAY') { - return $lpar_bsr; - } - $ios .= ": ".$lpar_bsr; + my $lpar_bsr = get_cec_lpar_bsr($node_name, $bsr_infos, $lparid, $lparname); + if (ref($lpar_bsr) eq 'ARRAY') { + return $lpar_bsr; + } + $ios .= ": " . $lpar_bsr; $hugepage = get_cec_lpar_hugepage($node_name, $huge_infos, $lparid, $lparname); if (ref($hugepage) eq 'ARRAY') { return $hugepage; } } else { - if ($lparid ne $id) { - next; - } + if ($lparid ne $id) { + next; + } if (defined($lpar_huges{$lparid})) { $hugepage = $lpar_huges{$lparid}; } else { @@ -1360,48 +1386,48 @@ sub list { } $lpar_huges{$lparid} = $hugepage; } - } - $ios .= ": ".$hugepage; + } + $ios .= ": " . $hugepage; if (ref($lparname) eq 'ARRAY') { return $lparname; } else { $lparname = "$lparname: $lparid"; } - $l_string .= "$lparname: ".$ios."\n"; + $l_string .= "$lparname: " . $ios . "\n"; } else { - if ($type=~/^(fsp|cec)$/) { - push @result,[$lparid, $ios, $Rc]; + if ($type =~ /^(fsp|cec)$/) { + push @result, [ $lparid, $ios, $Rc ]; } else { - if( $lparid eq $id) { - push @result,[$lparid, $ios, $Rc]; + if ($lparid eq $id) { + push @result, [ $lparid, $ios, $Rc ]; } } } - } + } } - - # get the octant configuration value - if ($type=~/^(fsp|cec)$/) { - xCAT::MsgUtils->verbose_message($request, "lsvm :parse octant info for $type:$node_name."); + + # get the octant configuration value + if ($type =~ /^(fsp|cec)$/) { + xCAT::MsgUtils->verbose_message($request, "lsvm :parse octant info for $type:$node_name."); my $value = $data->{$cec}; - if ($request->{opt}->{l}) { - my $cec_bsr = get_cec_cec_bsr($node_name, $bsr_infos); - my $cec_hugepage = get_cec_cec_hugepage($node_name, $huge_infos); - $l_string .= $value.$cec_bsr; - $l_string .= $cec_hugepage; - } else { + if ($request->{opt}->{l}) { + my $cec_bsr = get_cec_cec_bsr($node_name, $bsr_infos); + my $cec_hugepage = get_cec_cec_hugepage($node_name, $huge_infos); + $l_string .= $value . $cec_bsr; + $l_string .= $cec_hugepage; + } else { $l_string = $value; - } - } + } + } if ($l_string =~ /^\n$/) { next; } - push @result, [$node_name, $l_string, $Rc]; - $l_string = "\n"; - } # end of while - }# end of while + push @result, [ $node_name, $l_string, $Rc ]; + $l_string = "\n"; + } # end of while + } # end of while xCAT::MsgUtils->verbose_message($request, "lsvm END."); - return( \@result ); + return (\@result); } @@ -1416,12 +1442,12 @@ sub list_orig { my $args = $request->{opt}; my $values = (); my @value = (); - my $node_name; + my $node_name; my $d; my @result; - while (my ($mtms,$h) = each(%$hash) ) { - while (($node_name,$d) = each(%$h) ) { + while (my ($mtms, $h) = each(%$hash)) { + while (($node_name, $d) = each(%$h)) { my $lparid = @$d[0]; my $mtms = @$d[2]; my $type = @$d[4]; @@ -1430,50 +1456,53 @@ sub list_orig { #################################### # Must be CEC or LPAR #################################### - if ( $type !~ /^(lpar|fsp|cec)$/ ) { - #$values->{$lpar} = [$lpar,"Node must be LPAR or CEC",RC_ERROR]; - return ( [$node_name,"Node must be LPAR or CEC",RC_ERROR]); - #next; + if ($type !~ /^(lpar|fsp|cec)$/) { + + #$values->{$lpar} = [$lpar,"Node must be LPAR or CEC",RC_ERROR]; + return ([ $node_name, "Node must be LPAR or CEC", RC_ERROR ]); + + #next; } - + #################################### # This is a single LPAR #################################### - if ( $type eq "lpar" ) { - #$lpars[0] = "$lpar,$lparid"; + if ($type eq "lpar") { + + #$lpars[0] = "$lpar,$lparid"; } #################################### # This is a CEC #################################### else { - my $values = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "query_octant_cfg"); - my $Rc = @$values[2]; - my $data = @$values[1]; - if ( $Rc != SUCCESS ) { - push @result, [$node_name,$data,$Rc]; - } else { - my @value = split(/,/, $data); - my $pendingpumpmode = $value[0]; - my $currentpumpMode = $value[1]; - my $octantcount = $value[2]; - my $j = 3; - my $res = "PendingPumpMode=$pendingpumpmode,CurrentPumpMode=$currentpumpMode,OctantCount=$octantcount:"; - for(my $i=0; $i < $octantcount; $i++) { - $res = $res."OctantID=".$value[$j++].",PendingOctCfg=".$value[$j++].",CurrentOctCfg=".$value[$j++].",PendingMemoryInterleaveMode=".$value[$j++].",CurrentMemoryInterleaveMode".$value[$j++].";"; - } - push @result,[$node_name, $res, $Rc]; - } + my $values = xCAT::FSPUtils::fsp_api_action($request, $node_name, $d, "query_octant_cfg"); + my $Rc = @$values[2]; + my $data = @$values[1]; + if ($Rc != SUCCESS) { + push @result, [ $node_name, $data, $Rc ]; + } else { + my @value = split(/,/, $data); + my $pendingpumpmode = $value[0]; + my $currentpumpMode = $value[1]; + my $octantcount = $value[2]; + my $j = 3; + my $res = "PendingPumpMode=$pendingpumpmode,CurrentPumpMode=$currentpumpMode,OctantCount=$octantcount:"; + for (my $i = 0 ; $i < $octantcount ; $i++) { + $res = $res . "OctantID=" . $value[ $j++ ] . ",PendingOctCfg=" . $value[ $j++ ] . ",CurrentOctCfg=" . $value[ $j++ ] . ",PendingMemoryInterleaveMode=" . $value[ $j++ ] . ",CurrentMemoryInterleaveMode" . $value[ $j++ ] . ";"; + } + push @result, [ $node_name, $res, $Rc ]; + } } - } + } } - return( \@result ); + return (\@result); } ########################################################################## -# Creates/changes logical partitions +# Creates/changes logical partitions ########################################################################## sub create { @@ -1489,128 +1518,133 @@ sub create { my $type; my $profile; my $starting_lpar_id = $opt->{i}; - my $octant_cfg = $opt->{octant_cfg}; - my $node_number =@{$opt->{target}}; - my %node_id = (); - my @nodes = @{$opt->{target}}; - - xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); - #print Dumper($request); + my $octant_cfg = $opt->{octant_cfg}; + my $node_number = @{ $opt->{target} }; + my %node_id = (); + my @nodes = @{ $opt->{target} }; + + xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); + + #print Dumper($request); ##################################### # Get source node information ##################################### - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($name,$data) = each(%$h) ) { - $d = $data; - $lparid = @$d[0]; - $mtms = @$d[2]; - $type = @$d[4]; + while (my ($cec, $h) = each(%$hash)) { + while (my ($name, $data) = each(%$h)) { + $d = $data; + $lparid = @$d[0]; + $mtms = @$d[2]; + $type = @$d[4]; $cec_name = $name; ##################################### - # Must be LPAR + # Must be LPAR ##################################### - if ( $type !~ /^(fsp|cec)$/ ) { - return( [[$cec_name,"Node's parent must be fsp or CEC",RC_ERROR]] ); + if ($type !~ /^(fsp|cec)$/) { + return ([ [ $cec_name, "Node's parent must be fsp or CEC", RC_ERROR ] ]); } } - - xCAT::MsgUtils->verbose_message($request, "$request->{command} :query_octant_cfg for CEC:$cec_name."); - my $values = xCAT::FSPUtils::fsp_api_action ($request, $cec_name, $d, "query_octant_cfg"); - my $Rc = shift(@$values); - if ( $Rc != 0 ) { - return( [[$cec_name,$$values[0],$Rc]] ); - } - my @v = split(/:/, $$values[0]); - $octant_cfg->{pendingpumpmode} = $v[0]; - - my $number_of_lpars_per_octant; + xCAT::MsgUtils->verbose_message($request, "$request->{command} :query_octant_cfg for CEC:$cec_name."); + my $values = xCAT::FSPUtils::fsp_api_action($request, $cec_name, $d, "query_octant_cfg"); + my $Rc = shift(@$values); + if ($Rc != 0) { + return ([ [ $cec_name, $$values[0], $Rc ] ]); + } + my @v = split(/:/, $$values[0]); + $octant_cfg->{pendingpumpmode} = $v[0]; + + + my $number_of_lpars_per_octant; my $octant_num_needed; my $starting_octant_id; my $octant_conf_value; - my $octant_cfg_value = $octant_cfg->{octant_cfg_value}; + my $octant_cfg_value = $octant_cfg->{octant_cfg_value}; my $new_pending_interleave_mode = $octant_cfg->{memory_interleave}; - - $starting_octant_id = int($starting_lpar_id/4); - my $lparnum_from_octant = 0; + + $starting_octant_id = int($starting_lpar_id / 4); + my $lparnum_from_octant = 0; my $new_pending_pump_mode = $octant_cfg->{pendingpumpmode}; my $parameters; + #my $parameters = "$new_pending_pump_mode:$octant_num_needed"; - my $octant_id = $starting_octant_id ; - my $i = 0; + my $octant_id = $starting_octant_id; + my $i = 0; my $res; - for($i=0; $i < (keys %$octant_cfg_value) ; $i++) { - if(! exists($octant_cfg_value->{$octant_id})) { - $res = "starting LPAR id is $starting_lpar_id, starting octant id is $starting_octant_id. The octants should be used continuously. Octant $octant_id configuration value isn't provided. Wrong plan."; - return ([[$cec_name, $res, -1]]); + for ($i = 0 ; $i < (keys %$octant_cfg_value) ; $i++) { + if (!exists($octant_cfg_value->{$octant_id})) { + $res = "starting LPAR id is $starting_lpar_id, starting octant id is $starting_octant_id. The octants should be used continuously. Octant $octant_id configuration value isn't provided. Wrong plan."; + return ([ [ $cec_name, $res, -1 ] ]); } - my $octant_conf_value = $octant_cfg_value->{$octant_id}; + my $octant_conf_value = $octant_cfg_value->{$octant_id}; + #octant configuration values could be 1,2,3,4,5 ; AS following: # 1 - 1 partition with all cpus and memory of the octant # 2 - 2 partitions with a 50/50 split of cpus and memory # 3 - 3 partitions with a 25/25/50 split of cpus and memory # 4 - 4 partitions with a 25/25/25/25 split of cpus and memory # 5 - 2 partitions with a 25/75 split of cpus and memory - if($octant_conf_value == 1) { - $number_of_lpars_per_octant = 1; - } elsif($octant_conf_value == 2 ) { - $number_of_lpars_per_octant = 2; - } elsif($octant_conf_value == 3 ) { - $number_of_lpars_per_octant = 3; - } elsif($octant_conf_value == 4 ) { - $number_of_lpars_per_octant = 4; - } elsif($octant_conf_value == 5 ) { - $number_of_lpars_per_octant = 2; + if ($octant_conf_value == 1) { + $number_of_lpars_per_octant = 1; + } elsif ($octant_conf_value == 2) { + $number_of_lpars_per_octant = 2; + } elsif ($octant_conf_value == 3) { + $number_of_lpars_per_octant = 3; + } elsif ($octant_conf_value == 4) { + $number_of_lpars_per_octant = 4; + } elsif ($octant_conf_value == 5) { + $number_of_lpars_per_octant = 2; } else { $res = "octant $i, configuration values: $octant_conf_value. Wrong octant configuration values!\n"; - return ([[$cec_name, $res, -1]]); - } + return ([ [ $cec_name, $res, -1 ] ]); + } my $j; - for($j = 1; $j < $number_of_lpars_per_octant+1 ; $j++) { - if(@nodes) { + for ($j = 1 ; $j < $number_of_lpars_per_octant + 1 ; $j++) { + if (@nodes) { my $node = shift(@nodes); $node_id{$node} = $j + $octant_id * 4; } } - $lparnum_from_octant += $number_of_lpars_per_octant; - $octant_num_needed++; - $parameters .= ":$octant_id:$octant_conf_value:$new_pending_interleave_mode"; - $octant_id++; - - } - $parameters = "$new_pending_pump_mode:$octant_num_needed".$parameters; - ##if($node_number != $lparnum_from_octant ) {## - if($node_number > $lparnum_from_octant ) { - $res = "According to the partition split rule and the starting LPAR id, $lparnum_from_octant LPARs will be gotten. But the noderange has $node_number node. Wrong plan.\n"; - return ([[$cec_name, $res, -1]]); + $lparnum_from_octant += $number_of_lpars_per_octant; + $octant_num_needed++; + $parameters .= ":$octant_id:$octant_conf_value:$new_pending_interleave_mode"; + $octant_id++; + + } + $parameters = "$new_pending_pump_mode:$octant_num_needed" . $parameters; + ##if($node_number != $lparnum_from_octant ) {## + if ($node_number > $lparnum_from_octant) { + $res = "According to the partition split rule and the starting LPAR id, $lparnum_from_octant LPARs will be gotten. But the noderange has $node_number node. Wrong plan.\n"; + return ([ [ $cec_name, $res, -1 ] ]); } - - - xCAT::MsgUtils->verbose_message($request, "$request->{command} :set_octant_cfg for CEC:$cec_name,param:$parameters."); - #$values = xCAT::FSPUtils::fsp_api_create_parttion( $starting_lpar_id, $octant_cfg, $node_number, $d, "set_octant_cfg"); - $values = xCAT::FSPUtils::fsp_api_action ($request,$cec_name, $d, "set_octant_cfg", 0, $parameters); - my $Rc = $$values[2]; - my $data = $$values[1]; - if ( $Rc != SUCCESS ) { - push @result, [$cec_name,$data,$Rc]; + + + xCAT::MsgUtils->verbose_message($request, "$request->{command} :set_octant_cfg for CEC:$cec_name,param:$parameters."); + + #$values = xCAT::FSPUtils::fsp_api_create_parttion( $starting_lpar_id, $octant_cfg, $node_number, $d, "set_octant_cfg"); + $values = xCAT::FSPUtils::fsp_api_action($request, $cec_name, $d, "set_octant_cfg", 0, $parameters); + my $Rc = $$values[2]; + my $data = $$values[1]; + if ($Rc != SUCCESS) { + push @result, [ $cec_name, $data, $Rc ]; } else { - foreach my $name ( @{$opt->{target}} ) { - push @result, [$name,"Success", $Rc]; - xCAT::FSPvm::xCATdB("mkvm", $name, "",$node_id{$name}, $d, "fsp", $name ); + foreach my $name (@{ $opt->{target} }) { + push @result, [ $name, "Success", $Rc ]; + xCAT::FSPvm::xCATdB("mkvm", $name, "", $node_id{$name}, $d, "fsp", $name); } - push @result, [$cec_name,"Please reboot the CEC $cec_name before using chvm to assign the I/O slots to the LPARs", "mkvm"]; - #$request->{callback}->({info => ["Please reboot the CEC $cec_name before using chvm to assign the I/O slots to the LPARs"]}); - } - + push @result, [ $cec_name, "Please reboot the CEC $cec_name before using chvm to assign the I/O slots to the LPARs", "mkvm" ]; + + #$request->{callback}->({info => ["Please reboot the CEC $cec_name before using chvm to assign the I/O slots to the LPARs"]}); + } + } - - xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); - return( \@result ); + + xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); + return (\@result); } @@ -1629,85 +1663,85 @@ sub xCATdB { my $parent = shift; ####################################### - # Remove entry + # Remove entry ####################################### - if ( $cmd eq "rmvm" ) { - return( xCAT::PPCdb::rm_ppc( $name )); + if ($cmd eq "rmvm") { + return (xCAT::PPCdb::rm_ppc($name)); } ####################################### - # Change entry + # Change entry ####################################### - elsif ( $cmd eq "chvm" ) { - my $ppctab = xCAT::Table->new( "ppc", -create=>1, -autocommit=>1 ); + elsif ($cmd eq "chvm") { + my $ppctab = xCAT::Table->new("ppc", -create => 1, -autocommit => 1); ################################### # Error opening ppc database ################################### - if ( !defined( $ppctab )) { - return( "Error opening 'ppc' database" ); + if (!defined($ppctab)) { + return ("Error opening 'ppc' database"); } - $ppctab->setNodeAttribs( $name, {pprofile=>$profile} ); + $ppctab->setNodeAttribs($name, { pprofile => $profile }); } ####################################### - # Add entry + # Add entry ####################################### else { - if ( !defined( $profile )) { + if (!defined($profile)) { $profile = $name; } - my ($model,$serial) = split /\*/,@$d[2]; - my $server = @$d[3]; - my $fsp = @$d[2]; - - ################################### + my ($model, $serial) = split /\*/, @$d[2]; + my $server = @$d[3]; + my $fsp = @$d[2]; + + ################################### # Find FSP name in ppc database ################################### - my $tab = xCAT::Table->new( "ppc" ); + my $tab = xCAT::Table->new("ppc"); ################################### # Error opening ppc database ################################### - if ( !defined( $tab )) { - return( "Error opening 'ppc' database" ); + if (!defined($tab)) { + return ("Error opening 'ppc' database"); } ################################### # If there is no parent provided - # this lpar should be the cloned + # this lpar should be the cloned # in the same cec - # Otherwise it should be cloned + # Otherwise it should be cloned # between cecs ################################### - if ( ! $parent) + if (!$parent) { - my ($ent) = $tab->getNodeAttribs($lpar, ['parent'] ); + my ($ent) = $tab->getNodeAttribs($lpar, ['parent']); ################################### - # Node not found + # Node not found ################################### - if ( !defined( $ent )) { - return( "'$lpar' not found in 'ppc' database" ); + if (!defined($ent)) { + return ("'$lpar' not found in 'ppc' database"); } ################################### - # Attributes not found + # Attributes not found ################################### - if ( !exists( $ent->{parent} )) { - return( "'parent' attribute not found in 'ppc' database" ); + if (!exists($ent->{parent})) { + return ("'parent' attribute not found in 'ppc' database"); } $parent = $ent->{parent}; } - my $values = join( ",", - "lpar", - $name, - $lparid, - $model, - $serial, - "", - $server, - $profile, - $parent ); - - return( xCAT::PPCdb::add_ppc( $hwtype, [$values],'','',"FSP" )); + my $values = join(",", + "lpar", + $name, + $lparid, + $model, + $serial, + "", + $server, + $profile, + $parent); + + return (xCAT::PPCdb::add_ppc($hwtype, [$values], '', '', "FSP")); } return undef; } @@ -1719,10 +1753,10 @@ sub xCATdB { my @partition_query_actions = qw(part_get_partition_cap part_get_hyp_process_and_mem part_get_all_io_bus_info get_huge_page get_cec_bsr); sub parse_part_get_info { - my $hash = shift; - my $data = shift; + my $hash = shift; + my $data = shift; my $lparid = shift; - my @array = split /\n/, $data; + my @array = split /\n/, $data; foreach my $line (@array) { chomp($line); if ($line =~ /Num of lpar slots: (\d+)/i) { @@ -1735,30 +1769,34 @@ sub parse_part_get_info { $hash->{mem_region_size} = $1; } elsif ($line =~ /HYP Configurable Processors: (\d+),\s*Avail Processors: (\d+)/i) { $hash->{process_units_config} = $1; - $hash->{process_units_avail} = $2; + $hash->{process_units_avail} = $2; } elsif ($line =~ /Authority Lpar id:(\w+)/i) { $hash->{service_lparid} = $1; } elsif ($line =~ /(\d+),(\d+),[^,]*,(\w+),\w*\(([\w| |-|_|\/]*)\)/) { $hash->{bus}->{$3}->{cur_lparid} = $1; - $hash->{bus}->{$3}->{bus_slot} = $2; - $hash->{bus}->{$3}->{des} = $4; + $hash->{bus}->{$3}->{bus_slot} = $2; + $hash->{bus}->{$3}->{des} = $4; if ($lparid and $lparid eq $1) { - push @{$hash->{lpar_phy_bus}}, $3; + push @{ $hash->{lpar_phy_bus} }, $3; } } elsif ($line =~ /Phy drc_index:(\w+), Port group: (\w+), Phy port id: (\w+)/) { $hash->{phy_drc_group_port}->{$1}->{$2}->{$3} = '1'; - #} elsif ($line =~ /adapter_id=(\w+),lpar_id=([\d|-]+).*port_group=(\d+),phys_port_id=(\d+).*drc_index=(\w+),.*/) { + + #} elsif ($line =~ /adapter_id=(\w+),lpar_id=([\d|-]+).*port_group=(\d+),phys_port_id=(\d+).*drc_index=(\w+),.*/) { if (($2 == -1) && ($4 == 255)) { $hash->{logic_drc_phydrc}->{$3}->{$5} = $1; + #$hash->{logic_drc_phydrc}->{$5}->{$1} = [$2,$3,$4]; } - #} elsif ($line =~ /lpar 0:: Curr Memory::min: 1,cur: (\d+),max:/i) { + + #} elsif ($line =~ /lpar 0:: Curr Memory::min: 1,cur: (\d+),max:/i) { } elsif ($line =~ /HYP Reserved Memory Regions:([-]?)(\d+), Min Required Regions:(\d+)/i) { if ($1 eq '-') { $hash->{lpar0_used_dec} = 1; } - $hash->{lpar0_used_mem} = $2; + $hash->{lpar0_used_mem} = $2; $hash->{phy_min_mem_req} = $3; + #print "===>lpar0_used_mem:$hash->{lpar0_used_mem}.\n"; } elsif ($line =~ /Curr Memory (Min|Req|Max):\s*([\d]*)[^\(]*\((\d+)\s*regions\)/) { if ($1 eq 'Min') { @@ -1766,7 +1804,7 @@ sub parse_part_get_info { } elsif ($1 eq 'Max') { $hash->{lpar_mem_max} = $2; } else { - $hash->{lpar_mem_req} = $2; + $hash->{lpar_mem_req} = $2; $hash->{lpar_used_regions} = $3; } } elsif ($line =~ /Curr Processor (Min|Req|Max):\s*(\d+)/) { @@ -1781,7 +1819,7 @@ sub parse_part_get_info { if ($3 eq '0') { my $lparid = hex($4); my $slotid = hex($5); - push @{$hash->{lpar_vmstorage_client}}, "$lparid:$slotid"; + push @{ $hash->{lpar_vmstorage_client} }, "$lparid:$slotid"; } else { if (exists($hash->{lpar_vmstorage_server})) { $hash->{lpar_vmstorage_server}++; @@ -1790,45 +1828,48 @@ sub parse_part_get_info { } } } elsif ($line =~ /\s*lpar_id=(\d+),type=(vEth),slot=(\d+).*port_vlan_id=(\d+),mac_addr=(\w+)/) { - push @{$hash->{lpar_vmnics}}, "vlan$4"; + push @{ $hash->{lpar_vmnics} }, "vlan$4"; } elsif ($line =~ /Available huge page memory\(in pages\):\s*(\d+)/) { $hash->{huge_page_avail} = $1; } elsif ($line =~ /Available BSR array:\s*(\d+)/) { $hash->{cec_bsr_avail} = $1; } elsif ($line =~ /^\d+\/(\d+)\/\d+$/) { if ($1 ne 0) { - push @{$hash->{lpar_othersetting}}, "hugepage:$1"; + push @{ $hash->{lpar_othersetting} }, "hugepage:$1"; } } elsif ($line =~ /^(\d+)\.$/) { if ($1 ne 0) { - push @{$hash->{lpar_othersetting}}, "bsr:$1"; + push @{ $hash->{lpar_othersetting} }, "bsr:$1"; } } } } sub query_cec_info_actions { - my $request = shift; - my $name = shift; - my $td = shift; - my $usage = shift; + my $request = shift; + my $name = shift; + my $td = shift; + my $usage = shift; my $action_array = shift; - my $lpar_hash = shift; - my $lparid = @$td[0]; + my $lpar_hash = shift; + my $lparid = @$td[0]; my $data; my @array = (); - my %hash = (); + my %hash = (); + if (!defined($action_array) or ref($action_array) ne "ARRAY") { $action_array = \@partition_query_actions; } foreach my $action (@$action_array) { - #$data .= "======> ret info for $action:\n"; + + #$data .= "======> ret info for $action:\n"; my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $td, $action); chomp(@$values[1]); + #if ($action eq "part_get_partition_cap" and (@$values[1] =~ /Error:/i or @$values[2] ne 0)) { if (@$values[1] =~ /Error:/i or @$values[2] ne 0) { - next; #return ([[@$values]]); + next; #return ([[@$values]]); } if (@$values[1] =~ /^$/) { next; @@ -1840,13 +1881,15 @@ sub query_cec_info_actions { if ($usage eq 0 or $usage eq 2) { if ($lparid) { if ($action eq "lpar_lhea_mac") { - my @output = split /\n/,@$values[1]; + my @output = split /\n/, @$values[1]; foreach my $line (@output) { if ($line =~ /adapter_id=\w+,lpar_id=$lparid,type=hea/) { + #$data .= "$line\n"; - push @array, [$name, $line, 0]; + push @array, [ $name, $line, 0 ]; } } + #$data .= "\n"; next; } @@ -1854,64 +1897,69 @@ sub query_cec_info_actions { my @output = split /\n/, @$values[1]; foreach my $line (@output) { if ($line =~ /^$lparid,/) { + #$data .= "$line\n"; - push @array, [$name, $line, 0]; + push @array, [ $name, $line, 0 ]; } } + #$data .= "\n"; next; - } + } if ($action eq "part_get_all_vio_info") { my @output = split /\n/, @$values[1]; - my ($drc_index,$drc_name); + my ($drc_index, $drc_name); foreach my $line (@output) { chomp($line); if ($line =~ /Index:.*drc_index:([^,]*),\s*drc_name:(.*)$/) { $drc_index = $1; - $drc_name = $2; + $drc_name = $2; next; } elsif ($line =~ /\s*lpar_id=(\d+),type=(vSCSI|vSerial),slot=(\d+),attr=(\d+).*remote_lpar_id=(0x\w+),remote_slot_num=(0x\w+)/) { if ($4 eq '0') { - push @array, [$name, "$1,$3,$drc_name,$drc_index,$2 Client(Server_lparid=$5,Server_slotid=$6)", 0]; + push @array, [ $name, "$1,$3,$drc_name,$drc_index,$2 Client(Server_lparid=$5,Server_slotid=$6)", 0 ]; } else { - push @array, [$name, "$1,$3,$drc_name,$drc_index,$2 Server", 0]; + push @array, [ $name, "$1,$3,$drc_name,$drc_index,$2 Server", 0 ]; } } elsif ($line =~ /\s*lpar_id=(\d+),type=(vEth),slot=(\d+).*port_vlan_id=(\d+),mac_addr=(\w+)/) { - push @array, [$name, "$1,$3,$drc_name,$drc_index,$2 (port_vlanid=$4,mac_addr=$5)", 0]; - #} elsif ($line =~ /\s*lpar_id=(\d+),type=(\w+),slot=(\d+)/) { - # push @array, [$name, "$1,$3,$drc_name,$drc_index,$2", 0]; - #} else { + push @array, [ $name, "$1,$3,$drc_name,$drc_index,$2 (port_vlanid=$4,mac_addr=$5)", 0 ]; + + #} elsif ($line =~ /\s*lpar_id=(\d+),type=(\w+),slot=(\d+)/) { + # push @array, [$name, "$1,$3,$drc_name,$drc_index,$2", 0]; + #} else { #print "=====>line:$line\n"; #push @array, [$name, $line, 0]; } $drc_index = ''; - $drc_name = ''; + $drc_name = ''; } next; } } - #$data .= "@$values[1]\n\n"; - push @array, [$name, @$values[1], @$values[2]]; - } + + #$data .= "@$values[1]\n\n"; + push @array, [ $name, @$values[1], @$values[2] ]; + } } if ($usage eq 0 or $usage eq 2) { + #return $data; if ($usage eq 2) { %$lpar_hash = %hash; } return \@array; } else { - return \%hash; + return \%hash; } } sub update_vm_db { - my $request = shift; - my $lpar_hash = shift; - my $vm_hd = xCAT::Table->new('vm'); + my $request = shift; + my $lpar_hash = shift; + my $vm_hd = xCAT::Table->new('vm'); my %name_id_map = (); - my $commit = 0; - foreach (keys (%$lpar_hash)) { + my $commit = 0; + foreach (keys(%$lpar_hash)) { my %db_update = (); my $node_hash = $lpar_hash->{$_}; if (exists($node_hash->{lpar_cpu_min})) { @@ -1924,7 +1972,7 @@ sub update_vm_db { $db_update{storage} = $node_hash->{lpar_vmstorage_server}; } elsif (exists($node_hash->{lpar_vmstorage_client})) { my @tmp_array = (); - foreach (@{$node_hash->{lpar_vmstorage_client}}) { + foreach (@{ $node_hash->{lpar_vmstorage_client} }) { if (/(\d+):(\d+)/) { if (exists($name_id_map{$1})) { push @tmp_array, "$name_id_map{$1}:$2"; @@ -1937,19 +1985,19 @@ sub update_vm_db { } } } - $db_update{storage} = join(",",@tmp_array); + $db_update{storage} = join(",", @tmp_array); } if (exists($node_hash->{lpar_vmnics})) { - $db_update{nics} = join(",",@{$node_hash->{lpar_vmnics}}); + $db_update{nics} = join(",", @{ $node_hash->{lpar_vmnics} }); } if (exists($node_hash->{lpar_phy_bus})) { - $db_update{physlots} = join(",",@{$node_hash->{lpar_phy_bus}}); + $db_update{physlots} = join(",", @{ $node_hash->{lpar_phy_bus} }); } if (exists($node_hash->{lpar_othersetting})) { - $db_update{othersettings} = join(",",@{$node_hash->{lpar_othersetting}}); + $db_update{othersettings} = join(",", @{ $node_hash->{lpar_othersetting} }); } if (%db_update) { - $vm_hd->setNodeAttribs($_,\%db_update); + $vm_hd->setNodeAttribs($_, \%db_update); $commit = 1; } } @@ -1960,49 +2008,53 @@ sub update_vm_db { #my @partition_query_actions = qw(part_get_partition_cap part_get_num_of_lpar_slots part_get_hyp_config_process_and_mem part_get_hyp_avail_process_and_mem part_get_service_authority_lpar_id part_get_shared_processing_resource part_get_all_vio_info lpar_lhea_mac part_get_all_io_bus_info part_get_lpar_processing part_get_lpar_memory get_huge_page get_cec_bsr); sub query_cec_info { - my $request = shift; - my $hash = shift; - my $args = $request->{opt}; - my @td = (); - my @result = (); - my $usage = 0; + my $request = shift; + my $hash = shift; + my $args = $request->{opt}; + my @td = (); + my @result = (); + my $usage = 0; my %lpar_hash = (); + #print Dumper($request); #print Dumper($hash); - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name, $d) = each (%$h)) { + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { my %tmp_hash = (); @td = @$d; if (@$d[0] == 0 && @$d[4] !~ /lpar|vios/) { last; } + #my $rethash = query_cec_info_actions($request, $name, $d, 0, ["part_get_lpar_processing","part_get_lpar_memory","part_get_all_vio_info","lpar_lhea_mac","part_get_all_io_bus_info","get_huge_page","get_cec_bsr"]); if ($args->{updatedb}) { $usage = 2; } - my $rethash = query_cec_info_actions($request, $name, $d, $usage, ["part_get_lpar_processing","part_get_lpar_memory","part_get_all_io_bus_info","part_get_all_vio_info","get_huge_page","get_cec_bsr"], \%tmp_hash); - #push @result, [$name, $rethash, 0]; - #push @result, @$rethash; - if (scalar (@$rethash)) { - push @result, @$rethash; - } else { - push @result, [$name, "No information got", -1]; - last; - } - $lpar_hash{$name} = \%tmp_hash; - $lpar_hash{$name}->{parent} = @$d[3]; - } - if (@td[0] == 0) { - my $rethash = query_cec_info_actions($request, @td[3],\@td, $usage); - if (scalar (@$rethash)) { + my $rethash = query_cec_info_actions($request, $name, $d, $usage, [ "part_get_lpar_processing", "part_get_lpar_memory", "part_get_all_io_bus_info", "part_get_all_vio_info", "get_huge_page", "get_cec_bsr" ], \%tmp_hash); + + #push @result, [$name, $rethash, 0]; + #push @result, @$rethash; + if (scalar(@$rethash)) { push @result, @$rethash; } else { - push @result, [@td[3], "No information got", -1]; + push @result, [ $name, "No information got", -1 ]; last; } + $lpar_hash{$name} = \%tmp_hash; + $lpar_hash{$name}->{parent} = @$d[3]; + } + if (@td[0] == 0) { + my $rethash = query_cec_info_actions($request, @td[3], \@td, $usage); + if (scalar(@$rethash)) { + push @result, @$rethash; + } else { + push @result, [ @td[3], "No information got", -1 ]; + last; + } + #push @result, [@td[3], $rethash, 0]; #push @result, @$rethash; - } + } } if ($args->{updatedb} and %lpar_hash) { update_vm_db($request, \%lpar_hash); @@ -2018,21 +2070,21 @@ my @partition_config_actions = qw/part_set_lpar_def_state part_set_lpar_pending_ sub set_lpar_undefined { my $request = shift; - my $name = shift; - my $attr = shift; - my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $attr, "part_set_lpar_def_state", 0, 0x0); + my $name = shift; + my $attr = shift; + my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $attr, "part_set_lpar_def_state", 0, 0x0); if (!@$values[2]) { - return ([$name,"Done",0]); + return ([ $name, "Done", 0 ]); } return $values; } sub clear_service_authority_lpar { my $request = shift; - my $name = shift; - my $attr = shift; + my $name = shift; + my $attr = shift; my $values = xCAT::FSPUtils::fsp_api_action($request, $name, $attr, "part_get_service_authority_lpar_id"); - my @array = split /\n/, @$values[1]; + my @array = split /\n/, @$values[1]; my $service_lparid = undef; foreach my $line (@array) { if ($line =~ /Authority Lpar id:([-|\d]+)./i) { @@ -2046,37 +2098,38 @@ sub clear_service_authority_lpar { sub remove { my $request = shift; - my $hash = shift; - my @result = (); - while (my ($mtms, $h) = each (%$hash)) { - while (my ($name, $d) = each (%$h)) { - if (@$d[4] ne "lpar") { - push @result, [$name, "Node must be LPAR", 1]; - last; - } - &clear_service_authority_lpar($request, $name, $d); - my $values = &set_lpar_undefined($request, $name, $d); - push @result, $values; + my $hash = shift; + my @result = (); + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { + if (@$d[4] ne "lpar") { + push @result, [ $name, "Node must be LPAR", 1 ]; + last; + } + &clear_service_authority_lpar($request, $name, $d); + my $values = &set_lpar_undefined($request, $name, $d); + push @result, $values; } } return \@result; } sub deal_with_avail_mem { - my $request = shift; - my $name = shift; - my $d = shift; + my $request = shift; + my $name = shift; + my $d = shift; my $lparhash = shift; my $max_required_regions; if ($lparhash->{memory} =~ /(\d+)\/(\d+)\/(\d+)/) { - my ($min,$cur,$max); + my ($min, $cur, $max); my $used_regions = 0; - my $cur_avail = 0; + my $cur_avail = 0; $min = $1; $cur = $2; $max = $3; my %tmphash; my $values; + if (exists($lparhash->{lpar_used_regions})) { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_get_lpar_memory"); &parse_part_get_info(\%tmphash, @$values[1]); @@ -2090,26 +2143,27 @@ sub deal_with_avail_mem { if ($min < $tmphash{phy_min_mem_req}) { $min = $tmphash{phy_min_mem_req}; } - + if (exists($lparhash->{lpar0_used_dec})) { - $cur_avail = $lparhash->{hyp_avail_mem} + $used_regions + $tmphash{lpar0_used_mem}; + $cur_avail = $lparhash->{hyp_avail_mem} + $used_regions + $tmphash{lpar0_used_mem}; } else { $cur_avail = $lparhash->{hyp_avail_mem} + $used_regions - $tmphash{lpar0_used_mem}; } - #xCAT::MsgUtils->verbose_message($request, "====****====used:$used_regions,avail:$cur_avail,($min:$cur:$max)."); + + #xCAT::MsgUtils->verbose_message($request, "====****====used:$used_regions,avail:$cur_avail,($min:$cur:$max)."); if ($cur_avail < $min) { my $cur_mem_in_G = $lparhash->{hyp_avail_mem} * $lparhash->{mem_region_size} * 1.0 / 1024; - return([$name, "Parse reserverd regions failed, no enough memory, available:$cur_mem_in_G GB.", 1]); - } + return ([ $name, "Parse reserverd regions failed, no enough memory, available:$cur_mem_in_G GB.", 1 ]); + } if (($cur_avail > 0) and ($cur > $cur_avail)) { my $cur_avail_in_G = $cur_avail * $lparhash->{mem_region_size} * 1.0 / 1024; $lparhash->{memory} = "$min/$cur_avail/$max"; - unless ($lparhash->{full_par}) { - return([$name, "Available memory is less than required, allocate $cur_avail_in_G GB.", 0]); - } + unless ($lparhash->{full_par}) { + return ([ $name, "Available memory is less than required, allocate $cur_avail_in_G GB.", 0 ]); + } } } else { - return ([$name, "Failed to get hypervisor reserved memory regions.", 1]); + return ([ $name, "Failed to get hypervisor reserved memory regions.", 1 ]); } } return 0; @@ -2117,9 +2171,9 @@ sub deal_with_avail_mem { sub find_lpar_id { my $request = shift; - my $parent = shift; - my $name = shift; - my %mapping = %{$request->{ppc}->{$parent}->{mapping}}; + my $parent = shift; + my $name = shift; + my %mapping = %{ $request->{ppc}->{$parent}->{mapping} }; if (exists($mapping{$name})) { return $mapping{$name}; } @@ -2128,9 +2182,9 @@ sub find_lpar_id { sub find_lpar_name { my $request = shift; - my $parent = shift; - my $id = shift; - my %mapping = %{$request->{ppc}->{$parent}->{mapping}}; + my $parent = shift; + my $id = shift; + my %mapping = %{ $request->{ppc}->{$parent}->{mapping} }; foreach (keys %mapping) { if ($mapping{$_} eq $id) { return $_; @@ -2140,11 +2194,11 @@ sub find_lpar_name { } sub create_lpar { - my $request = shift; - my $name = shift; - my $d = shift; + my $request = shift; + my $name = shift; + my $d = shift; my $lparhash = shift; - my @ret = (); + my @ret = (); my $values; if (exists($request->{opt}->{vios})) { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_def_state", 0, 0x03); @@ -2152,72 +2206,78 @@ sub create_lpar { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_def_state", 0, 0x01); } if (@$values[2] ne 0) { - return ([[$name, @$values[1], @$values[0]]]); + return ([ [ $name, @$values[1], @$values[0] ] ]); } $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_lpar_name", 0, $name); if (@$values[2] ne 0) { &set_lpar_undefined($request, $name, $d); - return ([[$name, @$values[1], @$values[0]]]); + return ([ [ $name, @$values[1], @$values[0] ] ]); } xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_shared_pool_util_auth"); xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_group_id"); xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_avail_priority"); + #print "======>physlots:$lparhash->{physlots}.\n"; if (exists($lparhash->{physlots})) { - $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_io_slot_owner_uber", 0, $lparhash->{physlots}); - #$values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_io_slot_owner", 0, join(",",@phy_io_array)); + $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_io_slot_owner_uber", 0, $lparhash->{physlots}); + + #$values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_io_slot_owner", 0, join(",",@phy_io_array)); if (@$values[2] ne 0) { &set_lpar_undefined($request, $name, $d); - return ([[$name, @$values[1], @$values[2]]]); + return ([ [ $name, @$values[1], @$values[2] ] ]); } } if (exists($lparhash->{nics})) { - my @vlans = split /,/,$lparhash->{nics}; + my @vlans = split /,/, $lparhash->{nics}; foreach (@vlans) { if (/vlan(\d+)/i) { my $vlanid = $1; - my $mac = lc(xCAT::VMCommon::genMac($name)); + my $mac = lc(xCAT::VMCommon::genMac($name)); if ($mac =~ /(..):(..):(..):(..):(..):(..)/) { - my $tail = hex($6)+$vlanid; - $mac = sprintf("$1$2$3$4$5%02x",$tail); + my $tail = hex($6) + $vlanid; + $mac = sprintf("$1$2$3$4$5%02x", $tail); } - $values = xCAT::FSPUtils::fsp_api_action($request,$name, $d, "part_set_veth_slot_config",0,"0,$vlanid,$mac"); + $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_veth_slot_config", 0, "0,$vlanid,$mac"); if (@$values[2] ne 0) { &set_lpar_undefined($request, $name, $d); - return ([[$name, @$values[1], @$values[2]]]); + return ([ [ $name, @$values[1], @$values[2] ] ]); } } } } if (exists($lparhash->{storage})) { - foreach my $v_info (@{$lparhash->{storage}}) { - $values = xCAT::FSPUtils::fsp_api_action($request,$name, $d, "part_set_vscsi_slot_config",0,$v_info); + foreach my $v_info (@{ $lparhash->{storage} }) { + $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_vscsi_slot_config", 0, $v_info); if (@$values[2] ne 0) { &set_lpar_undefined($request, $name, $d); - return ([[$name, @$values[1], @$values[2]]]); + return ([ [ $name, @$values[1], @$values[2] ] ]); } } } + # ====== ====== # if (exists($lparhash->{phy_hea})) { my $phy_hash = $lparhash->{phy_hea}; foreach my $phy_drc (keys %$phy_hash) { + #print "======> set_lhea_assign_info: drc_index:$phy_drc.\n"; xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lhea_assign_info", 0, $phy_drc); my $group_hash = $phy_hash->{$phy_drc}; foreach my $group_id (keys %$group_hash) { - my @lhea_drc = (keys %{$lparhash->{logic_drc_phydrc}->{$group_id}}); - foreach my $phy_port_id (keys %{$group_hash->{$group_id}}) { + my @lhea_drc = (keys %{ $lparhash->{logic_drc_phydrc}->{$group_id} }); + foreach my $phy_port_id (keys %{ $group_hash->{$group_id} }) { my $tmp_param = "$phy_drc,$group_id,$phy_port_id"; + #print "======> set_phea_port_info: $tmp_param.\n"; xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_phea_port_info", 0, $tmp_param); - my $tmp_lhea_param = $lhea_drc[$phy_port_id].",$phy_port_id"; + my $tmp_lhea_param = $lhea_drc[$phy_port_id] . ",$phy_port_id"; + #print "======> set_lhea_port_info: $tmp_lhea_param.\n"; xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lhea_port_info", 0, $tmp_lhea_param); } - delete ($lparhash->{logic_drc_phydrc}->{$group_id}->{$lhea_drc[0]}); - delete ($lparhash->{logic_drc_phydrc}->{$group_id}->{$lhea_drc[1]}); - } + delete($lparhash->{logic_drc_phydrc}->{$group_id}->{ $lhea_drc[0] }); + delete($lparhash->{logic_drc_phydrc}->{$group_id}->{ $lhea_drc[1] }); + } } } @@ -2225,14 +2285,14 @@ sub create_lpar { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_pending_proc", 0, $lparhash->{cpus}); if (@$values[2] ne 0) { &set_lpar_undefined($request, $name, $d); - return ([[$name, @$values[1], @$values[2]]]); + return ([ [ $name, @$values[1], @$values[2] ] ]); } - $values = &deal_with_avail_mem($request, $name, $d,$lparhash); + $values = &deal_with_avail_mem($request, $name, $d, $lparhash); if (ref($values) eq "ARRAY") { if (@$values[2]) { &set_lpar_undefined($request, $name, $d); - return ([[@$values]]); - } else { + return ([ [@$values] ]); + } else { push @ret, $values; } } @@ -2241,64 +2301,69 @@ sub create_lpar { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_pending_mem", 0, $lparhash->{memory}); if (@$values[2] ne 0) { &set_lpar_undefined($request, $name, $d); - return ([[$name, @$values[1], @$values[2]]]); + return ([ [ $name, @$values[1], @$values[2] ] ]); } - - xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_comp_modes"); + + xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_comp_modes"); + #print "======>memory:$lparhash->{huge_page}.\n"; xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_huge_page", 0, $lparhash->{huge_page}); + #print "======>bsr:$lparhash->{bsr_num}.\n"; xCAT::FSPUtils::fsp_api_action($request, $name, $d, "set_lpar_bsr", 0, $lparhash->{bsr_num}); xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_partition_placement"); - if (exists($request->{opt}->{vios})) { + if (exists($request->{opt}->{vios})) { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_def_state", 0, 0x04); } else { $values = xCAT::FSPUtils::fsp_api_action($request, $name, $d, "part_set_lpar_def_state", 0, 0x02); } if (@$values[2] ne 0) { - return ([[$name, @$values[1], @$values[2]]]); + return ([ [ $name, @$values[1], @$values[2] ] ]); } - push @ret, [$name, "Done", 0]; + push @ret, [ $name, "Done", 0 ]; + #return ([$name, "Done", 0]); return \@ret; } sub mkspeclpar { my $request = shift; - my $hash = shift; - my $opt = $request->{opt}; + my $hash = shift; + my $opt = $request->{opt}; my $values; - my @result = (); + my @result = (); my %lpar_hash = (); - my $vmtab = xCAT::Table->new( 'vm'); - unless($vmtab) { - return([["Error","Cannot open vm table", 1]]); + my $vmtab = xCAT::Table->new('vm'); + unless ($vmtab) { + return ([ [ "Error", "Cannot open vm table", 1 ] ]); } - while (my ($mtms, $h) = each (%$hash)) { + while (my ($mtms, $h) = each(%$hash)) { my $memhash = undef; - my @nodes = keys(%$h); - my $ent = $vmtab->getNodesAttribs(\@nodes, ['cpus', 'memory','physlots', 'othersettings', 'storage', 'nics']); - while (my ($name, $d) = each (%$h)) { + my @nodes = keys(%$h); + my $ent = $vmtab->getNodesAttribs(\@nodes, [ 'cpus', 'memory', 'physlots', 'othersettings', 'storage', 'nics' ]); + while (my ($name, $d) = each(%$h)) { if (@$d[4] ne 'lpar') { - push @result, [$name, "Node must be LPAR", 1]; + push @result, [ $name, "Node must be LPAR", 1 ]; last; } - #if (!exists($memhash->{run})) + + #if (!exists($memhash->{run})) #{ - my @td = @$d; - @td[0] = 0; - $memhash = &query_cec_info_actions($request, $name, \@td, 1, ["part_get_hyp_process_and_mem","lpar_lhea_mac","part_get_all_io_bus_info"]); - unless (scalar keys(%$memhash)) { - push @result, [$mtms, "Can not get hypervisor information", 1]; - last; - } - #$memhash->{run} = 1; + my @td = @$d; + @td[0] = 0; + $memhash = &query_cec_info_actions($request, $name, \@td, 1, [ "part_get_hyp_process_and_mem", "lpar_lhea_mac", "part_get_all_io_bus_info" ]); + unless (scalar keys(%$memhash)) { + push @result, [ $mtms, "Can not get hypervisor information", 1 ]; + last; + } + + #$memhash->{run} = 1; #} - + my $tmp_ent = $ent->{$name}->[0]; if (exists($opt->{vmcpus})) { $tmp_ent->{cpus} = $opt->{vmcpus}; - } + } if (exists($opt->{vmmemory})) { $tmp_ent->{memory} = $opt->{vmmemory}; } @@ -2317,39 +2382,41 @@ sub mkspeclpar { } - if (!defined($tmp_ent) ) { - return ([[$name, "Not find params", 1]]); - #} elsif (!exists($tmp_ent->{cpus}) || !exists($tmp_ent->{memory}) || !exists($tmp_ent->{physlots})) { - } elsif (!exists($tmp_ent->{cpus}) || !exists($tmp_ent->{memory})) { - return ([[$name, "The attribute 'vmcpus', 'vmmemory' are needed to be specified.", 1]]); - } - # FIX bug 3873 [FVT]DFM illegal action could work - # + if (!defined($tmp_ent)) { + return ([ [ $name, "Not find params", 1 ] ]); - if ($tmp_ent->{cpus} =~ /^(\d+)\/(\d+)\/(\d+)$/) { + #} elsif (!exists($tmp_ent->{cpus}) || !exists($tmp_ent->{memory}) || !exists($tmp_ent->{physlots})) { + } elsif (!exists($tmp_ent->{cpus}) || !exists($tmp_ent->{memory})) { + return ([ [ $name, "The attribute 'vmcpus', 'vmmemory' are needed to be specified.", 1 ] ]); + } + + # FIX bug 3873 [FVT]DFM illegal action could work + # + + if ($tmp_ent->{cpus} =~ /^(\d+)\/(\d+)\/(\d+)$/) { unless ($1 <= $2 and $2 <= $3) { - return([[$name, "Parameter for 'vmcpus' is invalid", 1]]); - } elsif ($memhash->{process_units_avail} eq '0') { - push @result, [$name, "No process available", 1]; + return ([ [ $name, "Parameter for 'vmcpus' is invalid", 1 ] ]); + } elsif ($memhash->{process_units_avail} eq '0') { + push @result, [ $name, "No process available", 1 ]; next; } elsif ($2 > $memhash->{process_units_avail}) { my $cur = $memhash->{process_units_avail}; my $min = $1 > $cur ? $cur : $1; $tmp_ent->{cpus} = "$min/$cur/$3"; - push @result, [$name, "Available processor is less than required, allocate $cur processors.", 0]; + push @result, [ $name, "Available processor is less than required, allocate $cur processors.", 0 ]; } } else { - return([[$name, "Parameter for 'vmcpus' is invalid", 1]]); + return ([ [ $name, "Parameter for 'vmcpus' is invalid", 1 ] ]); } if ($tmp_ent->{memory} =~ /^([\d|.]+)([G|M]?)\/([\d|.]+)([G|M]?)\/([\d|.]+)([G|M]?)$/i) { if ($memhash->{hyp_avail_mem} eq '0') { - push @result, [$name, "No memory available", 1]; + push @result, [ $name, "No memory available", 1 ]; next; } my ($mmin, $mcur, $mmax); if ($2 eq "G" or $2 eq '') { $mmin = $1 * 1024; - } + } if ($4 eq "G" or $4 eq '') { $mcur = $3 * 1024; } @@ -2357,40 +2424,40 @@ sub mkspeclpar { $mmax = $5 * 1024; } unless ($mmin <= $mcur and $mcur <= $mmax) { - return([[$name, "Parameter for 'vmmemory' is invalid", 1]]); + return ([ [ $name, "Parameter for 'vmmemory' is invalid", 1 ] ]); } my $memsize = $memhash->{mem_region_size}; - $mmin = int(($mmin + $memsize - 1) / $memsize); - $mcur = int(($mcur + $memsize - 1) / $memsize); - $mmax = int(($mmax + $memsize - 1) / $memsize); + $mmin = int(($mmin + $memsize - 1) / $memsize); + $mcur = int(($mcur + $memsize - 1) / $memsize); + $mmax = int(($mmax + $memsize - 1) / $memsize); $tmp_ent->{memory} = "$mmin/$mcur/$mmax"; $tmp_ent->{mem_region_size} = $memsize; } else { - return([[$name, "Parameter for 'vmmemory' is invalid", 1]]); + return ([ [ $name, "Parameter for 'vmmemory' is invalid", 1 ] ]); } - + if (exists($tmp_ent->{physlots})) { - my @tmp_array = split ",",$tmp_ent->{physlots}; + my @tmp_array = split ",", $tmp_ent->{physlots}; foreach (@tmp_array) { unless (/(0x\w{8})/i) { - return([[$name, "Parameter:$_ for 'vmphyslots' is invalid", 1]]); + return ([ [ $name, "Parameter:$_ for 'vmphyslots' is invalid", 1 ] ]); } } } if (exists($tmp_ent->{othersettings})) { - my @tmp_array = split ",",$tmp_ent->{othersettings}; + my @tmp_array = split ",", $tmp_ent->{othersettings}; foreach (@tmp_array) { unless (/^(bsr|hugepage):\d+$/) { - return([[$name, "Parameter:$_ for 'vmothersetting' is invalid", 1]]); + return ([ [ $name, "Parameter:$_ for 'vmothersetting' is invalid", 1 ] ]); } } } - + if (exists($tmp_ent->{nics})) { - my @tmp_array = split ",",$tmp_ent->{nics}; + my @tmp_array = split ",", $tmp_ent->{nics}; foreach (@tmp_array) { unless (/^vlan\d+$/i) { - return([[$name, "Parameter:$_ for 'vmnics' is invalid", 1]]); + return ([ [ $name, "Parameter:$_ for 'vmnics' is invalid", 1 ] ]); } } } @@ -2398,22 +2465,22 @@ sub mkspeclpar { if (exists($opt->{vios})) { if (!exists($tmp_ent->{physlots})) { - my @phy_io_array = keys(%{$memhash->{bus}}); - $tmp_ent->{physlots} = join(",", @phy_io_array); - } + my @phy_io_array = keys(%{ $memhash->{bus} }); + $tmp_ent->{physlots} = join(",", @phy_io_array); + } if (exists($tmp_ent->{storage}) and $tmp_ent->{storage} !~ /^\d+$/) { - return ([[$name, "Parameter for 'vmstorage' is invalid", 1]]); + return ([ [ $name, "Parameter for 'vmstorage' is invalid", 1 ] ]); } elsif (exists($tmp_ent->{storage})) { - my $num = $tmp_ent->{storage}; + my $num = $tmp_ent->{storage}; my @array = (); - for (1..$num) { + for (1 .. $num) { push @array, '0'; } $tmp_ent->{storage} = \@array; } } else { if (exists($tmp_ent->{storage})) { - my @tmp_array = split ",",$tmp_ent->{storage}; + my @tmp_array = split ",", $tmp_ent->{storage}; my $storage_array = undef; foreach (@tmp_array) { if (/([\w_-]*):(\d+)/) { @@ -2422,25 +2489,25 @@ sub mkspeclpar { if (defined($vios)) { push @$storage_array, "0,$vios,$r_slotid"; } else { - return ([[$name, "Cannot find lparid for Server lpar:$1"]]); + return ([ [ $name, "Cannot find lparid for Server lpar:$1" ] ]); } } else { - return ([[$name, "Parameter for 'vmstorage' is invalid", 1]]); + return ([ [ $name, "Parameter for 'vmstorage' is invalid", 1 ] ]); } } $tmp_ent->{storage} = $storage_array; - + } } $tmp_ent->{hyp_config_mem} = $memhash->{hyp_config_mem}; - $tmp_ent->{hyp_avail_mem} = $memhash->{hyp_avail_mem}; - if (exists($tmp_ent->{othersettings})) { + $tmp_ent->{hyp_avail_mem} = $memhash->{hyp_avail_mem}; + if (exists($tmp_ent->{othersettings})) { my $setting = $tmp_ent->{othersettings}; if ($setting =~ /hugepage:(\d+)/) { my $tmp = $1; if ($tmp >= 1) { - $tmp_ent->{huge_page} = "1/".$tmp."/".$tmp; + $tmp_ent->{huge_page} = "1/" . $tmp . "/" . $tmp; } } if ($setting =~ /bsr:(\d+)/) { @@ -2449,82 +2516,84 @@ sub mkspeclpar { } } } - $tmp_ent->{phy_hea} = $memhash->{phy_drc_group_port}; + $tmp_ent->{phy_hea} = $memhash->{phy_drc_group_port}; $tmp_ent->{logic_drc_phydrc} = $memhash->{logic_drc_phydrc}; - $values = &create_lpar($request, $name, $d, $tmp_ent); + $values = &create_lpar($request, $name, $d, $tmp_ent); push @result, @$values; + #need to add update db here - my $rethash = query_cec_info_actions($request, $name, $d, 1, ["part_get_lpar_processing","part_get_lpar_memory","part_get_all_vio_info","part_get_all_io_bus_info","get_huge_page","get_cec_bsr"]); + my $rethash = query_cec_info_actions($request, $name, $d, 1, [ "part_get_lpar_processing", "part_get_lpar_memory", "part_get_all_vio_info", "part_get_all_io_bus_info", "get_huge_page", "get_cec_bsr" ]); unless (scalar keys(%$rethash)) { - push @result, [$mtms, "Can not get hypervisor information", 1]; + push @result, [ $mtms, "Can not get hypervisor information", 1 ]; next; } - $lpar_hash{$name} = $rethash; + $lpar_hash{$name} = $rethash; $lpar_hash{$name}->{parent} = @$d[3]; $name = undef; - $d = undef; + $d = undef; } } if (%lpar_hash) { update_vm_db($request, \%lpar_hash); } - return \@result; + return \@result; } sub mkfulllpar { my $request = shift; - my $hash = shift; + my $hash = shift; my $values; my @result = (); - while (my ($mtms, $h) = each (%$hash)) { + while (my ($mtms, $h) = each(%$hash)) { my $rethash; - while (my ($name, $d) = each (%$h)) { + while (my ($name, $d) = each(%$h)) { if (@$d[4] ne 'lpar') { - push @result, [$name, "Node must be LPAR", 1]; + push @result, [ $name, "Node must be LPAR", 1 ]; last; } if (!exists($rethash->{run})) { my @td = @$d; @td[0] = 0; - $rethash = query_cec_info_actions($request, $name, \@td, 1); + $rethash = query_cec_info_actions($request, $name, \@td, 1); unless (scalar keys(%$rethash)) { - push @result, [$mtms, "Can not get hypervisor information", 1]; + push @result, [ $mtms, "Can not get hypervisor information", 1 ]; next; } - $rethash->{run} = 1; + $rethash->{run} = 1; + #print Dumper($rethash); } my %lpar_param = (); - $lpar_param{cpus} = "1/".$rethash->{process_units_avail}."/".$rethash->{process_units_config}; - $lpar_param{memory} = "1/".$rethash->{hyp_avail_mem}."/".$rethash->{hyp_config_mem}; - $lpar_param{hyp_config_mem} = $rethash->{hyp_config_mem}; - $lpar_param{hyp_avail_mem} = $rethash->{hyp_avail_mem}; + $lpar_param{cpus} = "1/" . $rethash->{process_units_avail} . "/" . $rethash->{process_units_config}; + $lpar_param{memory} = "1/" . $rethash->{hyp_avail_mem} . "/" . $rethash->{hyp_config_mem}; + $lpar_param{hyp_config_mem} = $rethash->{hyp_config_mem}; + $lpar_param{hyp_avail_mem} = $rethash->{hyp_avail_mem}; $lpar_param{mem_region_size} = $rethash->{mem_region_size}; - my @phy_io_array = keys(%{$rethash->{bus}}); + my @phy_io_array = keys(%{ $rethash->{bus} }); $lpar_param{physlots} = join(",", @phy_io_array); - $lpar_param{huge_page} = "1/".$rethash->{huge_page_avail}."/".$rethash->{huge_page_avail}; - $lpar_param{bsr_num} = $rethash->{cec_bsr_avail}; - $lpar_param{phy_hea} = $rethash->{phy_drc_group_port}; - $lpar_param{logic_drc_phydrc} = $rethash->{logic_drc_phydrc}; - $lpar_param{full_par} = 1; + $lpar_param{huge_page} = "1/" . $rethash->{huge_page_avail} . "/" . $rethash->{huge_page_avail}; + $lpar_param{bsr_num} = $rethash->{cec_bsr_avail}; + $lpar_param{phy_hea} = $rethash->{phy_drc_group_port}; + $lpar_param{logic_drc_phydrc} = $rethash->{logic_drc_phydrc}; + $lpar_param{full_par} = 1; $values = &create_lpar($request, $name, $d, \%lpar_param); $rethash->{logic_drc_phydrc} = $lpar_param{logic_drc_phydrc}; push @result, @$values; $name = undef; - $d = undef; - } + $d = undef; + } } return \@result; } ########################################################################## -# Creates logical partitions +# Creates logical partitions ########################################################################## sub mkvm { my $request = $_[0]; my $opt = $request->{opt}; - + # decide if issuing mkvm with the option '-f'. # if yes, mklpar will be invoked to # create a full system partition for each CECs managed by the HMC. @@ -2539,25 +2608,26 @@ sub mkvm { } ########################################################################## -# Change logical partition +# Change logical partition ########################################################################## sub chvm { - return( modify(@_) ); + return (modify(@_)); } ########################################################################## -# No rmvm for Power 775 +# No rmvm for Power 775 ########################################################################## -sub rmvm { +sub rmvm { my $request = $_[0]; - my $opt = $request->{opt}; + my $opt = $request->{opt}; if (exists($opt->{p775})) { - return ([["lpar","rmvm only support Power Partitioning.", 1]]); + return ([ [ "lpar", "rmvm only support Power Partitioning.", 1 ] ]); } else { - return( remove(@_) ); + return (remove(@_)); } -# return( remove(@_) ); + + # return( remove(@_) ); } ########################################################################## @@ -2567,10 +2637,10 @@ sub lsvm { my $request = shift; my $hash = shift; my $args = $request->{opt}; - if (exists($args->{p775})) { - return( list($request, $hash) ); + if (exists($args->{p775})) { + return (list($request, $hash)); } else { - return (query_cec_info($request, $hash)); + return (query_cec_info($request, $hash)); } } diff --git a/perl-xCAT/xCAT/GlobalDef.pm b/perl-xCAT/xCAT/GlobalDef.pm index 872433cb8..b953a5168 100644 --- a/perl-xCAT/xCAT/GlobalDef.pm +++ b/perl-xCAT/xCAT/GlobalDef.pm @@ -17,84 +17,87 @@ This module contains all the global info for xCAT. # valid values for nodelist.hwtype column -$::NODETYPE_LPAR="lpar"; -$::NODETYPE_BPA="bpa"; -$::NODETYPE_FSP="fsp"; -$::NODETYPE_HMC="hmc"; -$::NODETYPE_IVM="ivm"; -$::NODETYPE_FRAME="frame"; -$::NODETYPE_CEC="cec"; -$::NODETYPE_BLADE="blade"; -$::NODETYPE_CMM="cmm"; +$::NODETYPE_LPAR = "lpar"; +$::NODETYPE_BPA = "bpa"; +$::NODETYPE_FSP = "fsp"; +$::NODETYPE_HMC = "hmc"; +$::NODETYPE_IVM = "ivm"; +$::NODETYPE_FRAME = "frame"; +$::NODETYPE_CEC = "cec"; +$::NODETYPE_BLADE = "blade"; +$::NODETYPE_CMM = "cmm"; # valid values for nodelist.nodetype column -$::NODETYPE_OSI="osi"; -$::NODETYPE_PPC="ppc"; -$::NODETYPE_ZVM="zvm"; -$::NODETYPE_MP="mp"; +$::NODETYPE_OSI = "osi"; +$::NODETYPE_PPC = "ppc"; +$::NODETYPE_ZVM = "zvm"; +$::NODETYPE_MP = "mp"; #valid values for nodelist.updatestatus -$::STATUS_SYNCING="syncing"; -$::STATUS_OUT_OF_SYNC="out-of-sync"; -$::STATUS_SYNCED="synced"; -$::STATUS_FAILED="failed"; +$::STATUS_SYNCING = "syncing"; +$::STATUS_OUT_OF_SYNC = "out-of-sync"; +$::STATUS_SYNCED = "synced"; +$::STATUS_FAILED = "failed"; -# valid values for nodelist.status columns or other status -$::STATUS_ACTIVE="alive"; -$::STATUS_INACTIVE="unreachable"; -$::STATUS_INSTALLING="installing"; -$::STATUS_INSTALLED="installed"; -$::STATUS_BOOTING="booting"; -$::STATUS_NETBOOTING="netbooting"; -$::STATUS_BOOTED="booted"; -$::STATUS_POWERING_OFF="powering-off"; -$::STATUS_DISCOVERING="discovering"; -$::STATUS_CONFIGURING="configuring"; -$::STATUS_STANDING_BY="standingby"; -$::STATUS_SHELL="shell"; -$::STATUS_DEFINED="defined"; -$::STATUS_UNKNOWN="unknown"; -$::STATUS_FAILED="failed"; -$::STATUS_BMCREADY="bmcready"; +# valid values for nodelist.status columns or other status +$::STATUS_ACTIVE = "alive"; +$::STATUS_INACTIVE = "unreachable"; +$::STATUS_INSTALLING = "installing"; +$::STATUS_INSTALLED = "installed"; +$::STATUS_BOOTING = "booting"; +$::STATUS_NETBOOTING = "netbooting"; +$::STATUS_BOOTED = "booted"; +$::STATUS_POWERING_ON = "powering-on"; +$::STATUS_POWERING_OFF = "powering-off"; +$::STATUS_DISCOVERING = "discovering"; +$::STATUS_CONFIGURING = "configuring"; +$::STATUS_STANDING_BY = "standingby"; +$::STATUS_SHELL = "shell"; +$::STATUS_DEFINED = "defined"; +$::STATUS_UNKNOWN = "unknown"; +$::STATUS_FAILED = "failed"; +$::STATUS_BMCREADY = "bmcready"; %::VALID_STATUS_VALUES = ( - $::STATUS_ACTIVE=>1, - $::STATUS_INACTIVE=>1, - $::STATUS_INSTALLING=>1, - $::STATUS_INSTALLED=>1, - $::STATUS_BOOTING=>1, - $::STATUS_NETBOOTING=>1, - $::STATUS_BOOTED=>1, - $::STATUS_POWERING_OFF=>1, - $::STATUS_DISCOVERING=>1, - $::STATUS_CONFIGURING=>1, - $::STATUS_STANDING_BY=>1, - $::STATUS_SHELL=>1, - $::STATUS_DEFINED=>1, - $::STATUS_UNKNOWN=>1, - $::STATUS_FAILED=>1, - $::STATUS_BMCREADY=>1, + $::STATUS_ACTIVE => 1, + $::STATUS_INACTIVE => 1, + $::STATUS_INSTALLING => 1, + $::STATUS_INSTALLED => 1, + $::STATUS_BOOTING => 1, + $::STATUS_NETBOOTING => 1, + $::STATUS_BOOTED => 1, + $::STATUS_POWERING_ON => 1, + $::STATUS_POWERING_OFF => 1, + $::STATUS_DISCOVERING => 1, + $::STATUS_CONFIGURING => 1, + $::STATUS_STANDING_BY => 1, + $::STATUS_SHELL => 1, + $::STATUS_DEFINED => 1, + $::STATUS_UNKNOWN => 1, + $::STATUS_FAILED => 1, + $::STATUS_BMCREADY => 1, - $::STATUS_SYNCING=>1, - $::STATUS_OUT_OF_SYNC=>1, - $::STATUS_SYNCED=>1, + $::STATUS_SYNCING => 1, + $::STATUS_OUT_OF_SYNC => 1, + $::STATUS_SYNCED => 1, ); #defined->[discovering]->[configuring]->[standingby]->installing->[installed]->booting->alive, defined->[discovering]->[configuring]-[standingby]->netbooting->booted->alive, alive/unreachable->booting->alive, powering-off->unreachable, alive->unreachable -%::NEXT_NODESTAT_VAL=( - $::STATUS_DEFINED=>{$::STATUS_DISCOVERING=>1, $::STATUS_INSTALLING=>1, $::STATUS_NETBOOTING=>1, $::STATUS_POWERING_OFF=>1, $::STATUS_BOOTING=>1, $::STATUS_CONFIGURING=>1}, - $::STATUS_DISCOVERING=>{$::STATUS_INSTALLING=>1, $::STATUS_NETBOOTING=>1, $::STATUS_CONFIGURING=>1, $::STATUS_BOOTING=>1}, - $::STATUS_CONFIGURING=>{$::STATUS_INSTALLING=>1, $::STATUS_NETBOOTING=>1, $::STATUS_STANDING_BY=>1}, - $::STATUS_INSTALLING =>{$::STATUS_INSTALLED=>1, $::STATUS_BOOTING=>1}, - $::STATUS_INSTALLED =>{$::STATUS_BOOTING=>1}, - $::STATUS_BOOTING=>{$::STATUS_BOOTED=>1, $::STATUS_ACTIVE=>1, $::STATUS_INACTIVE=>1}, - $::STATUS_NETBOOTING=>{$::STATUS_BOOTED=>1}, - $::STATUS_BOOTED=>{$::STATUS_ACTIVE=>1, $::STATUS_INACTIVE=>1}, - $::STATUS_ACTIVE=>{$::STATUS_INACTIVE=>1, $::STATUS_DISCOVERING=>1, $::STATUS_CONFIGURING=>1, $::STATUS_INSTALLING=>1, $::STATUS_NETBOOTING=>1, $::STATUS_POWERING_OFF=>1, $::STATUS_BOOTING=>1}, - $::STATUS_INACTIVE=>{$::STATUS_ACTIVE=>1, $::STATUS_DISCOVERING=>1, $::STATUS_CONFIGURING=>1, $::STATUS_INSTALLING=>1, $::STATUS_NETBOOTING=>1, $::STATUS_POWERING_OFF=>1, $::STATUS_BOOTING=>1}, - $::STATUS_POWERING_OFF=>{$::STATUS_INACTIVE=>1} +%::NEXT_NODESTAT_VAL = ( + $::STATUS_DEFINED => { $::STATUS_DISCOVERING => 1, $::STATUS_INSTALLING => 1, $::STATUS_NETBOOTING => 1, $::STATUS_POWERING_OFF => 1, $::STATUS_POWERING_ON => 1, $::STATUS_BOOTING => 1, $::STATUS_CONFIGURING => 1 }, + $::STATUS_DISCOVERING => { $::STATUS_INSTALLING => 1, $::STATUS_NETBOOTING => 1, $::STATUS_CONFIGURING => 1, $::STATUS_BOOTING => 1 }, + $::STATUS_CONFIGURING => { $::STATUS_INSTALLING => 1, $::STATUS_NETBOOTING => 1, $::STATUS_STANDING_BY => 1 }, + $::STATUS_INSTALLING => { $::STATUS_INSTALLED => 1, $::STATUS_BOOTING => 1 }, + $::STATUS_INSTALLED => { $::STATUS_BOOTING => 1 }, + $::STATUS_BOOTING => { $::STATUS_BOOTED => 1, $::STATUS_ACTIVE => 1, $::STATUS_INACTIVE => 1 }, + $::STATUS_NETBOOTING => { $::STATUS_BOOTED => 1 }, + $::STATUS_BOOTED => { $::STATUS_ACTIVE => 1, $::STATUS_INACTIVE => 1 }, + $::STATUS_ACTIVE => { $::STATUS_INACTIVE => 1, $::STATUS_DISCOVERING => 1, $::STATUS_CONFIGURING => 1, $::STATUS_INSTALLING => 1, $::STATUS_NETBOOTING => 1, $::STATUS_POWERING_OFF => 1, $::STATUS_POWERING_ON => 1 }, + $::STATUS_INACTIVE => { $::STATUS_ACTIVE => 1, $::STATUS_DISCOVERING => 1, $::STATUS_CONFIGURING => 1, $::STATUS_INSTALLING => 1, $::STATUS_NETBOOTING => 1, $::STATUS_POWERING_OFF => 1, $::STATUS_POWERING_ON => 1 }, + $::STATUS_POWERING_OFF => { $::STATUS_INACTIVE => 1 }, + $::STATUS_POWERING_ON => { $::STATUS_BOOTED => 1 } ); 1; - + diff --git a/perl-xCAT/xCAT/InstUtils.pm b/perl-xCAT/xCAT/InstUtils.pm index fcad5c651..eca717056 100755 --- a/perl-xCAT/xCAT/InstUtils.pm +++ b/perl-xCAT/xCAT/InstUtils.pm @@ -10,7 +10,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -24,6 +24,7 @@ use strict; require xCAT::Schema; use xCAT::NetworkUtils; use xCAT::TableUtils; + #require Data::Dumper; #use Data::Dumper; require xCAT::NodeRange; @@ -68,10 +69,11 @@ sub getnimprime # or it is the xCAT management node. my $nimprime = xCAT::TableUtils->get_site_Master(); + #my $sitetab = xCAT::Table->new('site'); #(my $et) = $sitetab->getAttribs({key => "nimprime"}, 'value'); my @nimprimes = xCAT::TableUtils->get_site_attribute("nimprime"); - my $tmp = $nimprimes[0]; + my $tmp = $nimprimes[0]; if (defined($tmp)) { $nimprime = $tmp; @@ -115,58 +117,59 @@ sub myxCATname { my ($junk, $name); - # make sure xcatd is running - & db is available - # this routine is called during initial install of xCAT - my $cmd="lsxcatd -d > /dev/null 2>&1"; - my $outref = []; - @$outref = `$cmd`; - my $rc = $? >> 8; - if ($rc == 0) - { - if (xCAT::Utils->isMN()) - { - # read the site table, master attrib - my $hostname = xCAT::TableUtils->get_site_Master(); - if (($hostname =~ /\d+\.\d+\.\d+\.\d+/) || ($hostname =~ /:/)) - { - $name = xCAT::NetworkUtils->gethostname($hostname); - } - else - { - $name = $hostname; - } - } - elsif (xCAT::Utils->isServiceNode()) - { - my $filename; - # get any files with the format myxcatpost_* - my $lscmd = qq~/bin/ls /xcatpost/myxcatpost_* 2>/dev/null~; - my $output = `$lscmd`; - my $rc = $? >> 8; - if ($rc == 0) - { - foreach my $line ( split(/\n/, $output)) { - my ($junk, $hostname) = split('myxcatpost_', $line); - if (xCAT::InstUtils->is_me($hostname)) { - $filename="/xcatpost/myxcatpost_$hostname"; - last; - } - } + # make sure xcatd is running - & db is available + # this routine is called during initial install of xCAT + my $cmd = "lsxcatd -d > /dev/null 2>&1"; + my $outref = []; + @$outref = `$cmd`; + my $rc = $? >> 8; + if ($rc == 0) + { + if (xCAT::Utils->isMN()) + { + # read the site table, master attrib + my $hostname = xCAT::TableUtils->get_site_Master(); + if (($hostname =~ /\d+\.\d+\.\d+\.\d+/) || ($hostname =~ /:/)) + { + $name = xCAT::NetworkUtils->gethostname($hostname); + } + else + { + $name = $hostname; + } + } + elsif (xCAT::Utils->isServiceNode()) + { + my $filename; - if ( -e $filename ) { - my $catcmd = qq~/bin/cat $filename | grep '^NODE=' 2>/dev/null~; - my $string = `$catcmd`; - if ($rc == 0) { - ($junk, $name) = split('=', $string); - } - } - } - } - } + # get any files with the format myxcatpost_* + my $lscmd = qq~/bin/ls /xcatpost/myxcatpost_* 2>/dev/null~; + my $output = `$lscmd`; + my $rc = $? >> 8; + if ($rc == 0) + { + foreach my $line (split(/\n/, $output)) { + my ($junk, $hostname) = split('myxcatpost_', $line); + if (xCAT::InstUtils->is_me($hostname)) { + $filename = "/xcatpost/myxcatpost_$hostname"; + last; + } + } - if (!$name) { - $name = hostname(); - } + if (-e $filename) { + my $catcmd = qq~/bin/cat $filename | grep '^NODE=' 2>/dev/null~; + my $string = `$catcmd`; + if ($rc == 0) { + ($junk, $name) = split('=', $string); + } + } + } + } + } + + if (!$name) { + $name = hostname(); + } my $shorthost; ($shorthost = $name) =~ s/\..*$//; @@ -220,7 +223,7 @@ sub is_me # this is a common subroutine for both AIX and Linux, # AIX does not have ip command my $ipcmd; - if ( -f "/sbin/ip" ) + if (-f "/sbin/ip") { $ipcmd = "ip addr | grep 'inet'"; } @@ -231,7 +234,7 @@ sub is_me my $result = xCAT::Utils->runcmd($ipcmd, -1, 1); if ($::RUNCMD_RC != 0) { - my $str="Error running ipcmd"; + my $str = "Error running ipcmd"; xCAT::MsgUtils->message("S", $str); $::VERBOSE = $verb; return 0; @@ -241,16 +244,16 @@ sub is_me { my ($inet, $myIP, $str) = split(" ", $int); chomp $myIP; - $myIP =~ s/\/.*//; # ipv6 address 4000::99/64 - $myIP =~ s/\%.*//; # ipv6 address ::1%1/128 + $myIP =~ s/\/.*//; # ipv6 address 4000::99/64 + $myIP =~ s/\%.*//; # ipv6 address ::1%1/128 if ($myIP eq $nameIP) { - $::VERBOSE = $verb; + $::VERBOSE = $verb; return 1; } } - $::VERBOSE = $verb; + $::VERBOSE = $verb; return 0; } @@ -282,58 +285,59 @@ sub is_me sub get_nim_attrs { my $class = shift; - my $resname = shift; - my $callback = shift; - my $target = shift; - my $sub_req = shift; + my $resname = shift; + my $callback = shift; + my $target = shift; + my $sub_req = shift; - my %attrvals = undef; + my %attrvals = undef; - if (!$target) - { - $target = xCAT::InstUtils->getnimprime(); - } - chomp $target; + if (!$target) + { + $target = xCAT::InstUtils->getnimprime(); + } + chomp $target; - my $cmd = "/usr/sbin/lsnim -l $resname 2>/dev/null"; + my $cmd = "/usr/sbin/lsnim -l $resname 2>/dev/null"; - my @nout = xCAT::InstUtils->xcmd($callback, $sub_req, "xdsh", $target, $cmd, 1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not run lsnim command: \'$cmd\'.\n"; - xCAT::MsgUtils->message("E", $rsp, $callback); - return undef; - } + my @nout = xCAT::InstUtils->xcmd($callback, $sub_req, "xdsh", $target, $cmd, 1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not run lsnim command: \'$cmd\'.\n"; + xCAT::MsgUtils->message("E", $rsp, $callback); + return undef; + } - foreach my $line (@nout) { + foreach my $line (@nout) { - chomp $line; - my $junk; - my $attrval; - if ($line =~ /.*$target:(.*)/) { - ($junk, $attrval) = split(/:/, $line); - } else { - $attrval = $line; - } + chomp $line; + my $junk; + my $attrval; + if ($line =~ /.*$target:(.*)/) { + ($junk, $attrval) = split(/:/, $line); + } else { + $attrval = $line; + } - if ($attrval =~ /=/) { + if ($attrval =~ /=/) { - my ($attr, $val) = $attrval =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/; + my ($attr, $val) = $attrval =~ /^\s*(\S+?)\s*=\s*(\S*.*)$/; - if ($attr && $val) { - # $attrvals{$resname}{$attr} = $val; - $attrvals{$attr} = $val; - } - } - } + if ($attr && $val) { - if (%attrvals) { - return \%attrvals; - } else { - return undef; - } + # $attrvals{$resname}{$attr} = $val; + $attrvals{$attr} = $val; + } + } + } + + if (%attrvals) { + return \%attrvals; + } else { + return undef; + } } #---------------------------------------------------------------------------- @@ -373,7 +377,7 @@ sub get_nim_attr_val } chomp $target; - my $cmd = "/usr/sbin/lsnim -a $attrname -Z $resname 2>/dev/null"; + my $cmd = "/usr/sbin/lsnim -a $attrname -Z $resname 2>/dev/null"; my $nout = xCAT::InstUtils->xcmd($callback, $sub_req, "xdsh", $target, $cmd, 0); if ($::RUNCMD_RC != 0) @@ -442,15 +446,15 @@ sub xcmd push(@snodes, $target); $output = xCAT::Utils->runxcmd( - { - command => [$xdcmd], - node => \@snodes, - arg => ["-s", $cmd] - }, - $sub_req, - $exitcode, - $returnformat - ); + { + command => [$xdcmd], + node => \@snodes, + arg => [ "-s", $cmd ] + }, + $sub_req, + $exitcode, + $returnformat + ); } } else @@ -461,15 +465,15 @@ sub xcmd @snodes = @{$target}; $output = xCAT::Utils->runxcmd( - { - command => [$xdcmd], - node => \@snodes, - arg => ["-s", $cmd] - }, - $sub_req, - $exitcode, - $returnformat - ); + { + command => [$xdcmd], + node => \@snodes, + arg => [ "-s", $cmd ] + }, + $sub_req, + $exitcode, + $returnformat + ); } if ($returnformat == 1) { @@ -503,15 +507,15 @@ sub readBNDfile # get the location of the file from the NIM resource definition my $bnd_file_name = - xCAT::InstUtils->get_nim_attr_val($BNDname, 'location', $callback, - $nimprime, $sub_req); + xCAT::InstUtils->get_nim_attr_val($BNDname, 'location', $callback, + $nimprime, $sub_req); # The boundle file may be on nimprime my $ccmd = qq~cat $bnd_file_name~; - my $output=xCAT::InstUtils->xcmd($callback, $sub_req, "xdsh", $nimprime, $ccmd, 0); + my $output = xCAT::InstUtils->xcmd($callback, $sub_req, "xdsh", $nimprime, $ccmd, 0); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Command: $ccmd failed."; + push @{ $rsp->{data} }, "Command: $ccmd failed."; xCAT::MsgUtils->message("E", $rsp, $callback); } @@ -521,6 +525,7 @@ sub readBNDfile { #May include xdsh prefix $nimprime: $line =~ s/$nimprime:\s+//; + # skip blank and comment lines next if ($line =~ /^\s*$/ || $line =~ /^\s*#/); push(@pkglist, $line); @@ -680,14 +685,14 @@ sub getOSnodes my @linuxnodes; my $nodetab = xCAT::Table->new('nodetype'); - my $os = $nodetab->getNodesAttribs(\@nodelist, ['node', 'os']); + my $os = $nodetab->getNodesAttribs(\@nodelist, [ 'node', 'os' ]); foreach my $n (@nodelist) { my $osname; if (defined($os->{$n}->[0]->{os})) { $osname = $os->{$n}->[0]->{os}; } else { - $osname = $^O; + $osname = $^O; } if (($osname ne "AIX") && ($osname ne "aix")) { @@ -728,47 +733,47 @@ sub getOSnodes #------------------------------------------------------------------------------- sub get_server_nodes { - my $class = shift; - my $callback = shift; - my $nodes = shift; + my $class = shift; + my $callback = shift; + my $nodes = shift; - my @nodelist; - if ($nodes) + my @nodelist; + if ($nodes) { @nodelist = @$nodes; } - # + # # get the server name for each node - as known by node # - my $noderestab = xCAT::Table->new('noderes'); - my $xcatmasters = $noderestab->getNodesAttribs(\@nodelist, ['node', 'xcatmaster']); - $noderestab->close; + my $noderestab = xCAT::Table->new('noderes'); + my $xcatmasters = $noderestab->getNodesAttribs(\@nodelist, [ 'node', 'xcatmaster' ]); + $noderestab->close; - my %servernodes; + my %servernodes; foreach my $node (@nodelist) { - my $serv; + my $serv; if ($xcatmasters->{$node}->[0]->{xcatmaster}) { - # get ip of node xcatmaster attribute - my $xcatmaster = $xcatmasters->{$node}->[0]->{xcatmaster}; - $serv = xCAT::NetworkUtils->getipaddr($xcatmaster); + # get ip of node xcatmaster attribute + my $xcatmaster = $xcatmasters->{$node}->[0]->{xcatmaster}; + $serv = xCAT::NetworkUtils->getipaddr($xcatmaster); } else { # get ip facing node - my @servd= xCAT::NetworkUtils->my_ip_facing($node); - unless ($servd[0]) { $serv = $servd[1];} + my @servd = xCAT::NetworkUtils->my_ip_facing($node); + unless ($servd[0]) { $serv = $servd[1]; } } - chomp $serv; + chomp $serv; - if (xCAT::NetworkUtils->validate_ip($serv)) { - push (@{$servernodes{$serv}}, $node); - } + if (xCAT::NetworkUtils->validate_ip($serv)) { + push(@{ $servernodes{$serv} }, $node); + } } - return \%servernodes; + return \%servernodes; } #---------------------------------------------------------------------------- @@ -790,13 +795,13 @@ sub get_server_nodes #----------------------------------------------------------------------- sub dolitesetup { - my $class = shift; - my $imagename = shift; - my $imagehash = shift; - my $nodes = shift; - my $callback = shift; - my $subreq = shift; - my @litefiles; # lists of entries in the litefile table + my $class = shift; + my $imagename = shift; + my $imagehash = shift; + my $nodes = shift; + my $callback = shift; + my $subreq = shift; + my @litefiles; # lists of entries in the litefile table my %imghash; if ($imagehash) @@ -804,347 +809,351 @@ sub dolitesetup %imghash = %$imagehash; } - # get name as known by xCAT + # get name as known by xCAT my $Sname = xCAT::InstUtils->myxCATname(); chomp $Sname; - my $nimprime = xCAT::InstUtils->getnimprime(); + my $nimprime = xCAT::InstUtils->getnimprime(); my $target; if (xCAT::Utils->isSN($Sname)) { - $target=$Sname; + $target = $Sname; } else { - $target=$nimprime; + $target = $nimprime; } - my @nodelist; - my @nodel; - my @nl; + my @nodelist; + my @nodel; + my @nl; if ($nodes) { @nl = @$nodes; - foreach my $n (@nl) { - push(@nodel, xCAT::NodeRange::noderange($n)); - } + foreach my $n (@nl) { + push(@nodel, xCAT::NodeRange::noderange($n)); + } } - # - # Need to set the "provmethod" attr of the node defs or the litetree - # cmd wil not get the info we need - # + # + # Need to set the "provmethod" attr of the node defs or the litetree + # cmd wil not get the info we need + # - my %nodeattrs; + my %nodeattrs; foreach my $node (@nodel) { - chomp $node; - $nodeattrs{$node}{objtype} = 'node'; - $nodeattrs{$node}{os} = "AIX"; + chomp $node; + $nodeattrs{$node}{objtype} = 'node'; + $nodeattrs{$node}{os} = "AIX"; $nodeattrs{$node}{profile} = $imagename; $nodeattrs{$node}{provmethod} = $imagename; } - if (xCAT::DBobjUtils->setobjdefs(\%nodeattrs) != 0) + if (xCAT::DBobjUtils->setobjdefs(\%nodeattrs) != 0) { my $rsp; - push @{$rsp->{data}}, "Could not set the \'provmethod\' attribute for nodes.\n"; + push @{ $rsp->{data} }, "Could not set the \'provmethod\' attribute for nodes.\n"; xCAT::MsgUtils->message("W", $rsp, $::callback); } - # the node list is always "all" nodes. There is only one version of the - # statelite, litefile and litetree files in an image and these files - # must always contain all the info from the corresponding database - # table. - @nodelist= xCAT::DBobjUtils->getObjectsOfType('node'); - my $noderange; - if (scalar(@nodelist) > 0) - { - $noderange = join(',',@nodelist); - } else { - my $rsp; - push @{$rsp->{data}}, "Could not get list of xCAT nodes. No statelite configuration will be done.\n"; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 2; - } + # the node list is always "all" nodes. There is only one version of the + # statelite, litefile and litetree files in an image and these files + # must always contain all the info from the corresponding database + # table. + @nodelist = xCAT::DBobjUtils->getObjectsOfType('node'); + my $noderange; + if (scalar(@nodelist) > 0) + { + $noderange = join(',', @nodelist); + } else { + my $rsp; + push @{ $rsp->{data} }, "Could not get list of xCAT nodes. No statelite configuration will be done.\n"; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 2; + } - # get spot inst_root loc - my $spotloc = xCAT::InstUtils->get_nim_attr_val($imghash{$imagename}{spot}, 'location', $callback, $target, $subreq); + # get spot inst_root loc + my $spotloc = xCAT::InstUtils->get_nim_attr_val($imghash{$imagename}{spot}, 'location', $callback, $target, $subreq); - my $instrootloc = $spotloc . "/lpp/bos/inst_root"; + my $instrootloc = $spotloc . "/lpp/bos/inst_root"; - # get the statelite info - put each table into it's own file - my $statelitetab = xCAT::Table->new('statelite', -create=>1); - my $litefiletab = xCAT::Table->new('litefile'); - my $litetreetab = xCAT::Table->new('litetree'); + # get the statelite info - put each table into it's own file + my $statelitetab = xCAT::Table->new('statelite', -create => 1); + my $litefiletab = xCAT::Table->new('litefile'); + my $litetreetab = xCAT::Table->new('litetree'); - # these will wind up in the root dir on the node ("/") - my $statelitetable = "$instrootloc/statelite.table"; - my $litefiletable = "$instrootloc/litefile.table"; - my $litetreetable = "$instrootloc/litetree.table"; + # these will wind up in the root dir on the node ("/") + my $statelitetable = "$instrootloc/statelite.table"; + my $litefiletable = "$instrootloc/litefile.table"; + my $litetreetable = "$instrootloc/litetree.table"; - # get rid of any old files - if (-e $statelitetable) { - my $rc = xCAT::Utils->runcmd("rm $statelitetable", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not remove existing $statelitetable file."; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } - } + # get rid of any old files + if (-e $statelitetable) { + my $rc = xCAT::Utils->runcmd("rm $statelitetable", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not remove existing $statelitetable file."; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + } - if (-e $litefiletable) { - my $rc = xCAT::Utils->runcmd("rm $litefiletable", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not remove existing $litefiletable file."; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } - } + if (-e $litefiletable) { + my $rc = xCAT::Utils->runcmd("rm $litefiletable", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not remove existing $litefiletable file."; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + } - if (-e $litetreetable) { - my $rc = xCAT::Utils->runcmd("rm $litetreetable", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not remove existing $litetreetable file."; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } - } + if (-e $litetreetable) { + my $rc = xCAT::Utils->runcmd("rm $litetreetable", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not remove existing $litetreetable file."; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + } - # - # create files for each statelite table. add them to the SPOT. - # use the "|" as a separator, remove all blanks from the entries. - # put them in $instrootloc location. they will be available as soon - # as the root dir is mounted during the boot process. + # + # create files for each statelite table. add them to the SPOT. + # use the "|" as a separator, remove all blanks from the entries. + # put them in $instrootloc location. they will be available as soon + # as the root dir is mounted during the boot process. - my $foundstatelite=0; - unless (open(STATELITE, ">$statelitetable")) + my $foundstatelite = 0; + unless (open(STATELITE, ">$statelitetable")) { my $rsp; - push @{$rsp->{data}}, "Could not open $statelitetable.\n"; + push @{ $rsp->{data} }, "Could not open $statelitetable.\n"; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - # create the statelite table file - my $foundentry=0; - my $stateHash = $statelitetab->getNodesAttribs(\@nodelist, ['statemnt', 'mntopts']); - foreach my $node (@nodelist) { + # create the statelite table file + my $foundentry = 0; + my $stateHash = $statelitetab->getNodesAttribs(\@nodelist, [ 'statemnt', 'mntopts' ]); + foreach my $node (@nodelist) { - # process statelite entry - # add line to file for each node - # note: if statement is xcatmn:/nodedata - # /nodedata is mounted to /.statelite/persistent - # then - on node - a nodename subdir is created + # process statelite entry + # add line to file for each node + # note: if statement is xcatmn:/nodedata + # /nodedata is mounted to /.statelite/persistent + # then - on node - a nodename subdir is created - my $statemnt=""; - my $mntopts; + my $statemnt = ""; + my $mntopts; if (exists($stateHash->{$node})) { - $mntopts = $stateHash->{$node}->[0]->{mntopts}; + $mntopts = $stateHash->{$node}->[0]->{mntopts}; $statemnt = $stateHash->{$node}->[0]->{statemnt}; my ($server, $dir) = split(/:/, $statemnt); #if server is blank, then its the directory - unless($dir) { - $dir = $server; + unless ($dir) { + $dir = $server; $server = ''; } - $dir = xCAT::SvrUtils->subVars($dir, $node, 'dir', $callback); - $dir =~ s/\/\//\//g; + $dir = xCAT::SvrUtils->subVars($dir, $node, 'dir', $callback); + $dir =~ s/\/\//\//g; - if($server) { + if ($server) { $server = xCAT::SvrUtils->subVars($server, $node, 'server', $callback); - $server =~ s/\///g; # remove "/" - bug in subVars?? - my $serverIP = xCAT::NetworkUtils->getipaddr($server); - $statemnt = $serverIP . "|" . $dir; + $server =~ s/\///g; # remove "/" - bug in subVars?? + my $serverIP = xCAT::NetworkUtils->getipaddr($server); + $statemnt = $serverIP . "|" . $dir; } else { - $statemnt = $dir; - } - } + $statemnt = $dir; + } + } - my $entry = qq~$node|$statemnt~; - if ($mntopts) { - $entry = qq~$node|$statemnt|$mntopts~; - } - $entry =~ s/\s*//g; #remove blanks + my $entry = qq~$node|$statemnt~; + if ($mntopts) { + $entry = qq~$node|$statemnt|$mntopts~; + } + $entry =~ s/\s*//g; #remove blanks - if ($statemnt) { - print STATELITE $entry . "\n"; - $foundentry++; - } - } - close(STATELITE); + if ($statemnt) { + print STATELITE $entry . "\n"; + $foundentry++; + } + } + close(STATELITE); - if (!$foundentry) { - # don't leave empty file - my $rc = xCAT::Utils->runcmd("rm $statelitetable", -1); + if (!$foundentry) { + + # don't leave empty file + my $rc = xCAT::Utils->runcmd("rm $statelitetable", -1); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Could not remove $statelitetable file."; + push @{ $rsp->{data} }, "Could not remove $statelitetable file."; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - } + } - unless (open(LITEFILE, ">$litefiletable")) + unless (open(LITEFILE, ">$litefiletable")) { my $rsp; - push @{$rsp->{data}}, "Could not open $litefiletable.\n"; + push @{ $rsp->{data} }, "Could not open $litefiletable.\n"; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - my @filelist = xCAT::Utils->runcmd("/opt/xcat/bin/litefile $noderange", -1); - if (scalar(@filelist) > 0) { - foreach my $l (@filelist) { - $l =~ s/://g; # remove ":"'s - $l =~ s/\s+/|/g; # change separator to "|" - print LITEFILE $l . "\n"; - push (@litefiles, $l); - $foundstatelite++; - } - close(LITEFILE); - } else { - close(LITEFILE); - # remove empty files - my $rc = xCAT::Utils->runcmd("rm $litefiletable", -1); + my @filelist = xCAT::Utils->runcmd("/opt/xcat/bin/litefile $noderange", -1); + if (scalar(@filelist) > 0) { + foreach my $l (@filelist) { + $l =~ s/://g; # remove ":"'s + $l =~ s/\s+/|/g; # change separator to "|" + print LITEFILE $l . "\n"; + push(@litefiles, $l); + $foundstatelite++; + } + close(LITEFILE); + } else { + close(LITEFILE); + + # remove empty files + my $rc = xCAT::Utils->runcmd("rm $litefiletable", -1); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Could not remove $litefiletable file."; + push @{ $rsp->{data} }, "Could not remove $litefiletable file."; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - } - - # need list for just this set of nodes!!! - my $nrange; - my @flist; - my @litef; - if (scalar(@nodel) > 0) - { - $nrange = join(',',@nodel); } - @flist = xCAT::Utils->runcmd("/opt/xcat/bin/litefile $nrange", -1); + # need list for just this set of nodes!!! + my $nrange; + my @flist; + my @litef; + if (scalar(@nodel) > 0) + { + $nrange = join(',', @nodel); + } + + @flist = xCAT::Utils->runcmd("/opt/xcat/bin/litefile $nrange", -1); if (scalar(@flist) > 0) { foreach my $l (@flist) { - my ($j1, $j2, $file) = split /\s+/, $l; - push (@litef, $file); + my ($j1, $j2, $file) = split /\s+/, $l; + push(@litef, $file); } } - my $foundras; - if (scalar(@litef) > 0) { - foreach my $f (@litef) { - chomp $f; - if (($f eq "/var/adm/ras/") || ($f eq "/var/adm/ras/conslog")) { - $foundras++; - } - } - } - if ($foundras) { - my $rsp; - push @{$rsp->{data}}, "One or more nodes is using a persistent \/var\/adm\/ras\/ directory. \nWhen the nodes boot up you will then have to move the conslog file to a \nlocation outside of the persistent directory. (Leaving the conslog \nfile in a persistent directory can occasionally lead to a deadlock situation.) \nThis can be done by using the xdsh command to run swcons on the \ncluster nodes. \n(Ex. xdsh \'\/usr\/sbin\/swcons -p \/tmp\/conslog\') \n"; - xCAT::MsgUtils->message("W", $rsp, $callback); - } + my $foundras; + if (scalar(@litef) > 0) { + foreach my $f (@litef) { + chomp $f; + if (($f eq "/var/adm/ras/") || ($f eq "/var/adm/ras/conslog")) { + $foundras++; + } + } + } + if ($foundras) { + my $rsp; + push @{ $rsp->{data} }, "One or more nodes is using a persistent \/var\/adm\/ras\/ directory. \nWhen the nodes boot up you will then have to move the conslog file to a \nlocation outside of the persistent directory. (Leaving the conslog \nfile in a persistent directory can occasionally lead to a deadlock situation.) \nThis can be done by using the xdsh command to run swcons on the \ncluster nodes. \n(Ex. xdsh \'\/usr\/sbin\/swcons -p \/tmp\/conslog\') \n"; + xCAT::MsgUtils->message("W", $rsp, $callback); + } - unless (open(LITETREE, ">$litetreetable")) + unless (open(LITETREE, ">$litetreetable")) { my $rsp; - push @{$rsp->{data}}, "Could not open $litetreetable.\n"; + push @{ $rsp->{data} }, "Could not open $litetreetable.\n"; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - my @treelist = xCAT::Utils->runcmd("/opt/xcat/bin/litetree $noderange", -1); - if (scalar(@treelist) > 0) { - foreach my $l (@treelist) { - my ($p, $serv, $dir, $mopts) = split (/:/, $l); - $p =~ s/\s*//g; - $serv =~ s/\s*//g; - $dir =~ s/\s*//g; - $mopts =~ s/\s*//g; - my $serverIP = xCAT::NetworkUtils->getipaddr($serv); - my $entry = "$p|$serverIP|$dir|$mopts"; - print LITETREE $entry . "\n"; - $foundstatelite++; - } - close(LITETREE); - } else { - close(LITETREE); - # don't leave empty file - my $rc = xCAT::Utils->runcmd("rm $litetreetable", -1); + my @treelist = xCAT::Utils->runcmd("/opt/xcat/bin/litetree $noderange", -1); + if (scalar(@treelist) > 0) { + foreach my $l (@treelist) { + my ($p, $serv, $dir, $mopts) = split(/:/, $l); + $p =~ s/\s*//g; + $serv =~ s/\s*//g; + $dir =~ s/\s*//g; + $mopts =~ s/\s*//g; + my $serverIP = xCAT::NetworkUtils->getipaddr($serv); + my $entry = "$p|$serverIP|$dir|$mopts"; + print LITETREE $entry . "\n"; + $foundstatelite++; + } + close(LITETREE); + } else { + close(LITETREE); + + # don't leave empty file + my $rc = xCAT::Utils->runcmd("rm $litetreetable", -1); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Could not remove $litetreetable file."; + push @{ $rsp->{data} }, "Could not remove $litetreetable file."; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - } + } - # if there is no statelite info then just return - if (!$foundstatelite) { + # if there is no statelite info then just return + if (!$foundstatelite) { if ($::VERBOSE) { my $rsp; - push @{$rsp->{data}}, "Please update statlite,litefile,litetree tables if you want to use AIX statelite support.\n"; + push @{ $rsp->{data} }, "Please update statlite,litefile,litetree tables if you want to use AIX statelite support.\n"; xCAT::MsgUtils->message("I", $rsp, $callback); - } + } - return 2; - } + return 2; + } - # - # ok - do more statelite setup - # + # + # ok - do more statelite setup + # - # create some local directories in the SPOT - # create .default, .statelite, - if ( ! -d "$instrootloc/.default" ) { - my $mcmd = qq~/bin/mkdir -m 644 -p $instrootloc/.default ~; - my $output = xCAT::Utils->runcmd("$mcmd", -1); + # create some local directories in the SPOT + # create .default, .statelite, + if (!-d "$instrootloc/.default") { + my $mcmd = qq~/bin/mkdir -m 644 -p $instrootloc/.default ~; + my $output = xCAT::Utils->runcmd("$mcmd", -1); if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not create $instrootloc/.default.\n"; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } - } + { + my $rsp; + push @{ $rsp->{data} }, "Could not create $instrootloc/.default.\n"; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + } - if ( ! -d "$instrootloc/.statelite" ) { + if (!-d "$instrootloc/.statelite") { my $mcmd = qq~/bin/mkdir -m 644 -p $instrootloc/.statelite ~; my $output = xCAT::Utils->runcmd("$mcmd", -1); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Could not create $instrootloc/.statelite.\n"; + push @{ $rsp->{data} }, "Could not create $instrootloc/.statelite.\n"; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } } - # populate the .defaults dir with files and dirs from the image - if any - my $default="$instrootloc/.default"; + # populate the .defaults dir with files and dirs from the image - if any + my $default = "$instrootloc/.default"; - # read the litefile and try to copy into $default - # everything in the litefile command output should be processed + # read the litefile and try to copy into $default + # everything in the litefile command output should be processed foreach my $line (@litefiles) { + # $file could be full path file name or dir name # ex. /foo/bar/ or /etc/lppcfg - my ($node, $option, $file) = split (/\|/, $line); + my ($node, $option, $file) = split(/\|/, $line); - if (!$file) { - next; - } + if (!$file) { + next; + } # ex. .../inst_root/foo/bar/ or .../inst_root/etc/lppcfg my $instrootfile = $instrootloc . $file; @@ -1152,230 +1161,237 @@ sub dolitesetup # there's one scenario to be handled firstly # in litefile table, there's one entry: /path/to/file, which is one file # however, there's already one directory named "/path/to/file/" - # + # # Or: # the entry in litefile is "/path/to/file/", which is one directory # however, there's already one file named "/path/to/file" - # + # # in these cases, # need to indicate the user there's already one existing file/directory in the spot # then, exit - if ($file =~ m/\/$/ and -f $instrootfile) { + if ($file =~ m/\/$/ and -f $instrootfile) { my $rsp; - push @{$rsp->{data}}, qq{there is already one file named "$file", but the entry in litefile table is set to one directory, please check it}; + push @{ $rsp->{data} }, qq{there is already one file named "$file", but the entry in litefile table is set to one directory, please check it}; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } if ($file !~ m/\/$/ and -d $instrootfile) { my $rsp; - push @{$rsp->{data}}, qq{there is already one directory named "$file", but the entry in litefile table is set to one file, please check it}; + push @{ $rsp->{data} }, qq{there is already one directory named "$file", but the entry in litefile table is set to one file, please check it}; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } } - my @copiedfiles; - foreach my $line (@litefiles) { + my @copiedfiles; + foreach my $line (@litefiles) { - # $file could be full path file name or dir name - # ex. /foo/bar/ or /etc/lppcfg - my ($node, $option, $file) = split (/\|/, $line); + # $file could be full path file name or dir name + # ex. /foo/bar/ or /etc/lppcfg + my ($node, $option, $file) = split(/\|/, $line); - # entry must be an absolute path - unless ($file =~ m{^/}) { - my $rsp; - push @{$rsp->{data}}, "The litefile entry \'$file\' is not an absolute path name.\n"; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } + # entry must be an absolute path + unless ($file =~ m{^/}) { + my $rsp; + push @{ $rsp->{data} }, "The litefile entry \'$file\' is not an absolute path name.\n"; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } - # ex. /foo or /etc - my $filedir = dirname($file); + # ex. /foo or /etc + my $filedir = dirname($file); - # ex. .../inst_root/foo/bar/ or .../inst_root/etc/lppcfg - my $instrootfile = $instrootloc . $file; + # ex. .../inst_root/foo/bar/ or .../inst_root/etc/lppcfg + my $instrootfile = $instrootloc . $file; - my $cpcmd; - my $mkdircmd; - my $output; + my $cpcmd; + my $mkdircmd; + my $output; - if (!grep (/^$instrootfile$/, @copiedfiles)) { - # don't copy same file twice - push (@copiedfiles, $instrootfile); - if (-e $instrootfile) { + if (!grep (/^$instrootfile$/, @copiedfiles)) { - if (-d $instrootfile) { - # it's a dir so copy everything in it - # ex. mkdir -p ../inst_root/.default/foo/bar - # ex. cp -r .../inst_root/foo/bar/ ../inst_root/.default/foo/bar + # don't copy same file twice + push(@copiedfiles, $instrootfile); + if (-e $instrootfile) { - if ( ! -e "$default$file" ) { # do mkdir - $mkdircmd = qq~mkdir -p $default$file 2>/dev/null~; - $output = xCAT::Utils->runcmd("$mkdircmd", -1); - if ($::RUNCMD_RC != 0) { - my $rsp; - push @{$rsp->{data}}, "Could not copy create $default$file."; - if ($::VERBOSE) - { - push @{$rsp->{data}}, "$output\n"; - } - xCAT::MsgUtils->message("E", $rsp, $callback); - } - } + if (-d $instrootfile) { - # ok - do copy - $cpcmd = qq~cp -p -r $instrootfile* $default$file 2>/dev/null~; - $output = xCAT::Utils->runcmd("$cpcmd", -1); + # it's a dir so copy everything in it + # ex. mkdir -p ../inst_root/.default/foo/bar + # ex. cp -r .../inst_root/foo/bar/ ../inst_root/.default/foo/bar - } else { - # copy file - # ex. mkdir -p ../inst_root/.default/etc - # ex. cp .../inst_root/etc/lppcfg ../inst_root/.default/etc - $cpcmd = qq~mkdir -p $default$filedir; cp -p $instrootfile $default$filedir 2>/dev/null~; - $output = xCAT::Utils->runcmd("$cpcmd", -1); - } - } else { + if (!-e "$default$file") { # do mkdir + $mkdircmd = qq~mkdir -p $default$file 2>/dev/null~; + $output = xCAT::Utils->runcmd("$mkdircmd", -1); + if ($::RUNCMD_RC != 0) { + my $rsp; + push @{ $rsp->{data} }, "Could not copy create $default$file."; + if ($::VERBOSE) + { + push @{ $rsp->{data} }, "$output\n"; + } + xCAT::MsgUtils->message("E", $rsp, $callback); + } + } - # could not find file or dir in ../inst_root (spot dir) - # so create empty file or dir - my $mkcmd; + # ok - do copy + $cpcmd = qq~cp -p -r $instrootfile* $default$file 2>/dev/null~; + $output = xCAT::Utils->runcmd("$cpcmd", -1); - # check if it's a dir - if(grep /\/$/, $file) { - # create dir in .default - if ( ! -d "$default$file" ) { - $mkcmd = qq~mkdir -p $default$file~; - $output = xCAT::Utils->runcmd("$mkcmd", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not create $default$file.\n"; - if ($::VERBOSE) - { - push @{$rsp->{data}}, "$output\n"; - } - } - } - } else { - # create dir and touch file in .default - my $dir = dirname($file); - if ( ! -d "$default$dir" ) { - $mkcmd = qq~mkdir -p $default$dir~; - $output = xCAT::Utils->runcmd("$mkcmd", -1); + } else { + + # copy file + # ex. mkdir -p ../inst_root/.default/etc + # ex. cp .../inst_root/etc/lppcfg ../inst_root/.default/etc + $cpcmd = qq~mkdir -p $default$filedir; cp -p $instrootfile $default$filedir 2>/dev/null~; + $output = xCAT::Utils->runcmd("$cpcmd", -1); + } + } else { + + # could not find file or dir in ../inst_root (spot dir) + # so create empty file or dir + my $mkcmd; + + # check if it's a dir + if (grep /\/$/, $file) { + + # create dir in .default + if (!-d "$default$file") { + $mkcmd = qq~mkdir -p $default$file~; + $output = xCAT::Utils->runcmd("$mkcmd", -1); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Could not create $default$dir."; + push @{ $rsp->{data} }, "Could not create $default$file.\n"; if ($::VERBOSE) { - push @{$rsp->{data}}, "$output\n"; + push @{ $rsp->{data} }, "$output\n"; } } - } + } + } else { - # touch the file - my $tcmd = qq~touch $default$file~; - $output = xCAT::Utils->runcmd("$tcmd", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not create $default$file.\n"; - if ($::VERBOSE) - { - push @{$rsp->{data}}, "$output\n"; - } - xCAT::MsgUtils->message("E", $rsp, $callback); - } - } - } # end - if not exist in spot - } # end - if not already copied - } # end - for each line in litefile + # create dir and touch file in .default + my $dir = dirname($file); + if (!-d "$default$dir") { + $mkcmd = qq~mkdir -p $default$dir~; + $output = xCAT::Utils->runcmd("$mkcmd", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not create $default$dir."; + if ($::VERBOSE) + { + push @{ $rsp->{data} }, "$output\n"; + } + } + } - # add aixlitesetup to ..inst_root/aixlitesetup - # this will wind up in the root dir on the node ("/") - my $install_dir = xCAT::TableUtils->getInstallDir(); - my $cpcmd = "/bin/cp $install_dir/postscripts/aixlitesetup $instrootloc/aixlitesetup; chmod +x $instrootloc/aixlitesetup"; + # touch the file + my $tcmd = qq~touch $default$file~; + $output = xCAT::Utils->runcmd("$tcmd", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not create $default$file.\n"; + if ($::VERBOSE) + { + push @{ $rsp->{data} }, "$output\n"; + } + xCAT::MsgUtils->message("E", $rsp, $callback); + } + } + } # end - if not exist in spot + } # end - if not already copied + } # end - for each line in litefile - my $out = xCAT::Utils->runcmd("$cpcmd", -1); + # add aixlitesetup to ..inst_root/aixlitesetup + # this will wind up in the root dir on the node ("/") + my $install_dir = xCAT::TableUtils->getInstallDir(); + my $cpcmd = "/bin/cp $install_dir/postscripts/aixlitesetup $instrootloc/aixlitesetup; chmod +x $instrootloc/aixlitesetup"; + + my $out = xCAT::Utils->runcmd("$cpcmd", -1); if ($::RUNCMD_RC != 0) { my $rsp; - push @{$rsp->{data}}, "Could not copy aixlitesetup."; + push @{ $rsp->{data} }, "Could not copy aixlitesetup."; xCAT::MsgUtils->message("E", $rsp, $callback); return 1; } - # if this is an update then we need to copy the new files to - # the shared_root location - # ??? - maybe we should try this all the time???? - if (1) { - # if we have a shared_root resource - if ($imghash{$imagename}{shared_root} ) { - my $nimprime = xCAT::InstUtils->getnimprime(); - chomp $nimprime; - # get the location of the shared_root directory - my $SRloc = xCAT::InstUtils->get_nim_attr_val($imghash{$imagename}{shared_root}, 'location', $callback, $Sname, $subreq); + # if this is an update then we need to copy the new files to + # the shared_root location + # ??? - maybe we should try this all the time???? + if (1) { - # copy the statelite table file to the shared root location - # this will not effect any running nodes that are using - # this shared_root resource. However the new table will - # include any info need for existing nodes - for when they - # need to be rebooted + # if we have a shared_root resource + if ($imghash{$imagename}{shared_root}) { + my $nimprime = xCAT::InstUtils->getnimprime(); + chomp $nimprime; - if (-d $SRloc) { - my $ccmd = "/bin/cp"; - if (-e $statelitetable) - { - $ccmd .= " $statelitetable"; - } + # get the location of the shared_root directory + my $SRloc = xCAT::InstUtils->get_nim_attr_val($imghash{$imagename}{shared_root}, 'location', $callback, $Sname, $subreq); - if (-e $litefiletable) - { - $ccmd .= " $litefiletable"; - } + # copy the statelite table file to the shared root location + # this will not effect any running nodes that are using + # this shared_root resource. However the new table will + # include any info need for existing nodes - for when they + # need to be rebooted - if (-e $litetreetable) - { - $ccmd .= " $litetreetable"; - } - - $ccmd .= " $instrootloc/aixlitesetup $SRloc"; - my $out = xCAT::Utils->runcmd("$ccmd", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not copy statelite files to $SRloc."; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } + if (-d $SRloc) { + my $ccmd = "/bin/cp"; + if (-e $statelitetable) + { + $ccmd .= " $statelitetable"; + } - # also copy $instrootloc/.default contents - $ccmd = "/usr/bin/cp -p -r $instrootloc/.default $SRloc"; - $out = xCAT::Utils->runcmd("$ccmd", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not copy $instrootloc/.default to $SRloc."; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } + if (-e $litefiletable) + { + $ccmd .= " $litefiletable"; + } - # also copy $instrootloc/.statelite contents - $ccmd = "/usr/bin/cp -p -r $instrootloc/.statelite $SRloc"; - $out = xCAT::Utils->runcmd("$ccmd", -1); - if ($::RUNCMD_RC != 0) - { - my $rsp; - push @{$rsp->{data}}, "Could not copy $instrootloc/.statelite to $SRloc."; - xCAT::MsgUtils->message("E", $rsp, $callback); - return 1; - } - } - } - } - return 0; + if (-e $litetreetable) + { + $ccmd .= " $litetreetable"; + } + + $ccmd .= " $instrootloc/aixlitesetup $SRloc"; + my $out = xCAT::Utils->runcmd("$ccmd", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not copy statelite files to $SRloc."; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + + # also copy $instrootloc/.default contents + $ccmd = "/usr/bin/cp -p -r $instrootloc/.default $SRloc"; + $out = xCAT::Utils->runcmd("$ccmd", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not copy $instrootloc/.default to $SRloc."; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + + # also copy $instrootloc/.statelite contents + $ccmd = "/usr/bin/cp -p -r $instrootloc/.statelite $SRloc"; + $out = xCAT::Utils->runcmd("$ccmd", -1); + if ($::RUNCMD_RC != 0) + { + my $rsp; + push @{ $rsp->{data} }, "Could not copy $instrootloc/.statelite to $SRloc."; + xCAT::MsgUtils->message("E", $rsp, $callback); + return 1; + } + } + } + } + return 0; } #---------------------------------------------------------------------------- @@ -1392,7 +1408,7 @@ sub dolitesetup sub convert_xcatmaster { my $shorthost = xCAT::InstUtils->myxCATname(); - my $selfip = xCAT::NetworkUtils->getipaddr($shorthost); + my $selfip = xCAT::NetworkUtils->getipaddr($shorthost); return $selfip; } diff --git a/perl-xCAT/xCAT/KitPluginUtils.pm b/perl-xCAT/xCAT/KitPluginUtils.pm index 5a612d69e..082c93b65 100644 --- a/perl-xCAT/xCAT/KitPluginUtils.pm +++ b/perl-xCAT/xCAT/KitPluginUtils.pm @@ -49,15 +49,15 @@ sub get_kits_used_by_nodes { # Group the nodes by what osimage they use my $tablename = "nodetype"; - my $table = xCAT::Table->new($tablename); - my $ent = $table->getNodesAttribs($nodes, ["provmethod"]); - + my $table = xCAT::Table->new($tablename); + my $ent = $table->getNodesAttribs($nodes, ["provmethod"]); + my $osimage_to_nodes = {}; foreach my $node (keys(%$ent)) { my $provmethod = $ent->{$node}->[0]->{"provmethod"}; if (defined($provmethod)) { push(@{ $osimage_to_nodes->{$provmethod} }, $node); - } + } } # Group the osimages by what kits they use @@ -68,9 +68,10 @@ sub get_kits_used_by_nodes { # Group nodes by kit my $kits_to_nodes = {}; foreach my $kit (keys(%$kits_to_osimages)) { - my $tmphash = {}; + my $tmphash = {}; my $osimages = $kits_to_osimages->{$kit}; foreach my $osimage (@$osimages) { + # Store nodes as hash keys to eliminate duplicates my @nodes = @{ $osimage_to_nodes->{$osimage} }; @$tmphash{@nodes} = (); @@ -111,14 +112,14 @@ sub get_kits_used_by_nodes { sub get_kits_used_by_osimages { - my $class = shift; + my $class = shift; my $osimages = shift; # Get the kit components used by each osimage my $tablename = "osimage"; - my $table = xCAT::Table->new($tablename); + my $table = xCAT::Table->new($tablename); - my $osimages_str = join ",", map {'\''.$_.'\''} @$osimages; + my $osimages_str = join ",", map { '\'' . $_ . '\'' } @$osimages; my $filter_stmt = sprintf("imagename in (%s)", $osimages_str); my @table_rows = $table->getAllAttribsWhere($filter_stmt, ("imagename", "kitcomponents")); @@ -134,15 +135,15 @@ sub get_kits_used_by_osimages { # Get the kit for each kit component $tablename = "kitcomponent"; - $table = xCAT::Table->new($tablename); + $table = xCAT::Table->new($tablename); - my $kitcomps_str = join ",", map {'\''.$_.'\''} keys(%$kitcomps_to_osimages); + my $kitcomps_str = join ",", map { '\'' . $_ . '\'' } keys(%$kitcomps_to_osimages); $filter_stmt = sprintf("kitcompname in (%s)", $kitcomps_str); @table_rows = $table->getAllAttribsWhere($filter_stmt, ("kitcompname", "kitname")); my $kits_to_kitcomps = {}; foreach my $row (@table_rows) { - my $kitname = $row->{kitname}; + my $kitname = $row->{kitname}; my $kitcompname = $row->{kitcompname}; push(@{ $kits_to_kitcomps->{$kitname} }, $kitcompname); } @@ -151,9 +152,10 @@ sub get_kits_used_by_osimages { my $kits_to_osimages = {}; foreach my $kit (keys(%$kits_to_kitcomps)) { - my $tmphash = {}; + my $tmphash = {}; my $kitcomps = $kits_to_kitcomps->{$kit}; foreach my $kitcomp (@$kitcomps) { + # Store osimages as hash keys to eliminate duplicates my @osimages = @{ $kitcomps_to_osimages->{$kitcomp} }; @$tmphash{@osimages} = (); diff --git a/perl-xCAT/xCAT/LparNetbootExp.pm b/perl-xCAT/xCAT/LparNetbootExp.pm index 1a7e0960b..56a47ce34 100755 --- a/perl-xCAT/xCAT/LparNetbootExp.pm +++ b/perl-xCAT/xCAT/LparNetbootExp.pm @@ -67,16 +67,16 @@ my $server_ip; # the script searches for in the device tree listing. dev_type is the type # of device displayed in the output. my @dev_pat = ( - "ethernet", - "token-ring", - "fddi" - ); + "ethernet", + "token-ring", + "fddi" +); my @dev_type = ( - "ent", - "tok", - "fddi" - ); -my $dev_count = scalar(@dev_type); #number of supported device type + "ent", + "tok", + "fddi" +); +my $dev_count = scalar(@dev_type); #number of supported device type #------------------------------------------------------------------------------- @@ -96,19 +96,20 @@ my $dev_count = scalar(@dev_type); #number of supported device type sub nc_msg { my $verbose = shift; - my $msg = shift; + my $msg = shift; my $rsp; - if ( $verbose eq 1 ) { + if ($verbose eq 1) { $rsp->{data}->[0] = $msg; - xCAT::MsgUtils->message("I", $rsp ,$::CALLBACK); + xCAT::MsgUtils->message("I", $rsp, $::CALLBACK); } - if ( $verbose eq 2 ) { + if ($verbose eq 2) { $rsp->{data}->[0] = $msg; - xCAT::MsgUtils->message("E", $rsp ,$::CALLBACK); + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); } } + #------------------------------------------------------------------------------- =head3 run_lssyscfg @@ -128,7 +129,7 @@ sub run_lssyscfg $req = shift; } my $verbose = shift; - my $node = shift; + my $node = shift; my $cmd; my $out; @@ -138,15 +139,15 @@ sub run_lssyscfg node => [$node], arg => ['state'] }, - $req, 0, 1); - if ($::RUNCMD_RC != 0) { + $req, 0, 1); + if ($::RUNCMD_RC != 0) { nc_msg($verbose, "Unable to run rpower $node state.\n"); return undef; } my $output = join ',', @$out; nc_msg($verbose, "Status: run_lssyscg : partition status : $output\n"); - nc_msg($verbose, "####msg:$output#########\n" ); + nc_msg($verbose, "####msg:$output#########\n"); ################################################################### @@ -207,6 +208,7 @@ sub usage { return 0; } + #------------------------------------------------------------------------------- =head3 ck_args @@ -227,35 +229,35 @@ sub ck_args { $opt = shift; } my $verbose = shift; - my $node = $opt->{node}; - my $mtms = $opt->{fsp}; - my $hcp = $opt->{hcp}; - my $lparid = $opt->{id}; + my $node = $opt->{node}; + my $mtms = $opt->{fsp}; + my $hcp = $opt->{hcp}; + my $lparid = $opt->{id}; my $profile = $opt->{pprofile}; - if (exists( $opt->{D}) and !exists($opt->{noping}) and (!exists ($opt->{s}) or !exists ($opt->{d} ))) { + if (exists($opt->{D}) and !exists($opt->{noping}) and (!exists($opt->{s}) or !exists($opt->{d}))) { nc_msg($verbose, "Speed and duplex required\n"); usage; return 1; } - if (exists ($opt->{D}) and !exists($opt->{noping}) and !exists ($opt->{C})) { + if (exists($opt->{D}) and !exists($opt->{noping}) and !exists($opt->{C})) { nc_msg($verbose, "Client IP is required\n"); usage; return 1; } - if (exists( $opt->{D}) and !exists($opt->{noping}) and !exists($opt->{S})) { + if (exists($opt->{D}) and !exists($opt->{noping}) and !exists($opt->{S})) { nc_msg($verbose, "Server IP is required\n"); usage; return 1; } - if (exists( $opt->{D}) and !exists($opt->{noping}) and !exists($opt->{G})) { + if (exists($opt->{D}) and !exists($opt->{noping}) and !exists($opt->{G})) { nc_msg($verbose, "Gateway IP is required\n"); usage; return 1; } - unless($node) { + unless ($node) { nc_msg($verbose, "Node is required\n"); usage; return 1; @@ -263,7 +265,7 @@ sub ck_args { nc_msg($verbose, "Node is $node\n"); } - unless($mtms) { + unless ($mtms) { nc_msg($verbose, "Managed system is required\n"); usage; return 1; @@ -324,13 +326,13 @@ sub ck_args { return 1; } - if ($opt->{M} and $opt->{D} and !exists($opt->{noping}) and (!exists($opt->{S}) or !exists($opt->{G}) or !exists($opt->{C}) or !exists( $opt->{s}) or !exists($opt->{d}))) { + if ($opt->{M} and $opt->{D} and !exists($opt->{noping}) and (!exists($opt->{S}) or !exists($opt->{G}) or !exists($opt->{C}) or !exists($opt->{s}) or !exists($opt->{d}))) { nc_msg($verbose, "Flag -M with -D require arguments for -C, -S, -G, -s and -d.\n"); usage; return 1; } - if ($opt->{M} and !exists($opt->{D}) and (!exists($opt->{S}) or !exists($opt->{G}) or !exists($opt->{C}) or !exists($opt->{s}) or !exists($opt->{d}))){ + if ($opt->{M} and !exists($opt->{D}) and (!exists($opt->{S}) or !exists($opt->{G}) or !exists($opt->{C}) or !exists($opt->{s}) or !exists($opt->{d}))) { nc_msg($verbose, "Flag -M with arguments for -C, -S, -G, -s and -d require -D flag.\n"); usage; return 1; @@ -383,10 +385,10 @@ sub ck_args { #----------------------------------------------------------------------------- -sub send_command { - my $verbose = shift; +sub send_command { + my $verbose = shift; my $rconsole = shift; - my $cmd = shift; + my $cmd = shift; nc_msg($verbose, "sending commands $cmd to expect \n"); my $msg; @@ -415,10 +417,10 @@ sub send_command { sub get_phandle { my $rconsole = shift; - my $node = shift; - my $verbose = shift; - my $timeout = 30; - my $done = 0; + my $node = shift; + my $verbose = shift; + my $timeout = 30; + my $done = 0; my @result; my $expect_out; my $retry_count; @@ -434,39 +436,40 @@ sub get_phandle { # The pwd command can be used to determine what the current device is. # - send_command($verbose, $rconsole, "dev /\r"); + send_command($verbose, $rconsole, "dev /\r"); @result = $rconsole->expect( $timeout, - [qr/ok/=> - sub { - nc_msg($verbose, "Status: at root\n"); - $rconsole->clear_accum(); - } + [ qr/ok/ => + sub { + nc_msg($verbose, "Status: at root\n"); + $rconsole->clear_accum(); + } ], - [qr/]/=> - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/]/ => + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [timeout => - sub { - $rconsole->send("\r"); - $rconsole->clear_accum(); - $rc = 1; - } + [ timeout => + sub { + $rconsole->send("\r"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [eof => - sub { - nc_msg($verbose, "Cannot connect to $node"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); return 1 if ($rc eq 1); + # Next, the 'ls' command is sent. The result is a display of the entire # device tree. The code then looks at the # output from the ls command one line at a time, trying to match it with the @@ -501,11 +504,12 @@ sub get_phandle { # Using the -d flag helped a lot in finding the correct pattern. # - send_command($verbose, $rconsole, "ls \r"); + send_command($verbose, $rconsole, "ls \r"); $timeout = 60; - $done = 0; + $done = 0; while (!$done) { + # this expect call isolates single lines # This code uses the tcl regexp to parse the single line # isolated by expect. @@ -519,72 +523,75 @@ sub get_phandle { @result = (); @result = $rconsole->expect( $timeout, - [qr/(\n)([^\r]*)(\r)/=> - sub { - nc_msg($verbose, "Parsing network adapters... \n"); - #$rconsole->clear_accum(); - } + [ qr/(\n)([^\r]*)(\r)/ => + sub { + nc_msg($verbose, "Parsing network adapters... \n"); + + #$rconsole->clear_accum(); + } ], - [qr/>/=> - sub { - nc_msg($verbose, "finished \n"); - $rconsole->clear_accum(); - $done = 1; - } + [ qr/>/ => + sub { + nc_msg($verbose, "finished \n"); + $rconsole->clear_accum(); + $done = 1; + } ], - [timeout=> - sub { - nc_msg($verbose, "Timeout isolating single line of ls output\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ timeout => + sub { + nc_msg($verbose, "Timeout isolating single line of ls output\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [eof => - sub { - nc_msg($verbose, "Cannot connect to $node"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); return 1 if ($rc eq 1); if ($result[2] =~ /(\w*)\:(\s*)\/(\S*)/) { my $x1 = $1; - my $x2 = $2; #number of space - my $x3 = $3; #device - # Each level is inspected for a match - my $level = (length($x2)-1)/2; + my $x2 = $2; #number of space + my $x3 = $3; #device + # Each level is inspected for a match + my $level = (length($x2) - 1) / 2; $path{$level} = $x3; my $j = 0; - for ($j = 0; $j < $dev_count; $j++) { + for ($j = 0 ; $j < $dev_count ; $j++) { if ($x3 =~ /$dev_pat[$j]/) { - if ( $x3 =~ /hfi-ethernet/ and $dev_pat[$j] eq "ethernet" ){ + if ($x3 =~ /hfi-ethernet/ and $dev_pat[$j] eq "ethernet") { next; } my $i = 0; - for ($i = 0; $i <= $level; $i++) + for ($i = 0 ; $i <= $level ; $i++) { $full_path_name_array[$adapter_found] .= "/" . $path{$i}; } $phandle_array[$adapter_found] = $x1; - $adap_type[$adapter_found] = $dev_type[$j]; - $adapter_found ++; + $adap_type[$adapter_found] = $dev_type[$j]; + $adapter_found++; last; } } } } + # Did we find one or more adapters? - if ( $adapter_found > 0 ) { + if ($adapter_found > 0) { return 0; } else { - nc_msg($verbose, "No network adapters found\n" ); + nc_msg($verbose, "No network adapters found\n"); return 1; } } + #------------------------------------------------------------------------------- =head3 get_adap_prop @@ -601,14 +608,14 @@ sub get_phandle { =cut #----------------------------------------------------------------------------- -sub get_adap_prop { - my $phandle = shift; +sub get_adap_prop { + my $phandle = shift; my $rconsole = shift; - my $node = shift; - my $verbose = shift; - my $timeout = 120; - my $rc = 0; - my $state = 0; + my $node = shift; + my $verbose = shift; + my $timeout = 120; + my $rc = 0; + my $state = 0; my @cmd; my @done; my @msg; @@ -627,140 +634,149 @@ sub get_adap_prop { $done[0] = 0; $cmd[0] = "\" supported-network-types\" " . $phandle . " get-package-property\r"; $msg[0] = "Status: rc and all supported network types now on stack\n"; + #$pattern[0] = "(.*)3 >(.*)"; #$pattern[0] = "3 >"; - $pattern[0] = "ok"; + $pattern[0] = "ok"; $newstate[0] = 1; # state 1, return code and string on stack $done[1] = 0; - $cmd[1] = ".\r"; - $msg[1] = "Status: All supported network types now on stack\n"; + $cmd[1] = ".\r"; + $msg[1] = "Status: All supported network types now on stack\n"; + #$pattern[1] = "(.*)2 >(.*)"; #$pattern[1] = "2 >"; - $pattern[1] = "ok"; + $pattern[1] = "ok"; $newstate[1] = 2; # state 2, data ready to decode $done[2] = 0; - $cmd[2] = "decode-string\r"; - $msg[2] = "Status: supported network type isolated on stack\n"; + $cmd[2] = "decode-string\r"; + $msg[2] = "Status: supported network type isolated on stack\n"; + #$pattern[2] = "(.*)ok(.*)4 >(.*)"; - $pattern[2] = "4 >"; + $pattern[2] = "4 >"; $newstate[2] = 3; # state 3, decoded string on stack - $done[3]= 0; - $cmd[3] = "dump\r"; - $msg[3] = "Status: supported network type off stack\n"; + $done[3] = 0; + $cmd[3] = "dump\r"; + $msg[3] = "Status: supported network type off stack\n"; + #$pattern[3] = ".*:.*:(.*):.*:.*:(.*):.*(2 >)(.*)"; - $pattern[3] = "ok"; + $pattern[3] = "ok"; $newstate[3] = 4; # state 4, need to check for more data to decode $done[4] = 0; - $cmd[4] = ".s\r"; - $msg[4] = "Status: checking for more supported network types\n"; + $cmd[4] = ".s\r"; + $msg[4] = "Status: checking for more supported network types\n"; + #$pattern[4] = ".s (\[0-9a-f]* )(.*)>"; - $pattern[4] = "ok"; - $newstate[4]= 5; + $pattern[4] = "ok"; + $newstate[4] = 5; # state 5, done decoding string, clear stack $done[5] = 0; $cmd[5] = ".\r"; $msg[5] = "Status: one entry on stack cleared\n"; + #$pattern[5] = "(.*)ok(.*)1 >(.*)"; - $pattern[5] = "ok"; + $pattern[5] = "ok"; $newstate[5] = 6; # state 6, finish clearing stack, choose correct adapter type - $done[6]= 0; - $cmd[6] = ".\r"; - $msg[6] = "Status: finished clearing stack\n"; + $done[6] = 0; + $cmd[6] = ".\r"; + $msg[6] = "Status: finished clearing stack\n"; + #$pattern[6] = "(.*)ok(.*)0 >(.*)"; - $pattern[6] = "ok"; - $newstate[6]= 7; + $pattern[6] = "ok"; + $newstate[6] = 7; # state 7, done $done[7] = 1; - while($done[$state] eq 0) { + while ($done[$state] eq 0) { nc_msg($verbose, "Status: command is $cmd[$state]\n"); send_command($verbose, $rconsole, $cmd[$state]); @result = (); @result = $rconsole->expect( - $timeout, - [ qr/$pattern[$state]/i, - sub { - if ($state eq 1) { - if ($rconsole->before() =~ /-\d+/) { - nc_msg($verbose, "Status: Error getting adapter property for phandle=$phandle.\n"); - $state = 7; - $rconsole->clear_accum(); - $rc = 1; - return 1; + $timeout, + [ qr/$pattern[$state]/i, + sub { + if ($state eq 1) { + if ($rconsole->before() =~ /-\d+/) { + nc_msg($verbose, "Status: Error getting adapter property for phandle=$phandle.\n"); + $state = 7; + $rconsole->clear_accum(); + $rc = 1; + return 1; + } } - } - nc_msg($verbose, $msg[$state]); - $state = $newstate[$state]; - $rconsole->clear_accum(); - } - ], - [ qr/]/, - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } - ], - [ qr/(.*)DEFAULT(.*)/, - sub { - nc_msg($verbose, " Default catch error\n"); - $rconsole->clear_accum(); - $rc = 1; - } - ], - [ timeout=> - sub { - nc_msg($verbose, "Timeout in getting adapter properpties\n"); - $rconsole->clear_accum(); - $rc = 1; - } - ], - [ eof => - sub { - nc_msg($verbose, "Cannot connect to $node\n"); - $rconsole->clear_accum(); - $rc = 1; - } - ] + nc_msg($verbose, $msg[$state]); + $state = $newstate[$state]; + $rconsole->clear_accum(); + } + ], + [ qr/]/, + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ], + [ qr/(.*)DEFAULT(.*)/, + sub { + nc_msg($verbose, " Default catch error\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ], + [ timeout => + sub { + nc_msg($verbose, "Timeout in getting adapter properpties\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ], + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ] ); return 1 if ($rc eq 1); + # After state 3, the network type is parsed and the connector # type extracted. If the type hasn't been found, add it to # the list of supported connector types. - if ( $state eq 4 ) { + if ($state eq 4) { + # Build the adapter properties from the string #regexp .*,(.*),(.*),(.*) $nw_type dummy nw_speed nw_conn nw_duplex #set adap_prop "$nw_speed,$nw_conn,$nw_duplex" #nc_msg "Status: Adapter properties are $adap_prop\n" # if it's not in the list, add it, otherwise continue - if ( $result[3] =~ /(\w*):(.*):(\w*)\,(\w*)\,(\w*):/) { - $nw_type = $3; + if ($result[3] =~ /(\w*):(.*):(\w*)\,(\w*)\,(\w*):/) { + $nw_type = $3; $nw_speed = $4; - $nw_conn = $5; + $nw_conn = $5; nc_msg($verbose, "nwtype is $3, nwspeed is $4, nwconn is $5\n"); } - if ( $result[3] =~ /(\w*):(.*):(\w*)\,(\w*):/) { + if ($result[3] =~ /(\w*):(.*):(\w*)\,(\w*):/) { $nw_duplex = $4; nc_msg($verbose, "nwduplex is $4\n"); } } #push @adap_prop_array, $nw_type.",".$nw_speed.",".$nw_conn.",".$nw_duplex; - push @adap_prop_array, $nw_speed.",".$nw_conn.",".$nw_duplex; + push @adap_prop_array, $nw_speed . "," . $nw_conn . "," . $nw_duplex; nc_msg($verbose, "Status: Adding adapter properties to list\n"); # After state 4, a test is done to see if all of the supported @@ -768,8 +784,8 @@ sub get_adap_prop { # state variable is left alone. if not, the state variable is # set to 2, causing a loop back to the step where the # decode-string command is sent. - if ( $state eq 5 ) { - if ($result[3] =~/2 > \.s \w+ (\w*)/) { + if ($state eq 5) { + if ($result[3] =~ /2 > \.s \w+ (\w*)/) { $state = 2 if ($1 != 0); } } @@ -806,12 +822,12 @@ sub get_adap_prop { #----------------------------------------------------------------------------- sub get_mac_addr { - my $phandle = shift; + my $phandle = shift; my $rconsole = shift; - my $node = shift; - my $verbose = shift; - my $timeout = 60; - my $state = 0; + my $node = shift; + my $verbose = shift; + my $timeout = 60; + my $state = 0; my @result; my $mac_rc; my @cmd; @@ -836,21 +852,22 @@ sub get_mac_addr { # are 3 stack entries (return code, address and length of mac-address). # state 0, stack count 0, send command $done[0] = 0; - $cmd[0] = "\" local-mac-address\" ". $phandle . " get-package-property\r"; - $msg[0] = "Status: return code and mac-address now on stack\n"; - $pattern[0] = "local-mac-address.*ok";#"\s*3 >"; + $cmd[0] = "\" local-mac-address\" " . $phandle . " get-package-property\r"; + $msg[0] = "Status: return code and mac-address now on stack\n"; + $pattern[0] = "local-mac-address.*ok"; #"\s*3 >"; $newstate[0] = 1; # cmd(1) is a dot (.). This is a stack manipulation command that removes one # thing from the stack. pattern(1) is looking for a prompt with the 2 indicating # that there are 2 things left on the stack. # state 1, return code and mac-address on stack - $done[1]= 0; - $cmd[1] = ".\r"; - $msg[1] = "Status: mac-address now on stack\n"; + $done[1] = 0; + $cmd[1] = ".\r"; + $msg[1] = "Status: mac-address now on stack\n"; + #$pattern[1] = "(.*)2 >(.*)"; - $pattern[1] = "ok"; #"2 >"; - $newstate[1]= 2; + $pattern[1] = "ok"; #"2 >"; + $newstate[1] = 2; # cmd(2) is the dump command. This takes an address and a length off the stack # and displays the contents of that storage in ascii and hex. The long pattern @@ -858,7 +875,7 @@ sub get_mac_addr { # used to eliminate the spaces put in by the dump command. # state 2, mac-address on stack $done[2] = 0; - $cmd[2] = ": dump-mac ( prop-addr prop-len -- ) \ + $cmd[2] = ": dump-mac ( prop-addr prop-len -- ) \ cr \ dup decode-bytes 2swap 2drop ( data-addr data-len ) \ ( data-len ) 0 ?do \ @@ -868,111 +885,114 @@ sub get_mac_addr { drop \ cr \ ; \r"; - $msg[2] = "Status: set command\n"; - $pattern[2] = "ok"; - $newstate[2]= 3; + $msg[2] = "Status: set command\n"; + $pattern[2] = "ok"; + $newstate[2] = 3; - $done[3]= 0; - $cmd[3] = "dump-mac\r"; - $msg[3] = "Status: mac-address displayed, stack empty\n"; - $pattern[3] = "dump-mac(\\s*)(\\w*)(\\s*)ok"; - $newstate[3] = 4 ; + $done[3] = 0; + $cmd[3] = "dump-mac\r"; + $msg[3] = "Status: mac-address displayed, stack empty\n"; + $pattern[3] = "dump-mac(\\s*)(\\w*)(\\s*)ok"; + $newstate[3] = 4; # state 4, all done $done[4] = 1; - while($done[$state] eq 0) { + while ($done[$state] eq 0) { @result = (); send_command($verbose, $rconsole, $cmd[$state]); @result = $rconsole->expect( $timeout, - [qr/$pattern[$state]/=> - sub { - if ($state eq 1) { - if ($rconsole->before() =~ /-\d+/) { - nc_msg($verbose, "Status: Error getting MAC address for phandle=$phandle.\n"); - $rconsole->clear_accum(); - $state = 4; - $rc = 1; - return undef; + [ qr/$pattern[$state]/ => + sub { + if ($state eq 1) { + if ($rconsole->before() =~ /-\d+/) { + nc_msg($verbose, "Status: Error getting MAC address for phandle=$phandle.\n"); + $rconsole->clear_accum(); + $state = 4; + $rc = 1; + return undef; + } } - } - nc_msg($verbose, $msg[$state]); - $state = $newstate[$state]; - $rconsole->clear_accum(); - } + nc_msg($verbose, $msg[$state]); + $state = $newstate[$state]; + $rconsole->clear_accum(); + } ], - [qr/1 > /=> - sub { - $rconsole->clear_accum(); - if( $state eq 0 ) { - # An error occurred while obtaining the mac address. Log the error, - # but don't quit nodecond. instead, return NA for the address - # - send_command($verbose, $rconsole, ".\r"); - $rconsole->expect( - $timeout, - #[ qr/(-*\[0-9\]*) ok(.*)0 >(.*)/i, - [ qr/0 >/i, - sub { - #$mac_rc = $expect_out; - nc_msg($verbose, "Status: Error getting MAC address for phandle=$phandle. RC=$mac_rc.\n"); - nc_msg($verbose, "Could not obtain MAC address; setting MAX to NA\n" ); - $rconsole->clear_accum(); - $rc = 1; - } - ], - [ timeout=> - sub { - nc_msg($verbose, "Timeout when getting mac address\n"); - $rconsole->clear_accum(); - $rc = 1; - } - ], - [ eof => - sub { - nc_msg($verbose, " Cannot connect to $node\n"); - $rconsole->clear_accum(); - $rc = 1; - } - ] - ); - } - } + [ qr/1 > / => + sub { + $rconsole->clear_accum(); + if ($state eq 0) { + + # An error occurred while obtaining the mac address. Log the error, + # but don't quit nodecond. instead, return NA for the address + # + send_command($verbose, $rconsole, ".\r"); + $rconsole->expect( + $timeout, + + #[ qr/(-*\[0-9\]*) ok(.*)0 >(.*)/i, + [ qr/0 >/i, + sub { + #$mac_rc = $expect_out; + nc_msg($verbose, "Status: Error getting MAC address for phandle=$phandle. RC=$mac_rc.\n"); + nc_msg($verbose, "Could not obtain MAC address; setting MAX to NA\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ], + [ timeout => + sub { + nc_msg($verbose, "Timeout when getting mac address\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ], + [ eof => + sub { + nc_msg($verbose, " Cannot connect to $node\n"); + $rconsole->clear_accum(); + $rc = 1; + } + ] + ); + } + } ], - [qr/]/=> - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/]/ => + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [qr/(.*)DEFAULT(.*)/=> - sub { - nc_msg($verbose, "Default catch error\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/(.*)DEFAULT(.*)/ => + sub { + nc_msg($verbose, "Default catch error\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [timeout=> - sub { - nc_msg($verbose, "Timeout in getting mac address\n"); - nc_msg($verbose, "timeout state is $state\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ timeout => + sub { + nc_msg($verbose, "Timeout in getting mac address\n"); + nc_msg($verbose, "timeout state is $state\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [eof => - sub { - nc_msg($verbose, "Cannot connect to $node"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); return undef if ($rc eq 1); } + # if the state is 0, 1, or 2, an error occurred and the join will fail if ($state eq 4) { if ($result[2] =~ /dump-mac\s*(\w*)\s*ok/) { @@ -1007,24 +1027,25 @@ sub get_mac_addr { =cut #----------------------------------------------------------------------------- - sub get_adaptr_loc { - my $phandle = shift; +sub get_adaptr_loc { + my $phandle = shift; my $rconsole = shift; - my $node = shift; - my $verbose = shift; + my $node = shift; + my $verbose = shift; my @cmd; my @done; my @msg; my @pattern; my @newstate; - my $state = 0; - my $timeout = 60; # shouldn't take long + my $state = 0; + my $timeout = 60; # shouldn't take long my @result; my @path; my $loc_code; my $rc = 0; nc_msg($verbose, "Status: get_adaptr_loc start\n"); + # cmd(0) could have been sent as 3 commands. " ibm,loc-code" (tcl forces # the use of \") is the first command on this line. The result of entering # " ibm,loc-code" is that 2 stack entries are created, and address and a length. @@ -1036,132 +1057,137 @@ sub get_mac_addr { # are 3 stack entries (return code, address and length of mac-address). # state 0, stack count 0, send command $done[0] = 0; - $cmd[0] = "\" ibm,loc-code\" $phandle get-package-property\r"; - $msg[0] = "Status: return code and loc-code now on stack\n"; + $cmd[0] = "\" ibm,loc-code\" $phandle get-package-property\r"; + $msg[0] = "Status: return code and loc-code now on stack\n"; + #$pattern[0] = "(.*)3 >(.*)"; #$pattern[0] = "3 >"; - $pattern[0] = "ok"; + $pattern[0] = "ok"; $newstate[0] = 1; # cmd(1) is a dot (.). This is a stack manipulation command that removes one # thing from the stack. pattern(1) is looking for a prompt with the 2 indicating # that there are 2 things left on the stack. # state 1, return code and loc-code on stack - $done[1]= 0; - $cmd[1] = ".\r"; - $msg[1] = "Status: loc-code now on stack\n"; + $done[1] = 0; + $cmd[1] = ".\r"; + $msg[1] = "Status: loc-code now on stack\n"; + #$pattern[1] = "(.*)2 >(.*)"; - $pattern[1] = "ok"; #"2 >"; - $newstate[1]= 2; + $pattern[1] = "ok"; #"2 >"; + $newstate[1] = 2; # state 2, loc-code on stack - $done[2]= 0; - $cmd[2] = "dump\r"; - $msg[2] = "Status: loc-code displayed, stack empty\n"; + $done[2] = 0; + $cmd[2] = "dump\r"; + $msg[2] = "Status: loc-code displayed, stack empty\n"; + #$pattern[2] = "(.*)(: )(.*)( :)(.*)(\.: ok)"; - $pattern[2] = "ok"; - $newstate[2]= 3; + $pattern[2] = "ok"; + $newstate[2] = 3; # state 3, all done $done[3] = 1; - while($done[$state] eq 0) { + while ($done[$state] eq 0) { @result = (); nc_msg($verbose, "PROGRAM Status: command is $cmd[$state]\n"); send_command($verbose, $rconsole, $cmd[$state]); @result = $rconsole->expect( $timeout, - [qr/$pattern[$state]/=> - sub { - if ($state eq 1) { - if ($rconsole->before() =~ /-\d+/) { - nc_msg($verbose, "Status: Error getting adapter location for phandle=$phandle."); - $rconsole->clear_accum(); - $state = 3; - $rc = 1; - return undef; + [ qr/$pattern[$state]/ => + sub { + if ($state eq 1) { + if ($rconsole->before() =~ /-\d+/) { + nc_msg($verbose, "Status: Error getting adapter location for phandle=$phandle."); + $rconsole->clear_accum(); + $state = 3; + $rc = 1; + return undef; + } } - } - nc_msg($verbose, $msg[$state]); - $rconsole->clear_accum(); - $state = $newstate[$state]; - } + nc_msg($verbose, $msg[$state]); + $rconsole->clear_accum(); + $state = $newstate[$state]; + } ], - [qr/1 >/=> - sub { - $rconsole->clear_accum(); - my $exp = shift; - if($state eq 0) { - send_command($verbose, $rconsole, ".\r"); - $exp->expect( - #[qr/(-*\[0-9\]*) ok(.*)0 >(.*)/=> - [qr/0 >/=> - sub { - $rconsole->clear_accum(); - my $loc_rc = shift; - nc_msg($verbose, "Error getting adapter physical location.\n"); - nc_msg($verbose, "Status: Error getting physical location for phandle=$phandle. RC=$loc_rc.\n"); - $rc = 1; - } - ], - [timeout=> - sub { - $rconsole->clear_accum(); - nc_msg($verbose, "Timeout when openning console\n"); - $rc = 1; - } - ], - [eof=> - sub { - $rconsole->clear_accum(); - nc_msg($verbose, "Cannot connect to the $node\n"); - $rc = 1; - } - ], - ); + [ qr/1 >/ => + sub { + $rconsole->clear_accum(); + my $exp = shift; + if ($state eq 0) { + send_command($verbose, $rconsole, ".\r"); + $exp->expect( - } - } + #[qr/(-*\[0-9\]*) ok(.*)0 >(.*)/=> + [ qr/0 >/ => + sub { + $rconsole->clear_accum(); + my $loc_rc = shift; + nc_msg($verbose, "Error getting adapter physical location.\n"); + nc_msg($verbose, "Status: Error getting physical location for phandle=$phandle. RC=$loc_rc.\n"); + $rc = 1; + } + ], + [ timeout => + sub { + $rconsole->clear_accum(); + nc_msg($verbose, "Timeout when openning console\n"); + $rc = 1; + } + ], + [ eof => + sub { + $rconsole->clear_accum(); + nc_msg($verbose, "Cannot connect to the $node\n"); + $rc = 1; + } + ], + ); + + } + } ], - [qr/]/=> - sub { - $rconsole->clear_accum(); - nc_msg($verbose, "Unexpected prompt\n"); - $rc = 1; - } + [ qr/]/ => + sub { + $rconsole->clear_accum(); + nc_msg($verbose, "Unexpected prompt\n"); + $rc = 1; + } ], - [qr/(.*)DEFAULT(.*)/=> - sub { - $rconsole->clear_accum(); - nc_msg($verbose, "Default catch error\n"); - $rc = 1; - } + [ qr/(.*)DEFAULT(.*)/ => + sub { + $rconsole->clear_accum(); + nc_msg($verbose, "Default catch error\n"); + $rc = 1; + } ], - [timeout=> - sub { - $rconsole->clear_accum(); - nc_msg($verbose, "Timeout when openning console\n"); - $rc = 1; - } + [ timeout => + sub { + $rconsole->clear_accum(); + nc_msg($verbose, "Timeout when openning console\n"); + $rc = 1; + } ], - [eof => - sub { - $rconsole->clear_accum(); - nc_msg($verbose, "Cannot connect to the $node\n"); - $rc = 1; - } + [ eof => + sub { + $rconsole->clear_accum(); + nc_msg($verbose, "Cannot connect to the $node\n"); + $rc = 1; + } ], ); return undef if ($rc eq 1); } + # Did we find one or more adapters? - my @loc_array = split /\n/,$result[3]; + my @loc_array = split /\n/, $result[3]; my $found = 0; $loc_code = ''; - foreach my $line ( @loc_array ) { + foreach my $line (@loc_array) { if ($line =~ /(\w*):(.*):([\w|\.|-]*):/) { - $loc_code .= $3; + $loc_code .= $3; $found = 1; } } @@ -1192,20 +1218,21 @@ sub get_mac_addr { =cut #----------------------------------------------------------------------------- -sub ping_server{ - my $phandle = shift; +sub ping_server { + my $phandle = shift; my $full_path_name = shift; - my $rconsole = shift; - my $node = shift; - my $mac_address = shift; - my $verbose = shift; - my $adap_speed = shift; - my $adap_duplex = shift; - my $list_type = shift; - my $server_ip = shift; - my $client_ip = shift; - my $gateway_ip = shift; + my $rconsole = shift; + my $node = shift; + my $mac_address = shift; + my $verbose = shift; + my $adap_speed = shift; + my $adap_duplex = shift; + my $list_type = shift; + my $server_ip = shift; + my $client_ip = shift; + my $gateway_ip = shift; my $adap_prop_list_array; + #my %env = shift; my $command; my $linklocal_ip; @@ -1223,9 +1250,9 @@ sub ping_server{ #if (exists($env{'FIRMWARE_DUMP'})) { # $full_path_name = Firmware_Dump($phandle); #} - my $j = 0; - my $tty_do_ping = 0; - my $stack_level = 0; + my $j = 0; + my $tty_do_ping = 0; + my $stack_level = 0; my $properties_matched = 0; my $adap_conn; my $speed_list; @@ -1253,41 +1280,45 @@ sub ping_server{ # # state 0, set the current adapter $done[0] = 0; - $cmd[0] = "dev $full_path_name\r"; - $msg[0] = "Status: selected $full_path_name as the active adapter\n"; + $cmd[0] = "dev $full_path_name\r"; + $msg[0] = "Status: selected $full_path_name as the active adapter\n"; + #$pattern[0] = ".*dev(.*)0 >(.*)"; - $pattern[0] = "0 >"; + $pattern[0] = "0 >"; $newstate[0] = 1; # state 1, send property command to $selected type; $done[1] = 0; $cmd[1] = "\" ethernet,$adap_speed,$adap_conn,$adap_duplex\" encode-string \" chosen-network-type\" property\r"; $msg[1] = "Status: chosen network type set\n"; + #$pattern[1] =".*ethernet(.*)0 >(.*)"; - $pattern[1] ="0 >"; - $newstate[1]= 2; + $pattern[1] = "0 >"; + $newstate[1] = 2; # state 2, activate /packages/net $done[2] = 0; - $cmd[2] = "dev /packages/net\r"; + $cmd[2] = "dev /packages/net\r"; $msg[2] = "Status: selected the /packages/net node as the active package\n"; $pattern[2] = ".*dev.*packages.*net(.*)ok(.*)0 >(.*)"; + #$pattern[2] = "ok"; - $newstate[2]= 3; + $newstate[2] = 3; # state 3, ping the server - $done[3] = 0; - $msg[3] = "Status: ping return code now on stack\n"; + $done[3] = 0; + $msg[3] = "Status: ping return code now on stack\n"; $newstate[3] = 4; # get the timeout for ping test my $to4pt; - if ( $ENV{TIMEOUT4PINGTEST} =~ /^\d+$/ ) { + if ($ENV{TIMEOUT4PINGTEST} =~ /^\d+$/) { $to4pt = ",$ENV{TIMEOUT4PINGTEST}"; - } + } #IPv6 - if ( $server_ip =~ /:/ ) { + if ($server_ip =~ /:/) { + #::1, calculate link local address if ($client_ip eq "::1") { my $command = "/opt/xcat/share/xcat/tools/mac2linklocal -m $mac_address"; @@ -1303,10 +1334,11 @@ sub ping_server{ # state 4, all done $done[4] = 0; - $cmd[4] = "0 to my-self\r"; - $msg[4] = "Status: resetting pointer\n"; + $cmd[4] = "0 to my-self\r"; + $msg[4] = "Status: resetting pointer\n"; + #$pattern[4] = "(.*)ok(.*)0 >(.*)"; - $pattern[4] = "ok"; + $pattern[4] = "ok"; $newstate[4] = 5; # state 5, all done @@ -1315,18 +1347,18 @@ sub ping_server{ # for ping, only need to set speed and duplex for ethernet adapters # - if ( $list_type eq "ent" ) { + if ($list_type eq "ent") { $state = 0; # Get the list of properties for this adapter # $adap_prop_list_array = get_adap_prop($phandle, $rconsole, $node, $verbose); - if ( $adap_prop_list_array eq 1 ) { + if ($adap_prop_list_array eq 1) { nc_msg($verbose, "ERROR return from get_adap_prop\n"); return 1; } - if ( $adap_prop_list_array eq 0 ) { + if ($adap_prop_list_array eq 0) { nc_msg($verbose, "No properties found for adapter '$full_path_name'\n"); return 1; } @@ -1338,29 +1370,29 @@ sub ping_server{ my $a_conn; my $a_duplex; for my $prop (@$adap_prop_list_array) { - if( $prop =~ /(.*),(.*),(.*)/) { - $a_speed = $1; - $a_conn = $2; + if ($prop =~ /(.*),(.*),(.*)/) { + $a_speed = $1; + $a_conn = $2; $a_duplex = $3; - if ( ( $a_speed eq $adap_speed ) && ( $a_duplex eq $adap_duplex ) ) { + if (($a_speed eq $adap_speed) && ($a_duplex eq $adap_duplex)) { $properties_matched = 1; - if ( grep {$_ eq $a_conn } @adap_conn_list) { + if (grep { $_ eq $a_conn } @adap_conn_list) { push @adap_conn_list, $a_conn; } } } } - if ( $properties_matched eq 0 ) { - $adap_speed = $a_speed; - $adap_duplex = $a_duplex; + if ($properties_matched eq 0) { + $adap_speed = $a_speed; + $adap_duplex = $a_duplex; $properties_matched = 1; push @adap_conn_list, $a_conn; } $i = scalar(@adap_conn_list); - if ( $properties_matched eq 0 ) { + if ($properties_matched eq 0) { nc_msg($verbose, "'$adap_speed/$adap_duplex' settings are not supported on this adapter\n"); return 1; } @@ -1369,101 +1401,103 @@ sub ping_server{ } $timeout = 300; - while ( $done[$state] eq 0 ) { + while ($done[$state] eq 0) { send_command($verbose, $rconsole, $cmd[$state]); @result = $rconsole->expect( $timeout, - [qr/$pattern[$state]/s=> - sub { - nc_msg($verbose, $msg[$state]); - $rconsole->clear_accum(); - $state = $newstate[$state]; - } + [ qr/$pattern[$state]/s => + sub { + nc_msg($verbose, $msg[$state]); + $rconsole->clear_accum(); + $state = $newstate[$state]; + } ], - [qr/]/=> - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/]/ => + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [qr/(.*)DEFAULT(.*)/=> - sub { - nc_msg($verbose, "Default catch error\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/(.*)DEFAULT(.*)/ => + sub { + nc_msg($verbose, "Default catch error\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [timeout=> - sub { - nc_msg($verbose, "Timeout when openning console\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ timeout => + sub { + nc_msg($verbose, "Timeout when openning console\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [eof=> - sub { - nc_msg($verbose, "Cannot connect to the $node\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Cannot connect to the $node\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); - return 1 if ($rc eq 1); + return 1 if ($rc eq 1); - if ( $state eq 1 ) { + if ($state eq 1) { $adap_conn = $adap_conn_list[$j]; $cmd[1] = "\" ethernet,$adap_speed,$adap_conn,$adap_duplex\" encode-string \" chosen-network-type\" property\r"; nc_msg($verbose, "Status: Trying connector type $adap_conn\n"); $j++; } - if ((($tty_do_ping eq 1) && ($state eq 4)) || ($tty_do_ping != 1) && ($state eq 3) ) { + if ((($tty_do_ping eq 1) && ($state eq 4)) || ($tty_do_ping != 1) && ($state eq 3)) { $ping_debug = $result[2]; } - if ( ( ($tty_do_ping eq 1) && ($state eq 5) ) || ($tty_do_ping != 1) && ($state eq 4) ) { - if ( ($tty_do_ping eq 1) && ($state eq 5) ) { + if ((($tty_do_ping eq 1) && ($state eq 5)) || ($tty_do_ping != 1) && ($state eq 4)) { + if (($tty_do_ping eq 1) && ($state eq 5)) { + #$ping_rc = $result[2]; $stack_level = length($result[4]); - } elsif ( ($state eq 4) && ($tty_do_ping != 1) && ($result[2] =~ /PING SUCCESS/)) { + } elsif (($state eq 4) && ($tty_do_ping != 1) && ($result[2] =~ /PING SUCCESS/)) { $ping_rc = 0; - #} elsif ( $result[2] =~ /unknown word/ ) { - # nc_msg($verbose, "Status: try tty-do-ping.\n"); - # $ping_rc = 1; - # $tty_do_ping = 1; - # $state = 3 ; - # $cmd[3] = "\"" . $full_path_name . ":" . $client_ip . "," . $server_ip . "," . $gateway_ip . "\" tty-do-ping\r"; - # $pattern[3] = "(.*)ok(.*)(\[1-2\]) >(.*)"; - # - # # state 4, get the return code off the stack - # $done[4] = 0; - # $cmd[4] = ".\r"; - # $msg[4] = "Status: return code displayed, stack empty\n"; - # $pattern[4] = "(\[0-9\]*) ok(.*)(\[0-1\]) >(.*)"; - # $newstate[4] = 5; - # - # # this command is used to work around a default catch problem in open - # # firmware. Without it, a default catch occurs if we try to set - # # adapter properties again after a ping - # # - # # state 5, re$pointer - # $done[5] = 0; - # $cmd[5] = "0 to my-self\r"; - # $msg[5] = "Status: resetting pointer\n" ; - # $pattern[5] = "(.*)ok(.*)0 >(.*)"; - # $newstate[5] = 6 ; - # - # # state 6, all done - # $done[6] = 1; + + #} elsif ( $result[2] =~ /unknown word/ ) { + # nc_msg($verbose, "Status: try tty-do-ping.\n"); + # $ping_rc = 1; + # $tty_do_ping = 1; + # $state = 3 ; + # $cmd[3] = "\"" . $full_path_name . ":" . $client_ip . "," . $server_ip . "," . $gateway_ip . "\" tty-do-ping\r"; + # $pattern[3] = "(.*)ok(.*)(\[1-2\]) >(.*)"; + # + # # state 4, get the return code off the stack + # $done[4] = 0; + # $cmd[4] = ".\r"; + # $msg[4] = "Status: return code displayed, stack empty\n"; + # $pattern[4] = "(\[0-9\]*) ok(.*)(\[0-1\]) >(.*)"; + # $newstate[4] = 5; + # + # # this command is used to work around a default catch problem in open + # # firmware. Without it, a default catch occurs if we try to set + # # adapter properties again after a ping + # # + # # state 5, re$pointer + # $done[5] = 0; + # $cmd[5] = "0 to my-self\r"; + # $msg[5] = "Status: resetting pointer\n" ; + # $pattern[5] = "(.*)ok(.*)0 >(.*)"; + # $newstate[5] = 6 ; + # + # # state 6, all done + # $done[6] = 1; } else { $ping_rc = 1; } - if ( $ping_rc eq 0 ) { + if ($ping_rc eq 0) { nc_msg($verbose, "# $full_path_name ping successful.\n"); - } elsif ( $ping_rc eq 1 ) { + } elsif ($ping_rc eq 1) { nc_msg($verbose, "# $full_path_name ping unsuccessful.\n"); nc_msg($verbose, "# $full_path_name ping unsuccessful.\n"); nc_msg($verbose, "$ping_debug\n"); @@ -1472,55 +1506,56 @@ sub ping_server{ # be removed. Check for it, and remove if necessary my $matchexp = 0; my @exp_out; - while ( $stack_level != 0 ) { + while ($stack_level != 0) { @exp_out = (); send_command($verbose, $rconsole, ".\r"); @exp_out = $rconsole->expect( - [qr/(\[0-9\]*) ok(.*)(\[0-1\]) >(.*)/s=> - sub { - $rconsole->clear_accum(); - $matchexp = 1; - } + [ qr/(\[0-9\]*) ok(.*)(\[0-1\]) >(.*)/s => + sub { + $rconsole->clear_accum(); + $matchexp = 1; + } ], - [qr/]/=> - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/]/ => + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [qr/(.*)DEFAULT(.*)/=> - sub { - nc_msg($verbose, "Default catch error\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/(.*)DEFAULT(.*)/ => + sub { + nc_msg($verbose, "Default catch error\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [timeout=> - sub { - nc_msg($verbose, "Timeout in ping server\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ timeout => + sub { + nc_msg($verbose, "Timeout in ping server\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [eof => - sub { - nc_msg($verbose, "Cannot connect to $node\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); if ($matchexp) { - $matchexp = 0; + $matchexp = 0; $stack_level = length($exp_out[4]); nc_msg($verbose, "Status: stack_level is <$stack_level>\n"); } } + # Check if there are any more adapter connector types # to try # - if ( ( $list_type eq "ent" ) && ( $j < $i ) ) { + if (($list_type eq "ent") && ($j < $i)) { $adap_conn = $adap_conn_list[$j]; nc_msg($verbose, "Status: Trying connector type $adap_conn\n"); $j++; @@ -1533,10 +1568,10 @@ sub ping_server{ # the array. This is OK, since we only set the current # adapter once, upon entering this procedure. # - $done[0] = 0; - $cmd[0] = "0 to my-self\r"; - $msg[0] = "Status: resetting pointer\n"; - $pattern[0] = "(.*)ok(.*)0 >(.*)"; + $done[0] = 0; + $cmd[0] = "0 to my-self\r"; + $msg[0] = "Status: resetting pointer\n"; + $pattern[0] = "(.*)ok(.*)0 >(.*)"; $newstate[0] = 1; $state = 0; @@ -1572,9 +1607,9 @@ sub ping_server{ #----------------------------------------------------------------------------- sub set_disk_boot { my @expect_out = shift; - my $rconsole = shift; - my $node = shift; - my $verbose = shift; + my $rconsole = shift; + my $node = shift; + my $verbose = shift; my $x0; my $x1; my $x2; @@ -1590,10 +1625,10 @@ sub set_disk_boot { # state 0, get SMS screen $done[0] = 0; - if($expect_out[0] =~ /(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Select Boot Options(\r)/){ - $x0 = $1; - $x1 = $2; - $x2 = $3; + if ($expect_out[0] =~ /(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Select Boot Options(\r)/) { + $x0 = $1; + $x1 = $2; + $x2 = $3; $command = $4; } $cmd[0] = "$command\r"; @@ -1602,111 +1637,111 @@ sub set_disk_boot { $newstate[0] = 1; # state 1, Multiboot - $done[1] = 0; - $msg[1] = "Status: Multiboot\n"; - $pattern[1] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Select 1st Boot Device(\r)"; + $done[1] = 0; + $msg[1] = "Status: Multiboot\n"; + $pattern[1] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Select 1st Boot Device(\r)"; $newstate[1] = 2; # state 2, Configure Boot Device Order - $done[2] = 0; - $msg[2] = "Status: Configure Boot Device Order"; - $pattern[2] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Hard Drive(.*)"; + $done[2] = 0; + $msg[2] = "Status: Configure Boot Device Order"; + $pattern[2] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Hard Drive(.*)"; $newstate[2] = 3; # state 3, Select Device Type - $done[3] = 0; - $msg[3] = "Status: Select Device Type"; - $pattern[3] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)SCSI(.*)"; + $done[3] = 0; + $msg[3] = "Status: Select Device Type"; + $pattern[3] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)SCSI(.*)"; $newstate[3] = 4; # state 4, Select Media Type - $done[4] = 0; - $msg[4] = "Status: Select Media Type"; - $pattern[4] = "(\n)(\[ ])(\[1])(\[.])(\[ ]+)(\\S+)(.*)"; - $newstate[4] = 5 ; + $done[4] = 0; + $msg[4] = "Status: Select Media Type"; + $pattern[4] = "(\n)(\[ ])(\[1])(\[.])(\[ ]+)(\\S+)(.*)"; + $newstate[4] = 5; # state 5, Select Media Adapter $done[5] = 0; - $msg[5] = "Status: Select Media Adapter"; + $msg[5] = "Status: Select Media Adapter"; $pattern[5] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)(\\S)(\[ ]+)SCSI (\[0-9]+) MB Harddisk(.*)loc=(.*)\[)]"; $newstate[5] = 6; # state 6, Select Device - $done[6] = 0; - $msg[6] = "Status: Select Device"; - $pattern[6] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Set Boot Sequence(.*)"; + $done[6] = 0; + $msg[6] = "Status: Select Device"; + $pattern[6] = "(\n)(\[ ])(\[0-9])(\[.])(\[ ]+)Set Boot Sequence(.*)"; $newstate[6] = 7; # state 7, Select Task - $done[7] = 0; - $msg[7] = "Status: Select Task"; - $pattern[7] = "(.*)Current Boot Sequence(.*)"; - $newstate[7] = 8 ; + $done[7] = 0; + $msg[7] = "Status: Select Task"; + $pattern[7] = "(.*)Current Boot Sequence(.*)"; + $newstate[7] = 8; # state 8, Return to Main Menu - $done[8] = 0; - $cmd[8] = "M"; - $msg[8] = "Status: Restored Default Setting.\n" ; - $pattern[8] = "(.*)Navigation key(.*)"; + $done[8] = 0; + $cmd[8] = "M"; + $msg[8] = "Status: Restored Default Setting.\n"; + $pattern[8] = "(.*)Navigation key(.*)"; $newstate[8] = 9; # state 9, Getting to SMS Main Menu - $done[9] = 0; - $cmd[9] = "0\r"; - $msg[9] = "Status: Getting to SMS Main Menu.\n"; - $pattern[9] = "(.*)Exit SMS(.*)Prompt?(.*)"; + $done[9] = 0; + $cmd[9] = "0\r"; + $msg[9] = "Status: Getting to SMS Main Menu.\n"; + $pattern[9] = "(.*)Exit SMS(.*)Prompt?(.*)"; $newstate[9] = 10; # state 10, Exiting SMS - $done[10] = 0; - $cmd[10] = "Y"; - $msg[10] = "Status: Exiting SMS.\n"; - $pattern[10] = "(.*)ok(.*)0 >(.*)"; + $done[10] = 0; + $cmd[10] = "Y"; + $msg[10] = "Status: Exiting SMS.\n"; + $pattern[10] = "(.*)ok(.*)0 >(.*)"; $newstate[10] = 11; # state 11, all done $done[11] = 1; $timeout = 30; - $state = 0; + $state = 0; - while ( $done[$state] eq 0 ) { + while ($done[$state] eq 0) { send_command($verbose, $rconsole, $cmd[$state]); $rconsole->expect( - [qr/$pattern[$state]/=> - sub { + [ qr/$pattern[$state]/ => + sub { $rconsole->clear_accum(); - if ( $state eq 4 ) { - if ( $expect_out[6] eq "None" ) { + if ($state eq 4) { + if ($expect_out[6] eq "None") { $state = 8; } } $state = $newstate[$state]; - if ( ($state != 8) && ($state != 9) && ($state != 10) ) { + if (($state != 8) && ($state != 9) && ($state != 10)) { $cmd[$state] = "$expect_out[3]\r"; } - } + } ], - [qr/THE SELECTED DEVICES WERE NOT DETECTED IN THE SYSTEM/=> - sub { + [ qr/THE SELECTED DEVICES WERE NOT DETECTED IN THE SYSTEM/ => + sub { $rconsole->clear_accum(); nc_msg($verbose, " Status: THE hard disk WERE NOT DETECTED IN THE SYSTEM!\n"); $rc = 1; - } + } ], - [timeout => - sub { + [ timeout => + sub { $rconsole->clear_accum(); nc_msg($verbose, "Timeout in settin boot order\n"); $rc = 1; - } + } ], - [eof => - sub { + [ eof => + sub { $rconsole->clear_accum(); nc_msg($verbose, "Cannot connect to $node\n"); $rc = 1; - } + } ], ); if ($rc eq 1) { @@ -1737,21 +1772,21 @@ sub boot_network { { $rconsole = shift; } - my $full_path_name = shift; - my $speed = shift; - my $duplex = shift; + my $full_path_name = shift; + my $speed = shift; + my $duplex = shift; my $chosen_adap_type = shift; - my $server_ip = shift; - my $client_ip = shift; - my $gateway_ip = shift; - my $netmask = shift; - my $dump_target = shift; - my $dump_lun = shift; - my $dump_port = shift; - my $verbose = shift; - my $extra_args = shift; - my $node = shift; - my $set_boot_order = shift; + my $server_ip = shift; + my $client_ip = shift; + my $gateway_ip = shift; + my $netmask = shift; + my $dump_target = shift; + my $dump_lun = shift; + my $dump_port = shift; + my $verbose = shift; + my $extra_args = shift; + my $node = shift; + my $set_boot_order = shift; my @net_device; my @pattern; my @cmd; @@ -1790,14 +1825,14 @@ sub boot_network { $net_device[0] = "$full_path_name:iscsi,ciaddr=$client_ip,subnet-mask=$netmask,itname=dummy,iport=$dump_port,ilun=$dump_lun,iname=$dump_target,siaddr=$server_ip,2"; $pattern[0] = "iSCSI"; } else { - if ($extra_args ne "" ) { - if ( $server_ip =~ /:/ ) { #ipv6 + if ($extra_args ne "") { + if ($server_ip =~ /:/) { #ipv6 $net_device[0] = "$full_path_name:ipv6,speed=$speed,duplex=$duplex,siaddr=$server_ip,ciaddr=$client_ip,giaddr=$gateway_ip,filename=$node,$extra_args"; } else { $net_device[0] = "$full_path_name:speed=$speed,duplex=$duplex,bootp,$server_ip,,$client_ip,$gateway_ip $extra_args"; } } else { - if ( $server_ip =~ /:/ ) { #ipv6 + if ($server_ip =~ /:/) { #ipv6 $net_device[0] = "$full_path_name:ipv6,speed=$speed,duplex=$duplex,siaddr=$server_ip,ciaddr=$client_ip,giaddr=$gateway_ip,filename=$node"; } else { $net_device[0] = "$full_path_name:speed=$speed,duplex=$duplex,bootp,$server_ip,,$client_ip,$gateway_ip"; @@ -1806,29 +1841,29 @@ sub boot_network { $pattern[0] = "BOOTP"; } - $cmd[0] = "boot $net_device[0]\r"; - $msg[0] = "Status: network boot initiated\n"; + $cmd[0] = "boot $net_device[0]\r"; + $msg[0] = "Status: network boot initiated\n"; $newstate[0] = 99; # If the install adapter is FDDI, don't set the speed and duplex # state 1 - $done[1] = 0; + $done[1] = 0; $net_device[1] = "$full_path_name:bootp,$server_ip,,$client_ip,$gateway_ip"; - $cmd[1] = "boot $net_device[1]\r"; - $msg[1] = "Status: network boot initiated\n"; - $pattern[1] = "BOOTP"; - $newstate[1] = 99; + $cmd[1] = "boot $net_device[1]\r"; + $msg[1] = "Status: network boot initiated\n"; + $pattern[1] = "BOOTP"; + $newstate[1] = 99; # state 99, all done $done[99] = 1; # state -1, all done - $done[100] = 1; #-1??? + $done[100] = 1; #-1??? - if ($chosen_adap_type eq "fddi" ) { + if ($chosen_adap_type eq "fddi") { $state = 1; } else { - if ($speed eq "" || $duplex eq "" ) { + if ($speed eq "" || $duplex eq "") { nc_msg($verbose, "Cannot set speed or duplex for network boot\n"); return 1; } @@ -1837,104 +1872,105 @@ sub boot_network { ################################################################## # Set the boot device order. ################################################################## - if ( $set_boot_order > 0 ) { - $done[2] = 0; - $msg[2] = "Status: read original boot-device\n"; - $cmd[2] = "printenv boot-device\r"; - $pattern[2] = ".*boot-device\\s+(\\S+)(.*)ok(.*)"; - $newstate[2] = 3; + if ($set_boot_order > 0) { + $done[2] = 0; + $msg[2] = "Status: read original boot-device\n"; + $cmd[2] = "printenv boot-device\r"; + $pattern[2] = ".*boot-device\\s+(\\S+)(.*)ok(.*)"; + $newstate[2] = 3; - $done[3] = 0; - $msg[3] = "Status: set the environment variable boot-device\n"; - $pattern[3] = "(.*)ok(.*)(\[0-9]) >(.*)"; - if ( $state eq 0 ) { - $newstate[3] = 0; + $done[3] = 0; + $msg[3] = "Status: set the environment variable boot-device\n"; + $pattern[3] = "(.*)ok(.*)(\[0-9]) >(.*)"; + if ($state eq 0) { + $newstate[3] = 0; } else { - $newstate[3] = 1; + $newstate[3] = 1; } $state = 2; } - $timeout = 30; # shouldn't take long - while ( $done[$state] eq 0 ) { + $timeout = 30; # shouldn't take long + while ($done[$state] eq 0) { send_command($verbose, $rconsole, $cmd[$state]); $rconsole->expect( - [qr/$pattern[$state]/=> - sub { + [ qr/$pattern[$state]/ => + sub { $rconsole->clear_accum(); my @expect_out = shift; - if ( $state eq 2 ) { - if ( $set_boot_order eq 1 ) { + if ($state eq 2) { + if ($set_boot_order eq 1) { ######################################## # Set network as boot device ######################################## $cmd[3] = "setenv boot-device $net_device[$newstate[3]]\r"; - } elsif ( $set_boot_order eq 2 ) { + } elsif ($set_boot_order eq 2) { ######################################## # Set network as 1st boot device,disk as 2nd boot device ######################################## $boot_device_bk = $expect_out[1]; - $cmd[3] = "setenv boot-device $net_device[$newstate[3]] $boot_device_bk\r"; - } elsif ( $set_boot_order eq 3 ) { + $cmd[3] = "setenv boot-device $net_device[$newstate[3]] $boot_device_bk\r"; + } elsif ($set_boot_order eq 3) { ######################################## # Set disk as 1st boot device,network as 2nd boot device ######################################## $boot_device_bk = $expect_out[1]; - $cmd[3] = "setenv boot-device $boot_device_bk $net_device[$newstate[3]]\r"; - } elsif ( $set_boot_order eq 4 ) { + $cmd[3] = "setenv boot-device $boot_device_bk $net_device[$newstate[3]]\r"; + } elsif ($set_boot_order eq 4) { ######################################## # set disk as boot device ######################################## $boot_device_bk = $expect_out[1]; - $cmd[3] = "setenv boot-device $boot_device_bk\r"; + $cmd[3] = "setenv boot-device $boot_device_bk\r"; } } nc_msg($verbose, $msg[$state]); $state = $newstate[$state]; - } + } ], - [qr/----/=> - sub { - nc_msg ($verbose, $msg[$state]); - $rconsole->clear_accum(); - $state = $newstate[$state]; - } + [ qr/----/ => + sub { + nc_msg($verbose, $msg[$state]); + $rconsole->clear_accum(); + $state = $newstate[$state]; + } ], + # For some old firmware, does not output "----" - [qr/BOOTP/=> - sub { - nc_msg ($verbose, $msg[$state]); - $rconsole->clear_accum(); - $state = $newstate[$state]; - } + [ qr/BOOTP/ => + sub { + nc_msg($verbose, $msg[$state]); + $rconsole->clear_accum(); + $state = $newstate[$state]; + } ], - [qr/]/=> - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/]/ => + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [qr/(.*)DEFAULT(.*)/=> - sub { + [ qr/(.*)DEFAULT(.*)/ => + sub { nc_msg($verbose, "Default catch error\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], - [timeout=> - sub { + [ timeout => + sub { nc_msg($verbose, "Timeout when openning console\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], - [eof=> - sub { + [ eof => + sub { nc_msg($verbose, "Cannot connect to the $node\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], ); return 1 if ($rc eq 1); @@ -1947,8 +1983,9 @@ sub boot_network { # sub Boot { my $rconsole = shift; - my $node = shift; - my $verbose = shift; + my $node = shift; + my $verbose = shift; + #my @expect_out = shift; my $rc = 0; my $timeout; @@ -1956,17 +1993,18 @@ sub Boot { nc_msg($verbose, "Status: waiting for the boot image to boot up.\n"); - $timeout = 1200; # could take a while depending on configuration + $timeout = 1200; # could take a while depending on configuration $rconsole->expect( - [qr/RESTART-CMD/=> - sub { + [ qr/RESTART-CMD/ => + sub { # If we see a "problem doing RESTART-CMD" message, we re-hit the OPEN-DEV # issue after firmware rebooted itself and we need to retry the netboot once more nc_msg($verbose, "The network boot ended in an error.\nError : RESTART-CMD\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], + #[!(qr/[0-9A-F]+/)=> # sub { # nc_msg($verbose, "The network boot ended in an error.\n"); @@ -1974,58 +2012,62 @@ sub Boot { # $rc = 1; # } #], - [qr/BOOTP/=> #-ex - sub { + [ qr/BOOTP/ => #-ex + sub { nc_msg($verbose, "# Network boot proceeding - matched BOOTP, exiting.\n"); $rconsole->clear_accum(); - } + } ], + # Welcome to AIX - some old firmware does not output BOOTP or ---- - [qr/Welcome/=> #-ex - sub { + [ qr/Welcome/ => #-ex + sub { nc_msg($verbose, "# Network boot proceeding - matched Welcome, exiting.\n"); $rconsole->clear_accum(); - } + } ], + # tftp file download - some old firmware does not output BOOTP or ---- - [qr/FILE/=> #-ex - sub { + [ qr/FILE/ => #-ex + sub { nc_msg($verbose, "# Network boot proceeding - matched FILE.\n"); $rconsole->clear_accum(); - } + } ], + # some old firmware does not output BOOTP or ---- - [qr/Elapsed/=> #-ex - sub { + [ qr/Elapsed/ => #-ex + sub { nc_msg($verbose, "# Network boot proceeding - matched Elapsed, exiting.\n"); $rconsole->clear_accum(); - } + } ], - [qr/------/=> #-ex - sub { + [ qr/------/ => #-ex + sub { nc_msg($verbose, "# Network boot proceeding, exiting.\n"); $rconsole->clear_accum(); - } + } ], - [timeout=> - sub { - my $mins = $timeout/60; - nc_msg($verbose, "Timeout waiting for the boot image to boot up. \ + [ timeout => + sub { + my $mins = $timeout / 60; + nc_msg($verbose, "Timeout waiting for the boot image to boot up. \ \n waited '$mins' minutes for the boot image to boot. \ \nEither the boot up has taken longer than expected or \ \nthere is a problem with system boot. Check the boot \ \nof the node to determine if there is a problem.\n"); - $rconsole->clear_accum(); - #nc_msg($verbose, $expect_out[buffer]); - $rc = 1; - } + $rconsole->clear_accum(); + + #nc_msg($verbose, $expect_out[buffer]); + $rc = 1; + } ], - [eof=> - sub { - nc_msg($verbose, "Port closed waiting for boot image to boot.\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Port closed waiting for boot image to boot.\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); return $rc; @@ -2048,7 +2090,7 @@ sub multiple_open_dev { { $rconsole = shift; } - my $node = shift; + my $node = shift; my $verbose = shift; my $expect_out; my $command; @@ -2059,7 +2101,7 @@ sub multiple_open_dev { send_command($verbose, $rconsole, "FALSE value OPEN-DEV_DEBUG \r"); if (exists $ENV{'OPEN_DEV_DEBUG'}) { - send_command($verbose, $rconsole, "TRUE to OPEN-DEV_DEBUG \r"); + send_command($verbose, $rconsole, "TRUE to OPEN-DEV_DEBUG \r"); } $command = ": new-open-dev ( str len -- true|false ) \ @@ -2104,33 +2146,34 @@ sub multiple_open_dev { $timeout = 30; $rconsole->expect( $timeout, - [qr/new-open-dev(.*)ok/=> - #[qr/>/=> - sub { + [ qr/new-open-dev(.*)ok/ => + + #[qr/>/=> + sub { nc_msg($verbose, "Status: at End of multiple_open_dev \n"); $rconsole->clear_accum(); - } + } ], - [qr/]/=> - sub { + [ qr/]/ => + sub { nc_msg($verbose, "Unexpected prompt\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], - [timeout => - sub { + [ timeout => + sub { send_user(2, "Timeout\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], - [eof => - sub { + [ eof => + sub { send_user(2, "Cannot connect to $node\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], ); @@ -2139,34 +2182,35 @@ sub multiple_open_dev { $rconsole->expect( $timeout, - [qr/patch new-open-dev(.*)ok/=> - #[qr/>/=> - sub { + [ qr/patch new-open-dev(.*)ok/ => + + #[qr/>/=> + sub { nc_msg($verbose, "Status: at End of multiple_open_dev \n"); $rconsole->clear_accum(); return 0; - } + } ], - [qr/]/=> - sub { + [ qr/]/ => + sub { nc_msg($verbose, "Unexpected prompt\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], - [timeout => - sub { + [ timeout => + sub { send_user(2, "Timeout\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], - [eof => - sub { + [ eof => + sub { send_user(2, "Cannot connect to $node\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], ); @@ -2179,12 +2223,12 @@ sub multiple_open_dev { # Declare procedure to get additional firmware debug statement. # ################################################################### -sub Firmware_Dump { - my $rconsole = shift; - my $node = shift; - my $verbose = shift; +sub Firmware_Dump { + my $rconsole = shift; + my $node = shift; + my $verbose = shift; my $device_path = shift; - my $phandle = shift; + my $phandle = shift; my $expect_out; my @done; my @cmd; @@ -2193,130 +2237,130 @@ sub Firmware_Dump { my @newstate; my $timeout; my $state = 0; - my $rc = 0; + my $rc = 0; - nc_msg($verbose,"Status: Firmware_Dump start\n"); + nc_msg($verbose, "Status: Firmware_Dump start\n"); # state 0 - $done[0] = 0; - $cmd[0] = "dev /packages/obp-tftp\r"; - $msg[0] = "Status: selected /packages/obp_tftp\n"; - $pattern[0] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[0] = 0; + $cmd[0] = "dev /packages/obp-tftp\r"; + $msg[0] = "Status: selected /packages/obp_tftp\n"; + $pattern[0] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[0] = 1; # state 1 $done[1] = 0; - $cmd[1] = ": testing1 .\" OBP-TFTP entry\" cr init-nvram-adptr-parms ;\r"; - $msg[1] = "Status: running test - OBP-TFTP entry\n"; - $pattern[1] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $cmd[1] = ": testing1 .\" OBP-TFTP entry\" cr init-nvram-adptr-parms ;\r"; + $msg[1] = "Status: running test - OBP-TFTP entry\n"; + $pattern[1] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[1] = 2; # state 2 - $done[2] = 0; - $cmd[2] = ": testing2 .\" OBP-TFTP exit, TRUE\" cr true ;\r"; - $msg[2] = "Status: running test - OBP-TFTP exit\n"; - $pattern[2] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[2] = 0; + $cmd[2] = ": testing2 .\" OBP-TFTP exit, TRUE\" cr true ;\r"; + $msg[2] = "Status: running test - OBP-TFTP exit\n"; + $pattern[2] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[2] = 3; # state 3 - $done[3] = 0; - $cmd[3] = "patch testing1 init-nvram-adptr-parms open\r"; - $msg[3] = "Status: running test - patch testing1\n"; - $pattern[3] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[3] = 0; + $cmd[3] = "patch testing1 init-nvram-adptr-parms open\r"; + $msg[3] = "Status: running test - patch testing1\n"; + $pattern[3] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[3] = 4; # state 4 - $done[4] = 0; - $cmd[4] = "patch testing2 true open\r"; - $msg[4] = "Status: running test - patch testing2\n"; - $pattern[4] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[4] = 0; + $cmd[4] = "patch testing2 true open\r"; + $msg[4] = "Status: running test - patch testing2\n"; + $pattern[4] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[4] = 5; # state 5 - $done[5] = 0; - $cmd[5] = "dev $device_path\r"; - $msg[5] = "Status: running test - dev $device_path\n"; - $pattern[5] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[5] = 0; + $cmd[5] = "dev $device_path\r"; + $msg[5] = "Status: running test - dev $device_path\n"; + $pattern[5] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[5] = 6; # state 6 - $done[6] = 0; - $cmd[6] = "true to debug-init\r"; - $msg[6] = "Status: running test - true to debug-init\n"; - $pattern[6] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[6] = 0; + $cmd[6] = "true to debug-init\r"; + $msg[6] = "Status: running test - true to debug-init\n"; + $pattern[6] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[6] = 7; # state 7 - $done[7] = 0; - $cmd[7] = "true to debug-error\r"; - $msg[7] = "Status: running test - true to debug-error\n"; - $pattern[7] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[7] = 0; + $cmd[7] = "true to debug-error\r"; + $msg[7] = "Status: running test - true to debug-error\n"; + $pattern[7] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[7] = 8; # state 8 - $done[8] = 0; - $cmd[8] = "$phandle to active-package\r"; - $msg[8] = "Status: running $phandle to active-package\n"; - $pattern[8] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[8] = 0; + $cmd[8] = "$phandle to active-package\r"; + $msg[8] = "Status: running $phandle to active-package\n"; + $pattern[8] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[8] = 9; # state 9 - $done[9] = 0; - $cmd[9] = ".properties\r"; - $msg[9] = "Status: running .properies\n"; - $pattern[9] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[9] = 0; + $cmd[9] = ".properties\r"; + $msg[9] = "Status: running .properies\n"; + $pattern[9] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[9] = 10; # state 10 - $done[10] = 0; - $cmd[10] = "clear\r"; - $msg[10] = "Status: running clear\n"; - $pattern[10] = "(.*)ok(.*)(\[0-9]) >(.*)"; + $done[10] = 0; + $cmd[10] = "clear\r"; + $msg[10] = "Status: running clear\n"; + $pattern[10] = "(.*)ok(.*)(\[0-9]) >(.*)"; $newstate[10] = 11; # state 11, all done $done[11] = 1; - $state = 0; - $timeout = 30; # shouldn't take long + $state = 0; + $timeout = 30; # shouldn't take long while ($done[$state] == 0) { send_command($verbose, $rconsole, $cmd[$state]); $rconsole->expect( - [qr/$pattern[$state]/ => - sub { - nc_msg($verbose, $msg[$state]); - $rconsole->clear_accum(); - $state = $newstate[$state]; - } + [ qr/$pattern[$state]/ => + sub { + nc_msg($verbose, $msg[$state]); + $rconsole->clear_accum(); + $state = $newstate[$state]; + } ], - [qr/]/=> - sub { - nc_msg($verbose, "Unexpected prompt\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/]/ => + sub { + nc_msg($verbose, "Unexpected prompt\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [qr/(.*)DEFAULT(.*)/=> - sub { - nc_msg($verbose, "Default catch error\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ qr/(.*)DEFAULT(.*)/ => + sub { + nc_msg($verbose, "Default catch error\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [timeout=> - sub { - nc_msg($verbose, "Timeout\n"); - nc_msg($verbose, "Status: timeout state is $state\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ timeout => + sub { + nc_msg($verbose, "Timeout\n"); + nc_msg($verbose, "Status: timeout state is $state\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], - [eof => - sub { - nc_msg($verbose, "Cannot connect to $node\n"); - $rconsole->clear_accum(); - $rc = 1; - } + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node\n"); + $rconsole->clear_accum(); + $rc = 1; + } ], ); return 1 if ($rc eq 1); @@ -2337,6 +2381,7 @@ sub Firmware_Dump { 2 - usage error =cut + #----------------------------------------------------------------------------- sub lparnetbootexp { @@ -2345,9 +2390,9 @@ sub lparnetbootexp { $opt = shift; } - my $CONSOLEBIN = "/opt/xcat/bin/rcons"; - my $PROGRAM = "lpar_netboot"; - my $noboot = 0; #default is to boot + my $CONSOLEBIN = "/opt/xcat/bin/rcons"; + my $PROGRAM = "lpar_netboot"; + my $noboot = 0; #default is to boot my $Boot_timeout = 3000; my @expect_out; my $req = shift; @@ -2368,23 +2413,24 @@ sub lparnetbootexp my $list_type; my $sysoutput; my $exp_internal; -# Flags and initial variable - my $discovery = 0; - my $discover_all = 0; - my $discoverynoping = 0; + + # Flags and initial variable + my $discovery = 0; + my $discover_all = 0; + my $discoverynoping = 0; my $discoverytimeout = 0; - my $verbose = 0; + my $verbose = 0; my $discover_macaddr = 0; - my $rc = 0; - my $debug_flag = 0; - my $rmvterm_flag = 0; - my $immed_flag = 0; - my $from_of = 0; - my $dev_type_found = 0; - my $list_physical = 0; - my $set_boot_order = 0; - my $colon = 0; - my $choice = 0; + my $rc = 0; + my $debug_flag = 0; + my $rmvterm_flag = 0; + my $immed_flag = 0; + my $from_of = 0; + my $dev_type_found = 0; + my $list_physical = 0; + my $set_boot_order = 0; + my $colon = 0; + my $choice = 0; my $full_path_name; my $adap_speed; my $adap_duplex; @@ -2400,121 +2446,121 @@ sub lparnetbootexp my $phys_loc; my $userid; my $passwd; - my $prompt = "\\\$ \$"; + my $prompt = "\\\$ \$"; my $ssh_spawn_id = 0; my $mac_address; my @outputarray; my $outputarrayindex = 0; $::CALLBACK = $req->{callback}; -# -# Log the process id -# + # + # Log the process id + # my $proc_id = getppid; nc_msg($verbose, "$PROGRAM Status: process id is $proc_id\n"); -# -# -# Process command line options and parameters -# -# -#done== + # + # + # Process command line options and parameters + # + # + #done== - if ( exists ($opt->{A})) { + if (exists($opt->{A})) { $discover_all = 1; } - if ( exists ($opt->{C})) { + if (exists($opt->{C})) { $client_ip = $opt->{C}; } - if ( exists ($opt->{D})) { + if (exists($opt->{D})) { $discovery = 1; } - if ( exists ($opt->{noping})) { + if (exists($opt->{noping})) { $discoverynoping = 1; } - if ( exists ($opt->{G})) { + if (exists($opt->{G})) { $gateway_ip = $opt->{G}; } - if ( exists ($opt->{P})) { + if (exists($opt->{P})) { $list_physical = 1; } - if ( exists ($opt->{M})) { + if (exists($opt->{M})) { $discover_macaddr = 1; } - if ( exists ($opt->{N})) { + if (exists($opt->{N})) { $netmask = $opt->{N}; } - if ( exists ($opt->{S})) { + if (exists($opt->{S})) { $server_ip = $opt->{S}; } - if ( exists ($opt->{c})) { + if (exists($opt->{c})) { $colon = 1; } - if ( exists ($opt->{d})) { + if (exists($opt->{d})) { $adap_duplex = $opt->{d}; } - if ( exists ($opt->{f})) { + if (exists($opt->{f})) { $rmvterm_flag = 1; } - if ( exists ($opt->{g})) { + if (exists($opt->{g})) { $extra_args = $opt->{g}; } - if ( exists ($opt->{i})) { + if (exists($opt->{i})) { $immed_flag = 1; } - if ( exists ($opt->{o})) { + if (exists($opt->{o})) { $from_of = 1; } - if ( exists ($opt->{w})) { + if (exists($opt->{w})) { $set_boot_order = $opt->{w}; } - if ( exists ($opt->{L})) { + if (exists($opt->{L})) { $dump_lun = $opt->{L}; } - if ( exists ($opt->{l})) { + if (exists($opt->{l})) { $phys_loc = $opt->{l}; } - if ( exists ($opt->{m})) { + if (exists($opt->{m})) { $macaddress = $opt->{m}; } - if ( exists ($opt->{n})) { + if (exists($opt->{n})) { $noboot = 1; } - if ( exists ($opt->{p})) { + if (exists($opt->{p})) { $dump_port = $opt->{p}; } - if ( exists ($opt->{s})) { + if (exists($opt->{s})) { $adap_speed = $opt->{s}; } - if ( exists ($opt->{T})) { + if (exists($opt->{T})) { $dump_target = $opt->{T}; } - if ( exists ($opt->{t})) { + if (exists($opt->{t})) { $list_type = $opt->{t}; - if ( $list_type eq "hfi-ent" ) { - $dev_pat[0] = "hfi-ethernet"; + if ($list_type eq "hfi-ent") { + $dev_pat[0] = "hfi-ethernet"; $dev_type[0] = "hfi-ent"; } # @@ -2522,29 +2568,30 @@ sub lparnetbootexp # $dev_type_found = 0; foreach my $dev (@dev_type) { - if ( $dev eq $list_type) { + if ($dev eq $list_type) { $dev_type_found = 1; last; } } - if ( $dev_type_found eq 0 ) { - nc_msg($verbose, "$PROGRAM:$dev_type_found, '$list_type' is not a valid adapter choice\n"); - return [1]; + if ($dev_type_found eq 0) { + nc_msg($verbose, "$PROGRAM:$dev_type_found, '$list_type' is not a valid adapter choice\n"); + return [1]; } } - if ( exists ($opt->{v})) { + if (exists($opt->{v})) { $verbose = 1; } else { $verbose = 0; } - if ( exists ($opt->{x})) { + if (exists($opt->{x})) { $debug_flag = 1; } - if ( exists ($opt->{help})) { + if (exists($opt->{help})) { usage; } + #set arg0 [lindex $argv 0] #set arg1 [lindex $argv 1] #if ( scalar(%$opt) > 10 ) { @@ -2552,52 +2599,54 @@ sub lparnetbootexp # usage; #} - if ( $list_physical eq 0 ) { - $dev_pat[3] = "l-lan"; + if ($list_physical eq 0) { + $dev_pat[3] = "l-lan"; $dev_type[3] = "ent"; - $dev_count = scalar(@dev_pat); + $dev_count = scalar(@dev_pat); } else { - $dev_pat[3] = ""; + $dev_pat[3] = ""; $dev_type[3] = ""; - $dev_count = scalar(@dev_pat); + $dev_count = scalar(@dev_pat); } - if ( $set_boot_order > 1 ) { - $dev_pat[4] = "scsi"; + if ($set_boot_order > 1) { + $dev_pat[4] = "scsi"; $dev_type[4] = "disk"; - $dev_count = scalar(@dev_pat); + $dev_count = scalar(@dev_pat); } - my $node = $opt->{node}; + my $node = $opt->{node}; my $profile = $opt->{pprofile}; - my $manage = $opt->{fsp}; - my $lparid = $opt->{id}; - my $hcp = $opt->{hcp}; + my $manage = $opt->{fsp}; + my $lparid = $opt->{id}; + my $hcp = $opt->{hcp}; - if ($dev_type_found) { nc_msg($verbose, "$PROGRAM Status: List only $list_type adapters\n"); } - if ($noboot) { nc_msg($verbose, "$PROGRAM Status: -n (no boot) flag detected\n"); } - if ($discovery) { nc_msg($verbose, "$PROGRAM Status: -D (discovery) flag detected\n"); } - if ($discoverynoping) { nc_msg($verbose, "$PROGRAM Status: --noping (discovery) flag detected\n"); } - if ($discover_all) { nc_msg($verbose, "$PROGRAM Status: -A (discover all) flag detected\n" ); } - if ($verbose) { nc_msg($verbose, "$PROGRAM Status: -v (verbose debug) flag detected\n"); } - if ($discover_macaddr) { nc_msg($verbose, "$PROGRAM Status: -M (discover mac address) flag detected\n"); } - if ($immed_flag) { nc_msg($verbose, "$PROGRAM Status: -i (force immediate shutdown) flag detected\n"); } - if ($list_physical) { nc_msg($verbose, "$PROGRAM Status: -P (list only phsical network) flag detected\n");} - if ($colon) { nc_msg($verbose, "$PROGRAM Status: -c (list colon separated ) flag detected\n" ); } - if ($debug_flag) { + if ($dev_type_found) { nc_msg($verbose, "$PROGRAM Status: List only $list_type adapters\n"); } + if ($noboot) { nc_msg($verbose, "$PROGRAM Status: -n (no boot) flag detected\n"); } + if ($discovery) { nc_msg($verbose, "$PROGRAM Status: -D (discovery) flag detected\n"); } + if ($discoverynoping) { nc_msg($verbose, "$PROGRAM Status: --noping (discovery) flag detected\n"); } + if ($discover_all) { nc_msg($verbose, "$PROGRAM Status: -A (discover all) flag detected\n"); } + if ($verbose) { nc_msg($verbose, "$PROGRAM Status: -v (verbose debug) flag detected\n"); } + if ($discover_macaddr) { nc_msg($verbose, "$PROGRAM Status: -M (discover mac address) flag detected\n"); } + if ($immed_flag) { nc_msg($verbose, "$PROGRAM Status: -i (force immediate shutdown) flag detected\n"); } + if ($list_physical) { nc_msg($verbose, "$PROGRAM Status: -P (list only phsical network) flag detected\n"); } + if ($colon) { nc_msg($verbose, "$PROGRAM Status: -c (list colon separated ) flag detected\n"); } + + if ($debug_flag) { nc_msg($verbose, "$PROGRAM Status: -d (debug) flag detected\n"); + #$exp_internal = 1; #$log_user = 1; } - if ($discovery and $adap_speed ) { nc_msg($verbose, "$PROGRAM Status: using adapter speed of $adap_speed\n" ); } - if ($discovery and $adap_duplex ) { nc_msg($verbose, "$PROGRAM Status: using adapter duplex of $adap_duplex\n" ); } - if ($discovery and $server_ip ) { nc_msg($verbose, "$PROGRAM Status: using server IP address of $server_ip\n"); } - if ($discovery and $client_ip) { nc_msg($verbose, "$PROGRAM Status: using client IP address of $client_ip\n" ); } - if ($discovery and $gateway_ip) { nc_msg($verbose, "$PROGRAM Status: using gateway IP address of $gateway_ip\n"); } - if ($discovery and $macaddress) { nc_msg($verbose, "$PROGRAM Status: using macaddress of $macaddress\n" ); } - if ($discovery and $phys_loc ) { nc_msg($verbose, "$PROGRAM Status: using physical location code of $phys_loc\n"); } - nc_msg($verbose, "node:".$node); + if ($discovery and $adap_speed) { nc_msg($verbose, "$PROGRAM Status: using adapter speed of $adap_speed\n"); } + if ($discovery and $adap_duplex) { nc_msg($verbose, "$PROGRAM Status: using adapter duplex of $adap_duplex\n"); } + if ($discovery and $server_ip) { nc_msg($verbose, "$PROGRAM Status: using server IP address of $server_ip\n"); } + if ($discovery and $client_ip) { nc_msg($verbose, "$PROGRAM Status: using client IP address of $client_ip\n"); } + if ($discovery and $gateway_ip) { nc_msg($verbose, "$PROGRAM Status: using gateway IP address of $gateway_ip\n"); } + if ($discovery and $macaddress) { nc_msg($verbose, "$PROGRAM Status: using macaddress of $macaddress\n"); } + if ($discovery and $phys_loc) { nc_msg($verbose, "$PROGRAM Status: using physical location code of $phys_loc\n"); } + nc_msg($verbose, "node:" . $node); #################################### # process the arguments #################################### @@ -2641,9 +2690,10 @@ sub lparnetbootexp # This corresponds to the Tcl log_user variable. ################################################## #$rconsole->log_stdout( $verbose ); #hidden information return from rcons - $rconsole->log_stdout(0); #hidden information return from rcons + $rconsole->log_stdout(0); #hidden information return from rcons my $consolefork = $rconsole->spawn($cmd); + #$rconsole->log_file("/tmp/consolelog"); my $console_pid = $rconsole->pid; unless ($console_pid) { @@ -2664,38 +2714,39 @@ sub lparnetbootexp # Send Ctrl-E, c and ? to get the help to come out to support # both confluent and conserver consoles $rconsole->send("\005c?"); - # for some reason the ctrl-e is not being sent for confluent, just getting c? + + # for some reason the ctrl-e is not being sent for confluent, just getting c? $timeout = 10; $rconsole->expect( $timeout, [ qr/c?/i => - sub { + sub { $rc = 0; $rconsole->clear_accum(); nc_msg($verbose, "Confluent -> Connected.\n"); - } + } ], [ qr/help.*/i => - sub { + sub { $rc = 0; $rconsole->clear_accum(); nc_msg($verbose, "Conserver -> Connected.\n"); - } + } ], [ timeout => - sub { + sub { $rc = 1; $rconsole->clear_accum(); nc_msg($verbose, "Timeout waiting for console connection.\n"); - } + } ], [ eof => - sub { + sub { $rc = 2; $rconsole->clear_accum(); nc_msg(1, "Please make sure rcons $node works.\n"); - } + } ], ); @@ -2716,7 +2767,7 @@ sub lparnetbootexp } if ($from_of) { - unless($output =~ /open firmware/i){ + unless ($output =~ /open firmware/i) { nc_msg(2, "You are using the -o option. Please make sure the LPAR's initial state is open firmware.\n"); return [1]; } @@ -2727,7 +2778,7 @@ sub lparnetbootexp # if -o is not used, power node of #################################### unless ($from_of) { - if (($output =~ /^off$/i) or ($output =~ /Not Activated/i) ) { + if (($output =~ /^off$/i) or ($output =~ /Not Activated/i)) { nc_msg($verbose, "# Power off complete.\n"); } else { nc_msg($verbose, "# Begin to Power off the node.\n"); @@ -2737,9 +2788,9 @@ sub lparnetbootexp node => [$node], arg => ['off'] }, - $subreq, 0, 1); + $subreq, 0, 1); $output = join ',', @$sysoutput; - if ($::RUNCMD_RC != 0) { #$::RUNCMD_RC will get its value from runxcmd_output + if ($::RUNCMD_RC != 0) { #$::RUNCMD_RC will get its value from runxcmd_output nc_msg($verbose, "Unable to run rpower $node off.\n"); return [1]; } @@ -2751,7 +2802,7 @@ sub lparnetbootexp nc_msg($verbose, "Wait for power off.\n"); } - $done = 0; + $done = 0; $query_count = 0; while (!$done) { $output = xCAT::LparNetbootExp->run_lssyscfg($subreq, $verbose, $node); @@ -2775,7 +2826,7 @@ sub lparnetbootexp # if set_boot_order is set, set the boot order # if not set, power the node to open firmware ################################################# - $done = 0; + $done = 0; $retry_count = 0; if ($set_boot_order > 1) { nc_msg($verbose, "Power on $node to SMS.\n"); @@ -2786,7 +2837,7 @@ sub lparnetbootexp node => [$node], arg => ['sms'] }, - $subreq, 0, 1); + $subreq, 0, 1); $output = join ',', @$sysoutput; nc_msg($verbose, "Waiting for power on...\n"); @@ -2800,7 +2851,7 @@ sub lparnetbootexp return [1]; } sleep 1; - $retry_count ++; + $retry_count++; } else { $done = 1; } @@ -2814,7 +2865,7 @@ sub lparnetbootexp node => [$node], arg => ['of'] }, - $subreq, 0, 1); + $subreq, 0, 1); $output = join ',', @$sysoutput; nc_msg($verbose, "Waiting for power on...\n"); @@ -2828,7 +2879,7 @@ sub lparnetbootexp return [1]; } sleep 1; - $retry_count ++; + $retry_count++; } else { $done = 1; } @@ -2839,11 +2890,11 @@ sub lparnetbootexp ########################### # Check the node state ########################### - $done = 0; + $done = 0; $query_count = 0; - $timeout = 1; + $timeout = 1; nc_msg($verbose, "Check the node state again;"); - while(!$done) { + while (!$done) { $output = xCAT::LparNetbootExp->run_lssyscfg($subreq, $verbose, $node); nc_msg($verbose, "The node state is $output.\n"); if ($output =~ /Open Firmware/i) { @@ -2853,19 +2904,21 @@ sub lparnetbootexp } $query_count++; + # if the node is not in openfirmware state, just wait for it my @result = $rconsole->expect( $timeout, - [ qr/(.*)elect this consol(.*)/=> - sub { - $rconsole->send("0\r"); - $rconsole->clear_accum(); - #$rconsole->exp_continue(); - } + [ qr/(.*)elect this consol(.*)/ => + sub { + $rconsole->send("0\r"); + $rconsole->clear_accum(); + + #$rconsole->exp_continue(); + } ], ); - if ($query_count > 300 ) { + if ($query_count > 300) { nc_msg($verbose, "Timed out waiting for power on of $node"); nc_msg($verbose, "error from rpower command : \"$output\" \n"); return [1]; @@ -2879,7 +2932,7 @@ sub lparnetbootexp # Check for active console ############################## nc_msg($verbose, "Check for active console.\n"); - $done = 0; + $done = 0; $retry_count = 0; $timeout = 10; @@ -2887,66 +2940,67 @@ sub lparnetbootexp while (!$done) { my @result = $rconsole->expect( $timeout, + #[qr/ok(.*)0 >/=> - [qr/0(.*)ok/=> - sub { - nc_msg($verbose, " at ok prompt\n"); - $rconsole->clear_accum(); - $done = 1; - } + [ qr/0(.*)ok/ => + sub { + nc_msg($verbose, " at ok prompt\n"); + $rconsole->clear_accum(); + $done = 1; + } ], - [qr/(.*)elect this consol(.*)/=> - sub { - nc_msg($verbose, " selecting active console\n"); - $rconsole->clear_accum(); - $rconsole->send("0\r"); - } + [ qr/(.*)elect this consol(.*)/ => + sub { + nc_msg($verbose, " selecting active console\n"); + $rconsole->clear_accum(); + $rconsole->send("0\r"); + } ], - [qr/English|French|German|Italian|Spanish|Portuguese|Chinese|Japanese|Korean/=> - sub { - nc_msg($verbose, "Languagae Selection Panel received\n"); - $rconsole->clear_accum(); - $rconsole->send("2\r"); - } + [ qr/English|French|German|Italian|Spanish|Portuguese|Chinese|Japanese|Korean/ => + sub { + nc_msg($verbose, "Languagae Selection Panel received\n"); + $rconsole->clear_accum(); + $rconsole->send("2\r"); + } ], - [qr/admin/=> - sub { - nc_msg($verbose, "No password specified\n"); - $rconsole->soft_close(); - $rc = 1; - } - ], - [qr/Invalid Password/=> - sub { - nc_msg($verbose, "FSP password is invalid.\n"); - $rconsole->soft_close(); - $rc = 1; - } - ], - [qr/SMS(.*)Navigation Keys/=> - sub { - nc_msg($verbose, "SMS\n"); - $rconsole->clear_accum(); - $done = 1; - } - ], - [timeout=> - sub { - $rconsole->send("\r"); - $retry_count++; - if ($retry_count eq 9) { - nc_msg($verbose, "Timeout waiting for ok prompt; exiting.\n"); + [ qr/admin/ => + sub { + nc_msg($verbose, "No password specified\n"); $rconsole->soft_close(); $rc = 1; - } - } + } ], - [eof => - sub { - nc_msg($verbose, "Cannot connect to $node"); - $rconsole->soft_close(); - $rc = 1; - } + [ qr/Invalid Password/ => + sub { + nc_msg($verbose, "FSP password is invalid.\n"); + $rconsole->soft_close(); + $rc = 1; + } + ], + [ qr/SMS(.*)Navigation Keys/ => + sub { + nc_msg($verbose, "SMS\n"); + $rconsole->clear_accum(); + $done = 1; + } + ], + [ timeout => + sub { + $rconsole->send("\r"); + $retry_count++; + if ($retry_count eq 9) { + nc_msg($verbose, "Timeout waiting for ok prompt; exiting.\n"); + $rconsole->soft_close(); + $rc = 1; + } + } + ], + [ eof => + sub { + nc_msg($verbose, "Cannot connect to $node"); + $rconsole->soft_close(); + $rc = 1; + } ], ); return [1] if ($rc eq 1); @@ -2958,10 +3012,10 @@ sub lparnetbootexp ############################## # Set the node boot order ############################## - if ($set_boot_order) { #rnetboot node will not go here + if ($set_boot_order) { #rnetboot node will not go here nc_msg($verbose, "begin to set disk boot"); - my $result = set_disk_boot( $rconsole, $node, $verbose);#@expect_out, $rconsole, $node, $verbose); - unless( $result ) { + my $result = set_disk_boot($rconsole, $node, $verbose); #@expect_out, $rconsole, $node, $verbose); + unless ($result) { nc_msg($verbose, "Unable to set $node boot order"); } } @@ -2974,15 +3028,15 @@ sub lparnetbootexp # supported network adapters # in the device tree. ############################## - $done = 0; + $done = 0; $retry_count = 0; nc_msg($verbose, "begin to run get_phandle"); while (!$done) { my $result = get_phandle($rconsole, $node, $verbose); - if ( $result eq 1) { + if ($result eq 1) { $retry_count++; $rconsole->send("\r"); - if ( $retry_count eq 3) { + if ($retry_count eq 3) { nc_msg($verbose, "Unable to obtain network adapter information. Quitting.\n"); return [1]; } @@ -2999,16 +3053,16 @@ sub lparnetbootexp ############################## nc_msg($verbose, "begin to run multiple_open_dev"); my $result = xCAT::LparNetbootExp->multiple_open_dev($rconsole, $node, $verbose); - if ( $result eq 1) { - nc_msg($verbose, "Unable to obtain network adapter information. Quitting.\n"); - return [1]; + if ($result eq 1) { + nc_msg($verbose, "Unable to obtain network adapter information. Quitting.\n"); + return [1]; } ############################## # ############################## nc_msg($verbose, "begin to process opt-discovery"); - if ($discovery && !$discoverynoping) { #rnetboot node will not go here + if ($discovery && !$discoverynoping) { #rnetboot node will not go here nc_msg($verbose, "# Client IP address is $client_ip\n"); nc_msg($verbose, "# Server IP address is $server_ip\n"); nc_msg($verbose, "# Gateway IP address is $gateway_ip\n"); @@ -3019,7 +3073,7 @@ sub lparnetbootexp # Display information for all # supported adapters ############################## - if ($noboot) { #if not do net boot + if ($noboot) { #if not do net boot if ($list_type) { $match_pat = $list_type; } else { @@ -3027,9 +3081,9 @@ sub lparnetbootexp } - if($colon) { + if ($colon) { nc_msg($verbose, "#Type:Location_Code:MAC_Address:Full_Path_Name:Ping_Result:Device_Type:Size_MB:OS:OS_Version:\n"); - $outputarrayindex++; # start from 1, 0 is used to set as 0 + $outputarrayindex++; # start from 1, 0 is used to set as 0 $outputarray[$outputarrayindex] = "#Type:Location_Code:MAC_Address:Full_Path_Name:Ping_Result:Device_Type:Size_MB:OS:OS_Version:"; } else { if ($discoverynoping) { @@ -3043,8 +3097,8 @@ sub lparnetbootexp } } - if ( $discover_all ) { #getmacs here - for( $i = 0; $i < $adapter_found; $i++) { + if ($discover_all) { #getmacs here + for ($i = 0 ; $i < $adapter_found ; $i++) { if ($adap_type[$i] =~ /$match_pat/) { if (!($adap_type[$i] eq "hfi-ent")) { $mac_address = get_mac_addr($phandle_array[$i], $rconsole, $node, $verbose); @@ -3054,19 +3108,19 @@ sub lparnetbootexp if ($discovery && !$discoverynoping) { $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); nc_msg($verbose, "ping_server returns $ping_rc\n"); - unless( $ping_rc eq 0) { + unless ($ping_rc eq 0) { $ping_result = "unsuccessful"; } else { $ping_result = "successful"; } } - if ( $adap_type[$i] eq "hfi-ent") { + if ($adap_type[$i] eq "hfi-ent") { $mac_address = get_mac_addr($phandle_array[$i], $rconsole, $node, $verbose); $loc_code = get_adaptr_loc($phandle_array[$i], $rconsole, $node, $verbose); } - if ($full_path_name_array[$i] =~ /vdevice/) { + if ($full_path_name_array[$i] =~ /vdevice/) { $device_type = "virtual"; } else { $device_type = "physical"; @@ -3074,20 +3128,20 @@ sub lparnetbootexp if (defined($mac_address)) { my @newmacs = (); - my @allmacs = split /\|/,$mac_address; - if ( !xCAT::Utils->isAIX() ) { - foreach my $mac_a ( @allmacs ) { + my @allmacs = split /\|/, $mac_address; + if (!xCAT::Utils->isAIX()) { + foreach my $mac_a (@allmacs) { $mac_a = lc($mac_a); $mac_a =~ s/(\w{2})/$1:/g; $mac_a =~ s/:$//; push @newmacs, $mac_a; } - $mac_address = join("|",@newmacs); - } + $mac_address = join("|", @newmacs); + } } - if($colon) { + if ($colon) { nc_msg($verbose, "$adap_type[$i]\:$loc_code\:$mac_address\:$full_path_name_array[$i]\:$ping_result\:$device_type\:\:\:\:\n"); $outputarrayindex++; $outputarray[$outputarrayindex] = "$adap_type[$i]\:$loc_code\:$mac_address\:$full_path_name_array[$i]\:$ping_result\:$device_type\:\:\:\:"; @@ -3099,7 +3153,7 @@ sub lparnetbootexp } } } else { - for( $i = 0; $i < $adapter_found; $i++) { + for ($i = 0 ; $i < $adapter_found ; $i++) { if ($adap_type[$i] =~ /$match_pat/) { if (!($adap_type[$i] eq "hfi-ent")) { $mac_address = get_mac_addr($phandle_array[$i], $rconsole, $node, $verbose); @@ -3109,25 +3163,25 @@ sub lparnetbootexp if ($discovery && !$discoverynoping) { $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); nc_msg($verbose, "ping_server returns $ping_rc\n"); - unless( $ping_rc eq 0) { + unless ($ping_rc eq 0) { $ping_result = "unsuccessful"; } else { $ping_result = "successful"; } } - if ( $adap_type[$i] eq "hfi-ent") { + if ($adap_type[$i] eq "hfi-ent") { $mac_address = get_mac_addr($phandle_array[$i], $rconsole, $node, $verbose); $loc_code = get_adaptr_loc($phandle_array[$i], $rconsole, $node, $verbose); } - if ($full_path_name_array[$i] =~ /vdevice/) { + if ($full_path_name_array[$i] =~ /vdevice/) { $device_type = "virtual"; } else { $device_type = "physical"; } - if($colon) { + if ($colon) { nc_msg($verbose, "$adap_type[$i]\:$loc_code\:$mac_address\:$full_path_name_array[$i]\:$ping_result\:$device_type\:\:\:\:\n"); } else { nc_msg($verbose, "$adap_type[$i] $loc_code $mac_address $full_path_name_array[$i] $ping_result $device_type\n"); @@ -3144,7 +3198,7 @@ sub lparnetbootexp node => [$node], arg => ['off'] }, - $subreq, 0, 1); + $subreq, 0, 1); $output = join ',', @$sysoutput; if ($::RUNCMD_RC != 0) { nc_msg($verbose, "Unable to run rpower $node sms.\n"); @@ -3153,52 +3207,52 @@ sub lparnetbootexp return [1]; } } - } else { # Do a network boot - # Loop throught the adapters and perform a ping test to discover an - # adapter that pings successfully, then use that adapter to network boot. - if ($discover_all) { #rnetboot should not use -A - for ($i = 0; $i < $adapter_found; $i++) { + } else { # Do a network boot + # Loop throught the adapters and perform a ping test to discover an + # adapter that pings successfully, then use that adapter to network boot. + if ($discover_all) { #rnetboot should not use -A + for ($i = 0 ; $i < $adapter_found ; $i++) { $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); - if ( $ping_rc eq 0) { - $phandle = $phandle_array[$i]; - $full_path_name = $full_path_name_array[$i]; + if ($ping_rc eq 0) { + $phandle = $phandle_array[$i]; + $full_path_name = $full_path_name_array[$i]; $chosen_adap_type = $adap_type[$i]; last; } } - } elsif ( $macaddress ne "" ) { #rnetboot here + } elsif ($macaddress ne "") { #rnetboot here $match = 0; - for ($i = 0; $i < $adapter_found; $i++) { + for ($i = 0 ; $i < $adapter_found ; $i++) { if ($adap_type[$i] =~ /hfi-ent/) { $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); } $mac_address = get_mac_addr($phandle_array[$i], $rconsole, $node, $verbose); - if ( $macaddress =~ /$mac_address/ ) { + if ($macaddress =~ /$mac_address/) { if (($discovery eq 1) && !$discoverynoping) { - unless ( $adap_type[$i] eq "hfi-ent" ) { - $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); + unless ($adap_type[$i] eq "hfi-ent") { + $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); } - unless ( $ping_rc eq 0) { - nc_msg($verbose, "Unable to boot network adapter.\n" ); + unless ($ping_rc eq 0) { + nc_msg($verbose, "Unable to boot network adapter.\n"); return [1]; } } - $phandle = $phandle_array[$i]; - $full_path_name = $full_path_name_array[$i]; - $chosen_adap_type = $adap_type[$i]; - $match = 1; - last; + $phandle = $phandle_array[$i]; + $full_path_name = $full_path_name_array[$i]; + $chosen_adap_type = $adap_type[$i]; + $match = 1; + last; } } - unless($match) { + unless ($match) { nc_msg($verbose, "Can not find mac address '$macaddress'\n"); return [1]; } - } elsif ( $phys_loc ne "") { + } elsif ($phys_loc ne "") { $match = 0; - for ($i = 0; $i < $adapter_found; $i++) { + for ($i = 0 ; $i < $adapter_found ; $i++) { $loc_code = get_adaptr_loc($phandle_array[$i], $rconsole, $node, $verbose); if ($loc_code =~ /$phys_loc/) { if ($discovery && !$discoverynoping) { @@ -3208,10 +3262,10 @@ sub lparnetbootexp return [1]; } } - $phandle = $phandle_array[$i]; - $full_path_name = $full_path_name_array[$i]; + $phandle = $phandle_array[$i]; + $full_path_name = $full_path_name_array[$i]; $chosen_adap_type = $adap_type[$i]; - $match = 1; + $match = 1; last; } } @@ -3220,21 +3274,21 @@ sub lparnetbootexp return [1]; } } else { - # - # Use the first ethernet adapter in the - # device tree. - # - for ($i = 0; $i < $adapter_found; $i++) { - nc_msg($verbose, " begint to boot from first adapter in the device tree \n"); - if ($adap_type[$i] eq $list_type ) { - if ( ($discovery eq 1) && !$discoverynoping ){ + # + # Use the first ethernet adapter in the + # device tree. + # + for ($i = 0 ; $i < $adapter_found ; $i++) { + nc_msg($verbose, " begint to boot from first adapter in the device tree \n"); + if ($adap_type[$i] eq $list_type) { + if (($discovery eq 1) && !$discoverynoping) { $ping_rc = ping_server($phandle_array[$i], $full_path_name_array[$i], $rconsole, $node, $mac_address, $verbose, $adap_speed, $adap_duplex, $list_type, $server_ip, $client_ip, $gateway_ip); unless ($ping_rc eq 0) { return [1]; } } - $phandle = $phandle_array[$i]; - $full_path_name = $full_path_name_array[$i]; + $phandle = $phandle_array[$i]; + $full_path_name = $full_path_name_array[$i]; $chosen_adap_type = $adap_type[$i]; last; } @@ -3246,13 +3300,13 @@ sub lparnetbootexp return [1]; } else { nc_msg($verbose, "# Network booting install adapter.\n"); - $result = xCAT::LparNetbootExp->boot_network($rconsole, $full_path_name, $adap_speed, $adap_duplex , $chosen_adap_type, $server_ip, $client_ip, $gateway_ip, $netmask, $dump_target, $dump_lun, $dump_port, $verbose, $extra_args, $node, $set_boot_order ); + $result = xCAT::LparNetbootExp->boot_network($rconsole, $full_path_name, $adap_speed, $adap_duplex, $chosen_adap_type, $server_ip, $client_ip, $gateway_ip, $netmask, $dump_target, $dump_lun, $dump_port, $verbose, $extra_args, $node, $set_boot_order); } if ($result eq 0) { nc_msg($verbose, "bootp sent over netowrk.\n"); - my $res = Boot($rconsole, $node, $verbose);#, @expect_out); + my $res = Boot($rconsole, $node, $verbose); #, @expect_out); unless ($res eq 0) { nc_msg($verbose, "Can not boot, result = $res. \n"); } @@ -3284,18 +3338,18 @@ sub lparnetbootexp } ], [ eof => - sub { + sub { nc_msg($verbose, "cannot connect to $node.\n"); $rconsole->clear_accum(); $rc = 1; - } + } ], [ sub { nc_msg($verbose, "# Network booting install adapter.\n"); nc_msg($verbose, "Retrying network-boot from RESTART-CMD error.\n"); $done = 0; - while (! $done ) { + while (!$done) { my $res = xCAT::LparNetbootExp->boot_network($node,); if ($res eq 0) { $done = 1; @@ -3308,7 +3362,7 @@ sub lparnetbootexp ); return [1] if ($rc eq 1); nc_msg($verbose, "# bootp sent over network.\n"); - $rc = Boot($rconsole, $node, $verbose);#, @expect_out); + $rc = Boot($rconsole, $node, $verbose); #, @expect_out); unless ($rc eq 0) { nc_msg($verbose, "Can't boot here. \n"); } @@ -3318,9 +3372,9 @@ sub lparnetbootexp ################################################ # mission accomplished, beam me up scotty. ################################################# - unless ($noboot) { #if do the rnetboot, just return - if ( $rc eq 0) { - nc_msg($verbose, "# Finished.\n" ); + unless ($noboot) { #if do the rnetboot, just return + if ($rc eq 0) { + nc_msg($verbose, "# Finished.\n"); $outputarrayindex++; $outputarray[$outputarrayindex] = "Finished."; } else { @@ -3328,26 +3382,26 @@ sub lparnetbootexp $outputarrayindex++; $outputarray[$outputarrayindex] = "Finished in an error."; } - } else { #if not rnetboot, for example, getmacs, power off the node - $done = 0; + } else { #if not rnetboot, for example, getmacs, power off the node + $done = 0; $query_count = 0; - while(!$done) { + while (!$done) { $output = xCAT::LparNetbootExp->run_lssyscfg($subreq, $verbose, $node); ############################################## # separate the nodename from the query status ############################################## if ($from_of != 1) { - if (( $output =~ /^off$/i ) or ($output =~ /Not Activated/i)) { + if (($output =~ /^off$/i) or ($output =~ /Not Activated/i)) { $done = 1; } } else { - if ( $output =~ /firmware/i ) { + if ($output =~ /firmware/i) { $done = 1; } } $query_count++; - if ( $query_count > 60 ){ + if ($query_count > 60) { $done = 1; } sleep 1; diff --git a/perl-xCAT/xCAT/MacMap.pm b/perl-xCAT/xCAT/MacMap.pm index ef92f18d2..23eb69e91 100644 --- a/perl-xCAT/xCAT/MacMap.pm +++ b/perl-xCAT/xCAT/MacMap.pm @@ -4,25 +4,28 @@ package xCAT::MacMap; BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : '/opt/xcat'; } use lib "$::XCATROOT/lib/perl"; require Exporter; -our @ISA=qw/Exporter/; -our @EXPORT_OK=qw/walkoid/; +our @ISA = qw/Exporter/; +our @EXPORT_OK = qw/walkoid/; use strict; use xCAT::Table; use xCAT::Utils; use xCAT::MsgUtils; use xCAT::TableUtils; +use xCAT::NetworkUtils; use IO::Select; use IO::Handle; use Sys::Syslog; + #use Data::Dumper; use POSIX qw/WNOHANG/; use SNMP; my %cisco_vlans; #Special hash structure to reflect discovered VLANS on Cisco equip + #use IF-MIB (1.3.6.1.2.1.2) for all switches # 1.3.6.1.2.1.31.1.1 - ifXtable # 1.3.6.1.2.1.31.1.1.1.1.N = name - ifName @@ -30,9 +33,9 @@ my %cisco_vlans; #Special hash structure to reflect discovered VLANS on Cisco eq # 1.3.6.1.2.1.17.1.4 - dot1dBasePortTable # 1.3.6.1.2.1.17.1.4.1.1.X = N - dot1dBasePort # 1.3.6.1.2.1.17.4.3 - dot1dTpFdbTable #FAILS on FORCE10, -# +# #If particular result fails, fallback to Q-BRIDGE-MIB for Force10 (1.3.6.1.2.1.17.7) -# 1.3.6.1.2.1.17.7.1.2.2 - dot1qTpFdbTable +# 1.3.6.1.2.1.17.7.1.2.2 - dot1qTpFdbTable #now for the lldp fun. lldp mib uses yet another index. The mib states @@ -81,6 +84,7 @@ my %cisco_vlans; #Special hash structure to reflect discovered VLANS on Cisco eq sub namesmatch { + =pod MacMap attempts to do it's best to determine whether or not a particular SNMP description of @@ -96,68 +100,76 @@ existing rule, it is recommended to use snmpwalk on the switch with the .1.3.6.1 OID, and have the switch table port value match exactly the format suggested by that OID. =cut - my $namepercfg = shift; - my $namepersnmp = shift; - if ($namepercfg eq $namepersnmp) { - return 1; # They matched perfectly - } - #Begin guessing, first off, all tested scenarios have likely correct guesses ending - #in the cfg string, with some non-numeric prefix before it. - #3com convention, contributed by Aaron Knister - if ( $namepersnmp =~ /^RMON Port (0?)(\d+) on unit \d+/ ) { - if ( $2 =~ $namepercfg ) { - return 1; - } - } - # dell 6248 convention - if ( $namepersnmp =~ /^Unit \d Port (\d+)$/ ) { - if ( $1 eq $namepercfg ) { - return 1; + my $namepercfg = shift; + my $namepersnmp = shift; + if ($namepercfg eq $namepersnmp) { + return 1; # They matched perfectly + } + + #Begin guessing, first off, all tested scenarios have likely correct guesses ending + #in the cfg string, with some non-numeric prefix before it. + #3com convention, contributed by Aaron Knister + if ($namepersnmp =~ /^RMON Port (0?)(\d+) on unit \d+/) { + if ($2 =~ $namepercfg) { + return 1; + } + } + + # dell 6248 convention + if ($namepersnmp =~ /^Unit \d Port (\d+)$/) { + if ($1 eq $namepercfg) { + return 1; + } } - } - unless ($namepersnmp =~ /[^0123456789]$namepercfg(\.0)?\z/) { #ensure name from user exists in the string without being preceeded immediately by a number, and allowing a .0 to exist after the cfg for juniper - #Most common case, won't match at all - return 0; - } - #at this point we know the string the user wanted does exist on this port, now we move on to non-ethernet ports that may ambiguously match the user request as well + unless ($namepersnmp =~ /[^0123456789]$namepercfg(\.0)?\z/) { #ensure name from user exists in the string without being preceeded immediately by a number, and allowing a .0 to exist after the cfg for juniper + #Most common case, won't match at all + return 0; + } - #stop contemplating vlan, Nu, stacking ports, and console interfaces - if (($namepersnmp =~ /vl/i) or ($namepersnmp =~ /Nu/) or ($namepersnmp =~ /onsole/) or ($namepersnmp =~ /Stack/) or ($namepersnmp =~ /Trunk/)) { - return 0; - } - #broken up for code readablitiy, don't check port channel numbers or CPU - #have to distinguish betweer Port and Po and PortChannel - if (($namepersnmp !~ /Port #/) and ($namepersnmp !~ /Port\d/) and ($namepersnmp =~ /Po/) or ($namepersnmp =~ /po\d/) or ($namepersnmp =~ /XGE/) or ($namepersnmp =~ /LAG/) or ($namepersnmp =~ /CPU/)) { - return 0; - } - #don't contemplate ManagementEthernet - if (($namepersnmp =~ /Management/)) { - return 0; - } - #The blacklist approach has been exhausted. For now, assuming that means good, - #if something ambiguous happens, the whitelist would have been: - #'Port','Port #','/' (if namepercfg has no /, then / would be...), - #'Gi','Te','GigabitEthernet','TenGigabitEthernet' - return 1; + #at this point we know the string the user wanted does exist on this port, now we move on to non-ethernet ports that may ambiguously match the user request as well + + #stop contemplating vlan, Nu, stacking ports, and console interfaces + if (($namepersnmp =~ /vl/i) or ($namepersnmp =~ /Nu/) or ($namepersnmp =~ /onsole/) or ($namepersnmp =~ /Stack/) or ($namepersnmp =~ /Trunk/)) { + return 0; + } + + #broken up for code readablitiy, don't check port channel numbers or CPU + #have to distinguish betweer Port and Po and PortChannel + if (($namepersnmp !~ /Port #/) and ($namepersnmp !~ /Port\d/) and ($namepersnmp =~ /Po/) or ($namepersnmp =~ /po\d/) or ($namepersnmp =~ /XGE/) or ($namepersnmp =~ /LAG/) or ($namepersnmp =~ /CPU/)) { + return 0; + } + + #don't contemplate ManagementEthernet + if (($namepersnmp =~ /Management/)) { + return 0; + } + + #The blacklist approach has been exhausted. For now, assuming that means good, + #if something ambiguous happens, the whitelist would have been: + #'Port','Port #','/' (if namepercfg has no /, then / would be...), + #'Gi','Te','GigabitEthernet','TenGigabitEthernet' + return 1; } sub new { - my $self = {}; - # Since switch.pm and lsslp.pm both create a MacMap object, SNMP is still required at xcatd start up. - # So we are going back to "use SNMP;" at the top of this file so RPM will automatically generate a prereq. - #eval { require SNMP; }; - #if ($@) { die "SNMP support required to use MacMAP"; } - my $proto = shift; - my $class = ref($proto) || $proto; + my $self = {}; - bless ($self, $class); - return $self; + # Since switch.pm and lsslp.pm both create a MacMap object, SNMP is still required at xcatd start up. + # So we are going back to "use SNMP;" at the top of this file so RPM will automatically generate a prereq. + #eval { require SNMP; }; + #if ($@) { die "SNMP support required to use MacMAP"; } + my $proto = shift; + my $class = ref($proto) || $proto; + + bless($self, $class); + return $self; } sub rvlan { + #The Q-BRIDGE way: #IF-MIB for ifName<->ifIndex (much like the find_mac code) #BRIDGE-MIB for ifIndex<->BridgeIndex (again, familiar) @@ -171,436 +183,642 @@ sub rvlan { #argument specification: # nodes => [ list reference of nodes to query/set ] # operation => "pvid= or vlan=" for now, addvlan= and delvlan= for tagged vlans, 'pvid', vlan, or stat without = checks current value - my $self=shift; + my $self = shift; my $community = "public"; + #$self->{sitetab} = xCAT::Table->new('site'); #my $tmp = $self->{sitetab}->getAttribs({key=>'snmpc'},'value'); - my @snmpcs = xCAT::TableUtils->get_site_attribute("snmpc"); - my $tmp = $snmpcs[0]; - if ( defined($tmp) ) { $community = $tmp } - my %args = @_; - my $op=$args{operation}; - my $nodes=$args{nodes}; + my @snmpcs = xCAT::TableUtils->get_site_attribute("snmpc"); + my $tmp = $snmpcs[0]; + if (defined($tmp)) { $community = $tmp } + my %args = @_; + my $op = $args{operation}; + my $nodes = $args{nodes}; + #first order of business is to identify the target switches - my $switchtab=xCAT::Table->new('switch',-create=>0); + my $switchtab = xCAT::Table->new('switch', -create => 0); unless ($switchtab) { return; } - my $switchents = $switchtab->getNodesAttribs($nodes,[qw/switch port interface/]); + my $switchents = $switchtab->getNodesAttribs($nodes, [qw/switch port interface/]); my $node; foreach $node (keys %$switchents) { my $entry; - foreach $entry (@{$switchents->{$node}}) { + foreach $entry (@{ $switchents->{$node} }) { + #skip the none primary interface. # The vlaue of the primary interface could be empty, primary or primary:ethx - if (defined($entry->{interface})) { - if ($entry->{interface} !~ /primary/) { - next; - } - } + if (defined($entry->{interface})) { + if ($entry->{interface} !~ /primary/) { + next; + } + } - $self->{switches}->{$entry->{switch}}->{$entry->{port}} = $node; + $self->{switches}->{ $entry->{switch} }->{ $entry->{port} } = $node; } - } - my $switches=[keys %{$self->{switches}}]; - my $switchestab=xCAT::Table->new('switches',-create=>0); + } + my $switches = [ keys %{ $self->{switches} } ]; + my $switchestab = xCAT::Table->new('switches', -create => 0); my @switchesents; if ($switchestab) { - foreach (values %{$switchestab->getNodesAttribs($switches,[qw(switch snmpversion username password privacy auth)])}) { - push @switchesents,@$_; + foreach (values %{ $switchestab->getNodesAttribs($switches, [qw(switch snmpversion username password privacy auth)]) }) { + push @switchesents, @$_; } } - $self->fill_switchparms(community=>$community,switchesents=>\@switchesents); + $self->fill_switchparms(community => $community, switchesents => \@switchesents); my $switch; - foreach $switch (keys %{$self->{switches}}) { #first we'll extract the lay of the land... - $self->refresh_switch(undef,$community,$switch); - unless ($self->{switchinfo}->{$switch}->{vlanidtoindex}) { #need vlan id to vlanindex map for qbridge unless cisco - $self->scan_qbridge_vlans(switch=>$switch,community=>$community); - } + foreach $switch (keys %{ $self->{switches} }) { #first we'll extract the lay of the land... + $self->refresh_switch(undef, $community, $switch); + unless ($self->{switchinfo}->{$switch}->{vlanidtoindex}) { #need vlan id to vlanindex map for qbridge unless cisco + $self->scan_qbridge_vlans(switch => $switch, community => $community); + } } + #print Dumper($self->{switchinfo}); - # $self->{switchinfo}->{$switch}->{bridgeidxtoifname}->{$boid}=$portname; - # $self->{switchinfo}->{$switch}->{ifnametobridgeidx}->{$portname}=$boid; + # $self->{switchinfo}->{$switch}->{bridgeidxtoifname}->{$boid}=$portname; + # $self->{switchinfo}->{$switch}->{ifnametobridgeidx}->{$portname}=$boid; $op =~ s/stat/pvid/; $op =~ s/vlan/pvid/; - if ($op =~ /^addpvid/) { # add tagged vlan - } elsif ($op =~ /delpvid/) { #remove tagged vlan - } else { #native vlan query or set + if ($op =~ /^addpvid/) { # add tagged vlan + } elsif ($op =~ /delpvid/) { #remove tagged vlan + } else { #native vlan query or set } } + sub scan_qbridge_vlans { - my $self = shift; - my %args = @_; - my $switch = $args{switch}; + my $self = shift; + my %args = @_; + my $switch = $args{switch}; my $session = $self->{switchsessions}->{$switch}; - $self->{switchinfo}->{vlanindextoid} = walkoid($session,'.1.3.6.1.2.1.17.7.1.4.2.1.3'); - foreach (keys %{$self->{switchinfo}->{vlanindextoid}}) { -#TODO: try to scan + $self->{switchinfo}->{vlanindextoid} = walkoid($session, '.1.3.6.1.2.1.17.7.1.4.2.1.3'); + foreach (keys %{ $self->{switchinfo}->{vlanindextoid} }) { + + #TODO: try to scan } } -sub find_mac { -# This function is given a mac address, checks for given mac address -# and returns undef if unable to find the node, and the nodename otherwise - my $self = shift; - my $mac = shift; - my $cachedonly = shift; -# For now HARDCODE (TODO, configurable?) a cache as stale after five minutes -# Also, if things are changed in the config, our cache could be wrong, -# invalidate on switch table write? - if ($self->{mactable}->{lc($mac)} and ($self->{timestamp} > (time() - 300))) { - my $reftbl = 0; - foreach (keys %{$self->{mactable}}) { - if ((lc($mac) ne $_) and ($self->{mactable}->{lc($mac)} eq $self->{mactable}->{$_})) { - #$reftbl = 1; - #Delete *possibly* stale data, without being heavy handed.. - #But if this mac indicates multiple nodes, leave it there - if ( $self->{mactable}->{lc($mac)} !~ /,/) - { - delete $self->{mactable}->{$_}; - } - } + +#-------------------------------------------------------------------------------- + +=head3 dump_mac_info + Descriptions: + Retrieve information (switchport and the mac addresses got for that port) for the specified switch or all switches if no specified. + Arguments: + $req: the xcat request hash + $callback: the function to output information + Returns: + The hash variable store retrieved inforamtions + Usage example: + my $macmap = xCAT::MacMap->new(); + my $switch_data = $macmap->dump_mac_info($req, $callback); + foreach my $switch (keys %$switch_data) {...} +=cut + +#-------------------------------------------------------------------------------- + +sub dump_mac_info { + my $self = shift; + my $req = shift; + my $callback = shift; + my $noderange = undef; + if (defined($req->{node})) { + $noderange = $req->{node}; } - unless ($reftbl) { return $self->{mactable}->{lc($mac)};} - } - #If requesting a cache only check or the cache is a mere 20 seconds old - #don't bother querying switches - if ($cachedonly or ($self->{timestamp} > (time() - 20))) { return undef; } - $self->refresh_table; #not cached or stale cache, refresh - if ($self->{mactable}->{lc($mac)}) { - return $self->{mactable}->{lc($mac)}; - } - return undef; + my %ret = (); + $self->{collect_mac_info} = 1; + if (defined($req->{opt}->{verbose})) { + $self->{show_verbose_info} = 1; + $self->{callback} = $callback; + } + my $community = "public"; + my $dump_all_switches = 0; + my %switches_to_dump = (); + if (!defined($noderange)) { + $dump_all_switches = 1; + } + else { + foreach (@$noderange) { + $switches_to_dump{$_} = 1; + } + } + my $switchestab = xCAT::Table->new('switches', -create => 0); + my @switchesents = $switchestab->getAllNodeAttribs([qw(switch snmpversion username password privacy auth)]); + $self->fill_switchparms(community => $community, switchesents => \@switchesents); + my $switchtab = xCAT::Table->new('switch', -create => 0); + my @entries = (); + if ($switchtab) { + @entries = $switchtab->getAllNodeAttribs([ 'node', 'switch', 'port' ]); + } + + #Build hash of switch port names per switch + $self->{switches} = {}; + foreach my $entry (@entries) { + if (defined($entry->{switch}) and $entry->{switch} ne "" and defined($entry->{port}) and $entry->{port} ne "") { + if (!$self->{switches}->{ $entry->{switch} }->{ $entry->{port} }) { + $self->{switches}->{ $entry->{switch} }->{ $entry->{port} } = $entry->{node}; + } + else { + $self->{switches}->{ $entry->{switch} }->{ $entry->{port} } .= ",$entry->{node}"; + } + } + else { + xCAT::MsgUtils->message("S", "xCAT Table error:" . $entry->{node} . "Has missing or invalid switch.switch and/or switch.port fields"); + } + } + foreach my $switch (keys %{ $self->{switchparmhash} }) { + if ($dump_all_switches or defined($switches_to_dump{$switch})) { + if ($self->{show_verbose_info}) { + xCAT::MsgUtils->message("I", { data => ["$switch: Start to get information"] }, $self->{callback}); + } + $self->refresh_switch(undef, $community, $switch); + if ($self->{show_verbose_info}) { + xCAT::MsgUtils->message("I", { data => ["$switch: Finish to get information"] }, $self->{callback}); + } + if (!defined($self->{macinfo}->{$switch})) { + $ret{$switch}->{ErrorStr} = "No information get"; + foreach my $defportname (keys %{ $self->{switches}->{$switch} }) { + $ret{$switch}->{$defportname}->{Node} = $self->{switches}->{$switch}->{$defportname}; + } + } + elsif (defined($self->{macinfo}->{$switch}->{ErrorStr})) { + $ret{$switch}->{ErrorStr} = $self->{macinfo}->{$switch}->{ErrorStr}; + + # To show the error message that the username/password related error is for SNMP only + if ($ret{$switch}->{ErrorStr} =~ /username|password/i) { + $ret{$switch}->{ErrorStr} .= " through SNMP"; + } + } else { + foreach my $snmpportname (keys %{ $self->{macinfo}->{$switch} }) { + foreach my $defportname (keys %{ $self->{switches}->{$switch} }) { + if (namesmatch($defportname, $snmpportname)) { + $ret{$switch}->{$snmpportname}->{Node} = $self->{switches}->{$switch}->{$defportname}; + } + } + @{ $ret{$switch}->{$snmpportname}->{MACaddress} } = @{ $self->{macinfo}->{$switch}->{$snmpportname} }; + } + } + } + } + return \%ret; +} + +sub find_mac { + + # This function is given a mac address, checks for given mac address + # and returns undef if unable to find the node, and the nodename otherwise + my $self = shift; + my $mac = shift; + my $cachedonly = shift; + + # For now HARDCODE (TODO, configurable?) a cache as stale after five minutes + # Also, if things are changed in the config, our cache could be wrong, + # invalidate on switch table write? + if ($self->{mactable}->{ lc($mac) } and ($self->{timestamp} > (time() - 300))) { + my $reftbl = 0; + foreach (keys %{ $self->{mactable} }) { + if ((lc($mac) ne $_) and ($self->{mactable}->{ lc($mac) } eq $self->{mactable}->{$_})) { + + #$reftbl = 1; + #Delete *possibly* stale data, without being heavy handed.. + #But if this mac indicates multiple nodes, leave it there + if ($self->{mactable}->{ lc($mac) } !~ /,/) + { + delete $self->{mactable}->{$_}; + } + } + } + unless ($reftbl) { return $self->{mactable}->{ lc($mac) }; } + } + + #If requesting a cache only check or the cache is a mere 20 seconds old + #don't bother querying switches + if ($cachedonly or ($self->{timestamp} > (time() - 20))) { return undef; } + $self->refresh_table; #not cached or stale cache, refresh + if ($self->{mactable}->{ lc($mac) }) { + return $self->{mactable}->{ lc($mac) }; + } + return undef; } sub fill_switchparms { - my $self = shift; - my %args = @_; - my $community=$args{community}; - $self->{switchparmhash}={}; - my @switchentries = @{$args{switchesents}}; - foreach (@switchentries) { - my $curswitch=$_->{switch}; - $self->{switchparmhash}->{$curswitch}=$_; - if ($_->{snmpversion}) { - if ($_->{snmpversion} =~ /3/) { #clean up to accept things like v3 or ver3 or 3, whatever. - $self->{switchparmhash}->{$curswitch}->{snmpversion}=3; - unless ($_->{auth}) { - $self->{switchparmhash}->{$curswitch}->{auth}='md5'; #Default to md5 auth if not specified but using v3 - } - } elsif ($_->{snmpversion} =~ /2/) { - $self->{switchparmhash}->{$curswitch}->{snmpversion}=2; - } else { - $self->{switchparmhash}->{$curswitch}->{snmpversion}=1; #Default to lowest common denominator, snmpv1 - } - } - unless (defined $_->{password}) { #if no password set, inherit the community - $self->{switchparmhash}->{$curswitch}->{password}=$community; - } - } + my $self = shift; + my %args = @_; + my $community = $args{community}; + $self->{switchparmhash} = {}; + my @switchentries = @{ $args{switchesents} }; + foreach (@switchentries) { + my $curswitch = $_->{switch}; + $self->{switchparmhash}->{$curswitch} = $_; + if ($_->{snmpversion}) { + if ($_->{snmpversion} =~ /3/) { #clean up to accept things like v3 or ver3 or 3, whatever. + $self->{switchparmhash}->{$curswitch}->{snmpversion} = 3; + unless ($_->{auth}) { + $self->{switchparmhash}->{$curswitch}->{auth} = 'md5'; #Default to md5 auth if not specified but using v3 + } + } elsif ($_->{snmpversion} =~ /2/) { + $self->{switchparmhash}->{$curswitch}->{snmpversion} = 2; + } else { + $self->{switchparmhash}->{$curswitch}->{snmpversion} = 1; #Default to lowest common denominator, snmpv1 + } + } + unless (defined $_->{password}) { #if no password set, inherit the community + $self->{switchparmhash}->{$curswitch}->{password} = $community; + } + } } sub refresh_table { - my $self = shift; - my $curswitch; - $self->{mactable}={}; - $self->{switchtab} = xCAT::Table->new('switch', -create => 1); - $self->{switchestab} = xCAT::Table->new('switches', -create => 1); - my @switchentries=$self->{switchestab}->getAllNodeAttribs([qw(switch snmpversion username password privacy auth)]); - my $community = "public"; - #$self->{sitetab} = xCAT::Table->new('site'); - #my $tmp = $self->{sitetab}->getAttribs({key=>'snmpc'},'value'); - #if ($tmp and $tmp->{value}) { $community = $tmp->{value} } - my @snmpcs = xCAT::TableUtils->get_site_attribute("snmpc"); - my $tmp = $snmpcs[0]; - if ( defined($tmp) ) { $community = $tmp } - else { #Would warn here.. - } - $self->{switchparmhash}={}; - foreach (@switchentries) { - $curswitch=$_->{switch}; - $self->{switchparmhash}->{$curswitch}=$_; - if ($_->{snmpversion}) { - if ($_->{snmpversion} =~ /3/) { #clean up to accept things like v3 or ver3 or 3, whatever. - $self->{switchparmhash}->{$curswitch}->{snmpversion}=3; - unless ($_->{auth}) { - $self->{switchparmhash}->{$curswitch}->{auth}='md5'; #Default to md5 auth if not specified but using v3 - } - } elsif ($_->{snmpversion} =~ /2/) { - #$self->{switchparmhash}->{$curswitch}->{snmpversion}=2; - # we have Juniper switch enabled snmp v2c, not v2 - $self->{switchparmhash}->{$curswitch}->{snmpversion}=$_->{snmpversion}; - } else { - $self->{switchparmhash}->{$curswitch}->{snmpversion}=1; #Default to lowest common denominator, snmpv1 - } + my $self = shift; + my $curswitch; + $self->{mactable} = {}; + $self->{switchtab} = xCAT::Table->new('switch', -create => 1); + $self->{switchestab} = xCAT::Table->new('switches', -create => 1); + my @switchentries = $self->{switchestab}->getAllNodeAttribs([qw(switch snmpversion username password privacy auth)]); + my $community = "public"; + + #$self->{sitetab} = xCAT::Table->new('site'); + #my $tmp = $self->{sitetab}->getAttribs({key=>'snmpc'},'value'); + #if ($tmp and $tmp->{value}) { $community = $tmp->{value} } + my @snmpcs = xCAT::TableUtils->get_site_attribute("snmpc"); + my $tmp = $snmpcs[0]; + if (defined($tmp)) { $community = $tmp } + else { #Would warn here.. + } + $self->{switchparmhash} = {}; + foreach (@switchentries) { + $curswitch = $_->{switch}; + $self->{switchparmhash}->{$curswitch} = $_; + if ($_->{snmpversion}) { + if ($_->{snmpversion} =~ /3/) { #clean up to accept things like v3 or ver3 or 3, whatever. + $self->{switchparmhash}->{$curswitch}->{snmpversion} = 3; + unless ($_->{auth}) { + $self->{switchparmhash}->{$curswitch}->{auth} = 'md5'; #Default to md5 auth if not specified but using v3 + } + } elsif ($_->{snmpversion} =~ /2/) { + + #$self->{switchparmhash}->{$curswitch}->{snmpversion}=2; + # we have Juniper switch enabled snmp v2c, not v2 + $self->{switchparmhash}->{$curswitch}->{snmpversion} = $_->{snmpversion}; + } else { + $self->{switchparmhash}->{$curswitch}->{snmpversion} = 1; #Default to lowest common denominator, snmpv1 + } } unless (defined $_->{password}) { #if no password set, inherit the community - $self->{switchparmhash}->{$curswitch}->{password}=$community; + $self->{switchparmhash}->{$curswitch}->{password} = $community; } - } - my %checked_pairs; - my @entries = $self->{switchtab}->getAllNodeAttribs(['node','port','switch']); - #Build hash of switch port names per switch - $self->{switches} = {}; - foreach my $entry (@entries) { - if (defined($entry->{switch}) and $entry->{switch} ne "" and defined($entry->{port}) and $entry->{port} ne "") { + } + my %checked_pairs; + my @entries = $self->{switchtab}->getAllNodeAttribs([ 'node', 'port', 'switch' ]); - if ( !$self->{switches}->{$entry->{switch}}->{$entry->{port}}) - { - $self->{switches}->{$entry->{switch}}->{$entry->{port}} = $entry->{node}; + #Build hash of switch port names per switch + $self->{switches} = {}; + foreach my $entry (@entries) { + if (defined($entry->{switch}) and $entry->{switch} ne "" and defined($entry->{port}) and $entry->{port} ne "") { + + if (!$self->{switches}->{ $entry->{switch} }->{ $entry->{port} }) + { + $self->{switches}->{ $entry->{switch} }->{ $entry->{port} } = $entry->{node}; + } + else + { + $self->{switches}->{ $entry->{switch} }->{ $entry->{port} } .= ",$entry->{node}"; + } + } else { + xCAT::MsgUtils->message("S", "xCAT Table error:" . $entry->{node} . "Has missing or invalid switch.switch and/or switch.port fields"); } - else - { - $self->{switches}->{$entry->{switch}}->{$entry->{port}} .= ",$entry->{node}"; + } + my $children = 0; + my $inputs = new IO::Select; + $SIG{CHLD} = sub { while (waitpid(-1, WNOHANG) > 0) { $children-- } }; + foreach my $entry (@entries) { + if ($checked_pairs{ $entry->{switch} }) { + next; } - } else { - xCAT::MsgUtils->message("S","xCAT Table error:".$entry->{node}."Has missing or invalid switch.switch and/or switch.port fields"); + while ($children > 64) { + $self->handle_output($inputs); + } + $checked_pairs{ $entry->{switch} } = 1; + pipe my $child, my $parent; + $child->autoflush(1); + $parent->autoflush(1); + $children++; + my $cpid = xCAT::Utils->xfork; + unless (defined $cpid) { die "Cannot fork" } + + if ($cpid == 0) { + close($child); + $self->refresh_switch($parent, $community, $entry->{switch}); + exit(0); + } + close($parent); + $inputs->add($child); } - } - my $children = 0; - my $inputs = new IO::Select; - $SIG{CHLD}= sub { while(waitpid(-1,WNOHANG) > 0) { $children-- } }; - foreach my $entry (@entries) { - if ($checked_pairs{$entry->{switch}}) { - next; + while ($children) { + $self->handle_output($inputs); } - while($children > 64) { - $self->handle_output($inputs); - } - $checked_pairs{$entry->{switch}}=1; - pipe my $child,my $parent; - $child->autoflush(1); - $parent->autoflush(1); - $children++; - my $cpid = xCAT::Utils->xfork; - unless (defined $cpid) { die "Cannot fork" }; - if ($cpid == 0) { - close($child); - $self->refresh_switch($parent,$community,$entry->{switch}); - exit(0); - } - close($parent); - $inputs->add($child); - } - while($children) { - $self->handle_output($inputs); - } - while ($self->handle_output($inputs)) {}; #Drain the pipes - $self->{timestamp}=time; + while ($self->handle_output($inputs)) { }; #Drain the pipes + $self->{timestamp} = time; } sub handle_output { - my $self = shift; - my $inputs = shift; - my @readied = $inputs->can_read(1); - my $rc = @readied; - my $ready; - foreach $ready (@readied) { - my $line = <$ready>; - unless ($line) { - $inputs->remove($ready); - close($ready); - next; + my $self = shift; + my $inputs = shift; + my @readied = $inputs->can_read(1); + my $rc = @readied; + my $ready; + foreach $ready (@readied) { + my $line = <$ready>; + unless ($line) { + $inputs->remove($ready); + close($ready); + next; + } + $line =~ m/^([^|]*)\|(.*)/; + $self->{mactable}->{$1} = $2; } - $line =~ m/^([^|]*)\|(.*)/; - $self->{mactable}->{$1}=$2; - } - return $rc; + return $rc; } sub walkoid { - my $session = shift; - my $oid = shift; - my %namedargs = @_; - my $retmap = undef; - my $varbind = new SNMP::Varbind([$oid,'']); - $session->getnext($varbind); - if ($session->{ErrorStr}) { - unless ($namedargs{silentfail}) { - if ($namedargs{ciscowarn}) { - xCAT::MsgUtils->message("S","Error communicating with ".$session->{DestHost}." (First attempt at indexing by VLAN failed, ensure that the switch has the vlan configured such that it appears in 'show vlan'): ".$session->{ErrorStr}); - } else { - xCAT::MsgUtils->message("S","Error communicating with ".$session->{DestHost}.": ".$session->{ErrorStr}); - } + my $session = shift; + my $oid = shift; + my %namedargs = @_; + my $retmap = undef; + my $switch = undef; + my $callback = undef; + if (defined($namedargs{verbose})) { + $switch = $namedargs{switch}; + $callback = $namedargs{callback}; } - return undef; - } - my $count=0; - while ($varbind->[0] =~ /^$oid\.?(.*)/) { - $count++; - if ($1) { - $retmap->{$1.".".$varbind->[1]}=$varbind->[2]; #If $1 is set, means key should - } else { - $retmap->{$varbind->[1]}=$varbind->[2]; #If $1 is set, means key should + if ($switch) { + xCAT::MsgUtils->message("I", { data => ["$switch: SNMP Session query OID:\"$oid\""] }, $callback); } - + my $varbind = new SNMP::Varbind([ $oid, '' ]); $session->getnext($varbind); - } - return $retmap; + if ($session->{ErrorStr}) { + unless ($namedargs{silentfail}) { + if ($namedargs{ciscowarn}) { + xCAT::MsgUtils->message("S", "Error communicating with " . $session->{DestHost} . " (First attempt at indexing by VLAN failed, ensure that the switch has the vlan configured such that it appears in 'show vlan'): " . $session->{ErrorStr}); + } else { + xCAT::MsgUtils->message("S", "Error communicating with " . $session->{DestHost} . ": " . $session->{ErrorStr}); + } + } + if ($switch) { + xCAT::MsgUtils->message("I", { data => ["$switch: SNMP Session query OID:\"$oid\" Failed"] }, $callback); + } + return undef; + } + my $count = 0; + my $data_string; + while ($varbind->[0] =~ /^$oid\.?(.*)/) { + $count++; + if ($1) { + $retmap->{ $1 . "." . $varbind->[1] } = $varbind->[2]; #If $1 is set, means key should + $data_string .= "\t\t '" . $1 . "." . $varbind->[1] . "' => '$varbind->[2]'\n"; + } else { + $retmap->{ $varbind->[1] } = $varbind->[2]; #If $1 is set, means key should + $data_string .= "\t\t '$varbind->[1]' => '$varbind->[2]'\n"; + } + $session->getnext($varbind); + } + if ($switch) { + chomp($data_string); + xCAT::MsgUtils->message("I", { data => ["$switch: SNMP Session get data for OID:\"$oid\":\n$data_string"] }, $callback); + } + return $retmap; } sub getsnmpsession { -#gets an snmp v3 session appropriate for a switch using the switches table for guidance on the hows -#arguments: switch => $switchname and optionally vlan=> $vid if needed for community string indexing - my $self = shift; - my %args = @_; - my $switch = $args{'switch'}; - my $vlanid = $args{'vlanid'}; + + #gets an snmp v3 session appropriate for a switch using the switches table for guidance on the hows + #arguments: switch => $switchname and optionally vlan=> $vid if needed for community string indexing + my $self = shift; + my %args = @_; + my $switch = $args{'switch'}; + my $vlanid = $args{'vlanid'}; my $community = $args{'community'}; my $session; - my $snmpver='1'; - my $swent = $self->{switchparmhash}->{$switch}; + my $snmpver = '1'; + my $swent = $self->{switchparmhash}->{$switch}; - if ($swent) { - $snmpver=$swent->{snmpversion}; - $community=$swent->{password}; - } - if ($snmpver ne '3') { - if ($vlanid) { $community .= '@'.$vlanid; } - $session = new SNMP::Session( - DestHost => $switch, - Version => $snmpver, - Community => $community, - UseNumeric => 1 - ); - } else { #we have snmp3 - my %args= ( - DestHost => $switch, - SecName => $swent->{username}, - AuthProto => uc($swent->{auth}), - AuthPass => $community, - Version => $snmpver, - SecLevel => 'authNoPriv', - UseNumeric => 1 - ); - if ($vlanid) { $args{Context}="vlan-".$vlanid; } - if ($swent->{privacy}) { - $args{SecLevel}='authPriv'; - $args{PrivProto} = uc($swent->{privacy}); - $args{PrivPass} = $community; - } - $session = new SNMP::Session(%args); - } - return $session; + if ($swent) { + if ($swent->{snmpversion}) { + $snmpver = $swent->{snmpversion}; + } + if ($swent->{password}) { + $community = $swent->{password}; + } + } + my $switch_ip = xCAT::NetworkUtils->getipaddr($switch); + unless ($switch_ip) { + return ({ "ErrorStr" => "Can not resolve IP address for $switch" }); + } + if ($snmpver ne '3') { + if ($vlanid) { $community .= '@' . $vlanid; } + $session = new SNMP::Session( + DestHost => $switch_ip, + Version => $snmpver, + Community => $community, + UseNumeric => 1 + ); + if ($self->{show_verbose_info}) { + xCAT::MsgUtils->message("I", { data => ["$switch: Generate SNMP session with parameter: \n\t\t'Version' => '$snmpver'\n\t\t'Community' => '$community'"] }, $self->{callback}); + } + + } else { #we have snmp3 + my %args = ( + DestHost => $switch_ip, + SecName => $swent->{username}, + AuthProto => uc($swent->{auth}), + AuthPass => $community, + Version => $snmpver, + SecLevel => 'authNoPriv', + UseNumeric => 1 + ); + if ($vlanid) { $args{Context} = "vlan-" . $vlanid; } + if ($swent->{privacy}) { + $args{SecLevel} = 'authPriv'; + $args{PrivProto} = uc($swent->{privacy}); + $args{PrivPass} = $community; + } + if ($self->{show_verbose_info}) { + my $parameter_string = ''; + foreach (keys %args) { + $parameter_string .= "\t\t'$_' => '$args{$_}'\n"; + } + chomp($parameter_string); + xCAT::MsgUtils->message("I", { data => ["$switch: Generate SNMP session with parameter: \n$parameter_string"] }, $self->{callback}); + } + + $session = new SNMP::Session(%args); + } + return $session; } sub refresh_switch { - my $self = shift; - my $output = shift; - my $community = shift; - my $switch = shift; + my $self = shift; + my $output = shift; + my $community = shift; + my $switch = shift; + + #if ($error) { die $error; } + my $session = $self->getsnmpsession('community' => $community, 'switch' => $switch); + unless ($session) { + xCAT::MsgUtils->message("S", "Failed to communicate with $switch"); + if ($self->{collect_mac_info}) { + $self->{macinfo}->{$switch}->{ErrorStr} = "Failed to communicate with $switch through SNMP"; + } + return; + } + elsif ($session->{ErrorStr}) { + if ($self->{collect_mac_info}) { + $self->{macinfo}->{$switch}->{ErrorStr} = $session->{ErrorStr}; + } + return; + } + my $namemap = walkoid($session, '.1.3.6.1.2.1.31.1.1.1.1', verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); - #if ($error) { die $error; } - my $session = $self->getsnmpsession('community'=>$community,'switch'=>$switch); - unless ($session) { xCAT::MsgUtils->message("S","Failed to communicate with $switch"); return; } - my $namemap = walkoid($session,'.1.3.6.1.2.1.31.1.1.1.1'); #namemap is the mapping of ifIndex->(human readable name) - if ($namemap) { - my $ifnamesupport=0; #Assume broken ifnamesupport until proven good... (Nortel switch) - foreach (keys %{$namemap}) { - if ($namemap->{$_}) { - $ifnamesupport=1; - last; - } - } - unless ($ifnamesupport) { - $namemap=0; - } - } - unless ($namemap) { #Failback to ifDescr. ifDescr is close, but not perfect on some switches - $namemap = walkoid($session,'.1.3.6.1.2.1.2.2.1.2'); - } - unless ($namemap) { - return; - } - #Above is valid without community string indexing, on cisco, we need it on the next one and onward - my $iftovlanmap = walkoid($session,'.1.3.6.1.4.1.9.9.68.1.2.2.1.2',silentfail=>1); #use cisco vlan membership mib to ascertain vlan - my $trunktovlanmap = walkoid($session,'.1.3.6.1.4.1.9.9.46.1.6.1.1.5',silentfail=>1); #for trunk ports, we are interested in the native vlan - #so we need cisco vtp mib too - my %vlans_to_check; - if (defined($iftovlanmap) or defined($trunktovlanmap)) { #We have a cisco, the intelligent thing is to do SNMP gets on the ports - $self->{switchinfo}->{$switch}->{vlanidtoindex}="NA";#mark this switch to ignore for qbridge scans -# that we can verify are populated per switch table - my $portid; - foreach $portid (keys %{$namemap}) { - my $portname; - my $switchport = $namemap->{$portid}; - foreach $portname (keys %{$self->{switches}->{$switch}}) { - unless (namesmatch($portname,$switchport)) { - next; - } - if (not defined $iftovlanmap->{$portid} and not defined $trunktovlanmap->{$portid}) { - xCAT::MsgUtils->message("S","$portid missing from switch"); - next; - } - if (defined $iftovlanmap->{$portid}) { - $vlans_to_check{"".$iftovlanmap->{$portid}} = 1; #cast to string, may not be needed - $self->{nodeinfo}->{$self->{switches}->{$switch}->{$portname}}->{vlans}->{$portname}=$iftovlanmap->{$portid}; - } else { #given above if statement, brigetovlanmap *must* be defined* - $vlans_to_check{"".$trunktovlanmap->{$portid}} = 1; #cast to string, may not be needed - $self->{nodeinfo}->{$self->{switches}->{$switch}->{$portname}}->{vlans}->{$portname}=$trunktovlanmap->{$portid}; - } - } - } - } else { - $vlans_to_check{'NA'}=1; - } - - my $vlan; - my $iscisco=0; - foreach $vlan (sort keys %vlans_to_check) { #Sort, because if numbers, we want 1 first, because that vlan should not get communiy string indexed query - unless (not $vlan or $vlan eq 'NA' or $vlan eq '1') { #don't subject users to the context pain unless needed - $iscisco=1; - $session = $self->getsnmpsession('switch'=>$switch,'community'=>$community,'vlanid'=>$vlan); - } - unless ($session) { return; } - my $bridgetoifmap = walkoid($session,'.1.3.6.1.2.1.17.1.4.1.2',ciscowarn=>$iscisco); # Good for all switches - if (not ref $bridgetoifmap or !keys %{$bridgetoifmap}) { - xCAT::MsgUtils->message("S","Error communicating with ".$session->{DestHost}.": failed to get a valid response to BRIDGE-MIB request"); - return; - } - - # my $mactoindexmap = walkoid($session,'.1.3.6.1.2.1.17.4.3.1.2'); - my $mactoindexmap = walkoid($session,'.1.3.6.1.2.1.17.7.1.2.2.1.2',silentfail=>1); - unless (defined($mactoindexmap)) { #if no qbridge defined, try bridge mib, probably cisco - #$mactoindexmap = walkoid($session,'.1.3.6.1.2.1.17.7.1.2.2.1.2'); - $mactoindexmap = walkoid($session,'.1.3.6.1.2.1.17.4.3.1.2',ciscowarn=>$iscisco); - } #Ok, time to process the data - if (not ref $mactoindexmap or !keys %{$mactoindexmap}) { - xCAT::MsgUtils->message("S","Error communicating with ".$session->{DestHost}.": Unable to get MAC entries via either BRIDGE or Q-BRIDE MIB"); - return; - } - foreach my $oid (keys %$namemap) { - #$oid =~ m/1.3.6.1.2.1.31.1.1.1.1.(.*)/; - my $ifindex = $oid; - my $portname; - my $switchport = $namemap->{$oid}; - foreach $portname (keys %{$self->{switches}->{$switch}}) { # a little redundant, but - # computationally trivial - unless (namesmatch($portname,$switchport)) { next } - #if still running, we have match - foreach my $boid (keys %$bridgetoifmap) { - unless ($bridgetoifmap->{$boid} == $ifindex) { next; } - $self->{switchinfo}->{$switch}->{bridgeidxtoifname}->{$boid}=$portname; - $self->{switchinfo}->{$switch}->{ifnametobridgeidx}->{$portname}=$boid; - $self->{nodeinfo}->{$self->{switches}->{$switch}->{$portname}}->{portnametobridgeindex}->{$portname}=$boid; - $self->{nodeinfo}->{$self->{switches}->{$switch}->{$portname}}->{bridgeindextoportname}->{$boid}=$portname; - my $bridgeport = $boid; - foreach (keys %$mactoindexmap) { - if ($mactoindexmap->{$_} == $bridgeport) { - my @tmp = split /\./, $_; - my @mac = @tmp[-6 .. -1]; - my $macstring=sprintf("%02x:%02x:%02x:%02x:%02x:%02x",@mac); - if ($output) { - printf $output "$macstring|%s\n",$self->{switches}->{$switch}->{$portname}; - } - push @{$self->{nodeinfo}->{$self->{switches}->{$switch}->{$portname}}->{macs}->{$portname}},$macstring; #this could be used as getmacs sort of deal + if ($namemap) { + my $ifnamesupport = 0; #Assume broken ifnamesupport until proven good... (Nortel switch) + foreach (keys %{$namemap}) { + if ($namemap->{$_}) { + $ifnamesupport = 1; + last; } - } } - } + unless ($ifnamesupport) { + $namemap = 0; + } } - } - $self->{switchsessions}->{$switch}=$session; #save session for future use + unless ($namemap) { #Failback to ifDescr. ifDescr is close, but not perfect on some switches + $namemap = walkoid($session, '.1.3.6.1.2.1.2.2.1.2', verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); + } + unless ($namemap) { + if ($session->{ErrorStr} and $self->{collect_mac_info}) { + $self->{macinfo}->{$switch}->{ErrorStr} = $session->{ErrorStr}; + } + return; + } + + #Above is valid without community string indexing, on cisco, we need it on the next one and onward + my $iftovlanmap = walkoid($session, '.1.3.6.1.4.1.9.9.68.1.2.2.1.2', silentfail => 1, verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); #use cisco vlan membership mib to ascertain vlan + my $trunktovlanmap = walkoid($session, '.1.3.6.1.4.1.9.9.46.1.6.1.1.5', silentfail => 1, verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); #for trunk ports, we are interested in the native vlan, so we need cisco vtp mib too + my %vlans_to_check; + if (defined($iftovlanmap) or defined($trunktovlanmap)) { #We have a cisco, the intelligent thing is to do SNMP gets on the ports + $self->{switchinfo}->{$switch}->{vlanidtoindex} = "NA"; #mark this switch to ignore for qbridge scans + + # that we can verify are populated per switch table + my $portid; + foreach $portid (keys %{$namemap}) { + my $portname; + my $switchport = $namemap->{$portid}; + foreach $portname (keys %{ $self->{switches}->{$switch} }) { + unless (namesmatch($portname, $switchport)) { + next; + } + if (not defined $iftovlanmap->{$portid} and not defined $trunktovlanmap->{$portid}) { + xCAT::MsgUtils->message("S", "$portid missing from switch"); + next; + } + if (defined $iftovlanmap->{$portid}) { + $vlans_to_check{ "" . $iftovlanmap->{$portid} } = 1; #cast to string, may not be needed + $self->{nodeinfo}->{ $self->{switches}->{$switch}->{$portname} }->{vlans}->{$portname} = $iftovlanmap->{$portid}; + } else { #given above if statement, brigetovlanmap *must* be defined* + $vlans_to_check{ "" . $trunktovlanmap->{$portid} } = 1; #cast to string, may not be needed + $self->{nodeinfo}->{ $self->{switches}->{$switch}->{$portname} }->{vlans}->{$portname} = $trunktovlanmap->{$portid}; + } + } + } + } else { + $vlans_to_check{'NA'} = 1; + } + + my $vlan; + my $iscisco = 0; + foreach $vlan (sort keys %vlans_to_check) { #Sort, because if numbers, we want 1 first, because that vlan should not get communiy string indexed query + unless (not $vlan or $vlan eq 'NA' or $vlan eq '1') { #don't subject users to the context pain unless needed + $iscisco = 1; + $session = $self->getsnmpsession('switch' => $switch, 'community' => $community, 'vlanid' => $vlan); + } + unless ($session) { return; } + elsif ($session->{ErrorStr}) { + if ($self->{collect_mac_info}) { + $self->{macinfo}->{$switch}->{ErrorStr} = $session->{ErrorStr}; + } + return; + } + my $bridgetoifmap = walkoid($session, '.1.3.6.1.2.1.17.1.4.1.2', ciscowarn => $iscisco, verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); # Good for all switches + if (not ref $bridgetoifmap or !keys %{$bridgetoifmap}) { + xCAT::MsgUtils->message("S", "Error communicating with " . $session->{DestHost} . ": failed to get a valid response to BRIDGE-MIB request"); + return; + } + + # my $mactoindexmap = walkoid($session,'.1.3.6.1.2.1.17.4.3.1.2'); + my $mactoindexmap = walkoid($session, '.1.3.6.1.2.1.17.7.1.2.2.1.2', silentfail => 1, verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); + unless (defined($mactoindexmap)) { #if no qbridge defined, try bridge mib, probably cisco + #$mactoindexmap = walkoid($session,'.1.3.6.1.2.1.17.7.1.2.2.1.2'); + $mactoindexmap = walkoid($session, '.1.3.6.1.2.1.17.4.3.1.2', ciscowarn => $iscisco, verbose => $self->{show_verbose_info}, switch => $switch, callback => $self->{callback}); + } #Ok, time to process the data + if (not ref $mactoindexmap or !keys %{$mactoindexmap}) { + xCAT::MsgUtils->message("S", "Error communicating with " . $session->{DestHost} . ": Unable to get MAC entries via either BRIDGE or Q-BRIDE MIB"); + return; + } + if (defined($self->{collect_mac_info})) { + my %index_to_mac = (); + foreach (keys %$mactoindexmap) { + my $index = $mactoindexmap->{$_}; + my @tmp = split /\./, $_; + my @mac = @tmp[ -6 .. -1 ]; + my $macstring = sprintf("%02x:%02x:%02x:%02x:%02x:%02x", @mac); + push @{ $index_to_mac{$index} }, $macstring; + } + foreach my $boid (keys %$bridgetoifmap) { + my $port_index = $boid; + my $port_name = $namemap->{ $bridgetoifmap->{$port_index} }; + if (defined($index_to_mac{$port_index})) { + push @{ $self->{macinfo}->{$switch}->{$port_name} }, @{ $index_to_mac{$port_index} }; + } + else { + $self->{macinfo}->{$switch}->{$port_name}->[0] = ''; + } + } + return; + } + + foreach my $oid (keys %$namemap) { + + #$oid =~ m/1.3.6.1.2.1.31.1.1.1.1.(.*)/; + my $ifindex = $oid; + my $portname; + my $switchport = $namemap->{$oid}; + foreach $portname (keys %{ $self->{switches}->{$switch} }) { # a little redundant, but + # computationally trivial + unless (namesmatch($portname, $switchport)) { next } + + #if still running, we have match + foreach my $boid (keys %$bridgetoifmap) { + unless ($bridgetoifmap->{$boid} == $ifindex) { next; } + $self->{switchinfo}->{$switch}->{bridgeidxtoifname}->{$boid} = $portname; + $self->{switchinfo}->{$switch}->{ifnametobridgeidx}->{$portname} = $boid; + $self->{nodeinfo}->{ $self->{switches}->{$switch}->{$portname} }->{portnametobridgeindex}->{$portname} = $boid; + $self->{nodeinfo}->{ $self->{switches}->{$switch}->{$portname} }->{bridgeindextoportname}->{$boid} = $portname; + my $bridgeport = $boid; + foreach (keys %$mactoindexmap) { + if ($mactoindexmap->{$_} == $bridgeport) { + my @tmp = split /\./, $_; + my @mac = @tmp[ -6 .. -1 ]; + my $macstring = sprintf("%02x:%02x:%02x:%02x:%02x:%02x", @mac); + if ($output) { + printf $output "$macstring|%s\n", $self->{switches}->{$switch}->{$portname}; + } + push @{ $self->{nodeinfo}->{ $self->{switches}->{$switch}->{$portname} }->{macs}->{$portname} }, $macstring; #this could be used as getmacs sort of deal + } + } + } + } + } + } + $self->{switchsessions}->{$switch} = $session; #save session for future use } - + diff --git a/perl-xCAT/xCAT/MsgUtils.pm b/perl-xCAT/xCAT/MsgUtils.pm index d4bcc879e..b2e6484be 100644 --- a/perl-xCAT/xCAT/MsgUtils.pm +++ b/perl-xCAT/xCAT/MsgUtils.pm @@ -6,12 +6,13 @@ package xCAT::MsgUtils; # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use strict; use Sys::Syslog; use xCAT::Utils; + #use locale; use Socket; use File::Path; @@ -294,12 +295,12 @@ sub message # my $newrsp; if (($sev eq 'SA') || ($sev eq 'A')) - { # if SA ( syslog and auditlog) or A ( only auditlog)then need to pull first entry from $rsp - # for syslog, to preserve old interface + { # if SA ( syslog and auditlog) or A ( only auditlog)then need to pull first entry from $rsp + # for syslog, to preserve old interface $newrsp = $rsp; - if ($sev eq 'SA'){ # syslog and auditlog - $rsp = $newrsp->{syslogdata}->[0]; - } + if ($sev eq 'SA') { # syslog and auditlog + $rsp = $newrsp->{syslogdata}->[0]; + } } my $stdouterrf = \*STDOUT; my $stdouterrd = ''; @@ -323,17 +324,17 @@ sub message # build callback structure my $newrsp; my $sevkey = 'error'; - my $err = - "Logging requested without setting up log by calling xCAT:MsgUtils->start_logging.\n"; - push @{$newrsp->{$sevkey}}, $err; - push @{$newrsp->{errorcode}}, "1"; + my $err = +"Logging requested without setting up log by calling xCAT:MsgUtils->start_logging.\n"; + push @{ $newrsp->{$sevkey} }, $err; + push @{ $newrsp->{errorcode} }, "1"; $call_back->($newrsp); # send message to daemon/Client.pm return 1; } else { print - "Logging requested without setting up log by calling xCAT:MsgUtils->start_logging.\n"; +"Logging requested without setting up log by calling xCAT:MsgUtils->start_logging.\n"; return 1; } } @@ -369,11 +370,11 @@ sub message if ($call_back) { # callback routine provided my $sevkey; - if ($sev =~ /D/) { $sevkey = 'data'; } - elsif ($sev =~ /N/) { $sevkey = 'node'; } + if ($sev =~ /D/) { $sevkey = 'data'; } + elsif ($sev =~ /N/) { $sevkey = 'node'; } elsif ($sev =~ /IS/) { $sevkey = 'sinfo'; } - elsif ($sev =~ /I/) { $sevkey = 'info'; } - elsif ($sev =~ /W/) { $sevkey = 'warning'; } + elsif ($sev =~ /I/) { $sevkey = 'info'; } + elsif ($sev =~ /W/) { $sevkey = 'warning'; } elsif ($sev =~ /E/) { $sevkey = 'error'; @@ -388,10 +389,10 @@ sub message # build callback structure my $newrsp; my $sevkey = 'error'; - my $err = + my $err = "Invalid or no severity code passed to MsgUtils::message().\n"; - push @{$newrsp->{$sevkey}}, $err; - push @{$newrsp->{errorcode}}, "1"; + push @{ $newrsp->{$sevkey} }, $err; + push @{ $newrsp->{errorcode} }, "1"; $call_back->($newrsp); # send message to daemon/Client.pm return 1; } @@ -403,35 +404,35 @@ sub message { if ($sevkey ne 'data') { - if (!defined($rsp->{$sevkey}) || !scalar(@{$rsp->{$sevkey}})) + if (!defined($rsp->{$sevkey}) || !scalar(@{ $rsp->{$sevkey} })) { # did not pass the text in in the severity-specific field # so fix it - if (defined($rsp->{data}) && scalar(@{$rsp->{data}})) + if (defined($rsp->{data}) && scalar(@{ $rsp->{data} })) { - push @{$rsp->{$sevkey}}, @{$rsp->{data}}; + push @{ $rsp->{$sevkey} }, @{ $rsp->{data} }; # assume they passed # in the text in the data field instead - @{$rsp->{data}} = (); # clear out the data field + @{ $rsp->{data} } = (); # clear out the data field } } } # if still nothing in the array, there is nothing to print out - if (!defined($rsp->{$sevkey}) || !scalar(@{$rsp->{$sevkey}})) + if (!defined($rsp->{$sevkey}) || !scalar(@{ $rsp->{$sevkey} })) { return; } if (defined($exitcode)) { - push @{$rsp->{errorcode}}, $exitcode; + push @{ $rsp->{errorcode} }, $exitcode; } $call_back->($rsp); # send message to daemon/Client.pm - @{$rsp->{$sevkey}} = + @{ $rsp->{$sevkey} } = (); # clear out the rsp structure in case they use it again - @{$rsp->{data}} = (); - @{$rsp->{errorcode}} = (); + @{ $rsp->{data} } = (); + @{ $rsp->{errorcode} } = (); } else # logging { @@ -441,10 +442,10 @@ sub message # build callback structure my $newrsp; - push @{$newrsp->{$sevkey}}, $rsp; + push @{ $newrsp->{$sevkey} }, $rsp; if ($exitcode) { - push @{$newrsp->{errorcode}}, $exitcode; + push @{ $newrsp->{errorcode} }, $exitcode; } $call_back->($newrsp); # send message to daemon/Client.pm @@ -464,7 +465,7 @@ sub message } } - # is syslog option requested + # is syslog option requested if ($sev =~ /S/) { @@ -472,9 +473,9 @@ sub message eval { openlog("xcat", "nofatal,pid", "local4"); if ($sev eq 'SE') { - syslog("err", $rsp); + syslog("err", $rsp); } else { - syslog("info", $rsp); + syslog("info", $rsp); } closelog(); }; @@ -487,59 +488,59 @@ sub message } # if write to auditlog table requested, if not on service node - if (xCAT::Utils->isMN()){ - if (($sev eq 'SA') || ($sev eq 'A')) - { - require xCAT::Table; - my $auditlogentry; - my $tab = xCAT::Table->new("auditlog"); - if ($tab) + if (xCAT::Utils->isMN()) { + if (($sev eq 'SA') || ($sev eq 'A')) { - my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = - localtime(time); - - my $currtime = sprintf("%04d-%02d-%02d %02d:%02d:%02d", - $year + 1900, $mon + 1, $mday, - $hour, $min, $sec); - - $auditlogentry->{audittime} = $currtime; - $auditlogentry->{userid} = $newrsp->{userid}->[0]; - $auditlogentry->{clientname} = $newrsp->{clientname}->[0]; - $auditlogentry->{clienttype} = $newrsp->{clienttype}->[0]; - $auditlogentry->{command} = $newrsp->{command}->[0]; - $auditlogentry->{noderange} = $newrsp->{noderange}->[0]; - $auditlogentry->{args} = $newrsp->{args}->[0]; - $auditlogentry->{status} = $newrsp->{status}->[0]; - - my @ret = $tab->setAttribs(undef, $auditlogentry); - if (@ret > 1) + require xCAT::Table; + my $auditlogentry; + my $tab = xCAT::Table->new("auditlog"); + if ($tab) { + my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = + localtime(time); + + my $currtime = sprintf("%04d-%02d-%02d %02d:%02d:%02d", + $year + 1900, $mon + 1, $mday, + $hour, $min, $sec); + + $auditlogentry->{audittime} = $currtime; + $auditlogentry->{userid} = $newrsp->{userid}->[0]; + $auditlogentry->{clientname} = $newrsp->{clientname}->[0]; + $auditlogentry->{clienttype} = $newrsp->{clienttype}->[0]; + $auditlogentry->{command} = $newrsp->{command}->[0]; + $auditlogentry->{noderange} = $newrsp->{noderange}->[0]; + $auditlogentry->{args} = $newrsp->{args}->[0]; + $auditlogentry->{status} = $newrsp->{status}->[0]; + + my @ret = $tab->setAttribs(undef, $auditlogentry); + if (@ret > 1) + { + print $stdouterrf "Unable to open auditlog\n"; + eval { + openlog("xcat", "nofatal,pid", "local4"); + syslog("err", "Unable to write to auditlog"); + closelog(); + }; + } + else + { + my $DBname = xCAT::Utils->get_DBName; + if (!($DBname =~ /^SQLITE/)) { + $tab->commit; + } + } + } + else + { # error print $stdouterrf "Unable to open auditlog\n"; eval { openlog("xcat", "nofatal,pid", "local4"); - syslog("err", "Unable to write to auditlog"); + syslog("err", "Unable to open auditlog"); closelog(); }; - } - else - { - my $DBname = xCAT::Utils->get_DBName; - if (!($DBname =~ /^SQLITE/)) { - $tab->commit; - } - } - } - else - { # error - print $stdouterrf "Unable to open auditlog\n"; - eval { - openlog("xcat", "nofatal,pid", "local4"); - syslog("err", "Unable to open auditlog"); - closelog(); - }; + } } - } } return; } @@ -628,7 +629,8 @@ sub start_logging $::LOG_FILE_NAME = $logfile; # Make the file to be unbuffered - binmode( $::LOG_FILE_HANDLE, ":unix" ); + binmode($::LOG_FILE_HANDLE, ":unix"); + # Print the program name and date to the top of the logfile my $sdate = `/bin/date`; chomp $sdate; @@ -724,14 +726,14 @@ sub backup_logfile sub verbose_message { shift; - my $req = shift; + my $req = shift; my $data = shift; - if (!defined($req->{verbose})) { + if (!defined($req->{verbose})) { return; } - my ($sec,$min,$hour,$mday,$mon,$yr,$wday,$yday,$dst) = localtime(time); - my $time = sprintf "%04d%02d%02d.%02d:%02d:%02d", $yr+1900,$mon+1,$mday,$hour,$min,$sec; - $data = "$time ($$) ".$data; + my ($sec, $min, $hour, $mday, $mon, $yr, $wday, $yday, $dst) = localtime(time); + my $time = sprintf "%04d%02d%02d.%02d:%02d:%02d", $yr + 1900, $mon + 1, $mday, $hour, $min, $sec; + $data = "$time ($$) " . $data; if (defined($req->{callback})) { my %rsp; $rsp{data} = [$data]; @@ -779,39 +781,39 @@ sub verbose_message =cut #-------------------------------------------------------------------------------- -sub trace(){ +sub trace() { shift; - my $verbose = shift; - my $level = shift; + my $verbose = shift; + my $level = shift; my $logcontent = shift; - + my $prefix = ""; - if(($level eq "E")||($level eq "e")){$prefix="ERR";} - if(($level eq "W")||($level eq "w")){$prefix="WARNING";} - if(($level eq "I")||($level eq "i")){$prefix="INFO";} - if(($level eq "D")||($level eq "d")){$prefix="DEBUG";} + if (($level eq "E") || ($level eq "e")) { $prefix = "ERR"; } + if (($level eq "W") || ($level eq "w")) { $prefix = "WARNING"; } + if (($level eq "I") || ($level eq "i")) { $prefix = "INFO"; } + if (($level eq "D") || ($level eq "d")) { $prefix = "DEBUG"; } - my @tmp = xCAT::TableUtils->get_site_attribute("xcatdebugmode"); - my $xcatdebugmode=$tmp[0]; + my @tmp = xCAT::TableUtils->get_site_attribute("xcatdebugmode"); + my $xcatdebugmode = $tmp[0]; - if (($level eq "E") - ||($level eq "e") - ||($level eq "I") - ||($level eq "i") - ||($level eq "W") - ||($level eq "w")){ - my $msg = $prefix." ".$logcontent; + if (($level eq "E") + || ($level eq "e") + || ($level eq "I") + || ($level eq "i") + || ($level eq "W") + || ($level eq "w")) { + my $msg = $prefix . " " . $logcontent; eval { openlog("xcat", "nofatal,pid", "local4"); syslog("$prefix", $msg); closelog(); }; } - - if (($level eq "D") - ||($level eq "d")){ - if(($verbose == 1 )||($xcatdebugmode eq "1")||($xcatdebugmode eq "2")){ - my $msg = $prefix." ".$logcontent; + + if (($level eq "D") + || ($level eq "d")) { + if (($verbose == 1) || ($xcatdebugmode eq "1") || ($xcatdebugmode eq "2")) { + my $msg = $prefix . " " . $logcontent; eval { openlog("xcat", "nofatal,pid", "local4"); syslog("$prefix", $msg); diff --git a/perl-xCAT/xCAT/NetworkUtils.pm b/perl-xCAT/xCAT/NetworkUtils.pm index 2f699c8fa..d523dc8f3 100755 --- a/perl-xCAT/xCAT/NetworkUtils.pm +++ b/perl-xCAT/xCAT/NetworkUtils.pm @@ -10,7 +10,7 @@ BEGIN # if AIX - make sure we include perl 5.8.2 in INC path. # Needed to find perl dependencies shipped in deps tarball. if ($^O =~ /^aix/i) { - unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); + unshift(@INC, qw(/usr/opt/perl5/lib/5.8.2/aix-thread-multi /usr/opt/perl5/lib/5.8.2 /usr/opt/perl5/lib/site_perl/5.8.2/aix-thread-multi /usr/opt/perl5/lib/site_perl/5.8.2)); } use lib "$::XCATROOT/lib/perl"; @@ -19,6 +19,7 @@ use File::Path; use Math::BigInt; use Socket; use xCAT::GlobalDef; + #use Data::Dumper; use strict; use warnings "all"; @@ -27,7 +28,8 @@ my $socket6support = eval { require Socket6 }; our @ISA = qw(Exporter); our @EXPORT_OK = qw(getipaddr); -my $utildata; #data to persist locally +my $utildata; #data to persist locally + #-------------------------------------------------------------------------------- =head1 xCAT::NetworkUtils @@ -69,31 +71,31 @@ This program module file, is a set of network utilities used by xCAT commands. #------------------------------------------------------------------------------- sub getNodeDomains() { - my $class = shift; - my $nodes = shift; + my $class = shift; + my $nodes = shift; - my @nodelist = @$nodes; - my %nodedomains; + my @nodelist = @$nodes; + my %nodedomains; - # Get the network info for each node - my %nethash = xCAT::DBobjUtils->getNetwkInfo(\@nodelist); + # Get the network info for each node + my %nethash = xCAT::DBobjUtils->getNetwkInfo(\@nodelist); - # get the site domain value - my @domains = xCAT::TableUtils->get_site_attribute("domain"); - my $sitedomain = $domains[0]; + # get the site domain value + my @domains = xCAT::TableUtils->get_site_attribute("domain"); + my $sitedomain = $domains[0]; - # for each node - set hash value to network domain or default - # to site domain - foreach my $node (@nodelist) { - unless (defined($node)) {next;} - if (defined($nethash{$node}) && $nethash{$node}{domain}) { - $nodedomains{$node} = $nethash{$node}{domain}; - } else { - $nodedomains{$node} = $sitedomain; - } + # for each node - set hash value to network domain or default + # to site domain + foreach my $node (@nodelist) { + unless (defined($node)) { next; } + if (defined($nethash{$node}) && $nethash{$node}{domain}) { + $nodedomains{$node} = $nethash{$node}{domain}; + } else { + $nodedomains{$node} = $sitedomain; } + } - return \%nodedomains; + return \%nodedomains; } #------------------------------------------------------------------------------- @@ -123,11 +125,11 @@ sub gethostnameandip() { my ($class, $iporhost) = @_; - if (($iporhost =~ /\d+\.\d+\.\d+\.\d+/) || ($iporhost =~ /:/)) #ip address + if (($iporhost =~ /\d+\.\d+\.\d+\.\d+/) || ($iporhost =~ /:/)) #ip address { return (xCAT::NetworkUtils->gethostname($iporhost), $iporhost); } - else #hostname + else #hostname { return ($iporhost, xCAT::NetworkUtils->getipaddr($iporhost)); } @@ -165,18 +167,19 @@ sub gethostname() if (ref($iporhost) eq 'ARRAY') { - $iporhost = @{$iporhost}[0]; - if (!$iporhost) - { - return undef; - } + $iporhost = @{$iporhost}[0]; + if (!$iporhost) + { + return undef; + } } - + if (($iporhost !~ /\d+\.\d+\.\d+\.\d+/) && ($iporhost !~ /:/)) { #why you do so? pass in a hostname and only want a hostname?? return $iporhost; } + #cache, do not lookup DNS each time if (defined($::iphosthash{$iporhost}) && $::iphosthash{$iporhost}) { @@ -186,15 +189,15 @@ sub gethostname() { if ($socket6support) # the getaddrinfo and getnameinfo supports both IPv4 and IPv6 { - my ($family, $socket, $protocol, $ip, $name) = Socket6::getaddrinfo($iporhost,0,AF_UNSPEC,SOCK_STREAM,6); #specifically ask for TCP capable records, maximizing chance of no more than one return per v4/v6 + my ($family, $socket, $protocol, $ip, $name) = Socket6::getaddrinfo($iporhost, 0, AF_UNSPEC, SOCK_STREAM, 6); #specifically ask for TCP capable records, maximizing chance of no more than one return per v4/v6 my $host = (Socket6::getnameinfo($ip))[0]; - if ($host eq $iporhost) # can not resolve + if ($host eq $iporhost) # can not resolve { return undef; } if ($host) { - $host =~ s/\..*//; #short hostname + $host =~ s/\..*//; #short hostname } return $host; } @@ -207,12 +210,12 @@ sub gethostname() return undef; } my $hostname = gethostbyaddr(inet_aton($iporhost), AF_INET); - if ( $hostname ) { - $hostname =~ s/\..*//; #short hostname + if ($hostname) { + $hostname =~ s/\..*//; #short hostname } return $hostname; } - } + } } #------------------------------------------------------------------------------- @@ -241,26 +244,26 @@ sub gethostname() sub getipaddr { my $iporhost = shift; - if ($iporhost eq 'xCAT::NetworkUtils') { #was called with -> syntax + if ($iporhost eq 'xCAT::NetworkUtils') { #was called with -> syntax $iporhost = shift; } my %extraarguments = @_; - if (!defined($iporhost)) - { - return undef; - } + if (!defined($iporhost)) + { + return undef; + } - if (ref($iporhost) eq 'ARRAY') - { - $iporhost = @{$iporhost}[0]; - if (!$iporhost) - { - return undef; - } - } + if (ref($iporhost) eq 'ARRAY') + { + $iporhost = @{$iporhost}[0]; + if (!$iporhost) + { + return undef; + } + } - #go ahead and do the reverse lookup on ip, useful to 'frontend' aton/pton and also to + #go ahead and do the reverse lookup on ip, useful to 'frontend' aton/pton and also to #spit out a common abbreviation if leading zeroes or using different ipv6 presentation rules #if ($iporhost and ($iporhost =~ /\d+\.\d+\.\d+\.\d+/) || ($iporhost =~ /:/)) #{ @@ -278,31 +281,31 @@ sub getipaddr if ($socket6support) # the getaddrinfo and getnameinfo supports both IPv4 and IPv6 { my @returns; - my $reqfamily=AF_UNSPEC; + my $reqfamily = AF_UNSPEC; if ($extraarguments{OnlyV6}) { - $reqfamily=AF_INET6; + $reqfamily = AF_INET6; } elsif ($extraarguments{OnlyV4}) { - $reqfamily=AF_INET; + $reqfamily = AF_INET; } - my @addrinfo = Socket6::getaddrinfo($iporhost,0,$reqfamily,SOCK_STREAM,6); - my ($family, $socket, $protocol, $ip, $name) = splice(@addrinfo,0,5); + my @addrinfo = Socket6::getaddrinfo($iporhost, 0, $reqfamily, SOCK_STREAM, 6); + my ($family, $socket, $protocol, $ip, $name) = splice(@addrinfo, 0, 5); while ($ip) { if ($extraarguments{GetNumber}) { #return a BigInt for compare, e.g. for comparing ip addresses for determining if they are in a common network or range my $ip = (Socket6::getnameinfo($ip, Socket6::NI_NUMERICHOST()))[0]; my $bignumber = Math::BigInt->new(0); - foreach (unpack("N*",Socket6::inet_pton($family,$ip))) { #if ipv4, loop will iterate once, for v6, will go 4 times + foreach (unpack("N*", Socket6::inet_pton($family, $ip))) { #if ipv4, loop will iterate once, for v6, will go 4 times $bignumber->blsft(32); $bignumber->badd($_); } - push(@returns,$bignumber); + push(@returns, $bignumber); } else { - push @returns,(Socket6::getnameinfo($ip, Socket6::NI_NUMERICHOST()))[0]; + push @returns, (Socket6::getnameinfo($ip, Socket6::NI_NUMERICHOST()))[0]; } if (scalar @addrinfo and $extraarguments{GetAllAddresses}) { - ($family, $socket, $protocol, $ip, $name) = splice(@addrinfo,0,5); + ($family, $socket, $protocol, $ip, $name) = splice(@addrinfo, 0, 5); } else { - $ip=0; + $ip = 0; } } unless ($extraarguments{GetAllAddresses}) { @@ -312,25 +315,26 @@ sub getipaddr } else { - #return inet_ntoa(inet_aton($iporhost)) - #TODO, what if no scoket6 support, but passing in a IPv6 hostname? - if ($iporhost =~ /:/) { #ipv6 - return undef; - #die "Attempt to process IPv6 address, but system does not have requisite IPv6 perl support"; - } - my $packed_ip; - $iporhost and $packed_ip = inet_aton($iporhost); - if (!$packed_ip) - { + #return inet_ntoa(inet_aton($iporhost)) + #TODO, what if no scoket6 support, but passing in a IPv6 hostname? + if ($iporhost =~ /:/) { #ipv6 return undef; - } - if ($extraarguments{GetNumber}) { #only 32 bits, no for loop needed. - return Math::BigInt->new(unpack("N*",$packed_ip)); - } - return inet_ntoa($packed_ip); + + #die "Attempt to process IPv6 address, but system does not have requisite IPv6 perl support"; + } + my $packed_ip; + $iporhost and $packed_ip = inet_aton($iporhost); + if (!$packed_ip) + { + return undef; + } + if ($extraarguments{GetNumber}) { #only 32 bits, no for loop needed. + return Math::BigInt->new(unpack("N*", $packed_ip)); + } + return inet_ntoa($packed_ip); } } -} +} #------------------------------------------------------------------------------- @@ -357,8 +361,9 @@ sub linklocaladdr { my $localprefix = "fe80"; my ($m1, $m2, $m3, $m6, $m7, $m8); + # mac address can be 00215EA376B0 or 00:21:5E:A3:76:B0 - if($mac =~ /^([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2})$/) + if ($mac =~ /^([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2}).*?([0-9A-Fa-f]{2})$/) { ($m1, $m2, $m3, $m6, $m7, $m8) = ($1, $2, $3, $4, $5, $6); } @@ -367,7 +372,7 @@ sub linklocaladdr { #not a valid mac address return undef; } - my ($m4, $m5) = ("ff","fe"); + my ($m4, $m5) = ("ff", "fe"); #my $bit = (int $m1) & 2; #if ($bit) { @@ -420,31 +425,31 @@ sub ishostinsubnet { { return 0; } - my $numbits=32; - if ($ip =~ /:/) {#ipv6 - $numbits=128; + my $numbits = 32; + if ($ip =~ /:/) { #ipv6 + $numbits = 128; } if ($mask) { - if ($mask =~ /\//) { - $mask =~ s/^\///; - $mask=Math::BigInt->new("0b".("1"x$mask).("0"x($numbits-$mask))); - } else { - $mask=getipaddr($mask,GetNumber=>1); - } - } else { #CIDR notation supported - if ($subnet && ($subnet =~ /\//)) { - ($subnet,$mask) = split /\//,$subnet,2; - $mask=Math::BigInt->new("0b".("1"x$mask).("0"x($numbits-$mask))); + if ($mask =~ /\//) { + $mask =~ s/^\///; + $mask = Math::BigInt->new("0b" . ("1" x $mask) . ("0" x ($numbits - $mask))); + } else { + $mask = getipaddr($mask, GetNumber => 1); + } + } else { #CIDR notation supported + if ($subnet && ($subnet =~ /\//)) { + ($subnet, $mask) = split /\//, $subnet, 2; + $mask = Math::BigInt->new("0b" . ("1" x $mask) . ("0" x ($numbits - $mask))); } else { die "ishostinsubnet must either be called with a netmask or CIDR /bits notation"; } } - if ($subnet && ($subnet =~ /\//)) #remove CIDR suffix from subnet + if ($subnet && ($subnet =~ /\//)) #remove CIDR suffix from subnet { $subnet =~ s/\/.*$//; } - $ip = getipaddr($ip,GetNumber=>1); - $subnet = getipaddr($subnet,GetNumber=>1); + $ip = getipaddr($ip, GetNumber => 1); + $subnet = getipaddr($subnet, GetNumber => 1); $ip &= $mask; if ($ip && $subnet && ($ip == $subnet)) { return 1; @@ -464,21 +469,21 @@ sub ishostinsubnet { #----------------------------------------------------------------------------- sub setup_ip_forwarding { - my ($class, $enable)=@_; + my ($class, $enable) = @_; if (xCAT::Utils->isLinux()) { - my $conf_file="/etc/sysctl.conf"; - `grep "net.ipv4.ip_forward" $conf_file`; + my $conf_file = "/etc/sysctl.conf"; + `grep "net.ipv4.ip_forward" $conf_file`; if ($? == 0) { - `sed -i "s/^net.ipv4.ip_forward = .*/net.ipv4.ip_forward = $enable/" $conf_file`; - `sed -i "s/^#net.ipv4.ip_forward *= *.*/net.ipv4.ip_forward = $enable/" $conf_file`; #debian/ubuntu have different default format - } else { - `echo "net.ipv4.ip_forward = $enable" >> $conf_file`; - } - `sysctl -e -p $conf_file`; # workaround for redhat bug 639821 +`sed -i "s/^net.ipv4.ip_forward = .*/net.ipv4.ip_forward = $enable/" $conf_file`; +`sed -i "s/^#net.ipv4.ip_forward *= *.*/net.ipv4.ip_forward = $enable/" $conf_file`; #debian/ubuntu have different default format + } else { + `echo "net.ipv4.ip_forward = $enable" >> $conf_file`; + } + `sysctl -e -p $conf_file`; # workaround for redhat bug 639821 } else - { - `no -o ipforwarding=$enable`; + { + `no -o ipforwarding=$enable`; } return 0; } @@ -494,19 +499,19 @@ sub setup_ip_forwarding #----------------------------------------------------------------------------- sub setup_ipv6_forwarding { - my ($class, $enable)=@_; + my ($class, $enable) = @_; if (xCAT::Utils->isLinux()) { - my $conf_file="/etc/sysctl.conf"; + my $conf_file = "/etc/sysctl.conf"; `grep "net.ipv6.conf.all.forwarding" $conf_file`; if ($? == 0) { - `sed -i "s/^net.ipv6.conf.all.forwarding = .*/net.ipv6.conf.all.forwarding = $enable/" $conf_file`; +`sed -i "s/^net.ipv6.conf.all.forwarding = .*/net.ipv6.conf.all.forwarding = $enable/" $conf_file`; } else { `echo "net.ipv6.conf.all.forwarding = $enable" >> $conf_file`; } `sysctl -e -p $conf_file`; } else - { + { `no -o ip6forwarding=$enable`; } return 0; @@ -540,8 +545,8 @@ sub prefixtomask { { return 0; } - - my $number=Math::BigInt->new("0b".("1"x$prefixlength).("0"x(128-$prefixlength))); + + my $number = Math::BigInt->new("0b" . ("1" x $prefixlength) . ("0" x (128 - $prefixlength))); my $mask = $number->as_hex(); $mask =~ s/^0x//; $mask =~ s/(....)/$1/g; @@ -576,7 +581,7 @@ sub my_ip_in_subnet if (!$net || !$mask) { return undef; - } + } my $fmask = xCAT::NetworkUtils::formatNetmask($mask, 0, 1); @@ -621,6 +626,7 @@ sub ip_forwarding_enabled } return $enabled; } + #------------------------------------------------------------------------------- =head3 get_nic_ip @@ -644,10 +650,10 @@ sub get_nic_ip { my $nic; my %iphash; - my $mode = "MULTICAST"; - my $payingattention=0; - my $interface; - my $keepcurrentiface; + my $mode = "MULTICAST"; + my $payingattention = 0; + my $interface; + my $keepcurrentiface; if (xCAT::Utils->isAIX()) { @@ -660,66 +666,67 @@ sub get_nic_ip # en1: ... # ############################################################## - my $cmd = "ifconfig -a"; - my $result = `$cmd`; + my $cmd = "ifconfig -a"; + my $result = `$cmd`; ############################################# # Error running command ############################################# - if ( !$result ) { - return undef; + if (!$result) { + return undef; } my @adapter = split /(\w+\d+):\s+flags=/, $result; - foreach ( @adapter ) { + foreach (@adapter) { if ($_ =~ /^(en\d)/) { - $nic = $1; - next; + $nic = $1; + next; } - if ( !($_ =~ /LOOPBACK/ ) and - $_ =~ /UP(,|>)/ and - $_ =~ /$mode/ ) { + if (!($_ =~ /LOOPBACK/) and + $_ =~ /UP(,|>)/ and + $_ =~ /$mode/) { my @ip = split /\n/; - for my $ent ( @ip ) { - if ( $ent =~ /^\s*inet\s+(\d+\.\d+\.\d+\.\d+)/ ) { - $iphash{$nic} = $1; + for my $ent (@ip) { + if ($ent =~ /^\s*inet\s+(\d+\.\d+\.\d+\.\d+)/) { + $iphash{$nic} = $1; next; } } } } } - else { # linux + else { # linux my @ipoutput = `ip addr`; ############################################# # Error running command ############################################# - if ( !@ipoutput ) { - return undef; + if (!@ipoutput) { + return undef; } foreach my $line (@ipoutput) { - if ($line =~ /^\d/) { # new interface, new context.. + if ($line =~ /^\d/) { # new interface, new context.. if ($interface and not $keepcurrentiface) { + #don't bother reporting unusable nics delete $iphash{$interface}; } - $keepcurrentiface=0; - if ( !($line =~ /LOOPBACK/ ) and - $line =~ /UP( |,|>)/ and - $line =~ /$mode/ ) { - - $payingattention=1; + $keepcurrentiface = 0; + if (!($line =~ /LOOPBACK/) and + $line =~ /UP( |,|>)/ and + $line =~ /$mode/) { + + $payingattention = 1; $line =~ /^([^:]*): ([^:]*):/; - $interface=$2; - } else { - $payingattention=0; + $interface = $2; + } else { + $payingattention = 0; next; - } + } } - unless ($payingattention) { next; } + unless ($payingattention) { next; } if ($line =~ /inet/) { - $keepcurrentiface=1; + $keepcurrentiface = 1; } - if ( $line =~ /^\s*inet \s*(\d+\.\d+\.\d+\.\d+)/ ) { - $iphash{$interface} = $1; + if ($line =~ /^\s*inet \s*(\d+\.\d+\.\d+\.\d+)/) { + $iphash{$interface} = $1; } } } @@ -833,7 +840,7 @@ sub my_hexnets while ($nown <= $highn) { my $nowhex = sprintf("%08x", $nown); - $rethash->{substr($nowhex, 0, $numchars)} = $curnet; + $rethash->{ substr($nowhex, 0, $numchars) } = $curnet; $nown += 1 << (32 - $maskbits - $bitstoeven); } } @@ -871,7 +878,7 @@ sub get_host_from_ip { my $ip = shift; } - + #------------------------------------------------------------------------------- =head3 isPingable @@ -900,32 +907,33 @@ For an example #----------------------------------------------------------------------- my %PING_CACHE; + sub isPingable { my $ip = shift; my $rc; - if ( exists $PING_CACHE{ $ip}) + if (exists $PING_CACHE{$ip}) { - $rc = $PING_CACHE{ $ip}; + $rc = $PING_CACHE{$ip}; } else { my $res = `LANG=C ping -c 1 -w 5 $ip 2>&1`; - if ( $res =~ /100% packet loss/g) - { + if ($res =~ /100% packet loss/g) + { $rc = 1; } else { $rc = 0; } - $PING_CACHE{ $ip} = $rc; + $PING_CACHE{$ip} = $rc; } - return ! $rc; + return !$rc; } - + #------------------------------------------------------------------------------- =head3 my_nets @@ -953,6 +961,7 @@ For an example Comments: none =cut + #----------------------------------------------------------------------- sub my_nets { @@ -961,7 +970,7 @@ sub my_nets my @nets; my $v6net; my $v6ip; - if ( $^O eq 'aix') + if ($^O eq 'aix') { @nets = split /\n/, `/usr/sbin/ifconfig -a`; } @@ -978,19 +987,19 @@ sub my_nets next; } my $curnet; my $maskbits; - if ( $^O eq 'aix') + if ($^O eq 'aix') { if ($elems[1] eq 'inet6') { - $v6net=$elems[2]; - $v6ip=$elems[2]; - $v6ip =~ s/\/.*//; # ipv6 address 4000::99/64 - $v6ip =~ s/\%.*//; # ipv6 address ::1%1/128 + $v6net = $elems[2]; + $v6ip = $elems[2]; + $v6ip =~ s/\/.*//; # ipv6 address 4000::99/64 + $v6ip =~ s/\%.*//; # ipv6 address ::1%1/128 } else { $curnet = $elems[2]; - $maskbits = formatNetmask( $elems[4], 2, 1); + $maskbits = formatNetmask($elems[4], 2, 1); } } else @@ -1003,46 +1012,49 @@ sub my_nets } if (!$v6net) { - my $curmask = 2**$maskbits - 1 << (32 - $maskbits); - my $nown = unpack("N", inet_aton($curnet)); + my $curmask = 2**$maskbits - 1 << (32 - $maskbits); + my $nown = unpack("N", inet_aton($curnet)); $nown = $nown & $curmask; - my $textnet=inet_ntoa(pack("N",$nown)); - $textnet.="/$maskbits"; + my $textnet = inet_ntoa(pack("N", $nown)); + $textnet .= "/$maskbits"; $rethash->{$textnet} = $curnet; - } - else - { - $rethash->{$v6net} = $v6ip; - } + } + else + { + $rethash->{$v6net} = $v6ip; + } } - # now get remote nets + # now get remote nets my $nettab = xCAT::Table->new("networks"); + #my $sitetab = xCAT::Table->new("site"); #my $master = $sitetab->getAttribs({key=>'master'},'value'); #$master = $master->{value}; - my @masters = xCAT::TableUtils->get_site_attribute("master"); - my $master = $masters[0]; - my @vnets = $nettab->getAllAttribs('net','mgtifname','mask'); + my @masters = xCAT::TableUtils->get_site_attribute("master"); + my $master = $masters[0]; + my @vnets = $nettab->getAllAttribs('net', 'mgtifname', 'mask'); - foreach(@vnets){ - my $n = $_->{net}; - my $if = $_->{mgtifname}; - my $nm = $_->{mask}; - if (!$n || !$if || !$nm) - { - next; #incomplete network - } - if ($if =~ /!remote!/) { #only take in networks with special interface - $nm = formatNetmask($nm, 0 , 1); - $n .="/$nm"; - #$rethash->{$n} = $if; - $rethash->{$n} = $master; - } + foreach (@vnets) { + my $n = $_->{net}; + my $if = $_->{mgtifname}; + my $nm = $_->{mask}; + if (!$n || !$if || !$nm) + { + next; #incomplete network + } + if ($if =~ /!remote!/) { #only take in networks with special interface + $nm = formatNetmask($nm, 0, 1); + $n .= "/$nm"; + + #$rethash->{$n} = $if; + $rethash->{$n} = $master; + } } return $rethash; } + #------------------------------------------------------------------------------- =head3 my_if_netmap @@ -1074,11 +1086,11 @@ sub my_if_netmap my %retmap; foreach (@rtable) { - if (/^\D/) { next; } #skip headers + if (/^\D/) { next; } #skip headers if (/^\S+\s+\S+\s+\S+\s+\S*G/) { next; - } #Skip networks that require gateways to get to + } #Skip networks that require gateways to get to /^(\S+)\s.*\s(\S+)$/; $retmap{$1} = $2; } @@ -1118,11 +1130,11 @@ sub my_ip_facing { $peer = shift; } - - return my_ip_facing_aix( $peer) if ( $^O eq 'aix'); + + return my_ip_facing_aix($peer) if ($^O eq 'aix'); my @rst; - my $peernumber = inet_aton($peer); #TODO: IPv6 support - unless ($peernumber) { + my $peernumber = inet_aton($peer); #TODO: IPv6 support + unless ($peernumber) { $rst[0] = 1; $rst[1] = "The $peer can not be resolved"; return @rst; } @@ -1137,7 +1149,7 @@ sub my_ip_facing { next; } - (my $curnet, my $maskbits) = split /\//, $elems[2]; + (my $curnet, my $maskbits) = split /\//, $elems[2]; my $curmask = 2**$maskbits - 1 << (32 - $maskbits); my $curn = unpack("N", inet_aton($curnet)); if (($noden & $curmask) == ($curn & $curmask)) @@ -1183,14 +1195,14 @@ sub my_ip_facing_aix my @rst; foreach my $net (@nets) { - my ($curnet,$netmask); - if ( $net =~ /^\s*inet\s+([\d\.]+)\s+netmask\s+(\w+)\s+broadcast/) + my ($curnet, $netmask); + if ($net =~ /^\s*inet\s+([\d\.]+)\s+netmask\s+(\w+)\s+broadcast/) { - ($curnet,$netmask) = ($1,$2); + ($curnet, $netmask) = ($1, $2); } elsif ($net =~ /^\s*inet6\s+(.*)$/) { - ($curnet,$netmask) = split('/', $1); + ($curnet, $netmask) = split('/', $1); } else { @@ -1206,7 +1218,7 @@ sub my_ip_facing_aix $rst[0] = 0; push @rst, @ips; } - else + else { $rst[0] = 2; $rst[1] = "The IP address of node $peer is in an undefined subnet"; @@ -1243,22 +1255,23 @@ sub my_ip_facing_aix Comments: none =cut + #----------------------------------------------------------------------- sub formatNetmask { - my $mask = shift; + my $mask = shift; my $origType = shift; - my $newType = shift; + my $newType = shift; my $maskn; - if ( $origType == 0) + if ($origType == 0) { $maskn = unpack("N", inet_aton($mask)); } - elsif ( $origType == 1) + elsif ($origType == 1) { $maskn = 2**$mask - 1 << (32 - $mask); } - elsif( $origType == 2) + elsif ($origType == 2) { $maskn = hex $mask; } @@ -1267,17 +1280,17 @@ sub formatNetmask return undef; } - if ( $newType == 0) + if ($newType == 0) { - return inet_ntoa( pack('N', $maskn)); + return inet_ntoa(pack('N', $maskn)); } - if ( $newType == 1) + if ($newType == 1) { - my $bin = unpack ("B32", pack("N", $maskn)); - my @dup = ( $bin =~ /(1{1})0*/g); - return scalar ( @dup); + my $bin = unpack("B32", pack("N", $maskn)); + my @dup = ($bin =~ /(1{1})0*/g); + return scalar(@dup); } - if ( $newType == 2) + if ($newType == 2) { return sprintf "0x%1x", $maskn; } @@ -1315,12 +1328,13 @@ sub formatNetmask Comments: none =cut + #----------------------------------------------------------------------- sub isInSameSubnet { - my $ip1 = shift; - my $ip2 = shift; - my $mask = shift; + my $ip1 = shift; + my $ip2 = shift; + my $mask = shift; my $maskType = shift; $ip1 = xCAT::NetworkUtils->getipaddr($ip1); @@ -1332,7 +1346,7 @@ sub isInSameSubnet } if ((($ip1 =~ /\d+\.\d+\.\d+\.\d+/) && ($ip2 !~ /\d+\.\d+\.\d+\.\d+/)) - ||(($ip1 !~ /\d+\.\d+\.\d+\.\d+/) && ($ip2 =~ /\d+\.\d+\.\d+\.\d+/))) + || (($ip1 !~ /\d+\.\d+\.\d+\.\d+/) && ($ip2 =~ /\d+\.\d+\.\d+\.\d+/))) { #ipv4 and ipv6 can not be in the same subnet return undef; @@ -1341,15 +1355,15 @@ sub isInSameSubnet if (($ip1 =~ /\d+\.\d+\.\d+\.\d+/) && ($ip2 =~ /\d+\.\d+\.\d+\.\d+/)) { my $maskn; - if ( $maskType == 0) + if ($maskType == 0) { $maskn = unpack("N", inet_aton($mask)); } - elsif ( $maskType == 1) + elsif ($maskType == 1) { $maskn = 2**$mask - 1 << (32 - $mask); } - elsif( $maskType == 2) + elsif ($maskType == 2) { $maskn = hex $mask; } @@ -1361,7 +1375,7 @@ sub isInSameSubnet my $ip1n = unpack("N", inet_aton($ip1)); my $ip2n = unpack("N", inet_aton($ip2)); - return ( ( $ip1n & $maskn) == ( $ip2n & $maskn) ); + return (($ip1n & $maskn) == ($ip2n & $maskn)); } else { @@ -1370,20 +1384,21 @@ sub isInSameSubnet { return undef; } - my $netipmodule = eval {require Net::IP;}; + my $netipmodule = eval { require Net::IP; }; if ($netipmodule) { - my $eip1 = Net::IP::ip_expand_address ($ip1,6); - my $eip2 = Net::IP::ip_expand_address ($ip2,6); - my $bmask = Net::IP::ip_get_mask($mask,6); - my $bip1 = Net::IP::ip_iptobin($eip1,6); - my $bip2 = Net::IP::ip_iptobin($eip2,6); - if (($bip1 & $bmask) == ($bip2 & $bmask)) { - return 1; - } - } # else, can not check without Net::IP module - return undef; - } + my $eip1 = Net::IP::ip_expand_address($ip1, 6); + my $eip2 = Net::IP::ip_expand_address($ip2, 6); + my $bmask = Net::IP::ip_get_mask($mask, 6); + my $bip1 = Net::IP::ip_iptobin($eip1, 6); + my $bip2 = Net::IP::ip_iptobin($eip2, 6); + if (($bip1 & $bmask) == ($bip2 & $bmask)) { + return 1; + } + } # else, can not check without Net::IP module + return undef; + } } + #------------------------------------------------------------------------------- =head3 nodeonmynet - checks to see if node is on any network this server is attached to or remote network potentially managed by this system @@ -1411,7 +1426,7 @@ sub nodeonmynet $nodetocheck = shift; } - my $nodeip = getNodeIPaddress( $nodetocheck ); + my $nodeip = getNodeIPaddress($nodetocheck); if (!$nodeip) { return 0; @@ -1419,7 +1434,7 @@ sub nodeonmynet unless ($nodeip =~ /\d+\.\d+\.\d+\.\d+/) { #IPv6 - if ( $^O eq 'aix') + if ($^O eq 'aix') { my @subnets = get_subnet_aix(); for my $net_ent (@subnets) @@ -1429,7 +1444,7 @@ sub nodeonmynet #ipv4 next; } - my ($net, $interface, $mask, $flag) = split/-/ , $net_ent; + my ($net, $interface, $mask, $flag) = split /-/, $net_ent; if (xCAT::NetworkUtils->ishostinsubnet($nodeip, $mask, $net)) { return 1; @@ -1437,23 +1452,24 @@ sub nodeonmynet } } else { - my @v6routes = split /\n/,`ip -6 route`; + my @v6routes = split /\n/, `ip -6 route`; foreach (@v6routes) { if (/via/ or /^unreachable/ or /^fe80::\/64/) { - #only count local ones, remote ones can be caught in next loop - #also, link-local would be a pitfall, + + #only count local ones, remote ones can be caught in next loop + #also, link-local would be a pitfall, #since more context than address is - #needed to determine locality + #needed to determine locality next; } - s/ .*//; #remove all after the space - if (xCAT::NetworkUtils->ishostinsubnet($nodeip,'',$_)) { #bank on CIDR support + s/ .*//; #remove all after the space + if (xCAT::NetworkUtils->ishostinsubnet($nodeip, '', $_)) { #bank on CIDR support return 1; } } } - my $nettab=xCAT::Table->new("networks"); - my @vnets = $nettab->getAllAttribs('net','mgtifname','mask'); + my $nettab = xCAT::Table->new("networks"); + my @vnets = $nettab->getAllAttribs('net', 'mgtifname', 'mask'); foreach (@vnets) { if ((defined $_->{mgtifname}) && ($_->{mgtifname} eq '!remote!')) { @@ -1468,19 +1484,19 @@ sub nodeonmynet my $noden = unpack("N", inet_aton($nodeip)); my @nets; if ($utildata->{nodeonmynetdata} and $utildata->{nodeonmynetdata}->{pid} == $$) { - @nets = @{$utildata->{nodeonmynetdata}->{nets}}; + @nets = @{ $utildata->{nodeonmynetdata}->{nets} }; } else { - if ( $^O eq 'aix') + if ($^O eq 'aix') { my @subnets = get_subnet_aix(); for my $net_ent (@subnets) { - if ($net_ent =~ /-/) + if ($net_ent =~ /-/) { #ipv6 next; } - my @ents = split /:/ , $net_ent; + my @ents = split /:/, $net_ent; push @nets, $ents[0] . '/' . $ents[2] . ' dev ' . $ents[1]; } @@ -1489,21 +1505,21 @@ sub nodeonmynet { @nets = split /\n/, `/sbin/ip route`; } - my $nettab=xCAT::Table->new("networks"); - my @vnets = $nettab->getAllAttribs('net','mgtifname','mask'); + my $nettab = xCAT::Table->new("networks"); + my @vnets = $nettab->getAllAttribs('net', 'mgtifname', 'mask'); foreach (@vnets) { if ((defined $_->{mgtifname}) && ($_->{mgtifname} eq '!remote!')) - { #global scoped network + { #global scoped network my $curm = unpack("N", inet_aton($_->{mask})); - my $bits=32; - until ($curm & 1) { + my $bits = 32; + until ($curm & 1) { $bits--; - $curm=$curm>>1; + $curm = $curm >> 1; } - push @nets,$_->{'net'}."/".$bits." dev remote"; + push @nets, $_->{'net'} . "/" . $bits . " dev remote"; } } - $utildata->{nodeonmynetdata}->{pid}=$$; + $utildata->{nodeonmynetdata}->{pid} = $$; $utildata->{nodeonmynetdata}->{nets} = \@nets; } foreach (@nets) @@ -1540,7 +1556,7 @@ sub nodeonmynet #------------------------------------------------------------------------------- -sub getNodeIPaddress +sub getNodeIPaddress { require xCAT::Table; my $nodetocheck = shift; @@ -1550,22 +1566,22 @@ sub getNodeIPaddress $nodeip = xCAT::NetworkUtils->getipaddr($nodetocheck); if (!$nodeip) { - my $hoststab = xCAT::Table->new( 'hosts'); - my $ent = $hoststab->getNodeAttribs( $nodetocheck, ['ip'] ); - if ( $ent->{'ip'} ) { + my $hoststab = xCAT::Table->new('hosts'); + my $ent = $hoststab->getNodeAttribs($nodetocheck, ['ip']); + if ($ent->{'ip'}) { $nodeip = $ent->{'ip'}; } } - - if ( $nodeip ) { + + if ($nodeip) { return $nodeip; } else { return undef; } } - - - + + + #------------------------------------------------------------------------------- =head3 thishostisnot @@ -1594,7 +1610,7 @@ sub thishostisnot } my @ips; - if ( $^O eq 'aix') + if ($^O eq 'aix') { @ips = split /\n/, `/usr/sbin/ifconfig -a`; } @@ -1656,7 +1672,7 @@ sub thishostisnot # { # if ($addr =~ /inet6/) # { -# #TODO, Linux ipv6 +# #TODO, Linux ipv6 # } # else # { @@ -1710,48 +1726,48 @@ sub gethost_ips my @ipaddress; if (xCAT::Utils->isLinux()) { - $cmd="ip -4 --oneline addr show |awk -F ' ' '{print \$4}'|awk -F '/' '{print \$1}'"; - my @result =xCAT::Utils->runcmd($cmd); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("S", "Error from $cmd\n"); - exit $::RUNCMD_RC; - } - - push @ipaddress, @result; + $cmd = "ip -4 --oneline addr show |awk -F ' ' '{print \$4}'|awk -F '/' '{print \$1}'"; + my @result = xCAT::Utils->runcmd($cmd); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("S", "Error from $cmd\n"); + exit $::RUNCMD_RC; + } + + push @ipaddress, @result; } else { #AIX - - $cmd = "ifconfig" . " -a"; - $cmd = $cmd . "| grep \"inet\""; - my @result = xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { - xCAT::MsgUtils->message("S", "Error from $cmd\n"); - exit $::RUNCMD_RC; - } - - foreach my $addr (@result) - { - if ($addr =~ /inet6/) - { - $addr =~ /\s*inet6\s+([\da-fA-F:]+).*\/(\d+)/; - my $v6ip = $1; - my $v6mask = $2; - if ($v6ip) - { - push @ipaddress, $v6ip; - } - } - else - { - my ($inet, $addr1, $netmask, $mask1, $Bcast, $bcastaddr) = - split(" ", $addr); - push @ipaddress, $addr1; - } - } + $cmd = "ifconfig" . " -a"; + $cmd = $cmd . "| grep \"inet\""; + my @result = xCAT::Utils->runcmd($cmd, 0); + if ($::RUNCMD_RC != 0) + { + xCAT::MsgUtils->message("S", "Error from $cmd\n"); + exit $::RUNCMD_RC; + } + + foreach my $addr (@result) + { + if ($addr =~ /inet6/) + { + $addr =~ /\s*inet6\s+([\da-fA-F:]+).*\/(\d+)/; + my $v6ip = $1; + my $v6mask = $2; + if ($v6ip) + { + push @ipaddress, $v6ip; + } + } + else + { + my ($inet, $addr1, $netmask, $mask1, $Bcast, $bcastaddr) = + split(" ", $addr); + push @ipaddress, $addr1; + } + + } } my @names = @ipaddress; @@ -1794,18 +1810,18 @@ sub get_subnet_aix my @netstat_res = `/usr/bin/netstat -rn`; chomp @netstat_res; my @aix_nrn; - for my $entry ( @netstat_res) + for my $entry (@netstat_res) { -#We need to find entries like: -#Destination Gateway Flags Refs Use If Exp Groups -#9.114.47.192/27 9.114.47.205 U 1 1 en0 -#4000::/64 link#4 UCX 1 0 en2 - - - my ( $net, $netmask, $flag, $nic); - if ( $entry =~ /^\s*([\d\.]+)\/(\d+)\s+[\d\.]+\s+(\w+)\s+\d+\s+\d+\s(\w+)/) + #We need to find entries like: + #Destination Gateway Flags Refs Use If Exp Groups + #9.114.47.192/27 9.114.47.205 U 1 1 en0 + #4000::/64 link#4 UCX 1 0 en2 - - + my ($net, $netmask, $flag, $nic); + if ($entry =~ /^\s*([\d\.]+)\/(\d+)\s+[\d\.]+\s+(\w+)\s+\d+\s+\d+\s(\w+)/) { - ( $net, $netmask, $flag, $nic) = ($1,$2,$3,$4); + ($net, $netmask, $flag, $nic) = ($1, $2, $3, $4); my @dotsec = split /\./, $net; - for ( my $i = 4; $i > scalar(@dotsec); $i--) + for (my $i = 4 ; $i > scalar(@dotsec) ; $i--) { $net .= '.0'; } @@ -1814,7 +1830,8 @@ sub get_subnet_aix elsif ($entry =~ /^\s*([\dA-Fa-f\:]+)\/(\d+)\s+.*?\s+(\w+)\s+\d+\s+\d+\s(\w+)/) { #print "=====$entry====\n"; - ( $net, $netmask, $flag, $nic) = ($1,$2,$3,$4); + ($net, $netmask, $flag, $nic) = ($1, $2, $3, $4); + # for ipv6, can not use : as the delimiter push @aix_nrn, "$net-$nic-$netmask-$flag" if ($net ne '::') } @@ -1841,7 +1858,7 @@ sub determinehostname if ($::RUNCMD_RC != 0) { # could not get hostname xCAT::MsgUtils->message("S", - "Error $::RUNCMD_RC from $hostnamecmd command\n"); + "Error $::RUNCMD_RC from $hostnamecmd command\n"); exit $::RUNCMD_RC; } $hostname = $thostname[0]; @@ -1851,24 +1868,25 @@ sub determinehostname my @hostnamecandidates; my $nodename; while ($hostname =~ /\./) { - push @hostnamecandidates,$hostname; + push @hostnamecandidates, $hostname; $hostname =~ s/\.[^\.]*//; } - push @hostnamecandidates,$hostname; - my $checkhostnames = join(',',@hostnamecandidates); + push @hostnamecandidates, $hostname; + my $checkhostnames = join(',', @hostnamecandidates); my @validnodenames = xCAT::NodeRange::noderange($checkhostnames); unless (scalar @validnodenames) { #If the node in question is not in table, take output literrally. - push @validnodenames,$hostnamecandidates[0]; + push @validnodenames, $hostnamecandidates[0]; } + #now, noderange doesn't guarantee the order, so we search the preference order, most to least specific. foreach my $host (@hostnamecandidates) { - if (grep /^$host$/,@validnodenames) { + if (grep /^$host$/, @validnodenames) { $nodename = $host; last; } } - my @ips = xCAT::NetworkUtils->gethost_ips; - my @hostinfo = (@ips, $nodename); + my @ips = xCAT::NetworkUtils->gethost_ips; + my @hostinfo = (@ips, $nodename); return @hostinfo; } @@ -1887,14 +1905,14 @@ sub toIP if (($_[0] =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/) || ($_[0] =~ /:/)) { - return ([0, $_[0]]); + return ([ 0, $_[0] ]); } my $ip = xCAT::NetworkUtils->getipaddr($_[0]); if (!$ip) { - return ([1, "Cannot Resolve: $_[0]\n"]); + return ([ 1, "Cannot Resolve: $_[0]\n" ]); } - return ([0, $ip]); + return ([ 0, $ip ]); } #------------------------------------------------------------------------------- @@ -1922,26 +1940,28 @@ sub validate_ip my ($class, @IPs) = @_; foreach (@IPs) { my $ip = $_; + #TODO need more check for IPv6 address if ($ip =~ /:/) { - return([0]); + return ([0]); } ################################### # Length is 4 for IPv4 addresses ################################### my (@octets) = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/; - if ( scalar(@octets) != 4 ) { - return( [1,"Invalid IP address1: $ip"] ); + if (scalar(@octets) != 4) { + return ([ 1, "Invalid IP address1: $ip" ]); } - foreach my $octet ( @octets ) { - if (( $octet < 0 ) or ( $octet > 255 )) { - return( [1,"Invalid IP address2: $ip"] ); + foreach my $octet (@octets) { + if (($octet < 0) or ($octet > 255)) { + return ([ 1, "Invalid IP address2: $ip" ]); } } } - return([0]); + return ([0]); } + #------------------------------------------------------------------------------- =head3 isIpaddr @@ -1974,10 +1994,11 @@ sub isIpaddr $addr = shift; } - unless ( $addr ) + unless ($addr) { return 0; } + #print "addr=$addr\n"; if ($addr !~ /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/) { @@ -1998,6 +2019,7 @@ sub isIpaddr #------------------------------------------------------------------------------- + =head3 getNodeNameservers Description: Get nameservers of specified nodes. @@ -2017,36 +2039,37 @@ sub isIpaddr none =cut + #------------------------------------------------------------------------------- -sub getNodeNameservers{ - my $nodes=shift; - if( $nodes =~ /xCAT::NetworkUtils/) +sub getNodeNameservers { + my $nodes = shift; + if ($nodes =~ /xCAT::NetworkUtils/) { - $nodes=shift; + $nodes = shift; } my @nodelist = @$nodes; my %nodenameservers; - my $nrtab = xCAT::Table->new('noderes',-create=>0); - my %nrhash = %{$nrtab->getNodesAttribs(\@nodelist,['nameservers'])}; - - my $nettab = xCAT::Table->new("networks"); - my %nethash = xCAT::DBobjUtils->getNetwkInfo( \@nodelist ); + my $nrtab = xCAT::Table->new('noderes', -create => 0); + my %nrhash = %{ $nrtab->getNodesAttribs(\@nodelist, ['nameservers']) }; - my @nameservers = xCAT::TableUtils->get_site_attribute("nameservers"); - my $sitenameservers=$nameservers[0]; + my $nettab = xCAT::Table->new("networks"); + my %nethash = xCAT::DBobjUtils->getNetwkInfo(\@nodelist); + + my @nameservers = xCAT::TableUtils->get_site_attribute("nameservers"); + my $sitenameservers = $nameservers[0]; - foreach my $node (@nodelist){ - if ($nrhash{$node} and $nrhash{$node}->[0] and $nrhash{$node}->[0]->{nameservers}) - { - $nodenameservers{$node}=$nrhash{$node}->[0]->{nameservers}; - }elsif($nethash{$node}{nameservers}) - { - $nodenameservers{$node}=$nethash{$node}{nameservers}; - }elsif($sitenameservers) - { - $nodenameservers{$node}=$sitenameservers; - } + foreach my $node (@nodelist) { + if ($nrhash{$node} and $nrhash{$node}->[0] and $nrhash{$node}->[0]->{nameservers}) + { + $nodenameservers{$node} = $nrhash{$node}->[0]->{nameservers}; + } elsif ($nethash{$node}{nameservers}) + { + $nodenameservers{$node} = $nethash{$node}{nameservers}; + } elsif ($sitenameservers) + { + $nodenameservers{$node} = $sitenameservers; + } } return \%nodenameservers; @@ -2079,28 +2102,29 @@ sub getNodeNameservers{ sub getNodeNetworkCfg { my $node = shift; - if( $node =~ /xCAT::NetworkUtils/) + if ($node =~ /xCAT::NetworkUtils/) { - $node =shift; + $node = shift; } - my $ip = xCAT::NetworkUtils->getipaddr($node); - my $mask = undef; + my $ip = xCAT::NetworkUtils->getipaddr($node); + my $mask = undef; my $gateway = undef; my $nettab = xCAT::Table->new("networks"); if ($nettab) { - my @nets = $nettab->getAllAttribs('net','mask','gateway'); - foreach my $net (@nets) { - if (xCAT::NetworkUtils::isInSameSubnet( $net->{'net'}, $ip, $net->{'mask'}, 0)) { - $gateway=$net->{'gateway'}; - $mask=$net->{'mask'}; - } - } + my @nets = $nettab->getAllAttribs('net', 'mask', 'gateway'); + foreach my $net (@nets) { + if (xCAT::NetworkUtils::isInSameSubnet($net->{'net'}, $ip, $net->{'mask'}, 0)) { + $gateway = $net->{'gateway'}; + $mask = $net->{'mask'}; + } + } } - - return ($ip, $node, $gateway, xCAT::NetworkUtils::formatNetmask($mask,0,0)); + + return ($ip, $node, $gateway, xCAT::NetworkUtils::formatNetmask($mask, 0, 0)); } + #------------------------------------------------------------------------------- =head3 getNodesNetworkCfg @@ -2122,17 +2146,17 @@ sub getNodeNetworkCfg #------------------------------------------------------------------------------- -sub getNodesNetworkCfg +sub getNodesNetworkCfg { my $nodes = shift; if ($nodes =~ /xCAT::NetworkUtils/) { $nodes = shift; } - my @nets = (); + my @nets = (); my $nettab = xCAT::Table->new("networks"); - if($nettab) { + if ($nettab) { my @error_net = (); - my @all_nets = $nettab->getAllAttribs('net','mask','gateway'); + my @all_nets = $nettab->getAllAttribs('net', 'mask', 'gateway'); foreach my $net (@all_nets) { my $gateway = $net->{gateway}; if (defined($gateway) and ($gateway eq '')) { @@ -2141,7 +2165,7 @@ sub getNodesNetworkCfg $gateway = $gatewayd[1]; } } - push @nets, {net=>$net->{net}, mask=>$net->{mask}, gateway=>$gateway}; + push @nets, { net => $net->{net}, mask => $net->{mask}, gateway => $gateway }; } $nettab->close; } @@ -2155,9 +2179,9 @@ sub getNodesNetworkCfg foreach my $node (@$nodes) { my $ip = xCAT::NetworkUtils->getipaddr($node); foreach my $net (@nets) { - if (xCAT::NetworkUtils::isInSameSubnet( $net->{'net'}, $ip, $net->{'mask'}, 0)) { - $rethash{$node}->{ip} = $ip; - $rethash{$node}->{mask} = $net->{'mask'}; + if (xCAT::NetworkUtils::isInSameSubnet($net->{'net'}, $ip, $net->{'mask'}, 0)) { + $rethash{$node}->{ip} = $ip; + $rethash{$node}->{mask} = $net->{'mask'}; $rethash{$node}->{gateway} = $net->{'gateway'}; last; } @@ -2193,20 +2217,20 @@ sub get_hdwr_ip { require xCAT::Table; my $node = shift; - my $ip = undef; + my $ip = undef; my $Rc = undef; - my $ip_tmp_res = xCAT::NetworkUtils::toIP($node); + my $ip_tmp_res = xCAT::NetworkUtils::toIP($node); ($Rc, $ip) = @$ip_tmp_res; - if ( $Rc ) { - my $hosttab = xCAT::Table->new( 'hosts' ); - if ( $hosttab) { - my $node_ip_hash = $hosttab->getNodeAttribs( $node,[qw(ip)]); + if ($Rc) { + my $hosttab = xCAT::Table->new('hosts'); + if ($hosttab) { + my $node_ip_hash = $hosttab->getNodeAttribs($node, [qw(ip)]); $ip = $node_ip_hash->{ip}; } - + } - + if (!$ip) { return undef; } @@ -2215,6 +2239,7 @@ sub get_hdwr_ip } #-------------------------------------------------------------------------------- + =head3 pingNodeStatus This function takes an array of nodes and returns their status using nmap or fping. Arguments: @@ -2223,85 +2248,89 @@ sub get_hdwr_ip a hash that has the node status. The format is: {alive=>[node1, node3,...], unreachable=>[node4, node2...]} =cut + #-------------------------------------------------------------------------------- sub pingNodeStatus { - my ($class, @mon_nodes)=@_; - my %status=(); - my @active_nodes=(); - my @inactive_nodes=(); + my ($class, @mon_nodes) = @_; + my %status = (); + my @active_nodes = (); + my @inactive_nodes = (); + #print "NetworkUtils->pingNodeStatus called, nodes=@mon_nodes\n"; - if ((@mon_nodes)&& (@mon_nodes > 0)) { - #get all the active nodes - my $nodes= join(' ', @mon_nodes); - if (-x '/usr/bin/nmap' or -x '/usr/local/bin/nmap') { #use nmap - #print "use nmap\n"; - my %deadnodes; - foreach (@mon_nodes) { - $deadnodes{$_}=1; - } + if ((@mon_nodes) && (@mon_nodes > 0)) { - # get additional options from site table - my @nmap_options = xCAT::TableUtils->get_site_attribute("nmapoptions"); - my $more_options = $nmap_options[0]; + #get all the active nodes + my $nodes = join(' ', @mon_nodes); + if (-x '/usr/bin/nmap' or -x '/usr/local/bin/nmap') { #use nmap + #print "use nmap\n"; + my %deadnodes; + foreach (@mon_nodes) { + $deadnodes{$_} = 1; + } - #call namp - open (NMAP, "nmap -PE --system-dns --send-ip -sP $more_options ". $nodes . " 2> /dev/null|") or die("Cannot open nmap pipe: $!"); - my $node; - while () { - if (/Host (.*) \(.*\) appears to be up/) { - $node=$1; - unless ($deadnodes{$node}) { - foreach (keys %deadnodes) { - if ($node =~ /^$_\./) { - $node = $_; - last; - } - } - } - delete $deadnodes{$node}; - push(@active_nodes, $node); - } elsif (/Nmap scan report for ([^ ]*) /) { - $node=$1; - } elsif (/Host is up./) { - unless ($deadnodes{$node}) { - foreach (keys %deadnodes) { - if ($node =~ /^$_\./) { - $node = $_; - last; - } - } - } - delete $deadnodes{$node}; - push(@active_nodes, $node); - } - } - foreach (sort keys %deadnodes) { - push(@inactive_nodes, $_); - } - } else { #use fping - #print "use fping\n"; + # get additional options from site table + my @nmap_options = xCAT::TableUtils->get_site_attribute("nmapoptions"); + my $more_options = $nmap_options[0]; - my $temp=`fping -a $nodes 2> /dev/null`; - chomp($temp); - @active_nodes=split(/\n/, $temp); - - #get all the inactive nodes by substracting the active nodes from all. - my %temp2; - if ((@active_nodes) && ( @active_nodes > 0)) { - foreach(@active_nodes) { $temp2{$_}=1}; - foreach(@mon_nodes) { - if (!$temp2{$_}) { push(@inactive_nodes, $_);} - } - } - else {@inactive_nodes=@mon_nodes;} - } + #call namp + open(NMAP, "nmap -PE --system-dns --send-ip -sP $more_options " . $nodes . " 2> /dev/null|") or die("Cannot open nmap pipe: $!"); + my $node; + while () { + if (/Host (.*) \(.*\) appears to be up/) { + $node = $1; + unless ($deadnodes{$node}) { + foreach (keys %deadnodes) { + if ($node =~ /^$_\./) { + $node = $_; + last; + } + } + } + delete $deadnodes{$node}; + push(@active_nodes, $node); + } elsif (/Nmap scan report for ([^ ]*) /) { + $node = $1; + } elsif (/Host is up./) { + unless ($deadnodes{$node}) { + foreach (keys %deadnodes) { + if ($node =~ /^$_\./) { + $node = $_; + last; + } + } + } + delete $deadnodes{$node}; + push(@active_nodes, $node); + } + } + foreach (sort keys %deadnodes) { + push(@inactive_nodes, $_); + } + } else { #use fping + #print "use fping\n"; + + my $temp = `fping -a $nodes 2> /dev/null`; + chomp($temp); + @active_nodes = split(/\n/, $temp); + + #get all the inactive nodes by substracting the active nodes from all. + my %temp2; + if ((@active_nodes) && (@active_nodes > 0)) { + foreach (@active_nodes) { $temp2{$_} = 1 } + foreach (@mon_nodes) { + if (!$temp2{$_}) { push(@inactive_nodes, $_); } + } + } + else { @inactive_nodes = @mon_nodes; } + } } - - $status{$::STATUS_ACTIVE}=\@active_nodes; - $status{$::STATUS_INACTIVE}=\@inactive_nodes; + + $status{$::STATUS_ACTIVE} = \@active_nodes; + $status{$::STATUS_INACTIVE} = \@inactive_nodes; + #use Data::Dumper; #print Dumper(%status); - + return %status; } @@ -2318,7 +2347,7 @@ sub pingNodeStatus { sub isValidMAC { my ($class, $macstr) = @_; - if ($macstr =~ /^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}$/){ + if ($macstr =~ /^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}$/) { return 1; } return 0; @@ -2337,9 +2366,9 @@ sub isValidMAC sub isValidHostname { my ($class, $hostname) = @_; - if ($hostname =~ /^[a-z0-9]/){ - if ($hostname =~ /[a-z0-9]$/){ - if ($hostname =~ /^[\-a-z0-9]+$/){ + if ($hostname =~ /^[a-z0-9]/) { + if ($hostname =~ /[a-z0-9]$/) { + if ($hostname =~ /^[\-a-z0-9]+$/) { return 1; } } @@ -2361,7 +2390,7 @@ sub isValidHostname sub isValidFQDN { my ($class, $hostname) = @_; - if ($hostname =~ /^[a-z0-9][\.\-a-z0-9]+[a-z0-9]$/){ + if ($hostname =~ /^[a-z0-9][\.\-a-z0-9]+[a-z0-9]$/) { return 1; } return 0; @@ -2417,10 +2446,10 @@ sub int_to_ip sub getBroadcast { my ($class, $ipstr, $netmask) = @_; - my $ipint = xCAT::NetworkUtils->ip_to_int($ipstr); + my $ipint = xCAT::NetworkUtils->ip_to_int($ipstr); my $maskint = xCAT::NetworkUtils->ip_to_int($netmask); - my $tmp = sprintf("%d", ~$maskint); - my $bcnum = sprintf("%d", ($ipint | $tmp) & hex('0x00000000FFFFFFFF')); + my $tmp = sprintf("%d", ~$maskint); + my $bcnum = sprintf("%d", ($ipint | $tmp) & hex('0x00000000FFFFFFFF')); return xCAT::NetworkUtils->int_to_ip($bcnum); } @@ -2441,27 +2470,27 @@ sub getBroadcast #------------------------------------------------------------------------------- sub get_allips_in_range { - my $class = shift; - my $startip = shift; - my $endip = shift; + my $class = shift; + my $startip = shift; + my $endip = shift; my $increment = shift; - my @iplist = (); + my @iplist = (); my $tmpip; my $startipnum = xCAT::NetworkUtils->ip_to_int($startip); - my $endipnum = xCAT::NetworkUtils->ip_to_int($endip); + my $endipnum = xCAT::NetworkUtils->ip_to_int($endip); - if ($increment > 0){ - while ($startipnum <= $endipnum){ + if ($increment > 0) { + while ($startipnum <= $endipnum) { $tmpip = xCAT::NetworkUtils->int_to_ip($startipnum); $startipnum += $increment; - push (@iplist, $tmpip); + push(@iplist, $tmpip); } - }elsif($increment < 0){ - while ($endipnum >= $startipnum){ + } elsif ($increment < 0) { + while ($endipnum >= $startipnum) { $tmpip = xCAT::NetworkUtils->int_to_ip($endipnum); $endipnum += $increment; - push (@iplist, $tmpip); + push(@iplist, $tmpip); } } return \@iplist; @@ -2477,37 +2506,39 @@ sub get_allips_in_range =cut #------------------------------------------------------------------------------- -sub get_all_nicips{ +sub get_all_nicips { my ($class, $hashref) = @_; my %allipshash; my @allipslist; - my $table = xCAT::Table->new('nics'); + my $table = xCAT::Table->new('nics'); my @entries = $table->getAllNodeAttribs(['nicips']); - foreach (@entries){ + foreach (@entries) { + # $_->{nicips} looks like "eth0:ip1,eth1:ip2,bmc:ip3..." - if($_->{nicips}){ + if ($_->{nicips}) { my @nicandiplist = split(',', $_->{nicips}); + # Each record in @nicandiplist looks like "eth0:ip1" - # delimiter has been changed to use "!" in xCAT 2.8 - foreach (@nicandiplist){ - my @nicandip; - if ($_ =~ /!/) { - @nicandip = split('!', $_); - } else { - @nicandip = split(':', $_); - } - if ($hashref){ - $allipshash{$nicandip[1]} = 0; - } else{ - push (@allipslist, $nicandip[1]); + # delimiter has been changed to use "!" in xCAT 2.8 + foreach (@nicandiplist) { + my @nicandip; + if ($_ =~ /!/) { + @nicandip = split('!', $_); + } else { + @nicandip = split(':', $_); + } + if ($hashref) { + $allipshash{ $nicandip[1] } = 0; + } else { + push(@allipslist, $nicandip[1]); } } } } - if ($hashref){ + if ($hashref) { return \%allipshash; - } else{ + } else { return \@allipslist; } } @@ -2561,21 +2592,21 @@ sub get_all_nicips{ #------------------------------------------------------------------------------- -sub gen_net_boot_params +sub gen_net_boot_params { - my $class = shift; + my $class = shift; my $installnic = shift; my $primarynic = shift; - my $macmac = shift; + my $macmac = shift; my $nodebootif = shift; my $net_params; - + # arbitrary use primarynic if installnic is not set unless ($installnic) { - $installnic = $primarynic; + $installnic = $primarynic; } - + # just use the installnic to generate the nic related kernel parameters my $mac; my $nicname; @@ -2585,32 +2616,32 @@ sub gen_net_boot_params $nicname = $nodebootif; } - if ((! defined ($installnic)) || ($installnic eq "") || ($installnic =~ /^mac$/i)) { + if ((!defined($installnic)) || ($installnic eq "") || ($installnic =~ /^mac$/i)) { $mac = $macmac; $net_params->{mac} = $mac; } elsif ($installnic =~ /^[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}:[0-9a-fA-F]{2}$/) { - $mac = $installnic; - $net_params->{mac} = $mac; + $mac = $installnic; + $net_params->{mac} = $mac; $net_params->{setmac} = $mac; } else { - $mac = $macmac; - $nicname = $installnic; + $mac = $macmac; + $nicname = $installnic; $net_params->{nicname} = $nicname; - $net_params->{mac} = $mac; + $net_params->{mac} = $mac; } # if nicname is set and mac.mac is NOT set to , use nicname in the boot parameters - if ($nicname && ! defined ($net_params->{setmac})) { - $net_params->{ksdevice} = "ksdevice=$nicname"; - $net_params->{ip} = "ip=$nicname:dhcp"; - $net_params->{netdev} = "netdev=$nicname"; + if ($nicname && !defined($net_params->{setmac})) { + $net_params->{ksdevice} = "ksdevice=$nicname"; + $net_params->{ip} = "ip=$nicname:dhcp"; + $net_params->{netdev} = "netdev=$nicname"; $net_params->{netdevice} = "netdevice=$nicname"; $net_params->{ifname} = "ifname=$nicname:$mac"; # todo: may not use mac arbitrary } elsif ($mac) { - $net_params->{ksdevice} = "ksdevice=$mac"; - $net_params->{BOOTIF} = "BOOTIF=$mac"; - $net_params->{bootdev} = "bootdev=$mac"; - $net_params->{ip} = "ip=dhcp"; + $net_params->{ksdevice} = "ksdevice=$mac"; + $net_params->{BOOTIF} = "BOOTIF=$mac"; + $net_params->{bootdev} = "bootdev=$mac"; + $net_params->{ip} = "ip=dhcp"; $net_params->{netdevice} = "netdevice=$mac"; } diff --git a/perl-xCAT/xCAT/NodeRange.pm b/perl-xCAT/xCAT/NodeRange.pm index 85f7bb9cf..e28bac035 100644 --- a/perl-xCAT/xCAT/NodeRange.pm +++ b/perl-xCAT/xCAT/NodeRange.pm @@ -6,20 +6,21 @@ require Exporter; use strict; #Perl implementation of noderange -our @ISA = qw(Exporter); -our @EXPORT = qw(noderange nodesmissed); +our @ISA = qw(Exporter); +our @EXPORT = qw(noderange nodesmissed); our @EXPORT_OK = qw(extnoderange abbreviate_noderange); -my $missingnodes=[]; -my $nodelist; #=xCAT::Table->new('nodelist',-create =>1); +my $missingnodes = []; +my $nodelist; #=xCAT::Table->new('nodelist',-create =>1); my $grptab; + #TODO: MEMLEAK note # I've moved grptab up here to avoid calling 'new' on it on every noderange # Something is wrong in the Table object such that it leaks # a few kilobytes of memory, even if nodelist member is not created # To reproduce the mem leak, move 'my $grptab' to the place where it is used # then call 'getAllNodesAttribs' a few thousand times on some table -# No one noticed before 2.3 because the lifetime of processes doing noderange +# No one noticed before 2.3 because the lifetime of processes doing noderange # expansion was short (seconds) # In 2.3, the problem has been 'solved' for most contexts in that the DB worker # reuses Table objects rather than ever destroying them @@ -28,7 +29,7 @@ my $grptab; # in this case, we change NodeRange to reuse the same Table object # even if not relying upon DB worker to figure it out for noderange # This may be a good idea anyway, regardless of memory leak -# It remains a good way to induce the memleak to correctly fix it +# It remains a good way to induce the memleak to correctly fix it # rather than hiding from the problem #my $nodeprefix = "node"; @@ -36,16 +37,17 @@ my @allnodeset; my %allnodehash; my @grplist; my $didgrouplist; -my $glstamp=0; -my $allnodesetstamp=0; -my $allgrphashstamp=0; +my $glstamp = 0; +my $allnodesetstamp = 0; +my $allgrphashstamp = 0; my %allgrphash; -my $retaincache=0; -my $recurselevel=0; +my $retaincache = 0; +my $recurselevel = 0; my @cachedcolumns; + #TODO: With a very large nodelist (i.e. 65k or so), deriving the members -# of a group is a little sluggish. We may want to put in a mechanism to +# of a group is a little sluggish. We may want to put in a mechanism to # maintain a two-way hash anytime nodelist or nodegroup changes, allowing # nodegroup table and nodelist to contain the same information about # group membership indexed in different ways to speed this up. @@ -54,131 +56,138 @@ my @cachedcolumns; # but many other operations would probably benefit greatly. sub subnodes (\@@) { + #Subtract set of nodes from the first list my $nodes = shift; my $node; foreach $node (@_) { - @$nodes = (grep(!/^$node$/,@$nodes)); + @$nodes = (grep(!/^$node$/, @$nodes)); } } + sub nodesmissed { - return @$missingnodes; + return @$missingnodes; } sub reset_db { -#workaround, something seems to be trying to use a corrupted reference to grptab -#this allows init_dbworker to reset the object - $grptab=0; -} -sub nodesbycriteria { - #TODO: this should be in a common place, shared by tabutils nodech/nodels and noderange - #there is a set of functions already, but the path is a little complicated and - #might be hooked into the objective usage style, which this function is not trying to match - #Return nodes by criteria. Can accept a list reference of criteria - #returns a hash reference of criteria expressions to nodes that meet - my $nodes = shift; #the set from which to match - my $critlist = shift; #list of criteria to match - my %tables; - my %shortnames = ( - groups => [qw(nodelist groups)], - tags => [qw(nodelist groups)], - mgt => [qw(nodehm mgt)], - #switch => [qw(switch switch)], - ); - unless (ref $critlist) { - $critlist = [ $critlist ]; - } - my $criteria; - my %critnodes; - my $value; - my $tabcol; - my $matchtype; - foreach $criteria (@$critlist) { - my $table; - my $column; - $tabcol=$criteria; - if ($criteria =~ /^[^=]*\!=/) { - ($criteria,$value) = split /!=/,$criteria,2; - $matchtype='natch'; - } elsif ($criteria =~ /^[^=]*=~/) { - ($criteria,$value) = split /=~/,$criteria,2; - $value =~ s/^\///; - $value =~ s/\/$//; - $matchtype='regex'; - } elsif ($criteria =~ /[^=]*==/) { - ($criteria,$value) = split /==/,$criteria,2; - $matchtype='match'; - } elsif ($criteria =~ /[^=]*=/) { - ($criteria,$value) = split /=/,$criteria,2; - $matchtype='match'; - } elsif ($criteria =~ /[^=]*!~/) { - ($criteria,$value) = split /!~/,$criteria,2; - $value =~ s/^\///; - $value =~ s/\/$//; - $matchtype='negex'; - } - if ($shortnames{$criteria}) { - ($table, $column) = @{$shortnames{$criteria}}; - } elsif ($criteria =~ /\./) { - ($table, $column) = split('\.', $criteria, 2); - } else { - return undef; - } - unless (grep /$column/,@{$xCAT::Schema::tabspec{$table}->{cols}}) { - return undef; - } - push @{$tables{$table}},[$column,$tabcol,$value,$matchtype]; #Mark this as something to get - } - my $tab; - foreach $tab (keys %tables) { - my $tabh = xCAT::Table->new($tab,-create=>0); - unless ($tabh) { next; } - my @cols; - foreach (@{$tables{$tab}}) { - push @cols, $_->[0]; + #workaround, something seems to be trying to use a corrupted reference to grptab + #this allows init_dbworker to reset the object + $grptab = 0; +} + +sub nodesbycriteria { + + #TODO: this should be in a common place, shared by tabutils nodech/nodels and noderange + #there is a set of functions already, but the path is a little complicated and + #might be hooked into the objective usage style, which this function is not trying to match + #Return nodes by criteria. Can accept a list reference of criteria + #returns a hash reference of criteria expressions to nodes that meet + my $nodes = shift; #the set from which to match + my $critlist = shift; #list of criteria to match + my %tables; + my %shortnames = ( + groups => [qw(nodelist groups)], + tags => [qw(nodelist groups)], + mgt => [qw(nodehm mgt)], + + #switch => [qw(switch switch)], + ); + + unless (ref $critlist) { + $critlist = [$critlist]; + } + my $criteria; + my %critnodes; + my $value; + my $tabcol; + my $matchtype; + foreach $criteria (@$critlist) { + my $table; + my $column; + $tabcol = $criteria; + if ($criteria =~ /^[^=]*\!=/) { + ($criteria, $value) = split /!=/, $criteria, 2; + $matchtype = 'natch'; + } elsif ($criteria =~ /^[^=]*=~/) { + ($criteria, $value) = split /=~/, $criteria, 2; + $value =~ s/^\///; + $value =~ s/\/$//; + $matchtype = 'regex'; + } elsif ($criteria =~ /[^=]*==/) { + ($criteria, $value) = split /==/, $criteria, 2; + $matchtype = 'match'; + } elsif ($criteria =~ /[^=]*=/) { + ($criteria, $value) = split /=/, $criteria, 2; + $matchtype = 'match'; + } elsif ($criteria =~ /[^=]*!~/) { + ($criteria, $value) = split /!~/, $criteria, 2; + $value =~ s/^\///; + $value =~ s/\/$//; + $matchtype = 'negex'; } - if ($tab eq "nodelist") { #fun caching interaction - my $neednewcache=0; - my $nlcol; - foreach $nlcol (@cols) { - unless (grep /^$nlcol\z/,@cachedcolumns) { - $neednewcache=1; - push @cachedcolumns,$nlcol; - } - } - if ($neednewcache) { - if ($nodelist) { - #$nodelist->_clear_cache(); - $nodelist->_build_cache(\@cachedcolumns); - } - } - } - my $rechash = $tabh->getNodesAttribs($nodes,\@cols); #TODO: if not defined nodes, getAllNodesAttribs may be faster actually... + if ($shortnames{$criteria}) { + ($table, $column) = @{ $shortnames{$criteria} }; + } elsif ($criteria =~ /\./) { + ($table, $column) = split('\.', $criteria, 2); + } else { + return undef; + } + unless (grep /$column/, @{ $xCAT::Schema::tabspec{$table}->{cols} }) { + return undef; + } + push @{ $tables{$table} }, [ $column, $tabcol, $value, $matchtype ]; #Mark this as something to get + } + my $tab; + foreach $tab (keys %tables) { + my $tabh = xCAT::Table->new($tab, -create => 0); + unless ($tabh) { next; } + my @cols; + foreach (@{ $tables{$tab} }) { + push @cols, $_->[0]; + } + if ($tab eq "nodelist") { #fun caching interaction + my $neednewcache = 0; + my $nlcol; + foreach $nlcol (@cols) { + unless (grep /^$nlcol\z/, @cachedcolumns) { + $neednewcache = 1; + push @cachedcolumns, $nlcol; + } + } + if ($neednewcache) { + if ($nodelist) { + + #$nodelist->_clear_cache(); + $nodelist->_build_cache(\@cachedcolumns); + } + } + } + my $rechash = $tabh->getNodesAttribs($nodes, \@cols); #TODO: if not defined nodes, getAllNodesAttribs may be faster actually... foreach my $node (@$nodes) { my $recs = $rechash->{$node}; my $critline; - foreach $critline (@{$tables{$tab}}) { + foreach $critline (@{ $tables{$tab} }) { foreach my $rec (@$recs) { - my $value=""; - if (defined $rec->{$critline->[0]}) { - $value = $rec->{$critline->[0]}; + my $value = ""; + if (defined $rec->{ $critline->[0] }) { + $value = $rec->{ $critline->[0] }; } my $compstring = $critline->[2]; if ($critline->[3] eq 'match' and $value eq $compstring) { - push @{$critnodes{$critline->[1]}},$node; + push @{ $critnodes{ $critline->[1] } }, $node; } elsif ($critline->[3] eq 'natch' and $value ne $compstring) { - push @{$critnodes{$critline->[1]}},$node; + push @{ $critnodes{ $critline->[1] } }, $node; } elsif ($critline->[3] eq 'regex' and $value =~ /$compstring/) { - push @{$critnodes{$critline->[1]}},$node; + push @{ $critnodes{ $critline->[1] } }, $node; } elsif ($critline->[3] eq 'negex' and $value !~ /$compstring/) { - push @{$critnodes{$critline->[1]}},$node; + push @{ $critnodes{ $critline->[1] } }, $node; } } } } - } - return \%critnodes; + } + return \%critnodes; } # Expand one part of the noderange from the noderange() function. Initially, one part means the @@ -189,53 +198,55 @@ sub nodesbycriteria { # - verify: whether or not to require that the resulting nodenames exist in the nodelist table # - options: genericrange - a purely syntactical expansion of the range, not using the db at all, e.g not expanding group names sub expandatom { - my $atom = shift; - if ($recurselevel > 4096) { die "NodeRange seems to be hung on evaluating $atom, recursion limit hit"; } - unless (scalar(@allnodeset) and (($allnodesetstamp+5) > time())) { #Build a cache of all nodes, some corner cases will perform worse, but by and large it will do better. We could do tests to see where the breaking points are, and predict how many atoms we have to evaluate to mitigate, for now, implement the strategy that keeps performance from going completely off the rails - $allnodesetstamp=time(); - $nodelist->_set_use_cache(1); - @allnodeset = $nodelist->getAllAttribs('node','groups'); + my $atom = shift; + if ($recurselevel > 4096) { die "NodeRange seems to be hung on evaluating $atom, recursion limit hit"; } + unless (scalar(@allnodeset) and (($allnodesetstamp + 5) > time())) { #Build a cache of all nodes, some corner cases will perform worse, but by and large it will do better. We could do tests to see where the breaking points are, and predict how many atoms we have to evaluate to mitigate, for now, implement the strategy that keeps performance from going completely off the rails + $allnodesetstamp = time(); + $nodelist->_set_use_cache(1); + @allnodeset = $nodelist->getAllAttribs('node', 'groups'); %allnodehash = map { $_->{node} => 1 } @allnodeset; - $nodelist->_set_use_cache(0); #The {_use_cache} for nodelist table object must be turn off, otherwise it will keep open and affect the Table.pm subroutines like getNodesAttribs when it tries to access nodelist table to get status column. + $nodelist->_set_use_cache(0); #The {_use_cache} for nodelist table object must be turn off, otherwise it will keep open and affect the Table.pm subroutines like getNodesAttribs when it tries to access nodelist table to get status column. } - my $verify = (scalar(@_) >= 1 ? shift : 1); - my %options = @_; # additional options - $options{keepmissing} = 1; - my @nodes= (); - #TODO: these env vars need to get passed by the client to xcatd - my $nprefix=(defined ($ENV{'XCAT_NODE_PREFIX'}) ? $ENV{'XCAT_NODE_PREFIX'} : 'node'); - my $nsuffix=(defined ($ENV{'XCAT_NODE_SUFFIX'}) ? $ENV{'XCAT_NODE_SUFFIX'} : ''); + my $verify = (scalar(@_) >= 1 ? shift : 1); + my %options = @_; # additional options + $options{keepmissing} = 1; + my @nodes = (); - if (not $options{genericrange} and $allnodehash{$atom}) { #The atom is a plain old nodename - return ($atom); - } - if ($atom =~ /^\(.*\)$/) { # handle parentheses by recursively calling noderange() - $atom =~ s/^\((.*)\)$/$1/; - $recurselevel++; - return noderange($atom,$verify,1,%options); + #TODO: these env vars need to get passed by the client to xcatd + my $nprefix = (defined($ENV{'XCAT_NODE_PREFIX'}) ? $ENV{'XCAT_NODE_PREFIX'} : 'node'); + my $nsuffix = (defined($ENV{'XCAT_NODE_SUFFIX'}) ? $ENV{'XCAT_NODE_SUFFIX'} : ''); + + if (not $options{genericrange} and $allnodehash{$atom}) { #The atom is a plain old nodename + return ($atom); + } + if ($atom =~ /^\(.*\)$/) { # handle parentheses by recursively calling noderange() + $atom =~ s/^\((.*)\)$/$1/; + $recurselevel++; + return noderange($atom, $verify, 1, %options); } if ($atom =~ /@/) { - $recurselevel++; - return noderange($atom,$verify,1,%options); - } + $recurselevel++; + return noderange($atom, $verify, 1, %options); + } # Try to match groups? unless ($options{genericrange}) { unless ($grptab) { - $grptab = xCAT::Table->new('nodegroup'); + $grptab = xCAT::Table->new('nodegroup'); } - if ($grptab and (($glstamp < (time()-5)) or (not $didgrouplist and not scalar @grplist))) { + if ($grptab and (($glstamp < (time() - 5)) or (not $didgrouplist and not scalar @grplist))) { $didgrouplist = 1; - $glstamp=time(); + $glstamp = time(); my $grplist_ptr = $grptab->getAllEntries(); if (!$grplist_ptr) { - return undef; + return undef; } @grplist = @{$grplist_ptr}; } my $isdynamicgrp = 0; foreach my $grpdef_ref (@grplist) { my %grpdef = %$grpdef_ref; + # Try to match a dynamic node group # do not try to match the static node group from nodegroup table, # the static node groups are stored in nodelist table. @@ -244,7 +255,7 @@ sub expandatom { $isdynamicgrp = 1; my $grpname = $atom; my %grphash; - $grphash{$grpname}{'objtype'} = 'group'; + $grphash{$grpname}{'objtype'} = 'group'; $grphash{$grpname}{'grouptype'} = 'dynamic'; $grphash{$grpname}{'wherevals'} = $grpdef{'wherevals'}; my $memberlist = xCAT::DBobjUtils->getGroupMembers($grpname, \%grphash); @@ -253,48 +264,49 @@ sub expandatom { push @nodes, $grpmember; } last; #there should not be more than one group with the same name - } - } - # The atom is not a dynamic node group, is it a static node group??? - if(!$isdynamicgrp) - { - unless (scalar %allgrphash and (time() < ($allgrphashstamp+5))) { #build a group membership cache - $allgrphashstamp=time(); - %allgrphash=(); + } + } + + # The atom is not a dynamic node group, is it a static node group??? + if (!$isdynamicgrp) + { + unless (scalar %allgrphash and (time() < ($allgrphashstamp + 5))) { #build a group membership cache + $allgrphashstamp = time(); + %allgrphash = (); my $nlent; - foreach $nlent (@allnodeset) { - my @groups=split(/,/,$nlent->{groups}); + foreach $nlent (@allnodeset) { + my @groups = split(/,/, $nlent->{groups}); my $grp; foreach $grp (@groups) { - push @{$allgrphash{$grp}},$nlent->{node}; + push @{ $allgrphash{$grp} }, $nlent->{node}; } } } - if ($allgrphash{$atom}) { - push @nodes,@{$allgrphash{$atom}}; - } - } - - # check to see if atom is a defined group name that didn't have any current members - if ( scalar @nodes == 0 ) { - if(scalar @grplist) { #Use previously constructed cache to avoid hitting DB worker so much - #my @grouplist = $grptab->getAllAttribs('groupname'); - for my $row ( @grplist ) { - if ( $row->{groupname} eq $atom ) { - return (); - } + if ($allgrphash{$atom}) { + push @nodes, @{ $allgrphash{$atom} }; + } } - } - } -} + + # check to see if atom is a defined group name that didn't have any current members + if (scalar @nodes == 0) { + if (scalar @grplist) { #Use previously constructed cache to avoid hitting DB worker so much + #my @grouplist = $grptab->getAllAttribs('groupname'); + for my $row (@grplist) { + if ($row->{groupname} eq $atom) { + return (); + } + } + } + } + } # node selection based on db attribute values (nodetype.os==rhels5.3) if ($atom =~ m/[=~]/) { #TODO: this is the clunky, slow code path to acheive the goal. It also is the easiest to write, strange coincidence. Aggregating multiples would be nice my @nodes; foreach (@allnodeset) { - push @nodes,$_->{node}; + push @nodes, $_->{node}; } - my $nbyc_ref = nodesbycriteria(\@nodes,[$atom]); + my $nbyc_ref = nodesbycriteria(\@nodes, [$atom]); if ($nbyc_ref) { my $nbyc = $nbyc_ref->{$atom}; @@ -304,214 +316,220 @@ sub expandatom { } return (); } - if ($atom =~ m/^[0-9]+\z/) { # if only numbers, then add the prefix - my $nodename=$nprefix.$atom.$nsuffix; - return expandatom($nodename,$verify,%options); - } - my $nodelen=@nodes; - if ($nodelen > 0) { - return @nodes; - } + if ($atom =~ m/^[0-9]+\z/) { # if only numbers, then add the prefix + my $nodename = $nprefix . $atom . $nsuffix; + return expandatom($nodename, $verify, %options); + } + my $nodelen = @nodes; + if ($nodelen > 0) { + return @nodes; + } - if ($atom =~ m/^\//) { # A regular expression - if ($verify==0 or $options{genericrange}) { # If not in verify mode, regex makes zero possible sense - return ($atom); - } - #TODO: check against all groups - $atom = substr($atom,1); - foreach (@allnodeset) { #$nodelist->getAllAttribs('node')) { - if ($_->{node} =~ m/^${atom}$/) { - push(@nodes,$_->{node}); - } - } - return(@nodes); - } - - if ($atom =~ m/(.+?)\[(.+?)\](.*)/) { # square bracket range - # if there is more than 1 set of [], we picked off just the 1st. If there more sets of [], we will expand - # the 1st set and create a new set of atom by concatenating each result in the 1st expandsion with the rest - # of the brackets. Then call expandatom() recursively on each new atom. - my @subelems = split(/([\,\-\:])/,$2); # $2 is the range inside the 1st set of brackets - my $subrange=""; - my $subelem; - my $start = $1; # the text before the 1st set of brackets - my $ending = $3; # the text after the 1st set of brackets (could contain more brackets) - my $morebrackets = $ending =~ /\[.+?\]/; # if there are more brackets, we have to expand just the 1st part, then add the 2nd part later - while (scalar @subelems) { # this while loop turns something like a[1-3] into a1-a3 because another section of expand atom knows how to expand that - my $subelem = shift @subelems; - my $subop=shift @subelems; - $subrange=$subrange."$start$subelem" . ($morebrackets?'':$ending) . "$subop"; - } - foreach (split /,/,$subrange) { # this foreach is in case there were commas inside the brackets originally, e.g.: a[1,3,5]b[1-2] - # this expandatom just expands the part of the noderange that contains the 1st set of brackets - # e.g. if noderange is a[1-2]b[1-2] it will create newnodes of a1 and a2 - my @newnodes=expandatom($_, ($morebrackets?0:$verify), genericrange=>($morebrackets||$options{genericrange})); - if (!$morebrackets) { push @nodes,@newnodes; } - else { - # for each of the new nodes (prefixes), add the rest of the brackets and then expand recursively - foreach my $n (@newnodes) { - push @nodes, expandatom("$n$ending", $verify, %options); - } - } - } - return @nodes; - } - - if ($atom =~ m/\+/) { # process the + operator - $atom =~ m/^(.*)([0-9]+)([^0-9\+]*)\+([0-9]+)/; - my ($front, $increment) = split(/\+/, $atom, 2); - my ($pref, $startnum, $dom) = $front =~ /^(.*?)(\d+)(\..+)?$/; - my $suf=$3; - my $end=$startnum+$increment; - my $endnum = sprintf("%d",$end); - if (length ($startnum) > length ($endnum)) { - $endnum = sprintf("%0".length($startnum)."d",$end); - } - if (($pref eq "") && ($suf eq "")) { - $pref=$nprefix; - $suf=$nsuffix; - } - foreach ("$startnum".."$endnum") { - my @addnodes=expandatom($pref.$_.$suf,$verify,%options); - @nodes=(@nodes,@addnodes); - } - return (@nodes); - } - - if ($atom =~ m/[-:]/) { # process the minus range operator - my $left; - my $right; - if ($atom =~ m/:/) { - ($left,$right)=split /:/,$atom; - } else { - my $count= ($atom =~ tr/-//); - if (($count % 2)==0) { #can't understand even numbers of - in range context - if ($verify) { - push @$missingnodes,$atom; - return (); - } else { #but we might not really be in range context, if noverify - return ($atom); - } - } - my $expr="([^-]+?".("-[^-]*"x($count/2)).")-(.*)"; - $atom =~ m/$expr/; - $left=$1; - $right=$2; - } - if ($left eq $right) { #if they said node1-node1 for some strange reason - return expandatom($left,$verify,%options); - } - my @leftarr=split(/(\d+)/,$left); - my @rightarr=split(/(\d+)/,$right); - if (scalar(@leftarr) != scalar(@rightarr)) { #Mismatch formatting.. - if ($verify) { - push @$missingnodes,$atom; - return (); #mismatched range, bail. - } else { #Not in verify mode, just have to guess it's meant to be a nodename - return ($atom); - } - } - my $prefix = ""; - my $suffix = ""; - foreach (0..$#leftarr) { - my $idx = $_; - if ($leftarr[$idx] =~ /^\d+$/ and $rightarr[$idx] =~ /^\d+$/) { #pure numeric component - if ($leftarr[$idx] ne $rightarr[$idx]) { #We have found the iterator (only supporting one for now) - my $prefix = join('',@leftarr[0..($idx-1)]); #Make a prefix of the pre-validated parts - my $luffix; #However, the remainder must still be validated to be the same - my $ruffix; - if ($idx eq $#leftarr) { - $luffix=""; - $ruffix=""; - } else { - $ruffix = join('',@rightarr[($idx+1)..$#rightarr]); - $luffix = join('',@leftarr[($idx+1)..$#leftarr]); - } - if ($luffix ne $ruffix) { #the suffixes mismatched.. - if ($verify) { - push @$missingnodes,$atom; - return (); - } else { - return ($atom); - } - } - foreach ($leftarr[$idx]..$rightarr[$idx]) { - my @addnodes=expandatom($prefix.$_.$luffix,$verify,%options); - push @nodes,@addnodes; - } - return (@nodes); #the return has been built, return, exiting loop and all - } - } elsif ($leftarr[$idx] ne $rightarr[$idx]) { - if ($verify) { - push @$missingnodes,$atom; - return (); - } else { + if ($atom =~ m/^\//) { # A regular expression + if ($verify == 0 or $options{genericrange}) { # If not in verify mode, regex makes zero possible sense return ($atom); - } } - $prefix .= $leftarr[$idx]; #If here, it means that the pieces were the same, but more to come - } - #I cannot conceive how the code could possibly be here, but whatever it is, it must be questionable - if ($verify) { - push @$missingnodes,$atom; - return (); #mismatched range, bail. - } else { #Not in verify mode, just have to guess it's meant to be a nodename - return ($atom); - } - } - if ($verify) { - push @$missingnodes,$atom; - return (); - } else { - return ($atom); - } -} + #TODO: check against all groups + $atom = substr($atom, 1); + foreach (@allnodeset) { #$nodelist->getAllAttribs('node')) { + if ($_->{node} =~ m/^${atom}$/) { + push(@nodes, $_->{node}); + } + } + return (@nodes); + } -sub retain_cache { #A semi private operation to be used *ONLY* in the interesting Table<->NodeRange module interactions. - $retaincache=shift; - unless ($retaincache) { #take a call to retain_cache(0) to also mean that any existing - #cache must be zapped - if ($nodelist) { $nodelist->_build_cache(1); } - $glstamp=0; - $allnodesetstamp=0; - $allgrphashstamp=0; - undef $nodelist; - @allnodeset=(); - %allnodehash=(); - @grplist=(); - $didgrouplist = 0; - %allgrphash=(); - } -} -sub extnoderange { #An extended noderange function. Needed by the GUI as the more straightforward function return format too simple for this. - my $range = shift; - my $namedopts = shift; - my $verify=1; - if ($namedopts->{skipnodeverify}) { - $verify=0; - } - my $return; - $retaincache=1; - $return->{node}=[noderange($range,$verify)]; - if ($namedopts->{intersectinggroups}) { - my %grouphash=(); - my $nlent; - foreach (@{$return->{node}}) { - $nlent=$nodelist->getNodeAttribs($_,['groups']); #TODO: move to noderange side cache - if ($nlent and $nlent->{groups}) { - foreach (split /,/,$nlent->{groups}) { - $grouphash{$_}=1; + if ($atom =~ m/(.+?)\[(.+?)\](.*)/) { # square bracket range + # if there is more than 1 set of [], we picked off just the 1st. If there more sets of [], we will expand + # the 1st set and create a new set of atom by concatenating each result in the 1st expandsion with the rest + # of the brackets. Then call expandatom() recursively on each new atom. + my @subelems = split(/([\,\-\:])/, $2); # $2 is the range inside the 1st set of brackets + my $subrange = ""; + my $subelem; + my $start = $1; # the text before the 1st set of brackets + my $ending = $3; # the text after the 1st set of brackets (could contain more brackets) + my $morebrackets = $ending =~ /\[.+?\]/; # if there are more brackets, we have to expand just the 1st part, then add the 2nd part later + + while (scalar @subelems) { # this while loop turns something like a[1-3] into a1-a3 because another section of expand atom knows how to expand that + my $subelem = shift @subelems; + my $subop = shift @subelems; + $subrange = $subrange . "$start$subelem" . ($morebrackets ? '' : $ending) . "$subop"; + } + foreach (split /,/, $subrange) { # this foreach is in case there were commas inside the brackets originally, e.g.: a[1,3,5]b[1-2] + # this expandatom just expands the part of the noderange that contains the 1st set of brackets + # e.g. if noderange is a[1-2]b[1-2] it will create newnodes of a1 and a2 + my @newnodes = expandatom($_, ($morebrackets ? 0 : $verify), genericrange => ($morebrackets || $options{genericrange})); + if (!$morebrackets) { push @nodes, @newnodes; } + else { + # for each of the new nodes (prefixes), add the rest of the brackets and then expand recursively + foreach my $n (@newnodes) { + push @nodes, expandatom("$n$ending", $verify, %options); } } } - $return->{intersectinggroups}=[sort keys %grouphash]; + return @nodes; + } + + if ($atom =~ m/\+/) { # process the + operator + $atom =~ m/^(.*)([0-9]+)([^0-9\+]*)\+([0-9]+)/; + my ($front, $increment) = split(/\+/, $atom, 2); + my ($pref, $startnum, $dom) = $front =~ /^(.*?)(\d+)(\..+)?$/; + my $suf = $3; + my $end = $startnum + $increment; + my $endnum = sprintf("%d", $end); + if (length($startnum) > length($endnum)) { + $endnum = sprintf("%0" . length($startnum) . "d", $end); + } + if (($pref eq "") && ($suf eq "")) { + $pref = $nprefix; + $suf = $nsuffix; + } + foreach ("$startnum" .. "$endnum") { + my @addnodes = expandatom($pref . $_ . $suf, $verify, %options); + @nodes = (@nodes, @addnodes); + } + return (@nodes); + } + + if ($atom =~ m/[-:]/) { # process the minus range operator + my $left; + my $right; + if ($atom =~ m/:/) { + ($left, $right) = split /:/, $atom; + } else { + my $count = ($atom =~ tr/-//); + if (($count % 2) == 0) { #can't understand even numbers of - in range context + if ($verify) { + push @$missingnodes, $atom; + return (); + } else { #but we might not really be in range context, if noverify + return ($atom); + } + } + my $expr = "([^-]+?" . ("-[^-]*" x ($count / 2)) . ")-(.*)"; + $atom =~ m/$expr/; + $left = $1; + $right = $2; + } + if ($left eq $right) { #if they said node1-node1 for some strange reason + return expandatom($left, $verify, %options); + } + my @leftarr = split(/(\d+)/, $left); + my @rightarr = split(/(\d+)/, $right); + if (scalar(@leftarr) != scalar(@rightarr)) { #Mismatch formatting.. + if ($verify) { + push @$missingnodes, $atom; + return (); #mismatched range, bail. + } else { #Not in verify mode, just have to guess it's meant to be a nodename + return ($atom); + } + } + my $prefix = ""; + my $suffix = ""; + foreach (0 .. $#leftarr) { + my $idx = $_; + if ($leftarr[$idx] =~ /^\d+$/ and $rightarr[$idx] =~ /^\d+$/) { #pure numeric component + if ($leftarr[$idx] ne $rightarr[$idx]) { #We have found the iterator (only supporting one for now) + my $prefix = join('', @leftarr[ 0 .. ($idx - 1) ]); #Make a prefix of the pre-validated parts + my $luffix; #However, the remainder must still be validated to be the same + my $ruffix; + if ($idx eq $#leftarr) { + $luffix = ""; + $ruffix = ""; + } else { + $ruffix = join('', @rightarr[ ($idx + 1) .. $#rightarr ]); + $luffix = join('', @leftarr[ ($idx + 1) .. $#leftarr ]); + } + if ($luffix ne $ruffix) { #the suffixes mismatched.. + if ($verify) { + push @$missingnodes, $atom; + return (); + } else { + return ($atom); + } + } + foreach ($leftarr[$idx] .. $rightarr[$idx]) { + my @addnodes = expandatom($prefix . $_ . $luffix, $verify, %options); + push @nodes, @addnodes; + } + return (@nodes); #the return has been built, return, exiting loop and all + } + } elsif ($leftarr[$idx] ne $rightarr[$idx]) { + if ($verify) { + push @$missingnodes, $atom; + return (); + } else { + return ($atom); + } + } + $prefix .= $leftarr[$idx]; #If here, it means that the pieces were the same, but more to come + } + + #I cannot conceive how the code could possibly be here, but whatever it is, it must be questionable + if ($verify) { + push @$missingnodes, $atom; + return (); #mismatched range, bail. + } else { #Not in verify mode, just have to guess it's meant to be a nodename + return ($atom); + } + } + + if ($verify) { + push @$missingnodes, $atom; + return (); + } else { + return ($atom); + } +} + +sub retain_cache { #A semi private operation to be used *ONLY* in the interesting Table<->NodeRange module interactions. + $retaincache = shift; + unless ($retaincache) { #take a call to retain_cache(0) to also mean that any existing + #cache must be zapped + if ($nodelist) { $nodelist->_build_cache(1); } + $glstamp = 0; + $allnodesetstamp = 0; + $allgrphashstamp = 0; + undef $nodelist; + @allnodeset = (); + %allnodehash = (); + @grplist = (); + $didgrouplist = 0; + %allgrphash = (); + } +} + +sub extnoderange { #An extended noderange function. Needed by the GUI as the more straightforward function return format too simple for this. + my $range = shift; + my $namedopts = shift; + my $verify = 1; + if ($namedopts->{skipnodeverify}) { + $verify = 0; + } + my $return; + $retaincache = 1; + $return->{node} = [ noderange($range, $verify) ]; + if ($namedopts->{intersectinggroups}) { + my %grouphash = (); + my $nlent; + foreach (@{ $return->{node} }) { + $nlent = $nodelist->getNodeAttribs($_, ['groups']); #TODO: move to noderange side cache + if ($nlent and $nlent->{groups}) { + foreach (split /,/, $nlent->{groups}) { + $grouphash{$_} = 1; + } + } + } + $return->{intersectinggroups} = [ sort keys %grouphash ]; } return $return; } -sub abbreviate_noderange { + +sub abbreviate_noderange { + #takes a list of nodes or a string and reduces it by replacing a list of nodes that make up a group with the group name itself - my $nodes=shift; + my $nodes = shift; my %grouphash; my %sizedgroups; my %nodesleft; @@ -520,62 +538,66 @@ sub abbreviate_noderange { $nodes = noderange($nodes); } %nodesleft = map { $_ => 1 } @{$nodes}; - unless ($nodelist) { - $nodelist =xCAT::Table->new('nodelist',-create =>1); + unless ($nodelist) { + $nodelist = xCAT::Table->new('nodelist', -create => 1); } my $group; - foreach($nodelist->getAllAttribs('node','groups')) { - my @groups=split(/,/,$_->{groups}); #The where clause doesn't guarantee the atom is a full group name, only that it could be + foreach ($nodelist->getAllAttribs('node', 'groups')) { + my @groups = split(/,/, $_->{groups}); #The where clause doesn't guarantee the atom is a full group name, only that it could be foreach $group (@groups) { - push @{$grouphash{$group}},$_->{node}; + push @{ $grouphash{$group} }, $_->{node}; } } foreach $group (keys %grouphash) { + #skip single node sized groups, these outliers frequently pasted into non-noderange capable contexts - if (scalar @{$grouphash{$group}} < 2) { next; } - push @{$sizedgroups{scalar @{$grouphash{$group}}}},$group; + if (scalar @{ $grouphash{$group} } < 2) { next; } + push @{ $sizedgroups{ scalar @{ $grouphash{$group} } } }, $group; } my $node; + #use Data::Dumper; #print Dumper(\%sizedgroups); - foreach (reverse sort {$a <=> $b} keys %sizedgroups) { - GROUP: foreach $group (@{$sizedgroups{$_}}) { - foreach $node (@{$grouphash{$group}}) { - unless (grep $node eq $_,keys %nodesleft) { + foreach (reverse sort { $a <=> $b } keys %sizedgroups) { + GROUP: foreach $group (@{ $sizedgroups{$_} }) { + foreach $node (@{ $grouphash{$group} }) { + unless (grep $node eq $_, keys %nodesleft) { + #this group contains a node that isn't left, skip it - next GROUP; - } + next GROUP; } - foreach $node (@{$grouphash{$group}}){ - delete $nodesleft{$node}; - } - $targetelems{$group}=1; + } + foreach $node (@{ $grouphash{$group} }) { + delete $nodesleft{$node}; + } + $targetelems{$group} = 1; } } - return (join ',',keys %targetelems,keys %nodesleft); + return (join ',', keys %targetelems, keys %nodesleft); } sub set_arith { my $operand = shift; - my $op = shift; - my $newset = shift; - if ($op =~ /@/) { # compute the intersection of the current atom and the node list we have received before this - foreach (keys %$operand) { - unless ($newset->{$_}) { - delete $operand->{$_}; + my $op = shift; + my $newset = shift; + if ($op =~ /@/) { # compute the intersection of the current atom and the node list we have received before this + foreach (keys %$operand) { + unless ($newset->{$_}) { + delete $operand->{$_}; + } } - } - } elsif ($op =~ /,-/) { # add the nodes from this atom to the exclude list - foreach (keys %$newset) { + } elsif ($op =~ /,-/) { # add the nodes from this atom to the exclude list + foreach (keys %$newset) { delete $operand->{$_} - } - } else { # add the nodes from this atom to the total node list - foreach (keys %$newset) { - $operand->{$_}=1; - } - } + } + } else { # add the nodes from this atom to the total node list + foreach (keys %$newset) { + $operand->{$_} = 1; + } + } } + # Expand the given noderange # Input args: # - noderange to expand @@ -583,102 +605,103 @@ sub set_arith { # - exsitenode: whether or not to honor site.excludenodes to automatically exclude those nodes from all noderanges # - options: genericrange - a purely syntactical expansion of the range, not using the db at all, e.g not expanding group names sub noderange { - #We for now just do left to right operations - my $range=shift; - $range =~ s/['"]//g; - my $verify = (scalar(@_) >= 1 ? shift : 1); - my $exsitenode = (scalar(@_) >= 1 ? shift : 1); # if 1, honor site.excludenodes - my %options = @_; # additional options - unless ($options{keepmissing}) { - $missingnodes=[]; - } - unless ($nodelist) { - $nodelist =xCAT::Table->new('nodelist',-create =>1); - $nodelist->_set_use_cache(0); #TODO: a more proper external solution - @cachedcolumns = ('node','groups'); - $nodelist->_build_cache(\@cachedcolumns,noincrementref=>1); - $nodelist->_set_use_cache(1); #TODO: a more proper external solution - } - my %nodes = (); - my %delnodes = (); - if ($range =~ /\(/) { - my ($middle, $end, $start) = - extract_bracketed($range, '()', qr/[^()]*/); - unless ($middle) { die "Unbalanced parentheses in noderange" } - $middle = substr($middle,1,-1); + #We for now just do left to right operations + my $range = shift; + $range =~ s/['"]//g; + my $verify = (scalar(@_) >= 1 ? shift : 1); + my $exsitenode = (scalar(@_) >= 1 ? shift : 1); # if 1, honor site.excludenodes + my %options = @_; # additional options + unless ($options{keepmissing}) { + $missingnodes = []; + } + + unless ($nodelist) { + $nodelist = xCAT::Table->new('nodelist', -create => 1); + $nodelist->_set_use_cache(0); #TODO: a more proper external solution + @cachedcolumns = ('node', 'groups'); + $nodelist->_build_cache(\@cachedcolumns, noincrementref => 1); + $nodelist->_set_use_cache(1); #TODO: a more proper external solution + } + my %nodes = (); + my %delnodes = (); + if ($range =~ /\(/) { + my ($middle, $end, $start) = + extract_bracketed($range, '()', qr/[^()]*/); + unless ($middle) { die "Unbalanced parentheses in noderange" } + $middle = substr($middle, 1, -1); + my $op = ","; + if ($start =~ m/-$/) { #subtract the parenthetical + $op .= "-" + } elsif ($start =~ m/\@$/) { + $op = "@" + } + $start =~ s/,-$//; + $start =~ s/,$//; + $start =~ s/\@$//; + %nodes = map { $_ => 1 } noderange($start, $verify, $exsitenode, %options, keepmissing => 1); + my %innernodes = map { $_ => 1 } noderange($middle, $verify, $exsitenode, %options, keepmissing => 1); + set_arith(\%nodes, $op, \%innernodes); + $range = $end; + } + my $op = ","; - if ($start =~ m/-$/) { #subtract the parenthetical - $op .= "-" - } elsif ($start =~ m/\@$/) { - $op = "@" + my @elems = split(/(,(?![^[]*?])(?![^\(]*?\)))/, $range); # commas outside of [] or () + if (scalar(@elems) == 1) { + @elems = split(/(@(?![^\(]*?\)))/, $range); # only split on @ when no , are present (inner recursion) } - $start =~ s/,-$//; - $start =~ s/,$//; - $start =~ s/\@$//; - %nodes = map { $_ => 1 } noderange($start,$verify,$exsitenode,%options,keepmissing=>1); - my %innernodes = map { $_ => 1 } noderange($middle,$verify,$exsitenode,%options,keepmissing=>1); - set_arith(\%nodes,$op,\%innernodes); - $range = $end; - } - my $op = ","; - my @elems = split(/(,(?![^[]*?])(?![^\(]*?\)))/,$range); # commas outside of [] or () - if (scalar(@elems)==1) { - @elems = split(/(@(?![^\(]*?\)))/,$range); # only split on @ when no , are present (inner recursion) - } - - while (defined(my $atom = shift @elems)) { - if ($atom eq '') { next; } - if ($atom eq ',') { - next; - } - if ($atom =~ /^-/) { # if this is an exclusion, strip off the minus, but remember it - $atom = substr($atom,1); - $op = $op."-"; - } elsif ($atom =~ /^\@/) { # if this is an exclusion, strip off the minus, but remember it - $atom = substr($atom,1); - $op = "@"; - } - if ($atom eq '') { next; } - - if ($atom =~ /^\^(.*)$/) { # get a list of nodes from a file - open(NRF,$1); - while () { - my $line=$_; - unless ($line =~ m/^[\^#]/) { - $line =~ m/^([^: ]*)/; - my $newrange = $1; - chomp($newrange); - $recurselevel++; - my @filenodes = noderange($newrange,$verify,$exsitenode,%options); - foreach (@filenodes) { - $nodes{$_}=1; - } + while (defined(my $atom = shift @elems)) { + if ($atom eq '') { next; } + if ($atom eq ',') { + next; } - } - close(NRF); - next; - } - - my %newset = map { $_ =>1 } expandatom($atom,$verify,%options); # expand the atom and make each entry in the resulting array a key in newset - - if ($op =~ /@/) { # compute the intersection of the current atom and the node list we have received before this - foreach (keys %nodes) { - unless ($newset{$_}) { - delete $nodes{$_}; + if ($atom =~ /^-/) { # if this is an exclusion, strip off the minus, but remember it + $atom = substr($atom, 1); + $op = $op . "-"; + } elsif ($atom =~ /^\@/) { # if this is an exclusion, strip off the minus, but remember it + $atom = substr($atom, 1); + $op = "@"; } - } - } elsif ($op =~ /,-/) { # add the nodes from this atom to the exclude list - foreach (keys %newset) { - $delnodes{$_}=1; #delay removal to end - } - } else { # add the nodes from this atom to the total node list - foreach (keys %newset) { - $nodes{$_}=1; - } - } - $op = shift @elems; + if ($atom eq '') { next; } + + if ($atom =~ /^\^(.*)$/) { # get a list of nodes from a file + open(NRF, $1); + while () { + my $line = $_; + unless ($line =~ m/^[\^#]/) { + $line =~ m/^([^: ]*)/; + my $newrange = $1; + chomp($newrange); + $recurselevel++; + my @filenodes = noderange($newrange, $verify, $exsitenode, %options); + foreach (@filenodes) { + $nodes{$_} = 1; + } + } + } + close(NRF); + next; + } + + my %newset = map { $_ => 1 } expandatom($atom, $verify, %options); # expand the atom and make each entry in the resulting array a key in newset + + if ($op =~ /@/) { # compute the intersection of the current atom and the node list we have received before this + foreach (keys %nodes) { + unless ($newset{$_}) { + delete $nodes{$_}; + } + } + } elsif ($op =~ /,-/) { # add the nodes from this atom to the exclude list + foreach (keys %newset) { + $delnodes{$_} = 1; #delay removal to end + } + } else { # add the nodes from this atom to the total node list + foreach (keys %newset) { + $nodes{$_} = 1; + } + } + $op = shift @elems; } # end of main while loop @@ -686,22 +709,22 @@ sub noderange { # Exclude the nodes in site attribute excludenodes? if ($exsitenode) { my $badnoderange = 0; - my @badnodes = (); - if ($::XCATSITEVALS{excludenodes}) { - @badnodes = noderange($::XCATSITEVALS{excludenodes}, 1, 0, %options); - foreach my $bnode (@badnodes) { - if (!$delnodes{$bnode}) { - $delnodes{$bnode} = 1; - } - } + my @badnodes = (); + if ($::XCATSITEVALS{excludenodes}) { + @badnodes = noderange($::XCATSITEVALS{excludenodes}, 1, 0, %options); + foreach my $bnode (@badnodes) { + if (!$delnodes{$bnode}) { + $delnodes{$bnode} = 1; + } + } } } # Now remove all the exclusion nodes foreach (keys %nodes) { - if ($delnodes{$_}) { - delete $nodes{$_}; - } + if ($delnodes{$_}) { + delete $nodes{$_}; + } } if ($recurselevel) { $recurselevel--; diff --git a/perl-xCAT/xCAT/NotifHandler.pm b/perl-xCAT/xCAT/NotifHandler.pm index c70b73942..44ffa80e2 100644 --- a/perl-xCAT/xCAT/NotifHandler.pm +++ b/perl-xCAT/xCAT/NotifHandler.pm @@ -1,6 +1,7 @@ #!/usr/bin/env perl # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html package xCAT::NotifHandler; + BEGIN { $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; @@ -25,15 +26,18 @@ my $dbworkerid; 1; #------------------------------------------------------------------------------- + =head1 xCATi::NotifHandler =head2 Package Description This mondule caches the notification table and tracks the changes of it. It also handles the event notification when xCAT database changes. =cut + #------------------------------------------------------------------------------- #-------------------------------------------------------------------------------- + =head3 setup It is called by xcatd to get set the pid of the parent of all this object. Setup the signal to trap any changes in the notification table. It also @@ -45,21 +49,23 @@ my $dbworkerid; Returns: none =cut + #------------------------------------------------------------------------------- sub setup { - $masterpid=shift; - if ($masterpid =~ /xCAT::NotifHandler/) { - $masterpid=shift; - } - $dbworkerid=shift; + $masterpid = shift; + if ($masterpid =~ /xCAT::NotifHandler/) { + $masterpid = shift; + } + $dbworkerid = shift; - refreshNotification(); + refreshNotification(); - $SIG{USR1}=\&handleNotifSignal; + $SIG{USR1} = \&handleNotifSignal; } #-------------------------------------------------------------------------------- + =head3 handleNotifSignal It is called when the signal is received. It then update the cache with the latest data in the notification table. @@ -68,14 +74,17 @@ sub setup Returns: none =cut + #------------------------------------------------------------------------------- sub handleNotifSignal { - #print "handleNotifSignal pid=$$\n"; - refreshNotification(); - $SIG{USR1}=\&handleNotifSignal; + + #print "handleNotifSignal pid=$$\n"; + refreshNotification(); + $SIG{USR1} = \&handleNotifSignal; } #-------------------------------------------------------------------------------- + =head3 sendNotifSignal It is called by any module that has made changes to the notification table. Arguments: @@ -83,18 +92,20 @@ sub handleNotifSignal { Returns: none =cut + #------------------------------------------------------------------------------- sub sendNotifSignal { - if ($masterpid) { - kill('USR1', $masterpid); - } - if ($dbworkerid) { - kill('USR1', $dbworkerid); - } + if ($masterpid) { + kill('USR1', $masterpid); + } + if ($dbworkerid) { + kill('USR1', $dbworkerid); + } } #-------------------------------------------------------------------------------- + =head3 refreshNotification It loads the notification info from the "notification" table and store it into %notif variable. @@ -105,77 +116,81 @@ sub sendNotifSignal { Returns: none =cut + #------------------------------------------------------------------------------- sub refreshNotification { - #print "refreshNotification get called\n"; - #flush the cache - %notif=(); - my $table=xCAT::Table->new("notification", -create =>0); - if ($table) { - #get array of rows out of the notification table - my @row_array= $table->getTable; - if (@row_array) { - #store the information to the cache - foreach(@row_array) { - my $module=$_->{filename}; - my $ops=$_->{tableops}; - my $disable= $_->{disable}; - my @tablenames=split(/,/, $_->{tables}); + #print "refreshNotification get called\n"; + #flush the cache + %notif = (); + my $table = xCAT::Table->new("notification", -create => 0); + if ($table) { - foreach(@tablenames) { - if (!exists($notif{$_})) { - $notif{$_}={}; - } + #get array of rows out of the notification table + my @row_array = $table->getTable; + if (@row_array) { + + #store the information to the cache + foreach (@row_array) { + my $module = $_->{filename}; + my $ops = $_->{tableops}; + my $disable = $_->{disable}; + my @tablenames = split(/,/, $_->{tables}); + + foreach (@tablenames) { + if (!exists($notif{$_})) { + $notif{$_} = {}; + } - my $tempdisable=0; - if ($disable) { - if ($disable =~ m/^(yes|YES|Yes|Y|y|1)$/) { - $tempdisable=1; - } - } + my $tempdisable = 0; + if ($disable) { + if ($disable =~ m/^(yes|YES|Yes|Y|y|1)$/) { + $tempdisable = 1; + } + } - if (!$disable) { - if ($ops) { - if ($ops =~ m/a/) { - if (exists($notif{$_}->{a})) { - my $pa=$notif{$_}->{a}; - push(@$pa, $module); - } else { - $notif{$_}->{a}=[$module]; - } - } - if ($ops =~ m/d/) { - if (exists($notif{$_}->{d})) { - my $pa=$notif{$_}->{d}; - push(@$pa, $module); - } else { - $notif{$_}->{d}=[$module]; - } - } - if ($ops =~ m/u/) { - if (exists($notif{$_}->{u})) { - my $pa=$notif{$_}->{u}; - push(@$pa, $module); - } else { - $notif{$_}->{u}=[$module]; - } - } - } #end if - } - } #end foreach + if (!$disable) { + if ($ops) { + if ($ops =~ m/a/) { + if (exists($notif{$_}->{a})) { + my $pa = $notif{$_}->{a}; + push(@$pa, $module); + } else { + $notif{$_}->{a} = [$module]; + } + } + if ($ops =~ m/d/) { + if (exists($notif{$_}->{d})) { + my $pa = $notif{$_}->{d}; + push(@$pa, $module); + } else { + $notif{$_}->{d} = [$module]; + } + } + if ($ops =~ m/u/) { + if (exists($notif{$_}->{u})) { + my $pa = $notif{$_}->{u}; + push(@$pa, $module); + } else { + $notif{$_}->{u} = [$module]; + } + } + } #end if + } + } #end foreach - } #end foreach(@row_array) - }#end if (@row_array) - } #end if ($table) + } #end foreach(@row_array) + } #end if (@row_array) + } #end if ($table) - #print Dumper(%notif); - return 1; + #print Dumper(%notif); + return 1; } #-------------------------------------------------------------------------------- + =head3 dumpNotificationCache It print out the content of the notification cache for debugging purpose. Arguments: @@ -183,34 +198,36 @@ sub refreshNotification Returns: 0 =cut + #------------------------------------------------------------------------------- sub dumpNotificationCache { - print "dump the notification cache:\n"; - foreach(keys(%notif)) { - my $tmptn=$_; - print " $tmptn: \n"; + print "dump the notification cache:\n"; + foreach (keys(%notif)) { + my $tmptn = $_; + print " $tmptn: \n"; - if (exists($notif{$_}->{a})) { - print " a--:"; - my $files=$notif{$_}->{a}; - print "@$files\n"; + if (exists($notif{$_}->{a})) { + print " a--:"; + my $files = $notif{$_}->{a}; + print "@$files\n"; + } + if (exists($notif{$_}->{u})) { + print " u--:"; + my $files = $notif{$_}->{u}; + print "@$files\n"; + } + if (exists($notif{$_}->{d})) { + print " d--:"; + my $files = $notif{$_}->{d}; + print "@$files\n"; + } } - if (exists($notif{$_}->{u})) { - print " u--:"; - my $files=$notif{$_}->{u}; - print "@$files\n"; - } - if (exists($notif{$_}->{d})) { - print " d--:"; - my $files=$notif{$_}->{d}; - print "@$files\n"; - } - } - return 0; + return 0; } #-------------------------------------------------------------------------------- + =head3 needToNotify It check if the given table has interested parties watching for its changes. Arguments: @@ -221,34 +238,37 @@ sub dumpNotificationCache { 1 - if the table has interested parties. 0 - if no parties are interested in its changes. =cut + #------------------------------------------------------------------------------- sub needToNotify { - #print "needToNotify pid=$$, notify=" . Dumper(%notif) . "\n"; + #print "needToNotify pid=$$, notify=" . Dumper(%notif) . "\n"; - if (!%notif) { - # print "notif not defined\n"; - refreshNotification(); - } + if (!%notif) { - my $tablename=shift; - if ($tablename =~ /xCAT::NotifHandler/) { - $tablename=shift; - } - my $tableop=shift; - - if (%notif) { - if (exists($notif{$tablename})) { - if (exists($notif{$tablename}->{$tableop})) { - return 1; - } + # print "notif not defined\n"; + refreshNotification(); } - } - return 0; + + my $tablename = shift; + if ($tablename =~ /xCAT::NotifHandler/) { + $tablename = shift; + } + my $tableop = shift; + + if (%notif) { + if (exists($notif{$tablename})) { + if (exists($notif{$tablename}->{$tableop})) { + return 1; + } + } + } + return 0; } #-------------------------------------------------------------------------------- + =head3 notify It notifies the registered the modules with the latest changes in a DB table. @@ -284,79 +304,83 @@ sub needToNotify { ... =cut + #------------------------------------------------------------------------------- sub notify { - my $action=shift; - if ($action =~ /xCAT::NotifHandler/) { - $action=shift; - } - my $tablename=shift; - my $old_data=shift; - my $new_data=shift; - - # print "notify called: tablename=$tablename, action=$action\n"; - - my @filenames=(); - if (%notif) { - if (exists($notif{$tablename})) { - if (exists($notif{$tablename}->{$action})) { - my $pa=$notif{$tablename}->{$action}; - @filenames=@$pa; - } + my $action = shift; + if ($action =~ /xCAT::NotifHandler/) { + $action = shift; } - } + my $tablename = shift; + my $old_data = shift; + my $new_data = shift; + # print "notify called: tablename=$tablename, action=$action\n"; - foreach(@filenames) { - my ($modname, $path, $suffix) = fileparse($_, ".pm"); - # print "modname=$modname, path=$path, suffix=$suffix\n"; - if ($suffix =~ /.pm/) { #it is a perl module - my $fname; - if (($path eq "") || ($path eq ".\/")) { - #default path is /opt/xcat/lib/perl/xCAT_monitoring/ if there is no path specified - $fname = "$::XCATROOT/lib/perl/xCAT_monitoring/".$modname.".pm"; - } else { - $fname = $_; + my @filenames = (); + if (%notif) { + if (exists($notif{$tablename})) { + if (exists($notif{$tablename}->{$action})) { + my $pa = $notif{$tablename}->{$action}; + @filenames = @$pa; + } } - eval {require($fname)}; - if ($@) { - print "The file $fname cannot be located or has compiling errors.\n"; - } - else { - ${"xCAT_monitoring::".$modname."::"}{processTableChanges}->($action, $tablename, $old_data, $new_data); - } - return 0; } - else { #it is a command - my $pid; - if ($pid=xCAT::Utils->xfork()) { } - elsif (defined($pid)) { - # print "command=$_\n"; - if (open(CMD, "|$_")) { - print(CMD "$action\n"); - print(CMD "$tablename\n"); - print(CMD "[old data]\n"); - foreach (@$old_data) { - print(CMD join(',', @$_)."\n"); - } - print(CMD "[new data]\n"); - if (%$new_data) { - print(CMD join(',', keys %$new_data) . "\n"); - print(CMD join(',', values %$new_data) . "\n"); - } - close(CMD) or print "Cannot close the command $_\n"; + foreach (@filenames) { + my ($modname, $path, $suffix) = fileparse($_, ".pm"); + + # print "modname=$modname, path=$path, suffix=$suffix\n"; + if ($suffix =~ /.pm/) { #it is a perl module + my $fname; + if (($path eq "") || ($path eq ".\/")) { + + #default path is /opt/xcat/lib/perl/xCAT_monitoring/ if there is no path specified + $fname = "$::XCATROOT/lib/perl/xCAT_monitoring/" . $modname . ".pm"; + } else { + $fname = $_; + } + eval { require($fname) }; + if ($@) { + print "The file $fname cannot be located or has compiling errors.\n"; + } + else { + ${ "xCAT_monitoring::" . $modname . "::" }{processTableChanges}->($action, $tablename, $old_data, $new_data); + } + return 0; } - else { - print "Command $_ cannot be found\n"; + else { #it is a command + my $pid; + if ($pid = xCAT::Utils->xfork()) { } + elsif (defined($pid)) { + + # print "command=$_\n"; + if (open(CMD, "|$_")) { + print(CMD "$action\n"); + print(CMD "$tablename\n"); + + print(CMD "[old data]\n"); + foreach (@$old_data) { + print(CMD join(',', @$_) . "\n"); + } + + print(CMD "[new data]\n"); + if (%$new_data) { + print(CMD join(',', keys %$new_data) . "\n"); + print(CMD join(',', values %$new_data) . "\n"); + } + close(CMD) or print "Cannot close the command $_\n"; + } + else { + print "Command $_ cannot be found\n"; + } + + exit 0; + } #elsif } + } #foreach - exit 0; - } #elsif - } - } #foreach - - return 0; + return 0; } diff --git a/perl-xCAT/xCAT/PPCboot.pm b/perl-xCAT/xCAT/PPCboot.pm index 1f5b9e776..c29da6816 100644 --- a/perl-xCAT/xCAT/PPCboot.pm +++ b/perl-xCAT/xCAT/PPCboot.pm @@ -13,7 +13,7 @@ use xCAT::MsgUtils; use xCAT::LparNetbootExp; ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { @@ -27,56 +27,56 @@ sub parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(h|help V T v|version I|iscsiboot F f o s=s m:s@ r=s t=s) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(h|help V T v|version I|iscsiboot F f o s=s m:s@ r=s t=s))) { + return (usage()); } #################################### # Option -h for Help #################################### - if ( exists( $opt{h} )) { - return( usage() ); + if (exists($opt{h})) { + return (usage()); } #################################### # Option -v for version #################################### - if ( exists( $opt{v} )) { + if (exists($opt{v})) { my $version = xCAT::Utils->Version(); return ([$version]); } - if ( exists( $opt{s} ) ){ + if (exists($opt{s})) { my @boot_devices = split(/,/, $opt{s}); foreach (@boot_devices) { - if ( (!/^net$/) && (!/^hd$/) ) { - return(usage( "boot device $_ is not supported" )); + if ((!/^net$/) && (!/^hd$/)) { + return (usage("boot device $_ is not supported")); } - } + } } - if (exists( $opt{m} ) ){ + if (exists($opt{m})) { my $res = xCAT::Utils->check_deployment_monitoring_settings($request, \%opt); if ($res != SUCCESS) { - return(usage()); - } + return (usage()); + } } ############################################# # T is used for trace, V is used for debug @@ -85,30 +85,30 @@ sub parse_args { $opt{V} = 1; delete $opt{T}; - }elsif(exists($opt{V})) { + } elsif (exists($opt{V})) { $opt{T} = 1; delete $opt{V}; } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } ########################################################################## -# Netboot the lpar +# Netboot the lpar ########################################################################## sub do_rnetboot { @@ -130,10 +130,10 @@ sub do_rnetboot { ####################################### # Disconnect Expect session ####################################### - xCAT::PPCcli::disconnect( $exp ); - + xCAT::PPCcli::disconnect($exp); + ####################################### - # Get node data + # Get node data ####################################### my $id = @$d[0]; my $pprofile = @$d[1]; @@ -158,7 +158,7 @@ sub do_rnetboot { ####################################### # Save user name and passwd of hcp to # environment variables. - # lpar_netboot.expect depends on it + # lpar_netboot.expect depends on it ####################################### $ENV{HCP_USERID} = $userid; $ENV{HCP_PASSWD} = $pw; @@ -166,51 +166,59 @@ sub do_rnetboot { ####################################### # Turn on verbose and debugging ####################################### - if ( ${$request->{arg}}[0] eq '-V' ) { + if (${ $request->{arg} }[0] eq '-V') { + #$cmd.= " -v -x"; - $optarg{'v'} = 1; #for verbose - $optarg{'x'} = 1; #for debug + $optarg{'v'} = 1; #for verbose + $optarg{'x'} = 1; #for debug } ####################################### # Force LPAR shutdown ####################################### - if ( exists( $opt->{f} ) || !xCAT::Utils->isAIX() ) { + if (exists($opt->{f}) || !xCAT::Utils->isAIX()) { + #$cmd.= " -i"; $optarg{'i'} = 1; - } + } ####################################### # Write boot order ####################################### - if ( exists( $opt->{s} )) { + if (exists($opt->{s})) { foreach ($opt->{s}) { - if ( /^net$/ ) { + if (/^net$/) { + #$cmd.= " -w 1"; $optarg{'w'} = 1; - } elsif ( /^net,hd$/ ) { + } elsif (/^net,hd$/) { + #$cmd.= " -w 2"; $optarg{'w'} = 2; - } elsif ( /^hd,net$/ ) { + } elsif (/^hd,net$/) { + #$cmd.= " -w 3"; $optarg{'w'} = 3; - } elsif ( /^hd$/ ) { + } elsif (/^hd$/) { + #$cmd.= " -w 4"; $optarg{'w'} = 4; } } } - if ( exists( $opt->{o} )) { + if (exists($opt->{o})) { + #$cmd.= " -o"; $optarg{'o'} = 1; } my @macs = split /\|/, $opt->{m}; - foreach my $mac ( @macs ) { + foreach my $mac (@macs) { ####################################### # Network specified ####################################### my $mac_a = lc($mac); + #$cmd.= " -s auto -d auto -m $mac_a -S $opt->{S} -C $opt->{C} -N $opt->{N}"; $optarg{'s'} = 'auto'; @@ -224,14 +232,14 @@ sub do_rnetboot { #$cmd.= " -G $opt->{G}"; $optarg{'G'} = $opt->{G}; } - + ####################################### # Get required attributes from master # of the node if -I|--iscsiboot is # specified ####################################### - if ( exists( $opt->{I} )) { + if (exists($opt->{I})) { my $ret; my $dump_target; my $dump_lun; @@ -240,19 +248,19 @@ sub do_rnetboot { unless ($noderestab) { xCAT::MsgUtils->message('S', - "Unable to open noderes table.\n"); + "Unable to open noderes table.\n"); return 1; } my $et = $noderestab->getNodeAttribs($node, ['xcatmaster']); if ($et and $et->{'xcatmaster'}) { $ret = xCAT::Utils->runxcmd( - { - command => ['xdsh'], - node => [$et->{'xcatmaster'}], - arg => [ 'cat /tftpboot/$node.info' ] - }, - $subreq, 0, 0 ); + { + command => ['xdsh'], + node => [ $et->{'xcatmaster'} ], + arg => ['cat /tftpboot/$node.info'] + }, + $subreq, 0, 0); } else { $ret = `cat /tftpboot/$node.info`; } @@ -266,24 +274,27 @@ sub do_rnetboot { $dump_lun = $1; $dump_lun =~ s/^0x(.*)$/$1/g; } elsif (/DUMP_PORT=(.*)$/) { - $dump_port =$1; + $dump_port = $1; } } - if ( defined($dump_target) and defined($dump_lun) and defined($dump_port) ) { + if (defined($dump_target) and defined($dump_lun) and defined($dump_port)) { + #$cmd.= " -T \"$dump_target\" -L \"$dump_lun\" -p \"$dump_port\""; $optarg{'T'} = $dump_target; $optarg{'L'} = $dump_lun; $optarg{'p'} = $dump_port; } else { - return( [RC_ERROR,"Unable to find DUMP_TARGET, DUMP_LUN, DUMP_PORT for iscsi dump"] ); + return ([ RC_ERROR, "Unable to find DUMP_TARGET, DUMP_LUN, DUMP_PORT for iscsi dump" ]); } } - my %client_nethash = xCAT::DBobjUtils->getNetwkInfo( [$node] ); - if ( grep /hf/, $client_nethash{$node}{mgtifname} ) { + my %client_nethash = xCAT::DBobjUtils->getNetwkInfo([$node]); + if (grep /hf/, $client_nethash{$node}{mgtifname}) { + #$cmd.= " -t hfi-ent"; $optarg{'t'} = "hfi-ent"; } else { + #$cmd.= " -t ent"; $optarg{'t'} = "ent"; } @@ -292,18 +303,18 @@ sub do_rnetboot { # Add command options ####################################### #$cmd.= " -f \"$name\" \"$pprofile\" \"$fsp\" $id $hcp \"$node\""; - $optarg{'f'} = 1; - $optarg{'name'} = $name; + $optarg{'f'} = 1; + $optarg{'name'} = $name; $optarg{'pprofile'} = $pprofile; - $optarg{'fsp'} = $fsp; - $optarg{'id'} = $id; - $optarg{'hcp'} = $hcp; - $optarg{'node'} = $node; + $optarg{'fsp'} = $fsp; + $optarg{'id'} = $id; + $optarg{'hcp'} = $hcp; + $optarg{'node'} = $node; my $done = 0; - while ( $done < 2 ) { + while ($done < 2) { $result = ""; - $Rc = SUCCESS; + $Rc = SUCCESS; ######################################## ## Execute command ######################################## @@ -339,14 +350,14 @@ sub do_rnetboot { ####################################### $result = xCAT::LparNetbootExp->lparnetbootexp(\%optarg, $request); $Rc = @$result[0]; - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { $done = 2; } else { $done = $done + 1; sleep 1; } } - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { last; } } @@ -358,9 +369,10 @@ sub do_rnetboot { my $server = @$exp[3]; # creat connection first - my @newexp = xCAT::PPCcli::connect( $request, $hwtype, $server ); - if (ref($newexp[0]) eq "Expect" ) { + my @newexp = xCAT::PPCcli::connect($request, $hwtype, $server); + if (ref($newexp[0]) eq "Expect") { my $cfg = "lpar_id=@$d[0],boot_mode=norm"; + # change the boot mode to 'norm' xCAT::PPCcli::chsyscfg(\@newexp, "prof", $d, $cfg); xCAT::PPCcli::disconnect(\@newexp); @@ -371,7 +383,7 @@ sub do_rnetboot { } } - return $result; + return $result; } @@ -389,17 +401,17 @@ sub rnetboot { my $name; my $callback = $request->{callback}; ##################################### - # Get node data + # Get node data ##################################### my $lparid = @$d[0]; my $mtms = @$d[2]; my $type = @$d[4]; my $node = @$d[6]; - my $o = @$d[7]; + my $o = @$d[7]; ##################################### - # Gateway (-G) - # Server (-S) + # Gateway (-G) + # Server (-S) # Client (-C) # mac (-m) ##################################### @@ -413,58 +425,58 @@ sub rnetboot { ##################################### - # Strip colons from mac address + # Strip colons from mac address ##################################### $opt{m} =~ s/://g; ##################################### - # Force LPAR shutdown + # Force LPAR shutdown ##################################### - if ( exists( $options->{f} )) { + if (exists($options->{f})) { $opt{f} = 1; } ##################################### # Write boot device order ##################################### - if ( exists( $options->{s} )) { + if (exists($options->{s})) { $opt{s} = $options->{s}; } - - if ( exists( $options->{o} )) { + + if (exists($options->{o})) { $opt{o} = $options->{o}; } ##################################### # Do iscsi boot ##################################### - if ( exists( $options->{I} )) { - $opt{I} = 1; + if (exists($options->{I})) { + $opt{I} = 1; } ##################################### - # Invalid target hardware + # Invalid target hardware ##################################### - if ( $type !~ /^lpar$/ ) { - return( [[$name,"Not supported",RC_ERROR]] ); + if ($type !~ /^lpar$/) { + return ([ [ $name, "Not supported", RC_ERROR ] ]); } ######################################### # Get name known by HCP ######################################### my $filter = "name,lpar_id"; - my $values = xCAT::PPCcli::lssyscfg( $exp, $type, $mtms, $filter ); - my $Rc = shift(@$values); + my $values = xCAT::PPCcli::lssyscfg($exp, $type, $mtms, $filter); + my $Rc = shift(@$values); ######################################### # Return error ######################################### - if ( $Rc != SUCCESS ) { - return( [[$node,@$values[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $node, @$values[0], $Rc ] ]); } ######################################### # Find LPARs by lpar_id ######################################### - foreach ( @$values ) { - if ( /^(.*),$lparid$/ ) { + foreach (@$values) { + if (/^(.*),$lparid$/) { $name = $1; last; } @@ -472,8 +484,8 @@ sub rnetboot { ######################################### # Node not found by lpar_id ######################################### - if ( !defined( $name )) { - return( [[$node,"Node not found, lparid=$lparid",RC_ERROR]] ); + if (!defined($name)) { + return ([ [ $node, "Node not found, lparid=$lparid", RC_ERROR ] ]); } ######################################### @@ -481,79 +493,82 @@ sub rnetboot { # It is not allowed to rinitialize node # if it is in boot state ######################################### - if ( !exists( $options->{F} ) && !xCAT::Utils->isAIX() ) { + if (!exists($options->{F}) && !xCAT::Utils->isAIX()) { my $chaintab = xCAT::Table->new('chain'); - my $vcon = $chaintab->getAttribs({ node => "$node"}, 'currstate'); - if ( $vcon and $vcon->{"currstate"} and $vcon->{"currstate"} eq "boot" ) { - return( [[$node,"Node is in boot state. Use nodeset command before rnetboot or use -F option with rnetboot",RC_ERROR]] ); + my $vcon = $chaintab->getAttribs({ node => "$node" }, 'currstate'); + if ($vcon and $vcon->{"currstate"} and $vcon->{"currstate"} eq "boot") { + return ([ [ $node, "Node is in boot state. Use nodeset command before rnetboot or use -F option with rnetboot", RC_ERROR ] ]); } } #my $sitetab = xCAT::Table->new('site'); #my $vcon = $sitetab->getAttribs({key => "conserverondemand"}, 'value'); my @vcons = xCAT::TableUtils->get_site_attribute("conserverondemand"); - my $vcon = $vcons[0]; + my $vcon = $vcons[0]; + #if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { - if ( defined($vcon) and $vcon eq "yes" ) { + if (defined($vcon) and $vcon eq "yes") { $result = xCAT::PPCcli::lpar_netboot( - $exp, - $request->{verbose}, - $name, - $d, - \%opt ); + $exp, + $request->{verbose}, + $name, + $d, + \%opt); } else { ######################################### - # Manually perform boot. + # Manually perform boot. ######################################### - $result = do_rnetboot( $request, $d, $exp, $name, $node, \%opt ); + $result = do_rnetboot($request, $d, $exp, $name, $node, \%opt); } + #$sitetab->close; if (defined($request->{opt}->{m})) { - - my $retries = 0; + + my $retries = 0; my @monnodes = ($name); my $monsettings = xCAT::Utils->generate_monsettings($request, \@monnodes); - xCAT::Utils->monitor_installation($request, $monsettings);; - while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{$monsettings->{'nodes'}}) > 0) { + xCAT::Utils->monitor_installation($request, $monsettings); + while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{ $monsettings->{'nodes'} }) > 0) { ####lparnetboot can not support multiple nodes in one invocation ####for now, does not know how the $d and \%opt will be changed if ####support mulitiple nodes in one invocation, ####so just use the original node name and node attribute array and hash - - my $rsp={}; - $rsp->{data}->[0] = "$node: Reinitializing the installation: $retries retry"; - xCAT::MsgUtils->message("I", $rsp, $callback); - if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { + + my $rsp = {}; + $rsp->{data}->[0] = "$node: Reinitializing the installation: $retries retry"; + xCAT::MsgUtils->message("I", $rsp, $callback); + if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes") { $result = xCAT::PPCcli::lpar_netboot( - $exp, - $request->{verbose}, - $name, - $d, - \%opt ); + $exp, + $request->{verbose}, + $name, + $d, + \%opt); } else { - $result = do_rnetboot( $request, $d, $exp, $name, $node, \%opt ); + $result = do_rnetboot($request, $d, $exp, $name, $node, \%opt); } xCAT::Utils->monitor_installation($request, $monsettings); - + } + #failed after retries - if (scalar(keys %{$monsettings->{'nodes'}}) > 0) { - foreach my $node (keys %{$monsettings->{'nodes'}}) { - my $rsp={}; + if (scalar(keys %{ $monsettings->{'nodes'} }) > 0) { + foreach my $node (keys %{ $monsettings->{'nodes'} }) { + my $rsp = {}; $rsp->{data}->[0] = "The node \"$node\" can not reach the expected status after $monsettings->{'retrycount'} retries, the installation for this done failed"; xCAT::MsgUtils->message("E", $rsp, $callback); } - } + } } $Rc = shift(@$result); - + ################################## # Form string from array results ################################## - if ( exists($request->{verbose}) ) { - return( [[$node,join( '', @$result ),$Rc]] ); + if (exists($request->{verbose})) { + return ([ [ $node, join('', @$result), $Rc ] ]); } ################################## # Return error @@ -569,18 +584,18 @@ sub rnetboot { # lpar_netboot: can not find mac address 42DAB. # ################################## - if ( $Rc != SUCCESS ) { - if ( @$result[0] =~ /lpar_netboot (.*)/ ) { - return( [[$node,$1,$Rc]] ); + if ($Rc != SUCCESS) { + if (@$result[0] =~ /lpar_netboot (.*)/) { + return ([ [ $node, $1, $Rc ] ]); } - return( [[$node,join( '', @$result ),$Rc]] ); + return ([ [ $node, join('', @$result), $Rc ] ]); } ################################## # Split array into string ################################## my $data = @$result[0]; - if ( $hwtype eq "hmc" ) { - $data = join( '', @$result ); + if ($hwtype eq "hmc") { + $data = join('', @$result); } ################################## # lpar_netboot returns: @@ -595,8 +610,12 @@ sub rnetboot { # # Finished. # ##################################### - if ( $data =~ /Finished/) { - return( [[$node,"Success",$Rc]] ); + if ($data =~ /Finished/) { + my $newstat = $::STATUS_POWERING_ON; + my %newnodestatus = (); + $newnodestatus{$newstat} = [$node]; + xCAT_monitoring::monitorctrl::setNodeStatusAttributes(\%newnodestatus, 1); + return ([ [ $node, "Success", $Rc ] ]); } ##################################### # Can still be error w/ Rc=0: @@ -610,12 +629,12 @@ sub rnetboot { # lpar_netboot: bootp operation failed. # ##################################### - if ( $data =~ /lpar_netboot (.*)/ ) { - return( [[$node,$1,RC_ERROR]] ); + if ($data =~ /lpar_netboot (.*)/) { + return ([ [ $node, $1, RC_ERROR ] ]); } - return( [[$node,$data,RC_ERROR]] ); + return ([ [ $node, $data, RC_ERROR ] ]); } - + 1; diff --git a/perl-xCAT/xCAT/PPCcfg.pm b/perl-xCAT/xCAT/PPCcfg.pm index 92af8e851..9c0f1c2af 100644 --- a/perl-xCAT/xCAT/PPCcfg.pm +++ b/perl-xCAT/xCAT/PPCcfg.pm @@ -16,9 +16,9 @@ use HTTP::Cookies; ########################################## # Globals ########################################## -my %rspconfig = ( - sshcfg => \&sshcfg, - frame => \&frame, +my %rspconfig = ( + sshcfg => \&sshcfg, + frame => \&frame, hostname => \&hostname ); @@ -34,7 +34,7 @@ sub parse_args { my $args = $request->{arg}; my %opt = (); my %cmds = (); - my @fsp = ( + my @fsp = ( "memdecfg", "decfg", "procdecfg", @@ -71,12 +71,12 @@ sub parse_args { "sshcfg" ); my %rsp = ( - cec=> \@fsp, - frame=>\@bpa, - fsp => \@fsp, - bpa => \@bpa, - ivm => \@ppc, - hmc => \@ppc + cec => \@fsp, + frame => \@bpa, + fsp => \@fsp, + bpa => \@bpa, + ivm => \@ppc, + hmc => \@ppc ); ############################################# # Get support command list @@ -84,7 +84,7 @@ sub parse_args { #my $typetab = xCAT::Table->new( 'nodetype' ); #my $nodes = $request->{node}; #foreach (@$nodes) { - # if ( defined( $typetab )) { + # if ( defined( $typetab )) { # my ($ent) = $typetab->getAttribs({ node=>$_},'nodetype'); # if ( defined($ent) ) { # $request->{hwtype} = $ent->{nodetype}; @@ -94,148 +94,149 @@ sub parse_args { # } # #} - - my $nodes = $request->{node}; + + my $nodes = $request->{node}; my $typehash = xCAT::DBobjUtils->getnodetype($nodes); foreach my $nn (@$nodes) { $request->{hwtype} = $$typehash{$nn}; last if ($request->{hwtype}); } - - my $supported = $rsp{$request->{hwtype}}; - + + my $supported = $rsp{ $request->{hwtype} }; + ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [$_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); $request->{method} = undef; - if ( !GetOptions( \%opt, qw(V|verbose resetnet))) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose resetnet))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### - # Check for "=" with no argument + # Check for "=" with no argument #################################### - if (my ($c) = grep(/=$/, @ARGV )) { - return(usage( "Missing argument: $c" )); + if (my ($c) = grep(/=$/, @ARGV)) { + return (usage("Missing argument: $c")); } #################################### # Check for unsupported commands #################################### - foreach my $arg ( @ARGV ) { - my ($command,$value) = split( /=/, $arg ); - if ( !grep( /^$command$/, @$supported) and !$opt{resetnet}) { - return(usage( "Invalid command: $arg" )); - } - if ( exists( $cmds{$command} )) { - return(usage( "Command multiple times: $command" )); + foreach my $arg (@ARGV) { + my ($command, $value) = split(/=/, $arg); + if (!grep(/^$command$/, @$supported) and !$opt{resetnet}) { + return (usage("Invalid command: $arg")); + } + if (exists($cmds{$command})) { + return (usage("Command multiple times: $command")); } $cmds{$command} = $value; - } + } #################################### - # Check command arguments + # Check command arguments #################################### - foreach ( keys %cmds ) { - if ( $cmds{$_} ) { - my $result = parse_option( $request, $_, $cmds{$_} ); - if ( $result ) { - return( usage($result) ); + foreach (keys %cmds) { + if ($cmds{$_}) { + my $result = parse_option($request, $_, $cmds{$_}); + if ($result) { + return (usage($result)); } } elsif ($_ =~ /_passwd$/) { - return( usage("No argument specified for '$_'")); - } + return (usage("No argument specified for '$_'")); + } } { if ($request->{dev} eq '1' && $request->{other} eq '1') { - return ( usage("Invalid command arrays")); - } -# my $result = parse_dev_option( $request, \%cmds); -# if ($result) { -# return ( usage($result)); -# } - } - #################################### - # Return method to invoke - #################################### - if ( $request->{hwtype} =~ /(^hmc|ivm)$/ ) { - $request->{method} = "cfg"; - return( \%opt ); + return (usage("Invalid command arrays")); + } + + # my $result = parse_dev_option( $request, \%cmds); + # if ($result) { + # return ( usage($result)); + # } } #################################### # Return method to invoke #################################### - if ( exists($cmds{frame}) or exists($cmds{hostname}) ) { - $request->{hcp} = "hmc"; + if ($request->{hwtype} =~ /(^hmc|ivm)$/) { $request->{method} = "cfg"; - return( \%opt ); + return (\%opt); } #################################### # Return method to invoke #################################### - if ( $opt{resetnet} ) { - $request->{hcp} = "hmc"; + if (exists($cmds{frame}) or exists($cmds{hostname})) { + $request->{hcp} = "hmc"; + $request->{method} = "cfg"; + return (\%opt); + } + #################################### + # Return method to invoke + #################################### + if ($opt{resetnet}) { + $request->{hcp} = "hmc"; $request->{method} = "resetnet"; - return( \%opt ); + return (\%opt); } #################################### # Return method to invoke #################################### - if ( exists($cmds{HMC_passwd}) or exists($cmds{general_passwd}) or exists($cmds{admin_passwd}) or exists($cmds{"*_passwd"}) ) { - $request->{hcp} = "hmc"; + if (exists($cmds{HMC_passwd}) or exists($cmds{general_passwd}) or exists($cmds{admin_passwd}) or exists($cmds{"*_passwd"})) { + $request->{hcp} = "hmc"; $request->{method} = "passwd"; - return( \%opt ); + return (\%opt); } $request->{method} = \%cmds; - return( \%opt ); + return (\%opt); } -sub parse_dev_option{ - my $req = shift; +sub parse_dev_option { + my $req = shift; my $cmds = shift; foreach my $cmd (keys %$cmds) { - if ( $cmd =~ /^(dev|celogin1)$/ ) { - if ($cmds->{$cmd} and ($cmds->{$cmd} !~ /^(enable|disable)$/i) ) { - return( "Invalid argument ".$cmds->{$cmd}." for ".$cmd ); + if ($cmd =~ /^(dev|celogin1)$/) { + if ($cmds->{$cmd} and ($cmds->{$cmd} !~ /^(enable|disable)$/i)) { + return ("Invalid argument " . $cmds->{$cmd} . " for " . $cmd); } $req->{dev} = 1; } else { - $req->{other} = 1; + $req->{other} = 1; } } if ($req->{dev} eq '1' && $req->{other} eq '1') { return ("Invalid command arrays"); - } + } return undef; } ########################################################################## -# Parse the command line optional arguments +# Parse the command line optional arguments ########################################################################## sub parse_option { @@ -246,90 +247,90 @@ sub parse_option { #################################### # Set/get time #################################### - if ( $command =~ /^time$/ ) { - if ( $value !~ - /^([0-1]?[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9])$/){ - return( "Invalid time format '$value'" ); + if ($command =~ /^time$/) { + if ($value !~ +/^([0-1]?[0-9]|2[0-3]):(0?[0-9]|[1-5][0-9]):(0?[0-9]|[1-5][0-9])$/) { + return ("Invalid time format '$value'"); } } #################################### - # Set/get date + # Set/get date #################################### - if ( $command =~ /^date$/ ) { - if ( $value !~ - /^(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])-(20[0-9]{2})$/){ - return( "Invalid date format '$value'" ); + if ($command =~ /^date$/) { + if ($value !~ + /^(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])-(20[0-9]{2})$/) { + return ("Invalid date format '$value'"); } } #################################### # Set/get options #################################### - if ( $command =~ /^(autopower|iocap|sshcfg)$/ ) { - if ( $value !~ /^(enable|disable)$/i ) { - return( "Invalid argument '$value'" ); + if ($command =~ /^(autopower|iocap|sshcfg)$/) { + if ($value !~ /^(enable|disable)$/i) { + return ("Invalid argument '$value'"); } } #################################### - # Deconfiguration policy + # Deconfiguration policy #################################### - if ( $command =~ /^decfg$/ ) { - if ( $value !~ /^(enable|disable):.*$/i ) { - return( "Invalid argument '$value'" ); + if ($command =~ /^decfg$/) { + if ($value !~ /^(enable|disable):.*$/i) { + return ("Invalid argument '$value'"); } } #################################### - # Processor deconfiguration + # Processor deconfiguration #################################### - if ( $command =~ /^procdecfg$/ ) { - if ( $value !~ /^(configure|deconfigure):\d+:(all|[\d,]+)$/i ) { - return( "Invalid argument '$value'" ); + if ($command =~ /^procdecfg$/) { + if ($value !~ /^(configure|deconfigure):\d+:(all|[\d,]+)$/i) { + return ("Invalid argument '$value'"); } } ################################ - # Memory deconfiguration + # Memory deconfiguration ################################ - elsif ( $command =~ /^memdecfg$/ ) { - if ($value !~/^(configure|deconfigure):\d+:(unit|bank):(all|[\d,]+)$/i){ - return( "Invalid argument '$value'" ); - } + elsif ($command =~ /^memdecfg$/) { + if ($value !~ /^(configure|deconfigure):\d+:(unit|bank):(all|[\d,]+)$/i) { + return ("Invalid argument '$value'"); + } } - if ( $command eq 'network'){ - my ( $adapter_name, $ip, $host, $gateway, $netmask) = - split /,/, $value; - return ( "Network interface name is required") if ( ! $adapter_name); - return ( "Invalide network interface name $adapter_name") if ( $adapter_name !~ /^eth\d$/); - return undef if ( $ip eq '*'); - return ( "Invalid IP address format") if ( $ip and $ip !~ /\d+\.\d+\.\d+\.\d+/); - return ( "Invalid netmask format") if ( $netmask and $netmask !~ /\d+\.\d+\.\d+\.\d+/); + if ($command eq 'network') { + my ($adapter_name, $ip, $host, $gateway, $netmask) = + split /,/, $value; + return ("Network interface name is required") if (!$adapter_name); + return ("Invalide network interface name $adapter_name") if ($adapter_name !~ /^eth\d$/); + return undef if ($ip eq '*'); + return ("Invalid IP address format") if ($ip and $ip !~ /\d+\.\d+\.\d+\.\d+/); + return ("Invalid netmask format") if ($netmask and $netmask !~ /\d+\.\d+\.\d+\.\d+/); } - if ( $command eq 'frame' ){ - if ( $value !~ /^\d+$/i && $value ne '*' ) { - return( "Invalid frame number '$value'" ); + if ($command eq 'frame') { + if ($value !~ /^\d+$/i && $value ne '*') { + return ("Invalid frame number '$value'"); } } - if ( $command eq 'admin_passwd' or $command eq 'general_passwd' or $command eq '*_passwd' ){ - my ($passwd,$newpasswd) = split /,/, $value; - if ( !$passwd or !$newpasswd) { - return( "Current password and new password couldn't be empty" ); + if ($command eq 'admin_passwd' or $command eq 'general_passwd' or $command eq '*_passwd') { + my ($passwd, $newpasswd) = split /,/, $value; + if (!$passwd or !$newpasswd) { + return ("Current password and new password couldn't be empty"); } } - if ( $command eq 'HMC_passwd' ) { - my ($passwd,$newpasswd) = split /,/, $value; - if ( !$newpasswd ) { - return( "New password couldn't be empty for user 'HMC'" ); + if ($command eq 'HMC_passwd') { + my ($passwd, $newpasswd) = split /,/, $value; + if (!$newpasswd) { + return ("New password couldn't be empty for user 'HMC'"); } } - - if ( $command eq 'dev' or $command eq 'celogin1' ) { - if ($value !~ /^(enable|disable)$/i ) { - return( "Invalid argument '$value'" ); - } - $request->{dev} = 1; + + if ($command eq 'dev' or $command eq 'celogin1') { + if ($value !~ /^(enable|disable)$/i) { + return ("Invalid argument '$value'"); + } + $request->{dev} = 1; } else { - $request->{other} = 1; + $request->{other} = 1; } return undef; } @@ -346,13 +347,13 @@ sub passwd { my $result; my $users; - foreach my $arg ( @$args ) { - my ($user,$value) = split /=/, $arg; - my ($passwd,$newpasswd) = split /,/, $value; + foreach my $arg (@$args) { + my ($user, $value) = split /=/, $arg; + my ($passwd, $newpasswd) = split /,/, $value; $user =~ s/_passwd$//; $user =~ s/^HMC$/access/g; - if ( $user eq "*" ) { + if ($user eq "*") { push @$users, "access"; push @$users, "admin"; push @$users, "general"; @@ -360,30 +361,30 @@ sub passwd { push @$users, $user; } - foreach my $usr ( @$users ) { - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($node,$d) = each(%$h) ) { + foreach my $usr (@$users) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($node, $d) = each(%$h)) { my $type = @$d[4]; xCAT::MsgUtils->verbose_message($request, "rspconfig :modify password of $usr for node:$node."); - my $data = xCAT::PPCcli::chsyspwd( $exp, $usr, $type, $cec, $passwd, $newpasswd ); - my $Rc = shift(@$data); + my $data = xCAT::PPCcli::chsyspwd($exp, $usr, $type, $cec, $passwd, $newpasswd); + my $Rc = shift(@$data); my $usr_back = $usr; $usr_back =~ s/^access$/HMC/g; - push @$result, [$node,"$usr_back: @$data[0]",$Rc]; - + push @$result, [ $node, "$usr_back: @$data[0]", $Rc ]; + ################################## # Write the new password to table ################################## - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { xCAT::MsgUtils->verbose_message($request, "rspconfig :update xCATdb for node:$node,ID:$usr_back."); - xCAT::PPCdb::update_credentials( $node, $type, $usr_back, $newpasswd ); + xCAT::PPCdb::update_credentials($node, $type, $usr_back, $newpasswd); } } } } } - return( [@$result] ); + return ([@$result]); } ########################################################################## @@ -397,23 +398,23 @@ sub cfg { my $args = $request->{arg}; my $result; - foreach ( @$args ) { + foreach (@$args) { ################################## # Ignore switches in command-line ################################## - unless ( /^-/ ) { - my ($cmd,$value) = split /=/; + unless (/^-/) { + my ($cmd, $value) = split /=/; no strict 'refs'; - $result = $rspconfig{$cmd}( $request, $exp, $value, $hash ); + $result = $rspconfig{$cmd}($request, $exp, $value, $hash); use strict; } } - return( $result ); + return ($result); } ########################################################################## -# Enables/disables/displays SSH access to HMC/IVM +# Enables/disables/displays SSH access to HMC/IVM ########################################################################## sub sshcfg { my $request = shift; @@ -421,15 +422,15 @@ sub sshcfg { my $mode = shift; my $server = @$exp[3]; my $userid = @$exp[4]; - my $fname = ((xCAT::Utils::isAIX()) ? "/.ssh/":"/root/.ssh/")."id_rsa.pub"; - my $auth = "/home/$userid/.ssh/authorized_keys2"; + my $fname = ((xCAT::Utils::isAIX()) ? "/.ssh/" : "/root/.ssh/") . "id_rsa.pub"; + my $auth = "/home/$userid/.ssh/authorized_keys2"; ##################################### # Get SSH key on Management Node ##################################### - unless ( open(RSAKEY,"<$fname") ) { - return( [[$server,"Error opening '$fname'",RC_ERROR]] ); - } + unless (open(RSAKEY, "<$fname")) { + return ([ [ $server, "Error opening '$fname'", RC_ERROR ] ]); + } my ($sshkey) = ; close(RSAKEY); @@ -442,47 +443,47 @@ sub sshcfg { my $logon = $1; ##################################### - # Determine if SSH is enabled + # Determine if SSH is enabled ##################################### - if ( !defined( $mode )) { - my ($keytype, $key_string) = split /\ /, $sshkey; + if (!defined($mode)) { + my ($keytype, $key_string) = split /\ /, $sshkey; chomp($key_string); xCAT::MsgUtils->verbose_message($request, "rspconfig :check sshcfg for user:$logon on node:$server."); - my $result = xCAT::PPCcli::send_cmd( $exp, "cat $auth" ); - my $Rc = shift(@$result); + my $result = xCAT::PPCcli::send_cmd($exp, "cat $auth"); + my $Rc = shift(@$result); ################################# - # Return error + # Return error ################################# - if ( $Rc != SUCCESS ) { - return( [[$server,@$result[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $server, @$result[0], $Rc ] ]); } ################################# - # Find logon in key file + # Find logon in key file ################################# - foreach ( @$result ) { + foreach (@$result) { my ($tmp1, $tmp2) = split /\ /, $_; chomp($tmp2); - if ( "$tmp2" eq "$key_string" ) { - return( [[$server,"enabled",SUCCESS]] ); + if ("$tmp2" eq "$key_string") { + return ([ [ $server, "enabled", SUCCESS ] ]); } } - return( [[$server,"disabled",SUCCESS]] ); + return ([ [ $server, "disabled", SUCCESS ] ]); } ##################################### - # Enable/disable SSH + # Enable/disable SSH ##################################### xCAT::MsgUtils->verbose_message($request, "rspconfig :sshcfg $mode for user:$logon on node:$server."); - my $result = xCAT::PPCcli::mkauthkeys( $exp, $mode, $logon, $sshkey ); + my $result = xCAT::PPCcli::mkauthkeys($exp, $mode, $logon, $sshkey); my $Rc = shift(@$result); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - return( [[$server,@$result[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $server, @$result[0], $Rc ] ]); } - return( [[$server,lc($mode."d"),SUCCESS]] ); + return ([ [ $server, lc($mode . "d"), SUCCESS ] ]); } sub frame { @@ -492,14 +493,14 @@ sub frame { my $hash = shift; my $arg = $request->{arg}; - foreach ( @$arg ) { + foreach (@$arg) { my $result; my $Rc; my $data; my ($cmd, $value) = split /=/, $_; - if ( $cmd ne "frame" ) { - return( [[@$exp[2],"Multiple option $cmd and frame is not accepted",SUCCESS]] ); + if ($cmd ne "frame") { + return ([ [ @$exp[2], "Multiple option $cmd and frame is not accepted", SUCCESS ] ]); } ################################# @@ -507,58 +508,58 @@ sub frame { # the frame number between hcp # and database ################################# - my $tab = xCAT::Table->new( "ppc" ); + my $tab = xCAT::Table->new("ppc"); - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($node,$d) = each(%$h) ) { - if ( !defined($value) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($node, $d) = each(%$h)) { + if (!defined($value)) { ################################# # Get frame number ################################# xCAT::MsgUtils->verbose_message($request, "rspconfig :get frame_num for node:$node."); - $data = xCAT::PPCcli::lssyscfg( $exp, @$d[4], @$d[2], 'frame_num' ); + $data = xCAT::PPCcli::lssyscfg($exp, @$d[4], @$d[2], 'frame_num'); $Rc = shift(@$data); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - return( [[$node,@$data[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $node, @$data[0], $Rc ] ]); } - push @$result, [$node,@$data[0],SUCCESS]; + push @$result, [ $node, @$data[0], SUCCESS ]; ################################# # Set frame number to database ################################# - $tab->setNodeAttribs( $node, { id=>@$data[0] } ); + $tab->setNodeAttribs($node, { id => @$data[0] }); - } elsif ( $value eq '*' ) { + } elsif ($value eq '*') { ################################# # Set frame number - # Read the settings from database + # Read the settings from database ################################# - my $ent=$tab->getNodeAttribs( $node,['id'] ); + my $ent = $tab->getNodeAttribs($node, ['id']); ################################# # Return error ################################# - if ( !defined($ent) or !defined($ent->{id}) ) { - return( [[$node,"Cannot find frame num in database",RC_ERROR]] ); + if (!defined($ent) or !defined($ent->{id})) { + return ([ [ $node, "Cannot find frame num in database", RC_ERROR ] ]); } - xCAT::MsgUtils->verbose_message($request, "rspconfig :set frame_num=".$ent->{id}." for node:$node."); - $data = xCAT::PPCcli::chsyscfg( $exp, "bpa", $d, "frame_num=".$ent->{id} ); + xCAT::MsgUtils->verbose_message($request, "rspconfig :set frame_num=" . $ent->{id} . " for node:$node."); + $data = xCAT::PPCcli::chsyscfg($exp, "bpa", $d, "frame_num=" . $ent->{id}); $Rc = shift(@$data); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - return( [[$node,@$data[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $node, @$data[0], $Rc ] ]); } - push @$result, [$node,@$data[0],SUCCESS]; + push @$result, [ $node, @$data[0], SUCCESS ]; } else { ################################# @@ -566,28 +567,28 @@ sub frame { # Read the frame number from opt ################################# xCAT::MsgUtils->verbose_message($request, "rspconfig :set frame_num=$value for node:$node."); - $data = xCAT::PPCcli::chsyscfg( $exp, "bpa", $d, "frame_num=$value" ); + $data = xCAT::PPCcli::chsyscfg($exp, "bpa", $d, "frame_num=$value"); $Rc = shift(@$data); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - return( [[$node,@$data[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $node, @$data[0], $Rc ] ]); } - push @$result, [$node,@$data[0],SUCCESS]; + push @$result, [ $node, @$data[0], SUCCESS ]; ################################# # Set frame number to database ################################# xCAT::MsgUtils->verbose_message($request, "rspconfig : set frame_num, update node:$node attr id=$value."); - $tab->setNodeAttribs( $node, { id=>$value } ); + $tab->setNodeAttribs($node, { id => $value }); } } - return( [@$result] ); - } + return ([@$result]); + } } } @@ -599,65 +600,65 @@ sub hostname { my $arg = $request->{arg}; my $result; - foreach ( @$arg ) { + foreach (@$arg) { my $data; my $Rc; my ($cmd, $value) = split /=/, $_; - if ( $cmd ne "hostname" ) { - return( [[@$exp[2],"Multiple option $cmd and hostname is not accepted",SUCCESS]] ); + if ($cmd ne "hostname") { + return ([ [ @$exp[2], "Multiple option $cmd and hostname is not accepted", SUCCESS ] ]); } - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($node,$d) = each(%$h) ) { - if ( !defined($value) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($node, $d) = each(%$h)) { + if (!defined($value)) { ################################# # Get system name ################################# xCAT::MsgUtils->verbose_message($request, "rspconfig :get system name for node:$node."); - $data = xCAT::PPCcli::lssyscfg( $exp, @$d[4], @$d[2], 'name' ); + $data = xCAT::PPCcli::lssyscfg($exp, @$d[4], @$d[2], 'name'); $Rc = shift(@$data); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - push @$result, [$node,@$data[0],$Rc]; + if ($Rc != SUCCESS) { + push @$result, [ $node, @$data[0], $Rc ]; } - push @$result, [$node,@$data[0],SUCCESS]; - } elsif ( $value eq '*' ) { + push @$result, [ $node, @$data[0], SUCCESS ]; + } elsif ($value eq '*') { xCAT::MsgUtils->verbose_message($request, "rspconfig :set system name:$node for node:$node."); - $data = xCAT::PPCcli::chsyscfg( $exp, @$d[4], $d, "new_name=$node" ); + $data = xCAT::PPCcli::chsyscfg($exp, @$d[4], $d, "new_name=$node"); $Rc = shift(@$data); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - push @$result, [$node,@$data[0],$Rc]; + if ($Rc != SUCCESS) { + push @$result, [ $node, @$data[0], $Rc ]; } - push @$result, [$node,@$data[0],SUCCESS]; + push @$result, [ $node, @$data[0], SUCCESS ]; } else { xCAT::MsgUtils->verbose_message($request, "rspconfig :set system name:$value for node:$node."); - $data = xCAT::PPCcli::chsyscfg( $exp, @$d[4], $d, "new_name=$value" ); + $data = xCAT::PPCcli::chsyscfg($exp, @$d[4], $d, "new_name=$value"); $Rc = shift(@$data); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - push @$result, [$node,@$data[0],$Rc]; + if ($Rc != SUCCESS) { + push @$result, [ $node, @$data[0], $Rc ]; } - push @$result, [$node,@$data[0],SUCCESS]; + push @$result, [ $node, @$data[0], SUCCESS ]; } } } } - return( [@$result] ); + return ([@$result]); } ########################################################################## # Do resetnet public entry @@ -680,194 +681,201 @@ sub doresetnet { my %oihash; my %machash; my %vpdhash; - - unless ($req) { - send_msg( $req, 1, "request is empty, return" ); - return; - } + + unless ($req) { + send_msg($req, 1, "request is empty, return"); + return; + } ########################################### # prepare to reset network ########################################### xCAT::MsgUtils->verbose_message($req, "rspconfig :do resetnet begin to phase nodes"); - my $hoststab = xCAT::Table->new( 'hosts' ); - if ( !$hoststab ) { - send_msg( $req, 1, "Error open hosts table" ); + my $hoststab = xCAT::Table->new('hosts'); + if (!$hoststab) { + send_msg($req, 1, "Error open hosts table"); return; } else { - my @hostslist = $hoststab->getAllNodeAttribs(['node','otherinterfaces']); - foreach my $otherentry ( @hostslist) { - $oihash{$otherentry->{node}} = $otherentry->{otherinterfaces}; + my @hostslist = $hoststab->getAllNodeAttribs([ 'node', 'otherinterfaces' ]); + foreach my $otherentry (@hostslist) { + $oihash{ $otherentry->{node} } = $otherentry->{otherinterfaces}; } - } - - my $mactab = xCAT::Table->new( 'mac' ); - if ( !$mactab ) { - send_msg( $req, 1, "Error open mac table" ); + } + + my $mactab = xCAT::Table->new('mac'); + if (!$mactab) { + send_msg($req, 1, "Error open mac table"); return; - }else{ - my @maclist = $mactab->getAllNodeAttribs(['node','mac']); + } else { + my @maclist = $mactab->getAllNodeAttribs([ 'node', 'mac' ]); foreach my $macentry (@maclist) { - $machash{$macentry->{node}} = $macentry->{mac}; + $machash{ $macentry->{node} } = $macentry->{mac}; } } $mactab = (); - my $vpdtab = xCAT::Table->new( 'vpd' ); - if ( !$vpdtab ) { - send_msg( $req, 1, "Error open vpd table" ); + my $vpdtab = xCAT::Table->new('vpd'); + if (!$vpdtab) { + send_msg($req, 1, "Error open vpd table"); return; } else { - my @vpdlist = $vpdtab->getAllNodeAttribs(['node','mtm','serial','side']); + my @vpdlist = $vpdtab->getAllNodeAttribs([ 'node', 'mtm', 'serial', 'side' ]); foreach my $vpdentry (@vpdlist) { if ($vpdentry->{side} =~ /(\w)\-\w/) { my $side = $1; - $vpdhash{$vpdentry->{node}} = $vpdentry->{mtm}."*".$vpdentry->{serial}."*".$side; - } + $vpdhash{ $vpdentry->{node} } = $vpdentry->{mtm} . "*" . $vpdentry->{serial} . "*" . $side; + } } - } + } $vpdtab = (); - unless ( $req->{node} ) { - send_msg( $req, 0, "no node specified" ); + unless ($req->{node}) { + send_msg($req, 0, "no node specified"); return; } ########################################### # Process nodes and get network information ########################################### my $nodetype = $req->{hwtype}; - if ( $nodetype =~ /^(cec|frame)$/ ) { + if ($nodetype =~ /^(cec|frame)$/) { + # this brunch is just for the xcat 2.6(or 2.6+) database - foreach my $nn ( @{ $req->{node}} ) { + foreach my $nn (@{ $req->{node} }) { my $cnodep = xCAT::DBobjUtils->getchildren($nn); - $nodetype = ( $nodetype =~ /^frame$/i ) ? "bpa" : "fsp"; + $nodetype = ($nodetype =~ /^frame$/i) ? "bpa" : "fsp"; if ($cnodep) { foreach my $cnode (@$cnodep) { - my $ip = xCAT::NetworkUtils::getNodeIPaddress( $cnode ); + my $ip = xCAT::NetworkUtils::getNodeIPaddress($cnode); my $oi = $oihash{$cnode}; - if(!defined $ip) { + if (!defined $ip) { send_msg($req, "doresetnet: can't get $cnode ip"); next; - } - if(!defined $oi) { + } + if (!defined $oi) { send_msg($req, "doresetnet: can't get $cnode hosts.otherinterfaces"); next; } - if ( exists($oihash{$cnode}) and $ip eq $oihash{$cnode}) { - send_msg( $req, 0, "$cnode: same ip address, skipping $nn network reset" ); - } elsif( ! exists $machash{$cnode}){ - send_msg( $req, 0, "$cnode: no mac defined, skipping $nn network reset" ); + if (exists($oihash{$cnode}) and $ip eq $oihash{$cnode}) { + send_msg($req, 0, "$cnode: same ip address, skipping $nn network reset"); + } elsif (!exists $machash{$cnode}) { + send_msg($req, 0, "$cnode: no mac defined, skipping $nn network reset"); } else { $iphash{$cnode}{sip} = $ip; $iphash{$cnode}{tip} = $oihash{$cnode}; - if(exists $grouphash{$vpdhash{$cnode}}) { - $grouphash{$vpdhash{$cnode}} .= ",$cnode"; + if (exists $grouphash{ $vpdhash{$cnode} }) { + $grouphash{ $vpdhash{$cnode} } .= ",$cnode"; } else { - $grouphash{$vpdhash{$cnode}} = "$cnode"; + $grouphash{ $vpdhash{$cnode} } = "$cnode"; } $targets->{$nodetype}->{$ip}->{'args'} = "0.0.0.0,$cnode"; $targets->{$nodetype}->{$ip}->{'mac'} = $machash{$cnode}; $targets->{$nodetype}->{$ip}->{'name'} = $cnode; - $targets->{$nodetype}->{$ip}->{'ip'} = $ip; + $targets->{$nodetype}->{$ip}->{'ip'} = $ip; $targets->{$nodetype}->{$ip}->{'type'} = $nodetype; - my %netinfo = xCAT::DBobjUtils->getNetwkInfo( [$ip] ); + my %netinfo = xCAT::DBobjUtils->getNetwkInfo([$ip]); $targets->{$nodetype}->{$ip}->{'args'} .= ",$netinfo{$ip}{'gateway'},$netinfo{$ip}{'mask'}"; + #xCAT::MsgUtils->verbose_message($req, "doresetnet: get node $cnode info $targets->{$nodetype}->{$ip}->{'args'}, ip is $ip"); $targets->{$nodetype}->{$oi}->{'args'} = "0.0.0.0,$cnode"; $targets->{$nodetype}->{$oi}->{'mac'} = $machash{$cnode}; $targets->{$nodetype}->{$oi}->{'name'} = $cnode; - $targets->{$nodetype}->{$oi}->{'ip'} = $oi; + $targets->{$nodetype}->{$oi}->{'ip'} = $oi; $targets->{$nodetype}->{$oi}->{'type'} = $nodetype; - %netinfo = xCAT::DBobjUtils->getNetwkInfo( [$oi] ); + %netinfo = xCAT::DBobjUtils->getNetwkInfo([$oi]); $targets->{$nodetype}->{$oi}->{'args'} .= ",$netinfo{$oi}{'gateway'},$netinfo{$oi}{'mask'}"; + #xCAT::MsgUtils->verbose_message($req, "doresetnet: get node $cnode info $targets->{$nodetype}->{$oi}->{'args'}, oi is $oi"); } } } else { - send_msg( $req, 1, "Can't get the fsp/bpa nodes for the $nn" ); + send_msg($req, 1, "Can't get the fsp/bpa nodes for the $nn"); return; - } - } - # this brunch is just for the xcat 2.5(or 2.5-) databse - } elsif ( $nodetype =~ /^(fsp|bpa)$/ ) { - foreach my $nn ( @{ $req->{node}} ) { - my $ip = xCAT::NetworkUtils::getNodeIPaddress( $nn ); - if(!defined $ip) { + } + } + + # this brunch is just for the xcat 2.5(or 2.5-) databse + } elsif ($nodetype =~ /^(fsp|bpa)$/) { + foreach my $nn (@{ $req->{node} }) { + my $ip = xCAT::NetworkUtils::getNodeIPaddress($nn); + if (!defined $ip) { send_msg($req, "doresetnet: can't get $nn ip"); next; - } - if(!exists $oihash{$nn}) { + } + if (!exists $oihash{$nn}) { send_msg($req, "doresetnet: can't get $nn hosts.otherinterfaces"); next; } my $oi = $oihash{$nn}; - if( exists($oihash{$nn}) and $ip eq $oihash{$nn}) { - send_msg( $req, 0, "$nn: same ip address, skipping network reset" ); - } elsif (!exists $machash{$nn}){ - send_msg( $req, 0, "$nn: no mac defined, skipping network reset" ); + if (exists($oihash{$nn}) and $ip eq $oihash{$nn}) { + send_msg($req, 0, "$nn: same ip address, skipping network reset"); + } elsif (!exists $machash{$nn}) { + send_msg($req, 0, "$nn: no mac defined, skipping network reset"); } else { $iphash{$nn}{sip} = $ip; $iphash{$nn}{tip} = $oihash{$nn}; - if(exists $grouphash{$vpdhash{$nn}}) { - $grouphash{$vpdhash{$nn}} .= ",$nn"; + if (exists $grouphash{ $vpdhash{$nn} }) { + $grouphash{ $vpdhash{$nn} } .= ",$nn"; } else { - $grouphash{$vpdhash{$nn}} = "$nn"; + $grouphash{ $vpdhash{$nn} } = "$nn"; } $targets->{$nodetype}->{$ip}->{'args'} = "0.0.0.0,$nn"; - $targets->{$nodetype}->{$ip}->{'mac'} = $machash{$nn}; + $targets->{$nodetype}->{$ip}->{'mac'} = $machash{$nn}; $targets->{$nodetype}->{$ip}->{'name'} = $nn; - $targets->{$nodetype}->{$ip}->{'ip'} = $ip; + $targets->{$nodetype}->{$ip}->{'ip'} = $ip; $targets->{$nodetype}->{$ip}->{'type'} = $nodetype; - my %netinfo = xCAT::DBobjUtils->getNetwkInfo( [$ip] ); + my %netinfo = xCAT::DBobjUtils->getNetwkInfo([$ip]); $targets->{$nodetype}->{$ip}->{'args'} .= ",$netinfo{$ip}{'gateway'},$netinfo{$ip}{'mask'}"; + #xCAT::MsgUtils->verbose_message($req, "doresetnet: get node $nn info $targets->{$nodetype}->{$ip}->{'args'},ip is $ip"); $targets->{$nodetype}->{$oi}->{'args'} = "0.0.0.0,$nn"; - $targets->{$nodetype}->{$oi}->{'mac'} = $machash{$nn}; + $targets->{$nodetype}->{$oi}->{'mac'} = $machash{$nn}; $targets->{$nodetype}->{$oi}->{'name'} = $nn; - $targets->{$nodetype}->{$oi}->{'ip'} = $oi; + $targets->{$nodetype}->{$oi}->{'ip'} = $oi; $targets->{$nodetype}->{$oi}->{'type'} = $nodetype; - %netinfo = xCAT::DBobjUtils->getNetwkInfo( [$oi] ); + %netinfo = xCAT::DBobjUtils->getNetwkInfo([$oi]); $targets->{$nodetype}->{$oi}->{'args'} .= ",$netinfo{$oi}{'gateway'},$netinfo{$oi}{'mask'}"; + #xCAT::MsgUtils->verbose_message($req, "doresetnet: get node $nn info $targets->{$nodetype}->{$oi}->{'args'}, oi is $oi"); } - } - } elsif ( !$nodetype ){ - send_msg( $req, 0, "no nodetype defined, skipping network reset" ); + } + } elsif (!$nodetype) { + send_msg($req, 0, "no nodetype defined, skipping network reset"); return; } else { - send_msg( $req, 0, "$nodetype not supported, skipping network reset" ); + send_msg($req, 0, "$nodetype not supported, skipping network reset"); return; } - + unless (%grouphash) { - send_msg( $req, 0, "Failed to group the nodes, skipping network reset" ); + send_msg($req, 0, "Failed to group the nodes, skipping network reset"); return; - } + } ########################################### # Update target hardware w/discovery info ########################################### - my %rsp_dev = get_rsp_dev( $req, $targets); - + my %rsp_dev = get_rsp_dev($req, $targets); + ###################################################### # Start to reset network. Fork one process per BPA/FSP ###################################################### %oihash = (); %machash = (); %vpdhash = (); - $start = Time::HiRes::gettimeofday(); + $start = Time::HiRes::gettimeofday(); my $children = 0; $SIG{CHLD} = sub { while (waitpid(-1, WNOHANG) > 0) { $children--; } }; - my $fds = new IO::Select; - my $callback = $req->{callback}; - my $ij = 0; - foreach my $node ( keys %grouphash) { + my $fds = new IO::Select; + my $callback = $req->{callback}; + my $ij = 0; + + foreach my $node (keys %grouphash) { my %iphashfornode; my $gc = $grouphash{$node}; my %rsp_devfornode; foreach my $tn (split /,/, $gc) { $iphashfornode{$tn} = $iphash{$tn}; - for my $ti (keys %{$iphash{$tn}}){ + for my $ti (keys %{ $iphash{$tn} }) { my $tip = $iphash{$tn}{$ti}; $rsp_devfornode{$tip} = $rsp_dev{$tip}; } @@ -878,9 +886,9 @@ sub doresetnet { # Begin fork ###################################################### my $pipe; - my $rspdevref = \%rsp_devfornode; + my $rspdevref = \%rsp_devfornode; my $grouphashref = $gc; - my $iphashref = \%iphashfornode; + my $iphashref = \%iphashfornode; my $result; my @data = ("RSPCONFIG6sK4ci"); @@ -890,92 +898,94 @@ sub doresetnet { my $parent; my $child; pipe $parent, $child; - $ij ++; - $ij = int($ij%60); + $ij++; + $ij = int($ij % 60); my $pid = xCAT::Utils->xfork(); - if ( !defined($pid) ) { + if (!defined($pid)) { ################################### # Fork error ################################### - send_msg( $req, 1, "Fork error: $!" ); + send_msg($req, 1, "Fork error: $!"); return undef; } - elsif ( $pid == 0 ) { + elsif ($pid == 0) { sleep $ij; ################################### # Child process, clear memory first ################################### - %rsp_dev = (); + %rsp_dev = (); %grouphash = (); - %iphash = (); - close( $parent ); + %iphash = (); + close($parent); $req->{pipe} = $child; - my $msgs; - my $report; + my $msgs; + my $report; + #try and try to avoid the fail that caused by refreshing IP when doing resetnet - my $time = 0; - while (1) { - my $erflag = 0; - $msgs = child_process($grouphashref, $iphashref, $rspdevref, $req, $node ); - foreach my $port (keys %$msgs){ + my $time = 0; + while (1) { + my $erflag = 0; + $msgs = child_process($grouphashref, $iphashref, $rspdevref, $req, $node); + foreach my $port (keys %$msgs) { unless ($msgs->{$port} =~ /successful/) { $erflag = 1; - last; - } - } - if ($erflag) { - $report = (); - foreach my $port1 (keys %$msgs){ - $report .= $port1.":".$msgs->{$port1}.";"; + last; } - xCAT::MsgUtils->verbose_message($req, "========> try again, $report"); - #send_msg( $req, 0, "========> try again, $report"); - sleep 3; - $time++; - } else { + } + if ($erflag) { + $report = (); + foreach my $port1 (keys %$msgs) { + $report .= $port1 . ":" . $msgs->{$port1} . ";"; + } + xCAT::MsgUtils->verbose_message($req, "========> try again, $report"); + + #send_msg( $req, 0, "========> try again, $report"); + sleep 3; + $time++; + } else { last; } - last if ($time > 10); - } - $report = (); - foreach my $port (keys %$msgs){ - $report .= $port.":".$msgs->{$port}.";"; + last if ($time > 10); } - send_msg( $req, 0, "Resetnet result for $node is : $report"); + $report = (); + foreach my $port (keys %$msgs) { + $report .= $port . ":" . $msgs->{$port} . ";"; + } + send_msg($req, 0, "Resetnet result for $node is : $report"); #################################### # Pass result array back to parent #################################### my %data; - $data{errorcode} = 0; + $data{errorcode} = 0; my $out = $req->{pipe}; - print $out freeze( [\%data] ); + print $out freeze([ \%data ]); print $out "\nENDOFFREEZE6sK4ci\n"; exit(0); } else { ################################### # Parent process ################################### - close( $child ); - $pipe = $parent ; + close($child); + $pipe = $parent; } - if ( $pipe ) { - $fds->add( $pipe ); + if ($pipe) { + $fds->add($pipe); $children++; } } ############################################# # Process responses from children ############################################# - while ( $children > 0 ) { - child_response( $callback, $fds ); + while ($children > 0) { + child_response($callback, $fds); } - while (child_response($callback,$fds)) {} + while (child_response($callback, $fds)) { } my $elapsed = Time::HiRes::gettimeofday() - $start; - my $msg = sprintf( "Total rspconfig Time: %.3f sec\n", $elapsed ); + my $msg = sprintf("Total rspconfig Time: %.3f sec\n", $elapsed); xCAT::MsgUtils->verbose_message($req, $msg); return undef; @@ -985,10 +995,10 @@ sub doresetnet { ########################################################################## sub child_process { my $grouphashref = shift; - my $iphashref = shift; - my $rspdevref = shift; - my $req = shift; - my $node = shift; + my $iphashref = shift; + my $rspdevref = shift; + my $req = shift; + my $node = shift; my %msginfo; my @ns = split /,/, $grouphashref; my @valid_ips; @@ -999,38 +1009,38 @@ sub child_process { # ping static ip firstly, if succesufully, skip resetnet ########################################################## foreach my $fspport (@ns) { - my $ip = ${$iphashref->{$fspport}}{sip}; + my $ip = ${ $iphashref->{$fspport} }{sip}; my $rc = system("ping -q -n -c 1 -w 1 $ip > /dev/null"); if ($rc == 0) { - xCAT::MsgUtils->verbose_message( $req, "ping static $ip successfully"); - push @valid_ips, $ip; # static ip should be used first + xCAT::MsgUtils->verbose_message($req, "ping static $ip successfully"); + push @valid_ips, $ip; # static ip should be used first push @portsuccess, $fspport; $msginfo{$fspport} = "successful"; } else { - xCAT::MsgUtils->verbose_message( $req, "ping static $ip failed, need to do resetnet for $fspport"); + xCAT::MsgUtils->verbose_message($req, "ping static $ip failed, need to do resetnet for $fspport"); push @portneedreset, $fspport; } } - if (scalar (@portneedreset) == 0) { + if (scalar(@portneedreset) == 0) { return \%msginfo; } ########################################### # ping temp ip secondary ########################################### foreach my $fspport (@ns) { - my $ip = ${$iphashref->{$fspport}}{tip}; + my $ip = ${ $iphashref->{$fspport} }{tip}; my $rc = system("ping -q -n -c 1 -w 1 $ip > /dev/null"); if ($rc == 0) { push @valid_ips, $ip; - xCAT::MsgUtils->verbose_message( $req, "ping temp $ip successfully"); + xCAT::MsgUtils->verbose_message($req, "ping temp $ip successfully"); } else { - xCAT::MsgUtils->verbose_message( $req, "ping temp $ip failed"); + xCAT::MsgUtils->verbose_message($req, "ping temp $ip failed"); } } - if (scalar (@valid_ips) == 0) { + if (scalar(@valid_ips) == 0) { foreach my $fspport (@ns) { - $msginfo{$fspport} = "failed to find valid ip to log on"; - } + $msginfo{$fspport} = "failed to find valid ip to log on"; + } return \%msginfo; } ######################################### @@ -1039,119 +1049,119 @@ sub child_process { my @exp; my $goodip; my $retry = 2; - foreach my $ip(@valid_ips) { - @exp = xCAT::PPCcfg::connect(${$rspdevref->{$ip}}{username},${$rspdevref->{$ip}}{password}, $ip); + foreach my $ip (@valid_ips) { + @exp = xCAT::PPCcfg::connect(${ $rspdevref->{$ip} }{username}, ${ $rspdevref->{$ip} }{password}, $ip); #################################### # Successfully connected #################################### - if ( ref($exp[0]) eq "LWP::UserAgent" ) { - $goodip = $ip; - xCAT::MsgUtils->verbose_message( $req, "log in successfully with $ip"); - last; - } + if (ref($exp[0]) eq "LWP::UserAgent") { + $goodip = $ip; + xCAT::MsgUtils->verbose_message($req, "log in successfully with $ip"); + last; } - my $msg = "login result is :".join(',', @exp); - xCAT::MsgUtils->verbose_message( $req, $msg); + } + my $msg = "login result is :" . join(',', @exp); + xCAT::MsgUtils->verbose_message($req, $msg); #################################### # do resetnet #################################### unless ($goodip) { foreach my $fspport (@ns) { - $msginfo{$fspport} = "failed to log on with $exp[0]"; - } + $msginfo{$fspport} = "failed to log on with $exp[0]"; + } return \%msginfo; } my %handled; my $port; - if (scalar(@portneedreset) == 2 ) { ## do resetnet for the other port first - $port = $portneedreset[0]; - my $ip = ${$iphashref->{$port}}{sip}; - if ($goodip eq $ip) { - $port = $portneedreset[1]; - } - xCAT::MsgUtils->verbose_message( $req, "begin to reset for port $port.. good ip is $goodip, ip is $ip...................................."); + if (scalar(@portneedreset) == 2) { ## do resetnet for the other port first + $port = $portneedreset[0]; + my $ip = ${ $iphashref->{$port} }{sip}; + if ($goodip eq $ip) { + $port = $portneedreset[1]; + } + xCAT::MsgUtils->verbose_message($req, "begin to reset for port $port.. good ip is $goodip, ip is $ip...................................."); my $rc = system("ping -q -n -c 1 -w 1 $ip > /dev/null"); - unless ($rc == 0) { - $ip = ${$iphashref->{$port}}{tip}; - $handled{network} = $ip.",".${$rspdevref->{$ip}}{args}; - my @cmds = ("network=$ip,${$rspdevref->{$ip}}{args}"); + unless ($rc == 0) { + $ip = ${ $iphashref->{$port} }{tip}; + $handled{network} = $ip . "," . ${ $rspdevref->{$ip} }{args}; + my @cmds = ("network=$ip,${$rspdevref->{$ip}}{args}"); my %request = ( - ppcretry => 1, - verbose => 0, - ppcmaxp => 64, - ppctimeout => 0, - fsptimeout => 0, - ppcretry => 3, - maxssh => 8, - arg => \@cmds, - method => \%handled, - command => 'rspconfig', - hwtype => ${$rspdevref->{$ip}}{type}, - ); - xCAT::MsgUtils->verbose_message( $req, "Begin to do reset for $port, nic is $ip"); - my $result = xCAT::PPCfsp::handler($ip, \%request, \@exp, 1 ); - if ($result) { - my $errcode = ${@$result[0]}{errorcode}; - if ( $errcode == 0) { - $msginfo{$port} = "successful"; - } else { - my $node = ${@$result[0]}{node}; - $msginfo{$port} = @{${@{${@$node[0]}{data}}[0]}{contents}}[0]; - } - } else { - $msginfo{$port} = "failed with unknown reason"; - } - } else { + ppcretry => 1, + verbose => 0, + ppcmaxp => 64, + ppctimeout => 0, + fsptimeout => 0, + ppcretry => 3, + maxssh => 8, + arg => \@cmds, + method => \%handled, + command => 'rspconfig', + hwtype => ${ $rspdevref->{$ip} }{type}, + ); + xCAT::MsgUtils->verbose_message($req, "Begin to do reset for $port, nic is $ip"); + my $result = xCAT::PPCfsp::handler($ip, \%request, \@exp, 1); + if ($result) { + my $errcode = ${ @$result[0] }{errorcode}; + if ($errcode == 0) { + $msginfo{$port} = "successful"; + } else { + my $node = ${ @$result[0] }{node}; + $msginfo{$port} = @{ ${ @{ ${ @$node[0] }{data} }[0] }{contents} }[0]; + } + } else { + $msginfo{$port} = "failed with unknown reason"; + } + } else { $msginfo{$port} = "successful"; } - } + } if ($port) { - if ($port eq $portneedreset[0] ) { + if ($port eq $portneedreset[0]) { $port = $portneedreset[1]; } else { $port = $portneedreset[0]; } } else { $port = $portneedreset[0]; - } - xCAT::MsgUtils->verbose_message( $req, "begin to reset for port $port......................................"); - my $ip = ${$iphashref->{$port}}{sip}; - my $rc = system("ping -q -n -c 1 -w 1 $ip > /dev/null"); - unless ($rc == 0) { #should be unless!!!!!!!!!!!!! - $ip = ${$iphashref->{$port}}{tip}; - $handled{network} = $ip.",".${$rspdevref->{$ip}}{args}; - my @cmds = ("network=$ip,${$rspdevref->{$ip}}{args}"); - my %request = ( - ppcretry => 1, - verbose => 0, - ppcmaxp => 64, - ppctimeout => 0, - fsptimeout => 0, - ppcretry => 3, - maxssh => 8, - arg => \@cmds, - method => \%handled, - command => 'rspconfig', - hwtype => ${$rspdevref->{$ip}}{type}, - ); - xCAT::MsgUtils->verbose_message( $req, "Begin to do reset for $port, nic is $ip"); - my $result = xCAT::PPCfsp::handler($ip, \%request, \@exp); - if ($result) { - my $errcode = ${@$result[0]}{errorcode}; - if ( $errcode == 0) { - $msginfo{$port} = "successful"; - } else { - my $node = ${@$result[0]}{node}; - $msginfo{$port} = @{${@{${@$node[0]}{data}}[0]}{contents}}[0]; } - } else { - $msginfo{$port} = "failed with unknown reason"; - } - } else { - xCAT::PPCfsp::disconnect( \@exp ); + xCAT::MsgUtils->verbose_message($req, "begin to reset for port $port......................................"); + my $ip = ${ $iphashref->{$port} }{sip}; + my $rc = system("ping -q -n -c 1 -w 1 $ip > /dev/null"); + unless ($rc == 0) { #should be unless!!!!!!!!!!!!! + $ip = ${ $iphashref->{$port} }{tip}; + $handled{network} = $ip . "," . ${ $rspdevref->{$ip} }{args}; + my @cmds = ("network=$ip,${$rspdevref->{$ip}}{args}"); + my %request = ( + ppcretry => 1, + verbose => 0, + ppcmaxp => 64, + ppctimeout => 0, + fsptimeout => 0, + ppcretry => 3, + maxssh => 8, + arg => \@cmds, + method => \%handled, + command => 'rspconfig', + hwtype => ${ $rspdevref->{$ip} }{type}, + ); + xCAT::MsgUtils->verbose_message($req, "Begin to do reset for $port, nic is $ip"); + my $result = xCAT::PPCfsp::handler($ip, \%request, \@exp); + if ($result) { + my $errcode = ${ @$result[0] }{errorcode}; + if ($errcode == 0) { $msginfo{$port} = "successful"; - } + } else { + my $node = ${ @$result[0] }{node}; + $msginfo{$port} = @{ ${ @{ ${ @$node[0] }{data} }[0] }{contents} }[0]; + } + } else { + $msginfo{$port} = "failed with unknown reason"; + } + } else { + xCAT::PPCfsp::disconnect(\@exp); + $msginfo{$port} = "successful"; + } return \%msginfo; } @@ -1163,15 +1173,16 @@ sub get_rsp_dev my $request = shift; my $targets = shift; - my $mm = $targets->{'mm'} ? $targets->{'mm'} : {}; - my $hmc = $targets->{'hmc'} ? $targets->{'hmc'}: {}; - my $fsp = $targets->{'fsp'} ? $targets->{'fsp'}: {}; - my $bpa = $targets->{'bpa'} ? $targets->{'bpa'}: {}; + my $mm = $targets->{'mm'} ? $targets->{'mm'} : {}; + my $hmc = $targets->{'hmc'} ? $targets->{'hmc'} : {}; + my $fsp = $targets->{'fsp'} ? $targets->{'fsp'} : {}; + my $bpa = $targets->{'bpa'} ? $targets->{'bpa'} : {}; if (%$mm) { my $bladeuser = 'USERID'; my $bladepass = 'PASSW0RD'; + #if ( $verbose ) { # trace( $request, "telneting to management-modules....." ); #} @@ -1179,10 +1190,11 @@ sub get_rsp_dev # Check passwd table for userid/password ############################################# my $passtab = xCAT::Table->new('passwd'); - if ( $passtab ) { + if ($passtab) { + #my ($ent) = $passtab->getAttribs({key=>'blade'},'username','password'); - my $ent = $passtab->getNodeAttribs('blade', ['username','password']); - if ( defined( $ent )) { + my $ent = $passtab->getNodeAttribs('blade', [ 'username', 'password' ]); + if (defined($ent)) { $bladeuser = $ent->{username}; $bladepass = $ent->{password}; } @@ -1191,54 +1203,55 @@ sub get_rsp_dev # Get userid/password ############################################# my $mpatab = xCAT::Table->new('mpa'); - for my $nd ( keys %$mm ) { + for my $nd (keys %$mm) { my $user = $bladeuser; my $pass = $bladepass; - if ( defined( $mpatab )) { + if (defined($mpatab)) { + #my ($ent) = $mpatab->getAttribs({mpa=>$_},'username','password'); - my $ent = $mpatab->getNodeAttribs($nd, ['username','password']); - if ( defined( $ent->{password} )) { $pass = $ent->{password}; } - if ( defined( $ent->{username} )) { $user = $ent->{username}; } + my $ent = $mpatab->getNodeAttribs($nd, [ 'username', 'password' ]); + if (defined($ent->{password})) { $pass = $ent->{password}; } + if (defined($ent->{username})) { $user = $ent->{username}; } } $mm->{$nd}->{username} = $user; $mm->{$nd}->{password} = $pass; } } - if (%$hmc ) + if (%$hmc) { ############################################# # Get HMC userid/password ############################################# - foreach ( keys %$hmc ) { - ( $hmc->{$_}->{username}, $hmc->{$_}->{password}) = xCAT::PPCdb::credentials( $hmc->{$_}->{name}, lc($hmc->{$_}->{'type'}), "hscroot" ); - xCAT::MsgUtils->verbose_message( $request, "user/passwd for $_ is $hmc->{$_}->{username} $hmc->{$_}->{password}"); + foreach (keys %$hmc) { + ($hmc->{$_}->{username}, $hmc->{$_}->{password}) = xCAT::PPCdb::credentials($hmc->{$_}->{name}, lc($hmc->{$_}->{'type'}), "hscroot"); + xCAT::MsgUtils->verbose_message($request, "user/passwd for $_ is $hmc->{$_}->{username} $hmc->{$_}->{password}"); } } - if ( %$fsp) + if (%$fsp) { ############################################# # Get FSP userid/password ############################################# - foreach ( keys %$fsp ) { - ( $fsp->{$_}->{username}, $fsp->{$_}->{password}) = xCAT::PPCdb::credentials( $fsp->{$_}->{name}, lc($fsp->{$_}->{'type'}), "admin"); - xCAT::MsgUtils->verbose_message( $request, "user/passwd for $_ is $fsp->{$_}->{username} $fsp->{$_}->{password}"); + foreach (keys %$fsp) { + ($fsp->{$_}->{username}, $fsp->{$_}->{password}) = xCAT::PPCdb::credentials($fsp->{$_}->{name}, lc($fsp->{$_}->{'type'}), "admin"); + xCAT::MsgUtils->verbose_message($request, "user/passwd for $_ is $fsp->{$_}->{username} $fsp->{$_}->{password}"); } } - if ( %$bpa) + if (%$bpa) { ############################################# # Get BPA userid/password ############################################# - foreach ( keys %$bpa ) { - ( $bpa->{$_}->{username}, $bpa->{$_}->{password}) = xCAT::PPCdb::credentials( $bpa->{$_}->{name}, lc($bpa->{$_}->{'type'}), "admin"); - xCAT::MsgUtils->verbose_message( $request, "user/passwd for $_ is $bpa->{$_}->{username} $bpa->{$_}->{password}"); + foreach (keys %$bpa) { + ($bpa->{$_}->{username}, $bpa->{$_}->{password}) = xCAT::PPCdb::credentials($bpa->{$_}->{name}, lc($bpa->{$_}->{'type'}), "admin"); + xCAT::MsgUtils->verbose_message($request, "user/passwd for $_ is $bpa->{$_}->{username} $bpa->{$_}->{password}"); } } - return (%$mm,%$hmc,%$fsp,%$bpa); + return (%$mm, %$hmc, %$fsp, %$bpa); } ########################################################################## # Invokes the callback with the specified message @@ -1252,22 +1265,22 @@ sub send_msg { ################################################# # Called from child process - send to parent ################################################# - if ( exists( $request->{pipe} )) { + if (exists($request->{pipe})) { my $out = $request->{pipe}; $output{errorcode} = $ecode; - $output{data} = \@_; - print $out freeze( [\%output] ); + $output{data} = \@_; + print $out freeze([ \%output ]); print $out "\nENDOFFREEZE6sK4ci\n"; } ################################################# # Called from parent - invoke callback directly ################################################# - elsif ( exists( $request->{callback} )) { + elsif (exists($request->{callback})) { my $callback = $request->{callback}; $output{errorcode} = $ecode; - $output{data} = \@_; - $callback->( \%output ); + $output{data} = \@_; + $callback->(\%output); } } ########################################################################## @@ -1275,8 +1288,8 @@ sub send_msg { ########################################################################## sub child_response { - my $callback = shift; - my $fds = shift; + my $callback = shift; + my $fds = shift; my @ready_fds = $fds->can_read(1); foreach my $rfh (@ready_fds) { @@ -1285,7 +1298,7 @@ sub child_response { ################################# # Read from child process ################################# - if ( defined( $data )) { + if (defined($data)) { while ($data !~ /ENDOFFREEZE6sK4ci/) { $data .= <$rfh>; } @@ -1294,7 +1307,8 @@ sub child_response { ############################# # rspconfig results ############################# - if ( @$responses[0] =~ /^RSPCONFIG6sK4ci$/ ) { + if (@$responses[0] =~ /^RSPCONFIG6sK4ci$/) { + #shift @$responses; #my $ip = @$responses[0]; #my @rsp1 = (@$responses[1]); @@ -1309,8 +1323,8 @@ sub child_response { ############################# # Message or verbose trace ############################# - foreach ( @$responses ) { - $callback->( $_ ); + foreach (@$responses) { + $callback->($_); } next; } @@ -1327,9 +1341,9 @@ sub child_response { sub connect { my $username = shift; - my $passwd = shift; - my $server = shift; - my $verbose = shift; + my $passwd = shift; + my $server = shift; + my $verbose = shift; my $lwp_log; ################################## @@ -1340,10 +1354,10 @@ sub connect { ################################## # Redirect STDERR to variable ################################## - if ( $verbose ) { + if ($verbose) { close STDERR; - if ( !open( STDERR, '>', \$lwp_log )) { - return( "Unable to redirect STDERR: $!" ); + if (!open(STDERR, '>', \$lwp_log)) { + return ("Unable to redirect STDERR: $!"); } } $IO::Socket::SSL::VERSION = undef; @@ -1352,14 +1366,14 @@ sub connect { ################################## # Turn on tracing ################################## - if ( $verbose ) { - LWP::Debug::level( '+' ); + if ($verbose) { + LWP::Debug::level('+'); } ################################## # Create cookie ################################## my $cookie = HTTP::Cookies->new(); - $cookie->set_cookie( 0,'asm_session','0','cgi-bin','','443',0,0,3600,0 ); + $cookie->set_cookie(0, 'asm_session', '0', 'cgi-bin', '', '443', 0, 0, 3600, 0); ################################## # Create UserAgent @@ -1370,24 +1384,24 @@ sub connect { # Set options ################################## my $url = "https://$server/cgi-bin/cgi?form=2"; - $ua->cookie_jar( $cookie ); - $ua->timeout( $timeout ); + $ua->cookie_jar($cookie); + $ua->timeout($timeout); ################################## # Submit logon ################################## - my $res = $ua->post( $url, - [ user => $username, - password => $passwd, - lang => "0", - submit => "Log in" ] + my $res = $ua->post($url, + [ user => $username, + password => $passwd, + lang => "0", + submit => "Log in" ] ); ################################## # Logon failed ################################## - if ( !$res->is_success() ) { - return( $lwp_log.$res->status_line ); + if (!$res->is_success()) { + return ($lwp_log . $res->status_line); } ################################## # To minimize number of GET/POSTs, @@ -1396,7 +1410,7 @@ sub connect { # Set-Cookie: asm_session=3038839768778613290 # ################################## - if ( $res->as_string =~ /Set-Cookie: asm_session=(\d+)/ ) { + if ($res->as_string =~ /Set-Cookie: asm_session=(\d+)/) { ############################## # Successful logon.... # Return: @@ -1405,15 +1419,15 @@ sub connect { # UserId # Redirected STDERR/STDOUT ############################## - return( $ua, - $server, - $username, - \$lwp_log ); + return ($ua, + $server, + $username, + \$lwp_log); } ############################## # Logon error ############################## - $res = $ua->get( $url ); + $res = $ua->get($url); ############################## # Check for specific failures # $res->status_line is like "200 OK" @@ -1421,15 +1435,15 @@ sub connect { # $res->base is like https://41.17.4.2/cgi-bin/cgi?form=2 ############################## my $err; - if ( $res->content =~ /Too many users/i ) { + if ($res->content =~ /Too many users/i) { $err = "Too many users"; - }elsif ( $res->content =~ /Invalid user ID or password/i ) { + } elsif ($res->content =~ /Invalid user ID or password/i) { $err = "Invalid user ID or password"; - }else{ + } else { $err = "Logon failure with unknown reason"; } - return ($lwp_log.$err); + return ($lwp_log . $err); } diff --git a/perl-xCAT/xCAT/PPCcli.pm b/perl-xCAT/xCAT/PPCcli.pm index f625560bc..f128ff341 100644 --- a/perl-xCAT/xCAT/PPCcli.pm +++ b/perl-xCAT/xCAT/PPCcli.pm @@ -3,8 +3,8 @@ package xCAT::PPCcli; use strict; require Exporter; - our @ISA = qw(Exporter); - our @EXPORT_OK = qw(SUCCESS RC_ERROR EXPECT_ERROR NR_ERROR); +our @ISA = qw(Exporter); +our @EXPORT_OK = qw(SUCCESS RC_ERROR EXPECT_ERROR NR_ERROR); use Expect; use xCAT::NetworkUtils; @@ -14,75 +14,75 @@ use xCAT::NetworkUtils; $ENV{'TERM'} = "vt100"; ############################################## -# Constants +# Constants ############################################## use constant { - SUCCESS => 0, - RC_ERROR => 1, - EXPECT_ERROR => 2, - NR_ERROR => 3, - DEFAULT_TIMEOUT => 60 + SUCCESS => 0, + RC_ERROR => 1, + EXPECT_ERROR => 2, + NR_ERROR => 3, + DEFAULT_TIMEOUT => 60 }; ############################################## -# lssyscfg supported formats +# lssyscfg supported formats ############################################## my %lssyscfg = ( - fsp =>"lssyscfg -r sys -m %s -F %s", - cec =>"lssyscfg -r sys -m %s -F %s", - fsps =>"lssyscfg -r sys -F %s", - node =>"lssyscfg -r lpar -m %s -F %s --filter lpar_ids=%s", - lpar =>"lssyscfg -r lpar -m %s -F %s", - lpar2 =>"lssyscfg -r lpar -m %s --filter %s", - bpa =>"lssyscfg -r frame -e %s -F %s", - frame =>"lssyscfg -r frame -e %s -F %s", - bpas =>"lssyscfg -r frame -F %s", - prof =>"lssyscfg -r prof -m %s --filter %s", - profs =>"lssyscfg -r prof -m %s -F %s --filter %s", - cage =>"lssyscfg -r cage -e %s -F %s" + fsp => "lssyscfg -r sys -m %s -F %s", + cec => "lssyscfg -r sys -m %s -F %s", + fsps => "lssyscfg -r sys -F %s", + node => "lssyscfg -r lpar -m %s -F %s --filter lpar_ids=%s", + lpar => "lssyscfg -r lpar -m %s -F %s", + lpar2 => "lssyscfg -r lpar -m %s --filter %s", + bpa => "lssyscfg -r frame -e %s -F %s", + frame => "lssyscfg -r frame -e %s -F %s", + bpas => "lssyscfg -r frame -F %s", + prof => "lssyscfg -r prof -m %s --filter %s", + profs => "lssyscfg -r prof -m %s -F %s --filter %s", + cage => "lssyscfg -r cage -e %s -F %s" ); my %chsyscfg = ( - prof =>"chsyscfg -r prof -m %s -i %s", - bpa =>"chsyscfg -r frame -e %s -i %s", - fsp =>"chsyscfg -r sys -m %s -i %s", - frame =>"chsyscfg -r frame -e %s -i %s", - cec =>"chsyscfg -r sys -m %s -i %s", + prof => "chsyscfg -r prof -m %s -i %s", + bpa => "chsyscfg -r frame -e %s -i %s", + fsp => "chsyscfg -r sys -m %s -i %s", + frame => "chsyscfg -r frame -e %s -i %s", + cec => "chsyscfg -r sys -m %s -i %s", ); ############################################## -# Power control supported formats +# Power control supported formats ############################################## my %powercmd = ( - lpar => { - on =>"chsysstate -r %s -m %s -o on -b norm --id %s -f %s", - of =>"chsysstate -r %s -m %s -o on --id %s -f %s -b of", - sms =>"chsysstate -r %s -m %s -o on --id %s -f %s -b sms", - reset =>"chsysstate -r %s -m %s -o shutdown --id %s --immed --restart", - off =>"chsysstate -r %s -m %s -o shutdown --id %s --immed", - softoff =>"chsysstate -r %s -m %s -o shutdown --id %s", - boot =>"undetermined" }, - sys => { - reset =>"chsysstate -r %s -m %s -o off --immed --restart", - on =>"chsysstate -r %s -m %s -o on", - onstandby =>"chsysstate -r %s -m %s -o onstandby", - off =>"chsysstate -r %s -m %s -o off", - boot =>"undetermined" } + lpar => { + on => "chsysstate -r %s -m %s -o on -b norm --id %s -f %s", + of => "chsysstate -r %s -m %s -o on --id %s -f %s -b of", + sms => "chsysstate -r %s -m %s -o on --id %s -f %s -b sms", + reset => "chsysstate -r %s -m %s -o shutdown --id %s --immed --restart", + off => "chsysstate -r %s -m %s -o shutdown --id %s --immed", + softoff => "chsysstate -r %s -m %s -o shutdown --id %s", + boot => "undetermined" }, + sys => { + reset => "chsysstate -r %s -m %s -o off --immed --restart", + on => "chsysstate -r %s -m %s -o on", + onstandby => "chsysstate -r %s -m %s -o onstandby", + off => "chsysstate -r %s -m %s -o off", + boot => "undetermined" } ); ############################################## # lsrefcode supported formats ############################################## my %lsrefcode = ( - fsp => { - pri =>"lsrefcode -r sys -m %s -s p", - sec =>"lsrefcode -r sys -m %s -s s", - }, - cec => { - pri =>"lsrefcode -r sys -m %s -s p", - sec =>"lsrefcode -r sys -m %s -s s", - }, - lpar =>"lsrefcode -r lpar -m %s --filter lpar_ids=%s", + fsp => { + pri => "lsrefcode -r sys -m %s -s p", + sec => "lsrefcode -r sys -m %s -s s", + }, + cec => { + pri => "lsrefcode -r sys -m %s -s p", + sec => "lsrefcode -r sys -m %s -s s", + }, + lpar => "lsrefcode -r lpar -m %s --filter lpar_ids=%s", ); ############################################## @@ -141,46 +141,46 @@ sub connect { my $ssh; my $expect_log = "/dev/null"; my $errmsg; - + if ($req->{command} eq 'rflash') { - $verbose = 0; + $verbose = 0; } ################################################## - # Use timeout from site table (if defined) + # Use timeout from site table (if defined) ################################################## - if ( !$timeout ) { - $timeout = DEFAULT_TIMEOUT; + if (!$timeout) { + $timeout = DEFAULT_TIMEOUT; } ################################################## - # Shell prompt regexp based on HW Type + # Shell prompt regexp based on HW Type ################################################## my %prompt = ( hmc => "~>\\s*\$", ivm => "\\\$ \$" ); ################################################## - # Get userid/password + # Get userid/password ################################################## - my $cred = $req->{$server}{cred}; + my $cred = $req->{$server}{cred}; my $parameters = "@$cred[0]\@$server"; ################################################## # Redirect STDERR to variable ################################################## - if ( $verbose ) { + if ($verbose) { close STDERR; - if ( !open( STDERR, '>', $expect_log )) { - return( "Unable to redirect STDERR: $!" ); + if (!open(STDERR, '>', $expect_log)) { + return ("Unable to redirect STDERR: $!"); } } ################################################## # Redirect STDOUT to variable ################################################## - if ( $verbose ) { + if ($verbose) { close STDOUT; - if ( !open( STDOUT, '>', $expect_log )) { - return( "Unable to redirect STDOUT: $!" ); + if (!open(STDOUT, '>', $expect_log)) { + return ("Unable to redirect STDOUT: $!"); } } ###################################################### @@ -195,10 +195,10 @@ sub connect { # sending the password. # ###################################################### - while ( $retry-- ) { + while ($retry--) { my $success = 0; my $pwd_sent = 0; - $expect_log = undef; + $expect_log = undef; $ssh = new Expect; @@ -218,41 +218,41 @@ sub connect { # exp_internal(1) sets exp_internal debugging # to STDERR. ################################################## - $ssh->exp_internal( $verbose ); + $ssh->exp_internal($verbose); ################################################## # log_stdout(0) disables logging to STDOUT. # This corresponds to the Tcl log_user variable. ################################################## - $ssh->log_stdout( $verbose ); + $ssh->log_stdout($verbose); - unless ( $ssh->spawn( "ssh", $parameters )) { - return( $expect_log."Unable to spawn ssh connection to server"); + unless ($ssh->spawn("ssh", $parameters)) { + return ($expect_log . "Unable to spawn ssh connection to server"); } - my @result = $ssh->expect( $timeout, + my @result = $ssh->expect($timeout, [ $continue, - sub { - $ssh->send( "yes\r" ); - $ssh->clear_accum(); - $ssh->exp_continue(); - } ], + sub { + $ssh->send("yes\r"); + $ssh->clear_accum(); + $ssh->exp_continue(); + } ], [ $pwd_prompt, - sub { - if ( ++$pwd_sent ) { - $ssh->send( "@$cred[1]\r" ); - $ssh->exp_continue(); - } - } ], + sub { + if (++$pwd_sent) { + $ssh->send("@$cred[1]\r"); + $ssh->exp_continue(); + } + } ], [ $prompt{$hwtype}, - sub { - $success = 1; - } ] + sub { + $success = 1; + } ] ); ########################################## # Expect error - retry ########################################## - if ( defined( $result[1] )) { - $errmsg = $expect_log.expect_error(@result); + if (defined($result[1])) { + $errmsg = $expect_log . expect_error(@result); sleep(1); next; } @@ -268,24 +268,24 @@ sub connect { # Redirected STDERR/STDOUT # Connect/Command timeout ########################################## - if ( $success ) { - return( $ssh, - $prompt{$hwtype}, - $hwtype, - $server, - @$cred[0], - @$cred[1], - \$expect_log, - $timeout ); + if ($success) { + return ($ssh, + $prompt{$hwtype}, + $hwtype, + $server, + @$cred[0], + @$cred[1], + \$expect_log, + $timeout); } ########################################## # Failed logon - kill ssh process ########################################## $ssh->hard_close(); - return( $expect_log."Invalid userid/password" ); + return ($expect_log . "Invalid userid/password"); } $ssh->hard_close(); - return( $errmsg ); + return ($errmsg); } @@ -297,8 +297,8 @@ sub disconnect { my $exp = shift; my $ssh = @$exp[0]; - if ( defined( $ssh )) { - $ssh->send( "exit\r" ); + if (defined($ssh)) { + $ssh->send("exit\r"); $ssh->hard_close(); @$exp[0] = undef; } @@ -317,15 +317,15 @@ sub lssyscfg { my $d3 = shift; ################################### - # Select command + # Select command ################################### - my $cmd = sprintf( $lssyscfg{$res}, $d1, $d2, $d3 ); + my $cmd = sprintf($lssyscfg{$res}, $d1, $d2, $d3); ################################### # Send command ################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } @@ -342,13 +342,13 @@ sub chsyscfg { ##################################### # Select command ##################################### - my $cmd = sprintf( $chsyscfg{$res}, @$d[2], $cfgdata ); + my $cmd = sprintf($chsyscfg{$res}, @$d[2], $cfgdata); ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } ########################################################################## @@ -356,41 +356,41 @@ sub chsyscfg { ########################################################################## sub lsrefcode { - my $exp = shift; - my $res = shift; - my $d1 = shift; - my $d2 = shift; - my $cmd = undef; - my @cmds = undef; + my $exp = shift; + my $res = shift; + my $d1 = shift; + my $d2 = shift; + my $cmd = undef; + my @cmds = undef; my $result = undef; my @values; ################################### - # Select command + # Select command ################################### - if($res =~ /^(fsp|cec)$/) { + if ($res =~ /^(fsp|cec)$/) { $cmds[0] = sprintf($lsrefcode{$res}{pri}, $d1); $cmds[1] = sprintf($lsrefcode{$res}{sec}, $d1); - } elsif($res eq 'lpar'){ + } elsif ($res eq 'lpar') { $cmds[0] = sprintf($lsrefcode{$res}, $d1, $d2); } else { - return [[0,'Not available']]; + return [ [ 0, 'Not available' ] ]; } ################################### # Send command ################################### - foreach $cmd (@cmds){ - $result = send_cmd( $exp, $cmd ); + foreach $cmd (@cmds) { + $result = send_cmd($exp, $cmd); push @values, $result; } return \@values; } ########################################################################## -# Creates a logical partition on the managed system +# Creates a logical partition on the managed system ########################################################################## sub mksyscfg { @@ -400,21 +400,21 @@ sub mksyscfg { my $cfgdata = shift; ##################################### - # Command only support on LPARs + # Command only support on LPARs ##################################### - if ( @$d[4] ne "lpar" ) { - return( [RC_ERROR,"Command not supported on '@$d[4]'"] ); + if (@$d[4] ne "lpar") { + return ([ RC_ERROR, "Command not supported on '@$d[4]'" ]); } ##################################### # Format command based on CEC name ##################################### - my $cmd = "mksyscfg -r $res -m @$d[2] -i \"$cfgdata\""; + my $cmd = "mksyscfg -r $res -m @$d[2] -i \"$cfgdata\""; ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } @@ -423,14 +423,14 @@ sub mksyscfg { ########################################################################## sub rmsyscfg { - my $exp = shift; - my $d = shift; + my $exp = shift; + my $d = shift; ##################################### - # Command only supported on LPARs + # Command only supported on LPARs ##################################### - if ( @$d[4] ne "lpar" ) { - return( [RC_ERROR,"Command not supported on '@$d[4]'"] ); + if (@$d[4] ne "lpar") { + return ([ RC_ERROR, "Command not supported on '@$d[4]'" ]); } ##################################### # Format command based on CEC name @@ -440,13 +440,13 @@ sub rmsyscfg { ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } ########################################################################## -# Lists environmental information +# Lists environmental information ########################################################################## sub lshwinfo { @@ -463,8 +463,8 @@ sub lshwinfo { ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } @@ -480,24 +480,24 @@ sub chsysstate { ##################################### # Format command based on CEC name ##################################### - my $cmd = power_cmd( $op, $d ); - if ( !defined( $cmd )) { - return( [RC_ERROR,"'$op' command not supported"] ); + my $cmd = power_cmd($op, $d); + if (!defined($cmd)) { + return ([ RC_ERROR, "'$op' command not supported" ]); } ##################################### - # Special case - return immediately + # Special case - return immediately ##################################### - if ( $cmd =~ /^reboot$/ ) { + if ($cmd =~ /^reboot$/) { my $ssh = @$exp[0]; - $ssh->send( "$cmd\r" ); - return( [SUCCESS,"Success"] ); + $ssh->send("$cmd\r"); + return ([ SUCCESS, "Success" ]); } ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } @@ -505,7 +505,7 @@ sub chsysstate { ########################################################################## # Opens a virtual terminal session ########################################################################## -sub mkvterm { +sub mkvterm { my $exp = shift; my $type = shift; @@ -520,8 +520,8 @@ sub mkvterm { # Format command based on HW Type ########################################## my %mkvt = ( - hmc =>"mkvterm --id %s -m %s", - ivm =>"mkvt -id %s" + hmc => "mkvterm --id %s -m %s", + ivm => "mkvt -id %s" ); ########################################## # HMC returns: @@ -531,37 +531,37 @@ sub mkvterm { # Exiting...." # # HMCs may also return: - # "The open failed. - # "-The session may already be open on + # "The open failed. + # "-The session may already be open on # another management console" # # But Expect (for some reason) sees each # character preceeded with \000 (blank??) # ########################################## - my $fail_msg = "HSCL"; - my $ivm_open = "Virtual terminal is already connected"; - my $hmc_open = "\000o\000p\000e\000n\000 \000f\000a\000i\000l\000e\000d"; + my $fail_msg = "HSCL"; + my $ivm_open = "Virtual terminal is already connected"; + my $hmc_open = "\000o\000p\000e\000n\000 \000f\000a\000i\000l\000e\000d"; my $hmc_open2 = - "\000a\000l\000r\000e\000a\000d\000y\000 \000o\000p\000e\000n"; + "\000a\000l\000r\000e\000a\000d\000y\000 \000o\000p\000e\000n"; ########################################## # Set command based on HW type - # mkvterm -id lparid -m cecmtms + # mkvterm -id lparid -m cecmtms ########################################## - my $cmd = sprintf( $mkvt{$hwtype}, $lparid, $mtms ); - if ( $type ne "lpar" ) { - return( [RC_ERROR,"Command not supported on '$type'"] ); + my $cmd = sprintf($mkvt{$hwtype}, $lparid, $mtms); + if ($type ne "lpar") { + return ([ RC_ERROR, "Command not supported on '$type'" ]); } ########################################## # Close the old sessions ########################################## - if ( $hwtype eq "ivm" ) { - rmvterm( $exp, $lparid, $mtms ); + if ($hwtype eq "ivm") { + rmvterm($exp, $lparid, $mtms); sleep 1; } else { - rmvterm_noforce( $exp, $lparid, $mtms ); + rmvterm_noforce($exp, $lparid, $mtms); sleep 1; } @@ -569,25 +569,25 @@ sub mkvterm { # Send command ########################################## $ssh->clear_accum(); - $ssh->send( "$cmd\r" ); + $ssh->send("$cmd\r"); ########################################## - # Expect result + # Expect result ########################################## - my @result = $ssh->expect( $timeout, + my @result = $ssh->expect($timeout, [ "$hmc_open|$hmc_open2|$ivm_open|$fail_msg", - sub { - $failed = 1; - } ] + sub { + $failed = 1; + } ] ); - if ( $failed ) { + if ($failed) { $ssh->hard_close(); - if (grep(/$fail_msg/, @result)) { - return( [RC_ERROR, "mkvterm returns the unsuccessful value, please check your entry and retry the command."] ); - } else { - return( [RC_ERROR,"Virtual terminal is already connected"] ); - } + if (grep(/$fail_msg/, @result)) { + return ([ RC_ERROR, "mkvterm returns the unsuccessful value, please check your entry and retry the command." ]); + } else { + return ([ RC_ERROR, "Virtual terminal is already connected" ]); + } } ########################################## @@ -596,16 +596,16 @@ sub mkvterm { # the Ctrl-X (\030). ########################################## my $escape = "\030"; - $ssh->send( "\r" ); - $ssh->interact( \*STDIN, $escape ); - + $ssh->send("\r"); + $ssh->interact(\*STDIN, $escape); + ########################################## # Close session ########################################## - rmvterm( $exp, $lparid, $mtms ); + rmvterm($exp, $lparid, $mtms); $ssh->hard_close(); - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -624,20 +624,20 @@ sub rmvterm { # Format command based on HW Type ##################################### my %rmvt = ( - hmc =>"rmvterm --id %s -m %s", - ivm =>"rmvt -id %s" + hmc => "rmvterm --id %s -m %s", + ivm => "rmvt -id %s" ); ##################################### # Set command based on HW type - # rmvt(erm) -id lparid -m cecmtms + # rmvt(erm) -id lparid -m cecmtms ##################################### - my $cmd = sprintf( $rmvt{$hwtype}, $lparid, $mtms ); + my $cmd = sprintf($rmvt{$hwtype}, $lparid, $mtms); ##################################### # Send command ##################################### $ssh->clear_accum(); - $ssh->send( "$cmd\r" ); + $ssh->send("$cmd\r"); } ########################################################################## @@ -655,25 +655,25 @@ sub rmvterm_noforce { # Format command based on HW Type ##################################### my %rmvt = ( - hmc =>"rmvterm --id %s -m %s", - ivm =>"rmvt -id %s" + hmc => "rmvterm --id %s -m %s", + ivm => "rmvt -id %s" ); ##################################### # Set command based on HW type # rmvt(erm) -id lparid -m cecmtms ##################################### - my $cmd = sprintf( $rmvt{$hwtype}, $lparid, $mtms ); + my $cmd = sprintf($rmvt{$hwtype}, $lparid, $mtms); ##################################### # Send command ##################################### - send_cmd( $exp, $cmd ); + send_cmd($exp, $cmd); } ########################################################################## -# Lists the hardware resources of a managed system +# Lists the hardware resources of a managed system ########################################################################## sub lshwres { @@ -688,29 +688,29 @@ sub lshwres { ##################################### # Specify Filters ##################################### - if ( $Filter ) { - $cmd .=" -F $Filter"; - } - + if ($Filter) { + $cmd .= " -F $Filter"; + } + ##################################### - # level may be "sys" or "lpar" + # level may be "sys" or "lpar" ##################################### - if ( defined( $level )) { - $cmd .=" --level $level"; + if (defined($level)) { + $cmd .= " --level $level"; } ##################################### # Specify subtype ##################################### - if ( $rsubtype ) { - $cmd .=" --rsubtype $rsubtype" + if ($rsubtype) { + $cmd .= " --rsubtype $rsubtype" } ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd ); - return( $result ); + my $result = send_cmd($exp, $cmd); + return ($result); } @@ -724,63 +724,63 @@ sub lpar_netboot { my $name = shift; my $d = shift; my $opt = shift; - my $timeout = my $t = @$exp[7]*10; + my $timeout = my $t = @$exp[7] * 10; my $cmd = "lpar_netboot -t ent -f"; my $gateway = $opt->{G}; my $node = @$d[6]; ##################################### - # Power6 HMCs (V7) do not support - # 0.0.0.0 gateway. + # Power6 HMCs (V7) do not support + # 0.0.0.0 gateway. ##################################### - if ( $gateway =~ /^0.0.0.0$/ ) { - my $fw = lshmc( $exp, "RM" ); + if ($gateway =~ /^0.0.0.0$/) { + my $fw = lshmc($exp, "RM"); my $Rc = shift(@$fw); - - if ( $Rc == SUCCESS ) { - if ( @$fw[0] =~ /^V(\d+)/ ) { + + if ($Rc == SUCCESS) { + if (@$fw[0] =~ /^V(\d+)/) { ######################### # Power4 not supported ######################### - if ( $1 < 6 ) { - return( [RC_ERROR,"Command not supported on V$1 HMC"] ); - } + if ($1 < 6) { + return ([ RC_ERROR, "Command not supported on V$1 HMC" ]); + } ######################### - # Use server for gateway + # Use server for gateway ######################### - elsif ( $1 >= 7 ) { + elsif ($1 >= 7) { $opt->{G} = $opt->{S}; } } } } ##################################### - # Verbose output + # Verbose output ##################################### - if ( $verbose ) { - $cmd.= " -x -v"; + if ($verbose) { + $cmd .= " -x -v"; } ##################################### # Force LPAR shutdown if -f specified ##################################### - if ( exists( $opt->{f} )) { - $cmd.= " -i"; + if (exists($opt->{f})) { + $cmd .= " -i"; } else { ################################# # Force LPAR shutdown if LPAR is # running Linux ################################# - my $table = "nodetype"; - my $intable = 0; + my $table = "nodetype"; + my $intable = 0; my @TableRowArray = xCAT::DBobjUtils->getDBtable($table); - if ( @TableRowArray ) { - foreach ( @TableRowArray ) { + if (@TableRowArray) { + foreach (@TableRowArray) { my @nodelist = split(',', $_->{'node'}); - my @oslist = split(',', $_->{'os'}); - my $osname = "AIX"; - if ( grep(/^$node$/, @nodelist) ) { - if ( !grep(/^$osname$/, @oslist) ) { - $cmd.= " -i"; + my @oslist = split(',', $_->{'os'}); + my $osname = "AIX"; + if (grep(/^$node$/, @nodelist)) { + if (!grep(/^$osname$/, @oslist)) { + $cmd .= " -i"; } $intable = 1; last; @@ -789,11 +789,11 @@ sub lpar_netboot { } ################################# # Force LPAR shutdown if LPAR OS - # type is not assigned in table + # type is not assigned in table # but mnt node is running Linux ################################# - if ( xCAT::Utils->isLinux() && $intable == 0 ) { - $cmd.= " -i"; + if (xCAT::Utils->isLinux() && $intable == 0) { + $cmd .= " -i"; } } @@ -801,45 +801,45 @@ sub lpar_netboot { # Get MAC-address or network boot ##################################### my $mac = $opt->{m}; - $cmd.= ( defined( $mac )) ? " -m $mac" : " -M -A -n"; - + $cmd .= (defined($mac)) ? " -m $mac" : " -M -A -n"; + ##################################### # Command only supported on LPARs ##################################### - if ( @$d[4] ne "lpar" ) { - return( [RC_ERROR,"Command not supported on '@$d[4]'"] ); + if (@$d[4] ne "lpar") { + return ([ RC_ERROR, "Command not supported on '@$d[4]'" ]); } ##################################### # Network specified (-D ping test) ##################################### - if ( exists( $opt->{S} )) { - my %nethash = xCAT::DBobjUtils->getNetwkInfo( [$node] ); + if (exists($opt->{S})) { + my %nethash = xCAT::DBobjUtils->getNetwkInfo([$node]); ##################################### # Network attributes undefined ##################################### - if ( !%nethash ) { - return( [RC_ERROR,"Cannot get network information for $node"] ); + if (!%nethash) { + return ([ RC_ERROR, "Cannot get network information for $node" ]); } my $netmask = $nethash{$node}{mask}; - $cmd.= (!defined( $mac )) ? " -D" : ""; - $cmd.= " -s auto -d auto -S $opt->{S} -G $opt->{G} -C $opt->{C} -K $netmask"; + $cmd .= (!defined($mac)) ? " -D" : ""; + $cmd .= " -s auto -d auto -S $opt->{S} -G $opt->{G} -C $opt->{C} -K $netmask"; } ##################################### - # Add lpar name, profile, CEC name + # Add lpar name, profile, CEC name ##################################### - $cmd.= " \"$name\" \"@$d[1]\" \"@$d[2]\""; + $cmd .= " \"$name\" \"@$d[1]\" \"@$d[2]\""; ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd, $timeout ); - return( $result ); + my $result = send_cmd($exp, $cmd, $timeout); + return ($result); } ########################################################################## -# List Hardware Management Console configuration information +# List Hardware Management Console configuration information ########################################################################## sub lshmc { @@ -851,36 +851,36 @@ sub lshmc { # Format command based on HW Type ##################################### my %cmd = ( - hmc =>"lshmc -v", - ivm =>"lsivm" + hmc => "lshmc -v", + ivm => "lsivm" ); ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd{$hwtype} ); + my $result = send_cmd($exp, $cmd{$hwtype}); ##################################### # Return error ##################################### - if ( @$result[0] != SUCCESS ) { - return( $result ); - } + if (@$result[0] != SUCCESS) { + return ($result); + } ##################################### # Only return attribute requested ##################################### - if ( defined( $attr )) { - if ( my ($vpd) = grep( /^\*$attr\s/, @$result )) { + if (defined($attr)) { + if (my ($vpd) = grep(/^\*$attr\s/, @$result)) { $vpd =~ s/\*$attr\s+//; - return( [SUCCESS, $vpd ] ); + return ([ SUCCESS, $vpd ]); } - return( [RC_ERROR, "'$attr' not found"] ); + return ([ RC_ERROR, "'$attr' not found" ]); } ##################################### # IVM returns: # 9133-55A,10B7D1G,1 # - # HMC returns: + # HMC returns: # "vpd=*FC ???????? # *VC 20.0 # *N2 Mon Sep 24 13:54:00 GMT 2007 @@ -897,19 +897,19 @@ sub lshmc { # *DS Platform Firmware # *RM V7R3.1.0.1 ##################################### - if ( $hwtype eq "ivm" ) { - my ($model,$serial,$lparid) = split /,/, @$result[1]; - return( [SUCCESS,"$model,$serial"] ); + if ($hwtype eq "ivm") { + my ($model, $serial, $lparid) = split /,/, @$result[1]; + return ([ SUCCESS, "$model,$serial" ]); } my @values; - my $vpd = join( ",", @$result ); + my $vpd = join(",", @$result); ##################################### # Power4 (and below) HMCs unsupported ##################################### - if ( $vpd =~ /\*RM V(\d+)/ ) { - if ( $1 <= 5 ) { - return( [RC_ERROR,"Command not supported on V$1 HMC"] ); + if ($vpd =~ /\*RM V(\d+)/) { + if ($1 <= 5) { + return ([ RC_ERROR, "Command not supported on V$1 HMC" ]); } } ##################################### @@ -917,18 +917,18 @@ sub lshmc { # "eserver xSeries 336 -[7310CR3]-" # "7310-CR4" ##################################### - if ( $vpd =~ /\*TM ([^,]+)/ ) { - my $temp = $1; - my $model = ($temp =~ /\[(.*)\]/) ? $1 : $temp; + if ($vpd =~ /\*TM ([^,]+)/) { + my $temp = $1; + my $model = ($temp =~ /\[(.*)\]/) ? $1 : $temp; push @values, $model; } ##################################### # Serial number ##################################### - if ( $vpd =~ /\*SE ([^,]+)/ ) { + if ($vpd =~ /\*SE ([^,]+)/) { push @values, $1; } - return( [SUCCESS,join( ",",@values)] ); + return ([ SUCCESS, join(",", @values) ]); } @@ -947,54 +947,54 @@ sub mkauthkeys { my $userid = @$exp[4]; ######################################### - # On IVM-based systems, the mkauthkeys - # command does not exist, so we have to - # include the generated key at - # /home//.ssh/authorized_keys2 - # manually. + # On IVM-based systems, the mkauthkeys + # command does not exist, so we have to + # include the generated key at + # /home//.ssh/authorized_keys2 + # manually. ######################################### - if ( $hwtype =~ /^ivm$/ ) { - my @authkey; + if ($hwtype =~ /^ivm$/) { + my @authkey; my $auth = "/home/$userid/.ssh/authorized_keys2"; - my $result = send_cmd( $exp, "cat $auth" ); - my $Rc = shift(@$result); + my $result = send_cmd($exp, "cat $auth"); + my $Rc = shift(@$result); ##################################### # Return error ##################################### - if ( $Rc != SUCCESS ) { - return( $result ); + if ($Rc != SUCCESS) { + return ($result); } ##################################### # When adding, remove old keys first ##################################### - foreach ( @$result ) { - unless ( /$logon$/ ) { + foreach (@$result) { + unless (/$logon$/) { push @authkey, $_; } } ##################################### - # Add new key + # Add new key ##################################### - if ( $option =~ /^enable$/i ) { + if ($option =~ /^enable$/i) { push @authkey, $sshkey; } ##################################### - # Rewrite the key file + # Rewrite the key file ##################################### - my $keys = join( "\n", @authkey ); - $result = send_cmd( $exp,"echo \"$keys\" | tee $auth" ); - return( $result ); + my $keys = join("\n", @authkey); + $result = send_cmd($exp, "echo \"$keys\" | tee $auth"); + return ($result); } ######################################### # When adding, remove old keys first ######################################### - my $result = send_cmd( $exp,"mkauthkeys --remove '$logon'" ); - - if ( $option =~ /^enable$/i ) { - $result = send_cmd( $exp,"mkauthkeys --add '$sshkey'" ); + my $result = send_cmd($exp, "mkauthkeys --remove '$logon'"); + + if ($option =~ /^enable$/i) { + $result = send_cmd($exp, "mkauthkeys --add '$sshkey'"); } - return( $result ); + return ($result); } @@ -1003,41 +1003,41 @@ sub mkauthkeys { ########################################################################## sub lslic { - my $exp = shift; - my $d = shift; + my $exp = shift; + my $d = shift; my $timeout = shift; - my $cmd = "lslic "; - + my $cmd = "lslic "; + ########################################## - # Use timeout from site table (if defined) + # Use timeout from site table (if defined) ########################################## - if ( !defined( $timeout ) || $timeout == 0 ) { + if (!defined($timeout) || $timeout == 0) { $timeout = @$exp[7] * 3; } ##################################### # Command only support on CEC/BPAs ##################################### - if ( @$d[4] !~ /^(fsp|bpa)$/ ) { - return( [RC_ERROR,"Command not supported on '@$d[4]'"] ); + if (@$d[4] !~ /^(fsp|bpa)$/) { + return ([ RC_ERROR, "Command not supported on '@$d[4]'" ]); } ##################################### # Format command based on name ##################################### - $cmd.= (@$d[4] =~ /^fsp$/) ? "-t sys -m " : "-t power -e "; - $cmd.= @$d[2]; + $cmd .= (@$d[4] =~ /^fsp$/) ? "-t sys -m " : "-t power -e "; + $cmd .= @$d[2]; ##################################### # Send command ##################################### - my $result = send_cmd( $exp, $cmd , $timeout); - return( $result ); + my $result = send_cmd($exp, $cmd, $timeout); + return ($result); } ########################################################################## -# Sends command and waits for response +# Sends command and waits for response ########################################################################## sub send_cmd { @@ -1048,17 +1048,17 @@ sub send_cmd { my $prompt = @$exp[1]; ########################################## - # Use timeout from site table (if defined) + # Use timeout from site table (if defined) ########################################## - if ( !defined( $timeout )) { + if (!defined($timeout)) { $timeout = @$exp[7]; } ########################################## - # Send command + # Send command ########################################## $ssh->clear_accum(); - $ssh->send( "$cmd; echo Rc=\$\?\r" ); + $ssh->send("$cmd; echo Rc=\$\?\r"); ########################################## # The first element is the number of the # pattern or string that matched, the @@ -1075,40 +1075,40 @@ sub send_cmd { # is text before the match, and the fifth # argument is text after the match. ########################################## - my @result = $ssh->expect( $timeout, "-re", "(.*$prompt)" ); - + my @result = $ssh->expect($timeout, "-re", "(.*$prompt)"); + ########################################## - # Expect error + # Expect error ########################################## - if ( defined( $result[1] )) { - return( [EXPECT_ERROR,expect_error( @result )] ); - } + if (defined($result[1])) { + return ([ EXPECT_ERROR, expect_error(@result) ]); + } ########################################## # Extract error code ########################################## - if ( $result[3] =~ s/Rc=([0-9])+\r\n// ) { - if ( $1 != 0 ) { - return( [RC_ERROR,$result[3]] ); + if ($result[3] =~ s/Rc=([0-9])+\r\n//) { + if ($1 != 0) { + return ([ RC_ERROR, $result[3] ]); } } ########################################## # No data found - return error ########################################## - if ( $result[3] =~ /No results were found/ ) { - return( [NR_ERROR,"No results were found"] ); + if ($result[3] =~ /No results were found/) { + return ([ NR_ERROR, "No results were found" ]); } ########################################## - # If no command output, return "Success" + # If no command output, return "Success" ########################################## - if ( length( $result[3] ) == 0 ) { + if (length($result[3]) == 0) { $result[3] = "Success"; } ########################################## - # Success + # Success ########################################## - my @values = ( SUCCESS ); + my @values = (SUCCESS); push @values, split /\r\n/, $result[3]; - return( \@values ); + return (\@values); } @@ -1118,7 +1118,7 @@ sub send_cmd { sub expect_error { my @error = @_; - + ########################################## # The first element is the number of the # pattern or string that matched, the @@ -1126,8 +1126,8 @@ sub expect_error { # context. The second argument is a # string indicating why expect returned. # If there were no error, the second - # argument will be undef. Possible errors - # are 1:TIMEOUT, 2:EOF, 3:spawn id(...)died, + # argument will be undef. Possible errors + # are 1:TIMEOUT, 2:EOF, 3:spawn id(...)died, # and "4:..." (see Expect (3) manpage for # the precise meaning of these messages) # The third argument of expects return list @@ -1135,16 +1135,16 @@ sub expect_error { # is text before the match, and the fifth # argument is text after the match. ########################################## - if ( $error[1] eq "1:TIMEOUT" ) { - return( "Timeout waiting for prompt" ); + if ($error[1] eq "1:TIMEOUT") { + return ("Timeout waiting for prompt"); } - if ( $error[1] eq "2:EOF" ) { - if ( $error[3] ) { - return( $error[3] ); + if ($error[1] eq "2:EOF") { + if ($error[3]) { + return ($error[3]); } - return( "ssh connection terminated unexpectedly" ); + return ("ssh connection terminated unexpectedly"); } - return( "Logon failed" ); + return ("Logon failed"); } @@ -1154,18 +1154,19 @@ sub expect_error { ########################################################################## sub power_cmd { - my $op = shift; - my $d = shift; + my $op = shift; + my $d = shift; + #my $type = (@$d[4] eq "fsp") ? "sys" : @$d[4]; - my $type = ( @$d[4] =~ /^(fsp|cec)$/ ) ? "sys" : @$d[4]; + my $type = (@$d[4] =~ /^(fsp|cec)$/) ? "sys" : @$d[4]; ############################## - # Build command + # Build command ############################## my $cmd = $powercmd{$type}{$op}; - if ( defined( $cmd )) { - return( sprintf( $cmd, $type, @$d[2],@$d[0],@$d[1] )); + if (defined($cmd)) { + return (sprintf($cmd, $type, @$d[2], @$d[0], @$d[1])); } ############################## # Command not supported @@ -1178,40 +1179,40 @@ sub power_cmd { ##################################### sub network_reset { - my $exp = shift; - my $current_ip = shift; - my $hostname_ip =shift; - my $hwtype = @$exp[2]; + my $exp = shift; + my $current_ip = shift; + my $hostname_ip = shift; + my $hwtype = @$exp[2]; - my ($ip,$hostname) = split /,/, $hostname_ip; - if ( !$hostname || !$ip) + my ($ip, $hostname) = split /,/, $hostname_ip; + if (!$hostname || !$ip) { - return ( [RC_ERROR,"No valid hostname or IP find. This could be a internal bug of xCAT."] ); + return ([ RC_ERROR, "No valid hostname or IP find. This could be a internal bug of xCAT." ]); } ##################################### -# Format command based on HW Type + # Format command based on HW Type ##################################### my %cmd = ( - hmc =>"lshmc -n -F hostname:ipaddr", - ivm =>"lsivm" #just for future consideration - ); + hmc => "lshmc -n -F hostname:ipaddr", + ivm => "lsivm" #just for future consideration + ); ##################################### -# Get current hostname and IP + # Get current hostname and IP ##################################### - my $result = send_cmd( $exp, $cmd{$hwtype} ); - if ( @$result[0] != SUCCESS ) { - return( $result ); + my $result = send_cmd($exp, $cmd{$hwtype}); + if (@$result[0] != SUCCESS) { + return ($result); } - my ($current_hostname,$current_all_ip) = split /:/, @$result[1]; + my ($current_hostname, $current_all_ip) = split /:/, @$result[1]; ##################################### -# Find the correct interface + # Find the correct interface ##################################### - my @eth_ip = split /,/,$current_all_ip; + my @eth_ip = split /,/, $current_all_ip; my $i; my $matched = 0; - for( $i=0; $i < scalar(@eth_ip); $i++) + for ($i = 0 ; $i < scalar(@eth_ip) ; $i++) { if ($eth_ip[$i] eq $current_ip) { @@ -1219,22 +1220,23 @@ sub network_reset { last; } } - if ( !$matched ) + if (!$matched) { -# What's happen? - return ( [RC_ERROR,"No appropriate IP addresses to be updated. This could be a internal bug of xCAT."]); + # What's happen? + return ([ RC_ERROR, "No appropriate IP addresses to be updated. This could be a internal bug of xCAT." ]); } %cmd = ( -# probably need update netmask also - hmc => "chhmc -c network -s modify -h $hostname -i eth$i -a $ip", - ivm => "nothing" - ); - $result = send_cmd( $exp, $cmd{$hwtype} ); + + # probably need update netmask also + hmc => "chhmc -c network -s modify -h $hostname -i eth$i -a $ip", + ivm => "nothing" + ); + $result = send_cmd($exp, $cmd{$hwtype}); ##################################### -# Return error + # Return error ##################################### - return( $result ); + return ($result); } @@ -1246,9 +1248,9 @@ sub lssysconn my $exp = shift; my $res = shift; my $filter = shift; - my $cmd = sprintf( $lssysconn{$res}, $filter ); - my $result = send_cmd( $exp, $cmd); - return ( $result); + my $cmd = sprintf($lssysconn{$res}, $filter); + my $result = send_cmd($exp, $cmd); + return ($result); } ########################################################################## @@ -1260,10 +1262,10 @@ sub mksysconn my $ip = shift; my $type = shift; my $passwd = shift; - - my $cmd = sprintf( $mksysconn{$type}, $ip, $passwd); - my $result = send_cmd( $exp, $cmd); - return ( $result); + + my $cmd = sprintf($mksysconn{$type}, $ip, $passwd); + my $result = send_cmd($exp, $cmd); + return ($result); } ########################################################################## @@ -1278,9 +1280,9 @@ sub chsyspwd my $passwd = shift; my $newpwd = shift; - my $cmd = sprintf( $chsyspwd{$type}, $user, $mtms, $passwd, $newpwd ); - my $result = send_cmd( $exp, $cmd); - return ( $result ); + my $cmd = sprintf($chsyspwd{$type}, $user, $mtms, $passwd, $newpwd); + my $result = send_cmd($exp, $cmd); + return ($result); } ########################################################################## @@ -1288,13 +1290,13 @@ sub chsyspwd ########################################################################## sub rmsysconn { - my $exp = shift; - my $type = shift; - my $name = shift; - - my $cmd = sprintf( $rmsysconn{$type}, $name); - my $result = send_cmd( $exp, $cmd); - return ( $result); + my $exp = shift; + my $type = shift; + my $name = shift; + + my $cmd = sprintf($rmsysconn{$type}, $name); + my $result = send_cmd($exp, $cmd); + return ($result); } ########################################################################## # Get FSP/BPA IP address for the redundancy FSP/BPA from HMC @@ -1310,7 +1312,7 @@ sub getHMCcontrolIP my $exp = shift; #get node type first - my $type = xCAT::DBobjUtils::getnodetype($node, "ppc"); + my $type = xCAT::DBobjUtils::getnodetype($node, "ppc"); unless ($type) { return undef; @@ -1321,32 +1323,34 @@ sub getHMCcontrolIP my $tab = xCAT::Table->new("vpd"); my $ent; if ($tab) { - $ent = $tab->getNodeAttribs($node, ['serial', 'mtm']); + $ent = $tab->getNodeAttribs($node, [ 'serial', 'mtm' ]); } my $serial = $ent->{'serial'}; - my $mtm = $ent->{'mtm'}; + my $mtm = $ent->{'mtm'}; + #my $mtms = $mtm . '*' . $serial; #my $nodes_found = lssyscfg( $exp, "$type", "$mtms"); - my $nodes_found = lssysconn ($exp, "all"); + my $nodes_found = lssysconn($exp, "all"); my @ips; my $ip_result; - if ( @$nodes_found[0] eq SUCCESS ) { + if (@$nodes_found[0] eq SUCCESS) { my $Rc = shift(@$nodes_found); + #my @newnodes = split(/,/, $nodes_found->[0]); #$Rc = shift(@newnodes); #for my $entry (@newnodes) { # if(xCAT::NetworkUtils->isIpaddr($entry)) { # push @ips,$entry; - # } + # } # $ip_result = join( ",", @ips ); - #} - foreach my $entry ( @$nodes_found ) { - if ( $entry =~ /$mtm\*$serial/) { + #} + foreach my $entry (@$nodes_found) { + if ($entry =~ /$mtm\*$serial/) { $entry =~ /ipaddr=(\d+\.\d+\.\d+\.\d+),/; push @ips, $1; } - } - $ip_result = join( ",", @ips ); + } + $ip_result = join(",", @ips); } return $ip_result; } diff --git a/perl-xCAT/xCAT/PPCconn.pm b/perl-xCAT/xCAT/PPCconn.pm index b5836beae..84c3dad9c 100644 --- a/perl-xCAT/xCAT/PPCconn.pm +++ b/perl-xCAT/xCAT/PPCconn.pm @@ -24,13 +24,13 @@ my %method = ( sub parse_args { my $request = shift; - my $cmd = $request->{command}; + my $cmd = $request->{command}; ############################### # Invoke correct parse_args ############################### - my $result = $method{$cmd}( $request, $request->{arg}); - return( $result ); + my $result = $method{$cmd}($request, $request->{arg}); + return ($result); } ########################################################################## @@ -40,40 +40,40 @@ sub mkhwconn_parse_args { my $request = shift; my $args = shift; - my %opt = (); + my %opt = (); local *usage = sub { my $usage_string = xCAT::Usage->getUsage("mkhwconn"); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } - local @ARGV = ref($args) eq 'ARRAY'? @$args:(); + local @ARGV = ref($args) eq 'ARRAY' ? @$args : (); $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose h|help t p=s P=s port=s s:s) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose h|help t p=s P=s port=s s:s))) { + return (usage()); } - return usage() if ( exists $opt{h}); + return usage() if (exists $opt{h}); - if ( !exists $opt{t} and !exists $opt{p} and !exists $opt{s}) { - return ( usage('Flag -t or -p or -s must be used.')); + if (!exists $opt{t} and !exists $opt{p} and !exists $opt{s}) { + return (usage('Flag -t or -p or -s must be used.')); } - if (( exists $opt{t} and exists $opt{p}) or (exists $opt{s} and exists $opt{p}) or (exists $opt{t} and exists $opt{p})) + if ((exists $opt{t} and exists $opt{p}) or (exists $opt{s} and exists $opt{p}) or (exists $opt{t} and exists $opt{p})) { - return( usage('Flags -t and -p cannot be used together.')); + return (usage('Flags -t and -p cannot be used together.')); } - if ( exists $opt{P} and (!exists $opt{p} and !exists $opt{s})) + if (exists $opt{P} and (!exists $opt{p} and !exists $opt{s})) { - return( usage('Flags -P can only be used when flag -p is specified.')); + return (usage('Flags -P can only be used when flag -p is specified.')); } ########################################## @@ -83,42 +83,45 @@ sub mkhwconn_parse_args ########################################## # Check if CECs are controlled by a frame ########################################## - my $nodes = $request->{node}; - my $ppctab = xCAT::Table->new( 'ppc' ); + my $nodes = $request->{node}; + my $ppctab = xCAT::Table->new('ppc'); + #my $nodetypetab = xCAT::Table->new( 'nodetype'); - my $vpdtab = xCAT::Table->new( 'vpd'); + my $vpdtab = xCAT::Table->new('vpd'); my @bpa_ctrled_nodes = (); my @no_type_nodes = (); my @frame_members = (); - if ( $ppctab) + if ($ppctab) { - for my $node ( @$nodes) + for my $node (@$nodes) { my $node_parent = undef; my $nodetype = undef; + #my $nodetype_hash = $nodetypetab->getNodeAttribs( $node,[qw(nodetype)]); - my $node_parent_hash = $ppctab->getNodeAttribs( $node,[qw(parent)]); + my $node_parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); + #$nodetype = $nodetype_hash->{nodetype}; - $nodetype = xCAT::DBobjUtils->getnodetype($node,"ppc"); + $nodetype = xCAT::DBobjUtils->getnodetype($node, "ppc"); $node_parent = $node_parent_hash->{parent}; - if ( !$nodetype ) + if (!$nodetype) { push @no_type_nodes, $node; next; } else { - unless ( $nodetype =~ /^(blade|fsp|bpa|frame|cec|hmc)$/) + unless ($nodetype =~ /^(blade|fsp|bpa|frame|cec|hmc)$/) { - return ( usage("Node type is incorrect. \n")); + return (usage("Node type is incorrect. \n")); } } - if ( $nodetype eq 'fsp' ) + if ($nodetype eq 'fsp') { my $jr = xCAT::DBobjUtils::judge_node($node, $nodetype); unless ($jr) { - if ($node_parent and $node_parent ne $node ) + if ($node_parent and $node_parent ne $node) { push @bpa_ctrled_nodes, $node; } @@ -137,12 +140,12 @@ sub mkhwconn_parse_args ########################################## # Now we suppport the operation on sigal bpa ########################################## - if ( $nodetype eq 'bpa') + if ($nodetype eq 'bpa') { my $jr = xCAT::DBobjUtils::judge_node($node, $nodetype); - unless($jr) + unless ($jr) { - my $my_frame_bpa_cec = getFrameMembers( $node, $vpdtab, $ppctab); + my $my_frame_bpa_cec = getFrameMembers($node, $vpdtab, $ppctab); push @frame_members, @$my_frame_bpa_cec; } } @@ -150,10 +153,10 @@ sub mkhwconn_parse_args # For the Frame, we will have its CEC to do # mkhwconn at the same time ########################################## - if ( $nodetype eq 'frame') + if ($nodetype eq 'frame') { - my $my_frame_bpa_cec = xCAT::DBobjUtils::getcecchildren( $node) ; - push @frame_members, @$my_frame_bpa_cec if($my_frame_bpa_cec); + my $my_frame_bpa_cec = xCAT::DBobjUtils::getcecchildren($node); + push @frame_members, @$my_frame_bpa_cec if ($my_frame_bpa_cec); push @frame_members, $node; } } @@ -162,39 +165,40 @@ sub mkhwconn_parse_args if (scalar(@no_type_nodes)) { my $tmp_nodelist = join ',', @no_type_nodes; - return ( usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.")); + return (usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.")); } if (scalar(@bpa_ctrled_nodes)) { my $tmp_nodelist = join ',', @bpa_ctrled_nodes; - return ( usage("Node(s) $tmp_nodelist is(are) controlled by BPA.")); + return (usage("Node(s) $tmp_nodelist is(are) controlled by BPA.")); } - if ( scalar( @frame_members)) + if (scalar(@frame_members)) { - my @all_nodes = xCAT::Utils::get_unique_members( @$nodes, @frame_members); + my @all_nodes = xCAT::Utils::get_unique_members(@$nodes, @frame_members); $request->{node} = \@all_nodes; } + # Set HW type to 'hmc' anyway, so that this command will not going to # PPCfsp.pm - $request->{ 'hwtype'} = 'hmc'; + $request->{'hwtype'} = 'hmc'; $request->{hcp} = 'hmc'; - if( ! exists $opt{port} ) + if (!exists $opt{port}) { $opt{port} = "0"; } - if( $opt{port} ne "0" and $opt{port} ne "1") + if ($opt{port} ne "0" and $opt{port} ne "1") { - return( usage('Wrong value of --port option. The value can be 0 or 1, and the default value is 0.')); + return (usage('Wrong value of --port option. The value can be 0 or 1, and the default value is 0.')); } $request->{method} = 'mkhwconn'; - - if ( scalar( @ARGV)) { - return(usage( "No additional flag is support by this command" )); + + if (scalar(@ARGV)) { + return (usage("No additional flag is support by this command")); } - return( \%opt); + return (\%opt); } #################################################### @@ -203,38 +207,39 @@ sub mkhwconn_parse_args #ppc/vpd nodes cache my @all_ppc_nodes; my @all_vpd_nodes; + sub getFrameMembers { - my $node = shift; #this a BPA node - my $vpdtab = shift; - my $ppctab = shift; + my $node = shift; #this a BPA node + my $vpdtab = shift; + my $ppctab = shift; my @frame_members = (); my @bpa_nodes = (); - my $vpdhash = $vpdtab->getNodeAttribs( $node, [qw(mtm serial)]); - my $mtm = $vpdhash->{mtm}; - my $serial = $vpdhash->{serial}; - if ( scalar( @all_vpd_nodes) == 0) + my $vpdhash = $vpdtab->getNodeAttribs($node, [qw(mtm serial)]); + my $mtm = $vpdhash->{mtm}; + my $serial = $vpdhash->{serial}; + if (scalar(@all_vpd_nodes) == 0) { - @all_vpd_nodes = $vpdtab->getAllNodeAttribs( ['node', 'mtm', 'serial']); + @all_vpd_nodes = $vpdtab->getAllNodeAttribs([ 'node', 'mtm', 'serial' ]); } for my $vpd_node (@all_vpd_nodes) { - if ( $vpd_node->{'mtm'} eq $mtm and $vpd_node->{'serial'} eq $serial) + if ($vpd_node->{'mtm'} eq $mtm and $vpd_node->{'serial'} eq $serial) { push @frame_members, $vpd_node->{'node'}; - push @bpa_nodes, $vpd_node->{'node'}; + push @bpa_nodes, $vpd_node->{'node'}; } } - if ( scalar( @all_ppc_nodes) == 0) + if (scalar(@all_ppc_nodes) == 0) { - @all_ppc_nodes = $ppctab->getAllNodeAttribs( ['node', 'parent']); + @all_ppc_nodes = $ppctab->getAllNodeAttribs([ 'node', 'parent' ]); } for my $bpa_node (@bpa_nodes) { for my $ppc_node (@all_ppc_nodes) { - if ( $ppc_node->{parent} eq $bpa_node) + if ($ppc_node->{parent} eq $bpa_node) { push @frame_members, $ppc_node->{'node'}; } @@ -250,102 +255,103 @@ sub lshwconn_parse_args { my $request = shift; my $args = shift; - my %opt = (); + my %opt = (); local *usage = sub { my $usage_string = xCAT::Usage->getUsage("lshwconn"); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# -# Get options in command line + # Get options in command line ############################################# - local @ARGV = ref($args) eq 'ARRAY'? @$args:(); + local @ARGV = ref($args) eq 'ARRAY' ? @$args : (); $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose h|help s) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose h|help s))) { + return (usage()); } - return usage() if ( exists $opt{h}); + return usage() if (exists $opt{h}); ############################################# # Process command-line arguments ############################################# - if ( scalar( @ARGV)) { - unless( $opt{s}) { - return(usage( "No additional flag is support by this command" )); - } + if (scalar(@ARGV)) { + unless ($opt{s}) { + return (usage("No additional flag is support by this command")); + } } + #my $nodetypetab = xCAT::Table->new('nodetype'); #if (! $nodetypetab) #{ # return( ["Failed to open table 'nodetype'.\n"]); #} my $nodehmtab = xCAT::Table->new('nodehm'); - if (! $nodehmtab) + if (!$nodehmtab) { - return( ["Failed to open table 'nodehm'.\n"]); + return (["Failed to open table 'nodehm'.\n"]); } my $nodetype; - my @no_type_nodes = (); - my @no_mgt_nodes = (); + my @no_type_nodes = (); + my @no_mgt_nodes = (); my @error_type_nodes = (); - for my $node ( @{$request->{node}}) + for my $node (@{ $request->{node} }) { #my $ent = $nodetypetab->getNodeAttribs( $node, [qw(nodetype)]); my $ttype = xCAT::DBobjUtils->getnodetype($node); - my $nodehm = $nodehmtab->getNodeAttribs( $node, [qw(mgt)]); - if ( ! $ttype) + my $nodehm = $nodehmtab->getNodeAttribs($node, [qw(mgt)]); + if (!$ttype) { push @no_type_nodes, $node; next; } - if ( ! $nodehm) + if (!$nodehm) { push @no_mgt_nodes, $node; next; } - elsif ( $nodehm->{mgt} ne 'hmc') + elsif ($nodehm->{mgt} ne 'hmc') { - return( ["lshwconn can only support HMC nodes, or nodes managed by HMC, i.e. nodehm.mgt should be 'hmc'. Please make sure node $node has correect nodehm.mgt and ppc.hcp value.\n"]); + return (["lshwconn can only support HMC nodes, or nodes managed by HMC, i.e. nodehm.mgt should be 'hmc'. Please make sure node $node has correect nodehm.mgt and ppc.hcp value.\n"]); } - if ( $ttype ne 'hmc' - and $ttype ne 'fsp' and $ttype ne 'cec' - and $ttype ne 'bpa' and $ttype ne 'frame') + if ($ttype ne 'hmc' + and $ttype ne 'fsp' and $ttype ne 'cec' + and $ttype ne 'bpa' and $ttype ne 'frame') { push @error_type_nodes, $node; next; } - if ( ! $nodetype) + if (!$nodetype) { $nodetype = $ttype; } else { - if ( $nodetype ne $ttype) + if ($nodetype ne $ttype) { - return( ["Cannot support multiple node types in this command line.\n"]); + return (["Cannot support multiple node types in this command line.\n"]); } } } if (scalar(@no_type_nodes)) { my $tmp_nodelist = join ',', @no_type_nodes; - return( ["Failed to get node type for node(s) $tmp_nodelist. Please define first and try again\n"]); + return (["Failed to get node type for node(s) $tmp_nodelist. Please define first and try again\n"]); } if (scalar(@no_mgt_nodes)) { my $tmp_nodelist = join ',', @no_mgt_nodes; - return( ["Failed to get nodehm.mgt value for node(s) $tmp_nodelist. Please define first and try again.\n"]); + return (["Failed to get nodehm.mgt value for node(s) $tmp_nodelist. Please define first and try again.\n"]); } if (scalar(@error_type_nodes)) { my $tmp_nodelist = join ',', @error_type_nodes; - my $link = (scalar(@error_type_nodes) eq '1')? 'is':'are'; - return( ["Node type of node(s) $tmp_nodelist $link not supported for this command.\n"]); + my $link = (scalar(@error_type_nodes) eq '1') ? 'is' : 'are'; + return (["Node type of node(s) $tmp_nodelist $link not supported for this command.\n"]); } $request->{nodetype} = $nodetype; $request->{method} = 'lshwconn'; - return( \%opt); + return (\%opt); } ########################################################################## @@ -355,47 +361,48 @@ sub rmhwconn_parse_args { my $request = shift; my $args = shift; - my %opt = (); + my %opt = (); local *usage = sub { my $usage_string = xCAT::Usage->getUsage("rmhwconn"); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Get options in command line ############################################# - local @ARGV = ref($args) eq 'ARRAY'? @$args:(); + local @ARGV = ref($args) eq 'ARRAY' ? @$args : (); $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose h|help s) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose h|help s))) { + return (usage()); } - return usage() if ( exists $opt{h}); + return usage() if (exists $opt{h}); ############################################# # Process command-line arguments ############################################# - if ( scalar (@ARGV)) { - unless( $opt{s}) { - return(usage( "No additional flag is support by this command" )); + if (scalar(@ARGV)) { + unless ($opt{s}) { + return (usage("No additional flag is support by this command")); } } ########################################## # Check if CECs are controlled by a frame ########################################## - my $nodes = $request->{node}; - my $ppctab = xCAT::Table->new( 'ppc' ); - return( ["Failed to open table 'ppc'.\n"]) if ( ! $ppctab); - my $vpdtab = xCAT::Table->new( 'vpd'); - return( ["Failed to open table 'vpd'.\n"]) if ( ! $vpdtab); + my $nodes = $request->{node}; + my $ppctab = xCAT::Table->new('ppc'); + return (["Failed to open table 'ppc'.\n"]) if (!$ppctab); + my $vpdtab = xCAT::Table->new('vpd'); + return (["Failed to open table 'vpd'.\n"]) if (!$vpdtab); my @bpa_ctrled_nodes = (); my @no_type_nodes = (); my @frame_members = (); - for my $node ( @$nodes) + + for my $node (@$nodes) { my $node_parent = undef; - my $node_parent_hash = $ppctab->getNodeAttribs( $node,[qw(parent)]); + my $node_parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); $node_parent = $node_parent_hash->{parent}; my $newtype = xCAT::DBobjUtils::getnodetype($node); unless ($newtype) { @@ -403,7 +410,7 @@ sub rmhwconn_parse_args next; } - if ($newtype =~ /^(fsp|bpa)$/ ) + if ($newtype =~ /^(fsp|bpa)$/) { ########################################## # We should judge if the node is defined in xCAT 2.5 @@ -412,28 +419,29 @@ sub rmhwconn_parse_args # which means we support remove a sigal connection ########################################## my $jr = xCAT::DBobjUtils::judge_node($node, $newtype); + #$jr is defined by the xCAT2.5 unless ($jr) { - if ( ($newtype eq 'fsp') and $node_parent and $node_parent ne $node) + if (($newtype eq 'fsp') and $node_parent and $node_parent ne $node) { push @bpa_ctrled_nodes, $node; } - if ( $newtype eq 'bpa') + if ($newtype eq 'bpa') { - my $my_frame_bpa_cec = getFrameMembers( $node, $vpdtab, $ppctab); + my $my_frame_bpa_cec = getFrameMembers($node, $vpdtab, $ppctab); push @frame_members, @$my_frame_bpa_cec; } } } - if (( $newtype eq 'cec') and $node_parent and $node_parent ne $node) + if (($newtype eq 'cec') and $node_parent and $node_parent ne $node) { #push @bpa_ctrled_nodes, $node; } - if ( $newtype eq 'frame') + if ($newtype eq 'frame') { my $my_frame_bpa_cec = xCAT::DBobjUtils::getcecchildren($node); push @frame_members, @$my_frame_bpa_cec; @@ -444,22 +452,22 @@ sub rmhwconn_parse_args if (scalar(@no_type_nodes)) { my $tmp_nodelist = join ',', @no_type_nodes; - return ( usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.\n")); + return (usage("Attribute nodetype.nodetype cannot be found for node(s) $tmp_nodelist. Please define first and try again.\n")); } if (scalar(@bpa_ctrled_nodes)) { my $tmp_nodelist = join ',', @bpa_ctrled_nodes; - return ( usage("Node(s) $tmp_nodelist is(are) controlled by BPA.")); + return (usage("Node(s) $tmp_nodelist is(are) controlled by BPA.")); } - if ( scalar( @frame_members)) + if (scalar(@frame_members)) { - my @all_nodes = xCAT::Utils::get_unique_members( @$nodes, @frame_members); + my @all_nodes = xCAT::Utils::get_unique_members(@$nodes, @frame_members); $request->{node} = \@all_nodes; } $request->{method} = 'rmhwconn'; - return( \%opt); + return (\%opt); } ########################################################################## # Create connection for CECs/BPAs @@ -474,11 +482,11 @@ sub mkhwconn my @value = (); my $Rc = undef; - xCAT::MsgUtils->verbose_message($request, "mkhwconn START."); - for my $cec_bpa ( keys %$hash) + xCAT::MsgUtils->verbose_message($request, "mkhwconn START."); + for my $cec_bpa (keys %$hash) { my $node_hash = $hash->{$cec_bpa}; - for my $node_name ( keys %$node_hash) + for my $node_name (keys %$node_hash) { my $d = $node_hash->{$node_name}; @@ -486,6 +494,7 @@ sub mkhwconn # Get IP address ############################ my $cnode; + #my $ntype = xCAT::DBobjUtils::getnodetype($node_name); my $ntype = $$d[4]; if ($ntype =~ /^(cec|frame|blade)$/) @@ -499,69 +508,69 @@ sub mkhwconn } my @newnodes = (); - if ( $cnode =~ /ARRAY/ ) + if ($cnode =~ /ARRAY/) { foreach (@$cnode) { push @newnodes, $_; } } else { - push @newnodes,$cnode; + push @newnodes, $cnode; } - xCAT::MsgUtils->verbose_message($request, "mkhwconn :mksysconn for node:$node_name."); - for my $nn ( @newnodes ) + xCAT::MsgUtils->verbose_message($request, "mkhwconn :mksysconn for node:$node_name."); + for my $nn (@newnodes) { my $node_ip; - unless ( xCAT::NetworkUtils->isIpaddr($nn) ) { - $node_ip = xCAT::NetworkUtils::getNodeIPaddress( $nn ); + unless (xCAT::NetworkUtils->isIpaddr($nn)) { + $node_ip = xCAT::NetworkUtils::getNodeIPaddress($nn); } else { $node_ip = $nn; } - unless($node_ip) + unless ($node_ip) { - push @value, [$node_name, "Cannot get IP address. Please check table 'hosts' or name resolution", 1]; + push @value, [ $node_name, "Cannot get IP address. Please check table 'hosts' or name resolution", 1 ]; next; } - my ( undef,undef,$mtms,undef,$type,$bpa) = @$d; + my (undef, undef, $mtms, undef, $type, $bpa) = @$d; my ($user, $passwd); - if ( exists $opt->{P}) + if (exists $opt->{P}) { ($user, $passwd) = ('HMC', $opt->{P}); } elsif ($type eq "blade") { $user = "USERID"; - ($user, $passwd) = xCAT::PPCdb::credentials( $bpa, $type, $user); + ($user, $passwd) = xCAT::PPCdb::credentials($bpa, $type, $user); $type = "cec"; } else { - ($user, $passwd) = xCAT::PPCdb::credentials( $node_name, $type,'HMC'); - if ( !$passwd) + ($user, $passwd) = xCAT::PPCdb::credentials($node_name, $type, 'HMC'); + if (!$passwd) { - push @value, [$node_name, "Cannot get password of userid 'HMC'. Please check table 'passwd' or 'ppcdirect'.",1]; + push @value, [ $node_name, "Cannot get password of userid 'HMC'. Please check table 'passwd' or 'ppcdirect'.", 1 ]; next; } } - my $res = xCAT::PPCcli::mksysconn( $exp, $node_ip, $type, $passwd); + my $res = xCAT::PPCcli::mksysconn($exp, $node_ip, $type, $passwd); $Rc = shift @$res; - push @value, [$node_name, @$res[0], $Rc]; - if ( !$Rc and !(exists $opt->{s})) + push @value, [ $node_name, @$res[0], $Rc ]; + if (!$Rc and !(exists $opt->{s})) { - sethmcmgt( $node_name, $exp->[3]); + sethmcmgt($node_name, $exp->[3]); } } -# if ( exists $opt->{N} ) -# { -# my $newpwd = $opt->{N}; -# my $Res = xCAT::PPCcli::chsyspwd( $exp, "access", $type, $mtms, $passwd, $newpwd ); -# $Rc = shift @$Res; -# push @value, [$node_name, @$Res[0], $Rc]; -# } + # if ( exists $opt->{N} ) + # { + # my $newpwd = $opt->{N}; + # my $Res = xCAT::PPCcli::chsyspwd( $exp, "access", $type, $mtms, $passwd, $newpwd ); + # $Rc = shift @$Res; + # push @value, [$node_name, @$Res[0], $Rc]; + # } } } - xCAT::MsgUtils->verbose_message($request, "mkhwconn END."); + xCAT::MsgUtils->verbose_message($request, "mkhwconn END."); return \@value; } ########################################################################## @@ -578,35 +587,35 @@ sub lshwconn my $Rc = undef; - my $hosttab = xCAT::Table->new( 'hosts' ); - my $res = xCAT::PPCcli::lssysconn( $exp, "all" ); + my $hosttab = xCAT::Table->new('hosts'); + my $res = xCAT::PPCcli::lssysconn($exp, "all"); $Rc = shift @$res; - if ( $request->{nodetype} eq 'hmc') + if ($request->{nodetype} eq 'hmc') { - if ( $Rc) + if ($Rc) { - push @value, [$exp->[3], $res->[0], $Rc]; + push @value, [ $exp->[3], $res->[0], $Rc ]; return \@value; } - my $vpdtab = xCAT::Table->new('vpd'); + my $vpdtab = xCAT::Table->new('vpd'); my @vpdentries = $vpdtab->getAllAttribs(qw(node serial mtm)); my %node_vpd_hash; - for my $vpdent ( @vpdentries) + for my $vpdent (@vpdentries) { - if ( $vpdent->{node} and $vpdent->{serial} and $vpdent->{mtm}) + if ($vpdent->{node} and $vpdent->{serial} and $vpdent->{mtm}) { $node_vpd_hash{"$vpdent->{mtm}*$vpdent->{serial}"} = $vpdent->{node}; } } my %node_ppc_hash; - my $ppctab = xCAT::Table->new('ppc'); - for my $node ( values %node_vpd_hash) + my $ppctab = xCAT::Table->new('ppc'); + for my $node (values %node_vpd_hash) { - my $node_parent_hash = $ppctab->getNodeAttribs( $node, [qw(parent)]); + my $node_parent_hash = $ppctab->getNodeAttribs($node, [qw(parent)]); $node_ppc_hash{$node} = $node_parent_hash->{parent}; } - for my $r ( @$res) + for my $r (@$res) { $r =~ s/type_model_serial_num=([^,]*),//; my $mtms = $1; @@ -614,7 +623,7 @@ sub lshwconn $r =~ s/sp=.*?,//; $r =~ s/sp_phys_loc=.*?,//; my $node_name; - if ( exists $node_vpd_hash{$mtms}) + if (exists $node_vpd_hash{$mtms}) { $node_name = $node_vpd_hash{$mtms}; $r = "hcp=$exp->[3],parent=$node_ppc_hash{$node_name}," . $r; @@ -622,14 +631,14 @@ sub lshwconn else { $node_name = $mtms; - $r = "hcp=$exp->[3],parent=," . $r; + $r = "hcp=$exp->[3],parent=," . $r; } - push @value, [ $node_name, $r, $Rc]; + push @value, [ $node_name, $r, $Rc ]; } } else { - for my $cec_bpa ( keys %$hash) + for my $cec_bpa (keys %$hash) { my $node_hash = $hash->{$cec_bpa}; for my $node_name (keys %$node_hash) @@ -638,9 +647,9 @@ sub lshwconn # If lssysconn failed, put error into all # nodes' return values ############################################ - if ( $Rc ) + if ($Rc) { - push @value, [$node_name, @$res[0], $Rc]; + push @value, [ $node_name, @$res[0], $Rc ]; next; } @@ -648,39 +657,40 @@ sub lshwconn # Get IP address ############################ my $node_ip = undef; - if ( $hosttab) + if ($hosttab) { #my $node_ip_hash = $hosttab->getNodeAttribs( $node_name,[qw(ip)]); #$node_ip = $node_ip_hash->{ip}; #$node_ip = xCAT::NetworkUtils::getNodeIPaddress( $node_name ); - my $d = $node_hash->{$node_name}; - $node_ip = xCAT::FSPUtils::getIPaddress($request, $$d[4], $node_name ); + my $d = $node_hash->{$node_name}; + $node_ip = xCAT::FSPUtils::getIPaddress($request, $$d[4], $node_name); } if (!$node_ip || ($node_ip == -3)) { - push @value, [$node_name, "Failed to get IP address.", $Rc]; + push @value, [ $node_name, "Failed to get IP address.", $Rc ]; next; } my @nodes_ip = split(/,/, $node_ip); - for my $ip (@nodes_ip) + for my $ip (@nodes_ip) { - if ( my @res_matched = grep /\Qipaddr=$ip,\E/, @$res) + if (my @res_matched = grep /\Qipaddr=$ip,\E/, @$res) { - for my $r ( @res_matched) + for my $r (@res_matched) { $r =~ s/\Qtype_model_serial_num=$cec_bpa,\E//; + #$r =~ s/\Qresource_type=$type,\E//; $r =~ s/sp=.*?,//; $r =~ s/sp_phys_loc=.*?,//; - my $new_name = $node_name."(".$ip. ")"; - push @value, [$new_name, $r, $Rc]; + my $new_name = $node_name . "(" . $ip . ")"; + push @value, [ $new_name, $r, $Rc ]; } } else { - my $new_name = $node_name."(".$ip. ")"; - push @value, [$new_name, 'Connection not found', 1]; + my $new_name = $node_name . "(" . $ip . ")"; + push @value, [ $new_name, 'Connection not found', 1 ]; } } } @@ -702,21 +712,21 @@ sub rmhwconn my @value = (); my $Rc = undef; - my $nodes_found = xCAT::PPCcli::lssysconn ($exp, "all"); - if ( @$nodes_found[0] eq SUCCESS ) { + my $nodes_found = xCAT::PPCcli::lssysconn($exp, "all"); + if (@$nodes_found[0] eq SUCCESS) { $Rc = shift(@$nodes_found); - } else { + } else { return undef; - } - for my $cec_bpa ( keys %$hash) + } + for my $cec_bpa (keys %$hash) { my $node_hash = $hash->{$cec_bpa}; for my $node_name (keys %$node_hash) { my $d = $node_hash->{$node_name}; - my ( undef,undef,undef,undef,$type) = @$d; - if ($type eq "blade") {$type = "cec";} + my (undef, undef, undef, undef, $type) = @$d; + if ($type eq "blade") { $type = "cec"; } ############################ # Get IP address ############################ @@ -725,14 +735,14 @@ sub rmhwconn my $tab = xCAT::Table->new("vpd"); my $ent; if ($tab) { - $ent = $tab->getNodeAttribs($node_name, ['serial', 'mtm']); + $ent = $tab->getNodeAttribs($node_name, [ 'serial', 'mtm' ]); } my $serial = $ent->{'serial'}; - my $mtm = $ent->{'mtm'}; + my $mtm = $ent->{'mtm'}; my $node_ip; my @ips; - foreach my $entry ( @$nodes_found ) { + foreach my $entry (@$nodes_found) { if ($entry =~ /type_model_serial_num=([^,]*),/) { my $match_mtm1 = $1; my $match_mtm2 = $match_mtm1; @@ -742,24 +752,25 @@ sub rmhwconn push @ips, $1; } } - #if ( $entry =~ /$mtm\*$serial/) { - # $entry =~ /ipaddr=(\d+\.\d+\.\d+\.\d+),/; - # push @ips, $1; - #} - } + + #if ( $entry =~ /$mtm\*$serial/) { + # $entry =~ /ipaddr=(\d+\.\d+\.\d+\.\d+),/; + # push @ips, $1; + #} + } if (!@ips) { - push @value, [$node_name, $node_ip, $Rc]; + push @value, [ $node_name, $node_ip, $Rc ]; next; } - for my $nn ( @ips ) + for my $nn (@ips) { - my $res = xCAT::PPCcli::rmsysconn( $exp, $type, $nn); + my $res = xCAT::PPCcli::rmsysconn($exp, $type, $nn); $Rc = shift @$res; - push @value, [$node_name, @$res[0], $Rc]; - if ( !$Rc and !$opt->{s}) + push @value, [ $node_name, @$res[0], $Rc ]; + if (!$Rc and !$opt->{s}) { - rmhmcmgt( $node_name, $type); + rmhmcmgt($node_name, $type); } } } @@ -775,26 +786,26 @@ sub sethmcmgt my $node = shift; my $hcp = shift; - my $nodehm_tab = xCAT::Table->new('nodehm', -create=>1); - my $ppc_tab = xCAT::Table->new('ppc', -create=>1); + my $nodehm_tab = xCAT::Table->new('nodehm', -create => 1); + my $ppc_tab = xCAT::Table->new('ppc', -create => 1); my @nodes; push @nodes, $node; my $ntype = xCAT::DBobjUtils->getnodetype($node); - if ( $ntype =~ /^(cec|frame)$/ ) { + if ($ntype =~ /^(cec|frame)$/) { my $cnodep = xCAT::DBobjUtils->getchildren($node); if ($cnodep) { push @nodes, @$cnodep; - } - } - for my $n (@nodes) { - my $ent = $nodehm_tab->getNodeAttribs( $n, ['mgt']); - if ( !$ent or $ent->{mgt} ne 'hmc') { - $nodehm_tab->setNodeAttribs( $n, { mgt=>'hmc'}); } - my $ent = $ppc_tab->getNodeAttribs( $n, ['hcp']); - if ( !$ent or $ent->{hcp} ne $hcp) { - $ppc_tab->setNodeAttribs( $n, { hcp=>$hcp}); - } + } + for my $n (@nodes) { + my $ent = $nodehm_tab->getNodeAttribs($n, ['mgt']); + if (!$ent or $ent->{mgt} ne 'hmc') { + $nodehm_tab->setNodeAttribs($n, { mgt => 'hmc' }); + } + my $ent = $ppc_tab->getNodeAttribs($n, ['hcp']); + if (!$ent or $ent->{hcp} ne $hcp) { + $ppc_tab->setNodeAttribs($n, { hcp => $hcp }); + } } } ################################################################# @@ -802,34 +813,34 @@ sub sethmcmgt ################################################################# sub rmhmcmgt { - my $node = shift; + my $node = shift; my $hwtype = shift; - my $nodehm_tab = xCAT::Table->new('nodehm', -create=>1); - my $ppc_tab = xCAT::Table->new('ppc', -create=>1); + my $nodehm_tab = xCAT::Table->new('nodehm', -create => 1); + my $ppc_tab = xCAT::Table->new('ppc', -create => 1); my @nodes; push @nodes, $node; my $ntype = xCAT::DBobjUtils->getnodetype($node); - if ( $ntype =~ /^(cec|frame)$/ ) { + if ($ntype =~ /^(cec|frame)$/) { my $cnodep = xCAT::DBobjUtils->getchildren($node); if ($cnodep) { push @nodes, @$cnodep; - } + } } for my $n (@nodes) { - my $ent = $nodehm_tab->getNodeAttribs( $n, ['mgt']); - if ( !$ent or $ent->{mgt} ne $hwtype) { + my $ent = $nodehm_tab->getNodeAttribs($n, ['mgt']); + if (!$ent or $ent->{mgt} ne $hwtype) { if ($hwtype eq "cec" || $hwtype eq "frame") { - $nodehm_tab->setNodeAttribs( $n, { mgt=>"fsp"}); - } else { - $nodehm_tab->setNodeAttribs( $n, { mgt=>$hwtype}); - } + $nodehm_tab->setNodeAttribs($n, { mgt => "fsp" }); + } else { + $nodehm_tab->setNodeAttribs($n, { mgt => $hwtype }); + } } - my $ent = $ppc_tab->getNodeAttribs( $n, ['hcp']); - if ( !$ent or $ent->{hcp} ne $n) { - $ppc_tab->setNodeAttribs( $n, { hcp=>$n}); + my $ent = $ppc_tab->getNodeAttribs($n, ['hcp']); + if (!$ent or $ent->{hcp} ne $n) { + $ppc_tab->setNodeAttribs($n, { hcp => $n }); } - } + } } 1; diff --git a/perl-xCAT/xCAT/PPCdb.pm b/perl-xCAT/xCAT/PPCdb.pm index 2b7e30252..464ac4b34 100644 --- a/perl-xCAT/xCAT/PPCdb.pm +++ b/perl-xCAT/xCAT/PPCdb.pm @@ -13,12 +13,12 @@ require xCAT::data::ibmhwtypes; # Factory defaults ########################################### my %logon = ( - hmc => ["hscroot","abc123"], - ivm => ["padmin", "padmin"], - fsp => ["admin", "admin"], - bpa => ["admin", "admin"], - frame => ["admin", "admin"], - cec => ["admin", "admin"], + hmc => [ "hscroot", "abc123" ], + ivm => [ "padmin", "padmin" ], + fsp => [ "admin", "admin" ], + bpa => [ "admin", "admin" ], + frame => [ "admin", "admin" ], + cec => [ "admin", "admin" ], ); ########################################### @@ -31,7 +31,7 @@ my %hcptab = ( bpa => "ppcdirect", frame => "ppcdirect", cec => "ppcdirect", - blade => "mpa", + blade => "mpa", ); ########################################### @@ -44,7 +44,7 @@ my %defaultgrp = ( bpa => "bpa", frame => "frame", cec => "cec", - blade => "blade", + blade => "blade", ); my %globlehwtype = ( fsp => $::NODETYPE_FSP, @@ -57,13 +57,13 @@ my %globlehwtype = ( ); my %globalnodetype = ( - fsp => $::NODETYPE_PPC, - bpa => $::NODETYPE_PPC, - cec => $::NODETYPE_PPC, - frame=> $::NODETYPE_PPC, - hmc => $::NODETYPE_PPC, - ivm => $::NODETYPE_PPC, - lpar =>"$::NODETYPE_PPC,$::NODETYPE_OSI" + fsp => $::NODETYPE_PPC, + bpa => $::NODETYPE_PPC, + cec => $::NODETYPE_PPC, + frame => $::NODETYPE_PPC, + hmc => $::NODETYPE_PPC, + ivm => $::NODETYPE_PPC, + lpar => "$::NODETYPE_PPC,$::NODETYPE_OSI" ); ########################################################################## @@ -71,26 +71,26 @@ my %globalnodetype = ( ########################################################################## sub add_ppc { - my $hwtype = shift; - my $values = shift; - my $not_overwrite = shift; + my $hwtype = shift; + my $values = shift; + my $not_overwrite = shift; my $otherinterfaces = shift; - my $callfile = shift; - my @tabs = qw(ppc vpd nodehm nodelist nodetype hosts mac); - my %db = (); + my $callfile = shift; + my @tabs = qw(ppc vpd nodehm nodelist nodetype hosts mac); + my %db = (); ################################### # Open database needed ################################### - foreach ( @tabs ) { - $db{$_} = xCAT::Table->new( $_, -create=>1, -autocommit=>0 ); - if ( !$db{$_} ) { - return( "Error opening '$_'" ); + foreach (@tabs) { + $db{$_} = xCAT::Table->new($_, -create => 1, -autocommit => 0); + if (!$db{$_}) { + return ("Error opening '$_'"); } } ################################### - # Update tables + # Update tables ################################### - foreach ( @$values ) { + foreach (@$values) { my ($type, $name, $id, @@ -101,15 +101,15 @@ sub add_ppc { $pprofile, $parent, $ips, - $mac ) = split /,/; + $mac) = split /,/; ############################### # Update nodetype table ############################### - if ( $type =~ /^(fsp|bpa|hmc|ivm|frame|cec)$/ ) { - $db{nodetype}->setNodeAttribs( $name,{nodetype=>'ppc'} ); + if ($type =~ /^(fsp|bpa|hmc|ivm|frame|cec)$/) { + $db{nodetype}->setNodeAttribs($name, { nodetype => 'ppc' }); $db{nodetype}{commit} = 1; } elsif ($type =~ /^lpar$/) { - $db{nodetype}->setNodeAttribs( $name,{nodetype=>'ppc,osi'} ); + $db{nodetype}->setNodeAttribs($name, { nodetype => 'ppc,osi' }); $db{nodetype}{commit} = 1; } ############################### @@ -117,131 +117,131 @@ sub add_ppc { # old data firstly ############################### my $mgt = $hwtype; - + # Specify CEC and Frame's mgt as fsp and bpa - if ( $type =~ /^cec$/) { - if ( $callfile eq "PPC" ) { + if ($type =~ /^cec$/) { + if ($callfile eq "PPC") { $mgt = "hmc"; } - if ( $callfile eq "FSP" ) { + if ($callfile eq "FSP") { $mgt = "fsp"; } } - if ( $type =~ /^frame$/) { + if ($type =~ /^frame$/) { $mgt = "bpa"; - } - - - my $cons= $hwtype; - if ( $not_overwrite) + } + + + my $cons = $hwtype; + if ($not_overwrite) { - my $enthash = $db{ppc}->getNodeAttribs( $name, [qw(hcp id pprofile parent)]); - if ( $enthash ) + my $enthash = $db{ppc}->getNodeAttribs($name, [qw(hcp id pprofile parent)]); + if ($enthash) { - $server = $enthash->{hcp} if ($enthash->{hcp}); - $id = $enthash->{id} if ( $enthash->{id}); - $pprofile = $enthash->{pprofile} if ( $enthash->{pprofile}); - $parent = $enthash->{parent} if ( $enthash->{parent}); + $server = $enthash->{hcp} if ($enthash->{hcp}); + $id = $enthash->{id} if ($enthash->{id}); + $pprofile = $enthash->{pprofile} if ($enthash->{pprofile}); + $parent = $enthash->{parent} if ($enthash->{parent}); } - $enthash = $db{nodehm}->getNodeAttribs( $name, [qw(mgt)]); - if ( $enthash ) + $enthash = $db{nodehm}->getNodeAttribs($name, [qw(mgt)]); + if ($enthash) { - $mgt= $enthash->{mgt} if ( $enthash->{mgt}); - $cons= $enthash->{cons} if ( $enthash->{cons}); + $mgt = $enthash->{mgt} if ($enthash->{mgt}); + $cons = $enthash->{cons} if ($enthash->{cons}); } - $enthash = $db{vpd}->getNodeAttribs( $name, [qw(mtm serial)]); - if ( $enthash ) + $enthash = $db{vpd}->getNodeAttribs($name, [qw(mtm serial)]); + if ($enthash) { - $model = $enthash->{mtm} if ( $enthash->{mtm}); - $serial= $enthash->{serial} if ( $enthash->{serial}); + $model = $enthash->{mtm} if ($enthash->{mtm}); + $serial = $enthash->{serial} if ($enthash->{serial}); } } ############################### # Update ppc table ############################### - if ( $type =~ /^(fsp|bpa|lpar|frame|cec|hmc)$/ ) { - $db{ppc}->setNodeAttribs( $name, - { hcp=>$server, - id=>$id, - pprofile=>$pprofile, - parent=>$parent, - nodetype=>$globlehwtype{$type}, - }); + if ($type =~ /^(fsp|bpa|lpar|frame|cec|hmc)$/) { + $db{ppc}->setNodeAttribs($name, + { hcp => $server, + id => $id, + pprofile => $pprofile, + parent => $parent, + nodetype => $globlehwtype{$type}, + }); $db{ppc}{commit} = 1; ########################### # Update nodelist table ########################### - updategroups( $name, $db{nodelist}, $type ); + updategroups($name, $db{nodelist}, $type); my $tmp_group = xCAT::data::ibmhwtypes::parse_group($model); if (defined($tmp_group)) { updategroups($name, $db{nodelist}, $tmp_group); } - if ( $type =~ /^(fsp|bpa)$/ ) { - $db{nodelist}->setNodeAttribs( $name, {hidden => '1'}); + if ($type =~ /^(fsp|bpa)$/) { + $db{nodelist}->setNodeAttribs($name, { hidden => '1' }); } else { - $db{nodelist}->setNodeAttribs( $name, {hidden => '0'}); + $db{nodelist}->setNodeAttribs($name, { hidden => '0' }); } - + $db{nodelist}{commit} = 1; ########################### # Update nodehm table ########################### - if($type =~ /^lpar$/){ - $db{nodehm}->setNodeAttribs( $name, {mgt=>$mgt,cons=>$cons} ); + if ($type =~ /^lpar$/) { + $db{nodehm}->setNodeAttribs($name, { mgt => $mgt, cons => $cons }); } else { - $db{nodehm}->setNodeAttribs( $name, {mgt=>$mgt} ); + $db{nodehm}->setNodeAttribs($name, { mgt => $mgt }); } $db{nodehm}{commit} = 1; } ############################### # Update vpd table ############################### - if ( $type =~ /^(fsp|bpa)$/ ) { - $db{vpd}->setNodeAttribs( $name, - { mtm=>$model, - serial=>$serial, - side=>$side - }); - } - if ( $type =~ /^(frame|cec)$/ ) { - $db{vpd}->setNodeAttribs( $name, - { mtm=>$model, - serial=>$serial, - }); + if ($type =~ /^(fsp|bpa)$/) { + $db{vpd}->setNodeAttribs($name, + { mtm => $model, + serial => $serial, + side => $side + }); + } + if ($type =~ /^(frame|cec)$/) { + $db{vpd}->setNodeAttribs($name, + { mtm => $model, + serial => $serial, + }); } $db{vpd}{commit} = 1; ############################### # Update hosts table ############################### - if ( $otherinterfaces ) { - $db{hosts}->setNodeAttribs( $name, - { otherinterfaces=>$ips }); + if ($otherinterfaces) { + $db{hosts}->setNodeAttribs($name, + { otherinterfaces => $ips }); } else { - $db{hosts}->setNodeAttribs( $name, - { ip=>$ips }); + $db{hosts}->setNodeAttribs($name, + { ip => $ips }); } $db{hosts}{commit} = 1; - + ############################### # Update mac table ############################### - if ( $mac ) { - $db{mac}->setNodeAttribs( $name, - { mac=>$mac }); + if ($mac) { + $db{mac}->setNodeAttribs($name, + { mac => $mac }); } $db{mac}{commit} = 1; } ################################### - # Commit changes + # Commit changes ################################### - foreach ( @tabs ) { - if ( exists( $db{$_}{commit} )) { - $db{$_}->commit; + foreach (@tabs) { + if (exists($db{$_}{commit})) { + $db{$_}->commit; } } return undef; @@ -250,26 +250,27 @@ sub add_ppc { # Update lpar information in the xCAT databases ########################################################################## sub update_lpar { - my $hwtype = shift; - my $values = shift; - my $write = shift; - my @tabs = qw(ppc vpd nodehm nodelist nodetype ppcdirect hosts mac); - my %db = (); + my $hwtype = shift; + my $values = shift; + my $write = shift; + my @tabs = qw(ppc vpd nodehm nodelist nodetype ppcdirect hosts mac); + my %db = (); my @update_list = (); - my @write_list = (); + my @write_list = (); ################################### # Open database needed ################################### - foreach ( @tabs ) { - $db{$_} = xCAT::Table->new( $_, -create=>1, -autocommit=>0 ); - if ( !$db{$_} ) { - return( "Error opening '$_'" ); + foreach (@tabs) { + $db{$_} = xCAT::Table->new($_, -create => 1, -autocommit => 0); + if (!$db{$_}) { + return ("Error opening '$_'"); } } - my @vpdlist = $db{vpd}->getAllNodeAttribs(['node','serial','mtm','side']); - my @ppclist = $db{ppc}->getAllNodeAttribs(['node','hcp','id', - 'pprofile','parent','nodetype', - 'comments', 'disable']); + my @vpdlist = $db{vpd}->getAllNodeAttribs([ 'node', 'serial', 'mtm', 'side' ]); + my @ppclist = $db{ppc}->getAllNodeAttribs([ 'node', 'hcp', 'id', + 'pprofile', 'parent', 'nodetype', + 'comments', 'disable' ]); + # 'cec,cec1,,8246-L1D,100A9DA,,cec1,,cec1', # 'lpar,10-0A9DA,1,8246-L1D,100A9DA,,cec1,,cec1' my %ppchash = (); @@ -277,18 +278,18 @@ sub update_lpar { foreach my $ppcent (@ppclist) { if ($ppcent->{id} and $ppcent->{nodetype} and $ppcent->{nodetype} eq "lpar") { my $key = $ppcent->{node}; - $ppchash{$key}{id} = $ppcent->{id}; + $ppchash{$key}{id} = $ppcent->{id}; $ppchash{$key}{parent} = $ppcent->{parent}; } } foreach my $vpdent (@vpdlist) { my $key = $vpdent->{node}; - $vpdhash{$key}{mtm} = $vpdent->{mtm}; + $vpdhash{$key}{mtm} = $vpdent->{mtm}; $vpdhash{$key}{serial} = $vpdent->{serial}; } - my @ppc_lpars = keys %ppchash; - foreach my $value ( @$values ) { + my @ppc_lpars = keys %ppchash; + foreach my $value (@$values) { my ($ttype, $tname, $tid, @@ -298,40 +299,41 @@ sub update_lpar { $server, $pprofile, $parent) = split /,/, $value; - if ($ttype ne "lpar") { + + if ($ttype ne "lpar") { + push @update_list, $value; + next; + } + my $find_node = undef; + foreach my $tmp_node (@ppc_lpars) { + if ($ppchash{$tmp_node}{id} eq $tid) { + if (exists($ppchash{$tmp_node}{parent}) and $ppchash{$tmp_node}{parent} eq $parent) { + $find_node = $tmp_node; + last; + } elsif ($vpdhash{$tmp_node}{mtm} eq $tmtm and $vpdhash{$tmp_node}{serial} eq $tsn) { + $find_node = $tmp_node; + last; + } + } + } + if (defined($find_node)) { + if (update_node_attribs($hwtype, $ttype, $find_node, $tid, $tmtm, $tsn, $tside, + $server, $pprofile, $parent, "", \%db, $tname, \@ppclist)) + { + $value =~ s/^$ttype,$tname,/$ttype,$find_node,/; push @update_list, $value; - next; - } - my $find_node = undef; - foreach my $tmp_node (@ppc_lpars) { - if ($ppchash{$tmp_node}{id} eq $tid) { - if (exists($ppchash{$tmp_node}{parent}) and $ppchash{$tmp_node}{parent} eq $parent) { - $find_node = $tmp_node; - last; - } elsif ($vpdhash{$tmp_node}{mtm} eq $tmtm and $vpdhash{$tmp_node}{serial} eq $tsn) { - $find_node = $tmp_node; - last; - } - } - } - if (defined($find_node)) { - if ( update_node_attribs($hwtype, $ttype, $find_node, $tid, $tmtm, $tsn, $tside, - $server, $pprofile, $parent, "", \%db, $tname, \@ppclist)) - { - $value =~ s/^$ttype,$tname,/$ttype,$find_node,/; - push @update_list, $value; - } - } elsif (defined($write)) { - push @write_list, $value; } + } elsif (defined($write)) { + push @write_list, $value; + } } if (defined($write)) { - &add_ppc($hwtype, \@write_list,'','',"FSP"); - return ([@update_list,@write_list]); + &add_ppc($hwtype, \@write_list, '', '', "FSP"); + return ([ @update_list, @write_list ]); } else { - foreach ( @tabs ) { - if ( exists( $db{$_}{commit} )) { - $db{$_}->commit; + foreach (@tabs) { + if (exists($db{$_}{commit})) { + $db{$_}->commit; } } return \@update_list; @@ -343,32 +345,32 @@ sub update_lpar { ########################################################################## sub update_ppc { - my $hwtype = shift; - my $values = shift; + my $hwtype = shift; + my $values = shift; my $not_overwrite = shift; - my @tabs = qw(ppc vpd nodehm nodelist nodetype ppcdirect hosts mac); - my %db = (); + my @tabs = qw(ppc vpd nodehm nodelist nodetype ppcdirect hosts mac); + my %db = (); my @update_list = (); ################################### # Open database needed ################################### - foreach ( @tabs ) { - $db{$_} = xCAT::Table->new( $_, -create=>1, -autocommit=>0 ); - if ( !$db{$_} ) { - return( "Error opening '$_'" ); + foreach (@tabs) { + $db{$_} = xCAT::Table->new($_, -create => 1, -autocommit => 0); + if (!$db{$_}) { + return ("Error opening '$_'"); } } - my @vpdlist = $db{vpd}->getAllNodeAttribs(['node','serial','mtm','side']); - my @hostslist = $db{hosts}->getAllNodeAttribs(['node','ip']); - my @ppclist = $db{ppc}->getAllNodeAttribs(['node','hcp','id', - 'pprofile','parent','supernode', - 'comments', 'disable']); - my @maclist = $db{mac}->getAllNodeAttribs(['node','mac']); + my @vpdlist = $db{vpd}->getAllNodeAttribs([ 'node', 'serial', 'mtm', 'side' ]); + my @hostslist = $db{hosts}->getAllNodeAttribs([ 'node', 'ip' ]); + my @ppclist = $db{ppc}->getAllNodeAttribs([ 'node', 'hcp', 'id', + 'pprofile', 'parent', 'supernode', + 'comments', 'disable' ]); + my @maclist = $db{mac}->getAllNodeAttribs([ 'node', 'mac' ]); ################################### # Need to do database migration first ################################### - foreach my $value ( @$values ) { + foreach my $value (@$values) { my ($ttype, $tname, $tid, @@ -378,27 +380,28 @@ sub update_ppc { $server, $pprofile, $parent, - $ips ) = split /,/, $value; - if ( $ttype eq 'cec' ) + $ips) = split /,/, $value; + + if ($ttype eq 'cec') { - my $hostname = get_host($tname, "FSP", $tmtm, $tsn, "", "", $tid, "",""); - if ($hostname ne $tname) + my $hostname = get_host($tname, "FSP", $tmtm, $tsn, "", "", $tid, "", ""); + if ($hostname ne $tname) { $hostname =~ /\-(\w)$/; if ($1 =~ /^(A|B)$/) { $tside = $1; } - if ( update_node_attribs($hwtype, $ttype, $hostname, $tid, $tmtm, $tsn, $tside, - $server, $pprofile, $parent, $ips, \%db, $tname, \@ppclist)) + if (update_node_attribs($hwtype, $ttype, $hostname, $tid, $tmtm, $tsn, $tside, + $server, $pprofile, $parent, $ips, \%db, $tname, \@ppclist)) { - push @update_list, $value; + push @update_list, $value; } } - } elsif ( $ttype eq 'frame' ) + } elsif ($ttype eq 'frame') { - my $hostname = get_host($tname, "BPA", $tmtm, $tsn, "", "", $tid, "",""); - if ($hostname ne $tname) + my $hostname = get_host($tname, "BPA", $tmtm, $tsn, "", "", $tid, "", ""); + if ($hostname ne $tname) { $hostname =~ /\-(\w)$/; if ($1 =~ /^(A|B)$/) @@ -406,54 +409,19 @@ sub update_ppc { $tside = $1; } - if ( update_node_attribs($hwtype, $ttype, $hostname, $tid, $tmtm, $tsn, $tside, - $server, $pprofile, $parent, $ips, \%db, $tname, \@ppclist)) - { - push @update_list, $value; - } - } - } - } - - ################################### - # Update CEC in tables - ################################### - foreach my $value ( @$values ) { - my ($type, - $name, - $id, - $model, - $serial, - $side, - $server, - $pprofile, - $parent, - $ips ) = split /,/, $value; - next if ( $type ne 'cec' ); - my $predefined_node = undef; - foreach my $vpdent (@vpdlist) - { - if ( $vpdent->{mtm} eq $model && $vpdent->{serial} eq $serial ) - { - $predefined_node = $vpdent->{node}; - if ( update_node_attribs($hwtype, $type, $name, $id, $model, $serial, $side, - $server, $pprofile, $parent, $ips, - \%db, $predefined_node, \@ppclist)) + if (update_node_attribs($hwtype, $ttype, $hostname, $tid, $tmtm, $tsn, $tside, + $server, $pprofile, $parent, $ips, \%db, $tname, \@ppclist)) { push @update_list, $value; } } } - } - my @newppclist = $db{ppc}->getAllNodeAttribs(['node','hcp','id', - 'pprofile','parent','supernode', - 'comments', 'disable']); ################################### - # Update FRAME in tables + # Update CEC in tables ################################### - foreach my $value ( @$values ) { + foreach my $value (@$values) { my ($type, $name, $id, @@ -463,20 +431,55 @@ sub update_ppc { $server, $pprofile, $parent, - $ips ) = split /,/, $value; - - next if ( $type ne 'frame'); - + $ips) = split /,/, $value; + next if ($type ne 'cec'); my $predefined_node = undef; foreach my $vpdent (@vpdlist) { - if ( $vpdent->{mtm} eq $model && $vpdent->{serial} eq $serial && $vpdent->{side} eq $side ) + if ($vpdent->{mtm} eq $model && $vpdent->{serial} eq $serial) { $predefined_node = $vpdent->{node}; - if (update_node_attribs($hwtype, $type, $name, $id, $model, $serial, $side, - $server, $pprofile, $parent, $ips, - \%db, $predefined_node, \@newppclist)) + $server, $pprofile, $parent, $ips, + \%db, $predefined_node, \@ppclist)) + { + push @update_list, $value; + } + } + } + + } + + my @newppclist = $db{ppc}->getAllNodeAttribs([ 'node', 'hcp', 'id', + 'pprofile', 'parent', 'supernode', + 'comments', 'disable' ]); + ################################### + # Update FRAME in tables + ################################### + foreach my $value (@$values) { + my ($type, + $name, + $id, + $model, + $serial, + $side, + $server, + $pprofile, + $parent, + $ips) = split /,/, $value; + + next if ($type ne 'frame'); + + my $predefined_node = undef; + foreach my $vpdent (@vpdlist) + { + if ($vpdent->{mtm} eq $model && $vpdent->{serial} eq $serial && $vpdent->{side} eq $side) + { + $predefined_node = $vpdent->{node}; + + if (update_node_attribs($hwtype, $type, $name, $id, $model, $serial, $side, + $server, $pprofile, $parent, $ips, + \%db, $predefined_node, \@newppclist)) { push @update_list, $value; } @@ -486,11 +489,11 @@ sub update_ppc { } ################################### - # Commit changes + # Commit changes ################################### - foreach ( @tabs ) { - if ( exists( $db{$_}{commit} )) { - $db{$_}->commit; + foreach (@tabs) { + if (exists($db{$_}{commit})) { + $db{$_}->commit; } } return \@update_list; @@ -501,33 +504,33 @@ sub update_ppc { ########################################################################## sub update_node_attribs { - my $mgt = shift; - my $type = shift; - my $name = shift; - my $id = shift; - my $model = shift; - my $serial = shift; - my $side = shift; - my $server = shift; - my $pprofile = shift; - my $parent = shift; - my $ips = shift; - my $db = shift; + my $mgt = shift; + my $type = shift; + my $name = shift; + my $id = shift; + my $model = shift; + my $serial = shift; + my $side = shift; + my $server = shift; + my $pprofile = shift; + my $parent = shift; + my $ips = shift; + my $db = shift; my $predefined_node = shift; - my $ppclist = shift; + my $ppclist = shift; - my $updated = undef; + my $updated = undef; my $namediff = $name ne $predefined_node; - my $key_col = { node=>$predefined_node}; + my $key_col = { node => $predefined_node }; ############################# # update vpd table ############################# - my $vpdhash = $db->{vpd}->getNodeAttribs( $predefined_node, [qw(mtm serial)]); - if ( $model ne $vpdhash->{mtm} or $serial ne $vpdhash->{serial} or $namediff) + my $vpdhash = $db->{vpd}->getNodeAttribs($predefined_node, [qw(mtm serial)]); + if ($model ne $vpdhash->{mtm} or $serial ne $vpdhash->{serial} or $namediff) { - $db->{vpd}->delEntries( $key_col) if ( $namediff); - $db->{vpd}->setNodeAttribs( $name, { mtm=>$model, serial=>$serial, side=>$side}); + $db->{vpd}->delEntries($key_col) if ($namediff); + $db->{vpd}->setNodeAttribs($name, { mtm => $model, serial => $serial, side => $side }); $db->{vpd}->{commit} = 1; $updated = 1; } @@ -536,17 +539,17 @@ sub update_node_attribs # Update ppcdirect table ########################### my @users = qw(HMC admin general); - foreach my $user ( @users ) { - my $pwhash = $db->{ppcdirect}->getAttribs( {hcp=>$predefined_node,username=>$user}, qw(password comments disable)); # need regx - if ( $pwhash ) + foreach my $user (@users) { + my $pwhash = $db->{ppcdirect}->getAttribs({ hcp => $predefined_node, username => $user }, qw(password comments disable)); # need regx + if ($pwhash) { - if ( $namediff ) + if ($namediff) { - $db->{ppcdirect}->delEntries( {hcp=>$predefined_node,username=>$user}) if ( $namediff);; - $db->{ppcdirect}->setAttribs({hcp=>$name,username=>$user}, - {password=>$pwhash->{password}, - comments=>$pwhash->{comments}, - disable=>$pwhash->{disable}}); + $db->{ppcdirect}->delEntries({ hcp => $predefined_node, username => $user }) if ($namediff); + $db->{ppcdirect}->setAttribs({ hcp => $name, username => $user }, + { password => $pwhash->{password}, + comments => $pwhash->{comments}, + disable => $pwhash->{disable} }); $db->{ppcdirect}->{commit} = 1; $updated = 1; } @@ -556,35 +559,35 @@ sub update_node_attribs ############################# # update ppc table ############################# - my $ppchash = $db->{ppc}->getNodeAttribs( $predefined_node, [qw(hcp id pprofile parent)]); - if ( $ppchash->{parent} ne $predefined_node ) + my $ppchash = $db->{ppc}->getNodeAttribs($predefined_node, [qw(hcp id pprofile parent)]); + if ($ppchash->{parent} ne $predefined_node) { $parent = $ppchash->{parent}; } - if ( $server ne $ppchash->{hcp} or - $id ne $ppchash->{id} or - $pprofile ne $ppchash->{pprofile} or - $parent ne $ppchash->{parent} or - $type ne $ppchash->{nodetype} or - $namediff) + if ($server ne $ppchash->{hcp} or + $id ne $ppchash->{id} or + $pprofile ne $ppchash->{pprofile} or + $parent ne $ppchash->{parent} or + $type ne $ppchash->{nodetype} or + $namediff) { - $db->{ppc}->delEntries( $key_col) if ( $namediff); - $db->{ppc}->setNodeAttribs( $name, - { hcp=>$server, - id=>$id, - pprofile=>$pprofile, - parent=>$parent, - nodetype=>$globlehwtype{$type}, - }); - if ( $namediff) + $db->{ppc}->delEntries($key_col) if ($namediff); + $db->{ppc}->setNodeAttribs($name, + { hcp => $server, + id => $id, + pprofile => $pprofile, + parent => $parent, + nodetype => $globlehwtype{$type}, + }); + if ($namediff) { for my $ppcent (@$ppclist) { next if ($ppcent->{node} eq $predefined_node); if ($ppcent->{parent} eq $predefined_node) { - $db->{ppc}->setNodeAttribs( $ppcent->{node}, {parent=>$name}); + $db->{ppc}->setNodeAttribs($ppcent->{node}, { parent => $name }); } } } @@ -595,11 +598,11 @@ sub update_node_attribs ########################### # Update nodehm table ########################### - my $nodehmhash = $db->{nodehm}->getNodeAttribs( $predefined_node, [qw(mgt)]); - if ( $mgt ne $nodehmhash->{mgt} or $namediff) + my $nodehmhash = $db->{nodehm}->getNodeAttribs($predefined_node, [qw(mgt)]); + if ($mgt ne $nodehmhash->{mgt} or $namediff) { - $db->{nodehm}->delEntries( $key_col) if ( $namediff); - $db->{nodehm}->setNodeAttribs( $name, {mgt=>$mgt} ); + $db->{nodehm}->delEntries($key_col) if ($namediff); + $db->{nodehm}->setNodeAttribs($name, { mgt => $mgt }); $db->{nodehm}->{commit} = 1; $updated = 1; } @@ -607,11 +610,11 @@ sub update_node_attribs ########################### # Update nodetype table ########################### - my $nodetypehash = $db->{nodetype}->getNodeAttribs( $predefined_node, [qw(nodetype)]); - if ( $type ne $nodetypehash->{nodetype} or $namediff) + my $nodetypehash = $db->{nodetype}->getNodeAttribs($predefined_node, [qw(nodetype)]); + if ($type ne $nodetypehash->{nodetype} or $namediff) { - $db->{nodetype}->delEntries( $key_col) if ( $namediff); - $db->{nodetype}->setNodeAttribs( $name,{nodetype=>$globalnodetype{$type}} ); + $db->{nodetype}->delEntries($key_col) if ($namediff); + $db->{nodetype}->setNodeAttribs($name, { nodetype => $globalnodetype{$type} }); $db->{nodetype}->{commit} = 1; $updated = 1; } @@ -619,21 +622,21 @@ sub update_node_attribs ########################### # Update nodelist table ########################### - my $nodelisthash = $db->{nodelist}->getNodeAttribs( $predefined_node, [qw(groups status appstatus primarysn comments disable)]); - if ( $namediff) + my $nodelisthash = $db->{nodelist}->getNodeAttribs($predefined_node, [qw(groups status appstatus primarysn comments disable)]); + if ($namediff) { - updategroups( $name, $db->{nodelist}, $type ); + updategroups($name, $db->{nodelist}, $type); my $tmp_group = xCAT::data::ibmhwtypes::parse_group($model); if (defined($tmp_group)) { updategroups($name, $db->{nodelist}, $tmp_group); } - $db->{nodelist}->setNodeAttribs( $name, {status=>$nodelisthash->{status}, - appstatus=>$nodelisthash->{appstatus}, - primarysn=>$nodelisthash->{primarysn}, - comments=>$nodelisthash->{comments}, - disable=>$nodelisthash->{disable} - }); - $db->{nodelist}->delEntries( $key_col); + $db->{nodelist}->setNodeAttribs($name, { status => $nodelisthash->{status}, + appstatus => $nodelisthash->{appstatus}, + primarysn => $nodelisthash->{primarysn}, + comments => $nodelisthash->{comments}, + disable => $nodelisthash->{disable} + }); + $db->{nodelist}->delEntries($key_col); $db->{nodelist}->{commit} = 1; $updated = 1; } @@ -641,13 +644,13 @@ sub update_node_attribs ########################### # Update hosts table ########################### - my $hostslisthash = $db->{hosts}->getNodeAttribs( $predefined_node, [qw(ip otherinterfaces)]); - if ( $namediff ) + my $hostslisthash = $db->{hosts}->getNodeAttribs($predefined_node, [qw(ip otherinterfaces)]); + if ($namediff) { - $db->{hosts}->delEntries( $key_col); - $db->{hosts}->setNodeAttribs( $name,{ip=>$ips, - otherinterfaces=>$hostslisthash->{otherinterfaces} - } ); + $db->{hosts}->delEntries($key_col); + $db->{hosts}->setNodeAttribs($name, { ip => $ips, + otherinterfaces => $hostslisthash->{otherinterfaces} + }); $db->{hosts}->{commit} = 1; $updated = 1; } @@ -655,11 +658,11 @@ sub update_node_attribs ########################### # Update mac table ########################### - my $maclisthash = $db->{mac}->getNodeAttribs( $predefined_node, [qw(mac)]); - if ( $namediff ) + my $maclisthash = $db->{mac}->getNodeAttribs($predefined_node, [qw(mac)]); + if ($namediff) { - $db->{mac}->delEntries( $key_col); - $db->{mac}->setNodeAttribs( $name,{mac=>$maclisthash->{mac}} ); + $db->{mac}->delEntries($key_col); + $db->{mac}->setNodeAttribs($name, { mac => $maclisthash->{mac} }); $db->{mac}->{commit} = 1; $updated = 1; } @@ -668,7 +671,7 @@ sub update_node_attribs } ########################################################################## -# Updates the nodelist.groups attribute +# Updates the nodelist.groups attribute ########################################################################## sub updategroups { @@ -677,16 +680,16 @@ sub updategroups { my $hwtype = shift; ############################### - # Get current value + # Get current value ############################### - my ($ent) = $tab->getNodeAttribs( $name, ['groups'] ); - my @list = ( lc($hwtype), "all" ); + my ($ent) = $tab->getNodeAttribs($name, ['groups']); + my @list = (lc($hwtype), "all"); ############################### # Keep any existing groups ############################### - if ( defined($ent) and $ent->{groups} ) { - push @list, split( /,/, $ent->{groups} ); + if (defined($ent) and $ent->{groups}) { + push @list, split(/,/, $ent->{groups}); } ############################### # Remove duplicates @@ -695,7 +698,7 @@ sub updategroups { @saw{@list} = (); @list = keys %saw; - $tab->setNodeAttribs( $name, {groups=>join(",",@list)} ); + $tab->setNodeAttribs($name, { groups => join(",", @list) }); } @@ -714,47 +717,47 @@ sub add_ppchcp { ################################### # Open database needed ################################### - foreach ( @tabs ) { - $db{$_} = xCAT::Table->new( $_, -create=>1, -autocommit=>1 ); - if ( !$db{$_} ) { - return( "Error opening '$_'" ); + foreach (@tabs) { + $db{$_} = xCAT::Table->new($_, -create => 1, -autocommit => 1); + if (!$db{$_}) { + return ("Error opening '$_'"); } } ################################### # Update ppchcp table ################################### - my ($ent) = $db{ppchcp}->getNodeAttribs( $name,'hcp'); - if ( !defined($ent) ) { - $db{ppchcp}->setAttribs( {hcp=>$name}, - { username=>"", - password=>"" + my ($ent) = $db{ppchcp}->getNodeAttribs($name, 'hcp'); + if (!defined($ent)) { + $db{ppchcp}->setAttribs({ hcp => $name }, + { username => "", + password => "" }); } ################################### # Update nodehm table ################################### - $db{nodehm}->setNodeAttribs( $name, {mgt=>lc($hwtype)} ); - + $db{nodehm}->setNodeAttribs($name, { mgt => lc($hwtype) }); + ################################### # Update nodetype table ################################### - $db{nodetype}->setNodeAttribs( $name, {nodetype=>$globalnodetype{$hwtype}}); - $db{ppc}->setNodeAttribs( $name, {nodetype=>$globlehwtype{$hwtype}}); + $db{nodetype}->setNodeAttribs($name, { nodetype => $globalnodetype{$hwtype} }); + $db{ppc}->setNodeAttribs($name, { nodetype => $globlehwtype{$hwtype} }); ################################### # Update mac table ################################### - $db{mac}->setNodeAttribs( $name, {mac=>$mac}); + $db{mac}->setNodeAttribs($name, { mac => $mac }); ################################### # Update vpd table ################################### - $db{vpd}->setNodeAttribs( $name, {mtm=>$mtm}); - $db{vpd}->setNodeAttribs( $name, {serial=>$sn}); + $db{vpd}->setNodeAttribs($name, { mtm => $mtm }); + $db{vpd}->setNodeAttribs($name, { serial => $sn }); ################################### # Update nodelist table ################################### - updategroups( $name, $db{nodelist}, $hwtype ); + updategroups($name, $db{nodelist}, $hwtype); return undef; } @@ -767,18 +770,18 @@ sub rm_ppc { my $node = shift; my @tabs = qw(ppc nodehm nodelist); - foreach ( @tabs ) { + foreach (@tabs) { ################################### # Open table ################################### my $tab = xCAT::Table->new($_); - if ( !$tab ) { - return( "Error opening '$_'" ); + if (!$tab) { + return ("Error opening '$_'"); } ############################### # Remove entry ############################### - $tab->delEntries( {'node'=>$node} ); + $tab->delEntries({ 'node' => $node }); } return undef; } @@ -799,39 +802,39 @@ sub add_systemX { ################################### # Open database needed ################################### - foreach ( @tabs ) { - $db{$_} = xCAT::Table->new( $_, -create=>1, -autocommit=>1 ); - if ( !$db{$_} ) { - return( "Error opening '$_'" ); + foreach (@tabs) { + $db{$_} = xCAT::Table->new($_, -create => 1, -autocommit => 1); + if (!$db{$_}) { + return ("Error opening '$_'"); } } ################################### # Update mpa table ################################### - my ($ent) = $db{mpa}->getNodeAttribs( $name,'mpa'); - if ( !defined($ent) ) { - $db{mpa}->setAttribs( {mpa=>$name}, - { username=>"", - password=>"" + my ($ent) = $db{mpa}->getNodeAttribs($name, 'mpa'); + if (!defined($ent)) { + $db{mpa}->setAttribs({ mpa => $name }, + { username => "", + password => "" }); } ################################### # Update mp table ################################### - $db{mp}->setNodeAttribs( $name, - { mpa=>$name, - id=>"0" - }); + $db{mp}->setNodeAttribs($name, + { mpa => $name, + id => "0" + }); ################################### # Update nodehm table ################################### - $db{nodehm}->setNodeAttribs( $name, {mgt=>"blade"} ); + $db{nodehm}->setNodeAttribs($name, { mgt => "blade" }); ################################### # Update nodelist table ################################### - updategroups( $name, $db{nodelist}, $hwtype ); + updategroups($name, $db{nodelist}, $hwtype); return undef; } @@ -842,26 +845,26 @@ sub add_systemX { ########################################################################## sub credentials { - my $server = shift; - my $hwtype = shift; - my $user = shift; - my $pass = undef; + my $server = shift; + my $hwtype = shift; + my $user = shift; + my $pass = undef; my $user_specified = $user; - if ( !$user_specified or $user eq @{$logon{$hwtype}}[0]) + if (!$user_specified or $user eq @{ $logon{$hwtype} }[0]) { - $user = @{$logon{$hwtype}}[0]; - $pass = @{$logon{$hwtype}}[1]; + $user = @{ $logon{$hwtype} }[0]; + $pass = @{ $logon{$hwtype} }[1]; } ########################################### # find parent for fsp/bpa, use parent's attributes first ########################################### my $ntype = xCAT::DBobjUtils->getnodetype($server, "ppc"); - if ($ntype =~ /^(fsp|bpa)$/) { - my $ptab = xCAT::Table->new('ppc'); - if ($ptab) { + if ($ntype =~ /^(fsp|bpa)$/) { + my $ptab = xCAT::Table->new('ppc'); + if ($ptab) { my $parent = $ptab->getNodeAttribs($server, ["parent"]); - if ($parent and $parent->{parent}) { + if ($parent and $parent->{parent}) { my $ptype = xCAT::DBobjUtils->getnodetype($parent->{parent}, "ppc"); if (($ptype =~ /^cec$/ and $ntype =~ /^fsp$/) or ($ptype =~ /^frame$/ and $ntype =~ /^bpa$/)) { @@ -889,21 +892,21 @@ sub credentials { # if (defined($ent->{username})) { $user = $ent->{username}; } # } #} - my ($ent) = get_usr_passwd($hwtype, $user); + my ($ent) = get_usr_passwd($hwtype, $user); if ($ent) { - if (defined($ent->{password})) { $pass = $ent->{password};} - if (defined($ent->{username})) { $user = $ent->{username};} + if (defined($ent->{password})) { $pass = $ent->{password}; } + if (defined($ent->{username})) { $user = $ent->{username}; } } ########################################## - # Check table based on specific node + # Check table based on specific node ########################################## - my $tab = xCAT::Table->new( $hcptab{$hwtype} ); - if ( $tab ) { + my $tab = xCAT::Table->new($hcptab{$hwtype}); + if ($tab) { my $ent; - if ( $user_specified) - { # need regx - #($ent) = $tab->getAttribs( {hcp=>$server,username=>$user},qw(password)); - #($ent) = $tab->getNodeSpecAttribs( $server, {username=>$user},qw(password)); + if ($user_specified) + { # need regx + #($ent) = $tab->getAttribs( {hcp=>$server,username=>$user},qw(password)); + #($ent) = $tab->getNodeSpecAttribs( $server, {username=>$user},qw(password)); my @output = $tab->getNodeAttribs($server, qw(username password)); foreach my $tmp_entry (@output) { if ($tmp_entry->{username} =~ /^$user$/) { @@ -914,22 +917,22 @@ sub credentials { } else { - ($ent) = $tab->getNodeAttribs( $server, qw(username password)); + ($ent) = $tab->getNodeAttribs($server, qw(username password)); } - if ( $ent){ + if ($ent) { if (defined($ent->{password})) { $pass = $ent->{password}; } if (defined($ent->{username})) { $user = $ent->{username}; } } - ############################################################## - # If no user/passwd found, check if there is a default group - ############################################################## + ############################################################## + # If no user/passwd found, check if there is a default group + ############################################################## else { - if ( $user_specified) - { # need regx - #($ent) = $tab->getAllAttribs( {hcp=>$defaultgrp{$hwtype},username=>$user},qw(password)); - #($ent) = $tab->getNodeSpecAttribs( $defaultgrp{$hwtype}, {username=>$user},qw(password)); - my @output = $tab->getNodeAttribs( $defaultgrp{$hwtype}, qw(username password)); + if ($user_specified) + { # need regx + #($ent) = $tab->getAllAttribs( {hcp=>$defaultgrp{$hwtype},username=>$user},qw(password)); + #($ent) = $tab->getNodeSpecAttribs( $defaultgrp{$hwtype}, {username=>$user},qw(password)); + my @output = $tab->getNodeAttribs($defaultgrp{$hwtype}, qw(username password)); foreach my $tmp_entry (@output) { if ($tmp_entry->{username} =~ /^$user$/) { $ent = $tmp_entry; @@ -939,15 +942,15 @@ sub credentials { } else { - ($ent) = $tab->getNodeAttribs( $defaultgrp{$hwtype}, qw(username password)); + ($ent) = $tab->getNodeAttribs($defaultgrp{$hwtype}, qw(username password)); } - if ( $ent){ + if ($ent) { if (defined($ent->{password})) { $pass = $ent->{password}; } if (defined($ent->{username})) { $user = $ent->{username}; } } } } - return( $user,$pass ); + return ($user, $pass); } ########################################################################## @@ -955,23 +958,23 @@ sub credentials { # password for this user. ########################################################################## my %power_accounts = ( - HMC => 'abc123', + HMC => 'abc123', general => 'general', - admin => 'admin', + admin => 'admin', ); my %default_passwd_accounts = ( - system => { root => 'cluster',}, - hmc => { hscroot => 'abc123',}, - fsp => \%power_accounts, - bpa => \%power_accounts, - frame => \%power_accounts, - cec => \%power_accounts, - blade => { USERID => 'PASSW0RD', - HMC => 'PASSW0RD'}, - ipmi => { USERID => 'PASSW0RD',}, - ivm => { padmin => 'padmin',}, - vmware => { root => '',}, - vcenter => { Administrator => ''}, + system => { root => 'cluster', }, + hmc => { hscroot => 'abc123', }, + fsp => \%power_accounts, + bpa => \%power_accounts, + frame => \%power_accounts, + cec => \%power_accounts, + blade => { USERID => 'PASSW0RD', + HMC => 'PASSW0RD' }, + ipmi => { USERID => 'PASSW0RD', }, + ivm => { padmin => 'padmin', }, + vmware => { root => '', }, + vcenter => { Administrator => '' }, ); sub get_usr_passwd { @@ -986,7 +989,7 @@ sub get_usr_passwd { return undef; } if ($user) { - ($ent) = $passwdtab->getAttribs({key => $key, username => $user}, qw(password cryptmethod)); + ($ent) = $passwdtab->getAttribs({ key => $key, username => $user }, qw(password cryptmethod)); } else { ($ent) = $passwdtab->getNodeAttribs($key, qw(username password)); } @@ -997,7 +1000,7 @@ sub get_usr_passwd { $key = "bpa"; } if ($user) { - ($ent) = $passwdtab->getAttribs({key => $key, username => $user}, qw(password cryptmethod)); + ($ent) = $passwdtab->getAttribs({ key => $key, username => $user }, qw(password cryptmethod)); } else { ($ent) = $passwdtab->getNodeAttribs($key, qw(username password)); } @@ -1008,7 +1011,7 @@ sub get_usr_passwd { return undef; } if (!$user) { - my @tmp_keys = keys (%$hash); + my @tmp_keys = keys(%$hash); $user = $tmp_keys[0]; } $ent->{username} = $user; @@ -1020,7 +1023,7 @@ sub get_usr_passwd { ########################################################################## # Set userids and passwords to tables ########################################################################## -sub update_credentials +sub update_credentials { my $server = shift; @@ -1031,10 +1034,10 @@ sub update_credentials ########################################## # Set password to specific table ########################################## - my $tab = xCAT::Table->new( $hcptab{$hwtype} ); - if ( $tab ) { + my $tab = xCAT::Table->new($hcptab{$hwtype}); + if ($tab) { my $ent; - $tab->setAttribs( {hcp=>$server, username=>$user},{password=>$pass} ); + $tab->setAttribs({ hcp => $server, username => $user }, { password => $pass }); } return undef; @@ -1046,17 +1049,17 @@ sub update_credentials # if return undef, it means the ip is not invalid and won't make any definition ############################################################################# sub get_host { - my $nodename = shift; - my $type = shift; - my $mtm = shift; - my $sn = shift; - my $side = shift; - my $ip = shift; - my $cage_number = shift; - my $parmtm = shift; - my $parsn = shift; - my $pname = shift; - my $flagref = shift; + my $nodename = shift; + my $type = shift; + my $mtm = shift; + my $sn = shift; + my $side = shift; + my $ip = shift; + my $cage_number = shift; + my $parmtm = shift; + my $parsn = shift; + my $pname = shift; + my $flagref = shift; ####################################### # Extract IP from URL @@ -1064,29 +1067,31 @@ sub get_host { if ($ip) { my $nets = xCAT::NetworkUtils::my_nets(); - my $avip = getip_from_iplist( $ip, $nets); + my $avip = getip_from_iplist($ip, $nets); + #if ( !defined( $ip )) { # return undef; #} } + # get the information of existed nodes to do the migration read_from_table() unless (%::OLD_DATA_CACHE); - foreach my $oldnode ( keys %::OLD_DATA_CACHE ) + foreach my $oldnode (keys %::OLD_DATA_CACHE) { - my $tmpmtm = @{$::OLD_DATA_CACHE{$oldnode}}[0]; - my $tmpsn = @{$::OLD_DATA_CACHE{$oldnode}}[1]; - my $tmpside = @{$::OLD_DATA_CACHE{$oldnode}}[2]; - my $tmpip = @{$::OLD_DATA_CACHE{$oldnode}}[3]; - my $tmpid = @{$::OLD_DATA_CACHE{$oldnode}}[4]; - my $tmpparent = @{$::OLD_DATA_CACHE{$oldnode}}[5]; - my $tmptype = uc(@{$::OLD_DATA_CACHE{$oldnode}}[6]); - my $unmatched = @{$::OLD_DATA_CACHE{$oldnode}}[7]; + my $tmpmtm = @{ $::OLD_DATA_CACHE{$oldnode} }[0]; + my $tmpsn = @{ $::OLD_DATA_CACHE{$oldnode} }[1]; + my $tmpside = @{ $::OLD_DATA_CACHE{$oldnode} }[2]; + my $tmpip = @{ $::OLD_DATA_CACHE{$oldnode} }[3]; + my $tmpid = @{ $::OLD_DATA_CACHE{$oldnode} }[4]; + my $tmpparent = @{ $::OLD_DATA_CACHE{$oldnode} }[5]; + my $tmptype = uc(@{ $::OLD_DATA_CACHE{$oldnode} }[6]); + my $unmatched = @{ $::OLD_DATA_CACHE{$oldnode} }[7]; # used to match fsp defined by xcatsetup - # should return fast to save time + # should return fast to save time if (($type eq "BPA" or $type eq "FSP") and ($tmptype eq $type) and $pname and $side) { - if ($pname eq $tmpparent and $side eq $tmpside) { + if ($pname eq $tmpparent and $side eq $tmpside) { $$flagref = 1; return $oldnode; } @@ -1098,20 +1103,20 @@ sub get_host { next; } - if ( $tmpmtm eq $mtm and $tmpsn eq $sn) { + if ($tmpmtm eq $mtm and $tmpsn eq $sn) { my $ifip = xCAT::NetworkUtils->isIpaddr($oldnode); - if ( $ifip ) {# which means that the node is defined by the new lsslp - if ( $tmpside eq $side ) {# match! which means that node is the same as the new one - if ( $ip eq $tmpip ) { #which means that the ip is not changed - # maybe we should check if the ip is invalid and send a warning + if ($ifip) { # which means that the node is defined by the new lsslp + if ($tmpside eq $side) { # match! which means that node is the same as the new one + if ($ip eq $tmpip) { #which means that the ip is not changed + # maybe we should check if the ip is invalid and send a warning $$flagref = 1; return $ip; - } else { #which means that the ip is changed + } else { #which means that the ip is changed my $vip = check_ip($ip); - if ( !$vip ) { #which means the ip is changed and valid - # maybe we should check if the old ip is invalid and send a warning - # even so we should keep the definition as before - # because this case, we can't put check_ip in the end + if (!$vip) { #which means the ip is changed and valid + # maybe we should check if the old ip is invalid and send a warning + # even so we should keep the definition as before + # because this case, we can't put check_ip in the end $$flagref = 1; return $oldnode; } else { @@ -1120,56 +1125,58 @@ sub get_host { } } } - else { # name is not a ip + else { # name is not a ip $side =~ /(\w)\-(\w)/; my $slot = $1; - if ( $tmpside and $tmpside !~ /\-/ ) {# side is like A or B - if ( $slot eq $tmpside ) { - if ( $oldnode =~ /^Server\-/) {#judge if need to change node's name - if ( $ip eq $tmpip ) { - if ( $oldnode =~ /\-(A|B)$/) { - @{$::OLD_DATA_CACHE{$oldnode}}[7] = 0; + if ($tmpside and $tmpside !~ /\-/) { # side is like A or B + if ($slot eq $tmpside) { + if ($oldnode =~ /^Server\-/) { #judge if need to change node's name + if ($ip eq $tmpip) { + if ($oldnode =~ /\-(A|B)$/) { + @{ $::OLD_DATA_CACHE{$oldnode} }[7] = 0; $$flagref = 1; - return $oldnode; + return $oldnode; } else { - @{$::OLD_DATA_CACHE{$oldnode}}[7] = 0; + @{ $::OLD_DATA_CACHE{$oldnode} }[7] = 0; + #change node name, need to record the node here - $::UPDATE_CACHE{$mtm.'-'.$sn} = $oldnode; + $::UPDATE_CACHE{ $mtm . '-' . $sn } = $oldnode; $$flagref = 1; - return $oldnode.'-'.$slot; + return $oldnode . '-' . $slot; } - } else {# not find a matched definition, but need to use the old node name - if ($unmatched){ + } else { # not find a matched definition, but need to use the old node name + if ($unmatched) { $$flagref = 1; return $oldnode; } } - } elsif ( $tmpside =~ /\-/ ) {# end of if ( $oldnode =~ /^Server\-/) - if ( $ip eq $tmpip ) { - @{$::OLD_DATA_CACHE{$oldnode}}[7] = 0; + } elsif ($tmpside =~ /\-/) { # end of if ( $oldnode =~ /^Server\-/) + if ($ip eq $tmpip) { + @{ $::OLD_DATA_CACHE{$oldnode} }[7] = 0; $$flagref = 1; return $oldnode; - } else{ - if ($unmatched){ + } else { + if ($unmatched) { $$flagref = 1; return $oldnode; } } } } - } elsif ( $tmpside =~ /\-/ ){ - if ( $side eq $tmpside ) { + } elsif ($tmpside =~ /\-/) { + if ($side eq $tmpside) { $$flagref = 1; return $oldnode; } - } elsif ( !$tmpside ) { - if ( $oldnode =~ /^Server\-/) {#judge if need to change node's name - if ( $oldnode !~ /\-(A|B)$/ ) { + } elsif (!$tmpside) { + if ($oldnode =~ /^Server\-/) { #judge if need to change node's name + if ($oldnode !~ /\-(A|B)$/) { delete $::OLD_DATA_CACHE{$oldnode}; - $$flagref = 1; - return $oldnode."-".$slot; + $$flagref = 1; + return $oldnode . "-" . $slot; } } + # if mtms could match but side not defined, we will trate # it as the result by rscan. And alway use its name. delete $::OLD_DATA_CACHE{$oldnode}; @@ -1177,20 +1184,21 @@ sub get_host { return $oldnode; } } - }# end of if ($tmpmtm eq $mtm and $tmpsn eq $sn) + } # end of if ($tmpmtm eq $mtm and $tmpsn eq $sn) - } - if ( ($type eq "FRAME" or $type eq "CEC") and ($type eq $tmptype)){ - if ( !$tmpmtm and !$tmpid) { + } + if (($type eq "FRAME" or $type eq "CEC") and ($type eq $tmptype)) { + if (!$tmpmtm and !$tmpid) { next; } + # user may define cec only with parent /id /type # we should match this situation - if ( ($type eq "CEC") and $parmtm and $parsn and $cage_number ) { - my $tpparmtm = @{$::OLD_DATA_CACHE{$tmpparent}}[0]; - my $tpparsn = @{$::OLD_DATA_CACHE{$tmpparent}}[1]; - if ( ($tpparmtm eq $parmtm) and ($tpparsn eq $parsn) and ($cage_number eq $tmpid) and ($type eq $tmptype) ) { + if (($type eq "CEC") and $parmtm and $parsn and $cage_number) { + my $tpparmtm = @{ $::OLD_DATA_CACHE{$tmpparent} }[0]; + my $tpparsn = @{ $::OLD_DATA_CACHE{$tmpparent} }[1]; + if (($tpparmtm eq $parmtm) and ($tpparsn eq $parsn) and ($cage_number eq $tmpid) and ($type eq $tmptype)) { $$flagref = 1; return $oldnode; } @@ -1198,15 +1206,16 @@ sub get_host { # user may define cec/frame only with mtms # but what we consider here is just the data in xCAT 2.6 - if ($tmpmtm eq $mtm and $tmpsn eq $sn and $tmptype eq $type) { - if ( $oldnode =~ /^Server\-/) {#judge if need to change node's name - if ( $oldnode =~ /(\-A)$/) { + if ($tmpmtm eq $mtm and $tmpsn eq $sn and $tmptype eq $type) { + if ($oldnode =~ /^Server\-/) { #judge if need to change node's name + if ($oldnode =~ /(\-A)$/) { $nodename = s/(\-A)$//; + # should send a warning here $$flagref = 1; return $nodename; } - else { + else { $$flagref = 1; return $oldnode; } @@ -1215,16 +1224,16 @@ sub get_host { return $oldnode; } } - } # end of foreach my $oldnode ( keys %::OLD_DATA_CACHE ), not match + } # end of foreach my $oldnode ( keys %::OLD_DATA_CACHE ), not match } # not matched, use the new name my $ifip = xCAT::NetworkUtils->isIpaddr($nodename); unless ($ifip) { return $nodename; - }else { + } else { my $vip = check_ip($nodename); - if ( $vip ) {#which means the ip is a valid one + if ($vip) { #which means the ip is a valid one return $nodename; } else { return undef; @@ -1238,35 +1247,35 @@ sub get_host { ########################################################################## sub getip_from_iplist { - my $iplist = shift; - my $nets = shift; - my $inc = shift; + my $iplist = shift; + my $nets = shift; + my $inc = shift; - my @ips = split /,/, $iplist; + my @ips = split /,/, $iplist; my @ips2 = split /,/, $inc; - if ( $inc) + if ($inc) { for my $net (keys %$nets) { my $flag = 1; for my $einc (@ips2) { - if ( $nets->{$net} eq $einc) { + if ($nets->{$net} eq $einc) { $flag = 0; } } - delete $nets->{$net} if ($flag) ; + delete $nets->{$net} if ($flag); } } for my $ip (@ips) { - next if ( $ip =~ /:/); #skip IPV6 addresses - for my $net ( keys %$nets) + next if ($ip =~ /:/); #skip IPV6 addresses + for my $net (keys %$nets) { - my ($n,$m) = split /\//,$net; - if ( xCAT::NetworkUtils::isInSameSubnet( $n, $ip, $m, 1) and - xCAT::NetworkUtils::isPingable( $ip)) + my ($n, $m) = split /\//, $net; + if (xCAT::NetworkUtils::isInSameSubnet($n, $ip, $m, 1) and + xCAT::NetworkUtils::isPingable($ip)) { return $ip; } @@ -1280,77 +1289,78 @@ sub read_from_table { my %typehash; my %iphash; my %vpdhash; - if ( !(%::OLD_DATA_CACHE)) + if (!(%::OLD_DATA_CACHE)) { # find out all the existed nodes' ipaddresses - my $hoststab = xCAT::Table->new('hosts'); - if ( $hoststab ) { - my @ipentries = $hoststab->getAllNodeAttribs( ['node','ip'] ); - for my $ipentry ( @ipentries ) { - $iphash{$ipentry->{node}} = $ipentry->{ip}; + my $hoststab = xCAT::Table->new('hosts'); + if ($hoststab) { + my @ipentries = $hoststab->getAllNodeAttribs([ 'node', 'ip' ]); + for my $ipentry (@ipentries) { + $iphash{ $ipentry->{node} } = $ipentry->{ip}; } } else { return 1; } #find out all the existed nodes' type - my $nodetypetab = xCAT::Table->new('nodetype'); - if ( $nodetypetab ) { - my @typeentries = $nodetypetab->getAllNodeAttribs( ['node','nodetype'] ); - for my $typeentry ( @typeentries) { - $typehash{$typeentry->{node}} = $typeentry->{nodetype}; + my $nodetypetab = xCAT::Table->new('nodetype'); + if ($nodetypetab) { + my @typeentries = $nodetypetab->getAllNodeAttribs([ 'node', 'nodetype' ]); + for my $typeentry (@typeentries) { + $typehash{ $typeentry->{node} } = $typeentry->{nodetype}; } } else { return 2; } # find out all the existed nodes' mtms and side - my $vpdtab = xCAT::Table->new( 'vpd' ); - if ( $vpdtab ) { - my @vpdentries = $vpdtab->getAllNodeAttribs(['node','mtm','serial','side']); - for my $entry ( @vpdentries ) { - @{$vpdhash{$entry->{node}}}[0] = $entry->{mtm}; - @{$vpdhash{$entry->{node}}}[1] = $entry->{serial}; - @{$vpdhash{$entry->{node}}}[2] = $entry->{side}; + my $vpdtab = xCAT::Table->new('vpd'); + if ($vpdtab) { + my @vpdentries = $vpdtab->getAllNodeAttribs([ 'node', 'mtm', 'serial', 'side' ]); + for my $entry (@vpdentries) { + @{ $vpdhash{ $entry->{node} } }[0] = $entry->{mtm}; + @{ $vpdhash{ $entry->{node} } }[1] = $entry->{serial}; + @{ $vpdhash{ $entry->{node} } }[2] = $entry->{side}; } } else { return 3; } + # find out all the existed nodes' attributes - my $ppctab = xCAT::Table->new('ppc'); - if ( $ppctab ) { - my @identries = $ppctab->getAllNodeAttribs( ['node','id','parent','nodetype'] ); - for my $entry ( @identries ) { + my $ppctab = xCAT::Table->new('ppc'); + if ($ppctab) { + my @identries = $ppctab->getAllNodeAttribs([ 'node', 'id', 'parent', 'nodetype' ]); + for my $entry (@identries) { next if ($entry->{nodetype} =~ /lpar/); - @{$::OLD_DATA_CACHE{$entry->{node}}}[0] = @{$vpdhash{$entry->{node}}}[0];#mtm - @{$::OLD_DATA_CACHE{$entry->{node}}}[1] = @{$vpdhash{$entry->{node}}}[1];#sn - @{$::OLD_DATA_CACHE{$entry->{node}}}[2] = @{$vpdhash{$entry->{node}}}[2];#side - # find node ip address, check node name first, then check hosts table + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[0] = @{ $vpdhash{ $entry->{node} } }[0]; #mtm + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[1] = @{ $vpdhash{ $entry->{node} } }[1]; #sn + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[2] = @{ $vpdhash{ $entry->{node} } }[2]; #side + # find node ip address, check node name first, then check hosts table my $ifip = xCAT::NetworkUtils->isIpaddr($entry->{node}); - if ( $ifip ) + if ($ifip) { - @{$::OLD_DATA_CACHE{$entry->{node}}}[3] = $entry->{node};#ip + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[3] = $entry->{node}; #ip } else { - if ( exists ($iphash{$entry->{node}}) ) { - @{$::OLD_DATA_CACHE{$entry->{node}}}[3] = $iphash{$entry->{node}};#ip + if (exists($iphash{ $entry->{node} })) { + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[3] = $iphash{ $entry->{node} }; #ip } - else { - @{$::OLD_DATA_CACHE{$entry->{node}}}[3] = "";#ip + else { + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[3] = ""; #ip } } - @{$::OLD_DATA_CACHE{$entry->{node}}}[4] = $entry->{id};#id - @{$::OLD_DATA_CACHE{$entry->{node}}}[5] = $entry->{parent};#parent - if ( exists $entry->{nodetype}) { - @{$::OLD_DATA_CACHE{$entry->{node}}}[6] = $entry->{nodetype};#nodetype + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[4] = $entry->{id}; #id + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[5] = $entry->{parent}; #parent + if (exists $entry->{nodetype}) { + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[6] = $entry->{nodetype}; #nodetype } else { - if ( exists ($typehash{$entry->{node}}) ) { - @{$::OLD_DATA_CACHE{$entry->{node}}}[6] = $typehash{$entry->{node}}; + if (exists($typehash{ $entry->{node} })) { + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[6] = $typehash{ $entry->{node} }; } else { - @{$::OLD_DATA_CACHE{$entry->{node}}}[6] = ""; + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[6] = ""; } - } - @{$::OLD_DATA_CACHE{$entry->{node}}}[7] = 1; + } + @{ $::OLD_DATA_CACHE{ $entry->{node} } }[7] = 1; } } else { @@ -1364,8 +1374,8 @@ sub read_from_table { # return 1 if valid, 0 if invalid ########################################################################## sub check_ip { - my $myip = shift; - my $firstoctet = $myip; + my $myip = shift; + my $firstoctet = $myip; my @invalidiplist = ( "192.168.2.144", "192.168.2.145", @@ -1383,7 +1393,7 @@ sub check_ip { "127.0.0.0", "127", 0, - ); + ); $firstoctet =~ s/^(\d+)\..*/$1/; if ($firstoctet >= 224 and $firstoctet <= 239) { @@ -1391,7 +1401,7 @@ sub check_ip { } foreach (@invalidiplist) { - if ( $myip =~ /^($_)/ ) + if ($myip =~ /^($_)/) { return 0; } diff --git a/perl-xCAT/xCAT/PPCenergy.pm b/perl-xCAT/xCAT/PPCenergy.pm index eb8c53723..0e7e7047b 100644 --- a/perl-xCAT/xCAT/PPCenergy.pm +++ b/perl-xCAT/xCAT/PPCenergy.pm @@ -16,37 +16,39 @@ use xCAT::DBobjUtils; use xCAT::FSPUtils; use xCAT::TableUtils; %::QUERY_ATTRS = ( -'savingstatus' => 1, -'dsavingstatus' => 1, -'cappingstatus' => 1, -'cappingmaxmin' => 1, -'cappingvalue' => 1, -'cappingsoftmin' => 1, -'averageAC' => 1, -'averageDC' => 1, -'ambienttemp' => 1, -'exhausttemp' => 1, -'CPUspeed' => 1, -'syssbpower' => 1, -'sysIPLtime' => 1, -# for FFO, only supported when communicating to fsp directly -'ffoMin' => 1, -'ffoVmin' => 1, -'ffoTurbo' => 1, -'ffoNorm' => 1, -'fsavingstatus' => 1, -'ffovalue' => 1, + 'savingstatus' => 1, + 'dsavingstatus' => 1, + 'cappingstatus' => 1, + 'cappingmaxmin' => 1, + 'cappingvalue' => 1, + 'cappingsoftmin' => 1, + 'averageAC' => 1, + 'averageDC' => 1, + 'ambienttemp' => 1, + 'exhausttemp' => 1, + 'CPUspeed' => 1, + 'syssbpower' => 1, + 'sysIPLtime' => 1, + + # for FFO, only supported when communicating to fsp directly + 'ffoMin' => 1, + 'ffoVmin' => 1, + 'ffoTurbo' => 1, + 'ffoNorm' => 1, + 'fsavingstatus' => 1, + 'ffovalue' => 1, ); %::SET_ATTRS = ( -'savingstatus' => 1, -'dsavingstatus' => 1, -'cappingstatus' => 1, -'cappingwatt' => 1, -'cappingperc' => 1, -# for FFO -'fsavingstatus' => 1, -'ffovalue' => 1, + 'savingstatus' => 1, + 'dsavingstatus' => 1, + 'cappingstatus' => 1, + 'cappingwatt' => 1, + 'cappingperc' => 1, + + # for FFO + 'fsavingstatus' => 1, + 'ffovalue' => 1, ); $::CIM_CLIENT_PATH = "$::XCATROOT/sbin/xCAT_cim_client"; @@ -55,30 +57,30 @@ $::CIM_CLIENT_PATH = "$::XCATROOT/sbin/xCAT_cim_client"; sub parse_args { my $request = shift; - my %opt = (); - my $cmd = $request->{command}; - my $args = $request->{arg}; - my $nodes = $request->{node}; + my %opt = (); + my $cmd = $request->{command}; + my $args = $request->{arg}; + my $nodes = $request->{node}; my $query_attrs = (); # The attributes list for query operation - my $set_pair = (); # The attribute need to be set. e.g. savingstatus=on - my $set_flag = (); # Indicate there's setting param in the argv - my $argv_flag = (); # Indicate there's param in the argv - my @notfspnodes = (); # The nodes list which are not fsp + my $set_pair = (); # The attribute need to be set. e.g. savingstatus=on + my $set_flag = (); # Indicate there's setting param in the argv + my $argv_flag = (); # Indicate there's param in the argv + my @notfspnodes = (); # The nodes list which are not fsp # set the usage subroutine local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string ] ); + return ([ $_[0], $usage_string ]); }; if ($request->{arg}) { - @ARGV = @{$request->{arg}}; + @ARGV = @{ $request->{arg} }; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); if ($nodes) { - if (!GetOptions( 'V' => \$::VERBOSE )) { + if (!GetOptions('V' => \$::VERBOSE)) { return (&usage()); } @@ -92,7 +94,7 @@ sub parse_args { # Check the validity of the parameters of Query and Set foreach my $attr (@ARGV) { - my ($set_attr, $set_value) = split (/=/, $attr); + my ($set_attr, $set_value) = split(/=/, $attr); if (defined($set_value)) { if ($argv_flag) { return (&usage()); @@ -100,24 +102,24 @@ sub parse_args { if ($::SET_ATTRS{$set_attr} != 1) { return (&usage()); } - - if (($set_attr eq "savingstatus" || $set_attr eq "fsavingstatus") - && ($set_value ne "on" && $set_value ne "off")) { + + if (($set_attr eq "savingstatus" || $set_attr eq "fsavingstatus") + && ($set_value ne "on" && $set_value ne "off")) { return (&usage()); } elsif ($set_attr eq "dsavingstatus" - && ($set_value ne "off" - && $set_value ne "on-norm" && $set_value ne "on-maxp")) { + && ($set_value ne "off" + && $set_value ne "on-norm" && $set_value ne "on-maxp")) { return (&usage()); - } elsif ($set_attr eq "cappingstatus" - && ($set_value ne "on" && $set_value ne "off")) { + } elsif ($set_attr eq "cappingstatus" + && ($set_value ne "on" && $set_value ne "off")) { return (&usage()); - } elsif ( ($set_attr eq "cappingwatt" - || $set_attr eq "cappingperc" || $set_attr eq "ffovalue") - && $set_value =~ /\D/) { + } elsif (($set_attr eq "cappingwatt" + || $set_attr eq "cappingperc" || $set_attr eq "ffovalue") + && $set_value =~ /\D/) { return (&usage()); } - - $set_pair = $set_attr."=".$set_value; + + $set_pair = $set_attr . "=" . $set_value; $set_flag = 1; } else { if ($set_flag) { @@ -130,14 +132,14 @@ sub parse_args { if (!$set_flag) { my @query_list = @ARGV; - + if ($query_list[0] eq "all" and $#query_list == 0) { $query_attrs = "all"; } else { my @no_dup_query_list = (); foreach my $q_attr (@query_list) { chomp($q_attr); - + if ($::QUERY_ATTRS{$q_attr} != 1) { return (&usage()); } @@ -146,26 +148,27 @@ sub parse_args { push @no_dup_query_list, $q_attr; } } - $query_attrs = join (',', @no_dup_query_list); + $query_attrs = join(',', @no_dup_query_list); } } } else { + # If has not nodes, the -h or -v option must be input - if (!GetOptions( 'h|help' => \$::HELP, - 'v|version' => \$::VERSION)) { + if (!GetOptions('h|help' => \$::HELP, + 'v|version' => \$::VERSION)) { return (&usage()); } - - if (! ($::HELP || $::VERSION) ) { + + if (!($::HELP || $::VERSION)) { return (&usage()); } if ($::HELP) { return (&usage()); } - + if ($::VERSION) { my $version_string = xCAT::Usage->getVersion('renergy'); - return( [ $_[0], $version_string] ); + return ([ $_[0], $version_string ]); } if (scalar(@ARGV)) { @@ -183,7 +186,7 @@ sub parse_args { #} #my $nodetype_v = $nodetype_tb->getNodesAttribs($nodes, ['nodetype']); - my $nodetyperef = xCAT::DBobjUtils->getnodetype($nodes, "ppc"); + my $nodetyperef = xCAT::DBobjUtils->getnodetype($nodes, "ppc"); my $i = 0; foreach my $node (@{$nodes}) { if ($$nodetyperef{$node} ne 'fsp' && @@ -192,10 +195,11 @@ sub parse_args { } $i++; } + #$nodetype_tb->close(); if (@notfspnodes) { - return ([undef, "Error: The hardware type of following nodes are not fsp or cec: ".join(',', @notfspnodes)]); + return ([ undef, "Error: The hardware type of following nodes are not fsp or cec: " . join(',', @notfspnodes) ]); } if ($query_attrs) { @@ -210,28 +214,28 @@ sub parse_args { # Handle the energy query and setting work sub renergy { - my $request = shift; - my $hcphost = shift; + my $request = shift; + my $hcphost = shift; my $nodehash = shift; my @return_msg = (); - my $opt = $request->{'opt'}; + my $opt = $request->{'opt'}; my $verbose = $opt->{'verbose'}; - # Get the CEC + # Get the CEC my ($node, $attrs) = %$nodehash; my $cec_name = @$attrs[2]; - my $hw_type = @$attrs[4]; - + my $hw_type = @$attrs[4]; + if (!$cec_name) { - return ([[$node, "ERROR: Cannot find the cec name, check the attributes: vpd.serial, vpd.mtm.", 1]]); + return ([ [ $node, "ERROR: Cannot find the cec name, check the attributes: vpd.serial, vpd.mtm.", 1 ] ]); } # Check the existence of cim client - if ( (! -f $::CIM_CLIENT_PATH) - || (! -x $::CIM_CLIENT_PATH) ) { - return ([[$node, "ERROR: Cannot find the Energy Management Plugin for xCAT [$::CIM_CLIENT_PATH] or it's NOT executable. Please install the xCAT-cimclient package correctly. Get more information from man page of renergy command.", 1]]); + if ((!-f $::CIM_CLIENT_PATH) + || (!-x $::CIM_CLIENT_PATH)) { + return ([ [ $node, "ERROR: Cannot find the Energy Management Plugin for xCAT [$::CIM_CLIENT_PATH] or it's NOT executable. Please install the xCAT-cimclient package correctly. Get more information from man page of renergy command.", 1 ] ]); } my $verb_arg = ""; @@ -245,123 +249,127 @@ sub renergy { my $password; if ($hcp_type eq "hmc") { ($user, $password) = xCAT::PPCdb::credentials($hcphost, $hcp_type); - } else { - ($user, $password) = xCAT::PPCdb::credentials($hcphost, $hcp_type,'HMC'); + } else { + ($user, $password) = xCAT::PPCdb::credentials($hcphost, $hcp_type, 'HMC'); } - my $fsps; #The node of fsp that belong to the cec + my $fsps; #The node of fsp that belong to the cec my @hcps_ip; if ($hcp_type ne "hmc" && $hw_type eq "cec") { $fsps = xCAT::DBobjUtils->getchildren($node); - if( !defined($fsps) ) { - return ([[$node, "Failed to get the FSPs for the cec $hcphost.", -1]]); + if (!defined($fsps)) { + return ([ [ $node, "Failed to get the FSPs for the cec $hcphost.", -1 ] ]); } + #my $hcp_ip = xCAT::NetworkUtils::getNodeIPaddress($hcphost); my $hcp_ip = xCAT::FSPUtils::getIPaddress($request, $hw_type, $hcphost); if (!defined($hcp_ip) or ($hcp_ip == -3)) { - return ([[$node, "Failed to get IP address for $hcphost.", -1]]); + return ([ [ $node, "Failed to get IP address for $hcphost.", -1 ] ]); } push @hcps_ip, split(',', $hcp_ip); my $fsp_node = $$fsps[0]; - ($user, $password) = xCAT::PPCdb::credentials( $fsp_node, "fsp",'HMC'); - if ( !$password) { - return ([[$node, "Cannot get password of userid 'HMC'. Please check table 'ppchcp' or 'ppcdirect'.", -1]]); + ($user, $password) = xCAT::PPCdb::credentials($fsp_node, "fsp", 'HMC'); + if (!$password) { + return ([ [ $node, "Cannot get password of userid 'HMC'. Please check table 'ppchcp' or 'ppcdirect'.", -1 ] ]); } } else { + # for the case that hcp is hmc or fsp push @hcps_ip, xCAT::NetworkUtils::getNodeIPaddress($hcphost); } if (!$user || !$password) { - return ([[$node, "Cannot get user:password for the node. Please check table 'ppchcp' or 'ppcdirect'.", -1]]); + return ([ [ $node, "Cannot get user:password for the node. Please check table 'ppchcp' or 'ppcdirect'.", -1 ] ]); } # secure passwd in verbose mode my $tmpv = $verbose; $verbose = 0; if ($verbose) { - push @return_msg, [$node, "Attributes of $node:\n User=$user\n Password=$password\n CEC=$cec_name\n nodetype=$hw_type\n inithcp=$hcphost\n hcps=@hcps_ip\n hcptype=$hcp_type", 0]; + push @return_msg, [ $node, "Attributes of $node:\n User=$user\n Password=$password\n CEC=$cec_name\n nodetype=$hw_type\n inithcp=$hcphost\n hcps=@hcps_ip\n hcptype=$hcp_type", 0 ]; } $verbose = $tmpv; my @pingable_hcp; - if (-x '/usr/bin/nmap' or -x '/usr/local/bin/nmap') { #use nmap - #print "use nmap\n"; - if ($verbose) { - push @return_msg, [$node, "Checking ping status using nmap for @hcps_ip", 0]; - } - my %deadnodes; - foreach (@hcps_ip) { - $deadnodes{$_}=1; - } + if (-x '/usr/bin/nmap' or -x '/usr/local/bin/nmap') { #use nmap + #print "use nmap\n"; + if ($verbose) { + push @return_msg, [ $node, "Checking ping status using nmap for @hcps_ip", 0 ]; + } + my %deadnodes; + foreach (@hcps_ip) { + $deadnodes{$_} = 1; + } - # get additional options from site table - my @nmap_options = xCAT::TableUtils->get_site_attribute("nmapoptions"); - my $more_options = $nmap_options[0]; + # get additional options from site table + my @nmap_options = xCAT::TableUtils->get_site_attribute("nmapoptions"); + my $more_options = $nmap_options[0]; - open (NMAP, "nmap -PE --system-dns --send-ip -sP $more_options ". join(' ',@hcps_ip) . " 2> /dev/null|") or die("Cannot open nmap pipe: $!"); - my $node; - while () { - #print "$_\n"; - if (/Host (.*) \((.*)\) appears to be up/) { - $node=$2; - unless ($deadnodes{$node}) { - foreach (keys %deadnodes) { - if ($node =~ /^$_\./) { - $node = $_; - last; - } - } - } - delete $deadnodes{$node}; - if ($verbose) { - push @return_msg, [$node, $_, 0]; - } - push(@pingable_hcp, $node); - } elsif (/Nmap scan report for ([^ ]*)/) { - $node=$1; - } elsif (/Host is up./) { - unless ($deadnodes{$node}) { - foreach (keys %deadnodes) { - if ($node =~ /^$_\./) { - $node = $_; - last; - } - } - } - delete $deadnodes{$node}; - push(@pingable_hcp, $node); - } - } + open(NMAP, "nmap -PE --system-dns --send-ip -sP $more_options " . join(' ', @hcps_ip) . " 2> /dev/null|") or die("Cannot open nmap pipe: $!"); + my $node; + while () { + + #print "$_\n"; + if (/Host (.*) \((.*)\) appears to be up/) { + $node = $2; + unless ($deadnodes{$node}) { + foreach (keys %deadnodes) { + if ($node =~ /^$_\./) { + $node = $_; + last; + } + } + } + delete $deadnodes{$node}; + if ($verbose) { + push @return_msg, [ $node, $_, 0 ]; + } + push(@pingable_hcp, $node); + } elsif (/Nmap scan report for ([^ ]*)/) { + $node = $1; + } elsif (/Host is up./) { + unless ($deadnodes{$node}) { + foreach (keys %deadnodes) { + if ($node =~ /^$_\./) { + $node = $_; + last; + } + } + } + delete $deadnodes{$node}; + push(@pingable_hcp, $node); + } + } } else { - #use fping - #print "use fping\n"; - my $master = xCAT::TableUtils->get_site_Master(); - my $masterip = xCAT::NetworkUtils->getipaddr($master); - if ($masterip =~ /:/) { #IPv6, needs fping6 support - if (!-x '/usr/bin/fping6') - { - push @return_msg, [$node, "fping6 is not availabe for IPv6 ping.", -1]; - return \@return_msg; - } - open (FPING, "fping6 ".join(' ',@hcps_ip). " 2>&1 |") or die("Cannot open fping pipe: $!"); - } else { - open (FPING, "fping ".join(' ',@hcps_ip). " 2>&1 |") or die("Cannot open fping pipe: $!"); - } - - while () { - if ($verbose) { - push @return_msg, [$node, $_, 0]; - } - if ($_ =~ /is alive/) { - s/ is alive//; - push @pingable_hcp, $_; - } - } + + #use fping + #print "use fping\n"; + my $master = xCAT::TableUtils->get_site_Master(); + my $masterip = xCAT::NetworkUtils->getipaddr($master); + if ($masterip =~ /:/) { #IPv6, needs fping6 support + if (!-x '/usr/bin/fping6') + { + push @return_msg, [ $node, "fping6 is not availabe for IPv6 ping.", -1 ]; + return \@return_msg; + } + open(FPING, "fping6 " . join(' ', @hcps_ip) . " 2>&1 |") or die("Cannot open fping pipe: $!"); + } else { + open(FPING, "fping " . join(' ', @hcps_ip) . " 2>&1 |") or die("Cannot open fping pipe: $!"); + } + + while () { + if ($verbose) { + push @return_msg, [ $node, $_, 0 ]; + } + if ($_ =~ /is alive/) { + s/ is alive//; + push @pingable_hcp, $_; + } + } } if (!@pingable_hcp) { - push @return_msg, [$node, "No hcp can be pinged.", -1]; + push @return_msg, [ $node, "No hcp can be pinged.", -1 ]; return \@return_msg; } @@ -370,18 +378,19 @@ sub renergy { my @noerr_msg; my @last_msg; foreach my $hcp (@pingable_hcp) { - push @noerr_msg, @lastnoerr_msg; + push @noerr_msg, @lastnoerr_msg; @lastnoerr_msg = (); - @last_msg = (); + @last_msg = (); + # Generate the url path for CIM communication chomp($hcp); - my $url_path = "https://"."$user".":"."$password"."\@"."$hcp".":5989"; + my $url_path = "https://" . "$user" . ":" . "$password" . "\@" . "$hcp" . ":5989"; # Not display password in command outupt. - my $display_url_path = "https://"."$user".":"."xxxxxx"."\@"."$hcp".":5989"; - + my $display_url_path = "https://" . "$user" . ":" . "xxxxxx" . "\@" . "$hcp" . ":5989"; + # Execute the request - my $cmd = ""; + my $cmd = ""; my $display_cmd = ""; if ($opt->{'set'}) { $cmd = "$::CIM_CLIENT_PATH $verb_arg -u $url_path -n $cec_name -o $opt->{'set'}"; @@ -390,21 +399,21 @@ sub renergy { $cmd = "$::CIM_CLIENT_PATH $verb_arg -u $url_path -n $cec_name -o $opt->{'query'}"; $display_cmd = "$::CIM_CLIENT_PATH $verb_arg -u $display_url_path -n $cec_name -o $opt->{'query'}"; } - + if ($verbose) { - push @noerr_msg, [$node, "Run following command: $display_cmd", 0]; + push @noerr_msg, [ $node, "Run following command: $display_cmd", 0 ]; } - - # Disable the CHID signal before run the command. Otherwise the + + # Disable the CHID signal before run the command. Otherwise the # $? value of `$cmd` will come from handler of CHID signal - $SIG{CHLD} = 'DEFAULT'; - + $SIG{CHLD} = 'DEFAULT'; + # Call the xCAT_cim_client to query or set the energy capabilities $cmd .= " 2>&1"; # secure passwd in verbose mode my $tmpv = $::VERBOSE; - $::VERBOSE = 0; + $::VERBOSE = 0; my @result = xCAT::Utils->runcmd("$cmd", -1); $::VERBOSE = $tmpv; @@ -413,8 +422,8 @@ sub renergy { if ($line =~ /^\s*$/) { next; } - push @lastnoerr_msg, [$node, $line, 0]; - push @last_msg, [$node, $line, $::RUNCMD_RC]; + push @lastnoerr_msg, [ $node, $line, 0 ]; + push @last_msg, [ $node, $line, $::RUNCMD_RC ]; } if (!$::RUNCMD_RC) { last; @@ -424,7 +433,7 @@ sub renergy { # only display the correct msg when getting correct result from one fsp if ($::RUNCMD_RC || $verbose) { push @return_msg, @noerr_msg; - } + } push @return_msg, @last_msg; return \@return_msg; diff --git a/perl-xCAT/xCAT/PPCfsp.pm b/perl-xCAT/xCAT/PPCfsp.pm index 9ae78cb1e..081ac4217 100644 --- a/perl-xCAT/xCAT/PPCfsp.pm +++ b/perl-xCAT/xCAT/PPCfsp.pm @@ -9,7 +9,7 @@ use HTML::Form; use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::Usage; use Socket; -use xCAT::PPCdb; +use xCAT::PPCdb; use xCAT::MsgUtils qw(verbose_message); use xCAT::Utils; use xCAT::TableUtils; @@ -17,30 +17,30 @@ use xCAT::NetworkUtils; ########################################## # Globals ########################################## -my %cmds = ( - rpower => { - state => ["Power On/Off System", \&state], - powercmd => ["Power On/Off System", \&powercmd], - powercmd_boot => ["Power On/Off System", \&boot], - reset => ["System Reboot", \&reset] }, - reventlog => { - all => ["Error/Event Logs", \&all], - all_clear => ["Error/Event Logs", \&all_clear], - entries => ["Error/Event Logs", \&entries], - clear => ["Error/Event Logs", \&clear] }, - rspconfig => { - memdecfg => ["Memory Deconfiguration", \&memdecfg], - decfg => ["Deconfiguration Policies", \&decfg], - procdecfg => ["Processor Deconfiguration", \&procdecfg], - iocap => ["I/O Adapter Enlarged Capacity", \&iocap], - time => ["Time Of Day", \&time], - date => ["Time Of Day", \&date], - autopower => ["Auto Power Restart", \&autopower], - sysdump => ["System Dump", \&sysdump], - spdump => ["Service Processor Dump", \&spdump], - network => ["Network Configuration", \&netcfg], - dev => ["Service Processor Command Line", \&devenable], - celogin1 => ["Service Processor Command Line", \&ce1enable]}, +my %cmds = ( + rpower => { + state => [ "Power On/Off System", \&state ], + powercmd => [ "Power On/Off System", \&powercmd ], + powercmd_boot => [ "Power On/Off System", \&boot ], + reset => [ "System Reboot", \&reset ] }, + reventlog => { + all => [ "Error/Event Logs", \&all ], + all_clear => [ "Error/Event Logs", \&all_clear ], + entries => [ "Error/Event Logs", \&entries ], + clear => [ "Error/Event Logs", \&clear ] }, + rspconfig => { + memdecfg => [ "Memory Deconfiguration", \&memdecfg ], + decfg => [ "Deconfiguration Policies", \&decfg ], + procdecfg => [ "Processor Deconfiguration", \&procdecfg ], + iocap => [ "I/O Adapter Enlarged Capacity", \&iocap ], + time => [ "Time Of Day", \&time ], + date => [ "Time Of Day", \&date ], + autopower => [ "Auto Power Restart", \&autopower ], + sysdump => [ "System Dump", \&sysdump ], + spdump => [ "Service Processor Dump", \&spdump ], + network => [ "Network Configuration", \&netcfg ], + dev => [ "Service Processor Command Line", \&devenable ], + celogin1 => [ "Service Processor Command Line", \&ce1enable ] }, ); @@ -57,30 +57,30 @@ sub handler { ##################################### # Convert command to correct format ##################################### - if ( ref($request->{method}) ne "HASH" ) { - $request->{method} = [{$request->{method}=>undef}]; + if (ref($request->{method}) ne "HASH") { + $request->{method} = [ { $request->{method} => undef } ]; } ##################################### - # Process FSP command + # Process FSP command ##################################### my @outhash; - my $result = process_cmd( $exp, $request ); + my $result = process_cmd($exp, $request); - foreach ( @$result ) { + foreach (@$result) { my %output; $output{node}->[0]->{name}->[0] = $request->{host}; - $output{node}->[0]->{data}->[0]->{contents}->[0] = $server. ": ".@$_[1]; + $output{node}->[0]->{data}->[0]->{contents}->[0] = $server . ": " . @$_[1]; $output{node}->[0]->{cmd}->[0] = @$_[2]; $output{errorcode} = @$_[0]; push @outhash, \%output; } ##################################### - # Disconnect from FSP + # Disconnect from FSP ##################################### unless ($flag) { - xCAT::PPCfsp::disconnect( $exp ); - } - return( \@outhash ); + xCAT::PPCfsp::disconnect($exp); + } + return (\@outhash); } @@ -97,13 +97,13 @@ sub connect { my $lwp_log; ################################## - # Use timeout from site table + # Use timeout from site table ################################## - if ( !$timeout ) { + if (!$timeout) { $timeout = 30; } ################################## - # Get userid/password + # Get userid/password ################################## my $cred = undef; if (($req->{dev} eq '1') or ($req->{command} eq 'rpower')) { @@ -113,12 +113,12 @@ sub connect { $cred = $req->{$server}{cred}; } ################################## - # Redirect STDERR to variable + # Redirect STDERR to variable ################################## - if ( $verbose ) { + if ($verbose) { close STDERR; - if ( !open( STDERR, '>', \$lwp_log )) { - return( "Unable to redirect STDERR: $!" ); + if (!open(STDERR, '>', \$lwp_log)) { + return ("Unable to redirect STDERR: $!"); } } $IO::Socket::SSL::VERSION = undef; @@ -127,14 +127,14 @@ sub connect { ################################## # Turn on tracing ################################## - if ( $verbose ) { - LWP::Debug::level( '+' ); + if ($verbose) { + LWP::Debug::level('+'); } ################################## # Create cookie ################################## my $cookie = HTTP::Cookies->new(); - $cookie->set_cookie( 0,'asm_session','0','cgi-bin','','443',0,0,3600,0 ); + $cookie->set_cookie(0, 'asm_session', '0', 'cgi-bin', '', '443', 0, 0, 3600, 0); ################################## # Create UserAgent @@ -151,69 +151,71 @@ sub connect { # $server = $hostshash->{ip}; # } #} - $server = xCAT::NetworkUtils::getNodeIPaddress( $server ); + $server = xCAT::NetworkUtils::getNodeIPaddress($server); unless ($server) { - return( "Unable to get IP address for $server" ); + return ("Unable to get IP address for $server"); } -# my $serverip = inet_ntoa(inet_aton($server)); + + # my $serverip = inet_ntoa(inet_aton($server)); my $url = "https://$server/cgi-bin/cgi?form=2"; - $ua->cookie_jar( $cookie ); - $ua->timeout( $timeout ); + $ua->cookie_jar($cookie); + $ua->timeout($timeout); ################################## # Submit logon ################################## - my $res = $ua->post( $url, - [ user => @$cred[0], - password => @$cred[1], - lang => "0", - submit => "Log in" ] + my $res = $ua->post($url, + [ user => @$cred[0], + password => @$cred[1], + lang => "0", + submit => "Log in" ] ); ################################## # Logon failed ################################## - if ( !$res->is_success() ) { - return( $lwp_log.$res->status_line ); + if (!$res->is_success()) { + return ($lwp_log . $res->status_line); } ################################## # To minimize number of GET/POSTs, - # if we successfully logon, we should + # if we successfully logon, we should # get back a valid cookie: # Set-Cookie: asm_session=3038839768778613290 # ################################## - if ( $res->as_string =~ /Set-Cookie: asm_session=(\d+)/ ) { + if ($res->as_string =~ /Set-Cookie: asm_session=(\d+)/) { ############################## # Successful logon.... # Return: - # UserAgent + # UserAgent # Server hostname # UserId # Redirected STDERR/STDOUT ############################## - return( $ua, - $server, - @$cred[0], - \$lwp_log ); + return ($ua, + $server, + @$cred[0], + \$lwp_log); } ############################## - # Logon error + # Logon error ############################## - $res = $ua->get( $url ); + $res = $ua->get($url); - if ( !$res->is_success() ) { - return( $lwp_log.$res->status_line ); + if (!$res->is_success()) { + return ($lwp_log . $res->status_line); } ############################## # Check for specific failures ############################## - if ( $res->content =~ /(Invalid user ID or password|Too many users)/i ) { - return( $lwp_log.$1 . ". Please check node attribute hcp and its password settings."); + if ($res->content =~ /(Invalid user ID or password|Too many users)/i) { + return ($lwp_log . $1 . ". Please check node attribute hcp and its password settings."); } - return( $lwp_log."Logon failure" ); + return ($lwp_log . "Logon failure"); } + sub ce1enable { return &loginenable($_[0], $_[1], $_[2], "celogin1"); } @@ -223,107 +225,112 @@ sub devenable { } my %cmdline_for_log = ( dev => { - enable => "registry -Hw nets/DevEnabled 1", - disable => "registry -Hw nets/DevEnabled 0", - check_pwd => "registry -l DevPwdFile", + enable => "registry -Hw nets/DevEnabled 1", + disable => "registry -Hw nets/DevEnabled 0", + check_pwd => "registry -l DevPwdFile", create_pwd => "netsDynPwdTool --create dev FipSdev", - password => "FipSdev" + password => "FipSdev" }, celogin1 => { - enable => "registry -Hw nets/CE1Enabled 1", - disable => "registry -Hw nets/CE1Enabled 0", - check_pwd => "registry -l Ce1PwdFile", + enable => "registry -Hw nets/CE1Enabled 1", + disable => "registry -Hw nets/CE1Enabled 0", + check_pwd => "registry -l Ce1PwdFile", create_pwd => "netsDynPwdTool --create celogin1 FipSce1", - password => "FipSce1" + password => "FipSce1" }, - ); +); + sub send_command { - my $ua = shift; - my $server = shift; - my $id = shift; + my $ua = shift; + my $server = shift; + my $id = shift; my $log_name = shift; - my $cmd = shift; + my $cmd = shift; my $cmd_line = $cmdline_for_log{$log_name}{$cmd}; if (!defined($cmd_line)) { return undef; } - my $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - cmd => $cmd_line, + my $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + cmd => $cmd_line, submit => "Execute" ] - ); + ); - if ( !$res->is_success() ) { + if (!$res->is_success()) { return undef; } - if ( $res->content =~ /(not allowed.*\.|Invalid entry)/ ) { + if ($res->content =~ /(not allowed.*\.|Invalid entry)/) { return undef; - } + } return $res->content; } + sub loginstate { - my $ua = shift; - my $server = shift; + my $ua = shift; + my $server = shift; my $log_name = shift; - my $url = "https://$server/cgi-bin/cgi?form=4"; - my $res = $ua->get($url); + my $url = "https://$server/cgi-bin/cgi?form=4"; + my $res = $ua->get($url); if (!$res->is_success()) { - return ([RC_ERROR, $res->status_line]); + return ([ RC_ERROR, $res->status_line ]); } if ($res->content =~ m#[\d\D]+Status[\d\D]+$log_name]*>(\w+)#) { my $out = sprintf("%9s: %8s", $log_name, $1); - return ( [SUCCESS, $out]); + return ([ SUCCESS, $out ]); } else { - return ( [RC_ERROR, "not found status for $log_name"]); + return ([ RC_ERROR, "not found status for $log_name" ]); } } sub loginenable { - my $exp = shift; - my $request = shift; - my $id = shift; + my $exp = shift; + my $request = shift; + my $id = shift; my $log_name = shift; - my $ua = @$exp[0]; - my $server = @$exp[1]; - + my $ua = @$exp[0]; + my $server = @$exp[1]; + my $value = $request->{method}{$log_name}; if (!defined($value)) { return &loginstate($ua, $server, $log_name); - } + } my $url = "https://$server/cgi-bin/cgi?form=$id"; - my $res = $ua->get( $url ); + my $res = $ua->get($url); if (!$res->is_success()) { - return( [RC_ERROR,$res->status_line] ); + return ([ RC_ERROR, $res->status_line ]); } $res = &send_command($ua, $server, $id, $log_name, $value); if (!defined($res)) { - return ([RC_ERROR, "Send command Failed"]); + return ([ RC_ERROR, "Send command Failed" ]); } - if ( $value =~ m/^disable$/ ) { + if ($value =~ m/^disable$/) { my $out = sprintf("%9s: Disabled", $log_name); - return( [SUCCESS, $out] ); + return ([ SUCCESS, $out ]); } -#check password# + + #check password# $res = &send_command($ua, $server, $id, $log_name, "check_pwd"); if (!defined($res)) { - return ([RC_ERROR, "Send command Failed"]); + return ([ RC_ERROR, "Send command Failed" ]); } - my $password = undef; + my $password = undef; if ($res =~ m/\[\d+([a-zA-Z]+)\d+\]/) { $password = $1; } else { -# create password # + + # create password # $res = &send_command($ua, $server, $id, $log_name, "create_pwd"); if (!defined($res)) { - return ([RC_ERROR, "Send command Failed"]); + return ([ RC_ERROR, "Send command Failed" ]); } $password = $cmdline_for_log{$log_name}{password}; print "create password for $log_name is '$cmdline_for_log{$log_name}{password}'\n"; } my $out = sprintf("%9s: Enabled, password: $password", $log_name); - return( [SUCCESS, $out] ); + return ([ SUCCESS, $out ]); } + sub disconnect { my $exp = shift; @@ -334,16 +341,16 @@ sub disconnect { ################################## # POST Logoff ################################## - my $res = $ua->post( "https://$server/cgi-bin/cgi?form=1", - [ submit => "Log out" ] + my $res = $ua->post("https://$server/cgi-bin/cgi?form=1", + [ submit => "Log out" ] ); ################################## # Logoff failed ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -357,8 +364,8 @@ sub process_cmd { my $ua = @$exp[0]; my $server = @$exp[1]; my $uid = @$exp[2]; - my $command = $request->{command}; - my $methods = $request->{method}; + my $command = $request->{command}; + my $methods = $request->{method}; my %menu = (); my @result; @@ -369,47 +376,47 @@ sub process_cmd { # same across FSP models/firmware # versions. ################################## - my $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => "2", - e => "1" ] + my $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => "2", + e => "1" ] ); ################################## # Return error ################################## - if ( !$res->is_success() ) { + if (!$res->is_success()) { my @tmpres = (RC_ERROR, $res->status_line); my @rs; push @rs, \@tmpres; - return(\@rs ); + return (\@rs); } ################################## # Build hash of expanded menus ################################## - foreach ( split /\n/, $res->content ) { - if ( /form=(\d+).*window.status='(.*)'/ ) { + foreach (split /\n/, $res->content) { + if (/form=(\d+).*window.status='(.*)'/) { $menu{$2} = $1; } } - foreach ( keys %$methods ) { + foreach (keys %$methods) { ############################## - # Get form id + # Get form id ############################## - my $form = $menu{$cmds{$command}{$_}[0]}; - if ( !defined( $form )) { - my @tmpres = (RC_ERROR, "Cannot find '$cmds{$command}{$_}[0]' menu"); - my @rs; - push @rs, \@tmpres; - return(\@rs ); + my $form = $menu{ $cmds{$command}{$_}[0] }; + if (!defined($form)) { + my @tmpres = (RC_ERROR, "Cannot find '$cmds{$command}{$_}[0]' menu"); + my @rs; + push @rs, \@tmpres; + return (\@rs); } ################################## - # Run command + # Run command ################################## - xCAT::MsgUtils->verbose_message($request, "$command :$_ for node:$server."); + xCAT::MsgUtils->verbose_message($request, "$command :$_ for node:$server."); my $res = $cmds{$command}{$_}[1]($exp, $request, $form, \%menu); - push @$res, $_; + push @$res, $_; push @result, $res; } - return( \@result ); + return (\@result); } @@ -425,23 +432,23 @@ sub state { my $server = @$exp[1]; ################################## - # Get current power status + # Get current power status ################################## - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ################################## # Get power state ################################## - if ( $res->content =~ /Current system power state: (.*)
/) { - return( [SUCCESS,$1] ); + if ($res->content =~ /Current system power state: (.*)
/) { + return ([ SUCCESS, $1 ]); } - return( [RC_ERROR,"unknown"] ); + return ([ RC_ERROR, "unknown" ]); } @@ -458,72 +465,72 @@ sub powercmd { my $server = @$exp[1]; ################################## - # Get Power On/Off System URL + # Get Power On/Off System URL ################################## - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ################################## # Get current power state ################################## - if ( $res->content !~ /Current system power state: (.*)
/) { - return( [RC_ERROR,"Unable to determine current power state"] ); + if ($res->content !~ /Current system power state: (.*)
/) { + return ([ RC_ERROR, "Unable to determine current power state" ]); } my $state = $1; ################################## # Already in that state ################################## - if ( $op =~ /^$state$/i ) { - return( [SUCCESS,"Success"] ); + if ($op =~ /^$state$/i) { + return ([ SUCCESS, "Success" ]); } ################################## - # Get "Power On/Off System" form + # Get "Power On/Off System" form ################################## - my $form = HTML::Form->parse( $res->content, $res->base ); + my $form = HTML::Form->parse($res->content, $res->base); ################################## # Return error ################################## - if ( !defined( $form )) { - return( [RC_ERROR,"'Power On/Off System' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Power On/Off System' form not found" ]); } ################################## # Get "Save and Submit" button ################################## - my $button = ($op eq "on") ? "on" : "of"; + my $button = ($op eq "on") ? "on" : "of"; my @inputs = $form->inputs(); - if ( !grep( $_->{name} eq $button, @inputs )) { - return( [RC_ERROR,"Unable to power $op from state: $state"] ); - } + if (!grep($_->{name} eq $button, @inputs)) { + return ([ RC_ERROR, "Unable to power $op from state: $state" ]); + } ################################## - # Send command + # Send command ################################## - my $data = $form->click( $button ); - $res = $ua->request( $data ); + my $data = $form->click($button); + $res = $ua->request($data); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content =~ /(not allowed.*\.)/ ) { - return( [RC_ERROR,$1] ); + if ($res->content =~ /(not allowed.*\.)/) { + return ([ RC_ERROR, $1 ]); } ################################## - # Success + # Success ################################## - if ( $res->content =~ /(Operation completed successfully)/ ) { - return( [SUCCESS,"Success"] ); + if ($res->content =~ /(Operation completed successfully)/) { + return ([ SUCCESS, "Success" ]); } - return( [RC_ERROR,"Unknown error"] ); + return ([ RC_ERROR, "Unknown error" ]); } @@ -539,28 +546,28 @@ sub reset { my $server = @$exp[1]; ################################## - # Send Reset command + # Send Reset command ################################## - my $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - submit => "Continue" ] + my $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + submit => "Continue" ] ); ################################## # Return error ################################## - if ( !$res->is_success()) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content =~ /(This feature is only available.*)/ ) { - return( [RC_ERROR,$1] ); + if ($res->content =~ /(This feature is only available.*)/) { + return ([ RC_ERROR, $1 ]); } ################################## # Success ################################## - if ( $res->content =~ /(Operation completed successfully)/ ) { - return( [SUCCESS,"Success"] ); + if ($res->content =~ /(Operation completed successfully)/) { + return ([ SUCCESS, "Success" ]); } - return( [RC_ERROR,"Unknown error"] ); + return ([ RC_ERROR, "Unknown error" ]); } @@ -578,43 +585,43 @@ sub boot { ################################## # Check current power state ################################## - my $state = xCAT::PPCfsp::state( - $exp, - $request, - $menu->{$cmds{$command}{state}[0]}, - $menu ); + my $state = xCAT::PPCfsp::state( + $exp, + $request, + $menu->{ $cmds{$command}{state}[0] }, + $menu); my $Rc = shift(@$state); ################################## - # Return error + # Return error ################################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$state[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$state[0] ]); } - if ( @$state[0] !~ /^(on|off)$/i ) { - return( [RC_ERROR,"Unable to boot in state: '@$state[0]'"] ); + if (@$state[0] !~ /^(on|off)$/i) { + return ([ RC_ERROR, "Unable to boot in state: '@$state[0]'" ]); } ################################## - # Get command + # Get command ################################## - $request->{op} = "on"; - my $method = ( $state =~ /^on$/i ) ? "reset" : "powercmd"; - + $request->{op} = "on"; + my $method = ($state =~ /^on$/i) ? "reset" : "powercmd"; + ################################## # Get command form id ################################## - $id = $menu->{$cmds{$command}{$method}[0]}; + $id = $menu->{ $cmds{$command}{$method}[0] }; ################################## # Run command ################################## - my $result = $cmds{$command}{$method}[1]( $exp, $request, $id ); - return( $result ); + my $result = $cmds{$command}{$method}[1]($exp, $request, $id); + return ($result); } ########################################################################## -# Clears Error/Event Logs +# Clears Error/Event Logs ########################################################################## sub clear { @@ -623,40 +630,40 @@ sub clear { my $id = shift; my $ua = @$exp[0]; my $server = @$exp[1]; - + ################################## - # Get Error/Event Logs URL + # Get Error/Event Logs URL ################################## - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ################################## # Clear all error/event log entries: # Are you sure? (OK/Cancel) ################################## - my $form = HTML::Form->parse( $res->content, $res->base ); + my $form = HTML::Form->parse($res->content, $res->base); ################################## # Return error ################################## - if ( !defined( $form )) { - return( [RC_ERROR,"'Error/Event Logs' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Error/Event Logs' form not found" ]); } ################################## - # Send Clear to JavaScript + # Send Clear to JavaScript ################################## - my $data = $form->click( 'clear' ); - $res = $ua->request( $data ); + my $data = $form->click('clear'); + $res = $ua->request($data); - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -671,20 +678,20 @@ sub entries { my $ua = @$exp[0]; my $server = @$exp[1]; my $opt = $request->{opt}; - my $count = (exists($opt->{e})) ? $opt->{e} : -1; + my $count = (exists($opt->{e})) ? $opt->{e} : -1; my $result; my $i = 1; ################################## # Get log entries ################################## - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); - + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); + ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } my @entries = split /\n/, $res->content; @@ -692,29 +699,29 @@ sub entries { # Prepend header ################################## $result = (@entries) ? - "\n#Log ID Time Failing subsystem Severity SRC\n" : - "No entries"; - +"\n#Log ID Time Failing subsystem Severity SRC\n" : + "No entries"; + ################################## - # Parse log entries + # Parse log entries ################################## - foreach ( @entries ) { - if ( /tabindex=(\d+)><\/td>(.*)<\/td><\/tr>/ ){ + foreach (@entries) { + if (/tabindex=(\d+)><\/td>(.*)<\/td><\/tr>/) { my $values = $2; $values =~ s/<\/td>/ /g; - $result.= "$values\n"; + $result .= "$values\n"; - if ( $i++ == $count ) { + if ($i++ == $count) { last; } } } - return( [SUCCESS,$result] ); + return ([ SUCCESS, $result ]); } ########################################################################## -# Gets/Sets system time of day +# Gets/Sets system time of day ########################################################################## sub time { @@ -726,42 +733,42 @@ sub time { my $value = $request->{method}{time}; ############################## - # Send command + # Send command ############################## - my $result = xCAT::PPCfsp::timeofday( $exp, $request, $id ); + my $result = xCAT::PPCfsp::timeofday($exp, $request, $id); my $Rc = shift(@$result); ############################## # Return error ############################## - if ( $Rc != SUCCESS ) { - return( [$Rc,"Time: @$result[0]"] ); + if ($Rc != SUCCESS) { + return ([ $Rc, "Time: @$result[0]" ]); } ############################## # Get time ############################## - if ( !defined( $value )) { - @$result[0] =~ /(\d+) (\d+) (\d+) $/; - return( [SUCCESS,sprintf( "Time: %02d:%02d:%02d UTC",$1,$2,$3 )] ); + if (!defined($value)) { + @$result[0] =~ /(\d+) (\d+) (\d+) $/; + return ([ SUCCESS, sprintf("Time: %02d:%02d:%02d UTC", $1, $2, $3) ]); } ############################## - # Set time + # Set time ############################## my @t = split / /, @$result[0]; my @new = split /:/, $value; - splice( @t,3,3,@new ); + splice(@t, 3, 3, @new); ############################## - # Send command + # Send command ############################## - my $time = xCAT::PPCfsp::timeofday( $exp, $request, $id, \@t ); + my $time = xCAT::PPCfsp::timeofday($exp, $request, $id, \@t); $Rc = shift(@$time); - return( [$Rc,"Time: @$time[0]"] ); + return ([ $Rc, "Time: @$time[0]" ]); } ########################################################################## -# Gets/Sets system date +# Gets/Sets system date ########################################################################## sub date { @@ -773,42 +780,42 @@ sub date { my $value = $request->{method}{date}; ############################## - # Send command + # Send command ############################## - my $result = xCAT::PPCfsp::timeofday( $exp, $request, $id ); + my $result = xCAT::PPCfsp::timeofday($exp, $request, $id); my $Rc = shift(@$result); ############################## # Return error ############################## - if ( $Rc != SUCCESS ) { - return( [$Rc,"Date: @$result[0]"] ); + if ($Rc != SUCCESS) { + return ([ $Rc, "Date: @$result[0]" ]); } ############################## # Get date ############################## - if ( !defined( $value )) { - @$result[0] =~ /^(\d+) (\d+) (\d+)/; - return( [SUCCESS,sprintf( "Date: %02d-%02d-%4d",$1,$2,$3 )] ); + if (!defined($value)) { + @$result[0] =~ /^(\d+) (\d+) (\d+)/; + return ([ SUCCESS, sprintf("Date: %02d-%02d-%4d", $1, $2, $3) ]); } ############################## # Set date ############################## my @t = split / /, @$result[0]; my @new = split /-/, $value; - splice( @t,0,3,@new ); + splice(@t, 0, 3, @new); ############################## # Send command ############################## - my $date = xCAT::PPCfsp::timeofday( $exp, $request, $id, \@t ); + my $date = xCAT::PPCfsp::timeofday($exp, $request, $id, \@t); $Rc = shift(@$date); - return( [$Rc,"Date: @$date[0]"] ); + return ([ $Rc, "Date: @$date[0]" ]); } ########################################################################## -# Gets/Sets system time/date +# Gets/Sets system time/date ########################################################################## sub timeofday { @@ -820,71 +827,71 @@ sub timeofday { my $server = @$exp[1]; ###################################### - # Get time/date + # Get time/date ###################################### - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content =~ /(only when the system is powered off)/ ) { - return( [RC_ERROR,$1] ); + if ($res->content =~ /(only when the system is powered off)/) { + return ([ RC_ERROR, $1 ]); } ################################## # Get "Power On/Off System" form ################################## - my $form = HTML::Form->parse( $res->content, $res->base ); + my $form = HTML::Form->parse($res->content, $res->base); ################################## # Return error ################################## - if ( !defined( $form )) { - return( [RC_ERROR,"'Time Of Day' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Time Of Day' form not found" ]); } ###################################### - # Get time/date fields + # Get time/date fields ###################################### my $result; my @option = qw(omo od oy oh omi os); - - foreach ( @option ) { - if ( $res->content !~ /name='$_' value='(\d+)'/ ) { - return( [RC_ERROR,"Error getting time of day"] ); + + foreach (@option) { + if ($res->content !~ /name='$_' value='(\d+)'/) { + return ([ RC_ERROR, "Error getting time of day" ]); } - $result.= "$1 "; + $result .= "$1 "; } ###################################### - # Return time/date + # Return time/date ###################################### - if ( !defined( $d )) { - return( [SUCCESS,$result] ); + if (!defined($d)) { + return ([ SUCCESS, $result ]); } ###################################### - # Set time/date + # Set time/date ###################################### - $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - mo => @$d[0], - d => @$d[1], - y => @$d[2], - h => @$d[3], - mi => @$d[4], - s => @$d[5], - submit => "Save settings" ] + $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + mo => @$d[0], + d => @$d[1], + y => @$d[2], + h => @$d[3], + mi => @$d[4], + s => @$d[5], + submit => "Save settings" ] ); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content =~ /(not allowed.*\.|Invalid entry)/ ) { - return( [RC_ERROR,$1] ); - } - return( [SUCCESS,"Success"] ); + if ($res->content =~ /(not allowed.*\.|Invalid entry)/) { + return ([ RC_ERROR, $1 ]); + } + return ([ SUCCESS, "Success" ]); } @@ -893,73 +900,73 @@ sub timeofday { ########################################################################## sub iocap { - my $result = option( @_,"iocap" ); + my $result = option(@_, "iocap"); @$result[1] = "iocap: @$result[1]"; - return( $result ); + return ($result); } ########################################################################## -# Gets/Sets Auto Power Restart +# Gets/Sets Auto Power Restart ########################################################## sub autopower { - my $result = option( @_,"autopower" ); + my $result = option(@_, "autopower"); @$result[1] = "autopower: @$result[1]"; - return( $result ); + return ($result); } ########################################################################## -# Gets/Sets options +# Gets/Sets options ########################################################################## sub option { my $exp = shift; my $request = shift; - my $id = shift; + my $id = shift; my $menu = shift; my $command = shift; my $ua = @$exp[0]; my $server = @$exp[1]; - my $option = ($command =~ /^iocap$/) ? "pe" : "apor"; + my $option = ($command =~ /^iocap$/) ? "pe" : "apor"; my $value = $request->{method}{$command}; ###################################### # Get option URL ###################################### - if ( !defined( $value )) { - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); + if (!defined($value)) { + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); ################################## # Return errors ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content !~ /selected value='\d+'>(\w+)content !~ /selected value='\d+'>(\w+)post( "https://$server/cgi-bin/cgi", - [ form => $id, - $option => ($value =~ /^disable$/i) ? "0" : "1", - submit => "Save settings" ] + my $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + $option => ($value =~ /^disable$/i) ? "0" : "1", + submit => "Save settings" ] ); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content !~ /Operation completed successfully/i ) { - return( [RC_ERROR,"Error setting option"] ); + if ($res->content !~ /Operation completed successfully/i) { + return ([ RC_ERROR, "Error setting option" ]); } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -978,14 +985,14 @@ sub memdecfg { ################################## # Get settings ################################## - if ( !defined( $values )) { - return( readdecfg( $exp, $request, $id )); + if (!defined($values)) { + return (readdecfg($exp, $request, $id)); } ################################## # Set settings ################################## $values =~ /^(configure|deconfigure):(\d+):(unit|bank):(all|[\d,]+)$/i; - return( writedecfg( $exp, $request, $id, $1, $2, $3, $4 )); + return (writedecfg($exp, $request, $id, $1, $2, $3, $4)); } @@ -1004,14 +1011,14 @@ sub procdecfg { ################################## # Get settings ################################## - if ( !defined( $values )) { - return( readdecfg( $exp, $request, $id )); + if (!defined($values)) { + return (readdecfg($exp, $request, $id)); } ################################## # Set settings ################################## $values =~ /^(configure|deconfigure):(\d+):(all|[\d,]+)$/i; - return( writedecfg( $exp, $request, $id, $1, $2, "Processor ID",$3 )); + return (writedecfg($exp, $request, $id, $1, $2, "Processor ID", $3)); } @@ -1032,96 +1039,96 @@ sub writedecfg { my $server = @$exp[1]; ###################################### - # Command-line parameter specified + # Command-line parameter specified ###################################### - my @ids = split /,/, $id; - my $select = ($state =~ /^configure$/i) ? 0 : 1; + my @ids = split /,/, $id; + my $select = ($state =~ /^configure$/i) ? 0 : 1; ###################################### # Get Deconfiguration URL ###################################### my $url = "https://$server/cgi-bin/cgi?form=$formid"; - my $res = $ua->get( $url ); + my $res = $ua->get($url); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ###################################### - # Find unit specified by user + # Find unit specified by user ###################################### my $html = $res->content; my $value; - while ( $html =~ - s/]+><\/td>(\d+)]+><\/td>(\d+)parse( $res->content, $res->base ); + my $form = HTML::Form->parse($res->content, $res->base); my @inputs = $form->inputs(); ###################################### # Return error ###################################### - if ( !defined( $form )) { - return( [RC_ERROR,"'Deconfiguration' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Deconfiguration' form not found" ]); } ###################################### # Find radio button ###################################### - my ($radio) = grep($_->{type} eq "radio", @inputs ); - if ( !defined( $radio )) { - return( [RC_ERROR,"Radio button not found"] ); + my ($radio) = grep($_->{type} eq "radio", @inputs); + if (!defined($radio)) { + return ([ RC_ERROR, "Radio button not found" ]); } ###################################### # Select radio button ###################################### - $radio->value( $value ); + $radio->value($value); ###################################### # Send command ###################################### - my $data = $form->click( "submit" ); - $res = $ua->request( $data ); + my $data = $form->click("submit"); + $res = $ua->request($data); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ###################################### # Get current settings ###################################### - $form = HTML::Form->parse( $res->content, $res->base ); + $form = HTML::Form->parse($res->content, $res->base); @inputs = $form->inputs(); ###################################### # Return error ###################################### - if ( !defined( $form )) { - return( [RC_ERROR,"'Deconfiguration' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Deconfiguration' form not found" ]); } ###################################### - # Get options + # Get options ###################################### my %options = (); my %key = (); my $setall = 0; - foreach ( @inputs ) { - if ( $_->type eq "option" ) { - push @{$options{$_->name}}, $_->value; + foreach (@inputs) { + if ($_->type eq "option") { + push @{ $options{ $_->name } }, $_->value; } } my @units = split //, $res->content; @@ -1129,99 +1136,99 @@ sub writedecfg { $html = undef; ###################################### - # Break into unit types + # Break into unit types ###################################### - foreach ( @units ) { + foreach (@units) { /([\w\s]+)<\/th>/; - if ( $1 =~ /$type/i ) { + if ($1 =~ /$type/i) { $html = $_; last; } } ###################################### - # Look for unit type + # Look for unit type ###################################### - if ( !defined( $html )) { - return( [RC_ERROR,"unit=$unit '$type' not found"] ); + if (!defined($html)) { + return ([ RC_ERROR, "unit=$unit '$type' not found" ]); } ###################################### - # Set all IDs + # Set all IDs ###################################### - if ( $ids[0] eq "all" ) { - @ids = (); - $setall = 1; + if ($ids[0] eq "all") { + @ids = (); + $setall = 1; } ###################################### - # Associate 'option' name with ID + # Associate 'option' name with ID ###################################### - foreach ( keys %options ) { - if ( $html =~ /\n(\d+)<\/td>.*name='$_'/ ) { - if ( $setall ) { + foreach (keys %options) { + if ($html =~ /\n(\d+)<\/td>.*name='$_'/) { + if ($setall) { push @ids, $1; } - push @{$options{$_}}, $1; + push @{ $options{$_} }, $1; } } ###################################### - # Check if each specified ID exist + # Check if each specified ID exist ###################################### - foreach ( @ids ) { - foreach my $name ( keys %options ) { - my $id = @{$options{$name}}[1]; - - if ( $_ eq $id ) { - my $value = @{$options{$name}}[0]; - $key{$id} = [$value,$name]; + foreach (@ids) { + foreach my $name (keys %options) { + my $id = @{ $options{$name} }[1]; + + if ($_ eq $id) { + my $value = @{ $options{$name} }[0]; + $key{$id} = [ $value, $name ]; } } } ###################################### - # Check if ID exists + # Check if ID exists ###################################### - foreach ( @ids ) { - if ( !exists( $key{$_} )) { - return( [RC_ERROR,"Processing unit=$unit $type=$_ not found"] ); + foreach (@ids) { + if (!exists($key{$_})) { + return ([ RC_ERROR, "Processing unit=$unit $type=$_ not found" ]); } - my $value = @{$key{$_}}[0]; - if ( $value == $select ) { - delete $key{$_}; + my $value = @{ $key{$_} }[0]; + if ($value == $select) { + delete $key{$_}; } } ###################################### - # Check in already in that state + # Check in already in that state ###################################### - if ( !scalar( keys %key )) { - return( [RC_ERROR,"All $type(s) specified already in '$state' state"]); - } + if (!scalar(keys %key)) { + return ([ RC_ERROR, "All $type(s) specified already in '$state' state" ]); + } ###################################### - # Make changes to form + # Make changes to form ###################################### - foreach ( keys %key ) { - my $name = @{$key{$_}}[1]; - my ($button) = grep($_->{name} eq $name, @inputs ); - if ( !defined( $button )) { - return( [RC_ERROR,"Option=$name not found"] ); + foreach (keys %key) { + my $name = @{ $key{$_} }[1]; + my ($button) = grep($_->{name} eq $name, @inputs); + if (!defined($button)) { + return ([ RC_ERROR, "Option=$name not found" ]); } - $button->value( $select ); + $button->value($select); } ################################## # Send command ################################## - $data = $form->click( "submit" ); - $res = $ua->request( $data ); + $data = $form->click("submit"); + $res = $ua->request($data); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content =~ /\n(.*Operation not allowed.*\.)/ ) { + if ($res->content =~ /\n(.*Operation not allowed.*\.)/) { my $result = $1; $result =~ s/

/\n/g; - return( [RC_ERROR,$result] ); + return ([ RC_ERROR, $result ]); } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -1241,18 +1248,18 @@ sub readdecfg { # Get Deconfiguration URL ###################################### my $url = "https://$server/cgi-bin/cgi?form=$id"; - my $res = $ua->get( $url ); + my $res = $ua->get($url); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ###################################### # Get current settings ###################################### - my $form = HTML::Form->parse( $res->content, $res->base ); + my $form = HTML::Form->parse($res->content, $res->base); my @inputs = $form->inputs(); my $html = $res->content; my $unit; @@ -1260,53 +1267,53 @@ sub readdecfg { ###################################### # Return error ###################################### - if ( !defined( $form )) { - return( [RC_ERROR,"'Deconfiguration' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Deconfiguration' form not found" ]); } ###################################### # Find radio button ###################################### - my ($radio) = grep($_->{type} eq "radio", @inputs ); - if ( !defined( $radio )) { - return( [RC_ERROR,"Radio button not found"] ); + my ($radio) = grep($_->{type} eq "radio", @inputs); + if (!defined($radio)) { + return ([ RC_ERROR, "Radio button not found" ]); } ###################################### # Find unit identifier ###################################### - if ( $html =~ /<\/th>([\w\s]+)<\/th>([\w\s]+){menu}} ) { + foreach (@{ $radio->{menu} }) { ################################## # Select radio button ################################## - my $value = ( ref($_) eq 'HASH' ) ? $_->{value} : $_; - $radio->value( $value ); + my $value = (ref($_) eq 'HASH') ? $_->{value} : $_; + $radio->value($value); ################################## # Send command ################################## - my $request = $form->click( "submit" ); - $res = $ua->request( $request ); + my $request = $form->click("submit"); + $res = $ua->request($request); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } $html = $res->content; ################################## # Find unit identifier ################################## - if ( $html =~ /

([\w\s:]+)([\w\s:]+)/, $res->content; shift(@group); - foreach ( @group ) { + foreach (@group) { my @maxlen = (); my @values = (); @@ -1318,14 +1325,14 @@ sub readdecfg { pop(@heading); pop(@heading); - foreach ( @heading ) { + foreach (@heading) { push @maxlen, length($_); } ############################## # Entry values ############################## - foreach ( split /\n/ ) { - if ( s/^// ) { + foreach (split /\n/) { + if (s/^//) { s/
/ /g; my $i = 0; @@ -1336,8 +1343,8 @@ sub readdecfg { ###################### # Length formatting ###################### - foreach ( @d ) { - if ( length($_) > $maxlen[$i] ) { + foreach (@d) { + if (length($_) > $maxlen[$i]) { $maxlen[$i] = length($_); } $i++; @@ -1349,27 +1356,27 @@ sub readdecfg { # Output header ############################## my $i = 0; - foreach ( @heading ) { - my $format = sprintf( "%%-%ds",$maxlen[$i++]+2 ); - $result.= sprintf( $format, $_ ); + foreach (@heading) { + my $format = sprintf("%%-%ds", $maxlen[ $i++ ] + 2); + $result .= sprintf($format, $_); } - $result.= "\n"; + $result .= "\n"; ############################## # Output values ############################## - foreach ( @values ) { + foreach (@values) { $i = 0; - foreach ( @$_ ) { - my $format = sprintf( "%%-%ds",$maxlen[$i++]+2 ); - $result.= sprintf( $format, $_ ); + foreach (@$_) { + my $format = sprintf("%%-%ds", $maxlen[ $i++ ] + 2); + $result .= sprintf($format, $_); } - $result.= "\n"; + $result .= "\n"; } - $result.= "\n"; + $result .= "\n"; } } - return( [SUCCESS,$result] ); + return ([ SUCCESS, $result ]); } @@ -1388,13 +1395,13 @@ sub decfg { ###################################### # Get Deconfiguration Policy URL ###################################### - my $res = $ua->get( "https://$server/cgi-bin/cgi?form=$id" ); + my $res = $ua->get("https://$server/cgi-bin/cgi?form=$id"); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } my %d = (); my $len = 0; @@ -1402,7 +1409,7 @@ sub decfg { my $html = $res->content; my $result; - while ( $html =~ s/
(.*:)\s+(.*:)\s+(\w+)(\w+) $len ) { - $len = length( $desc ); + if (length($desc) > $len) { + $len = length($desc); } - $d{$desc} = [$value,$name]; + $d{$desc} = [ $value, $name ]; } ###################################### # Get Deconfiguration Policy ###################################### - if ( !defined( $value )) { - my $format = sprintf( "\n%%-%ds %%s",$len ); - foreach ( keys %d ) { - $result.= sprintf( $format,$_,$d{$_}[0] ); + if (!defined($value)) { + my $format = sprintf("\n%%-%ds %%s", $len); + foreach (keys %d) { + $result .= sprintf($format, $_, $d{$_}[0]); } - return( [SUCCESS,$result] ); + return ([ SUCCESS, $result ]); } ###################################### # Set Deconfiguration Policy ###################################### - my ($op,$names) = split /:/, $value; - my @policy = split /,/, $names; - my $state = ($op =~ /^enable$/i) ? 0 : 1; + my ($op, $names) = split /:/, $value; + my @policy = split /,/, $names; + my $state = ($op =~ /^enable$/i) ? 0 : 1; ###################################### # Check for duplicate policies ###################################### - foreach my $name ( @policy ) { - if ( grep( /^$name$/, @policy ) > 1 ) { - return( [RC_ERROR,"Duplicate policy specified: $name"] ); + foreach my $name (@policy) { + if (grep(/^$name$/, @policy) > 1) { + return ([ RC_ERROR, "Duplicate policy specified: $name" ]); } } ###################################### - # Get Deconfiguration Policy form + # Get Deconfiguration Policy form ###################################### - my $form = HTML::Form->parse( $res->content, $res->base ); + my $form = HTML::Form->parse($res->content, $res->base); ###################################### # Return error ###################################### - if ( !defined( $form )) { - return( [RC_ERROR,"'Deconfiguration Policies' form not found"] ); + if (!defined($form)) { + return ([ RC_ERROR, "'Deconfiguration Policies' form not found" ]); } ###################################### - # Get hidden inputs + # Get hidden inputs ###################################### my @inputs = $form->inputs(); - my (@hidden) = grep( $_->{type} eq "hidden", @inputs ); - if ( !@hidden ) { - return( [RC_ERROR," not found"] ); + my (@hidden) = grep($_->{type} eq "hidden", @inputs); + if (!@hidden) { + return ([ RC_ERROR, " not found" ]); } ###################################### # Check for invalid policies ###################################### - foreach my $name ( @policy ) { - my @p = grep( $_->{value_name}=~/\b$name\b/i, @hidden ); + foreach my $name (@policy) { + my @p = grep($_->{value_name} =~ /\b$name\b/i, @hidden); - if ( @p > 1 ) { - return( [RC_ERROR,"Ambiguous policy: $name"] ); - } elsif ( !@p ) { - return( [RC_ERROR,"Invalid policy: $name"] ); + if (@p > 1) { + return ([ RC_ERROR, "Ambiguous policy: $name" ]); + } elsif (!@p) { + return ([ RC_ERROR, "Invalid policy: $name" ]); } my $value_name = $p[0]->{value_name}; - $policy[$i++] = @{$d{$value_name}}[1]; + $policy[ $i++ ] = @{ $d{$value_name} }[1]; } ###################################### - # Select option + # Select option ###################################### - foreach my $name ( @policy ) { - my ($in) = grep( $_->{name} eq $name, @inputs ); - $in->value( $state ); + foreach my $name (@policy) { + my ($in) = grep($_->{name} eq $name, @inputs); + $in->value($state); } ###################################### # Send command ###################################### - my $data = $form->click( "submit" ); - $res = $ua->request( $data ); + my $data = $form->click("submit"); + $res = $ua->request($data); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -1525,40 +1532,40 @@ sub sysdump { # Get Dump URL ###################################### my $url = "https://$server/cgi-bin/cgi?form=$id"; - my $res = $ua->get( $url ); + my $res = $ua->get($url); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ###################################### - # Possible errors: + # Possible errors: # not allowed when a dump of this type exists. # not allowed when system is powered off. ###################################### - if ( $res->content =~ /(not allowed.*\.)/ ) { - return( [RC_ERROR,$1] ); + if ($res->content =~ /(not allowed.*\.)/) { + return ([ RC_ERROR, $1 ]); } my @d; my $html = $res->content; ###################################### - # Get current dump settings + # Get current dump settings ###################################### - foreach ( my $i=0; $i<3; $i++ ) { - if ($i == 0) { + foreach (my $i = 0 ; $i < 3 ; $i++) { + if ($i == 0) { if ($html !~ /Dump policy:\s+(\w+)/) { goto ERROR; } } if ($i != 0) { - if ($html !~ s/selected value='(\d+)'//) { -ERROR: - return( [RC_ERROR,"Error getting dump settings"] ); - } + if ($html !~ s/selected value='(\d+)'//) { + ERROR: + return ([ RC_ERROR, "Error getting dump settings" ]); + } } push @d, $1; @@ -1566,42 +1573,42 @@ ERROR: ###################################### # Send dump command ###################################### - $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - policy => $d[0], - content => $d[1], - phyp => $d[2], - page => "1", - takedump => "Save settings and initiate dump" ] + $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + policy => $d[0], + content => $d[1], + phyp => $d[2], + page => "1", + takedump => "Save settings and initiate dump" ] ); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ###################################### - # Continue ? + # Continue ? ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - policy => $d[0], - content => $d[1], - phyp => $d[2], - page => "2", - takedump => "Save settings and initiate dump", - submit => "Continue"] + $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + policy => $d[0], + content => $d[1], + phyp => $d[2], + page => "2", + takedump => "Save settings and initiate dump", + submit => "Continue" ] ); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -1610,88 +1617,88 @@ ERROR: ########################################################################## sub spdump { - my $exp = shift; - my $request = shift; - my $id = shift; - my $ua = @$exp[0]; - my $server = @$exp[1]; - my $button = "Save settings and initiate dump"; + my $exp = shift; + my $request = shift; + my $id = shift; + my $ua = @$exp[0]; + my $server = @$exp[1]; + my $button = "Save settings and initiate dump"; my $dump_setting = 1; ###################################### # Get Dump URL ###################################### my $url = "https://$server/cgi-bin/cgi?form=$id"; - my $res = $ua->get( $url ); + my $res = $ua->get($url); ###################################### # Return error ###################################### - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ###################################### - # Dump disabled - enable it + # Dump disabled - enable it ###################################### - if ( $res->content =~ /selected value='0'>Disabled/ ) { - $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - bdmp => "1", - save => "Save settings" ] + if ($res->content =~ /selected value='0'>Disabled/) { + $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + bdmp => "1", + save => "Save settings" ] ); ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } - if ( $res->content !~ /Operation completed successfully/ ) { - return( [RC_ERROR,"Error enabling dump setting"] ); + if ($res->content !~ /Operation completed successfully/) { + return ([ RC_ERROR, "Error enabling dump setting" ]); } ################################## # Get Dump URL again ################################## - $res = $ua->get( $url ); + $res = $ua->get($url); - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ################################## - # Restore setting after dump + # Restore setting after dump ################################## $dump_setting = 0; } - if ( $res->content !~ /$button/ ) { + if ($res->content !~ /$button/) { ################################################################# # For some firmware levels, button is changed to "initiate dump" ################################################################# $button = "Initiate dump"; - if ( $res->content !~ /$button/ ) { - return( [RC_ERROR,"'$button' button not found"] ); + if ($res->content !~ /$button/) { + return ([ RC_ERROR, "'$button' button not found" ]); } } ###################################### - # We will lose conection after dump + # We will lose conection after dump ###################################### $ua->timeout(10); ###################################### - # Send dump command + # Send dump command ###################################### - $res = $ua->post( "https://$server/cgi-bin/cgi", - [ form => $id, - bdmp => $dump_setting, - dump => $button ] + $res = $ua->post("https://$server/cgi-bin/cgi", + [ form => $id, + bdmp => $dump_setting, + dump => $button ] ); ###################################### - # Will lose connection on success -500 + # Will lose connection on success -500 ###################################### - if ( !$res->is_success() ) { - if ( $res->code ne "500" ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + if ($res->code ne "500") { + return ([ RC_ERROR, $res->status_line ]); } } - return( [SUCCESS,"Success"] ); + return ([ SUCCESS, "Success" ]); } @@ -1699,7 +1706,7 @@ sub spdump { # Gets all Error/Event Logs entries ########################################################################## sub all { - return( entries(@_) ); + return (entries(@_)); } @@ -1708,9 +1715,9 @@ sub all { ########################################################################## sub all_clear { - my $result = entries( @_ ); - clear( @_); - return( $result ); + my $result = entries(@_); + clear(@_); + return ($result); } ########################################################################## @@ -1721,40 +1728,40 @@ sub netcfg my $exp = shift; my $request = shift; my $id = shift; - + ###################################### # Parsing arg ###################################### my $set_config = 0; my ($inc_name, $inc_ip, $inc_host, $inc_gateway, $inc_netmask) = (); my $real_inc_name = undef; - if ( $request->{'method'}->{'network'}) + if ($request->{'method'}->{'network'}) { $set_config = 1; } - + my $interfaces = undef; - my $form = undef; - - my $res = get_netcfg( $exp, $request, $id, \$interfaces, \$form); - return $res if ( $res->[0] == RC_ERROR); - + my $form = undef; + + my $res = get_netcfg($exp, $request, $id, \$interfaces, \$form); + return $res if ($res->[0] == RC_ERROR); + my $output = ""; ####################################### # Set configuration ####################################### - if ( $set_config) + if ($set_config) { - return set_netcfg( $exp, $request, $interfaces, $form); + return set_netcfg($exp, $request, $interfaces, $form); } ####################################### # Get configuration and format output ####################################### else { - return format_netcfg( $interfaces); + return format_netcfg($interfaces); } - + } ########################################################################## @@ -1770,59 +1777,60 @@ sub get_netcfg my $ua = @$exp[0]; my $server = @$exp[1]; - ###################################### + ###################################### # Get Network Configuration URL ###################################### my $url = "https://$server/cgi-bin/cgi?form=$id"; - my $res = $ua->get( $url ); - + my $res = $ua->get($url); + ################################## # Return error ################################## - if ( !$res->is_success() ) { - return( [RC_ERROR,$res->status_line] ); + if (!$res->is_success()) { + return ([ RC_ERROR, $res->status_line ]); } ################################## - # Get "Network Configuraiton" form + # Get "Network Configuraiton" form ################################## - $$form = HTML::Form->parse( $res->content, $res->base ); + $$form = HTML::Form->parse($res->content, $res->base); ################################## # Return error ################################## - if ( !defined( $$form )) { - return( [RC_ERROR,"'Network Configuration' form not found at parse"] ); - } + if (!defined($$form)) { + return ([ RC_ERROR, "'Network Configuration' form not found at parse" ]); + } ################################## # For some P6 machines ################################## - if ( $$form->find_input('ip', 'radio', 1)) - { + if ($$form->find_input('ip', 'radio', 1)) + { my $ipv4Radio = $$form->find_input('ip', 'radio', 1); if (!$ipv4Radio) { print "Cannot find IPv4 option\n"; exit; } + #$ipv4Radio->check(); my $data = $$form->click('submit'); - $res = $ua->request( $data); - $$form = HTML::Form->parse( $res->content, $res->base ); - if ( !defined( $$form )) { - return( [RC_ERROR,"'Network Configuration' form not found at submit"] ); - } - } elsif ( $$form->find_input('submit', 'submit', 1) ) { + $res = $ua->request($data); + $$form = HTML::Form->parse($res->content, $res->base); + if (!defined($$form)) { + return ([ RC_ERROR, "'Network Configuration' form not found at submit" ]); + } + } elsif ($$form->find_input('submit', 'submit', 1)) { my $data = $$form->click('submit'); sleep 5; - $res = $ua->request( $data); - $$form = HTML::Form->parse( $res->content, $res->base ); - if ( !defined( $$form )) { - return( [RC_ERROR,"'Network Configuration' form not found at submit2"] ); + $res = $ua->request($data); + $$form = HTML::Form->parse($res->content, $res->base); + if (!defined($$form)) { + return ([ RC_ERROR, "'Network Configuration' form not found at submit2" ]); } - if ( $$form->find_input('ip', 'radio', 1)) + if ($$form->find_input('ip', 'radio', 1)) { my $ipv4Radio = $$form->find_input('ip', 'radio', 1); if (!$ipv4Radio) @@ -1830,46 +1838,48 @@ sub get_netcfg print "Cannot find IPv4 option\n"; exit; } + #$ipv4Radio->check(); - + my $data = $$form->click('submit'); - $res = $ua->request( $data); - $$form = HTML::Form->parse( $res->content, $res->base ); - if ( !defined( $$form )) { - return( [RC_ERROR,"'Network Configuration' form not found at submit3"] ); + $res = $ua->request($data); + $$form = HTML::Form->parse($res->content, $res->base); + if (!defined($$form)) { + return ([ RC_ERROR, "'Network Configuration' form not found at submit3" ]); } } - } + } ####################################### # Parse the form to get the inc input ####################################### my $has_found_all = 0; - my $i = 0; - while ( not $has_found_all) + my $i = 0; + while (not $has_found_all) { - my $input = $$form->find_input( "interface$i", 'checkbox'); - if ( ! $input) + my $input = $$form->find_input("interface$i", 'checkbox'); + if (!$input) { $has_found_all = 1; } else { $$interfaces->{"interface$i"}->{'selected'} = $input; - $$interfaces->{"interface$i"}->{'type'} = $$form->find_input("ip$i", 'option'); + $$interfaces->{"interface$i"}->{'type'} = $$form->find_input("ip$i", 'option'); $$interfaces->{"interface$i"}->{'hostname'} = $$form->find_input("host$i", 'text'); - $$interfaces->{"interface$i"}->{'ip'} = $$form->find_input("static_ip$i", 'text'); - $$interfaces->{"interface$i"}->{'gateway'} = $$form->find_input("gateway$i", 'text'); - $$interfaces->{"interface$i"}->{'netmask'} = $$form->find_input("subnet$i", 'text'); + $$interfaces->{"interface$i"}->{'ip'} = $$form->find_input("static_ip$i", 'text'); + $$interfaces->{"interface$i"}->{'gateway'} = $$form->find_input("gateway$i", 'text'); + $$interfaces->{"interface$i"}->{'netmask'} = $$form->find_input("subnet$i", 'text'); + #we do not support dns yet, just in case of future support - $$interfaces->{"interface$i"}->{'dns0'} = $$form->find_input("dns0$i", 'text'); - $$interfaces->{"interface$i"}->{'dns1'} = $$form->find_input("dns1$i", 'text'); - $$interfaces->{"interface$i"}->{'dns2'} = $$form->find_input("dns2$i", 'text'); + $$interfaces->{"interface$i"}->{'dns0'} = $$form->find_input("dns0$i", 'text'); + $$interfaces->{"interface$i"}->{'dns1'} = $$form->find_input("dns1$i", 'text'); + $$interfaces->{"interface$i"}->{'dns2'} = $$form->find_input("dns2$i", 'text'); $i++; } } - return ( [RC_ERROR,"Cannot find any network interface on $server"]) if ( ! $$interfaces); - - return ( [SUCCESS, undef]); + return ([ RC_ERROR, "Cannot find any network interface on $server" ]) if (!$$interfaces); + + return ([ SUCCESS, undef ]); } ########################################################################## @@ -1877,25 +1887,25 @@ sub get_netcfg ########################################################################## sub set_netcfg { - my $exp = shift; - my $request = shift; - my $interfaces = shift; - my $form = shift; - my $ua = @$exp[0]; + my $exp = shift; + my $request = shift; + my $interfaces = shift; + my $form = shift; + my $ua = @$exp[0]; my $real_inc_name; my ($inc_name, $inc_ip, $inc_host, $inc_gateway, $inc_netmask) = split /,/, $request->{'method'}->{'network'}; - chomp ($inc_name, $inc_ip, $inc_host, $inc_gateway, $inc_netmask); - if ( $inc_name =~ /^eth(\d)$/) + chomp($inc_name, $inc_ip, $inc_host, $inc_gateway, $inc_netmask); + if ($inc_name =~ /^eth(\d)$/) { $real_inc_name = "interface$1"; } - elsif ( $inc_name =~/(\d+)\.(\d+)\.(\d+)\.(\d+)/) + elsif ($inc_name =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/) { for my $inc (keys %$interfaces) { - if ($interfaces->{ $inc}->{'ip'}->value() eq $inc_name) + if ($interfaces->{$inc}->{'ip'}->value() eq $inc_name) { $real_inc_name = $inc; last; @@ -1904,18 +1914,18 @@ sub set_netcfg } else { - return( [RC_ERROR, "Incorrect network interface name $inc_name"] ); + return ([ RC_ERROR, "Incorrect network interface name $inc_name" ]); } - return ( [RC_ERROR,"Cannot find interface $inc_name"]) if ( ! exists ($$interfaces{ $real_inc_name})); + return ([ RC_ERROR, "Cannot find interface $inc_name" ]) if (!exists($$interfaces{$real_inc_name})); my $inc_type; my @set_entries = (); - if ( $inc_ip eq '0.0.0.0') + if ($inc_ip eq '0.0.0.0') { $inc_type = 'Dynamic'; push @set_entries, 'IP type to dynamic.'; } - elsif ( $inc_ip eq '*') + elsif ($inc_ip eq '*') { $inc_type = 'Static'; ($inc_ip, $inc_host, $inc_gateway, $inc_netmask) = xCAT::NetworkUtils::getNodeNetworkCfg(@$exp[1]); @@ -1925,73 +1935,74 @@ sub set_netcfg $inc_type = 'Static'; } -#not work on AIX -# $interfaces->{ $real_inc_name}->{'selected'}->check(); - my @tmp_options = $interfaces->{ $real_inc_name}->{'selected'}->possible_values(); - $interfaces->{ $real_inc_name}->{'selected'}->value(@tmp_options[1] ); - if ( $interfaces->{ $real_inc_name}->{'type'}) + #not work on AIX + # $interfaces->{ $real_inc_name}->{'selected'}->check(); + my @tmp_options = $interfaces->{$real_inc_name}->{'selected'}->possible_values(); + $interfaces->{$real_inc_name}->{'selected'}->value(@tmp_options[1]); + if ($interfaces->{$real_inc_name}->{'type'}) { - my @type_options = @{$interfaces->{ $real_inc_name}->{'type'}->{'menu'}}; - if (ref( $type_options[0]) eq 'HASH') + my @type_options = @{ $interfaces->{$real_inc_name}->{'type'}->{'menu'} }; + if (ref($type_options[0]) eq 'HASH') { - for my $typeopt ( @type_options) + for my $typeopt (@type_options) { - if ( $typeopt->{'name'} eq $inc_type) + if ($typeopt->{'name'} eq $inc_type) { - $interfaces->{ $real_inc_name}->{'type'}->value($typeopt->{'value'}); + $interfaces->{$real_inc_name}->{'type'}->value($typeopt->{'value'}); last; } } } - else #AIX made the things more complicated, it didn't ship the - #last HTML::Form. So let's take a guess of the type value - #Not sure if it can work for all AIX version + else #AIX made the things more complicated, it didn't ship the + #last HTML::Form. So let's take a guess of the type value + #Not sure if it can work for all AIX version { - my @types = $interfaces->{ $real_inc_name}->{'type'}->possible_values(); - if ( $inc_type eq 'Dynamic') + my @types = $interfaces->{$real_inc_name}->{'type'}->possible_values(); + if ($inc_type eq 'Dynamic') { - $interfaces->{ $real_inc_name}->{'type'}->value(@types[0]); + $interfaces->{$real_inc_name}->{'type'}->value(@types[0]); } else { - $interfaces->{ $real_inc_name}->{'type'}->value(@types[1]); + $interfaces->{$real_inc_name}->{'type'}->value(@types[1]); } } -#not work on AIX -# $interfaces->{ $real_inc_name}->{'type'}->value('Static'); + + #not work on AIX + # $interfaces->{ $real_inc_name}->{'type'}->value('Static'); } else { - return ( [RC_ERROR,"Cannot change interface type"]); + return ([ RC_ERROR, "Cannot change interface type" ]); } - if ( $inc_type eq 'Static') + if ($inc_type eq 'Static') { - if ( $inc_ip) + if ($inc_ip) { - return ( [RC_ERROR,"Cannot set IP address to $inc_ip"]) if (! $interfaces->{ $real_inc_name}->{'ip'}); - $interfaces->{ $real_inc_name}->{'ip'}->value( $inc_ip); + return ([ RC_ERROR, "Cannot set IP address to $inc_ip" ]) if (!$interfaces->{$real_inc_name}->{'ip'}); + $interfaces->{$real_inc_name}->{'ip'}->value($inc_ip); push @set_entries, 'IP address'; } - if ( $inc_host) + if ($inc_host) { - return ( [RC_ERROR,"Cannot set hostname to $inc_host"]) if (! $interfaces->{ $real_inc_name}->{'hostname'}); - $interfaces->{ $real_inc_name}->{'hostname'}->value( $inc_host); + return ([ RC_ERROR, "Cannot set hostname to $inc_host" ]) if (!$interfaces->{$real_inc_name}->{'hostname'}); + $interfaces->{$real_inc_name}->{'hostname'}->value($inc_host); push @set_entries, 'hostname'; - if( ! $interfaces->{ $real_inc_name}->{'hostname'}->value()) + if (!$interfaces->{$real_inc_name}->{'hostname'}->value()) { $inc_host = $exp->[1]; } } - if ( $inc_gateway) + if ($inc_gateway) { - return ( [RC_ERROR,"Cannot set gateway to $inc_gateway"]) if (! $interfaces->{ $real_inc_name}->{'gateway'}); - $interfaces->{ $real_inc_name}->{'gateway'}->value( $inc_gateway); + return ([ RC_ERROR, "Cannot set gateway to $inc_gateway" ]) if (!$interfaces->{$real_inc_name}->{'gateway'}); + $interfaces->{$real_inc_name}->{'gateway'}->value($inc_gateway); push @set_entries, 'gateway'; } - if ( $inc_netmask) + if ($inc_netmask) { - return ( [RC_ERROR,"Cannot set netmask to $inc_netmask"]) if (! $interfaces->{ $real_inc_name}->{'netmask'}); - $interfaces->{ $real_inc_name}->{'netmask'}->value( $inc_netmask); + return ([ RC_ERROR, "Cannot set netmask to $inc_netmask" ]) if (!$interfaces->{$real_inc_name}->{'netmask'}); + $interfaces->{$real_inc_name}->{'netmask'}->value($inc_netmask); push @set_entries, 'netmask'; } } @@ -1999,39 +2010,39 @@ sub set_netcfg #Click "Continue" button sleep 2; my $data = $form->click('save'); - my $res = $ua->request( $data); + my $res = $ua->request($data); if (!$res->is_success()) { - return ( [RC_ERROR, "Failed to set " . join ',', @set_entries]); + return ([ RC_ERROR, "Failed to set " . join ',', @set_entries ]); } #Go to the confirm page - if ( $res->content !~ /content !~ /content; my @lines_to_print; for my $page_line (@page_lines) { chomp $page_line; - if ( $page_line =~ s/
$//) + if ($page_line =~ s/
$//) { push @lines_to_print, $page_line; } } - return ( [RC_ERROR,join "\n", @lines_to_print]); + return ([ RC_ERROR, join "\n", @lines_to_print ]); } - $ua->timeout( 2 ); + $ua->timeout(2); - $form = HTML::Form->parse( $res->content, $res->base ); + $form = HTML::Form->parse($res->content, $res->base); $data = $form->click('submit'); - $res = $ua->request( $data); + $res = $ua->request($data); ############################################################## # We cannot get the result of this update, since the network # is updated, the old URI is invalid anymore # Return success directory ############################################################## - return ( [SUCCESS, "Success to set " . join ',', @set_entries]); + return ([ SUCCESS, "Success to set " . join ',', @set_entries ]); } ########################################################################## @@ -2039,17 +2050,18 @@ sub set_netcfg ########################################################################## sub format_netcfg { - my $interfaces = shift; - my $output = undef; - for my $inc ( sort keys %$interfaces) + my $interfaces = shift; + my $output = undef; + for my $inc (sort keys %$interfaces) { -#improve needed: need to make the output consistent to MM + #improve needed: need to make the output consistent to MM $output .= "\n\t" . $inc . ":\n"; $output =~ s/interface(\d)/eth$1/; - # There are 2 possible value for $type, + + # There are 2 possible value for $type, # the first means "Dynamic", 2nd means "Static" # Now to find the correct type name - my $curr_type = $interfaces->{$inc}->{'type'}->value(); + my $curr_type = $interfaces->{$inc}->{'type'}->value(); my @possible_values = $interfaces->{$inc}->{'type'}->possible_values(); my $type; if ($curr_type == @possible_values[0]) @@ -2059,8 +2071,9 @@ sub format_netcfg else { $type = "Static"; - } -#not work on AIX + } + + #not work on AIX #my @possible_names = $interfaces->{$inc}->{'type'}->value_names(); #my %value_names = {}; #for ( my $i = 0; $i < scalar( @possible_values); $i++) @@ -2068,19 +2081,19 @@ sub format_netcfg # $value_names{ @possible_values[$i]} = @possible_names[$i]; #} #my $type = $interfaces->{$inc}->{'type'} ? $value_names{ $interfaces->{$inc}->{'type'}->value()} : undef;; - $type = "Static" if ( $type == 2); + $type = "Static" if ($type == 2); my $ip = $interfaces->{$inc}->{'ip'} ? $interfaces->{$inc}->{'ip'}->value() : undef; my $hostname = $interfaces->{$inc}->{'hostname'} ? $interfaces->{$inc}->{'hostname'}->value() : undef; my $gateway = $interfaces->{$inc}->{'gateway'} ? $interfaces->{$inc}->{'gateway'}->value() : undef; my $netmask = $interfaces->{$inc}->{'netmask'} ? $interfaces->{$inc}->{'netmask'}->value() : undef; - $output .= "\t\tIP Type: " . $type . "\n"; - $output .= "\t\tIP Address: " . $ip . "\n"; - $output .= "\t\tHostname: " . $hostname . "\n"; - $output .= "\t\tGateway: " . $gateway . "\n"; - $output .= "\t\tNetmask: " . $netmask . "\n"; + $output .= "\t\tIP Type: " . $type . "\n"; + $output .= "\t\tIP Address: " . $ip . "\n"; + $output .= "\t\tHostname: " . $hostname . "\n"; + $output .= "\t\tGateway: " . $gateway . "\n"; + $output .= "\t\tNetmask: " . $netmask . "\n"; } - return( [SUCCESS,$output] ); + return ([ SUCCESS, $output ]); } 1; diff --git a/perl-xCAT/xCAT/PPCinv.pm b/perl-xCAT/xCAT/PPCinv.pm index fb7860059..0012d5649 100644 --- a/perl-xCAT/xCAT/PPCinv.pm +++ b/perl-xCAT/xCAT/PPCinv.pm @@ -13,23 +13,23 @@ require xCAT::data::ibmhwtypes; # Maps HMC "lslic" attributes to text ########################################## my @licmap = ( - ["ecnumber", "Release Level "], - ["activated_level", "Active Level "], - ["installed_level", "Installed Level"], - ["accepted_level", "Accepted Level "], - ["curr_ecnumber_a", "Release Level A"], - ["curr_level_a", "Level A "], - ["curr_ecnumber_b", "Release Level B"], - ["curr_level_b", "Level B "], - ["curr_ecnumber_primary", "Release Level Primary"], - ["curr_level_primary", "Level Primary "], - ["curr_ecnumber_secondary","Release Level Secondary"], - ["curr_level_secondary", "Level Secondary"] + [ "ecnumber", "Release Level " ], + [ "activated_level", "Active Level " ], + [ "installed_level", "Installed Level" ], + [ "accepted_level", "Accepted Level " ], + [ "curr_ecnumber_a", "Release Level A" ], + [ "curr_level_a", "Level A " ], + [ "curr_ecnumber_b", "Release Level B" ], + [ "curr_level_b", "Level B " ], + [ "curr_ecnumber_primary", "Release Level Primary" ], + [ "curr_level_primary", "Level Primary " ], + [ "curr_ecnumber_secondary", "Release Level Secondary" ], + [ "curr_level_secondary", "Level Secondary" ] ); ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { @@ -44,84 +44,84 @@ sub parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose t) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose t))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Unsupported command #################################### - my ($cmd) = grep(/^$ARGV[0]$/, @rinv ); - if ( !defined( $cmd )) { - return(usage( "Invalid command: $ARGV[0]" )); + my ($cmd) = grep(/^$ARGV[0]$/, @rinv); + if (!defined($cmd)) { + return (usage("Invalid command: $ARGV[0]")); } if (exists($opt{t}) and $cmd ne "model") { - return(["Option 't' can only work with 'model'."]); + return (["Option 't' can only work with 'model'."]); } #################################### # Check for an extra argument #################################### shift @ARGV; - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # Set method to invoke + # Set method to invoke #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } ########################################################################## -# Returns VPD (model-type,serial-number) +# Returns VPD (model-type,serial-number) ########################################################################## sub enumerate_vpd { - my $exp = shift; - my $mtms = shift; - my $hash = shift; - my $filter = "type_model,serial_num"; + my $exp = shift; + my $mtms = shift; + my $hash = shift; + my $filter = "type_model,serial_num"; my @vpd; - my ($name) = keys %{$hash->{$mtms}}; - my $type = @{$hash->{$mtms}->{$name}}[4]; + my ($name) = keys %{ $hash->{$mtms} }; + my $type = @{ $hash->{$mtms}->{$name} }[4]; ################################## - # BPAs + # BPAs ################################## - if ( $type =~ /^bpa$/ ) { + if ($type =~ /^bpa$/) { my $filter = "type_model,serial_num"; - my $frame = xCAT::PPCcli::lssyscfg( $exp, $type, $mtms, $filter ); - my $Rc = shift(@$frame); + my $frame = xCAT::PPCcli::lssyscfg($exp, $type, $mtms, $filter); + my $Rc = shift(@$frame); ############################## # Return error ############################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$frame[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$frame[0] ]); } ############################## # Success @@ -129,36 +129,36 @@ sub enumerate_vpd { @vpd = split /,/, @$frame[0]; } ################################## - # CECs and LPARs + # CECs and LPARs ################################## else { ############################## # Send command for CEC only ############################## - my $cec = xCAT::PPCcli::lssyscfg( $exp, "fsp", $mtms, $filter ); + my $cec = xCAT::PPCcli::lssyscfg($exp, "fsp", $mtms, $filter); my $Rc = shift(@$cec); ############################## # Return error ############################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$cec[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$cec[0] ]); } ############################## - # Success + # Success ############################## @vpd = split /,/, @$cec[0]; } my %outhash = ( model => $vpd[0], - serial => $vpd[1] + serial => $vpd[1] ); - return( [SUCCESS,\%outhash] ); + return ([ SUCCESS, \%outhash ]); } ########################################################################## -# Returns memory/processor information for CEC/LPARs +# Returns memory/processor information for CEC/LPARs ########################################################################## sub enumerate_cfg { @@ -168,26 +168,26 @@ sub enumerate_cfg { my %outhash = (); my $sys = 0; my @cmds = ( - [ "sys", "proc", "installed_sys_proc_units" ], - [ "sys", "mem", "installed_sys_mem" ], - [ "lpar","proc", "lpar_id,curr_procs" ], - [ "lpar","mem", "lpar_id,curr_mem" ] + [ "sys", "proc", "installed_sys_proc_units" ], + [ "sys", "mem", "installed_sys_mem" ], + [ "lpar", "proc", "lpar_id,curr_procs" ], + [ "lpar", "mem", "lpar_id,curr_mem" ] ); my $cec; - my ($name) = keys %{$hash->{$mtms}}; - my $type = @{$hash->{$mtms}->{$name}}[4]; + my ($name) = keys %{ $hash->{$mtms} }; + my $type = @{ $hash->{$mtms}->{$name} }[4]; ###################################### # Invalid target hardware ###################################### - if ( $type !~ /^(fsp|lpar|cec)$/ ) { - return( [RC_ERROR,"Information only available for CEC/LPAR"] ); + if ($type !~ /^(fsp|lpar|cec)$/) { + return ([ RC_ERROR, "Information only available for CEC/LPAR" ]); } ###################################### # Check for CECs in list ###################################### - while (my ($name,$d) = each(%{$hash->{$mtms}}) ) { - if ( @$d[4] =~ /^(fsp|cec)$/ ) { + while (my ($name, $d) = each(%{ $hash->{$mtms} })) { + if (@$d[4] =~ /^(fsp|cec)$/) { $cec = $name; last; } @@ -195,51 +195,51 @@ sub enumerate_cfg { ###################################### # No CECs - Skip command for CEC ###################################### - if ( !defined( $cec )) { + if (!defined($cec)) { shift @cmds; shift @cmds; } ###################################### # No LPARs - Skip command for LPAR ###################################### - if (( keys %{$hash->{$mtms}} == 1 ) and ( scalar(@cmds) == 4 )) { + if ((keys %{ $hash->{$mtms} } == 1) and (scalar(@cmds) == 4)) { pop @cmds; pop @cmds; } - - foreach my $cmd( @cmds ) { - my $result = xCAT::PPCcli::lshwres( $exp, $cmd, $mtms ); + + foreach my $cmd (@cmds) { + my $result = xCAT::PPCcli::lshwres($exp, $cmd, $mtms); my $Rc = shift(@$result); ################################## # Expect error ################################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$result[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$result[0] ]); } ################################## # Success... # lshwres does not return CEC name ################################## - if ( @$cmd[0] eq "sys" ) { - foreach ( @$result[0] ) { + if (@$cmd[0] eq "sys") { + foreach (@$result[0]) { s/(.*)/0,$1/; } } ################################## - # Save by CEC/LPAR id + # Save by CEC/LPAR id ################################## - foreach ( @$result ) { - my ($id,$value) = split /,/; - push @{$outhash{$id}}, $value; + foreach (@$result) { + my ($id, $value) = split /,/; + push @{ $outhash{$id} }, $value; } } - return( [SUCCESS,\%outhash] ); + return ([ SUCCESS, \%outhash ]); } ########################################################################## -# Returns I/O bus information +# Returns I/O bus information ########################################################################## sub enumerate_bus { @@ -250,77 +250,77 @@ sub enumerate_bus { my @res = qw(lpar); my $filter = "drc_name,bus_id,description"; my @cmds = ( - undef, - "io --rsubtype slot", + undef, + "io --rsubtype slot", $filter ); my $cec; - my ($name) = keys %{$hash->{$mtms}}; - my $type = @{$hash->{$mtms}->{$name}}[4]; + my ($name) = keys %{ $hash->{$mtms} }; + my $type = @{ $hash->{$mtms}->{$name} }[4]; ################################## - # Invalid target hardware + # Invalid target hardware ################################## - if ( $type !~ /^(fsp|lpar|cec)$/ ) { - return( [RC_ERROR,"Bus information only available for CEC/LPAR"] ); + if ($type !~ /^(fsp|lpar|cec)$/) { + return ([ RC_ERROR, "Bus information only available for CEC/LPAR" ]); } ################################## - # Send command for CEC only + # Send command for CEC only ################################## - my $cecs = xCAT::PPCcli::lshwres( $exp, \@cmds, $mtms ); + my $cecs = xCAT::PPCcli::lshwres($exp, \@cmds, $mtms); my $Rc = shift(@$cecs); ################################## # Return error ################################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$cecs[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$cecs[0] ]); } ################################## - # Success + # Success ################################## my @bus = @$cecs; ################################## # Check for CECs in list ################################## - foreach ( keys %{$hash->{$mtms}} ) { - if ( @{$hash->{$mtms}->{$_}}[4] =~ /^(fsp|cec)$/ ) { + foreach (keys %{ $hash->{$mtms} }) { + if (@{ $hash->{$mtms}->{$_} }[4] =~ /^(fsp|cec)$/) { $cec = $_; last; } } ################################## - # Get LPAR ids + # Get LPAR ids ################################## - my $lpars = xCAT::PPCcli::lssyscfg( $exp, "lpar", $mtms, "lpar_id" ); + my $lpars = xCAT::PPCcli::lssyscfg($exp, "lpar", $mtms, "lpar_id"); $Rc = shift(@$lpars); ################################## # Return error ################################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$lpars[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$lpars[0] ]); } ################################## - # Save LPARs by id + # Save LPARs by id ################################## - foreach ( @$lpars ) { + foreach (@$lpars) { $outhash{$_} = \@bus; } ################################## # Save CEC by id ################################## - if ( defined( $cec )) { + if (defined($cec)) { $outhash{"0"} = \@bus; } - return( [SUCCESS,\%outhash] ); + return ([ SUCCESS, \%outhash ]); } ########################################################################## -# Returns I/O bus information +# Returns I/O bus information ########################################################################## sub bus { @@ -329,54 +329,54 @@ sub bus { my $exp = shift; my @result = (); - while (my ($mtms,$h) = each(%$hash) ) { + while (my ($mtms, $h) = each(%$hash)) { ##################################### # Get information for this CEC ##################################### - my $bus = enumerate_bus( $exp, $mtms, $hash ); - my $Rc = shift(@$bus); + my $bus = enumerate_bus($exp, $mtms, $hash); + my $Rc = shift(@$bus); my $data = @$bus[0]; - while (my ($name,$d) = each(%$h) ) { + while (my ($name, $d) = each(%$h)) { ################################## # Look up by lparid ################################## my $type = @$d[4]; - my $id = ($type=~/^(fsp|cec)$/) ? 0 : @$d[0]; + my $id = ($type =~ /^(fsp|cec)$/) ? 0 : @$d[0]; ################################# - # Output header + # Output header ################################# - push @result, [$name,"I/O Bus Information", 0]; + push @result, [ $name, "I/O Bus Information", 0 ]; ################################# - # Output error + # Output error ################################# - if ( $Rc != SUCCESS ) { - push @result, [$name,@$bus[0],$Rc]; + if ($Rc != SUCCESS) { + push @result, [ $name, @$bus[0], $Rc ]; next; } ################################# - # Node not found + # Node not found ################################# - if ( !exists( $data->{$id} )) { - push @result, [$name,"Node not found",1]; + if (!exists($data->{$id})) { + push @result, [ $name, "Node not found", 1 ]; next; - } + } ################################# - # Output values + # Output values ################################# - foreach ( @{$data->{$id}} ) { - push @result, [$name,$_,$Rc]; + foreach (@{ $data->{$id} }) { + push @result, [ $name, $_, $Rc ]; } } } - return( \@result ); + return (\@result); } ########################################################################## -# Returns VPD information +# Returns VPD information ########################################################################## sub vpd { @@ -386,48 +386,48 @@ sub vpd { my @cmds = $request->{method}; my @result = (); my %prefix = ( - model => ["Machine Type/Model",0], - serial => ["Serial Number", 1] + model => [ "Machine Type/Model", 0 ], + serial => [ "Serial Number", 1 ] ); - ######################################### + ######################################### # Convert "all" - ######################################### - if ( $cmds[0] eq "all" ) { + ######################################### + if ($cmds[0] eq "all") { @cmds = qw( model serial ); } - while (my ($mtms,$h) = each(%$hash) ) { + while (my ($mtms, $h) = each(%$hash)) { ##################################### # Get information for this CEC ##################################### - my $vpd = enumerate_vpd( $exp, $mtms, $hash ); - my $Rc = shift(@$vpd); + my $vpd = enumerate_vpd($exp, $mtms, $hash); + my $Rc = shift(@$vpd); my $data = @$vpd[0]; - while (my ($name) = each(%$h) ) { - foreach ( @cmds ) { + while (my ($name) = each(%$h)) { + foreach (@cmds) { ############################# # Output error ############################# - if ( $Rc != SUCCESS ) { - push @result, [$name,"@{$prefix{$_}}[0]: @$vpd[0]",$Rc]; + if ($Rc != SUCCESS) { + push @result, [ $name, "@{$prefix{$_}}[0]: @$vpd[0]", $Rc ]; next; - } + } ############################# - # Output value + # Output value ############################# if ($_ eq 'model' and exists($request->{opt}->{t})) { - my $tmp_pre = xCAT::data::ibmhwtypes::parse_group($data->{$_}); - if (defined($tmp_pre)) { - xCAT::TableUtils->updatenodegroups($name, $tmp_pre); - } - } - my $value = "@{$prefix{$_}}[0]: $data->{$_}"; - push @result, [$name,$value,$Rc]; + my $tmp_pre = xCAT::data::ibmhwtypes::parse_group($data->{$_}); + if (defined($tmp_pre)) { + xCAT::TableUtils->updatenodegroups($name, $tmp_pre); + } + } + my $value = "@{$prefix{$_}}[0]: $data->{$_}"; + push @result, [ $name, $value, $Rc ]; } } } - return( \@result ); + return (\@result); } @@ -442,66 +442,66 @@ sub firmware { my $hwtype = @$exp[2]; my @result; - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { ##################################### - # Command only supported on FSP/BPA/LPARs + # Command only supported on FSP/BPA/LPARs ##################################### - if ( @$d[4] !~ /^(fsp|bpa|cec|frame|lpar)$/ ) { - push @result, - [$name,"Information only available for CEC/BPA/LPAR",RC_ERROR]; - next; + if (@$d[4] !~ /^(fsp|bpa|cec|frame|lpar)$/) { + push @result, + [ $name, "Information only available for CEC/BPA/LPAR", RC_ERROR ]; + next; } - ################# - #For support on Lpars, the flag need to be changed. - ########## - if(@$d[4] =~ /^(lpar|cec)$/) { - @$d[4] = "fsp"; - } - if(@$d[4] =~ /^frame$/) { - @$d[4] = "bpa"; - } - my $values = xCAT::PPCcli::lslic( $exp, $d ); + ################# + #For support on Lpars, the flag need to be changed. + ########## + if (@$d[4] =~ /^(lpar|cec)$/) { + @$d[4] = "fsp"; + } + if (@$d[4] =~ /^frame$/) { + @$d[4] = "bpa"; + } + my $values = xCAT::PPCcli::lslic($exp, $d); my $Rc = shift(@$values); - + ##################################### # Return error ##################################### - if ( $Rc != SUCCESS ) { - push @result, [$name,@$values[0],$Rc]; - next; + if ($Rc != SUCCESS) { + push @result, [ $name, @$values[0], $Rc ]; + next; } ##################################### # Success - format IVM results ##################################### - if ( $hwtype eq "ivm" ) { - if ( @$values[0] !~ - /^system:(\w+)\s+\(t\)\s+(\w+)\s+\(p\)\s+(\w+)\s+/ ) { - push @result, [$name,@$values[0],$Rc]; + if ($hwtype eq "ivm") { + if (@$values[0] !~ + /^system:(\w+)\s+\(t\)\s+(\w+)\s+\(p\)\s+(\w+)\s+/) { + push @result, [ $name, @$values[0], $Rc ]; next; } - push @result, [$name,"Activated Level: $1",$Rc]; - push @result, [$name,"Permanent Level: $2",$Rc]; - push @result, [$name,"Temporary Level: $3",$Rc]; + push @result, [ $name, "Activated Level: $1", $Rc ]; + push @result, [ $name, "Permanent Level: $2", $Rc ]; + push @result, [ $name, "Temporary Level: $3", $Rc ]; next; } ##################################### # Format HMC results ##################################### - foreach ( @licmap ) { - if ( @$values[0] =~ /@$_[0]=(\w+)/ ) { - push @result, [$name,"@$_[1]: $1",$Rc]; + foreach (@licmap) { + if (@$values[0] =~ /@$_[0]=(\w+)/) { + push @result, [ $name, "@$_[1]: $1", $Rc ]; } } } } - return( \@result ); + return (\@result); } ########################################################################## -# Returns memory/processor information +# Returns memory/processor information ########################################################################## sub config { @@ -509,79 +509,79 @@ sub config { my $hash = shift; my $exp = shift; my @result = (); - my @prefix = ( - "Number of Processors: %s", + my @prefix = ( + "Number of Processors: %s", "Total Memory (MB): %s" ); - while (my ($mtms,$h) = each(%$hash) ) { + while (my ($mtms, $h) = each(%$hash)) { ##################################### # Get information for this CEC ##################################### - my $cfg = enumerate_cfg( $exp, $mtms, $hash ); - my $Rc = shift(@$cfg); + my $cfg = enumerate_cfg($exp, $mtms, $hash); + my $Rc = shift(@$cfg); my $data = @$cfg[0]; - - while (my ($name,$d) = each(%$h) ) { + + while (my ($name, $d) = each(%$h)) { ################################## # Look up by lparid ################################## my $type = @$d[4]; - my $id = ($type=~/^(fsp|cec)$/) ? 0 : @$d[0]; + my $id = ($type =~ /^(fsp|cec)$/) ? 0 : @$d[0]; ################################# # Output header ################################# - push @result, [$name,"Machine Configuration Info", 0]; + push @result, [ $name, "Machine Configuration Info", 0 ]; my $i; - foreach ( @prefix ) { + foreach (@prefix) { ############################# # Output error ############################# - if ( $Rc != SUCCESS ) { - my $value = sprintf( "$_", $data ); - push @result, [$name,$value,$Rc]; + if ($Rc != SUCCESS) { + my $value = sprintf("$_", $data); + push @result, [ $name, $value, $Rc ]; next; } ############################# # Node not found ############################# - if (!exists( $data->{$id} )) { - push @result, [$name,"Node not found",1]; + if (!exists($data->{$id})) { + push @result, [ $name, "Node not found", 1 ]; next; } ############################# # Output value ############################# - my $value = sprintf( $_, @{$data->{$id}}[$i++] ); - push @result, [$name,$value,$Rc]; + my $value = sprintf($_, @{ $data->{$id} }[ $i++ ]); + push @result, [ $name, $value, $Rc ]; } } } - return( \@result ); + return (\@result); } ########################################################################## -# Returns firmware version +# Returns firmware version ########################################################################## sub firm { - return( firmware(@_) ); + return (firmware(@_)); } ########################################################################## # Returns serial-number ########################################################################## sub serial { - return( vpd(@_) ); + return (vpd(@_)); } ########################################################################## # Returns machine-type-model ########################################################################## sub model { - return( vpd(@_) ); + return (vpd(@_)); } ########################################################################## @@ -589,13 +589,13 @@ sub model { ########################################################################## sub all { - my @result = ( - @{vpd(@_)}, - @{bus(@_)}, - @{config(@_)}, - @{firmware(@_)} - ); - return( \@result ); + my @result = ( + @{ vpd(@_) }, + @{ bus(@_) }, + @{ config(@_) }, + @{ firmware(@_) } + ); + return (\@result); } diff --git a/perl-xCAT/xCAT/PPClog.pm b/perl-xCAT/xCAT/PPClog.pm index a95323193..720288f89 100644 --- a/perl-xCAT/xCAT/PPClog.pm +++ b/perl-xCAT/xCAT/PPClog.pm @@ -12,7 +12,7 @@ use xCAT::Usage; sub parse_args { my $request = shift; - my $command = $request->{command}; + my $command = $request->{command}; my $args = $request->{arg}; my %opt = (); my @reventlog = qw(clear all); @@ -23,60 +23,60 @@ sub parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|Verbose) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|Verbose))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Unsupported commands #################################### - ($cmd) = grep(/^$ARGV[0]$/, @reventlog ); - if ( !defined( $cmd )) { + ($cmd) = grep(/^$ARGV[0]$/, @reventlog); + if (!defined($cmd)) { ################################ # Check for non-zero integer ################################ - if ( $ARGV[0] !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/ ) { - return(usage( "Invalid entry count: $ARGV[0]" )); + if ($ARGV[0] !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/) { + return (usage("Invalid entry count: $ARGV[0]")); } $cmd = "entries"; $opt{e} = $ARGV[0]; } shift @ARGV; - + #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # Set method to invoke + # Set method to invoke #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } diff --git a/perl-xCAT/xCAT/PPCmac.pm b/perl-xCAT/xCAT/PPCmac.pm index c39b70b67..75b11ee0f 100644 --- a/perl-xCAT/xCAT/PPCmac.pm +++ b/perl-xCAT/xCAT/PPCmac.pm @@ -14,7 +14,7 @@ use xCAT::MsgUtils qw(verbose_message); use xCAT::LparNetbootExp; ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { @@ -23,34 +23,34 @@ sub parse_args { my $cmd = $request->{command}; my $args = $request->{arg}; my $node = $request->{node}; - my $vers = - my @VERSION = qw( 2.1 ); + my $vers = + my @VERSION = qw( 2.1 ); ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt,qw(h|help V|verbose v|version C=s G=s S=s D d f M o F=s arp noping))) { - return( usage() ); + if (!GetOptions(\%opt, qw(h|help V|verbose v|version C=s G=s S=s D d f M o F=s arp noping))) { + return (usage()); } #################################### # Option -h for Help @@ -61,36 +61,36 @@ sub parse_args { #################################### # Option -v for version #################################### - if ( exists( $opt{v} )) { - return( \@VERSION ); + if (exists($opt{v})) { + return (\@VERSION); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # Check -o argument + # Check -o argument #################################### - if ( exists($opt{o}) ) { - unless (exists($opt{D})){ - return(usage( "The -o flag must be used with -D flag" )); + if (exists($opt{o})) { + unless (exists($opt{D})) { + return (usage("The -o flag must be used with -D flag")); } } - + #################################### # Check --noping argument which is used to skip the ping test for -D #################################### - if ( exists($opt{noping}) ) { - unless (exists($opt{D})){ - return(usage( "The --noping flag must be used with -D flag" )); + if (exists($opt{noping})) { + unless (exists($opt{D})) { + return (usage("The --noping flag must be used with -D flag")); } } @@ -98,7 +98,7 @@ sub parse_args { # Check argument for ping test # If set --noping with -D, don't need to check the -S, -C, -G #################################### - if ( exists($opt{D}) && !exists($opt{noping})) { + if (exists($opt{D}) && !exists($opt{noping})) { my @network; my $client_ip; my $gateway; @@ -109,29 +109,29 @@ sub parse_args { #################################### # Set server IP #################################### - if ( exists($opt{S}) ) { + if (exists($opt{S})) { push @network, $_; } else { - $server = xCAT::ServiceNodeUtils->getSNformattedhash( $node, "xcat", "node", "primary" ); - foreach my $key ( keys %$server ) { - my $valid_ip = xCAT::NetworkUtils->validate_ip( $key ); - if ( $valid_ip ) { + $server = xCAT::ServiceNodeUtils->getSNformattedhash($node, "xcat", "node", "primary"); + foreach my $key (keys %$server) { + my $valid_ip = xCAT::NetworkUtils->validate_ip($key); + if ($valid_ip) { ################################################### - # Service node is returned as hostname, Convert - # hostname to IP + # Service node is returned as hostname, Convert + # hostname to IP #################################### $server_ip = xCAT::NetworkUtils->getipaddr($key); chomp $server_ip; } else { #################################### # Service node is returned as an IP - # set the IP as server + # set the IP as server #################################### $server_ip = $key; } - if ( $server_ip ) { - $opt{S} = $server_ip; + if ($server_ip) { + $opt{S} = $server_ip; push @network, $server_ip; } last; @@ -140,51 +140,56 @@ sub parse_args { #################################################################### # Fulfill in the server network information for gateway resolving #################################################################### - if ( exists($opt{S}) ) { + if (exists($opt{S})) { + # why convert to hostname?? #$server = gethostbyaddr( inet_aton($opt{S}), AF_INET ); $server = $opt{S}; - if ( $server ) { - %server_nethash = xCAT::DBobjUtils->getNetwkInfo( [$server] ); + if ($server) { + %server_nethash = xCAT::DBobjUtils->getNetwkInfo([$server]); } } - my %client_nethash = xCAT::DBobjUtils->getNetwkInfo( $node ); + my %client_nethash = xCAT::DBobjUtils->getNetwkInfo($node); ##################################### # Network attributes undefined ##################################### - if ( !%client_nethash ) { + if (!%client_nethash) { + # IPv6, the client ip address may not be available, # if the link local address is being used, # the link local address is calculated from mac address if ($opt{S} =~ /:/) { + #get the network "fe80::" my $tmpll = "fe80::1"; - %client_nethash = xCAT::DBobjUtils->getNetwkInfo( [$tmpll] ); + %client_nethash = xCAT::DBobjUtils->getNetwkInfo([$tmpll]); if (defined $client_nethash{$tmpll}) { - $client_nethash{@$node[0]} = $client_nethash{$tmpll}; + $client_nethash{ @$node[0] } = $client_nethash{$tmpll}; } } else { - my $nodes = join( ",", @$node); - return( [RC_ERROR,"Cannot get network information for $nodes, check networks table and IP address for this node to make sure there is correct network in networks table"] ); + my $nodes = join(",", @$node); + return ([ RC_ERROR, "Cannot get network information for $nodes, check networks table and IP address for this node to make sure there is correct network in networks table" ]); } } - if ( exists($opt{C}) ) { - if ( scalar(@$node) > 1 ) { - return( [RC_ERROR,"Option '-C' doesn't work with noderange\n"] ); + if (exists($opt{C})) { + if (scalar(@$node) > 1) { + return ([ RC_ERROR, "Option '-C' doesn't work with noderange\n" ]); } push @network, $_; } else { + # get, check the node IP $client_ip = xCAT::NetworkUtils->getipaddr(@$node[0]); chomp $client_ip; - if ( $client_ip ) { + if ($client_ip) { $opt{C} = $client_ip; push @network, $client_ip; } else { if ($opt{S} =~ /:/) { + # set the IPv6 loopback address, lpar_netboot will handle it $opt{C} = "::1"; push @network, "::1"; @@ -193,12 +198,12 @@ sub parse_args { } - if ( exists($opt{G}) ) { + if (exists($opt{G})) { push @network, $_; - } elsif ( $client_nethash{@$node[0]}{net} eq $server_nethash{$server}{net} ) { + } elsif ($client_nethash{ @$node[0] }{net} eq $server_nethash{$server}{net}) { #################################### - # Set gateway to service node if - # service node and client node are + # Set gateway to service node if + # service node and client node are # in the same net #################################### $gateway = $opt{S}; @@ -208,44 +213,44 @@ sub parse_args { #################################### # Set gateway in networks table #################################### - $gateway = $client_nethash{@$node[0]}{gateway}; - if ( $gateway ) { + $gateway = $client_nethash{ @$node[0] }{gateway}; + if ($gateway) { $opt{G} = $gateway; push @network, $gateway; } } - if ( @network ) { - if ( scalar(@network) != 3 ) { - return( usage() ); + if (@network) { + if (scalar(@network) != 3) { + return (usage()); } - my $result = xCAT::NetworkUtils->validate_ip( $opt{C}, $opt{G}, $opt{S} ); - if ( @$result[0] ) { - return(usage( @$result[1] )); + my $result = xCAT::NetworkUtils->validate_ip($opt{C}, $opt{G}, $opt{S}); + if (@$result[0]) { + return (usage(@$result[1])); } } - } elsif ( (exists($opt{S}) || exists($opt{G}) || exists($opt{C})) && !exists($opt{D}) ) { - return( [RC_ERROR,"Option '-D' is required for ping test\n"] ); + } elsif ((exists($opt{S}) || exists($opt{G}) || exists($opt{C})) && !exists($opt{D})) { + return ([ RC_ERROR, "Option '-D' is required for ping test\n" ]); } #################################### - # Check -F options's format + # Check -F options's format #################################### - if ( exists($opt{F}) ) { - my @filters = split /,/,$opt{F}; - foreach ( @filters ) { - my @value = split /=/,$_; - if ( !@value[1] ) { - return( usage("Option '-F' contains wrong filter format") ); + if (exists($opt{F})) { + my @filters = split /,/, $opt{F}; + foreach (@filters) { + my @value = split /=/, $_; + if (!@value[1]) { + return (usage("Option '-F' contains wrong filter format")); } } } #################################### - # Set method to invoke + # Set method to invoke #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } @@ -254,23 +259,23 @@ sub parse_args { ########################################################################## sub do_getmacs { - my $request = shift; - my $d = shift; - my $exp = shift; - my $name = shift; - my $node = shift; - my $opt = $request->{opt}; - my $ssh = @$exp[0]; - my $userid = @$exp[4]; - my $pw = @$exp[5]; + my $request = shift; + my $d = shift; + my $exp = shift; + my $name = shift; + my $node = shift; + my $opt = $request->{opt}; + my $ssh = @$exp[0]; + my $userid = @$exp[4]; + my $pw = @$exp[5]; my %optarg; my $cmd; my $result; ####################################### - # Disconnect Expect session + # Disconnect Expect session ####################################### - xCAT::PPCcli::disconnect( $exp ); + xCAT::PPCcli::disconnect($exp); ####################################### # Get node data @@ -293,7 +298,7 @@ sub do_getmacs { # return( [RC_ERROR,"Command not installed: $cmd"] ); #} ####################################### - # Save user name and passwd of hcp to + # Save user name and passwd of hcp to # environment variables. # lpar_netboot.expect depends on this ####################################### @@ -301,17 +306,19 @@ sub do_getmacs { $ENV{HCP_PASSWD} = $pw; ####################################### - # Turn on verbose and debugging + # Turn on verbose and debugging ####################################### - if ( exists($request->{verbose}) ) { + if (exists($request->{verbose})) { + #$cmd.= " -v -x"; - $optarg{'v'} = 1; #for verbose - $optarg{'x'} = 1; #for debug + $optarg{'v'} = 1; #for verbose + $optarg{'x'} = 1; #for debug } ####################################### # Force LPAR shutdown ####################################### - if ( exists( $opt->{f} )) { + if (exists($opt->{f})) { + #$cmd.= " -i"; $optarg{'i'} = 1; } else { @@ -319,16 +326,17 @@ sub do_getmacs { # Force LPAR shutdown if LPAR is # running Linux ################################# - my $table = "nodetype"; - my $intable = 0; + my $table = "nodetype"; + my $intable = 0; my @TableRowArray = xCAT::DBobjUtils->getDBtable($table); - if ( @TableRowArray ) { - foreach ( @TableRowArray ) { + if (@TableRowArray) { + foreach (@TableRowArray) { my @nodelist = split(',', $_->{'node'}); - my @oslist = split(',', $_->{'os'}); - my $osname = "AIX"; - if ( grep(/^$node$/, @nodelist) ) { - if ( !grep(/^$osname$/, @oslist) ) { + my @oslist = split(',', $_->{'os'}); + my $osname = "AIX"; + if (grep(/^$node$/, @nodelist)) { + if (!grep(/^$osname$/, @oslist)) { + #$cmd.= " -i"; $optarg{'i'} = 1; } @@ -342,17 +350,20 @@ sub do_getmacs { # type is not assigned in table # but mnt node is running Linux ################################# - if ( xCAT::Utils->isLinux() && $intable == 0 ) { - #$cmd.= " -i"; - $optarg{'i'} = 1; + if (xCAT::Utils->isLinux() && $intable == 0) { + + #$cmd.= " -i"; + $optarg{'i'} = 1; } } - my %client_nethash = xCAT::DBobjUtils->getNetwkInfo( [$node] ); - if ( grep /hf/, $client_nethash{$node}{mgtifname} ) { + my %client_nethash = xCAT::DBobjUtils->getNetwkInfo([$node]); + if (grep /hf/, $client_nethash{$node}{mgtifname}) { + #$cmd.= " -t hfi-ent"; $optarg{'t'} = "hfi-ent"; } else { + #$cmd.= " -t ent"; $optarg{'t'} = "ent"; } @@ -360,16 +371,18 @@ sub do_getmacs { ####################################### # Network specified (-D ping test) ####################################### - if ( exists( $opt->{noping} )) { - $optarg{'D'} = 1; + if (exists($opt->{noping})) { + $optarg{'D'} = 1; $optarg{'noping'} = 1; } - if ( exists( $opt->{S} )) { - if ( exists( $opt->{o} )) { + if (exists($opt->{S})) { + if (exists($opt->{o})) { + #$cmd .=" -o"; - $optarg{'o'} = 1; + $optarg{'o'} = 1; } + #$cmd.= " -D -s auto -d auto -S $opt->{S} -G $opt->{G} -C $opt->{C}"; $optarg{'D'} = 1; $optarg{'s'} = 'auto'; @@ -377,52 +390,52 @@ sub do_getmacs { $optarg{'S'} = $opt->{S}; $optarg{'C'} = $opt->{C}; $optarg{'G'} = $opt->{G}; - } + } ####################################### - # Add command options + # Add command options ####################################### #$cmd.= " -f -M -A -n \"$name\" \"$pprofile\" \"$fsp\" $id $hcp \"$node\""; - $optarg{'f'} = 1; - $optarg{'M'} = 1; - $optarg{'A'} = 1; - $optarg{'n'} = $name; + $optarg{'f'} = 1; + $optarg{'M'} = 1; + $optarg{'A'} = 1; + $optarg{'n'} = $name; $optarg{'pprofile'} = $pprofile; - $optarg{'fsp'} = $fsp; - $optarg{'id'} = $id; - $optarg{'hcp'} = $hcp; - $optarg{'node'} = $node; + $optarg{'fsp'} = $fsp; + $optarg{'id'} = $id; + $optarg{'hcp'} = $hcp; + $optarg{'node'} = $node; - ######################################## - ## Execute command - ######################################## - #my $pid = open( OUTPUT, "$cmd 2>&1 |"); - #$SIG{INT} = $SIG{TERM} = sub { #prepare to process job termination and propogate it down - # kill 9, $pid; - # return( [RC_ERROR,"Received INT or TERM signal"] ); - #}; - #if ( !$pid ) { - # return( [RC_ERROR,"$cmd fork error: $!"] ); - #} - ######################################## - ## Get command output - ######################################## - #while ( ) { - # $result.=$_; - #} - #close OUTPUT; - # - ######################################## - ## Get command exit code - ######################################## - # - #foreach ( split /\n/, $result ) { - # if ( /^lpar_netboot / ) { - # $Rc = RC_ERROR; - # last; - # } - #} - xCAT::MsgUtils->verbose_message($request, "getmacs :lparnetbootexp for node:$node."); - my $Rc = xCAT::LparNetbootExp->lparnetbootexp(\%optarg, $request); + ######################################## + ## Execute command + ######################################## + #my $pid = open( OUTPUT, "$cmd 2>&1 |"); + #$SIG{INT} = $SIG{TERM} = sub { #prepare to process job termination and propogate it down + # kill 9, $pid; + # return( [RC_ERROR,"Received INT or TERM signal"] ); + #}; + #if ( !$pid ) { + # return( [RC_ERROR,"$cmd fork error: $!"] ); + #} + ######################################## + ## Get command output + ######################################## + #while ( ) { + # $result.=$_; + #} + #close OUTPUT; + # + ######################################## + ## Get command exit code + ######################################## + # + #foreach ( split /\n/, $result ) { + # if ( /^lpar_netboot / ) { + # $Rc = RC_ERROR; + # last; + # } + #} + xCAT::MsgUtils->verbose_message($request, "getmacs :lparnetbootexp for node:$node."); + my $Rc = xCAT::LparNetbootExp->lparnetbootexp(\%optarg, $request); ###################################### # Split results into array ###################################### @@ -444,129 +457,129 @@ sub getmacs { my $name; my @emptynode; - if ( $par =~ /^HASH/ ) { + if ($par =~ /^HASH/) { ######################################### # Parse the filters specified by user ######################################### my $filter; - if ( $opt->{F} ) { - my @filters = split /,/,$opt->{F}; - foreach ( @filters ) { - my @value = split /=/,$_; - $filter->{@value[0]} = @value[1]; + if ($opt->{F}) { + my @filters = split /,/, $opt->{F}; + foreach (@filters) { + my @value = split /=/, $_; + $filter->{ @value[0] } = @value[1]; } } - ######################################### + ######################################### # A hash to save lpar attributes - ######################################### + ######################################### my %nodeatt = (); ######################################### # Cleanup old data ######################################### - my $result = (); + my $result = (); ######################################### # No ping test performed, call lshwres # to achieve the MAC address ######################################### - foreach my $hcp ( keys %$par ) { + foreach my $hcp (keys %$par) { my $hash = $par->{$hcp}; - my $cmd; + my $cmd; ######################################### # Achieve virtual ethernet MAC address ######################################### - @$cmd[0] = ["lpar","virtualio","","eth"]; - @$cmd[1] = ["port","hea","","logical"]; - @$cmd[2] = ["port","hea","","phys"]; + @$cmd[0] = [ "lpar", "virtualio", "", "eth" ]; + @$cmd[1] = [ "port", "hea", "", "logical" ]; + @$cmd[2] = [ "port", "hea", "", "phys" ]; ######################################### # Parse the output of lshwres command ######################################### - for ( my $stat = 0; $stat < 3; $stat++ ) { - my $output = xCAT::PPCcli::lshwres( $exp, @$cmd[$stat], $hcp); - my $macs; + for (my $stat = 0 ; $stat < 3 ; $stat++) { + my $output = xCAT::PPCcli::lshwres($exp, @$cmd[$stat], $hcp); + my $macs; - foreach my $line ( @$output ) { - if ( $line =~ /^.*lpar\_id=(\d+),.*$/ ) { + foreach my $line (@$output) { + if ($line =~ /^.*lpar\_id=(\d+),.*$/) { ######################################### # For the first two commands ######################################### my $lparid = $1; $nodeatt{$hcp}{$lparid}{'num'}++; - $macs = $nodeatt{$hcp}{$lparid}{'num'}; - my @attrs = split /,/, $line; - foreach ( @attrs ) { + $macs = $nodeatt{$hcp}{$lparid}{'num'}; + my @attrs = split /,/, $line; + foreach (@attrs) { my @attr = split /=/, $_; - $nodeatt{$hcp}{$lparid}{$macs}{@attr[0]} = @attr[1]; + $nodeatt{$hcp}{$lparid}{$macs}{ @attr[0] } = @attr[1]; } - } elsif ( ($line =~ /^(.*)port\_group=(\d+),(.*),"log\_port\_ids=(.*)"/) || ($line =~ /^(.*)port\_group=(\d+),(.*),log\_port\_ids=(.*)/) ) { + } elsif (($line =~ /^(.*)port\_group=(\d+),(.*),"log\_port\_ids=(.*)"/) || ($line =~ /^(.*)port\_group=(\d+),(.*),log\_port\_ids=(.*)/)) { ######################################### # For the third command ######################################### my $port_group = $2; - if ( $4 !~ /^none$/ ) { - my @ids = split /,/, $4; - my @attrs = split /,/, $1; + if ($4 !~ /^none$/) { + my @ids = split /,/, $4; + my @attrs = split /,/, $1; foreach (@attrs) { - my @attr = split /=/,$_; + my @attr = split /=/, $_; foreach (@ids) { - $nodeatt{$hcp}{$port_group}{$_}{@attr[0]} = @attr[1]; - } - } - my @attrs = split /,/, $3; - foreach (@attrs) { - my @attr = split /=/,$_; - foreach (@ids) { - $nodeatt{$hcp}{$port_group}{$_}{@attr[0]} = @attr[1]; + $nodeatt{$hcp}{$port_group}{$_}{ @attr[0] } = @attr[1]; } } - } + my @attrs = split /,/, $3; + foreach (@attrs) { + my @attr = split /=/, $_; + foreach (@ids) { + $nodeatt{$hcp}{$port_group}{$_}{ @attr[0] } = @attr[1]; + } + } + } } } } - - foreach ( keys %$hash ) { - my $node = $_; - my $d = $hash->{$_}; - my $mtms = @$d[2]; - my $id = @$d[0]; - my $nodetype = @$d[4]; - my $mac_count = $nodeatt{$mtms}{$id}{'num'}; - my $value = (); - my $data = (); + foreach (keys %$hash) { + my $node = $_; + my $d = $hash->{$_}; + my $mtms = @$d[2]; + my $id = @$d[0]; + my $nodetype = @$d[4]; + + my $mac_count = $nodeatt{$mtms}{$id}{'num'}; + my $value = (); + my $data = (); my $type; ######################################### # Invalid target hardware ######################################### - if ( $nodetype ne "lpar" ) { - return( [[$node,"Node must be LPAR",RC_ERROR]] ); + if ($nodetype ne "lpar") { + return ([ [ $node, "Node must be LPAR", RC_ERROR ] ]); } ######################################### # Put all the attributes required # together ######################################### - push @$value,"\n#Type Phys_Port_Loc MAC_Address Adapter Port_Group Phys_Port Logical_Port VLan VSwitch Curr_Conn_Speed"; + push @$value, "\n#Type Phys_Port_Loc MAC_Address Adapter Port_Group Phys_Port Logical_Port VLan VSwitch Curr_Conn_Speed"; - for ( my $num = 1; $num <= $mac_count; $num++ ) { - my $mac_addr = $nodeatt{$mtms}{$id}{$num}{'mac_addr'}; - my $adapter_id = $nodeatt{$mtms}{$id}{$num}{'adapter_id'}; - my $port_group = $nodeatt{$mtms}{$id}{$num}{'port_group'}; - my $phys_port_id = $nodeatt{$mtms}{$id}{$num}{'phys_port_id'}; + for (my $num = 1 ; $num <= $mac_count ; $num++) { + my $mac_addr = $nodeatt{$mtms}{$id}{$num}{'mac_addr'}; + my $adapter_id = $nodeatt{$mtms}{$id}{$num}{'adapter_id'}; + my $port_group = $nodeatt{$mtms}{$id}{$num}{'port_group'}; + my $phys_port_id = $nodeatt{$mtms}{$id}{$num}{'phys_port_id'}; my $logical_port_id = $nodeatt{$mtms}{$id}{$num}{'logical_port_id'}; - my $vlan_id = $nodeatt{$mtms}{$id}{$num}{'port_vlan_id'}; - my $vswitch = $nodeatt{$mtms}{$id}{$num}{'vswitch'}; - my $phys_port_loc = $nodeatt{$mtms}{$port_group}{$logical_port_id}{'phys_port_loc'}; + my $vlan_id = $nodeatt{$mtms}{$id}{$num}{'port_vlan_id'}; + my $vswitch = $nodeatt{$mtms}{$id}{$num}{'vswitch'}; + my $phys_port_loc = $nodeatt{$mtms}{$port_group}{$logical_port_id}{'phys_port_loc'}; my $curr_conn_speed = $nodeatt{$mtms}{$port_group}{$logical_port_id}{'curr_conn_speed'}; - if ( $phys_port_loc ) { - $type = "hea "; + if ($phys_port_loc) { + $type = "hea "; } else { $type = "virtualio"; } @@ -575,89 +588,89 @@ sub getmacs { } my %att = (); - $att{'MAC_Address'} = ($mac_addr) ? $mac_addr : "N/A"; - $att{'Adapter'} = ($adapter_id) ? $adapter_id : "N/A"; - $att{'Port_Group'} = ($port_group) ? $port_group : "N/A"; - $att{'Phys_Port'} = ($phys_port_id) ? $phys_port_id : "N/A"; - $att{'Logical_Port'} = ($logical_port_id) ? $logical_port_id : "N/A"; - $att{'VLan'} = ($vlan_id) ? $vlan_id : "N/A"; - $att{'VSwitch'} = ($vswitch) ? $vswitch : "N/A"; - $att{'Phys_Port_Loc'} = ($phys_port_loc) ? $phys_port_loc : "N/A"; - $att{'Curr_Conn_Speed'} = ($curr_conn_speed) ? $curr_conn_speed : "N/A"; - $att{'Type'} = $type; + $att{'MAC_Address'} = ($mac_addr) ? $mac_addr : "N/A"; + $att{'Adapter'} = ($adapter_id) ? $adapter_id : "N/A"; + $att{'Port_Group'} = ($port_group) ? $port_group : "N/A"; + $att{'Phys_Port'} = ($phys_port_id) ? $phys_port_id : "N/A"; + $att{'Logical_Port'} = ($logical_port_id) ? $logical_port_id : "N/A"; + $att{'VLan'} = ($vlan_id) ? $vlan_id : "N/A"; + $att{'VSwitch'} = ($vswitch) ? $vswitch : "N/A"; + $att{'Phys_Port_Loc'} = ($phys_port_loc) ? $phys_port_loc : "N/A"; + $att{'Curr_Conn_Speed'} = ($curr_conn_speed) ? $curr_conn_speed : "N/A"; + $att{'Type'} = $type; ######################################### # Parse the adapter with the filters # specified ######################################### - if ( defined($filter) ) { + if (defined($filter)) { my $matched = 0; - foreach my $key ( keys %$filter ) { - if ( $key eq "MAC_Address" ) { - my $mac = lc($att{$key}); + foreach my $key (keys %$filter) { + if ($key eq "MAC_Address") { + my $mac = lc($att{$key}); my $filter_mac = lc($filter->{$key}); $mac =~ s/://g; $filter_mac =~ s/://g; - if ( grep(/$filter_mac/, $mac) ) { + if (grep(/$filter_mac/, $mac)) { $matched = 1; last; } - } elsif ( grep(/$filter->{$key}/, $att{$key}) ) { + } elsif (grep(/$filter->{$key}/, $att{$key})) { $matched = 1; last; } } - if ( $matched ) { - push @$value,"$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}"; + if ($matched) { + push @$value, "$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}"; } } else { - push @$value,"$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}"; + push @$value, "$att{'Type'} $att{'Phys_Port_Loc'} $att{'MAC_Address'} $att{'Adapter'} $att{'Port_Group'} $att{'Phys_Port'} $att{'Logical_Port'} $att{'VLan'} $att{'VSwitch'} $att{'Curr_Conn_Speed'}"; } } ######################################### # Write MAC address to database ######################################### - if ( !exists( $opt->{d} )) { - writemac( $node, $value ); + if (!exists($opt->{d})) { + writemac($node, $value); } - if ( scalar(@$value) < 2 ) { + if (scalar(@$value) < 2) { my $filter = "lpar_id,curr_profile"; - my $prof = xCAT::PPCcli::lssyscfg( $exp, "node", $mtms, $filter, $id ); + my $prof = xCAT::PPCcli::lssyscfg($exp, "node", $mtms, $filter, $id); my $Rc = shift(@$prof); ######################################### # Return error ######################################### - if ( $Rc != SUCCESS ) { - return( [[$node,@$prof[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $node, @$prof[0], $Rc ] ]); } - foreach my $val ( @$prof ) { - my ($lpar_id,$curr_profile) = split /,/, $val; - if ( (!length($curr_profile)) || ($curr_profile =~ /^none$/) ) { - push @emptynode,$node; + foreach my $val (@$prof) { + my ($lpar_id, $curr_profile) = split /,/, $val; + if ((!length($curr_profile)) || ($curr_profile =~ /^none$/)) { + push @emptynode, $node; } } } - foreach ( @$value ) { - if ( /^#\s?Type/ ) { - $data.= "\n$_\n"; + foreach (@$value) { + if (/^#\s?Type/) { + $data .= "\n$_\n"; } else { - $data.= "$_\n"; + $data .= "$_\n"; } } - push @$result,[$node,$data,0]; + push @$result, [ $node, $data, 0 ]; } } - if ( scalar(@emptynode) > 0 ) { - return([[join(",", @emptynode),"\nThese nodes have no active profiles. Please active the nodes to enable the default profiles",RC_ERROR]]); - } - return([@$result]); + if (scalar(@emptynode) > 0) { + return ([ [ join(",", @emptynode), "\nThese nodes have no active profiles. Please active the nodes to enable the default profiles", RC_ERROR ] ]); + } + return ([@$result]); } else { ######################################### # Connect to fsp to achieve MAC address @@ -666,93 +679,95 @@ sub getmacs { my $d = $par; ######################################### - # Get node data + # Get node data ######################################### - my $lparid = @$d[0]; - my $mtms = @$d[2]; - my $type = @$d[4]; - my $node = @$d[6]; + my $lparid = @$d[0]; + my $mtms = @$d[2]; + my $type = @$d[4]; + my $node = @$d[6]; ######################################### - # Invalid target hardware + # Invalid target hardware ######################################### - if ( $type ne "lpar" ) { - return( [[$node,"Node must be LPAR",RC_ERROR]] ); + if ($type ne "lpar") { + return ([ [ $node, "Node must be LPAR", RC_ERROR ] ]); } ######################################### # Get name known by HCP ######################################### my $filter = "name,lpar_id"; xCAT::MsgUtils->verbose_message($request, "getmacs :lssyscfg filter '$filter'."); - my $values = xCAT::PPCcli::lssyscfg( $exp, $type, $mtms, $filter ); + my $values = xCAT::PPCcli::lssyscfg($exp, $type, $mtms, $filter); my $Rc = shift(@$values); ######################################### # Return error ######################################### - if ( $Rc != SUCCESS ) { - return( [[$node,@$values[0],$Rc]] ); + if ($Rc != SUCCESS) { + return ([ [ $node, @$values[0], $Rc ] ]); } ######################################### # Find LPARs by lpar_id ######################################### - foreach ( @$values ) { - if ( /^(.*),$lparid$/ ) { + foreach (@$values) { + if (/^(.*),$lparid$/) { $name = $1; last; } } ######################################### - # Node not found by lpar_id + # Node not found by lpar_id ######################################### - if ( !defined( $name )) { - return( [[$node,"Node not found, lparid=$lparid",RC_ERROR]] ); + if (!defined($name)) { + return ([ [ $node, "Node not found, lparid=$lparid", RC_ERROR ] ]); } #my $sitetab = xCAT::Table->new('site'); #my $vcon = $sitetab->getAttribs({key => "conserverondemand"}, 'value'); - #there may be something wrong with the conserverondemand attribute. + #there may be something wrong with the conserverondemand attribute. # Currently, the code is not used. So not fix this time. Just keep it here. my @vcons = xCAT::TableUtils->get_site_attribute("conserverondemand"); - my $vcon = $vcons[0]; + my $vcon = $vcons[0]; + #if ($vcon and $vcon->{"value"} and $vcon->{"value"} eq "yes" ) { - if ( defined($vcon) and $vcon eq "yes" ) { + if (defined($vcon) and $vcon eq "yes") { $result = xCAT::PPCcli::lpar_netboot( - $exp, - $request->{verbose}, - $name, - $d, - $opt ); + $exp, + $request->{verbose}, + $name, + $d, + $opt); } else { ######################################### # Manually collect MAC addresses. ######################################### xCAT::MsgUtils->verbose_message($request, "getmacs :do_getmacs for node:$node."); - $result = do_getmacs( $request, $d, $exp, $name, $node ); + $result = do_getmacs($request, $d, $exp, $name, $node); $Rc = shift(@$result); } + #$sitetab->close; - - + + ################################## - # Form string from array results + # Form string from array results ################################## - if ( exists($request->{verbose}) ) { - if ( $Rc == SUCCESS ) { - if ( !exists( $opt->{d} )) { - writemac( $node, $result ); + if (exists($request->{verbose})) { + if ($Rc == SUCCESS) { + if (!exists($opt->{d})) { + writemac($node, $result); } } - return( [[$node,join( '', @$result ),$Rc]] ); + return ([ [ $node, join('', @$result), $Rc ] ]); } ################################## # Return error ################################## - if ( $Rc != SUCCESS ) { - if ( @$result[0] =~ /lpar_netboot Status: (.*)/ ) { - return( [[$node,$1,$Rc]] ); + if ($Rc != SUCCESS) { + if (@$result[0] =~ /lpar_netboot Status: (.*)/) { + return ([ [ $node, $1, $Rc ] ]); } - return( [[$node,join( '', @$result ),$Rc]] ); + return ([ [ $node, join('', @$result), $Rc ] ]); } ##################################### # lpar_netboot returns: @@ -770,21 +785,21 @@ sub getmacs { ##################################### my $data; - foreach ( @$result ) { - if ( /^#\s?Type/ ) { - $data.= "\n$_\n"; - } elsif ( /^ent\s+/ or /^hfi-ent\s+/ ) { - $data.= "$_\n"; + foreach (@$result) { + if (/^#\s?Type/) { + $data .= "\n$_\n"; + } elsif (/^ent\s+/ or /^hfi-ent\s+/) { + $data .= "$_\n"; } } ##################################### # Write first valid adapter MAC to database ##################################### - if ( !exists( $opt->{d} )) { - writemac( $node, $result ); + if (!exists($opt->{d})) { + writemac($node, $result); } xCAT::MsgUtils->verbose_message($request, "getmacs END."); - return( [[$node,$data,$Rc]] ); + return ([ [ $node, $data, $Rc ] ]); } } @@ -797,11 +812,11 @@ sub cal_mac { my $mac = shift; $mac =~ s/://g; - $mac =~ /(.........)(.)(..)/; - my ($basemac, $mac_h, $mac_l) = ($1,$2, $3); + $mac =~ /(.........)(.)(..)/; + my ($basemac, $mac_h, $mac_l) = ($1, $2, $3); my $macnum_l = hex($mac_l); my $macnum_h = hex($mac_h); - $macnum_l += 1; + $macnum_l += 1; if ($macnum_l > 0xFF) { $macnum_h += 1; } @@ -809,9 +824,9 @@ sub cal_mac { $newmac_l =~ /(..)$/; $newmac_l = $1; my $newmac_h = sprintf("%01X", $macnum_h); - my $newmac = $basemac.$newmac_h.$newmac_l; + my $newmac = $basemac . $newmac_h . $newmac_l; - return( $newmac ); + return ($newmac); } ########################################################################## @@ -827,8 +842,8 @@ sub format_mac { my @newmacs; my @macs = split /\|/, $mac; - if ( !xCAT::Utils->isAIX() ) { - foreach my $mac_a ( @macs ) { + if (!xCAT::Utils->isAIX()) { + foreach my $mac_a (@macs) { if (&checkmac($mac_a)) { push @newmacs, $mac_a; next; @@ -841,20 +856,20 @@ sub format_mac { $mac_a =~ s/:$//; push @newmacs, $mac_a; } - $mac = join("|",@newmacs); + $mac = join("|", @newmacs); } - return( "$mac\n" ); + return ("$mac\n"); } ########################################################################## -# checkmac format +# checkmac format ########################################################################## sub checkmac { my $mac = shift; - if ( !xCAT::Utils->isAIX()) { + if (!xCAT::Utils->isAIX()) { if ($mac =~ /\w{2}:\w{2}:\w{2}:\w{2}:\w{2}:\w{2}/) { return 1; } else { @@ -867,12 +882,12 @@ sub checkmac { ########################################################################## -# Write first valid adapter MAC to database +# Write first valid adapter MAC to database ########################################################################## sub writemac { - my $name = shift; - my $data = shift; + my $name = shift; + my $data = shift; my $value; my $pingret; my $ping_test; @@ -882,21 +897,21 @@ sub writemac { ##################################### # Find first valid adapter ##################################### - foreach ( @$data ) { + foreach (@$data) { unless (&checkmac($_)) { next; } - if ( /^ent\s+/ or /^hfi-ent\s+/ ) { + if (/^ent\s+/ or /^hfi-ent\s+/) { $value = $_; ##################################### # MAC not found in output ##################################### - if ( !defined( $value )) { + if (!defined($value)) { return; } @fields = split /\s+/, $value; $pingret = $fields[4]; - if ( $pingret eq "successful" ) { + if ($pingret eq "successful") { $ping_test = 0; last; } @@ -906,17 +921,17 @@ sub writemac { ##################################### # If no valid adapter, find the first one ##################################### - if ( $pingret ne "successful" ) { - foreach ( @$data ) { + if ($pingret ne "successful") { + foreach (@$data) { unless (&checkmac($_)) { next; } - if ( /^ent\s+/ or /^hfi-ent\s+/ ) { - $value = $_; + if (/^ent\s+/ or /^hfi-ent\s+/) { + $value = $_; $ping_test = 0; last; - } elsif ( /^hea\s+/ || /^virtualio\s+/ ) { - $value = $_; + } elsif (/^hea\s+/ || /^virtualio\s+/) { + $value = $_; $ping_test = 1; last; } @@ -926,24 +941,24 @@ sub writemac { ##################################### # MAC not found in output ##################################### - if ( !defined( $value )) { + if (!defined($value)) { return; } ##################################### # Get adapter mac ##################################### - #$value = format_mac( $value ); + #$value = format_mac( $value ); @fields = split /\s+/, $value; - $mac = $fields[2]; + $mac = $fields[2]; ##################################### # Write adapter mac to database ##################################### - my $mactab = xCAT::Table->new( "mac", -create=>1, -autocommit=>1 ); - if ( !$mactab ) { - return( [[$name,"Error opening 'mac'",RC_ERROR]] ); + my $mactab = xCAT::Table->new("mac", -create => 1, -autocommit => 1); + if (!$mactab) { + return ([ [ $name, "Error opening 'mac'", RC_ERROR ] ]); } - $mactab->setNodeAttribs( $name,{mac=>$mac} ); + $mactab->setNodeAttribs($name, { mac => $mac }); $mactab->close(); } diff --git a/perl-xCAT/xCAT/PPCpower.pm b/perl-xCAT/xCAT/PPCpower.pm index a37453305..e61dbbcbf 100644 --- a/perl-xCAT/xCAT/PPCpower.pm +++ b/perl-xCAT/xCAT/PPCpower.pm @@ -8,6 +8,9 @@ use xCAT::Usage; use xCAT::MsgUtils; use xCAT::FSPpower; +use xCAT::GlobalDef; +use xCAT_monitoring::monitorctrl; + ########################################################################## # Parse the command line for options and operands ########################################################################## @@ -16,92 +19,92 @@ sub parse_args { my $command = $request->{command}; my $args = $request->{arg}; my %opt = (); - my @rpower = qw(on onstandby off softoff stat state reset boot of sms rackstandby exit_rackstandby lowpower resetsp cycle); + my @rpower = qw(on onstandby off softoff stat state reset boot of sms rackstandby exit_rackstandby lowpower resetsp cycle); ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose m:s@ t=s T=s r=s nodeps) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose m:s@ t=s T=s r=s nodeps))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Unsupported commands #################################### - my ($cmd) = grep(/^$ARGV[0]$/, @rpower ); - if ( !defined( $cmd )) { - return(usage( "Invalid command: $ARGV[0]" )); + my ($cmd) = grep(/^$ARGV[0]$/, @rpower); + if (!defined($cmd)) { + return (usage("Invalid command: $ARGV[0]")); } #################################### # Check for an extra argument #################################### shift @ARGV; - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # Change "stat" to "state" + # Change "stat" to "state" #################################### $request->{op} = $cmd; $cmd =~ s/^stat$/state/; - + #################################### # Power commands special case #################################### - if ( $cmd ne "state" ) { - $cmd = ($cmd eq "boot") ? "powercmd_boot" : "powercmd"; + if ($cmd ne "state") { + $cmd = ($cmd eq "boot") ? "powercmd_boot" : "powercmd"; } $request->{method} = $cmd; - if (exists( $opt{m} ) ){ + if (exists($opt{m})) { my $res = xCAT::Utils->check_deployment_monitoring_settings($request, \%opt); if ($res != SUCCESS) { - return(usage()); + return (usage()); } } - if( ! exists $opt{T} ) + if (!exists $opt{T}) { - $opt{T} = "lpar"; #defaut value is lpar. + $opt{T} = "lpar"; #defaut value is lpar. } - - if( $opt{T} eq "lpar") { - $opt{T} = 0; - } elsif($opt{T} eq "fnm") { + + if ($opt{T} eq "lpar") { + $opt{T} = 0; + } elsif ($opt{T} eq "fnm") { $opt{T} = 1; - if ( $request->{op} !~ /^(onstandby|state|stat)$/) { - return(usage("The tooltype fnm only could be used with onstandby/state/stat action.")); - } + if ($request->{op} !~ /^(onstandby|state|stat)$/) { + return (usage("The tooltype fnm only could be used with onstandby/state/stat action.")); + } } else { - return( usage('Wrong value of -T option. The value can be lpar or fnm. The defaut value is lpar.')); + return (usage('Wrong value of -T option. The value can be lpar or fnm. The defaut value is lpar.')); } - return( \%opt ); + return (\%opt); } @@ -114,42 +117,42 @@ sub enumerate { my $node = shift; my $mtms = shift; my %outhash = (); - my %cmds = (); + my %cmds = (); ###################################### # Check for CEC/LPAR/BPAs in list ###################################### - while (my ($name,$d) = each(%$node) ) { + while (my ($name, $d) = each(%$node)) { my $type = @$d[4]; - $cmds{$type} = ($type=~/^lpar$/) ? "state,lpar_id" : "state"; + $cmds{$type} = ($type =~ /^lpar$/) ? "state,lpar_id" : "state"; } - foreach my $type ( keys %cmds ) { + foreach my $type (keys %cmds) { my $filter = $cmds{$type}; - my $values = xCAT::PPCcli::lssyscfg( $exp, $type, $mtms, $filter ); - my $Rc = shift(@$values); + my $values = xCAT::PPCcli::lssyscfg($exp, $type, $mtms, $filter); + my $Rc = shift(@$values); ################################## - # Return error + # Return error ################################## - if ( $Rc != SUCCESS ) { - return( [$Rc,@$values[0]] ); + if ($Rc != SUCCESS) { + return ([ $Rc, @$values[0] ]); } ################################## - # Save LPARs by id + # Save LPARs by id ################################## - foreach ( @$values ) { - my ($state,$lparid) = split /,/; + foreach (@$values) { + my ($state, $lparid) = split /,/; ############################## - # No lparid for fsp/bpa + # No lparid for fsp/bpa ############################## - if ( $type =~ /^(fsp|bpa|cec|frame)$/ ) { + if ($type =~ /^(fsp|bpa|cec|frame)$/) { $lparid = $type; } - $outhash{ $lparid } = $state; + $outhash{$lparid} = $state; } } - return( [SUCCESS,\%outhash] ); + return ([ SUCCESS, \%outhash ]); } @@ -158,132 +161,148 @@ sub enumerate { ########################################################################## sub powercmd_boot { - my $request = shift; - my $hash = shift; - my $exp = shift; - my @output = (); + my $request = shift; + my $hash = shift; + my $exp = shift; + my @output = (); my $callback = $request->{'callback'}; ###################################### - # Power commands are grouped by CEC + # Power commands are grouped by CEC # not Hardware Control Point ###################################### ###################################### - # Get CEC MTMS + # Get CEC MTMS ###################################### my ($name) = keys %$hash; - my $mtms = @{$hash->{$name}}[2]; + my $mtms = @{ $hash->{$name} }[2]; ###################################### # Build CEC/LPAR information hash ###################################### - my $stat = enumerate( $exp, $hash, $mtms ); - my $Rc = shift(@$stat); + my $stat = enumerate($exp, $hash, $mtms); + my $Rc = shift(@$stat); my $data = @$stat[0]; - while (my ($name,$d) = each(%$hash) ) { + my $newstat; + my %newnodestatus = (); + + while (my ($name, $d) = each(%$hash)) { ################################## # Look up by lparid ################################## my $type = @$d[4]; - my $id = ($type=~/^(fsp|bpa|frame|cec)$/) ? $type : @$d[0]; + my $id = ($type =~ /^(fsp|bpa|frame|cec)$/) ? $type : @$d[0]; ################################## # Output error ################################## - if ( $Rc != SUCCESS ) { - push @output, [$name,$data,$Rc]; + if ($Rc != SUCCESS) { + push @output, [ $name, $data, $Rc ]; next; } + ################################## - # Node not found + # Node not found ################################## - if ( !exists( $data->{$id} )) { - push @output, [$name,"Node not found",1]; + if (!exists($data->{$id})) { + push @output, [ $name, "Node not found", 1 ]; next; } ################################## # Convert state to on/off ################################## my $state = power_status($data->{$id}); - my $op = ($state =~ /^off$/) ? "on" : "reset"; + my $op = ($state =~ /^off$/) ? "on" : "reset"; + + if ($state =~ /^off$/) { + $newstat = $::STATUS_POWERING_ON; + } # Attribute powerinterval in site table, # to control the rpower forking speed - if ((defined($request->{op})) && ($request->{op} ne 'stat') && ($request->{op} ne 'status') - && ($request->{op} ne 'state') && ($request->{op} ne 'off') && ($request->{op} ne 'softoff')) { - if(defined($request->{'powerinterval'}) && ($request->{'powerinterval'} ne '')) { + if ((defined($request->{op})) && ($request->{op} ne 'stat') && ($request->{op} ne 'status') + && ($request->{op} ne 'state') && ($request->{op} ne 'off') && ($request->{op} ne 'softoff')) { + if (defined($request->{'powerinterval'}) && ($request->{'powerinterval'} ne '')) { Time::HiRes::sleep($request->{'powerinterval'}); - } - } + } + } ############################## # Send power command ############################## my $result = xCAT::PPCcli::chsysstate( - $exp, - $op, - $d ); - push @output, [$name,@$result[1],@$result[0]]; + $exp, + $op, + $d); + unless (@$result[0] != SUCCESS) { + if ($newstat) { + push @{ $newnodestatus{$newstat} }, $name; + } + } + push @output, [ $name, @$result[1], @$result[0] ]; } if (defined($request->{opt}->{m})) { - my $retries = 0; + my $retries = 0; my @monnodes = keys %$hash; my $monsettings = xCAT::Utils->generate_monsettings($request, \@monnodes); xCAT::Utils->monitor_installation($request, $monsettings); - while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{$monsettings->{nodes}}) > 0) { + while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{ $monsettings->{nodes} }) > 0) { - #The nodes that need to retry - my @nodesretry = keys %{$monsettings->{'nodes'}}; - my $nodes = join ',', @nodesretry; - my $rsp={}; - $rsp->{data}->[0] = "$nodes: Reinitializing the installation: $retries retry"; - xCAT::MsgUtils->message("I", $rsp, $callback); + #The nodes that need to retry + my @nodesretry = keys %{ $monsettings->{'nodes'} }; + my $nodes = join ',', @nodesretry; + my $rsp = {}; + $rsp->{data}->[0] = "$nodes: Reinitializing the installation: $retries retry"; + xCAT::MsgUtils->message("I", $rsp, $callback); - foreach my $node (keys %$hash) - { - # The installation for this node has been finished - if(!grep(/^$node$/, @nodesretry)) { - delete($hash->{$node}); - } - } - while (my ($name,$d) = each(%$hash) ) { - my $type = @$d[4]; - my $id = ($type=~/^(fsp|bpa)$/) ? $type : @$d[0]; + foreach my $node (keys %$hash) + { + # The installation for this node has been finished + if (!grep(/^$node$/, @nodesretry)) { + delete($hash->{$node}); + } + } + while (my ($name, $d) = each(%$hash)) { + my $type = @$d[4]; + my $id = ($type =~ /^(fsp|bpa)$/) ? $type : @$d[0]; - if ( $Rc != SUCCESS ) { - push @output, [$name,$data,$Rc]; - next; - } - if ( !exists( $data->{$id} )) { - push @output, [$name,"Node not found",1]; - next; - } - my $state = power_status($data->{$id}); - my $op = ($state =~ /^off$/) ? "on" : "reset"; + if ($Rc != SUCCESS) { + push @output, [ $name, $data, $Rc ]; + next; + } + if (!exists($data->{$id})) { + push @output, [ $name, "Node not found", 1 ]; + next; + } + my $state = power_status($data->{$id}); + my $op = ($state =~ /^off$/) ? "on" : "reset"; - my $result = xCAT::PPCcli::chsysstate( - $exp, - $op, - $d ); - push @output, [$name,@$result[1],@$result[0]]; - } - my @monnodes = keys %{$monsettings->{nodes}}; - xCAT::Utils->monitor_installation($request, $monsettings); + my $result = xCAT::PPCcli::chsysstate( + $exp, + $op, + $d); + push @output, [ $name, @$result[1], @$result[0] ]; + } + my @monnodes = keys %{ $monsettings->{nodes} }; + xCAT::Utils->monitor_installation($request, $monsettings); } + #failed after retries - if (scalar(keys %{$monsettings->{'nodes'}}) > 0) { - foreach my $node (keys %{$monsettings->{nodes}}) { - my $rsp={}; + if (scalar(keys %{ $monsettings->{'nodes'} }) > 0) { + foreach my $node (keys %{ $monsettings->{nodes} }) { + my $rsp = {}; $rsp->{data}->[0] = "The node \"$node\" can not reach the expected status after $monsettings->{'retrycount'} retries, the installation for this done failed"; xCAT::MsgUtils->message("E", $rsp, $callback); - } + } } - } - return( \@output ); + } + + xCAT_monitoring::monitorctrl::setNodeStatusAttributes(\%newnodestatus, 1); + return (\@output); } @@ -292,86 +311,120 @@ sub powercmd_boot { ########################################################################## sub powercmd { - my $request = shift; - my $hash = shift; - my $exp = shift; - my @result = (); + my $request = shift; + my $hash = shift; + my $exp = shift; + my @result = (); my $callback = $request->{'callback'}; + my ($name) = keys %$hash; + my $mtms = @{ $hash->{$name} }[2]; + my $stat = enumerate($exp, $hash, $mtms); + my $Rc = shift(@$stat); + my $data = @$stat[0]; + + my $newstat; + my %newnodestatus = (); #################################### - # Power commands are grouped by CEC + # Power commands are grouped by CEC # not Hardware Control Point #################################### - while (my ($name,$d) = each(%$hash) ) { + while (my ($name, $d) = each(%$hash)) { + $newstat = ""; + # Attribute powerinterval in site table, # to control the rpower forking speed - if ((defined($request->{op})) && ($request->{op} ne 'stat') && ($request->{op} ne 'status') - && ($request->{op} ne 'state') && ($request->{op} ne 'off') && ($request->{op} ne 'softoff')) { - if(defined($request->{'powerinterval'}) && ($request->{'powerinterval'} ne '')) { + if ((defined($request->{op})) && ($request->{op} ne 'stat') && ($request->{op} ne 'status') + && ($request->{op} ne 'state') && ($request->{op} ne 'off') && ($request->{op} ne 'softoff')) { + if (defined($request->{'powerinterval'}) && ($request->{'powerinterval'} ne '')) { Time::HiRes::sleep($request->{'powerinterval'}); - } - } + } + } + if (($request->{op} eq 'off') || ($request->{op} ne 'softoff')) { + $newstat = $::STATUS_POWERING_OFF; + } + if ($request->{op} eq 'on') { + $newstat = $::STATUS_POWERING_ON; + } + + if ($request->{op} eq 'reset') { + my $type = @$d[4]; + my $id = ($type =~ /^(fsp|bpa|frame|cec)$/) ? $type : @$d[0]; + my $state = power_status($data->{$id}); + if ($state !~ /^off$/) { + $newstat = $::STATUS_POWERING_ON; + } + } ################################ # Send command to each LPAR ################################ my $values = xCAT::PPCcli::chsysstate( - $exp, - $request->{op}, - $d ); + $exp, + $request->{op}, + $d); my $Rc = shift(@$values); + unless ($Rc != SUCCESS) { + if ($newstat) { + push @{ $newnodestatus{$newstat} }, $name; + } + } + ################################ # Return result ################################ - push @result, [$name,@$values[0],$Rc]; + push @result, [ $name, @$values[0], $Rc ]; } if (defined($request->{opt}->{m})) { - my $retries = 0; + my $retries = 0; my @monnodes = keys %$hash; my $monsettings = xCAT::Utils->generate_monsettings($request, \@monnodes); xCAT::Utils->monitor_installation($request, $monsettings); - while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{$monsettings->{nodes}}) > 0) { - #The nodes that need to retry - my @nodesretry = keys %{$monsettings->{'nodes'}}; - my $nodes = join ',', @nodesretry; + while ($retries++ < $monsettings->{'retrycount'} && scalar(keys %{ $monsettings->{nodes} }) > 0) { - my $rsp={}; - $rsp->{data}->[0] = "$nodes: Reinitializing the installation: $retries retry"; - xCAT::MsgUtils->message("I", $rsp, $callback); + #The nodes that need to retry + my @nodesretry = keys %{ $monsettings->{'nodes'} }; + my $nodes = join ',', @nodesretry; - foreach my $node (keys %$hash) - { - # The installation for this node has been finished - if(!grep(/^$node$/, @nodesretry)) { - delete($hash->{$node}); - } - } - while (my ($name,$d) = each(%$hash) ) { - my $values = xCAT::PPCcli::chsysstate( - $exp, - $request->{op}, - $d ); - my $Rc = shift(@$values); + my $rsp = {}; + $rsp->{data}->[0] = "$nodes: Reinitializing the installation: $retries retry"; + xCAT::MsgUtils->message("I", $rsp, $callback); - push @result, [$name,@$values[0],$Rc]; - } - my @monnodes = keys %{$monsettings->{nodes}}; - xCAT::Utils->monitor_installation($request, $monsettings); + foreach my $node (keys %$hash) + { + # The installation for this node has been finished + if (!grep(/^$node$/, @nodesretry)) { + delete($hash->{$node}); + } + } + while (my ($name, $d) = each(%$hash)) { + my $values = xCAT::PPCcli::chsysstate( + $exp, + $request->{op}, + $d); + my $Rc = shift(@$values); + + push @result, [ $name, @$values[0], $Rc ]; + } + my @monnodes = keys %{ $monsettings->{nodes} }; + xCAT::Utils->monitor_installation($request, $monsettings); } + #failed after retries - if (scalar(keys %{$monsettings->{'nodes'}}) > 0) { - foreach my $node (keys %{$monsettings->{nodes}}) { - my $rsp={}; + if (scalar(keys %{ $monsettings->{'nodes'} }) > 0) { + foreach my $node (keys %{ $monsettings->{nodes} }) { + my $rsp = {}; $rsp->{data}->[0] = "The node \"$node\" can not reach the expected status after $monsettings->{'retrycount'} retries, the installation for this done failed"; xCAT::MsgUtils->message("E", $rsp, $callback); - } + } } - } - return( \@result ); + } + xCAT_monitoring::monitorctrl::setNodeStatusAttributes(\%newnodestatus, 1); + return (\@result); } @@ -385,12 +438,12 @@ sub power_status { "Running", "Open Firmware" ); - foreach ( @states ) { - if ( /^$_[0]$/ ) { - return("on"); + foreach (@states) { + if (/^$_[0]$/) { + return ("on"); } - } - return("off"); + } + return ("off"); } @@ -407,36 +460,36 @@ sub state { my @result = (); - if ( !defined( $prefix )) { + if (!defined($prefix)) { $prefix = ""; } - while (my ($mtms,$h) = each(%$hash) ) { + while (my ($mtms, $h) = each(%$hash)) { ###################################### # Build CEC/LPAR information hash ###################################### - my $stat = enumerate( $exp, $h, $mtms ); - my $Rc = shift(@$stat); + my $stat = enumerate($exp, $h, $mtms); + my $Rc = shift(@$stat); my $data = @$stat[0]; - - while (my ($name,$d) = each(%$h) ) { + + while (my ($name, $d) = each(%$h)) { ################################## - # Look up by lparid + # Look up by lparid ################################## my $type = @$d[4]; - my $id = ($type=~/^(fsp|bpa|cec|frame)$/) ? $type : @$d[0]; - + my $id = ($type =~ /^(fsp|bpa|cec|frame)$/) ? $type : @$d[0]; + ################################## # Output error ################################## - if ( $Rc != SUCCESS ) { - push @result, [$name, "$prefix$data",$Rc]; + if ($Rc != SUCCESS) { + push @result, [ $name, "$prefix$data", $Rc ]; next; } ################################## - # Node not found + # Node not found ################################## - if ( !exists( $data->{$id} )) { - push @result, [$name, $prefix."Node not found",1]; + if (!exists($data->{$id})) { + push @result, [ $name, $prefix . "Node not found", 1 ]; next; } ################################## @@ -445,15 +498,15 @@ sub state { my $value = $data->{$id}; ############################## - # Convert state to on/off + # Convert state to on/off ############################## - if ( defined( $convert )) { - $value = power_status( $value ); + if (defined($convert)) { + $value = power_status($value); } - push @result, [$name,"$prefix$value",$Rc]; + push @result, [ $name, "$prefix$value", $Rc ]; } } - return( \@result ); + return (\@result); } diff --git a/perl-xCAT/xCAT/PPCrflash.pm b/perl-xCAT/xCAT/PPCrflash.pm index ec1f9af4e..89184a49c 100644 --- a/perl-xCAT/xCAT/PPCrflash.pm +++ b/perl-xCAT/xCAT/PPCrflash.pm @@ -14,10 +14,10 @@ use Getopt::Long; use File::Spec; use POSIX qw(tmpnam); -my $packages_dir= (); -my $activate = (); -my $verbose = 0; -$::POWER_DEST_DIR = "/tmp"; +my $packages_dir = (); +my $activate = (); +my $verbose = 0; +$::POWER_DEST_DIR = "/tmp"; my $release_level; my $active_level; my @dirlist; @@ -33,16 +33,16 @@ my $housekeeping = undef; ################################### sub dpush { my $value = shift; - my $msg = shift; + my $msg = shift; - if($verbose == 1) { - push(@$value,$msg); + if ($verbose == 1) { + push(@$value, $msg); } } ########################################################################## -# Parse the command line for options and operands +# Parse the command line for options and operands ########################################################################## sub parse_args { @@ -53,7 +53,7 @@ sub parse_args { my $args = $request->{arg}; ############################################# # Change CEC/Frame node into FSPs/BPAs - ############################################# + ############################################# #my @newnodes = (); #my $nodes = $request->{node}; #foreach my $snode(@$nodes) { @@ -71,19 +71,19 @@ sub parse_args { # } #} #$request->{node} = \@newnodes; - + ############################################# # Responds with usage statement ############################################# local *usage = sub { - my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + my $usage_string = xCAT::Usage->getUsage($cmd); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No arguments specified" )); + if (!defined($args)) { + return (usage("No arguments specified")); } ############################################# @@ -91,155 +91,155 @@ sub parse_args { # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(h|help v|version V|verbose p=s d=s activate=s commit recover bpa_acdl) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(h|help v|version V|verbose p=s d=s activate=s commit recover bpa_acdl))) { + return (usage()); } - + #################################### # Option -v for version #################################### - if ( exists( $opt{v} )) { + if (exists($opt{v})) { if (!defined($::VERSION)) { - return ([xCAT::Usage->getVersion($cmd)]); - } - return( [$::VERSION] ); + return ([ xCAT::Usage->getVersion($cmd) ]); + } + return ([$::VERSION]); } - - if ( exists( $opt{h}) || $opt{help}) { - return( usage()); + + if (exists($opt{h}) || $opt{help}) { + return (usage()); } ################################# #Option --activate not valid with --commit or --recover ################################# - if (exists($opt{bpa_acdl}) && (exists($opt{activate}) || exists($opt{commit}) || - exists($opt{recover}) || exists($opt{p}) || exists($opt{d}))) { - return ( usage("Option --bpa_acdl not valid with other options ")); + if (exists($opt{bpa_acdl}) && (exists($opt{activate}) || exists($opt{commit}) || + exists($opt{recover}) || exists($opt{p}) || exists($opt{d}))) { + return (usage("Option --bpa_acdl not valid with other options ")); + } + + if (exists($opt{activate}) && (exists($opt{commit}) || exists($opt{recover}))) { + return (usage("Option --activate not valid with --commit or --recover ")); } - - if( exists( $opt{activate} ) && (exists( $opt{commit}) || exists( $opt{recover}))) { - return( usage("Option --activate not valid with --commit or --recover ") ); - } ################################# #Option -p not valid with --commit or --recover ################################# - if( exists( $opt{p} ) && (exists( $opt{commit}) || exists( $opt{recover} ))) { - return( usage("Option -p not valid with --commit or --recover ") ); + if (exists($opt{p}) && (exists($opt{commit}) || exists($opt{recover}))) { + return (usage("Option -p not valid with --commit or --recover ")); } - + ################################# #Option -p required ################################# - if( exists( $opt{p} ) && (!exists( $opt{activate}) )) { - return( usage("Option -p must be used with --activate ") ); - } - - if ( exists( $opt{p} ) && ($opt{p} !~ /^\//) ) {#relative path - $opt{p} = xCAT::Utils->full_path($opt{p}, $request->{cwd}->[0]); - } - - if( exists( $opt{d} ) ) { - if(!exists( $opt{activate}) ) { - return( usage("Option -d must be used with --activate ") ); - } + if (exists($opt{p}) && (!exists($opt{activate}))) { + return (usage("Option -p must be used with --activate ")); } - if ( exists( $opt{d} ) && ($opt{d} !~ /^\//) ) {#relative path + if (exists($opt{p}) && ($opt{p} !~ /^\//)) { #relative path + $opt{p} = xCAT::Utils->full_path($opt{p}, $request->{cwd}->[0]); + } + + if (exists($opt{d})) { + if (!exists($opt{activate})) { + return (usage("Option -d must be used with --activate ")); + } + } + + if (exists($opt{d}) && ($opt{d} !~ /^\//)) { #relative path $opt{d} = xCAT::Utils->full_path($opt{d}, $request->{cwd}->[0]); } ############################### #--activate's value only can be concurrent and disruptive ################################ - if(exists($opt{activate})) { + if (exists($opt{activate})) { if (defined($request->{mgt}) && $request->{mgt} =~ /xCAT::FSP/i) { if ($opt{activate} !~ /deferred|disruptive/) { return (usage("--activate's value can only be deferred or disruptive.")); } } else { - if(($opt{activate} ne "disruptive") && ($opt{activate} ne "concurrent")) { + if (($opt{activate} ne "disruptive") && ($opt{activate} ne "concurrent")) { return (usage("--activate's value can only be disruptive or concurrent.")); } } - if(!exists( $opt{d} )) { + if (!exists($opt{d})) { $opt{d} = "/tmp"; } } - + #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } - + #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } - - + + #check to see if we are housekeeping or updating # - if( defined( $opt{commit}) ) { + if (defined($opt{commit})) { print "commit flag\n"; $housekeeping = "commit"; - } elsif( defined( $opt{ recover }) ) { + } elsif (defined($opt{recover})) { print "recover flag\n"; $housekeeping = "recover"; - } elsif (defined( $opt{ bpa_acdl})) { + } elsif (defined($opt{bpa_acdl})) { print "bpa_acdl flag\n"; $housekeeping = "bpa_acdl"; } else { print "no housekeeping - update mode\n"; $housekeeping = undef; } - + $request->{housekeeping} = $housekeeping; ############################################# # Option -V for verbose output ############################################ - if ( exists( $opt{V} )) { + if (exists($opt{V})) { $verbose = 1; } - + #################### #suport for "rflash", copy the rpm and xml packages from user-spcefied-directory to /install/packages_fw - ##################### - if ( (!exists($opt{commit})) && (!exists($opt{ recover })) && (!exists($opt{bpa_acdl}))) { - if( preprocess_for_rflash($request, \%opt) == -1) { - return( usage() ); + ##################### + if ((!exists($opt{commit})) && (!exists($opt{recover})) && (!exists($opt{bpa_acdl}))) { + if (preprocess_for_rflash($request, \%opt) == -1) { + return (usage()); } } - - if(noderange_validate($request) == -1) { - return(usage()); - } - - $request->{callback}->({data =>[ "It may take considerable time to complete, depending on the number of systems being updated. In particular, power subsystem updates may take an hour or more if there are many attached managed systems. Please waiting. "]}); - if( $request->{hwtype} =~ /^(fsp|bpa)$/ && $opt{activate} =~ /^disruptive$/ ) { - $request->{callback}->({data =>[ "You can find the log files in the /var/log/xcatd/dfm/rflash/."]}); + if (noderange_validate($request) == -1) { + return (usage()); + } + + $request->{callback}->({ data => ["It may take considerable time to complete, depending on the number of systems being updated. In particular, power subsystem updates may take an hour or more if there are many attached managed systems. Please waiting. "] }); + + if ($request->{hwtype} =~ /^(fsp|bpa)$/ && $opt{activate} =~ /^disruptive$/) { + $request->{callback}->({ data => ["You can find the log files in the /var/log/xcatd/dfm/rflash/."] }); } #################################### - # No operands - add command name + # No operands - add command name #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ########################################################################## -# Invokes the callback with the specified message +# Invokes the callback with the specified message ########################################################################## sub send_msg { @@ -250,23 +250,23 @@ sub send_msg { ################################################# # Called from child process - send to parent ################################################# - if ( exists( $request->{pipe} )) { + if (exists($request->{pipe})) { my $out = $request->{pipe}; $output{errorcode} = $ecode; - $output{data} = \@_; - print $out freeze( [\%output] ); + $output{data} = \@_; + print $out freeze([ \%output ]); print $out "\nENDOFFREEZE6sK4ci\n"; } ################################################# # Called from parent - invoke callback directly ################################################# - elsif ( exists( $request->{callback} )) { + elsif (exists($request->{callback})) { my $callback = $request->{callback}; $output{errorcode} = $ecode; - $output{data} = \@_; - $callback->( \%output ); + $output{data} = \@_; + $callback->(\%output); } } @@ -275,8 +275,10 @@ sub send_msg { ##################################### sub noderange_validate { my $request = shift; - #my $opt = shift; + + #my $opt = shift; my $noderange = $request->{node}; + #my $t = print_var($request, "request"); #print $t; #################### @@ -289,8 +291,9 @@ sub noderange_validate { # Group nodes ########################################### my $mytypehash = xCAT::DBobjUtils->getnodetype($noderange, "ppc"); - foreach my $node ( @$noderange ) { + foreach my $node (@$noderange) { my $type = undef; + #my $sitetab = xCAT::Table->new( 'nodetype' ); #if ( defined( $sitetab )) { # my ($ent) = $sitetab->getAttribs({ node=>$node},'nodetype'); @@ -299,12 +302,14 @@ sub noderange_validate { # } #} $type = $$mytypehash{$node}; + #print "type:$type\n"; - if( $type =~/(fsp|lpar|cec)/) { + if ($type =~ /(fsp|lpar|cec)/) { $f1 = 1; } else { $f2 = 1; - my $exargs=$request->{arg}; + my $exargs = $request->{arg}; + #my $t = print_var($exargs, "exargs"); #print $t; #if ( grep(/commit/,@$exargs) != 0 || grep(/recover/,@$exargs) != 0) { @@ -315,103 +320,107 @@ sub noderange_validate { } } - if($f1 * $f2) { - send_msg( $request, 1, "The argument noderange of rflash can't be BPA and CEC(or LPAR) at the same time"); + if ($f1 * $f2) { + send_msg($request, 1, "The argument noderange of rflash can't be BPA and CEC(or LPAR) at the same time"); return -1; } } sub preprocess_for_rflash { - my $request = shift; - my $opt = shift; - my $callback = $request->{callback}; + my $request = shift; + my $opt = shift; + my $callback = $request->{callback}; my $install_dir = xCAT::TableUtils->getInstallDir(); my $packages_fw = "$install_dir/packages_fw"; - my $c = 0; + my $c = 0; my $packages_d; -# foreach (@$exargs) { -# $c++; -# if($_ eq "-p") { -# $packages_d = $$exargs[$c]; -# last; -# } -# } + + # foreach (@$exargs) { + # $c++; + # if($_ eq "-p") { + # $packages_d = $$exargs[$c]; + # last; + # } + # } $packages_d = $$opt{p}; - if($packages_d ne $packages_fw ) { + if ($packages_d ne $packages_fw) { $$opt{p} = $packages_fw; - if(! -d $packages_d) { + if (!-d $packages_d) { + #send_msg($request, 1, "The directory $packages_d doesn't exist!"); - $callback->({data=>["The directory $packages_d doesn't exist!"]}); - $request = (); - return -1; - } - - #print "opening directory and reading names\n"; - opendir DIRHANDLE, $packages_d; - my @dirlist= readdir DIRHANDLE; - closedir DIRHANDLE; - - @dirlist = File::Spec->no_upwards( @dirlist ); - - # Make sure we have some files to process - # - if( !scalar( @dirlist ) ) { - #send_msg($request, 1, "The directory $packages_d is empty !"); - $callback->({data=>["The directory $packages_d is empty !"]}); - $request = (); - return -1; - } - - #Find the rpm lic file - my @rpmlist = grep /\.rpm$/, @dirlist; - my @xmllist = grep /\.xml$/, @dirlist; - if( @rpmlist == 0 | @xmllist == 0) { - #send_msg($request, 1, "There isn't any rpm and xml files in the directory $packages_d!"); - $callback->({data=>["There isn't any rpm and xml files in the directory $packages_d!"]}); + $callback->({ data => ["The directory $packages_d doesn't exist!"] }); $request = (); return -1; } - - my $rpm_list = join(" ", @rpmlist); + + #print "opening directory and reading names\n"; + opendir DIRHANDLE, $packages_d; + my @dirlist = readdir DIRHANDLE; + closedir DIRHANDLE; + + @dirlist = File::Spec->no_upwards(@dirlist); + + # Make sure we have some files to process + # + if (!scalar(@dirlist)) { + + #send_msg($request, 1, "The directory $packages_d is empty !"); + $callback->({ data => ["The directory $packages_d is empty !"] }); + $request = (); + return -1; + } + + #Find the rpm lic file + my @rpmlist = grep /\.rpm$/, @dirlist; + my @xmllist = grep /\.xml$/, @dirlist; + if (@rpmlist == 0 | @xmllist == 0) { + + #send_msg($request, 1, "There isn't any rpm and xml files in the directory $packages_d!"); + $callback->({ data => ["There isn't any rpm and xml files in the directory $packages_d!"] }); + $request = (); + return -1; + } + + my $rpm_list = join(" ", @rpmlist); my $xml_list = join(" ", @xmllist); - + my $cmd; - if( -d $packages_fw) { + if (-d $packages_fw) { $cmd = "rm -rf $packages_fw/*"; xCAT::Utils->runcmd($cmd, 0); - if ($::RUNCMD_RC != 0) - { + if ($::RUNCMD_RC != 0) + { #send_msg($request, 1, "Failed to remove the old packages in $packages_fw."); - $callback->({data=>["Failed to remove the old packages in $packages_fw."]}); + $callback->({ data => ["Failed to remove the old packages in $packages_fw."] }); $request = (); return -1; - } } - + } + $cmd = "mkdir -p $packages_fw"; xCAT::Utils->runcmd("$cmd", 0); if ($::RUNCMD_RC != 0) { #send_msg($request, 1, "$cmd failed."); - $callback->({data=>["$cmd failed."]}); + $callback->({ data => ["$cmd failed."] }); $request = (); return; } - + $cmd = "cp $packages_d/*.rpm $packages_d/*.xml $packages_fw"; xCAT::Utils->runcmd($cmd, 0); if ($::RUNCMD_RC != 0) { #send_msg($request, 1, "$cmd failed."); - $callback->({data=>["$cmd failed."]}); + $callback->({ data => ["$cmd failed."] }); $request = (); return -1; } - #$req->{arg} = $exargs; + #$req->{arg} = $exargs; } return 0; } @@ -419,61 +428,65 @@ sub preprocess_for_rflash { sub print_var { - my $j = shift; + my $j = shift; my $msg = shift; - + my $var = "+++++++++$msg start--++++\n"; - if(ref($j) eq "ARRAY") { + if (ref($j) eq "ARRAY") { my $t; - foreach $t(@$j) { - if(ref($t) eq "ARRAY") { + foreach $t (@$j) { + if (ref($t) eq "ARRAY") { my $t0 = join(" ", @$t); + #if(ref($t0) eq "SCALAR") { - $var = $var."\t$t0(array)\n"; + $var = $var . "\t$t0(array)\n"; + #} else { # &print_var($t0); #} - } elsif( ref($t) eq "HASH" ) { + } elsif (ref($t) eq "HASH") { my $t12; my $t23; - while(($t12, $t23) = each(%$t)) { - $var = $var. "\t$t12 => \n"; - #if(ref($t23) eq "SCALAR") { - $var = $var. "\t$t23(hash)\n"; - #} else { - # &print_var($t23); - #} + while (($t12, $t23) = each(%$t)) { + $var = $var . "\t$t12 => \n"; + + #if(ref($t23) eq "SCALAR") { + $var = $var . "\t$t23(hash)\n"; + + #} else { + # &print_var($t23); + #} } - - }else { - $var = $var. "$t\n"; + + } else { + $var = $var . "$t\n"; } } } elsif (ref($j) eq "HASH") { my $t1; my $t2; - while(($t1, $t2) =each (%$j)) { - $var = $var. "$t1 =>"; - if(ref($t2) eq "HASH") { + while (($t1, $t2) = each(%$j)) { + $var = $var . "$t1 =>"; + if (ref($t2) eq "HASH") { my $t12; my $t23; - while(($t12, $t23) = each(%$t2)) { - $var = $var. "\t$t12 => $t23\n"; + while (($t12, $t23) = each(%$t2)) { + $var = $var . "\t$t12 => $t23\n"; } - } elsif(ref($t2) eq "ARRAY") { + } elsif (ref($t2) eq "ARRAY") { my $t = join(" ", @$t2); - $var = $var. "$t (array)\n"; + $var = $var . "$t (array)\n"; } else { - $var = $var. "$t2\n"; + $var = $var . "$t2\n"; } } } else { - $var = $var. "$j(scalar)\n"; + $var = $var . "$j(scalar)\n"; } - $var = $var. "+++++++++++$msg end+++++++++++\n"; - + $var = $var . "+++++++++++$msg end+++++++++++\n"; + return $var; } @@ -483,88 +496,91 @@ sub print_var { #-------------------------------------------------------------------------# # sub get_lic_filenames { - my $mtms = shift; - my $upgrade_required = 0; - my $msg = undef; + my $mtms = shift; + my $upgrade_required = 0; + my $msg = undef; my $filename; - if(! -d $packages_dir) { + if (!-d $packages_dir) { $msg = "The directory $packages_dir doesn't exist!"; - return ("","","", $msg, -1); + return ("", "", "", $msg, -1); } - + #print "opening directory and reading names\n"; opendir DIRHANDLE, $packages_dir; - @dirlist= readdir DIRHANDLE; + @dirlist = readdir DIRHANDLE; closedir DIRHANDLE; - @dirlist = File::Spec->no_upwards( @dirlist ); + @dirlist = File::Spec->no_upwards(@dirlist); # Make sure we have some files to process # - if( !scalar( @dirlist ) ) { + if (!scalar(@dirlist)) { $msg = "directory $packages_dir is empty"; - return ("","","",$msg, -1); + return ("", "", "", $msg, -1); } - $release_level =~/(\w{4})(\d{3})/; + $release_level =~ /(\w{4})(\d{3})/; my $pns = $1; my $fff = $2; - + #Find the latest version lic file @dirlist = grep /\.rpm$/, @dirlist; - @dirlist = grep /$1/, @dirlist; - if( !scalar( @dirlist ) ) { - $msg = "There isn't a package suitable for $mtms"; - return ("","","",$msg, -1); + @dirlist = grep /$1/, @dirlist; + if (!scalar(@dirlist)) { + $msg = "There isn't a package suitable for $mtms"; + return ("", "", "", $msg, -1); } - if( scalar(@dirlist) > 1) { + if (scalar(@dirlist) > 1) { + # Need to find the latest version package. - @dirlist =reverse sort(@dirlist); + @dirlist = reverse sort(@dirlist); my $t = "\n"; - foreach $t(@dirlist) { - $msg =$msg."$t\t"; + foreach $t (@dirlist) { + $msg = $msg . "$t\t"; } } - $filename = File::Spec->catfile( $packages_dir, $dirlist[0] ); - $dirlist[0] =~ /(\w{4})(\d{3})_(\w{3})_(\d{3}).rpm$/; + $filename = File::Spec->catfile($packages_dir, $dirlist[0]); + $dirlist[0] =~ /(\w{4})(\d{3})_(\w{3})_(\d{3}).rpm$/; ############## #If the release levels are different, it will be upgrade_required. ############# - if($fff ne $2) { + if ($fff ne $2) { $upgrade_required = 1; - if($activate ne "disruptive") { + if ($activate ne "disruptive") { $msg = "Option --activate's value should be disruptive"; - return ("", "","", $msg, -1); + return ("", "", "", $msg, -1); } } else { - if(($pns eq $1) && ($3 > $active_level) &&($4 <= $active_level)) { - $msg = $msg. "Upgrade $mtms $activate!"; - if($activate ne "concurrent") { + if (($pns eq $1) && ($3 > $active_level) && ($4 <= $active_level)) { + $msg = $msg . "Upgrade $mtms $activate!"; + if ($activate ne "concurrent") { $msg = "Option --actviate's value should be concurrent"; - return ("", "","", $msg, -1); + return ("", "", "", $msg, -1); } } else { $msg = $msg . "Upgrade $mtms!"; - if($activate ne "disruptive") { + if ($activate ne "disruptive") { $msg = "Option --activate's value should be disruptive"; - return ("", "","", $msg, -1); + return ("", "", "", $msg, -1); } - } + } } + #print "filename is $filename\n"; my $xml_file_name = $filename; $xml_file_name =~ s/(.+\.)rpm/\1xml/; + #print "check_licdd_update: source xml file is $xml_file_name\n"; - if( ( -z $filename)|| ( -z $xml_file_name) ) { - $msg = "The package $filename or xml $xml_file_name is empty" ; + if ((-z $filename) || (-z $xml_file_name)) { + $msg = "The package $filename or xml $xml_file_name is empty"; return ("", "", "", $msg, -1); } - - return ($filename, $xml_file_name ,$upgrade_required, $msg, 0); + + return ($filename, $xml_file_name, $upgrade_required, $msg, 0); } @@ -576,27 +592,27 @@ sub get_one_mtms { my $mtms; my $msg; - my $values = xCAT::PPCcli::send_cmd( $exp, $cmd ); + my $values = xCAT::PPCcli::send_cmd($exp, $cmd); my $Rc = shift(@$values); ##################################### # Return error ##################################### - if ( $Rc != SUCCESS ) { - $msg = "ERROR: Failed to find a CEC managed by $bpa on the HMC"; - return ("", $msg); + if ($Rc != SUCCESS) { + $msg = "ERROR: Failed to find a CEC managed by $bpa on the HMC"; + return ("", $msg); } foreach (@$values) { - if( $_ =~ /cage_num=(\w*),contents=sys,type_model_serial_num=(\w+)-(\w+)\*(\w+),loc_code=(\w+).(\w+).(\w+)/) { + if ($_ =~ /cage_num=(\w*),contents=sys,type_model_serial_num=(\w+)-(\w+)\*(\w+),loc_code=(\w+).(\w+).(\w+)/) { $mtms = "$2-$3*$4"; last; } } - + # print "the managed system is $mtms!\n"; - return ($mtms, $msg); + return ($mtms, $msg); } @@ -612,115 +628,119 @@ sub rflash { my $subreq = $request->{subreq}; my $hwtype = @$exp[2]; my @result; - my $timeout = $request->{ppctimeout}; - + my $timeout = $request->{ppctimeout}; + my $housekeeping = $request->{housekeeping}; $packages_dir = $request->{opt}->{p}; - $activate = $request->{opt}->{activate}; + $activate = $request->{opt}->{activate}; my $hmc; my $mtms; - my $component; # system or power + my $component; # system or power my $h; my $user; - - my $tmp_file; #the file handle of the stanza + + my $tmp_file; #the file handle of the stanza my $rpm_file; my $xml_file; my @rpm_files; my @xml_files; my $upgrade_required; my $stanza = undef; - my $mtms_t; + my $mtms_t; my @value; my %infor; $hmc = @$exp[3]; - dpush(\@value, [$hmc, "In rflash()"]); - dpush(\@value,[$hmc, print_var($request, "request")]); - dpush(\@value,[$hmc, print_var($hash, "hash")]); - dpush(\@value,[$hmc, print_var($exp, "exp")]); + dpush(\@value, [ $hmc, "In rflash()" ]); + dpush(\@value, [ $hmc, print_var($request, "request") ]); + dpush(\@value, [ $hmc, print_var($hash, "hash") ]); + dpush(\@value, [ $hmc, print_var($exp, "exp") ]); + # print_var($t); ######################## # Now build a temporary file containing the stanzas to be run on the HMC ################### - my $tmp_file = tmpnam();# the file handle of the stanza + my $tmp_file = tmpnam(); # the file handle of the stanza ############################## # Open the temp file ########################## - - dpush(\@value,[$hmc, "opening file $tmp_file"]); - unless( open TMP, ">$tmp_file" ) { - push (@value,[ $hmc, "cannot open $tmp_file, $!\n"]); - return (\@value); + + dpush(\@value, [ $hmc, "opening file $tmp_file" ]); + unless (open TMP, ">$tmp_file") { + push(@value, [ $hmc, "cannot open $tmp_file, $!\n" ]); + return (\@value); } - while(($mtms,$h) = each(%$hash)) { - dpush(\@value,[$hmc, "mtms:$mtms"]); + while (($mtms, $h) = each(%$hash)) { + dpush(\@value, [ $hmc, "mtms:$mtms" ]); $mtms_t = "$mtms_t $mtms"; - my $lflag = 0; + my $lflag = 0; my $managed_system = $mtms; - if( defined( $housekeeping ) ) { + if (defined($housekeeping)) { + #$hmc_has_work = 1; #$::work_flag = 1; - &dpush(\@value,[$hmc,"$mtms:creating stanza for housekeeping operation\n"]); + &dpush(\@value, [ $hmc, "$mtms:creating stanza for housekeeping operation\n" ]); $stanza = "updlic::" . $managed_system . "::" . $housekeeping . "::::"; - - &dpush(\@value,[$hmc, "$mtms:Writing $stanza to file\n"]); + + &dpush(\@value, [ $hmc, "$mtms:Writing $stanza to file\n" ]); + #push(@result,[$hmc,"$mtms:$housekeeping successfully!"]); - $infor{$mtms} = [$housekeeping]; + $infor{$mtms} = [$housekeeping]; print TMP "$stanza\n"; } else { - while(my ($name, $d) = each(%$h)) { - if ( @$d[4] !~ /^(fsp|bpa|lpar|cec|frame)$/ ) { - push @value, [$name,"Information only available for LPAR/CEC/BPA/Frame",RC_ERROR]; - next; + while (my ($name, $d) = each(%$h)) { + if (@$d[4] !~ /^(fsp|bpa|lpar|cec|frame)$/) { + push @value, [ $name, "Information only available for LPAR/CEC/BPA/Frame", RC_ERROR ]; + next; } - + ############### #If $name is a Lpar, the flag will be changed from "lpar" to "fsp" ####################### - if ( @$d[4] =~ /^lpar$/ || @$d[4] =~ /^cec$/ ) { - @$d[4] = "fsp"; - $lflag = 1; + if (@$d[4] =~ /^lpar$/ || @$d[4] =~ /^cec$/) { + @$d[4] = "fsp"; + $lflag = 1; + #push (@value, [$hmc,"$name is a Lpar on MTMS $mtms", 1]); } - if( @$d[4] eq "fsp" ) { + if (@$d[4] eq "fsp") { $component = "system"; } else { $component = "power"; - } - dpush(\@value, [$hmc,"$mtms:component:$component!"]); - - my $values = xCAT::PPCcli::lslic( $exp, $d, $timeout ); + } + dpush(\@value, [ $hmc, "$mtms:component:$component!" ]); + + my $values = xCAT::PPCcli::lslic($exp, $d, $timeout); my $Rc = shift(@$values); ##################################### # Return error - ##################################### - if ( $Rc != SUCCESS ) { - push @value, [$name,@$values[0],$Rc]; + ##################################### + if ($Rc != SUCCESS) { + push @value, [ $name, @$values[0], $Rc ]; next; } - - if ( @$values[0] =~ /ecnumber=(\w+)/ ) { + + if (@$values[0] =~ /ecnumber=(\w+)/) { $release_level = $1; - &dpush( \@value, [$hmc,"$mtms :release level:$1"]); + &dpush(\@value, [ $hmc, "$mtms :release level:$1" ]); } - - if ( @$values[0] =~ /activated_level=(\w+)/ ) { + + if (@$values[0] =~ /activated_level=(\w+)/) { $active_level = $1; - &dpush( \@value, [$hmc,"$mtms :activated level:$1"]); - } - my $msg; - my $flag = 0; - ($rpm_file, $xml_file, $upgrade_required,$msg, $flag) = &get_lic_filenames($mtms); - if( $flag == -1) { - push (@value, [$hmc,"$mtms: $msg"]); - push (@value, [$hmc,"Failed to upgrade the firmware of $mtms on $hmc"]); + &dpush(\@value, [ $hmc, "$mtms :activated level:$1" ]); + } + my $msg; + my $flag = 0; + ($rpm_file, $xml_file, $upgrade_required, $msg, $flag) = &get_lic_filenames($mtms); + if ($flag == -1) { + push(@value, [ $hmc, "$mtms: $msg" ]); + push(@value, [ $hmc, "Failed to upgrade the firmware of $mtms on $hmc" ]); return (\@value); } - dpush ( \@value, [$hmc, $msg]); + dpush(\@value, [ $hmc, $msg ]); # If we get to this point, the HMC has to attempt an update on the # managed system, so set the flag. @@ -729,98 +749,102 @@ sub rflash { #::work_flag = 1; # Collect the rpm and xml file names in a list so we can dcp then - # in one call. + # in one call. # - if( scalar( grep /$rpm_file/, @rpm_files ) == 0 ) { + if (scalar(grep /$rpm_file/, @rpm_files) == 0) { push @rpm_files, $rpm_file; push @xml_files, $xml_file; } - my ($volume,$directories,$file) = File::Spec->splitpath($rpm_file); + my ($volume, $directories, $file) = File::Spec->splitpath($rpm_file); + #push(@result,[$hmc, "Upgrade $mtms from release level:$release_level activated level:$active_level to $file successfully"]); - - #If mtms is a bpa, we should change the managed_system to a cec whose parent is a bpa. - if($component eq "power") { - ($managed_system, $msg)= &get_one_mtms($exp, $managed_system); - if($managed_system eq "") { - push(@value, [$hmc, $msg]); + + #If mtms is a bpa, we should change the managed_system to a cec whose parent is a bpa. + if ($component eq "power") { + ($managed_system, $msg) = &get_one_mtms($exp, $managed_system); + if ($managed_system eq "") { + push(@value, [ $hmc, $msg ]); return (\@value); - + } - dpush(\@value,[$hmc, $msg]); - $infor{$managed_system} = ["upgrade", $release_level, $active_level, $file, "power", $mtms]; + dpush(\@value, [ $hmc, $msg ]); + $infor{$managed_system} = [ "upgrade", $release_level, $active_level, $file, "power", $mtms ]; } else { - $infor{$managed_system} = ["upgrade", $release_level, $active_level, $file]; + $infor{$managed_system} = [ "upgrade", $release_level, $active_level, $file ]; } } - - my $rpm_dest = $::POWER_DEST_DIR."/".$dirlist[0]; + + my $rpm_dest = $::POWER_DEST_DIR . "/" . $dirlist[0]; + # The contents of the stanza file are slightly different depending # on the operation being performed. # # $managed_system = "9125-F2A*0262652"; - if( $upgrade_required ) { + if ($upgrade_required) { $stanza = "updlic::" . $managed_system . "::upgrade::::$rpm_dest"; } else { - $stanza = "updlic::" . $managed_system . "::activate::" . $component . "::" .$rpm_dest; + $stanza = "updlic::" . $managed_system . "::activate::" . $component . "::" . $rpm_dest; } - dpush(\@value,[$hmc, "Writing $stanza to file"]); + dpush(\@value, [ $hmc, "Writing $stanza to file" ]); print TMP "$stanza\n"; - @dirlist = (); + @dirlist = (); $rpm_file = (); $xml_file = (); - } + } } + # Close the file. dcp the stanza file, rpm update and xml file to the # target HMC # close TMP; - + ################################## # Get userid/password ################################## my $cred = $request->{$hmc}{cred}; - $user = @$cred[0]; - - dpush(\@value, [$hmc,"user: $user"]);; - #$password = @$cred[1] - + $user = @$cred[0]; - my $rpm_file_list = join(" ", @rpm_files); - my $xml_file_list = join(" ", @xml_files); + dpush(\@value, [ $hmc, "user: $user" ]); + + #$password = @$cred[1] + + + my $rpm_file_list = join(" ", @rpm_files); + my $xml_file_list = join(" ", @xml_files); ############################### #Prepare for "xdcp"-----runDcp_api is removed. ############################## - my $source = "$tmp_file $rpm_file_list $xml_file_list"; - my $target = "/tmp"; + my $source = "$tmp_file $rpm_file_list $xml_file_list"; + my $target = "/tmp"; my $current_userid = getpwuid($>); - - my $res = xCAT::Utils->runxcmd( { - command => ['xdcp'], - node => [$hmc], - arg => [ "-l", $user, $source, $target ], - env => ["DSH_FROM_USERID=$current_userid","DSH_TO_USERID=$user"], - }, - $subreq, 0, 1); - if ($::RUNCMD_RC ) { # error from dcp - my $rsp={}; - dpush(\@value, [$hmc,"invoking xdcp"]); + my $res = xCAT::Utils->runxcmd({ + command => ['xdcp'], + node => [$hmc], + arg => [ "-l", $user, $source, $target ], + env => [ "DSH_FROM_USERID=$current_userid", "DSH_TO_USERID=$user" ], + }, + $subreq, 0, 1); + + if ($::RUNCMD_RC) { # error from dcp + my $rsp = {}; + dpush(\@value, [ $hmc, "invoking xdcp" ]); $rsp->{data}->[0] = "Error from xdcp. Return Code = $::RUNCMD_RC"; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - push(@value,[$hmc,$rsp->{data}->[0]]); - push(@value,[$hmc,"Failed to copy $tmp_file $rpm_file_list $xml_file_list to $hmc"]); - push(@value,[$hmc,"Please check whether the HMC $hmc is configured to allow remote ssh automatic connections"]); - push (@value, [$hmc,"Failed to upgrade the firmware of $mtms_t on $hmc"]); - return(\@value); - } + push(@value, [ $hmc, $rsp->{data}->[0] ]); + push(@value, [ $hmc, "Failed to copy $tmp_file $rpm_file_list $xml_file_list to $hmc" ]); + push(@value, [ $hmc, "Please check whether the HMC $hmc is configured to allow remote ssh automatic connections" ]); + push(@value, [ $hmc, "Failed to upgrade the firmware of $mtms_t on $hmc" ]); + return (\@value); + } my $r = (); - foreach $r (@$res){ - push(@value, [$r]); + foreach $r (@$res) { + push(@value, [$r]); } - - - push(@value,[$hmc, "copy files to $hmc completely"]); + + + push(@value, [ $hmc, "copy files to $hmc completely" ]); ############################################### # Now that all the stanzas files have been built and copied to the HMCs, @@ -834,78 +858,81 @@ sub rflash { # }, # , $subreq, 0, 1); # - #$options{ 'user' } = $user; - #$options{ 'nodes' } = $hmc; + #$options{ 'user' } = $user; + #$options{ 'nodes' } = $hmc; #$options{ 'exit-status' } = 1; - #$options{ 'stream' } = 1; + #$options{ 'stream' } = 1; #$options{ 'command' } = "csmlicutil $tmp_file"; #$options{ 'command' } = "ls -al"; - + #@res = xCAT::DSHCLI->runDsh_api(\%options, 0); #my $Rc = pop(@res); #push(@value, [$Rc]); # The above code isn't supported. - + my $cmd_hmc = "csmlicutil $tmp_file"; + #my $cmd_hmc = "ls -al"; print "before runxcmd, current_userid = $current_userid; DSH_TO_USERID=$user \n"; - my $res = xCAT::Utils->runxcmd( { - command => ['xdsh'], - node => [$hmc], - arg => [ "-l", $user , $cmd_hmc ], - env => ["DSH_FROM_USERID=$current_userid","DSH_TO_USERID=$user"], - }, - $subreq, 0, 1); + my $res = xCAT::Utils->runxcmd({ + command => ['xdsh'], + node => [$hmc], + arg => [ "-l", $user, $cmd_hmc ], + env => [ "DSH_FROM_USERID=$current_userid", "DSH_TO_USERID=$user" ], + }, + $subreq, 0, 1); - if ($::RUNCMD_RC ) { # error from dsh - my $rsp={}; + if ($::RUNCMD_RC) { # error from dsh + my $rsp = {}; $rsp->{data}->[0] = "Error from xdsh. Return Code = $::RUNCMD_RC"; xCAT::MsgUtils->message("S", $rsp, $::CALLBACK, 1); - dpush(\@value,[$hmc,"failed to run xdsh"]); - push(@value,[$hmc,$rsp->{data}->[0]]); - push (@value, [$hmc,"Failed to upgrade the firmware of $mtms_t on $hmc"]); - return(\@value); + dpush(\@value, [ $hmc, "failed to run xdsh" ]); + push(@value, [ $hmc, $rsp->{data}->[0] ]); + push(@value, [ $hmc, "Failed to upgrade the firmware of $mtms_t on $hmc" ]); + return (\@value); } my $r = (); - foreach $r (@$res){ - push(@value, [$r]); + foreach $r (@$res) { + push(@value, [$r]); + #hmc1: mtms : LIC_RC = 0 -- successful #hmc1: mtms : LIC_RC = 8 -- failed #hmc1: mtms : LIC_RC = 12 -- failed - if(index($r, "LIC_RC") == -1) { - next; + if (index($r, "LIC_RC") == -1) { + next; } my @tmp1 = split(/:/, $r); $tmp1[1] =~ s/\s+//g; + # LIC_RC = 0 - # LIC_RC = 8 - $tmp1[2] =~ /LIC_RC\s=\s(\d*)/; - if($1 != 0) { # failed - my $tmp3 = $infor{$tmp1[1]}; - if($$tmp3[4] eq "power") { - $tmp1[1] = $$tmp3[5]; + # LIC_RC = 8 + $tmp1[2] =~ /LIC_RC\s=\s(\d*)/; + if ($1 != 0) { # failed + my $tmp3 = $infor{ $tmp1[1] }; + if ($$tmp3[4] eq "power") { + $tmp1[1] = $$tmp3[5]; } - if($$tmp3[0] eq "upgrade") { - push(@result,[$hmc, "failed to $$tmp3[0] $tmp1[1] from release level:$$tmp3[1] activated level:$$tmp3[2] to $$tmp3[3]"]); + if ($$tmp3[0] eq "upgrade") { + push(@result, [ $hmc, "failed to $$tmp3[0] $tmp1[1] from release level:$$tmp3[1] activated level:$$tmp3[2] to $$tmp3[3]" ]); } else { - push(@result,[$hmc, "failed to $$tmp3[0] the firmware for $tmp1[1]"] ); + push(@result, [ $hmc, "failed to $$tmp3[0] the firmware for $tmp1[1]" ]); } - } else { # successful - my $tmp3 = $infor{$tmp1[1]}; - if($$tmp3[4] eq "power") { - $tmp1[1] = $$tmp3[5]; + } else { # successful + my $tmp3 = $infor{ $tmp1[1] }; + if ($$tmp3[4] eq "power") { + $tmp1[1] = $$tmp3[5]; } - if($$tmp3[0] eq "upgrade") { - push(@result,[$hmc, "$$tmp3[0] $tmp1[1] from release level:$$tmp3[1] activated level:$$tmp3[2] to $$tmp3[3] successfully"]); + if ($$tmp3[0] eq "upgrade") { + push(@result, [ $hmc, "$$tmp3[0] $tmp1[1] from release level:$$tmp3[1] activated level:$$tmp3[2] to $$tmp3[3] successfully" ]); } else { - push(@result,[$hmc, "$$tmp3[0] the firmware for $tmp1[1] successfully"]); + push(@result, [ $hmc, "$$tmp3[0] the firmware for $tmp1[1] successfully" ]); } - } + } } push(@value, @result); - return (\@value); + return (\@value); } diff --git a/perl-xCAT/xCAT/PPCscan.pm b/perl-xCAT/xCAT/PPCscan.pm index d64f816e7..5a7f41f39 100644 --- a/perl-xCAT/xCAT/PPCscan.pm +++ b/perl-xCAT/xCAT/PPCscan.pm @@ -5,7 +5,7 @@ use strict; use Getopt::Long; use Socket; use XML::Simple; -$XML::Simple::PREFERRED_PARSER='XML::Parser'; +$XML::Simple::PREFERRED_PARSER = 'XML::Parser'; use xCAT::PPCcli qw(SUCCESS EXPECT_ERROR RC_ERROR NR_ERROR); use xCAT::PPCdb; use xCAT::GlobalDef; @@ -16,28 +16,28 @@ require xCAT::data::ibmhwtypes; ############################################## # Globals ############################################## -my @header = ( - ["type", "%-8s" ], - ["name", "placeholder" ], - ["id", "%-8s" ], - ["type-model", "%-12s" ], - ["serial-number", "%-15s" ], - ["side", "%-6s\n" ]); +my @header = ( + [ "type", "%-8s" ], + [ "name", "placeholder" ], + [ "id", "%-8s" ], + [ "type-model", "%-12s" ], + [ "serial-number", "%-15s" ], + [ "side", "%-6s\n" ]); my @attribs = qw(nodetype node id mtm serial side hcp pprofile parent groups mgt cons hwtype); my %globalnodetype = ( - fsp => $::NODETYPE_PPC, - bpa => $::NODETYPE_PPC, - cec => $::NODETYPE_PPC, - frame=> $::NODETYPE_PPC, - lpar =>"$::NODETYPE_PPC,$::NODETYPE_OSI" + fsp => $::NODETYPE_PPC, + bpa => $::NODETYPE_PPC, + cec => $::NODETYPE_PPC, + frame => $::NODETYPE_PPC, + lpar => "$::NODETYPE_PPC,$::NODETYPE_OSI" ); my %globalhwtype = ( - fsp => $::NODETYPE_FSP, - bpa => $::NODETYPE_BPA, - lpar => $::NODETYPE_LPAR, - cec => $::NODETYPE_CEC, - frame=> $::NODETYPE_FRAME, + fsp => $::NODETYPE_FSP, + bpa => $::NODETYPE_BPA, + lpar => $::NODETYPE_LPAR, + cec => $::NODETYPE_CEC, + frame => $::NODETYPE_FRAME, ); @@ -56,74 +56,74 @@ sub parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - $request->{method} = $cmd; - return( \%opt ); + if (!defined($args)) { + $request->{method} = $cmd; + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose u w x z) )){ - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose u w x z))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } ############################################# # Check for mutually-exclusive formatting ############################################# - if (( exists($opt{x}) + exists($opt{z})) > 1 ) { - return( usage() ); + if ((exists($opt{x}) + exists($opt{z})) > 1) { + return (usage()); } ############################################# # Check for mutually-exclusive flags ############################################# - if (( exists($opt{u}) + exists($opt{w})) > 1 ) { - return(usage( "Flag -u cannot be used with flag -w")); + if ((exists($opt{u}) + exists($opt{w})) > 1) { + return (usage("Flag -u cannot be used with flag -w")); } #################################### # No operands - add command name #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } ########################################################################## -# Returns short-hostname given an IP +# Returns short-hostname given an IP ########################################################################## sub getshorthost { my $ip = shift; my $host = xCAT::NetworkUtils->gethostname($ip); - if ( $host and !$! ) { + if ($host and !$!) { ############################## # Get short-hostname ############################## - if ( $host =~ /([^\.]+)\./ ) { - return($1); + if ($host =~ /([^\.]+)\./) { + return ($1); } } ################################## @@ -141,137 +141,137 @@ sub enumerate { my $exp = shift; my $hwtype = @$exp[2]; my $server = @$exp[3]; - my @values = (); + my @values = (); my %cage = (); my %hwconn = (); my $Rc; my $filter; ######################################### - # Get hardware control point info + # Get hardware control point info ######################################### { - my $hcp = xCAT::PPCcli::lshmc( $exp ); - $Rc = shift(@$hcp); + my $hcp = xCAT::PPCcli::lshmc($exp); + $Rc = shift(@$hcp); - ######################################### - # Return error - ######################################### - if ( $Rc != SUCCESS ) { - return( @$hcp[0] ); - } - ######################################### - # Success - ######################################### - my ($model,$serial) = split /,/, @$hcp[0]; - my $id = ""; - my $prof = ""; - my $ips = ""; - my $bpa = ""; - my $side = ""; + ######################################### + # Return error + ######################################### + if ($Rc != SUCCESS) { + return (@$hcp[0]); + } + ######################################### + # Success + ######################################### + my ($model, $serial) = split /,/, @$hcp[0]; + my $id = ""; + my $prof = ""; + my $ips = ""; + my $bpa = ""; + my $side = ""; - push @values, join( ",", - $hwtype,$server,$id,$model,$serial,$side,$server,$prof,$bpa,$ips ); + push @values, join(",", + $hwtype, $server, $id, $model, $serial, $side, $server, $prof, $bpa, $ips); } ######################################### # Save hardware connections ######################################### - if ( $hwtype ne "ivm" ) { #Not applicable for IVM + if ($hwtype ne "ivm") { #Not applicable for IVM $filter = "type_model_serial_num,ipaddr,sp,side"; - my $conns = xCAT::PPCcli::lssysconn( $exp, "alls", $filter ); + my $conns = xCAT::PPCcli::lssysconn($exp, "alls", $filter); $Rc = shift(@$conns); ######################################### # Return error ######################################### - if ( $Rc != SUCCESS ) { - return( @$conns[0] ); + if ($Rc != SUCCESS) { + return (@$conns[0]); } - foreach my $con ( @$conns ) { - my ($mtms,$ipaddr,$sp,$side) = split /,/,$con; + foreach my $con (@$conns) { + my ($mtms, $ipaddr, $sp, $side) = split /,/, $con; my $value = undef; - if ( $sp =~ /^primary$/ or $side =~ /^a$/ ) { + if ($sp =~ /^primary$/ or $side =~ /^a$/) { $value = "A"; - } elsif ($sp =~ /^secondary$/ or $side =~ /^b$/ ) { + } elsif ($sp =~ /^secondary$/ or $side =~ /^b$/) { $value = "B"; } $hwconn{$ipaddr} = "$mtms,$value"; } } - + ######################################### # Enumerate frames (IVM has no frame) ######################################### - if ( $hwtype ne "ivm" ) { - $filter = "type_model,serial_num,name,frame_num,ipaddr_a,ipaddr_b"; - my $frames = xCAT::PPCcli::lssyscfg( $exp, "bpas", $filter ); + if ($hwtype ne "ivm") { + $filter = "type_model,serial_num,name,frame_num,ipaddr_a,ipaddr_b"; + my $frames = xCAT::PPCcli::lssyscfg($exp, "bpas", $filter); $Rc = shift(@$frames); ##################################### - # Expect error + # Expect error ##################################### - if ( $Rc == EXPECT_ERROR ) { - return( @$frames[0] ); + if ($Rc == EXPECT_ERROR) { + return (@$frames[0]); } ##################################### - # CLI error + # CLI error ##################################### - if ( $Rc == RC_ERROR ) { - return( @$frames[0] ); + if ($Rc == RC_ERROR) { + return (@$frames[0]); } ##################################### - # If frames found, enumerate cages + # If frames found, enumerate cages ##################################### - if ( $Rc != NR_ERROR ) { + if ($Rc != NR_ERROR) { $filter = "cage_num,type_model_serial_num"; - foreach my $val ( @$frames ) { - my ($model,$serial) = split /,/, $val; + foreach my $val (@$frames) { + my ($model, $serial) = split /,/, $val; my $mtms = "$model*$serial"; - my $cages = xCAT::PPCcli::lssyscfg($exp,"cage",$mtms,$filter); + my $cages = xCAT::PPCcli::lssyscfg($exp, "cage", $mtms, $filter); $Rc = shift(@$cages); ############################# # Skip... - # Frame in bad state + # Frame in bad state ############################# - if ( $Rc != SUCCESS ) { + if ($Rc != SUCCESS) { push @values, "# $mtms: ERROR @$cages[0]"; next; } ############################# - # Success + # Success ############################# - foreach ( @$cages ) { - my ($cageid,$mtms) = split /,/; + foreach (@$cages) { + my ($cageid, $mtms) = split /,/; $cage{$mtms} = "$cageid,$val"; - } + } } } } ######################################### - # Enumerate CECs + # Enumerate CECs ######################################### - $filter = "name,type_model,serial_num,ipaddr"; - my $cecs = xCAT::PPCcli::lssyscfg( $exp, "fsps", $filter ); + $filter = "name,type_model,serial_num,ipaddr"; + my $cecs = xCAT::PPCcli::lssyscfg($exp, "fsps", $filter); $Rc = shift(@$cecs); ######################################### # Return error ######################################### - if ( $Rc != SUCCESS ) { - return( @$cecs[0] ); + if ($Rc != SUCCESS) { + return (@$cecs[0]); } - foreach ( @$cecs ) { + foreach (@$cecs) { ##################################### # Get CEC information ##################################### - my ($fsp,$model,$serial,$ips) = split /,/; + my ($fsp, $model, $serial, $ips) = split /,/; my $mtms = "$model*$serial"; my $cageid = ""; my $fname = ""; @@ -284,19 +284,19 @@ sub enumerate { ##################################### # Save frame information ##################################### - if ( defined($frame) ) { - my ($cage,$model,$serial,$name,$id,$ipa,$ipb) = split /,/, $frame; + if (defined($frame)) { + my ($cage, $model, $serial, $name, $id, $ipa, $ipb) = split /,/, $frame; my $prof = ""; - my $bpa = ""; - $cageid = $cage; - $fname = $name; + my $bpa = ""; + $cageid = $cage; + $fname = $name; ####################################### # Convert IP-A to short-hostname. # If fails, use user-defined FSP name ####################################### - my $host = getshorthost( $ipa ); - if ( defined($host) ) { + my $host = getshorthost($ipa); + if (defined($host)) { $fname = $host; } @@ -315,9 +315,9 @@ sub enumerate { # push @values, join( ",", # "bpa",$fname,$id,$model,$serial,"B",$server,$prof,$bpa,$ipb); #} - push @values, join( ",", - "frame",$fname,$id,$model,$serial,"",$server,$prof,$bpa,""); - + push @values, join(",", +"frame", $fname, $id, $model, $serial, "", $server, $prof, $bpa, ""); + } ##################################### # Save CEC information @@ -328,59 +328,59 @@ sub enumerate { # Convert IP to short-hostname. # If fails, use user-defined FSP name ####################################### - my $host = getshorthost( $ips ); - if ( defined($host) ) { + my $host = getshorthost($ips); + if (defined($host)) { $fsp = $host; } my $mtmss = $hwconn{$ips}; - if ( $hwtype ne "ivm" ) { #Not applicable for IVM - my ($mtms,$side) = split /,/, $mtmss; + if ($hwtype ne "ivm") { #Not applicable for IVM + my ($mtms, $side) = split /,/, $mtmss; } - push @values, join( ",", - "cec",$fsp,$cageid,$model,$serial,"",$server,$prof,$fname,"" ); + push @values, join(",", +"cec", $fsp, $cageid, $model, $serial, "", $server, $prof, $fname, ""); ##################################### - # Enumerate LPARs + # Enumerate LPARs ##################################### - $filter = "name,lpar_id,default_profile,curr_profile"; - my $lpars = xCAT::PPCcli::lssyscfg( $exp, "lpar", $mtms, $filter ); - $Rc = shift(@$lpars); + $filter = "name,lpar_id,default_profile,curr_profile"; + my $lpars = xCAT::PPCcli::lssyscfg($exp, "lpar", $mtms, $filter); + $Rc = shift(@$lpars); #################################### - # Expect error + # Expect error #################################### - if ( $Rc == EXPECT_ERROR ) { - return( @$lpars[0] ); + if ($Rc == EXPECT_ERROR) { + return (@$lpars[0]); } #################################### # Skip... # CEC could be "Incomplete" state #################################### - if ( $Rc == RC_ERROR ) { + if ($Rc == RC_ERROR) { push @values, "# $mtms: ERROR @$lpars[0]"; next; } #################################### - # No results found + # No results found #################################### - if ( $Rc == NR_ERROR ) { + if ($Rc == NR_ERROR) { next; } - foreach ( @$lpars ) { - my ($name,$lparid,$dprof,$curprof) = split /,/; + foreach (@$lpars) { + my ($name, $lparid, $dprof, $curprof) = split /,/; my $prof = (length($curprof) && ($curprof !~ /^none$/)) ? $curprof : $dprof; my $ips = ""; my $port = ""; - + ##################################### # Save LPAR information ##################################### - push @values, join( ",", - "lpar",$name,$lparid,$model,$serial,$port,$server,$prof,$fsp,$ips ); + push @values, join(",", +"lpar", $name, $lparid, $model, $serial, $port, $server, $prof, $fsp, $ips); } } - return( \@values ); + return (\@values); } @@ -390,19 +390,19 @@ sub enumerate { ########################################################################## sub format_output { - my $request = shift; - my $exp = shift; - my $values = shift; - my $opt = $request->{opt}; - my %output = (); - my $hwtype = @$exp[2]; + my $request = shift; + my $exp = shift; + my $values = shift; + my $opt = $request->{opt}; + my %output = (); + my $hwtype = @$exp[2]; my $max_length = 0; my $result; ########################################### # -w flag for write to xCat database ########################################### - if ( exists( $opt->{w} )) { + if (exists($opt->{w})) { my $server = @$exp[3]; my $uid = @$exp[4]; my $pw = @$exp[5]; @@ -410,20 +410,20 @@ sub format_output { ####################################### # Strip errors for results ####################################### - my @val = grep( !/^#.*: ERROR /, @$values ); - xCAT::PPCdb::add_ppc( $hwtype, \@val ,'','',"PPC"); + my @val = grep(!/^#.*: ERROR /, @$values); + xCAT::PPCdb::add_ppc($hwtype, \@val, '', '', "PPC"); } ########################################### # -u flag for write to xCat database ########################################### - if ( exists( $opt->{u} )) { + if (exists($opt->{u})) { ####################################### # Strip errors for results ####################################### - my @val = grep( !/^#.*: ERROR /, @$values ); - $values = xCAT::PPCdb::update_ppc( $hwtype, \@val ); - if ( exists( $opt->{x} ) or exists( $opt->{z} )) + my @val = grep(!/^#.*: ERROR /, @$values); + $values = xCAT::PPCdb::update_ppc($hwtype, \@val); + if (exists($opt->{x}) or exists($opt->{z})) { unshift @$values, "hmc"; } @@ -432,75 +432,75 @@ sub format_output { ########################################### # -x flag for xml format ########################################### - if ( exists( $opt->{x} )) { - $result .= format_xml( $hwtype, $values ); + if (exists($opt->{x})) { + $result .= format_xml($hwtype, $values); } ########################################### # -z flag for stanza format ########################################### - elsif ( exists( $opt->{z} )) { - $result .= format_stanza( $hwtype, $values ); + elsif (exists($opt->{z})) { + $result .= format_stanza($hwtype, $values); } else { - $result = sprintf( "#Updated following nodes:\n") if ( exists( $opt->{u})); + $result = sprintf("#Updated following nodes:\n") if (exists($opt->{u})); ####################################### # Get longest name for formatting ####################################### - my $nodehash; + my $nodehash; my @errmsg; - foreach ( @$values ) { + foreach (@$values) { ############################################## # Skip error message after saving it for last ############################################## - if ( /^#.*: ERROR / ) { + if (/^#.*: ERROR /) { push @errmsg, $_; next; } /([^\,]+),([^\,]+),/; - $nodehash->{$1.$2} = $_; - my $length = length( $2 ); + $nodehash->{ $1 . $2 } = $_; + my $length = length($2); $max_length = ($length > $max_length) ? $length : $max_length; } - my $format = sprintf( "%%-%ds", ($max_length + 2 )); + my $format = sprintf("%%-%ds", ($max_length + 2)); $header[1][1] = $format; ####################################### # Add header ####################################### - foreach ( @header ) { - $result .= sprintf( @$_[1], @$_[0] ); + foreach (@header) { + $result .= sprintf(@$_[1], @$_[0]); } ####################################### # Add node information ####################################### - foreach ( sort keys %$nodehash ) { + foreach (sort keys %$nodehash) { my @data = split /,/, $nodehash->{$_}; my $i = 0; - foreach ( @header ) { - my $d = $data[$i++]; + foreach (@header) { + my $d = $data[ $i++ ]; ############################### - # Use IPs instead of - # hardware control address + # Use IPs instead of + # hardware control address ############################### - if ( @$_[0] eq "address" ) { - if ( $data[0] !~ /^(hmc|ivm)$/ ) { - $d = $data[8]; + if (@$_[0] eq "address") { + if ($data[0] !~ /^(hmc|ivm)$/) { + $d = $data[8]; } } - $result .= sprintf( @$_[1], $d ); + $result .= sprintf(@$_[1], $d); } } ####################################### - # Add any error messages + # Add any error messages ####################################### - foreach ( @errmsg ) { - $result.= "\n$_"; + foreach (@errmsg) { + $result .= "\n$_"; } } $output{data} = [$result]; - return( [\%output] ); + return ([ \%output ]); } @@ -512,30 +512,30 @@ sub format_stanza { my $hwtype = shift; my $values = shift; - + my $result; my $nodehash; ##################################### - # Skip hardware control point + # Skip hardware control point ##################################### shift(@$values); - foreach ( @$values ) { - ################################### - # Skip error message - ################################### - if ( /^#.*: ERROR / ) { - next; - } - /[^\,]+,([^\,]+),/; - $nodehash->{$1} = $_; + foreach (@$values) { + ################################### + # Skip error message + ################################### + if (/^#.*: ERROR /) { + next; + } + /[^\,]+,([^\,]+),/; + $nodehash->{$1} = $_; } - foreach ( sort keys %$nodehash ) { + foreach (sort keys %$nodehash) { my @data = split /,/, $nodehash->{$_}; my $type = $data[0]; - my $i = 0; + my $i = 0; ################################# # Node attributes @@ -546,35 +546,36 @@ sub format_stanza { # Add each attribute ################################# my $mtm = undef; - foreach ( @attribs ) { - my $d = $data[$i++]; + foreach (@attribs) { + my $d = $data[ $i++ ]; - if ( /^node$/ ) { + if (/^node$/) { next; - } elsif ( /^nodetype$/ ) { + } elsif (/^nodetype$/) { $d = $globalnodetype{$type}; - } elsif ( /^hwtype$/ ) { + } elsif (/^hwtype$/) { $d = $globalhwtype{$type}; - } elsif ( /^groups$/ ) { + } elsif (/^groups$/) { next; + #$d = "$type,all"; - } elsif ( /^mgt$/ ) { + } elsif (/^mgt$/) { $d = $hwtype; - } elsif ( /^cons$/ ) { - if ( $type eq "lpar" ) { + } elsif (/^cons$/) { + if ($type eq "lpar") { $d = $hwtype; } else { $d = undef; } - - } elsif ( /^(mtm|serial)$/ ) { - if ( $type eq "lpar" ) { - $d = undef; + + } elsif (/^(mtm|serial)$/) { + if ($type eq "lpar") { + $d = undef; } elsif (/^mtm$/) { $mtm = $d; } } elsif (/^side$/) { - unless ( $type =~ /^fsp|bpa$/ ) { + unless ($type =~ /^fsp|bpa$/) { next; } } @@ -585,11 +586,11 @@ sub format_stanza { my $tmp_pre = xCAT::data::ibmhwtypes::parse_group($mtm); if (defined($tmp_pre)) { $tmp_groups .= ",$tmp_pre"; - } + } } $result .= "\tgroups=$tmp_groups\n"; } - return( $result ); + return ($result); } @@ -604,64 +605,65 @@ sub format_xml { my $nodehash; ##################################### - # Skip hardware control point + # Skip hardware control point ##################################### shift(@$values); - foreach ( @$values ) { - ################################### - # Skip error message - ################################### - if ( /^#.*: ERROR / ) { - next; - } - /[^\,]+,([^\,]+),/; - $nodehash->{$1} = $_; + foreach (@$values) { + ################################### + # Skip error message + ################################### + if (/^#.*: ERROR /) { + next; + } + /[^\,]+,([^\,]+),/; + $nodehash->{$1} = $_; } ##################################### # Create XML formatted attributes ##################################### - foreach ( sort keys %$nodehash ) { + foreach (sort keys %$nodehash) { my @data = split /,/, $nodehash->{$_}; my $type = $data[0]; - my $i = 0; + my $i = 0; ################################# # Initialize hash reference ################################# my $href = { - Node => { } + Node => {} }; ################################# - # Add each attribute + # Add each attribute ################################# - my $mtm = undef; - foreach ( @attribs ) { - my $d = $data[$i++]; + my $mtm = undef; + foreach (@attribs) { + my $d = $data[ $i++ ]; - if ( /^nodetype$/ ) { + if (/^nodetype$/) { $d = $globalnodetype{$type}; - } elsif ( /^hwtype$/ ) { + } elsif (/^hwtype$/) { $d = $globalhwtype{$type}; - } elsif ( /^groups$/ ) { + } elsif (/^groups$/) { next; + #$d = "$type,all"; - } elsif ( /^mgt$/ ) { + } elsif (/^mgt$/) { $d = $hwtype; - } elsif ( /^cons$/ ) { - if ( $type eq "lpar" ) { + } elsif (/^cons$/) { + if ($type eq "lpar") { $d = $hwtype; } else { $d = undef; } - } elsif ( /^(mtm|serial)$/ ) { - if ( $type eq "lpar" ) { + } elsif (/^(mtm|serial)$/) { + if ($type eq "lpar") { $d = undef; - } elsif (/^mtm$/){ + } elsif (/^mtm$/) { $mtm = $d; } } elsif (/^side$/) { - unless ( $type =~ /^fsp|bpa$/ ) { + unless ($type =~ /^fsp|bpa$/) { next; } } @@ -672,18 +674,18 @@ sub format_xml { my $tmp_pre = xCAT::data::ibmhwtypes::parse_group($mtm); if (defined($tmp_pre)) { $tmp_groups .= ",$tmp_pre"; - } + } } - $href->{Node}->{groups}=$tmp_groups; + $href->{Node}->{groups} = $tmp_groups; ################################# # XML encoding ################################# - $xml.= XMLout($href, - NoAttr => 1, - KeyAttr => [], - RootName => undef ); + $xml .= XMLout($href, + NoAttr => 1, + KeyAttr => [], + RootName => undef); } - return( $xml ); + return ($xml); } @@ -702,16 +704,16 @@ sub rscan { ################################### # Enumerate all the hardware ################################### - my $values = enumerate( $exp ); - if ( ref($values) ne 'ARRAY' ) { - return( [[$server,$values,1]] ); + my $values = enumerate($exp); + if (ref($values) ne 'ARRAY') { + return ([ [ $server, $values, 1 ] ]); } ################################### - # Success + # Success ################################### - my $result = format_output( $request, $exp, $values ); + my $result = format_output($request, $exp, $values); unshift @$result, "FORMATDATA6sK4ci"; - return( $result ); + return ($result); } diff --git a/perl-xCAT/xCAT/PPCvitals.pm b/perl-xCAT/xCAT/PPCvitals.pm index 375a48f0b..547f23fe6 100644 --- a/perl-xCAT/xCAT/PPCvitals.pm +++ b/perl-xCAT/xCAT/PPCvitals.pm @@ -23,43 +23,43 @@ sub parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($command); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Unsupported command #################################### - my ($cmd) = grep(/^$ARGV[0]$/, @rvitals ); - if ( !defined( $cmd )) { - return(usage( "Invalid command: $ARGV[0]" )); + my ($cmd) = grep(/^$ARGV[0]$/, @rvitals); + if (!defined($cmd)) { + return (usage("Invalid command: $ARGV[0]")); } - - if($ARGV[0] =~ /^rackenv$/) { - if($request->{hwtype} =~ /^hmc$/) { - return(usage( "Command $ARGV[0] is not valid when the nodes' hcp is hmc" )); + + if ($ARGV[0] =~ /^rackenv$/) { + if ($request->{hwtype} =~ /^hmc$/) { + return (usage("Command $ARGV[0] is not valid when the nodes' hcp is hmc")); } } @@ -67,14 +67,14 @@ sub parse_args { # Check for an extra argument #################################### shift @ARGV; - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### # Set method to invoke #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } @@ -87,24 +87,24 @@ sub enumerate_volt { my $d = shift; my $mtms = @$d[2]; - my $volt = xCAT::PPCcli::lshwinfo( $exp, "frame", $mtms ); - my $Rc = shift(@$volt); + my $volt = xCAT::PPCcli::lshwinfo($exp, "frame", $mtms); + my $Rc = shift(@$volt); #################################### # Return error #################################### - if ( $Rc != SUCCESS ) { - return( [RC_ERROR, @$volt[0]] ); + if ($Rc != SUCCESS) { + return ([ RC_ERROR, @$volt[0] ]); } #################################### - # Success - return voltages + # Success - return voltages #################################### - return( [SUCCESS, @$volt[0]] ); + return ([ SUCCESS, @$volt[0] ]); } ########################################################################## -# Returns cage temperatures +# Returns cage temperatures ########################################################################## sub enumerate_temp { @@ -116,23 +116,23 @@ sub enumerate_temp { # Get cage information for frame #################################### my $filter = "type_model_serial_num,temperature"; - my $cages = xCAT::PPCcli::lshwinfo( $exp, "sys", $frame, $filter ); - my $Rc = shift(@$cages); + my $cages = xCAT::PPCcli::lshwinfo($exp, "sys", $frame, $filter); + my $Rc = shift(@$cages); #################################### # Expect error #################################### - if ( $Rc == EXPECT_ERROR || $Rc == RC_ERROR ) { - return( [$Rc,@$cages[0]] ); + if ($Rc == EXPECT_ERROR || $Rc == RC_ERROR) { + return ([ $Rc, @$cages[0] ]); } #################################### # Save frame by CEC MTMS in cage #################################### - foreach ( @$cages ) { - my ($mtms,$temp) = split /,/; - $outhash{$mtms} = $temp; + foreach (@$cages) { + my ($mtms, $temp) = split /,/; + $outhash{$mtms} = $temp; } - return( [SUCCESS,\%outhash] ); + return ([ SUCCESS, \%outhash ]); } ########################################################################## @@ -140,30 +140,31 @@ sub enumerate_temp { ########################################################################## sub enumerate_lcds { - my $exp = shift; - my $d = shift; - my $mtms = @$d[2]; - my $Rc = undef; - my $value = undef; + my $exp = shift; + my $d = shift; + my $mtms = @$d[2]; + my $Rc = undef; + my $value = undef; my $nodetype = @$d[4]; - my $lpar_id = @$d[0]; - my @refcode = (); - + my $lpar_id = @$d[0]; + my @refcode = (); + my $values = xCAT::PPCcli::lsrefcode($exp, $nodetype, $mtms, $lpar_id); - foreach $value (@$values){ + foreach $value (@$values) { + #Return error $Rc = shift @$value; - if( @$value[0] =~ /refcode=(\w*)/){ + if (@$value[0] =~ /refcode=(\w*)/) { my $code = $1; - if ( ! $code) + if (!$code) { - push @refcode, [$Rc, "blank"]; + push @refcode, [ $Rc, "blank" ]; } else { - push @refcode, [$Rc, $code] ; + push @refcode, [ $Rc, $code ]; } - } + } } return \@refcode; @@ -171,7 +172,7 @@ sub enumerate_lcds { ########################################################################## -# Returns voltages/currents +# Returns voltages/currents ########################################################################## sub voltage { @@ -181,7 +182,7 @@ sub voltage { my $hwtype = @$exp[2]; my @result = (); my $text = "Frame Voltages: "; - my @prefix = ( + my @prefix = ( "Frame Voltage (Vab): %sV", "Frame Voltage (Vbc): %sV", "Frame Voltage (Vca): %sV", @@ -190,30 +191,30 @@ sub voltage { "Frame Current (Ic): %sA", ); - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { - ################################# - # No frame command on IVM + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { ################################# - if ( $hwtype eq "ivm" ) { - push @result, [$name,"$text Not available",1]; + # No frame command on IVM + ################################# + if ($hwtype eq "ivm") { + push @result, [ $name, "$text Not available", 1 ]; next; } - ################################# + ################################# # Voltages available in frame - ################################# - if ( @$d[4] ne "bpa" ) { - push @result, [$name,"$text Only available for BPA",0]; + ################################# + if (@$d[4] ne "bpa") { + push @result, [ $name, "$text Only available for BPA", 0 ]; next; } - my $volt = enumerate_volt( $exp, $d ); + my $volt = enumerate_volt($exp, $d); my $Rc = shift(@$volt); - ################################# - # Output error ################################# - if ( $Rc != SUCCESS ) { - push @result, [$name,"$text @$volt[0]",$Rc]; + # Output error + ################################# + if ($Rc != SUCCESS) { + push @result, [ $name, "$text @$volt[0]", $Rc ]; next; } ################################# @@ -222,13 +223,13 @@ sub voltage { my @values = split /,/, @$volt[0]; my $i = 0; - foreach ( @prefix ) { - my $value = sprintf($_, $values[$i++]); - push @result, [$name,$value,$Rc]; - } + foreach (@prefix) { + my $value = sprintf($_, $values[ $i++ ]); + push @result, [ $name, $value, $Rc ]; + } } } - return( \@result ); + return (\@result); } @@ -245,65 +246,65 @@ sub temp { my %frame = (); my $prefix = "System Temperature:"; - ######################################### + ######################################### # Group by frame - ######################################### - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($name,$d) = each(%$h) ) { + ######################################### + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { my $mtms = @$d[5]; ################################# - # No frame commands for IVM - ################################# - if ( $hwtype eq "ivm" ) { - push @result, [$name,"$prefix Not available (No BPA)",0]; + # No frame commands for IVM + ################################# + if ($hwtype eq "ivm") { + push @result, [ $name, "$prefix Not available (No BPA)", 0 ]; next; } - ################################# - # Temperatures not available - ################################# - if ( @$d[4] !~ /^(fsp|cec|lpar)$/ ) { + ################################# + # Temperatures not available + ################################# + if (@$d[4] !~ /^(fsp|cec|lpar)$/) { my $text = "$prefix Only available for CEC/LPAR"; - push @result, [$name,$text,0]; - next; - } - ################################# - # Error - No frame - ################################# - if ( $mtms eq "0" ) { - push @result, [$name,"$prefix Not available (No BPA)",0]; + push @result, [ $name, $text, 0 ]; next; } ################################# - # Save node - ################################# + # Error - No frame + ################################# + if ($mtms eq "0") { + push @result, [ $name, "$prefix Not available (No BPA)", 0 ]; + next; + } + ################################# + # Save node + ################################# $frame{$mtms}{$name} = $d; } } - while (my ($mtms,$h) = each(%frame) ) { - ################################# - # Get temperatures this frame - ################################# - my $temp = enumerate_temp( $exp, $mtms ); - my $Rc = shift(@$temp); + while (my ($mtms, $h) = each(%frame)) { + ################################# + # Get temperatures this frame + ################################# + my $temp = enumerate_temp($exp, $mtms); + my $Rc = shift(@$temp); my $data = @$temp[0]; - while (my ($name,$d) = each(%$h) ) { + while (my ($name, $d) = each(%$h)) { my $mtms = @$d[2]; ############################# # Output error ############################# - if ( $Rc != SUCCESS ) { - push @result, [$name,"$prefix $data",$Rc]; + if ($Rc != SUCCESS) { + push @result, [ $name, "$prefix $data", $Rc ]; next; } ############################# - # CEC not in frame + # CEC not in frame ############################# - if ( !exists( $data->{$mtms} )) { - push @result, [$name,"$prefix CEC '$mtms' not found",1]; + if (!exists($data->{$mtms})) { + push @result, [ $name, "$prefix CEC '$mtms' not found", 1 ]; next; } ############################# @@ -312,58 +313,59 @@ sub temp { my $cel = $data->{$mtms}; my $fah = ($cel * 1.8) + 32; my $value = "$prefix $cel C ($fah F)"; - push @result, [$name,$value,$Rc]; + push @result, [ $name, $value, $Rc ]; } } - return( \@result ); + return (\@result); } ########################################################################## -# Returns system power status (on or off) +# Returns system power status (on or off) ########################################################################## sub power { - return( xCAT::PPCpower::state(@_,"Current Power Status: ",1)); + return (xCAT::PPCpower::state(@_, "Current Power Status: ", 1)); } ########################################################################## -# Returns system state +# Returns system state ########################################################################## sub state { - return( xCAT::PPCpower::state(@_,"System State: ")); + return (xCAT::PPCpower::state(@_, "System State: ")); } ########################################################################### # Returns system LCD status (LCD1, LCD2) ########################################################################## sub lcds { - my $request = shift; - my $hash = shift; - my $exp = shift; - my $hwtype = @$exp[2]; - my @result = (); - my $text = "Current LCD:"; - my $prefix = "Current LCD%d: %s"; - my $rcode = undef; + my $request = shift; + my $hash = shift; + my $exp = shift; + my $hwtype = @$exp[2]; + my @result = (); + my $text = "Current LCD:"; + my $prefix = "Current LCD%d: %s"; + my $rcode = undef; my $refcodes = undef; - my $Rc = undef; - my $num = undef; - my $value = undef; + my $Rc = undef; + my $num = undef; + my $value = undef; + + while (my ($mtms, $h) = each(%$hash)) { + while (my ($name, $d) = each(%$h)) { - while (my ($mtms,$h) = each(%$hash) ) { - while(my ($name, $d) = each(%$h) ){ #Support HMC only - if($hwtype ne 'hmc'){ - push @result, [$name, "$text Not available(NO HMC)", 1]; + if ($hwtype ne 'hmc') { + push @result, [ $name, "$text Not available(NO HMC)", 1 ]; next; } $refcodes = enumerate_lcds($exp, $d); $num = 1; - foreach $rcode (@$refcodes){ + foreach $rcode (@$refcodes) { $Rc = shift(@$rcode); $value = sprintf($prefix, $num, @$rcode[0]); - push @result, [$name, $value, $Rc]; + push @result, [ $name, $value, $Rc ]; $num = $num + 1; - } + } } } return \@result; @@ -375,16 +377,16 @@ sub lcds { ########################################################################## sub all { - my @values = ( - @{temp(@_)}, - @{voltage(@_)}, - @{state(@_)}, - @{power(@_)}, - @{lcds(@_)}, - ); + my @values = ( + @{ temp(@_) }, + @{ voltage(@_) }, + @{ state(@_) }, + @{ power(@_) }, + @{ lcds(@_) }, + ); - my @sorted_values = sort {$a->[0] cmp $b->[0]} @values; - return( \@sorted_values ); + my @sorted_values = sort { $a->[0] cmp $b->[0] } @values; + return (\@sorted_values); } diff --git a/perl-xCAT/xCAT/PPCvm.pm b/perl-xCAT/xCAT/PPCvm.pm index d753a5efb..c8229d651 100644 --- a/perl-xCAT/xCAT/PPCvm.pm +++ b/perl-xCAT/xCAT/PPCvm.pm @@ -16,8 +16,8 @@ use xCAT::MsgUtils qw(verbose_message); my %method = ( mkvm => \&mkvm_parse_args, lsvm => \&lsvm_parse_args, - rmvm => \&rmvm_parse_args, - chvm => \&chvm_parse_args + rmvm => \&rmvm_parse_args, + chvm => \&chvm_parse_args ); @@ -30,10 +30,10 @@ sub parse_args { my $cmd = $request->{command}; ############################### - # Invoke correct parse_args + # Invoke correct parse_args ############################### - my $result = $method{$cmd}( $request ); - return( $result ); + my $result = $method{$cmd}($request); + return ($result); } @@ -52,67 +52,67 @@ sub chvm_parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args ) && !defined( $request->{stdin} ) ) { + if (!defined($args) && !defined($request->{stdin})) { $request->{method} = $cmd; - return( usage() ); + return (usage()); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - if ($args) { @ARGV = @$args; } - else { @ARGV = (); } + if ($args) { @ARGV = @$args; } + else { @ARGV = (); } $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose p=s) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose p=s))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { + if (defined($ARGV[0])) { $opt{a} = [@ARGV]; - for my $attr ( @{$opt{a}}) + for my $attr (@{ $opt{a} }) { - if ( $attr !~ /(\w+)=(\w*)/) + if ($attr !~ /(\w+)=(\w*)/) { - return(usage( "Invalid argument or attribute: $attr" )); + return (usage("Invalid argument or attribute: $attr")); } } } #################################### - # Configuration file required + # Configuration file required #################################### - if ( !exists( $opt{p}) and !exists( $opt{a})) { - if ( !defined( $request->{stdin} )) { - return(usage( "Configuration file or attributes not specified" )); + if (!exists($opt{p}) and !exists($opt{a})) { + if (!defined($request->{stdin})) { + return (usage("Configuration file or attributes not specified")); } } #################################### # Both configuration file and # attributes are specified #################################### - if ( exists( $opt{p}) and exists( $opt{a})) { - return(usage( "Flag -p cannot be used together with attribute list")); + if (exists($opt{p}) and exists($opt{a})) { + return (usage("Flag -p cannot be used together with attribute list")); } #################################### - # No operands - add command name + # No operands - add command name #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } @@ -123,39 +123,39 @@ sub mkvm_parse_args { my $request = shift; - my %opt = (); - my $cmd = $request->{command}; - my $args = $request->{arg}; + my %opt = (); + my $cmd = $request->{command}; + my $args = $request->{arg}; ############################################# # Responds with usage statement ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { - return(usage( "No command specified" )); + if (!defined($args)) { + return (usage("No command specified")); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); - if ( !GetOptions( \%opt, qw(V|verbose ibautocfg ibacap=s i=s l=s c=s p=s full) )) { - return( usage() ); + Getopt::Long::Configure("bundling"); + if (!GetOptions(\%opt, qw(V|verbose ibautocfg ibacap=s i=s l=s c=s p=s full))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } ############################################################# # Check if only ibacap or ibautocfg specified with the other @@ -163,66 +163,66 @@ sub mkvm_parse_args { #if ( exists $opt{ibautocfg} and ! exists $opt{ibacap}) #{ # return(usage( "Missing option ibacap when ibautocfg is specified")); - #} + #} #elsif ( exists $opt{ibacap} and !exists $opt{ibautocfg}) #{ # return(usage( "Missing option ibautocfg when ibacap is specified")); - #} + #} #if ( $opt{ibacap} ne '1' and $opt{ibacap} ne '2' and $opt{ibacap} ne '3' and $opt{ibacap} ne '4') #{ # return(usage( "IB adapter virtual capability (option --ibacap) can only be number 1,2,3,4. \n\t 1 means 'Low utilization': 6.25% of HCA resources (1/16 of an HCA); \n\t 2 means 'Medium utilization': 12.5% of HCA resources (1/8 of an HCA); \n\t 3 means 'High utilization': 25% of HCA resources (1/4 of an HCA);\n\t 4 means 'Dedicated HCA': 100% of HCA resources (complete HCA).\n")); #} #################################### - # Check for non-zero integer + # Check for non-zero integer #################################### - if ( exists( $opt{i} )) { - if ( $opt{i} !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/ ) { - return(usage( "Invalid entry: $opt{i}" )); + if (exists($opt{i})) { + if ($opt{i} !~ /^([1-9]{1}|[1-9]{1}[0-9]+)$/) { + return (usage("Invalid entry: $opt{i}")); } } #################################### - # -i and -l not valid with -c + # -i and -l not valid with -c #################################### - if ( exists( $opt{c} ) ) { - if ( exists($opt{i}) or exists($opt{l}) or exists($opt{full})) { - return( usage() ); + if (exists($opt{c})) { + if (exists($opt{i}) or exists($opt{l}) or exists($opt{full})) { + return (usage()); } - #################################### - # -p is required for -c - #################################### - if ( !exists($opt{p})) { - return( usage() ); + #################################### + # -p is required for -c + #################################### + if (!exists($opt{p})) { + return (usage()); } } #################################### - # -i, -l and -c not valid with -f + # -i, -l and -c not valid with -f #################################### - elsif ( exists( $opt{full} ) ) { - if ( exists($opt{c}) or exists($opt{i}) or exists($opt{l})) { - return( usage() ); + elsif (exists($opt{full})) { + if (exists($opt{c}) or exists($opt{i}) or exists($opt{l})) { + return (usage()); } } #################################### # If -i and -l, both required #################################### - elsif ( !exists($opt{l}) or !exists($opt{i})) { - return( usage() ); + elsif (!exists($opt{l}) or !exists($opt{i})) { + return (usage()); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### # Expand -l noderange #################################### - if ( exists( $opt{l} )) { - my @noderange = xCAT::NodeRange::noderange( $opt{l},0 ); - if ( !@noderange ) { - return(usage( "Invalid noderange: '$opt{l}'" )); + if (exists($opt{l})) { + my @noderange = xCAT::NodeRange::noderange($opt{l}, 0); + if (!@noderange) { + return (usage("Invalid noderange: '$opt{l}'")); } @noderange = sort @noderange; $opt{lpar} = \@noderange; @@ -230,44 +230,44 @@ sub mkvm_parse_args { #################################### # Expand -c noderange #################################### - if ( exists( $opt{c} )) { - my @noderange = xCAT::NodeRange::noderange( $opt{c},0 ); - if ( !@noderange ) { - return(usage( "Invalid noderange: '$opt{l}'" )); + if (exists($opt{c})) { + my @noderange = xCAT::NodeRange::noderange($opt{c}, 0); + if (!@noderange) { + return (usage("Invalid noderange: '$opt{l}'")); } $opt{cec} = \@noderange; } ################################################# # Swap the targets to be processed in PPC.pm ################################################# - $opt{target} = [@{$request->{node}}]; - if ( $opt{l}) + $opt{target} = [ @{ $request->{node} } ]; + if ($opt{l}) { - $request->{node} = [@{$opt{lpar}}]; + $request->{node} = [ @{ $opt{lpar} } ]; $request->{noderange} = $opt{l}; } - if ( $opt{c}) + if ($opt{c}) { - $request->{node} = [@{$opt{cec}}]; + $request->{node} = [ @{ $opt{cec} } ]; $request->{noderange} = $opt{c}; - } + } ############################################# - # Only 1 node allowed + # Only 1 node allowed ############################################# - if ( !exists($opt{full}) && scalar( @{$request->{node}} ) > 1) { - return(usage( "Multiple source specified" )); - } + if (!exists($opt{full}) && scalar(@{ $request->{node} }) > 1) { + return (usage("Multiple source specified")); + } ################################################ # Check if the multiple nodes of the same CEC are specified with -f ################################################ - if ( (exists($opt{full})) && (scalar (@{$opt{target}}) > 1) ) { + if ((exists($opt{full})) && (scalar(@{ $opt{target} }) > 1)) { my $lparparent; - my $ppctab = xCAT::Table->new('ppc'); - foreach my $vnode (@{$opt{target}}) { - my $vcon = $ppctab->getNodeAttribs( $vnode, ('node','parent')); + my $ppctab = xCAT::Table->new('ppc'); + foreach my $vnode (@{ $opt{target} }) { + my $vcon = $ppctab->getNodeAttribs($vnode, ('node', 'parent')); if ($vcon and $vcon->{"node"} and $vcon->{"parent"}) { my $lparent = $vcon->{"parent"}; $lparparent->{$lparent}->{$vnode} = $vnode; @@ -275,59 +275,59 @@ sub mkvm_parse_args { } $ppctab->close; - my $cbmsg = "mkvm: multiple LPAR nodes which belong to the same CEC have been defined.\n"; - my $sameflag = 0; - foreach my $iparent (keys %$lparparent) { - if (scalar (keys %{$lparparent->{$iparent}}) > 1) { - $sameflag = 1; - $cbmsg = $cbmsg . $iparent . ":" . "\t"; - foreach my $inode (keys %{$lparparent->{$iparent}}) { - $cbmsg = $cbmsg . $inode . ","; - } - } - + my $cbmsg = "mkvm: multiple LPAR nodes which belong to the same CEC have been defined.\n"; + my $sameflag = 0; + foreach my $iparent (keys %$lparparent) { + if (scalar(keys %{ $lparparent->{$iparent} }) > 1) { + $sameflag = 1; + $cbmsg = $cbmsg . $iparent . ":" . "\t"; + foreach my $inode (keys %{ $lparparent->{$iparent} }) { + $cbmsg = $cbmsg . $inode . ","; + } + } + $cbmsg =~ s/,$/ /; $cbmsg = $cbmsg . "\n"; - } - if ($sameflag) { - return(usage( $cbmsg )); } - } + if ($sameflag) { + return (usage($cbmsg)); + } + } #################################### # Read and check profile #################################### - if ( exists( $opt{p})) { - $opt{p} = $request->{cwd}->[0] . '/' . $opt{p} if ( $opt{p} !~ /^\//); - return ( usage( "Profile $opt{p} cannot be found")) if ( ! -f $opt{p}); - open (PROFFILE, "<$opt{p}") or return ( usage( "Cannot open profile $opt{p}")); + if (exists($opt{p})) { + $opt{p} = $request->{cwd}->[0] . '/' . $opt{p} if ($opt{p} !~ /^\//); + return (usage("Profile $opt{p} cannot be found")) if (!-f $opt{p}); + open(PROFFILE, "<$opt{p}") or return (usage("Cannot open profile $opt{p}")); my @cfgdata = (); - while( ) + while () { chomp; /\w+/ or next; - if ( /name=/ and /lpar_name/ and /lpar_id/ and /lpar_env/) + if (/name=/ and /lpar_name/ and /lpar_id/ and /lpar_env/) { push @cfgdata, $_; } else { s/^[^,]*:\s*(name=.*)$/$1/; - return ( usage( "Invalid line in profile: $_")); + return (usage("Invalid line in profile: $_")); } } - return ( usage( "No valid line was found in profile $opt{p}.")) if ( scalar( @cfgdata) < 1); + return (usage("No valid line was found in profile $opt{p}.")) if (scalar(@cfgdata) < 1); - my @lpars = @{$opt{target}}; - my $min_lpar_num = scalar( @cfgdata); - if ( scalar(@cfgdata) > scalar( @lpars)) + my @lpars = @{ $opt{target} }; + my $min_lpar_num = scalar(@cfgdata); + if (scalar(@cfgdata) > scalar(@lpars)) { xCAT::MsgUtils->message('W', "Warning: Lpar configuration number in profile is greater than lpars in command line. Only first " . scalar(@lpars) . " lpars will be created.\n"); - $min_lpar_num = scalar( @lpars); + $min_lpar_num = scalar(@lpars); } - elsif ( scalar(@cfgdata) < scalar( @lpars)) + elsif (scalar(@cfgdata) < scalar(@lpars)) { - my $lparlist = join ",", @lpars[0..($min_lpar_num-1)]; + my $lparlist = join ",", @lpars[ 0 .. ($min_lpar_num - 1) ]; xCAT::MsgUtils->message('W', "Warning: Lpar number in command line is greater than lpar configuration number in profile. Only lpars " . $lparlist . " will be created.\n"); } @@ -335,10 +335,10 @@ sub mkvm_parse_args { } #################################### - # No operands - add command name + # No operands - add command name #################################### $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } @@ -356,46 +356,46 @@ sub rmvm_parse_args { ############################################# # Responds with usage statement ############################################# - local *usage = sub { + local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose service r) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose service r))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # No operands - add command name + # No operands - add command name #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } @@ -414,90 +414,90 @@ sub lsvm_parse_args { ############################################# local *usage = sub { my $usage_string = xCAT::Usage->getUsage($cmd); - return( [ $_[0], $usage_string] ); + return ([ $_[0], $usage_string ]); }; ############################################# # Process command-line arguments ############################################# - if ( !defined( $args )) { + if (!defined($args)) { $request->{method} = $cmd; - return( \%opt ); + return (\%opt); } ############################################# # Checks case in GetOptions, allows opts # to be grouped (e.g. -vx), and terminates # at the first unrecognized option. ############################################# - @ARGV = @$args; + @ARGV = @$args; $Getopt::Long::ignorecase = 0; - Getopt::Long::Configure( "bundling" ); + Getopt::Long::Configure("bundling"); - if ( !GetOptions( \%opt, qw(V|verbose a|all) )) { - return( usage() ); + if (!GetOptions(\%opt, qw(V|verbose a|all))) { + return (usage()); } #################################### # Check for "-" with no option #################################### - if ( grep(/^-$/, @ARGV )) { - return(usage( "Missing option: -" )); + if (grep(/^-$/, @ARGV)) { + return (usage("Missing option: -")); } #################################### # Check for an extra argument #################################### - if ( defined( $ARGV[0] )) { - return(usage( "Invalid Argument: $ARGV[0]" )); + if (defined($ARGV[0])) { + return (usage("Invalid Argument: $ARGV[0]")); } #################################### - # No operands - add command name + # No operands - add command name #################################### - $request->{method} = $cmd; - return( \%opt ); + $request->{method} = $cmd; + return (\%opt); } ########################################################################## -# Clones all the LPARs from one CEC to another (must be on same HMC) +# Clones all the LPARs from one CEC to another (must be on same HMC) ########################################################################## sub clone { - my $request = shift; - my $exp = shift; - my $targets = shift; - my $profile = shift; - my $destd = shift; - my $destname= shift; - my $hwtype = @$exp[2]; - my $server = @$exp[3]; - my @values = (); - my @lpars = @$targets; + my $request = shift; + my $exp = shift; + my $targets = shift; + my $profile = shift; + my $destd = shift; + my $destname = shift; + my $hwtype = @$exp[2]; + my $server = @$exp[3]; + my @values = (); + my @lpars = @$targets; my $destcec; - my $opt = $request->{opt}; + my $opt = $request->{opt}; - ##################################### - # Always one source CEC specified - ##################################### + ##################################### + # Always one source CEC specified + ##################################### my $lparid = @$destd[0]; my $mtms = @$destd[2]; my $type = @$destd[4]; ##################################### - # Not supported on IVM + # Not supported on IVM ##################################### - if ( $hwtype eq "ivm" ) { - return( [[RC_ERROR,"Not supported for IVM"]] ); + if ($hwtype eq "ivm") { + return ([ [ RC_ERROR, "Not supported for IVM" ] ]); } ##################################### - # Source must be CEC + # Source must be CEC ##################################### #if ( $type ne "fsp" ) { - unless ( $type =~ /^(cec|fsp)$/) { - return( [[RC_ERROR,"Node must be an FSP"]] ); + unless ($type =~ /^(cec|fsp)$/) { + return ([ [ RC_ERROR, "Node must be an FSP" ] ]); } ##################################### # Attributes not found ##################################### - if ( !$mtms) { - return( [[RC_ERROR,"Cannot found serial and mtm for $destname"]] ); + if (!$mtms) { + return ([ [ RC_ERROR, "Cannot found serial and mtm for $destname" ] ]); } ##################################### @@ -505,53 +505,53 @@ sub clone { ##################################### my $filter = "type_model,serial_num"; xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg fsps.filter:'$filter'."); - my $cecs = xCAT::PPCcli::lssyscfg( $exp, "fsps", $filter ); + my $cecs = xCAT::PPCcli::lssyscfg($exp, "fsps", $filter); my $Rc = shift(@$cecs); ##################################### # Return error ##################################### - if ( $Rc != SUCCESS ) { - return( [[$Rc, @$cecs[0]]] ); + if ($Rc != SUCCESS) { + return ([ [ $Rc, @$cecs[0] ] ]); } ##################################### # Get HCA info ##################################### - my $unassigned_iba = undef; + my $unassigned_iba = undef; my $iba_replace_pair = undef; - if ( exists $opt->{ibautocfg}) + if (exists $opt->{ibautocfg}) { - $unassigned_iba = get_unassigned_iba( $exp, $mtms, $opt->{ibacap}); + $unassigned_iba = get_unassigned_iba($exp, $mtms, $opt->{ibacap}); } else { - $unassigned_iba = get_unassigned_iba( $exp, $mtms, undef); - $iba_replace_pair = get_iba_replace_pair( $unassigned_iba, $profile); + $unassigned_iba = get_unassigned_iba($exp, $mtms, undef); + $iba_replace_pair = get_iba_replace_pair($unassigned_iba, $profile); } ##################################### - # Find source/dest CEC + # Find source/dest CEC ##################################### - foreach ( @$cecs ) { + foreach (@$cecs) { s/(.*),(.*)/$1*$2/; - if ( $_ eq $mtms ) { + if ($_ eq $mtms) { $destcec = $_; } } ##################################### # Destination CEC not found ##################################### - if ( !defined( $destcec )) { - return([[RC_ERROR,"Destination CEC '$destname' not found on '$server'"]]); + if (!defined($destcec)) { + return ([ [ RC_ERROR, "Destination CEC '$destname' not found on '$server'" ] ]); } ##################################### # Modify read back profile ##################################### - my $min_lpar_num = scalar(@$profile) < scalar(@$targets) ? scalar(@$profile) : scalar(@$targets) ; + my $min_lpar_num = scalar(@$profile) < scalar(@$targets) ? scalar(@$profile) : scalar(@$targets); my $i; - for ($i = 0; $i < $min_lpar_num; $i++) + for ($i = 0 ; $i < $min_lpar_num ; $i++) { my $cfg = $profile->[$i]; $cfg =~ s/^[^,]*:\s*(name=.*)$/$1/; @@ -560,20 +560,20 @@ sub clone { $cfg =~ s/\blpar_name=([^,]+|$)/name=$targets->[$i]/; - $cfg = strip_profile( $cfg, $hwtype); + $cfg = strip_profile($cfg, $hwtype); $cfg =~ /lpar_id=([^,]+)/; $lparid = $1; if (exists $opt->{ibautocfg}) { - $cfg = hcaautoconf( $cfg, $unassigned_iba); - } + $cfg = hcaautoconf($cfg, $unassigned_iba); + } else { - $cfg = hcasubst( $cfg, $iba_replace_pair); + $cfg = hcasubst($cfg, $iba_replace_pair); } ################################# - # Create new LPAR + # Create new LPAR ################################# my @temp = @$destd; $temp[0] = $lparid; @@ -581,155 +581,155 @@ sub clone { $temp[4] = 'lpar'; xCAT::MsgUtils->verbose_message($request, "$request->{command} :mksyscfg lpar.cfg:'$cfg'."); - my $result = xCAT::PPCcli::mksyscfg( $exp, "lpar", \@temp, $cfg ); + my $result = xCAT::PPCcli::mksyscfg($exp, "lpar", \@temp, $cfg); $Rc = shift(@$result); ################################# - # Success - add LPAR to database + # Success - add LPAR to database ################################# - if ( $Rc == SUCCESS ) { - my $err = xCATdB( - "mkvm", $targets->[$i], $profile, $lparid, $destd, $hwtype, $targets->[$i], $destname ); + if ($Rc == SUCCESS) { + my $err = xCATdB( +"mkvm", $targets->[$i], $profile, $lparid, $destd, $hwtype, $targets->[$i], $destname); - if ( defined( $err )) { - push @values, [$err, RC_ERROR]; + if (defined($err)) { + push @values, [ $err, RC_ERROR ]; } next; } ################################# - # Error - Save error + # Error - Save error ################################# - push @values, [@$result[0], $Rc]; + push @values, [ @$result[0], $Rc ]; } - if ( !scalar(@values) ) { - return( [[SUCCESS,"Success"]]); - } - return( \@values ); + if (!scalar(@values)) { + return ([ [ SUCCESS, "Success" ] ]); + } + return (\@values); } - ########################################################################## - # Removes logical partitions - ########################################################################## +########################################################################## +# Removes logical partitions +########################################################################## sub remove { - + my $request = shift; my $hash = shift; my $exp = shift; my $opt = $request->{opt}; my @lpars = (); my @values = (); - + xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { + while (my ($mtms, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { my $lparid = @$d[0]; my $mtms = @$d[2]; my $type = @$d[4]; #################################### # Must be CEC or LPAR #################################### - if ( $type !~ /^(lpar|fsp|cec)$/ ) { - push @values, [$lpar, "Node must be LPAR or CEC", RC_ERROR]; + if ($type !~ /^(lpar|fsp|cec)$/) { + push @values, [ $lpar, "Node must be LPAR or CEC", RC_ERROR ]; next; - } + } #################################### # This is a single LPAR #################################### - if ( $type eq "lpar" ) { + if ($type eq "lpar") { $lpars[0] = "$lpar,$lparid"; } #################################### - # This is a CEC - remove all LPARs + # This is a CEC - remove all LPARs #################################### else { my $filter = "name,lpar_id"; xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg lpar.filter:'$filter'."); - my $result = xCAT::PPCcli::lssyscfg( - $exp, - "lpar", - $mtms, - $filter ); + my $result = xCAT::PPCcli::lssyscfg( + $exp, + "lpar", + $mtms, + $filter); my $Rc = shift(@$result); ################################ # Expect error ################################ - if ( $Rc != SUCCESS ) { - push @values, [$lpar, @$result[0], $Rc]; + if ($Rc != SUCCESS) { + push @values, [ $lpar, @$result[0], $Rc ]; next; } ################################ - # Success - save LPARs + # Success - save LPARs ################################ - foreach ( @$result ) { - push @lpars, $_; + foreach (@$result) { + push @lpars, $_; } } #################################### # Remove the LPARs #################################### - foreach ( @lpars ) { - my $lparinfo = $_; # shift(@lpars); - my ($name,$id) = split /,/, $lparinfo; + foreach (@lpars) { + my $lparinfo = $_; # shift(@lpars); + my ($name, $id) = split /,/, $lparinfo; my $mtms = @$d[2]; - + if ($opt->{service}) { ############################################### # begin to retrieve the CEC's service lpar id - ############################################### + ############################################### xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg fsp.filter:'service_lpar_id'."); my $service_lparid = xCAT::PPCcli::lssyscfg( - $exp, - "fsp", - $mtms, - "service_lpar_id" ); + $exp, + "fsp", + $mtms, + "service_lpar_id"); my $Rc = shift(@$service_lparid); - + ##################################################### # Change the CEC's state to standby and set it's service lpar id to none ##################################################### - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { my $cfgdata = @$service_lparid[0]; - if ( ($id == $cfgdata) && ($cfgdata !~ /none/) ) { - $cfgdata = "service_lpar_id=none"; - xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg fsp.filter:'$cfgdata'."); - my $result = xCAT::PPCcli::chsyscfg( $exp, "fsp", $d, $cfgdata ); - $Rc = shift(@$result); - if ( $Rc != SUCCESS ) { - return( [[$lpar, @$service_lparid[0], $Rc]] ); - } + if (($id == $cfgdata) && ($cfgdata !~ /none/)) { + $cfgdata = "service_lpar_id=none"; + xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg fsp.filter:'$cfgdata'."); + my $result = xCAT::PPCcli::chsyscfg($exp, "fsp", $d, $cfgdata); + $Rc = shift(@$result); + if ($Rc != SUCCESS) { + return ([ [ $lpar, @$service_lparid[0], $Rc ] ]); } + } } } - - ################################ - # id profile mtms hcp type frame - ################################ - my @d = ( $id,0,$mtms,0,"lpar",0 ); + ################################ - # Send remove command + # id profile mtms hcp type frame + ################################ + my @d = ($id, 0, $mtms, 0, "lpar", 0); + ################################ + # Send remove command ################################ xCAT::MsgUtils->verbose_message($request, "$request->{command} :rmsyscfg lpar.id:$id."); - my $result = xCAT::PPCcli::rmsyscfg( $exp, \@d ); + my $result = xCAT::PPCcli::rmsyscfg($exp, \@d); my $Rc = shift(@$result); ################################ - # Remove LPAR from database + # Remove LPAR from database ################################ - if ( $Rc == SUCCESS and !exists( $opt->{r} ) ) { + if ($Rc == SUCCESS and !exists($opt->{r})) { xCAT::MsgUtils->verbose_message($request, "$request->{command} :remove lpar:$name from xCATdb."); - my $err = xCATdB( "rmvm", $name,"", $id,"", $type,"" , $lpar ); - if ( defined( $err )) { - push @values, [$lpar,$err,RC_ERROR]; + my $err = xCATdB("rmvm", $name, "", $id, "", $type, "", $lpar); + if (defined($err)) { + push @values, [ $lpar, $err, RC_ERROR ]; next; } } - push @values, [$lpar,@$result[0],$Rc]; + push @values, [ $lpar, @$result[0], $Rc ]; } } } xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); - return( \@values ); + return (\@values); } @@ -738,56 +738,56 @@ sub remove { ########################################################################## sub getprofile { - my $exp = shift; + my $exp = shift; my $name = shift; ############################### # Get all CECs ############################### - my $cecs = xCAT::PPCcli::lssyscfg( $exp, "fsps", "name" ); + my $cecs = xCAT::PPCcli::lssyscfg($exp, "fsps", "name"); ############################### # Return error ############################### - if ( @$cecs[0] != NR_ERROR ) { - if ( @$cecs[0] != SUCCESS ) { - return( $cecs ); + if (@$cecs[0] != NR_ERROR) { + if (@$cecs[0] != SUCCESS) { + return ($cecs); } my $Rc = shift(@$cecs); ########################### - # List profiles for CECs + # List profiles for CECs ########################### - foreach my $mtms ( @$cecs ) { + foreach my $mtms (@$cecs) { my $prof = xCAT::PPCcli::lssyscfg( - $exp, - "prof", - $mtms, - "profile_names=$name" ); + $exp, + "prof", + $mtms, + "profile_names=$name"); my $Rc = shift(@$prof); - if ( $Rc == SUCCESS ) { - return( [SUCCESS,$mtms,@$prof[0]] ); + if ($Rc == SUCCESS) { + return ([ SUCCESS, $mtms, @$prof[0] ]); } } } - return( [RC_ERROR,"The partition profile named '$name' was not found"] ); + return ([ RC_ERROR, "The partition profile named '$name' was not found" ]); } ########################################################################## -# Changes the configuration of an existing partition +# Changes the configuration of an existing partition ########################################################################## sub modify { my $request = shift; my $hash = shift; my $exp = shift; - return modify_by_prof( $request, $hash, $exp) if ( $request->{opt}->{p}); - return modify_by_attr( $request, $hash, $exp); + return modify_by_prof($request, $hash, $exp) if ($request->{opt}->{p}); + return modify_by_attr($request, $hash, $exp); } ########################################################################## -# Changes the configuration of an existing +# Changes the configuration of an existing # partition based on the attributes specified ########################################################################## sub modify_by_attr { @@ -795,18 +795,19 @@ sub modify_by_attr { my $hash = shift; my $exp = shift; my $hwtype = @$exp[2]; - my $name = @{$request->{node}}[0]; + my $name = @{ $request->{node} }[0]; my $opt = $request->{opt}; - my $attrstr= $opt->{a}; + my $attrstr = $opt->{a}; my @values; xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); + # attrstr will be in stdin for "cat vmdef | chvm nodename" if (!defined($attrstr) && defined($request->{stdin})) { my $tempattr = $request->{stdin}; $tempattr =~ s/\s+$//; $tempattr =~ s/^[\w]+: //; - my $newcfg = strip_profile( $tempattr, $hwtype ); + my $newcfg = strip_profile($tempattr, $hwtype); $newcfg =~ s/,*lpar_env=[^,]+|$//; $newcfg =~ s/,*all_resources=[^,]+|$//; $newcfg =~ s/,*lpar_name=[^,]+|$//; @@ -817,9 +818,9 @@ sub modify_by_attr { ########################################## my @newcfgarray; my $full_line; - while (my $line = shift( @cfgarray)) + while (my $line = shift(@cfgarray)) { - if ( !$full_line) + if (!$full_line) { $full_line = $line; } @@ -827,7 +828,7 @@ sub modify_by_attr { { $full_line = "$full_line,$line"; } - if ( $full_line =~ /^[^\"]/ or $full_line =~ /^\".+\"$/) + if ($full_line =~ /^[^\"]/ or $full_line =~ /^\".+\"$/) { $full_line =~ s/^\"(.+)\"$/$1/; push @newcfgarray, $full_line; @@ -837,78 +838,78 @@ sub modify_by_attr { } $attrstr = \@newcfgarray; } - if ( defined( $attrstr )) { + if (defined($attrstr)) { ################################### - # Get LPAR active profiles + # Get LPAR active profiles ################################### - while (my ($cec,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { ########################### # Get current profile ########################### xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg node.id:'@$d[0]'."); my $cfg_res = xCAT::PPCcli::lssyscfg( - $exp, - "node", - $cec, - 'curr_profile', - @$d[0]); + $exp, + "node", + $cec, + 'curr_profile', + @$d[0]); my $Rc = shift(@$cfg_res); - if ( $Rc != SUCCESS ) { - push @values, [$lpar, @$cfg_res[0], $Rc]; + if ($Rc != SUCCESS) { + push @values, [ $lpar, @$cfg_res[0], $Rc ]; next; } ############################################## # If there is no curr_profile, which means no - # profile has been applied yet (before first + # profile has been applied yet (before first # boot?), use the default_profile ############################################## - if ( (!@$cfg_res[0]) || (@$cfg_res[0] =~ /^none$/) ) + if ((!@$cfg_res[0]) || (@$cfg_res[0] =~ /^none$/)) { $cfg_res = xCAT::PPCcli::lssyscfg( - $exp, - "node", - $cec, - 'default_profile', - @$d[0]); + $exp, + "node", + $cec, + 'default_profile', + @$d[0]); $Rc = shift(@$cfg_res); - if ( $Rc != SUCCESS ) { - push @values, [$lpar, @$cfg_res[0], $Rc]; + if ($Rc != SUCCESS) { + push @values, [ $lpar, @$cfg_res[0], $Rc ]; next; } } - xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg prof.filter:'lpar_ids=@$d[0],profile_names=@$cfg_res[0]'."); + xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg prof.filter:'lpar_ids=@$d[0],profile_names=@$cfg_res[0]'."); my $prof = xCAT::PPCcli::lssyscfg( - $exp, - "prof", - $cec, - "lpar_ids=@$d[0],profile_names=@$cfg_res[0]" ); + $exp, + "prof", + $cec, + "lpar_ids=@$d[0],profile_names=@$cfg_res[0]"); $Rc = shift(@$prof); - if ( $Rc != SUCCESS ) { - push @values, [$lpar, @$prof[0], $Rc]; + if ($Rc != SUCCESS) { + push @values, [ $lpar, @$prof[0], $Rc ]; next; } my $cfgdata = @$prof[0]; ########################### # Modify profile ########################### - $cfgdata = strip_profile( $cfgdata, $hwtype ); + $cfgdata = strip_profile($cfgdata, $hwtype); $cfgdata =~ s/,*lpar_env=[^,]+|$//; $cfgdata =~ s/,*all_resources=[^,]+|$//; $cfgdata =~ s/,*lpar_name=[^,]+|$//; my $err_msg; - ($Rc, $err_msg, $cfgdata) = subst_profile( $cfgdata, $attrstr); - if ( $Rc != SUCCESS ) { - push @values, [$lpar, $err_msg, $Rc]; + ($Rc, $err_msg, $cfgdata) = subst_profile($cfgdata, $attrstr); + if ($Rc != SUCCESS) { + push @values, [ $lpar, $err_msg, $Rc ]; next; } xCAT::MsgUtils->verbose_message($request, "$request->{command} :chsyscfg prof.cfg:'$cfgdata'."); - my $result = xCAT::PPCcli::chsyscfg( $exp, "prof", $d, $cfgdata ); + my $result = xCAT::PPCcli::chsyscfg($exp, "prof", $d, $cfgdata); $Rc = shift(@$result); - push @values, [$lpar,@$result[0],$Rc]; + push @values, [ $lpar, @$result[0], $Rc ]; } } } @@ -921,7 +922,7 @@ sub modify_by_attr { ########################################################################## sub subst_profile { - my $cfgdata = shift; + my $cfgdata = shift; my $attrlist = shift; $cfgdata =~ s/\\\"/\"/g; @@ -931,9 +932,9 @@ sub subst_profile ########################################## my @newcfgarray; my $full_line; - while (my $line = shift( @cfgarray)) + while (my $line = shift(@cfgarray)) { - if ( !$full_line) + if (!$full_line) { $full_line = $line; } @@ -941,7 +942,7 @@ sub subst_profile { $full_line = "$full_line,$line"; } - if ( $full_line =~ /^[^\"]/ or $full_line =~ /^\".+\"$/) + if ($full_line =~ /^[^\"]/ or $full_line =~ /^\".+\"$/) { $full_line =~ s/^\"(.+)\"$/$1/; push @newcfgarray, $full_line; @@ -955,36 +956,37 @@ sub subst_profile ########################################## my @final_array; my @attrs = @$attrlist; - for my $cfgline ( @newcfgarray) + for my $cfgline (@newcfgarray) { - for ( my $i = 0; $i < scalar(@attrs); $i++ ) + for (my $i = 0 ; $i < scalar(@attrs) ; $i++) { my $av_pair = $attrs[$i]; - next if ( !$av_pair); + next if (!$av_pair); + #assuming there will not be too many attributes to be changed - my ($attr,$value) = $av_pair =~ /^\s*(\S+?)\s*=\s*(\S+)\s*$/; - if ( $cfgline =~ /^$attr=/) + my ($attr, $value) = $av_pair =~ /^\s*(\S+?)\s*=\s*(\S+)\s*$/; + if ($cfgline =~ /^$attr=/) { - if ( $cfgline =~ /lhea_logical_ports/) + if ($cfgline =~ /lhea_logical_ports/) { $cfgline = "$attr=\\\"\\\"$value\\\"\\\""; - } else + } else { $cfgline = "$attr=$value"; } - + delete $attrs[$i]; last; } - + } - if ( $cfgline =~ /,/) + if ($cfgline =~ /,/) { $cfgline = "\\\"$cfgline\\\""; } push @final_array, $cfgline; } - $cfgdata = join ',',@final_array; + $cfgdata = join ',', @final_array; ########################################## # Get not found attribute list @@ -992,7 +994,7 @@ sub subst_profile my %not_found = (); for (@attrs) { - if ( $_) + if ($_) { my ($a) = split /=/; $not_found{$a} = 1; @@ -1004,7 +1006,7 @@ sub subst_profile } ########################################################################## -# Changes the configuration of an existing +# Changes the configuration of an existing # partition based on the profile specified ########################################################################## sub modify_by_prof { @@ -1012,9 +1014,9 @@ sub modify_by_prof { my $hash = shift; my $exp = shift; my $hwtype = @$exp[2]; - my $name = @{$request->{node}}[0]; + my $name = @{ $request->{node} }[0]; my $opt = $request->{opt}; - my $cfgdata = $request->{stdin}; + my $cfgdata = $request->{stdin}; my $profile = $opt->{p}; my @values; @@ -1022,43 +1024,43 @@ sub modify_by_prof { ####################################### # -p flag, find profile specified ####################################### - if ( defined( $profile )) { - my $prof = getprofile( $exp, $profile ); + if (defined($profile)) { + my $prof = getprofile($exp, $profile); ################################### # Return error ################################### my $Rc = shift(@$prof); - if ( $Rc != SUCCESS ) { - return( [[$name,@$prof,RC_ERROR]] ); + if ($Rc != SUCCESS) { + return ([ [ $name, @$prof, RC_ERROR ] ]); } $cfgdata = @$prof[1]; my $mtms = @$prof[0]; ################################### - # Check if LPAR profile exists + # Check if LPAR profile exists ################################### - while (my ($cec,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { ########################### - # Get LPAR profiles + # Get LPAR profiles ########################### xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg prof.filter:'lpar_ids=@$d[0],profile_names=$profile'."); my $prof = xCAT::PPCcli::lssyscfg( - $exp, - "prof", - $cec, - "lpar_ids=@$d[0],profile_names=$profile" ); + $exp, + "prof", + $cec, + "lpar_ids=@$d[0],profile_names=$profile"); my $Rc = shift(@$prof); ########################### - # Already has that profile + # Already has that profile ########################### - if ( $Rc == SUCCESS ) { - push @values, [$lpar,"Success",$Rc]; - xCATdB( "chvm", $lpar, $profile ); - delete $h->{$lpar}; + if ($Rc == SUCCESS) { + push @values, [ $lpar, "Success", $Rc ]; + xCATdB("chvm", $lpar, $profile); + delete $h->{$lpar}; } } } @@ -1067,14 +1069,14 @@ sub modify_by_prof { # Remove "node: " in case the # configuration file was created as # the result of an "lsvm" command. - # "lpar9: name=lpar9, lpar_name=..." + # "lpar9: name=lpar9, lpar_name=..." ####################################### $cfgdata =~ s/^[\w]+: //; - if ( $cfgdata !~ /^name=/ ) { + if ($cfgdata !~ /^name=/) { my $text = "Invalid file format: must begin with 'name='"; - return( [[$name,$text,RC_ERROR]] ); + return ([ [ $name, $text, RC_ERROR ] ]); } - my $cfg = strip_profile( $cfgdata, $hwtype ); + my $cfg = strip_profile($cfgdata, $hwtype); $cfg =~ s/,*lpar_env=[^,]+|$//; $cfg =~ s/,*all_resources=[^,]+|$//; $cfg =~ s/,*lpar_name=[^,]+|$//; @@ -1082,62 +1084,62 @@ sub modify_by_prof { ####################################### # Send change profile command ####################################### - while (my ($cec,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { - + while (my ($cec, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { + ############################### - # Only valid for LPARs + # Only valid for LPARs ############################### - if ( @$d[4] ne "lpar" ) { - push @values, [$lpar,"Command not supported on '@$d[4]'",RC_ERROR]; + if (@$d[4] ne "lpar") { + push @values, [ $lpar, "Command not supported on '@$d[4]'", RC_ERROR ]; next; } ############################### - # Change LPAR Id + # Change LPAR Id ############################### - $cfg =~ s/lpar_id=[^,]+/lpar_id=@$d[0]/; + $cfg =~ s/lpar_id=[^,]+/lpar_id=@$d[0]/; ################################# # Modify SCSI/LHEA adapters ################################# - if ( exists( $opt->{p} )) { - if ( $cfg =~ /virtual_scsi_adapters=(\w+)/ ) { - if ( $1 !~ /^none$/i ) { - $cfg = scsi_adapter( $cfg ); + if (exists($opt->{p})) { + if ($cfg =~ /virtual_scsi_adapters=(\w+)/) { + if ($1 !~ /^none$/i) { + $cfg = scsi_adapter($cfg); } } - if ( $cfg =~ /lhea_logical_ports=(\w+)/ ) { - if ( $1 !~ /^none$/i ) { - $cfg = lhea_adapter( $cfg ); + if ($cfg =~ /lhea_logical_ports=(\w+)/) { + if ($1 !~ /^none$/i) { + $cfg = lhea_adapter($cfg); } } } ############################### - # Send command + # Send command ############################### - if ( defined( $profile )) { - xCAT::MsgUtils->verbose_message($request, "$request->{command} :mksyscfg prof.cfg:'$cfg'."); - my $result = xCAT::PPCcli::mksyscfg( $exp, "prof", $d, $cfg ); - my $Rc = shift(@$result); + if (defined($profile)) { + xCAT::MsgUtils->verbose_message($request, "$request->{command} :mksyscfg prof.cfg:'$cfg'."); + my $result = xCAT::PPCcli::mksyscfg($exp, "prof", $d, $cfg); + my $Rc = shift(@$result); - ############################ - # Update database - ############################ - if ( $Rc == SUCCESS ) { - xCATdB( "chvm", $lpar, $profile ); - } - push @values, [$lpar,@$result[0],$Rc]; + ############################ + # Update database + ############################ + if ($Rc == SUCCESS) { + xCATdB("chvm", $lpar, $profile); + } + push @values, [ $lpar, @$result[0], $Rc ]; } else { - xCAT::MsgUtils->verbose_message($request, "$request->{command} :chsyscfg prof.cfg:'$cfg'."); - my $result = xCAT::PPCcli::chsyscfg( $exp, "prof", $d, $cfg ); - my $Rc = shift(@$result); - push @values, [$lpar,@$result[0],$Rc]; + xCAT::MsgUtils->verbose_message($request, "$request->{command} :chsyscfg prof.cfg:'$cfg'."); + my $result = xCAT::PPCcli::chsyscfg($exp, "prof", $d, $cfg); + my $Rc = shift(@$result); + push @values, [ $lpar, @$result[0], $Rc ]; } } } xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); - return( \@values ); + return (\@values); } @@ -1156,8 +1158,8 @@ sub list { my $result; xCAT::MsgUtils->verbose_message($request, "$request->{command} START."); - while (my ($mtms,$h) = each(%$hash) ) { - while (my ($lpar,$d) = each(%$h) ) { + while (my ($mtms, $h) = each(%$hash)) { + while (my ($lpar, $d) = each(%$h)) { my $lparid = @$d[0]; my $mtms = @$d[2]; my $type = @$d[4]; @@ -1166,14 +1168,14 @@ sub list { #################################### # Must be CEC or LPAR #################################### - if ( $type !~ /^(lpar|fsp|cec)$/ ) { - $values->{$lpar} = [$lpar,"Node must be LPAR or CEC",RC_ERROR]; + if ($type !~ /^(lpar|fsp|cec)$/) { + $values->{$lpar} = [ $lpar, "Node must be LPAR or CEC", RC_ERROR ]; next; } #################################### # This is a single LPAR #################################### - if ( $type eq "lpar" ) { + if ($type eq "lpar") { $lpars[0] = "$lpar,$lparid"; } #################################### @@ -1183,48 +1185,48 @@ sub list { my $filter = "name,lpar_id"; xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg lpar.filter:'$filter'."); my $result = xCAT::PPCcli::lssyscfg( - $exp, - "lpar", - $mtms, - $filter ); + $exp, + "lpar", + $mtms, + $filter); my $Rc = shift(@$result); ################################ # Expect error ################################ - if ( $Rc != SUCCESS ) { - $values->{$lpar} = [$lpar,@$result[0], $Rc]; + if ($Rc != SUCCESS) { + $values->{$lpar} = [ $lpar, @$result[0], $Rc ]; next; } ################################ # Success - save LPARs ################################ - foreach ( @$result ) { + foreach (@$result) { push @lpars, $_; } } #################################### - # Get LPAR profile + # Get LPAR profile #################################### - foreach ( sort @lpars ) { - my ($name,$id) = split /,/; - + foreach (sort @lpars) { + my ($name, $id) = split /,/; + ################################# # Get source LPAR profile ################################# xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg prof.filter:'lpar_ids=$id'."); my $prof = xCAT::PPCcli::lssyscfg( - $exp, - "prof", - $mtms, - "lpar_ids=$id" ); + $exp, + "prof", + $mtms, + "lpar_ids=$id"); my $Rc = shift(@$prof); ################################# # Return error ################################# - if ( $Rc != SUCCESS ) { - $values->{$lpar} = [$lpar,@$prof[0], $Rc]; + if ($Rc != SUCCESS) { + $values->{$lpar} = [ $lpar, @$prof[0], $Rc ]; next; } ################################# @@ -1232,21 +1234,22 @@ sub list { # or all the profiles if option # -a|--all is assigned ################################# - if (exists( $args->{a} )) { + if (exists($args->{a})) { my $count = 0; foreach (@$prof) { $pprofile .= "@$prof[$count]\n\n"; $count++; } } else { + #$pprofile .= "@$prof[0]\n\n"; my $lparprof = xCAT::PPCcli::lssyscfg( - $exp, - "lpar2", - $mtms, - "lpar_ids=$id" ); + $exp, + "lpar2", + $mtms, + "lpar_ids=$id"); my $Rc = shift(@$lparprof); - if ( $Rc != SUCCESS ) { + if ($Rc != SUCCESS) { $pprofile .= "@$lparprof[0]\n\n"; } else { @$lparprof[0] =~ /curr_profile=(\w+)/; @@ -1254,20 +1257,20 @@ sub list { foreach my $pr (@$prof) { if ($pr =~ /name=$pname/) { $pprofile .= "$pr\n\n"; - } + } } - } + } } - } - $values->{$lpar} = [$lpar, $pprofile, SUCCESS]; + } + $values->{$lpar} = [ $lpar, $pprofile, SUCCESS ]; } } - foreach ( sort keys %$values ) { - push @value,$values->{$_}; + foreach (sort keys %$values) { + push @value, $values->{$_}; } xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); - return( \@value ); + return (\@value); } ########################################################################## # Increments hca adapter in partition profile @@ -1278,72 +1281,72 @@ sub hca_adapter { ######################################### # Increment HCA adapters if present - # "23001eff/2550010250300/2,23001eff/2550010250400/2" - # Increment the last 2 number of 2550010250300 and + # "23001eff/2550010250300/2,23001eff/2550010250400/2" + # Increment the last 2 number of 2550010250300 and # 2550010250400 in example above. ######################################### - if ( $cfgdata =~ /(\"*hca_adapters)/ ) { + if ($cfgdata =~ /(\"*hca_adapters)/) { ##################################### # If double-quoted, has comma- # seperated list of adapters ##################################### - my $delim = ( $1 =~ /^\"/ ) ? "\\\\\"" : ","; - $cfgdata =~ /hca_adapters=([^$delim]+)|$/; + my $delim = ($1 =~ /^\"/) ? "\\\\\"" : ","; + $cfgdata =~ /hca_adapters=([^$delim]+)|$/; my @hcas = split ",", $1; my $adapters = "hca_adapters="; - for my $hca ( @hcas) + for my $hca (@hcas) { my @hcainfo = split /\//, $hca; ###################################################### # split it to 2 part, only increase the last 2 number # otherwise it can overflow if change it to dec ###################################################### - my $portlen = length( $hcainfo[1]); - my $portprefix = substr($hcainfo[1],0,$portlen-2); - my $portpostfix = substr($hcainfo[1],$portlen-2); - my $portnum = hex $portpostfix; + my $portlen = length($hcainfo[1]); + my $portprefix = substr($hcainfo[1], 0, $portlen - 2); + my $portpostfix = substr($hcainfo[1], $portlen - 2); + my $portnum = hex $portpostfix; $portnum++; $portpostfix = sprintf '%x', $portnum; - if ( length( $portpostfix) == 1) + if (length($portpostfix) == 1) { $portpostfix = '0' . $portpostfix; - } + } $hcainfo[1] = $portprefix . $portpostfix; - - $adapters = $adapters . join( "/", @hcainfo ) . ','; + + $adapters = $adapters . join("/", @hcainfo) . ','; } $adapters =~ s/^(.*),$/$1/; $cfgdata =~ s/hca_adapters=[^$delim]+/$adapters/; } - return( $cfgdata ); + return ($cfgdata); } ########################################################################## # Get unassigned hca guid ########################################################################## sub get_unassigned_iba { - my $exp = shift; - my $mtms = shift; - my $ibacap = shift; + my $exp = shift; + my $mtms = shift; + my $ibacap = shift; my $max_ib_num = 0; - if ( ! $ibacap) + if (!$ibacap) { $ibacap = '1'; } - if ( $ibacap eq '1') + if ($ibacap eq '1') { $max_ib_num = 16; } - elsif ( $ibacap eq '2') + elsif ($ibacap eq '2') { $max_ib_num = 8; } - elsif ( $ibacap eq '3') + elsif ($ibacap eq '3') { $max_ib_num = 4; } - elsif ( $ibacap eq '4') + elsif ($ibacap eq '4') { $max_ib_num = 1; } @@ -1352,9 +1355,9 @@ sub get_unassigned_iba return undef; } - my $hwres = xCAT::PPCcli::lshwres( $exp, ['sys','hca', 'adapter_id:phys_loc:unassigned_guids'], $mtms); + my $hwres = xCAT::PPCcli::lshwres($exp, [ 'sys', 'hca', 'adapter_id:phys_loc:unassigned_guids' ], $mtms); my $Rc = shift(@$hwres); - if ( $Rc == SUCCESS) + if ($Rc == SUCCESS) { my @unassigned_ibas; my $ib_hash = {}; @@ -1366,33 +1369,33 @@ sub get_unassigned_iba my $adapter_id = $1; my $phys_loc = $2; my $unassigned_guids = $3; - if ( $phys_loc =~ /C65$/ or $phys_loc =~ /C66$/ or $phys_loc =~ /C7$/) + if ($phys_loc =~ /C65$/ or $phys_loc =~ /C66$/ or $phys_loc =~ /C7$/) { my @guids = split /,/, $unassigned_guids; - $max_ib_num = scalar( @guids) if (scalar( @guids) < $max_ib_num); - for (my $i = 0; $i < $max_ib_num; $i++) + $max_ib_num = scalar(@guids) if (scalar(@guids) < $max_ib_num); + for (my $i = 0 ; $i < $max_ib_num ; $i++) { my $guid = @guids[$i]; $guid =~ s/\s*(\S+)\s*/$1/; - unshift @{$ib_hash->{$phys_loc}->{$adapter_id}}, "$adapter_id/$guid/$ibacap"; + unshift @{ $ib_hash->{$phys_loc}->{$adapter_id} }, "$adapter_id/$guid/$ibacap"; } } } } - for my $loc ( sort keys %$ib_hash) + for my $loc (sort keys %$ib_hash) { my $min_guid_num = -1; - for my $id (keys %{$ib_hash->{$loc}}) + for my $id (keys %{ $ib_hash->{$loc} }) { - if ( $min_guid_num == -1 or $min_guid_num > scalar( @{$ib_hash->{$loc}->{$id}})) + if ($min_guid_num == -1 or $min_guid_num > scalar(@{ $ib_hash->{$loc}->{$id} })) { - $min_guid_num = scalar( @{$ib_hash->{$loc}->{$id}}); + $min_guid_num = scalar(@{ $ib_hash->{$loc}->{$id} }); } } - for (my $i = 0; $i < $min_guid_num; $i++) + for (my $i = 0 ; $i < $min_guid_num ; $i++) { my $unassigned_iba = undef; - for my $adp_id (sort keys %{$ib_hash->{$loc}}) + for my $adp_id (sort keys %{ $ib_hash->{$loc} }) { my $iba = $ib_hash->{$loc}->{$adp_id}->[$i]; $unassigned_iba .= ",$iba"; @@ -1426,15 +1429,15 @@ sub get_iba_replace_pair my @oldhca_prefixes; for my $cfg (@$profile) { - if ( $cfg =~ /(\"*hca_adapters)/ ) + if ($cfg =~ /(\"*hca_adapters)/) { - my $delim = ( $1 =~ /^\"/ ) ? "\\\\\"" : ","; - $cfg =~ /hca_adapters=([^$delim]+)|$/; + my $delim = ($1 =~ /^\"/) ? "\\\\\"" : ","; + $cfg =~ /hca_adapters=([^$delim]+)|$/; my $oldhca = $1; my @oldhcas = split /,/, $oldhca; for my $oldhca_entry (@oldhcas) { - if ( $oldhca_entry =~ /(.+\/.+)..\/\d+/) + if ($oldhca_entry =~ /(.+\/.+)..\/\d+/) { my $oldhca_prefix = $1; if (!grep /\Q$oldhca_prefix\E/, @oldhca_prefixes) @@ -1449,28 +1452,28 @@ sub get_iba_replace_pair # Get hca info from unasigned hca array ########################################### my @newhca_prefixes; - for my $newhca ( @$unassigned_iba) + for my $newhca (@$unassigned_iba) { my @newhcas = split /,/, $newhca; - for my $newhca_entry ( @newhcas) + for my $newhca_entry (@newhcas) { - if ( $newhca_entry =~ /(.+\/.+)..\/\d+/) + if ($newhca_entry =~ /(.+\/.+)..\/\d+/) { my $newhca_prefix = $1; - if (!grep /\Q$newhca_prefix\E/,@newhca_prefixes) + if (!grep /\Q$newhca_prefix\E/, @newhca_prefixes) { push @newhca_prefixes, $newhca_prefix; } } } } - ############################# + ############################# # Create replacement pair ############################# my %pair_hash; - for ( my $i = 0; $i < scalar @oldhca_prefixes; $i++) + for (my $i = 0 ; $i < scalar @oldhca_prefixes ; $i++) { - $pair_hash{ @oldhca_prefixes[$i]} = @newhca_prefixes[$i]; + $pair_hash{ @oldhca_prefixes[$i] } = @newhca_prefixes[$i]; } return \%pair_hash; @@ -1480,9 +1483,9 @@ sub get_iba_replace_pair ########################################################################## sub hcasubst { - my $cfgdata = shift; + my $cfgdata = shift; my $replace_hash = shift; - if ( $cfgdata =~ /(\"*hca_adapters)/ ) { + if ($cfgdata =~ /(\"*hca_adapters)/) { for my $oldhca_prefix (keys %$replace_hash) { $cfgdata =~ s/\Q$oldhca_prefix\E/$replace_hash->{$oldhca_prefix}/g; @@ -1495,42 +1498,42 @@ sub hcasubst ########################################################################## sub hcaautoconf { - my $cfgdata = shift; + my $cfgdata = shift; my $unassignedhca = shift; $unassignedhca = [] if (!$unassignedhca); - if ( $cfgdata =~ /(\"*hca_adapters)/ ) { - - ##################################### - # If double-quoted, has comma- - # seperated list of adapters - ##################################### - my $delim = ( $1 =~ /^\"/ ) ? "\\\\\"" : ","; - $cfgdata =~ /hca_adapters=([^$delim]+)|$/; + if ($cfgdata =~ /(\"*hca_adapters)/) { + + ##################################### + # If double-quoted, has comma- + # seperated list of adapters + ##################################### + my $delim = ($1 =~ /^\"/) ? "\\\\\"" : ","; + $cfgdata =~ /hca_adapters=([^$delim]+)|$/; my $oldhca = $1; my $newhca; $newhca = shift @$unassignedhca; - + my $adapters = undef; - if ( $newhca ) + if ($newhca) { - $adapters = "hca_adapters=$newhca"; + $adapters = "hca_adapters=$newhca"; } else { $adapters = "hca_adapters=none"; } - if ( $adapters =~ /,/ and $delim ne "\\\\\"") + if ($adapters =~ /,/ and $delim ne "\\\\\"") { $adapters = "\\\\\"" . $adapters . "\\\\\""; } $cfgdata =~ s/hca_adapters=[^$delim]+/$adapters/; } - return $cfgdata ; + return $cfgdata; } ########################################################################## -# Increments virtual lhea adapter in partition profile +# Increments virtual lhea adapter in partition profile ########################################################################## sub lhea_adapter { @@ -1538,41 +1541,42 @@ sub lhea_adapter { ######################################### # Increment LHEA adapters if present - # 23000000/2/1/7/none,23000008/2/1/4/none + # 23000000/2/1/7/none,23000008/2/1/4/none # Increment 7 and 4 in example above. ######################################### - if ( $cfgdata =~ /(\"*lhea_logical_ports)/ ) { + if ($cfgdata =~ /(\"*lhea_logical_ports)/) { ##################################### # If double-quoted, has comma- # seperated list of adapters ##################################### - #my $delim = ( $1 =~ /^\"/ ) ? "\\\\\"" : ","; + #my $delim = ( $1 =~ /^\"/ ) ? "\\\\\"" : ","; #$cfgdata =~ /lhea_logical_ports=([^$delim]+)|$/; - $cfgdata =~ /lhea_logical_ports=(.*)lhea_capabilities/; + $cfgdata =~ /lhea_logical_ports=(.*)lhea_capabilities/; my @lhea = split ",", $1; - foreach ( @lhea ) + foreach (@lhea) { - if ( /(\d+)\/(\d+)\/(\d+)\/(\d+)/) + if (/(\d+)\/(\d+)\/(\d+)\/(\d+)/) { my $id = $4; - if($id =~ /\d+/) + if ($id =~ /\d+/) { $id = $id + 1; } s/(\d+)\/(\d+)\/(\d+)\/(\d+)/$1\/$2\/$3\/$id/; - } - } - my $adapters = "lhea_logical_ports=".join( ",", @lhea ); + } + } + my $adapters = "lhea_logical_ports=" . join(",", @lhea); + #$cfgdata =~ s/lhea_logical_ports=[^$delim]+/$adapters/; - $cfgdata =~ s/lhea_logical_ports=(.*)lhea_capabilities/$adapters,lhea_capabilities/; + $cfgdata =~ s/lhea_logical_ports=(.*)lhea_capabilities/$adapters,lhea_capabilities/; } - return( $cfgdata ); + return ($cfgdata); } ########################################################################## -# Increments virtual scsi adapter in partition profile +# Increments virtual scsi adapter in partition profile ########################################################################## sub scsi_adapter { @@ -1582,34 +1586,34 @@ sub scsi_adapter { # Increment SCSI adapters if present # 15/server/6/1ae0-node1/11/1, # 14/server/5/1ae0-ms04/12/1, - # 20/server/any//any/1 + # 20/server/any//any/1 # Increment 11 and 12 in example above. ######################################### - if ( $cfgdata =~ /(\"*virtual_scsi_adapters)/ ) { + if ($cfgdata =~ /(\"*virtual_scsi_adapters)/) { ##################################### # If double-quoted, has comma- # seperated list of adapters ##################################### - my $delim = ( $1 =~ /^\"/ ) ? "\\\\\"" : ","; - $cfgdata =~ /virtual_scsi_adapters=([^$delim]+)|$/; - + my $delim = ($1 =~ /^\"/) ? "\\\\\"" : ","; + $cfgdata =~ /virtual_scsi_adapters=([^$delim]+)|$/; + my @scsi = split ",", $1; - foreach ( @scsi ) { - if ( /(\w+)\/(\w+)$/ ) { - my $id = ($1 =~ /(\d+)/) ? $1+1 : $1; + foreach (@scsi) { + if (/(\w+)\/(\w+)$/) { + my $id = ($1 =~ /(\d+)/) ? $1 + 1 : $1; s/(\w+)\/(\w+)$/$id\/$2/; - } + } } - my $adapters = "virtual_scsi_adapters=".join( ",", @scsi ); + my $adapters = "virtual_scsi_adapters=" . join(",", @scsi); $cfgdata =~ s/virtual_scsi_adapters=[^$delim]+/$adapters/; } - return( $cfgdata ); + return ($cfgdata); } ########################################################################## -# Creates/changes logical partitions +# Creates/changes logical partitions ########################################################################## sub create { @@ -1630,8 +1634,8 @@ sub create { ##################################### # Get source node information ##################################### - while ( my ($cec,$h) = each(%$hash) ) { - while ( my ($name,$data) = each(%$h) ) { + while (my ($cec, $h) = each(%$hash)) { + while (my ($name, $data) = each(%$h)) { $d = $data; $lparid = @$d[0]; $mtms = @$d[2]; @@ -1640,45 +1644,45 @@ sub create { } } ##################################### - # Must be CEC or LPAR + # Must be CEC or LPAR ##################################### - if ( $type !~ /^(lpar|fsp|cec)$/ ) { - return( [[$lpar,"Node must be LPAR or CEC",RC_ERROR]] ); + if ($type !~ /^(lpar|fsp|cec)$/) { + return ([ [ $lpar, "Node must be LPAR or CEC", RC_ERROR ] ]); } ##################################### - # Clone all the LPARs on CEC + # Clone all the LPARs on CEC ##################################### - if ( exists( $opt->{c} )) { - my $result = clone( $request, - $exp, - $opt->{target}, - $opt->{profile}, - $d, - $request->{node}->[0] - ); - foreach ( @$result ) { + if (exists($opt->{c})) { + my $result = clone($request, + $exp, + $opt->{target}, + $opt->{profile}, + $d, + $request->{node}->[0] + ); + foreach (@$result) { my $Rc = shift(@$_); - push @values, [$opt->{c}, @$_[0], $Rc]; + push @values, [ $opt->{c}, @$_[0], $Rc ]; } - return( \@values ); + return (\@values); } ##################################### - # Get source LPAR profile + # Get source LPAR profile ##################################### xCAT::MsgUtils->verbose_message($request, "$request->{command} :lssyscfg prof.filter:'lpar_ids=$lparid'."); my $prof = xCAT::PPCcli::lssyscfg( - $exp, - "prof", - $mtms, - "lpar_ids=$lparid" ); + $exp, + "prof", + $mtms, + "lpar_ids=$lparid"); my $Rc = shift(@$prof); ##################################### # Return error ##################################### - if ( $Rc != SUCCESS ) { - return( [[$lpar, @$prof[0], $Rc]] ); - } + if ($Rc != SUCCESS) { + return ([ [ $lpar, @$prof[0], $Rc ] ]); + } ##################################### # Get source node pprofile attribute ##################################### @@ -1688,25 +1692,25 @@ sub create { # Find pprofile on source node ##################################### my ($prof) = grep /^name=$pprofile\,/, @$prof; - if ( !$prof ) { - return( [[$lpar, "'pprofile=$pprofile' not found on '$lpar'", RC_ERROR]] ); + if (!$prof) { + return ([ [ $lpar, "'pprofile=$pprofile' not found on '$lpar'", RC_ERROR ] ]); } ##################################### # Get command-line options ##################################### - my $id = $opt->{i}; - my $cfgdata = strip_profile( $prof, $hwtype ); - + my $id = $opt->{i}; + my $cfgdata = strip_profile($prof, $hwtype); + ##################################### # Set profile name for all LPARs ##################################### - if ( $hwtype eq "hmc" ) { + if ($hwtype eq "hmc") { $cfgdata =~ s/^name=([^,]+|$)/profile_name=$1/; $profile = $1; $cfgdata =~ s/lpar_name=/name=/; } - - foreach my $name ( @{$opt->{target}} ) { + + foreach my $name (@{ $opt->{target} }) { ################################# # Modify read-back profile. @@ -1720,56 +1724,56 @@ sub create { ################################# # Modify LHEA adapters ################################# - if ( $cfgdata =~ /lhea_logical_ports=(\w+)/ ) { - if ( $1 !~ /^none$/i ) { - $cfgdata = lhea_adapter( $cfgdata ); + if ($cfgdata =~ /lhea_logical_ports=(\w+)/) { + if ($1 !~ /^none$/i) { + $cfgdata = lhea_adapter($cfgdata); } } ################################# # Modify HCA adapters ################################# - if ( $cfgdata =~ /hca_adapters=(\w+)/ ) { - if ( $1 !~ /^none$/i ) { - $cfgdata = hca_adapter( $cfgdata ); + if ($cfgdata =~ /hca_adapters=(\w+)/) { + if ($1 !~ /^none$/i) { + $cfgdata = hca_adapter($cfgdata); } } ################################# # Modify SCSI adapters ################################# - if ( $cfgdata =~ /virtual_scsi_adapters=(\w+)/ ) { - if ( $1 !~ /^none$/i ) { - $cfgdata = scsi_adapter( $cfgdata ); + if ($cfgdata =~ /virtual_scsi_adapters=(\w+)/) { + if ($1 !~ /^none$/i) { + $cfgdata = scsi_adapter($cfgdata); } } ################################# - # Create new LPAR + # Create new LPAR ################################# xCAT::MsgUtils->verbose_message($request, "$request->{command} :mksyscfg lpar.cfg:'$cfgdata'."); - $result = xCAT::PPCcli::mksyscfg( $exp, "lpar", $d, $cfgdata ); + $result = xCAT::PPCcli::mksyscfg($exp, "lpar", $d, $cfgdata); $Rc = shift(@$result); ################################# - # Add new LPAR to database + # Add new LPAR to database ################################# - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { xCAT::MsgUtils->verbose_message($request, "$request->{command} :add lpar:$name from xCATdb."); - my $err = xCATdB( "mkvm", $name, $profile, $id, $d, $hwtype, $lpar); - if ( defined( $err )) { - push @values, [$name,$err,RC_ERROR]; + my $err = xCATdB("mkvm", $name, $profile, $id, $d, $hwtype, $lpar); + if (defined($err)) { + push @values, [ $name, $err, RC_ERROR ]; $id++; next; } } - push @values, [$name,@$result[0],$Rc]; + push @values, [ $name, @$result[0], $Rc ]; $id++; } xCAT::MsgUtils->verbose_message($request, "$request->{command} END."); - return( \@values ); + return (\@values); } ########################################################################## -# Strips attributes from profile not valid for creation +# Strips attributes from profile not valid for creation ########################################################################## sub strip_profile { @@ -1781,14 +1785,14 @@ sub strip_profile { # HMC mksyscfg man page for valid # attributes. ##################################### - if ( $hwtype eq "hmc" ) { + if ($hwtype eq "hmc") { $cfgdata =~ s/,*\"virtual_serial_adapters=[^\"]+\"//; $cfgdata =~ s/,*electronic_err_reporting=[^,]+|$//; $cfgdata =~ s/,*shared_proc_pool_id=[^,]+|$//; $cfgdata =~ s/,*lpar_proc_compat_mode=[^,]+|$//; $cfgdata =~ s/\"/\\"/g; $cfgdata =~ s/\n//g; - return( $cfgdata ); + return ($cfgdata); } ##################################### # Modify read-back profile. See @@ -1803,7 +1807,7 @@ sub strip_profile { $cfgdata =~ s/,*conn_monitoring=[^,]+|$//; $cfgdata =~ s/,*power_ctrl_lpar_ids=[^,]+|$//; $cfgdata =~ s/\"/\\"/g; - return( $cfgdata ); + return ($cfgdata); } @@ -1822,98 +1826,98 @@ sub xCATdB { my $parent = shift; ####################################### - # Remove entry + # Remove entry ####################################### - if ( $cmd eq "rmvm" ) { + if ($cmd eq "rmvm") { my $ppctab = xCAT::Table->new('ppc'); - unless ($ppctab) { # no ppc table - return( "Error opening 'ppc' database" ); + unless ($ppctab) { # no ppc table + return ("Error opening 'ppc' database"); } - my @nodes = $ppctab->getAllNodeAttribs(['node','id','parent']); + my @nodes = $ppctab->getAllNodeAttribs([ 'node', 'id', 'parent' ]); foreach my $node (@nodes) { my $type = xCAT::DBobjUtils->getnodetype($node->{node}); - if ( $type =~ /lpar/ and $lparid eq $node->{id} and $parent eq $node->{parent} ) { - return( xCAT::PPCdb::rm_ppc( $node->{node} )); + if ($type =~ /lpar/ and $lparid eq $node->{id} and $parent eq $node->{parent}) { + return (xCAT::PPCdb::rm_ppc($node->{node})); } } } ####################################### - # Change entry + # Change entry ####################################### - elsif ( $cmd eq "chvm" ) { - my $ppctab = xCAT::Table->new( "ppc", -create=>1, -autocommit=>1 ); + elsif ($cmd eq "chvm") { + my $ppctab = xCAT::Table->new("ppc", -create => 1, -autocommit => 1); ################################### # Error opening ppc database ################################### - if ( !defined( $ppctab )) { - return( "Error opening 'ppc' database" ); + if (!defined($ppctab)) { + return ("Error opening 'ppc' database"); } - $ppctab->setNodeAttribs( $name, {pprofile=>$profile} ); + $ppctab->setNodeAttribs($name, { pprofile => $profile }); } ####################################### - # Add entry + # Add entry ####################################### else { - if ( !defined( $profile )) { + if (!defined($profile)) { $profile = $name; } - my ($model,$serial) = split /\*/,@$d[2]; - my $server = @$d[3]; - my $fsp = @$d[2]; - - ################################### + my ($model, $serial) = split /\*/, @$d[2]; + my $server = @$d[3]; + my $fsp = @$d[2]; + + ################################### # Find FSP name in ppc database ################################### - my $tab = xCAT::Table->new( "ppc" ); + my $tab = xCAT::Table->new("ppc"); ################################### # Error opening ppc database ################################### - if ( !defined( $tab )) { - return( "Error opening 'ppc' database" ); + if (!defined($tab)) { + return ("Error opening 'ppc' database"); } ################################### # If there is no parent provided - # this lpar should be the cloned + # this lpar should be the cloned # in the same cec - # Otherwise it should be cloned + # Otherwise it should be cloned # between cecs ################################### - if ( ! $parent) + if (!$parent) { - my ($ent) = $tab->getNodeAttribs($lpar, ['parent'] ); + my ($ent) = $tab->getNodeAttribs($lpar, ['parent']); ################################### - # Node not found + # Node not found ################################### - if ( !defined( $ent )) { - return( "'$lpar' not found in 'ppc' database" ); + if (!defined($ent)) { + return ("'$lpar' not found in 'ppc' database"); } ################################### - # Attributes not found + # Attributes not found ################################### - if ( !exists( $ent->{parent} )) { - return( "'parent' attribute not found in 'ppc' database" ); + if (!exists($ent->{parent})) { + return ("'parent' attribute not found in 'ppc' database"); } $parent = $ent->{parent}; } - my $values = join( ",", - "lpar", - $name, - $lparid, - $model, - $serial, - "", - $server, - $profile, - $parent ); - - return( xCAT::PPCdb::add_ppc( $hwtype, [$values],'','',"PPC" )); + my $values = join(",", + "lpar", + $name, + $lparid, + $model, + $serial, + "", + $server, + $profile, + $parent); + + return (xCAT::PPCdb::add_ppc($hwtype, [$values], '', '', "PPC")); } return undef; } @@ -1942,154 +1946,156 @@ sub mkfulllpar { my $mtms; my $type; my $profile; - - my $ppctab = xCAT::Table->new('ppc'); + + my $ppctab = xCAT::Table->new('ppc'); ##################################### # Get source node information ##################################### - while ( my ($cec,$h) = each(%$hash) ) { - my ($name,$data) = each(%$h); - $d = $data; - $lparid = @$d[0]; - $mtms = @$d[2]; - $type = @$d[4]; - $lpar = $name; - ##################################### - # Must be CEC or LPAR - ##################################### - if ( $type !~ /^(lpar|fsp|cec)$/ ) { - return( [[$lpar,"Node must be LPAR or CEC",RC_ERROR]] ); - } - - my $ppctab = xCAT::Table->new('ppc'); + while (my ($cec, $h) = each(%$hash)) { + my ($name, $data) = each(%$h); + $d = $data; + $lparid = @$d[0]; + $mtms = @$d[2]; + $type = @$d[4]; + $lpar = $name; ##################################### - # Check if a existing with requested LPAR ID has existed + # Must be CEC or LPAR + ##################################### + if ($type !~ /^(lpar|fsp|cec)$/) { + return ([ [ $lpar, "Node must be LPAR or CEC", RC_ERROR ] ]); + } + + my $ppctab = xCAT::Table->new('ppc'); + ##################################### + # Check if a existing with requested LPAR ID has existed ##################################### my $value = xCAT::PPCcli::lssyscfg( - $exp, - "profs", - $mtms, - "all_resources", - "lpar_ids=$lparid" ); + $exp, + "profs", + $mtms, + "all_resources", + "lpar_ids=$lparid"); my $Rc = shift(@$value); ####################################### # make how to handle according to the result of lssyscfg ####################################### - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { + # close the DB handler of the ppc table $ppctab->close; - # change the lpar's attribute before removing it. + + # change the lpar's attribute before removing it. my $all_res_flag = @$value[0]; - if ( $all_res_flag != 1 ) { - return( [[$lpar,"The LPAR ID has been occupied",RC_ERROR]] ); + if ($all_res_flag != 1) { + return ([ [ $lpar, "The LPAR ID has been occupied", RC_ERROR ] ]); } else { - return( [[$lpar,"This full LPAR has been created",RC_ERROR]] ); + return ([ [ $lpar, "This full LPAR has been created", RC_ERROR ] ]); } } - + ################################# - # Create the new full LPAR's configure data + # Create the new full LPAR's configure data ################################# my ($lpar_id, $profname); - my $vcon = $ppctab->getAttribs($name, ('id','pprofile')); - if ($vcon) { - if ($vcon->{"id"}) { + my $vcon = $ppctab->getAttribs($name, ('id', 'pprofile')); + if ($vcon) { + if ($vcon->{"id"}) { $lpar_id = $vcon->{"id"}; - } else { + } else { $lpar_id = 1; - } + } - if ($vcon->{"pprofile"}) { + if ($vcon->{"pprofile"}) { $profname = $vcon->{"pprofile"}; - } else { + } else { $profname = $name; - } - } else { - $lpar_id = 1; - $profname = $name; - } - - my $cfgdata = "name=$name,profile_name=$profname,lpar_id=$lpar_id,lpar_env=aixlinux,all_resources=1,boot_mode=norm,conn_monitoring=0"; - + } + } else { + $lpar_id = 1; + $profname = $name; + } + + my $cfgdata = "name=$name,profile_name=$profname,lpar_id=$lpar_id,lpar_env=aixlinux,all_resources=1,boot_mode=norm,conn_monitoring=0"; + ################################# # Create a new full LPAR ################################# - $result = xCAT::PPCcli::mksyscfg( $exp, "lpar", $d, $cfgdata ); - $Rc = shift(@$result); + $result = xCAT::PPCcli::mksyscfg($exp, "lpar", $d, $cfgdata); + $Rc = shift(@$result); ########################################### # Set the CEC's service_lpar_id to the lpar_id of the full LPAR ########################################### - if ( $Rc == SUCCESS) { - $cfgdata = "service_lpar_id=$lpar_id"; - $result = xCAT::PPCcli::chsyscfg( $exp, "fsp", $d, $cfgdata ); - $Rc = shift(@$result); - if ( $Rc != SUCCESS ) { + if ($Rc == SUCCESS) { + $cfgdata = "service_lpar_id=$lpar_id"; + $result = xCAT::PPCcli::chsyscfg($exp, "fsp", $d, $cfgdata); + $Rc = shift(@$result); + if ($Rc != SUCCESS) { $ppctab->close; - return( [[$lpar, @$result[0], $Rc]] ); + return ([ [ $lpar, @$result[0], $Rc ] ]); } } - + ################################# - # Add a new full LPAR to database + # Add a new full LPAR to database ################################# - if ( $Rc == SUCCESS ) { + if ($Rc == SUCCESS) { $profile = $profname; my $id = $lpar_id; - my $err = xCATdB( "mkvm", $name, $profile, $id, $d, $hwtype, $lpar); - if ( defined( $err )) { - push @values, [$name,$err,RC_ERROR]; + my $err = xCATdB("mkvm", $name, $profile, $id, $d, $hwtype, $lpar); + if (defined($err)) { + push @values, [ $name, $err, RC_ERROR ]; next; } } - push @values, [$name,@$result[0],$Rc]; + push @values, [ $name, @$result[0], $Rc ]; } $ppctab->close; - return( \@values ); + return (\@values); } ########################################################################## -# Creates logical partitions +# Creates logical partitions ########################################################################## sub mkvm { my $request = $_[0]; my $opt = $request->{opt}; - + # decide if issuing mkvm with the option '-f'. # if yes, mklpar will be invoked to # create a full system partition for each CECs managed by the HMC. - if ( exists($opt->{full})) { - return( mkfulllpar(@_) ); - } - else { + if (exists($opt->{full})) { + return (mkfulllpar(@_)); + } + else { # if no, it will execute the original function. - return( create(@_) ); + return (create(@_)); } } ########################################################################## -# Change logical partition +# Change logical partition ########################################################################## sub chvm { - return( modify(@_) ); + return (modify(@_)); } ########################################################################## -# Removes logical partitions +# Removes logical partitions ########################################################################## -sub rmvm { - return( remove(@_) ); +sub rmvm { + return (remove(@_)); } ########################################################################## # Lists logical partition profile ########################################################################## sub lsvm { - return( list(@_) ); + return (list(@_)); } diff --git a/perl-xCAT/xCAT/ProfiledNodeUtils.pm b/perl-xCAT/xCAT/ProfiledNodeUtils.pm index bf8a88547..d65ea1cdd 100644 --- a/perl-xCAT/xCAT/ProfiledNodeUtils.pm +++ b/perl-xCAT/xCAT/ProfiledNodeUtils.pm @@ -38,32 +38,33 @@ This program module file, is a set of node management utilities for Profile base #------------------------------------------------------------------------------- sub get_allocable_staticips_innet { - my $class = shift; - my $netname = shift; + my $class = shift; + my $netname = shift; my $exclude_ips_ref = shift; my %iphash; my @allocableips; - foreach (@$exclude_ips_ref){ + foreach (@$exclude_ips_ref) { $iphash{$_} = 0; } my $networkstab = xCAT::Table->new('networks'); my $netentry = ($networkstab->getAllAttribsWhere("netname = '$netname'", 'ALL'))[0]; - my ($startip, $endip) = split('-', $netentry->{'staticrange'}); + my ($startip, $endip) = split('-', $netentry->{'staticrange'}); my $incremental = $netentry->{'staticrangeincrement'}; - my $netmask = $netentry->{'mask'}; - my $gateway = $netentry->{'gateway'}; + my $netmask = $netentry->{'mask'}; + my $gateway = $netentry->{'gateway'}; my $validipsref; - if ($incremental and $startip and $endip){ + if ($incremental and $startip and $endip) { $validipsref = xCAT::NetworkUtils->get_allips_in_range($startip, $endip, $incremental); } - + my $broadcastip = xCAT::NetworkUtils->getBroadcast($startip, $netmask); - foreach (@$validipsref){ + foreach (@$validipsref) { + #Remove ip which is broadcast ip, exclude ip, ips ended with 0, gateway ip - if (exists($iphash{$_}) or $_ eq $broadcastip or $_ eq $gateway - or $_ =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(0)$/){ + if (exists($iphash{$_}) or $_ eq $broadcastip or $_ eq $gateway + or $_ =~ /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(0)$/) { next; } push @allocableips, $_; @@ -115,11 +116,11 @@ sub split_hostname my $idx = index $format, "#$patt_char"; my @array_format = split(//, $format); - my $pos = $idx+2; - while ( $pos <= (scalar(@array_format) - 1)){ - if ($array_format[$pos] eq "$patt_char"){ + my $pos = $idx + 2; + while ($pos <= (scalar(@array_format) - 1)) { + if ($array_format[$pos] eq "$patt_char") { $pos++; - }else{ + } else { last; } } @@ -128,7 +129,7 @@ sub split_hostname my $prefix = ""; $prefix = substr $format, 0, $idx; my $appendix = ""; - if (($ridx + 1) != scalar(@array_format)){ + if (($ridx + 1) != scalar(@array_format)) { $appendix = substr $format, $ridx + 1; } return $prefix, $appendix, ($ridx - $idx); @@ -156,16 +157,16 @@ sub gen_numric_hostnames my @hostnames; my $cnt = 0; - if ($rank){ + if ($rank) { $cnt = $rank; - } - my $maxnum = 10 ** $len; - while($cnt < $maxnum) + } + my $maxnum = 10**$len; + while ($cnt < $maxnum) { my $fullnum = $maxnum + $cnt; - my $hostname = $prefix.(substr $fullnum, 1).$appendix; - push (@hostnames, $hostname); - if ($amount && (@hostnames == $amount)){ + my $hostname = $prefix . (substr $fullnum, 1) . $appendix; + push(@hostnames, $hostname); + if ($amount && (@hostnames == $amount)) { last; } $cnt++; @@ -187,38 +188,39 @@ sub gen_numric_hostnames =cut #------------------------------------------------------------------------------- -sub get_hostname_format_type{ - my ($class, $format) = @_; +sub get_hostname_format_type { + my ($class, $format) = @_; my $type; my ($prefix, $appendix, $rlen, $nlen); my $ridx = index $format, "#R"; my $nidx = index $format, "#N"; my $simpname = ""; - if ($ridx >= 0){ + if ($ridx >= 0) { ($prefix, $appendix, $rlen) = xCAT::ProfiledNodeUtils->split_hostname($format, 'R'); - $simpname = $prefix."0".$appendix; + $simpname = $prefix . "0" . $appendix; ($prefix, $appendix, $nlen) = xCAT::ProfiledNodeUtils->split_hostname($simpname, 'N'); - $simpname = $prefix."0".$appendix; - if ($rlen >= 10 || $nlen >= 10 || $nlen == 0){ + $simpname = $prefix . "0" . $appendix; + if ($rlen >= 10 || $nlen >= 10 || $nlen == 0) { $type = "unknown"; - } else{ + } else { $type = "rack"; } - } elsif ($nidx >= 0){ + } elsif ($nidx >= 0) { ($prefix, $appendix, $nlen) = xCAT::ProfiledNodeUtils->split_hostname($format, 'N'); - $simpname = $prefix."0".$appendix; - if ($nlen >= 10){ + $simpname = $prefix . "0" . $appendix; + if ($nlen >= 10) { $type = "unknown"; - } else{ + } else { $type = "numric"; } - } else{ + } else { $type = "unknown"; } + # validate whether hostname format includes other invalid characters. - if ($type ne "unknown"){ - if (! xCAT::NetworkUtils->isValidHostname($simpname)){ + if ($type ne "unknown") { + if (!xCAT::NetworkUtils->isValidHostname($simpname)) { $type = "unknown"; } } @@ -238,19 +240,19 @@ sub get_hostname_format_type{ =cut #------------------------------------------------------------------------------- -sub rackformat_to_numricformat{ +sub rackformat_to_numricformat { my ($class, $format, $rackname) = @_; my ($prefix, $appendix, $len) = xCAT::ProfiledNodeUtils->split_hostname($format, 'R'); - my %objhash = xCAT::DBobjUtils->getobjdefs({$rackname, "rack"}); + my %objhash = xCAT::DBobjUtils->getobjdefs({ $rackname, "rack" }); my $racknum = $objhash{$rackname}{"num"}; - my $maxnum = 10 ** $len; - if ($racknum >= $maxnum ){ + my $maxnum = 10**$len; + if ($racknum >= $maxnum) { return undef; } my $fullnum = $maxnum + $racknum; - return $prefix.(substr $fullnum, 1).$appendix; + return $prefix . (substr $fullnum, 1) . $appendix; } #------------------------------------------------------------------------------- @@ -272,106 +274,106 @@ sub rackformat_to_numricformat{ =cut #------------------------------------------------------------------------------- -sub get_nodes_nic_attrs{ +sub get_nodes_nic_attrs { my $class = shift; my $nodes = shift; - my $nicstab = xCAT::Table->new( 'nics'); - my $entry = $nicstab->getNodesAttribs($nodes, ['nictypes', 'nichostnamesuffixes', 'nichostnameprefixes', 'niccustomscripts', 'nicnetworks', 'nicips', 'nicextraparams']); + my $nicstab = xCAT::Table->new('nics'); + my $entry = $nicstab->getNodesAttribs($nodes, [ 'nictypes', 'nichostnamesuffixes', 'nichostnameprefixes', 'niccustomscripts', 'nicnetworks', 'nicips', 'nicextraparams' ]); my %nicsattrs; my @nicattrslist; - foreach my $node (@$nodes){ - if ($entry->{$node}->[0]->{'nictypes'}){ + foreach my $node (@$nodes) { + if ($entry->{$node}->[0]->{'nictypes'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'nictypes'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'type'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'type'} = $nicattrs[1]; } } - if($entry->{$node}->[0]->{'nichostnamesuffixes'}){ + if ($entry->{$node}->[0]->{'nichostnamesuffixes'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'nichostnamesuffixes'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'hostnamesuffix'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'hostnamesuffix'} = $nicattrs[1]; } } - if($entry->{$node}->[0]->{'nichostnameprefixes'}){ + if ($entry->{$node}->[0]->{'nichostnameprefixes'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'nichostnameprefixes'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'hostnameprefix'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'hostnameprefix'} = $nicattrs[1]; } } - if($entry->{$node}->[0]->{'niccustomscripts'}){ + if ($entry->{$node}->[0]->{'niccustomscripts'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'niccustomscripts'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'customscript'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'customscript'} = $nicattrs[1]; } } - if($entry->{$node}->[0]->{'nicnetworks'}){ + if ($entry->{$node}->[0]->{'nicnetworks'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'nicnetworks'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'network'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'network'} = $nicattrs[1]; } } - if($entry->{$node}->[0]->{'nicips'}){ + if ($entry->{$node}->[0]->{'nicips'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'nicips'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'ip'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'ip'} = $nicattrs[1]; } } - if($entry->{$node}->[0]->{'nicextraparams'}){ + if ($entry->{$node}->[0]->{'nicextraparams'}) { @nicattrslist = split(",", $entry->{$node}->[0]->{'nicextraparams'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - $nicsattrs{$node}{$nicattrs[0]}{'extraparams'} = $nicattrs[1]; + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + $nicsattrs{$node}{ $nicattrs[0] }{'extraparams'} = $nicattrs[1]; } } } @@ -388,14 +390,14 @@ sub get_nodes_nic_attrs{ =cut #------------------------------------------------------------------------------- -sub get_netprofile_bmcnet{ +sub get_netprofile_bmcnet { my ($class, $netprofilename) = @_; my $netprofile_nicshash_ref = xCAT::ProfiledNodeUtils->get_nodes_nic_attrs($netprofilename)->{$netprofilename}; my %netprofile_nicshash = %$netprofile_nicshash_ref; - if (exists $netprofile_nicshash{'bmc'}{"network"}){ + if (exists $netprofile_nicshash{'bmc'}{"network"}) { return $netprofile_nicshash{'bmc'}{"network"} - }else{ + } else { return undef; } } @@ -409,17 +411,17 @@ sub get_netprofile_bmcnet{ =cut #------------------------------------------------------------------------------- -sub get_netprofile_provisionnet{ +sub get_netprofile_provisionnet { my ($class, $netprofilename) = @_; my $netprofile_nicshash_ref = xCAT::ProfiledNodeUtils->get_nodes_nic_attrs([$netprofilename])->{$netprofilename}; my %netprofile_nicshash = %$netprofile_nicshash_ref; - my $restab = xCAT::Table->new('noderes'); + my $restab = xCAT::Table->new('noderes'); my $installnicattr = $restab->getNodeAttribs($netprofilename, ['installnic']); my $installnic = $installnicattr->{'installnic'}; - if ($installnic){ - if (exists $netprofile_nicshash{$installnic}{"network"}){ + if ($installnic) { + if (exists $netprofile_nicshash{$installnic}{"network"}) { return $netprofile_nicshash{$installnic}{"network"} } } @@ -439,12 +441,12 @@ sub get_netprofile_provisionnet{ sub get_output_filename { my $installdir = xCAT::TableUtils->getInstallDir(); - my $pcmworkdir = $installdir."/pcm/work/"; - if (! -d $pcmworkdir) + my $pcmworkdir = $installdir . "/pcm/work/"; + if (!-d $pcmworkdir) { mkpath($pcmworkdir); } - return tempfile("hostinfo_result_XXXXXXX", DIR=>$pcmworkdir); + return tempfile("hostinfo_result_XXXXXXX", DIR => $pcmworkdir); } #------------------------------------------------------------------------------- @@ -466,9 +468,9 @@ sub get_output_filename #------------------------------------------------------------------------------- sub get_all_chassis { - my $class = shift; + my $class = shift; my $hashref = shift; - my $type = shift; + my $type = shift; my %chassishash; my %chassistype = ('all' => '__Chassis', 'cmm' => '__Chassis_IBM_Flex_chassis'); @@ -476,12 +478,12 @@ sub get_all_chassis $type = 'all'; } my @chassis = xCAT::NodeRange::noderange($chassistype{$type}); - if ($hashref){ - foreach (@chassis){ + if ($hashref) { + foreach (@chassis) { $chassishash{$_} = 1; } return \%chassishash; - } else{ + } else { return \@chassis; } } @@ -501,26 +503,26 @@ sub get_all_chassis #------------------------------------------------------------------------------- sub get_all_rack { - my $class = shift; - my $hashref = shift; + my $class = shift; + my $hashref = shift; my %rackhash = (); my @racklist = (); my $racktab = xCAT::Table->new('rack'); - my @racks = $racktab->getAllAttribs(('rackname')); - foreach (@racks){ - if($_->{'rackname'}){ - if ($hashref){ - $rackhash{$_->{'rackname'}} = 1; - }else { + my @racks = $racktab->getAllAttribs(('rackname')); + foreach (@racks) { + if ($_->{'rackname'}) { + if ($hashref) { + $rackhash{ $_->{'rackname'} } = 1; + } else { push @racklist, $_->{'rackname'}; } } } - - if ($hashref){ + + if ($hashref) { return \%rackhash; - }else{ + } else { return \@racklist; } } @@ -536,13 +538,13 @@ sub get_all_rack #------------------------------------------------------------------------------- sub get_racks_for_chassises { - my $class = shift; + my $class = shift; my $chassislistref = shift; - my %rackinfodict = (); + my %rackinfodict = (); my $nodepostab = xCAT::Table->new('nodepos'); my $racksref = $nodepostab->getNodesAttribs($chassislistref, ['rack']); - foreach (@$chassislistref){ + foreach (@$chassislistref) { $rackinfodict{$_} = $racksref->{$_}->[0]->{'rack'}; } return \%rackinfodict; @@ -562,15 +564,15 @@ sub get_racks_for_chassises #------------------------------------------------------------------------------- sub get_allnode_singleattrib_hash { - my $class = shift; + my $class = shift; my $tabname = shift; - my $attr = shift; - my $table = xCAT::Table->new($tabname); + my $attr = shift; + my $table = xCAT::Table->new($tabname); my @entries = $table->getAllNodeAttribs([$attr]); my %allrecords; foreach (@entries) { - if ($_->{$attr}){ - $allrecords{$_->{$attr}} = 0; + if ($_->{$attr}) { + $allrecords{ $_->{$attr} } = 0; } } return \%allrecords; @@ -587,16 +589,17 @@ sub get_allnode_singleattrib_hash #------------------------------------------------------------------------------- sub get_db_switches { - my $class = shift; - my $table = xCAT::Table->new("switches"); + my $class = shift; + my $table = xCAT::Table->new("switches"); my @attribs = ("switch"); my @entries = $table->getAllAttribs(@attribs); $table->close(); my %allrecords; - foreach (@entries) + foreach (@entries) { - if ($_->{'switch'}){ - $allrecords{$_->{'switch'}} = 0; + + if ($_->{'switch'}) { + $allrecords{ $_->{'switch'} } = 0; } } return \%allrecords; @@ -613,15 +616,15 @@ sub get_db_switches #------------------------------------------------------------------------------- sub get_db_switchports { - my $class = shift; - my $table = xCAT::Table->new("switch"); + my $class = shift; + my $table = xCAT::Table->new("switch"); my @attribs = ("switch", "port"); my @entries = $table->getAllAttribs(@attribs); $table->close(); my %allrecords; - foreach (@entries) + foreach (@entries) { - $allrecords{$_->{'switch'} . "_" . $_->{'port'}} = 0; + $allrecords{ $_->{'switch'} . "_" . $_->{'port'} } = 0; } return \%allrecords; } @@ -648,9 +651,9 @@ sub get_all_cecs my $ppctab = xCAT::Table->new('ppc'); my @cecs = $ppctab->getAllAttribsWhere("nodetype = 'cec'", 'node'); foreach (@cecs) { - if($_->{'node'}) { + if ($_->{'node'}) { if ($hashref) { - $cecshash{$_->{'node'}} = 1; + $cecshash{ $_->{'node'} } = 1; } else { push @cecslist, $_->{'node'}; } @@ -658,7 +661,7 @@ sub get_all_cecs } $ppctab->close(); - # Return the ref accordingly + # Return the ref accordingly if ($hashref) { return \%cecshash; } else { @@ -667,7 +670,7 @@ sub get_all_cecs } #------------------------------------------------------------------------------- - + =head3 get_all_lparids Description : Get all LPAR ids in system. Arguments : ref of all cecs @@ -679,22 +682,22 @@ sub get_all_cecs #------------------------------------------------------------------------------- sub get_all_lparids { - my $class= shift; + my $class = shift; my $cecsref = shift; my %allcecs = %$cecsref; my %lparids; my $ppctab = xCAT::Table->new('ppc'); - foreach my $cec (keys %allcecs) { + foreach my $cec (keys %allcecs) { my @ids = $ppctab->getAllAttribsWhere("hcp = '$cec'", 'id'); foreach (@ids) { - if ( $_->{'id'} ){ - $lparids{$cec}{$_->{'id'}} = 0; + if ($_->{'id'}) { + $lparids{$cec}{ $_->{'id'} } = 0; } } } $ppctab->close(); - + return \%lparids; } @@ -712,7 +715,7 @@ sub get_all_lparids sub is_discover_started { my @sitevalues = xCAT::TableUtils->get_site_attribute("__PCMDiscover"); - if (! $sitevalues[0]){ + if (!$sitevalues[0]) { return 0; } return 1; @@ -734,31 +737,34 @@ sub is_discover_started sub get_nodes_profiles { - my $class = shift; - my $nodelistref = shift; + my $class = shift; + my $nodelistref = shift; my $groupnamemode = shift; my %profile_dict; - my $nodelisttab = xCAT::Table->new('nodelist'); + my $nodelisttab = xCAT::Table->new('nodelist'); my $groupshashref = $nodelisttab->getNodesAttribs($nodelistref, ['groups']); - my %groupshash = %$groupshashref; + my %groupshash = %$groupshashref; - foreach (keys %groupshash){ - my $value = $groupshash{$_}; + foreach (keys %groupshash) { + my $value = $groupshash{$_}; my $groups = $value->[0]->{'groups'}; + # groups looks like "__Managed,__NetworkProfile_default_cn,__ImageProfile_rhels6.3-x86_64-install-compute" my @grouplist = split(',', $groups); my @profilelist = ("NetworkProfile", "ImageProfile", "HardwareProfile"); - foreach my $group (@grouplist){ - foreach my $profile (@profilelist){ - my $idx = index ($group, $profile); + foreach my $group (@grouplist) { + foreach my $profile (@profilelist) { + my $idx = index($group, $profile); + # The Group starts with __, so index will be 2. - if ( $idx == 2 ){ + if ($idx == 2) { + # The group string will like @NetworkProfile_ # So, index should +3, 2 for '__', 1 for _. - if ($groupnamemode) { + if ($groupnamemode) { $profile_dict{$_}{$profile} = $group; - } else{ + } else { my $append_index = length($profile) + 3; $profile_dict{$_}{$profile} = substr $group, $append_index; } @@ -785,11 +791,11 @@ sub get_imageprofile_prov_method # For imageprofile, we can get node's provisioning method through: # nodetype table: node (imageprofile name), provmethod (osimage name) # osimage table: imagename (osimage name), provmethod (node deploy method: install, netboot...) - my $class = shift; + my $class = shift; my $imgprofilename = shift; my $nodetypestab = xCAT::Table->new('nodetype'); - my $entry = ($nodetypestab->getAllAttribsWhere("node = '$imgprofilename'", 'ALL' ))[0]; + my $entry = ($nodetypestab->getAllAttribsWhere("node = '$imgprofilename'", 'ALL'))[0]; return $entry->{'provmethod'}; #my $osimgtab = xCAT::Table->new('osimage'); @@ -809,12 +815,12 @@ sub get_imageprofile_prov_method sub get_imageprofile_prov_osvers { - my $class = shift; + my $class = shift; my $imgprofilename = shift; - my $osimgtab = xCAT::Table->new('osimage'); - my $osimgentry = ($osimgtab->getAllAttribsWhere("imagename = '$imgprofilename'", 'ALL' ))[0]; + my $osimgtab = xCAT::Table->new('osimage'); + my $osimgentry = ($osimgtab->getAllAttribsWhere("imagename = '$imgprofilename'", 'ALL'))[0]; my $osversion = $osimgentry->{'osvers'}; - my $profile = $osimgentry->{'profile'}; + my $profile = $osimgentry->{'profile'}; return ($osversion, $profile); } @@ -831,86 +837,86 @@ sub get_imageprofile_prov_osvers =cut #------------------------------------------------------------------------------- -sub check_profile_consistent{ - my $class = shift; - my $imageprofile = shift; - my $networkprofile = shift; +sub check_profile_consistent { + my $class = shift; + my $imageprofile = shift; + my $networkprofile = shift; my $hardwareprofile = shift; - + # Check the profiles are existing in DB. my @nodegrps = xCAT::TableUtils->list_all_node_groups(); - unless(grep{ $_ eq $imageprofile} @nodegrps){ + unless (grep { $_ eq $imageprofile } @nodegrps) { return 0, "Image profile not defined in DB." } - unless(grep{ $_ eq $networkprofile} @nodegrps){ + unless (grep { $_ eq $networkprofile } @nodegrps) { return 0, "Network profile not defined in DB." } - if ($hardwareprofile){ - unless(grep{ $_ eq $hardwareprofile} @nodegrps){ + if ($hardwareprofile) { + unless (grep { $_ eq $hardwareprofile } @nodegrps) { return 0, "Hardware profile not defined in DB." } } # Get Imageprofile arch my $nodetypetab = xCAT::Table->new('nodetype'); - my $nodetypeentry = $nodetypetab->getNodeAttribs($imageprofile, ['os','arch']); - my $os = $nodetypeentry->{'os'}; + my $nodetypeentry = $nodetypetab->getNodeAttribs($imageprofile, [ 'os', 'arch' ]); + my $os = $nodetypeentry->{'os'}; my $arch = $nodetypeentry->{'arch'}; $nodetypetab->close(); - + # Get Imageprofile pkgdir my $osdistroname = $os . "-" . $arch; - my $osdistrotab = xCAT::Table->new('osdistro'); - my $osdistroentry = ($osdistrotab->getAllAttribsWhere("osdistroname = '$osdistroname'", 'ALL' ))[0]; + my $osdistrotab = xCAT::Table->new('osdistro'); + my $osdistroentry = ($osdistrotab->getAllAttribsWhere("osdistroname = '$osdistroname'", 'ALL'))[0]; my $pkgdir = $osdistroentry->{'dirpaths'}; $osdistrotab->close(); - + # Get networkprofile netboot and installnic my $noderestab = xCAT::Table->new('noderes'); - my $noderesentry = $noderestab->getNodeAttribs($networkprofile, ['netboot', 'installnic']); - my $netboot = $noderesentry->{'netboot'}; - my $installnic = $noderesentry->{'installnic'}; + my $noderesentry = $noderestab->getNodeAttribs($networkprofile, [ 'netboot', 'installnic' ]); + my $netboot = $noderesentry->{'netboot'}; + my $installnic = $noderesentry->{'installnic'}; $noderestab->close(); - + # Get networkprofile nictypes my $netprofile_nicshash_ref = xCAT::ProfiledNodeUtils->get_nodes_nic_attrs([$networkprofile])->{$networkprofile}; my %netprofile_nicshash = %$netprofile_nicshash_ref; - my $nictype = undef; + my $nictype = undef; foreach (keys %netprofile_nicshash) { my $value = $netprofile_nicshash{$_}{'type'}; if (($value eq 'FSP') or ($value eq 'BMC')) { $nictype = $value; } } - + #Get hardwareprofile mgt my $nodehmtab = xCAT::Table->new('nodehm'); - my $mgtentry = $nodehmtab->getNodeAttribs($hardwareprofile, ['mgt']); - my $mgt = undef; + my $mgtentry = $nodehmtab->getNodeAttribs($hardwareprofile, ['mgt']); + my $mgt = undef; $mgt = $mgtentry->{'mgt'} if ($mgtentry->{'mgt'}); $nodehmtab->close(); #Get hardwareprofile nodetype - my $ppctab = xCAT::Table->new('ppc'); - my $ntentry = $ppctab->getNodeAttribs($hardwareprofile, ['nodetype']); + my $ppctab = xCAT::Table->new('ppc'); + my $ntentry = $ppctab->getNodeAttribs($hardwareprofile, ['nodetype']); my $nodetype = undef; $nodetype = $ntentry->{'nodetype'} if ($ntentry->{'nodetype'}); - $ppctab->close(); - + $ppctab->close(); + # Checking whether netboot initrd image for Ubuntu ppc64 # This image should be downloaded from internet - if ($arch =~ /ppc64/i and $os =~ /ubuntu/i and !(-e "$pkgdir/install/netboot/initrd.gz")){ + if ($arch =~ /ppc64/i and $os =~ /ubuntu/i and !(-e "$pkgdir/install/netboot/initrd.gz")) { return 0, "The netboot initrd is not found in $pkgdir/install/netboot, please download it firstly."; } - + # Check if exists provision network - if (not ($installnic and exists $netprofile_nicshash{$installnic}{"network"})){ + if (not($installnic and exists $netprofile_nicshash{$installnic}{"network"})) { return 0, "Provisioning network not defined for network profile." } # Remove check mechanism about arch and netboot attribute # Attribute 'neboot' will be generated based on arch, management method, os - + # Profile consistent keys, arch=>netboot, mgt=>nictype #my $ppc_netboot = 'yaboot'; #if( $os =~ /rhels7/ ){ @@ -923,38 +929,39 @@ sub check_profile_consistent{ #if ($profile_dict{$arch} ne $netboot) { # return 0, "Imageprofile's arch is not consistent with networkprofile's netboot." #} - + # Check if networkprofile is consistent with hardwareprofile - if (not $hardwareprofile) { # Not define hardwareprofile - if (not $nictype) { # Networkprofile is not fsp or bmc + if (not $hardwareprofile) { # Not define hardwareprofile + if (not $nictype) { # Networkprofile is not fsp or bmc return 1, ""; - }elsif ($nictype eq 'FSP' or $nictype eq 'BMC') { + } elsif ($nictype eq 'FSP' or $nictype eq 'BMC') { return 0, "$nictype networkprofile must use with hardwareprofile."; } } - + my %mgt_dict = ('fsp' => 'FSP', 'ipmi' => 'BMC', 'kvm' => ''); - + if ($mgt eq 'vm') { return 1, ""; } - + if ($nodetype eq 'lpar') { if ($nictype) { + # Can not associate FSP/BMC network if the node type is lpar return 0, "The node with hardware type $nodetype can not use with $nictype networkprofile."; } return 1, "" } - + if ($mgt and $mgt_dict{$mgt} ne $nictype) { my $errmsg = "$mgt hardwareprofile must use with $mgt_dict{$mgt} networkprofile."; - if ( $mgt eq 'kvm' ) { + if ($mgt eq 'kvm') { $errmsg = "$mgt hardwareprofile must use with non-BMC and non-FSP networkprofile." } return 0, $errmsg; } - + return 1, ""; } @@ -970,22 +977,22 @@ sub check_profile_consistent{ #------------------------------------------------------------------------------- sub is_fsp_node { - my $class = shift; - my $node = shift; + my $class = shift; + my $node = shift; my $nicstab = xCAT::Table->new('nics'); - my $entry = $nicstab->getNodeAttribs($node, ['nictypes']); + my $entry = $nicstab->getNodeAttribs($node, ['nictypes']); $nicstab->close(); - - if ($entry->{'nictypes'}){ + + if ($entry->{'nictypes'}) { my @nicattrslist = split(",", $entry->{'nictypes'}); - foreach (@nicattrslist){ - my @nicattrs; - if ($_ =~ /!/) { - @nicattrs = split("!", $_); - } else { - @nicattrs = split(":", $_); - } - if ($nicattrs[1] eq 'FSP'){ + foreach (@nicattrslist) { + my @nicattrs; + if ($_ =~ /!/) { + @nicattrs = split("!", $_); + } else { + @nicattrs = split(":", $_); + } + if ($nicattrs[1] eq 'FSP') { return 1; } } @@ -1006,24 +1013,24 @@ sub is_fsp_node #------------------------------------------------------------------------------- sub is_kvm_node { - my $class = shift; + my $class = shift; my $hardwareprofile = shift; - + if (not $hardwareprofile) { return 0; } - + #Get hardwareprofile mgt my $nodehmtab = xCAT::Table->new('nodehm'); - my $mgtentry = $nodehmtab->getNodeAttribs($hardwareprofile, ['mgt']); - my $mgt = undef; + my $mgtentry = $nodehmtab->getNodeAttribs($hardwareprofile, ['mgt']); + my $mgt = undef; $mgt = $mgtentry->{'mgt'} if ($mgtentry->{'mgt'}); $nodehmtab->close(); - + if ($mgt eq 'kvm') { return 1; - } - + } + return 0; } @@ -1039,24 +1046,24 @@ sub is_kvm_node #------------------------------------------------------------------------------- sub is_kvm_hypv_node { - my $class = shift; + my $class = shift; my $imageprofile = shift; - + # Get provmethod my $provmethod = xCAT::ProfiledNodeUtils->get_imageprofile_prov_method($imageprofile); - unless ($provmethod ){ + unless ($provmethod) { return 0; } - + my $osimage_tab = xCAT::Table->new('osimage'); - my $osimage_tab_entry = $osimage_tab->getAttribs({'imagename'=> $provmethod},('osdistroname')); + my $osimage_tab_entry = $osimage_tab->getAttribs({ 'imagename' => $provmethod }, ('osdistroname')); my $osdistroname = $osimage_tab_entry->{'osdistroname'}; $osimage_tab->close(); - - if ($osdistroname and $osdistroname =~ /^pkvm/ ) { + + if ($osdistroname and $osdistroname =~ /^pkvm/) { return 1; } - + return 0; } @@ -1075,22 +1082,22 @@ sub is_kvm_hypv_node #------------------------------------------------------------------------------- sub get_nodes_cmm { - my $class = shift; + my $class = shift; my $nodelistref = shift; - my @nodes = @$nodelistref; + my @nodes = @$nodelistref; my %returncmm; - + my $mptab = xCAT::Table->new('mp'); my $entry = $mptab->getNodesAttribs($nodelistref, ['mpa']); $mptab->close(); - + foreach (@nodes) { my $mpa = $entry->{$_}->[0]->{'mpa'}; - if ($mpa and not exists $returncmm{$mpa}){ + if ($mpa and not exists $returncmm{$mpa}) { $returncmm{$mpa} = 1; } } - + return \%returncmm } @@ -1111,39 +1118,41 @@ sub get_nodes_cmm #------------------------------------------------------------------------------- sub parse_nodeinfo_file { - my($class, $filedata) = @_; + my ($class, $filedata) = @_; @::profiledNodeObjNames = (); - %::profiledNodeAttrs = (); + %::profiledNodeAttrs = (); - my @lines = split /\n/, $filedata; - my $obj_found = 0; + my @lines = split /\n/, $filedata; + my $obj_found = 0; my $attr_found = 0; my $null_obj; my ($objname, $append); - foreach my $line (@lines){ + foreach my $line (@lines) { + # skip blank and comment lines next if ($line =~ /^\s*$/ || $line =~ /^\s*#/); # The line ends with : - if (grep(/:\s*$/, $line)){ + if (grep(/:\s*$/, $line)) { $attr_found = 0; - $null_obj = $line; + $null_obj = $line; ($objname, $append) = split(/:/, $line); $objname =~ s/^\s*//; # Remove any leading whitespace $objname =~ s/\s*$//; # Remove any trailing whitespace # OK we've found one object. - if ($objname){ + if ($objname) { $obj_found = 1; push(@::profiledNodeObjNames, $objname); - }else{ + } else { return 0, "No node name defined in line \'$line\'"; } - } # The line has = - elsif (($line =~ /^\s*(.*?)\s*=\s*(.*)\s*/)){ + } # The line has = + elsif (($line =~ /^\s*(.*?)\s*=\s*(.*)\s*/)) { + # No one object clarified yet. So this file format is illegal. - if (! $obj_found){ + if (!$obj_found) { return 0, "No node defined before line \'$line\'"; } $attr_found = 1; @@ -1152,30 +1161,30 @@ sub parse_nodeinfo_file my $val = $2; $attr =~ s/^\s*//; # Remove any leading whitespace $attr =~ s/\s*$//; # Remove any trailing whitespace - $val =~ s/^\s*//; - $val =~ s/\s*$//; + $val =~ s/^\s*//; + $val =~ s/\s*$//; # remove spaces and quotes $val =~ s/^\s*"\s*//; $val =~ s/\s*"\s*$//; - if($attr && $val){ + if ($attr && $val) { $::profiledNodeAttrs{$objname}{$attr} = $val; - }else{ + } else { return 0, "Line \'$line\' does not contain a valid key and value"; } - } #invalid line. - else{ + } #invalid line. + else { return 0, "Invalid Line \'$line\' found"; } } - + # Defined object has no attributes - if (! $attr_found){ + if (!$attr_found) { return 0, "Invalid Line \'$null_obj\' found"; } - + return 1, ""; } @@ -1188,6 +1197,7 @@ sub parse_nodeinfo_file $retcode = 1. update failed, the value is undef $retcode = 0. save into db is OK.. =cut + #------------------------------------------------------- sub update_windows_prodkey @@ -1196,24 +1206,26 @@ sub update_windows_prodkey my $node = shift; my $product = shift; my $key = shift; - unless(defined($node) && defined($product) && defined($key)) + unless (defined($node) && defined($product) && defined($key)) { return 1; } + # please notice this db usage my %keyhash; my %updates; - $keyhash{'node'} = $node; - $updates{'product'} = $product; - $updates{'key'} = $key; - my $tab = xCAT::Table->new('prodkey', -create=>1, -autocommit=>0); - $tab->setAttribs( \%keyhash,\%updates ); + $keyhash{'node'} = $node; + $updates{'product'} = $product; + $updates{'key'} = $key; + my $tab = xCAT::Table->new('prodkey', -create => 1, -autocommit => 0); + $tab->setAttribs(\%keyhash, \%updates); $tab->commit; - $tab->close; + $tab->close; return 0; } #------------------------------------------------------------------------------- + =head3 check_nicips Description: Check if the nicips defined in MAC file is correct format @@ -1226,63 +1238,65 @@ sub update_windows_prodkey $retcode = 0. Parse success, the format of nicips is OK.. =cut + #------------------------------------------------------------------------------- -sub check_nicips{ - my $class = shift; - my $installnic = shift; +sub check_nicips { + my $class = shift; + my $installnic = shift; my $netprofileattrsref = shift; - my $freeipshash = shift; - my $othernics = shift; - - my $errmsg = ""; - my %nics_hash = (); + my $freeipshash = shift; + my $othernics = shift; + + my $errmsg = ""; + my %nics_hash = (); my %netprofileattr = %$netprofileattrsref; - + foreach my $nic_ips (split(/,/, $othernics)) { my @nic_and_ips = (); - my $nic = ""; - my $nic_ip = ""; - if($nic_ips =~ /!/ and $nic_ips !~ /!$/) { + my $nic = ""; + my $nic_ip = ""; + if ($nic_ips =~ /!/ and $nic_ips !~ /!$/) { @nic_and_ips = split(/!/, $nic_ips); my $len = @nic_and_ips; - $nic = $nic_and_ips[0]; + $nic = $nic_and_ips[0]; $nic_ip = $nic_and_ips[1]; - + if (exists $nics_hash{$nic} or $len ne 2) { $errmsg = "The specified nicips is incorrect. It must be formatted correctly, in the form: !,!,..."; return (1, "", $errmsg); } - + # Check whether other interfaces contain provision nic if ($nic eq $installnic) { $errmsg = "The specified nicips cannot contain NICs used for provisioning."; return (1, "", $errmsg); } - + # Check whether this interface is defined in networkprofile - unless (exists $netprofileattr{$nic}){ + unless (exists $netprofileattr{$nic}) { $errmsg = "The specified nicips contains NICs that are not defined in the network profile."; return (1, "", $errmsg); } - + # Check whether specified IP is in each network's static range my $nicnetwork = $netprofileattr{$nic}{'network'}; my $freeipsref = $freeipshash->{$nicnetwork}; - unless (grep{ $_ eq $nic_ip} @$freeipsref){ + unless (grep { $_ eq $nic_ip } @$freeipsref) { $errmsg = "Specified IP address $nic_ip not in static range of network $netprofileattr{$nic}{'network'}"; return (1, "", $errmsg); } - }else { + } else { $errmsg = "The specified nicips is incorrect. It must be formatted correctly, in the form: !,!,..."; return (1, "", $errmsg); } $nics_hash{$nic} = $nic_ip; } - + return (0, \%nics_hash, ""); } #------------------------------------------------------------------------------- + =head3 gen_chain_for_profiles Description: Generate a chain string based on Network/Hardware/Image profiles. Arguments: $profiles_hash: The reference for profiles hash. @@ -1298,36 +1312,38 @@ sub check_nicips{ $retcode = 0. Generate chain OK. $chain stands for the chain string. =cut + #------------------------------------------------------------------------------- -sub gen_chain_for_profiles{ - my $class = shift; +sub gen_chain_for_profiles { + my $class = shift; my $profiles_hashref = shift; - my $hw_reconfig = shift; - my $final_chain = ""; - if (! $profiles_hashref){ + my $hw_reconfig = shift; + my $final_chain = ""; + if (!$profiles_hashref) { return (1, "Missing parameter for gen_chain_for_profiles."); } + # A node must have at least imageprofile and network profile. - unless (defined $profiles_hashref->{'ImageProfile'}){ + unless (defined $profiles_hashref->{'ImageProfile'}) { return (1, "No imageprofile specified in profiles hash."); } - unless (defined $profiles_hashref->{'NetworkProfile'}){ + unless (defined $profiles_hashref->{'NetworkProfile'}) { return (1, "No networkprofile specified in profiles hash."); } - my $hwprofile = $profiles_hashref->{'HardwareProfile'}; + my $hwprofile = $profiles_hashref->{'HardwareProfile'}; my $imgprofile = $profiles_hashref->{'ImageProfile'}; my $netprofile = $profiles_hashref->{'NetworkProfile'}; # Get node's provisioning method my $provmethod = xCAT::ProfiledNodeUtils->get_imageprofile_prov_method($imgprofile); - unless ($provmethod ){ + unless ($provmethod) { return (1, "Can not get provisioning method for image profile $imgprofile"); } my $netprofileattr = xCAT::ProfiledNodeUtils->get_nodes_nic_attrs([$netprofile])->{$netprofile}; - unless ($netprofileattr){ + unless ($netprofileattr) { return (1, "Can not get attributes for network profile $netprofile"); } - + # Get node's netboot attribute my ($retcode, $retval) = xCAT::ProfiledNodeUtils->get_netboot_attr($imgprofile, $hwprofile); if (not $retcode) { @@ -1335,34 +1351,36 @@ sub gen_chain_for_profiles{ } my $netboot = $retval; - $final_chain = 'osimage='.$provmethod.":--noupdateinitrd"; + $final_chain = 'osimage=' . $provmethod . ":--noupdateinitrd"; + # get the chain attribute from hardwareprofile and insert it to node. - if (defined $hwprofile and $hwprofile and $hw_reconfig){ + if (defined $hwprofile and $hwprofile and $hw_reconfig) { my $chaintab = xCAT::Table->new('chain'); my $chain = $chaintab->getNodeAttribs($hwprofile, ['chain']); if (exists $chain->{'chain'}) { - my $hw_chain = $chain->{'chain'}; - $final_chain = $hw_chain.',osimage='.$provmethod.":--noupdateinitrd"; + my $hw_chain = $chain->{'chain'}; + $final_chain = $hw_chain . ',osimage=' . $provmethod . ":--noupdateinitrd"; } } + #run bmcsetups. #PowerNV nodes can't use 'runcmd=bmcsetup' to set BMC. #But OpenPower need to support bmcsetup - my $nodehmtab = xCAT::Table->new('nodehm'); - my $comments = ""; + my $nodehmtab = xCAT::Table->new('nodehm'); + my $comments = ""; my $nodehmtab_entry = $nodehmtab->getNodeAttribs($hwprofile, ['comments']); if (defined $nodehmtab_entry->{'comments'}) { - $comments = $nodehmtab_entry->{'comments'}; + $comments = $nodehmtab_entry->{'comments'}; } - if ((exists $netprofileattr->{"bmc"}) and $hw_reconfig){ - if ((($netboot eq 'petitboot') and ($comments eq 'openpower')) or ($netboot ne 'petiboot')) + if ((exists $netprofileattr->{"bmc"}) and $hw_reconfig) { + if ((($netboot eq 'petitboot') and ($comments eq 'openpower')) or ($netboot ne 'petitboot')) { - if (index($final_chain, "runcmd=bmcsetup") == -1){ - $final_chain = 'runcmd=bmcsetup,'.$final_chain.':reboot4deploy'; + if (index($final_chain, "runcmd=bmcsetup") == -1) { + $final_chain = 'runcmd=bmcsetup,' . $final_chain . ':reboot4deploy'; } - else{ - $final_chain = $final_chain.':reboot4deploy'; + else { + $final_chain = $final_chain . ':reboot4deploy'; } } } @@ -1385,16 +1403,17 @@ sub get_all_vmhosts my %vmhostshash; my $nodelisttab = xCAT::Table->new('nodelist'); + # groups like '__Hypervisor_pkvm' means this node is Power KVM hypervisor my @vmhosts = $nodelisttab->getAllAttribsWhere("groups like '%__Hypervisor_kvm%'", 'node'); foreach (@vmhosts) { - if($_->{'node'}) { - $vmhostshash{$_->{'node'}} = 1; + if ($_->{'node'}) { + $vmhostshash{ $_->{'node'} } = 1; } } $nodelisttab->close(); - # Return the ref accordingly + # Return the ref accordingly return \%vmhostshash; } @@ -1410,21 +1429,21 @@ sub get_all_vmhosts =cut #------------------------------------------------------------------------------- -sub get_netboot_attr{ - my $class = shift; - my $imageprofile = shift; +sub get_netboot_attr { + my $class = shift; + my $imageprofile = shift; my $hardwareprofile = shift; my $netboot; my @nodegrps = xCAT::TableUtils->list_all_node_groups(); - unless(grep{ $_ eq $imageprofile} @nodegrps) + unless (grep { $_ eq $imageprofile } @nodegrps) { return 0, "Image profile not defined in DB." } $imageprofile =~ s/^__ImageProfile_//; - if ($hardwareprofile){ - unless(grep{ $_ eq $hardwareprofile} @nodegrps) + if ($hardwareprofile) { + unless (grep { $_ eq $hardwareprofile } @nodegrps) { return 0, "Hardware profile not defined in DB." } @@ -1436,15 +1455,15 @@ sub get_netboot_attr{ # Get os name, os major version, osarch my $osimage_tab = xCAT::Table->new('osimage'); - my $osimage_tab_entry = $osimage_tab->getAttribs({'imagename'=> $imageprofile},('osdistroname')); + my $osimage_tab_entry = $osimage_tab->getAttribs({ 'imagename' => $imageprofile }, ('osdistroname')); my $osdistroname = $osimage_tab_entry->{'osdistroname'}; $osimage_tab->close(); my $osdistro_tab = xCAT::Table->new('osdistro'); - my $osdistro_tab_entry = $osdistro_tab->getAttribs({'osdistroname'=> $osdistroname},('basename', 'majorversion', 'arch')); - my $os_name = $osdistro_tab_entry->{'basename'}; + my $osdistro_tab_entry = $osdistro_tab->getAttribs({ 'osdistroname' => $osdistroname }, ('basename', 'majorversion', 'arch')); + my $os_name = $osdistro_tab_entry->{'basename'}; my $os_major_version = $osdistro_tab_entry->{'majorversion'}; - my $os_arch = $osdistro_tab_entry->{'arch'}; + my $os_arch = $osdistro_tab_entry->{'arch'}; $osdistro_tab->close; # Treate os name rhel,centos,rhelhpc same as rhels @@ -1452,17 +1471,18 @@ sub get_netboot_attr{ { $os_name = 'rhels'; } + # Treate arch ppc64el same as ppc64le,x86 same as x86_64 if ($os_arch eq 'ppc64el') { $os_arch = 'ppc64le'; - }elsif ($os_arch eq 'x86') + } elsif ($os_arch eq 'x86') { $os_arch = 'x86_64'; } - + # Identify whether this node is PowerKVM or PowerNV if os arch is ppc64le - # If hardware profile is defined + # If hardware profile is defined my $mgt = '*'; if ($os_arch eq 'ppc64le' and $hardwareprofile ne '*') { my $nodehmtab = xCAT::Table->new('nodehm'); @@ -1471,47 +1491,48 @@ sub get_netboot_attr{ $mgt = $nodehmtab_entry->{'mgt'}; } } - -# Rule for netboot attribute.If update the rule,just update %netboot_dict and @condition_array -# It's sequence sensitive: os arch -> os name -> os major version -> hardware profile -# Priority | Arch | OS Name | OS Major Version | Management method | Noderes.netboot | -# 1 | x86_64/x86 | * | * | * | xnba | -# 2 | ppc64 | rhels | 7 | * | grub2 | -# 2 | ppc64 | pkvm | * | * | petitboot | -# 3 | | * | * | * | yaboot | -# 4 | ppc64le/el | * | * | * | grub2 -# 4 | ppc64le/el | * | * | ipmi | petitboot -# arch osname version hardware netboot - my %netboot_dict = ( 'x86_64' => 'xnba', - 'ppc64' => { - 'rhels' => { - '7' => 'grub2', - '*' => 'yaboot', - }, - 'pkvm' => 'petitboot', - '*' => 'yaboot', - }, - 'ppc64le' => { - '*' => { - '*' => { - '*' => 'grub2', - 'ipmi' => 'petitboot', - }, - }, - }, - ); - my $condition_array_ref = [$os_arch, $os_name, $os_major_version, $mgt]; + + # Rule for netboot attribute.If update the rule,just update %netboot_dict and @condition_array + # It's sequence sensitive: os arch -> os name -> os major version -> hardware profile + # Priority | Arch | OS Name | OS Major Version | Management method | Noderes.netboot | + # 1 | x86_64/x86 | * | * | * | xnba | + # 2 | ppc64 | rhels | 7 | * | grub2 | + # 2 | ppc64 | pkvm | * | * | petitboot | + # 3 | | * | * | * | yaboot | + # 4 | ppc64le/el | * | * | * | grub2 + # 4 | ppc64le/el | * | * | ipmi | petitboot + # arch osname version hardware netboot + my %netboot_dict = ('x86_64' => 'xnba', + 'ppc64' => { + 'rhels' => { + '7' => 'grub2', + '*' => 'yaboot', + }, + 'pkvm' => 'petitboot', + '*' => 'yaboot', + }, + 'ppc64le' => { + '*' => { + '*' => { + '*' => 'grub2', + 'ipmi' => 'petitboot', + }, + }, + }, + ); + my $condition_array_ref = [ $os_arch, $os_name, $os_major_version, $mgt ]; $netboot = cal_netboot(\%netboot_dict, $condition_array_ref); - if($netboot eq '0') + if ($netboot eq '0') { return 0, "Can not get the netboot attribute"; } else - { + { return 1, $netboot; } } + #------------------------------------------------------------------------------- =head3 cal_netboot @@ -1523,25 +1544,25 @@ sub get_netboot_attr{ =cut #------------------------------------------------------------------------------- -sub cal_netboot{ - my $netboot_dict_ref = shift; +sub cal_netboot { + my $netboot_dict_ref = shift; my $condition_array_ref = shift; my $condition_array_len = scalar @$condition_array_ref; - - if( $condition_array_len == 0 ){ + + if ($condition_array_len == 0) { return 0; } my $condition = shift @$condition_array_ref; - if( (exists($netboot_dict_ref->{$condition})) || (exists($netboot_dict_ref->{'*'})) ) + if ((exists($netboot_dict_ref->{$condition})) || (exists($netboot_dict_ref->{'*'}))) { - if(!exists($netboot_dict_ref->{$condition})) + if (!exists($netboot_dict_ref->{$condition})) { $condition = '*'; } - if(ref($netboot_dict_ref->{$condition}) eq 'HASH') + if (ref($netboot_dict_ref->{$condition}) eq 'HASH') { - if($condition_array_len > 1) + if ($condition_array_len > 1) { return cal_netboot($netboot_dict_ref->{$condition}, $condition_array_ref); } diff --git a/perl-xCAT/xCAT/RSH.pm b/perl-xCAT/xCAT/RSH.pm index 6fdd03eb3..8a03e9db2 100644 --- a/perl-xCAT/xCAT/RSH.pm +++ b/perl-xCAT/xCAT/RSH.pm @@ -2,6 +2,7 @@ # IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html package xCAT::RSH; + # cannot use strict # cannot use strict use base xCAT::DSHRemoteShell; @@ -9,14 +10,14 @@ use base xCAT::DSHRemoteShell; # Determine if OS is AIX or Linux # Configure standard locations of commands based on OS -if ( $^O eq 'aix' ) { - our $RCP_CMD = '/bin/rcp'; - our $RSH_CMD = '/bin/rsh'; +if ($^O eq 'aix') { + our $RCP_CMD = '/bin/rcp'; + our $RSH_CMD = '/bin/rsh'; } -if ( $^O eq 'linux' ) { - our $RCP_CMD = '/usr/bin/rcp'; - our $RSH_CMD = '/usr/bin/rsh'; +if ($^O eq 'linux') { + our $RCP_CMD = '/usr/bin/rcp'; + our $RSH_CMD = '/usr/bin/rsh'; } =head3 @@ -53,28 +54,28 @@ if ( $^O eq 'linux' ) { =cut sub remote_shell_command { - my ( $class, $config, $exec_path ) = @_; + my ($class, $config, $exec_path) = @_; - $exec_path || ( $exec_path = $RSH_CMD ); + $exec_path || ($exec_path = $RSH_CMD); - my @command = (); + my @command = (); - push @command, $exec_path; - push @command, $$config{'hostname'}; + push @command, $exec_path; + push @command, $$config{'hostname'}; - if ( $$config{'user'} ) { - push @command, '-l'; - push @command, $$config{'user'}; - } + if ($$config{'user'}) { + push @command, '-l'; + push @command, $$config{'user'}; + } - if ( $$config{'options'} ) { - my @options = split ' ', $$config{'options'}; - push @command, @options; - } + if ($$config{'options'}) { + my @options = split ' ', $$config{'options'}; + push @command, @options; + } - push @command, $$config{'command'}; + push @command, $$config{'command'}; - return @command; + return @command; } =head3 @@ -117,41 +118,41 @@ sub remote_shell_command { =cut sub remote_copy_command { - my ( $class, $config, $exec_path ) = @_; + my ($class, $config, $exec_path) = @_; - $exec_path || ( $exec_path = $RCP_CMD ); + $exec_path || ($exec_path = $RCP_CMD); - my @command = (); - my @src_files = (); - my @dest_file = (); + my @command = (); + my @src_files = (); + my @dest_file = (); - my @src_file_list = split $::__DCP_DELIM, $$config{'src-file'}; + my @src_file_list = split $::__DCP_DELIM, $$config{'src-file'}; - foreach $src_file (@src_file_list) { - my @src_path = (); - $$config{'src-user'} && push @src_path, "$$config{'src-user'}@"; - $$config{'src-host'} && push @src_path, "$$config{'src-host'}:"; - $$config{'src-file'} && push @src_path, $src_file; - push @src_files, ( join '', @src_path ); - } + foreach $src_file (@src_file_list) { + my @src_path = (); + $$config{'src-user'} && push @src_path, "$$config{'src-user'}@"; + $$config{'src-host'} && push @src_path, "$$config{'src-host'}:"; + $$config{'src-file'} && push @src_path, $src_file; + push @src_files, (join '', @src_path); + } - $$config{'dest-user'} && push @dest_file, "$$config{'dest-user'}@"; - $$config{'dest-host'} && push @dest_file, "$$config{'dest-host'}:"; - $$config{'dest-file'} && push @dest_file, $$config{'dest-file'}; + $$config{'dest-user'} && push @dest_file, "$$config{'dest-user'}@"; + $$config{'dest-host'} && push @dest_file, "$$config{'dest-host'}:"; + $$config{'dest-file'} && push @dest_file, $$config{'dest-file'}; - push @command, $exec_path; - $$config{'preserve'} && push @command, '-p'; - $$config{'recursive'} && push @command, '-r'; + push @command, $exec_path; + $$config{'preserve'} && push @command, '-p'; + $$config{'recursive'} && push @command, '-r'; - if ( $$config{'options'} ) { - my @options = split ' ', $$config{'options'}; - push @command, @options; - } + if ($$config{'options'}) { + my @options = split ' ', $$config{'options'}; + push @command, @options; + } - push @command, @src_files; - push @command, ( join '', @dest_file ); + push @command, @src_files; + push @command, (join '', @dest_file); - return @command; + return @command; } 1; diff --git a/perl-xCAT/xCAT/RSYNC.pm b/perl-xCAT/xCAT/RSYNC.pm index 52b0725f4..b40158d80 100644 --- a/perl-xCAT/xCAT/RSYNC.pm +++ b/perl-xCAT/xCAT/RSYNC.pm @@ -6,6 +6,7 @@ package xCAT::RSYNC; # cannot use strict use base xCAT::DSHRemoteShell; use xCAT::TableUtils qw(get_site_attribute); + # Determine if OS is AIX or Linux # Configure standard locations of commands based on OS @@ -13,9 +14,9 @@ if ($^O eq 'aix') { if (-e ("/usr/bin/rsync")) { - our $RSYNC_CMD = '/usr/bin/rsync'; + our $RSYNC_CMD = '/usr/bin/rsync'; } else { - our $RSYNC_CMD = '/usr/local/bin/rsync'; + our $RSYNC_CMD = '/usr/local/bin/rsync'; } } @@ -23,6 +24,7 @@ if ($^O eq 'linux') { our $RSYNC_CMD = '/usr/bin/rsync'; } + #----------------------------------------------------------------------- =head3 @@ -69,22 +71,22 @@ if ($^O eq 'linux') sub remote_copy_command { - my ($class, $config, $exec_path,$localhost) = @_; + my ($class, $config, $exec_path, $localhost) = @_; $exec_path || ($exec_path = $RSYNC_CMD); # see if we are using rsh or ssh on AIX - my $usersh=0; + my $usersh = 0; if ($^O eq 'aix') { - my @useSSH = xCAT::TableUtils->get_site_attribute("useSSHonAIX"); - if (defined($useSSH[0])) { - $useSSH[0] =~ tr/a-z/A-Z/; # convert to upper - if (($useSSH[0] eq "0") || ($useSSH[0] eq "NO")) - { - $usersh=1; + my @useSSH = xCAT::TableUtils->get_site_attribute("useSSHonAIX"); + if (defined($useSSH[0])) { + $useSSH[0] =~ tr/a-z/A-Z/; # convert to upper + if (($useSSH[0] eq "0") || ($useSSH[0] eq "NO")) + { + $usersh = 1; + } } - } } @@ -97,46 +99,47 @@ sub remote_copy_command if ($^O eq 'aix') { if (-e ("/usr/bin/rsync")) { - if (($usersh == 0) || ($localhost == 1)) { # using ssh, or local - if ($$config{'sudo'}){ - $sync_opt = '--rsync-path=sudo /usr/bin/rsync '; - } else { - $sync_opt = '--rsync-path /usr/bin/rsync '; - } - } else { - $sync_opt = '--rsh /bin/rsh --rsync-path /usr/bin/rsync '; - } + if (($usersh == 0) || ($localhost == 1)) { # using ssh, or local + if ($$config{'sudo'}) { + $sync_opt = '--rsync-path=sudo /usr/bin/rsync '; + } else { + $sync_opt = '--rsync-path /usr/bin/rsync '; + } + } else { + $sync_opt = '--rsh /bin/rsh --rsync-path /usr/bin/rsync '; + } } else { - if (($usersh == 0) || ($localhost == 1)) { # using ssh, or local - if ($$config{'sudo'}){ - $sync_opt = '--rsync-path=sudo /usr/local/bin/rsync '; - } else { - $sync_opt = '--rsync-path=/usr/local/bin/rsync '; - } - } else { - $sync_opt = '--rsh /bin/rsh --rsync-path /usr/local/bin/rsync '; - } + if (($usersh == 0) || ($localhost == 1)) { # using ssh, or local + if ($$config{'sudo'}) { + $sync_opt = '--rsync-path=sudo /usr/local/bin/rsync '; + } else { + $sync_opt = '--rsync-path=/usr/local/bin/rsync '; + } + } else { + $sync_opt = '--rsh /bin/rsh --rsync-path /usr/local/bin/rsync '; + } } } - else #linux + else #linux { - if ($$config{'sudo'}) { - $sync_opt = '--rsync-path=\'sudo /usr/bin/rsync\' '; - } else { - $sync_opt = '--rsync-path /usr/bin/rsync '; - } + if ($$config{'sudo'}) { + $sync_opt = '--rsync-path=\'sudo /usr/bin/rsync\' '; + } else { + $sync_opt = '--rsync-path /usr/bin/rsync '; + } } + # if only syncing the service node or # (no postscripts and no append lines) then do not # get update file notification - if (($::SYNCSN == 1) || ((!(@::postscripts)) && (!(@::appendlines)) && (!(@::mergelines)))) { - $sync_opt .= '-Lprogtz '; + if (($::SYNCSN == 1) || ((!(@::postscripts)) && (!(@::appendlines)) && (!(@::mergelines)))) { + $sync_opt .= '-Lprogtz '; } else { - $sync_opt .= '-Liprogtz --out-format=%f%L '; # add notify of update + $sync_opt .= '-Liprogtz --out-format=%f%L '; # add notify of update } $sync_opt .= $$config{'options'}; if ($::SYNCSN == 1) - { # syncing service node + { # syncing service node $rsyncfile = "/tmp/rsync_$$config{'dest-host'}"; $rsyncfile .= "_s"; } @@ -146,7 +149,7 @@ sub remote_copy_command } open RSCYCCMDFILE, "> $rsyncfile" or die "Can not open file $rsyncfile"; - my $dest_dir_list = join ' ', keys %{$$config{'destDir_srcFile'}}; + my $dest_dir_list = join ' ', keys %{ $$config{'destDir_srcFile'} }; my $dest_user_host = $$config{'dest-host'}; if ($$config{'dest-user'}) { @@ -154,47 +157,48 @@ sub remote_copy_command "$$config{'dest-user'}@" . "$$config{'dest-host'}"; } print RSCYCCMDFILE "#!/bin/sh\n"; - if ($localhost == 1) { # running to the MN from the MN + if ($localhost == 1) { # running to the MN from the MN print RSCYCCMDFILE "/bin/mkdir -p $dest_dir_list\n"; - } else { # running to another node - if ($usersh == 0) { # using ssh - print RSCYCCMDFILE - "/usr/bin/ssh $dest_user_host '/bin/mkdir -p $dest_dir_list'\n"; - } else { - print RSCYCCMDFILE - "/usr/bin/rsh $dest_user_host '/bin/mkdir -p $dest_dir_list'\n"; - } + } else { # running to another node + if ($usersh == 0) { # using ssh + print RSCYCCMDFILE +"/usr/bin/ssh $dest_user_host '/bin/mkdir -p $dest_dir_list'\n"; + } else { + print RSCYCCMDFILE +"/usr/bin/rsh $dest_user_host '/bin/mkdir -p $dest_dir_list'\n"; + } } - foreach my $dest_dir (keys %{$$config{'destDir_srcFile'}}) + foreach my $dest_dir (keys %{ $$config{'destDir_srcFile'} }) { my @src_file = - @{$$config{'destDir_srcFile'}{$dest_dir}{'same_dest_name'}}; + @{ $$config{'destDir_srcFile'}{$dest_dir}{'same_dest_name'} }; my $src_file_list = join ' ', @src_file; if ($src_file_list) { - if ($localhost == 1) { # running local ( on MN) - print RSCYCCMDFILE - "$exec_path $sync_opt $src_file_list $dest_dir\n"; - } else { # running to another node - print RSCYCCMDFILE - "$exec_path $sync_opt $src_file_list $dest_user_host:$dest_dir\n"; - } + if ($localhost == 1) { # running local ( on MN) + print RSCYCCMDFILE + "$exec_path $sync_opt $src_file_list $dest_dir\n"; + } else { # running to another node + print RSCYCCMDFILE +"$exec_path $sync_opt $src_file_list $dest_user_host:$dest_dir\n"; + } } my %diff_dest_hash = - %{$$config{'destDir_srcFile'}{$dest_dir}{'diff_dest_name'}}; + %{ $$config{'destDir_srcFile'}{$dest_dir}{'diff_dest_name'} }; foreach my $src_file_diff_dest (keys %diff_dest_hash) { my $diff_basename = $diff_dest_hash{$src_file_diff_dest}; + # if localhost do not put in hostname: - if ($localhost == 1) { # running to the MN from the MN (local) - print RSCYCCMDFILE - "$exec_path $sync_opt $src_file_diff_dest $dest_dir/$diff_basename\n"; - } else { # running remote - print RSCYCCMDFILE - "$exec_path $sync_opt $src_file_diff_dest $dest_user_host:$dest_dir/$diff_basename\n"; + if ($localhost == 1) { # running to the MN from the MN (local) + print RSCYCCMDFILE +"$exec_path $sync_opt $src_file_diff_dest $dest_dir/$diff_basename\n"; + } else { # running remote + print RSCYCCMDFILE +"$exec_path $sync_opt $src_file_diff_dest $dest_user_host:$dest_dir/$diff_basename\n"; } } @@ -227,9 +231,9 @@ sub remote_copy_command $$config{'dest-file'} && push @dest_file, $$config{'dest-file'}; push @command, $exec_path; - if ($usersh == 1) { # using rsh - push @command, "--rsh"; - push @command, "/bin/rsh"; + if ($usersh == 1) { # using rsh + push @command, "--rsh"; + push @command, "/bin/rsh"; } $$config{'preserve'} && push @command, ('-p', '-t'); $$config{'recursive'} && push @command, '-r'; diff --git a/perl-xCAT/xCAT/RemoteShellExp.pm b/perl-xCAT/xCAT/RemoteShellExp.pm index 1991607cb..19ee11541 100755 --- a/perl-xCAT/xCAT/RemoteShellExp.pm +++ b/perl-xCAT/xCAT/RemoteShellExp.pm @@ -69,149 +69,159 @@ use Expect; use strict; #----------------------------------------------------------------------------- -sub remoteshellexp +sub remoteshellexp { - my ($class, $flag, $callback, $remoteshell, $nodes, $timeout) = @_; - my $rc=0; - $::CALLBACK = $callback; - if (!($flag)) - { - my $rsp = {}; - $rsp->{error}->[0] = - "No flag provide to remoteshellexp."; + my ($class, $flag, $callback, $remoteshell, $nodes, $timeout) = @_; + my $rc = 0; + $::CALLBACK = $callback; + if (!($flag)) + { + my $rsp = {}; + $rsp->{error}->[0] = + "No flag provide to remoteshellexp."; xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 2); return 2; - } - - if (($flag ne "k") && ($flag ne "t") && ($flag ne "s")) { - my $rsp = {}; - $rsp->{error}->[0] = - "Invalid flag $flag provided."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 2; - - } - my $expecttimeout=10; # default - if (defined($timeout)) { # value supplied - $expecttimeout=$timeout; - } - - # for -s flag must have nodes and a $to_userid password - my $to_user_password; - if ($ENV{'DSH_REMOTE_PASSWORD'}) { - $to_user_password=$ENV{'DSH_REMOTE_PASSWORD'}; - } - if ($flag eq "s"){ - if (!$to_user_password) { - my $rsp = {}; - $rsp->{error}->[0] = - "The DSH_REMOTE_PASSWORD environment variable has not been set to the user id password on the node which will have their ssh keys updated (ususally root)."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 2; - } - if (!$nodes) { - my $rsp = {}; - $rsp->{error}->[0] = - "No nodes were input to update the user's ssh keys."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 2; - } - } - my $ssh_setup_cmd; - my $from_userid; - my $to_userid; - my $home; - my $remotecopy; - # if caller input a path to ssh remote command, use it - if ($ENV{'DSH_REMOTE_CMD'}) { - $remoteshell=$ENV{'DSH_REMOTE_CMD'}; - } else { - if (!$remoteshell) { - $remoteshell="/usr/bin/ssh"; } - } - # figure out path to scp - my ($path,$ssh) = split(/ssh/,$remoteshell); - $remotecopy=$path . "scp"; - # if caller input the ssh setup command (such as for IB Switch) - if ($ENV{'SSH_SETUP_COMMAND'}) { - $ssh_setup_cmd=$ENV{'SSH_SETUP_COMMAND'}; - } - # set User on the Management node that has the ssh keys - # this id can be a local (non-root) id as well as root - if ($ENV{'DSH_FROM_USERID'}) { - $from_userid=$ENV{'DSH_FROM_USERID'}; - } else { - $from_userid="root"; - } - # set User on the node where we will send the keys - # this id can be a local id as well as root - if ($ENV{'DSH_TO_USERID'}) { - $to_userid=$ENV{'DSH_TO_USERID'}; - } else { - $to_userid="root"; - } - # set User home directory to find the ssh public key to send - # For non-root ids information may not be in /etc/passwd - # but elsewhere like LDAP - - if ($ENV{'DSH_FROM_USERID_HOME'}) { - $home=$ENV{'DSH_FROM_USERID_HOME'}; - } else { - $home=xCAT::Utils->getHomeDir($from_userid); - } - # This indicates we will generate new ssh keys for the user, - # if they are not already there - # unless using zones - my $key="$home/.ssh/id_rsa"; - my $key2="$home/.ssh/id_rsa.pub"; - # Check to see if empty - if (-z $key) { - my $rsp = {}; - $rsp->{error}->[0] = - "The $key file is empty. Remove it and rerun the command."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 1; - } - if (-z $key2) { - my $rsp = {}; - $rsp->{error}->[0] = - "The $key2 file is empty. Remove it and rerun the command."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 1; + if (($flag ne "k") && ($flag ne "t") && ($flag ne "s")) { + my $rsp = {}; + $rsp->{error}->[0] = + "Invalid flag $flag provided."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 2; - } - if (($flag eq "k") && (!(-e $key))) - { - # updating keys and the key file does not exist - $rc=xCAT::RemoteShellExp->gensshkeys($expecttimeout); - } - # send ssh keys to the nodes/devices, to setup passwordless ssh - if ($flag eq "s") - { - if (!($nodes)) { - my $rsp = {}; - $rsp->{error}->[0] = - "There are no nodes defined to update the ssh keys."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 1; } - if ($ssh_setup_cmd) { # setup ssh on devices - $rc=xCAT::RemoteShellExp->senddeviceskeys($remoteshell,$remotecopy,$to_userid,$to_user_password,$home,$ssh_setup_cmd,$nodes, $expecttimeout); - } else { #setup ssh on nodes - if ($ENV{'DSH_ZONE_SSHKEYS'}) { # if using zones the override the location of the keys - $home= $ENV{'DSH_ZONE_SSHKEYS'}; - } - $rc=xCAT::RemoteShellExp->sendnodeskeys($remoteshell,$remotecopy,$to_userid,$to_user_password,$home,$nodes, $expecttimeout); - } - } - # test ssh setup on the node - if ($flag eq "t") - { - $rc=xCAT::RemoteShellExp->testkeys($remoteshell,$to_userid,$nodes,$expecttimeout); - } - return $rc; + my $expecttimeout = 10; # default + if (defined($timeout)) { # value supplied + $expecttimeout = $timeout; + } + + # for -s flag must have nodes and a $to_userid password + my $to_user_password; + if ($ENV{'DSH_REMOTE_PASSWORD'}) { + $to_user_password = $ENV{'DSH_REMOTE_PASSWORD'}; + } + if ($flag eq "s") { + if (!$to_user_password) { + my $rsp = {}; + $rsp->{error}->[0] = +"The DSH_REMOTE_PASSWORD environment variable has not been set to the user id password on the node which will have their ssh keys updated (ususally root)."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 2; + } + if (!$nodes) { + my $rsp = {}; + $rsp->{error}->[0] = + "No nodes were input to update the user's ssh keys."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 2; + } + } + my $ssh_setup_cmd; + my $from_userid; + my $to_userid; + my $home; + my $remotecopy; + + # if caller input a path to ssh remote command, use it + if ($ENV{'DSH_REMOTE_CMD'}) { + $remoteshell = $ENV{'DSH_REMOTE_CMD'}; + } else { + if (!$remoteshell) { + $remoteshell = "/usr/bin/ssh"; + } + } + + # figure out path to scp + my ($path, $ssh) = split(/ssh/, $remoteshell); + $remotecopy = $path . "scp"; + + # if caller input the ssh setup command (such as for IB Switch) + if ($ENV{'SSH_SETUP_COMMAND'}) { + $ssh_setup_cmd = $ENV{'SSH_SETUP_COMMAND'}; + } + + # set User on the Management node that has the ssh keys + # this id can be a local (non-root) id as well as root + if ($ENV{'DSH_FROM_USERID'}) { + $from_userid = $ENV{'DSH_FROM_USERID'}; + } else { + $from_userid = "root"; + } + + # set User on the node where we will send the keys + # this id can be a local id as well as root + if ($ENV{'DSH_TO_USERID'}) { + $to_userid = $ENV{'DSH_TO_USERID'}; + } else { + $to_userid = "root"; + } + + # set User home directory to find the ssh public key to send + # For non-root ids information may not be in /etc/passwd + # but elsewhere like LDAP + + if ($ENV{'DSH_FROM_USERID_HOME'}) { + $home = $ENV{'DSH_FROM_USERID_HOME'}; + } else { + $home = xCAT::Utils->getHomeDir($from_userid); + } + + # This indicates we will generate new ssh keys for the user, + # if they are not already there + # unless using zones + my $key = "$home/.ssh/id_rsa"; + my $key2 = "$home/.ssh/id_rsa.pub"; + + # Check to see if empty + if (-z $key) { + my $rsp = {}; + $rsp->{error}->[0] = + "The $key file is empty. Remove it and rerun the command."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 1; + + } + if (-z $key2) { + my $rsp = {}; + $rsp->{error}->[0] = + "The $key2 file is empty. Remove it and rerun the command."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 1; + + } + if (($flag eq "k") && (!(-e $key))) + { + # updating keys and the key file does not exist + $rc = xCAT::RemoteShellExp->gensshkeys($expecttimeout); + } + + # send ssh keys to the nodes/devices, to setup passwordless ssh + if ($flag eq "s") + { + if (!($nodes)) { + my $rsp = {}; + $rsp->{error}->[0] = + "There are no nodes defined to update the ssh keys."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 1; + } + if ($ssh_setup_cmd) { # setup ssh on devices + $rc = xCAT::RemoteShellExp->senddeviceskeys($remoteshell, $remotecopy, $to_userid, $to_user_password, $home, $ssh_setup_cmd, $nodes, $expecttimeout); + } else { #setup ssh on nodes + if ($ENV{'DSH_ZONE_SSHKEYS'}) { # if using zones the override the location of the keys + $home = $ENV{'DSH_ZONE_SSHKEYS'}; + } + $rc = xCAT::RemoteShellExp->sendnodeskeys($remoteshell, $remotecopy, $to_userid, $to_user_password, $home, $nodes, $expecttimeout); + } + } + + # test ssh setup on the node + if ($flag eq "t") + { + $rc = xCAT::RemoteShellExp->testkeys($remoteshell, $to_userid, $nodes, $expecttimeout); + } + return $rc; } #----------------------------------------------------------------------------- @@ -225,25 +235,25 @@ sub remoteshellexp #----------------------------------------------------------------------------- -sub gensshkeys +sub gensshkeys { my ($class, $expecttimeout) = @_; my $keygen; - my $timeout = $expecttimeout; # sets Expect default timeout, 0 accepts immediately + my $timeout = $expecttimeout; # sets Expect default timeout, 0 accepts immediately my $keygen_sent = 0; - my $prompt1 = 'Generating public/private rsa'; - my $prompt2 = 'Enter file.*:'; - my $prompt3 = 'Enter passphrase.*:'; - my $prompt4 = 'Enter same passphrase.*:'; - my $expect_log = undef; - my $debug = 0; + my $prompt1 = 'Generating public/private rsa'; + my $prompt2 = 'Enter file.*:'; + my $prompt3 = 'Enter passphrase.*:'; + my $prompt4 = 'Enter same passphrase.*:'; + my $expect_log = undef; + my $debug = 0; if ($::VERBOSE) { $debug = 1; } $keygen = new Expect; - + # run /usr/bin/ssh-keygen -t rsa # prompt1 = 'Generating public/private rsa'; # prompt2 = 'Enter file.*:'; @@ -274,53 +284,53 @@ sub gensshkeys my $spawncmd = "/usr/bin/ssh-keygen -t rsa"; unless ($keygen->spawn($spawncmd)) { - my $rsp = {}; - $rsp->{error}->[0] = - "Unable to run $spawncmd."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 1; + my $rsp = {}; + $rsp->{error}->[0] = + "Unable to run $spawncmd."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 1; } # - #ssh-keygen prompts starts here + #ssh-keygen prompts starts here # my @result = $keygen->expect( $timeout, [ - $prompt1, # Generating public/private rsa - sub { - $keygen->send("\r"); - $keygen->clear_accum(); - $keygen->exp_continue(); - } + $prompt1, # Generating public/private rsa + sub { + $keygen->send("\r"); + $keygen->clear_accum(); + $keygen->exp_continue(); + } ], [ - $prompt2, # Enter file.*: - sub { - $keygen->send("\r"); - $keygen->clear_accum(); - $keygen->exp_continue(); - } + $prompt2, # Enter file.*: + sub { + $keygen->send("\r"); + $keygen->clear_accum(); + $keygen->exp_continue(); + } ], [ - $prompt3, # Enter passphrase.* - sub { - $keygen->send("\r"); - $keygen->clear_accum(); - $keygen->exp_continue(); - } + $prompt3, # Enter passphrase.* + sub { + $keygen->send("\r"); + $keygen->clear_accum(); + $keygen->exp_continue(); + } ], [ - $prompt4, # Enter same passphrase. - sub { - $keygen->send("\r"); - $keygen->clear_accum(); - $keygen->exp_continue(); - } + $prompt4, # Enter same passphrase. + sub { + $keygen->send("\r"); + $keygen->clear_accum(); + $keygen->exp_continue(); + } ] - ); # end prompts + ); # end prompts ########################################## # Expect error - report and quit ########################################## @@ -328,20 +338,21 @@ sub gensshkeys { my $msg = $result[1]; $keygen->soft_close(); - if ($msg =~ /status 0/i) { # no error - return 0; + if ($msg =~ /status 0/i) { # no error + return 0; } else { - my $rsp = {}; - $rsp->{error}->[0] = $msg; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - return 1; + my $rsp = {}; + $rsp->{error}->[0] = $msg; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + return 1; } } else { - $keygen->soft_close(); - return 0; - } + $keygen->soft_close(); + return 0; + } } + #----------------------------------------------------------------------------- =head3 testkeys @@ -352,27 +363,28 @@ sub gensshkeys #----------------------------------------------------------------------------- -sub testkeys +sub testkeys { - my ($class,$remoteshell,$to_userid,$nodes, $expecttimeout) = @_; + my ($class, $remoteshell, $to_userid, $nodes, $expecttimeout) = @_; my $testkeys; - my $timeout = $expecttimeout; # sets Expect default timeout + my $timeout = $expecttimeout; # sets Expect default timeout my $testkeys_sent = 0; - my $prompt1 = 'Are you sure you want to continue connecting (yes/no)?'; - my $prompt2 = 'ssword:'; - my $prompt3 = 'Permission denied*'; - my $prompt4 = 'test.success'; - my $expect_log = undef; - my $debug = 0; - my $rc=1; # default to error + my $prompt1 = 'Are you sure you want to continue connecting (yes/no)?'; + my $prompt2 = 'ssword:'; + my $prompt3 = 'Permission denied*'; + my $prompt4 = 'test.success'; + my $expect_log = undef; + my $debug = 0; + my $rc = 1; # default to error + if ($::VERBOSE) { $debug = 1; } $testkeys = new Expect; - - # run ssh -l to_userid echo test.success + + # run ssh -l to_userid echo test.success # possible return # bad ## Are you sure you want to continue connecting (yes/no)? @@ -401,48 +413,48 @@ sub testkeys my $spawncmd = "$remoteshell $nodes -l $to_userid echo test.success"; unless ($testkeys->spawn($spawncmd)) { - my $rsp = {}; - $rsp->{error}->[0] = - "Unable to run $spawncmd."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - return 1; + my $rsp = {}; + $rsp->{error}->[0] = + "Unable to run $spawncmd."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + return 1; } # - #testkeys prompts starts here + #testkeys prompts starts here # my @result = $testkeys->expect( $timeout, [ - $prompt1, # Are you sure you want to ... - sub { - $rc= 1; - $testkeys->hard_close(); - } + $prompt1, # Are you sure you want to ... + sub { + $rc = 1; + $testkeys->hard_close(); + } ], [ - $prompt2, # *ssword* - sub { - $rc= 1; - $testkeys->hard_close(); - } + $prompt2, # *ssword* + sub { + $rc = 1; + $testkeys->hard_close(); + } ], [ - $prompt3, # Permission denied - sub { - $rc= 1; - $testkeys->hard_close(); - } + $prompt3, # Permission denied + sub { + $rc = 1; + $testkeys->hard_close(); + } ], [ - $prompt4, # test.success - sub { - $rc= 0; - } + $prompt4, # test.success + sub { + $rc = 0; + } ] - ); # end prompts + ); # end prompts ########################################## # Expect error - report and quit ########################################## @@ -450,20 +462,21 @@ sub testkeys { my $msg = $result[1]; $testkeys->soft_close(); - if ($msg =~ /status 0/i) { # no error - return 0; + if ($msg =~ /status 0/i) { # no error + return 0; } else { - my $rsp = {}; - $rsp->{error}->[0] = $msg; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - return 1; + my $rsp = {}; + $rsp->{error}->[0] = $msg; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + return 1; } } else { - $testkeys->soft_close(); - return $rc; - } + $testkeys->soft_close(); + return $rc; + } } + #------------------------------------------------------------------------------- =head3 sendnodeskeys @@ -474,299 +487,303 @@ sub testkeys #----------------------------------------------------------------------------- -sub sendnodeskeys +sub sendnodeskeys { - my ($class,$remoteshell,$remotecopy,$to_userid,$to_userpassword,$home,$nodes, $expecttimeout) = @_; + my ($class, $remoteshell, $remotecopy, $to_userid, $to_userpassword, $home, $nodes, $expecttimeout) = @_; my $sendkeys; - my $timeout = $expecttimeout; # sets Expect default timeout, 0 accepts immediately + my $timeout = $expecttimeout; # sets Expect default timeout, 0 accepts immediately my $sendkeys_sent = 0; - my $prompt1 = 'Are you sure you want to continue connecting (yes/no)?'; - my $prompt2 = 'ssword:'; - my $prompt3 = 'Permission denied*'; - my $expect_log = undef; - my $debug = 0; - my $rc=0; + my $prompt1 = 'Are you sure you want to continue connecting (yes/no)?'; + my $prompt2 = 'ssword:'; + my $prompt3 = 'Permission denied*'; + my $expect_log = undef; + my $debug = 0; + my $rc = 0; if ($::VERBOSE) { $debug = 1; } + # For each node # make a temporary directory on the node - # run scp -l /bin/mkdir -p /tmp/$to_userid/.ssh - # xdsh has built an authorized_keys file for the node - # in $HOME/.ssh/tmp/authorized_keys - # copy to the node to the temp directory + # run scp -l /bin/mkdir -p /tmp/$to_userid/.ssh + # xdsh has built an authorized_keys file for the node + # in $HOME/.ssh/tmp/authorized_keys + # copy to the node to the temp directory # scp $HOME/.ssh/tmp/authorized_keys to_userid@:/tmp/$to_userid/.ssh # scp $HOME/.ssh/id_rsa.pub to_userid@:/tmp/$to_userid/.ssh # Note if using zones, the keys do not come from ~/.ssh but from the # zone table, sshkeydir attribute. For zones the userid is always root # If you are going to enable ssh to ssh between nodes, then # scp $HOME/.ssh/id_rsa to that temp directory on the node - # copy the script $HOME/.ssh/copy.sh to the node, it will do the + # copy the script $HOME/.ssh/copy.sh to the node, it will do the # the work of setting up the user's ssh keys and clean up # ssh (run) copy.sh on the node - - my @nodelist=split(/,/,$nodes); + + my @nodelist = split(/,/, $nodes); foreach my $node (@nodelist) { - $sendkeys = new Expect; + $sendkeys = new Expect; - # disable command echoing - #$sendkeys->slave->stty(qw(sane -echo)); - # - # exp_internal(1) sets exp_internal debugging - # to STDERR. - # - #$sendkeys->exp_internal(1); - $sendkeys->exp_internal($debug); - # - # log_stdout(0) prevent the program's output from being shown. - # turn on if debugging error - #$sendkeys->log_stdout(1); - $sendkeys->log_stdout($debug); - - # command to make the temp directory on the node - my $spawnmkdir= - "$remoteshell $node -l $to_userid /bin/mkdir -p /tmp/$to_userid/.ssh"; - # command to copy the needed files to the node - - # send mkdir command - unless ($sendkeys->spawn($spawnmkdir)) - { - my $rsp = {}; - $rsp->{error}->[0] = - "Unable to run $spawnmkdir on $node"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - next; - } + # disable command echoing + #$sendkeys->slave->stty(qw(sane -echo)); + # + # exp_internal(1) sets exp_internal debugging + # to STDERR. + # + #$sendkeys->exp_internal(1); + $sendkeys->exp_internal($debug); + # + # log_stdout(0) prevent the program's output from being shown. + # turn on if debugging error + #$sendkeys->log_stdout(1); + $sendkeys->log_stdout($debug); - # - #mkdir prompts starts here - # + # command to make the temp directory on the node + my $spawnmkdir = + "$remoteshell $node -l $to_userid /bin/mkdir -p /tmp/$to_userid/.ssh"; - my @result = $sendkeys->expect( - $timeout, - [ - $prompt1, # Are you sure you want to ... - sub { - $sendkeys->send("yes\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt2, # *ssword* - sub { - $sendkeys->send("$to_userpassword\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt3, # Permission denied - sub { - $rc= 1; - $sendkeys->hard_close(); - } - ], - ); # end prompts - ########################################## - # Expect error - report - ########################################## - if (defined($result[1])) + # command to copy the needed files to the node + + # send mkdir command + unless ($sendkeys->spawn($spawnmkdir)) { - my $msg = $result[1]; - if ($msg =~ /status 0/i) { # no error - $rc=0; - } else { - if ($msg =~ /2:EOF/i) { # no error - $rc=0; - } else { - my $rsp = {}; - $rsp->{error}->[0] = "mkdir:$node has error,$msg"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - $rc=1; - } - } + my $rsp = {}; + $rsp->{error}->[0] = + "Unable to run $spawnmkdir on $node"; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + next; } - $sendkeys->soft_close(); - # - #copy files prompts starts here - # + # + #mkdir prompts starts here + # - $sendkeys = new Expect; - - # disable command echoing - #$sendkeys->slave->stty(qw(sane -echo)); - # - # exp_internal(1) sets exp_internal debugging - # to STDERR. - # - #$sendkeys->exp_internal(1); - $sendkeys->exp_internal($debug); - # - # log_stdout(0) prevent the program's output from being shown. - # turn on if debugging error - #$sendkeys->log_stdout(1); - $sendkeys->log_stdout($debug); - - my $spawncopyfiles; - if ($ENV{'DSH_ENABLE_SSH'}) { # we will enable node to node ssh - $spawncopyfiles= - "$remotecopy $home/.ssh/id_rsa $home/.ssh/id_rsa.pub $home/.ssh/copy.sh $home/.ssh/tmp/authorized_keys $to_userid\@$node:/tmp/$to_userid/.ssh"; - - } else { # no node to node ssh ( don't send private key) - $spawncopyfiles= - "$remotecopy $home/.ssh/id_rsa.pub $home/.ssh/copy.sh $home/.ssh/tmp/authorized_keys $to_userid\@$node:/tmp/$to_userid/.ssh"; - } - # send copy command - unless ($sendkeys->spawn($spawncopyfiles)) - { - my $rsp = {}; - $rsp->{error}->[0] = - "Unable to run $spawncopyfiles on $node."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - next; - } - - @result = $sendkeys->expect( - $timeout, - [ - $prompt1, # Are you sure you want to ... - sub { - $sendkeys->send("yes\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt2, # *ssword* - sub { - $sendkeys->send("$to_userpassword\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt3, # Permission denied - sub { - $rc= 1; - $sendkeys->hard_close(); - - } - ], - ); # end prompts + my @result = $sendkeys->expect( + $timeout, + [ + $prompt1, # Are you sure you want to ... + sub { + $sendkeys->send("yes\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt2, # *ssword* + sub { + $sendkeys->send("$to_userpassword\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt3, # Permission denied + sub { + $rc = 1; + $sendkeys->hard_close(); + } + ], + ); # end prompts ########################################## - # Expect error - report + # Expect error - report ########################################## if (defined($result[1])) { my $msg = $result[1]; - if ($msg =~ /status 0/i) { # no error - $rc=0; + if ($msg =~ /status 0/i) { # no error + $rc = 0; } else { - if ($msg =~ /2:EOF/i) { # no error - $rc=0; - } else { - my $rsp = {}; - $rsp->{error}->[0] = "copykeys:$node has error,$msg"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - $rc=1; - } + if ($msg =~ /2:EOF/i) { # no error + $rc = 0; + } else { + my $rsp = {}; + $rsp->{error}->[0] = "mkdir:$node has error,$msg"; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + $rc = 1; + } } } $sendkeys->soft_close(); - # - # ssh to the node to run the copy.sh to setup the keys starts here - # - $sendkeys = new Expect; + # + #copy files prompts starts here + # - # disable command echoing - #$sendkeys->slave->stty(qw(sane -echo)); - # - # exp_internal(1) sets exp_internal debugging - # to STDERR. - # - #$sendkeys->exp_internal(1); - $sendkeys->exp_internal($debug); - # - # log_stdout(0) prevent the program's output from being shown. - # turn on if debugging error - #$sendkeys->log_stdout(1); - $sendkeys->log_stdout($debug); - - # command to run copy.sh - my $spawnruncopy= - "$remoteshell $node -l $to_userid /tmp/$to_userid/.ssh/copy.sh"; - - # send mkdir command - unless ($sendkeys->spawn($spawnruncopy)) - { - my $rsp = {}; - $rsp->{error}->[0] = - "Unable to run $spawnruncopy."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - next; # go to next node + $sendkeys = new Expect; - } + # disable command echoing + #$sendkeys->slave->stty(qw(sane -echo)); + # + # exp_internal(1) sets exp_internal debugging + # to STDERR. + # + #$sendkeys->exp_internal(1); + $sendkeys->exp_internal($debug); + # + # log_stdout(0) prevent the program's output from being shown. + # turn on if debugging error + #$sendkeys->log_stdout(1); + $sendkeys->log_stdout($debug); - # - #run copy.sh prompts starts here - # + my $spawncopyfiles; + if ($ENV{'DSH_ENABLE_SSH'}) { # we will enable node to node ssh + $spawncopyfiles = +"$remotecopy $home/.ssh/id_rsa $home/.ssh/id_rsa.pub $home/.ssh/copy.sh $home/.ssh/tmp/authorized_keys $to_userid\@$node:/tmp/$to_userid/.ssh"; + + } else { # no node to node ssh ( don't send private key) + $spawncopyfiles = +"$remotecopy $home/.ssh/id_rsa.pub $home/.ssh/copy.sh $home/.ssh/tmp/authorized_keys $to_userid\@$node:/tmp/$to_userid/.ssh"; + } + + # send copy command + unless ($sendkeys->spawn($spawncopyfiles)) + { + my $rsp = {}; + $rsp->{error}->[0] = + "Unable to run $spawncopyfiles on $node."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + next; + } @result = $sendkeys->expect( - $timeout, - [ - $prompt1, # Are you sure you want to ... - sub { - $sendkeys->send("yes\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt2, # *ssword* - sub { - $sendkeys->send("$to_userpassword\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt3, # Permission denied - sub { - $rc= 1; - $sendkeys->hard_close(); - } - ], - ); # end prompts + $timeout, + [ + $prompt1, # Are you sure you want to ... + sub { + $sendkeys->send("yes\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt2, # *ssword* + sub { + $sendkeys->send("$to_userpassword\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt3, # Permission denied + sub { + $rc = 1; + $sendkeys->hard_close(); + + } + ], + ); # end prompts ########################################## - # Expect error - report + # Expect error - report ########################################## if (defined($result[1])) { my $msg = $result[1]; - if ($msg =~ /status 0/i) { # no error - $rc=0; + if ($msg =~ /status 0/i) { # no error + $rc = 0; } else { - if ($msg =~ /2:EOF/i) { # no error - $rc=0; - } else { - my $rsp = {}; - $rsp->{error}->[0] = "copy.sh:$node has error,$msg"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - $rc=1; - } + if ($msg =~ /2:EOF/i) { # no error + $rc = 0; + } else { + my $rsp = {}; + $rsp->{error}->[0] = "copykeys:$node has error,$msg"; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + $rc = 1; + } } } - $sendkeys->soft_close(); + $sendkeys->soft_close(); + + # + # ssh to the node to run the copy.sh to setup the keys starts here + # + $sendkeys = new Expect; + + # disable command echoing + #$sendkeys->slave->stty(qw(sane -echo)); + # + # exp_internal(1) sets exp_internal debugging + # to STDERR. + # + #$sendkeys->exp_internal(1); + $sendkeys->exp_internal($debug); + # + # log_stdout(0) prevent the program's output from being shown. + # turn on if debugging error + #$sendkeys->log_stdout(1); + $sendkeys->log_stdout($debug); + + # command to run copy.sh + my $spawnruncopy = + "$remoteshell $node -l $to_userid /tmp/$to_userid/.ssh/copy.sh"; + + # send mkdir command + unless ($sendkeys->spawn($spawnruncopy)) + { + my $rsp = {}; + $rsp->{error}->[0] = + "Unable to run $spawnruncopy."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + next; # go to next node + + } + + # + #run copy.sh prompts starts here + # + + @result = $sendkeys->expect( + $timeout, + [ + $prompt1, # Are you sure you want to ... + sub { + $sendkeys->send("yes\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt2, # *ssword* + sub { + $sendkeys->send("$to_userpassword\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt3, # Permission denied + sub { + $rc = 1; + $sendkeys->hard_close(); + } + ], + ); # end prompts + ########################################## + # Expect error - report + ########################################## + if (defined($result[1])) + { + my $msg = $result[1]; + if ($msg =~ /status 0/i) { # no error + $rc = 0; + } else { + if ($msg =~ /2:EOF/i) { # no error + $rc = 0; + } else { + my $rsp = {}; + $rsp->{error}->[0] = "copy.sh:$node has error,$msg"; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + $rc = 1; + } + } + } + $sendkeys->soft_close(); - } # end foreach node - return $rc; + } # end foreach node + return $rc; } + #------------------------------------------------------------------------------- =head3 senddeviceskeys @@ -777,130 +794,133 @@ sub sendnodeskeys #----------------------------------------------------------------------------- -sub senddeviceskeys +sub senddeviceskeys { - my ($class,$remoteshell,$remotecopy,$to_userid,$to_userpassword,$home,$ssh_setup_cmd,$nodes, $expecttimeout) = @_; + my ($class, $remoteshell, $remotecopy, $to_userid, $to_userpassword, $home, $ssh_setup_cmd, $nodes, $expecttimeout) = @_; my $sendkeys; - my $timeout = $expecttimeout; # sets Expect default timeout, 0 accepts immediately + my $timeout = $expecttimeout; # sets Expect default timeout, 0 accepts immediately my $sendkeys_sent = 0; - my $prompt1 = 'Are you sure you want to continue connecting (yes/no)?'; - my $prompt2 = 'ssword:'; - my $prompt3 = 'Permission denied*'; - my $expect_log = undef; - my $debug = 0; - my $rc=0; + my $prompt1 = 'Are you sure you want to continue connecting (yes/no)?'; + my $prompt2 = 'ssword:'; + my $prompt3 = 'Permission denied*'; + my $expect_log = undef; + my $debug = 0; + my $rc = 0; if ($::VERBOSE) { $debug = 1; } - + # quote the setup command and key "sshKey add \"slave->stty(qw(sane -echo)); - # - # exp_internal(1) sets exp_internal debugging - # to STDERR. - # - #$sendkeys->exp_internal(1); - $sendkeys->exp_internal($debug); - # - # log_stdout(0) prevent the program's output from being shown. - # turn on if debugging error - #$sendkeys->log_stdout(1); - $sendkeys->log_stdout($debug); - - # command to send key to the device - # sshKey add "key" - my $spawnaddkey= - "$remoteshell $node -l $to_userid $setupcmd"; - - # send mkdir command - unless ($sendkeys->spawn($spawnaddkey)) - { - my $rsp = {}; - $rsp->{error}->[0] = - "Unable to run $spawnaddkey."; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); - next; # go to next node + # disable command echoing + #$sendkeys->slave->stty(qw(sane -echo)); + # + # exp_internal(1) sets exp_internal debugging + # to STDERR. + # + #$sendkeys->exp_internal(1); + $sendkeys->exp_internal($debug); + # + # log_stdout(0) prevent the program's output from being shown. + # turn on if debugging error + #$sendkeys->log_stdout(1); + $sendkeys->log_stdout($debug); - } + # command to send key to the device + # sshKey add "key" + my $spawnaddkey = + "$remoteshell $node -l $to_userid $setupcmd"; - # - #run copy.sh prompts starts here - # + # send mkdir command + unless ($sendkeys->spawn($spawnaddkey)) + { + my $rsp = {}; + $rsp->{error}->[0] = + "Unable to run $spawnaddkey."; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK, 1); + next; # go to next node - my @result = $sendkeys->expect( - $timeout, - [ - $prompt1, # Are you sure you want to ... - sub { - $sendkeys->send("yes\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt2, # *ssword* - sub { - $sendkeys->send("$to_userpassword\r"); - $sendkeys->clear_accum(); - $sendkeys->exp_continue(); - } - ], - [ - $prompt3, # Permission denied - sub { - $rc= 1; - $sendkeys->soft_close(); - next; # go to next node - } - ], - ); # end prompts + } + + # + #run copy.sh prompts starts here + # + + my @result = $sendkeys->expect( + $timeout, + [ + $prompt1, # Are you sure you want to ... + sub { + $sendkeys->send("yes\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt2, # *ssword* + sub { + $sendkeys->send("$to_userpassword\r"); + $sendkeys->clear_accum(); + $sendkeys->exp_continue(); + } + ], + [ + $prompt3, # Permission denied + sub { + $rc = 1; + $sendkeys->soft_close(); + next; # go to next node + } + ], + ); # end prompts ########################################## - # Expect error - report + # Expect error - report ########################################## if (defined($result[1])) { my $msg = $result[1]; - if ($msg =~ /status 0/i) { # no error - $rc=0; + if ($msg =~ /status 0/i) { # no error + $rc = 0; } else { - my $rsp = {}; - $rsp->{error}->[0] = "$node has error,$msg"; - xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); - $rc=1; - next; # go to next node + my $rsp = {}; + $rsp->{error}->[0] = "$node has error,$msg"; + xCAT::MsgUtils->message("E", $rsp, $::CALLBACK); + $rc = 1; + next; # go to next node } } - $sendkeys->soft_close(); - } # end foreach node + $sendkeys->soft_close(); + } # end foreach node return $rc; } 1; diff --git a/perl-xCAT/xCAT/SINV.pm b/perl-xCAT/xCAT/SINV.pm index 2df6d6420..51852c4cd 100644 --- a/perl-xCAT/xCAT/SINV.pm +++ b/perl-xCAT/xCAT/SINV.pm @@ -16,9 +16,10 @@ the sinv command. #------------------------------------------------------------------------------ package xCAT::SINV; + BEGIN { - $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; + $::XCATROOT = $ENV{'XCATROOT'} ? $ENV{'XCATROOT'} : -d '/opt/xcat' ? '/opt/xcat' : '/usr'; } use strict; use xCAT::MsgUtils; @@ -27,6 +28,7 @@ use xCAT::NodeRange qw/noderange abbreviate_noderange/; use xCAT::Utils; use Fcntl qw(:flock); use Getopt::Long; + #use Data::Dumper; my $tempfile; my $errored = 0; @@ -54,14 +56,14 @@ sub usage ## usage message my $usagemsg1 = - "The sinv command is designed to check the configuration of nodes in a cluster.\nRun man sinv for more information.\n\nInput parameters are as follows:\n"; +"The sinv command is designed to check the configuration of nodes in a cluster.\nRun man sinv for more information.\n\nInput parameters are as follows:\n"; my $usagemsg1a = "sinv -h \nsinv -v \nsinv"; - my $usagemsg3 = + my $usagemsg3 = " -p