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