#!/bin/bash
Jenkins_Path='/data/script/Jenkins_Scripts'
cd ${Jenkins_Path}/EIC/Ngx-Env &&if [ -f "${ENV}.sh" ];then source ${Jenkins_Path}/EIC/Ngx-Env/${ENV}.sh ;fi
check_file=$(find $WORKSPACE -name check.yml |grep -v 'https' |grep '/src/main/resources/')
NGX_API(){
if [ -f "$check_file" ];then
Server_Port=$(cat $check_file | shyaml get-values $ENV.server_port 2>/dev/null)
if [ -n "$Server_Port" ];then
if [ -n "${Domain}" ];then UPSTREAM="${Domain}" ;fi
upstream=${UPSTREAM//[\/.]/_}
#service_ip=$(ping $target -c 1 |grep PING |awk '{print $3}' |sed 's/[()]//g')
echo "##########################################################################################"
for ip in ${nginx_list}; do
#echo "### 【NGINX】 $ip"
if [ $NGX_STATUS == "DOWN" ];then
curl -sq "http://${ip}/dynamic?upstream=${upstream}&server=${service_ip}:${Server_Port}&down=" | egrep "server.+${service_ip}:${Server_Port}.+;$" >/dev/null || echo "Action: down Upstream: $upstream Server: ${service_ip}:${Server_Port} Failed"
echo -e "${service_ip}:${Server_Port} 已从【NGINX】 < $ip > 摘除!"
elif [ $NGX_STATUS == "UP" ];then
curl -sq "http://${ip}/dynamic?upstream=${upstream}&server=${service_ip}:${Server_Port}&up=" | egrep "server.+${service_ip}:${Server_Port}.+;$" >/dev/null || echo "Action: up Upstream: $upstream Server: ${service_ip}:${Server_Port} Failed"
echo -e "${service_ip}:${Server_Port} 已从【NGINX】 < $ip > 加载!"
else
echo "NGINX Status is error"
fi
echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
curl -sq "http://${ip}/dynamic?upstream=${upstream}&verbose="
done
echo "##########################################################################################"
echo
sleep 10
else
echo 'Nginx服务端口不存在,无需操作!'
fi
else
echo '检测文件不存在,Nginx 无需操作!'
fi
}
GET_PORT(){
for port in ${PORT_ALL}
do
check_url="http://${service_ip}:${port}/isDubboActive"
#check_code=$(curl -I -sS --retry 2 -m 10 -o /dev/null -s -w %{http_code} ${check_url})
check_code=$(curl -I -sS --retry 1 -m 5 -o /dev/null -s -w %{http_code} ${check_url} 2>/dev/null)
echo -e "Url: ${check_url} Check_Code: ${check_code}"
if [ "${check_code}" == "200" ];then
#if [ -n "${check_code}" ];then
HTTP_PORT=${port} &&break
else
HTTP_PORT="None"
fi
done
}
check_status(){
#check_file=$(find $WORKSPACE -mindepth 5 -name check.yml)
#echo "检测文件: $check_file"
if [[ -n "${HTTP_PORT}" && ${HTTP_PORT} != "None" ]];then
Check_Httpstatus
elif [ -f "$check_file" ];then
check_port=$(cat $check_file | shyaml get-values $ENV.check_port 2>/dev/null)
check_max=$(cat $check_file | shyaml get-value $ENV.check_max)
check_interval=$(cat $check_file | shyaml get-value $ENV.check_interval)
if [ -n "`echo ${check_port} |sed -n '/^[0-9][0-9]*$/p'`" ];then
for x in $check_port
do
CHECK_PORT=$x
check_true
done
elif [ -n "`echo ${Server_Port} |sed -n '/^[0-9][0-9]*$/p'`" ];then
CHECK_PORT=$Server_Port
check_true
else
echo '检测端口不存在!'
fi
else
echo '检测文件不存在,无需检测!'
fi
}
Check_Httpstatus(){
sum=1
check_max=10
echo "检测端口: $HTTP_PORT"
while true
do
if [ $sum -le $check_max ];then
curl -I -s -o /dev/null http://${service_ip}:${port}/isDubboActive
if [ $? == 0 ];then
check_res=$(curl -X GET -Ss --retry 2 --connect-timeout 5 http://${service_ip}:${port}/isDubboActive)
status_res=$(echo "${check_res}" |jq -c '.status'|sed "s/['\"]//g")
msg_res=$(echo "${check_res}" |jq -c '.msg'|sed "s/['\"]//g")
echo -e "$status_res,$msg_res"
if [[ "$status_res" == "1" && ${msg_res} == "ok" ]];then
#if [[ $status_res -eq 1 -a ${msg_res} == "ok" ];then
echo -e "${check_res} \n 接口探测正常,检测通过!" &&break
else
echo "第${sum}次检测,接口探测异常!"
let sum=sum+1
sleep 5
fi
else
echo "第${sum}次检测,服务未启动..."
let sum=sum+1
sleep 5
fi
else
echo "端口未启动或CODE码异常,请检查!" && exit 911
fi
done
}
check_true(){
sum=1
echo "检测端口: $CHECK_PORT"
echo "检测间隔: $check_interval"
echo "检测最大次数: $check_max"
while true
do
if [ $sum -le $check_max ];then
check_cmd="lsof -i :${CHECK_PORT} |wc -l"
check_res=$(ssh -q -p8822 "$target" "$check_cmd")
if [ ${check_res} -ge 1 ];then
echo "服务启动成功,检测通过!" && break
else
echo "第${sum}次检测,服务未启动..."
let sum=sum+1
sleep $check_interval
fi
else
echo "服务启动失败,请检查!!!"
exit 999
fi
done
}
for jarpath in $(find $WORKSPACE -type f -path "*/target/*.jar" | egrep ${PACKAGE_FILTER} | egrep -v ${PACKAGE_EXCLUDE})
do
# 提取包名作为项目名
project_name=$(basename "$jarpath" | awk '$0~/\.jar$/{gsub("(-[0-9.-]+[A-Z]+|).jar","",$0);print $0}')
if [ -z "$project_name" ]; then
echo "无法获取项目名称,或项目名称格式错误!"
exit 100
fi
target_dir="/data/service/${project_name}"
target_path="/data/service/${project_name}/${project_name}.jar"
# JVM参数
LOGS_DIR="/data/logs/${project_name}"
JVM_GCPOLICY_OPTS="-Xnoclassgc -XX:MaxTenuringThreshold=7 -XX:GCTimeRatio=19 -XX:+DisableExplicitGC -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:+CMSParallelRemarkEnabled -XX:+CMSClassUnloadingEnabled -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=70 -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+UseFastAccessorMethods -XX:+UseCompressedOops"
JVM_GCLOG_OPTS="-XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -Xloggc:${LOGS_DIR}/debug/gc.$(date +%Y%m%d_%H%M%S).log"
JVM_DUMP_OPTS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${LOGS_DIR}/debug/${project_name}.$(date +%Y%m%d_%H%M%S).dump"
[ -n "$DEBUG_PORT" ] && JVM_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=${DEBUG_PORT},suspend=n,server=y" || JVM_DEBUG_OPTS=""
[ -n "$JMX_PORT" ] && JAVA_JMX_OPTS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=${JMX_PORT} -Dcom.sun.management.jmxremote.rmi.port=${JMX_PORT}" || JAVA_JMX_OPTS=""
[ -n "$APOLLO_CLUSTER" ] && JVM_OTHER_OPTS="-Dfile.encoding=UTF-8 -Djava.awt.headless=true -Djava.io.tmp=/tmp -Dapollo.cluster=${APOLLO_CLUSTER}" || JVM_OTHER_OPTS="-Dfile.encoding=UTF-8 -Djava.awt.headless=true -Djava.io.tmp=/tmp"
JAVA_OPTIONS="$JVM_MEM_OPTS $JVM_GCPOLICY_OPTS $JVM_GCLOG_OPTS $JVM_OTHER_OPTS $JAVA_JMX_OPTS $JVM_DEBUG_OPTS"
echo "--------------------------------【$project_name】---------------------------------------"
echo "当前操作: 【$ACTION】"
echo "当前环境: 【$ENV】"
echo "项目名称: 【$project_name】"
echo "服务路径: 【$target_path】"
i=1
for target in $(echo "$DEPLOY_HOST" | awk -F '[,; ]' '{for(i=1;i<=NF;i++){print $i}}'); do
RETVAL=0
service_ip=$(ping $target -c 1 |grep PING |awk '{print $3}' |sed 's/[()]//g')
# JAVA_PID=$(ssh -q -p8822 "$target" ps -ef |grep "${project_name}" |grep -v "grep" |grep "java" |awk "{print \$2}")
# PORT_ALL=$(ssh -q -p8822 "$target" netstat -tnlp |grep "${JAVA_PID}" |awk "{print \$4}"|cut -d : -f 2)
# if [ -z "${HTTP_PORT}" ];then GET_PORT &&echo "JAVA_PID:${JAVA_PID} HTTP_PORT:${HTTP_PORT}";fi
if [ "$ACTION" = "代码发布" ]; then
if [ $i -gt 1 ];then echo -e "等待10s继续发布:\n" && sleep 10 ;fi
echo "发布主机: 【$i】 -> $target"
NGX_STATUS="DOWN" &&NGX_API
# 环境检查
ssh -q -p8822 "$target" "if ! id app &>/dev/null;then groupadd -g 618 app && useradd -g 618 -u 618 -r -m app;fi; mkdir -p \"/data/service/${project_name}\" \"/data/logs/${project_name}/debug\" 2>&1 && chown -R app. \"/data/service/${project_name}\" \"/data/logs/${project_name}\"; [ -f /usr/lib/systemd/system/service@.service ] || exit 1" || \
(scp -q -P8822 /data/script/service@.service "$target:/usr/lib/systemd/system/service@.service" && ssh -q -p8822 "$target" "systemctl daemon-reload")
echo -n "拷贝文件: "
rsync -az -e "ssh -q -p 8822" "$jarpath" "root@${target}:${target_path}" 2>&1 || RETVAL=1
if [ $RETVAL -eq 0 ]; then
echo "成功!"
echo -n "停止服务: "
ssh -q -p8822 "$target" "systemctl stop service@$project_name" || RETVAL=1
if [ $RETVAL -eq 0 ]; then
echo "成功!"
else
EXITCODE=1
echo "失败!"
fi
RETVAL=0
echo -e "10s后重新启动服务: \n"
sleep 10
ssh -q -p8822 "$target" "echo -e \"OPTS=${JAVA_OPTIONS}\\nPROFILE=--spring.profiles.active=${ENV}\" > /data/service/${project_name}/.env; systemctl restart service@$project_name" || RETVAL=1
if [ $RETVAL -eq 0 ]; then
echo "启动成功!"
else
EXITCODE=1
echo "启动失败! "
fi
echo "启动命令:systemctl restart service@$project_name"
echo "启动日志:"
echo
sleep 5
ssh -q -p8822 "$target" "systemctl enable service@$project_name;systemctl status service@$project_name" || EXITCODE=1
i=`expr $i + 1`
# if [ -z "${Domain}" ] && [[ "${project_name}" =~ "http" ]]; then echo '跳过端口检测!'; else check_status; fi
NGX_STATUS="UP" &&NGX_API
else
RETVAL=0
EXITCODE=1
echo "失败!"
fi
else
echo "当前主机: 【$((i++))】 -> $target"
case $ACTION in
"停止服务")
DO_ACTION="stop"
;;
"启动服务")
DO_ACTION="start"
;;
"重启服务")
DO_ACTION="restart"
;;
*)
DO_ACTION="status"
esac
if [ "$DO_ACTION" = "stop" ]; then
OTHER_ACTION="systemctl disable service@$project_name"
else
OTHER_ACTION=":"
fi
if [ "$DO_ACTION" != "status" ]; then
echo "执行命令:systemctl $DO_ACTION service@$project_name"
ssh -q -p8822 "$target" "$OTHER_ACTION; systemctl $DO_ACTION service@$project_name" || EXITCODE=1
sleep 3
fi
echo "查看状态:"
ssh -q -p8822 "$target" "systemctl status service@$project_name && echo '*************** 服务正常运行中 ***************' || echo '*************** 服务未启动或已停止 ***************'" || EXITCODE=1
fi
done
done
exit $EXITCODE
#!/bin/bash
APP_NAME=ai-material-generated.jar
SPRING_PROFILES_ACTIVE=ns_test
#使用说明,用来提示输入参数
usage() {
echo "Usage: sh 执行脚本.sh [start|stop|restart[r]|status]"
exit 1
}
#检查程序是否在运行
is_exist() {
pid=`ps -ef|grep $APP_NAME|grep -v grep|awk '{print $2}' `
#如果不存在返回1,存在返回0
if [ -z "${pid}" ]; then
return 1
else
return 0
fi
}
#启动方法
start() {
is_exist
if [ $? -eq "0" ]; then
echo " ## ${APP_NAME} 该服务已经运行. pid=${pid} ."
else
if [ "$2" != "" ];
then
SPRING_PROFILES_ACTIVE=$2
fi
nohup java -server -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m -Xms512m -Xmx1024m -Xmn256m -Xss512k -verbose:gc -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=oom.hprof -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=18887 -jar $APP_NAME --spring.profiles.active=${SPRING_PROFILES_ACTIVE} > /dev/null 2>&1 &
echo " ## $APP_NAME 启动成功 ! 已激活profiles: ${SPRING_PROFILES_ACTIVE}"
fi
}
#停止方法
stop() {
is_exist
if [ $? -eq "0" ]; then
kill -15 $pid
echo " ## $APP_NAME 服务停止成功 !"
else
echo " ## ${APP_NAME} 服务没法有运行,无法停止"
fi
}
#输出运行状态
status() {
is_exist
if [ $? -eq "0" ]; then
echo " ## ${APP_NAME} 服务正在运行. 进程号(pid): ${pid}"
else
echo " ## ${APP_NAME} 服务已停止运行."
fi
}
deployJar(){
if [ -d "./boot_jar/classes" ]; then
cp $APP_NAME ./boot_jar
cd ./boot_jar
rm -rf ./BOOT-INF/*
mv classes ./BOOT-INF
jar -uf $APP_NAME BOOT-INF/*
echo " ## ${APP_NAME} 更新jar中的项目文件成功 !"
echo " ## $APP_NAME 未发现需要更新的jar中的项目文件 !"
if [ -f "./boot_jar/$APP_NAME" ]; then
rm -rf $APP_NAME
mv ./boot_jar/$APP_NAME .
echo " ## $APP_NAME 服务jar部署成功 !"
else
echo " ## $APP_NAME 未发现服务jar包 !"
fi
fi
}
#重启
restart() {
stop
deployJar
start
}
#根据输入参数,选择执行对应方法,不输入则执行使用说明
case "$1" in
"start")
start
;;
"stop")
stop
;;
"status")
status
;;
"restart")
restart
;;
"r")
restart
;;
*)
usage
;;
esac
监控并自动重启:
#!/bin/bash
i=1
while(($i > 0))
do
result=`ps -ef|grep -v grep|grep "ai-gateway-zuul.jar"|wc -l`
if [ $result != 1 ]
then
nohup java -server -XX:MetaspaceSize=256m -XX:MaxMetaspaceSize=512m -Xms512m -Xmx1024m -Xmn256m -Xss512k -verbose:gc -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=oom.hprof -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=18888 -jar ai-gateway-zuul.jar > /dev/null 2>&1 &
fi
sleep 2
done