forked from infinispan/infinispan
-
Notifications
You must be signed in to change notification settings - Fork 2
/
DefaultCacheManager.java
1213 lines (1077 loc) · 50.7 KB
/
DefaultCacheManager.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.manager;
import static org.infinispan.factories.KnownComponentNames.CACHE_DEPENDENCY_GRAPH;
import static org.infinispan.util.logging.Log.CONFIG;
import static org.infinispan.util.logging.Log.CONTAINER;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
import java.util.StringJoiner;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.security.auth.Subject;
import org.infinispan.Cache;
import org.infinispan.commons.CacheConfigurationException;
import org.infinispan.commons.CacheException;
import org.infinispan.commons.IllegalLifecycleStateException;
import org.infinispan.commons.api.CacheContainerAdmin;
import org.infinispan.commons.api.Lifecycle;
import org.infinispan.commons.configuration.ClassAllowList;
import org.infinispan.commons.dataconversion.MediaType;
import org.infinispan.commons.util.FileLookupFactory;
import org.infinispan.commons.util.Immutables;
import org.infinispan.configuration.ConfigurationManager;
import org.infinispan.configuration.cache.Configuration;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.format.PropertyFormatter;
import org.infinispan.configuration.global.GlobalAuthorizationConfiguration;
import org.infinispan.configuration.global.GlobalConfiguration;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.global.TransportConfiguration;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.factories.ComponentRegistry;
import org.infinispan.factories.GlobalComponentRegistry;
import org.infinispan.factories.InternalCacheFactory;
import org.infinispan.factories.KnownComponentNames;
import org.infinispan.factories.annotations.SurvivesRestarts;
import org.infinispan.factories.impl.BasicComponentRegistry;
import org.infinispan.factories.scopes.Scope;
import org.infinispan.factories.scopes.Scopes;
import org.infinispan.globalstate.GlobalConfigurationManager;
import org.infinispan.health.Health;
import org.infinispan.health.impl.HealthImpl;
import org.infinispan.health.impl.jmx.HealthJMXExposerImpl;
import org.infinispan.health.jmx.HealthJMXExposer;
import org.infinispan.jmx.CacheManagerJmxRegistration;
import org.infinispan.jmx.annotations.DataType;
import org.infinispan.jmx.annotations.MBean;
import org.infinispan.jmx.annotations.ManagedAttribute;
import org.infinispan.jmx.annotations.ManagedOperation;
import org.infinispan.jmx.annotations.Parameter;
import org.infinispan.lifecycle.ComponentStatus;
import org.infinispan.manager.impl.ClusterExecutors;
import org.infinispan.notifications.cachemanagerlistener.CacheManagerNotifier;
import org.infinispan.registry.InternalCacheRegistry;
import org.infinispan.remoting.transport.Address;
import org.infinispan.remoting.transport.Transport;
import org.infinispan.security.AuditContext;
import org.infinispan.security.AuthorizationPermission;
import org.infinispan.security.impl.Authorizer;
import org.infinispan.security.impl.PrincipalRoleMapperContextImpl;
import org.infinispan.security.impl.SecureCacheImpl;
import org.infinispan.stats.CacheContainerStats;
import org.infinispan.stats.impl.CacheContainerStatsImpl;
import org.infinispan.util.CyclicDependencyException;
import org.infinispan.util.DependencyGraph;
import org.infinispan.util.concurrent.CompletableFutures;
import org.infinispan.util.logging.Log;
import org.infinispan.util.logging.LogFactory;
/**
* A <tt>CacheManager</tt> is the primary mechanism for retrieving a {@link Cache} instance, and is often used as a
* starting point to using the {@link Cache}.
* <p/>
* <tt>CacheManager</tt>s are heavyweight objects, and we foresee no more than one <tt>CacheManager</tt> being used per
* JVM (unless specific configuration requirements require more than one; but either way, this would be a minimal and
* finite number of instances).
* <p/>
* Constructing a <tt>CacheManager</tt> is done via one of its constructors, which optionally take in a {@link
* org.infinispan.configuration.cache.Configuration} or a path or URL to a configuration XML file.
* <p/>
* Lifecycle - <tt>CacheManager</tt>s have a lifecycle (it implements {@link Lifecycle}) and the default constructors
* also call {@link #start()}. Overloaded versions of the constructors are available, that do not start the
* <tt>CacheManager</tt>, although it must be kept in mind that <tt>CacheManager</tt>s need to be started before they
* can be used to create <tt>Cache</tt> instances.
* <p/>
* Once constructed, <tt>CacheManager</tt>s should be made available to any component that requires a <tt>Cache</tt>,
* via JNDI or via some other mechanism such as an IoC container.
* <p/>
* You obtain <tt>Cache</tt> instances from the <tt>CacheManager</tt> by using one of the overloaded
* <tt>getCache()</tt>, methods. Note that with <tt>getCache()</tt>, there is no guarantee that the instance you get is
* brand-new and empty, since caches are named and shared. Because of this, the <tt>CacheManager</tt> also acts as a
* repository of <tt>Cache</tt>s, and is an effective mechanism of looking up or creating <tt>Cache</tt>s on demand.
* <p/>
* When the system shuts down, it should call {@link #stop()} on the <tt>CacheManager</tt>. This will ensure all caches
* within its scope are properly stopped as well.
* <p/>
* Sample usage:
* <pre><code>
* CacheManager manager = CacheManager.getInstance("my-config-file.xml");
* Cache<String, Person> entityCache = manager.getCache("myEntityCache");
* entityCache.put("aPerson", new Person());
*
* ConfigurationBuilder confBuilder = new ConfigurationBuilder();
* confBuilder.clustering().cacheMode(CacheMode.REPL_SYNC);
* manager.createCache("myReplicatedCache", confBuilder.build());
* Cache<String, String> replicatedCache = manager.getCache("myReplicatedCache");
* </code></pre>
*
* @author Manik Surtani
* @author Galder Zamarreño
* @since 4.0
*/
@Scope(Scopes.GLOBAL)
@SurvivesRestarts
@MBean(objectName = DefaultCacheManager.OBJECT_NAME, description = "Component that acts as a manager, factory and container for caches in the system.")
public class DefaultCacheManager implements EmbeddedCacheManager {
public static final String OBJECT_NAME = "CacheManager";
private static final Log log = LogFactory.getLog(DefaultCacheManager.class);
private final ConcurrentMap<String, CompletableFuture<Cache<?, ?>>> caches = new ConcurrentHashMap<>();
private final GlobalComponentRegistry globalComponentRegistry;
private final Authorizer authorizer;
private final DependencyGraph<String> cacheDependencyGraph = new DependencyGraph<>();
private final CacheContainerStats stats;
private final Health health;
private final ConfigurationManager configurationManager;
private final String defaultCacheName;
private final Lock lifecycleLock = new ReentrantLock();
private final Condition lifecycleCondition = lifecycleLock.newCondition();
private volatile ComponentStatus status = ComponentStatus.INSTANTIATED;
private final DefaultCacheManagerAdmin cacheManagerAdmin;
private final ClassAllowList classAllowList;
private final CacheManagerInfo cacheManagerInfo;
// Keep the transport around so async view listeners can still see the address after stop
private volatile Transport transport;
/**
* Constructs and starts a default instance of the CacheManager, using configuration defaults. See
* {@link org.infinispan.configuration.cache.Configuration} and {@link org.infinispan.configuration.global.GlobalConfiguration}
* for details of these defaults.
*/
public DefaultCacheManager() {
this(null, null, true);
}
/**
* Constructs a default instance of the CacheManager, using configuration defaults. See
* {@link org.infinispan.configuration.cache.Configuration} and {@link org.infinispan.configuration.global.GlobalConfiguration}
* for details of these defaults.
*
* @param start if true, the cache manager is started
*/
public DefaultCacheManager(boolean start) {
this(null, null, start);
}
/**
* Constructs and starts a new instance of the CacheManager, using the default configuration passed in. See
* {@link org.infinispan.configuration.cache.Configuration} and {@link org.infinispan.configuration.global.GlobalConfiguration}
* for details of these defaults.
*
* @param defaultConfiguration configuration to use as a template for all caches created
* @deprecated Since 11.0, please use {@link #DefaultCacheManager(ConfigurationBuilderHolder, boolean)} instead.
*/
@Deprecated
public DefaultCacheManager(Configuration defaultConfiguration) {
this(null, defaultConfiguration, true);
}
/**
* Constructs a new instance of the CacheManager, using the default configuration passed in. See
* {@link org.infinispan.configuration.global.GlobalConfiguration} for details of these defaults.
*
* @param defaultConfiguration configuration file to use as a template for all caches created
* @param start if true, the cache manager is started
* @deprecated Since 11.0, please use {@link #DefaultCacheManager(ConfigurationBuilderHolder, boolean)} instead.
*/
@Deprecated
public DefaultCacheManager(Configuration defaultConfiguration, boolean start) {
this(null, defaultConfiguration, start);
}
/**
* Constructs and starts a new instance of the CacheManager, using the global configuration passed in, and system
* defaults for the default named cache configuration. See {@link org.infinispan.configuration.cache.Configuration}
* for details of these defaults.
*
* @param globalConfiguration GlobalConfiguration to use for all caches created
*/
public DefaultCacheManager(GlobalConfiguration globalConfiguration) {
this(globalConfiguration, null, true);
}
/**
* Constructs a new instance of the CacheManager, using the global configuration passed in, and system defaults for
* the default named cache configuration. See {@link org.infinispan.configuration.cache.Configuration}
* for details of these defaults.
*
* @param globalConfiguration GlobalConfiguration to use for all caches created
* @param start if true, the cache manager is started.
*/
public DefaultCacheManager(GlobalConfiguration globalConfiguration, boolean start) {
this(globalConfiguration, null, start);
}
/**
* Constructs and starts a new instance of the CacheManager, using the global and default configurations passed in.
* If either of these are null, system defaults are used.
*
* @param globalConfiguration global configuration to use. If null, a default instance is created.
* @param defaultConfiguration default configuration to use. If null, a default instance is created.
* @deprecated Since 11.0, please use {@link #DefaultCacheManager(ConfigurationBuilderHolder, boolean)} instead.
*/
@Deprecated
public DefaultCacheManager(GlobalConfiguration globalConfiguration, Configuration defaultConfiguration) {
this(globalConfiguration, defaultConfiguration, true);
}
/**
* Constructs a new instance of the CacheManager, using the global and default configurations passed in. If either of
* these are null, system defaults are used.
*
* @param globalConfiguration global configuration to use. If null, a default instance is created.
* @param defaultConfiguration default configuration to use. If null, a default instance is created.
* @param start if true, the cache manager is started
* @deprecated Since 11.0, please use {@link #DefaultCacheManager(ConfigurationBuilderHolder, boolean)} instead.
*/
@Deprecated
public DefaultCacheManager(GlobalConfiguration globalConfiguration, Configuration defaultConfiguration,
boolean start) {
globalConfiguration = globalConfiguration == null ? new GlobalConfigurationBuilder().build() : globalConfiguration;
this.configurationManager = new ConfigurationManager(globalConfiguration);
if (defaultConfiguration != null) {
if (globalConfiguration.defaultCacheName().isPresent()) {
defaultCacheName = globalConfiguration.defaultCacheName().get();
} else {
throw CONFIG.defaultCacheConfigurationWithoutName();
}
configurationManager.putConfiguration(defaultCacheName, defaultConfiguration);
} else {
if (globalConfiguration.defaultCacheName().isPresent()) {
throw CONFIG.missingDefaultCacheDeclaration(globalConfiguration.defaultCacheName().get());
} else {
defaultCacheName = null;
}
}
ModuleRepository moduleRepository = ModuleRepository.newModuleRepository(globalConfiguration.classLoader(), globalConfiguration);
this.classAllowList = globalConfiguration.serialization().allowList().create();
this.globalComponentRegistry = new GlobalComponentRegistry(globalConfiguration, this, caches.keySet(),
moduleRepository, configurationManager);
InternalCacheRegistry internalCacheRegistry = globalComponentRegistry.getComponent(InternalCacheRegistry.class);
this.globalComponentRegistry.registerComponent(cacheDependencyGraph, CACHE_DEPENDENCY_GRAPH, false);
this.authorizer = new Authorizer(globalConfiguration.security(), AuditContext.CACHEMANAGER, globalConfiguration.cacheManagerName());
this.globalComponentRegistry.registerComponent(authorizer, Authorizer.class);
this.stats = new CacheContainerStatsImpl(this);
globalComponentRegistry.registerComponent(stats, CacheContainerStats.class);
health = new HealthImpl(this, globalComponentRegistry.getComponent(InternalCacheRegistry.class));
cacheManagerInfo = new CacheManagerInfo(this, configurationManager, internalCacheRegistry);
globalComponentRegistry.registerComponent(new HealthJMXExposerImpl(health), HealthJMXExposer.class);
this.cacheManagerAdmin = new DefaultCacheManagerAdmin(this, authorizer, EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class), null,
globalComponentRegistry.getComponent(GlobalConfigurationManager.class));
if (start)
start();
}
/**
* Constructs and starts a new instance of the CacheManager, using the configuration file name passed in. This
* constructor first searches for the named file on the classpath, and failing that, treats the file name as an
* absolute path.
*
* @param configurationFile name of configuration file to use as a template for all caches created
* @throws java.io.IOException if there is a problem with the configuration file.
*/
public DefaultCacheManager(String configurationFile) throws IOException {
this(configurationFile, true);
}
/**
* Constructs a new instance of the CacheManager, using the configuration file name passed in. This constructor first
* searches for the named file on the classpath, and failing that, treats the file name as an absolute path.
*
* @param configurationFile name of configuration file to use as a template for all caches created
* @param start if true, the cache manager is started
* @throws java.io.IOException if there is a problem with the configuration file.
*/
public DefaultCacheManager(String configurationFile, boolean start) throws IOException {
this(FileLookupFactory.newInstance().lookupFileStrict(configurationFile, Thread.currentThread().getContextClassLoader()), start);
}
/**
* Constructs and starts a new instance of the CacheManager, using the input stream passed in to read configuration
* file contents.
*
* @param configurationStream stream containing configuration file contents, to use as a template for all caches
* created
* @throws java.io.IOException if there is a problem with the configuration stream.
*/
public DefaultCacheManager(InputStream configurationStream) throws IOException {
this(configurationStream, true);
}
/**
* Constructs a new instance of the CacheManager, using the input stream passed in to read configuration file
* contents.
*
* @param configurationStream stream containing configuration file contents, to use as a template for all caches
* created
* @param start if true, the cache manager is started
* @throws java.io.IOException if there is a problem reading the configuration stream
*/
public DefaultCacheManager(InputStream configurationStream, boolean start) throws IOException {
this(new ParserRegistry().parse(configurationStream, null, MediaType.APPLICATION_XML), start);
}
/**
* Constructs a new instance of the CacheManager, using the input stream passed in to read configuration file
* contents.
*
* @param configurationURL stream containing configuration file contents, to use as a template for all caches
* created
* @param start if true, the cache manager is started
* @throws java.io.IOException if there is a problem reading the configuration stream
*/
public DefaultCacheManager(URL configurationURL, boolean start) throws IOException {
this(new ParserRegistry().parse(configurationURL), start);
}
/**
* Constructs a new instance of the CacheManager, using the holder passed in to read configuration settings.
*
* @param holder holder containing configuration settings, to use as a template for all caches created
* @param start if true, the cache manager is started
*/
public DefaultCacheManager(ConfigurationBuilderHolder holder, boolean start) {
try {
configurationManager = new ConfigurationManager(holder);
GlobalConfiguration globalConfiguration = configurationManager.getGlobalConfiguration();
classAllowList = globalConfiguration.serialization().allowList().create();
defaultCacheName = globalConfiguration.defaultCacheName().orElse(null);
ModuleRepository moduleRepository = ModuleRepository.newModuleRepository(globalConfiguration.classLoader(), globalConfiguration);
globalComponentRegistry = new GlobalComponentRegistry(globalConfiguration, this, caches.keySet(),
moduleRepository, configurationManager);
InternalCacheRegistry internalCacheRegistry = globalComponentRegistry.getComponent(InternalCacheRegistry.class);
globalComponentRegistry.registerComponent(cacheDependencyGraph, CACHE_DEPENDENCY_GRAPH, false);
stats = new CacheContainerStatsImpl(this);
globalComponentRegistry.registerComponent(stats, CacheContainerStats.class);
health = new HealthImpl(this, internalCacheRegistry);
cacheManagerInfo = new CacheManagerInfo(this, getConfigurationManager(), internalCacheRegistry);
globalComponentRegistry.registerComponent(new HealthJMXExposerImpl(health), HealthJMXExposer.class);
authorizer = new Authorizer(globalConfiguration.security(), AuditContext.CACHEMANAGER, globalConfiguration.cacheManagerName());
globalComponentRegistry.registerComponent(authorizer, Authorizer.class);
cacheManagerAdmin = new DefaultCacheManagerAdmin(this, authorizer, EnumSet.noneOf(CacheContainerAdmin.AdminFlag.class),
null, globalComponentRegistry.getComponent(GlobalConfigurationManager.class));
} catch (CacheConfigurationException ce) {
throw ce;
} catch (RuntimeException re) {
throw new CacheConfigurationException(re);
}
if (start)
start();
}
private DefaultCacheManager(DefaultCacheManager original) {
this.authorizer = original.authorizer;
this.configurationManager = original.configurationManager;
this.health = original.health;
this.classAllowList = original.classAllowList;
this.cacheManagerInfo = original.cacheManagerInfo;
this.cacheManagerAdmin = original.cacheManagerAdmin;
this.defaultCacheName = original.defaultCacheName;
this.stats = original.stats;
this.globalComponentRegistry = original.globalComponentRegistry;
}
@Override
public Configuration defineConfiguration(String name, Configuration configuration) {
return doDefineConfiguration(name, configuration);
}
@Override
public Configuration defineConfiguration(String name, String template, Configuration configurationOverride) {
if (template != null) {
Configuration c = configurationManager.getConfiguration(template, true);
if (c == null) {
throw CONFIG.undeclaredConfiguration(template, name);
} else if (configurationOverride == null) {
return doDefineConfiguration(name, c);
} else {
return doDefineConfiguration(name, c, configurationOverride);
}
}
return doDefineConfiguration(name, configurationOverride);
}
private Configuration doDefineConfiguration(String name, Configuration... configurations) {
authorizer.checkPermission(getSubject(), AuthorizationPermission.ADMIN);
assertIsNotTerminated();
if (name == null || configurations == null)
throw new NullPointerException("Null arguments not allowed");
Configuration existing = configurationManager.getConfiguration(name, false);
if (existing != null) {
throw CONFIG.configAlreadyDefined(name);
}
ConfigurationBuilder builder = new ConfigurationBuilder();
boolean template = true;
for (Configuration configuration : configurations) {
if (configuration != null) {
builder.read(configuration);
template = template && configuration.isTemplate();
} else {
throw new NullPointerException("Null arguments not allowed");
}
}
builder.template(template);
return configurationManager.putConfiguration(name, builder);
}
@Override
public void undefineConfiguration(String configurationName) {
authorizer.checkPermission(getSubject(), AuthorizationPermission.ADMIN);
Configuration existing = configurationManager.getConfiguration(configurationName, false);
if (existing != null) {
for (CompletableFuture<Cache<?, ?>> cacheFuture : caches.values()) {
Cache<?, ?> cache = cacheFuture.exceptionally(t -> null).join();
if (cache != null && cache.getCacheConfiguration() == existing && cache.getStatus() != ComponentStatus.TERMINATED) {
throw CONFIG.configurationInUse(configurationName);
}
}
configurationManager.removeConfiguration(configurationName);
globalComponentRegistry.removeCache(configurationName);
}
}
@Override
public <K, V> Cache<K, V> createCache(String name, Configuration configuration) {
defineConfiguration(name, configuration);
return getCache(name);
}
/**
* Retrieves the default cache associated with this cache manager. Note that the default cache does not need to be
* explicitly created with {@link #createCache(String)} (String)} since it is automatically created lazily
* when first used.
* <p/>
* As such, this method is always guaranteed to return the default cache.
*
* @return the default cache.
*/
@Override
public <K, V> Cache<K, V> getCache() {
if (defaultCacheName == null) {
throw CONFIG.noDefaultCache();
}
return internalGetCache(defaultCacheName);
}
/**
* Retrieves a named cache from the system. If the cache has been previously created with the same name, the running
* cache instance is returned. Otherwise, this method attempts to create the cache first.
* <p/>
* When creating a new cache, this method will use the configuration passed in to the CacheManager on construction,
* as a template, and then optionally apply any overrides previously defined for the named cache using the {@link
* #defineConfiguration(String, Configuration)} or {@link #defineConfiguration(String, String, Configuration)}
* methods, or declared in the configuration file.
*
* @param cacheName name of cache to retrieve
* @return a cache instance identified by cacheName
*/
@Override
public <K, V> Cache<K, V> getCache(String cacheName) {
return internalGetCache(cacheName);
}
private <K, V> Cache<K, V> internalGetCache(String cacheName) {
if (cacheName == null)
throw new NullPointerException("Null arguments not allowed");
assertIsNotTerminated();
// No need to block if another thread (or even the current thread) is starting the global components
// Because each cache component will wait for the global components it depends on
// And and ComponentRegistry depends on GlobalComponentRegistry.ModuleInitializer
internalStart(false);
CompletableFuture<Cache<?, ?>> cacheFuture = caches.get(cacheName);
if (cacheFuture != null) {
try {
return (Cache<K, V>) cacheFuture.join();
} catch (CompletionException e) {
throw ((CacheException) e.getCause());
}
}
return createCache(cacheName);
}
@Override
public boolean cacheExists(String cacheName) {
return caches.containsKey(cacheName);
}
@Override
public <K, V> Cache<K, V> getCache(String cacheName, boolean createIfAbsent) {
boolean cacheExists = cacheExists(cacheName);
if (!cacheExists && !createIfAbsent)
return null;
else {
return internalGetCache(cacheName);
}
}
@Override
public EmbeddedCacheManager startCaches(final String... cacheNames) {
authorizer.checkPermission(getSubject(), AuthorizationPermission.LIFECYCLE);
internalStart(false);
Map<String, Thread> threads = new HashMap<>(cacheNames.length);
final AtomicReference<RuntimeException> exception = new AtomicReference<>(null);
for (final String cacheName : cacheNames) {
if (!threads.containsKey(cacheName)) {
String threadName = "CacheStartThread," + configurationManager.getGlobalConfiguration().transport().nodeName() + "," + cacheName;
Thread thread = new Thread(threadName) {
@Override
public void run() {
try {
createCache(cacheName);
} catch (RuntimeException e) {
exception.set(e);
} catch (Throwable t) {
exception.set(new RuntimeException(t));
}
}
};
thread.start();
threads.put(cacheName, thread);
}
}
try {
for (Thread thread : threads.values()) {
thread.join();
}
} catch (InterruptedException e) {
throw new CacheException("Interrupted while waiting for the caches to start");
}
RuntimeException runtimeException = exception.get();
if (runtimeException != null) {
throw runtimeException;
}
return this;
}
@Override
public void removeCache(String cacheName) {
cacheManagerAdmin.removeCache(cacheName);
}
/**
* {@inheritDoc}
*/
@Override
public List<Address> getMembers() {
Transport t = getTransport();
return t == null ? null : t.getMembers();
}
/**
* {@inheritDoc}
*/
@Override
public Address getAddress() {
Transport t = getTransport();
return t == null ? null : t.getAddress();
}
/**
* {@inheritDoc}
*/
@Override
public Address getCoordinator() {
Transport t = getTransport();
return t == null ? null : t.getCoordinator();
}
@ManagedAttribute(description = "The logical address of the cluster's coordinator", displayName = "Coordinator address")
public String getCoordinatorAddress() {
return cacheManagerInfo.getCoordinatorAddress();
}
/**
* {@inheritDoc}
*/
@Override
@ManagedAttribute(description = "Indicates whether this node is coordinator", displayName = "Is coordinator?")
public boolean isCoordinator() {
return cacheManagerInfo.isCoordinator();
}
private <K, V> Cache<K, V> createCache(String cacheName) {
final boolean trace = log.isTraceEnabled();
LogFactory.pushNDC(cacheName, trace);
try {
return wireAndStartCache(cacheName);
} finally {
LogFactory.popNDC(trace);
}
}
/**
* @return a null return value means the cache was created by someone else before we got the lock
*/
private <K, V> Cache<K, V> wireAndStartCache(String cacheName) {
Configuration c = configurationManager.getConfiguration(cacheName);
if (c == null) {
throw CONFIG.noSuchCacheConfiguration(cacheName);
}
if (c.security().authorization().enabled()) {
// Don't even attempt to wire anything if we don't have LIFECYCLE privileges
authorizer.checkPermission(c.security().authorization(), getSubject(), AuthorizationPermission.LIFECYCLE, null);
}
if (c.isTemplate()) {
throw CONFIG.templateConfigurationStartAttempt(cacheName);
}
CompletableFuture<Cache<?, ?>> cacheFuture = new CompletableFuture<>();
CompletableFuture<Cache<?, ?>> oldFuture = caches.computeIfAbsent(cacheName, name -> {
assertIsNotTerminated();
return cacheFuture;
});
Cache<K, V> cache = null;
try {
if (oldFuture != cacheFuture) {
cache = (Cache<K, V>) oldFuture.join();
if (!cache.getStatus().isTerminated()) {
return cache;
}
}
} catch (CompletionException ce) {
throw ((CacheException) ce.getCause());
}
try {
log.tracef("About to wire and start cache %s", cacheName);
if (cache == null) {
cache = new InternalCacheFactory<K, V>().createCache(c, globalComponentRegistry, cacheName);
if (cache.getAdvancedCache().getAuthorizationManager() != null) {
cache = new SecureCacheImpl<>(cache.getAdvancedCache());
}
}
ComponentRegistry cr = SecurityActions.getUnwrappedCache(cache).getAdvancedCache().getComponentRegistry();
boolean notStartedYet =
cr.getStatus() != ComponentStatus.RUNNING && cr.getStatus() != ComponentStatus.INITIALIZING;
// start the cache-level components
cache.start();
cacheFuture.complete(cache);
boolean needToNotifyCacheStarted = notStartedYet && cr.getStatus() == ComponentStatus.RUNNING;
if (needToNotifyCacheStarted) {
globalComponentRegistry.notifyCacheStarted(cacheName);
}
log.tracef("Cache %s started", cacheName);
return cache;
} catch (CacheException e) {
cacheFuture.completeExceptionally(e);
throw e;
} catch (Throwable t) {
cacheFuture.completeExceptionally(new CacheException(t));
throw t;
}
}
@Override
public void start() {
authorizer.checkPermission(getSubject(), AuthorizationPermission.LIFECYCLE);
internalStart(true);
}
/**
* @param block {@code true} when we need all the global components to be running.
*/
private void internalStart(boolean block) {
final GlobalConfiguration globalConfiguration = configurationManager.getGlobalConfiguration();
lifecycleLock.lock();
try {
while (block && status == ComponentStatus.INITIALIZING) {
lifecycleCondition.await();
}
if (status != ComponentStatus.INSTANTIATED) {
return;
}
log.debugf("Starting cache manager %s", configurationManager.getGlobalConfiguration().transport().nodeName());
initializeSecurity(globalConfiguration);
updateStatus(ComponentStatus.INITIALIZING);
} catch (InterruptedException e) {
throw new CacheException("Interrupted waiting for the cache manager to start");
} finally {
lifecycleLock.unlock();
}
try {
globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).start();
globalComponentRegistry.start();
String nodeName = globalConfiguration.transport().nodeName();
log.debugf("Started cache manager %s on %s", nodeName, getAddress());
} catch (Exception e) {
throw new EmbeddedCacheManagerStartupException(e);
} finally {
updateStatus(globalComponentRegistry.getStatus());
}
}
private void initializeSecurity(GlobalConfiguration globalConfiguration) {
GlobalAuthorizationConfiguration authorizationConfig = globalConfiguration.security().authorization();
if (authorizationConfig.enabled() && System.getSecurityManager() == null) {
CONFIG.authorizationEnabledWithoutSecurityManager();
}
if (authorizationConfig.enabled()) {
authorizationConfig.principalRoleMapper().setContext(new PrincipalRoleMapperContextImpl(this));
}
}
private void updateStatus(ComponentStatus status) {
lifecycleLock.lock();
try {
this.status = status;
lifecycleCondition.signalAll();
} finally {
lifecycleLock.unlock();
}
}
private void terminate(String cacheName) {
CompletableFuture<Cache<?, ?>> cacheFuture = this.caches.get(cacheName);
if (cacheFuture != null) {
Cache<?, ?> cache = cacheFuture.join();
if (cache.getStatus().isTerminated()) {
log.tracef("Ignoring cache %s, it is already terminated.", cacheName);
return;
}
cache.stop();
}
}
@Override
public void stop() {
authorizer.checkPermission(getSubject(), AuthorizationPermission.LIFECYCLE);
internalStop();
}
private void internalStop() {
lifecycleLock.lock();
try {
while (status == ComponentStatus.STOPPING) {
lifecycleCondition.await();
}
if (status != ComponentStatus.RUNNING && status != ComponentStatus.FAILED) {
log.trace("Ignore call to stop as the cache manager is not running");
return;
}
// We can stop the manager
log.infof("Stopping cache manager %s on %s", configurationManager.getGlobalConfiguration().transport().nodeName(), getAddress());
updateStatus(ComponentStatus.STOPPING);
} catch (InterruptedException e) {
throw new CacheException("Interrupted waiting for the cache manager to stop");
} finally {
lifecycleLock.unlock();
}
try {
stopCaches();
globalComponentRegistry.getComponent(CacheManagerJmxRegistration.class).stop();
globalComponentRegistry.stop();
log.debugf("Stopped cache manager %s", configurationManager.getGlobalConfiguration().transport().nodeName());
} finally {
updateStatus(ComponentStatus.TERMINATED);
}
}
private void stopCaches() {
Set<String> cachesToStop = new LinkedHashSet<>(this.caches.size());
// stop ordered caches first
try {
List<String> ordered = cacheDependencyGraph.topologicalSort();
cachesToStop.addAll(ordered);
} catch (CyclicDependencyException e) {
CONTAINER.stopOrderIgnored();
}
// The caches map includes the default cache
cachesToStop.addAll(caches.keySet());
log.tracef("Cache stop order: %s", cachesToStop);
for (String cacheName : cachesToStop) {
try {
terminate(cacheName);
} catch (Throwable t) {
CONTAINER.componentFailedToStop(t);
}
}
}
@Override
public CompletionStage<Void> addListenerAsync(Object listener) {
authorizer.checkPermission(getSubject(), AuthorizationPermission.LISTEN);
CacheManagerNotifier notifier = globalComponentRegistry.getComponent(CacheManagerNotifier.class);
return notifier.addListenerAsync(listener);
}
@Override
public CompletionStage<Void> removeListenerAsync(Object listener) {
authorizer.checkPermission(getSubject(), AuthorizationPermission.LISTEN);
try {
CacheManagerNotifier notifier = globalComponentRegistry.getComponent(CacheManagerNotifier.class);
return notifier.removeListenerAsync(listener);
} catch (IllegalLifecycleStateException e) {
// Ignore the exception for backwards compatibility
return CompletableFutures.completedNull();
}
}
@Deprecated
@Override
public Set<Object> getListeners() {
authorizer.checkPermission(getSubject(), AuthorizationPermission.LISTEN);
CacheManagerNotifier notifier = globalComponentRegistry.getComponent(CacheManagerNotifier.class);
return notifier.getListeners();
}
@Override
public ComponentStatus getStatus() {
return status;
}
@Override
public GlobalConfiguration getCacheManagerConfiguration() {
authorizer.checkPermission(getSubject(), AuthorizationPermission.ADMIN);
return configurationManager.getGlobalConfiguration();
}
@Override
public org.infinispan.configuration.cache.Configuration getDefaultCacheConfiguration() {
authorizer.checkPermission(getSubject(), AuthorizationPermission.ADMIN);
if (defaultCacheName != null) {
return configurationManager.getConfiguration(defaultCacheName, true);
} else {
return null;
}
}
@Override
public Configuration getCacheConfiguration(String name) {
authorizer.checkPermission(getSubject(), AuthorizationPermission.ADMIN);
Configuration configuration = configurationManager.getConfiguration(name, true);
if (configuration == null && cacheExists(name)) {
return getDefaultCacheConfiguration();
}
return configuration;
}
@Override
public Set<String> getCacheNames() {
// Get the XML/programmatically defined caches
Set<String> names = new HashSet<>(configurationManager.getDefinedCaches());
// Add the caches created dynamically without explicit config
names.addAll(caches.keySet());
InternalCacheRegistry internalCacheRegistry = globalComponentRegistry.getComponent(InternalCacheRegistry.class);
internalCacheRegistry.filterPrivateCaches(names);
if (names.isEmpty())
return Collections.emptySet();
else
return Immutables.immutableSetWrap(names);
}
@Override
public Set<String> getCacheConfigurationNames() {
return cacheManagerInfo.getCacheConfigurationNames();
}
@Override
public boolean isRunning(String cacheName) {
CompletableFuture<Cache<?, ?>> cacheFuture = caches.get(cacheName);
boolean started = cacheFuture != null && cacheFuture.isDone() && !cacheFuture.isCompletedExceptionally();
return started && cacheFuture.join().getStatus() == ComponentStatus.RUNNING;
}
@Override
public boolean isDefaultRunning() {
Optional<String> defaultCacheName = configurationManager.getGlobalConfiguration().defaultCacheName();
return defaultCacheName.isPresent() && isRunning(defaultCacheName.get());
}
@ManagedAttribute(description = "The status of the cache manager instance.", displayName = "Cache manager status", dataType = DataType.TRAIT)
public String getCacheManagerStatus() {
return cacheManagerInfo.getCacheManagerStatus();
}
@ManagedAttribute(description = "The defined cache names and their statuses. The default cache is not included in this representation.", displayName = "List of defined caches", dataType = DataType.TRAIT)
public String getDefinedCacheNames() {
StringJoiner stringJoiner = new StringJoiner("", "[", "]");
cacheManagerInfo.getDefinedCaches().forEach(c -> stringJoiner.add(c.name).add(c.isStarted() ? "(created)" : "(not created)"));
return stringJoiner.toString();
}
@ManagedAttribute(description = "The defined cache configuration names.", displayName = "List of defined cache configurations", dataType = DataType.TRAIT)
public String getDefinedCacheConfigurationNames() {
StringJoiner stringJoiner = new StringJoiner(",", "[", "]");
cacheManagerInfo.getCacheConfigurationNames().forEach(stringJoiner::add);
return stringJoiner.toString();
}
@ManagedAttribute(description = "The total number of defined cache configurations.", displayName = "Number of caches defined")
public String getDefinedCacheCount() {
return String.valueOf(getNumberOfCacheConfigurations());
}
@ManagedAttribute(description = "The total number of defined cache configurations.", displayName = "Number of caches defined")
public int getNumberOfCacheConfigurations() {
return getCacheConfigurationNames().size();
}
@ManagedAttribute(description = "The total number of created caches, including the default cache.", displayName = "Number of caches created")
public String getCreatedCacheCount() {
return String.valueOf(getNumberOfCreatedCaches());
}
@ManagedAttribute(description = "The total number of created caches, including the default cache.", displayName = "Number of caches created")
public long getNumberOfCreatedCaches() {
return cacheManagerInfo.getCreatedCacheCount();
}
@ManagedAttribute(description = "The total number of running caches, including the default cache.", displayName = "Number of running caches")
public String getRunningCacheCount() {
return String.valueOf(getNumberOfRunningCaches());
}
@ManagedAttribute(description = "The total number of running caches, including the default cache.", displayName = "Number of running caches")
public long getNumberOfRunningCaches() {
return cacheManagerInfo.getRunningCacheCount();
}
@ManagedAttribute(description = "Returns the version of Infinispan", displayName = "Infinispan version", dataType = DataType.TRAIT)
public String getVersion() {
return cacheManagerInfo.getVersion();
}
@ManagedAttribute(description = "The name of this cache manager", displayName = "Cache manager name", dataType = DataType.TRAIT)
public String getName() {
return cacheManagerInfo.getName();
}
@ManagedOperation(description = "Starts the default cache associated with this cache manager", displayName = "Starts the default cache")
public void startCache() {
if (defaultCacheName == null) {