2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.config.manager.impl;
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;
20 import java.util.Map.Entry;
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;
62 * Singleton that is responsible for creating and committing Config
63 * Transactions. It is registered in Platform MBean Server.
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");
70 private final ModuleFactoriesResolver resolver;
71 private final MBeanServer configMBeanServer;
72 private final BindingContextProvider bindingContextProvider;
74 private volatile long version = 0;
75 private volatile long versionCounter = 0;
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.
82 private final ConfigHolder currentConfig = new ConfigHolder();
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.
89 private volatile boolean isHealthy = true;
92 * Holds Map<transactionName, transactionController> and purges it each time
93 * its content is requested.
95 private final TransactionsHolder transactionsHolder = new TransactionsHolder();
97 private final BaseJMXRegistrator baseJMXRegistrator;
99 private final BeanToOsgiServiceManager beanToOsgiServiceManager;
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;
106 private final AtomicBoolean closed = new AtomicBoolean();
108 private final Object readableSRRegistryLock = new Object();
110 private final Lock configTransactionLock = new ReentrantLock();
112 // Used for finding new factory instances for default module functionality
113 @GuardedBy("configTransactionLock")
114 private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
116 // switched in every 2ndPC
117 @GuardedBy("readableSRRegistryLock")
118 private CloseableServiceReferenceReadableRegistry readableSRRegistry =
119 ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
122 public ConfigRegistryImpl(final ModuleFactoriesResolver resolver,
123 final MBeanServer configMBeanServer, final BindingContextProvider bindingContextProvider) {
124 this(resolver, configMBeanServer,
125 new BaseJMXRegistrator(configMBeanServer), bindingContextProvider);
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());
144 * Create new {@link ConfigTransactionControllerImpl }
147 public ObjectName beginConfig() {
148 return beginConfig(false);
152 * @param blankTransaction true if this transaction is created automatically by
153 * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
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.
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".
168 if(blankTransaction) {
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
173 if(!configTransactionLock.tryLock(5, TimeUnit.SECONDS)) {
174 LOG.debug("Timed out trying to obtain configTransactionLock");
177 } catch(final InterruptedException e) {
178 LOG.debug("Interrupted trying to obtain configTransactionLock", e);
179 Thread.currentThread().interrupt();
183 configTransactionLock.lock();
187 return beginConfigSafe(blankTransaction).getControllerObjectName();
189 configTransactionLock.unlock();
193 @GuardedBy("configTransactionLock")
194 private ConfigTransactionControllerInternal beginConfigSafe(final boolean blankTransaction) {
196 final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
198 TransactionJMXRegistratorFactory factory =
199 () -> baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
201 Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
202 resolver.getAllFactories());
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()));
213 allCurrentFactories = Collections.unmodifiableMap(allCurrentFactories);
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);
221 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
222 txLookupRegistry, version, bindingContextProvider,
223 versionCounter, allCurrentFactories, transactionsMBeanServer,
224 configMBeanServer, blankTransaction, writableRegistry);
226 txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
227 } catch (final InstanceAlreadyExistsException e) {
228 throw new IllegalStateException(e);
230 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
231 transactionsHolder.add(transactionName, transactionController, txLookupRegistry);
232 return transactionController;
237 * @throws ConflictingVersionException
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());
246 configTransactionLock.lock();
248 return commitConfigSafe(transactionControllerON);
250 configTransactionLock.unlock();
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);
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));
268 ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
269 // check optimistic lock
270 if (version != configTransactionController.getParentVersion()) {
271 throw new ConflictingVersionException(
273 "Optimistic lock failed. Expected parent version %d, was %d",
275 configTransactionController.getParentVersion()));
277 // optimistic lock ok
279 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
280 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
281 // non recoverable from here:
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) {
288 LOG.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
289 throw Throwables.propagate(t);
293 @GuardedBy("configTransactionLock")
294 private CommitStatus secondPhaseCommit(final ConfigTransactionControllerInternal configTransactionController,
295 final CommitInfo commitInfo, final ConfigTransactionLookupRegistry txLookupRegistry) {
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
305 toBeDestroyed.close();
306 currentConfig.remove(toBeDestroyed.getIdentifier());
309 // set RuntimeBeanRegistrators on beans implementing
310 // RuntimeBeanRegistratorAwareModule
311 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
312 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
314 // set runtime jmx registrator if required
315 Module module = entry.getProxiedModule();
316 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = null;
318 if (module instanceof RuntimeBeanRegistratorAwareModule) {
320 if(entry.hasOldModule()) {
322 if(module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
323 runtimeBeanRegistrator = entry.getOldInternalInfo().getRuntimeBeanRegistrator();
324 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
326 runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
327 entry.getOldInternalInfo().getRuntimeBeanRegistrator().close();
328 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
331 runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
332 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
335 // save it to info so it is accessible afterwards
336 if(runtimeBeanRegistrator != null) {
337 runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
341 // can register runtime beans
342 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController.secondPhaseCommit();
343 txLookupRegistry.close();
344 configTransactionController.close();
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<>();
351 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
354 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
355 LOG.trace("Registering {}", moduleIdentifier);
356 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
357 .get(moduleIdentifier);
359 throw new NullPointerException("Module not found "
363 ObjectName primaryReadOnlyON = ObjectNameUtil
364 .createReadOnlyModuleON(moduleIdentifier);
366 // determine if current instance was recreated or reused or is new
368 // rules for closing resources:
369 // osgi registration - will be reused if possible.
370 // module jmx registration - will be (re)created every time, needs
372 // runtime jmx registration - should be taken care of by module
374 // instance - is closed only if it was destroyed
375 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
376 .createModuleJMXRegistrator();
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());
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();
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);
397 // close old osgi registration
398 oldInternalInfo.getOsgiRegistration().close();
401 // close old module jmx registrator
402 oldInternalInfo.getModuleJMXRegistrator().close();
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();
410 // wrap in readable dynamic mbean
411 newInstances.add(primaryReadOnlyON);
413 Module realModule = entry.getRealModule();
415 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
416 realModule, instance, moduleIdentifier,
417 registryMBeanServer, configMBeanServer);
421 newModuleJMXRegistrator.registerMBean(newReadableConfigBean, primaryReadOnlyON);
422 } catch (final InstanceAlreadyExistsException e) {
423 throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON,e);
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);
434 osgiRegistration.updateRegistrations(annotationMapping, bc, instance);
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());
444 newConfigEntries.put(realModule, newInfo);
447 currentConfig.addAll(newConfigEntries.values());
450 version = configTransactionController.getVersion();
452 // switch readable Service Reference Registry
453 synchronized(readableSRRegistryLock) {
454 readableSRRegistry.close();
455 readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
456 configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
459 return new CommitStatus(newInstances, reusedInstances,
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
473 result.add(configTransactionControllerEntry.getKey().getControllerObjectName());
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
485 public void close() {
486 if(!closed.compareAndSet(false, true)) {
490 // abort transactions
491 Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
492 .getCurrentTransactions();
493 for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
496 ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
498 configTransactionControllerEntry.getValue().close();
499 configTransactionController.abortConfig();
500 } catch (final RuntimeException e) {
501 LOG.debug("Ignoring exception while aborting {}", configTransactionController, e);
505 // destroy all live objects one after another in order of the dependency hierarchy, from top to bottom
506 List<DestroyedModule> destroyedModules = currentConfig.getModulesToBeDestroyed();
508 LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size());
510 for (DestroyedModule destroyedModule : destroyedModules) {
511 destroyedModule.close();
513 // unregister MBeans that failed to unregister properly
514 baseJMXRegistrator.close();
515 // remove jmx servers
516 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
517 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
519 LOG.info("ConfigRegistry closed");
526 public long getVersion() {
534 public Set<String> getAvailableModuleNames() {
535 return new HierarchicalConfigMBeanFactoriesHolder(
536 resolver.getAllFactories()).getModuleNames();
543 public boolean isHealthy() {
553 public Set<ObjectName> lookupConfigBeans() {
554 return lookupConfigBeans("*", "*");
561 public Set<ObjectName> lookupConfigBeans(final String moduleName) {
562 return lookupConfigBeans(moduleName, "*");
569 public ObjectName lookupConfigBean(final String moduleName, final String instanceName)
570 throws InstanceNotFoundException {
571 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
578 public Set<ObjectName> lookupConfigBeans(final String moduleName,
579 final String instanceName) {
580 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
582 return baseJMXRegistrator.queryNames(namePattern, null);
589 public Set<ObjectName> lookupRuntimeBeans() {
590 return lookupRuntimeBeans("*", "*");
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);
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);
614 // make sure exactly one match is found:
615 LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
618 // service reference functionality:
620 public ObjectName lookupConfigBeanByServiceInterfaceName(final String serviceInterfaceQName, final String refName) {
621 synchronized(readableSRRegistryLock) {
622 return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
627 public Map<String, Map<String, ObjectName>> getServiceMapping() {
628 synchronized(readableSRRegistryLock) {
629 return readableSRRegistry.getServiceMapping();
634 public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(final String serviceInterfaceQName) {
635 synchronized(readableSRRegistryLock) {
636 return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
641 public Set<String> lookupServiceInterfaceNames(final ObjectName objectName) throws InstanceNotFoundException {
642 synchronized(readableSRRegistryLock) {
643 return readableSRRegistry.lookupServiceInterfaceNames(objectName);
648 public String getServiceInterfaceName(final String namespace, final String localName) {
649 synchronized(readableSRRegistryLock) {
650 return readableSRRegistry.getServiceInterfaceName(namespace, localName);
655 public void checkServiceReferenceExists(final ObjectName objectName) throws InstanceNotFoundException {
656 synchronized(readableSRRegistryLock) {
657 readableSRRegistry.checkServiceReferenceExists(objectName);
662 public ObjectName getServiceReference(final String serviceInterfaceQName, final String refName) throws InstanceNotFoundException {
663 synchronized(readableSRRegistryLock) {
664 return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
669 public Set<String> getAvailableModuleFactoryQNames() {
670 return ModuleQNameUtil.getQNames(resolver.getAllFactories());
674 public String toString() {
675 return "ConfigRegistryImpl{" +
676 "versionCounter=" + versionCounter +
677 ", version=" + version +
683 * Holds currently running modules
686 private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
689 * Add all modules to the internal map. Also add service instance to OSGi
692 public void addAll(final Collection<ModuleInternalInfo> configInfos) {
693 if (!currentConfig.isEmpty()) {
694 throw new IllegalStateException(
695 "Error - some config entries were not removed: "
698 for (ModuleInternalInfo configInfo : configInfos) {
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);
713 * Remove entry from current config.
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);
723 public Collection<ModuleInternalInfo> getEntries() {
724 return currentConfig.values();
727 public List<DestroyedModule> getModulesToBeDestroyed() {
728 List<DestroyedModule> result = new ArrayList<>();
729 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
730 result.add(moduleInternalInfo.toDestroyedModule());
732 Collections.sort(result);
740 * Holds Map<transactionName, transactionController> and purges it each time its
741 * content is requested.
743 class TransactionsHolder {
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.
750 private final ConcurrentMap<String /* transactionName */,
751 Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
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");
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.
767 * @return current view on transactions map.
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
775 if (entry.getValue().getKey().isClosed()) {
779 return Collections.unmodifiableMap(transactions);