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