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