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