unet.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. # The contents of this file are subject to the BitTorrent Open Source License
  2. # Version 1.1 (the License). You may not copy or use this file, in either
  3. # source code or executable form, except in compliance with the License. You
  4. # may obtain a copy of the License at http://www.bittorrent.com/license/.
  5. #
  6. # Software distributed under the License is distributed on an AS IS basis,
  7. # WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
  8. # for the specific language governing rights and limitations under the
  9. # License.
  10. #
  11. # knet.py
  12. # create a network of khashmir nodes
  13. # usage: knet.py <num_nodes> <start_port> <ip_address>
  14. from utkhashmir import UTKhashmir
  15. from BitTorrent.RawServer_twisted import RawServer
  16. from BitTorrent.defaultargs import common_options, rare_options
  17. from random import randrange
  18. from BitTorrent.stackthreading import Event
  19. import sys, os
  20. from krpc import KRPC
  21. KRPC.noisy = 1
  22. class Network:
  23. def __init__(self, size=0, startport=5555, localip='127.0.0.1'):
  24. self.num = size
  25. self.startport = startport
  26. self.localip = localip
  27. def _done(self, val):
  28. self.done = 1
  29. def simpleSetUp(self):
  30. #self.kfiles()
  31. d = dict([(x[0],x[1]) for x in common_options + rare_options])
  32. self.r = RawServer(Event(), d)
  33. self.l = []
  34. for i in range(self.num):
  35. self.l.append(UTKhashmir('', self.startport + i, 'kh%s.db' % (self.startport + i), self.r))
  36. for i in self.l:
  37. i.addContact(self.localip, self.l[randrange(0,self.num)].port)
  38. i.addContact(self.localip, self.l[randrange(0,self.num)].port)
  39. i.addContact(self.localip, self.l[randrange(0,self.num)].port)
  40. self.r.listen_once(1)
  41. self.r.listen_once(1)
  42. self.r.listen_once(1)
  43. for i in self.l:
  44. self.done = 0
  45. i.findCloseNodes(self._done)
  46. while not self.done:
  47. self.r.listen_once(1)
  48. for i in self.l:
  49. self.done = 0
  50. i.findCloseNodes(self._done)
  51. while not self.done:
  52. self.r.listen_once(1)
  53. def tearDown(self):
  54. for i in self.l:
  55. i.rawserver.stop_listening_udp(i.socket)
  56. i.socket.close()
  57. #self.kfiles()
  58. def kfiles(self):
  59. for i in range(self.startport, self.startport+self.num):
  60. try:
  61. os.unlink('kh%s.db' % i)
  62. except:
  63. pass
  64. self.r.listen_once(1)
  65. if __name__ == "__main__":
  66. n = Network(int(sys.argv[1]), int(sys.argv[2]))
  67. n.simpleSetUp()
  68. print ">>> network ready"
  69. try:
  70. n.r.listen_forever()
  71. finally:
  72. n.tearDown()