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.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;
19 import java.util.Map.Entry;
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;
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 @GuardedBy("readableSRRegistryLock") // switched in every 2ndPC
117 private CloseableServiceReferenceReadableRegistry readableSRRegistry =
118 ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
121 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
122 MBeanServer configMBeanServer, BindingContextProvider bindingContextProvider) {
123 this(resolver, configMBeanServer,
124 new BaseJMXRegistrator(configMBeanServer), bindingContextProvider);
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());
143 * Create new {@link ConfigTransactionControllerImpl }
146 public ObjectName beginConfig() {
147 return beginConfig(false);
151 * @param blankTransaction true if this transaction is created automatically by
152 * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
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.
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".
167 if(blankTransaction) {
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
172 if(!configTransactionLock.tryLock(5, TimeUnit.SECONDS)) {
173 LOG.debug("Timed out trying to obtain configTransactionLock");
176 } catch(InterruptedException e) {
177 LOG.debug("Interrupted trying to obtain configTransactionLock", e);
178 Thread.currentThread().interrupt();
182 configTransactionLock.lock();
186 return beginConfigSafe(blankTransaction).getControllerObjectName();
188 configTransactionLock.unlock();
192 @GuardedBy("configTransactionLock")
193 private ConfigTransactionControllerInternal beginConfigSafe(boolean blankTransaction) {
195 final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
197 TransactionJMXRegistratorFactory factory = new TransactionJMXRegistratorFactory() {
199 public TransactionJMXRegistrator create() {
200 return baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
204 Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
205 resolver.getAllFactories());
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()));
216 allCurrentFactories = Collections.unmodifiableMap(allCurrentFactories);
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);
224 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
225 txLookupRegistry, version, bindingContextProvider,
226 versionCounter, allCurrentFactories, transactionsMBeanServer,
227 configMBeanServer, blankTransaction, writableRegistry);
229 txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
230 } catch (InstanceAlreadyExistsException e) {
231 throw new IllegalStateException(e);
233 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
234 transactionsHolder.add(transactionName, transactionController, txLookupRegistry);
235 return transactionController;
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());
248 configTransactionLock.lock();
250 return commitConfigSafe(transactionControllerON);
252 configTransactionLock.unlock();
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);
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));
270 ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
271 // check optimistic lock
272 if (version != configTransactionController.getParentVersion()) {
273 throw new ConflictingVersionException(
275 "Optimistic lock failed. Expected parent version %d, was %d",
277 configTransactionController.getParentVersion()));
279 // optimistic lock ok
281 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
282 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
283 // non recoverable from here:
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
289 LOG.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
290 if (t instanceof RuntimeException) {
291 throw (RuntimeException) t;
298 @GuardedBy("configTransactionLock")
299 private CommitStatus secondPhaseCommit(ConfigTransactionControllerInternal configTransactionController,
300 CommitInfo commitInfo, ConfigTransactionLookupRegistry txLookupRegistry) {
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
310 currentConfig.remove(toBeDestroyed.getIdentifier());
313 // set RuntimeBeanRegistrators on beans implementing
314 // RuntimeBeanRegistratorAwareModule
315 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
316 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
318 // set runtime jmx registrator if required
319 Module module = entry.getProxiedModule();
320 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = null;
322 if (module instanceof RuntimeBeanRegistratorAwareModule) {
324 if(entry.hasOldModule()) {
326 if(module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
327 runtimeBeanRegistrator = entry.getOldInternalInfo().getRuntimeBeanRegistrator();
328 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
330 runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
331 entry.getOldInternalInfo().getRuntimeBeanRegistrator().close();
332 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
335 runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
336 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
339 // save it to info so it is accessible afterwards
340 if(runtimeBeanRegistrator != null) {
341 runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
345 // can register runtime beans
346 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController.secondPhaseCommit();
347 txLookupRegistry.close();
348 configTransactionController.close();
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<>();
355 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
358 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
359 LOG.trace("Registering {}", moduleIdentifier);
360 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
361 .get(moduleIdentifier);
363 throw new NullPointerException("Module not found "
367 ObjectName primaryReadOnlyON = ObjectNameUtil
368 .createReadOnlyModuleON(moduleIdentifier);
370 // determine if current instance was recreated or reused or is new
372 // rules for closing resources:
373 // osgi registration - will be reused if possible.
374 // module jmx registration - will be (re)created every time, needs
376 // runtime jmx registration - should be taken care of by module
378 // instance - is closed only if it was destroyed
379 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
380 .createModuleJMXRegistrator();
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());
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();
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);
401 // close old osgi registration
402 oldInternalInfo.getOsgiRegistration().close();
405 // close old module jmx registrator
406 oldInternalInfo.getModuleJMXRegistrator().close();
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();
414 // wrap in readable dynamic mbean
415 newInstances.add(primaryReadOnlyON);
417 Module realModule = entry.getRealModule();
419 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
420 realModule, instance, moduleIdentifier,
421 registryMBeanServer, configMBeanServer);
425 newModuleJMXRegistrator.registerMBean(newReadableConfigBean, primaryReadOnlyON);
426 } catch (InstanceAlreadyExistsException e) {
427 throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON,e);
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);
438 osgiRegistration.updateRegistrations(annotationMapping, bc, instance);
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());
448 newConfigEntries.put(realModule, newInfo);
451 currentConfig.addAll(newConfigEntries.values());
454 version = configTransactionController.getVersion();
456 // switch readable Service Reference Registry
457 synchronized(readableSRRegistryLock) {
458 readableSRRegistry.close();
459 readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
460 configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
463 return new CommitStatus(newInstances, reusedInstances,
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
477 result.add(configTransactionControllerEntry.getKey().getControllerObjectName());
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
489 public void close() {
490 if(!closed.compareAndSet(false, true)) {
494 // abort transactions
495 Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
496 .getCurrentTransactions();
497 for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
500 ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
502 configTransactionControllerEntry.getValue().close();
503 configTransactionController.abortConfig();
504 } catch (RuntimeException e) {
505 LOG.debug("Ignoring exception while aborting {}", configTransactionController, e);
509 // destroy all live objects one after another in order of the dependency hierarchy, from top to bottom
510 List<DestroyedModule> destroyedModules = currentConfig.getModulesToBeDestroyed();
512 LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size());
514 for (DestroyedModule destroyedModule : destroyedModules) {
515 destroyedModule.close();
517 // unregister MBeans that failed to unregister properly
518 baseJMXRegistrator.close();
519 // remove jmx servers
520 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
521 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
523 LOG.info("ConfigRegistry closed");
530 public long getVersion() {
538 public Set<String> getAvailableModuleNames() {
539 return new HierarchicalConfigMBeanFactoriesHolder(
540 resolver.getAllFactories()).getModuleNames();
547 public boolean isHealthy() {
557 public Set<ObjectName> lookupConfigBeans() {
558 return lookupConfigBeans("*", "*");
565 public Set<ObjectName> lookupConfigBeans(String moduleName) {
566 return lookupConfigBeans(moduleName, "*");
573 public ObjectName lookupConfigBean(String moduleName, String instanceName)
574 throws InstanceNotFoundException {
575 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
582 public Set<ObjectName> lookupConfigBeans(String moduleName,
583 String instanceName) {
584 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
586 return baseJMXRegistrator.queryNames(namePattern, null);
593 public Set<ObjectName> lookupRuntimeBeans() {
594 return lookupRuntimeBeans("*", "*");
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);
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);
618 // make sure exactly one match is found:
619 LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
622 // service reference functionality:
624 public ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceQName, String refName) {
625 synchronized(readableSRRegistryLock) {
626 return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
631 public Map<String, Map<String, ObjectName>> getServiceMapping() {
632 synchronized(readableSRRegistryLock) {
633 return readableSRRegistry.getServiceMapping();
638 public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceQName) {
639 synchronized(readableSRRegistryLock) {
640 return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
645 public Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException {
646 synchronized(readableSRRegistryLock) {
647 return readableSRRegistry.lookupServiceInterfaceNames(objectName);
652 public String getServiceInterfaceName(String namespace, String localName) {
653 synchronized(readableSRRegistryLock) {
654 return readableSRRegistry.getServiceInterfaceName(namespace, localName);
659 public void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException {
660 synchronized(readableSRRegistryLock) {
661 readableSRRegistry.checkServiceReferenceExists(objectName);
666 public ObjectName getServiceReference(String serviceInterfaceQName, String refName) throws InstanceNotFoundException {
667 synchronized(readableSRRegistryLock) {
668 return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
673 public Set<String> getAvailableModuleFactoryQNames() {
674 return ModuleQNameUtil.getQNames(resolver.getAllFactories());
678 public String toString() {
679 return "ConfigRegistryImpl{" +
680 "versionCounter=" + versionCounter +
681 ", version=" + version +
687 * Holds currently running modules
690 private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
693 * Add all modules to the internal map. Also add service instance to OSGi
696 public void addAll(Collection<ModuleInternalInfo> configInfos) {
697 if (!currentConfig.isEmpty()) {
698 throw new IllegalStateException(
699 "Error - some config entries were not removed: "
702 for (ModuleInternalInfo configInfo : configInfos) {
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);
717 * Remove entry from current config.
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);
727 public Collection<ModuleInternalInfo> getEntries() {
728 return currentConfig.values();
731 public List<DestroyedModule> getModulesToBeDestroyed() {
732 List<DestroyedModule> result = new ArrayList<>();
733 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
734 result.add(moduleInternalInfo.toDestroyedModule());
736 Collections.sort(result);
744 * Holds Map<transactionName, transactionController> and purges it each time its
745 * content is requested.
747 class TransactionsHolder {
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.
754 private final ConcurrentMap<String /* transactionName */,
755 Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
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");
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.
771 * @return current view on transactions map.
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
779 if (entry.getValue().getKey().isClosed()) {
783 return Collections.unmodifiableMap(transactions);