PageRenderTime 25ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/twisted/twisted/plugins/bartercast_crawler_plugin.py

https://gitlab.com/billyprice1/tribler
Python | 163 lines | 107 code | 29 blank | 27 comment | 10 complexity | 0d5891265d135323f06d6a8df3950847 MD5 | raw file
  1. """
  2. Run Dispersy in standalone bartercast crawler mode.
  3. Crawls BarterCommunity and collects interaction data from peers.
  4. Temporary approach: all peers will run this service if this works OK. See Github issue #3.
  5. """
  6. import os
  7. import signal
  8. from twisted.logger import globalLogPublisher
  9. from Tribler.dispersy.crypto import NoVerifyCrypto, NoCrypto
  10. # from dispersy.discovery.community import DiscoveryCommunity
  11. from Tribler.dispersy.dispersy import Dispersy
  12. from Tribler.dispersy.endpoint import StandaloneEndpoint
  13. from Tribler.dispersy.exception import CommunityNotFoundException
  14. from twisted.application.service import IServiceMaker, MultiService
  15. from twisted.conch import manhole_tap
  16. from twisted.internet import reactor
  17. from twisted.plugin import IPlugin
  18. from twisted.python import usage
  19. from twisted.python.log import msg
  20. from twisted.python.threadable import isInIOThread
  21. from zope.interface import implements
  22. from Tribler.community.bartercast4.community import BarterCommunityCrawler
  23. from Tribler.dispersy.tool.clean_observers import clean_twisted_observers
  24. clean_twisted_observers(globalLogPublisher)
  25. class BartercastCrawler(Dispersy):
  26. def __init__(self, endpoint, working_directory, silent=False, crypto=NoVerifyCrypto()):
  27. super(BartercastCrawler, self).__init__(endpoint, working_directory, u":memory:", crypto)
  28. # location of persistent storage
  29. self._persistent_storage_filename = os.path.join(working_directory, "persistent-storage.data")
  30. self._silent = silent
  31. self._my_member = None
  32. def start(self):
  33. assert isInIOThread()
  34. if super(BartercastCrawler, self).start():
  35. self._create_my_member()
  36. print "loading bartercc as member %s: " % self._my_member
  37. # self.register_task("unload inactive communities",
  38. # LoopingCall(self.unload_inactive_communities)).start(COMMUNITY_CLEANUP_INTERVAL)
  39. self.define_auto_load(BarterCommunityCrawler, self._my_member, (), load=True)
  40. # self.define_auto_load(TrackerHardKilledCommunity, self._my_member)
  41. # if not self._silent:
  42. # self._statistics_looping_call = LoopingCall(self._report_statistics)
  43. # self._statistics_looping_call.start(300)
  44. return True
  45. return False
  46. def _create_my_member(self):
  47. # generate a new my-member
  48. ec = self.crypto.generate_key(u"very-low")
  49. self._my_member = self.get_member(private_key=self.crypto.key_to_bin(ec))
  50. @property
  51. def persistent_storage_filename(self):
  52. return self._persistent_storage_filename
  53. def get_community(self, cid, load=False, auto_load=True):
  54. try:
  55. return super(BartercastCrawler, self).get_community(cid, True, True)
  56. except CommunityNotFoundException:
  57. return BarterCommunityCrawler.init_community(self, self.get_member(mid=cid), self._my_member)
  58. class Options(usage.Options):
  59. optFlags = [
  60. ["profiler" , "P", "use cProfile on the Dispersy thread"],
  61. ["memory-dump", "d", "use meliae to dump the memory periodically"],
  62. ["silent" , "s", "Prevent tracker printing to console"],
  63. ]
  64. optParameters = [
  65. ["statedir", "s", "." , "Use an alternate statedir" , str],
  66. ["ip" , "i", "0.0.0.0" , "Dispersy uses this ip" , str],
  67. ["port" , "p", 6421 , "Dispersy uses this UDL port" , int],
  68. ["crypto" , "c", "ECCrypto", "The Crypto object type Dispersy is going to use" , str],
  69. ["manhole" , "m", 0 , "Enable manhole telnet service listening at the specified port", int],
  70. ]
  71. class BartercastCrawlerServiceMaker(object):
  72. implements(IServiceMaker, IPlugin)
  73. tapname = "bartercast_crawler"
  74. description = "A BartercastCommunity statistics crawler"
  75. options = Options
  76. def makeService(self, options):
  77. """
  78. Construct a dispersy service.
  79. """
  80. tracker_service = MultiService()
  81. tracker_service.setName("Bartercast Crawler")
  82. # crypto
  83. if options["crypto"] == 'NoCrypto':
  84. crypto = NoCrypto()
  85. else:
  86. crypto = NoVerifyCrypto()
  87. container = [None]
  88. manhole_namespace = {}
  89. if options["manhole"]:
  90. port = options["manhole"]
  91. manhole = manhole_tap.makeService({
  92. 'namespace': manhole_namespace,
  93. 'telnetPort': 'tcp:%d:interface=127.0.0.1' % port,
  94. 'sshPort': None,
  95. 'passwd': os.path.join(os.path.dirname(__file__), 'passwd'),
  96. })
  97. tracker_service.addService(manhole)
  98. manhole.startService()
  99. def run():
  100. # setup
  101. dispersy = BartercastCrawler(StandaloneEndpoint(options["port"],
  102. options["ip"]),
  103. unicode(options["statedir"]),
  104. bool(options["silent"]),
  105. crypto)
  106. container[0] = dispersy
  107. manhole_namespace['dispersy'] = dispersy
  108. self._stopping = False
  109. def signal_handler(sig, frame):
  110. msg("Received signal '%s' in %s (shutting down)" % (sig, frame))
  111. if not self._stopping:
  112. self._stopping = True
  113. try:
  114. dispersy.stop()
  115. except Exception, e:
  116. msg("Got exception when stopping dispersy: %s" % e)
  117. reactor.stop()
  118. signal.signal(signal.SIGINT, signal_handler)
  119. signal.signal(signal.SIGTERM, signal_handler)
  120. # start
  121. print "starting dispersy"
  122. if not dispersy.start():
  123. raise RuntimeError("Unable to start Dispersy")
  124. # wait forever
  125. reactor.exitCode = 0
  126. reactor.callWhenRunning(run)
  127. # TODO: exit code
  128. return tracker_service
  129. # Now construct an object which *provides* the relevant interfaces
  130. # The name of this variable is irrelevant, as long as there is *some*
  131. # name bound to a provider of IPlugin and IServiceMaker.
  132. serviceMaker = BartercastCrawlerServiceMaker()