Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
cdf3e3b6425dffe0ab0cc669bf94cb4b7a84009c
[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   -- Initialization of the random generator
29   math.randomseed(42)
30   -- Retrieve the end time
31   tracker_data.deadline = tonumber(args[1])
32   
33   simgrid.info("Tracker launched")
34   
35   local now = simgrid.get_clock()
36   
37   tracker_data.comm_received = simgrid.task.irecv("tracker")
38   while now < tracker_data.deadline do
39         task, err = tracker_data.comm_received:test()
40         if task then
41                 simgrid.debug("Received a request from " .. task.mailbox)
42                 tracker_data.comm_received = simgrid.task.irecv("tracker")
43                 -- Sending peers to the peer
44                 local peers = {}
45                 local i = 0 
46                 if #tracker_data.peers_list > 0 then
47                         i = math.random(1,#tracker_data.peers_list)
48                 end
49                 while #peers < #tracker_data.peers_list and #peers < common_tracker.MAXIMUM_PEERS do
50                         table.insert(peers,tracker_data.peers_list[i])
51                         i = (i % #tracker_data.peers_list) +1
52                 end
53                 task.type = "ANSWER"
54                 task.peers = peers
55                 -- Add the peer to our peer list
56                 table.insert(tracker_data.peers_list,task.peer_id)
57                 -- Setting the interval
58                 task.interval = TRACKER_QUERY_INTERVAL
59                 -- Sending the task back to the peer
60                 task:dsend(task.mailbox)
61         else
62                 simgrid.process.sleep(1)
63                 now = simgrid.get_clock()
64         end
65   end
66   
67   simgrid.info("Tracker is leaving")
68 end