/
RouterService.java
816 lines (753 loc) · 39.1 KB
/
RouterService.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
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jumpmind.symmetric.service.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.jumpmind.db.model.Table;
import org.jumpmind.symmetric.ISymmetricEngine;
import org.jumpmind.symmetric.SyntaxParsingException;
import org.jumpmind.symmetric.common.Constants;
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.io.data.DataEventType;
import org.jumpmind.symmetric.model.Data;
import org.jumpmind.symmetric.model.DataGap;
import org.jumpmind.symmetric.model.DataMetaData;
import org.jumpmind.symmetric.model.Node;
import org.jumpmind.symmetric.model.NodeChannel;
import org.jumpmind.symmetric.model.NodeGroupLink;
import org.jumpmind.symmetric.model.NodeGroupLinkAction;
import org.jumpmind.symmetric.model.NodeSecurity;
import org.jumpmind.symmetric.model.OutgoingBatch;
import org.jumpmind.symmetric.model.OutgoingBatch.Status;
import org.jumpmind.symmetric.model.ProcessInfo;
import org.jumpmind.symmetric.model.ProcessInfoKey;
import org.jumpmind.symmetric.model.ProcessInfoKey.ProcessType;
import org.jumpmind.symmetric.model.Router;
import org.jumpmind.symmetric.model.TriggerRouter;
import org.jumpmind.symmetric.route.AuditTableDataRouter;
import org.jumpmind.symmetric.route.BshDataRouter;
import org.jumpmind.symmetric.route.ChannelRouterContext;
import org.jumpmind.symmetric.route.ColumnMatchDataRouter;
import org.jumpmind.symmetric.route.ConfigurationChangedDataRouter;
import org.jumpmind.symmetric.route.DataGapDetector;
import org.jumpmind.symmetric.route.DataGapRouteReader;
import org.jumpmind.symmetric.route.DefaultBatchAlgorithm;
import org.jumpmind.symmetric.route.DefaultDataRouter;
import org.jumpmind.symmetric.route.FileSyncDataRouter;
import org.jumpmind.symmetric.route.IBatchAlgorithm;
import org.jumpmind.symmetric.route.IDataRouter;
import org.jumpmind.symmetric.route.IDataToRouteReader;
import org.jumpmind.symmetric.route.LookupTableDataRouter;
import org.jumpmind.symmetric.route.NonTransactionalBatchAlgorithm;
import org.jumpmind.symmetric.route.SimpleRouterContext;
import org.jumpmind.symmetric.route.SubSelectDataRouter;
import org.jumpmind.symmetric.route.TransactionalBatchAlgorithm;
import org.jumpmind.symmetric.service.ClusterConstants;
import org.jumpmind.symmetric.service.INodeService;
import org.jumpmind.symmetric.service.IRouterService;
import org.jumpmind.symmetric.statistic.StatisticConstants;
/**
* @see IRouterService
*/
public class RouterService extends AbstractService implements IRouterService {
protected Map<String, IDataRouter> routers;
protected Map<String, IBatchAlgorithm> batchAlgorithms;
protected Map<String, Boolean> defaultRouterOnlyLastState = new HashMap<String, Boolean>();
protected transient ExecutorService readThread = null;
protected ISymmetricEngine engine;
protected boolean syncTriggersBeforeInitialLoadAttempted = false;
public RouterService(ISymmetricEngine engine) {
super(engine.getParameterService(), engine.getSymmetricDialect());
this.engine = engine;
this.batchAlgorithms = new HashMap<String, IBatchAlgorithm>();
this.batchAlgorithms.put("default", new DefaultBatchAlgorithm());
this.batchAlgorithms.put("nontransactional", new NonTransactionalBatchAlgorithm());
this.batchAlgorithms.put("transactional", new TransactionalBatchAlgorithm());
this.routers = new HashMap<String, IDataRouter>();
this.routers.put(ConfigurationChangedDataRouter.ROUTER_TYPE, new ConfigurationChangedDataRouter(engine));
this.routers.put("bsh", new BshDataRouter(engine));
this.routers.put("subselect", new SubSelectDataRouter(symmetricDialect));
this.routers.put("lookuptable", new LookupTableDataRouter(symmetricDialect));
this.routers.put("default", new DefaultDataRouter());
this.routers.put("audit", new AuditTableDataRouter(engine));
this.routers.put("column", new ColumnMatchDataRouter(engine.getConfigurationService(),
engine.getSymmetricDialect()));
this.routers.put(FileSyncDataRouter.ROUTER_TYPE, new FileSyncDataRouter(engine));
setSqlMap(new RouterServiceSqlMap(symmetricDialect.getPlatform(),
createSqlReplacementTokens()));
}
/**
* For use in data load events
*/
public boolean shouldDataBeRouted(SimpleRouterContext context, DataMetaData dataMetaData,
Node node, boolean initialLoad, boolean initialLoadSelectUsed) {
IDataRouter router = getDataRouter(dataMetaData.getRouter());
Set<Node> oneNodeSet = new HashSet<Node>(1);
oneNodeSet.add(node);
Collection<String> nodeIds = router.routeToNodes(context, dataMetaData, oneNodeSet,
initialLoad, initialLoadSelectUsed);
return nodeIds != null && nodeIds.contains(node.getNodeId());
}
public synchronized void stop() {
if (readThread != null) {
try {
log.info("RouterService is shutting down");
readThread.shutdown();
readThread = null;
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
}
/**
* This method will route data to specific nodes.
*/
synchronized public long routeData(boolean force) {
long dataCount = -1l;
if (engine.getNodeService().findIdentity() != null) {
if (force || engine.getClusterService().lock(ClusterConstants.ROUTE)) {
try {
engine.getOutgoingBatchService().updateAbandonedRoutingBatches();
insertInitialLoadEvents();
long ts = System.currentTimeMillis();
DataGapDetector gapDetector = new DataGapDetector(
engine.getDataService(), parameterService, symmetricDialect,
this, engine.getStatisticManager(), engine.getNodeService());
gapDetector.beforeRouting();
dataCount = routeDataForEachChannel(gapDetector);
ts = System.currentTimeMillis() - ts;
if (dataCount > 0 || ts > Constants.LONG_OPERATION_THRESHOLD) {
log.info("Routed {} data events in {} ms", dataCount, ts);
}
} finally {
if (!force) {
engine.getClusterService().unlock(ClusterConstants.ROUTE);
}
}
}
}
return dataCount;
}
/**
* If a load has been queued up by setting the initial load enabled or reverse initial load
* enabled flags, then the router service will insert the reload events. This process will
* not run at the same time sync triggers is running.
*/
protected void insertInitialLoadEvents() {
if (engine.getClusterService().lock(ClusterConstants.SYNCTRIGGERS)) {
try {
synchronized (engine.getTriggerRouterService()) {
engine.getClusterService().lock(ClusterConstants.SYNCTRIGGERS);
INodeService nodeService = engine.getNodeService();
Node identity = nodeService.findIdentity();
if (identity != null) {
NodeSecurity identitySecurity = nodeService.findNodeSecurity(identity
.getNodeId());
if (engine.getParameterService().isRegistrationServer() ||
(identitySecurity != null && !identitySecurity.isRegistrationEnabled()
&& identitySecurity.getRegistrationTime() != null)) {
List<NodeSecurity> nodeSecurities = nodeService
.findNodeSecurityWithLoadEnabled();
if (nodeSecurities != null) {
boolean reverseLoadFirst = parameterService
.is(ParameterConstants.INTITAL_LOAD_REVERSE_FIRST);
for (NodeSecurity security : nodeSecurities) {
if (engine.getTriggerRouterService()
.getActiveTriggerHistories().size() > 0) {
boolean reverseLoadQueued = security
.isRevInitialLoadEnabled();
boolean initialLoadQueued = security.isInitialLoadEnabled();
boolean thisMySecurityRecord = security.getNodeId().equals(
identity.getNodeId());
boolean registered = security.getRegistrationTime() != null;
boolean parent = identity.getNodeId().equals(
security.getCreatedAtNodeId());
if (thisMySecurityRecord && reverseLoadQueued
&& (reverseLoadFirst || !initialLoadQueued)) {
sendReverseInitialLoad();
} else if (!thisMySecurityRecord && registered && parent
&& initialLoadQueued
&& (!reverseLoadFirst || !reverseLoadQueued)) {
long ts = System.currentTimeMillis();
engine.getDataService().insertReloadEvents(
engine.getNodeService().findNode(
security.getNodeId()), false);
ts = System.currentTimeMillis() - ts;
if (ts > Constants.LONG_OPERATION_THRESHOLD) {
log.warn(
"Inserted reload events for node {} in {} ms",
security.getNodeId(), ts);
} else {
log.info(
"Inserted reload events for node {} in {} ms",
security.getNodeId(), ts);
}
}
} else {
List<NodeGroupLink> links = engine.getConfigurationService().getNodeGroupLinksFor(parameterService.getNodeGroupId());
if (links == null || links.size() == 0) {
log.warn("Could not queue up a load for {} because a node group link is NOT configured over which a load could be delivered", security.getNodeId());
} else {
log.warn("Could not queue up a load for {} because sync triggers has not yet run", security.getNodeId());
if (!syncTriggersBeforeInitialLoadAttempted) {
syncTriggersBeforeInitialLoadAttempted = true;
engine.getTriggerRouterService().syncTriggers();
}
}
}
}
}
}
}
}
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
} finally {
engine.getClusterService().unlock(ClusterConstants.SYNCTRIGGERS);
}
} else {
log.info("Not attempting to insert reload events because sync trigger is currently running");
}
}
protected void sendReverseInitialLoad() {
INodeService nodeService = engine.getNodeService();
boolean queuedLoad = false;
List<Node> nodes = new ArrayList<Node>();
nodes.addAll(nodeService.findTargetNodesFor(NodeGroupLinkAction.P));
nodes.addAll(nodeService.findTargetNodesFor(NodeGroupLinkAction.W));
for (Node node : nodes) {
engine.getDataService().insertReloadEvents(node, true);
queuedLoad = true;
}
if (!queuedLoad) {
log.info("{} was enabled but no nodes were linked to load",
ParameterConstants.AUTO_RELOAD_REVERSE_ENABLED);
}
}
/**
* We route data channel by channel for two reasons. One is that if/when we
* decide to multi-thread the routing it is a simple matter of inserting a
* thread pool here and waiting for all channels to be processed. The other
* reason is to reduce the number of connections we are required to have.
*/
protected int routeDataForEachChannel(DataGapDetector gapDetector) {
int dataCount = 0;
Node sourceNode = engine.getNodeService().findIdentity();
ProcessInfo processInfo = engine.getStatisticManager().newProcessInfo(
new ProcessInfoKey(sourceNode.getNodeId(), null, ProcessType.ROUTER_JOB));
try {
final List<NodeChannel> channels = engine.getConfigurationService().getNodeChannels(
false);
Map<String, List<TriggerRouter>> triggerRouters = engine.getTriggerRouterService()
.getTriggerRoutersByChannel(engine.getParameterService().getNodeGroupId());
for (NodeChannel nodeChannel : channels) {
if (nodeChannel.isEnabled()) {
processInfo.setCurrentChannelId(nodeChannel.getChannelId());
dataCount += routeDataForChannel(processInfo,
nodeChannel,
sourceNode,
producesCommonBatches(nodeChannel.getChannelId(),
triggerRouters.get(nodeChannel.getChannelId())), gapDetector);
} else {
if (log.isDebugEnabled()) {
log.debug(
"Not routing the {} channel. It is either disabled or suspended.",
nodeChannel.getChannelId());
}
}
}
processInfo.setStatus(ProcessInfo.Status.DONE);
} catch (RuntimeException ex) {
processInfo.setStatus(ProcessInfo.Status.ERROR);
throw ex;
}
return dataCount;
}
protected boolean producesCommonBatches(String channelId,
List<TriggerRouter> allTriggerRoutersForChannel) {
Boolean producesCommonBatches = !Constants.CHANNEL_CONFIG.equals(channelId)
&& !Constants.CHANNEL_FILESYNC.equals(channelId)
&& !Constants.CHANNEL_RELOAD.equals(channelId)
&& !Constants.CHANNEL_HEARTBEAT.equals(channelId) ? true : false;
String nodeGroupId = parameterService.getNodeGroupId();
if (allTriggerRoutersForChannel != null) {
for (TriggerRouter triggerRouter : allTriggerRoutersForChannel) {
IDataRouter dataRouter = getDataRouter(triggerRouter.getRouter());
/*
* If the data router is not a default data router or there will
* be incoming data on the channel where sync_on_incoming_batch
* is on, then we can not do 'optimal' routing. When
* sync_on_incoming_batch is on, then we might not be sending
* data to all nodes in a node_group. We can only do 'optimal'
* routing if data is going to go to all nodes in a group.
*/
if (triggerRouter.getRouter().getNodeGroupLink().getSourceNodeGroupId()
.equals(nodeGroupId)) {
if (!(dataRouter instanceof DefaultDataRouter)) {
producesCommonBatches = false;
break;
} else {
if (triggerRouter.getTrigger().isSyncOnIncomingBatch()) {
String tableName = triggerRouter.getTrigger()
.getFullyQualifiedSourceTableName();
for (TriggerRouter triggerRouter2 : allTriggerRoutersForChannel) {
if (triggerRouter2.getTrigger().getFullyQualifiedSourceTableName()
.equals(tableName)
&& triggerRouter2.getRouter().getNodeGroupLink()
.getTargetNodeGroupId().equals(nodeGroupId)) {
producesCommonBatches = false;
break;
}
}
}
}
}
}
}
if (!producesCommonBatches.equals(defaultRouterOnlyLastState.get(channelId))) {
if (producesCommonBatches) {
log.info("The '{}' channel is in common batch mode", channelId);
} else {
log.info("The '{}' channel is NOT in common batch mode", channelId);
}
defaultRouterOnlyLastState.put(channelId, producesCommonBatches);
}
return producesCommonBatches;
}
protected int routeDataForChannel(ProcessInfo processInfo, final NodeChannel nodeChannel, final Node sourceNode,
boolean produceCommonBatches, DataGapDetector gapDetector) {
ChannelRouterContext context = null;
long ts = System.currentTimeMillis();
int dataCount = -1;
try {
context = new ChannelRouterContext(sourceNode.getNodeId(), nodeChannel,
symmetricDialect.getPlatform().getSqlTemplate().startSqlTransaction());
context.setProduceCommonBatches(produceCommonBatches);
dataCount = selectDataAndRoute(processInfo, context);
return dataCount;
} catch (InterruptedException ex) {
log.warn("The routing process was interrupted. Rolling back changes");
if (context != null) {
context.rollback();
}
return 0;
} catch (SyntaxParsingException ex) {
log.error(
String.format(
"Failed to route and batch data on '%s' channel due to an invalid router expression",
nodeChannel.getChannelId()), ex);
if (context != null) {
context.rollback();
}
return 0;
} catch (Throwable ex) {
log.error(
String.format("Failed to route and batch data on '%s' channel",
nodeChannel.getChannelId()), ex);
if (context != null) {
context.rollback();
}
return 0;
} finally {
try {
if (dataCount > 0) {
long insertTs = System.currentTimeMillis();
engine.getDataService().insertDataEvents(context.getSqlTransaction(),
context.getDataEventList());
context.clearDataEventsList();
completeBatchesAndCommit(context);
context.incrementStat(System.currentTimeMillis() - insertTs,
ChannelRouterContext.STAT_INSERT_DATA_EVENTS_MS);
Data lastDataProcessed = context.getLastDataProcessed();
if (lastDataProcessed != null && lastDataProcessed.getDataId() > 0) {
String channelId = nodeChannel.getChannelId();
long queryTs = System.currentTimeMillis();
long dataLeftToRoute = sqlTemplate.queryForInt(
getSql("selectUnroutedCountForChannelSql"), channelId,
lastDataProcessed.getDataId());
queryTs = System.currentTimeMillis() - queryTs;
if (queryTs > Constants.LONG_OPERATION_THRESHOLD) {
log.warn("Unrouted query for channel {} took {} ms", channelId, queryTs);
}
engine.getStatisticManager().setDataUnRouted(channelId, dataLeftToRoute);
}
}
} catch (Exception e) {
if (context != null) {
context.rollback();
}
log.error(e.getMessage(), e);
} finally {
long totalTime = System.currentTimeMillis() - ts;
context.incrementStat(totalTime, ChannelRouterContext.STAT_ROUTE_TOTAL_TIME);
context.logStats(log, totalTime);
boolean detectGaps = context.isRequestGapDetection();
context.cleanup();
if (detectGaps) {
gapDetector.beforeRouting();
}
}
}
}
protected void completeBatchesAndCommit(ChannelRouterContext context) {
Set<IDataRouter> usedRouters = new HashSet<IDataRouter>(context.getUsedDataRouters());
List<OutgoingBatch> batches = new ArrayList<OutgoingBatch>(context.getBatchesByNodes()
.values());
context.commit();
for (OutgoingBatch batch : batches) {
batch.setRouterMillis(System.currentTimeMillis() - batch.getCreateTime().getTime());
for (IDataRouter dataRouter : usedRouters) {
dataRouter.completeBatch(context, batch);
}
if (Constants.UNROUTED_NODE_ID.equals(batch.getNodeId())) {
batch.setStatus(Status.OK);
} else {
batch.setStatus(Status.NE);
}
engine.getOutgoingBatchService().updateOutgoingBatch(batch);
context.getBatchesByNodes().remove(batch.getNodeId());
}
for (IDataRouter dataRouter : usedRouters) {
dataRouter.contextCommitted(context);
}
context.setNeedsCommitted(false);
}
protected Set<Node> findAvailableNodes(TriggerRouter triggerRouter, ChannelRouterContext context) {
Set<Node> nodes = context.getAvailableNodes().get(triggerRouter);
if (nodes == null) {
nodes = new HashSet<Node>();
Router router = triggerRouter.getRouter();
NodeGroupLink link = engine.getConfigurationService().getNodeGroupLinkFor(
router.getNodeGroupLink().getSourceNodeGroupId(),
router.getNodeGroupLink().getTargetNodeGroupId());
if (link != null) {
nodes.addAll(engine.getNodeService().findEnabledNodesFromNodeGroup(
router.getNodeGroupLink().getTargetNodeGroupId()));
} else {
log.error("The router {} has no node group link configured from {} to {}",
new Object[] { router.getRouterId(),
router.getNodeGroupLink().getSourceNodeGroupId(),
router.getNodeGroupLink().getTargetNodeGroupId() });
}
context.getAvailableNodes().put(triggerRouter, nodes);
}
return engine.getGroupletService().getTargetEnabled(triggerRouter, nodes);
}
protected IDataToRouteReader startReading(ChannelRouterContext context) {
IDataToRouteReader reader = new DataGapRouteReader(context, engine);
if (parameterService.is(ParameterConstants.SYNCHRONIZE_ALL_JOBS)) {
reader.run();
} else {
if (readThread == null) {
readThread = Executors.newCachedThreadPool(new ThreadFactory() {
final AtomicInteger threadNumber = new AtomicInteger(1);
final String namePrefix = parameterService.getEngineName()
.toLowerCase() + "-router-reader-";
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(namePrefix + threadNumber.getAndIncrement());
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
});
}
readThread.execute(reader);
}
return reader;
}
/**
* Pre-read data and fill up a queue so we can peek ahead to see if we have
* crossed a database transaction boundary. Then route each {@link Data}
* while continuing to keep the queue filled until the result set is
* entirely read.
*
* @param conn
* The connection to use for selecting the data.
* @param context
* The current context of the routing process
*/
protected int selectDataAndRoute(ProcessInfo processInfo, ChannelRouterContext context) throws InterruptedException {
IDataToRouteReader reader = startReading(context);
Data data = null;
Data nextData = null;
int totalDataCount = 0;
int totalDataEventCount = 0;
int statsDataCount = 0;
int statsDataEventCount = 0;
final int maxNumberOfEventsBeforeFlush = parameterService
.getInt(ParameterConstants.ROUTING_FLUSH_JDBC_BATCH_SIZE);
try {
nextData = reader.take();
do {
if (nextData != null) {
data = nextData;
nextData = reader.take();
if (data != null) {
processInfo.setCurrentTableName(data.getTableName());
processInfo.incrementDataCount();
boolean atTransactionBoundary = false;
if (nextData != null) {
String nextTxId = nextData.getTransactionId();
atTransactionBoundary = nextTxId == null
|| !nextTxId.equals(data.getTransactionId());
}
context.setEncountedTransactionBoundary(atTransactionBoundary);
statsDataCount++;
totalDataCount++;
int dataEventsInserted = routeData(processInfo, data, context);
statsDataEventCount += dataEventsInserted;
totalDataEventCount += dataEventsInserted;
long insertTs = System.currentTimeMillis();
try {
if (maxNumberOfEventsBeforeFlush <= context.getDataEventList().size()
|| context.isNeedsCommitted()) {
engine.getDataService().insertDataEvents(
context.getSqlTransaction(), context.getDataEventList());
context.clearDataEventsList();
}
if (context.isNeedsCommitted()) {
completeBatchesAndCommit(context);
}
} finally {
context.incrementStat(System.currentTimeMillis() - insertTs,
ChannelRouterContext.STAT_INSERT_DATA_EVENTS_MS);
if (statsDataCount > StatisticConstants.FLUSH_SIZE_ROUTER_DATA) {
engine.getStatisticManager().incrementDataRouted(
context.getChannel().getChannelId(), statsDataCount);
statsDataCount = 0;
engine.getStatisticManager().incrementDataEventInserted(
context.getChannel().getChannelId(), statsDataEventCount);
statsDataEventCount = 0;
}
}
context.setLastDataProcessed(data);
}
} else {
data = null;
}
} while (data != null);
} finally {
reader.setReading(false);
if (statsDataCount > 0) {
engine.getStatisticManager().incrementDataRouted(
context.getChannel().getChannelId(), statsDataCount);
}
if (statsDataEventCount > 0) {
engine.getStatisticManager().incrementDataEventInserted(
context.getChannel().getChannelId(), statsDataEventCount);
}
}
context.incrementStat(totalDataCount, ChannelRouterContext.STAT_DATA_ROUTED_COUNT);
return totalDataEventCount;
}
@SuppressWarnings("unchecked")
protected int routeData(ProcessInfo processInfo, Data data, ChannelRouterContext context) {
int numberOfDataEventsInserted = 0;
List<TriggerRouter> triggerRouters = getTriggerRoutersForData(data);
Table table = symmetricDialect.getTable(data.getTriggerHistory(), true);
if (triggerRouters != null && triggerRouters.size() > 0) {
for (TriggerRouter triggerRouter : triggerRouters) {
DataMetaData dataMetaData = new DataMetaData(data, table, triggerRouter.getRouter(),
context.getChannel());
Collection<String> nodeIds = null;
if (!context.getChannel().isIgnoreEnabled()
&& triggerRouter.isRouted(data.getDataEventType())) {
String targetNodeIds = data.getNodeList();
if (StringUtils.isNotBlank(targetNodeIds)) {
List<String> targetNodeIdsList = Arrays.asList(targetNodeIds.split(","));
nodeIds = CollectionUtils.intersection(targetNodeIdsList, toNodeIds(findAvailableNodes(triggerRouter, context)));
if (nodeIds.size() == 0) {
log.warn(
"None of the target nodes specified in the data.node_list field ({}) were qualified nodes. {} will not be routed",
targetNodeIds, data.getDataId());
}
} else {
IDataRouter dataRouter = getDataRouter(triggerRouter.getRouter());
context.addUsedDataRouter(dataRouter);
long ts = System.currentTimeMillis();
nodeIds = dataRouter.routeToNodes(context, dataMetaData,
findAvailableNodes(triggerRouter, context), false, false);
context.incrementStat(System.currentTimeMillis() - ts,
ChannelRouterContext.STAT_DATA_ROUTER_MS);
}
if (nodeIds != null) {
if (!triggerRouter.isPingBackEnabled() && data.getSourceNodeId() != null) {
nodeIds.remove(data.getSourceNodeId());
}
// should never route to self
nodeIds.remove(engine.getNodeService().findIdentityNodeId());
}
}
numberOfDataEventsInserted += insertDataEvents(processInfo, context, dataMetaData, nodeIds);
}
} else {
log.warn(
"Could not find trigger routers for trigger history id of {}. Not processing data with the data id of {}",
data.getTriggerHistory().getTriggerHistoryId(), data.getDataId());
numberOfDataEventsInserted += insertDataEvents(processInfo, context, new DataMetaData(data, table,
null, context.getChannel()), new HashSet<String>());
}
context.incrementStat(numberOfDataEventsInserted,
ChannelRouterContext.STAT_DATA_EVENTS_INSERTED);
return numberOfDataEventsInserted;
}
protected int insertDataEvents(ProcessInfo processInfo, ChannelRouterContext context, DataMetaData dataMetaData,
Collection<String> nodeIds) {
int numberOfDataEventsInserted = 0;
if (nodeIds == null || nodeIds.size() == 0) {
nodeIds = new HashSet<String>(1);
nodeIds.add(Constants.UNROUTED_NODE_ID);
}
long ts = System.currentTimeMillis();
long batchIdToReuse = -1;
boolean dataEventAdded = false;
for (String nodeId : nodeIds) {
if (nodeId != null) {
Map<String, OutgoingBatch> batches = context.getBatchesByNodes();
OutgoingBatch batch = batches.get(nodeId);
if (batch == null) {
batch = new OutgoingBatch(nodeId, dataMetaData.getNodeChannel().getChannelId(),
Status.RT);
batch.setBatchId(batchIdToReuse);
batch.setCommonFlag(context.isProduceCommonBatches());
log.debug(
"About to insert a new batch for node {} on the '{}' channel. Batches in progress are: {}.",
new Object[] { nodeId, batch.getChannelId(),
context.getBatchesByNodes().values() });
engine.getOutgoingBatchService().insertOutgoingBatch(batch);
processInfo.incrementBatchCount();
context.getBatchesByNodes().put(nodeId, batch);
// if in reuse mode, then share the batch id
if (context.isProduceCommonBatches()) {
batchIdToReuse = batch.getBatchId();
}
}
if (dataMetaData.getData().getDataEventType() == DataEventType.RELOAD) {
long loadId = context.getLastLoadId();
if (loadId < 0) {
loadId = engine.getSequenceService().nextVal(Constants.SEQUENCE_OUTGOING_BATCH_LOAD_ID);
context.setLastLoadId(loadId);
}
batch.setLoadId(loadId);
} else {
context.setLastLoadId(-1);
}
batch.incrementEventCount(dataMetaData.getData().getDataEventType());
batch.incrementDataEventCount();
if (!context.isProduceCommonBatches()
|| (context.isProduceCommonBatches() && !dataEventAdded)) {
Router router = dataMetaData.getRouter();
context.addDataEvent(dataMetaData.getData().getDataId(), batch.getBatchId(),
router != null ? router.getRouterId()
: Constants.UNKNOWN_ROUTER_ID);
numberOfDataEventsInserted++;
dataEventAdded = true;
}
if (batchAlgorithms.get(context.getChannel().getBatchAlgorithm()).isBatchComplete(
batch, dataMetaData, context)) {
context.setNeedsCommitted(true);
}
}
}
context.incrementStat(System.currentTimeMillis() - ts,
ChannelRouterContext.STAT_INSERT_DATA_EVENTS_MS);
return numberOfDataEventsInserted;
}
protected IDataRouter getDataRouter(Router router) {
IDataRouter dataRouter = null;
if (!StringUtils.isBlank(router.getRouterType())) {
dataRouter = routers.get(router.getRouterType());
if (dataRouter == null) {
log.warn(
"Could not find configured router type of {} with the id of {}. Defaulting the router",
router.getRouterType(), router.getRouterId());
}
}
if (dataRouter == null) {
return routers.get("default");
}
return dataRouter;
}
protected List<TriggerRouter> getTriggerRoutersForData(Data data) {
List<TriggerRouter> triggerRouters = null;
if (data != null) {
if (data.getTriggerHistory() != null) {
triggerRouters = engine.getTriggerRouterService()
.getTriggerRoutersForCurrentNode(false)
.get((data.getTriggerHistory().getTriggerId()));
if (triggerRouters == null || triggerRouters.size() == 0) {
triggerRouters = engine.getTriggerRouterService()
.getTriggerRoutersForCurrentNode(true)
.get((data.getTriggerHistory().getTriggerId()));
}
} else {
log.warn(
"Could not find a trigger hist record for recorded data {}. Was the trigger hist record deleted manually?",
data.getDataId());
}
}
return triggerRouters;
}
public void addDataRouter(String name, IDataRouter dataRouter) {
routers.put(name, dataRouter);
}
public void addBatchAlgorithm(String name, IBatchAlgorithm algorithm) {
batchAlgorithms.put(name, algorithm);
}
public long getUnroutedDataCount() {
long maxDataIdAlreadyRouted = sqlTemplate
.queryForLong(getSql("selectLastDataIdRoutedUsingDataGapSql"));
long leftToRoute = engine.getDataService().findMaxDataId() - maxDataIdAlreadyRouted;
List<DataGap> gaps = engine.getDataService().findDataGaps();
for (int i = 0; i < gaps.size()-2; i++) {
DataGap gap = gaps.get(i);
leftToRoute += (gap.getEndId() - gap.getStartId());
}
if (leftToRoute > 0) {
return leftToRoute;
} else {
return 0;
}
}
public List<String> getAvailableBatchAlgorithms() {
return new ArrayList<String>(batchAlgorithms.keySet());
}
public Map<String, IDataRouter> getRouters() {
return routers;
}
}