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