root / DistributedBackupService / src / handlers / BackupChunkHandler.java @ 1
History | View | Annotate | Download (2.24 KB)
1 |
package handlers; |
---|---|
2 |
|
3 |
import server.Peer; |
4 |
import sockets.Socket; |
5 |
import utils.Utils; |
6 |
|
7 |
import java.io.IOException; |
8 |
import java.util.concurrent.atomic.AtomicIntegerArray; |
9 |
|
10 |
import chunk.Chunk; |
11 |
import protocols.BackupChunk; |
12 |
|
13 |
public class BackupChunkHandler implements Runnable { |
14 |
|
15 |
private final String protocolVersion; |
16 |
private Peer parentPeer;
|
17 |
private Chunk chunk;
|
18 |
private AtomicIntegerArray chunkReplication; |
19 |
private int retries = 5; |
20 |
|
21 |
public BackupChunkHandler(BackupChunk backupInitiator, Chunk chunk) {
|
22 |
this.chunk = chunk;
|
23 |
this.parentPeer = backupInitiator.getPeer();
|
24 |
this.protocolVersion = backupInitiator.getVersion();
|
25 |
this.chunkReplication = parentPeer.getPeerInformation().getChunkReplication(chunk.getFileID());
|
26 |
} |
27 |
|
28 |
BackupChunkHandler(Peer parentPeer, Chunk chunk) { |
29 |
this.chunk = chunk;
|
30 |
this.parentPeer = parentPeer;
|
31 |
this.protocolVersion = Utils.VERSION;
|
32 |
this.chunkReplication = null; |
33 |
} |
34 |
|
35 |
@Override
|
36 |
public void run() { |
37 |
|
38 |
int waitTime = 1000; |
39 |
Message msg = generatePutChunkMsg(chunk, protocolVersion); |
40 |
|
41 |
for (int i = 0; i < retries; ++i) { |
42 |
if (isDesiredReplicationDegree()) {
|
43 |
System.out.println("Achieved desired replication at i=" + i); |
44 |
break;
|
45 |
} |
46 |
|
47 |
try {
|
48 |
parentPeer.sendMsg(Socket.SocketType.MDB, msg);
|
49 |
} catch (IOException e) { |
50 |
System.out.println(e.getMessage());
|
51 |
} |
52 |
|
53 |
sleep(waitTime); |
54 |
waitTime *= 2;
|
55 |
} |
56 |
} |
57 |
|
58 |
protected boolean isDesiredReplicationDegree() { |
59 |
return chunkReplication != null && chunkReplication.get(chunk.getChunkNo()) >= chunk.getReplication(); |
60 |
} |
61 |
|
62 |
private void sleep(int waitTime) { |
63 |
try {
|
64 |
Thread.sleep(waitTime);
|
65 |
} catch (InterruptedException e) { |
66 |
e.printStackTrace(); |
67 |
} |
68 |
} |
69 |
|
70 |
private Message generatePutChunkMsg(Chunk chunk, String protocolVersion) { |
71 |
String[] args = { protocolVersion, Integer.toString(parentPeer.getID()), chunk.getFileID(), Integer.toString(chunk.getChunkNo()), Integer.toString(chunk.getReplication()) |
72 |
}; |
73 |
|
74 |
return new Message(Utils.MessageType.PUTCHUNK, args, chunk.getData()); |
75 |
} |
76 |
|
77 |
} |