-
Notifications
You must be signed in to change notification settings - Fork 0
/
RMIServerImpl.java
523 lines (483 loc) · 13.8 KB
/
RMIServerImpl.java
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
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.RMISecurityManager;
import java.rmi.RemoteException;
import java.rmi.Naming;
import java.rmi.registry.*;
import java.io.*;
import java.util.*;
import Requests.*;
import Responses.*;
public class RMIServerImpl extends UnicastRemoteObject implements RMIServer , RMIBroadcastServer{
private static RMIServerImpl server;
public static int server_id;
public static long lamportClock;
public static AccountManager accountManager;
public final String filename= "serverLogfile";
public static String peerInfo[] ;
public static int numPeers;
public static RMIBroadcastServer peers[];
public static PriorityQueue<Ticket> pq = new PriorityQueue<Ticket>();
public static int requestCount;
public static long respondTime;
public static Calendar calendar = Calendar.getInstance();
public synchronized void recordPerformance(long duration){
respondTime = respondTime + duration;
requestCount = requestCount+1;
}
class Ticket implements Comparable<Ticket>{
public long timestamp;
public int pid;
public Request req;
Ticket(long timestamp, int id,Request req){
this.timestamp = timestamp;
this.pid = id;
this.req = req;
}
public int compareTo(Ticket t ){
if(this.timestamp > t.timestamp)
return 1;
else if (this.timestamp < t.timestamp)
return -1;
else{
if(this.pid < t.pid)
return -1;
else if(this.pid == t.pid)
return 0;
else
return 1;
}
}
};
public synchronized void writeLog(String content) {
try{
FileWriter fw = new FileWriter("logs/"+filename+(server_id+1),true);
fw.write(content+"\n");
fw.close();
}catch(IOException e){
}
}
public synchronized long setLamportClock(long timestamp){
this.lamportClock = Math.max(lamportClock,timestamp);
return this.lamportClock;
};
public synchronized void assignTimestamp(Request r){
r.timestamp = ++lamportClock;
}
public static void readFileByLine(String fileName) throws Exception {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
numPeers = Integer.parseInt(scanner.nextLine());
peerInfo = new String [numPeers];
int i = 0;
for(i=0;i<numPeers;i++){
peerInfo[i] = scanner.nextLine();
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
RMIServerImpl() throws RemoteException{
lamportClock = 0;
requestCount = 0;
respondTime = 0;
}
public NewAccountResponse newAccount(NewAccountRequest nar) throws RemoteException{
NewAccountResponse narr = new NewAccountResponse("Fail",-1);
try{
int id = accountManager.newAccount(nar.firstname,nar.lastname,nar.address);
narr = new NewAccountResponse("OK",id);
}catch(Exception e){
narr.setStatus(e.toString());
}finally{
//writeLog("Request of type "+nar.requestType+", firstname = "+nar.firstname+" lastname = "+nar.lastname+" address= "+nar.address+" status = "+narr.status);
}
return narr;
};
public DepositResponse deposit(DepositRequest dr) throws RemoteException{
DepositResponse dp = new DepositResponse("OK");
try{
Account account = accountManager.getAccountById(dr.accountId);
if(account!=null){
synchronized(account){
account.deposit(dr.amount);
}
}else{
throw new RuntimeException("Account ID not found");
}
}catch(Exception e){
dp.setStatus(e.toString());
}finally{
//writeLog("Handling request of type "+dr.requestType+", account ID = "+dr.accountId+" amount = "+dr.amount+ " status = "+dp.status);
}
return dp;
};
public GetBalanceResponse getBalance(GetBalanceRequest gbr) throws RemoteException{
GetBalanceResponse gbrr = new GetBalanceResponse("Fail",-1);
int balance;
try{
Account account = accountManager.getAccountById(gbr.accountId);
if(account!=null){
synchronized(account){
balance = account.getBalance();
}
}else{
throw new RuntimeException("Account Id not found");
}
gbrr = new GetBalanceResponse("OK",balance);
}catch(Exception e){
gbrr.setStatus(e.toString());
}finally{
//writeLog("Handling request of type "+gbr.requestType+", account ID = "+gbr.accountId+" status = "+gbrr.status);
}
return gbrr;
};
public TransferResponse transfer(TransferRequest tr) throws RemoteException{
TransferResponse trr = new TransferResponse("OK");
try{
Account source = accountManager.getAccountById(tr.sourceId);
Account target = accountManager.getAccountById(tr.targetId);
if(source!=null){
if(target!=null){
if(tr.sourceId<tr.targetId){
synchronized(source){
synchronized(target){
source.withdraw(tr.amount);
target.deposit(tr.amount);
}
}
}else{
synchronized(target){
synchronized(source){
source.withdraw(tr.amount);
target.deposit(tr.amount);
}
}
}
}else{
throw new RuntimeException("Target ID not FOUND");
}
}else{
throw new RuntimeException("Source ID not FOUND");
}
}catch(Exception e){
trr.setStatus(e.toString());
}finally{
// writeLog("Handling request of type "+tr.requestType+", from account ID = "+tr.sourceId+"to accountId"+tr.targetId+" amount = "+tr.amount+" status = "+trr.status);
}
return trr;
};
public WithdrawResponse withdraw(WithdrawRequest wr) throws RemoteException{
WithdrawResponse wrr = new WithdrawResponse("OK");
try{
Account account = accountManager.getAccountById((wr.accountId));
if(account!=null){
synchronized(account){
account.withdraw(wr.amount);
}
}else{
throw new RuntimeException("Account ID not Found");
}
}catch(Exception e){
wrr.setStatus(e.toString());
}finally{
// writeLog("Handling request of type "+wr.requestType+", account ID = "+wr.accountId+" amount = "+wr.amount+" status = "+wrr.status);
}
return wrr;
};
class PeerThread extends Thread{
int peer_id ;
PeerThread(int i){
peer_id = i;
}
public void run(){
while(true){
try{
peers[peer_id] = (RMIBroadcastServer) Naming.lookup ("//" + peerInfo[peer_id] + "/RMIBroadcastServer");
}catch(Exception e){
System.out.println("Failed to connect to server of id "+ (peer_id+1) +" with "+e);
System.out.println("Retry in 1 seconds");
try{
Thread.sleep(1000);
}catch(Exception e2){
e2.printStackTrace();
}finally{
continue;
}
}
break;
}
}
}
public void buildPeerConnections(){
PeerThread pt [] = new PeerThread[numPeers];
System.out.println("Building Peer Connections");
int i =0 ;
peers = new RMIBroadcastServer[numPeers];
for (i =0 ; i < numPeers ;i++){
if(i == server_id) continue;
pt[i] = new PeerThread(i);
pt[i].start();
}
for (i =0 ; i < numPeers ;i++){
if(i == server_id ) continue;
try{
pt[i].join();
}catch(Exception e){
}
}
System.out.println("Peer Connections Built Successfully");
};
public void executeRequest(Request r,int from_pid) throws RemoteException{
writeLog((from_pid+1)+" Process "+calendar.getTime()+" "+r.timestamp);
switch(r.requestType){
case "Deposit":
deposit((DepositRequest) r);
break;
case "GetBalance":
getBalance((GetBalanceRequest) r);
break;
case "NewAccount":
newAccount((NewAccountRequest) r);
break;
case "Transfer":
transfer((TransferRequest) r);
break;
case "Withdraw":
withdraw((WithdrawRequest) r);
break;
case "Halt":
halt();
break;
default:
throw new RemoteException("Unsupported Request");
}
};
public void halt(){
System.out.println("Printing Balance Info :");
accountManager.printAccountsBalance();
System.out.println("Printing Pending Requests");
while(pq.peek()!=null){
System.out.println(pq.poll().req);
}
if(requestCount != 0 )
System.out.println("The average respone time for "+ requestCount + " requests is "+ (respondTime/requestCount) +" nanoseconds. ");
else
System.out.println("This server has no request from the client");
new HaltThread().start();
}
public Response processRequest(Request r) throws RemoteException{
Response ret = null;
writeLog((server_id+1)+" Process "+calendar.getTime()+" "+r.timestamp);
switch(r.requestType){
case "Deposit":
ret= deposit((DepositRequest) r);
break;
case "GetBalance":
ret= getBalance((GetBalanceRequest) r);
break;
case "NewAccount":
ret= newAccount((NewAccountRequest) r);
break;
case "Transfer":
ret= transfer((TransferRequest) r);
break;
case "Withdraw":
ret= withdraw((WithdrawRequest) r);
break;
case "Halt":
halt();
ret= new HaltResponse("Halt");
break;
default:
throw new RemoteException("Unsupported Request");
}
synchronized(pq){
pq.poll();
pq.notifyAll();
}
return ret;
}
class HaltThread extends Thread{
HaltThread(){
}
public void run(){
try{
Thread.sleep(3000);
System.exit(1);
}catch(Exception e){
e.printStackTrace();
}
}
}
class BCastThread extends Thread{
int peer_id ;
Request r ;
int from_pid ;
long timestamp;
BCastThread(int peer_id,Request r ,int from_pid ){
this.peer_id = peer_id;
this.r = r;
this.from_pid = from_pid;
}
public void run(){
try{
timestamp = peers[peer_id].requestBCast(r,from_pid);
}catch(Exception e ){
e.printStackTrace();
}
}
long getTimestamp(){
return this.timestamp;
}
}
class BCastExecuteThread extends Thread{
int peer_id ;
Request r ;
int from_pid ;
BCastExecuteThread(int peer_id,Request r ,int from_pid ){
this.peer_id = peer_id;
this.r = r;
this.from_pid = from_pid;
}
public void run(){
try{
peers[peer_id].executeRequest(r,from_pid);
}catch(Exception e ){
e.printStackTrace();
}
}
}
public Response submitRequest(Request r) throws RemoteException{
BCastThread bct [] = new BCastThread[numPeers];
BCastExecuteThread bcet [] = new BCastExecuteThread[numPeers];
long ts = System.nanoTime();
synchronized(pq){
assignTimestamp(r);
r.id = server_id+1;
Ticket t = new Ticket(r.timestamp,server_id,r);
pq.add(t);
while(pq.size()!=0 && pq.peek().compareTo(t)!=0){
try{
pq.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
writeLog((server_id+1)+" CLNT-REQ "+calendar.getTime()+" "+ r);
int i =0 ;
/*
Start Multiple Threads to Broadcast the Request to All Replicated Systems
*/
for ( i =0 ;i < numPeers ; i++){
if(i== server_id) continue;
bct[i]= new BCastThread(i,r,server_id);
bct[i].start();
}
for ( i =0 ;i < numPeers ; i++){
if(i== server_id) continue;
try{
bct[i].join();
}catch(Exception e){
e.printStackTrace();
}
}
for ( i =0 ;i < numPeers ; i++){
if(i== server_id) continue;
setLamportClock(bct[i].getTimestamp());
}
//writeLog(id+" SERVER-ACK "+calendar.getTime()+" "+ r);
/*
After Getting the Response from all other process, send the request to all otehr process for
*/
for ( i =0 ;i < numPeers ; i++){
if(i== server_id) continue;
bcet[i]= new BCastExecuteThread(i,r,server_id);
bcet[i].start();
}
for ( i =0 ;i < numPeers ; i++){
if(i== server_id) continue;
try{
bcet[i].join();
}catch(Exception e){
e.printStackTrace();
}
}
/*
As the server facing client, prepare the response for client and measure the respone time data.
*/
Response ret = processRequest(r);
recordPerformance( System.nanoTime() - ts);
return ret;
}
public long requestBCast(Request r, int pid) throws RemoteException{
long tempClock = setLamportClock(r.timestamp);
writeLog((pid+1)+" SRV-REQ "+calendar.getTime()+" "+ r);
Ticket t = new Ticket(r.timestamp, pid , r);
/*
If there is currently no request in the local queue, simply ack
Otherwise, wait on the peek of the queue until you have a smaller timestamp, then return the lamportclock value
*/
synchronized(pq){
while(pq.size()!=0 && pq.peek().compareTo(t)<0){
try{
pq.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
//writeLog(pid+" ACK-ING "+calendar.getTime()+" "+r);
return tempClock;
}
class InitialThread extends Thread{
public void run(){
try{
NewAccountResponse resp =(NewAccountResponse) submitRequest(new NewAccountRequest("p","a","b"));
submitRequest(new DepositRequest(resp.accountId,1000));;
}catch(Exception e){
e.printStackTrace();
}
}
}
public void initialization(){
System.out.println("Start of Initialization");
InitialThread its[] = new InitialThread[1000];
int i;
for(i=0;i<10;i++){
its[i] = new InitialThread();
its[i].start();
}
for(i=0;i<10;i++){
try{
its[i].join();
}catch(Exception e){
e.printStackTrace();
}
}
System.out.println("End of Initialization");
}
public static void main (String args[]) throws Exception {
accountManager = new AccountManager();
server = new RMIServerImpl ();
System.out.println("Before Binding");
if(args.length != 2 ){
throw new Exception("Usage : <config file name> <server id>");
}else{
readFileByLine(args[0]);
server.server_id = Integer.parseInt(args[1])-1;
Registry localRegistry = LocateRegistry.getRegistry(Integer.parseInt((peerInfo[server.server_id].split(":"))[1]));
localRegistry.bind ("RMIServer", server);
localRegistry.bind ("RMIBroadcastServer", server);
server.buildPeerConnections();
if(server.server_id==0){
server.initialization();
}
System.out.println("Server "+(server_id+1)+" waiting for request");
}
}
}