forked from SeattleTestbed/timeserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime_server.repy
101 lines (62 loc) · 2.33 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
100
101
"""
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 'serviced requests: '+str(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'
# 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
obtainingtime = True
while obtainingtime:
try:
time_updatetime(port)
except Exception,e:
print e, " trying again to connect to a NTP" # print exception, try again
else:
obtainingtime = False # time obtained, exit while loop
listencommhandle = waitforconn(ip,port,send_time_to_client)
# Begin announcing presence to central server
ipPortstring = "%s:%s"%(ip,port)
time_server_announce(ipPortstring)