#!/bin/bash

cp ../lib/kafka-clients-0.10.2.2.jar ./
KAFKA_JAR_PATH=kafka-clients-0.10.2.2.jar
APP_NAME=stream.hbase.farm_
APP_VERSION=2021.8.6
APP_JAR=../lib/uml-stream-hbase-farm-2.0.0.jar
MAIN_CLASS=com.uml.tech.spark.StreamingApp

        # ---------------项目需要调整参数------------------
# 分区数
NUM_PARTITIONS=8
# 窗口周期(秒)
WINDOW_DURATIONS=5
# 项目启动时，初始化executor的数量
INITIAL_EXECUTORS=2
# 最小executor数量
MIN_EXECUTORS=2
# 最大executor数量
MAX_EXECUTORS=8
# driver内存
DRIVER_MEMORY=2g
# executor核心数
EXECUTOR_CORES=2
# executor内存
EXECUTOR_MEMORY=4g
# executor空闲多久没有收到任务就被杀掉
EXECUTOR_IDLE_TIMEOUT=60s
# executor执行任务超过多久，就创建新的executor，最大创建到 MAX_EXECUTORS 个，指数型个数创建，1、2、4、8这种方式创建
SCHEDULER_BACKLOG_TIMEOUT=30s
# 再次触发创建新executor的间隔时间
SUSTAINED_SCHEDULER_BACKLOG_TIMEOUT=60s
# 每批从kafka分区中拉取多少数据
MAX_RATE_PER_PARTITION=100000

APP_ID=`yarn application -list |grep ${APP_NAME} |awk '{print $1}'`

if [ "${APP_ID}" != "" ] ; then
  echo `yarn application -kill ${APP_ID}`
fi

echo "Start Spark Application ${APP_NAME}${APP_VERSION} ...."

for jar in ../lib/*.jar
do
  if [ ${jar} != ${APP_JAR} ] ; then
    LIBJARS=${jar},${LIBJARS}
  fi
done

for file in ../resources/*; do
  if [ -f ${file} ]; then
    RESOURCES_FILES=${file},${RESOURCES_FILES}
  fi
done

spark-submit \
  --class ${MAIN_CLASS} \
  --master yarn \
  --deploy-mode cluster \
  --jars ${LIBJARS} \
  --files ${RESOURCES_FILES} \
  --conf spark.app.name=${APP_NAME}${APP_VERSION} \
  --driver-memory ${DRIVER_MEMORY} \
    --executor-cores ${EXECUTOR_CORES} \
    --executor-memory ${EXECUTOR_MEMORY} \
    --driver-java-options "-XX:+UseG1GC" \
    --driver-java-options -verbose:class \
    --conf spark.executor.extraJavaOptions="-XX:+UseG1GC" \
    --conf spark.app.name=${APP_NAME}${APP_VERSION} \
    --conf spark.driver.maxResultSize=0 \
    --conf spark.dynamicAllocation.initialExecutors=${INITIAL_EXECUTORS} \
    --conf spark.dynamicAllocation.minExecutors=${MIN_EXECUTORS} \
    --conf spark.dynamicAllocation.maxExecutors=${MAX_EXECUTORS} \
    --conf spark.dynamicAllocation.executorIdleTimeout=${EXECUTOR_IDLE_TIMEOUT} \
    --conf spark.dynamicAllocation.schedulerBacklogTimeout=${SCHEDULER_BACKLOG_TIMEOUT} \
    --conf spark.dynamicAllocation.sustainedSchedulerBacklogTimeout=${SUSTAINED_SCHEDULER_BACKLOG_TIMEOUT} \
    --conf spark.dynamicAllocation.enabled=true \
    --conf spark.shuffle.service.enabled=true \
    --conf spark.memory.useLegacyMode=true \
    --conf spark.storage.memoryFraction=0.3 \
    --conf spark.streaming.kafka.maxRatePerPartition=${MAX_RATE_PER_PARTITION} \
    --conf spark.streaming.stopGracefullyOnShutdown=true \
    --conf spark.driver.extraClassPath=${KAFKA_JAR_PATH} \
    --conf spark.executor.extraClassPath=${KAFKA_JAR_PATH} \
  $APP_JAR \
  5000