-
Notifications
You must be signed in to change notification settings - Fork 33
/
Destination.java
4460 lines (3866 loc) · 164 KB
/
Destination.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, 2020 Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2020 Payara Services Ltd.
* Copyright (c) 2021, 2022 Contributors to the Eclipse Foundation
*
* 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.core;
import com.sun.messaging.jmq.jmsserver.DMQ;
import com.sun.messaging.jmq.util.DestType;
import com.sun.messaging.jmq.util.selector.*;
import com.sun.messaging.jmq.util.DestState;
import com.sun.messaging.jmq.util.DestMetricsCounters;
import com.sun.messaging.jmq.util.DestLimitBehavior;
import com.sun.messaging.jmq.util.ClusterDeliveryPolicy;
import com.sun.messaging.jmq.util.DestScope;
import com.sun.messaging.jmq.util.timer.*;
import com.sun.messaging.jmq.io.Packet;
import com.sun.messaging.jmq.io.SysMessageID;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.jmsserver.FaultInjection;
import com.sun.messaging.jmq.jmsserver.plugin.spi.ProducerSpi;
import com.sun.messaging.jmq.jmsserver.plugin.spi.DestinationSpi;
import com.sun.messaging.jmq.jmsserver.BrokerStateHandler;
import com.sun.messaging.jmq.jmsserver.service.ConnectionUID;
import com.sun.messaging.jmq.jmsserver.service.Connection;
import com.sun.messaging.jmq.jmsserver.service.imq.IMQConnection;
import com.sun.messaging.jmq.jmsserver.util.BrokerException;
import com.sun.messaging.jmq.jmsserver.util.ConsumerAlreadyAddedException;
import com.sun.messaging.jmq.jmsserver.util.lists.AddReason;
import com.sun.messaging.jmq.jmsserver.util.lists.RemoveReason;
import com.sun.messaging.jmq.jmsserver.util.DestinationNotFoundException;
import com.sun.messaging.jmq.jmsserver.data.TransactionUID;
import com.sun.messaging.jmq.jmsserver.data.handlers.RefCompare;
import com.sun.messaging.jmq.jmsserver.data.TransactionList;
import com.sun.messaging.jmq.jmsserver.data.TransactionState;
import com.sun.messaging.jmq.jmsserver.persist.api.Store;
import com.sun.messaging.jmq.jmsserver.persist.api.DiskFileStore;
import com.sun.messaging.jmq.jmsserver.persist.api.PartitionedStore;
import com.sun.messaging.jmq.jmsserver.persist.api.ChangeRecordInfo;
import com.sun.messaging.jmq.jmsserver.cluster.api.ClusterBroadcast;
import com.sun.messaging.jmq.jmsserver.cluster.api.ha.HAMonitorService;
import com.sun.messaging.jmq.util.log.Logger;
import com.sun.messaging.jmq.util.SizeString;
import com.sun.messaging.jmq.util.admin.DestinationInfo;
import com.sun.messaging.jmq.io.Status;
import com.sun.messaging.jmq.jmsserver.resources.BrokerResources;
import com.sun.messaging.jmq.jmsserver.memory.MemoryManager;
import com.sun.messaging.jmq.jmsserver.management.agent.Agent;
import com.sun.messaging.jmq.util.lists.*;
import java.util.*;
import java.io.*;
/**
* This class represents a destination (topic or queue name)
*/
public abstract class Destination implements DestinationSpi, Serializable, com.sun.messaging.jmq.util.lists.EventListener {
static final long serialVersionUID = 4399175316523022128L;
protected static boolean DEBUG = false;
protected static final boolean DEBUG_CLUSTER = DestinationList.DEBUG_CLUSTER;
private static final FaultInjection FI = FaultInjection.getInjection();
protected String INITIALIZEBY = "";
transient protected boolean destvalid = true;
transient protected boolean startedDestroy = false;
protected transient Logger logger = Globals.getLogger();
protected transient BrokerResources br = Globals.getBrokerResources();
protected transient BrokerMonitor bm = null;
protected transient boolean stored = false;
protected transient boolean neverStore = false;
protected transient SimpleNFLHashMap<SysMessageID, PacketReference> destMessages = null;
private transient HashMap destMessagesInRemoving = null;
private transient Object _removeMessageLock = null;
private boolean dest_inited = false;
private transient int refCount = 0;
/**
* metrics counters
*/
protected int expiredCnt = 0;
protected int purgedCnt = 0;
protected int ackedCnt = 0;
protected int discardedCnt = 0;
protected int overflowCnt = 0;
protected int errorCnt = 0;
protected int rollbackCnt = 0;
transient Object sizeLock = new Object();
/**
* size of a destination when it is unloaded
*/
transient int size = 0;
transient int remoteSize = 0;
/**
* bytes of a destination when it is unloaded
*/
transient long bytes = 0;
transient long remoteBytes = 0;
transient boolean loaded = false;
protected transient SimpleNFLHashMap consumers = new SimpleNFLHashMap();
protected transient SimpleNFLHashMap producers = new SimpleNFLHashMap();
transient DestReaperTask destReaper = null;
protected DestinationUID uid = null;
protected int type = -1;
protected transient int state = DestState.UNKNOWN;
protected int scope = DestScope.CLUSTER;
protected int limit = DestLimitBehavior.REJECT_NEWEST;
protected ConnectionUID id = null; // only for temp destinations
protected SizeString msgSizeLimit = null;
protected int countLimit = 0;
protected SizeString memoryLimit = null;
protected int maxConsumerLimit = DestinationList.UNLIMITED;
protected int maxProducerLimit = DestinationList.DEFAULT_MAX_PRODUCERS;
protected int maxPrefetch = DestinationList.DEFAULT_PREFETCH;
protected transient int producerMsgBatchSize = DestinationList.MAX_PRODUCER_BATCH;
protected transient long producerMsgBatchBytes = -1;
private long clientReconnectInterval = 0;
private transient ReconnectReaperTask reconnectReaper = null;
private transient ProducerFlow producerFlow = new ProducerFlow();
boolean useDMQ = true;
boolean isDMQ = false;
boolean validateXMLSchemaEnabled = false;
String XMLSchemaUriList = null;
boolean reloadXMLSchemaOnFailure = false;
private transient boolean clusterNotifyFlag = false;
private transient Map<Integer, ChangeRecordInfo> currentChangeRecordInfo = Collections.synchronizedMap(new HashMap<Integer, ChangeRecordInfo>());
private transient DestinationList DL = null;
protected transient PartitionedStore pstore = null;
private transient String logsuffix = "";
private transient Object queueRemoteLock = new Object();
private transient Object queueRemoteLockThread = null;
public static final int UNLIMITED = -1;
public static final String TEMP_CNT = "JMQ_SUN_JMSQ_TempRedeliverCnt";
public static final int DEFAULT_RECONNECT_MULTIPLIER = 5;
public static final int RECONNECT_MULTIPLIER = getRECONNECT_MULTIPLIER();
private static final int LOAD_COUNT = Globals.getConfig().getIntProperty(Globals.IMQ + ".destination.verbose.cnt", 10000);
private static final boolean EXPIRE_DELIVERED_MSG = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".destination.expireDeliveredMessages", false);
private static final boolean PURGE_DELIVERED_MSG = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".destination.purgeDeliveredMessages", false);
public static final boolean PERSIST_SYNC = DestinationList.PERSIST_SYNC;
protected static final int NONE = 0;
private static MQTimer timer = Globals.getTimer();
private static boolean getDEBUG() {
return (DEBUG || DestinationList.DEBUG);
}
private static int getRECONNECT_MULTIPLIER() {
int v = Globals.getConfig().getIntProperty(Globals.IMQ + ".reconnect.interval", DEFAULT_RECONNECT_MULTIPLIER);
if (v < 1) {
v = DEFAULT_RECONNECT_MULTIPLIER;
}
return v;
}
public ChangeRecordInfo getCurrentChangeRecordInfo(int type) {
return currentChangeRecordInfo.get(Integer.valueOf(type));
}
public void setCurrentChangeRecordInfo(int type, ChangeRecordInfo cri) {
currentChangeRecordInfo.put(Integer.valueOf(type), cri);
}
public PacketReference peekNext() {
return null;
}
public void setDestinationList(DestinationList dl) {
this.DL = dl;
this.pstore = dl.getPartitionedStore();
if (DL.isPartitionMode()) {
logsuffix = " [" + pstore + "]";
}
}
public PartitionedStore getPartitionedStore() {
return pstore;
}
public void setUseDMQ(boolean use) throws BrokerException {
if (use && isDMQ) {
throw new BrokerException(br.getKString(BrokerResources.X_DMQ_USE_DMQ_INVALID));
}
Boolean oldVal = Boolean.valueOf(this.useDMQ);
this.useDMQ = use;
notifyAttrUpdated(DestinationInfo.USE_DMQ, oldVal, Boolean.valueOf(this.useDMQ));
}
public boolean getUseDMQ() {
return useDMQ;
}
// used only as a space holder when deleting corrupted destinations
protected Destination(DestinationUID uid) {
this.uid = uid;
}
/**
* this method is called when a message has been completely acked and is dead
*/
public boolean removeDeadMessage(PacketReference ref) throws IOException, BrokerException {
return removeDeadMessage(ref, ref.getDeadComment(), ref.getDeadException(), ref.getDeadDeliverCnt(), ref.getDeadReason(), ref.getDeadBroker());
}
public boolean removeDeadMessage(PacketReference ref, String comment, Throwable exception, int deliverCnt, Reason r, String broker)
throws IOException, BrokerException {
if (getDEBUG()) {
logger.log(Logger.DEBUG, "Calling removeDeadMessage on " + ref + " [" + comment + "," + exception + "," + deliverCnt + "," + r + "]");
}
if (ref.isInvalid()) {
logger.log(Logger.DEBUG, "Internal Error: message is already dead");
return false;
}
Destination d = ref.getDestination();
if (d == DL.getDMQ()) {
throw new RuntimeException("Already dead");
}
Hashtable m = new Hashtable();
if (comment != null) {
m.put(DMQ.UNDELIVERED_COMMENT, comment);
}
if (deliverCnt != -1) {
m.put(TEMP_CNT, Integer.valueOf(deliverCnt));
}
if (exception != null) {
m.put(DMQ.UNDELIVERED_EXCEPTION, exception);
}
if (broker != null) {
m.put(DMQ.DEAD_BROKER, broker);
} else {
m.put(DMQ.DEAD_BROKER, Globals.getMyAddress().toString());
}
// remove the old message
if (r == null) {
r = RemoveReason.ERROR;
}
RemoveMessageReturnInfo ret = _removeMessage(ref.getSysMessageID(), r, m, null, !ref.isExpired());
return ret.removed;
}
public int seqCnt = 0;
/**
* place the message in the DMQ.
* <P>
* called from Destination and Consumer.
*/
private void markDead(PacketReference pr, Reason reason, Hashtable props) throws BrokerException {
Packet p = pr.getPacket();
if (p == null) {
logger.log(Logger.DEBUG, "Internal Error: null packet for DMQ");
return;
}
Hashtable packetProps = null;
try {
packetProps = p.getProperties();
if (packetProps == null) {
packetProps = new Hashtable();
}
} catch (Exception ex) {
logger.logStack(Logger.DEBUG, "could not get props ", ex);
packetProps = new Hashtable();
}
boolean useVerbose = false;
Object o = packetProps.get(DMQ.VERBOSE);
if (o != null) {
if (o instanceof Boolean) {
useVerbose = ((Boolean) o).booleanValue();
} else if (o instanceof String) {
useVerbose = Boolean.parseBoolean((String) o);
} else {
logger.log(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR, "Unknown type for verbose " + o.getClass());
useVerbose = DL.getVerbose();
}
} else {
useVerbose = DL.getVerbose();
}
if (isDMQ) {
if (getDEBUG() || useVerbose) {
logger.log(Logger.INFO, BrokerResources.I_DMQ_REMOVING_DMQ_MSG, pr.getSysMessageID(),
DestinationUID.getUID(p.getDestination(), p.getIsQueue()).toString());
}
return;
}
// OK deal with various flags
boolean useDMQforMsg = false;
o = packetProps.get(DMQ.PRESERVE_UNDELIVERED);
if (o != null) {
if (o instanceof Boolean) {
useDMQforMsg = ((Boolean) o).booleanValue();
} else if (o instanceof String) {
useDMQforMsg = Boolean.parseBoolean((String) o);
} else {
logger.log(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR, "Unknown type for preserve undelivered " + o.getClass());
useDMQforMsg = useDMQ;
}
} else {
useDMQforMsg = useDMQ;
}
long receivedTime = pr.getTime();
long senderTime = pr.getTimestamp();
long expiredTime = pr.getExpireTime();
if (!useDMQforMsg) {
if (getDEBUG() || useVerbose) {
String args[] = { pr.getSysMessageID().toString(), pr.getDestinationUID().toString(),
lookupReasonString(reason, receivedTime, expiredTime, senderTime) };
logger.log(Logger.INFO, BrokerResources.I_DMQ_REMOVING_MSG, args);
}
if (!pr.isLocal()) {
boolean waitack = !pr.isNoAckRemoteConsumers();
Globals.getClusterBroadcast().acknowledgeMessage(pr.getBrokerAddress(), pr.getSysMessageID(), pr.getQueueUID(), ClusterBroadcast.MSG_DEAD,
props, waitack);
}
return;
}
boolean truncateBody = false;
o = packetProps.get(DMQ.TRUNCATE_BODY);
if (o != null) {
if (o instanceof Boolean) {
truncateBody = ((Boolean) o).booleanValue();
} else if (o instanceof String) {
truncateBody = Boolean.parseBoolean((String) o);
} else {
logger.log(Logger.WARNING, BrokerResources.E_INTERNAL_BROKER_ERROR, "Unknown type for preserve undelivered " + o.getClass());
truncateBody = !DL.getStoreBodyInDMQ();
}
} else {
truncateBody = !DL.getStoreBodyInDMQ();
}
if (props == null) {
props = new Hashtable();
}
Integer cnt = (Integer) props.remove(TEMP_CNT);
if (cnt != null) {
// set as a header property
props.put(DMQ.DELIVERY_COUNT, cnt);
} else { // total deliver cnt ?
}
if (pr.isLocal()) {
props.putAll(packetProps);
} else {
// reason for the other side
props.put("REASON", Integer.valueOf(reason.intValue()));
}
if (props.get(DMQ.UNDELIVERED_COMMENT) == null) {
props.put(DMQ.UNDELIVERED_COMMENT, lookupReasonString(reason, receivedTime, expiredTime, senderTime));
}
props.put(DMQ.UNDELIVERED_TIMESTAMP, Long.valueOf(System.currentTimeMillis()));
props.put(DMQ.BODY_TRUNCATED, Boolean.valueOf(truncateBody));
if (reason == RemoveReason.EXPIRED || reason == RemoveReason.EXPIRED_BY_CLIENT || reason == RemoveReason.EXPIRED_ON_DELIVERY) {
props.put(DMQ.UNDELIVERED_REASON, DMQ.REASON_EXPIRED);
} else if (reason == RemoveReason.REMOVED_LOW_PRIORITY) {
props.put(DMQ.UNDELIVERED_REASON, DMQ.REASON_LOW_PRIORITY);
} else if (reason == RemoveReason.REMOVED_OLDEST) {
props.put(DMQ.UNDELIVERED_REASON, DMQ.REASON_OLDEST);
} else if (reason == RemoveReason.UNDELIVERABLE) {
props.put(DMQ.UNDELIVERED_REASON, DMQ.REASON_UNDELIVERABLE);
} else {
props.put(DMQ.UNDELIVERED_REASON, DMQ.REASON_ERROR);
}
if (pr.getBrokerAddress() != null) {
props.put(DMQ.BROKER, pr.getBrokerAddress().toString());
} else {
props.put(DMQ.BROKER, Globals.getMyAddress().toString());
}
String deadbkr = (String) packetProps.get(DMQ.DEAD_BROKER);
if (deadbkr != null) {
props.put(DMQ.DEAD_BROKER, deadbkr);
} else {
props.put(DMQ.DEAD_BROKER, Globals.getMyAddress().toString());
}
if (!pr.isLocal()) {
boolean waitack = !pr.isNoAckRemoteConsumers();
Globals.getClusterBroadcast().acknowledgeMessage(pr.getBrokerAddress(), pr.getSysMessageID(), pr.getQueueUID(), ClusterBroadcast.MSG_DEAD, props,
waitack);
return; // done
}
// OK ... now create the packet
Packet newp = new Packet();
// first make sure we have the room to put it on the
// queue ... if we dont, an exception will be thrown
// from queue Message
PacketReference ref = null;
try {
newp.generateSequenceNumber(false);
newp.generateTimestamp(false);
newp.fill(p);
newp.setProperties(props);
if (truncateBody) {
newp.setMessageBody(new byte[0]);
}
Queue dmq = DL.getDMQ();
ref = PacketReference.createReference(pstore, newp, dmq.getDestinationUID(), null);
ref.overrideExpireTime(0);
ref.clearExpireInfo();
ref.clearDeliveryTimeInfo();
ref.setTimestamp(System.currentTimeMillis());
synchronized (dmq) {
ref.setSequence(dmq.seqCnt++);
}
DL.routeMoveAndForwardMessage(pr, ref, dmq);
} catch (Exception ex) {
// depending on the type, we either ignore or throw out
if (reason == RemoveReason.UNDELIVERABLE || reason == RemoveReason.ERROR) {
if (ex instanceof BrokerException) {
throw (BrokerException) ex;
}
throw new BrokerException(br.getKString(BrokerResources.X_DMQ_MOVE_INVALID), ex);
}
if (getDEBUG() || useVerbose) {
logger.logStack(Logger.WARNING, BrokerResources.W_DMQ_ADD_FAILURE, pr.getSysMessageID().toString(), ex);
}
}
if ((getDEBUG() || useVerbose) && useDMQforMsg) {
String args[] = { pr.getSysMessageID().toString(), pr.getDestinationUID().toString(),
lookupReasonString(reason, receivedTime, expiredTime, senderTime) };
logger.log(Logger.INFO, BrokerResources.I_DMQ_MOVING_TO_DMQ, args);
}
ref.unload();
}
/**
* replaces the body of the message, adds the addProps (if not null) and returns a new SysMessageID
*
*/
protected PacketReference _replaceMessage(SysMessageID old, Hashtable addProps, byte[] data) throws BrokerException, IOException {
PacketReference ref = DL.get(old, true);
if (ref == null) {
throw new BrokerException(br.getKString(br.I_MESSAGE_NOT_FOUND, old, getDestinationUID()), Status.NOT_FOUND);
}
if (!ref.checkDeliveryAndSetInReplacing()) {
if (ref.isInvalid() || ref.isDestroyed() || ref.isExpired() || ref.isAcknowledged() || ref.inRemoval) {
throw new BrokerException(br.getKString(br.I_MESSAGE_REMOVED_OR_REMOVING, old, getDestinationUID()), Status.CONFLICT);
}
if (ref.inReplacing) {
throw new BrokerException(br.getKString(br.I_MESSAGE_BEING_REPLACED, old, getDestinationUID()), Status.CONFLICT);
}
throw new BrokerException(br.getKString(br.I_MESSAGE_IN_DELIVERY_TO_CONSUMER, old, getDestinationUID()), Status.CONFLICT);
}
try {
long oldbsize = ref.byteSize();
ArrayList subs = new ArrayList();
Consumer c = null;
Iterator itr = getConsumers();
while (itr.hasNext()) {
c = (Consumer) itr.next();
if (c instanceof Subscription) {
if (c.unrouteMessage(ref)) {
subs.add(c);
}
}
}
SysMessageID newid = ref.replacePacket(addProps, data);
destMessages.remove(old);
DL.removePacketList(old, ref.getDestinationUID(), ref);
PacketListDMPair dmp = DL.packetlistAdd(newid, ref.getDestinationUID(), ref);
destMessages.put(newid, ref);
dmp.nullRef();
DL.adjustTotalBytes(ref.byteSize() - oldbsize);
Subscription sub = null;
itr = subs.iterator();
while (itr.hasNext()) {
sub = (Subscription) itr.next();
sub.routeMessage(ref, false);
}
} finally {
ref.clearInReplacing();
}
return ref;
}
public SysMessageID replaceMessage(SysMessageID old, Hashtable addProps, byte[] data) throws BrokerException, IOException {
return _replaceMessage(old, addProps, data).getSysMessageID();
}
public String replaceMessageString(SysMessageID old, Hashtable addProps, byte[] data) throws BrokerException, IOException {
return _replaceMessage(old, addProps, data).getSysMessageIDString();
}
public abstract Set routeAndMoveMessage(PacketReference oldRef, PacketReference newRef) throws IOException, BrokerException;
public void setReconnectInterval(long val) {
clientReconnectInterval = val * RECONNECT_MULTIPLIER;
}
public void clientReconnect() {
synchronized (this) {
if (reconnectReaper != null) {
reconnectReaper.cancel();
reconnectReaper = null;
}
}
}
private void updateProducerBatch(boolean notifyProducers) {
int oldsize = producerMsgBatchSize;
long oldbytes = producerMsgBatchBytes;
notifyProducers = notifyProducers && limit == DestLimitBehavior.FLOW_CONTROL;
if (limit == DestLimitBehavior.FLOW_CONTROL) {
producerMsgBatchSize = DL.calcProducerBatchCnt(destMessages.capacity(), maxProducerLimit);
producerMsgBatchBytes = DL.calcProducerBatchBytes(destMessages.byteCapacity(), maxProducerLimit);
} else {
producerMsgBatchSize = DestinationList.MAX_PRODUCER_BATCH;
producerMsgBatchBytes = -1;
}
if (notifyProducers && (oldsize != producerMsgBatchSize || oldbytes != producerMsgBatchBytes)) {
producerFlow.updateAllProducers(DEST_UPDATE, "update batch");
}
}
class RemoveBehaviorListener implements com.sun.messaging.jmq.util.lists.EventListener {
Set orderedSet = null;
Reason r = null;
RemoveBehaviorListener(Set orderedSet, Reason r) {
this.orderedSet = orderedSet;
this.r = r;
}
@Override
public void eventOccured(EventType type, Reason reason, Object target, Object orig_value, Object cur_value, Object userdata) {
assert type == EventType.SET_CHANGED_REQUEST;
boolean full = destMessages.isFull();
if (full && cur_value != null) {
long tbytes = ((Sized) cur_value).byteSize();
while (true) {
Iterator itr = null;
synchronized (orderedSet) {
itr = new LinkedHashSet(orderedSet).iterator();
}
if (!itr.hasNext()) {
break;
}
Object n = itr.next();
if (n == null) {
continue;
}
try {
Destination.this.removeMessage(((PacketReference) n).getSysMessageID(), r);
} catch (Exception ex) {
logger.logStack(Logger.WARNING, ex.getMessage(), ex);
itr.remove();
continue;
}
if ((destMessages.capacity() == -1 || destMessages.freeSpace() > 0)
&& (destMessages.byteCapacity() == -1 || destMessages.freeBytes() > tbytes)) {
break;
}
}
}
}
}
class FlowListener implements com.sun.messaging.jmq.util.lists.EventListener {
@Override
public void eventOccured(EventType type, Reason reason, Object target, Object orig_value, Object cur_value, Object userdata) {
if (reason instanceof RemoveReason) {
return;
}
assert type == EventType.FULL;
if (reason != AddReason.LOADED) {
assert cur_value instanceof Boolean;
boolean shouldStop = destMessages.isFull();
if (shouldStop) {
logger.log(Logger.DEBUG, "Destination " + Destination.this + " is full, " + " all producers should be stopped");
// for misbehaving producers, we may want to
// force a stop
producerFlow.updateAllProducers(DEST_PAUSE, "Destination Full");
} else {
logger.log(Logger.DEBUG, "Destination " + Destination.this + " is not full, " + " some producers should be stopped");
producerFlow.checkResumeFlow(null, true);
}
}
}
}
transient Object behaviorListener = null;
protected boolean sendClusterUpdate() {
return !isInternal() && !isAdmin();
}
protected void handleLimitBehavior(int limit) {
if (limit == DestLimitBehavior.FLOW_CONTROL) {
destMessages.enforceLimits(false);
FlowListener rl = new FlowListener();
if (behaviorListener != null) {
destMessages.removeEventListener(behaviorListener);
behaviorListener = null;
}
behaviorListener = destMessages.addEventListener(rl, EventType.FULL, null);
producerFlow.updateAllProducers(DEST_BEHAVIOR_CHANGE, "behavior change");
} else if (limit == DestLimitBehavior.REMOVE_OLDEST) {
Set<PacketReference> s = destMessages.subSet(new OldestComparator());
RemoveBehaviorListener rl = new RemoveBehaviorListener(s, RemoveReason.REMOVED_OLDEST);
if (behaviorListener != null) {
destMessages.removeEventListener(behaviorListener);
behaviorListener = null;
}
behaviorListener = destMessages.addEventListener(rl, EventType.SET_CHANGED_REQUEST, null);
destMessages.enforceLimits(false);
} else if (limit == DestLimitBehavior.REJECT_NEWEST) {
destMessages.enforceLimits(true);
if (behaviorListener != null) {
destMessages.removeEventListener(behaviorListener);
behaviorListener = null;
}
} else if (limit == DestLimitBehavior.REMOVE_LOW_PRIORITY) {
destMessages.enforceLimits(false);
Set<PacketReference> s = destMessages.subSet(new LowPriorityComparator());
RemoveBehaviorListener rl = new RemoveBehaviorListener(s, RemoveReason.REMOVED_LOW_PRIORITY);
if (behaviorListener != null) {
destMessages.removeEventListener(behaviorListener);
behaviorListener = null;
}
behaviorListener = destMessages.addEventListener(rl, EventType.SET_CHANGED_REQUEST, null);
}
}
class DestReaperTask extends TimerTask {
DestinationUID uid = null;
private boolean canceled = false;
Logger logger = Globals.getLogger();
DestReaperTask(DestinationUID uid) {
this.uid = uid;
}
@Override
public synchronized boolean cancel() {
canceled = true;
return super.cancel();
}
@Override
public void run() {
synchronized (this) {
if (!canceled) {
canceled = true;
} else {
return;
}
}
try {
Destination d = DL.getDestination(uid);
if (d == null) {
return;
}
// Re-verify that the destination can be removed
synchronized (d) {
if (!d.shouldDestroy()) {
return;
}
}
synchronized (DL.destinationList) {
if (d.getRefCount() > 0) {
return;
}
int level = (DestType.isAdmin(d.getType()) ? Logger.DEBUG : Logger.INFO);
logger.log(level, BrokerResources.I_AUTO_DESTROY, uid.getLocalizedName(), String.valueOf(DL.AUTOCREATE_EXPIRE / 1000));
d.destvalid = false;
DL.removeDestination(uid, false, Globals.getBrokerResources().getString(BrokerResources.M_AUTO_REAPED));
}
} catch (Exception ex) {
logger.logStack(Logger.WARNING, BrokerResources.X_REMOVE_DESTINATION_FAILED, uid.getLocalizedName(), ex);
}
}
}
class ReconnectReaperTask extends TimerTask {
DestinationUID uid = null;
private boolean canceled = false;
private long time = 0;
ReconnectReaperTask(DestinationUID uid, long time) {
this.uid = uid;
this.time = time;
}
@Override
public synchronized boolean cancel() {
canceled = true;
return super.cancel();
}
@Override
public void run() {
synchronized (this) {
if (canceled) {
return;
}
}
Globals.getLogger().log(Logger.DEBUG, "Destroying temp destination " + uid + " inactive for " + (time / 1000) + " seconds");
try {
DL.removeDestination(uid, false, Globals.getBrokerResources().getString(BrokerResources.M_RECONNECT_TIMEOUT));
} catch (Exception ex) {
if (BrokerStateHandler.isShuttingDown()) {
Globals.getLogger().log(Logger.INFO, BrokerResources.X_REMOVE_DESTINATION_FAILED, uid.getLocalizedName(), ex);
} else {
Globals.getLogger().logStack(Logger.WARNING, BrokerResources.X_REMOVE_DESTINATION_FAILED, uid.getLocalizedName(), ex);
}
}
}
}
transient MsgExpirationReaper expireReaper = new MsgExpirationReaper();
class MsgExpirationReaper {
SortedSet messages = null;
TimerTask mytimer = null;
MsgExpirationReaper() {
messages = new TreeSet(ExpirationInfo.getComparator());
}
public synchronized void addExpiringMessage(ExpirationInfo ei) {
messages.add(ei);
if (mytimer == null) {
addTimer();
}
}
public synchronized void removeMessage(ExpirationInfo ei) {
boolean rem = messages.remove(ei);
// assert rem;
if (rem && messages.isEmpty()) {
removeTimer();
}
}
public synchronized void destroy() {
if (mytimer != null) {
removeTimer();
}
messages.clear();
}
void addTimer() {
assert Thread.holdsLock(this);
assert mytimer == null;
mytimer = new MyExpireTimerTask();
try {
timer.schedule(mytimer, DL.MESSAGE_EXPIRE, DL.MESSAGE_EXPIRE);
} catch (IllegalStateException ex) {
logger.log(Logger.INFO, BrokerResources.E_INTERNAL_BROKER_ERROR, "Canceling message expiration on " + this, ex);
}
}
void removeTimer() {
assert Thread.holdsLock(this);
try {
if (mytimer != null) {
mytimer.cancel();
}
} catch (IllegalStateException ex) {
logger.logStack(Logger.DEBUG, "timer canceled ", ex);
}
mytimer = null;
}
class MyExpireTimerTask extends TimerTask {
@Override
public void run() {
long currentTime = System.currentTimeMillis();
int removedCount = 0;
int indeliveryCount = 0;
LinkedHashSet removed = new LinkedHashSet();
DestinationUID duid = Destination.this.uid;
synchronized (MsgExpirationReaper.this) {
Iterator itr = messages.iterator();
while (itr.hasNext()) {
ExpirationInfo ei = (ExpirationInfo) itr.next();
if (ei.getExpireTime() > currentTime) {
if (FI.FAULT_INJECTION) {
if (FI.checkFault(FI.FAULT_MSG_EXPIRE_REAPER_EXPIRE1, null)) {
FI.unsetFault(FI.FAULT_MSG_EXPIRE_REAPER_EXPIRE1);
removed.add(ei);
continue;
}
}
break;
}
removed.add(ei);
}
}
// we dont want to do this inside the loop because
// removeExpiredMessage can generate a callback which
// can generate a deadlock .. bummer
Iterator itr = removed.iterator();
while (itr.hasNext()) {
ExpirationInfo ei = (ExpirationInfo) itr.next();
try {
ei.incrementReapCount();
RemoveMessageReturnInfo ret = removeExpiredMessage(duid, ei.id);
if (ret.removed) {
removeMessage(ei);
removedCount++;
} else if (ret.indelivery) {
indeliveryCount++;
} else if (ei.getReapCount() > 1) {
removeMessage(ei);
removedCount++;
}
} catch (Exception ex) {
logger.logStack(Logger.WARNING, ex.getMessage(), ex);
}
}
if (removedCount > 0) {
logger.log(Logger.INFO, BrokerResources.I_REMOVE_DSTEXP_MSGS, String.valueOf(removedCount), duid.getLocalizedName());
}
if (indeliveryCount > 0) {
logger.log(Logger.INFO, BrokerResources.I_NUM_MSGS_INDELIVERY_NOT_EXPIRED_FROM_DEST, String.valueOf(indeliveryCount),
duid.getLocalizedName());
}
removed.clear();
}
}
}
class DestFilter implements Filter {
@Override
public boolean matches(Object o) {
return uid.equals(((PacketReference) o).getDestinationUID());
}
}
protected transient Filter filter = new DestFilter();
protected transient DestMetricsCounters dmc = new DestMetricsCounters();
protected transient MessageDeliveryTimeTimer deliveryTimeTimer = null;
protected synchronized void initialize() {
try {
if (stored) {
synchronized (sizeLock) {
int oldsize = size;
long oldbytes = bytes;
HashMap data = pstore.getMessageStorageInfo(this);
size = ((Integer) data.get(DestMetricsCounters.CURRENT_MESSAGES)).intValue();
bytes = ((Long) data.get(DestMetricsCounters.CURRENT_MESSAGE_BYTES)).longValue();
size += remoteSize;
bytes += remoteBytes;
int sizediff = size - oldsize;
long bytediff = bytes - oldbytes;
if (!isAdmin() && (getIsDMQ() || !isInternal())) {
DL.adjustTotals(sizediff, bytediff);
}
}
}
} catch (Exception ex) {
logger.logStack(Logger.WARNING, br.getKString(br.E_GET_MSG_METRICS_FROM_STORE_FAIL, this), ex);
}
dest_inited = true;
}
protected boolean isDestInited() {
return dest_inited;
}
// used during upgrade
public void initializeOldDestination() {
overridePersistence(true);
stored = true;
dest_inited = false;
loaded = false;
}
public boolean getIsDMQ() {
return isDMQ;
}
/**
* handles transient data when class is deserialized
*/
private void readObject(java.io.ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
logger = Globals.getLogger();
br = Globals.getBrokerResources();
DL = Globals.getDestinationList();
currentChangeRecordInfo = Collections.synchronizedMap(new HashMap<Integer, ChangeRecordInfo>());
producerFlow = new ProducerFlow();
isDMQ = DestType.isDMQ(type);
if (!isDMQ) {
expireReaper = new MsgExpirationReaper();
}
dest_inited = false;
loaded = false;
destvalid = true;
sizeLock = new Object();
size = 0;
remoteSize = 0;
bytes = 0L;
remoteBytes = 0L;
destMessages = new SimpleNFLHashMap<>();
destMessagesInRemoving = new HashMap();