Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
[Lua] Updated the bittorent.lua test
[simgrid.git] / examples / lua / bittorrent / tracker.lua
1 -- Copyright (c) 2012, 2014. The SimGrid Team.
2 -- All rights reserved.
3
4 -- This program is free software; you can redistribute it and/or modify it
5 -- under the terms of the license (GNU LGPL) which comes with this package.
6
7 -- A SimGrid Lua implementation of the Bittorrent protocol.
8
9 require("simgrid")
10
11 common_tracker = {
12         MAXIMUM_PEERS = 50
13 }
14
15
16
17 function tracker(...)
18         tracker_data = {
19                 peers_list = {},
20                 deadline = 0,
21                 comm_received = nil
22         }
23   -- Check the arguments
24   local args = {...}
25   if #args ~= 1 then
26         simgrid.info("Wrong number of arguments for the tracker")
27   end
28   -- Retrieve the end time
29   tracker_data.deadline = tonumber(args[1])
30   
31   simgrid.info("Tracker launched")
32   
33   local now = simgrid.get_clock()
34   
35   tracker_data.comm_received = simgrid.task.irecv("tracker")
36   while now < tracker_data.deadline do
37         task, err = tracker_data.comm_received:test()
38         if task then
39                 simgrid.debug("Received a request from " .. task.mailbox)
40                 tracker_data.comm_received = simgrid.task.irecv("tracker")
41                 -- Sending peers to the peer
42                 local peers = {}
43                 local i = 0 
44                 if #tracker_data.peers_list > 0 then
45                         i = math.random(1,#tracker_data.peers_list)
46                 end
47                 while #peers < #tracker_data.peers_list and #peers < common_tracker.MAXIMUM_PEERS do
48                         table.insert(peers,tracker_data.peers_list[i])
49                         i = (i % #tracker_data.peers_list) +1
50                 end
51                 task.type = "ANSWER"
52                 task.peers = peers
53                 -- Add the peer to our peer list
54                 table.insert(tracker_data.peers_list,task.peer_id)
55                 -- Setting the interval
56                 task.interval = TRACKER_QUERY_INTERVAL
57                 -- Sending the task back to the peer
58                 task:dsend(task.mailbox)
59         else
60                 simgrid.process.sleep(1)
61                 now = simgrid.get_clock()
62         end
63   end
64   
65   simgrid.info("Tracker is leaving")
66 end