-
Notifications
You must be signed in to change notification settings - Fork 1
/
time_server.repy
100 lines (61 loc) · 2.47 KB
/
time_server.repy
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
"""
Author: Zachary Boka
time_server.repy
Start Date: 3 May 2009
Description:
This repy service listens for connections and returns the current
time, obtained from a subset of NTPs via time.repy, whenever it receives
a request.
"""
# this program will NOT use tcp_time
include ntp_time.repy
include advertise.repy
# Announce presence to central server every four to five minutes
def time_server_announce(ipPortstring):
announced = False
while announced != True:
try:
announced = advertise_announce("time_server",ipPortstring,150)
except Exception,e:
print e, " trying again to announce presence to the central server"
sleep(5) # Announce failed, retry in 5 seconds
else:
announced = True # Announce succeeded, exit while loop
# Re-announce to central server sometime after 60 seconds has passed
timerhandle = settimer(60,time_server_announce,(ipPortstring,))
# Supplies the current time obtained from a NTP to a client via time.repy
def send_time_to_client(ip,port,sockobj,thiscommhandle,listencommhandle):
serverTime = str(time_gettime())
sockobj.send(serverTime+'$')
#countingis done after sending the time so clients get a fast response
mycontext['count_lock'].acquire()
mycontext['count']+=1
if mycontext['count'] % 10 == 0:
print 'Unix time:', time_gettime() - 2208988800, 'serviced requests:', mycontext['count']
mycontext['count_lock'].release()
stopcomm(thiscommhandle)
if callfunc == 'initialize':
if len(callargs) > 1:
raise Exception("Too many call arguments")
elif len(callargs) == 1:
port = int(callargs[0])
ip = getmyip()
else:
port = 12345
ip = '127.0.0.1'
print 'You did not supply a server port I should listen on. Using default port', port
# track how many connections are made so we have an idea of how
# often this service is used
mycontext['count'] = 0
mycontext['count_lock'] = getlock()
# Establish time via a connection to a NTP server
# Don't spin in a loop if we fail -- the error might be on our
# side, not the NTP server's (disallowed port, no connectivity, etc.)
print "Getting NTP timestamp..."
time_updatetime(port)
print "Got timestamp."
print 'time_server to listen on IP address', ip, 'port', port, 'now.'
listencommhandle = waitforconn(ip,port,send_time_to_client)
# Begin announcing presence to central server
ipPortstring = "%s:%s"%(ip,port)
time_server_announce(ipPortstring)