本文整理汇总了Python中Peer.Peer类的典型用法代码示例。如果您正苦于以下问题:Python Peer类的具体用法?Python Peer怎么用?Python Peer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Peer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sitePublish
def sitePublish(self, address, peer_ip=None, peer_port=15441, inner_path="content.json"):
global file_server
from Site import SiteManager
from File import FileServer # We need fileserver to handle incoming file requests
from Peer import Peer
logging.info("Creating FileServer....")
file_server = FileServer()
file_server_thread = gevent.spawn(file_server.start, check_sites=False) # Dont check every site integrity
file_server.openport()
site = SiteManager.site_manager.list()[address]
site.settings["serving"] = True # Serving the site even if its disabled
# Notify local client on new content
if config.ip_external:
logging.info("Sending siteReload")
my_peer = Peer(config.ip_external, config.fileserver_port)
logging.info(my_peer.request("siteReload", {"site": site.address, "inner_path": inner_path}))
if peer_ip: # Announce ip specificed
site.addPeer(peer_ip, peer_port)
else: # Just ask the tracker
logging.info("Gathering peers from tracker")
site.announce() # Gather peers
published = site.publish(20, inner_path) # Push to 20 peers
if published > 0:
time.sleep(3)
logging.info("Serving files (max 60s)...")
gevent.joinall([file_server_thread], timeout=60)
logging.info("Done.")
else:
logging.info("No peers found, sitePublish command only works if you already have visitors serving your site")
示例2: testPassive
def testPassive(self, file_server, bootstrapper_db):
peer = Peer("127.0.0.1", 1544, connection_server=file_server)
hash1 = hashlib.sha256("hash1").digest()
bootstrapper_db.peerAnnounce(ip4=None, port=15441, hashes=[hash1])
res = peer.request("announce", {
"hashes": [hash1], "port": 15441, "need_types": ["ip4"], "need_num": 10, "add": []
})
assert len(res["peers"][0]["ip4"]) == 0 # Empty result
示例3: testAnnounceList
def testAnnounceList(self, file_server):
peer = Peer("127.0.0.1", 1544, connection_server=file_server)
assert peer.request("getTrackers")["trackers"] == []
tracker_storage = AnnounceSharePlugin.tracker_storage
tracker_storage.onTrackerFound("zero://127.0.0.1:15441")
assert peer.request("getTrackers")["trackers"] == []
# It needs to have at least one successfull announce to be shared to other peers
tracker_storage.onTrackerSuccess("zero://127.0.0.1:15441", 1.0)
assert peer.request("getTrackers")["trackers"] == ["zero://127.0.0.1:15441"]
示例4: peerGetFile
def peerGetFile(self, peer_ip, peer_port, site, filename):
logging.info("Opening a simple connection server")
global file_server
from Connection import ConnectionServer
file_server = ConnectionServer()
from Peer import Peer
logging.info("Getting %s/%s from peer: %s:%s..." % (site, filename, peer_ip, peer_port))
peer = Peer(peer_ip, peer_port)
s = time.time()
print peer.getFile(site, filename).read()
print "Response time: %.3fs" % (time.time()-s)
示例5: peerPing
def peerPing(self, peer_ip, peer_port):
logging.info("Opening a simple connection server")
global file_server
from Connection import ConnectionServer
file_server = ConnectionServer("127.0.0.1", 1234)
from Peer import Peer
logging.info("Pinging 5 times peer: %s:%s..." % (peer_ip, int(peer_port)))
peer = Peer(peer_ip, peer_port)
for i in range(5):
s = time.time()
print peer.ping(),
print "Response time: %.3fs" % (time.time()-s)
time.sleep(1)
示例6: peerCmd
def peerCmd(self, peer_ip, peer_port, cmd, parameters):
logging.info("Opening a simple connection server")
global file_server
from Connection import ConnectionServer
file_server = ConnectionServer()
from Peer import Peer
peer = Peer(peer_ip, peer_port)
import json
if parameters:
parameters = json.loads(parameters.replace("'", '"'))
else:
parameters = {}
logging.info("Response: %s" % peer.request(cmd, parameters))
示例7: peerPing
def peerPing(self, peer_ip, peer_port=None):
if not peer_port:
peer_port = config.fileserver_port
logging.info("Opening a simple connection server")
global file_server
from Connection import ConnectionServer
file_server = ConnectionServer("127.0.0.1", 1234)
from Crypt import CryptConnection
CryptConnection.manager.loadCerts()
from Peer import Peer
logging.info("Pinging 5 times peer: %s:%s..." % (peer_ip, int(peer_port)))
peer = Peer(peer_ip, peer_port)
for i in range(5):
s = time.time()
print peer.ping(),
print "Response time: %.3fs (crypt: %s)" % (time.time() - s, peer.connection.crypt)
time.sleep(1)
peer.remove()
print "Reconnect test..."
peer = Peer(peer_ip, peer_port)
for i in range(5):
s = time.time()
print peer.ping(),
print "Response time: %.3fs (crypt: %s)" % (time.time() - s, peer.connection.crypt)
time.sleep(1)
示例8: testWorkerManagerPiecefieldDownload
def testWorkerManagerPiecefieldDownload(self, file_server, site, site_temp):
inner_path = self.createBigfile(site)
server1 = file_server
server1.sites[site.address] = site
server2 = FileServer("127.0.0.1", 1545)
server2.sites[site_temp.address] = site_temp
site_temp.connection_server = server2
sha512 = site.content_manager.getFileInfo(inner_path)["sha512"]
# Create 10 fake peer for each piece
for i in range(10):
peer = Peer("127.0.0.1", 1544, site_temp, server2)
peer.piecefields[sha512][i] = "1"
peer.updateHashfield = mock.MagicMock(return_value=False)
peer.updatePiecefields = mock.MagicMock(return_value=False)
peer.findHashIds = mock.MagicMock(return_value={"nope": []})
peer.hashfield = site.content_manager.hashfield
peer.has_hashfield = True
peer.key = "Peer:%s" % i
site_temp.peers["Peer:%s" % i] = peer
site_temp.downloadContent("content.json", download_files=False)
site_temp.needFile("data/optional.any.iso.piecemap.msgpack")
with Spy.Spy(Peer, "getFile") as requests:
for i in range(10):
site_temp.needFile("%s|%s-%s" % (inner_path, i * 1024 * 1024, (i + 1) * 1024 * 1024))
assert len(requests) == 10
for i in range(10):
assert requests[i][0] == site_temp.peers["Peer:%s" % i] # Every part should be requested from piece owner peer
示例9: peerGetFile
def peerGetFile(self, peer_ip, peer_port, site, filename, benchmark=False):
logging.info("Opening a simple connection server")
global file_server
from Connection import ConnectionServer
file_server = ConnectionServer()
from Peer import Peer
logging.info("Getting %s/%s from peer: %s:%s..." % (site, filename, peer_ip, peer_port))
peer = Peer(peer_ip, peer_port)
s = time.time()
peer.getFile(site, filename)
if benchmark:
for i in range(10):
print peer.getFile(site, filename),
print "Response time: %.3fs" % (time.time() - s)
raw_input("Check memory")
示例10: sitePublish
def sitePublish(self, address, peer_ip=None, peer_port=15441, inner_path="content.json", diffs={}):
global file_server
from Site import Site
from Site import SiteManager
from File import FileServer # We need fileserver to handle incoming file requests
from Peer import Peer
SiteManager.site_manager.load()
logging.info("Loading site...")
site = Site(address, allow_create=False)
site.settings["serving"] = True # Serving the site even if its disabled
logging.info("Creating FileServer....")
file_server = FileServer()
site.connection_server = file_server
file_server_thread = gevent.spawn(file_server.start, check_sites=False) # Dont check every site integrity
time.sleep(0.001)
if not file_server_thread.ready():
# Started fileserver
file_server.openport()
if peer_ip: # Announce ip specificed
site.addPeer(peer_ip, peer_port)
else: # Just ask the tracker
logging.info("Gathering peers from tracker")
site.announce() # Gather peers
published = site.publish(5, inner_path, diffs=diffs) # Push to peers
if published > 0:
time.sleep(3)
logging.info("Serving files (max 60s)...")
gevent.joinall([file_server_thread], timeout=60)
logging.info("Done.")
else:
logging.info("No peers found, sitePublish command only works if you already have visitors serving your site")
else:
# Already running, notify local client on new content
logging.info("Sending siteReload")
if config.fileserver_ip == "*":
my_peer = Peer("127.0.0.1", config.fileserver_port)
else:
my_peer = Peer(config.fileserver_ip, config.fileserver_port)
logging.info(my_peer.request("siteReload", {"site": site.address, "inner_path": inner_path}))
logging.info("Sending sitePublish")
logging.info(my_peer.request("sitePublish", {"site": site.address, "inner_path": inner_path, "diffs": diffs}))
logging.info("Done.")
示例11: connect_server
def connect_server(self,ip,port,node=False):
handshake = 'Salamatsyzby' + self.content_id + self.peer_id + struct.pack('!H',self.port)
handshake = pack('!I',len(handshake)) + handshake
stream_data = {'content_id':self.content_id,'chunk_length':0,'piece_length':0, 'handshake':handshake}
p = Peer(stream_data,self,self.Buffer,ip=ip,port=port,server=True,node=node)
if p.socket is not None:
r,w,e = select.select([p],[p],[p],SOCKET_TIMEOUT)
if not w:
self.logger.error('Server (%s:%s) is not available' % (ip,port))
return
p.request_peers()
p.handle_write()
r,w,e = select.select([p],[p],[p],SOCKET_TIMEOUT)
if not r:
self.logger.error('Server (%s:%s) does not respond' % (ip,port))
return
p.handle_read()
if not p.handshaked:
self.logger.error('Could not connect to Server (%s:%s)' % (ip,port))
return
self.logger.info('Connection with Server (%s:%s) established' % (ip,port))
return p
else:
self.logger.error('Server (%s:%s) is not available' % (ip,port))
return
示例12: peerJoin
def peerJoin(self, good=True):
# TODO: Don't assume all are trusted
trusted = None
if len(self.peers) > 0:
trusted = random.sample(self.cPeers, 1)
trusted = trusted[0] # No need for the array
# Add this peer to our network through the trusted node
peer = Peer(trusted, self.peers, self.msgs, self.dkg, good)
self.peers.append(peer)
if good == True:
self.cPeers.append(peer)
# Recalculate n and ln(n) so our swarms are correct
self.n = len(self.peers)
self.lnn = math.log(self.n)
return peer.getId()
示例13: addPeer
def addPeer(self, ip, port, return_peer=False, connection=None, source="other"):
if not ip or ip == "0.0.0.0":
return False
key = "%s:%s" % (ip, port)
peer = self.peers.get(key)
if peer: # Already has this ip
peer.found(source)
if return_peer: # Always return peer
return peer
else:
return False
else: # New peer
if (ip, port) in self.peer_blacklist:
return False # Ignore blacklist (eg. myself)
peer = Peer(ip, port, self)
self.peers[key] = peer
peer.found(source)
return peer
示例14: __processHeartBeats
def __processHeartBeats(self, heartbeats):
""" Process all new peer discoveries """
for ipAddr, macAddr, randomBits in heartbeats:
if macAddr in self.peers.keys():
self.peers[macAddr].checkIP(ipAddr, randomBits)
else:
peer = Peer.createPeer(
ipAddr, self.httpPort, macAddr, randomBits, self.testDistributor, self.resultWorker
)
if peer:
self.peers[macAddr] = peer
示例15: peerCmd
def peerCmd(self, peer_ip, peer_port, cmd, parameters):
logging.info("Opening a simple connection server")
global file_server
from Connection import ConnectionServer
file_server = ConnectionServer()
from Crypt import CryptConnection
CryptConnection.manager.loadCerts()
from Peer import Peer
peer = Peer(peer_ip, peer_port)
import json
if parameters:
parameters = json.loads(parameters.replace("'", '"'))
else:
parameters = {}
try:
res = peer.request(cmd, parameters)
print json.dumps(res, indent=2, ensure_ascii=False)
except Exception, err:
print "Unknown response (%s): %s" % (err, res)