Wednesday 18 May 2016

Shell script to control Tomcat instances using PE MCollective

This is a script building on the previous post describing how to run remote commands from puppet master using mcollective.

The script uses the mco command to control Tomcat.
this can be called by either jenkins or rundeck to automate starting and stopping tomcat.

The motive behind making this is 2 fold:
1- There is no simple way to restart nodes in puppet, you need to change puppet code and run puppet agent multiple times to achieve this.

2- In my case, using puppet for recycling Tomcat relies on using init scripts, this doesn't set a current working directory and causes issues to the apps deployed in my Tomcat, so i need to always use the tcruntime from bin directory to have the PWD set correctly.

The script manages to achieve this and still is inline with my puppet strategy.

[root@vardamir]# cat restart_tc_mco.sh
for OPT in $*
do
        #echo ${OPT}
        #Look for the taget env
        if [ -n "`echo ${OPT}|grep  'env='`" ]
        then
                #echo ${OPT}
                ENV=`echo ${OPT}|cut -d"=" -f2`
                #echo  ${ENV}

        #look for the TC instance_name
        elif [ -n "`echo ${OPT}|grep 'tc='`" ]
        then
                TC_NAME_LIST=`echo ${OPT}|cut -d"=" -f2`
                #echo ${WAR}

        else
                echo "Worng command line parameters"

        fi
done

DEPLOY_DESC=/apps/topo/deploy_topology_${ENV}.dat

for TC_NAME in `echo ${TC_NAME_LIST}|tr "," " "`
do

    for NODE in `cat $DEPLOY_DESC|grep -v "^#"|grep ${TC_NAME}|cut -d":" -f2`
    do
        echo "Restarting TC ${TC_NAME} on Node ${NODE}"
        #Lots of escaping done to have this work:
   
        echo "mco puppet resource exec tc_restart command=""\"/bin/su - tomcat -c \\""\"""cd /apps/vfabric-tc-server-standard-2.9.2.RELEASE/${TC_NAME}/bin;./tcruntime-ctl.sh restart""\\\" \""" -I ${NODE}" >/tmp/tc_restart.sh

        su - peadmin -c "bash /tmp/tc_restart.sh"
        #echo ${NODE} ${TC_NAME}
    done
done


The script starts with setting up a couple of parametes, an env and a list of comma separated TC instances.

Then the script uses a topology file to link which node has which TC.
Once we know the TC instance name and the node we can construct the mco command and then run it with peadmin user as above.

the echo to generate the mco command is actually working by utilizing multiple string outputs that are stacked one after the other and pushed to a file which is executed by peadmin using su -  (assuming root runs the command ).


No comments:

Post a Comment