Repository navigation
Expand file tree
/
Copy pathpeerProcess.java
More file actions
571 lines (507 loc) · 16.3 KB
/
Copy pathpeerProcess.java
File metadata and controls
571 lines (507 loc) · 16.3 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
import java.io.*;
import java.net.*;
import java.util.*;
public class peerProcess implements MessageConstants
{
public ServerSocket listeningSocket = null;
public int LISTENING_PORT;
public String PEER_IP = null;
public static String peerID;
public int myPeerIndex;
public Thread listeningThread; // Thread for listening to remote clients
public static boolean isFinished = false;
public static BitField ownBitField = null;
public static volatile Timer timerPref;
public static volatile Timer timerUnChok;
public static volatile Hashtable<String, RemotePeerInfo> remotePeerInfoHash = new Hashtable<String, RemotePeerInfo>();
public static volatile Hashtable<String, RemotePeerInfo> preferedNeighbors = new Hashtable<String, RemotePeerInfo>();
public static volatile Hashtable<String, RemotePeerInfo> unchokedNeighbors = new Hashtable<String, RemotePeerInfo>();
public static volatile Queue<DataMessageWrapper> messageQ = new LinkedList<DataMessageWrapper>();
public static Hashtable<String, Socket> peerIDToSocketMap = new Hashtable<String, Socket>();
public static Vector<Thread> receivingThread = new Vector<Thread>();
public static Vector<Thread> sendingThread = new Vector<Thread>();
public static Thread messageProcessor;
public static synchronized void addToMsgQueue(DataMessageWrapper msg)
{
messageQ.add(msg);
}
public static synchronized DataMessageWrapper removeFromMsgQueue()
{
DataMessageWrapper msg = null;
if(!messageQ.isEmpty())
{
msg = messageQ.remove();
}
return msg;
}
public static void readPeerInfoAgain()
{
try
{
String st;
BufferedReader in = new BufferedReader(new FileReader("PeerInfo.cfg"));
while ((st = in.readLine()) != null)
{
String[]args = st.trim().split("\\s+");
String peerID = args[0];
int isCompleted = Integer.parseInt(args[3]);
if(isCompleted == 1)
{
remotePeerInfoHash.get(peerID).isCompleted = 1;
remotePeerInfoHash.get(peerID).isInterested = 0;
remotePeerInfoHash.get(peerID).isChoked = 0;
}
}
in.close();
}
catch (Exception e) {
showLog(peerID + e.toString());
}
}
/**
* Class that handles the preferred neighbors information
* Adding the preferred neighbors with highest data rate to the corresponding list
*/
public static class PreferedNeighbors extends TimerTask {
public void run()
{
//updates remotePeerInfoHash
readPeerInfoAgain();
Enumeration<String> keys = remotePeerInfoHash.keys();
int countInterested = 0;
String strPref = "";
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
RemotePeerInfo pref = remotePeerInfoHash.get(key);
if(key.equals(peerID))continue;
if (pref.isCompleted == 0 && pref.isHandShaked == 1)
{
countInterested++;
}
else if(pref.isCompleted == 1)
{
try
{
preferedNeighbors.remove(key);
}
catch (Exception e) {
}
}
}
if(countInterested > CommonProperties.numOfPreferredNeighbr)
{
boolean flag = preferedNeighbors.isEmpty();
if(!flag)
preferedNeighbors.clear();
List<RemotePeerInfo> pv = new ArrayList<RemotePeerInfo>(remotePeerInfoHash.values());
Collections.sort(pv, new PeerDataRateComparator(false));
int count = 0;
for (int i = 0; i < pv.size(); i++)
{
if (count > CommonProperties.numOfPreferredNeighbr - 1)
break;
if(pv.get(i).isHandShaked == 1 && !pv.get(i).peerId.equals(peerID)
&& remotePeerInfoHash.get(pv.get(i).peerId).isCompleted == 0)
{
remotePeerInfoHash.get(pv.get(i).peerId).isPreferredNeighbor = 1;
preferedNeighbors.put(pv.get(i).peerId, remotePeerInfoHash.get(pv.get(i).peerId));
count++;
strPref = strPref + pv.get(i).peerId + ", ";
if (remotePeerInfoHash.get(pv.get(i).peerId).isChoked == 1)
{
sendUnChoke(peerProcess.peerIDToSocketMap.get(pv.get(i).peerId), pv.get(i).peerId);
peerProcess.remotePeerInfoHash.get(pv.get(i).peerId).isChoked = 0;
sendHave(peerProcess.peerIDToSocketMap.get(pv.get(i).peerId), pv.get(i).peerId);
peerProcess.remotePeerInfoHash.get(pv.get(i).peerId).state = 3;
}
}
}
}
else
{
keys = remotePeerInfoHash.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
RemotePeerInfo pref = remotePeerInfoHash.get(key);
if(key.equals(peerID)) continue;
if (pref.isCompleted == 0 && pref.isHandShaked == 1)
{
if(!preferedNeighbors.containsKey(key))
{
strPref = strPref + key + ", ";
preferedNeighbors.put(key, remotePeerInfoHash.get(key));
remotePeerInfoHash.get(key).isPreferredNeighbor = 1;
}
if (pref.isChoked == 1)
{
sendUnChoke(peerProcess.peerIDToSocketMap.get(key), key);
peerProcess.remotePeerInfoHash.get(key).isChoked = 0;
sendHave(peerProcess.peerIDToSocketMap.get(key), key);
peerProcess.remotePeerInfoHash.get(key).state = 3;
}
}
}
}
// LOG 3: Preferred Neighbors
if (strPref != "")
peerProcess.showLog(peerProcess.peerID + " has selected the preferred neighbors - " + strPref);
}
}
private static void sendUnChoke(Socket socket, String remotePeerID) {
showLog(peerID + " is sending UNCHOKE message to remote Peer " + remotePeerID);
DataMessage d = new DataMessage(DATA_MSG_UNCHOKE);
byte[] msgByte = DataMessage.encodeMessage(d);
SendData(socket, msgByte);
}
private static void sendHave(Socket socket, String remotePeerID) {
byte[] encodedBitField = peerProcess.ownBitField.encode();
showLog(peerID + " sending HAVE message to Peer " + remotePeerID);
DataMessage d = new DataMessage(DATA_MSG_HAVE, encodedBitField);
SendData(socket,DataMessage.encodeMessage(d));
encodedBitField = null;
}
private static int SendData(Socket socket, byte[] encodedBitField) {
try {
OutputStream out = socket.getOutputStream();
out.write(encodedBitField);
} catch (IOException e) {
e.printStackTrace();
return 0;
}
return 1;
}
/**
* Class that handles the Optimistically unchoked neigbhbors information
* 1. Adding the Optimistically unchoked neighors to the corresponding
* list; here it is taken as the first neighbor which is in choked state
*
*/
public static class UnChokedNeighbors extends TimerTask {
public void run()
{
//updates remotePeerInfoHash
readPeerInfoAgain();
if(!unchokedNeighbors.isEmpty())
unchokedNeighbors.clear();
Enumeration<String> keys = remotePeerInfoHash.keys();
Vector<RemotePeerInfo> peers = new Vector<RemotePeerInfo>();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
RemotePeerInfo pref = remotePeerInfoHash.get(key);
if (pref.isChoked == 1
&& !key.equals(peerID)
&& pref.isCompleted == 0
&& pref.isHandShaked == 1)
peers.add(pref);
}
// Randomize the vector elements
if (peers.size() > 0)
{
Collections.shuffle(peers);
RemotePeerInfo p = peers.firstElement();
remotePeerInfoHash.get(p.peerId).isOptUnchokedNeighbor = 1;
unchokedNeighbors.put(p.peerId, remotePeerInfoHash.get(p.peerId));
// LOG 4:
peerProcess.showLog(peerProcess.peerID + " has the optimistically unchoked neighbor " + p.peerId);
if (remotePeerInfoHash.get(p.peerId).isChoked == 1)
{
peerProcess.remotePeerInfoHash.get(p.peerId).isChoked = 0;
sendUnChoke(peerProcess.peerIDToSocketMap.get(p.peerId), p.peerId);
sendHave(peerProcess.peerIDToSocketMap.get(p.peerId), p.peerId);
peerProcess.remotePeerInfoHash.get(p.peerId).state = 3;
}
}
}
}
/**
* Methods to start and stop the Prefered Neighbors and Optimistically
* unchoked neigbhbors update threads
*/
public static void startUnChokedNeighbors()
{
timerPref = new Timer();
timerPref.schedule(new UnChokedNeighbors(),
CommonProperties.optUnchokingInterval * 1000 * 0,
CommonProperties.optUnchokingInterval * 1000);
}
public static void stopUnChokedNeighbors() {
timerPref.cancel();
}
public static void startPreferredNeighbors() {
timerPref = new Timer();
timerPref.schedule(new PreferedNeighbors(),
CommonProperties.unchokingInterval * 1000 * 0,
CommonProperties.unchokingInterval * 1000);
}
public static void stopPreferredNeighbors() {
timerPref.cancel();
}
/**
* Generates log message in following format
* [Time]: Peer [peer_ID] [message]
* @param message
*/
public static void showLog(String message)
{
LogGenerator.writeLog(DateUtil.getTime() + ": Peer " + message);
System.out.println(DateUtil.getTime() + ": Peer " + message);
}
/**
* Reads the system details from the Common.cfg file
* and populates to CommonProperties class static variables
*/
public static void readCommonProperties() {
String line;
try {
BufferedReader in = new BufferedReader(new FileReader("Common.cfg"));
while ((line = in.readLine()) != null) {
String[] tokens = line.split("\\s+");
if (tokens[0].equalsIgnoreCase("NumberOfPreferredNeighbors")) {
CommonProperties.numOfPreferredNeighbr = Integer
.parseInt(tokens[1]);
} else if (tokens[0].equalsIgnoreCase("UnchokingInterval")) {
CommonProperties.unchokingInterval = Integer
.parseInt(tokens[1]);
} else if (tokens[0]
.equalsIgnoreCase("OptimisticUnchokingInterval")) {
CommonProperties.optUnchokingInterval = Integer
.parseInt(tokens[1]);
} else if (tokens[0].equalsIgnoreCase("FileName")) {
CommonProperties.fileName = tokens[1];
} else if (tokens[0].equalsIgnoreCase("FileSize")) {
CommonProperties.fileSize = Integer.parseInt(tokens[1]);
} else if (tokens[0].equalsIgnoreCase("PieceSize")) {
CommonProperties.pieceSize = Integer.parseInt(tokens[1]);
}
}
showLog(peerID + " has set Common Configurations: NumberOfPreferredNeighbors = " + CommonProperties.numOfPreferredNeighbr
+ ", UnchokingInterval = " + CommonProperties.unchokingInterval
+ ", OptimisticUnchokingInterval = " + CommonProperties.optUnchokingInterval
+ ", FileName = " + CommonProperties.fileName
+ ", FileSize = " + CommonProperties.fileSize
+ ", PieceSize = " + CommonProperties.pieceSize);
in.close();
} catch (Exception ex) {
showLog(peerID + ex.toString());
}
}
/**
* Reads the Peer details from the PeerInfo.cfg file
* and populates to peerInfoVector vector
*/
public static void readPeerInfo() {
String st;
try {
BufferedReader in = new BufferedReader(new FileReader("PeerInfo.cfg"));
int i = 0;
while ((st = in.readLine()) != null) {
String[] tokens = st.split("\\s+");
remotePeerInfoHash.put(tokens[0], new RemotePeerInfo(tokens[0],
tokens[1], tokens[2], Integer.parseInt(tokens[3]), i));
i++;
}
in.close();
} catch (Exception ex) {
showLog(peerID + ex.toString());
}
}
@SuppressWarnings("deprecation")
public static void main(String[] args)
{
peerProcess pProcess = new peerProcess();
peerID = args[0];
try
{
// starts saving standard output to log file
LogGenerator.start("log_peer_" + peerID +".log");
showLog(peerID + " is started");
// reads Common.cfg file and populates CommonProperties class
readCommonProperties();
// reads PeerInfo.cfg file and populates RemotePeerInfo class
readPeerInfo();
// for the initial calculation
initializePrefferedNeighbours();
boolean isFirstPeer = false;
Enumeration<String> e = remotePeerInfoHash.keys();
while(e.hasMoreElements())
{
RemotePeerInfo peerInfo = remotePeerInfoHash.get(e.nextElement());
if(peerInfo.peerId.equals(peerID))
{
// checks if the peer is the first peer or not
pProcess.LISTENING_PORT = Integer.parseInt(peerInfo.peerPort);
pProcess.myPeerIndex = peerInfo.peerIndex;
if(peerInfo.getIsFirstPeer() == 1)
{
isFirstPeer = true;
break;
}
}
}
// Initialize the Bit field class
ownBitField = new BitField();
ownBitField.initOwnBitfield(peerID, isFirstPeer?1:0);
messageProcessor = new Thread(new MessageProcessor(peerID));
messageProcessor.start();
if(isFirstPeer)
{
try
{
pProcess.listeningSocket = new ServerSocket(pProcess.LISTENING_PORT);
//instantiates and starts Listening Thread
pProcess.listeningThread = new Thread(new ListeningThread(pProcess.listeningSocket, peerID));
pProcess.listeningThread.start();
}
catch(SocketTimeoutException tox)
{
showLog(peerID + " gets time out expetion: " + tox.toString());
LogGenerator.stop();
System.exit(0);
}
catch(IOException ex)
{
showLog(peerID + " gets exception in Starting Listening thread: " + pProcess.LISTENING_PORT + ex.toString());
LogGenerator.stop();
System.exit(0);
}
}
// Not the first peer
else
{
createEmptyFile();
e = remotePeerInfoHash.keys();
while(e.hasMoreElements())
{
RemotePeerInfo peerInfo = remotePeerInfoHash.get(e.nextElement());
if(pProcess.myPeerIndex > peerInfo.peerIndex)
{
Thread tempThread = new Thread(new RemotePeerHandler(
peerInfo.getPeerAddress(), Integer
.parseInt(peerInfo.getPeerPort()), 1,
peerID));
receivingThread.add(tempThread);
tempThread.start();
}
}
// Spawns a listening thread
try
{
pProcess.listeningSocket = new ServerSocket(pProcess.LISTENING_PORT);
pProcess.listeningThread = new Thread(new ListeningThread(pProcess.listeningSocket, peerID));
pProcess.listeningThread.start();
}
catch(SocketTimeoutException tox)
{
showLog(peerID + " gets time out exception in Starting the listening thread: " + tox.toString());
LogGenerator.stop();
System.exit(0);
}
catch(IOException ex)
{
showLog(peerID + " gets exception in Starting the listening thread: " + pProcess.LISTENING_PORT + " "+ ex.toString());
LogGenerator.stop();
System.exit(0);
}
}
startPreferredNeighbors();
startUnChokedNeighbors();
while(true)
{
// checks for termination
isFinished = isFinished();
if (isFinished) {
showLog("All peers have completed downloading the file.");
stopPreferredNeighbors();
stopUnChokedNeighbors();
try {
Thread.currentThread();
Thread.sleep(2000);
} catch (InterruptedException ex) {
}
if (pProcess.listeningThread.isAlive())
pProcess.listeningThread.stop();
if (messageProcessor.isAlive())
messageProcessor.stop();
for (int i = 0; i < receivingThread.size(); i++)
if (receivingThread.get(i).isAlive())
receivingThread.get(i).stop();
for (int i = 0; i < sendingThread.size(); i++)
if (sendingThread.get(i).isAlive())
sendingThread.get(i).stop();
break;
} else {
try {
Thread.currentThread();
Thread.sleep(5000);
} catch (InterruptedException ex) {
}
}
}
}
catch(Exception ex)
{
showLog(peerID + " Exception in ending : " + ex.getMessage() );
}
finally
{
showLog(peerID + " Peer process is exiting..");
LogGenerator.stop();
System.exit(0);
}
}
private static void initializePrefferedNeighbours()
{
Enumeration<String> keys = remotePeerInfoHash.keys();
while(keys.hasMoreElements())
{
String key = (String)keys.nextElement();
if(!key.equals(peerID))
{
preferedNeighbors.put(key, remotePeerInfoHash.get(key));
}
}
}
/**
* Checks if all peer has down loaded the file
*/
public static synchronized boolean isFinished() {
String line;
int hasFileCount = 1;
try {
BufferedReader in = new BufferedReader(new FileReader(
"PeerInfo.cfg"));
while ((line = in.readLine()) != null) {
hasFileCount = hasFileCount
* Integer.parseInt(line.trim().split("\\s+")[3]);
}
if (hasFileCount == 0) {
in.close();
return false;
} else {
in.close();
return true;
}
} catch (Exception e) {
showLog(e.toString());
return false;
}
}
public static void createEmptyFile() {
try {
File dir = new File(peerID);
dir.mkdir();
File newfile = new File(peerID, CommonProperties.fileName);
OutputStream os = new FileOutputStream(newfile, true);
byte b = 0;
for (int i = 0; i < CommonProperties.fileSize; i++)
os.write(b);
os.close();
}
catch (Exception e) {
showLog(peerID + " ERROR in creating the file : " + e.getMessage());
}
}
}