2 # Module vtime - Keep virtual time between two nodes.
4 # We try for synchronised clocks by sending a packet of the for
5 # (1,mytime,0) to the other side, and waiting (at most) a second for
6 # a reply. This reply has the form (2,mytime,histime), and we can
7 # estimate the time difference by defining histime to be exactly half-way
8 # between the time we sent our message and got our reply. We send a
9 # final (3,mynewtime,histime) message to allow the other side to do the
12 # Note that the protocol suffers heavily from the 2-army problem.
13 # It'll have to do until I can read up on time-sync protocols, though.
21 recv_timeout
= 'receive timeout'
22 bad_connect
= 'Bad connection'
25 return int((long(a
)+b
)/2L)
30 return s
.recvfrom(MSGSIZE
)
37 def init(self
,(client
,host
,port
)):
38 s
= socket(AF_INET
, SOCK_DGRAM
)
39 host
= gethostbyname(host
)
40 localhost
= gethostbyname(gethostname())
42 s
.bind((localhost
,port
))
45 # We loop here because we want the *second* measurement
48 curtijd
= time
.millitimer()
49 check
= `
(loopct
,curtijd
,0)`
54 data
, other
= s
.recvfrom(MSGSIZE
)
56 data
, other
= tryrecv(s
)
57 newtijd
= time
.millitimer()
59 print 'Someone else syncing to us: ', other
62 if data
[:2] == (loopct
+1,curtijd
):
65 print 'Illegal sync reply: ', data
68 curtijd
= time
.millitimer()
69 check
= `
(loopct
,curtijd
,0)`
72 s
.sendto(`
(4,newtijd
,histime
)`
,raddr
)
73 mytime
= timeavg(curtijd
,newtijd
)
75 self
.timediff
= histime
- mytime
78 data
,other
= s
.recvfrom(MSGSIZE
)
80 print 'Someone else syncing to us: ', other
, ' Wanted ', raddr
84 curtijd
= time
.millitimer()
85 s
.sendto(`
(data
[0]+1,data
[1],curtijd
)`
,raddr
)
87 newtijd
= time
.millitimer()
89 mytime
= timeavg(curtijd
,newtijd
)
91 self
.timediff
= histime
-mytime
94 print 'Funny data: ', data
98 def his2mine(self
,tijd
):
99 return tijd
- self
.timediff
101 def mine2his(self
, tijd
):
102 return tijd
+ self
.timediff
104 def test(clt
, host
, port
):
105 xx
= VTime().init(clt
,host
,port
)
106 print 'Time diff: ', xx
.his2mine(0)