-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbankServer.cpp
455 lines (375 loc) · 11.8 KB
/
bankServer.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
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
#include "bankServer.h"
#include "bankAccount.h"
#include "hashtable.h"
#include "readWriteFunct.h"
#include "queue.h"
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h> /* sockets */
#include <netinet/in.h> /* internet sockets */
#include <netdb.h> /* gethostbyaddr */
pthread_cond_t cond_nonempty;
pthread_cond_t cond_nonfull;
using namespace std;
BankServer::BankServer(int numberBuckets, int queueSize)
{
bankAccounts = new HashTable(numberBuckets);
socketQueue = new Queue(queueSize);
}
BankServer::~BankServer()
{
delete bankAccounts;
delete socketQueue;
}
bool BankServer::addAccount(bankAccount* bAccount, long delay)
{
bool result;
bankAccounts->lockHashtable();
usleep(delay); //koimathe msec
result = bankAccounts->insertNode(bAccount);
bankAccounts->unlockHashtable();
return result;
}
bool BankServer::addTransfer(std::string fromAccount, std::string toAccount, double amount, long delay, bool lock)
{
bankAccount* frAccount;
bankAccount* tAccount;
if(lock == true) //an prepei na kleidwthei to kleidwnei
{
bankAccounts->lockHashtable();
usleep(delay);
}
frAccount = bankAccounts->searchNode(fromAccount); //psaxnw ta dyo stoxeia
tAccount = bankAccounts->searchNode(toAccount);
if(frAccount == NULL || tAccount == NULL)
{
if(lock == true) bankAccounts->unlockHashtable();
return false;
}
if(frAccount->sendAmount(tAccount->get_name(), amount) == false)
{
if(lock == true) bankAccounts->unlockHashtable();
return false;
}
tAccount->receiveAmount(frAccount->get_name(), amount); //kai metaferw ta xrhmata
if(lock == true) bankAccounts->unlockHashtable(); //ama to kleidwsa prepei na to kseklidwsw
return true;
}
bool BankServer::multi_addTransfer(std::string from, List<std::string>* to, double amount, long delay)
{
string* tmp;
bool success = true;
bankAccounts->lockHashtable(); //kleidwno to hashtable
usleep(delay);
for(Node<std::string>* i = to->get_begin(); i != NULL; i = i->get_next())
{
tmp = i->get_data();
if(this->addTransfer(from, *tmp, amount, 0, false) == false) //ama apotyxei esto kai mia prepei na epistrafoun ta proigoumena posa
{
success = false;
for(Node<std::string>* j = to->get_begin(); j != i; j = j->get_next()) // prepei na epanaferw oso xrhmata esteila mexri tora
{
tmp = j->get_data();
this->addTransfer(*tmp, from, amount, 0, false);
}
break;
}
}
bankAccounts->unlockHashtable(); //kseklidwma
return success;
}
bool BankServer::printBalance(std::string accountName, double& amount, bool lock)
{
bankAccount* bAccount;
if(lock == true) bankAccounts->lockHashtable();
bAccount = bankAccounts->searchNode(accountName);
if(bAccount == NULL) //an dn yparxei vgainw kai epistrefw apotyxia
{
if(lock == true) bankAccounts->unlockHashtable();
return false;
}
amount = bAccount->get_amount();
if(lock == true) bankAccounts->unlockHashtable();
return true;
}
bool BankServer::multiPrintBalance(List<std::string>* que, int fd)
{
string printString = "";
string* tmp;
bool success = true;
double amount;
char amountString[24];
bankAccounts->lockHashtable();
for(Node<std::string>* i = que->get_begin(); i != NULL; i = i->get_next())
{
tmp = i->get_data();
if(this->printBalance(*tmp, amount, false) == false) //an apotyxei esto kai ena prepei na steilw mnm apotyxias
{
success = false;
break;
}
sprintf(amountString, "%lf", amount);
printString += *tmp + "/" + amountString; //prosthetw to name kai amount sto string ektypwshs
if(i->get_next() != NULL) printString +=":"; //sto teleutaio dn prepei na mpei to ":"
}
bankAccounts->unlockHashtable();
if(success == true)
{
printString.insert(0, "Success. Multi-Balance (");
printString.append(")");
}
else //an apetyxe prepei na steilw mnm sfalmatos
{
printString.clear();
printString.insert(0, "Error. Multi-Balance (");
for(Node<std::string>* i = que->get_begin(); i != NULL; i = i->get_next()) //vazw ola ta names
{
printString += *(i->get_data());
if(i->get_next() != NULL) printString +=":";
}
printString.append(")");
}
write_data(fd, printString.c_str());
return success;
}
void BankServer::masterThread(int port, int numberOfThreads) //arxiko thread
{
int sock, newsock;
struct sockaddr_in server, client;
socklen_t clientlen = sizeof(struct sockaddr_in);
struct sockaddr *serverptr=(struct sockaddr *)&server;
struct sockaddr *clientptr=(struct sockaddr *)&client;
struct hostent *rem;
pthread_t cons, prod;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket");
exit(2);
}
server.sin_family = AF_INET; /* Internet domain */
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(port); /* The given port */
/* Bind socket to address */
if (bind(sock, serverptr, sizeof(server)) < 0)
{
perror("bind");
exit(2);
}
/* Listen for connections */
if (listen(sock, 5) < 0)
{
perror("listen");
exit(2);
}
printf("Listening for connections to port %d\n", port);
//kataskeuei threads
struct threadData* data = (struct threadData*) malloc(sizeof(struct threadData));
data->socketsQueue = this->socketQueue;
data->server = this;
for(int i=0; i< numberOfThreads; i++)
{
pthread_create(&cons, NULL, worker, (void*)data); //kathe thread ttha parei ta idia data giati douleuei ston idio server kai sto ido queue
}
while (1) //stamataei mono me control c
{
/* accept connection */
if ((newsock = accept(sock, clientptr, &clientlen)) < 0)
{
perror("accept");
exit(2);
}
printf("Accepted connection\n");
socketQueue->push(newsock); //to prosthetw sthn oura
pthread_cond_signal(&cond_nonempty); //kai eidopoiw oti h oura dn einai kenh, akrivos ena kai opoiodipote thread thelw na ksypnisei gia auto dn xreiazetai broadcast
}
delete data;
}
void* worker(void* ptr) //thread function
{
struct threadData* data = (struct threadData*)(ptr);
char buf[1024];
cout<<"thread created"<<endl;
string buff;
int i, fd;
while(1)
{
fd = data->socketsQueue->pop(); //afairw ena socket apo thn oura
pthread_cond_signal(&cond_nonfull); //eidopoiw oti dn einai gemati
printf("pop %d thread %ld\n", fd, pthread_self());
while((i = read_data(fd, buf)) > 0) //diavaszw mexri na kleisei h syndesh
{
buff = buf;
if(data->server->parseCommand(buff, fd) == false) //stelnw apanthsh 'h mnm sfalmatos
{
write_data(fd, "Error. Unknown command");
}
}
printf("Closing connection.\n");
close(fd); /* Close socket */
}
}
bool BankServer::parseCommand(string& line, int fd) //ektelei thn entolh kai stelnei apotelesma
{
string command, name;
double amount;
long delay;
istringstream iss(line);
iss>> command;
if(iss.fail())
{
return false;
}
if(command == "add_account")
{
iss>> amount>>name;
if(!iss)
{
return false;
}
iss>>delay;
if(!iss) //an dn yparxei delay to thetw 0
{
delay = 0;
}
bankAccount* tmp = new bankAccount(name, amount);
string answer = "Account creation ";
if(!this->addAccount(tmp, delay)) //prosthetw to account sto hashtable
{
answer.insert(0, "Error. ");
answer +="failed ";
delete tmp;
}
else
{
answer.insert(0, "Success. ");
}
char amountString[24];
sprintf(amountString, "%lf", amount); //metatropi se string
answer += "(" + name + ":" + string(amountString)+")"; //egrafh mnmatos
write_data(fd, answer.c_str());
}
else if(command == "add_transfer")
{
string fromAc, ToAc;
iss >>amount >> fromAc >> ToAc;
if(!iss)
{
return false;
}
iss>>delay;
if(!iss)
{
delay = 0;
}
string answer = "Transfer addition ";
if(!this->addTransfer(fromAc, ToAc, amount, delay))
{
answer.insert(0, "Error. ");
answer +="failed ";
}
else
{
answer.insert(0, "Success. ");
}
char amountString[24];
char delayString[24];
sprintf(amountString, "%lf", amount);
sprintf(delayString, "%ld", delay);
answer += "(" + fromAc + ":" + ToAc + ":" + string(amountString)+"[:" + string(delayString)+ "]" + ")";
write_data(fd, answer.c_str());
}
else if(command == "add_multi_transfer")
{
List<std::string>* accounts = new List<std::string>();
string dstName;
string* tmp;
iss >> amount >> name;
while(true)
{
iss >> dstName;
if(!iss) break;
tmp = new string(dstName); //kathe name pou diavazw to prosthetw sthn lista
accounts->insertEnd(tmp);
}
tmp = accounts->get_last()->get_data(); //to teleutaio mporei na einai to delay
delay = atoi(tmp->c_str());
if(delay != 0) delete accounts->deleteLastNode(); //an einai to delay to afairw apo thn lista
string answer = "Multi-Transfer addition ";
if(this->multi_addTransfer(name, accounts, amount, delay) == true)
{
answer.insert(0, "Success. ");
}
else
{
answer.insert(0, "Error. ");
answer+=("failed ");
}
char amountString[24];
char delayString[24];
sprintf(amountString, "%lf", amount);
sprintf(delayString, "%ld", delay);
answer += "(" + name + ":" + string(amountString)+"[:" + string(delayString)+ "]" + ")";
write_data(fd, answer.c_str());
while((tmp = accounts->deleteFirstNode()) != NULL)//diagrafh domwn pou eftiksa proigoumenos
{
delete tmp;
}
delete accounts;
}
else if(command == "print_balance")
{
double tmpAmount;
iss>> name;
if(!iss)
{
return false;
}
string answer = "Balance ";
answer += "(" + name;
if(this->printBalance(name, tmpAmount))
{
answer.insert(0, "Success. ");
char amountString[24];
sprintf(amountString, "%lf", tmpAmount);
answer += ":" + string(amountString)+")";
}
else
{
answer.insert(0, "Error. ");
answer += ")";
}
write_data(fd, answer.c_str());
}
else if(command == "print_multi_balance")
{
double tmpAmount;
List<std::string>* accounts = new List<std::string>();
string* tmp;
while(true)
{
iss >> name;
if(!iss) break;
tmp = new string(name);
accounts->insertEnd(tmp);
}
this->multiPrintBalance(accounts, fd);
while((tmp = accounts->deleteFirstNode()) != NULL)
{
delete tmp;
}
delete accounts;
}
else //error
{
return false;
}
return true;
}