-
Notifications
You must be signed in to change notification settings - Fork 612
/
DefaultExecutorService.java
1186 lines (1046 loc) · 43.3 KB
/
DefaultExecutorService.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
package org.infinispan.distexec;
import static org.infinispan.factories.KnownComponentNames.CACHE_MARSHALLER;
import java.io.Externalizable;
import java.io.NotSerializableException;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import org.infinispan.AdvancedCache;
import org.infinispan.Cache;
import org.infinispan.commands.CancelCommand;
import org.infinispan.commands.CancellationService;
import org.infinispan.commands.CommandsFactory;
import org.infinispan.commands.read.DistributedExecuteCommand;
import org.infinispan.commons.marshall.Marshaller;
import org.infinispan.commons.marshall.StreamingMarshaller;
import org.infinispan.commons.util.InfinispanCollections;
import org.infinispan.commons.util.Util;
import org.infinispan.commons.util.concurrent.FutureListener;
import org.infinispan.commons.util.concurrent.NoOpFuture;
import org.infinispan.commons.util.concurrent.NotifyingFuture;
import org.infinispan.commons.util.concurrent.NotifyingFutureImpl;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.distexec.spi.DistributedTaskLifecycleService;
import org.infinispan.distribution.DistributionManager;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.interceptors.InterceptorChain;
import org.infinispan.interceptors.locking.ClusteringDependentLogic;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.remoting.responses.Response;
import org.infinispan.remoting.responses.SuccessfulResponse;
import org.infinispan.remoting.rpc.ResponseMode;
import org.infinispan.remoting.rpc.RpcManager;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.TopologyAwareAddress;
import org.infinispan.remoting.transport.jgroups.SuspectException;
import org.infinispan.security.AuthorizationManager;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.util.TimeService;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* Infinispan's implementation of an {@link ExecutorService} and {@link DistributedExecutorService}.
* This ExecutorService provides methods to submit tasks for an execution on a cluster of Infinispan
* nodes.
* <p>
*
*
* Note that due to potential task migration to another nodes every {@link Callable},
* {@link Runnable} and/or {@link DistributedCallable} submitted must be either {@link Serializable}
* or {@link Externalizable}. Also the value returned from a callable must be {@link Serializable}
* or {@link Externalizable}. Unfortunately if the value returned is not serializable then a
* {@link NotSerializableException} will be thrown.
*
* @author Vladimir Blagojevic
* @since 5.0
*
*/
public class DefaultExecutorService extends AbstractExecutorService implements DistributedExecutorService {
private static final NodeFilter SAME_MACHINE_FILTER = new NodeFilter(){
@Override
public boolean include(TopologyAwareAddress thisAddress, TopologyAwareAddress otherAddress) {
return thisAddress.isSameMachine(otherAddress);
};
};
private static final NodeFilter SAME_RACK_FILTER = new NodeFilter(){
@Override
public boolean include(TopologyAwareAddress thisAddress, TopologyAwareAddress otherAddress) {
return thisAddress.isSameRack(otherAddress);
};
};
private static final NodeFilter SAME_SITE_FILTER = new NodeFilter(){
@Override
public boolean include(TopologyAwareAddress thisAddress, TopologyAwareAddress otherAddress) {
return thisAddress.isSameSite(otherAddress);
};
};
private static final NodeFilter ALL_FILTER = new NodeFilter(){
@Override
public boolean include(TopologyAwareAddress thisAddress, TopologyAwareAddress otherAddress) {
return true;
};
};
public static final DistributedTaskFailoverPolicy NO_FAILOVER = new NoTaskFailoverPolicy();
public static final DistributedTaskFailoverPolicy RANDOM_NODE_FAILOVER = new RandomNodeTaskFailoverPolicy();
private static final Log log = LogFactory.getLog(DefaultExecutorService.class);
private static final boolean trace = log.isTraceEnabled();
protected final AtomicBoolean isShutdown = new AtomicBoolean(false);
protected final AdvancedCache cache;
protected final RpcManager rpc;
protected final InterceptorChain invoker;
protected final CommandsFactory factory;
protected final Marshaller marshaller;
protected final ExecutorService localExecutorService;
protected final CancellationService cancellationService;
protected final ClusteringDependentLogic clusterDependentLogic;
protected final boolean takeExecutorOwnership;
private final TimeService timeService;
/**
* Creates a new DefaultExecutorService given a master cache node for local task execution. All
* distributed task executions will be initiated from this Infinispan cache node
*
* @param masterCacheNode
* Cache node initiating distributed task
*/
public DefaultExecutorService(Cache<?, ?> masterCacheNode) {
this(masterCacheNode, Executors.newSingleThreadExecutor(), true);
}
/**
* Creates a new DefaultExecutorService given a master cache node and an ExecutorService for
* parallel execution of tasks ran on this node. All distributed task executions will be
* initiated from this Infinispan cache node.
* <p>
* Note that DefaultExecutorService will not shutdown client supplied localExecutorService once
* this DefaultExecutorService is shutdown. Lifecycle management of a supplied ExecutorService is
* left to the client
*
* Also note that client supplied ExecutorService should not execute tasks in the caller's thread
* ( i.e rejectionHandler of {@link ThreadPoolExecutor} configured with {link
* {@link ThreadPoolExecutor.CallerRunsPolicy})
*
* @param masterCacheNode
* Cache node initiating distributed task
* @param localExecutorService
* ExecutorService to run local tasks
*/
public DefaultExecutorService(Cache<?, ?> masterCacheNode, ExecutorService localExecutorService) {
this(masterCacheNode, localExecutorService, false);
}
/**
* Creates a new DefaultExecutorService given a master cache node and an ExecutorService for
* parallel execution of task ran on this node. All distributed task executions will be initiated
* from this Infinispan cache node.
*
* @param masterCacheNode
* Cache node initiating distributed task
* @param localExecutorService
* ExecutorService to run local tasks
* @param takeExecutorOwnership
* if true {@link DistributedExecutorService#shutdown()} and
* {@link DistributedExecutorService#shutdownNow()} method will shutdown
* localExecutorService as well
*
*/
public DefaultExecutorService(Cache<?, ?> masterCacheNode, ExecutorService localExecutorService,
boolean takeExecutorOwnership) {
super();
if (masterCacheNode == null)
throw new IllegalArgumentException("Can not use null cache for DefaultExecutorService");
else if (localExecutorService == null)
throw new IllegalArgumentException("Can not use null instance of ExecutorService");
else {
try {
if (localExecutorService.isShutdown())
throw new IllegalArgumentException("Can not use an instance of ExecutorService which is shutdown");
} catch (IllegalStateException e) {
if (takeExecutorOwnership) {
throw new IllegalArgumentException("Can not take ownership of a ManagedExecutorService");
}
}
}
ensureAccessPermissions(masterCacheNode.getAdvancedCache());
ensureProperCacheState(masterCacheNode.getAdvancedCache());
this.cache = masterCacheNode.getAdvancedCache();
ComponentRegistry registry = SecurityActions.getCacheComponentRegistry(cache);
this.rpc = SecurityActions.getCacheRpcManager(cache);
this.invoker = registry.getComponent(InterceptorChain.class);
this.factory = registry.getComponent(CommandsFactory.class);
this.marshaller = registry.getComponent(StreamingMarshaller.class, CACHE_MARSHALLER);
this.cancellationService = registry.getComponent(CancellationService.class);
this.localExecutorService = localExecutorService;
this.takeExecutorOwnership = takeExecutorOwnership;
this.timeService = registry.getTimeService();
this.clusterDependentLogic = registry.getComponent(ClusteringDependentLogic.class);
}
@Override
public <T> DistributedTaskBuilder<T> createDistributedTaskBuilder(Callable<T> callable) {
Configuration cacheConfiguration = SecurityActions.getCacheConfiguration(cache);
long to = cacheConfiguration.clustering().sync().replTimeout();
DistributedTaskBuilder<T> dtb = new DefaultDistributedTaskBuilder<T>(to);
dtb.callable(callable);
return dtb;
}
@Override
public <T> NotifyingFuture<T> submit(Runnable task, T result) {
return (NotifyingFuture<T>) super.submit(task, result);
}
@Override
public <T> NotifyingFuture<T> submit(Callable<T> task) {
return (NotifyingFuture<T>) super.submit(task);
}
@Override
public void shutdown() {
realShutdown(false);
}
protected List<Address> getMembers() {
if (rpc != null) {
return rpc.getMembers();
} else {
return Collections.singletonList(getAddress());
}
}
protected <T> List<Address> executionCandidates(DistributedTask<T> task) {
return filterMembers(task.getTaskExecutionPolicy(), getMembers());
}
private Address getAddress() {
return clusterDependentLogic.getAddress();
}
private List<Runnable> realShutdown(boolean interrupt) {
isShutdown.set(true);
// TODO cancel all tasks
if (takeExecutorOwnership) {
if (interrupt)
localExecutorService.shutdownNow();
else
localExecutorService.shutdown();
}
return InfinispanCollections.emptyList();
}
@Override
public List<Runnable> shutdownNow() {
return realShutdown(true);
}
@Override
public boolean isShutdown() {
return isShutdown.get();
}
@Override
public boolean isTerminated() {
if (isShutdown.get()) {
// TODO account for all tasks
return true;
}
return false;
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
//long nanoTimeWait = unit.toNanos(timeout);
// TODO wait for all tasks to finish
return true;
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException,
ExecutionException {
try {
return doInvokeAny(tasks, false, 0);
} catch (TimeoutException cannotHappen) {
assert false;
return null;
}
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return doInvokeAny(tasks, true, unit.toNanos(timeout));
}
/**
* the main mechanics of invokeAny. This was essentially copied from
* {@link AbstractExecutorService} doInvokeAny except that we replaced the
* {@link ExecutorCompletionService} with our {@link DistributedExecutionCompletionService}.
*/
private <T> T doInvokeAny(Collection<? extends Callable<T>> tasks, boolean timed, long nanos)
throws InterruptedException, ExecutionException, TimeoutException {
if (tasks == null)
throw new NullPointerException();
int ntasks = tasks.size();
if (ntasks == 0)
throw new IllegalArgumentException();
List<Future<T>> futures = new ArrayList<Future<T>>(ntasks);
CompletionService<T> ecs = new DistributedExecutionCompletionService<T>(this);
// For efficiency, especially in executors with limited
// parallelism, check to see if previously submitted tasks are
// done before submitting more of them. This interleaving
// plus the exception mechanics account for messiness of main
// loop.
try {
// Record exceptions so that if we fail to obtain any
// result, we can throw the last exception we got.
ExecutionException ee = null;
long lastTime = (timed) ? timeService.time() : 0;
Iterator<? extends Callable<T>> it = tasks.iterator();
// Start one task for sure; the rest incrementally
futures.add(ecs.submit(it.next()));
--ntasks;
int active = 1;
for (;;) {
Future<T> f = ecs.poll();
if (f == null) {
if (ntasks > 0) {
--ntasks;
futures.add(ecs.submit(it.next()));
++active;
} else if (active == 0)
break;
else if (timed) {
f = ecs.poll(nanos, TimeUnit.NANOSECONDS);
if (f == null)
throw new TimeoutException();
long now = timeService.time();
nanos -= timeService.timeDuration(lastTime, now, TimeUnit.NANOSECONDS);
lastTime = now;
} else
f = ecs.take();
}
if (f != null) {
--active;
try {
return f.get();
} catch (InterruptedException ie) {
throw ie;
} catch (ExecutionException eex) {
ee = eex;
} catch (RuntimeException rex) {
ee = new ExecutionException(rex);
}
}
}
if (ee == null)
ee = new ExecutionException() {
private static final long serialVersionUID = 200818694545553992L;
};
throw ee;
} finally {
for (Future<T> f : futures)
f.cancel(true);
}
}
@Override
public void execute(Runnable command) {
if (!isShutdown.get()) {
DistributedTaskPart<Object> cmd;
if (command instanceof DistributedTaskPart<?>) {
cmd = (DistributedTaskPart<Object>) command;
} else if (command instanceof Serializable) {
cmd = (DistributedTaskPart<Object>) newTaskFor(command, null);
} else {
throw new IllegalArgumentException("Runnable command is not Serializable " + command);
}
cmd.execute();
} else {
throw new RejectedExecutionException();
}
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
if (runnable == null) throw new NullPointerException();
RunnableAdapter<T> adapter = new RunnableAdapter<T>(runnable, value);
return newTaskFor(adapter);
}
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
if (callable == null) throw new NullPointerException();
DistributedTaskBuilder<T> distributedTaskBuilder = createDistributedTaskBuilder(callable);
DistributedTask<T> task = distributedTaskBuilder.build();
DistributedExecuteCommand<T> executeCommand = factory.buildDistributedExecuteCommand(
callable, getAddress(), null);
return createDistributedTaskPart(task, executeCommand, selectExecutionNode(task), 0);
}
@Override
public <T> NotifyingFuture<T> submit(Address target, Callable<T> task) {
DistributedTaskBuilder<T> distributedTaskBuilder = createDistributedTaskBuilder(task);
DistributedTask<T> distributedTask = distributedTaskBuilder.build();
return submit(target, distributedTask);
}
@Override
public <T> NotifyingFuture<T> submit(Address target, DistributedTask<T> task) {
if (task == null)
throw new NullPointerException();
if (target == null)
throw new NullPointerException();
List<Address> members = getMembers();
if (!members.contains(target)) {
return new NoOpFuture<>(new SuspectException("Target node " + target
+ " is not a cluster member, members are " + members));
}
Address me = getAddress();
DistributedExecuteCommand<T> c = null;
if (target.equals(me)) {
c = factory.buildDistributedExecuteCommand(clone(task.getCallable()), me, null);
} else {
c = factory.buildDistributedExecuteCommand(task.getCallable(), me, null);
}
DistributedTaskPart<T> part = createDistributedTaskPart(task, c, target, 0);
part.execute();
return part;
}
@Override
public <T, K> NotifyingFuture<T> submit(Callable<T> task, K... input) {
DistributedTaskBuilder<T> distributedTaskBuilder = createDistributedTaskBuilder(task);
DistributedTask<T> distributedTask = distributedTaskBuilder.build();
return submit(distributedTask, input);
}
@Override
public <T, K> NotifyingFuture<T> submit(DistributedTask<T> task, K... input) {
if (task == null) throw new NullPointerException();
if(inputKeysSpecified(input)){
Map<Address, List<K>> nodesKeysMap = keysToExecutionNodes(task.getTaskExecutionPolicy(), input);
checkExecutionPolicy(task, nodesKeysMap, input);
Address me = getAddress();
DistributedExecuteCommand<T> c = factory.buildDistributedExecuteCommand(task.getCallable(), me, Arrays.asList(input));
ArrayList<Address> nodes = new ArrayList<Address>(nodesKeysMap.keySet());
DistributedTaskPart<T> part = createDistributedTaskPart(task, c, Arrays.asList(input), selectExecutionNode(nodes), 0);
part.execute();
return part;
} else {
return submit(task.getCallable());
}
}
@Override
public <T> List<Future<T>> submitEverywhere(Callable<T> task) {
DistributedTaskBuilder<T> distributedTaskBuilder = createDistributedTaskBuilder(task);
DistributedTask<T> distributedTask = distributedTaskBuilder.build();
return submitEverywhere(distributedTask);
}
@Override
public <T> List<Future<T>> submitEverywhere(DistributedTask<T> task) {
if (task == null) throw new NullPointerException();
List<Address> members = executionCandidates(task);
List<Future<T>> futures = new ArrayList<Future<T>>(members.size());
Address me = getAddress();
for (Address target : members) {
DistributedExecuteCommand<T> c = null;
if (target.equals(me)) {
c = factory.buildDistributedExecuteCommand(clone(task.getCallable()), me, null);
} else {
c = factory.buildDistributedExecuteCommand(task.getCallable(), me, null);
}
DistributedTaskPart<T> part = createDistributedTaskPart(task, c, target, 0);
futures.add(part);
part.execute();
}
return futures;
}
@Override
public <T, K> List<Future<T>> submitEverywhere(Callable<T> task, K... input) {
DistributedTaskBuilder<T> distributedTaskBuilder = createDistributedTaskBuilder(task);
DistributedTask<T> distributedTask = distributedTaskBuilder.build();
return submitEverywhere(distributedTask, input);
}
@Override
public <T, K> List<Future<T>> submitEverywhere(DistributedTask<T> task, K... input) {
if (task == null) throw new NullPointerException();
if(inputKeysSpecified(input)) {
List<Future<T>> futures = new ArrayList<Future<T>>(input.length * 2);
Address me = getAddress();
Map<Address, List<K>> nodesKeysMap = keysToExecutionNodes(task.getTaskExecutionPolicy(), input);
checkExecutionPolicy(task, nodesKeysMap, input);
for (Entry<Address, List<K>> e : nodesKeysMap.entrySet()) {
Address target = e.getKey();
DistributedExecuteCommand<T> c = null;
if (target.equals(me)) {
c = factory.buildDistributedExecuteCommand(clone(task.getCallable()), me, e.getValue());
} else {
c = factory.buildDistributedExecuteCommand(task.getCallable(), me, e.getValue());
}
DistributedTaskPart<T> part = createDistributedTaskPart(task, c, e.getValue(), target, 0);
futures.add(part);
part.execute();
}
return futures;
} else {
return submitEverywhere(task);
}
}
protected <T> Callable<T> clone(Callable<T> task){
return Util.cloneWithMarshaller(marshaller, task);
}
protected <T, K> DistributedTaskPart<T> createDistributedTaskPart(DistributedTask<T> task,
DistributedExecuteCommand<T> c, List<K> inputKeys, Address target,
int failoverCount) {
return getAddress().equals(target) ?
new LocalDistributedTaskPart<T>(task, c, (List<Object>) inputKeys, failoverCount) :
new RemoteDistributedTaskPart<T>(task, c, (List<Object>) inputKeys, target, failoverCount);
}
protected <T, K> DistributedTaskPart<T> createDistributedTaskPart(DistributedTask<T> task,
DistributedExecuteCommand<T> c, Address target, int failoverCount) {
return createDistributedTaskPart(task, c, Collections.emptyList(), target, failoverCount);
}
private <T, K> void checkExecutionPolicy(DistributedTask<T> task,
Map<Address, List<K>> nodesKeysMap, K... input) {
if (nodesKeysMap == null || nodesKeysMap.isEmpty()) {
throw new IllegalStateException("DistributedTaskExecutionPolicy "
+ task.getTaskExecutionPolicy() + " for task " + task
+ " returned invalid keysToExecutionNodes " + nodesKeysMap
+ " execution policy plan for a given input " + Arrays.toString(input));
}
}
private <K> boolean inputKeysSpecified(K...input){
return input != null && input.length > 0;
}
protected Address selectExecutionNode(List<Address> candidates) {
List<Address> list = randomClusterMembers(candidates,1);
return list.get(0);
}
protected <T> Address selectExecutionNode(DistributedTask <T> task) {
return selectExecutionNode(executionCandidates(task));
}
protected List<Address> randomClusterMembers(final List<Address> members, int numNeeded) {
if(members == null || members.isEmpty())
throw new IllegalArgumentException("Invalid member list " + members);
if (members.size() < numNeeded) {
log.cannotSelectRandomMembers(numNeeded, members);
numNeeded = members.size();
}
List<Address> membersCopy = new ArrayList<Address>(members);
List<Address> chosen = new ArrayList<Address>(numNeeded);
Random r = new Random();
while (!membersCopy.isEmpty() && numNeeded >= chosen.size()) {
int count = membersCopy.size();
Address address = membersCopy.remove(r.nextInt(count));
chosen.add(address);
}
return chosen;
}
protected <K> Map<Address, List<K>> keysToExecutionNodes(DistributedTaskExecutionPolicy policy, K... input) {
DistributionManager dm = cache.getDistributionManager();
Map<Address, List<K>> addressToKey = new HashMap<Address, List<K>>(input.length * 2);
boolean usingREPLMode = dm == null;
for (K key : input) {
Address ownerOfKey = null;
if (usingREPLMode) {
List<Address> members = new ArrayList<Address>(getMembers());
members = filterMembers(policy, members);
// using REPL mode https://issues.jboss.org/browse/ISPN-1886
// since keys and values are on all nodes, lets just pick randomly
Collections.shuffle(members);
ownerOfKey = members.get(0);
} else {
// DIST mode
List<Address> owners = dm.locate(key);
List<Address> filtered = filterMembers(policy, owners);
if(!filtered.isEmpty()){
ownerOfKey = filtered.get(0);
} else {
ownerOfKey = owners.get(0);
}
}
List<K> keysAtNode = addressToKey.get(ownerOfKey);
if (keysAtNode == null) {
keysAtNode = new LinkedList<K>();
addressToKey.put(ownerOfKey, keysAtNode);
}
keysAtNode.add(key);
}
return addressToKey;
}
private List<Address> filterMembers(DistributedTaskExecutionPolicy policy, List<Address> members) {
NodeFilter filter = null;
switch (policy) {
case SAME_MACHINE:
filter = SAME_MACHINE_FILTER;
break;
case SAME_SITE:
filter = SAME_SITE_FILTER;
break;
case SAME_RACK:
filter = SAME_RACK_FILTER;
break;
case ALL:
filter = ALL_FILTER;
break;
default:
filter = ALL_FILTER;
break;
}
List<Address> result = new ArrayList<Address>();
for (Address address : members) {
if(address instanceof TopologyAwareAddress){
TopologyAwareAddress taa = (TopologyAwareAddress)address;
if(filter.include(taa, (TopologyAwareAddress)getAddress())){
result.add(address);
}
} else {
result.add(address);
}
}
return result;
}
private void ensureAccessPermissions(final AdvancedCache<?, ?> cache) {
AuthorizationManager authorizationManager = SecurityActions.getCacheAuthorizationManager(cache);
if (authorizationManager != null) {
authorizationManager.checkPermission(AuthorizationPermission.EXEC);
}
}
private void ensureProperCacheState(AdvancedCache<?, ?> cache) throws NullPointerException,
IllegalStateException {
// We allow for INITIALIZING state so the ExecutorService can be used by components defining a method with
// {@link Start} annotation
if (cache.getStatus() != ComponentStatus.RUNNING && cache.getStatus() != ComponentStatus.INITIALIZING)
throw new IllegalStateException("Invalid cache state " + cache.getStatus());
}
private static class RandomNodeTaskFailoverPolicy implements DistributedTaskFailoverPolicy {
public RandomNodeTaskFailoverPolicy() {
super();
}
@Override
public Address failover(FailoverContext fc) {
return randomNode(fc.executionCandidates(),fc.executionFailureLocation());
}
protected Address randomNode(List<Address> candidates, Address failedExecutionLocation){
Random r = new Random();
candidates.remove(failedExecutionLocation);
if (candidates.isEmpty())
throw new IllegalStateException("There are no candidates for failover: " + candidates);
int tIndex = r.nextInt(candidates.size());
return candidates.get(tIndex);
}
@Override
public int maxFailoverAttempts() {
return 1;
}
}
private static class NoTaskFailoverPolicy implements DistributedTaskFailoverPolicy {
public NoTaskFailoverPolicy() {
super();
}
@Override
public Address failover(FailoverContext fc) {
return fc.executionFailureLocation();
}
@Override
public int maxFailoverAttempts() {
return 0;
}
}
/**
* NodeFilter allows selection of nodes according to {@link DistributedTaskExecutionPolicy}
*/
interface NodeFilter {
boolean include(TopologyAwareAddress thisAddress, TopologyAwareAddress otherAddress);
}
private class DefaultDistributedTaskBuilder<T> implements DistributedTaskBuilder<T>, DistributedTask<T>{
private Callable<T> callable;
private long timeout;
private DistributedTaskExecutionPolicy executionPolicy = DistributedTaskExecutionPolicy.ALL;
private DistributedTaskFailoverPolicy failoverPolicy = NO_FAILOVER;
public DefaultDistributedTaskBuilder(long taskTimeout) {
this.timeout = taskTimeout;
}
@Override
public DistributedTaskBuilder<T> callable(Callable<T> callable) {
if (callable == null)
throw new IllegalArgumentException("Callable cannot be null");
this.callable = callable;
return this;
}
@Override
public DistributedTaskBuilder<T> timeout(long t, TimeUnit tu) {
timeout = TimeUnit.MILLISECONDS.convert(t, tu);
return this;
}
@Override
public DistributedTaskBuilder<T> executionPolicy(DistributedTaskExecutionPolicy policy) {
if (policy == null)
throw new IllegalArgumentException("DistributedTaskExecutionPolicy cannot be null");
this.executionPolicy = policy;
return this;
}
@Override
public DistributedTaskBuilder<T> failoverPolicy(DistributedTaskFailoverPolicy policy) {
if (policy == null) {
this.failoverPolicy = NO_FAILOVER;
} else {
this.failoverPolicy = policy;
}
return this;
}
@Override
public DistributedTask<T> build() {
DefaultDistributedTaskBuilder<T> task = new DefaultDistributedTaskBuilder<T>(timeout);
task.callable(callable);
task.executionPolicy(executionPolicy);
task.failoverPolicy(failoverPolicy);
return task;
}
@Override
public long timeout() {
return timeout;
}
@Override
public DistributedTaskExecutionPolicy getTaskExecutionPolicy() {
return executionPolicy;
}
@Override
public DistributedTaskFailoverPolicy getTaskFailoverPolicy() {
return failoverPolicy;
}
@Override
public Callable<T> getCallable() {
return callable;
}
}
/**
* DistributedTaskPart represents a unit of work sent to remote VM and executed there
*
*
* @author Mircea Markus
* @author Vladimir Blagojevic
*/
private abstract class DistributedTaskPart<V> implements NotifyingFuture<V>, RunnableFuture<V> {
protected final DistributedExecuteCommand<V> distCommand;
private final List<Object> inputKeys;
private final DistributedTask<V> owningTask;
private int failedOverCount;
private volatile boolean cancelled;
protected DistributedTaskPart(List<Object> inputKeys, DistributedExecuteCommand<V> command, DistributedTask<V> task, int failedOverCount) {
this.inputKeys = inputKeys;
this.distCommand = command;
this.owningTask = task;
this.failedOverCount = failedOverCount;
}
public List<Object> getInputKeys() {
return inputKeys;
}
public DistributedExecuteCommand<V> getCommand() {
return distCommand;
}
public DistributedTask<V> getOwningTask() {
return owningTask;
}
public abstract Address getExecutionTarget();
private DefaultExecutorService getOuterType() {
return DefaultExecutorService.this;
}
public abstract void execute();
@Override
public void run() {
//intentionally empty
}
@Override
public boolean isCancelled() {
return cancelled;
}
@Override
public V get() throws InterruptedException, ExecutionException {
try {
return innerGet(0, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
throw new ExecutionException(e);
}
}
@Override
public V get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
return innerGet(timeout, unit);
}
protected V innerGet(long timeout, TimeUnit unit)
throws ExecutionException, TimeoutException, InterruptedException {
if (isCancelled())
throw new CancellationException("Task already cancelled");
long timeoutNanos = computeTimeoutNanos(timeout, unit);
long endNanos = timeService.expectedEndTime(timeoutNanos, TimeUnit.NANOSECONDS);
try {
return getResult(timeoutNanos);
} catch (TimeoutException te) {
throw te;
} catch (Exception e) {
// The RPC could have finished with a org.infinispan.util.concurrent.TimeoutException right before
// the Future.get timeout expired. If that's the case, we want to throw a TimeoutException.
long remainingNanos = timeoutNanos > 0 ? timeService.remainingTime(endNanos, TimeUnit.NANOSECONDS) : timeoutNanos;
if (timeoutNanos > 0 && remainingNanos <= 0) {
if (trace) log.tracef("Distributed task timed out, throwing a TimeoutException and ignoring exception", e);
throw new TimeoutException();
}
boolean canFailover = failedOverCount++ < getOwningTask().getTaskFailoverPolicy().maxFailoverAttempts();
if (canFailover) {
try {
return failoverExecution(e, timeoutNanos, TimeUnit.NANOSECONDS);
} catch (Exception failedOver) {
throw wrapIntoExecutionException(failedOver);
}
} else {
throw wrapIntoExecutionException(e);
}
}
}
protected abstract V getResult(long timeoutNanos) throws Exception;
protected long computeTimeoutNanos(long timeout, TimeUnit unit) {
long taskTimeout = TimeUnit.MILLISECONDS.toNanos(getOwningTask().timeout());
long futureTimeout = TimeUnit.NANOSECONDS.convert(timeout, unit);
long actualTimeout;
if (taskTimeout > 0 && futureTimeout > 0) {
actualTimeout = Math.min(taskTimeout, futureTimeout);
} else {
actualTimeout = Math.max(taskTimeout, futureTimeout);
}
return actualTimeout;
}
protected ExecutionException wrapIntoExecutionException(Exception e){
if (e instanceof ExecutionException) {
return (ExecutionException) e;
} else {
return new ExecutionException(e);
}
}
protected V failoverExecution(final Exception cause, long timeout, TimeUnit unit)
throws Exception {
final List<Address> executionCandidates = executionCandidates(getOwningTask());
FailoverContext fc = new FailoverContext() {
@Override
public <K> List<K> inputKeys() {
return (List<K>) getInputKeys();
}
@Override
public Address executionFailureLocation() {
return getExecutionTarget();
}
@Override
public List<Address> executionCandidates() {
return executionCandidates;
}
@Override
public Throwable cause() {
return cause;
}
};
Address failoverTarget = getOwningTask().getTaskFailoverPolicy().failover(fc);
log.distributedTaskFailover(fc.executionFailureLocation(), failoverTarget, cause);
DistributedTaskPart<V> part = createDistributedTaskPart(owningTask, distCommand,
getInputKeys(), failoverTarget, failedOverCount);
part.execute();
return part.get(timeout, unit);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((distCommand == null) ? 0 : distCommand.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof DistributedTaskPart)) {
return false;
}
DistributedTaskPart other = (DistributedTaskPart) obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (distCommand == null) {
if (other.distCommand != null) {
return false;
}
} else if (!distCommand.equals(other.distCommand)) {
return false;
}
return true;
}
protected void setCancelled() {
cancelled = true;
}
}
private class RemoteDistributedTaskPart<V> extends DistributedTaskPart<V> {
private final Address executionTarget;
private final NotifyingFutureImpl<Object> future = new NotifyingFutureImpl<Object>();
public RemoteDistributedTaskPart(DistributedTask<V> task, DistributedExecuteCommand<V> command,
List<Object> inputKeys, Address executionTarget, int failoverCount) {
super(inputKeys, command, task, failoverCount);
if (getAddress().equals(executionTarget)) {
throw new IllegalArgumentException("This task should be executed as local.");
}
this.executionTarget = executionTarget;
}
@Override
public Address getExecutionTarget() {
return executionTarget;
}
@Override
public void execute() {
if (trace) log.tracef("Sending %s to remote execution at node %s", this, getExecutionTarget());
try {
rpc.invokeRemotelyInFuture(Collections.singletonList(getExecutionTarget()), getCommand(),
rpc.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS)