#!/bin/bash
################################################################################
# Filename: ./src/base/include/qrm-nodes-functions
# 
# The contents of this file are subject to the Qlusters Public License
# Version 1.1 (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.openqrm.org/content/view/33/69/.
# 
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
# 
# The Original Code is openQRM.
# 
# The Initial Developer of the Original Code is Qlusters Corporation. Portions
# created by Qlusters Corporation are Copyright (C) 2003-2005. All Rights
# Reserved.
# 
# Contributor(s):
# 
# Description:
# 
# Comments:
################################################################################
# Qrm node functions
# 

# source node paratmeres
. /var/qrm/conf/node-parameter.conf 1>/dev/null 2>&1

# function to send an event to the Qrm-server
# parameter 1 : name (name of the event, for hooks)
# parameter 2 : priority  (can be 1 for error, 2 for notice)
# parameter 3 : event source (what component caused the event)
# parameter 4 : description (what happened)

export q_wget="/usr/bin/wget"
if wget --help 2> /dev/null | grep "\--no-check-certificate" > /dev/null; then
       export q_wget="${q_wget} --no-check-certificate"
fi


function set_node_error() {
  local ERROR_MSG=$1
  export QRM_SERVER_IP=$QRM_SERVER_IP_ADDRESS
  $QRM_NODES_BASE_DIR/qrm/bin/qrm-cli event add -k Node.State.Operation.Error -t moreInfo="$ERROR_MSG" --internal_vm_id $CS_ID
  echo "$ERROR_MSG" > /dev/console
}



function get_pkg() {
	PKG=$1
	FILE=$2

	if [ ! -x "$FILE" ]; then
		PKG_NAME=`basename $PKG`
		case "$PKG" in
			http:*)
		        # TODO: choose location by package size.
			    wget -q "$PKG"
			    tar -zxf $PKG_NAME
			    rm $PKG_NAME
				;;
			nfs:*)
				# it is better to fail then to double mount
				if ! cat /proc/mounts | grep -q "`basename $PWD`/$PKG_NAME"; then
					mkdir -p $PKG_NAME
					mount -o ro $PKG $PKG_NAME
				fi
				;;
		esac
	fi

	if [ -x "$FILE" ]; then
		return 0
	else
		return 1
	fi

}

function run_services() {
	WHEN=$1

	if [ -z "$BOOT_SERVICES" ]; then
		echo "ERROR: Boot services not set"
		return
	fi

	IFS='|'
	for S in $BOOT_SERVICES; do
		IFS=','
		SERVICE=($S)

		SERVICE_WHEN=${SERVICE[0]}
		SERVICE_PKG=${SERVICE[1]}
		SERVICE_INIT=${SERVICE[2]}

		if [ "$WHEN" = "$SERVICE_WHEN" ]; then
			#echo "pkg=$SERVICE_PKG init=$SERVICE_INIT"
			if get_pkg $SERVICE_PKG $SERVICE_INIT; then
				$SERVICE_INIT &
			else
				echo "ERROR: Unable to get package $SERVICE_PKG"
			fi
		fi

	done

}





function qrm_save_halt() {
	# do a quick check
	if [ "$VE_NAME" != "idle" ]; then
		SAVEHALT=1
		HALTNETWORK=127.0.0.0
		INTERFACE=`/sbin/ifconfig | awk '/^eth.:qrm/ { print $1 }' | cut -d":" -f 1`
		if ! /sbin/ifconfig $INTERFACE | grep inet 1>/dev/null 2>&1; then
			# finding an ip-address to save halt the system
			echo "NOTICE: Searching a free ip-address for $INTERFACE for shutting down save"
			BASEHALTNETWORK=`echo $HALTNETWORK | cut -d'.' -f 1-3`
			for (( TESTIP=2; TESTIP<255; TESTIP++ )); do
				TESTHALTIP="$BASEHALTNETWORK.$TESTIP"
				if ! arping -c 1 -w 1 $TESTHALTIP 1>/dev/null 2>&1; then
					export HALTIP=$TESTHALTIP
					break
				fi
			done
			# bringing up the haltip
			if [ -z "$HALTIP" ]; then
				echo "ERROR: could not find a valid ip to halt the system"
				return 1
			else
				ifconfig $INTERFACE $HALTIP up
			fi
		fi
	fi
	return 0
}

# getting nodes-paramter file from the QRM-servlet
function get_nodes_parameter() {

        if [ -z "$QRM_SERVER_IP_ADDRESS" ] || [ -z "$CS_ID" ]; then
                qerror "ERROR: Failed to get configuration from /var/qrm/conf/node-parameter.conf"
                return 2
        fi

        unset ROOT_MOUNT
        while (true); do
                $q_wget -O "/var/qrm/conf/node-parameter.conf" -q "http://${QRM_SERVER_IP_ADDRESS}:$QRM_EVENT_MONITOR_PORT/config/parameters?type=$CS_TYPE&id=$CS_ID&ip=&name="
                QRET=$?
                . /var/qrm/conf/node-parameter.conf
                if [ ! -z "$ROOT_MOUNT" ]; then
                        break
                fi
                qwarning "WARNING: Could not get a valid nodes-parameter file. Retrying...."
                sleep 5
        done
        return $QRET
}

##############################################################
#Loading qrm invironment which permits us to restart qrminfod#
#this part istaken from qrm-init start script                #
##############################################################
function q_qrm_environment_load() {

	. /var/qrm/conf/node-parameter.conf
	
	# for qrm-execd + qrm-infod
	export QRM_SERVER_BASE_DIR
	export QRM_NODES_LOG_DIR
	export QRM_NODES_BASE_DIR
	export q_qrm_ip=$QRM_SERVER_IP_ADDRESS
	export q_statistics_servlet="http://$q_qrm_ip/monitor/submit.do"
	export q_peer=$QRM_SERVER_IP_ADDRESS
	export q_node_ip=$CS_QRM_IP
	export q_res_ip=$CS_QRM_IP
	export q_node_id=$CS_ID
	export q_res_id=$CS_ID
	export q_ve_id=$VE_ID
	export q_gather_interval=1
	export q_cpu_util_changedelta=0.1
	export q_cpu_load_changedelta=0.1
	export q_mem_used_changedelta=20
	export q_swap_used_changedelta=20
	export q_node_heartbeat=$CS_HEARTBEAT
	export q_min_stats_interval=60
	export q_nodes_logdir=$QRM_NODES_LOG_DIR
	export q_agent_mode=$CS_TYPE
	export q_nodes_logdir=$QRM_NODES_LOG_DIR
	export QRM_EASYMIGRATION_CONF=/etc/qrm/easymigration.conf
	if [ "$QRM_NODES_LOG_DIR" != "syslog" ]; then
		export LOG_SYSLOG=false
	else
		export LOG_SYSLOG=true
	fi
	export LOG_DIR=$QRM_NODES_LOG_DIR
	export LOCKFILE=$QRM_NODES_LOG_DIR/qrm.lock
}


