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