-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtracker.py
More file actions
72 lines (56 loc) · 2.4 KB
/
tracker.py
File metadata and controls
72 lines (56 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import json
from flask import Flask, request, jsonify
# This is a simple tracker server that registers peers and allows chunk lookups.
app = Flask(__name__)
peer_chunk_map = {}
# This endpoint allows peers to register themselves with the tracker.
@app.route('/register', methods=['POST'])
def register_peer():
try:
data = request.get_json()
file_name = data.get("file_name")
ip = data.get("ip")
port = data.get("port")
chunks = data.get("chunks")
if not all([file_name, ip, port, chunks]):
return jsonify({"error": "Missing required fields"}), 400
for h in chunks:
if not isinstance(h, str) or len(h) < 10:
return jsonify({"error": f"Invalid chunk hash: {h}"}), 400
peer = (ip, port)
if peer in peer_chunk_map:
peer_chunk_map[peer].update(chunks)
else:
peer_chunk_map[peer] = set(chunks)
print(f"✅ Registered peer {peer} with {len(chunks)} chunks.")
print(f"📦 Current peer_chunk_map has {len(peer_chunk_map)} peers.")
print("Registering chunks:", chunks)
return jsonify({"message": "Successfully registered with tracker."}), 200
except Exception as e:
print(f"❌ Error during registration: {e}")
return jsonify({"error": "Registration failed"}), 500
# This endpoint allows peers to look up which peers have a specific chunk.
@app.route('/lookup', methods=['POST'])
def lookup_chunk():
try:
data = request.get_json()
chunk_hash = data.get("chunk_hash")
print(f"🔍 Lookup request for chunk: {chunk_hash}")
if not chunk_hash:
return jsonify({"error": "chunk_hash is required"}), 400
peers_with_chunk = [
{"ip": ip, "port": port}
for (ip, port), chunks in peer_chunk_map.items()
if chunk_hash in chunks
]
if not peers_with_chunk:
print(f"⚠️ No peers found for chunk {chunk_hash}.")
return jsonify({"peers": []}), 404
print(f"✅ Found {len(peers_with_chunk)} peer(s) for chunk {chunk_hash}.")
return jsonify({"peers": peers_with_chunk}), 200
except Exception as e:
print(f"❌ Error during chunk lookup: {e}")
return jsonify({"error": "Chunk lookup failed"}), 500
# Driver code to run the Flask app
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000)