-
Notifications
You must be signed in to change notification settings - Fork 3
/
cubian-ntpdate
executable file
·101 lines (86 loc) · 2.12 KB
/
cubian-ntpdate
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#! /bin/bash
set -e
# Warning:
# this program is designed to be executed by at command,
# don't use STDOUT in the program
# STDOUT,STDERROR will be mailed to /var/mail/
LOCKFILE=/var/lock/cubian-ntpdate.lock
SUCCESS_LOCKFILE=/var/lock/cubian-ntpdate-success.lock
DELAY=${1:-0}
MAX_AVG=0.8
# definition of some helper functions
log(){
logger -t "networktime" "$1"
}
get_loadavg(){
cat /proc/loadavg | awk '{print $1}'
}
do_ntpdate(){
log "start probe interfaces"
for interface in $(ls /sys/class/net/ | grep -v 'lo\|tunl[0-9][0-9]*\|gre[0-9][0-9]*\|ip6tnl[0-9][0-9]*\|sit[0-9][0-9]*\|p2p[0-9][0-9]*');do
hasNetWork=$(cat /sys/class/net/$interface/carrier 2>/dev/null)
if [[ "$hasNetWork" = "1" ]];then
log "network interface $interface online"
break
else
log "network interface $interface offline"
fi
done
log "Waiting IP address for 20 seconds"
sleep 20
if [ "x`/usr/lib/cubian/cubian-getip`" = "x" ];then
log "No IPv4 address available"
rm $LOCKFILE
log "Quit"
exit 0
fi
if [[ "$hasNetWork" = "1" ]];then
avg=$(get_loadavg)
if expr $avg \< $MAX_AVG > /dev/null;then
ntpdateLog=$(/usr/sbin/ntpdate-debian 2>&1)
ret="$?"
echo $ntpdateLog | logger -t "networktime"
if [ "$ret" = "0" ];then
log "success"
touch $SUCCESS_LOCKFILE
else
log "fail, ntpdate error, see log, process deferred"
fi
else
log "system is busy, current $avg maximium $MAX_AVG, process deferred"
fi
else
log "fail, no network connection, process deferred"
fi
}
## core logic of this script
# check for already running instance
if [ -f $LOCKFILE ];then
exit 0
fi
# check for installed ntpd
if [ -f /etc/init.d/ntp ];then
exit 0
fi
echo $$ > $LOCKFILE
sleep 1
[ "x$(cat $LOCKFILE)" == "x"$$ ] || exit
if [ -f $SUCCESS_LOCKFILE ];then
log "already update time, quit automatically"
fi
log "wait interfaces ready"
while true;do
DELAY=$(expr $DELAY \* 2)
log "wait $DELAY seconds"
sleep $DELAY
set +e
log "execute ntpdate"
do_ntpdate
set -e
if [ -f $SUCCESS_LOCKFILE ];then
break
fi
done
rm $LOCKFILE
log "Quit"
exit 0