-
Notifications
You must be signed in to change notification settings - Fork 33
/
Consumer.java
1974 lines (1747 loc) · 70.1 KB
/
Consumer.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 java.io.*;
import java.util.Map;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Set;
import java.util.Iterator;
import com.sun.messaging.jmq.util.DestType;
import com.sun.messaging.jmq.util.lists.*;
import com.sun.messaging.jmq.jmsserver.util.lists.*;
import com.sun.messaging.jmq.io.*;
import com.sun.messaging.jmq.util.log.Logger;
import com.sun.messaging.jmq.util.selector.Selector;
import com.sun.messaging.jmq.util.selector.SelectorFormatException;
import com.sun.messaging.jmq.jmsserver.service.ConnectionUID;
import com.sun.messaging.jmq.jmsserver.util.*;
import com.sun.messaging.jmq.jmsserver.service.Connection;
import com.sun.messaging.jmq.jmsserver.service.imq.IMQConnection;
import com.sun.messaging.jmq.jmsserver.resources.*;
import com.sun.messaging.jmq.jmsserver.persist.api.PartitionedStore;
import com.sun.messaging.jmq.jmsserver.persist.api.NoPersistPartitionedStoreImpl;
import com.sun.messaging.jmq.jmsserver.Globals;
import com.sun.messaging.jmq.jmsserver.FaultInjection;
import com.sun.messaging.jmq.jmsserver.cluster.api.ClusterBroadcast;
import com.sun.messaging.jmq.jmsserver.plugin.spi.ConsumerSpi;
public class Consumer implements ConsumerSpi, EventBroadcaster, Serializable {
transient Logger logger = Globals.getLogger();
static final long serialVersionUID = 3353669107150988952L;
public static final String PREFETCH = "prefetch";
private static boolean DEBUG = false;
private static final FaultInjection FI = FaultInjection.getInjection();
protected static final boolean DEBUG_CLUSTER_TXN = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".cluster.debug.txn") || DEBUG;
protected static final boolean DEBUG_CLUSTER_MSG = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".cluster.debug.msg") || DEBUG_CLUSTER_TXN || DEBUG;
private transient boolean useConsumerFlowControl = false;
private transient int msgsToConsumer = 0;
transient Map<PartitionedStore, LinkedHashSet<Destination>> destinationMap = Collections
.synchronizedMap(new LinkedHashMap<PartitionedStore, LinkedHashSet<Destination>>());
protected transient BrokerResources br = Globals.getBrokerResources();
private static boolean C_FLOW_CONTROL_ALLOWED = Globals.getConfig().getBooleanProperty(Globals.IMQ + ".destination.flowControlAllowed", true);
long lastAckTime = 0;
SessionUID sessionuid = null;
DestinationUID dest;
ConsumerUID uid;
transient ConsumerUID stored_uid;
ConnectionUID conuid = null;
transient boolean valid = true;
transient boolean active = true;
transient boolean paused = false;
transient int pauseCnt = 0;
transient int pauseFlowCnt = 0;
transient int resumeFlowCnt = 0;
boolean noLocal = false;
transient boolean busy = false;
transient Subscription parent = null;
transient boolean isSpecialRemote = false;
transient boolean isFailover = false;
transient int position = 0;
transient int lockPosition = -1;
transient EventBroadcastHelper evb = null;
boolean ackMsgsOnDestroy = true;
transient int flowCount = 0;
transient boolean flowPaused = false;
transient int msgsOut = 0;
transient int prefetch = -1; // unlimited
transient int remotePrefetch = -1;
transient String creator = null;
transient boolean requestedRecreation = false;
/**
* Optional selector string specified by the client application.
*/
protected String selstr = null;
protected transient Selector selector = null;
transient NFLPriorityFifoSet<PacketReference> msgs;
protected transient Map<PartitionedStore, SubSet> parentListMap = Collections.synchronizedMap(new LinkedHashMap<PartitionedStore, SubSet>());
protected transient Map plistenerMap = Collections.synchronizedMap(new LinkedHashMap<PartitionedStore, Object>());
private transient Object mlistener = null;
private transient boolean localConsumerCreationReady = false;
private static final int DEFAULT_MSG_MAX_CONSECUTIVE_ROLLBACKS = 0;
public static final int MSG_MAX_CONSECUTIVE_ROLLBACKS = Globals.getConfig().getIntProperty(Globals.IMQ + ".transaction.message.maxConsecutiveRollbacks",
DEFAULT_MSG_MAX_CONSECUTIVE_ROLLBACKS);
private transient HashMap messageRollbacks = new HashMap();
transient EventListener busylistener = null;
class BusyListener implements EventListener {
@Override
public void eventOccured(EventType type, Reason r, Object target, Object oldval, Object newval, Object userdata) {
assert type == EventType.EMPTY;
assert newval instanceof Boolean;
checkState(null);
}
}
transient EventListener removeListener = null;
class RemoveListener implements EventListener {
@Override
public void eventOccured(EventType type, Reason r, Object target, Object oldval, Object newval, Object userdata) {
assert type == EventType.SET_CHANGED_REQUEST;
if (!(r instanceof RemoveReason)) {
return;
}
// OK .. we are only registered to get the
// following events:
// RemoveReason.EXPIRED
// RemoveReason.PURGED
// RemoveReason.REMOVED_LOW_PRIORITY
// RemoveReason.REMOVED_OLDEST
// RemoveReason.REMOVED_REJECTED
// RemoveReason.REMOVED_OTHER
assert r != RemoveReason.UNLOADED;
assert r != RemoveReason.ROLLBACK;
assert r != RemoveReason.DELIVERED;
assert r != RemoveReason.ACKNOWLEDGED;
assert r != RemoveReason.ROLLBACK;
assert r != RemoveReason.OVERFLOW;
assert r != RemoveReason.ERROR;
PacketReference ref = (PacketReference) oldval;
msgs.remove(ref);
if (DEBUG || DEBUG_CLUSTER_MSG) {
logger.log(logger.INFO, "Consumer.removeListener: removed msg " + ref + " from msgs in consumer " + Consumer.this);
}
if (!ref.isLocal() && ref.getMessageDeliveredAck(uid)) {
try {
Map props = new HashMap();
props.put(Consumer.PREFETCH, Integer.valueOf(1));
Globals.getClusterBroadcast().acknowledgeMessage(ref.getBrokerAddress(), ref.getSysMessageID(), uid, ClusterBroadcast.MSG_DELIVERED, props,
false);
} catch (Exception e) {
if (DEBUG) {
logger.logStack(Logger.INFO, "Cannot send DELIVERED ack for message " + ref + " for consumer " + uid, e);
}
}
}
}
}
private transient Object expiredID = null;
private transient Object purgedID = null;
private transient Object removedID1 = null;
private transient Object removedID2 = null;
private transient Object removedID3 = null;
private transient Object removedID4 = null;
public void addRemoveListener(EventBroadcaster l) {
// add consumer interest in REMOVE of messages
expiredID = l.addEventListener(removeListener, EventType.SET_CHANGED_REQUEST, RemoveReason.EXPIRED, null);
purgedID = l.addEventListener(removeListener, EventType.SET_CHANGED_REQUEST, RemoveReason.PURGED, null);
removedID1 = l.addEventListener(removeListener, EventType.SET_CHANGED_REQUEST, RemoveReason.REMOVED_OLDEST, null);
removedID2 = l.addEventListener(removeListener, EventType.SET_CHANGED_REQUEST, RemoveReason.REMOVED_LOW_PRIORITY, null);
removedID3 = l.addEventListener(removeListener, EventType.SET_CHANGED_REQUEST, RemoveReason.REMOVED_REJECTED, null);
removedID4 = l.addEventListener(removeListener, EventType.SET_CHANGED_REQUEST, RemoveReason.REMOVED_OTHER, null);
}
public void removeRemoveListener(EventBroadcaster l) {
l.removeEventListener(expiredID);
l.removeEventListener(purgedID);
l.removeEventListener(removedID1);
l.removeEventListener(removedID2);
l.removeEventListener(removedID3);
l.removeEventListener(removedID4);
}
private boolean getParentBusy() {
// Fix for CR 6875642 New direct mode hangs when creating a durable subscriber
// if (parent !=null){
// if (parent.isPaused()){
// return false;
// }
// }
return (parentListMap.size() > 0 && !isParentListEmpty(parentListMap)) || (parent != null && parent.isBusy());
}
private static boolean isParentListEmpty(Map<PartitionedStore, SubSet> map) {
synchronized (map) {
Iterator<SubSet> itr = map.values().iterator();
while (itr.hasNext()) {
if (!itr.next().isEmpty()) {
return false;
}
}
}
return true;
}
private static SubSet getNonEmptyParentList(Map<PartitionedStore, SubSet> map, SubSet lastpl) {
SubSet pl = null, foundpl = null;
synchronized (map) {
Iterator<SubSet> itr = map.values().iterator();
while (itr.hasNext()) {
pl = itr.next();
if (!pl.isEmpty()) {
if (lastpl == null) {
return pl;
}
foundpl = pl;
if (!(foundpl == lastpl || foundpl.equals(lastpl))) {
return foundpl;
}
}
}
}
return foundpl;
}
public void setPrefetch(int count) {
prefetch = count;
useConsumerFlowControl = C_FLOW_CONTROL_ALLOWED;
}
@Override
public void setPrefetch(int count, boolean useConsumerFlowControl) {
prefetch = count;
this.useConsumerFlowControl = useConsumerFlowControl;
}
public void setRemotePrefetch(int count) {
remotePrefetch = count;
}
public int getRemotePrefetch() {
return remotePrefetch;
}
public static int calcPrefetch(Consumer consumer, int cprefetch) {
Destination d = consumer.getFirstDestination();
Subscription sub = consumer.getSubscription();
int dprefetch = -1;
if (d != null) {
dprefetch = (sub == null || !sub.getShared()) ? d.getMaxPrefetch() : d.getSharedConsumerFlowLimit();
}
int pref = (dprefetch == -1) ? cprefetch : (cprefetch == -1 ? cprefetch : (cprefetch > dprefetch ? dprefetch : cprefetch));
return pref;
}
public long getLastAckTime() {
return lastAckTime;
}
public void setLastAckTime(long time) {
lastAckTime = time;
if (parent != null) {
parent.setLastAckTime(time);
}
}
@Override
public int getPrefetch() {
return prefetch;
}
public int getPrefetchForRemote() {
int fetch = prefetch;
if (DestinationList.getMaxMessages() > 0) {
long room = (DestinationList.getMaxMessages() - DestinationList.totalCount());
if (room <= 0) {
room = 1L;
}
if (fetch > room) {
fetch = (int) room;
}
}
long room = -1L, m;
Destination d = null;
Iterator itr = getDestinations().iterator();
while (itr.hasNext()) {
d = (Destination) itr.next();
m = d.checkDestinationCapacity(null);
if (m < 0L) {
continue;
}
if (room < 0L || room > m) {
room = m;
}
}
if (room == 0) {
room = 1L;
}
if (room > 0L) {
if (fetch > room) {
fetch = (int) room;
}
}
return fetch;
}
public void setSubscription(Subscription sub) {
ackMsgsOnDestroy = false;
parent = sub;
}
/**
* Triggers loading of any associated destiantions
*/
public void load() {
Iterator itr = getDestinations().iterator();
while (itr.hasNext()) {
Destination d = (Destination) itr.next();
try {
d.load();
} catch (Exception ex) {
}
}
}
public String getCreator() {
return creator;
}
public void setCreator(String id) {
creator = id;
}
public String getClientID() {
ConnectionUID cuid = getConnectionUID();
if (cuid == null) {
return "<unknown>";
}
Connection con = Globals.getConnectionManager().getConnection(cuid);
return (String) con.getClientData(IMQConnection.CLIENT_ID);
}
public boolean isDurableSubscriber() {
if (parent != null) {
return parent.isDurable();
}
if (this instanceof Subscription) {
return ((Subscription) this).isDurable();
}
return false;
}
public boolean getIsFlowPaused() {
return flowPaused;
}
public void msgRetrieved() {
msgsOut++;
}
public int totalMsgsDelivered() {
return msgsOut;
}
public int numPendingAcks() {
Session s = Session.getSession(sessionuid);
if (s == null) {
return 0;
}
return s.getNumPendingAcks(getConsumerUID());
}
public Subscription getSubscription() {
return parent;
}
protected static Selector getSelector(String selstr) throws SelectorFormatException {
return Selector.compile(selstr);
}
public Map<PartitionedStore, SubSet> getParentList() {
Map m = new LinkedHashMap<>();
synchronized (parentListMap) {
m.putAll(parentListMap);
}
return m;
}
transient Object destroyLock = new Object();
public void destroyConsumer(Set delivered, boolean destroyingDest) {
destroyConsumer(delivered, (Map) null, false, destroyingDest, true);
}
public void destroyConsumer(Set delivered, boolean destroyingDest, boolean notify) {
destroyConsumer(delivered, (Map) null, false, destroyingDest, notify);
}
public void destroyConsumer(Set delivered, Map remotePendings, boolean remoteCleanup, boolean destroyingDest, boolean notify) {
if (DEBUG) {
logger.log(logger.INFO,
"destroyConsumer(" + delivered.size() + ", " + remotePendings + ", " + remoteCleanup + ", " + destroyingDest + ", " + notify + ")");
}
synchronized (destroyLock) {
if (!valid) {
// already removed
return;
}
valid = false; // we are going into destroy, so we are invalid
}
Subscription sub = parent;
if (sub != null) {
sub.pause("Consumer.java: destroy " + this);
}
pause("Consumer.java: destroy ");
// clean up hooks to any parent list
if (parentListMap.size() > 0 && plistenerMap.size() > 0) {
Object pll = null;
for (Map.Entry<PartitionedStore, SubSet> pair : parentListMap.entrySet()) {
pll = plistenerMap.get(pair.getKey());
if (pll != null) {
pair.getValue().removeEventListener(pll);
plistenerMap.remove(pair.getKey());
}
}
}
List<Destination> ds = getDestinations();
Map<PartitionedStore, SubSet> oldParent = new LinkedHashMap<>();
synchronized (parentListMap) {
oldParent.putAll(parentListMap);
parentListMap.clear();
}
if (parent != null) {
parent.releaseConsumer(uid);
parent = null;
if (notify) {
try {
sendDestroyConsumerNotification(remotePendings, remoteCleanup);
} catch (Exception ex) {
logger.logStack(Logger.WARNING, "Sending detach notification for " + uid + " from " + parent, ex);
}
}
} else {
if ((ds == null || ds.isEmpty()) && !destroyingDest) {
// destination already gone
// can happen if the destination is destroyed
logger.log(Logger.DEBUG, "Removing consumer from non-existant destination" + dest);
} else if (!destroyingDest) {
Iterator itr = ds.iterator();
while (itr.hasNext()) {
Destination d = null;
try {
d = (Destination) itr.next();
d.removeConsumer(uid, remotePendings, remoteCleanup, notify);
} catch (Exception ex) {
logger.logStack(Logger.WARNING, "removing consumer " + uid + " from " + d, ex);
}
}
}
}
if (DEBUG) {
logger.log(Logger.DEBUG, "Destroying consumer " + this + "[" + delivered.size() + ":" + msgs.size() + "]");
}
// now clean up and/or requeue messages
// any consumed messages will stay on the session
// until we are done
Set<PacketReference> s = new LinkedHashSet<>(msgs);
Reason cleanupReason = (ackMsgsOnDestroy ? RemoveReason.ACKNOWLEDGED : RemoveReason.UNLOADED);
delivered.addAll(s);
// automatically ack any remote or ack On Destroy messages
Iterator itr = delivered.iterator();
while (itr.hasNext()) {
PacketReference r = (PacketReference) itr.next();
if (r == null) {
continue;
}
if (ackMsgsOnDestroy || !r.isLocal()) {
itr.remove();
try {
if (r.acknowledged(getConsumerUID(), getStoredConsumerUID(), !uid.isUnsafeAck(), r.isLocal())) {
try {
Destination[] dds = DestinationList.getDestination(r.getPartitionedStore(), r.getDestinationUID());
Destination d = null;
for (int i = 0; i < dds.length; i++) {
d = dds[i];
if (d == null) {
continue;
}
if (r.isLocal()) {
d.removeMessage(r.getSysMessageID(), RemoveReason.ACKNOWLEDGED);
} else {
d.removeRemoteMessage(r.getSysMessageID(), RemoveReason.ACKNOWLEDGED, r);
}
}
} finally {
r.postAcknowledgedRemoval();
}
}
} catch (Exception ex) {
logger.log(Logger.DEBUG, "Broker down Unable to acknowlege" + r.getSysMessageID() + ":" + uid, ex);
}
}
}
msgs.removeAll(s, cleanupReason);
if (!ackMsgsOnDestroy) {
Map<PartitionedStore, Set> map = new LinkedHashMap<>();
Set set = null;
PacketReference ref = null;
PartitionedStore pstore = null;
itr = delivered.iterator();
while (itr.hasNext()) {
ref = (PacketReference) itr.next();
if (ref.getDestinationUID().isQueue()) {
pstore = ref.getPartitionedStore();
} else {
pstore = new NoPersistPartitionedStoreImpl(getStoredConsumerUID());
}
set = map.get(pstore);
if (set == null) {
set = new LinkedHashSet();
map.put(pstore, set);
}
set.add(ref);
}
SubSet pl = null;
for (Map.Entry<PartitionedStore, Set> pair : map.entrySet()) {
pl = oldParent.get(pair.getKey());
if (pl != null) {
((Prioritized) pl).addAllOrdered(pair.getValue());
}
}
delivered.clear(); // help gc
}
destroy();
if (msgs != null && mlistener != null) {
msgs.removeEventListener(mlistener);
mlistener = null;
}
if (sub != null) {
sub.resume("Consumer.java: destroyConsumer " + this);
}
selstr = null;
selector = null;
}
/**
* This method is called from ConsumerHandler.
*/
public void sendCreateConsumerNotification() throws BrokerException {
// OK, we may have multiple consumers
// we just want the first one
Destination d = getFirstDestination();
if ((dest.isWildcard() || (!d.getIsLocal() && !d.isInternal() && !d.isAdmin())) && Globals.getClusterBroadcast() != null) {
Globals.getClusterBroadcast().createConsumer(this);
}
}
public void sendDestroyConsumerNotification(Map remotePendings, boolean remoteCleanup) throws BrokerException {
// OK, we may have multiple consumers
// we just want the first one
Destination d = getFirstDestination();
if (dest.isWildcard() || (d != null && !d.getIsLocal() && !d.isInternal() && !d.isAdmin() && Globals.getClusterBroadcast() != null)) {
Globals.getClusterBroadcast().destroyConsumer(this, remotePendings, remoteCleanup);
}
}
protected void destroy() {
valid = false;
pause("Consumer.java: destroy()");
synchronized (consumers) {
consumers.remove(uid);
}
wildcardConsumers.remove(uid);
selector = null; // easier for weak hashmap
Reason cleanupReason = RemoveReason.UNLOADED;
if (ackMsgsOnDestroy) {
cleanupReason = RemoveReason.ACKNOWLEDGED;
}
Set<PacketReference> s = new HashSet<>(msgs);
try {
DestinationList DL = Globals.getDestinationList();
synchronized (s) {
Iterator<PacketReference> itr = s.iterator();
while (itr.hasNext()) {
PacketReference pr = itr.next();
if (ackMsgsOnDestroy && pr.acknowledged(getConsumerUID(), getStoredConsumerUID(), !uid.isUnsafeAck(), true)) {
try {
Destination[] ds = DL.getDestination(pr.getPartitionedStore(), pr.getDestinationUID());
Destination d = ds[0];
if (pr.isLocal()) {
d.removeMessage(pr.getSysMessageID(), cleanupReason);
} else {
d.removeRemoteMessage(pr.getSysMessageID(), cleanupReason, pr);
}
} finally {
pr.postAcknowledgedRemoval();
}
}
}
}
msgs.removeAll(s, cleanupReason);
} catch (Exception ex) {
logger.logStack(Logger.WARNING, br.getKString(br.W_EXCEPTION_CLEANUP_CONSUMER, this, ex.getMessage()), ex);
}
}
/**
* the list (if any) that the consumer can pull messages from
*/
public void setParentList(PartitionedStore pstore, SubSet set) {
if (DEBUG) {
logger.log(Logger.INFO, "Consumer.setParentList(" + pstore + ", " + set + ")");
}
ackMsgsOnDestroy = false;
SubSet pl = parentListMap.get(pstore);
if (pl != null) {
Object pll = plistenerMap.get(pstore);
if (pll != null) {
pl.removeEventListener(pll);
}
}
plistenerMap.remove(pstore);
synchronized (parentListMap) {
if (set != null) {
parentListMap.put(pstore, set);
plistenerMap.put(pstore, set.addEventListener(busylistener, EventType.EMPTY, null));
}
}
checkState(null);
}
protected void getMoreMessages(int num) {
final Map<PartitionedStore, SubSet> ss = new LinkedHashMap<>();
synchronized (parentListMap) {
ss.putAll(parentListMap);
}
if (paused || ss.size() == 0 || isParentListEmpty(ss) || (parent != null && parent.isPaused())) {
// nothing to do
return;
} else {
// pull
int count = 0;
if (isParentListEmpty(ss)) {
return;
}
SubSet pl = null;
assert ss != null;
while (!isFailover && isActive() && !isPaused() && isValid() && (pl = getNonEmptyParentList(ss, pl)) != null && count < num
&& (parent == null || !parent.isPaused())) {
PacketReference mm = (PacketReference) pl.removeNext();
if (mm == null) {
continue;
}
msgs.add(11 - mm.getPriority(), mm);
count++;
busy = true;
}
}
}
void setIsActiveConsumer(boolean active) {
isFailover = !active;
checkState(null);
}
public boolean getIsFailoverConsumer() {
return isFailover;
}
public boolean getIsActiveConsumer() {
return !isFailover;
}
/**
* handles transient data when class is deserialized
*/
private void readObject(java.io.ObjectInputStream ois) throws IOException, ClassNotFoundException {
ois.defaultReadObject();
logger = Globals.getLogger();
remotePendingResumes = new ArrayList();
lastDestMetrics = new Hashtable();
localConsumerCreationReady = false;
parent = null;
busy = false;
paused = false;
flowPaused = false;
flowCount = 0;
active = true;
valid = true;
destroyLock = new Object();
destinationMap = Collections.synchronizedMap(new LinkedHashMap<PartitionedStore, LinkedHashSet<Destination>>());
parentListMap = Collections.synchronizedMap(new LinkedHashMap<PartitionedStore, SubSet>());
plistenerMap = Collections.synchronizedMap(new LinkedHashMap<PartitionedStore, Object>());
mlistener = null;
prefetch = -1;
isFailover = false;
position = 0;
isSpecialRemote = false;
useConsumerFlowControl = false;
stored_uid = null;
active = true;
pauseCnt = 0;
try {
selector = getSelector(selstr);
} catch (Exception ex) {
logger.logStack(Logger.ERROR, "Internal Error: bad stored selector[" + selstr + "], ignoring", ex);
selector = null;
}
initInterest();
}
@Override
public boolean isBusy() {
return busy;
}
@Override
public DestinationUID getDestinationUID() {
return dest;
}
protected Consumer(ConsumerUID uid) {
// used for removing a consumer during load problems
// only
// XXX - revisit changing protocol to use UID so we
// dont have to do this
this.uid = uid;
}
public static Consumer newInstance(ConsumerUID uid) {
return new Consumer(uid);
}
public Consumer(DestinationUID d, String selstr, boolean noLocal, ConnectionUID con_uid) throws IOException, SelectorFormatException {
dest = d;
this.noLocal = noLocal;
uid = new ConsumerUID();
uid.setConnectionUID(con_uid);
this.selstr = selstr;
selector = getSelector(selstr);
initInterest();
if (DEBUG) {
logger.log(Logger.INFO, "Consumer: created new consumer " + uid + " on destination " + d + " with selector " + selstr);
}
}
public Consumer(DestinationUID d, String selstr, boolean noLocal, ConsumerUID uid) throws IOException, SelectorFormatException {
dest = d;
this.noLocal = noLocal;
this.uid = uid;
if (uid == null) {
this.uid = new ConsumerUID();
}
this.selstr = selstr;
selector = getSelector(selstr);
initInterest();
}
public static Consumer newConsumer(DestinationUID destid, String selectorstr, boolean isnolocal, ConsumerUID consumerid)
throws IOException, SelectorFormatException, ConsumerAlreadyAddedException {
synchronized (consumers) {
if (consumers.get(consumerid) != null) {
throw new ConsumerAlreadyAddedException(Globals.getBrokerResources().getKString(BrokerResources.I_CONSUMER_ALREADY_ADDED, consumerid, destid));
}
return new Consumer(destid, selectorstr, isnolocal, consumerid);
}
}
public void localConsumerCreationReady() {
synchronized (consumers) {
localConsumerCreationReady = true;
}
}
private boolean isLocalConsumerCreationReady() {
synchronized (consumers) {
return localConsumerCreationReady;
}
}
public boolean isValid() {
return valid;
}
protected void initInterest() {
removeListener = new RemoveListener();
busylistener = new BusyListener();
evb = new EventBroadcastHelper();
msgs = new NFLPriorityFifoSet<>(12, false);
mlistener = msgs.addEventListener(busylistener, EventType.EMPTY, null);
synchronized (consumers) {
consumers.put(uid, this);
}
if (dest.isWildcard()) {
wildcardConsumers.add(uid);
}
}
protected static void attachConsumers(DestinationList dl) throws BrokerException {
try {
DestinationList DL = Globals.getDestinationList();
Consumer c = null;
DestinationUID did = null;
synchronized (consumers) {
Iterator itr = consumers.values().iterator();
while (itr.hasNext()) {
c = (Consumer) itr.next();
if (c instanceof Subscription) {
continue;
}
did = c.getDestinationUID();
if (did.isWildcard()) {
List<DestinationUID> dids = DL.findMatchingIDsByDestinationList(dl, did);
Iterator itr1 = dids.iterator();
while (itr1.hasNext()) {
DestinationUID match_did = (DestinationUID) itr1.next();
Destination d = DL.getDestinationByDestinationList(dl, match_did);
d.addConsumer(c, false, null, true);
Globals.getLogger().log(Logger.INFO, "XXXI18N attached regular consumer " + c + " to partition " + dl);
}
} else {
Destination d = DL.getDestinationByDestinationList(dl, did.getName(),
(did.isQueue() ? DestType.DEST_TYPE_QUEUE : DestType.DEST_TYPE_TOPIC), true, true);
d.addConsumer(c, false, null, true);
Globals.getLogger().log(Logger.INFO, "XXXI18N attached regular consumer " + c + " to partition " + dl);
}
}
}
} catch (Exception e) {
Globals.getLogger().logStack(Logger.ERROR, e.getMessage(), e);
if (e instanceof BrokerException) {
throw (BrokerException) e;
}
throw new BrokerException(e.getMessage(), e);
}
}
public PacketReference peekNext() {
// ok first see if there is anything on msgs
PacketReference ref = msgs.peekNext();
if (ref == null && parentListMap.size() > 0) {
synchronized (parentListMap) {
Iterator<SubSet> itr = parentListMap.values().iterator();
while (itr.hasNext()) {
ref = (PacketReference) itr.next().peekNext();
if (ref != null) {
break;
}
}
}
}
return ref;
}
public void setAckMsgsOnDestroy(boolean ack) {
ackMsgsOnDestroy = ack;
}
@Override
public ConsumerUID getConsumerUID() {
return uid;
}
public void setStoredConsumerUID(ConsumerUID uid) {
stored_uid = uid;
}
@Override
public ConsumerUID getStoredConsumerUID() {
if (stored_uid == null) {
return uid;
}
return stored_uid;
}
public void messageCommitted(SysMessageID sysid) {
if (MSG_MAX_CONSECUTIVE_ROLLBACKS <= 0) {
return;
}
synchronized (messageRollbacks) {
messageRollbacks.clear();
}
}
public boolean addRollbackCnt(SysMessageID sysid, int maxRollbacks) {
if (maxRollbacks <= 0 && MSG_MAX_CONSECUTIVE_ROLLBACKS <= 0) {
return true;
}
int maxrb = maxRollbacks;
if (maxRollbacks <= 0) {
maxrb = MSG_MAX_CONSECUTIVE_ROLLBACKS;
}
synchronized (messageRollbacks) {
Integer count = (Integer) messageRollbacks.get(sysid);
if (count == null) {
messageRollbacks.put(sysid, Integer.valueOf(0));
return true;
}
int cnt = count.intValue();
if (cnt < maxrb) {
messageRollbacks.put(sysid, Integer.valueOf(++cnt));
return true;
}
return false;
}
}
public boolean routeMessages(Collection<PacketReference> c, boolean toFront) {
if (toFront) {
if (!valid) {
return false;
}
msgs.addAllToFront(c, 0);
synchronized (destroyLock) {
msgsToConsumer += c.size();
}
checkState(null);
} else {
Iterator<PacketReference> itr = c.iterator();
while (itr.hasNext()) {
routeMessage(itr.next(), false);
}
}
if (!valid) {
return false;