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