-
Notifications
You must be signed in to change notification settings - Fork 33
/
ClusterImpl.java
2146 lines (1895 loc) · 77.7 KB
/
ClusterImpl.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
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
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000, 2017 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020, 2022 Contributors to the Eclipse Foundation
* Copyright (c) 2021 Payara Services Ltd.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0, which is available at
* http://www.eclipse.org/legal/epl-2.0.
*
* This Source Code may also be made available under the following Secondary
* Licenses when the conditions for such availability set forth in the
* Eclipse Public License v. 2.0 are satisfied: GNU General Public License,
* version 2 with the GNU Classpath Exception, which is available at
* https://www.gnu.org/software/classpath/license.html.
*
* SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0
*/
package com.sun.messaging.jmq.jmsserver.multibroker.fullyconnected;
import java.util.*;
import java.io.*;
import java.net.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import com.sun.messaging.jmq.io.GPacket;
import com.sun.messaging.jmq.io.Status;
import com.sun.messaging.jmq.jmsserver.core.BrokerAddress;
import com.sun.messaging.jmq.jmsserver.core.BrokerMQAddress;
import com.sun.messaging.jmq.jmsserver.multibroker.BrokerInfo;
import com.sun.messaging.jmq.jmsserver.multibroker.Cluster;
import com.sun.messaging.jmq.jmsserver.multibroker.ClusterCallback;
import com.sun.messaging.jmq.jmsserver.multibroker.Protocol;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.jmsserver.Broker;
import com.sun.messaging.jmq.jmsservice.BrokerEvent;
import com.sun.messaging.jmq.jmsserver.service.PortMapper;
import com.sun.messaging.jmq.jmsserver.resources.BrokerResources;
import com.sun.messaging.jmq.jmsserver.util.BrokerException;
import com.sun.messaging.jmq.jmsserver.util.LoopbackAddressException;
import com.sun.messaging.jmq.util.log.Logger;
import com.sun.messaging.jmq.util.UID;
import com.sun.messaging.jmq.util.io.FilteringObjectInputStream;
import com.sun.messaging.jmq.jmsserver.persist.api.LoadException;
import com.sun.messaging.jmq.jmsserver.persist.api.Store;
import com.sun.messaging.jmq.jmsserver.persist.api.ChangeRecordInfo;
import com.sun.messaging.jmq.jmsserver.multibroker.ClusterGlobals;
import com.sun.messaging.jmq.jmsserver.multibroker.ClusterBrokerInfoReply;
import com.sun.messaging.jmq.jmsserver.multibroker.raptor.ClusterFirstInfoInfo;
import com.sun.messaging.jmq.jmsserver.multibroker.raptor.ClusterTransferFileListInfo;
import com.sun.messaging.jmq.jmsserver.multibroker.raptor.ClusterTransferFileStartInfo;
import com.sun.messaging.jmq.jmsserver.multibroker.raptor.ClusterTransferFileEndInfo;
import com.sun.messaging.jmq.jmsserver.cluster.api.*;
import com.sun.messaging.jmq.jmsserver.cluster.api.ha.*;
import com.sun.messaging.jmq.io.MQAddress;
import com.sun.messaging.jmq.jmsserver.multibroker.raptor.ProtocolGlobals;
/**
* This class implements the default fully connected topology. Version 2.0 : Brokers are connected using single TCP
* connection.
*/
public class ClusterImpl implements Cluster, ClusterListener {
static boolean DEBUG = false;
ClusterCallback cb = null;
private Properties matchProps = null;
protected boolean useGPackets = false;
private BrokerAddressImpl self;
private Map connectList;
private HashMap brokerList;
private boolean readyForBroadcast = false;
private int flowControlState = Packet.RESUME_FLOW;
private String transport = null; // "tcp" or "ssl"
private InetAddress listenHost = null;
private int listenPort = 0;
private ClusterServiceListener listener = null;
private PingTimerTask pingTimer = null;
private int tcpInbufsz = Globals.getConfig().getIntProperty(Globals.IMQ + ".cluster.tcp.inbufsz", 2048);
private int sslInbufsz = Globals.getConfig().getIntProperty(Globals.IMQ + ".cluster.ssl.inbufsz",
Globals.getConfig().getIntProperty(Globals.IMQ + ".cluster.tls.inbufsz", 2048));
private int tcpOutbufsz = Globals.getConfig().getIntProperty(Globals.IMQ + ".cluster.tcp.outbufsz", 2048);
private int sslOutbufsz = Globals.getConfig().getIntProperty(Globals.IMQ + ".cluster.ssl.outbufsz",
Globals.getConfig().getIntProperty(Globals.IMQ + ".cluster.tls.outbufsz", 2048));
private boolean tcpNodelay = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".cluster.tcp.nodelay", true);
private boolean sslNodelay = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".cluster.ssl.nodelay",
Globals.getConfig().getBooleanProperty(Globals.IMQ + ".cluster.tls.nodelay", true));
private Object configServerLock = new Object();
private BrokerAddressImpl configServer = null;
private boolean configServerResolved = false;
public static final String SERVICE_NAME = "cluster";
public static final String SERVICE_TYPE = "CLUSTER";
private static final Logger logger = Globals.getLogger();
private static final BrokerResources br = Globals.getBrokerResources();
private TimerTask warningTask = null;
private static final int DEFAULT_SHUTDOWN_TIMEOUT = 30; // seconds
private static final String SHUTDOWN_TIMEOUT_PROP = "imq.cluster.shutdownTimeout";
private ClusterManager clsmgr = null;
protected Map<BrokerAddress, String> pendingFileTransfers = Collections.synchronizedMap(new LinkedHashMap<>());
private Map<String, ExecutorService> fileTransferExecutors = Collections.synchronizedMap(new LinkedHashMap<>());
protected boolean fileTransferShutdownIn = false;
private boolean fileTransferShutdownOut = false;
private final int FILE_TRANSFER_SOTIMEOUT_IN = 15000; // 15sec
private final int FILE_TRANSFER_SOTIMEOUT_OUT = 5 * 60 * 1000; // 5min
protected static final int FILE_TRANSFER_CHUNK_SIZE = 8192;
private int pingInterval = ClusterManager.CLUSTER_PING_INTERVAL_DEFAULT;
public ClusterImpl() throws BrokerException {
clsmgr = Globals.getClusterManager();
transport = clsmgr.getTransport();
assert (transport != null);
if (transport.equalsIgnoreCase("tls")) {
transport = "ssl";
}
boolean nocluster = (!Globals.getHAEnabled() && clsmgr.getConfigBrokerCount() == 0);
listenPort = clsmgr.getClusterPort();
String listenh = clsmgr.getClusterHost(); // can be null
try {
listenHost = BrokerMQAddress.resolveBindAddress(listenh, true);
} catch (LoopbackAddressException e) {
int level = nocluster ? Logger.WARNING : Logger.ERROR;
logger.log(level, br.E_CLUSTER_HOSTNAME, ClusterManager.HOST_PROPERTY);
if (nocluster) {
throw e;
}
Broker.getBroker().exit(1, br.getKString(br.E_CLUSTER_HOSTNAME, ClusterManager.HOST_PROPERTY), BrokerEvent.Type.FATAL_ERROR);
throw e;
} catch (Exception e) {
if (e instanceof BrokerException) {
logger.log(Logger.ERROR, br.getKString(br.E_BADADDRESS_CLUSTER_SERVICE, ClusterManager.HOST_PROPERTY, e.getMessage()));
} else {
logger.logStack(Logger.ERROR, br.getKString(br.E_BADADDRESS_CLUSTER_SERVICE, ClusterManager.HOST_PROPERTY, e.getMessage()), e);
}
Broker.getBroker().exit(1, br.getString(br.E_BADADDRESS_CLUSTER_SERVICE, ClusterManager.HOST_PROPERTY, e.getMessage()),
BrokerEvent.Type.FATAL_ERROR);
if (e instanceof BrokerException) {
throw (BrokerException) e;
}
BrokerException be = new BrokerException(e.getMessage());
be.initCause(e);
throw be;
}
try {
BrokerMQAddress.checkLoopbackAddress(Globals.getPortMapper().getBindAddress(), Globals.getPortMapper().getHostname());
} catch (LoopbackAddressException e) {
int level = nocluster ? Logger.WARNING : Logger.ERROR;
logger.log(level, br.E_BADADDRESS_PORTMAPPER_FOR_CLUSTER, PortMapper.HOSTNAME_PROPERTY, e.getMessage());
if (nocluster) {
throw e;
}
Broker.getBroker().exit(1, br.getString(br.E_BADADDRESS_PORTMAPPER_FOR_CLUSTER, PortMapper.HOSTNAME_PROPERTY, e.getMessage()),
BrokerEvent.Type.FATAL_ERROR);
throw e;
} catch (Exception e) {
if (e instanceof BrokerException) {
logger.log(logger.ERROR, br.E_BADADDRESS_PORTMAPPER_FOR_CLUSTER, PortMapper.HOSTNAME_PROPERTY, e.getMessage());
} else {
logger.logStack(logger.ERROR, br.E_BADADDRESS_PORTMAPPER_FOR_CLUSTER, PortMapper.HOSTNAME_PROPERTY, e.getMessage(), e);
}
Broker.getBroker().exit(1, br.getString(br.E_BADADDRESS_PORTMAPPER_FOR_CLUSTER, PortMapper.HOSTNAME_PROPERTY, e.getMessage()),
BrokerEvent.Type.FATAL_ERROR);
if (e instanceof BrokerException) {
throw (BrokerException) e;
}
BrokerException be = new BrokerException(e.getMessage());
be.initCause(e);
throw be;
}
try {
self = new BrokerAddressImpl();
} catch (LoopbackAddressException e) {
int level = nocluster ? Logger.WARNING : Logger.ERROR;
logger.log(level, br.getKString(br.E_BADADDRESS_THIS_BROKER, e.getMessage()));
if (nocluster) {
throw e;
}
Broker.getBroker().exit(1, br.getString(br.E_BADADDRESS_THIS_BROKER, e.getMessage()), BrokerEvent.Type.FATAL_ERROR);
throw e;
} catch (Exception e) {
if (e instanceof BrokerException) {
logger.log(Logger.ERROR, br.getKString(br.E_BADADDRESS_THIS_BROKER, e.getMessage()));
} else {
logger.logStack(Logger.ERROR, br.getKString(br.E_BADADDRESS_THIS_BROKER, e.getMessage()), e);
}
Broker.getBroker().exit(1, br.getString(br.E_BADADDRESS_THIS_BROKER, e.getMessage()), BrokerEvent.Type.FATAL_ERROR);
if (e instanceof BrokerException) {
throw (BrokerException) e;
}
BrokerException be = new BrokerException(e.getMessage());
be.initCause(e);
throw be;
}
readyForBroadcast = false;
ClusteredBroker masterb = clsmgr.getMasterBroker();
initConfigServer(masterb);
initBrokerList();
}
private void initConfigServer(ClusteredBroker masterb) throws BrokerException {
if (masterb == null) {
configServer = null;
configServerResolved = true;
return;
}
if (Globals.getHAEnabled()) { // sync log message /w clsmgr
String emsg = br.getKString(br.E_CLUSTER_HA_NOT_SUPPORT_MASTERBROKER);
logger.log(Logger.ERROR, emsg);
Broker.getBroker().exit(1, emsg, BrokerEvent.Type.FATAL_ERROR);
throw new BrokerException(emsg);
}
checkStoredLastConfigServer();
try {
configServer = new BrokerAddressImpl((BrokerMQAddress) masterb.getBrokerURL(), null, Globals.getHAEnabled(), masterb.getBrokerName());
} catch (Exception e) {
configServer = null;
configServerResolved = false;
throw new BrokerException(e.getMessage(), e);
}
BrokerMQAddress key = configServer.getMQAddress();
if (key.equals(self.getMQAddress())) {
configServer = self;
configServerResolved = true;
return;
}
configServerResolved = false;
}
/**
* Check to see if stored last config server property loaded properly
*
* System.exit if the last config server info is corrupted the last refresh timestamp info is corrupted and unable to
* reset potentially last config server info is corrupted: store LoadPropertyException occurred with key corruption and
* LastConfigServer property does not in store
*
* In future release, the System.exit behavior may be changed to allow administratively repair - eg. through imqbrokerd
* option to force set last config server info to the current master broker
*
*/
private void checkStoredLastConfigServer() throws BrokerException {
Store s = Globals.getStore();
boolean bad = false;
boolean potentiallyBad = false;
LoadException le = s.getLoadPropertyException();
LoadException savele = null;
while (le != null) {
Object o = le.getKey();
if (o == null || !(o instanceof String)) {
potentiallyBad = true;
savele = le;
le = le.getNextException();
continue;
}
if (((String) o).equals(ClusterGlobals.STORE_PROPERTY_LASTCONFIGSERVER)) {
logger.log(Logger.ERROR, BrokerResources.E_CLUSTER_LOAD_LASTCONFIGSERVER, le);
bad = true;
break;
}
if (((String) o).equals(ClusterGlobals.STORE_PROPERTY_LASTREFRESHTIME)) {
logger.log(Logger.WARNING, BrokerResources.W_CLUSTER_LOAD_LASTREFRESHTIME, le);
try {
s.updateProperty(ClusterGlobals.STORE_PROPERTY_LASTREFRESHTIME, Long.valueOf(-1), false);
} catch (BrokerException e) {
logger.log(Logger.ERROR, BrokerResources.E_CLUSTER_RESET_LASTREFRESHTIME, e);
bad = true;
break;
}
}
le = le.getNextException();
}
if (potentiallyBad && !bad) {
try {
if (s.getProperty(ClusterGlobals.STORE_PROPERTY_LASTCONFIGSERVER) == null) {
logger.log(Logger.ERROR, BrokerResources.E_CLUSTER_LOAD_LASTCONFIGSERVER, savele);
bad = true;
}
} catch (BrokerException e) {
logger.log(Logger.ERROR, e.getMessage(), e);
logger.log(Logger.ERROR, BrokerResources.E_CLUSTER_LOAD_LASTCONFIGSERVER, savele);
bad = true;
}
}
if (bad) {
logger.log(Logger.ERROR, BrokerResources.E_CLUSTER_LOAD_LASTCONFIGSERVER);
Broker.getBroker().exit(1, Globals.getBrokerResources().getKString(BrokerResources.E_CLUSTER_LOAD_LASTCONFIGSERVER), BrokerEvent.Type.FATAL_ERROR);
}
}
/**
* Processes the configuration and command line info.
*
* Creates 'connectList' : A mapping of Remote BrokerAddress <--> BrokerLink objects for all the 'autoConnect' links
* that are initiated by this broker.
*/
private void initBrokerList() throws BrokerException {
connectList = Collections.synchronizedMap(new HashMap());
BrokerMQAddress selfKey = self.getMQAddress();
if (DEBUG) {
logger.log(Logger.INFO, "ClusterImpl:initBrokerList. selfKey =" + selfKey);
}
ClusteredBroker cb = null;
BrokerAddressImpl b = null;
BrokerLink link = null;
Iterator itr = clsmgr.getConfigBrokers();
int i = 0;
while (itr.hasNext()) {
cb = (ClusteredBroker) itr.next();
try {
b = new BrokerAddressImpl((BrokerMQAddress) cb.getBrokerURL(), null, Globals.getHAEnabled(), cb.getBrokerName());
} catch (Exception e) {
throw new BrokerException(e.getMessage(), e);
}
BrokerMQAddress key = b.getMQAddress();
if (!key.equals(selfKey)) {
link = new BrokerLink(self, b, this);
link.setAutoConnect(true);
connectList.put(key, link);
i++;
if (DEBUG) {
logger.log(Logger.INFO, "ClusterImpl: Added to connectList: key=" + key + ", link=" + link + " (" + i + ")");
}
}
}
brokerList = new HashMap();
}
private BrokerLink searchBrokerList(BrokerMQAddress key) {
if (brokerList == null) {
return null;
}
synchronized (brokerList) {
Iterator itr = brokerList.keySet().iterator();
while (itr.hasNext()) {
BrokerAddressImpl b = (BrokerAddressImpl) itr.next();
if (key.equals(b.getMQAddress())) {
return (BrokerLink) brokerList.get(b);
}
}
return null;
}
}
protected String getTransport() {
return transport;
}
protected boolean getTCPNodelay() {
return tcpNodelay;
}
protected boolean getSSLNodelay() {
return sslNodelay;
}
protected int getTCPInputBufferSize() {
return tcpInbufsz;
}
protected int getTCPOutputBufferSize() {
return tcpOutbufsz;
}
protected int getSSLInputBufferSize() {
return sslInbufsz;
}
protected int getSSLOutputBufferSize() {
return sslOutbufsz;
}
/*
* private void setListenHost(String host) throws Exception { if (DEBUG) { logger.log(Logger.DEBUG,
* "ClusterImpl: Changing the listening hostname to {0}", host); }
*
* if (supportClusters == false) return;
*
* InetAddress saveListenHost = listenHost; try { listenHost = BrokerMQAddress.resolveBindAddress(host, true);
* ClusterServiceListener newListener = new ClusterServiceListener(this);
*
* // Success! Replace the global listener. if (listener != null) listener.shutdown(); listener = newListener; } catch
* (Exception e) { listenHost = saveListenHost; throw e; } }
*/
protected InetAddress getListenHost() {
return listenHost;
}
private void setListenPort(int port) throws IOException {
String args[] = { SERVICE_NAME, String.valueOf(port), String.valueOf(1), String.valueOf(1) };
logger.log(Logger.INFO, BrokerResources.I_UPDATE_SERVICE_REQ, args);
int saveListenPort = listenPort;
try {
listenPort = port;
ClusterServiceListener newListener = new ClusterServiceListener(this);
// Success! Replace the global listener.
if (listener != null) {
listener.shutdown();
}
listener = newListener;
} catch (IOException e) {
listenPort = saveListenPort;
throw e;
}
}
protected int getListenPort() {
return listenPort;
}
protected boolean isConfigServerResolved() {
return configServerResolved;
}
protected boolean waitForConfigSync() {
if (cb == null) {
return true;
}
return ((Protocol) cb).waitForConfigSync();
}
protected boolean checkConfigServer(BrokerAddressImpl b) {
synchronized (configServerLock) {
if (configServerResolved) {
return true; // Alredy resolved...
}
if (configServer == null) {
return false; // Illegal config, reject cluster connections.
}
BrokerMQAddress key = b.getMQAddress();
if (key.equals(configServer.getMQAddress())) {
configServer = b;
configServerResolved = true;
if (warningTask != null) {
warningTask.cancel();
warningTask = null;
}
}
return configServerResolved;
}
}
protected boolean addBroker(BrokerAddressImpl b, BrokerLink link) {
if (DEBUG) {
logger.log(Logger.DEBUGMED, "ClusterImpl: Activating link = {0}", link);
}
synchronized (brokerList) {
BrokerLink rlink = (BrokerLink) brokerList.get(b);
if (rlink != null) {
BrokerAddressImpl remoteb = rlink.getRemote();
if (!remoteb.getMQAddress().equals(b.getMQAddress())) {
String args[] = { b.toShortString(), link.toString(), rlink.toString() };
logger.log(Logger.ERROR, br.getKString(br.E_MBUS_SAME_ADDRESS_PEERS, args));
Broker.getBroker().exit(1, br.getString(br.E_MBUS_SAME_ADDRESS_PEERS, args), BrokerEvent.Type.FATAL_ERROR, null, false, true, false);
}
return false;
}
brokerList.put(b, link);
return true;
}
}
/**
* @param broken link IOException after handshake
*/
protected void removeBroker(BrokerAddressImpl remote, BrokerLink link, boolean broken) {
synchronized (brokerList) {
BrokerLink reallink = (BrokerLink) brokerList.get(remote);
if (reallink != null && reallink != link) {
return;
}
if (brokerList.remove(remote) == null) {
return;
}
brokerList.notifyAll();
}
cb.removeBrokerInfo(remote, broken);
if (DEBUG) {
logger.log(Logger.DEBUGMED, "ClusterImpl: Removed link with = {0}", remote);
}
}
protected void handleBrokerLinkShutdown(BrokerAddressImpl remote) {
connectList.remove(remote.getMQAddress());
}
@Override
public void receivedFileTransferRequest(BrokerAddress from, String uuid) {
pendingFileTransfers.put(from, uuid + ":" + System.currentTimeMillis());
}
/**
* Accept a connection from another broker.
*
* This method is invoked by the common 'ClusterServiceListener' object. The first packet must be of type
* 'Packet.LINK_INIT' - so that the identity of the remote broker can be determined.
*/
protected void acceptConnection(Socket conn, boolean ssl) throws IOException {
boolean elog = false;
BrokerAddressImpl remote = null;
try {
Object o = BrokerLink.consumeLinkInit(conn, null, this, true);
if (o instanceof BrokerAddressImpl) {
remote = (BrokerAddressImpl) o;
} else if (o == null) {
return;
} else {
elog = true;
LinkInfo li = (LinkInfo) o;
remote = li.getAddress();
if (li.isFileTransferRequest()) {
logger.log(logger.INFO, br.getKString(br.I_RECEIVED_FILE_TX_REQUEST, remote + "[" + conn.getInetAddress() + "]"));
ExecutorService es = null;
synchronized (fileTransferExecutors) {
if (fileTransferShutdownIn) {
String emsg = br.getKString(br.W_CLUSTER_SERVICE_SHUTDOWN);
logger.log(logger.WARNING, emsg);
throw new BrokerException(emsg);
}
String key = remote.getMQAddress().getHostAddressNPort() + ":" + li.getAddress().getBrokerID();
es = fileTransferExecutors.get(key);
if (es != null) {
es.shutdownNow();
fileTransferExecutors.remove(key);
}
es = Executors.newSingleThreadExecutor();
fileTransferExecutors.put(key, es);
}
FileTransferRunnable runner = new FileTransferRunnable(conn, FILE_TRANSFER_SOTIMEOUT_IN, remote, es, this);
es.execute(runner);
return;
} else {
logger.log(Logger.ERROR, br.getKString(br.E_CLUSTER_UNEXPECTED_PACKET_FROM, "LINK_INIT[" + remote.getClusterVersion() + "]",
remote + "[" + conn.getInetAddress() + "]"));
conn.close();
return;
}
}
} catch (Exception e) {
if (elog) {
if (e instanceof BrokerException) {
logger.log(logger.WARNING, e.getMessage(), e);
} else {
logger.logStack(logger.WARNING, e.getMessage(), e);
}
} else if (DEBUG) {
logger.logStack(logger.WARNING, e.getMessage(), e);
}
conn.close();
return;
}
// If remote is in connectList, either
// Drop this connection.
// (i.e. This broker initiates the connections)
// or
// Kill the brokerLink in connectList.
// (i.e. Let remote initiate the connections ...)
//
// This can happen if the brokers are started like this -
// broker -name A -cluster B ...
// broker -name B -cluster A ...
//
BrokerMQAddress key = remote.getMQAddress();
BrokerLink oldlink = null;
synchronized (connectList) {
oldlink = (BrokerLink) connectList.get(key);
if (oldlink != null) {
if (connectionInitiator(remote)) {
connectList.remove(key);
oldlink.shutdown();
oldlink = null;
}
}
}
if (oldlink != null) {
/**
* We already have a BrokerLink thread that's trying to initiate the connection with the remote broker. So just pass on
* this connection to that thread..
*/
oldlink.acceptConnection(remote, conn, ssl);
return;
}
// Create the BrokerLink object
BrokerLink link = new BrokerLink(self, remote, this);
link.setAutoConnect(false);
if (link.acceptConnection(remote, conn, ssl)) {
link.start();
}
}
/**
* Construct a packet of type 'Packet.LINK_INIT' for this broker.
*
* Packet.LINK_INIT is always the first packet sent on any new broker-to-broker connection.
*/
protected Packet getLinkInitPkt() {
return getLinkInitPkt((Integer) null);
}
private Packet getLinkInitPkt(Integer service) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
if (service == null) {
dos.writeInt(self.getClusterVersion());
} else {
dos.writeInt(service.intValue());
}
dos.writeUTF(self.getHostName());
dos.writeUTF(self.getInstanceName());
dos.writeInt(self.getPort());
BrokerAddressImpl cs = (BrokerAddressImpl) getConfiguredConfigServer();
dos.writeBoolean(cs != null);
if (cs != null) {
dos.writeUTF(cs.getHostName());
dos.writeUTF(cs.getInstanceName());
dos.writeInt(cs.getPort());
}
dos.writeInt(matchProps.size());
for (Enumeration e = matchProps.propertyNames(); e.hasMoreElements();) {
String prop = (String) e.nextElement();
dos.writeUTF(prop);
dos.writeUTF(matchProps.getProperty(prop));
}
dos.writeBoolean(Globals.getHAEnabled());
dos.writeBoolean(self.getBrokerID() != null);
if (self.getBrokerID() != null) {
dos.writeUTF(self.getBrokerID());
}
dos.writeLong(self.getBrokerSessionUID().longValue());
if (Globals.getHAEnabled()) {
dos.writeLong(self.getStoreSessionUID().longValue());
} else {
UID uid = self.getStoreSessionUID();
dos.writeBoolean((uid != null));
if (uid != null) {
dos.writeLong(uid.longValue());
}
}
dos.flush();
bos.flush();
} catch (Exception e) {
/* Ignore */ }
byte[] buf = bos.toByteArray();
Packet p = new Packet();
p.setPacketType(Packet.LINK_INIT);
p.setPacketBody(buf);
p.setDestId(0);
return p;
}
/**
* Process the Packet.LINK_INIT packet.
*/
protected static LinkInfo processLinkInit(Packet p) throws Exception {
String hostName = null;
String instName = null;
String brokerID = null;
UID brokerSessionUID = null;
UID storeSessionUID = null;
boolean ha = false;
int port = 0;
BrokerAddressImpl remote = null;
ByteArrayInputStream bis = new ByteArrayInputStream(p.getPacketBody());
DataInputStream dis = new DataInputStream(bis);
int clusterVersion = dis.readInt();
hostName = dis.readUTF();
instName = dis.readUTF();
port = dis.readInt();
BrokerAddressImpl configServer = null;
boolean hasConfigServer = false;
String cfgHostName = null;
String cfgInstName = null;
int cfgPort = 0;
hasConfigServer = dis.readBoolean();
if (hasConfigServer) {
cfgHostName = dis.readUTF();
cfgInstName = dis.readUTF();
cfgPort = dis.readInt();
}
Properties props = new Properties();
int nprops = dis.readInt();
for (int i = 0; i < nprops; i++) {
String prop = dis.readUTF();
String value = dis.readUTF();
props.setProperty(prop, value);
}
if (clusterVersion >= ProtocolGlobals.VERSION_400) {
ha = dis.readBoolean();
if (dis.readBoolean()) {
brokerID = dis.readUTF();
}
brokerSessionUID = new UID(dis.readLong());
if (ha) {
storeSessionUID = new UID(dis.readLong());
} else {
try {
if (dis.readBoolean()) {
storeSessionUID = new UID(dis.readLong());
}
} catch (Exception e) {
}
}
}
if (hasConfigServer) {
if (ha) {
throw new BrokerException(br.getKString(br.E_CLUSTER_HA_NOT_SUPPORT_MASTERBROKER));
}
configServer = new BrokerAddressImpl(cfgHostName, cfgInstName, cfgPort, ha, null, null, null);
}
remote = new BrokerAddressImpl(hostName, instName, port, ha, brokerID, brokerSessionUID, storeSessionUID);
remote.setClusterVersion(clusterVersion);
LinkInfo li = new LinkInfo(remote, configServer, props);
if (clusterVersion < 0) {
int type = clusterVersion;
li.setServiceRequestType(type);
}
return li;
}
/**
* Detects duplicate connections between a pair of brokers.
*
* @param remote BrokerAddress of the remote broker.
* @return <code> true </code> if this broker is supposed to initiate the connection, <code> false </code> if remote is
* supposed to initiate the connection.
*/
private boolean connectionInitiator(BrokerAddressImpl remote) {
if (self.getMQAddress().hashCode() > remote.getMQAddress().hashCode()) {
return true;
}
return false;
}
/**
* Construct the Packet.BROKER_INFO packet.
*/
protected Packet getBrokerInfoPkt() {
// Get the BrokerInfo object from MessageBus...
BrokerInfo selfInfo = cb.getBrokerInfo();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(selfInfo);
oos.flush();
oos.close();
} catch (Exception e) {
/* Ignore */ }
byte[] buf = bos.toByteArray();
Packet p = new Packet();
p.setPacketType(Packet.BROKER_INFO);
p.setPacketBody(buf);
p.setDestId(0);
return p;
}
protected ClusterBrokerInfoReply getBrokerInfoReply(BrokerInfo remote) throws Exception {
if (cb == null) {
throw new BrokerException(br.getKString(BrokerResources.X_CLUSTER_PROTOCOL_NOT_READY), Status.UNAVAILABLE);
}
return cb.getBrokerInfoReply(remote);
}
/**
* Receive and process the BROKER_INFO packet.
*/
private BrokerInfo receiveBrokerInfo(BrokerAddressImpl sender, byte[] pkt, String realRemote, BrokerLink l) {
ByteArrayInputStream bis = new ByteArrayInputStream(pkt);
BrokerInfo info = null;
try {
ObjectInputStream ois = new FilteringObjectInputStream(bis);
info = (BrokerInfo) ois.readObject();
info.setRealRemoteString(realRemote);
} catch (Exception e) {
logger.log(Logger.WARNING, br.W_MBUS_SERIALIZATION, sender);
if (l != null) {
l.shutdown();
}
return null;
}
Integer v = info.getClusterProtocolVersion();
if (v != null && v.intValue() >= ProtocolGlobals.VERSION_400) {
return info;
}
if (l != null) {
l.handshakeSent();
}
int status = cb.addBrokerInfo(info);
if (status == cb.ADD_BROKER_INFO_OK) {
return info;
}
if (status == cb.ADD_BROKER_INFO_RETRY) {
synchronized (brokerList) {
BrokerLink link = (BrokerLink) brokerList.get(sender);
if (link != null) {
link.closeConn();
}
}
} else if (status == cb.ADD_BROKER_INFO_BAN) {
synchronized (brokerList) {
BrokerLink link = (BrokerLink) brokerList.get(sender);
if (link != null) {
link.shutdown();
}
}
}
return null;
}
private void receiveBrokerInfoReply(BrokerAddressImpl sender, GPacket gp, String realRemote) {
BrokerInfo info = null;
try {
ClusterBrokerInfoReply cbi = ClusterBrokerInfoReply.newInstance(gp);
info = cbi.getBrokerInfo();
info.setRealRemoteString(realRemote);
if (DEBUG) {
logger.log(Logger.DEBUG, "Received BROKER_INFO_REPLY from " + sender);
}
if (!info.getBrokerAddr().equals(sender)) {
logger.log(Logger.ERROR, BrokerResources.E_INTERNAL_BROKER_ERROR, "mismatched BROKER_INFO (" + info.getBrokerAddr() + ") from " + sender);
throw new BrokerException("mismatched BROKER_INFO");
}
if (Globals.getHAEnabled() && cbi.isTakingover()) {
String msg = br.getKString(BrokerResources.E_CLUSTER_TAKINGOVER_NOTIFY_RESTART, sender);
BrokerException ex = new BrokerException(msg);
logger.log(logger.ERROR, msg);
Broker.getBroker().exit(Globals.getBrokerStateHandler().getRestartCode(), msg, BrokerEvent.Type.RESTART, null, true, true, true);
throw ex;
}
} catch (Exception e) {
logger.logStack(Logger.ERROR, e.getMessage(), e);
synchronized (brokerList) {
BrokerLink link = (BrokerLink) brokerList.get(sender);
if (link != null) {
link.shutdown();
}
}
return;
}
int status = cb.addBrokerInfo(info);
if (status == cb.ADD_BROKER_INFO_OK) {
return;
}
if (status == cb.ADD_BROKER_INFO_RETRY) {
synchronized (brokerList) {
BrokerLink link = (BrokerLink) brokerList.get(sender);
if (link != null) {
link.closeConn();
}
}
} else if (status == cb.ADD_BROKER_INFO_BAN) {
synchronized (brokerList) {
BrokerLink link = (BrokerLink) brokerList.get(sender);
if (link != null) {
link.shutdown();
}
}
}
}
protected GPacket getFirstInfoPacket() {
if (!Globals.useSharedConfigRecord()) {
return null;
}
ChangeRecordInfo cri = cb.getLastStoredChangeRecord();
if (cri == null) {
return null;
}
ClusterFirstInfoInfo cii = ClusterFirstInfoInfo.newInstance();
cii.setLastStoredChangeRecord(cri);
cii.setBroadcast(false);
return cii.getGPacket();
}
protected void processFirstInfoPacket(GPacket gp, BrokerLink link) {
try {
if (!Globals.useSharedConfigRecord()) {// should never happen
throw new BrokerException("Unexpected " + ProtocolGlobals.getPacketTypeDisplayString(gp.getType()) + " packet from " + link.getRemote());
}
ClusterFirstInfoInfo cii = ClusterFirstInfoInfo.newInstance(gp);
ChangeRecordInfo cri = cii.getLastStoredChangeRecord();
if (cri == null) {
return;
}
logger.log(logger.INFO, br.getKString(br.I_CLUSTER_RECEIVED_FIRST_INFO,
ProtocolGlobals.getPacketTypeDisplayString(gp.getType()) + "[(sharecc)" + cri.toString() + "]", link.getRemote()));
cb.syncChangeRecordOnJoin(link.getRemote(), cri);
} catch (Exception e) {
logger.logStack(logger.ERROR, e.getMessage(), e);
if (e instanceof BrokerException) {
if (((BrokerException) e).getStatusCode() == Status.PRECONDITION_FAILED) {
link.shutdown();
return;
}
}
link.closeConn();
}
}
private void setFlowControl(BrokerAddressImpl addr, boolean enabled) {
BrokerLink link = null;
synchronized (brokerList) {
link = (BrokerLink) brokerList.get(addr);
}
if (link != null) {
link.setFlowControl(enabled);