1
0

knet.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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 khashmir import Khashmir
  15. from random import randrange
  16. import sys, os
  17. class Network:
  18. def __init__(self, size=0, startport=5555, localip='127.0.0.1'):
  19. self.num = size
  20. self.startport = startport
  21. self.localip = localip
  22. def _done(self, val):
  23. self.done = 1
  24. def setUp(self):
  25. self.kfiles()
  26. self.l = []
  27. for i in range(self.num):
  28. self.l.append(Khashmir('', self.startport + i, '/tmp/kh%s.db' % (self.startport + i)))
  29. reactor.iterate()
  30. reactor.iterate()
  31. for i in self.l:
  32. i.addContact(self.localip, self.l[randrange(0,self.num)].port)
  33. i.addContact(self.localip, self.l[randrange(0,self.num)].port)
  34. i.addContact(self.localip, self.l[randrange(0,self.num)].port)
  35. reactor.iterate()
  36. reactor.iterate()
  37. reactor.iterate()
  38. for i in self.l:
  39. self.done = 0
  40. i.findCloseNodes(self._done)
  41. while not self.done:
  42. reactor.iterate()
  43. for i in self.l:
  44. self.done = 0
  45. i.findCloseNodes(self._done)
  46. while not self.done:
  47. reactor.iterate()
  48. def tearDown(self):
  49. for i in self.l:
  50. i.listenport.stopListening()
  51. self.kfiles()
  52. def kfiles(self):
  53. for i in range(self.startport, self.startport+self.num):
  54. try:
  55. os.unlink('/tmp/kh%s.db' % i)
  56. except:
  57. pass
  58. reactor.iterate()
  59. if __name__ == "__main__":
  60. n = Network(int(sys.argv[1]), int(sys.argv[2]), sys.argv[3])
  61. n.setUp()
  62. try:
  63. reactor.run()
  64. finally:
  65. n.tearDown()