Fixed netconf monitoring.
[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.spi.Module;
29 import org.opendaylight.controller.config.spi.ModuleFactory;
30 import org.osgi.framework.BundleContext;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 import javax.annotation.concurrent.GuardedBy;
35 import javax.annotation.concurrent.NotThreadSafe;
36 import javax.annotation.concurrent.ThreadSafe;
37 import javax.management.InstanceAlreadyExistsException;
38 import javax.management.InstanceNotFoundException;
39 import javax.management.MBeanServer;
40 import javax.management.MBeanServerFactory;
41 import javax.management.ObjectName;
42 import java.util.ArrayList;
43 import java.util.Collection;
44 import java.util.Collections;
45 import java.util.HashMap;
46 import java.util.Iterator;
47 import java.util.LinkedList;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Map.Entry;
51 import java.util.Set;
52
53 /**
54  * Singleton that is responsible for creating and committing Config
55  * Transactions. It is registered in Platform MBean Server.
56  */
57 @ThreadSafe
58 public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
59     private static final Logger logger = LoggerFactory.getLogger(ConfigRegistryImpl.class);
60
61     private final ModuleFactoriesResolver resolver;
62     private final MBeanServer configMBeanServer;
63
64     @GuardedBy("this")
65     private final BundleContext bundleContext;
66
67     @GuardedBy("this")
68     private long version = 0;
69     @GuardedBy("this")
70     private long versionCounter = 0;
71
72     /**
73      * Contains current configuration in form of {moduleName:{instanceName,read
74      * only module}} for copying state to new transaction. Each running module
75      * is present just once, no matter how many interfaces it exposes.
76      */
77     @GuardedBy("this")
78     private final ConfigHolder currentConfig = new ConfigHolder();
79
80     /**
81      * Will return true unless there was a transaction that succeeded during
82      * validation but failed in second phase of commit. In this case the server
83      * is unstable and its state is undefined.
84      */
85     @GuardedBy("this")
86     private boolean isHealthy = true;
87
88     /**
89      * Holds Map<transactionName, transactionController> and purges it each time
90      * its content is requested.
91      */
92     @GuardedBy("this")
93     private final TransactionsHolder transactionsHolder = new TransactionsHolder();
94
95     private final BaseJMXRegistrator baseJMXRegistrator;
96
97     private final BeanToOsgiServiceManager beanToOsgiServiceManager;
98
99     // internal jmx server for read only beans
100     private final MBeanServer registryMBeanServer;
101     // internal jmx server shared by all transactions
102     private final MBeanServer transactionsMBeanServer;
103
104     @GuardedBy("this")
105     private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
106
107     @GuardedBy("this") // switched in every 2ndPC
108     private ServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
109
110     // constructor
111     public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
112             BundleContext bundleContext, MBeanServer configMBeanServer) {
113         this(resolver, bundleContext, configMBeanServer,
114                 new BaseJMXRegistrator(configMBeanServer));
115     }
116
117     // constructor
118     public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
119             BundleContext bundleContext, MBeanServer configMBeanServer,
120             BaseJMXRegistrator baseJMXRegistrator) {
121         this.resolver = resolver;
122         this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
123         this.bundleContext = bundleContext;
124         this.configMBeanServer = configMBeanServer;
125         this.baseJMXRegistrator = baseJMXRegistrator;
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         ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(new TransactionIdentifier(
160                 transactionName), factory);
161         Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = Collections.unmodifiableMap(
162                 resolver.getAllFactories());
163         ServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
164                 readableSRRegistry, txLookupRegistry, allCurrentFactories);
165
166         ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
167                 txLookupRegistry, version,
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.info("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
304                         .getReadableModule();
305                 currentConfig.remove(entry.getIdentifier());
306
307                 // test if old instance == new instance
308                 if (oldReadableConfigBean.getInstance().equals(module.getInstance())) {
309                     // reused old instance:
310                     // wrap in readable dynamic mbean
311                     reusedInstances.add(primaryReadOnlyON);
312                     osgiRegistration = oldInternalInfo.getOsgiRegistration();
313                 } else {
314                     // recreated instance:
315                     // it is responsibility of module to call the old instance -
316                     // we just need to unregister configbean
317                     recreatedInstances.add(primaryReadOnlyON);
318
319                     // close old osgi registration
320                     oldInternalInfo.getOsgiRegistration().close();
321                 }
322
323                 // close old module jmx registrator
324                 oldInternalInfo.getModuleJMXRegistrator().close();
325             } else {
326                 // new instance:
327                 // wrap in readable dynamic mbean
328                 newInstances.add(primaryReadOnlyON);
329             }
330
331             DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
332                     module, module.getInstance(), moduleIdentifier,
333                     registryMBeanServer, configMBeanServer);
334
335             // register to JMX
336             try {
337                 newModuleJMXRegistrator.registerMBean(newReadableConfigBean,
338                         primaryReadOnlyON);
339             } catch (InstanceAlreadyExistsException e) {
340                 throw new IllegalStateException(e);
341             }
342
343             // register to OSGi
344             if (osgiRegistration == null) {
345                 ModuleFactory moduleFactory = entry.getModuleFactory();
346                 if(moduleFactory != null) {
347                     BundleContext bc = configTransactionController.
348                             getModuleFactoryBundleContext(moduleFactory.getImplementationName());
349                     osgiRegistration = beanToOsgiServiceManager.registerToOsgi(module.getClass(),
350                             newReadableConfigBean.getInstance(), entry.getIdentifier(), bc);
351                 } else {
352                     throw new NullPointerException(entry.getIdentifier().getFactoryName() + " ModuleFactory not found.");
353                 }
354
355             }
356
357             RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
358                     .get(entry.getIdentifier());
359             ModuleInternalInfo newInfo = new ModuleInternalInfo(
360                     entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
361                     runtimeBeanRegistrator, newModuleJMXRegistrator,
362                     orderingIdx, entry.isDefaultBean());
363
364             newConfigEntries.put(module, newInfo);
365             orderingIdx++;
366         }
367         currentConfig.addAll(newConfigEntries.values());
368
369         // update version
370         version = configTransactionController.getVersion();
371
372         // switch readable Service Reference Registry
373         this.readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(configTransactionController.getWritableRegistry(), this);
374
375         return new CommitStatus(newInstances, reusedInstances,
376                 recreatedInstances);
377     }
378
379     /**
380      * {@inheritDoc}
381      */
382     @Override
383     public synchronized List<ObjectName> getOpenConfigs() {
384         Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
385                 .getCurrentTransactions();
386         List<ObjectName> result = new ArrayList<>(transactions.size());
387         for (ConfigTransactionControllerInternal configTransactionController : transactions
388                 .values()) {
389             result.add(configTransactionController.getControllerObjectName());
390         }
391         return result;
392     }
393
394     /**
395      * Abort open transactions and unregister read only modules. Since this
396      * class is not responsible for registering itself under
397      * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
398      * here.
399      */
400     @Override
401     public synchronized void close() {
402         // abort transactions
403         Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
404                 .getCurrentTransactions();
405         for (ConfigTransactionControllerInternal configTransactionController : transactions
406                 .values()) {
407             try {
408                 configTransactionController.abortConfig();
409             } catch (RuntimeException e) {
410                 logger.warn("Ignoring exception while aborting {}",
411                         configTransactionController, e);
412             }
413         }
414
415         // destroy all live objects one after another in order of the dependency
416         // hierarchy
417         List<DestroyedModule> destroyedModules = currentConfig
418                 .getModulesToBeDestroyed();
419         for (DestroyedModule destroyedModule : destroyedModules) {
420             destroyedModule.close();
421         }
422         // unregister MBeans that failed to unregister properly
423         baseJMXRegistrator.close();
424         // remove jmx servers
425         MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
426         MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
427
428     }
429
430     /**
431      * {@inheritDoc}
432      */
433     @Override
434     public long getVersion() {
435         return version;
436     }
437
438     /**
439      * {@inheritDoc}
440      */
441     @Override
442     public Set<String> getAvailableModuleNames() {
443         return new HierarchicalConfigMBeanFactoriesHolder(
444                 resolver.getAllFactories()).getModuleNames();
445     }
446
447     /**
448      * {@inheritDoc}
449      */
450     @Override
451     public boolean isHealthy() {
452         return isHealthy;
453     }
454
455     // filtering methods
456
457     /**
458      * {@inheritDoc}
459      */
460     @Override
461     public Set<ObjectName> lookupConfigBeans() {
462         return lookupConfigBeans("*", "*");
463     }
464
465     /**
466      * {@inheritDoc}
467      */
468     @Override
469     public Set<ObjectName> lookupConfigBeans(String moduleName) {
470         return lookupConfigBeans(moduleName, "*");
471     }
472
473     /**
474      * {@inheritDoc}
475      */
476     @Override
477     public ObjectName lookupConfigBean(String moduleName, String instanceName)
478             throws InstanceNotFoundException {
479         return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
480     }
481
482     /**
483      * {@inheritDoc}
484      */
485     @Override
486     public Set<ObjectName> lookupConfigBeans(String moduleName,
487             String instanceName) {
488         ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
489                 instanceName);
490         return baseJMXRegistrator.queryNames(namePattern, null);
491     }
492
493     /**
494      * {@inheritDoc}
495      */
496     @Override
497     public Set<ObjectName> lookupRuntimeBeans() {
498         return lookupRuntimeBeans("*", "*");
499     }
500
501     /**
502      * {@inheritDoc}
503      */
504     @Override
505     public Set<ObjectName> lookupRuntimeBeans(String moduleName,
506             String instanceName) {
507         if (moduleName == null)
508             moduleName = "*";
509         if (instanceName == null)
510             instanceName = "*";
511         ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
512                 moduleName, instanceName);
513         return baseJMXRegistrator.queryNames(namePattern, null);
514     }
515
516     @Override
517     public void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException {
518         ObjectNameUtil.checkDomain(objectName);
519         ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
520         String transactionName = ObjectNameUtil.getTransactionName(objectName);
521         if (transactionName != null) {
522             throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
523         }
524         // make sure exactly one match is found:
525         LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
526     }
527
528     // service reference functionality:
529     @Override
530     public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceName, String refName) {
531         return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceName, refName);
532     }
533
534     @Override
535     public synchronized Map<String, Map<String, ObjectName>> getServiceMapping() {
536         return readableSRRegistry.getServiceMapping();
537     }
538
539     @Override
540     public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceName) {
541         return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceName);
542     }
543
544     @Override
545     public synchronized Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException {
546         return readableSRRegistry.lookupServiceInterfaceNames(objectName);
547     }
548
549     @Override
550     public synchronized String getServiceInterfaceName(String namespace, String localName) {
551         return readableSRRegistry.getServiceInterfaceName(namespace, localName);
552     }
553 }
554
555 /**
556  * Holds currently running modules
557  */
558 @NotThreadSafe
559 class ConfigHolder {
560     private final Map<ModuleIdentifier, ModuleInternalInfo> currentConfig = new HashMap<>();
561
562     /**
563      * Add all modules to the internal map. Also add service instance to OSGi
564      * Service Registry.
565      */
566     public void addAll(Collection<ModuleInternalInfo> configInfos) {
567         if (currentConfig.size() > 0) {
568             throw new IllegalStateException(
569                     "Error - some config entries were not removed: "
570                             + currentConfig);
571         }
572         for (ModuleInternalInfo configInfo : configInfos) {
573             add(configInfo);
574         }
575     }
576
577     private void add(ModuleInternalInfo configInfo) {
578         ModuleInternalInfo oldValue = currentConfig.put(configInfo.getName(),
579                 configInfo);
580         if (oldValue != null) {
581             throw new IllegalStateException(
582                     "Cannot overwrite module with same name:"
583                             + configInfo.getName() + ":" + configInfo);
584         }
585     }
586
587     /**
588      * Remove entry from current config.
589      */
590     public void remove(ModuleIdentifier name) {
591         ModuleInternalInfo removed = currentConfig.remove(name);
592         if (removed == null) {
593             throw new IllegalStateException(
594                     "Cannot remove from ConfigHolder - name not found:" + name);
595         }
596     }
597
598     public Collection<ModuleInternalInfo> getEntries() {
599         return currentConfig.values();
600     }
601
602     public List<DestroyedModule> getModulesToBeDestroyed() {
603         List<DestroyedModule> result = new ArrayList<>();
604         for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
605             result.add(moduleInternalInfo.toDestroyedModule());
606         }
607         Collections.sort(result);
608         return result;
609     }
610 }
611
612 /**
613  * Holds Map<transactionName, transactionController> and purges it each time its
614  * content is requested.
615  */
616 @NotThreadSafe
617 class TransactionsHolder {
618     /**
619      * This map keeps transaction names and
620      * {@link ConfigTransactionControllerInternal} instances, because platform
621      * MBeanServer transforms mbeans into another representation. Map is cleaned
622      * every time current transactions are requested.
623      *
624      */
625     @GuardedBy("ConfigRegistryImpl.this")
626     private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
627
628     /**
629      * Can only be called from within synchronized method.
630      */
631     public void add(String transactionName,
632             ConfigTransactionControllerInternal transactionController) {
633         Object oldValue = transactions.put(transactionName,
634                 transactionController);
635         if (oldValue != null) {
636             throw new IllegalStateException(
637                     "Error: two transactions with same name");
638         }
639     }
640
641     /**
642      * Purges closed transactions from transactions map. Can only be called from
643      * within synchronized method. Calling this method more than once within the
644      * method can modify the resulting map that was obtained in previous calls.
645      *
646      * @return current view on transactions map.
647      */
648     public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
649         // first, remove closed transaction
650         for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
651                 .entrySet().iterator(); it.hasNext();) {
652             Entry<String, ConfigTransactionControllerInternal> entry = it
653                     .next();
654             if (entry.getValue().isClosed()) {
655                 it.remove();
656             }
657         }
658         return Collections.unmodifiableMap(transactions);
659     }
660 }