-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDServer.java
More file actions
750 lines (488 loc) · 17.8 KB
/
DServer.java
File metadata and controls
750 lines (488 loc) · 17.8 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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
import spread.*;
import java.net.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.io.*;
public class DServer extends ServerProcess implements BasicMessageListener {
private final String groupName = "SERVER_GROUP";
// The Processes List from each process
public List<ServerProcess> processesList;
// The Slaves List from each process
public List<String> slavesList;
// The queue of operations that will be execute
public Queue<String> opsQueue;
// The list containing files which are stored and in which slave
// ex.: "file02.a#SLAVE_3" - file02.a is stored on SLAVE_3
List<String> storedFilesList;
// Atribute that says if this process is the master process from spreadGroup
private boolean isMaster;
// The Spread Connection.
private SpreadConnection connection;
// A spreadGroup.
private SpreadGroup spreadGroup;
private int currentSlave;
// Print this membership data. Does so in a generic way so identical
// function is used in recThread and User.
private void handleMembershipInfo(MembershipInfo info)
{
//SpreadGroup spreadGroup = info.getGroup();
//int auxint;
if(info.isRegularMembership()) {
//SpreadGroup members[] = info.getMembers();
//MembershipInfo.VirtualSynchronySet virtual_synchrony_sets[] = info.getVirtualSynchronySets();
//MembershipInfo.VirtualSynchronySet my_virtual_synchrony_set = info.getMyVirtualSynchronySet();
System.out.print("\tDevido a ");
if(info.isCausedByJoin()) {
System.out.println("entrada de " + info.getJoined());
} else if(info.isCausedByLeave()) {
System.out.println("saida de " + info.getLeft());
// Tratar mensagem de um processo que foi cancelado
} else if(info.isCausedByDisconnect()) {
// monta a mensagem pela desconexao
System.out.println("desconexao de " + info.getDisconnected());
String dado = info.getDisconnected() + "";
String[] s = dado.split("#");
int IDx = Integer.parseInt(s[1].substring(7));
System.out.println("Remover o processo: " + IDx);
ServerProcess p = new ServerProcess(IDx, 0);
removeProcess(p);
election();
// Imprime a lista de processos
System.out.print("\nLista de processos atual: \n\t");
printProcessesList();
}
}
}
private void resolveMessage(SpreadMessage msg)
{
try
{
if(msg.isRegular())
{
String sender = msg.getSender().toString();
String a[] = sender.split("#");
sender = a[1];
System.out.print("\nRecebida uma mensagem [REGULAR] ");
System.out.println(" enviada por " + sender + ".");
//SpreadGroup groups[] = msg.getGroups();
//System.out.println("para " + groups.length + " grupos.");
byte data[] = msg.getData();
String dado = new String(data);
String newInfo = dado;
//System.out.println("A informacao tem " + data.length + " bytes.");
System.out.println("A mensagem eh: " + dado);
String fileName;
char letra = dado.charAt(0);
//System.out.println("Letra = " + letra);
int ID = 0;
int PRIORITY = 0;
String[] s = dado.split("#");
if (letra == 'J' || letra == 'R') {
ID = Integer.parseInt(s[1]);
//System.out.println("ID = " + ID);
PRIORITY = Integer.parseInt(s[2]);
//System.out.println("PRIORITY = " + PRIORITY);
}
String slave = "";
int numReplicas = 1;
// Envia a mensagem de retorno para os outros processos preencherem seus vetores de prioridades
switch (letra){
case 'J':
// Monta a mensagem de resposta
String info = new String();
info = "R#" + id + "#" + Integer.toString(priority);
sendMessage(info, groupName);
break;
case 'R':
// Adiciona o processo que respondeu à lista de processos
ServerProcess process = new ServerProcess(ID, PRIORITY);
System.out.println("Adicionando o processo " + process + " na lista de processos.");
addProcess(process);
election();
// Imprime a lista de processos
System.out.print("\nLista de processos atual: \n\t");
printProcessesList();
/*for (ServerProcess p : this.processesList){
System.out.print(p + " ");
}
*/
//System.out.println("\nEu sou o master: " + this.isMaster);
break;
case 'S':
// Monta a lista de slaves
String novoSlave = s[1];
slavesList.add(novoSlave);
break;
case 'C':
// Processo Servidor Master trata a mensagem recebida do cliente
// e envia a mensagem para criar o arquivo no grupo de processos Slave
fileName = s[1];
numReplicas = Integer.parseInt(s[2]);
// Limita o número de réplicas ao número de Slaves (storages)
if (numReplicas > slavesList.size())
numReplicas = slavesList.size();
boolean arquivoExiste = false;
// Verifica se o arquivo já está na lista de arquivos criados
for (String f : storedFilesList) {
String fi[] = f.split("#");
if (fi[0].equals(fileName)){
// Arquivo solicitado para criação já foi criado anteriormente
String resp = "E#Arquivo já existe no Serviço de Arquivos#" + sender;
System.out.println(resp);
if (this.isMaster)
sendMessage(resp, "CLIENT_GROUP");
arquivoExiste = true;
break;
}
}
if (!arquivoExiste) {
//sendMessage("E#Arquivo não existe", "CLIENT_GROUP");
for (int i = 0; i < numReplicas; i++){
// Seleciona o Slave da vez que vai armazenar o arquivo - Balanceamento por rounding robin
String currentSlave = getNextSlave();
newInfo = dado + "#" + sender + "#" + currentSlave;
String operation = newInfo;
System.out.println("Slave da vez: " + currentSlave);
// Insere a operação no inÃcio da fila
opsQueue.offer(operation);
String currentOp;
currentOp = opsQueue.peek();
if (this.isMaster){
System.out.println("Enviando a solicitação para criar o arquivo: " + fileName + " no SLAVE_GROUP");
System.out.println("Enviando mensagem: <" + currentOp + ">");
sendMessage(currentOp, "SLAVE_GROUP");
//inicia o timer com 5 segundos
//aguardaResposta();
//if (timeout) {
// sendMessage("Serviço de Arquivos indisponÃvel", "CLIENT_GROUP");
opsQueue.poll();
}
}
if (this.isMaster)
sendMessage("K#Arquivo criado com sucesso", "CLIENT_GROUP");
} else
if (this.isMaster)
sendMessage("E#Arquivo já exite no Serviço de Arquivos", "CLIENT_GROUP");
break;
case 'K':
// Processo Servidor Master trata a mensagem recebida do SLAVE_GROUP
// e envia a mensagem para o cliente informando que o arquivo foi criado
// Insere o registro do arquivo na lista de arquivos armazenados
if (!s[1].equals("Arquivo deletado com sucesso.") && !s[1].equals("Arquivo editado com sucesso."))
storedFilesList.add(dado.substring(2));
System.out.println("\nLista de arquivos armazenados: ");
for (String f : storedFilesList)
System.out.println(f);
if (this.isMaster){
System.out.println("Enviando a resposta para o CLIENT_GROUP");
System.out.println("Enviando mensagem: <" + newInfo + ">");
//sendMessage(newInfo, "CLIENT_GROUP");
}
// Remove a operação do inÃcio da fila
opsQueue.poll();
break;
case 'L':
// Mensagem para ler o arquivo
fileName = s[1];
System.out.println("Lendo o arquivo " + fileName);
slave = "";
if (this.isMaster){
if (arquivoExiste(fileName)) {
String slaves = getSlaves(fileName);
slave = slaves.split("#")[1];
// Insere a operação no inÃcio da fila
opsQueue.offer(dado);
newInfo = dado + "#" + slave;
System.out.println("Enviando a msg " + newInfo);
sendMessage(newInfo, "SLAVE_GROUP");
} else {
sendMessage("E#Arquivo não existe", "CLIENT_GROUP");
}
}
break;
case 'l':
// Processo Servidor Master trata a mensagem recebida do SLAVE_GROUP
// e envia a mensagem para o cliente com a leitura do arquivo
if (this.isMaster){
System.out.println("Enviando a resposta para o CLIENT_GROUP");
System.out.println("Enviando mensagem: <" + newInfo + ">");
sendMessage(newInfo, "CLIENT_GROUP");
// Remove a operação do inÃcio da fila
opsQueue.remove();
}
break;
case 'D':
// Mensagem para deletar o arquivo
List<String> slavesComArquivosD = new ArrayList<>();
fileName = s[1];
System.out.println("Deletando o arquivo " + fileName);
List<String> storedFilesListAux = new ArrayList<String>(storedFilesList);
arquivoExiste = false;
// Verifica se o arquivo já está na lista de arquivos criados
for (String f : storedFilesListAux) {
String fi[] = f.split("#");
if (fi[0].equals(fileName)){
// Arquivo que se quer deletar foi encontrado na lista de arquivos armazenados
System.out.println("Arquivo " + fileName + " encontrado no slave " + fi[1]);
slavesComArquivosD.add(fi[1]);
arquivoExiste = true;
storedFilesList.remove(f);
System.out.println("Excluindo o arquivo " + fileName + " do slave " + fi[1]);
System.out.println();
}
}
if (arquivoExiste) {
for (String slaveID : slavesComArquivosD) {
// Insere a operação no inÃcio da fila
opsQueue.offer(dado);
if (this.isMaster){
newInfo = dado + "#" + slaveID;
System.out.println("Enviando a msg " + newInfo);
sendMessage(newInfo, "SLAVE_GROUP");
}
}
if (this.isMaster)
sendMessage("K#Arquivo deletado com sucessso.", "CLIENT_GROUP");
} else {
System.out.println("Arquivo não existe");
if (this.isMaster)
sendMessage("E#Arquivo não existe", "CLIENT_GROUP");
}
break;
case 'W':
// Mensagem para editar o arquivo
List<String> slavesComArquivosW = new ArrayList<>();
fileName = s[1];
System.out.println("Enviando msg para editar o arquivo " + fileName);
arquivoExiste = false;
// Verifica se o arquivo já está na lista de arquivos criados
for (String f : storedFilesList) {
String fi[] = f.split("#");
if (fi[0].equals(fileName)){
// Arquivo que se quer deletar foi encontrado na lista de arquivos armazenados
slavesComArquivosW.add(fi[1]);
arquivoExiste = true;
}
}
if (arquivoExiste) {
if (this.isMaster)
sendMessage("K#Arquivo editado com sucesso.", "CLIENT_GROUP");
for (String slaveID : slavesComArquivosW) {
// Insere a operação no inÃcio da fila
opsQueue.offer(dado);
if (this.isMaster){
newInfo = dado + "#" + slaveID;
System.out.println("Enviando a msg " + newInfo);
sendMessage(newInfo, "SLAVE_GROUP");
}
}
} else {
if (this.isMaster)
sendMessage("E#Arquivo não existe", "CLIENT_GROUP");
}
break;
default:
break;
}
}
else if (msg.isMembership())
{
System.out.println("\nRecebida uma mensagem [DE GRUPO]: ");
MembershipInfo info = msg.getMembershipInfo();
handleMembershipInfo(info);
}
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
private boolean arquivoExiste(String fName) {
// Verifica se o arquivo já está na lista de arquivos criados
for (String f : storedFilesList) {
String fi[] = f.split("#");
if (fi[0].equals(fName)) {
// Arquivo solicitado para criação já foi criado anteriormente
return true;
}
}
return false;
}
private String getSlaves(String fName) {
// Verifica se o arquivo já está na lista de arquivos criados
String listaDeSlaves = fName;
for (String f : storedFilesList) {
String fi[] = f.split("#");
if (fi[0].equals(fName)) {
listaDeSlaves += "#" + fi[1];
}
}
return listaDeSlaves;
}
private void sendMessage(String info, String groupName) {
SpreadMessage msg = new SpreadMessage();
msg.setSafe();
msg.addGroup(groupName);
msg.setData(info.getBytes());
// Envia a mensagem
try {
connection.multicast(msg);
} catch (SpreadException e) {
e.printStackTrace();
}
}
// Construtor
public DServer(String user, int priority, String address, int port)
{
super(Integer.parseInt(user.substring(7)), priority);
this.turnMaster(false);
this.processesList = new ArrayList<ServerProcess>();
this.opsQueue = new LinkedList<String>();
this.storedFilesList = new ArrayList<String>();
// Cria e inicializa a lista de processos servidores escravos (SLAVES)
this.slavesList = new ArrayList<>();
/*slavesList.add("SLAVE_1");
slavesList.add("SLAVE_2");
slavesList.add("SLAVE_3");
slavesList.add("SLAVE_4");*/
currentSlave = -1;
startSpreadConnection(user, address, port);
}
public String getNextSlave() {
currentSlave++;
if (currentSlave == slavesList.size())
currentSlave = 0;
return slavesList.get(currentSlave);
}
public void addProcess(ServerProcess process) {
boolean processIsInTheList = false;
for (ServerProcess p : this.processesList){
if (p.getId() == process.getId())
processIsInTheList = true;
}
if (!processIsInTheList){
System.out.println("O Processo " + process + " NAO esta na lista.");
this.processesList.add(process);
}
else System.out.println("O Processo " + process + " JA esta na lista.");
}
public void removeProcess(ServerProcess process) {
List<ServerProcess> list = this.processesList;
for (int i = 0; i < list.size(); i ++){
if (list.get(i).equals(process))
list.remove(i);
}
}
public void election() {
List<ServerProcess> list = this.processesList;
int lastIndex = list.size() - 1;
Collections.sort(list);
if (this.getId() == list.get(lastIndex).getId()){
this.turnMaster(true);
} else this.turnMaster(false);
}
public void printProcessesList() {
List<ServerProcess> list = this.processesList;
int lastIndex = list.size() - 1;
for (ServerProcess p : this.processesList)
System.out.print(p + " ");
// Imprime o processo master
System.out.println("\nMaster Process: " + list.get(lastIndex));
System.out.println("___________________________________________________________________________");
System.out.println();
}
public void turnMaster(boolean b) {
this.isMaster = b;
}
public ServerProcess getMaster() {
List<ServerProcess> list = this.processesList;
int lastIndex = list.size() - 1;
return list.get(lastIndex);
}
private void startSpreadConnection(String user, String address, int port) {
SpreadMessage msg;
SpreadMessage msgreceived = new SpreadMessage();
// Establish the spread connection.
///////////////////////////////////
try
{
connection = new SpreadConnection();
connection.connect(InetAddress.getByName(address), port, user, false, true);
// Join to the group specified by constant groupName
//this.groupName = "SERVER_GROUP";
this.spreadGroup = new SpreadGroup();
this.spreadGroup.join(connection, groupName);
System.out.println("Juntou-se ao " + spreadGroup + ".");
// Send message to spreadGroup with ID and priority
msg = new SpreadMessage();
msg.setSafe();
msg.addGroup(groupName);
// Monta a mensagem de join
String info = new String();
info = "J#" + user.substring(7) + "#" + Integer.toString(priority);
msg.setData(info.getBytes());
// Envia a mensagem
connection.multicast(msg);
//System.out.print("Enviada a mensagem: ");
//System.out.println(new String(msg.getData()));
}
catch(SpreadException e)
{
System.err.println("Houve um erro ao tentar conectar ao daemon.");
if (e.getMessage().equals("Connection attempt rejected=-6"))
System.err.println("Processo ja participa do grupo " + groupName);
//e.printStackTrace();
System.exit(1);
}
catch(UnknownHostException e)
{
System.err.println("O daemon nao foi encontrado. Tente executar o daemon spread na pasta java." + address);
System.exit(1);
}
// Server loop
while(true){
try{
// Receive a message.
/////////////////////
msgreceived = connection.receive();
messageReceived(msgreceived);
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
private void closeSpreadConnection() {
try {
connection.disconnect();
} catch (SpreadException e) {
e.printStackTrace();
}
}
public void messageReceived(SpreadMessage message)
{
resolveMessage(message);
}
public static final void main(String[] args)
{
// Default values.
//////////////////
String user;
String address = "127.0.0.1";
int port = 0;
int prio = 0;
user = "SERVER_" + args[0];
prio = Integer.parseInt(args[1]);
System.out.print("\nCriando o " + user + "\n");
System.out.print(", com prioridade ");
System.out.println(prio);
new DServer(user, prio, address, port);
}
}