#!/bin/bash

#######################################################################
#
# Linux on Hyper-V and Azure Test Code, ver. 1.0.0
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
# Licensed under the Apache License, Version 2.0 (the ""License"");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#
#######################################################################

#######################################################################
#
#
#
# Description:
#######################################################################

#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments

while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

master=$master
slaves=$slaves

#
# Constants/Globals
#
CONSTANTS_FILE="/root/constants.sh"
ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # Error during the setup of the test
ICA_TESTFAILED="TestFailed"        # Error occurred during the test
CurrentMachine=""
#######################################################################
#
# LogMsg()
#
#######################################################################
LogMsg()
{
    echo `date "+%b %d %Y %T"` : "${1}"    # Add the time stamp to the log message
    echo "${1}" >> ~/rdmaPreparation.log
}

UpdateTestState()
{
    echo "${1}" > ~/state.txt
}

PrepareForRDMA()
{
	ssh root@${1} "test -e etcHostsEditedSuccessfully"
	if [ $? -ne 0 ]; then
		LogMsg "${1} : Editing /etc/hosts"
		scp etc-hosts.txt root@${1}:
		ssh root@${1} "cat etc-hosts.txt >> /etc/hosts"
		if [ $? -ne 0 ]; then
			LogMsg "${1} : Unable to edit /etc/hosts."
			UpdateTestState $ICA_TESTFAILED
			exit 1
		fi
	fi
	ssh root@${1} touch etcHostsEditedSuccessfully

	LogMsg "${1} : Installing RDMA package..."
	ssh root@${1} yum -y install rdma
	if [ $? -ne 0 ]; then
		LogMsg "${1} : Unable to install RDMA package."
		UpdateTestState $ICA_TESTFAILED
		exit 1
	fi
	LogMsg "${1} : Enabling RDMA..."
	ssh root@${1} chkconfig rdma on
	if [ $? -ne 0 ]; then
		LogMsg "${1} : Unable to enable RDMA"
		UpdateTestState $ICA_TESTFAILED
		exit 1
	fi

	LogMsg "${1} : Installing required packages..."
	ssh root@${1} yum install -y libmlx4 libibverbs librdmacm
	if [ $? -ne 0 ]; then
		LogMsg "${1} : Unable to install some packges."
		UpdateTestState $ICA_TESTFAILED
		exit 1
	fi
	LogMsg "${1} : Installing dapl..."
	ssh root@${1} yum install -y dapl
	if [ $? -ne 0 ]; then
		LogMsg "${1} : Unable to install some packges."
		UpdateTestState $ICA_TESTFAILED
		exit 1
	fi

	LogMsg "${1} : Installing IBM binaries.."
	ssh root@${1} test -e platform_mpi-09.01.02.00u.x64.bin
	if [ $? -eq 0 ]; then
		LogMsg "${1} : IBM binary already exists."
	else
		LogMsg "${1} : Downloading https://ciwestus.blob.core.windows.net/linuxbinaries/platform_mpi-09.01.02.00u.x64.bin..."
		ssh root@${1} wget -q https://ciwestus.blob.core.windows.net/linuxbinaries/platform_mpi-09.01.02.00u.x64.bin
		if [ $? -ne 0 ]; then
			LogMsg "${1} : Unable to download platform_mpi-09.01.02.00u.x64.bin"
			UpdateTestState $ICA_TESTFAILED
			exit 1
		fi
	fi

	ssh root@${1} test -e /opt/ibm/platform_mpi/bin/mpirun
	if [ $? -eq 0 ]; then
		LogMsg "${1} : IBM binaries already installed"
	else
		ssh root@${1} chmod +x platform_mpi-09.01.02.00u.x64.bin
		LogMsg "${1} : Installing prerequisites..."
		ssh root@${1} yum -y install gcc-c++
		ssh root@${1} yum -y install libgcc.i686
		ssh root@${1} yum -y install glibc.i686
		ssh root@${1} yum -y install libstdc++-4.8.5-4.el7.i686
		ssh root@${1} yum -y install redhat-lsb redhat-lsb*i686
		LogMsg "${1} : Installing platform_mpi-09.01.02.00u.x64.bin..."
		ssh root@${1} ./platform_mpi-09.01.02.00u.x64.bin -i silent
		if [ $? -ne 0 ]; then
			LogMsg "${1} : Unable to install platform_mpi-09.01.02.00u.x64.bin"
			UpdateTestState $ICA_TESTFAILED
			exit 1
		fi
		LogMsg "${1} : IBM binaries installed."
	fi

	LogMsg "${1} : Installing Intel MPI binaries on ${1}.."
	ssh root@${1} test -e l_mpi_p_5.1.3.181.tgz
	if [ $? -eq 0 ]; then
		LogMsg "${1} : binary already exists."
	else
		LogMsg "${1} : Downloading https://ciwestus.blob.core.windows.net/linuxbinaries/l_mpi_p_5.1.3.181.tgz..."
		ssh root@${1} wget -q https://ciwestus.blob.core.windows.net/linuxbinaries/l_mpi_p_5.1.3.181.tgz
		if [ $? -ne 0 ]; then
			LogMsg "${1} : Unable to download l_mpi_p_5.1.3.181.tgz"
			UpdateTestState $ICA_TESTFAILED
			exit 1
		fi
	fi
	ssh root@${1} test -d /opt/intel/impi
	if [ $? -eq 0 ]; then
		LogMsg "${1} : Intel binaries already installed."
	else

		ssh root@${1} tar -xvzf l_mpi_p_5.1.3.181.tgz
		ssh root@${1} sed -i '/ACCEPT_EULA/c\ACCEPT_EULA=accept' ./l_mpi_p_5.1.3.181/silent.cfg
		ssh root@${1} sed -i '/ACTIVATION_TYPE/c\ACTIVATION_TYPE=trial_lic' ./l_mpi_p_5.1.3.181/silent.cfg
		LogMsg "${1} : Installing l_mpi_p_5.1.3.181..."
		ssh root@${1} ./l_mpi_p_5.1.3.181/install.sh --silent ./l_mpi_p_5.1.3.181/silent.cfg
		if [ $? -ne 0 ]; then
			LogMsg "${1} : Unable to install Intel MPI binaries."
			cd /root
			UpdateTestState $ICA_TESTFAILED
			exit 1
		fi
		LogMsg "${1} : Intel binaries installed."
	fi
	LogMsg "${1} : Setting up nfs..."
	ssh root@${1} yum -y install nfs-utils.x86_64
	ssh root@${1} mkdir -p /mirror
	ssh root@${1} chmod -R 777 /mirror/
	#ssh root@${1} test -e limits.conf.editedSuccessfully
	#if [ $? -ne 0 ]; then
	#	LogMsg "${1} : Editing /etc/security/limits.conf"
	#	echo "* hard    memlock unlimited" | ssh root@${1} "cat >> /etc/security/limits.conf"
	#	echo "* soft    memlock unlimited" | ssh root@${1} "cat >> /etc/security/limits.conf"
	#	if [ $? -ne 0 ]; then
	#		LogMsg "${1} : Unable to edit /etc/security/limits.conf"
	#		UpdateTestState $ICA_TESTFAILED
	#		exit 1
	#	fi
	#fi
	#ssh root@${1} touch limits.conf.editedSuccessfully

	ssh root@${1} rm -rf /etc/exports
	echo '/mirror *(rw,sync)' | ssh root@${1} "cat >> /etc/exports"

	ssh root@${1} systemctl enable rpcbind
	ssh root@${1} systemctl enable nfs-server
	ssh root@${1} systemctl start rpcbind
	ssh root@${1} systemctl start nfs-server
	ssh root@${1} systemctl start nfs-lock
	ssh root@${1} systemctl start nfs-idmap

	ssh root@${1} touch rdmaPrepared
}

rm -f ~/summary.log
touch ~/summary.log

if [ -e ${CONSTANTS_FILE} ]; then
    source ${CONSTANTS_FILE}
else
    errMsg="Error: missing ${CONSTANTS_FILE} file"
    LogMsg "${errMsg}"
    echo "${errMsg}" >> ~/summary.log
    UpdateTestState $ICA_TESTABORTED
    exit 10
fi

if [ "${installLocal}" != "yes" ]; then
	if [ ! ${master} ]; then
		errMsg="Please add/provide value for master in constants.sh. master=<Master VM hostname>"
		LogMsg "${errMsg}"
		echo "${errMsg}" >> ~/summary.log
		UpdateTestState $ICA_TESTABORTED
		exit 1
	fi
	if [ ! ${slaves} ]; then
		errMsg="Please add/provide value for slaves in constants.sh. slaves=<hostname1,hostname2,hostname3>"
		LogMsg "${errMsg}"
		echo "${errMsg}" >> ~/summary.log
		UpdateTestState $ICA_TESTABORTED
		exit 1
	fi
fi

if [ "${rdmaPrepare}" != "yes" ] && [ "${rdmaPrepare}" != "no" ]; then
	errMsg="Please add/provide value for rdmaPrepare in constants.sh. rdmaPrepare=<yes>/<no>"
    LogMsg "${errMsg}"
    echo "${errMsg}" >> ~/summary.log
	UpdateTestState $ICA_TESTABORTED
	exit 1
fi
if [ "${rdmaRun}" != "yes" ] && [ "${rdmaRun}" != "no" ]; then
	errMsg="Please add/provide value for rdmaRun in constants.sh. rdmaRun=<yes>/<no>"
    LogMsg "${errMsg}"
    echo "${errMsg}" >> ~/summary.log
	UpdateTestState $ICA_TESTABORTED
	exit 1
fi

slavesArr=`echo ${slaves} | tr ',' ' '`

if [ "${rdmaPrepare}" == "yes" ]; then

	# master VM preparation for RDMA tests...

	if [ ${installLocal} == "yes" ]; then
		localVM=`hostname`
		ssh root@${localVM} test -e rdmaPrepared
		if [ $? -ne 0 ]; then
			LogMsg "Info : Running config on current machine : '${localVM}'"
			PrepareForRDMA "${localVM}"
		else
			LogMsg "${localVM} is already prepared for RDMA tests."
		fi
	else
		ssh root@${master} test -e rdmaPrepared
		if [ $? -ne 0 ]; then
			LogMsg "Info : Running config on master : '${master}'"
			PrepareForRDMA "${master}"
		else
			LogMsg "${master} is already prepared for RDMA tests."
		fi

		# slave VMs preparation for RDMA tests...
		for slave in $slavesArr
		do
			ssh root@${slave} test -e rdmaPrepared
			if [ $? -ne 0 ]; then
				LogMsg "Info : Running config on slave '${slave}'"
				PrepareForRDMA "${slave}"
				LogMsg "Info : mounting ${master}:/mirror NFS directory to /mirror on '${slave}'"
				ssh root@${slave} mount ${master}:/mirror /mirror
			else
				LogMsg "${slave} is already prepared for RDMA tests."
			fi
		done
	fi
else
	LogMsg "Info : Skipping RDMA preparation. (Source : constants.sh)"
fi

if [ "${rdmaRun}" == "yes" ];
then
	mpirunPath=`find / -name mpirun | grep intel64`
	imb_mpi1Path=`find / -name IMB-MPI1 | grep intel64`
	eth1server=`ifconfig eth1 | grep "inet "`
	eth1ServerStatus=$?
	eth1client=`ssh root@${slaves} "ifconfig eth1 | grep 'inet '"`
	eth1ClientStatus=$?
	eth1Status=$(( $eth1ServerStatus + $eth1ClientStatus ))
	if [ $eth1Status -eq 0 ];
	then
		LogMsg "eth1 IP detected for server and client."
	else
		LogMsg "Error: eth1 failed to get IP address."
		LogMsg "Checking if NetworkManager is running..."
		service NetworkManager status
		if [ $? -eq 0 ]; then
			LogMsg "Info: NetworkManager is running. Stopping it."
			service NetworkManager stop
			sleep 5
			ssh root@${slaves} "service NetworkManager stop"
			sleep 5
			LogMsg "Info: restart waagent service..."
			service waagent restart
			sleep 5
			service waagent restart
			ssh root@${slaves} "service waagent restart"
			sleep 5
		fi
	fi
	LogMsg "Executing test command : ${mpirunPath} -hosts ${master},${slaves} -ppn 2 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 ${imb_mpi1Path} pingpong > pingPongTestIntraNodeTestOut.txt 2>&1"
	#MPI-pingpong intra node
	$mpirunPath -hosts ${master} -ppn 2 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 $imb_mpi1Path pingpong > pingPongTestIntraNodeTestOut.txt 2>&1
	mpiStatus1=$?
	sleep 20
	#MPI-pingpong inter node
	LogMsg "Executing test command : $mpirunPath -hosts ${master},${slaves} -ppn 1 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 $imb_mpi1Path pingpong > pingPongTestInterNodeTestOut.txt 2>&1"
	$mpirunPath -hosts ${master},${slaves} -ppn 1 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 $imb_mpi1Path pingpong > pingPongTestInterNodeTestOut.txt 2>&1
	mpiStatus2=$?
	finalStatus=$(( $eth1Status + $mpiStatus1 + $mpiStatus2 ))
	if [ $finalStatus -ne 0 ];
	then
		errMsg="Failures detected. eth1 Status: $eth1Status, IntraNodeTestStatus: $mpiStatus1, InterNodeTestStatus: $mpiStatus2"
		LogMsg "${errMsg}"
		echo "${errMsg}" >> ~/summary.log
		UpdateTestState $ICA_TESTFAILED
		exit 1
	else
		UpdateTestState $ICA_TESTCOMPLETED
		LogMsg "eth1 Status: $eth1Status, IntraNodeTestStatus: $mpiStatus1, InterNodeTestStatus: $mpiStatus2"
	fi
fi


#!/bin/bash

#######################################################################
#
# Linux on Hyper-V and Azure Test Code, ver. 1.0.0
# Copyright (c) Microsoft Corporation
#
# All rights reserved.
# Licensed under the Apache License, Version 2.0 (the ""License"");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#     http://www.apache.org/licenses/LICENSE-2.0
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR
# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
#
# See the Apache Version 2.0 License for specific language governing
# permissions and limitations under the License.
#
#######################################################################

#######################################################################
#
#
#
# Description:
#######################################################################

#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments

while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

master=$master
slaves=$slaves
rm -rf /root/TestRDMALogs.txt
#
# Constants/Globals
#
CONSTANTS_FILE="/root/constants.sh"
ICA_TESTRUNNING="TestRunning"      # The test is running
ICA_TESTCOMPLETED="TestCompleted"  # The test completed successfully
ICA_TESTABORTED="TestAborted"      # Error during the setup of the test
ICA_TESTFAILED="TestFailed"        # Error occurred during the test
CurrentMachine=""
imb_mpi1_finalStatus=0
imb_rma_finalStatus=0
imb_nbc_finalStatus=0
#######################################################################
#
# LogMsg()
#
#######################################################################
LogMsg()
{
    timeStamp=`date "+%b %d %Y %T"`
    echo "$timeStamp : ${1}"    # Add the time stamp to the log message
    echo "$timeStamp : ${1}" >> /root/TestRDMALogs.txt
}

UpdateTestState()
{
    echo "${1}" > /root/state.txt
}

PrepareForRDMA()
{
        # TODO
        echo Doing Nothing
}
#Get all the Kernel-Logs from all VMs.
CollectKernelLogs()
{
    slavesArr=`echo ${slaves} | tr ',' ' '`
    for vm in $master $slavesArr
    do
                    LogMsg "Getting kernel logs from $vm"
                    ssh root@${vm} "dmesg > kernel-logs-${vm}.txt"
                    scp root@${vm}:kernel-logs-${vm}.txt .
                    if [ $? -eq 0 ];
                    then
                                    LogMsg "Kernel Logs collected successfully from ${vm}."
                    else
                                    LogMsg "Error: Failed to collect kernel logs from ${vm}."
                    fi

    done
}

CompressFiles()
{
    compressedFileName=$1
    pattern=$2
    LogMsg "Compressing ${pattern} files into ${compressedFileName}"
    tar -cvzf ${compressedFileName} ${pattern}*
    if [ $? -eq 0 ];
    then
            LogMsg "${pattern}* files compresssed successfully."
            LogMsg "Deleting local copies of ${pattern}* files"
            rm -rvf ${pattern}*
    else
            LogMsg "Error: Failed to compress files."
            LogMsg "Don't worry. Your files are still here."
    fi
}

if [ -e ${CONSTANTS_FILE} ]; then
    source ${CONSTANTS_FILE}
else
    errMsg="Error: missing ${CONSTANTS_FILE} file"
    LogMsg "${errMsg}"
    UpdateTestState $ICA_TESTABORTED
    exit 10
fi

slavesArr=`echo ${slaves} | tr ',' ' '`
mpirunPath=`find / -name mpirun | grep intel64`
LogMsg "MPIRUN Path: $mpirunPath"
imb_mpi1Path=`find / -name IMB-MPI1 | grep intel64`
LogMsg "IMB-MPI1 Path: $imb_mpi1Path"
imb_rmaPath=`find / -name IMB-RMA | grep intel64`
LogMsg "IMB-RMA Path: $imb_rmaPath"
imb_nbcPath=`find / -name IMB-NBC | grep intel64`
LogMsg "IMB-NBC Path: $imb_nbcPath"

#Verify if eth1 got IP address on All VMs in current cluster.
finaleth1Status=0
totalVMs=0
slavesArr=`echo ${slaves} | tr ',' ' '`
for vm in $master $slavesArr
do
                LogMsg "Checking eth1 status in $vm"
                temp=`ssh root@${vm} "ifconfig eth1 | grep 'inet '"`
                eth1Status=$?
                ssh root@${vm} "ifconfig eth1 > eth1-status-${vm}.txt"
                scp root@${vm}:eth1-status-${vm}.txt .
                if [ $eth1Status -eq 0 ];
                then
                                LogMsg "eth1 IP detected for ${vm}."
                else
                                LogMsg "Error: eth1 failed to get IP address for ${vm}."
                fi
                finaleth1Status=$(( $finaleth1Status + $eth1Status ))
                totalVMs=$(( $totalVMs + 1 ))
done
if [ $finaleth1Status -ne 0 ]; then
                LogMsg "ERROR: Some VMs did get IP address for eth1. Aborting Tests"
                UpdateTestState $ICA_TESTFAILED
                CollectKernelLogs
                LogMsg "INFINIBAND_VERIFICATION_FAILED_ETH1"
                exit 0
else
                LogMsg "INFINIBAND_VERIFICATION_SUCCESS_ETH1"
fi

##Verify MPI Tests

#Verify PingPong Tests (IntraNode).
finalMpiIntranodeStatus=0
slavesArr=`echo ${slaves} | tr ',' ' '`
for vm in $master $slavesArr
do
                LogMsg "$mpirunPath -hosts $vm -ppn $mpi1_ppn -n $mpi1_ppn $mpi_settings $imb_mpi1Path pingpong"
                LogMsg "Checking IMB-MPI1 Intranode status in $vm"
                ssh root@${vm} "$mpirunPath -hosts $vm -ppn $mpi1_ppn -n $mpi1_ppn $mpi_settings $imb_mpi1Path pingpong > IMB-MPI1-IntraNode-pingpong-output-$vm.txt"
                mpiIntranodeStatus=$?
                scp root@${vm}:IMB-MPI1-IntraNode-pingpong-output-$vm.txt .
                if [ $mpiIntranodeStatus -eq 0 ];
                then
                                LogMsg "IMB-MPI1 Intranode status in $vm - Succeeded."
                else
                                LogMsg "IMB-MPI1 Intranode status in $vm - Failed"
                fi
                finalMpiIntranodeStatus=$(( $finalMpiIntranodeStatus + $mpiIntranodeStatus ))
done

if [ $finalMpiIntranodeStatus -ne 0 ]; then
                LogMsg "ERROR: IMB-MPI1 Intranode test failed in somes VMs. Aborting further tests."
                UpdateTestState $ICA_TESTFAILED
                CollectKernelLogs
                LogMsg "INFINIBAND_VERIFICATION_FAILED_MPI1_INTRANODE"
                exit 0
else
                LogMsg "INFINIBAND_VERIFICATION_SUCCESS_MPI1_INTRANODE"
fi

#Verify PingPong Tests (InterNode).
finalMpiInternodeStatus=0
slavesArr=`echo ${slaves} | tr ',' ' '`
for vm in $slavesArr
do
        LogMsg "$mpirunPath -hosts $master,$vm -ppn $mpi1_ppn -n $(( $mpi1_ppn * 2 )) $mpi_settings $imb_mpi1Path pingpong"
        LogMsg "Checking IMB-MPI1 InterNode status in $vm"
        $mpirunPath -hosts $master,$vm -ppn $mpi1_ppn -n $(( $mpi1_ppn * 2 )) $mpi_settings $imb_mpi1Path pingpong > IMB-MPI1-InterNode-pingpong-output-${master}-${vm}.txt
        mpiInternodeStatus=$?
        if [ $mpiInternodeStatus -eq 0 ];
        then
                        LogMsg "IMB-MPI1 Internode status in $vm - Succeeded."
        else
                        LogMsg "IMB-MPI1 Internode status in $vm - Failed"
        fi
        finalMpiInternodeStatus=$(( $finalMpiInternodeStatus + $mpiInternodeStatus ))
done

if [ $finalMpiInternodeStatus -ne 0 ]; then
                LogMsg "ERROR: IMB-MPI1 Internode test failed in somes VMs. Aborting further tests."
                UpdateTestState $ICA_TESTFAILED
                CollectKernelLogs
                LogMsg "INFINIBAND_VERIFICATION_FAILED_MPI1_INTERNODE"
                exit 0
else
                LogMsg "INFINIBAND_VERIFICATION_SUCCESS_MPI1_INTERNODE"
fi

#Verify IMB-MPI1 (pingpong & allreduce etc) tests.
Attempts=`seq 1 1 $imb_mpi1_tests_iterations`
imb_mpi1_finalStatus=0
for i in $Attempts;
do
                if [[ $imb_mpi1_tests == "all" ]];
                then
                    LogMsg "$mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path"
                    LogMsg "IMB-MPI1 test iteration $i - Running."
                    $mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path > IMB-MPI1-AllNodes-output-Attempt-${i}.txt
                    mpiStatus=$?
                else
                    LogMsg "$mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path $imb_mpi1_tests"
                    LogMsg "IMB-MPI1 test iteration $i - Running."
                    $mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path $imb_mpi1_tests > IMB-MPI1-AllNodes-output-Attempt-${i}.txt
                    mpiStatus=$?
                fi
                if [ $mpiStatus -eq 0 ];
                then
                                LogMsg "IMB-MPI1 test iteration $i - Succeeded."
                                sleep 1
                else
                                LogMsg "IMB-MPI1 test iteration $i - Failed."
                                imb_mpi1_finalStatus=$(( $imb_mpi1_finalStatus + $mpiStatus ))
                                sleep 1
                fi
done

if [ $imb_mpi1_tests_iterations -gt 5 ];
then
    CompressFiles "IMB-MPI1-AllNodes-output.tar.gz" "IMB-MPI1-AllNodes-output-Attempt"
fi

if [ $imb_mpi1_finalStatus -ne 0 ]; then
                LogMsg "ERROR: IMB-MPI1 tests returned non-zero exit code."
                UpdateTestState $ICA_TESTFAILED
                CollectKernelLogs
                LogMsg "INFINIBAND_VERIFICATION_FAILED_MPI1_ALLNODES"
                exit 0
else
                LogMsg "INFINIBAND_VERIFICATION_SUCCESS_MPI1_ALLNODES"

fi

#Verify IMB-RMA tests.
Attempts=`seq 1 1 $imb_rma_tests_iterations`
imb_rma_finalStatus=0
for i in $Attempts;
do
                if [[ $imb_rma_tests == "all" ]];
                then
                    LogMsg "$mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath"
                    LogMsg "IMB-RMA test iteration $i - Running."
                    $mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath > IMB-RMA-AllNodes-output-Attempt-${i}.txt
                    rmaStatus=$?
                else
                    LogMsg "$mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath $imb_rma_tests"
                    LogMsg "IMB-RMA test iteration $i - Running."
                    $mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath $imb_rma_tests > IMB-RMA-AllNodes-output-Attempt-${i}.txt
                    rmaStatus=$?
                fi
                if [ $rmaStatus -eq 0 ];
                then
                                LogMsg "IMB-RMA test iteration $i - Succeeded."
                                sleep 1
                else
                                LogMsg "IMB-RMA test iteration $i - Failed."
                                imb_rma_finalStatus=$(( $imb_rma_finalStatus + $rmaStatus ))
                                sleep 1
                fi
done

if [ $imb_rma_tests_iterations -gt 5 ];
then
    CompressFiles "IMB-RMA-AllNodes-output.tar.gz" "IMB-RMA-AllNodes-output-Attempt"
fi

if [ $imb_rma_finalStatus -ne 0 ]; then
                LogMsg "ERROR: IMB-RMA tests returned non-zero exit code. Aborting further tests."
                UpdateTestState $ICA_TESTFAILED
                CollectKernelLogs
                LogMsg "INFINIBAND_VERIFICATION_FAILED_RMA_ALLNODES"
                exit 0
else
                LogMsg "INFINIBAND_VERIFICATION_SUCCESS_RMA_ALLNODES"
fi

#Verify IMB-NBC tests.
Attempts=`seq 1 1 $imb_nbc_tests_iterations`
imb_nbc_finalStatus=0
for i in $Attempts;
do
                if [[ $imb_nbc_tests == "all" ]];
                then
                    LogMsg "$mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath"
                    LogMsg "IMB-NBC test iteration $i - Running."
                    $mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath > IMB-NBC-AllNodes-output-Attempt-${i}.txt
                    nbcStatus=$?
                else
                    LogMsg "$mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath $imb_nbc_tests"
                    LogMsg "IMB-NBC test iteration $i - Running."
                    $mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath $imb_nbc_tests > IMB-NBC-AllNodes-output-Attempt-${i}.txt
                    nbcStatus=$?
                fi
                if [ $nbcStatus -eq 0 ];
                then
                                LogMsg "IMB-NBC test iteration $i - Succeeded."
                                sleep 1
                else
                                LogMsg "IMB-NBC test iteration $i - Failed."
                                imb_nbc_finalStatus=$(( $imb_nbc_finalStatus + $nbcStatus ))
                                sleep 1
                fi
done

if [ $imb_rma_tests_iterations -gt 5 ];
then
    CompressFiles "IMB-NBC-AllNodes-output.tar.gz" "IMB-NBC-AllNodes-output-Attempt"
fi

if [ $imb_nbc_finalStatus -ne 0 ]; then
                LogMsg "ERROR: IMB-RMA tests returned non-zero exit code. Aborting further tests."
                UpdateTestState $ICA_TESTFAILED
                CollectKernelLogs
                LogMsg "INFINIBAND_VERIFICATION_FAILED_NBC_ALLNODES"
                exit 0
else
                LogMsg "INFINIBAND_VERIFICATION_SUCCESS_NBC_ALLNODES"
fi

CollectKernelLogs

finalStatus=$(( $eth1Status +  $finalMpiIntranodeStatus + $finalMpiInternodeStatus + $imb_mpi1_finalStatus + $imb_rma_finalStatus + $imb_nbc_finalStatus ))
if [ $finalStatus -ne 0 ];
then
                LogMsg LogMsg "eth1Status: $eth1Status,  finalMpiIntranodeStatus:$finalMpiIntranodeStatus, finalMpiInternodeStatus:$finalMpiInternodeStatus, imb_mpi1_finalStatus:$imb_mpi1_finalStatu, imb_rma_finalStatus:$imb_rma_finalStatus, imb_nbc_finalStatus:$imb_nbc_finalStatus"
                UpdateTestState $ICA_TESTFAILED
                LogMsg "INFINIBAND_VERIFICATION_FAILED"
else
                UpdateTestState $ICA_TESTCOMPLETED
                LogMsg "INFINIBAND_VERIFIED_SUCCESSFULLY"
fi


# This script is meant for quick & easy install via:
curl -fsSL get.docker.com -o get-docker.sh
sh get-docker.sh

systemctl status docker > /dev/null
dockerServiceStatus=$?
systemctl status docker > ./dockerServiceStatusLogs.txt
docker version > dockerVersion.txt

if [ $dockerServiceStatus -eq 0 ];then
	echo "DOCKER_VERIFIED_SUCCESSFULLY"
else
	echo "DOCKER_VERIFICATION_FAILED"
fi

#TODO : More Tests

#TODO Cleanup


#!/bin/sh
#Verify Installation of waaagent

if [ -e /etc/init.d/waagent ]; then

	echo "Verify Install waagent : Success"
else
	echo "Verify Install waagent : Failed"
	exit

fi


echo 'iface eth0 inet6 auto' >> /etc/network/interfaces.d/50-cloud-init.cfg
echo 'up sleep 5' >> /etc/network/interfaces.d/50-cloud-init.cfg
echo 'up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true' >> /etc/network/interfaces.d/50-cloud-init.cfg
ifdown eth0 && ifup eth0


#!/bin/bash
#V-SHISAV@MICROSOFT.COM
# THIS SCRIPT DETECT FOLLOWING DISTROS:
#  UBUNTU [VERSION INDEPENDANT]
#  CENTOS [VERSION INDEPENDANT]
#  SUSE LINUX ENTERPRISE SERVER [VERSION INDEPENDANT]
#  OPENSUSE [VERSION INDEPENDANT]
#  REDHAT
#  ORACLELINUX
#  FEDORA
DetectDistro()
{
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done
        if [ -e /etc/debian_version ]; then
		        tmp=`cat /etc/*-release`
                if [[ "$tmp" == *Ubuntu* ]]; then
                    echo "UBUNTU"
                    exitVal=0
                else
                    echo "DEBIAN"
                    exitVal=0
                fi
        elif [ -e /etc/redhat-release ]; then
                tmp=`cat /etc/redhat-release`
                if [ -e /etc/oracle-release ]; then
                    tmp=`cat /etc/oracle-release`
                    if [[ "$tmp" == *Oracle* ]]; then
                        echo "ORACLELINUX"
                        exitVal=0
                    else
                        echo "Unknown"
                        exitVal=1
                    fi
                elif [[ "$tmp" == *CentOS* ]]; then
                    echo "CENTOS"
                    exitVal=0
                elif [[ "$tmp" == *Fedora* ]]; then
                    echo "FEDORA"
                    exitVal=0
                elif [[ "$tmp" == *Red* ]]; then
                    echo "REDHAT"
                    exitVal=0
                else
                    echo "Unknown"
                    exitVal=1
                fi
        elif [ -e /etc/SuSE-release ]; then
                tmp=`cat /etc/SuSE-release`
                if [[ "$tmp" == *Enterprise* ]]; then
                    echo "SLES"
                    exitVal=0
                elif [[ "$tmp" == *open* ]]; then
                    echo "SUSE"
                    exitVal=0
                else
                    echo "Unknown"
                fi
        elif [ -e /etc/os-release ]; then
                tmp=`cat /etc/os-release`
                if [[ "$tmp" == *coreos* ]]; then
                    echo "COREOS"
                    exitVal=0
                fi
        elif [ -e /usr/share/clear/version ]; then
                tmp=`cat /usr/share/clear/version`
                echo "CLEARLINUX"
                exitVal=0
        fi
return $exitVal
}
DetectDistro


#!/bin/bash
#V-SHISAV@MICROSOFT.COM

#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments

while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done
packageName=$install
isRemote=$isRemote
isLocal=$isLocal
fileName=$file
CurrentDate=`date`

installFromFolder()
{
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done
sourceFolder=$sourceFolder
cd $sourceFolder
ls
if [ -e ./configure ]; then
    chmod +x configure && ./configure && make && make install
    exitVal=$?
elif [ -e ./setup.py ]; then
    python setup.py build && python setup.py install
    exitVal=$?
fi
cd ..
return $exitVal
}

getFolderName()
{
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

compressedFile=$compressedFile
if [[ "$compressedFile" == *.tar.gz ]]; then
    folderName=${compressedFile%.tar.gz*}
elif [[ "$compressedFile" == *.tar ]]; then
    folderName=${compressedFile%.tar.bz2*}
elif [[ "$compressedFile" == *.tar ]]; then
    folderName=${compressedFile%.tar*}
fi
echo $folderName
}

installFromCompressedFile()
{
#{
#   extract the source code.
#   invoke : decompressFile -file $fileName
#   search for installation files in extracted folder. Like - setup.py / configure / make etc.
#   invoke "appropriate" installation method.. [installPythonSourceCode() / installMakeSourceCode() / ...]
#   return exit code.
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

compressedFile=$compressedFile
decompressFile -fileToDecompress $compressedFile
installFolder=`getFolderName -compressedFile $compressedFile`
echo "$installFolder"
installFromFolder -sourceFolder $installFolder
exitVal=$?

return $exitVal
}

decompressFile()
{
#   determine the extraction method depending on *.tar, *.tar.gz, *.bz2, *.gzip etc.
#   execute : tar -xzf / gunzip / bzip etc. and untar the compressed file.
#   return exit code.
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

fileToDecompress=$fileToDecompress
if [[ "$installFile" == *.tar ]]; then
    tar -xzvf $fileToDecompress
        #installFromCompressedFile
    exitVal=$?
elif [[ "$installFile" == *.tar.gz ]]; then
    tar -xvf $fileToDecompress
    exitVal=$?
fi

if [ $exitVal == 0 ]; then
    echo "Decompresssion Successfull"
else
    echo "Decompresssion Failed"
fi
return $exitVal

}
#other installation methods support can be added depending on requirement.

installLocalFile()
{
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done

installFile=$LocalFile
if [[ ( "$installFile" == *.tar ) || ( "$installFile" == *.tar.gz ) || ( "$installFile" == *.tar.bz2 ) ]]; then
    echo "provided file $installFile"
    echo "Installing from copressed file"
    installFromCompressedFile -compressedFile $installFile
    exitVal=$?
elif [[ "$installFile" == *.rpm ]]; then
    echo "provided file $installFile"
    echo "Installing rpm file"
    rpm -ivh $installFile
    exitVal=$?
elif [[ "$installFile" == *.deb ]]; then
    echo "provided file $installFile"
    echo "Installing deb file"
    dpkg -i $installFile
    exitVal=$?
elif [[ "$installFile" == *.sh ]]; then
    echo "provided file $installFile"
    echo "Executing shell script ..."
    chmod +x $installFile
	dos2unix $installFile
    ./$installFile
    exitVal=$?
elif [ -z $installFile ]; then
    echo "Please provide file with -file <filename> argument"
    exitVal=1
else
    echo "Unknowin file type.."
    exitVal=1
fi
return $exitVal
}
installRemotePackage()
{
while echo $1 | grep ^- > /dev/null; do
    eval $( echo $1 | sed 's/-//g' | tr -d '\012')=$2
    shift
    shift
done
packageName=$install
        if [ -e /etc/debian_version ]; then
                apt-get install --force-yes -y $packageName
                installStatus=$?
                if [ $installStatus = 0 ]; then
                        echo "Install $packageName : InstallSuccess"
                        exitVal=0
                else
                        echo "Install $packageName : FAILED"
                        exitVal=1
                fi
        fi
        if [ -e /etc/redhat-release ]; then
                sed -i 's/exclude=kernel/#exclude=kernel/' /etc/yum.conf
                yum install --nogpgcheck -y $packageName
                installStatus=$?
                if [ $installStatus = "0" ]; then
                        echo "Install $packageName : InstallSuccess"
                        exitVal=0
                else
                        echo "Install $packageName : FAILED"
                        exitVal=1
                fi
        fi
        if [ -e /etc/SuSE-release ]; then
                zypper --non-interactive --no-gpg-checks install $packageName
                installStatus=$?
                if [ $installStatus = "0" ]; then
                        echo "Install $packageName : InstallSuccess"
                        exitVal=0
                else
                        echo "Install $packageName : FAILED"
                        exitVal=1
                fi
        fi
return $exitVal
}
updateDistro()
{
    if [ -e /etc/debian_version ]; then
        apt-get --force-yes -y update
        installStatus=$?
        if [ $installStatus = 0 ]; then
            echo "Install Update : InstallSuccess"
            exitVal=0
        else
        echo "Install Update : FAILED"
        exitVal=1
        fi
    fi
    if [ -e /etc/redhat-release ]; then
            sed -i 's/exclude=kernel/#exclude=kernel/' /etc/yum.conf
        yum --nogpgcheck -y update
        installStatus=$?
        if [ $installStatus = "0" ]; then
            echo "Install Update : InstallSuccess"
            exitVal=0
        else
            echo "Install Update : FAILED"
            exitVal=1
        fi
    fi
    if [ -e /etc/SuSE-release ]; then
        zypper --non-interactive --no-gpg-checks update
        installStatus=$?
        if [ $installStatus = "0" ]; then
            echo "Updated successfully.."
            exitVal=0
        else
            echo "Update failed.."
            exitVal=1
        fi
    fi

return $exitVal
}

# main body starts here..

if [ "$packageName" = "UpdateCurrentDistro" ]; then
    updateDistro
    installStatus=$?
    if [ $installStatus = "0" ]; then
        echo "Install $packageName : InstallSuccess"
        exitVal=0
    else
        echo "Install $packageName  : FAILED"
        exitVal=1
    fi

    exit $exitVal
else
    if [ -z $packageName ]; then
        echo "No packages are given to install. Please use -package <Package Name>"
        exitVal=0
    else
        if [ -z $isLocal ]; then
            echo "Please mention -isLocal yes/no"
        elif [ "$isLocal" = "no" ]; then
                installRemotePackage -install $packageName
                exitVal=$?
        elif [ "$isLocal" = "yes" ]; then
                installLocalFile -LocalFile $fileName
				installStatus=$?
                if [ $installStatus = "0" ]; then
                    echo "Install $packageName : InstallSuccess"
                    exitVal=0
                else
                    echo "Install packageName : FAILED"
                    exitVal=1
                fi
        else
            echo "Please provide -isLocal yes or -isLocal no [CaSe SensitivE]"
        fi
    fi
fi
exit $exitVal


#!/bin/bash
proj_name="aem"
proj_version="1.0"

proj_full_name="$proj_name-$proj_version"

script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`

build_dir=$root/build
target_dir=$build_dir/$proj_full_name

mkdir -p $build_dir
mkdir -p $target_dir

cd $root/clib
make clean

cp -r $root/nodejs $build_dir
cd $build_dir/nodejs
npm pack

cp -r $root/clib $target_dir
cp $build_dir/nodejs/*.tgz $target_dir
cp $root/bin/setup.sh $target_dir
chmod +x $root/bin/setup.sh

#install.sh is a self-extracting script.
#The begin of this file is sh script while the end is a tar
echo "#!/bin/bash"                              >  $build_dir/install.sh
echo "#"                                        >> $build_dir/install.sh
echo "#Auto-generated. Do NOT edit this file."  >> $build_dir/install.sh
echo "#"                                        >> $build_dir/install.sh
echo "root=\$(dirname \$0)"                     >> $build_dir/install.sh
echo "cd \$root"                                >> $build_dir/install.sh
echo "root=\`pwd\`"                             >> $build_dir/install.sh
echo "if [ -d $proj_full_name ]; then"          >> $build_dir/install.sh
echo "    echo \"[INFO]Remove old package...\"" >> $build_dir/install.sh
echo "    rm $proj_full_name -rf"               >> $build_dir/install.sh
echo "fi"                                       >> $build_dir/install.sh
echo "echo \"[INFO]Unpacking...\""              >> $build_dir/install.sh
echo "sed -e '1,/^exit$/d' "\$0" | tar xzf -"   >> $build_dir/install.sh
echo "$proj_full_name/setup.sh"                 >> $build_dir/install.sh
echo "exit"                                     >> $build_dir/install.sh
cd $build_dir
tar czf - $proj_full_name                       >> $build_dir/install.sh
chmod +x $build_dir/install.sh

cp -r $root/clib $build_dir
cd $build_dir
tar czf clib.tar.gz clib/


#!/bin/bash

install_log=`pwd`/install.log
root=$(dirname $0)
cd $root
root=`pwd`

if [[ $EUID -ne 0 ]]; then
    echo "[ERROR]This script must be run as root" 1>&2
    exit 1
fi

function install_nodejs_tarball()
{
    version="v0.10.37"
    node_version="node-$version-linux-x64"
    src="$root/$node_version"
    target="/usr/local"

    echo "[INFO]Installing nodejs from http://nodejs.org/dist/$version/${node_version}.tar.gz"
    if [ -f ${src}.tar.gz ]; then
        rm ${src}.tar.gz -f
    fi
    if [ -d ${src} ]; then
        rm ${src} -rf
    fi
    wget http://nodejs.org/dist/$version/${node_version}.tar.gz 1>>$install_log 2>&1
    tar -zxf ${node_version}.tar.gz  1>>$install_log 2>&1

    echo "[INFO]Install nodejs to $target"
    if [ -f $target/bin/node ]; then
        rm $target/bin/node -f
    fi
    cp $src/bin/node $target/bin/node

    echo "[INFO]Create link to $target/bin/node"
    if [ -f /usr/bin/node ]; then
        rm /usr/bin/node -f
    fi
    ln -s $target/bin/node /usr/bin/node

    echo "[INFO]Install npm"
    curl -sL https://www.npmjs.org/install.sh | sh 1>>$install_log 2>&1

}

function install_nodejs()
{
    echo "[INFO]Installing nodejs and npm"
    if [ "$(type apt-get 2>/dev/null)" != "" ] ; then
        curl -sL https://deb.nodesource.com/setup | bash - 1>>$install_log 2>&1
        apt-get -y install nodejs 1>>$install_log 2>&1
    elif [ "$(type yum 2>/dev/null)" != "" ] ; then
        curl -sL https://rpm.nodesource.com/setup | bash - 1>>$install_log 2>&1
        yum -y install nodejs 1>>$install_log 2>&1
    else
        install_nodejs_tarball
    fi
    if [ ! $? ]; then
        echo "[ERROR]Install nodejs and npm failed. See $install_log."
        exit 1
    fi
}

echo "[INFO]Checking dependency..."
echo "" > $install_log
if [ "$(type node 2>/dev/null)" == "" ]; then
    install_nodejs
fi
echo "[INFO]  nodejs version: $(node --version)"

if [ "$(type npm 2>/dev/null)" == "" ]; then
    install_nodejs
fi
echo "[INFO]  npm version: $(npm -version)"

if [ "$(type azure 2> /dev/null)" == "" ]; then
    echo "[INFO]Installing azure-cli"
    npm install -g azure-cli 1>>$install_log 2>&1
    if [ ! $? ]; then
        echo "[ERROR]Install azure-cli failed. See $install_log."
        exit 1
    fi
fi
echo "[INFO]  azure-cli version: $(azure --version)"

npm_pkg="azure-linux-tools-1.0.0.tgz"
echo "[INFO]Installing Azure Enhanced Monitor tools..."
if [ -f ./$npm_pkg ]; then
    npm install -g ./$npm_pkg 1>>$install_log 2>&1
    if [ ! $? ]; then
        echo "[ERROR]Install Azure Enhanced Monitor tools failed. See $install_log."
        exit 1
    fi
else
    echo "[ERROR] Couldn't find npm package $npm_pkg"
    exit 1
fi

echo "[INFO]Finished."


#! /bin/bash

source ./agent.version

echo "AGENT_VERSION=$AGENT_VERSION"
echo "MDSD_DEB_PACKAGE_NAME=$MDSD_DEB_PACKAGE_NAME"
echo "MDSD_RPM_PACKAGE_NAME=$MDSD_RPM_PACKAGE_NAME"

# updating HandlerManifest.json
# check for "version": "x.x.x",
sed -i "s/\"version\".*$/\"version\": \"$AGENT_VERSION\",/g" HandlerManifest.json

# updating agent.py
sed -i "s/^BundleFileNameDeb = .*$/BundleFileNameDeb = '$MDSD_DEB_PACKAGE_NAME'/" agent.py
sed -i "s/^BundleFileNameRpm = .*$/BundleFileNameRpm = '$MDSD_RPM_PACKAGE_NAME'/" agent.py

# updating manifest.xml
# check <Version>...</Version>
sed -i -e "s|<Version>[0-9a-z.]\{1,\}</Version>|<Version>$AGENT_VERSION</Version>|g" manifest.xml


#! /bin/bash
set -e
source agent.version

usage()
{
    local basename=`basename $0`
    echo "usage: ./$basename <path to mdsd-<version>.{.deb, .rpm}> [path for zip output]"
}

input_path=$1
output_path=$2
PACKAGE_NAME="azuremonitor$AGENT_VERSION.zip"
if [[ "$1" == "--help" ]]; then
    usage
    exit 0
elif [[ ! -d $input_path ]]; then
    echo "DEB/RPM files path '$input_path' not found"
    usage
    exit 1
fi

if [[ "$output_path" == "" ]]; then
    output_path="../"
fi

# Packaging starts here
cp -r ../Utils .
cp ../Common/WALinuxAgent-2.0.16/waagent .

cp -r  ../LAD-AMA-Common/metrics_ext_utils .
cp -r  ../LAD-AMA-Common/telegraf_utils .
cp -r  ../Diagnostic/services .

# cleanup packages, ext
rm -rf packages MetricsExtensionBin ext/future amaCoreAgentBin agentLauncherBin
mkdir -p packages MetricsExtensionBin ext/future amaCoreAgentBin agentLauncherBin

# copy shell bundle to packages/
cp $input_path/azuremonitoragent_$AGENT_VERSION* packages/
cp $input_path/azuremonitoragent-$AGENT_VERSION* packages/
cp $input_path/MetricsExtension* MetricsExtensionBin/
cp $input_path/amacoreagent amaCoreAgentBin/
cp $input_path/agentlauncher agentLauncherBin/

# copy just the source of python-future
cp -r ext/python-future/src/* ext/future

# make the shim.sh file executable
chmod +x shim.sh

# sync the file copy
sync

if [[ -f $output_path/$PACKAGE_NAME ]]; then
    echo "Removing existing $PACKAGE_NAME ..."
    rm -f $output_path/$PACKAGE_NAME
fi

echo "Packaging extension $PACKAGE_NAME to $output_path"
excluded_files="agent.version packaging.sh apply_version.sh update_version.sh"
zip -r $output_path/$PACKAGE_NAME * -x $excluded_files "./test/*" "./extension-test/*" "./references" "./ext/python-future/*" "./ext/future/future/backports/test/*"

# cleanup newly added dir or files
rm -rf Utils/ waagent


#!/usr/bin/env bash

# This is the main driver file for AMA extension. This file first checks if Python 3 or 2 is available on the VM
# and if yes then uses that Python (if both are available then, default is set to python3) to run extension operations in agent.py
# Control arguments passed to the shim are redirected to agent.py without validation.

COMMAND="./agent.py"
PYTHON=""
FUTURE_PATH=""
ARG="$@"

function find_python() {
    local python_exec_command=$1
    local future_path=$2

    if command -v python3 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python3"
        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment
    elif command -v python2 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python2"
        eval ${future_path}="${PWD}/ext/future:"
    elif command -v /usr/libexec/platform-python >/dev/null 2>&1 ; then
        # If a user-installed python isn't available, check for a platform-python. This is typically only used in RHEL 8.0.
        echo "User-installed python not found. Using /usr/libexec/platform-python as the python interpreter."
        eval ${python_exec_command}="/usr/libexec/platform-python"
        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment
    fi
}

find_python PYTHON FUTURE_PATH

if [ -z "$PYTHON" ] # If python is not installed, we will fail the install with the following error, requiring cx to have python pre-installed
then
    echo "No Python interpreter found, which is an AMA extension dependency. Please install Python 3, or Python 2 if the former is unavailable." >&2
    exit 52 # Missing Dependency
else
    ${PYTHON} --version 2>&1
fi

PYTHONPATH=${FUTURE_PATH}${PYTHONPATH} ${PYTHON} ${COMMAND} ${ARG}
exit $?


#! /bin/bash
set -x

if [[ "$1" == "--help" ]]; then
    echo "update_version.sh <AGENT_VERSION> <MDSD_DEB_PACKAGE_NAME> <MDSD_RPM_PACKAGE_NAME>"
    exit 0
fi

UPDATE_DATE=`date +%Y%m%d`
AGENT_VERSION=$1
MDSD_DEB_PACKAGE_NAME=$2
MDSD_RPM_PACKAGE_NAME=$3

if [[ "$AGENT_VERSION" == "" ]]; then
    echo "AGENT_VERSION version is empty"
    exit 1
fi

if [[ "$MDSD_DEB_PACKAGE_NAME" == "" ]]; then
    echo "MDSD_DEB_PACKAGE_NAME is empty"
    exit 1
fi

if [[ "$MDSD_RPM_PACKAGE_NAME" == "" ]]; then
    echo "MDSD_RPM_PACKAGE_NAME is empty"
    exit 1
fi

sed -i "s/^AGENT_VERSION=.*$/AGENT_VERSION=$AGENT_VERSION/" agent.version
sed -i "s/^MDSD_DEB_PACKAGE_NAME=.*$/MDSD_DEB_PACKAGE_NAME=$MDSD_DEB_PACKAGE_NAME/" agent.version
sed -i "s/^MDSD_RPM_PACKAGE_NAME=.*$/MDSD_RPM_PACKAGE_NAME=$MDSD_RPM_PACKAGE_NAME/" agent.version
sed -i "s/^AGENT_VERSION_DATE=.*$/AGENT_VERSION_DATE=$UPDATE_DATE/" agent.version


#!/usr/bin/env bash

COMMAND="./modules/main.py"
PYTHON=""
FUTURE_PATH=""
TST_VERSION="1.3"  # update when changes are made to TST
ARG="$@"

display_help() {
    echo "OPTIONS"
    echo "  -A              Run All Troubleshooting Tool checks"
    echo "  -L              Run Log Collector"
    echo "  -v, --version   Print Troubleshooting Tool version"
}

find_python() {
    local python_exec_command=$1
    local future_path=$2

    if command -v python3 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python3"
        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment
    elif command -v python2 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python2"
        eval ${future_path}="${PWD}/ext/future:"
    elif command -v /usr/libexec/platform-python >/dev/null 2>&1 ; then
        # If a user-installed python isn't available, check for a platform-python. This is typically only used in RHEL 8.0.
        echo "User-installed python not found. Using /usr/libexec/platform-python as the python interpreter."
        eval ${python_exec_command}="/usr/libexec/platform-python"
        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment
    fi
}

find_python PYTHON FUTURE_PATH

if [ -z "$PYTHON" ] # If python is not installed, we will fail the install with the following error, requiring cx to have python pre-installed
then
    echo "No Python interpreter found, which is an AMA extension dependency. Please install Python 3, or Python 2 if the former is unavailable." >&2
    exit 1
else
    echo "Python version being used is:"
    ${PYTHON} --version 2>&1
    echo ""
fi

if [ "$1" = "--help" ] || [ "$1" = "-h" ]
then
    display_help
elif [ "$1" = "--version" ] || [ "$1" = "-v" ]
then
    echo "AMA Troubleshooting Tool v.$TST_VERSION"
else
    echo "Starting AMA Troubleshooting Tool v.$TST_VERSION..."
    echo ""
    PYTHONPATH=${FUTURE_PATH}${PYTHONPATH} ${PYTHON} ${COMMAND} ${ARG}
fi
exit $?


#!/usr/bin/env bash

# The shim scripts provide a single entry point for CSE and will invoke the customscript.py entry point using the
# appropriate python interpreter version.
# Arguments passed to the shim layer are redirected to the invoked script without any validation.

COMMAND="./customscript.py"
PYTHON=""
ARG="$@"

function find_python(){
    local python_exec_command=$1

    # Check if there is python defined.
    if command -v python >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python"
    else
        # Python was not found. Searching for Python3 now.
        if command -v python3 >/dev/null 2>&1 ; then
            eval ${python_exec_command}="python3"
        fi
    fi
}

find_python PYTHON

if [ -z "$PYTHON" ]
then
   echo "No Python interpreter found on the box" >&2
   exit 51 # Not Supported
else
    echo "Found: `${PYTHON} --version`"
fi

${PYTHON} ${COMMAND} ${ARG}
exit $?

# DONE


#!/bin/bash
#
# This script is used to set up a test env for extensions
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

script=$(dirname $0)
root=$script
cd $root
root=`pwd`

echo "Run unit test:"
ls test_*.py
ls test_*.py | sed -e 's/\.py//'|xargs python -m unittest


#!/bin/bash

for i in $(seq 1500)
do
    echo `date` + The script is running...
    >&2 echo `date` + ERROR:The script is running...
    sleep 1
done


#!/bin/bash

# A shell script utility to decrypt the extension's protected settings for debugging purpose
# Must be run at /var/lib/waagent/Microsoft.Azure.Diagnostics.LinuxDiagnostic-.../
# with the settings file path (e.g., config/0.settings) as the only cmdline arg

if [ $# -lt 1 ]; then
    echo "Usage: $0 <ext_settings_file_path>"
    exit 1
fi

thumbprint=$(jq -r '.runtimeSettings[].handlerSettings.protectedSettingsCertThumbprint' $1)
jq -r '.runtimeSettings[].handlerSettings.protectedSettings' $1 | base64 --decode | openssl smime -inform DER -decrypt -recip ../$thumbprint.crt -inkey ../$thumbprint.prv | jq .


#!/bin/bash

for test in watchertests test_commonActions test_lad_logging_config test_lad_config_all test_LadDiagnosticUtil \
                test_builtin test_lad_ext_settings; do
    python -m tests.$test
done


#!/usr/bin/env bash

# This is the main driver file for LAD extension. This file first checks if Python 2 is available on the VM and exits early if not
# Control arguments passed to the shim are redirected to diagnostic.py without validation.

COMMAND="./diagnostic.py"
PYTHON=""
ARG="$@"

function find_python() {
    local python_exec_command=$1

    if command -v python2 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python2"
    fi
}

find_python PYTHON

if [ -z "$PYTHON" ] # If python2 is not installed, we will fail the install with the following error, requiring cx to have python pre-installed
then
    echo "No Python 2 interpreter found, which is an LAD extension dependency. Please install Python 2 before retrying LAD extension deployment." >&2
    exit 52 # Missing Dependency
else
    ${PYTHON} --version 2>&1
fi

${PYTHON} ${COMMAND} ${ARG}
exit $?


#!/bin/bash

# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.

# This will build mdsd and its libraries
# Usage: see Usage()
#

TotalErrors=0

BuildType=
CCompiler=gcc
CXXCompiler=g++
BuildName=dev
BUILDDIR=builddir
MakeFileOnly=0
Parallelism="-j4"

# If CodeCoverage=1, build with code coverage options.
# NOTE: only gcc is supported and it must be debug build.
CodeCoverage=OFF

Usage()
{
    echo "Usage: $0 <-a> | <-d|-o> <-c|-g> [-b buildname] [-mC] [-p parallelism] [-s] [-t]"
    echo "    -b: use buildname. Default: timestamp."
    echo "    -C: capture code coverage."
    echo "    -d: build debug build."
    echo "    -m: create makefiles only. After done, run 'make help' for options."
    echo "    -o: build optimized(release) build."
    echo "    -p: specify number of parallel compile operations (default 4)."
}

if [ "$#" == "0" ]; then
    Usage
    exit 1
fi

args=`getopt b:Cdhmop: $*`
if [ $? != 0 ]; then
    Usage
    exit 1
fi
set -- $args

for i; do
    case "$i" in
        -b)
            BuildName=$2
            shift ; shift ;;
        -C)
            CodeCoverage=ON
            shift ;;
        -d)
            if [ -z "${BuildType}" ]; then
                BuildType=d
            else
                echo "Error: build type is already set to be ${BuildType}."
                exit 1
            fi
            shift ;;
        -h)
            Usage
            exit 0
            shift ;;
        -m)
            MakeFileOnly=1
            shift ;;
        -o)
            if [ -z "${BuildType}" ]; then
                BuildType=o
            else
                echo "Error: build type is already set to be ${BuildType}."
                exit 1
            fi
            shift ;;
        -p)
            declare -i numJobs  # This variable is an integer, guaranteed by the shell
            numJobs=$2
            if [ $numJobs -gt 1 ]; then
                Parallelism="-j$numJobs"
                echo "Setting parallelism to $Parallelism"
            else
                Parallelism=""
                echo "Disabling parallel compilation"
            fi
            shift; shift ;;
        --) shift; break ;;
    esac
done

if [ -z "${BuildType}" ]; then
    echo "Error: missing build type. -d or -o is required."
    exit 1
fi

if [ "${CodeCoverage}" == "ON" ]; then
    if [ "${BuildType}" != "d" ]; then
        echo "Error: only debug build is supported for code coverage."
        exit 1
    fi
fi

BuildWithCMake()
{
    echo
    echo Start to build source code. BuildType=${BuildType} ...
    BinDropDir=${BUILDDIR}.${BuildType}.${CCompiler}
    rm -rf ${BUILDDIR} ${BinDropDir}
    mkdir ${BinDropDir}
    ln -s ${BinDropDir} ${BUILDDIR}

    pushd ${BinDropDir}

    DefBuildNumber=
    if [ ! -z "${BuildName}" ]; then
        DefBuildNumber=-DBUILD_NUMBER=${BuildName}
    fi
    echo "BuildName: '${DefBuildNumber}'"

    CMakeBuildType="Release"
    if [ ${BuildType} == "d" ]; then
        CMakeBuildType="Debug"
    fi

    cmake -DCMAKE_C_COMPILER=${CCompiler} -DCMAKE_CXX_COMPILER=${CXXCompiler} \
          -DCMAKE_BUILD_TYPE=${CMakeBuildType} ${DefBuildNumber} \
          -DBUILD_COV=${CodeCoverage} ../

    CheckCmdError "cmake"

    if [ ${MakeFileOnly} != 0 ]; then
        echo
        echo Makfiles are created. To make, cd ${BUILDDIR}, run make \<target\>.
        echo
        make help
        exit ${TotalErrors}
    fi

    make ${Parallelism}
    CheckCmdError "make ${Parallelism}"

    make install
    CheckCmdError "make install"

    if [ ${CCompiler} == "gcc" ]; then
        # Make deb/rpm packages for LAD mdsd
        make -C ../lad-mdsd/deb LABEL=${BuildName}
        CheckCmdError  "lad-mdsd/deb"
        make -C ../lad-mdsd/rpm LABEL=${BuildName}
        CheckCmdError  "lad-mdsd/rpm"
    fi
    tar czf release.tar.gz release
    popd
}

# Check whether previous command has error or not.
# Usage: CheckCmdError "description"
CheckCmdError()
{
    if [ $? != 0 ]; then
        let TotalErrors+=1
        echo Error: build $1 failed
        exit ${TotalErrors}
    else
        echo Finished building $1 successfully
    fi
}

# Usage: ParseGlibcVer <dirname> <filename>(optional)
ParseGlibcVer()
{
    # Maximum GLIBC version supported by oldest supported distro
    glibcver=2.15
    ParserScript=./parseglibc.py
    dirname=$1
    filename=$2  # optional, can be NULL
    echo
    if [ -n "${filename}" ]; then
        echo python ${ParserScript} -f ${dirname}/${filename} -v ${glibcver}
        python ${ParserScript} -f ${dirname}/${filename} -v ${glibcver}
    else
        echo python ${ParserScript} -d ${dirname} -v ${glibcver}
        python ${ParserScript} -d ${dirname} -v ${glibcver}
    fi

    if [ $? != 0 ]; then
        let TotalErrors+=1
        echo Error: ParseGlibcVer failed: maximum supported GLIBC version is ${glibcver}.
        exit ${TotalErrors}
    fi
}

# Download/build/install the appropriate version of openssl.
#    This is needed because the lib{ssl,crypto}.a that's available through the Ubuntu repo
#    is causing some link errors at the last stage. We need to use /usr/local/ssl as the
#    top-level OpenSSL directory for the libraries, to make them work on all distros
#    (especially SUSE 11, which is already done that way).
BuildOpenSsl()
{
    opensslDir=openssl-1.0.2* # Grab the only (which must be latest) OpenSSL 1.0.2 release
    tgzFile=$opensslDir.tar.gz
    wget ftp://ftp.openssl.org/source/$tgzFile || exit 1
    InstallOpenSSL=1
    if [ -e /usr/local/lib/libcrypto.a -a -e /usr/local/lib/libssl.a ]; then
        OpenSSLVersion=$(strings /usr/local/lib/libssl.a | egrep "^OpenSSL " | awk '{ print $2 }')
        DownloadedTGZName=$(ls $tgzFile)
        if [ "$DownloadedTGZName" == "openssl-$OpenSSLVersion.tar.gz" ]; then # Already latest
            InstallOpenSSL=0
        fi
    fi
    if [ "$InstallOpenSSL" == "1" ]; then
        tar xfz $tgzFile
        cd $opensslDir
         # Need to make the lib*.a linkable to .so as well (for AI SDK lib*.so) by adding -fPIC.
        export CC="gcc -fPIC"
        ./config --prefix=/usr/local --openssldir=/usr/lib/ssl zlib
        make
        CheckCmdError "openssl make"
        sudo make install_sw
        CheckCmdError "openssl make install_sw"
        cd ..
    fi
}

echo Start build at `date`. BuildType=${BuildType} CC=${CCompiler} ...

BuildOpenSsl

BuildWithCMake

# Remaining steps should be run only on a non-static build except ParseGlibcVer on bin build.

ParseGlibcVer ./${BUILDDIR}/release/bin
ParseGlibcVer ./${BUILDDIR}/release/lib

echo
echo Finished all builds at `date`. error = ${TotalErrors}
exit ${TotalErrors}


#!/usr/bin/env bash

# Keeping the default command
COMMAND=""
PYTHON=""

# We are writing logs to error stream in extension_shim.sh as the logs written to output stream are being overriden by HandlerUtil.py. This has been done as part of OMIGOD hotfix
# Default variables for OMI Package Upgrade
REQUIRED_OMI_VERSION="1.6.12.1"
INSTALLED_OMI_VERSION=""
UPGRADED_OMI_VERSION=""
OPENSSL_VERSION=""
OMI_PACKAGE_PREFIX='packages/omi-1.6.12-1.ssl_'
OMI_PACKAGE_PATH=""
OMI_SERVICE_STATE=""

USAGE="$(basename "$0") [-h] [-i|--install] [-u|--uninstall] [-d|--disable] [-e|--enable] [-p|--update]

Program to find the installed python on the box and invoke a Python extension script.

where:
    -h|--help       show this help text
    -i|--install    install the extension
    -u|--uninstall  uninstall the extension
    -d|--disable    disable the extension
    -e|--enable     enable the extension
    -p|--update     update the extension
    -c|--command    command to run

example:
# Install usage
$ bash extension_shim.sh -i
python ./vmaccess.py -install

# Custom executable python file
$ bash extension_shim.sh -c ""hello.py"" -i
python hello.py -install

# Custom executable python file with arguments
$ bash extension_shim.sh -c ""hello.py --install""
python hello.py --install
"

function find_python(){
    local python_exec_command=$1

    # Check if there is python2 defined.
    if command -v python2 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python2"
    else
        # Python2 was not found. Searching for Python3 now.
        if command -v python3 >/dev/null 2>&1 ; then
            eval ${python_exec_command}="python3"
        fi
    fi
}

function get_openssl_version(){
    openssl=`openssl version | awk '{print $2}'`
    if [[ ${openssl} =~ ^1.0.* ]]; then
        OPENSSL_VERSION="100"
    else
        if [[ ${openssl} =~ ^1.1.* ]]; then
            OPENSSL_VERSION="110"
        else
            if [[ ${openssl} =~ ^0.9.8* ]]; then
                OPENSSL_VERSION="098"
            fi
        fi
    fi
}

function start_omiservice(){
    echo "Attempting to start OMI service" >&2
    RESULT=`/opt/omi/bin/service_control start >/dev/null 2>&1`
    RESULT=`service omid status >/dev/null 2>&1`
    if [ $? -eq 0 ]; then
        echo "OMI service succesfully started." >&2
    else
        echo "OMI service could not be started." >&2
    fi
}

function stop_omiservice(){
    echo "Attempting to stop OMI service" >&2
    RESULT=`/opt/omi/bin/service_control stop >/dev/null 2>&1`
    RESULT=`service omid status >/dev/null 2>&1`
    if [ $? -eq 3 ]; then
        echo "OMI service succesfully stopped." >&2
    else
        echo "OMI service could not be stopped." >&2
    fi
}

function compare_versions(){
    if [[ $1 == $2 ]]
    then
        return 0
    fi
    local IFS=.
    local i v1=($1) v2=($2)
    for ((i=0; i<${#v1[@]}; i++))
    do
        if ((${v1[i]} > ${v2[i]}))
        then
            return 1
        fi
        if ((${v1[i]} < ${v2[i]}))
        then
            return 2
        fi
    done
    return 0
}

function get_compiler_mitigated_flag() {
    OS_NAME=`grep '^NAME' /etc/os-release | tr -d 'NAME=' | tr -d '"' | tr '[:upper:]' '[:lower:]'`
    echo "OS: ${OS_NAME}" >&2
    OS_VERSION=`grep '^VERSION_ID' /etc/os-release | tr -d 'VERSION_ID=' | tr -d '"' | tr '[:upper:]' '[:lower:]'`
    echo "OS VERSION: ${OS_VERSION}" >&2

    # Compiler-mitigated OMI is not supported in the following
    # SLES 11

    # To be enhanced if there are future distros not supporting compiler-mitigated OMI package

	FLAG=""
	if [[ $OS_NAME == sles* && $OS_VERSION == 11* ]]
	then
		FLAG=""
	else
		FLAG=".s"
	fi
	echo $FLAG
}

function ensure_required_omi_version_exists(){
    # Populate SSL Version
    get_openssl_version

    echo "Checking if OMI is installed. Required OMI version: ${REQUIRED_OMI_VERSION};" >&2

    COMPILER_MITIGATED_VERSION_FLAG=$( get_compiler_mitigated_flag )
    echo "OMI compiler-mitigated flag: (${COMPILER_MITIGATED_VERSION_FLAG})" >&2

    # Check if RPM exists
    if command -v rpm >/dev/null 2>&1 ; then
        echo "Package Manager Type: RPM" >&2
        INSTALLED_OMI_VERSION=`rpm -q --queryformat "%{VERSION}.%{RELEASE}" omi 2>&1`
        if [ -z "$INSTALLED_OMI_VERSION" -o "$INSTALLED_OMI_VERSION" = "package omi is not installed" ]; then
            echo "OMI is not installed on the machine." >&2
        else
            RESULT=`service omid status >/dev/null 2>&1`
            OMI_SERVICE_STATE=$?
            echo "OMI is already installed. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};" >&2 # Add current running status
            compare_versions ${INSTALLED_OMI_VERSION} ${REQUIRED_OMI_VERSION}
            if [ $? -eq 2 ]; then
                OMI_PACKAGE_PATH="${OMI_PACKAGE_PREFIX}${OPENSSL_VERSION}.ulinux${COMPILER_MITIGATED_VERSION_FLAG}.x64.rpm"
                echo "Installed OMI version is lower than the Required OMI version. Trying to upgrade." >&2
                if [ -f ${OMI_PACKAGE_PATH} ]; then
                    echo "The OMI package exists at ${OMI_PACKAGE_PATH}. Using this to upgrade." >&2
                    stop_omiservice
                    RESULT=`rpm -Uvh ${OMI_PACKAGE_PATH} >/dev/null 2>&1`
                    if [ $? -eq 0 ]; then
                        UPGRADED_OMI_VERSION=`rpm -q --queryformat "%{VERSION}.%{RELEASE}" omi 2>&1`
                        echo "Succesfully upgraded the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION}; Upgraded: ${UPGRADED_OMI_VERSION};" >&2
                    else
                        echo "Failed to upgrade the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION};" >&2
                    fi
                    # Start OMI only if previous state was running
                    if [ $OMI_SERVICE_STATE -eq 0 ]; then
                        start_omiservice
                    fi
                else
                    echo "The OMI package does not exists at ${OMI_PACKAGE_PATH}. Skipping upgrade." >&2
                fi
            else
                echo "Installed OMI version is equal to or greater than the Required OMI version. No action needed." >&2
            fi
        fi
        INSTALLED_OMI_VERSION=`rpm -q --queryformat "%{VERSION}.%{RELEASE}" omi 2>&1`
        RESULT=`service omid status >/dev/null 2>&1`
        OMI_SERVICE_STATE=$?
        echo "OMI upgrade is complete. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};" >&2
    else
        # Check if DPKG exists
        if command -v dpkg >/dev/null 2>&1 ; then
            echo "Package Manager Type: DPKG" >&2
            INSTALLED_OMI_VERSION=`dpkg -s omi 2>&1 | grep Version: | awk '{print $2}'`
            if [ -z "$INSTALLED_OMI_VERSION" -o "$INSTALLED_OMI_VERSION" = "package omi is not installed" ]; then
                echo "OMI is not installed on the machine." >&2
            else
                RESULT=`service omid status >/dev/null 2>&1`
                OMI_SERVICE_STATE=$?
                echo "OMI is already installed. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};" >&2
                compare_versions ${INSTALLED_OMI_VERSION} ${REQUIRED_OMI_VERSION}
                if [ $? -eq 2 ]; then
                    OMI_PACKAGE_PATH="${OMI_PACKAGE_PREFIX}${OPENSSL_VERSION}.ulinux${COMPILER_MITIGATED_VERSION_FLAG}.x64.deb"
                    echo "Installed OMI version is lower than the Required OMI version. Trying to upgrade." >&2
                    if [ -f ${OMI_PACKAGE_PATH} ]; then
                        echo "The OMI package exists at ${OMI_PACKAGE_PATH}. Using this to upgrade." >&2
                        stop_omiservice
                        RESULT=`dpkg -i --force-confold --force-confdef --refuse-downgrade ${OMI_PACKAGE_PATH} >/dev/null 2>&1`
                        if [ $? -eq 0 ]; then
                            UPGRADED_OMI_VERSION=`dpkg -s omi 2>&1 | grep Version: | awk '{print $2}'`
                            echo "Succesfully upgraded the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION}; Upgraded: ${UPGRADED_OMI_VERSION};" >&2
                        else
                            echo "Failed to upgrade the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION};" >&2
                        fi
                        # Start OMI only if previous state was running
                        if [ $OMI_SERVICE_STATE -eq 0 ]; then
                            start_omiservice
                        fi
                    else
                        echo "The OMI package does not exists at ${OMI_PACKAGE_PATH}. Skipping upgrade." >&2
                    fi
                else
                    echo "Installed OMI version is equal to or greater than the Required OMI version. No action needed." >&2
                fi
            fi
            INSTALLED_OMI_VERSION=`dpkg -s omi 2>&1 | grep Version: | awk '{print $2}'`
            RESULT=`service omid status >/dev/null 2>&1`
            OMI_SERVICE_STATE=$?
            echo "OMI upgrade is complete. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};" >&2
        fi
    fi
}

# Transform long options to short ones for getopts support (getopts doesn't support long args)
for arg in "$@"; do
  shift
  case "$arg" in
    "--help")       set -- "$@" "-h" ;;
    "--install")    set -- "$@" "-i" ;;
    "--update")     set -- "$@" "-p" ;;
    "--enable")     set -- "$@" "-e" ;;
    "--disable")    set -- "$@" "-d" ;;
    "--uninstall")  set -- "$@" "-u" ;;
    *)              set -- "$@" "$arg"
  esac
done

if [ -z "$arg" ]
then
   echo "$USAGE" >&2
   exit 1
fi

# Get the arguments
while getopts "iudephc:?" o; do
    case "${o}" in
        h|\?)
            echo "$USAGE"
            exit 0
            ;;
        i)
            operation="-install"
            ;;
        u)
            operation="-uninstall"
            ;;
        d)
            operation="-disable"
            ;;
        e)
            operation="-enable"
            ;;
        p)
            operation="-update"
            ;;
        c)
            COMMAND="$OPTARG"
            ;;
        *)
            echo "$USAGE" >&2
            exit 1
            ;;
    esac
done

shift $((OPTIND-1))

# Ensure OMI package if exists is of required version.
ensure_required_omi_version_exists

# If find_python is not able to find a python installed, $PYTHON will be null.
find_python PYTHON

if [ -z "$PYTHON" ]; then
   echo "No Python interpreter found on the box" >&2
   exit 51 # Not Supported
else
    `${PYTHON} --version`
fi

${PYTHON} ${COMMAND} ${operation}
# DONE


#! /bin/bash

source ./omsagent.version

echo "OMS_EXTENSION_VERSION=$OMS_EXTENSION_VERSION"
echo "OMS_SHELL_BUNDLE_VERSION=$OMS_SHELL_BUNDLE_VERSION"

# updating HandlerManifest.json
# check for "version": "1.12.5",
sed -i "s/\"version\".*$/\"version\": \"$OMS_EXTENSION_VERSION\",/g" HandlerManifest.json

# updating watcherutil.py
# check OMSExtensionVersion = '1.12.5'
sed -i "s/^OMSExtensionVersion = .*$/OMSExtensionVersion = '$OMS_EXTENSION_VERSION'/"  watcherutil.py

# updating omsagent.py
# check BundleFileName = 'omsagent-0.0.0-0.universal.x64.sh'
sed -i "s/^BundleFileName = .*$/BundleFileName = 'omsagent-$OMS_SHELL_BUNDLE_VERSION.universal.x64.sh'/" omsagent.py

# updating manifest.xml
# check <Version>...</Version>
sed -i -e "s|<Version>[0-9a-z.]\{1,\}</Version>|<Version>$OMS_EXTENSION_VERSION</Version>|g" manifest.xml


#!/bin/sh

if [ -z "$1" ]; then
    echo "Usage:"
    echo "   $0 PUBLIC_GPG_KEY"
    exit 1
fi

if [ -z "$2" ]; then
    KEYRING_NAME="keyring.gpg"
else
    KEYRING_NAME=$2
fi

TARGET_DIR="$(dirname $1)"
HOME=$TARGET_DIR gpg --no-default-keyring --keyring $TARGET_DIR/$KEYRING_NAME --import $1
RETVAL=$?

# chown omsagent $TARGET_DIR/$KEYRING_NAME

exit $RETVAL


#!/usr/bin/env bash

# The entry point for the OMS extension through which the correct python version (if any) is used to invoke omsagent.py.
# We default to python2 and always invoke with the versioned python command to accomodate the RHEL 8+ python strategy.
# Control arguments passed to the shim are redirected to omsagent.py without validation.

COMMAND="./omsagent.py"
PYTHON=""
FUTURE_PATH=""
ARG="$@"

function find_python() {
    local python_exec_command=$1
    local future_path=$2

    if command -v python2 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python2"
        eval ${future_path}="${PWD}/ext/future:"
    elif command -v python3 >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python3"
        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment
    fi
}

find_python PYTHON FUTURE_PATH

if [ -z "$PYTHON" ]
then
    echo "No Python interpreter found, which is an OMS extension dependency. Please install either Python 2 or 3." >&2
    exit 52 # Missing Dependency
else
    ${PYTHON} --version 2>&1
fi

PYTHONPATH=${FUTURE_PATH}${PYTHONPATH} ${PYTHON} ${COMMAND} ${ARG}
exit $?


#! /bin/bash
set -e
source omsagent.version

usage()
{
    local basename=`basename $0`
    echo "usage: ./$basename <path to omsagent-<version>.universal.x64{.sh, .sha256sums, .asc}> [path for zip output]"
}

input_path=$1
output_path=$2
PACKAGE_NAME="oms$OMS_EXTENSION_VERSION.zip"
if [[ "$1" == "--help" ]]; then
    usage
    exit 0
elif [[ ! -d $input_path ]]; then
    echo "OMS files path '$input_path' not found"
    usage
    exit 1
fi

if [[ "$output_path" == "" ]]; then
    output_path="../"
fi

# Packaging starts here
cp -r ../Utils .
cp ../Common/WALinuxAgent-2.0.16/waagent .

# cleanup packages, ext
rm -rf packages ext/future
mkdir -p packages ext/future
# copy shell bundle to packages/
cp $input_path/omsagent-$OMS_SHELL_BUNDLE_VERSION.universal.x64.* packages/
# copy just the source of python-future
cp -r ext/python-future/src/* ext/future
# sync the file copy
sync

if [[ -f $output_path/$PACKAGE_NAME ]]; then
    echo "Removing existing $PACKAGE_NAME ..."
    rm -f $output_path/$PACKAGE_NAME
fi

echo "Packaging extension $PACKAGE_NAME to $output_path"
excluded_files="omsagent.version packaging.sh apply_version.sh update_version.sh"
zip -r $output_path/$PACKAGE_NAME * -x $excluded_files "./test/*" "./extension-test/*" "./references" "./ext/python-future/*" "./ext/future/future/backports/test/*"

# cleanup newly added dir or files
rm -rf Utils/ waagent


#! /bin/bash
set -x

if [[ "$1" == "--help" ]]; then
    echo "update_version.sh <MAJOR> <MINOR> <PATCH> <BUILDNR>"
    exit 0
fi

UPDATE_DATE=`date +%Y%m%d`
OMS_BUILDVERSION_MAJOR=$1
OMS_BUILDVERSION_MINOR=$2
OMS_BUILDVERSION_PATCH=$3
OMS_BUILDVERSION_BUILDNR=$4

if [[ "$OMS_BUILDVERSION_MAJOR" == "" ]]; then
    echo "MAJOR version is empty"
    exit 1
fi

if [[ "$OMS_BUILDVERSION_MINOR" == "" ]]; then
    echo "MINOR version is empty"
    exit 1
fi

if [[ "$OMS_BUILDVERSION_PATCH" == "" ]]; then
    echo "PATH version is empty"
    exit 1
fi

if [[ "$OMS_BUILDVERSION_BUILDNR" == "" ]]; then
    echo "BUILDNR version is empty"
    exit 1
fi

sed -i "s/^OMS_VERSION_MAJOR=.*$/OMS_VERSION_MAJOR=$OMS_BUILDVERSION_MAJOR/" omsagent.version
sed -i "s/^OMS_VERSION_MINOR=.*$/OMS_VERSION_MINOR=$OMS_BUILDVERSION_MINOR/" omsagent.version
sed -i "s/^OMS_VERSION_PATCH_EXTENSION=.*$/OMS_VERSION_PATCH_EXTENSION=$OMS_BUILDVERSION_PATCH/" omsagent.version
sed -i "s/^OMS_VERSION_PATCH_SHELL_BUNDLE=.*$/OMS_VERSION_PATCH_SHELL_BUNDLE=$OMS_BUILDVERSION_PATCH/" omsagent.version
sed -i "s/^OMS_VERSION_BUILDNR_SHELL_BUNDLE=.*$/OMS_VERSION_BUILDNR_SHELL_BUNDLE=$OMS_BUILDVERSION_BUILDNR/" omsagent.version
sed -i "s/^OMS_VERSION_DATE=.*$/OMS_VERSION_DATE=$UPDATE_DATE/" omsagent.version


#!/bin/bash
#
# This script is used to set up a test env for extensions
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

if [ $# != 2 ]  ; then
    echo ""
    echo "    Usage: $0 <path-to-extension> <version>"
    echo "    Example: $0 SampleExtension 1.0.0.0"
    echo ""
    exit 1
fi

if [ ! -d $1 ]  ; then
    echo ""
    echo "    Error: Couldn't find dir: $1"
    echo ""
    exit 1
fi

curr_dir=`pwd`
ext_dir=$1
cd $ext_dir
ext_dir=`pwd`
cd $curr_dir

script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`

util_dir=$root/Utils
build_dir=$root/build

if [ ! -d $build_dir ] ; then
    mkdir $build_dir
fi

ext_name=`echo $1 | sed 's/\/$//'`
ext_version=$2
ext_full_name=$ext_name-$ext_version
tmp_dir=$build_dir/$ext_full_name

echo "Create zip for $ext_name version $ext_version"

echo "Creat tmp dir: $tmp_dir"
mkdir $tmp_dir

echo "Copy files..."
cp -r $ext_dir/* $tmp_dir
rm $tmp_dir/references

echo "Copy dependecies..."
cat $ext_dir/references
cat $ext_dir/references | xargs cp -r -t $tmp_dir

echo "Switch to tmp dir..."
cd $tmp_dir

echo "Remove test dir..."
rm -r test
rm -r */test

echo "Remove *.pyc..."
find . -name "*.pyc" | xargs rm -f

echo "Create zip..."
zip -r $build_dir/$ext_full_name.zip .

echo "Delete tmp dir..."
rm $tmp_dir -r
echo "Done!"


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

echo $1
curl -v -X 'POST'  -H "$VERSION" -H 'Content-Type: application/xml' -E $CERT -d@$1 $ENDPOINT/$SUBSCRIPTION/services/extensions


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

echo $1
curl -v -X 'GET' --keepalive-time 30 --user-agent ' Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient/0.9.0.0 WindowsAzurePowershell/v0.8.0' -H 'x-ms-version: 2014-06-01' -H 'Content-Type: application/xml'  --insecure  -E $CERT --data-binary @$1  $ENDPOINT/$SUBSCRIPTION/operations/$1


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

curl -v -X 'DELETE'  -H "$VERSION" -H 'Content-Type: application/xml' -E $CERT $ENDPOINT/$SUBSCRIPTION/services/extensions/$1/$2/$3


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

curl -v -X 'GET'  -H "$VERSION" -H 'Content-Type: application/xml' -E $CERT $ENDPOINT/$SUBSCRIPTION/services/resourceextensions/$1/$2


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

echo "GET $ENDPOINT/$SUBSCRIPTION"

curl -v -X 'GET' --keepalive-time 30 --user-agent ' Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient/0.9.0.0 WindowsAzurePowershell/v0.8.0' -H 'x-ms-version: 2014-06-01' -H 'Content-Type: application/xml'  --insecure  -E $CERT $ENDPOINT/$SUBSCRIPTION


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

curl -v -X 'GET' -H 'x-ms-version: 2014-06-01' -H 'Content-Type: application/xml' -E $CERT $ENDPOINT/$SUBSCRIPTION/services/publisherextensions


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script
source params
export script=`pwd`
cd $original_dir

curl -v -X 'PUT' -H "$VERSION" -H 'Content-Type: application/xml' -E $CERT -d@$1 $ENDPOINT/$SUBSCRIPTION/services/extensions?action=update


#!/bin/bash

original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "Add extension: $1"
$root/api/add-extension.sh 2>/tmp/restoutput $1 | sed -e 's/></>\n</g'

echo "===================="
echo "Check request by running bin/check.sh <request-id>"
tail /tmp/restoutput
echo "===================="
echo "More info is saved in /tmp/restoutput"


#!/bin/bash

original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "Check Request: $1"
$root/api/check-request-status.sh 2>>/tmp/restoutput $1 | sed -e 's/></>\n</g'


#!/bin/bash

original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "Delete extension: $1 $2 $3"
$root/api/del-extension.sh 2>/tmp/restoutput $1 $2 $3| sed -e 's/></>\n</g'

echo "===================="
echo "Check request by running bin/check.sh <request-id>"
tail /tmp/restoutput
echo "===================="
echo "More info is saved in /tmp/restoutput"


#!/bin/bash
original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "Get extension: $1 $2"
$root/api/get-extension.sh 2>/tmp/restoutput $1 $2 | sed -e 's/></>\n</g'


#!/bin/bash

original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "List extensions: $1"
$root/api/list-extension.sh 2>/tmp/restoutput | sed -e 's/></>\n</g' | sed -e 's/<\/ExtensionImage>/<\/ExtensionImage>\n/g'


#!/bin/bash

original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "Get subscription"
$root/api/get-subscription.sh 2>>/tmp/restoutput | sed -e 's/></>\n</g'


#!/bin/bash

original_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
cd $original_dir

echo "Update extension: $1"
$root/api/update-extension.sh 2>/tmp/restoutput $1 | sed -e 's/></>\n</g'

echo "===================="
echo "Check request by running bin/check.sh <request-id>"
tail /tmp/restoutput
echo "===================="
echo "More info is saved in /tmp/restoutput"


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script/../../api
source params
export script=`pwd`
cd $original_dir

azure storage blob list -c $CONN_STR extensions


#!/bin/bash
original_dir=`pwd`
script=`dirname $0`
cd $script/../../api
source params
export script=`pwd`
cd $original_dir

zip_file=$(readlink -f $1)
if [ ! -f $zip_file ] ; then
    echo "File not found: $zip_file"
    exit 1
fi
file_name=$(basename $zip_file)
echo "Uploading $zip_file to azure..."
azure storage blob upload -c $CONN_STR $zip_file extensions $file_name


#!/bin/bash
#
# This script is used to set up a test env for extensions
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

if [ ! $1 ]  || [ ! $2 ] || [ ! $3 ]  ; then
    echo ""
    echo "    Usage: create_zip.sh <path_to_extension_dir> <name> <version>"
    echo ""
    exit 1
fi

if [ ! -d $1 ]  ; then
    echo ""
    echo "    Error: Couldn't find dir: $1>"
    echo ""
    exit 1
fi

curr_dir=`pwd`
ext_dir=$1
ext_name=$2
ext_version=$3
cd $ext_dir
ext_dir=`pwd`
cd $curr_dir

script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`

echo $ext_name
echo $ext_version

util_dir=$root/Utils
build_dir=$root/build

if [ ! $ext_name ] ; then
    echo ""
    echo "    Error: Couldn't detect extention name: $ext_name"
    echo ""
    exit 1
fi

if [ ! $ext_version ] ; then
    echo ""
    echo "    Error: Couldn't detect extention version: $ext_version"
    echo ""
    exit 1
fi

if [ ! -d $build_dir ] ; then
    mkdir $build_dir
fi

ext_full_name=$ext_name-$ext_version
tmp_dir=$build_dir/$ext_full_name

echo "Create zip for $ext_name version $ext_version"

echo "Creat tmp dir: $tmp_dir"
mkdir $tmp_dir

echo "Copy files..."
cp -r $ext_dir/* $tmp_dir
rm $tmp_dir/references

echo "Copy dependecies..."
cat $ext_dir/references
cat $ext_dir/references | xargs cp -r -t $tmp_dir

echo "Switch to tmp dir..."
cd $tmp_dir

echo "Remove test dir..."
rm -r test
rm -r */test
rm *.pyc

echo "Create zip..."
zip -r $build_dir/$ext_full_name.zip .

echo "Delete tmp dir..."
rm $tmp_dir -r
echo "Done!"


#!/bin/bash
#
# This script is used to create stub for unit test
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
if [ ! $1 ]  ; then
    echo ""
    echo "    Usage: mkstub.sh <path_to_extension_dir>"
    echo ""
    exit 1
fi

if [ ! -d $1 ]  ; then
    echo ""
    echo "    Error: Couldn't find dir: $1>"
    echo ""
    exit 1
fi

ext_dir=$1
ext_meta=$ext_dir/HandlerManifest.json

if [ ! -f $ext_meta ] ; then
    echo ""
    echo "    Error: Couldn't find \"HandlerManifest.json\" file under $ext_dir"
    echo ""
    exit 1
fi

cur_dir=`pwd`
script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
waagent_path='/usr/sbin/waagent'
waagent_lib_dir='/var/lib/waagent'
ext_log_dir='/var/log/azure'

ext_name=`grep 'name' $ext_meta | sed 's/[\"| |,]//g' |gawk -F ':' '{print $2}'`
ext_version=`grep 'version' $ext_meta | sed 's/[\"| |,]//g' |gawk -F ':' '{print $2}'`

ext_full_name=$ext_name-$ext_version
ext_dir=$waagent_lib_dir/$ext_full_name
ext_status_dir=$ext_dir/status
ext_config_dir=$ext_dir/config
ext_env_json=$ext_dir/HandlerEnvironment.json
test_cert_file=$waagent_lib_dir/TEST.crt
test_pk_file=$waagent_lib_dir/TEST.prv
ovf_env_file=$waagent_lib_dir/ovf-env.xml

if [ ! -f $waagent_path ] ; then
    echo "Download latest waagent code"
    wget https://raw.githubusercontent.com/Azure/WALinuxAgent/2.0/waagent -O $waagent_path
    chmod +x $waagent_path
fi

if [ ! -d $waagent_lib_dir ] ; then
    echo "Create lib dir"
    mkdir $waagent_lib_dir
fi

if [ ! -d $ext_dir ] ; then
    echo "Create extension dir"
    mkdir $ext_dir
fi

if [ ! -d $ext_config_dir ] ; then
    echo "Create extension config dir"
    mkdir $ext_config_dir
fi

if [ ! -d $ext_status_dir ] ; then
    echo "Create extension status dir"
    mkdir $ext_status_dir
fi

if [ ! -f $ext_env_json ] ; then
    echo "Create HandlerEnvironment.json file"
    cp $script/HandlerEnvironment.json $ext_env_json
fi

if [ ! -f $test_cert_file ] ; then
    echo "Create test cert file"
    cp $script/test.crt $test_cert_file
fi

if [ ! -f $test_pk_file ] ; then
    echo "Create test pk file"
    cp $script/test.prv $test_pk_file
fi

if [ ! -f $ovf_env_file ] ; then
    echo "Create ovf-env.xml file"
    cp $script/ovf-env.xml $ovf_env_file
fi

if [ ! -f $ext_config_dir/0.settings ] ; then
    echo "Create 0.settings"
    cp $script/0.settings $ext_config_dir/0.settings
fi

if [ ! -d $ext_log_dir ] ; then
    echo "Create ext log dir"
    mkdir $ext_log_dir
fi

if [ ! -d $ext_log_dir/$ext_name ] ; then
    echo "Create ext log dir for $ext_name"
    mkdir $ext_log_dir/$ext_name
fi

if [ ! -d $ext_log_dir/$ext_name/$ext_version ] ; then
    echo "Create ext log dir for $ext_name $ext_version"
    mkdir $ext_log_dir/$ext_name/$ext_version
fi

echo "Change permission of waagent lib dir"
chmod -R 600 $waagent_lib_dir


#!/bin/bash
#
# This script is used to set up a test env for extensions
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

script=$(dirname $0)
root=$script/..
cd $root
root=`pwd`
lib_path="."

echo "\$PYTHONPATH=$PYTHONPATH"

if [ ! `echo $PYTHONPATH | grep $root` ] ; then
    lib_path=$lib_path:$root
fi

if [ $lib_path != "." ] ; then
    echo "echo \"export PYTHONPATH=\$PYTHONPATH:$lib_path\" >> /etc/bash.bashrc"
    echo "export PYTHONPATH=\$PYTHONPATH:$lib_path" >> /etc/bash.bashrc
    echo "Enviroment variable PYTHONPATH has been set."
    echo "Run \"bash\" to reload bash."
else
    echo "Your enviroment is cool. No action required."
fi


#!/bin/bash
#
# Copyright 2014 Microsoft Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

echo "Start..."
sleep 0.1
echo "Running"
>&2 echo "Warning"
sleep 0.1
echo "Finished"
exit $1


#!/usr/bin/env bash
# must run with sudo permissions
# this file copies the local changes to /var/lib/waagent/Microsoft.OSTCExtensions.VMAccessForLinux-<version>

# remember to update the version number to what you have
destdir="/var/lib/waagent/Microsoft.OSTCExtensions.VMAccessForLinux-1.5.4"
utilsDest="$destdir/Utils"
vmaccessDest="$destdir/vmaccess.py"

currentDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"

utilsSource="$currentDir/.."
vmaccessSource="$currentDir/../../VMAccess/vmaccess.py"

cp -r -f $utilsSource $utilsDest
cp -f $vmaccessSource $vmaccessDest
find $destdir -name '*.pyc' | xargs rm


#!/usr/bin/env bash

# Keeping the default command
COMMAND=""
PYTHON=""

USAGE="$(basename "$0") [-h] [-i|--install] [-u|--uninstall] [-d|--disable] [-e|--enable] [-p|--update]

Program to find the installed python on the box and invoke a Python extension script.

where:
    -h|--help       show this help text
    -i|--install    install the extension
    -u|--uninstall  uninstall the extension
    -d|--disable    disable the extension
    -e|--enable     enable the extension
    -p|--update     update the extension
    -c|--command    command to run

example:
# Install usage
$ bash extension_shim.sh -i
python ./vmaccess.py -install

# Custom executable python file
$ bash extension_shim.sh -c ""hello.py"" -i
python hello.py -install

# Custom executable python file with arguments
$ bash extension_shim.sh -c ""hello.py --install""
python hello.py --install
"

function find_python(){
    local python_exec_command=$1

    # Check if there is python defined.
    if command -v python >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python"
    else
        # Python was not found. Searching for Python3 now.
        if command -v python3 >/dev/null 2>&1 ; then
            eval ${python_exec_command}="python3"
        fi
    fi
}

# Transform long options to short ones for getopts support (getopts doesn't support long args)
for arg in "$@"; do
  shift
  case "$arg" in
    "--help")       set -- "$@" "-h" ;;
    "--install")    set -- "$@" "-i" ;;
    "--update")     set -- "$@" "-p" ;;
    "--enable")     set -- "$@" "-e" ;;
    "--disable")    set -- "$@" "-d" ;;
    "--uninstall")  set -- "$@" "-u" ;;
    *)              set -- "$@" "$arg"
  esac
done

if [ -z "$arg" ]
then
   echo "$USAGE" >&2
   exit 1
fi

# Get the arguments
while getopts "iudephc:?" o; do
    case "${o}" in
        h|\?)
            echo "$USAGE"
            exit 0
            ;;
        i)
            operation="-install"
            ;;
        u)
            operation="-uninstall"
            ;;
        d)
            operation="-disable"
            ;;
        e)
            operation="-enable"
            ;;
        p)
            operation="-update"
            ;;
        c)
            COMMAND="$OPTARG"
            ;;
        *)
            echo "$USAGE" >&2
            exit 1
            ;;
    esac
done

shift $((OPTIND-1))

# If find_python is not able to find a python installed, $PYTHON will be null.
find_python PYTHON

if [ -z "$PYTHON" ]; then
   echo "No Python interpreter found on the box" >&2
   exit 51 # Not Supported
else
   echo `${PYTHON} --version`
fi

${PYTHON} ${COMMAND} ${operation}
# DONE


#!/usr/bin/env sh
pwdcommand=`pwd`
pwdstr="$pwdcommand"
output=`cat $pwdstr'/HandlerEnvironment.json'`
outputstr="$output"
poststr=${outputstr#*logFolder\"}
postsubstr=${poststr#*\"}
postsubstr1=${postsubstr#*\"}
resultstrlen=`expr ${#postsubstr} - 1 - ${#postsubstr1}`
logfolder=$(echo $postsubstr | cut -b 1-$resultstrlen)
logfile=$logfolder'/shell.log'

rc=3
arc=0

if [ "$1" = "install" ]
then
    if [ -f "/etc/azure/workload.conf" ]
    then
		WorkloadConfEdited=`awk '/(workload_name)([ ]*[=])([ ]*[(^|\")a-zA-Z(^|\")])/' /etc/azure/workload.conf`
		if [ "$WorkloadConfEdited" != "" ]
			then
				#Workload.conf is edited
				echo "`date -u`- The command is $1, exiting without conf file copy" >> $logfile
			else
				#workload.conf is not edited
				cp main/workloadPatch/WorkloadUtils/workload.conf /etc/azure/workload.conf
				echo "`date -u`- The command is $1, exiting with conf file copy" >> $logfile
		fi
        exit $arc
    else
        mkdir -p /etc/azure
        cp main/workloadPatch/WorkloadUtils/workload.conf /etc/azure/workload.conf
        echo "`date -u`- The command is $1, exiting with conf file copy" >> $logfile
        exit $arc
    fi
elif [ "$1" != "enable"  ] && [ "$1" != "daemon" ]
then
    echo "`date -u`- The command is $1, exiting" >> $logfile
    exit $arc
fi

configSeqNo="$(echo `printenv ConfigSequenceNumber`)"
if [ -z ${configSeqNo} ]
then
	configSeqNo='seqNo:-1'
	echo "`date -u`- ConfigSequenceNumber not found in environment variable ${configSeqNo}" >> $logfile
else
	configSeqNo='seqNo:'$configSeqNo
	echo "`date -u`- ConfigSequenceNumber from environment variable ${configSeqNo}" >> $logfile
fi

pythonVersionList="python3.8 python3.7 python3.6 python3.5 python3.4 python3.3 python3 python2.7 python2.6 python2 python"

for pythonVersion in ${pythonVersionList};
do
	cmnd="/usr/bin/${pythonVersion}"
	if [ -f "${cmnd}" ]
    then
		echo "`date -u`- ${pythonVersion} path exists" >> $logfile
		$cmnd main/handle.py -$configSeqNo -$1
		rc=$?
	fi
	if [ $rc -eq 0 ]
	then
		break
	fi
done

pythonProcess=$(ps -ef | grep waagent | grep python)
pythonPath=$(echo "${pythonProcess}" | head -n1 | awk '{print $8;}')

if [ $rc -ne 0 ] && [ -f "`which python`" ]
then
	echo "`date -u`- python path exists" >> $logfile
	/usr/bin/env python main/handle.py -$configSeqNo -$1
	rc=$?
fi

if [ $rc -ne 0 ] && [ -f "${pythonPath}" ]
then
	echo "`date -u`- python path exists" >> $logfile
	$pythonPath main/handle.py -$configSeqNo -$1
	rc=$?
fi

if [ $rc -eq 3 ]
then
	echo "`date -u`- python version unknown" >> $logfile
fi

echo "`date -u`- $rc returned from handle.py" >> $logfile

exit $rc


#!/bin/bash
instance=$1

# variables used for returning the status of the scripts
success=0
error=1
warning=2

retVal=$success
exit $retVal


#!/usr/bin/env sh

arc=0

comand="$2"
cred_string="$3"
timeout="$4"
scriptPath="$5"

sleep $timeout

if [ "$1" = "oracle" ]
then
    cmd="$comand/sqlplus -S -R 2 /nolog @$scriptPath/postOracleMaster.sql"
    exec $cmd
elif [ "$1" = "postgres" ]
then
    cmd="$comand/psql $cred_string -f $scriptPath/postPostgresMaster.sql"
    exec $cmd
else
    echo "`date`- incorrect workload name"
fi

exit $arc


#!/usr/bin/env bash

# Keeping the default command
COMMAND=""
PYTHON=""

USAGE="$(basename "$0") [-h] [-i|--install] [-u|--uninstall] [-d|--disable] [-e|--enable] [-p|--update] [-m|--daemon]

Program to find the installed python on the box and invoke a Python extension script using Python 2.7.

where:
    -h|--help       show this help text
    -i|--install    install the extension
    -u|--uninstall  uninstall the extension
    -d|--disable    disable the extension
    -e|--enable     enable the extension
    -p|--update     update the extension
    -m|--daemon     invoke daemon option
    -c|--command    command to run

example:
# Install usage
$ bash extension_shim.sh -i
python ./main/handle.py -install

# Custom executable python file
$ bash extension_shim.sh -c ""hello.py"" -i
python hello.py -install

# Custom executable python file with arguments
$ bash extension_shim.sh -c ""hello.py --install""
python hello.py --install
"

function find_python(){
    local python_exec_command=$1

    # Check if there is python defined.
    if command -v python >/dev/null 2>&1 ; then
        eval ${python_exec_command}="python"
    fi
}

# Transform long options to short ones for getopts support (getopts doesn't support long args)
for arg in "$@"; do
  shift
  case "$arg" in
    "--help")       set -- "$@" "-h" ;;
    "--install")    set -- "$@" "-i" ;;
    "--update")     set -- "$@" "-p" ;;
    "--enable")     set -- "$@" "-e" ;;
    "--disable")    set -- "$@" "-d" ;;
    "--uninstall")  set -- "$@" "-u" ;;
    "--daemon")     set -- "$@" "-m" ;;
    *)              set -- "$@" "$arg"
  esac
done

if [ -z "$arg" ]
then
   echo "$USAGE" >&2
   exit 1
fi

# Get the arguments
while getopts "iudephc:?" o; do
    case "${o}" in
        h|\?)
            echo "$USAGE"
            exit 0
            ;;
        i)
            operation="-install"
            ;;
        u)
            operation="-uninstall"
            ;;
        d)
            operation="-disable"
            ;;
        e)
            operation="-enable"
            ;;
        p)
            operation="-update"
            ;;
        m)
            operation="-daemon"
            ;;
        c)
            COMMAND="$OPTARG"
            ;;
        *)
            echo "$USAGE" >&2
            exit 1
            ;;
    esac
done

shift "$((OPTIND-1))"

# If find_python is not able to find a python installed, $PYTHON will be null.
find_python PYTHON

if [ -z "$PYTHON" ]; then
   echo "No Python interpreter found on the box" >&2
   exit 51 # Not Supported
else
    PYTHON_VER=`${PYTHON} --version 2>&1`
    if [[ "$PYTHON_VER" =~ "Python 2.6" ]] || [[ "$PYTHON_VER" =~ "Python 2.7" ]]; then
        echo $PYTHON_VER
    else
        echo "Expected Python 2.7, found $PYTHON_VER" >&2
        exit 51 # Not Supported
    fi
fi

${PYTHON} ${COMMAND} ${operation} 2>&1
# DONE