Simplify method isMutualExclusive in Subnet.
[controller.git] / opendaylight / config / config-manager / src / main / java / org / opendaylight / controller / config / manager / impl / ConfigRegistryImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.controller.config.manager.impl;
9
10 import org.opendaylight.controller.config.api.ConflictingVersionException;
11 import org.opendaylight.controller.config.api.ModuleIdentifier;
12 import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
13 import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
14 import org.opendaylight.controller.config.api.ServiceReferenceWritableRegistry;
15 import org.opendaylight.controller.config.api.ValidationException;
16 import org.opendaylight.controller.config.api.jmx.CommitStatus;
17 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
18 import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
19 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HierarchicalConfigMBeanFactoriesHolder;
20 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
21 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
22 import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
23 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
24 import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
25 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager;
26 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
27 import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
28 import org.opendaylight.controller.config.manager.impl.util.ModuleQNameUtil;
29 import org.opendaylight.controller.config.spi.Module;
30 import org.opendaylight.controller.config.spi.ModuleFactory;
31 import org.osgi.framework.BundleContext;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 import javax.annotation.concurrent.GuardedBy;
36 import javax.annotation.concurrent.NotThreadSafe;
37 import javax.annotation.concurrent.ThreadSafe;
38 import javax.management.InstanceAlreadyExistsException;
39 import javax.management.InstanceNotFoundException;
40 import javax.management.MBeanServer;
41 import javax.management.MBeanServerFactory;
42 import javax.management.ObjectName;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.LinkedList;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Map.Entry;
52 import java.util.Set;
53
54 /**
55  * Singleton that is responsible for creating and committing Config
56  * Transactions. It is registered in Platform MBean Server.
57  */
58 @ThreadSafe
59 public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
60     private static final Logger logger = LoggerFactory.getLogger(ConfigRegistryImpl.class);
61
62     private final ModuleFactoriesResolver resolver;
63     private final MBeanServer configMBeanServer;
64
65     @GuardedBy("this")
66     private long version = 0;
67     @GuardedBy("this")
68     private long versionCounter = 0;
69
70     /**
71      * Contains current configuration in form of {moduleName:{instanceName,read
72      * only module}} for copying state to new transaction. Each running module
73      * is present just once, no matter how many interfaces it exposes.
74      */
75     @GuardedBy("this")
76     private final ConfigHolder currentConfig = new ConfigHolder();
77
78     /**
79      * Will return true unless there was a transaction that succeeded during
80      * validation but failed in second phase of commit. In this case the server
81      * is unstable and its state is undefined.
82      */
83     @GuardedBy("this")
84     private boolean isHealthy = true;
85
86     /**
87      * Holds Map<transactionName, transactionController> and purges it each time
88      * its content is requested.
89      */
90     @GuardedBy("this")
91     private final TransactionsHolder transactionsHolder = new TransactionsHolder();
92
93     private final BaseJMXRegistrator baseJMXRegistrator;
94
95     private final BeanToOsgiServiceManager beanToOsgiServiceManager;
96
97     // internal jmx server for read only beans
98     private final MBeanServer registryMBeanServer;
99     // internal jmx server shared by all transactions
100     private final MBeanServer transactionsMBeanServer;
101
102     // Used for finding new factory instances for default module functionality
103     @GuardedBy("this")
104     private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
105
106     @GuardedBy("this") // switched in every 2ndPC
107     private ServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
108
109     // constructor
110     public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
111             MBeanServer configMBeanServer) {
112         this(resolver, configMBeanServer,
113                 new BaseJMXRegistrator(configMBeanServer));
114     }
115
116     // constructor
117     public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
118             MBeanServer configMBeanServer,
119             BaseJMXRegistrator baseJMXRegistrator) {
120         this.resolver = resolver;
121         this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
122         this.configMBeanServer = configMBeanServer;
123         this.baseJMXRegistrator = baseJMXRegistrator;
124         this.registryMBeanServer = MBeanServerFactory
125                 .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
126         this.transactionsMBeanServer = MBeanServerFactory
127                 .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
128     }
129
130     /**
131      * Create new {@link ConfigTransactionControllerImpl }
132      */
133     @Override
134     public synchronized ObjectName beginConfig() {
135         return beginConfig(false);
136     }
137
138     /**
139      * @param blankTransaction true if this transaction is created automatically by
140      *                         org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
141      */
142     public synchronized ObjectName beginConfig(boolean blankTransaction) {
143         return beginConfigInternal(blankTransaction).getControllerObjectName();
144     }
145
146     private synchronized ConfigTransactionControllerInternal beginConfigInternal(boolean blankTransaction) {
147         versionCounter++;
148         final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
149
150         TransactionJMXRegistratorFactory factory = new TransactionJMXRegistratorFactory() {
151             @Override
152             public TransactionJMXRegistrator create() {
153                 return baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
154             }
155         };
156
157         Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = Collections.unmodifiableMap(
158                 resolver.getAllFactories());
159         ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(new TransactionIdentifier(
160                 transactionName), factory, allCurrentFactories);
161         ServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
162                 readableSRRegistry, txLookupRegistry, allCurrentFactories);
163
164         ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
165                 txLookupRegistry, version,
166                 versionCounter, allCurrentFactories, transactionsMBeanServer,
167                 configMBeanServer, blankTransaction, writableRegistry);
168         try {
169             txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
170         } catch (InstanceAlreadyExistsException e) {
171             throw new IllegalStateException(e);
172         }
173         transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
174         transactionsHolder.add(transactionName, transactionController);
175         return transactionController;
176     }
177
178     /**
179      * {@inheritDoc}
180      */
181     @Override
182     public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
183             throws ConflictingVersionException, ValidationException {
184         final String transactionName = ObjectNameUtil
185                 .getTransactionName(transactionControllerON);
186         logger.info("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
187
188         // find ConfigTransactionController
189         Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder.getCurrentTransactions();
190         ConfigTransactionControllerInternal configTransactionController = transactions.get(transactionName);
191         if (configTransactionController == null) {
192             throw new IllegalArgumentException(String.format(
193                     "Transaction with name '%s' not found", transactionName));
194         }
195         // check optimistic lock
196         if (version != configTransactionController.getParentVersion()) {
197             throw new ConflictingVersionException(
198                     String.format(
199                             "Optimistic lock failed. Expected parent version %d, was %d",
200                             version,
201                             configTransactionController.getParentVersion()));
202         }
203         // optimistic lock ok
204
205         CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
206         lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
207         // non recoverable from here:
208         try {
209             return secondPhaseCommit(
210                     configTransactionController, commitInfo);
211         } catch (Throwable t) { // some libs throw Errors: e.g.
212                                 // javax.xml.ws.spi.FactoryFinder$ConfigurationError
213             isHealthy = false;
214             logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
215             if (t instanceof RuntimeException) {
216                 throw (RuntimeException) t;
217             } else if (t instanceof Error) {
218                 throw (Error) t;
219             } else {
220                 throw new RuntimeException(t);
221             }
222         }
223     }
224
225     private CommitStatus secondPhaseCommit(ConfigTransactionControllerInternal configTransactionController,
226                                            CommitInfo commitInfo) {
227
228         // close instances which were destroyed by the user, including
229         // (hopefully) runtime beans
230         for (DestroyedModule toBeDestroyed : commitInfo
231                 .getDestroyedFromPreviousTransactions()) {
232             toBeDestroyed.close(); // closes instance (which should close
233                                    // runtime jmx registrator),
234             // also closes osgi registration and ModuleJMXRegistrator
235             // registration
236             currentConfig.remove(toBeDestroyed.getIdentifier());
237         }
238
239         // set RuntimeBeanRegistrators on beans implementing
240         // RuntimeBeanRegistratorAwareModule, each module
241         // should have exactly one runtime jmx registrator.
242         Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
243         for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
244                 .values()) {
245             RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
246             if (entry.hasOldModule() == false) {
247                 runtimeBeanRegistrator = baseJMXRegistrator
248                         .createRuntimeBeanRegistrator(entry.getIdentifier());
249             } else {
250                 // reuse old JMX registrator
251                 runtimeBeanRegistrator = entry.getOldInternalInfo()
252                         .getRuntimeBeanRegistrator();
253             }
254             // set runtime jmx registrator if required
255             Module module = entry.getModule();
256             if (module instanceof RuntimeBeanRegistratorAwareModule) {
257                 ((RuntimeBeanRegistratorAwareModule) module)
258                         .setRuntimeBeanRegistrator(runtimeBeanRegistrator);
259             }
260             // save it to info so it is accessible afterwards
261             runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
262         }
263
264         // can register runtime beans
265         List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController
266                 .secondPhaseCommit();
267
268         // copy configuration to read only mode
269         List<ObjectName> newInstances = new LinkedList<>();
270         List<ObjectName> reusedInstances = new LinkedList<>();
271         List<ObjectName> recreatedInstances = new LinkedList<>();
272
273         Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
274
275         int orderingIdx = 0;
276         for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
277             ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
278                     .get(moduleIdentifier);
279             if (entry == null)
280                 throw new NullPointerException("Module not found "
281                         + moduleIdentifier);
282             Module module = entry.getModule();
283             ObjectName primaryReadOnlyON = ObjectNameUtil
284                     .createReadOnlyModuleON(moduleIdentifier);
285
286             // determine if current instance was recreated or reused or is new
287
288             // rules for closing resources:
289             // osgi registration - will be reused if possible.
290             // module jmx registration - will be (re)created every time, needs
291             // to be closed here
292             // runtime jmx registration - should be taken care of by module
293             // itself
294             // instance - is closed only if it was destroyed
295             ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
296                     .createModuleJMXRegistrator();
297
298             OsgiRegistration osgiRegistration = null;
299             if (entry.hasOldModule()) {
300                 ModuleInternalInfo oldInternalInfo = entry.getOldInternalInfo();
301                 DynamicReadableWrapper oldReadableConfigBean = oldInternalInfo
302                         .getReadableModule();
303                 currentConfig.remove(entry.getIdentifier());
304
305                 // test if old instance == new instance
306                 if (oldReadableConfigBean.getInstance().equals(module.getInstance())) {
307                     // reused old instance:
308                     // wrap in readable dynamic mbean
309                     reusedInstances.add(primaryReadOnlyON);
310                     osgiRegistration = oldInternalInfo.getOsgiRegistration();
311                 } else {
312                     // recreated instance:
313                     // it is responsibility of module to call the old instance -
314                     // we just need to unregister configbean
315                     recreatedInstances.add(primaryReadOnlyON);
316
317                     // close old osgi registration
318                     oldInternalInfo.getOsgiRegistration().close();
319                 }
320
321                 // close old module jmx registrator
322                 oldInternalInfo.getModuleJMXRegistrator().close();
323             } else {
324                 // new instance:
325                 // wrap in readable dynamic mbean
326                 newInstances.add(primaryReadOnlyON);
327             }
328
329             DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
330                     module, module.getInstance(), moduleIdentifier,
331                     registryMBeanServer, configMBeanServer);
332
333             // register to JMX
334             try {
335                 newModuleJMXRegistrator.registerMBean(newReadableConfigBean,
336                         primaryReadOnlyON);
337             } catch (InstanceAlreadyExistsException e) {
338                 throw new IllegalStateException(e);
339             }
340
341             // register to OSGi
342             if (osgiRegistration == null) {
343                 ModuleFactory moduleFactory = entry.getModuleFactory();
344                 if(moduleFactory != null) {
345                     BundleContext bc = configTransactionController.
346                             getModuleFactoryBundleContext(moduleFactory.getImplementationName());
347                     osgiRegistration = beanToOsgiServiceManager.registerToOsgi(module.getClass(),
348                             newReadableConfigBean.getInstance(), entry.getIdentifier(), bc);
349                 } else {
350                     throw new NullPointerException(entry.getIdentifier().getFactoryName() + " ModuleFactory not found.");
351                 }
352
353             }
354
355             RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
356                     .get(entry.getIdentifier());
357             ModuleInternalInfo newInfo = new ModuleInternalInfo(
358                     entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
359                     runtimeBeanRegistrator, newModuleJMXRegistrator,
360                     orderingIdx, entry.isDefaultBean());
361
362             newConfigEntries.put(module, newInfo);
363             orderingIdx++;
364         }
365         currentConfig.addAll(newConfigEntries.values());
366
367         // update version
368         version = configTransactionController.getVersion();
369
370         // switch readable Service Reference Registry
371         this.readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(configTransactionController.getWritableRegistry(), this);
372
373         return new CommitStatus(newInstances, reusedInstances,
374                 recreatedInstances);
375     }
376
377     /**
378      * {@inheritDoc}
379      */
380     @Override
381     public synchronized List<ObjectName> getOpenConfigs() {
382         Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
383                 .getCurrentTransactions();
384         List<ObjectName> result = new ArrayList<>(transactions.size());
385         for (ConfigTransactionControllerInternal configTransactionController : transactions
386                 .values()) {
387             result.add(configTransactionController.getControllerObjectName());
388         }
389         return result;
390     }
391
392     /**
393      * Abort open transactions and unregister read only modules. Since this
394      * class is not responsible for registering itself under
395      * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
396      * here.
397      */
398     @Override
399     public synchronized void close() {
400         // abort transactions
401         Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
402                 .getCurrentTransactions();
403         for (ConfigTransactionControllerInternal configTransactionController : transactions
404                 .values()) {
405             try {
406                 configTransactionController.abortConfig();
407             } catch (RuntimeException e) {
408                 logger.warn("Ignoring exception while aborting {}",
409                         configTransactionController, e);
410             }
411         }
412
413         // destroy all live objects one after another in order of the dependency
414         // hierarchy
415         List<DestroyedModule> destroyedModules = currentConfig
416                 .getModulesToBeDestroyed();
417         for (DestroyedModule destroyedModule : destroyedModules) {
418             destroyedModule.close();
419         }
420         // unregister MBeans that failed to unregister properly
421         baseJMXRegistrator.close();
422         // remove jmx servers
423         MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
424         MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
425
426     }
427
428     /**
429      * {@inheritDoc}
430      */
431     @Override
432     public long getVersion() {
433         return version;
434     }
435
436     /**
437      * {@inheritDoc}
438      */
439     @Override
440     public Set<String> getAvailableModuleNames() {
441         return new HierarchicalConfigMBeanFactoriesHolder(
442                 resolver.getAllFactories()).getModuleNames();
443     }
444
445     /**
446      * {@inheritDoc}
447      */
448     @Override
449     public boolean isHealthy() {
450         return isHealthy;
451     }
452
453     // filtering methods
454
455     /**
456      * {@inheritDoc}
457      */
458     @Override
459     public Set<ObjectName> lookupConfigBeans() {
460         return lookupConfigBeans("*", "*");
461     }
462
463     /**
464      * {@inheritDoc}
465      */
466     @Override
467     public Set<ObjectName> lookupConfigBeans(String moduleName) {
468         return lookupConfigBeans(moduleName, "*");
469     }
470
471     /**
472      * {@inheritDoc}
473      */
474     @Override
475     public ObjectName lookupConfigBean(String moduleName, String instanceName)
476             throws InstanceNotFoundException {
477         return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
478     }
479
480     /**
481      * {@inheritDoc}
482      */
483     @Override
484     public Set<ObjectName> lookupConfigBeans(String moduleName,
485             String instanceName) {
486         ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
487                 instanceName);
488         return baseJMXRegistrator.queryNames(namePattern, null);
489     }
490
491     /**
492      * {@inheritDoc}
493      */
494     @Override
495     public Set<ObjectName> lookupRuntimeBeans() {
496         return lookupRuntimeBeans("*", "*");
497     }
498
499     /**
500      * {@inheritDoc}
501      */
502     @Override
503     public Set<ObjectName> lookupRuntimeBeans(String moduleName,
504             String instanceName) {
505         if (moduleName == null)
506             moduleName = "*";
507         if (instanceName == null)
508             instanceName = "*";
509         ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
510                 moduleName, instanceName);
511         return baseJMXRegistrator.queryNames(namePattern, null);
512     }
513
514     @Override
515     public void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException {
516         ObjectNameUtil.checkDomain(objectName);
517         ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
518         String transactionName = ObjectNameUtil.getTransactionName(objectName);
519         if (transactionName != null) {
520             throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
521         }
522         // make sure exactly one match is found:
523         LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
524     }
525
526     // service reference functionality:
527     @Override
528     public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceName, String refName) {
529         return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceName, refName);
530     }
531
532     @Override
533     public synchronized Map<String, Map<String, ObjectName>> getServiceMapping() {
534         return readableSRRegistry.getServiceMapping();
535     }
536
537     @Override
538     public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceName) {
539         return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceName);
540     }
541
542     @Override
543     public synchronized Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException {
544         return readableSRRegistry.lookupServiceInterfaceNames(objectName);
545     }
546
547     @Override
548     public synchronized String getServiceInterfaceName(String namespace, String localName) {
549         return readableSRRegistry.getServiceInterfaceName(namespace, localName);
550     }
551
552     @Override
553     public Set<String> getAvailableModuleFactoryQNames() {
554         return ModuleQNameUtil.getQNames(resolver.getAllFactories());
555     }
556
557 }
558
559 /**
560  * Holds currently running modules
561  */
562 @NotThreadSafe
563 class ConfigHolder {
564     private final Map<ModuleIdentifier, ModuleInternalInfo> currentConfig = new HashMap<>();
565
566     /**
567      * Add all modules to the internal map. Also add service instance to OSGi
568      * Service Registry.
569      */
570     public void addAll(Collection<ModuleInternalInfo> configInfos) {
571         if (currentConfig.size() > 0) {
572             throw new IllegalStateException(
573                     "Error - some config entries were not removed: "
574                             + currentConfig);
575         }
576         for (ModuleInternalInfo configInfo : configInfos) {
577             add(configInfo);
578         }
579     }
580
581     private void add(ModuleInternalInfo configInfo) {
582         ModuleInternalInfo oldValue = currentConfig.put(configInfo.getName(),
583                 configInfo);
584         if (oldValue != null) {
585             throw new IllegalStateException(
586                     "Cannot overwrite module with same name:"
587                             + configInfo.getName() + ":" + configInfo);
588         }
589     }
590
591     /**
592      * Remove entry from current config.
593      */
594     public void remove(ModuleIdentifier name) {
595         ModuleInternalInfo removed = currentConfig.remove(name);
596         if (removed == null) {
597             throw new IllegalStateException(
598                     "Cannot remove from ConfigHolder - name not found:" + name);
599         }
600     }
601
602     public Collection<ModuleInternalInfo> getEntries() {
603         return currentConfig.values();
604     }
605
606     public List<DestroyedModule> getModulesToBeDestroyed() {
607         List<DestroyedModule> result = new ArrayList<>();
608         for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
609             result.add(moduleInternalInfo.toDestroyedModule());
610         }
611         Collections.sort(result);
612         return result;
613     }
614
615
616 }
617
618 /**
619  * Holds Map<transactionName, transactionController> and purges it each time its
620  * content is requested.
621  */
622 @NotThreadSafe
623 class TransactionsHolder {
624     /**
625      * This map keeps transaction names and
626      * {@link ConfigTransactionControllerInternal} instances, because platform
627      * MBeanServer transforms mbeans into another representation. Map is cleaned
628      * every time current transactions are requested.
629      *
630      */
631     @GuardedBy("ConfigRegistryImpl.this")
632     private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
633
634     /**
635      * Can only be called from within synchronized method.
636      */
637     public void add(String transactionName,
638             ConfigTransactionControllerInternal transactionController) {
639         Object oldValue = transactions.put(transactionName,
640                 transactionController);
641         if (oldValue != null) {
642             throw new IllegalStateException(
643                     "Error: two transactions with same name");
644         }
645     }
646
647     /**
648      * Purges closed transactions from transactions map. Can only be called from
649      * within synchronized method. Calling this method more than once within the
650      * method can modify the resulting map that was obtained in previous calls.
651      *
652      * @return current view on transactions map.
653      */
654     public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
655         // first, remove closed transaction
656         for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
657                 .entrySet().iterator(); it.hasNext();) {
658             Entry<String, ConfigTransactionControllerInternal> entry = it
659                     .next();
660             if (entry.getValue().isClosed()) {
661                 it.remove();
662             }
663         }
664         return Collections.unmodifiableMap(transactions);
665     }
666 }