1. #!/bin/bash
    2. Jenkins_Path='/data/script/Jenkins_Scripts'
    3. cd ${Jenkins_Path}/EIC/Ngx-Env &&if [ -f "${ENV}.sh" ];then source ${Jenkins_Path}/EIC/Ngx-Env/${ENV}.sh ;fi
    4. check_file=$(find $WORKSPACE -name check.yml |grep -v 'https' |grep '/src/main/resources/')
    5. NGX_API(){
    6. if [ -f "$check_file" ];then
    7. Server_Port=$(cat $check_file | shyaml get-values $ENV.server_port 2>/dev/null)
    8. if [ -n "$Server_Port" ];then
    9. if [ -n "${Domain}" ];then UPSTREAM="${Domain}" ;fi
    10. upstream=${UPSTREAM//[\/.]/_}
    11. #service_ip=$(ping $target -c 1 |grep PING |awk '{print $3}' |sed 's/[()]//g')
    12. echo "##########################################################################################"
    13. for ip in ${nginx_list}; do
    14. #echo "### 【NGINX】 $ip"
    15. if [ $NGX_STATUS == "DOWN" ];then
    16. 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"
    17. echo -e "${service_ip}:${Server_Port} 已从【NGINX】 < $ip > 摘除!"
    18. elif [ $NGX_STATUS == "UP" ];then
    19. 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"
    20. echo -e "${service_ip}:${Server_Port} 已从【NGINX】 < $ip > 加载!"
    21. else
    22. echo "NGINX Status is error"
    23. fi
    24. echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    25. curl -sq "http://${ip}/dynamic?upstream=${upstream}&verbose="
    26. done
    27. echo "##########################################################################################"
    28. echo
    29. sleep 10
    30. else
    31. echo 'Nginx服务端口不存在,无需操作!'
    32. fi
    33. else
    34. echo '检测文件不存在,Nginx 无需操作!'
    35. fi
    36. }
    37. GET_PORT(){
    38. for port in ${PORT_ALL}
    39. do
    40. check_url="http://${service_ip}:${port}/isDubboActive"
    41. #check_code=$(curl -I -sS --retry 2 -m 10 -o /dev/null -s -w %{http_code} ${check_url})
    42. check_code=$(curl -I -sS --retry 1 -m 5 -o /dev/null -s -w %{http_code} ${check_url} 2>/dev/null)
    43. echo -e "Url: ${check_url} Check_Code: ${check_code}"
    44. if [ "${check_code}" == "200" ];then
    45. #if [ -n "${check_code}" ];then
    46. HTTP_PORT=${port} &&break
    47. else
    48. HTTP_PORT="None"
    49. fi
    50. done
    51. }
    52. check_status(){
    53. #check_file=$(find $WORKSPACE -mindepth 5 -name check.yml)
    54. #echo "检测文件: $check_file"
    55. if [[ -n "${HTTP_PORT}" && ${HTTP_PORT} != "None" ]];then
    56. Check_Httpstatus
    57. elif [ -f "$check_file" ];then
    58. check_port=$(cat $check_file | shyaml get-values $ENV.check_port 2>/dev/null)
    59. check_max=$(cat $check_file | shyaml get-value $ENV.check_max)
    60. check_interval=$(cat $check_file | shyaml get-value $ENV.check_interval)
    61. if [ -n "`echo ${check_port} |sed -n '/^[0-9][0-9]*$/p'`" ];then
    62. for x in $check_port
    63. do
    64. CHECK_PORT=$x
    65. check_true
    66. done
    67. elif [ -n "`echo ${Server_Port} |sed -n '/^[0-9][0-9]*$/p'`" ];then
    68. CHECK_PORT=$Server_Port
    69. check_true
    70. else
    71. echo '检测端口不存在!'
    72. fi
    73. else
    74. echo '检测文件不存在,无需检测!'
    75. fi
    76. }
    77. Check_Httpstatus(){
    78. sum=1
    79. check_max=10
    80. echo "检测端口: $HTTP_PORT"
    81. while true
    82. do
    83. if [ $sum -le $check_max ];then
    84. curl -I -s -o /dev/null http://${service_ip}:${port}/isDubboActive
    85. if [ $? == 0 ];then
    86. check_res=$(curl -X GET -Ss --retry 2 --connect-timeout 5 http://${service_ip}:${port}/isDubboActive)
    87. status_res=$(echo "${check_res}" |jq -c '.status'|sed "s/['\"]//g")
    88. msg_res=$(echo "${check_res}" |jq -c '.msg'|sed "s/['\"]//g")
    89. echo -e "$status_res,$msg_res"
    90. if [[ "$status_res" == "1" && ${msg_res} == "ok" ]];then
    91. #if [[ $status_res -eq 1 -a ${msg_res} == "ok" ];then
    92. echo -e "${check_res} \n 接口探测正常,检测通过!" &&break
    93. else
    94. echo "第${sum}次检测,接口探测异常!"
    95. let sum=sum+1
    96. sleep 5
    97. fi
    98. else
    99. echo "第${sum}次检测,服务未启动..."
    100. let sum=sum+1
    101. sleep 5
    102. fi
    103. else
    104. echo "端口未启动或CODE码异常,请检查!" && exit 911
    105. fi
    106. done
    107. }
    108. check_true(){
    109. sum=1
    110. echo "检测端口: $CHECK_PORT"
    111. echo "检测间隔: $check_interval"
    112. echo "检测最大次数: $check_max"
    113. while true
    114. do
    115. if [ $sum -le $check_max ];then
    116. check_cmd="lsof -i :${CHECK_PORT} |wc -l"
    117. check_res=$(ssh -q -p8822 "$target" "$check_cmd")
    118. if [ ${check_res} -ge 1 ];then
    119. echo "服务启动成功,检测通过!" && break
    120. else
    121. echo "第${sum}次检测,服务未启动..."
    122. let sum=sum+1
    123. sleep $check_interval
    124. fi
    125. else
    126. echo "服务启动失败,请检查!!!"
    127. exit 999
    128. fi
    129. done
    130. }
    131. for jarpath in $(find $WORKSPACE -type f -path "*/target/*.jar" | egrep ${PACKAGE_FILTER} | egrep -v ${PACKAGE_EXCLUDE})
    132. do
    133. # 提取包名作为项目名
    134. project_name=$(basename "$jarpath" | awk '$0~/\.jar$/{gsub("(-[0-9.-]+[A-Z]+|).jar","",$0);print $0}')
    135. if [ -z "$project_name" ]; then
    136. echo "无法获取项目名称,或项目名称格式错误!"
    137. exit 100
    138. fi
    139. target_dir="/data/service/${project_name}"
    140. target_path="/data/service/${project_name}/${project_name}.jar"
    141. # JVM参数
    142. LOGS_DIR="/data/logs/${project_name}"
    143. 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"
    144. JVM_GCLOG_OPTS="-XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -Xloggc:${LOGS_DIR}/debug/gc.$(date +%Y%m%d_%H%M%S).log"
    145. JVM_DUMP_OPTS="-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${LOGS_DIR}/debug/${project_name}.$(date +%Y%m%d_%H%M%S).dump"
    146. [ -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=""
    147. [ -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=""
    148. [ -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"
    149. JAVA_OPTIONS="$JVM_MEM_OPTS $JVM_GCPOLICY_OPTS $JVM_GCLOG_OPTS $JVM_OTHER_OPTS $JAVA_JMX_OPTS $JVM_DEBUG_OPTS"
    150. echo "--------------------------------【$project_name】---------------------------------------"
    151. echo "当前操作: 【$ACTION】"
    152. echo "当前环境: 【$ENV】"
    153. echo "项目名称: 【$project_name】"
    154. echo "服务路径: 【$target_path】"
    155. i=1
    156. for target in $(echo "$DEPLOY_HOST" | awk -F '[,; ]' '{for(i=1;i<=NF;i++){print $i}}'); do
    157. RETVAL=0
    158. service_ip=$(ping $target -c 1 |grep PING |awk '{print $3}' |sed 's/[()]//g')
    159. # JAVA_PID=$(ssh -q -p8822 "$target" ps -ef |grep "${project_name}" |grep -v "grep" |grep "java" |awk "{print \$2}")
    160. # PORT_ALL=$(ssh -q -p8822 "$target" netstat -tnlp |grep "${JAVA_PID}" |awk "{print \$4}"|cut -d : -f 2)
    161. # if [ -z "${HTTP_PORT}" ];then GET_PORT &&echo "JAVA_PID:${JAVA_PID} HTTP_PORT:${HTTP_PORT}";fi
    162. if [ "$ACTION" = "代码发布" ]; then
    163. if [ $i -gt 1 ];then echo -e "等待10s继续发布:\n" && sleep 10 ;fi
    164. echo "发布主机: 【$i】 -> $target"
    165. NGX_STATUS="DOWN" &&NGX_API
    166. # 环境检查
    167. 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" || \
    168. (scp -q -P8822 /data/script/service@.service "$target:/usr/lib/systemd/system/service@.service" && ssh -q -p8822 "$target" "systemctl daemon-reload")
    169. echo -n "拷贝文件: "
    170. rsync -az -e "ssh -q -p 8822" "$jarpath" "root@${target}:${target_path}" 2>&1 || RETVAL=1
    171. if [ $RETVAL -eq 0 ]; then
    172. echo "成功!"
    173. echo -n "停止服务: "
    174. ssh -q -p8822 "$target" "systemctl stop service@$project_name" || RETVAL=1
    175. if [ $RETVAL -eq 0 ]; then
    176. echo "成功!"
    177. else
    178. EXITCODE=1
    179. echo "失败!"
    180. fi
    181. RETVAL=0
    182. echo -e "10s后重新启动服务: \n"
    183. sleep 10
    184. 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
    185. if [ $RETVAL -eq 0 ]; then
    186. echo "启动成功!"
    187. else
    188. EXITCODE=1
    189. echo "启动失败! "
    190. fi
    191. echo "启动命令:systemctl restart service@$project_name"
    192. echo "启动日志:"
    193. echo
    194. sleep 5
    195. ssh -q -p8822 "$target" "systemctl enable service@$project_name;systemctl status service@$project_name" || EXITCODE=1
    196. i=`expr $i + 1`
    197. # if [ -z "${Domain}" ] && [[ "${project_name}" =~ "http" ]]; then echo '跳过端口检测!'; else check_status; fi
    198. NGX_STATUS="UP" &&NGX_API
    199. else
    200. RETVAL=0
    201. EXITCODE=1
    202. echo "失败!"
    203. fi
    204. else
    205. echo "当前主机: 【$((i++))】 -> $target"
    206. case $ACTION in
    207. "停止服务")
    208. DO_ACTION="stop"
    209. ;;
    210. "启动服务")
    211. DO_ACTION="start"
    212. ;;
    213. "重启服务")
    214. DO_ACTION="restart"
    215. ;;
    216. *)
    217. DO_ACTION="status"
    218. esac
    219. if [ "$DO_ACTION" = "stop" ]; then
    220. OTHER_ACTION="systemctl disable service@$project_name"
    221. else
    222. OTHER_ACTION=":"
    223. fi
    224. if [ "$DO_ACTION" != "status" ]; then
    225. echo "执行命令:systemctl $DO_ACTION service@$project_name"
    226. ssh -q -p8822 "$target" "$OTHER_ACTION; systemctl $DO_ACTION service@$project_name" || EXITCODE=1
    227. sleep 3
    228. fi
    229. echo "查看状态:"
    230. ssh -q -p8822 "$target" "systemctl status service@$project_name && echo '*************** 服务正常运行中 ***************' || echo '*************** 服务未启动或已停止 ***************'" || EXITCODE=1
    231. fi
    232. done
    233. done
    234. 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