Esempio n. 1
0
def peer(request):
	# Answer the peer request from an node
	if request.method == "POST":
		print("overlay/peer request:", request.POST)
		print("overlay/peer request keys:", request.POST.keys())
		peer_node = request.POST.get("node", "")
		print("node info in request:", peer_node)
		peer_id  = int(re.findall(r'\d+', peer_node)[0])
		peer_ip = request.POST.get("ip", "")
		print("ip info in request:", peer_ip)
		new_peer = Peer(id=peer_id, name=peer_node, ip=peer_ip)
		new_peer.save()
		return HttpResponse("Successfully peering with agent " + get_host_name() + ".")
	elif request.method == "GET":
		print("The requested url is: ", request.get_full_path())
		return HttpResponse("Please use POST method to peer with an agent when using http://cache_agent:port/overlay/peer/.")
def peer_with(peer):
	url = 'http://%s:8615/overlay/peer/'%peer['ip']
	cur_srv = Server.objects.filter(isLocal=True)[0]
	peer_data = {}
	peer_data['node'] = cur_srv.name
	peer_data['ip'] = cur_srv.ip
	encoded_peer_data = urllib.parse.urlencode(peer_data)
	data = encoded_peer_data.encode('utf-8')

	try:
		req = urllib.request.Request(url, data)
		rsp = urllib.request.urlopen(req,timeout=10)
		rsp_data = rsp.read()
		print(rsp_data)
		peer_name = peer['name']
		peer_id = peer['id']
		peer_ip = peer['ip']
		new_peer = Peer(id=peer_id, name=peer_name, ip=peer_ip)
		new_peer.save()
		print("Added new peer", peer_name, "to the agentPeer listi!")
		return True
	except:
		return False