Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Add java-bittorrent example (still not working).
[simgrid.git] / examples / lua / bittorrent / tracker.lua
1 -- A SimGrid Lua implementation of the Bittorrent protocol.
2
3 require("simgrid")
4
5 common_tracker = {
6         MAXIMUM_PEERS = 50
7 }
8
9
10
11 function tracker(...)
12         tracker_data = {
13                 peers_list = {},
14                 deadline = 0,
15                 comm_received = nil
16         }
17   -- Check the arguments
18   local args = {...}
19   if #args ~= 1 then
20         simgrid.info("Wrong number of arguments for the tracker")
21   end
22   -- Initialization of the random generator
23   math.randomseed(42)
24   -- Retrieve the end time
25   tracker_data.deadline = tonumber(args[1])
26   
27   simgrid.info("Tracker launched")
28   
29   local now = simgrid.get_clock()
30   
31   tracker_data.comm_received = simgrid.task.irecv("tracker")
32   while now < tracker_data.deadline do
33         task, err = tracker_data.comm_received:test()
34         if task then
35                 simgrid.debug("Received a request from " .. task.mailbox)
36                 tracker_data.comm_received = simgrid.task.irecv("tracker")
37                 -- Sending peers to the peer
38                 local peers = {}
39                 local i = 0 
40                 if #tracker_data.peers_list > 0 then
41                         i = math.random(1,#tracker_data.peers_list)
42                 end
43                 while #peers < #tracker_data.peers_list and #peers < common_tracker.MAXIMUM_PEERS do
44                         table.insert(peers,tracker_data.peers_list[i])  
45                         i = (i + 1) % #tracker_data.peers_list
46                 end
47                 task.type = "ANSWER"
48                 task.peers = peers
49                 -- Add the peer to our peer list
50                 table.insert(tracker_data.peers_list,task.peer_id)
51                 -- Setting the interval
52                 task.interval = TRACKER_QUERY_INTERVAL
53                 -- Sending the task back to the peer
54                 task:dsend(task.mailbox)
55         else
56                 simgrid.process.sleep(1)
57                 now = simgrid.get_clock()
58         end
59   end
60   
61   simgrid.info("Tracker is leaving")
62 end