netswitch_ipv4

netswitch_ipv4

 

usr@USR-G816:~# cat /sbin/netswitch_ipv4.sh
#
!/bin/sh #filename: netswitch_ipv4.sh
.
/lib/auto.conf #LOGG_STYLE="tty" LOGG_STYLE="file" #LOGG_STYLE="echo" #打印log logg() { if [ $LOGG_STYLE == "file" ]; then echo "$*" >>/tmp/log/netswitch_log #判断文件大小,mv /tmp/netswitch_log mv /tmp/netswitch_old_log elif [ $LOGG_STYLE == "tty" ]; then echo "$*" >/dev/ttyS1 else echo "$*" >/dev/null fi } #打印log logg_echo() { echo "$*" >/dev/null } send_alarm() { if [[ "$CONFIG_BOARD_G806_E" == "y" -o "$CONFIG_BOARD_G807_E" == "y" \ -o "$CONFIG_BOARD_G802_E" == "y" -o "$CONFIG_BOARD_G802_E_7628E" == "y" ]];then devname=$1 timecur=$(date +%s) if [ "$devname" != "" ]; then if [ "$devname" == "br-wwan" ]; then devname="wwan" else devname=$(uci show network | grep $devname | awk -F "." '{print $2}') fi gateway=$(uci -c /tmp get device_status.info.gateway) if [ "$gateway" != "$devname" ]; then if [ ! -f /tmp/device_status ] ; then echo "config device 'info'" > /tmp/device_status fi uci -c /tmp set device_status.info.gateway=$devname #devname=$(echo $devname | sed "s/_//g") usr_altsend -n netswitch -s $timecur -m $devname fi fi fi } #检测vpn是否运行,vpn运行时不启动切网 is_vpnrunning() { vpn_list="pptp l2tp" for i in $vpn_list; do vpn_status=$(uci get vpn.$i.defaultroute -p /tmp/state/ -q) logg_echo "uci get vpn.$i.defaultroute -p /tmp/state/ -q" if [ "$vpn_status" == "on" ]; then logg_echo "vpn is running, exit" exit fi done } #结束其他切网进程 kill_others() { pid=$1 kill_list=$(ps | grep netswitch_ipv4 | grep -v $pid | grep -v grep | awk '{print $1}') if [ "$kill_list" != "" ]; then for i in $kill_list; do kill -9 $i &>/dev/null logg_echo "kill -9 $i" done fi } #创建定时进程,超时重启netswitch_ipv4 start_shelldog() { cat>/tmp/netswitchdog<<EOF #!/bin/sh timeout -t 620 sleep 640 /sbin/netswitch_ipv4.sh & exit EOF chmod +x /tmp/netswitchdog /tmp/netswitchdog & } #结束上次定时,重新定时 reset_shelldog() { pdog=$(ps | awk '/[n]etswitchdog/{print $1}') ptimeout=$(ps | awk '/[t]imeout -t 620 sleep 640/{print $1}') psleep=$(ps | awk '/[s]leep 640/{print $1}') #echo "get shelldog pid" $pdog #kill -TERM $pdog kill -9 $pdog kill -9 $ptimeout kill -9 $psleep #killall timeout start_shelldog } #检查是否存在其他切网进程 killall netswitchdog selfpid=$$ logg_echo "my pid $selfpid, killall others netswitch" kill_others $selfpid #检查vpn是否运行 logg_echo "check vpn is running" is_vpnrunning start_shelldog #定义网卡名 if [ "$CONFIG_BOARD_G816" = "y" ];then wan_wired="wan_wired" wan_cellular="wan_5g" wan_sta0="wwan1" wan_sta1="wwan0" elif [ "$CONFIG_BOARD_G817" = "y" ] || [ "$CONFIG_BOARD_G817_IPQ6018" = "y" ];then wan_wired="wan_wired" wan_cellular="wan_5g" wan_sta0="wwan0" wan_sta1="wwan1" else wan_wired="wan_wired" wan_cellular="wan_4g" wan_sta0="wwan" fi #定义默认的fping参考地址 def_referadd1="223.6.6.6 8.8.4.4" def_referadd2="119.29.29.29 8.8.8.8" #============获取参数============= #探测(fping)参数 #探测(fping)参数 fping_cnt=$(uci get netswitch.@netswitch[0].fping_cnt -q) fping_cnt=${fping_cnt:-1} logg_echo $fping_cnt fping_size=$(uci get netswitch.@netswitch[0].fping_size -q) fping_size=${fping_size:-0} logg_echo $fping_size fping_timeout=$(uci get netswitch.@netswitch[0].fping_timeout -q) fping_timeout=${fping_timeout:-2000} logg_echo $fping_timeout fping_retry=$(uci get netswitch.@netswitch[0].fping_retry -q) fping_retry=${fping_retry:-1} logg_echo $fping_retry #总开关 #1-on, 0-off, 默认开启 netswitch_enable=1 #优先级 #1-"4g", 2-"wan", 3-"sta" priority=$(uci get netswitch.@netswitch[0].wanprio -q) priority=${priority:-"5g wan sta sta1"} logg_echo $priority #检测时间 check_interval=$(uci get netswitch.@netswitch[0].check_interval -q) check_interval=${check_interval:-10} logg_echo $check_interval #支持三种方式的参考地址配置:1网关,2默认,3用户自定义 fping_refermode=$(uci get netswitch.@netswitch[0].refermode -q) fping_refermode=${fping_refermode:-3} logg_echo $fping_refermode #获取并配置fping地址参考地址 if [ "$fping_refermode" == "3" ]; then first_referip=$(uci get netswitch.@netswitch[0].first_referip -q) second_referip=$(uci get netswitch.@netswitch[0].second_referip -q) third_referip=$(uci get netswitch.@netswitch[0].third_referip -q) if [ "$first_referip" == "" ]; then fping_referaddr=$def_referadd1" "$def_referadd2 else fping_referaddr=$first_referip" "$second_referip" "$third_referip" "$def_referadd1 fi elif [ "$fping_refermode" == "2" ]; then fping_referaddr=$(uci get netswitch.@netswitch[0].referip -q) if [ "$fping_referaddr" = "" ]; then fping_referaddr=$def_referadd1" "$def_referadd2 fi else fping_referaddr=$(uci get netswitch.@netswitch[0].referip -q) if [ "$fping_referaddr" = "" ]; then fping_referaddr=$def_referadd1" "$def_referadd2 fi fi #获取网关及网卡 wan_wired_gw=$(ifstatus $wan_wired | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_wired_phy=$(ifstatus $wan_wired | grep l3_device | awk -F '\"' '{print $4}') wan_wired_up=$(ifstatus $wan_wired | grep \"up\" | awk -F 'true' '{print $2}') wan_cellular_gw=$(ifstatus $wan_cellular | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_cellular_phy=$(ifstatus $wan_cellular | grep l3_device | awk -F '\"' '{print $4}') wan_cellular_up=$(ifstatus $wan_cellular | grep \"up\" | awk -F 'true' '{print $2}') wan_sta0_gw=$(ifstatus $wan_sta0 | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_sta0_phy=$(ifstatus $wan_sta0 | grep l3_device | awk -F '\"' '{print $4}') wan_sta0_up=$(ifstatus $wan_sta0 | grep \"up\" | awk -F 'true' '{print $2}') wan_sta1_gw=$(ifstatus $wan_sta1 | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_sta1_phy=$(ifstatus $wan_sta1 | grep l3_device | awk -F '\"' '{print $4}') wan_sta1_up=$(ifstatus $wan_sta1 | grep \"up\" | awk -F 'true' '{print $2}') # 网卡启动后,系统会自动做上metric 5/10的默认路由 #这里根据优先级做路由,确保路由与优先级对应 #根据优先级增加跃点数 def_metric=0 for i in $priority; do case $i in "4g" | "5g") def_metric=$(($def_metric + 5)) ip route del default metric $def_metric &>/dev/null uci set network.$wan_cellular.metric=$def_metric if [ "$wan_cellular_up" != "" ]; then ip r replace default via $wan_cellular_gw metric $def_metric dev $wan_cellular_phy &>/dev/null logg_echo "set wan_cellular route" fi logg_echo "1:$wan_cellular_gw 2:$def_metric 3:$wan_cellular_phy" ;; "wan") def_metric=$(($def_metric + 5)) ip route del default metric $def_metric &>/dev/null uci set network.$wan_wired.metric=$def_metric if [ "$wan_wired_up" != "" ]; then ip r replace default via $wan_wired_gw metric $def_metric dev $wan_wired_phy &>/dev/null logg_echo "set wan_wired route" fi logg_echo "1:$wan_wired_gw 2:$def_metric 3:$wan_wired_phy" ;; "sta" | "sta0") def_metric=$(($def_metric + 5)) ip route del default metric $def_metric &>/dev/null uci set network.$wan_sta0.metric=$def_metric if [ "$wan_sta0_up" != "" ]; then ip r replace default via $wan_sta0_gw metric $def_metric dev $wan_sta0_phy &>/dev/null logg_echo "set wan_sta0 route" fi logg_echo "1:$wan_sta0_gw 2:$def_metric 3:$wan_sta0_phy" ;; "sta1") def_metric=$(($def_metric + 5)) ip route del default metric $def_metric &>/dev/null uci set network.$wan_sta1.metric=$def_metric if [ "$wan_sta1_up" != "" ]; then ip r replace default via $wan_sta1_gw metric $def_metric dev $wan_sta1_phy &>/dev/null logg_echo "set wan_sta1 route" fi logg_echo "1:$wan_sta1_gw 2:$def_metric 3:$wan_sta1_phy" ;; "disable") #禁用时配置为关闭 #总开关关闭 #1-on, 0-off netswitch_enable=0 #echo $netswitch_enable ;; esac done #否则网卡up依旧会使用之前的跃点数 ubus call network reload #再检查一遍开关 netswitch_enable=${netswitch_enable:-1} #这里把开关参数配上供其他程序使用 uci set netswitch.@netswitch[0].netswitch_enable=$netswitch_enable logg_echo $netswitch_enable #提交network uci commit network uci commit netswitch CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4_start -- $CURTIME " #变量控制log打印 print_log="0" print_cnt=0 print_maxtime=1800 old_defaultroute="" # 切网时只变更metric为0的路由即可,dns暂不切换 while true; do # 在这里重置定时 reset_shelldog sleep $check_interval #CURTIME=$(date +'%y-%m-%d %H:%M:%S') #logg "netswitch_ipv4 -- $CURTIME" print_cnt=$(($print_cnt + $check_interval)) if [ "$print_cnt" -ge "$print_maxtime" ]; then print_log="0" print_cnt=0 CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME netswitch_running" fi #定义全局变量 priority_wan_gw="" priority_wan_phy="" priority_wan_metric=0 gw_cnt=0 gw_ready="" phy_ready="" metric_ready="" is_allnetblocked=1 #获取多wan网关参数 wan_wired_gw=$(ifstatus $wan_wired | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_wired_phy=$(ifstatus $wan_wired | grep l3_device | awk -F '\"' '{print $4}') wan_wired_metric=0 wan_cellular_gw=$(ifstatus $wan_cellular | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_cellular_phy=$(ifstatus $wan_cellular | grep l3_device | awk -F '\"' '{print $4}') wan_cellular_metric=0 wan_sta0_gw=$(ifstatus $wan_sta0 | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_sta0_phy=$(ifstatus $wan_sta0 | grep l3_device | awk -F '\"' '{print $4}') wan_sta0_metric=0 wan_sta1_gw=$(ifstatus $wan_sta1 | grep nexthop | awk -F '\"' '{print $4}' | tail -n 1) wan_sta1_phy=$(ifstatus $wan_sta1 | grep l3_device | awk -F '\"' '{print $4}') wan_sta1_metric=0 #增加网关跃点参数 gw_metric=0 #根据优先级调整,对不同优先级网卡进行赋值 #1-"4g", 2-"wan", 3-"sta" #echo $priority for current in $priority; do #echo $current if [ "$current" == "wan" ]; then priority_wan_gw=$wan_wired_gw priority_wan_phy=$wan_wired_phy priority_wan_metric=$wan_wired_metric elif [ "$current" == "4g" ] || [ "$current" == "5g" ]; then priority_wan_gw=$wan_cellular_gw priority_wan_phy=$wan_cellular_phy priority_wan_metric=$wan_cellular_metric elif [ "$current" == "sta" ] || [ "$current" == "sta0" ]; then priority_wan_gw=$wan_sta0_gw priority_wan_phy=$wan_sta0_phy priority_wan_metric=$wan_sta0_metric elif [ "$current" == "sta1" ]; then priority_wan_gw=$wan_sta1_gw priority_wan_phy=$wan_sta1_phy priority_wan_metric=$wan_sta1_metric else continue fi gw_metric=$(($gw_metric + 5)) #logg_echo $priority_wan_gw if [ "$priority_wan_gw" != "" ]; then gw_cnt=$(($gw_cnt + 1)) gw_ready=$gw_ready" "$priority_wan_gw"-"$priority_wan_phy phy_ready=$phy_ready" "$priority_wan_phy metric_ready=$metric" "$priority_wan_metric logg_echo $gw_ready $gw_cnt #这里增加路由判断 #logg_echo "ip r | grep \"default via $priority_wan_gw dev $priority_wan_phy metric $gw_metric\"" is_route=$(ip r | grep "default via $priority_wan_gw dev $priority_wan_phy metric $gw_metric") if [ "$is_route" == "" ]; then #这里把缺失的路由做上 logg_echo "def route lost, add $priority_wan_gw wihit $gw_metric of $priority_wan_phy" ip r replace default via $priority_wan_gw metric $gw_metric dev $priority_wan_phy &>/dev/null ifname=$(uci show network | grep $priority_wan_phy | awk -F '.' '{print $2}') logg_echo $ifname for i in $ifname; do if [ "$i" == "$wan_cellular" ] || [ "$i" == "$wan_wired" ] || [ "$i" == "$wan_sta0" ] || [ "$i" == "$wan_sta1" ]; then uci set network.$i.metric=$gw_metric logg_echo "uci set network.$i.metric=$gw_metric" uci commit network fi done fi fi logg_echo "set gw_ready" done #logg_echo "get wan info" #禁用时不再切网 if [ "$netswitch_enable" == "0" ]; then continue fi if [ "$gw_cnt" == "0" ]; then #不做路由直接下一步 if [ "$print_log" != "a" ]; then print_log="a" CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME no wan,continue" fi else #设置标记,单独处理所有网络都不通的情况 first_gw="" first_phy="" is_first=0 #断网标志记为1 is_allnetblocked=1 for gw_phy in $gw_ready; do logg_echo "gw_ready:"$gw_phy #获取到'-'之前的内容,此处为网关 gw=${gw_phy%%-*} logg_echo $gw #获取到'-'之后的内容,此处为网卡 phy=${gw_phy#*-} logg_echo $phy if [ "$gw_cnt" == "1" ]; then ##断网标志清零 is_allnetblocked=0 #只做路由即可,不需要fping if [ "$print_log" != "b" ]; then print_log="b" CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME only $gw exist,continue" fi defaultroute=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $2}' | head -1) defaultrouteMetric=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $5}' | head -1) defaultroutephy=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $8}' | head -1) if [ "$defaultroute" == "$gw" -a "$defaultrouteMetric" != "0" ]; then ip r replace default via $gw metric 0 dev $phy &>/dev/null send_alarm $phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $gw whith $phy tobe defroute" elif [[ "$defaultroute" != "$gw" ]]; then ip r replace default via $gw metric 0 dev $phy &>/dev/null send_alarm $phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $gw whith $phy tobe defroute" elif [[ "$defaultroutephy" != "$phy" ]]; then ip r replace default via $gw metric 0 dev $phy &>/dev/null send_alarm $phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $gw whith $phy tobe defroute" fi break else if [ "$is_first" == "0" ]; then is_first=1 first_gw=$gw first_phy=$phy fi #通过fping确定通断情况,再做路由 #如果设置为网关 if [ "$fping_refermode" == "1" ]; then fping $gw -4 -I $phy -c$fping_cnt -b$fping_size -t$fping_timeout -r$fping_retry -x 1 &>/tmp/fping_first_priority_tmp else fping $fping_referaddr -4 -I $phy -c$fping_cnt -b$fping_size -t$fping_timeout -r$fping_retry -x 1 &>/tmp/fping_first_priority_tmp fi priority_wan_alive=$(cat /tmp/fping_first_priority_tmp | grep "Enough hosts reachable") if [[ "$priority_wan_alive" != "" ]]; then ##断网标志清零 is_allnetblocked=0 defaultroute=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $2}' | head -1) defaultrouteMetric=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $5}' | head -1) defaultroutephy=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $8}' | head -1) if [ "$defaultroute" == "$gw" -a "$defaultrouteMetric" != "0" ]; then ip r replace default via $gw metric 0 dev $phy &>/dev/null send_alarm $phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $gw whith $phy tobe defroute" elif [[ "$defaultroute" != "$gw" ]]; then ip r replace default via $gw metric 0 dev $phy &>/dev/null send_alarm $phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $gw whith $phy tobe defroute" elif [[ "$defaultroutephy" != "$phy" ]]; then ip r replace default via $gw metric 0 dev $phy &>/dev/null send_alarm $phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $gw whith $phy tobe defroute" fi break else CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME network:$phy blocked" fi fi done #判断是否网都不通 if [ "$is_allnetblocked" != "0" ]; then defaultroute=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $2}' | head -1) defaultrouteMetric=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $5}' | head -1) defaultdev=$(route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $8}' | head -1) if [ "$defaultroute" == "$first_gw" -a "$defaultrouteMetric" != "0" ]; then ip r replace default via $first_gw metric 0 dev $first_phy &>/dev/null send_alarm $first_phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $first_gw tobe defroute" elif [[ "$defaultroute" != "$first_gw" ]]; then ip r replace default via $first_gw metric 0 dev $first_phy &>/dev/null send_alarm $first_phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $first_gw tobe defroute" elif [[ "$defaultdev" != "$first_phy" ]]; then ip r replace default via $first_gw metric 0 dev $first_phy &>/dev/null send_alarm $first_phy CURTIME=$(date +'%y-%m-%d %H:%M:%S') logg "netswitch_ipv4 -- $CURTIME $first_gw tobe defroute" fi fi fi #可以统一在此处for循环检测defroute #获取默认路由下一跳地址 #defaultroute=`route -n | grep 0.0.0.0.*0.0.0.0 | awk '{print $2}'| head -n 1` defaultroute=$(ip r |grep default | head -1 |awk '{print $3}') if [[ "$defaultroute" != "" -a "$defaultroute" != "$old_defaultroute" ]];then old_defaultroute=$defaultroute conntrack -D &>/dev/null & echo "route change ,start conntrack -D" > /dev/ttyMSM0 logg "route change ,start conntrack -D" #restart limit_ip_rate grep "domain" /etc/config/ratelimit >/dev/null 2>&1 if [ $? -eq 0 ];then /etc/init.d/limit_ip_rate restart &>/dev/null & echo "$(date) restart limit_ip_rate " >/dev/ttyMSM0 logg "def route change, restart limit_ip_rate" fi #restart phtunnel phtunnel_en=$(uci get phtunnel.base.enabled -q) if [ "$phtunnel_en" == "1" ];then /etc/init.d/phtunnel restart &>/dev/null & echo "$(date) restart phtunnel " >/dev/ttyMSM0 logg "def route change, restart phtunnel" fi fi done

 

#!/bin/sh
#filename: usr_log.sh

#打印log
logg_echo() {
    echo "$*" >/dev/null
}

syslog_start() {
    #读取配置参数,生成配置文件
    remote_log_ip=$1
    remote_log_port=$2
    kern_log_leve=$3
    app_log_leve=$4
    logg_echo "$kern_log_leve, $app_log_leve"
    cat /dev/null >/etc/syslog.conf
    echo -e "kern.$kern_log_leve;daemon.$kern_log_leve;mail.crit\t/tmp/log/kernellogd" >/etc/syslog.conf
    echo -e "user.$app_log_leve;cron.$app_log_leve\t/tmp/log/userlogd" >>/etc/syslog.conf
    echo -e "local5.info\t/tmp/log/vpnlogd" >>/etc/syslog.conf
    echo -e "*.debug\t/dev/null" >>/etc/syslog.conf
    logg_echo "get param: $remote_log_ip, $remote_log_port, $kern_log_leve, $app_log_leve"
    #先结束旧进程再开启新进程
    killall -9 syslogd
    #启动syslogd
    if [ "$remote_log_ip" == "0.0.0.0" ] ||
        [ "$remote_log_port" == "0" ]; then
        logg_echo "set syslog no -R"
        syslogd -s 0 -t -f /etc/syslog.conf -L &
    else
        syslogd -s 0 -t -f /etc/syslog.conf -R $remote_log_ip:$remote_log_port -L &
    fi
    logg_echo "start syslogd"
}

syslog_reload() {
    #配置改变,重启进程,增加空值判断
    remote_log_ip_cur=$(uci get system.@system[0].remote_log_ip)
    if [ "$remote_log_ip_cur" == "" ]; then
        remote_log_ip_cur="0.0.0.0"
    fi
    logg_echo "$remote_log_ip_cur"
    remote_log_port_cur=$(uci get system.@system[0].remote_log_port)
    if [ "$remote_log_port_cur" == "" ]; then
        remote_log_port_cur="0"
    fi
    logg_echo "$remote_log_port_cur"
    kern_log_leve_cur=$(uci get system.@system[0].kernel_log_level)
    logg_echo "$kern_log_leve_cur"
    app_log_leve_cur=$(uci get system.@system[0].applacation_log_level)
    logg_echo "$app_log_leve_cur"
    if [ "$remote_log_ip_cur" != "$remote_log_ip" ] ||
        [ "$remote_log_port_cur" != "$remote_log_port" ] ||
        [ "$kern_log_leve_cur" != "$kern_log_leve" ] ||
        [ "$app_log_leve_cur" != "$app_log_leve" ]; then
        syslog_start $remote_log_ip_cur $remote_log_port_cur $kern_log_leve_cur $app_log_leve_cur
    fi
    
    PID=`ps | grep syslogd | grep -v grep`
    if [ "$PID" == "" ] ; then
        syslog_start $remote_log_ip_cur $remote_log_port_cur $kern_log_leve_cur $app_log_leve_cur
    fi
}

log_rolling() {
    #这里检查大小及个数
    num=0
    while [ $filenumber -gt $rotate -o $flashfreesize -lt $flash_reserved_size_kb ]; do
        logg_echo "check size and members"

        #如果压缩包超过上限,删除序列号最小的压缩包
        delfilename=$(ls $save_path/*.app_log.tar.gz | awk -F "/" '{print $NF}' |sort -n |head -n1)
        logg_echo $delfilename
        if [ "$delfilename" != "" ]; then
            logg_echo "delete the $save_path/$num.*.app_log.tar.gz"
            delfilename="$save_path/$(ls $save_path/*.*.app_log.tar.gz | awk -F "/" '{print $NF}' | awk -F "." '{print $1}'|sort -n |head -n1).*.app_log.tar.gz"
            logg_echo $delfilename
            logg_echo $num
            rm -rf $delfilename
        else
            rm -rf $save_path/
            break
        fi
        #如果压缩文件已经删空
        if [ "$filenumber" == "0" ]; then
            logg_echo "no file to delete"
            tmp_file=$(ls $save_path)
            for i in $tmp_file; do
                tail -n 1000 $save_path/$i >$save_path/$i
            done
            break
        fi
        #获取文件个数
        filenumber=$(ls $save_path | grep -c app_log.tar.gz)
        logg_echo "filenumber:"$filenumber
        #获取文件大小
        flashfreesize=$(df | grep overlayfs | awk '{print $4}')
    done
    logg_echo "delete end"
    #排序并重命名
    file_cnt=$(ls $save_path | grep -c app_log.tar.gz)
    num=0
    file_saved_name=$(ls -1v /etc/syslog | grep app_log)
    for i in $file_saved_name; do
        logg_echo "get file:"$i
        old_num=$(echo $i | awk -F '.' '{print $1}')
        if [ "${#old_num}" -ge "10" ]; then
            mv $save_path/$i $save_path/$num.$old_num.app_log.tar.gz
            logg_echo "mv $save_path/$i $save_path/$num.$old_num.app_log.tar.gz"
            continue
        fi
        startchar=$(echo $old_num | wc -c)
        filename=$(echo $i | cut -c$startchar-)
        if [ "$old_num" != "$num" ]; then
            mv $save_path/$old_num$filename $save_path/$num$filename
            logg_echo "mv $save_path/$i $save_path/$num$filename"
        fi
        let num=$num+1
    done
}

#获取全局配置
#log大于maxsize大小时,压缩保存,单位k
compressed_size_kb=300
#需要保存的log列表
log_list="/tmp/log/userlogd /tmp/log/kernellogd /tmp/log/vpnlogd /tmp/log/netswitch_log"
#需要预留的最小flash空间,单位k
flash_reserved_size_kb=2000
#log滚动保存的最大数量
rotate=30
save_path="/etc/syslog"
save_interval=100 #10min
remote_log_ip=$(uci get system.@system[0].remote_log_ip)
remote_log_port=$(uci get system.@system[0].remote_log_port)
kern_log_leve=$(uci get system.@system[0].kernel_log_level)
app_log_leve=$(uci get system.@system[0].applacation_log_level)
if [ "$remote_log_ip" == "" ]; then
    remote_log_ip="0.0.0.0"
fi
if [ "$remote_log_port" == "" ]; then
    remote_log_port="0"
fi

if [ ! -e $save_path ]; then 
    mkdir -p $save_path
fi

logg_echo "get all param:$compressed_size_kb,$log_list,$flash_reserved_size_kb,$rotate,$save_path,$save_interval,$remote_log_ip,$remote_log_port,$kern_log_leve,$app_log_leve"
#全局变量
num_of_compressed=0
let maxsize_bit=$compressed_size_kb*1024
cnt=0

#创建日志tmp存储文件
touch /tmp/log/kernellogd
touch /tmp/log/userlogd
touch /tmp/log/vpnlogd
logg_echo "touch log file"

syslog_start $remote_log_ip $remote_log_port $kern_log_leve $app_log_leve

#存储目录是否存在
if [ ! -d $save_path ]; then
    mkdir -p $save_path
    logg_echo "mkdir -p $save_path"
else
    #是否存在未压缩的日志文件
    if [ -n "$(ls $save_path/* | grep app_log.tar.gz -v)" ]; then
        logg_echo "has uncmpress"
        mkdir -p /tmp/this_log/
        for logfile in $log_list; do
            savefile=$(echo $logfile | awk -F "/" '{print $NF}')
            if [ -f $save_path/$savefile ]; then
                cp $save_path/$savefile /tmp/this_log/
            fi
        done
        #压缩文件
        filetime=$(date "+%Y%m%d%H%M%S")
        tar -zcf $save_path/$filetime.app_log.tar.gz this_log -C /tmp
        rm -rf /tmp/this_log
        ls $save_path
        #清理掉旧文件
        for logfile in $log_list; do
            cat /dev/null > $logfile
            savefile=$(echo $logfile | awk -F "/" '{print $NF}')
            cat /dev/null > $save_path/$savefile
            logg_echo "clear $savefile"
        done

        #获取文件个数
        filenumber=$(ls $save_path | grep -c app_log.tar.gz)
        #计算flash可用空间大小(kB)
        flashfreesize=$(df | grep overlayfs | awk '{print $4}')
        #日志滚动
        log_rolling
    fi

fi

while true; do
    let cnt=cnt+1
    #syslog重启
    syslog_reload

    #flash存储时间到
    if [ $cnt -ge $save_interval ]; then
        cnt=0

        #计算ram中log总大小
        logsize=0
        for logfile in $log_list; do
            if [ -n $logfile ]; then
                logsizetmp=$(ls -l $logfile | awk '{print $5}')
                let logsize=$logsizetmp+$logsize
                let logsize=$logsize
            fi
        done

        #获取文件个数
        filenumber=$(ls $save_path | grep -c app_log.tar.gz)

        #计算flash可用空间大小(kB)
        flashfreesize=$(df | grep overlayfs | awk '{print $4}')

        num=0
        logg_echo "logsize:$logsize"
        let flashfreesize=$flashfreesize-$logsize/1024
        #如果flash剩余空间减去tmp日志文件大小,小于配置的flash剩余空间,日志滚动
        log_rolling

        #日志达到压缩标准
        if [ $logsize -ge $maxsize_bit ]; then
            #压缩并保存
            mkdir -p /tmp/this_log/
            for logfile in $log_list; do
                if [ -n $logfile ]; then
                    cp $logfile /tmp/this_log/
                fi
                logg_echo "this log"
                ls /tmp/this_log
            done
            filetime=$(date "+%Y%m%d%H%M%S")
            tar -zcf $save_path/$filetime.app_log.tar.gz this_log -C /tmp
            rm -rf /tmp/this_log
            for logfile in $log_list; do
                cat /dev/null > $logfile
                savefile=$(echo $logfile | awk -F "/" '{print $NF}')
                cat /dev/null > $save_path/$savefile
                logg_echo "clear $savefile"
            done
            #清理掉旧文件
            #kill -HUP `cat /var/run/syslogd.pid`
            echo "copy log file and compress to flash" | logger -t log.config[shell] -p user.debug -s
        else
            for logfile in $log_list; do
                savefile=$(echo $logfile | awk -F "/" '{print $NF}')
                cat $logfile > $save_path/$savefile
                logg_echo "copy $logfile $save_path/$savefile"
            done
            #logg_echo "only copy log file to flash" | logger -t usr_log[shell] -p user.debug -s
        fi
    else
        logg_echo $cnt
    fi

    sleep 6

done

 

========== End

 

posted @ 2024-04-10 09:49  lsgxeva  阅读(14)  评论(0编辑  收藏  举报