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