util.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. from struct import pack, unpack
  11. def bucket_stats(l):
  12. """given a list of khashmir instances, finds min, max, and average number of nodes in tables"""
  13. max = avg = 0
  14. min = None
  15. def count(buckets):
  16. c = 0
  17. for bucket in buckets:
  18. c = c + len(bucket.l)
  19. return c
  20. for node in l:
  21. c = count(node.table.buckets)
  22. if min == None:
  23. min = c
  24. elif c < min:
  25. min = c
  26. if c > max:
  27. max = c
  28. avg = avg + c
  29. avg = avg / len(l)
  30. return {'min':min, 'max':max, 'avg':avg}
  31. def compact_peer_info(ip, port):
  32. return pack('!BBBBH', *([int(i) for i in ip.split('.')] + [port]))
  33. def packPeers(peers):
  34. return map(lambda a: compact_peer_info(a[0], a[1]), peers)
  35. def reducePeers(peers):
  36. return reduce(lambda a, b: a + b, peers, '')
  37. def unpackPeers(p):
  38. peers = []
  39. if type(p) == type(''):
  40. for x in xrange(0, len(p), 6):
  41. ip = '.'.join([str(ord(i)) for i in p[x:x+4]])
  42. port = unpack('!H', p[x+4:x+6])[0]
  43. peers.append((ip, port, None))
  44. else:
  45. for x in p:
  46. peers.append((x['ip'], x['port'], x.get('peer id')))
  47. return peers
  48. def compact_node_info(id, ip, port):
  49. return id + compact_peer_info(ip, port)
  50. def packNodes(nodes):
  51. return ''.join([compact_node_info(x['id'], x['host'], x['port']) for x in nodes])
  52. def unpackNodes(n):
  53. nodes = []
  54. for x in xrange(0, len(n), 26):
  55. id = n[x:x+20]
  56. ip = '.'.join([str(ord(i)) for i in n[x+20:x+24]])
  57. port = unpack('!H', n[x+24:x+26])[0]
  58. nodes.append({'id':id, 'host':ip, 'port': port})
  59. return nodes