-
Notifications
You must be signed in to change notification settings - Fork 0
/
local_peer.cpp
302 lines (255 loc) · 7.77 KB
/
local_peer.cpp
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
/*
* File local_peer.cpp
* Group: 14
* Description: Implementation for the LocalPeer class.
*/
#include <fstream>
#include <cstdlib>
#include "local_peer.h"
#include "return_codes.h"
#include "util.h"
#include "constants.h"
#include "queue/concurrent_queue.h"
#include "message.h"
#include <sstream>
/*
* Constructor. Creates new ServerSocket and Server objects using the default
* port number.
*/
LocalPeer::LocalPeer() {
Log::info("LocalPeer() constructor");
_serverSocket = new ServerSocket(constants::DEFAULT_PORT_NUMBER);
_server = new Server(_serverSocket, &_peers);
}
/*
* Constructor. Create new ServerSocket and Server objects using the given
* port number.
*
* portNum: The portNumber on which this local peer will listen for connections.
*/
LocalPeer::LocalPeer(unsigned short portNum) : _portNumber(portNum) {
Log::info("LocalPeer constructor(portNum)");
_serverSocket = new ServerSocket(_portNumber);
_server = new Server(_serverSocket, &_peers);
}
/*
* Destructor
*/
LocalPeer::~LocalPeer() {
Log::info("LocalPeer destructor()");
stopThread();
_serverSocket->closeConnection();
delete _server;
delete _serverSocket;
}
/*
* Adds the given file to the set of files that are/will be replicated across
* the network. A copy of the file is placed with the other files that are being
* synced and then uploaded to other peers via the BitTorrent protocol.
*
* filepath: The file to be replicated
*/
int LocalPeer::insert(std::string filepath) {
Log::info("in LocalPeer::insert()");
int rc = _fileManager.addLocalFile(filepath);
if (rc != 0) {
Log::error("Could not add file");
return rc;
}
Log::info("after addLocalFile() call");
broadcastFileNotification(Util::extractFilename(filepath));
Log::info("after broadcastFileNotification() call");
}
int LocalPeer::query(Status& status) {
return 0;
}
/*
* Attempts to join the set of peers by iterating throught the list of peers.
* Pushes any local files out and also receives any files that the peers might
* have that are not present locally.
*/
int LocalPeer::join() {
Log::info("in LocalPeer::join()");
_peers.initialize(constants::PEERS_LIST);
int returnCode = _peers.connectToAllPeers();
// Start server so it can begin accepting connections
if (!_server->startServer())
return returnCodes::ERROR_UNKNOWN;
// Broadcast files to peers
std::map<std::string, File*>* ft = _fileManager.getFilesTable();
std::map<std::string, File*>::iterator it;
for (it = ft->begin(); it != ft->end(); it++){
broadcastFileNotification(it->first);
}
Log::info("About to start LocalPeer thread");
startThread();
return returnCode;
}
/*
* Leaves the set of peers. The local peer informs all other peers that it is
* leaving. Attempts to push any remaining least replicated chunks out to the
* peers before leaving if there is a small number of them.
*/
int LocalPeer::leave() {
Log::info("in LocalPeer::leave()");
broadcastLeaveNotification();
_server->stopServer();
for (int i = 0; i < _peers.getNumPeers(); i++) {
_peers(i).disconnect();
}
return returnCodes::OK;
}
/*
* Notifies the other peers about the given file
*
* filename: The name of the file
*/
void LocalPeer::broadcastFileNotification(std::string filename) {
Log::info("in LocalPeer::broadcastFileNotification()");
// Construct message
std::stringstream ss;
ss << *(_fileManager.getFile(filename));
Log::info("file serialized");
Message m(Message::FILE_NOTIFICATION, ss.str());
Log::info("message created");
// Iterate through all peers, sending them the message
std::list<Peer*>* peersList = _peers.getPeersList();
std::list<Peer*>::iterator it;
for (it = peersList->begin(); it != peersList->end(); it++) {
if ((*it)->getState() == Peer::connected)
(*it)->sendMessage(m);
}
}
/*
* Notifies the other peers that the peer is leaving the network.
*/
void LocalPeer::broadcastLeaveNotification() {
Log::info("in LocalPeer::broadcastLeaveNotification()");
Message m(Message::LEAVE_NOTIFICATION, "");
std::list<Peer*>* peersList = _peers.getPeersList();
std::list<Peer*>::iterator it;
for (it = peersList->begin(); it != peersList->end(); it++) {
if ((*it)->getState() == Peer::connected)
(*it)->sendMessage(m);
}
}
/*
* Inherited from Thread class. Runs in another thread. Processes messages
* received from other peers by checking each peer's receive message queue. Also
* sends out file chunk requests to other peers.
*/
void LocalPeer::run() {
static int flag = 0;
Log::info("in LocalPeer::run()");
while (true) {
if (isCancelFlagSet())
return;
std::list<Peer*>* peersList = _peers.getPeersList();
std::list<Peer*>::iterator it;
for (it = peersList->begin(); it != peersList->end(); it++) {
ConcurrentQueue<Message>* q = (*it)->getReceiveQueue();
Message m;
// Check peer's receive queue
if (q->tryPop(m)) {
switch(m.getMessageType()) {
case Message::LEAVE_NOTIFICATION:
// Remove peer from list of peers
Log::info("received leave notification");
(*it)->disconnect();
peersList->erase(it++);
continue;
break;
case Message::FILE_CHUNK:
{
Log::info("received file chunk");
// Extract FileChunk object
//std::stringstream ss;
//ss << m.getMessageBody();
//Log::info("after putting message body into stream");
//Log::info("message body: " + m.getMessageBody());
FileChunk fc;
fc.deserialize(m.getMessageBody());
//ss >> fc;
Log::info("deserialized file chunk");
// Write FileChunk to file
_fileManager.addChunkToFile(fc);
Log::info("added chunk to file");
}
break;
case Message::FILE_CHUNK_REQUEST:
{
Log::info("received file chunk request");
std::stringstream ss;
std::string filename;
int chunkIndex = 0;
int totalChunks = 0;
int dataSize = 0;
ss << m.getMessageBody();
ss >> filename;
ss >> chunkIndex;
ss >> totalChunks;
ss >> dataSize;
FileChunk fc(filename, chunkIndex, totalChunks,
dataSize);
//Log::info("created file chunk object");
if (_fileManager.getChunkFromFile(fc)) {
Log::info("got chunk from file");
//std::stringstream ss2;
//ss2 << fc;
Message m(Message::FILE_CHUNK, fc.serialize());
(*it)->sendMessage(m);
}
}
break;
case Message::FILE_NOTIFICATION:
{
Log::info("received file notification");
std::stringstream ss;
ss << m.getMessageBody();
File f;
ss >> f;
_fileManager.addRemoteFile(f.getFilename(),
f.getTotalChunks(), f.getFileSize());
}
break;
default:
Log::info("received default");
break;
}
}
if (flag == 0) { // remove
// Send file chunk request
std::map<std::string, File*>* ft = _fileManager.getFilesTable();
std::map<std::string, File*>::iterator mit;
for (mit = ft->begin(); mit != ft->end(); mit++) {
_fileManager.lock();
File* f = mit->second;
_fileManager.unlock();
if (f->getNumChunks() == f->getTotalChunks())
continue;
for (int i = 0; i < f->getTotalChunks(); i++) {
// Skip chunks we already have
if (f->isAvailable(i))
continue;
// Calculate chunk size
int dataSize = constants::CHUNK_SIZE;
if (i == f->getTotalChunks() - 1) {
// The remainder or chunk size if its divisable
dataSize = f->getFileSize() % constants::CHUNK_SIZE;
if (dataSize == 0)
dataSize = constants::CHUNK_SIZE;
}
std::stringstream ss;
ss << f->getFilename() << " ";
ss << i << " ";
ss << f->getTotalChunks() << " ";
ss << dataSize << " ";
Message m(Message::FILE_CHUNK_REQUEST, ss.str());
(*it)->sendMessage(m);
flag = 1; // remove
}
}
}
}
}
}