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