#!/usr/bin/bash
#############################################################################
#  Copyright (C) 2013-2015 Lawrence Livermore National Security, LLC.
#  Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER).
#  Written by Albert Chu <chu11@llnl.gov>
#  LLNL-CODE-644248
#
#  This file is part of Magpie, scripts for running Hadoop on
#  traditional HPC systems.  For details, see https://github.com/llnl/magpie.
#
#  Magpie is free software; you can redistribute it and/or modify it
#  under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  Magpie is distributed in the hope that it will be useful, but
#  WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#  General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with Magpie.  If not, see <http://www.gnu.org/licenses/>.
#############################################################################

# These are functions to be called by magpie-run

source ${MAGPIE_SCRIPTS_HOME}/magpie/exports/magpie-exports-submission-type
source ${MAGPIE_SCRIPTS_HOME}/magpie/exports/magpie-exports-dirs
source ${MAGPIE_SCRIPTS_HOME}/magpie/exports/magpie-exports-user
source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-defaults
source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-node-identification
source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-run
source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-log
source ${MAGPIE_SCRIPTS_HOME}/magpie/lib/magpie-lib-paths

# Return 0 if service up, 1 if not
__Magpie_run_check_hbase_up () {
    cd ${HBASE_HOME}

    # example output : "9 servers, 0 dead, 4.7778 average load"
    if echo status | ${hbasecmdprefix}/hbase shell | grep -q "servers"
    then
        return 0
    fi

    return 1
}

Magpie_run_start_hbase () {
    if [ "${HBASE_SETUP}" == "yes" ] && [ "${magpie_run_prior_startup_successful}" == "true" ]
    then
        if [ "${magpie_run_hadoop_setup_successful}" == "0" ]
        then
            Magpie_output_internal_error "Attempt to setup Hbase without Hadoop being setup"
            magpie_run_hbase_should_be_torndown=0
            magpie_run_hbase_setup_successful=0
            return 1
        fi

        if [ "${magpie_run_zookeeper_setup_successful}" == "0" ]
        then
            Magpie_output_internal_error "Attempt to setup Hbase without Zookeeper being setup"
            magpie_run_hbase_should_be_torndown=0
            magpie_run_hbase_setup_successful=0
            return 1
        fi

        cd ${HBASE_HOME}

        if [ ${MAGPIE_JOB_TYPE} != "setuponly" ]
        then
            # Make variables unspecified for launching
            Magpie_make_all_local_dirs_unspecified

            echo "Starting hbase"
            ${hbasesetupscriptprefix}/start-hbase.sh
            if [ "${HBASE_START_THRIFT_SERVER}" == "yes" ]
            then
                ${hbasesetupscriptprefix}/hbase-daemon.sh start thrift -threadpool
            fi

            # Make variables specific now within Magpie
            Magpie_make_all_local_dirs_node_specific

            # My rough estimate for setup time is 30 seconds per 128 nodes
            local sleepwait=`expr ${HBASE_REGIONSERVER_COUNT} \/ 128 \* 30`
            if [ ${sleepwait} -lt 30 ]
            then
                sleepwait=30
            fi
            echo "Waiting ${sleepwait} seconds to allow Hbase daemons to setup"
            sleep ${sleepwait}
            magpie_run_total_sleep_wait=`expr ${magpie_run_total_sleep_wait} + ${sleepwait}`
        fi

        echo "*******************************************************"
        echo "*"
        echo "* Hbase Information"
        echo "*"
        echo "* You can view your Hbase status by launching a web browser and pointing to ..."
        echo "*"
        echo "* Hbase Master: http://${HBASE_MASTER_NODE}:${default_hbase_master_info_port}"
        echo "* Hbase RegionServer: http://<REGIONSERVER>:${default_hbase_regionserver_info_port}"
        echo "*"
        echo "* To access Hbase directly, you'll want to:"
        echo "*"
        echo "*   ${MAGPIE_REMOTE_CMD:-ssh}${MAGPIE_REMOTE_CMD_OPTS:+" "}${MAGPIE_REMOTE_CMD_OPTS} ${HBASE_MASTER_NODE}"
        if echo $MAGPIE_SHELL | grep -q csh
        then
            echo "*   setenv JAVA_HOME \"${JAVA_HOME}\""
            echo "*   setenv HBASE_HOME \"${HBASE_HOME}\""
            echo "*   setenv HBASE_CONF_DIR \"${HBASE_CONF_DIR}\""
        else
            echo "*   export JAVA_HOME=\"${JAVA_HOME}\""
            echo "*   export HBASE_HOME=\"${HBASE_HOME}\""
            echo "*   export HBASE_CONF_DIR=\"${HBASE_CONF_DIR}\""
        fi
        echo "*"
        echo "* Then you can do as you please.  For example to interact in the Hbase shell :"
        echo "*"
        echo "*   \$HBASE_HOME/${hbasecmdprefix}/hbase shell"
        echo "*"

        if [ "${MAGPIE_JOB_TYPE}" == "setuponly" ]
        then
            echo "* To setup, login and set environment variables per the"
            echo "* instructions above, then run:"
            echo "*"
            echo "*   \$HBASE_HOME/${hbasesetupscriptprefix}/start-hbase.sh"
            echo "*"
            echo "* To end/cleanup your session & kill all daemons, login and set"
            echo "* environment variables per the instructions above, then run:"
            echo "*"
            echo "*   \$HBASE_HOME/${hbasesetupscriptprefix}/stop-hbase.sh"
            echo "*"
        fi
        if [ "${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}X" != "X" ]
        then
            echo "* If running interactively, sourcing"
            echo "*"
            echo "* ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}"
            echo "*"
            echo "* will set most common environment variables for your job."
            echo "*"
        fi
        echo "*******************************************************"

        if [ "${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}X" != "X" ]
        then
            if echo $MAGPIE_SHELL | grep -q csh
            then
                echo "setenv HBASE_HOME \"${HBASE_HOME}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "setenv HBASE_CONF_DIR \"${HBASE_CONF_DIR}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "setenv HBASE_LOG_DIR \"${HBASE_LOG_DIR}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "setenv HBASE_MASTER_NODE \"${HBASE_MASTER_NODE}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "setenv HBASE_REGIONSERVER_COUNT \"${HBASE_REGIONSERVER_COUNT}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "setenv HBASE_VERSION \"${HBASE_VERSION}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
            else
                echo "export HBASE_HOME=\"${HBASE_HOME}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "export HBASE_CONF_DIR=\"${HBASE_CONF_DIR}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "export HBASE_LOG_DIR=\"${HBASE_LOG_DIR}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "export HBASE_MASTER_NODE=\"${HBASE_MASTER_NODE}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "export HBASE_REGIONSERVER_COUNT=\"${HBASE_REGIONSERVER_COUNT}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
                echo "export HBASE_VERSION=\"${HBASE_VERSION}\"" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
            fi
            echo "" >> ${MAGPIE_ENVIRONMENT_VARIABLE_SCRIPT}
        fi

        if [ ${MAGPIE_JOB_TYPE} != "setuponly" ]
        then
            # Return 0 if service up, 1 if not
            Magpie_check_service_up "Hbase" "__Magpie_run_check_hbase_up"

            if [ $? -eq 0 ]
            then
                magpie_run_hbase_should_be_torndown=1
                magpie_run_hbase_setup_successful=1
            else
                magpie_run_hbase_should_be_torndown=1
                magpie_run_hbase_setup_successful=0
                magpie_run_prior_startup_successful=false
            fi
        else
            magpie_run_hbase_should_be_torndown=1
            magpie_run_hbase_setup_successful=1
        fi
    else
        magpie_run_hbase_should_be_torndown=0
        magpie_run_hbase_setup_successful=1
    fi
}

Magpie_run_hbase () {
    if [ "${HBASE_JOB}" == "performanceeval" ]
    then
        echo "*******************************************************"
        echo "* Running Performance Evaluation"
        echo "*******************************************************"
        ${MAGPIE_SCRIPTS_HOME}/magpie/run/magpie-run-execute script ${MAGPIE_SCRIPTS_HOME}/magpie/job/magpie-job-hbase-performanceeval &
        local scriptpid=$!
        Magpie_wait_script_sigusr2_on_job_timeout ${scriptpid}
    else
        Magpie_output_internal_error "HBASE_JOB = ${HBASE_JOB} not handled"
    fi
}

Magpie_run_stop_hbase () {
    if [ "${magpie_run_hadoop_teardown_complete}" == "1" ]
    then
        Magpie_output_internal_warning "tearing down Hbase after Hadoop"
    fi

    if [ "${magpie_run_zookeeper_teardown_complete}" == "1" ]
    then
        Magpie_output_internal_warning "tearing down Hbase after Zookeeper"
    fi

    if [ "${HBASE_SETUP}" == "yes" ] && [ "${magpie_run_hbase_should_be_torndown}" == "1" ]
    then
        if [ ${MAGPIE_JOB_TYPE} != "setuponly" ]
        then
            cd ${HBASE_HOME}

            echo "Stopping hbase"

            if [ "${magpie_run_hbase_setup_successful}" == "1" ]
            then
                # Hbase compaction meaningless if this is a one time run
                if [ "${MAGPIE_ONE_TIME_RUN}" != "yes" ]
                then
                    if [ "${HBASE_MAJOR_COMPACTION_ON_SHUTDOWN}X" == "X" ] || [ "${HBASE_MAJOR_COMPACTION_ON_SHUTDOWN}" == "yes" ]
                    then
                        echo "Doing major compaction before shutting down ..."

                        local command="echo list"
                        echo "Running $command in hbase shell" >&2
                        local listoutput=`$command | ${hbasecmdprefix}/hbase shell | sed -n '/TABLE/,/seconds/p' | tail -n+2 | head -n -1`

                        for table in ${listoutput}
                        do
                            command="echo major_compact '${table}'"
                            echo "Running $command in hbase shell" >&2
                            $command | ${hbasecmdprefix}/hbase shell
                        done
                    fi
                fi
            fi

            # Make variables unspecified for shutdown
            Magpie_make_all_local_dirs_unspecified

            if [ "${HBASE_START_THRIFT_SERVER}" == "yes" ]
            then
                ${hbasesetupscriptprefix}/hbase-daemon.sh stop thrift
            fi

            ${hbasesetupscriptprefix}/stop-hbase.sh

            # Make variables specific now within Magpie
            Magpie_make_all_local_dirs_node_specific
        fi
    fi
    magpie_run_hbase_teardown_complete=1
}
