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.jmx.TransactionJMXRegistrator;
51 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager;
52 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
53 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
54 import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
55 import org.opendaylight.controller.config.manager.impl.util.ModuleQNameUtil;
56 import org.opendaylight.controller.config.spi.Module;
57 import org.opendaylight.controller.config.spi.ModuleFactory;
58 import org.osgi.framework.BundleContext;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * Singleton that is responsible for creating and committing Config
64 * Transactions. It is registered in Platform MBean Server.
67 public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
68 private static final Logger LOG = LoggerFactory.getLogger(ConfigRegistryImpl.class);
69 private static final ObjectName NOOP_TX_NAME = ObjectNameUtil.createTransactionControllerON("noop");
71 private final ModuleFactoriesResolver resolver;
72 private final MBeanServer configMBeanServer;
73 private final BindingContextProvider bindingContextProvider;
75 private volatile long version = 0;
76 private volatile long versionCounter = 0;
79 * Contains current configuration in form of {moduleName:{instanceName,read
80 * only module}} for copying state to new transaction. Each running module
81 * is present just once, no matter how many interfaces it exposes.
83 private final ConfigHolder currentConfig = new ConfigHolder();
86 * Will return true unless there was a transaction that succeeded during
87 * validation but failed in second phase of commit. In this case the server
88 * is unstable and its state is undefined.
90 private volatile boolean isHealthy = true;
93 * Holds Map<transactionName, transactionController> and purges it each time
94 * its content is requested.
96 private final TransactionsHolder transactionsHolder = new TransactionsHolder();
98 private final BaseJMXRegistrator baseJMXRegistrator;
100 private final BeanToOsgiServiceManager beanToOsgiServiceManager;
102 // internal jmx server for read only beans
103 private final MBeanServer registryMBeanServer;
104 // internal jmx server shared by all transactions
105 private final MBeanServer transactionsMBeanServer;
107 private final AtomicBoolean closed = new AtomicBoolean();
109 private final Object readableSRRegistryLock = new Object();
111 private final Lock configTransactionLock = new ReentrantLock();
113 // Used for finding new factory instances for default module functionality
114 @GuardedBy("configTransactionLock")
115 private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
117 // switched in every 2ndPC
118 @GuardedBy("readableSRRegistryLock")
119 private CloseableServiceReferenceReadableRegistry readableSRRegistry =
120 ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
123 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
124 MBeanServer configMBeanServer, BindingContextProvider bindingContextProvider) {
125 this(resolver, configMBeanServer,
126 new BaseJMXRegistrator(configMBeanServer), bindingContextProvider);
130 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
131 MBeanServer configMBeanServer,
132 BaseJMXRegistrator baseJMXRegistrator, BindingContextProvider bindingContextProvider) {
133 this.resolver = resolver;
134 this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
135 this.configMBeanServer = configMBeanServer;
136 this.baseJMXRegistrator = baseJMXRegistrator;
137 this.bindingContextProvider = bindingContextProvider;
138 this.registryMBeanServer = MBeanServerFactory
139 .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
140 this.transactionsMBeanServer = MBeanServerFactory
141 .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
145 * Create new {@link ConfigTransactionControllerImpl }
148 public ObjectName beginConfig() {
149 return beginConfig(false);
153 * @param blankTransaction true if this transaction is created automatically by
154 * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
156 public ObjectName beginConfig(boolean blankTransaction) {
157 // If we're closed or in the process of closing then all modules are destroyed or being destroyed
158 // so there's no point in trying to acquire the lock and beginning an actual transaction. Also we want
159 // to avoid trying to lock as it may block the shutdown process if there is an outstanding transaction
160 // attempting to be committed.
162 // We could throw an exception here to indicate this but that's not part of the original API contract
163 // and callers may not be expecting an unchecked exception. Therefore we return a special transaction
164 // handle that signifies a "no-op".
169 if(blankTransaction) {
171 // For a "blank" transaction, we'll try to obtain the config lock but "blank" transactions
172 // are initiated via OSGi events so we don't want to block indefinitely or for a long period
174 if(!configTransactionLock.tryLock(5, TimeUnit.SECONDS)) {
175 LOG.debug("Timed out trying to obtain configTransactionLock");
178 } catch(InterruptedException e) {
179 LOG.debug("Interrupted trying to obtain configTransactionLock", e);
180 Thread.currentThread().interrupt();
184 configTransactionLock.lock();
188 return beginConfigSafe(blankTransaction).getControllerObjectName();
190 configTransactionLock.unlock();
194 @GuardedBy("configTransactionLock")
195 private ConfigTransactionControllerInternal beginConfigSafe(boolean blankTransaction) {
197 final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
199 TransactionJMXRegistratorFactory factory = new TransactionJMXRegistratorFactory() {
201 public TransactionJMXRegistrator create() {
202 return baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
206 Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = new HashMap<>(
207 resolver.getAllFactories());
209 // add all factories that disappeared from SR but are still committed
210 for (ModuleInternalInfo moduleInternalInfo : currentConfig.getEntries()) {
211 String name = moduleInternalInfo.getModuleFactory().getImplementationName();
212 if (!allCurrentFactories.containsKey(name)) {
213 LOG.trace("Factory {} not found in SR, using reference from previous commit", name);
214 allCurrentFactories.put(name,
215 Maps.immutableEntry(moduleInternalInfo.getModuleFactory(), moduleInternalInfo.getBundleContext()));
218 allCurrentFactories = Collections.unmodifiableMap(allCurrentFactories);
220 // closed by transaction controller
221 ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(new TransactionIdentifier(
222 transactionName), factory, allCurrentFactories);
223 SearchableServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
224 readableSRRegistry, txLookupRegistry, allCurrentFactories);
226 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
227 txLookupRegistry, version, bindingContextProvider,
228 versionCounter, allCurrentFactories, transactionsMBeanServer,
229 configMBeanServer, blankTransaction, writableRegistry);
231 txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
232 } catch (InstanceAlreadyExistsException e) {
233 throw new IllegalStateException(e);
235 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
236 transactionsHolder.add(transactionName, transactionController, txLookupRegistry);
237 return transactionController;
242 * @throws ConflictingVersionException
245 public CommitStatus commitConfig(ObjectName transactionControllerON)
246 throws ValidationException, ConflictingVersionException {
247 if(NOOP_TX_NAME.equals(transactionControllerON) || closed.get()) {
248 return new CommitStatus(Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
251 configTransactionLock.lock();
253 return commitConfigSafe(transactionControllerON);
255 configTransactionLock.unlock();
259 @GuardedBy("configTransactionLock")
260 private CommitStatus commitConfigSafe(ObjectName transactionControllerON)
261 throws ConflictingVersionException, ValidationException {
262 final String transactionName = ObjectNameUtil
263 .getTransactionName(transactionControllerON);
264 LOG.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
266 // find ConfigTransactionController
267 Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder.getCurrentTransactions();
268 Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry = transactions.get(transactionName);
269 if (configTransactionControllerEntry == null) {
270 throw new IllegalArgumentException(String.format(
271 "Transaction with name '%s' not found", transactionName));
273 ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
274 // check optimistic lock
275 if (version != configTransactionController.getParentVersion()) {
276 throw new ConflictingVersionException(
278 "Optimistic lock failed. Expected parent version %d, was %d",
280 configTransactionController.getParentVersion()));
282 // optimistic lock ok
284 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
285 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
286 // non recoverable from here:
288 return secondPhaseCommit(configTransactionController, commitInfo, configTransactionControllerEntry.getValue());
289 // some libs throw Errors: e.g.
290 // javax.xml.ws.spi.FactoryFinder$ConfigurationError
291 } catch (Throwable t) {
293 LOG.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
294 throw Throwables.propagate(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 // closes instance (which should close
307 // runtime jmx registrator),
308 // also closes osgi registration and ModuleJMXRegistrator
310 toBeDestroyed.close();
311 currentConfig.remove(toBeDestroyed.getIdentifier());
314 // set RuntimeBeanRegistrators on beans implementing
315 // RuntimeBeanRegistratorAwareModule
316 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
317 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
319 // set runtime jmx registrator if required
320 Module module = entry.getProxiedModule();
321 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = null;
323 if (module instanceof RuntimeBeanRegistratorAwareModule) {
325 if(entry.hasOldModule()) {
327 if(module.canReuse(entry.getOldInternalInfo().getReadableModule().getModule())) {
328 runtimeBeanRegistrator = entry.getOldInternalInfo().getRuntimeBeanRegistrator();
329 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
331 runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
332 entry.getOldInternalInfo().getRuntimeBeanRegistrator().close();
333 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
336 runtimeBeanRegistrator = baseJMXRegistrator.createRuntimeBeanRegistrator(entry.getIdentifier());
337 ((RuntimeBeanRegistratorAwareModule) module).setRuntimeBeanRegistrator(runtimeBeanRegistrator);
340 // save it to info so it is accessible afterwards
341 if(runtimeBeanRegistrator != null) {
342 runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
346 // can register runtime beans
347 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController.secondPhaseCommit();
348 txLookupRegistry.close();
349 configTransactionController.close();
351 // copy configuration to read only mode
352 List<ObjectName> newInstances = new LinkedList<>();
353 List<ObjectName> reusedInstances = new LinkedList<>();
354 List<ObjectName> recreatedInstances = new LinkedList<>();
356 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
359 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
360 LOG.trace("Registering {}", moduleIdentifier);
361 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
362 .get(moduleIdentifier);
364 throw new NullPointerException("Module not found "
368 ObjectName primaryReadOnlyON = ObjectNameUtil
369 .createReadOnlyModuleON(moduleIdentifier);
371 // determine if current instance was recreated or reused or is new
373 // rules for closing resources:
374 // osgi registration - will be reused if possible.
375 // module jmx registration - will be (re)created every time, needs
377 // runtime jmx registration - should be taken care of by module
379 // instance - is closed only if it was destroyed
380 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
381 .createModuleJMXRegistrator();
383 OsgiRegistration osgiRegistration = null;
384 AutoCloseable instance = entry.getProxiedModule().getInstance();
385 if (entry.hasOldModule()) {
386 ModuleInternalInfo oldInternalInfo = entry.getOldInternalInfo();
387 DynamicReadableWrapper oldReadableConfigBean = oldInternalInfo.getReadableModule();
388 currentConfig.remove(entry.getIdentifier());
390 // test if old instance == new instance
391 if (oldReadableConfigBean.getInstance().equals(instance)) {
392 // reused old instance:
393 // wrap in readable dynamic mbean
394 reusedInstances.add(primaryReadOnlyON);
395 osgiRegistration = oldInternalInfo.getOsgiRegistration();
397 // recreated instance:
398 // it is responsibility of module to call the old instance -
399 // we just need to unregister configbean
400 recreatedInstances.add(primaryReadOnlyON);
402 // close old osgi registration
403 oldInternalInfo.getOsgiRegistration().close();
406 // close old module jmx registrator
407 oldInternalInfo.getModuleJMXRegistrator().close();
409 // We no longer need old internal info. Clear it out, so we do not create a serial leak evidenced
410 // by BUG-4514. The reason is that modules retain their resolver, which retains modules. If we retain
411 // the old module, we would have the complete reconfiguration history held in heap for no good reason.
412 entry.clearOldInternalInfo();
415 // wrap in readable dynamic mbean
416 newInstances.add(primaryReadOnlyON);
418 Module realModule = entry.getRealModule();
420 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
421 realModule, instance, moduleIdentifier,
422 registryMBeanServer, configMBeanServer);
426 newModuleJMXRegistrator.registerMBean(newReadableConfigBean, primaryReadOnlyON);
427 } catch (InstanceAlreadyExistsException e) {
428 throw new IllegalStateException("Possible code error, already registered:" + primaryReadOnlyON,e);
431 // register services to OSGi
432 Map<ServiceInterfaceAnnotation, String /* service ref name */> annotationMapping = configTransactionController.getWritableRegistry().findServiceInterfaces(moduleIdentifier);
433 BundleContext bc = configTransactionController.getModuleFactoryBundleContext(
434 entry.getModuleFactory().getImplementationName());
435 if (osgiRegistration == null) {
436 osgiRegistration = beanToOsgiServiceManager.registerToOsgi(
437 newReadableConfigBean.getInstance(), moduleIdentifier, bc, annotationMapping);
439 osgiRegistration.updateRegistrations(annotationMapping, bc, instance);
442 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
443 .get(entry.getIdentifier());
444 ModuleInternalInfo newInfo = new ModuleInternalInfo(
445 entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
446 runtimeBeanRegistrator, newModuleJMXRegistrator,
447 orderingIdx, entry.isDefaultBean(), entry.getModuleFactory(), entry.getBundleContext());
449 newConfigEntries.put(realModule, newInfo);
452 currentConfig.addAll(newConfigEntries.values());
455 version = configTransactionController.getVersion();
457 // switch readable Service Reference Registry
458 synchronized(readableSRRegistryLock) {
459 readableSRRegistry.close();
460 readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
461 configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
464 return new CommitStatus(newInstances, reusedInstances,
472 public List<ObjectName> getOpenConfigs() {
473 Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
474 .getCurrentTransactions();
475 List<ObjectName> result = new ArrayList<>(transactions.size());
476 for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
478 result.add(configTransactionControllerEntry.getKey().getControllerObjectName());
484 * Abort open transactions and unregister read only modules. Since this
485 * class is not responsible for registering itself under
486 * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
490 public void close() {
491 if(!closed.compareAndSet(false, true)) {
495 // abort transactions
496 Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = transactionsHolder
497 .getCurrentTransactions();
498 for (Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry> configTransactionControllerEntry : transactions
501 ConfigTransactionControllerInternal configTransactionController = configTransactionControllerEntry.getKey();
503 configTransactionControllerEntry.getValue().close();
504 configTransactionController.abortConfig();
505 } catch (RuntimeException e) {
506 LOG.debug("Ignoring exception while aborting {}", configTransactionController, e);
510 // destroy all live objects one after another in order of the dependency hierarchy, from top to bottom
511 List<DestroyedModule> destroyedModules = currentConfig.getModulesToBeDestroyed();
513 LOG.info("ConfigRegistry closing - destroying {} modules", destroyedModules.size());
515 for (DestroyedModule destroyedModule : destroyedModules) {
516 destroyedModule.close();
518 // unregister MBeans that failed to unregister properly
519 baseJMXRegistrator.close();
520 // remove jmx servers
521 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
522 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
524 LOG.info("ConfigRegistry closed");
531 public long getVersion() {
539 public Set<String> getAvailableModuleNames() {
540 return new HierarchicalConfigMBeanFactoriesHolder(
541 resolver.getAllFactories()).getModuleNames();
548 public boolean isHealthy() {
558 public Set<ObjectName> lookupConfigBeans() {
559 return lookupConfigBeans("*", "*");
566 public Set<ObjectName> lookupConfigBeans(String moduleName) {
567 return lookupConfigBeans(moduleName, "*");
574 public ObjectName lookupConfigBean(String moduleName, String instanceName)
575 throws InstanceNotFoundException {
576 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
583 public Set<ObjectName> lookupConfigBeans(String moduleName,
584 String instanceName) {
585 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
587 return baseJMXRegistrator.queryNames(namePattern, null);
594 public Set<ObjectName> lookupRuntimeBeans() {
595 return lookupRuntimeBeans("*", "*");
602 public Set<ObjectName> lookupRuntimeBeans(String moduleName,
603 String instanceName) {
604 String finalModuleName = moduleName == null ? "*" : moduleName;
605 String finalInstanceName = instanceName == null ? "*" : instanceName;
606 ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
607 finalModuleName, finalInstanceName);
608 return baseJMXRegistrator.queryNames(namePattern, null);
612 public void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException {
613 ObjectNameUtil.checkDomain(objectName);
614 ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
615 String transactionName = ObjectNameUtil.getTransactionName(objectName);
616 if (transactionName != null) {
617 throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
619 // make sure exactly one match is found:
620 LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
623 // service reference functionality:
625 public ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceQName, String refName) {
626 synchronized(readableSRRegistryLock) {
627 return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
632 public Map<String, Map<String, ObjectName>> getServiceMapping() {
633 synchronized(readableSRRegistryLock) {
634 return readableSRRegistry.getServiceMapping();
639 public Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceQName) {
640 synchronized(readableSRRegistryLock) {
641 return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
646 public Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException {
647 synchronized(readableSRRegistryLock) {
648 return readableSRRegistry.lookupServiceInterfaceNames(objectName);
653 public String getServiceInterfaceName(String namespace, String localName) {
654 synchronized(readableSRRegistryLock) {
655 return readableSRRegistry.getServiceInterfaceName(namespace, localName);
660 public void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException {
661 synchronized(readableSRRegistryLock) {
662 readableSRRegistry.checkServiceReferenceExists(objectName);
667 public ObjectName getServiceReference(String serviceInterfaceQName, String refName) throws InstanceNotFoundException {
668 synchronized(readableSRRegistryLock) {
669 return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
674 public Set<String> getAvailableModuleFactoryQNames() {
675 return ModuleQNameUtil.getQNames(resolver.getAllFactories());
679 public String toString() {
680 return "ConfigRegistryImpl{" +
681 "versionCounter=" + versionCounter +
682 ", version=" + version +
688 * Holds currently running modules
691 private final ConcurrentMap<ModuleIdentifier, ModuleInternalInfo> currentConfig = new ConcurrentHashMap<>();
694 * Add all modules to the internal map. Also add service instance to OSGi
697 public void addAll(Collection<ModuleInternalInfo> configInfos) {
698 if (!currentConfig.isEmpty()) {
699 throw new IllegalStateException(
700 "Error - some config entries were not removed: "
703 for (ModuleInternalInfo configInfo : configInfos) {
708 private void add(ModuleInternalInfo configInfo) {
709 ModuleInternalInfo oldValue = currentConfig.putIfAbsent(configInfo.getIdentifier(), configInfo);
710 if (oldValue != null) {
711 throw new IllegalStateException(
712 "Cannot overwrite module with same name:"
713 + configInfo.getIdentifier() + ":" + configInfo);
718 * Remove entry from current config.
720 public void remove(ModuleIdentifier name) {
721 ModuleInternalInfo removed = currentConfig.remove(name);
722 if (removed == null) {
723 throw new IllegalStateException(
724 "Cannot remove from ConfigHolder - name not found:" + name);
728 public Collection<ModuleInternalInfo> getEntries() {
729 return currentConfig.values();
732 public List<DestroyedModule> getModulesToBeDestroyed() {
733 List<DestroyedModule> result = new ArrayList<>();
734 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
735 result.add(moduleInternalInfo.toDestroyedModule());
737 Collections.sort(result);
745 * Holds Map<transactionName, transactionController> and purges it each time its
746 * content is requested.
748 class TransactionsHolder {
750 * This map keeps transaction names and
751 * {@link ConfigTransactionControllerInternal} instances, because platform
752 * MBeanServer transforms mbeans into another representation. Map is cleaned
753 * every time current transactions are requested.
755 private final ConcurrentMap<String /* transactionName */,
756 Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> transactions = new ConcurrentHashMap<>();
758 public void add(String transactionName,
759 ConfigTransactionControllerInternal transactionController, ConfigTransactionLookupRegistry txLookupRegistry) {
760 Object oldValue = transactions.putIfAbsent(transactionName,
761 Maps.immutableEntry(transactionController, txLookupRegistry));
762 if (oldValue != null) {
763 throw new IllegalStateException(
764 "Error: two transactions with same name");
769 * Purges closed transactions from transactions map. Calling this method more than once within the
770 * method can modify the resulting map that was obtained in previous calls.
772 * @return current view on transactions map.
774 public Map<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> getCurrentTransactions() {
775 // first, remove closed transaction
776 for (Iterator<Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>>> it = transactions
777 .entrySet().iterator(); it.hasNext(); ) {
778 Entry<String, Entry<ConfigTransactionControllerInternal, ConfigTransactionLookupRegistry>> entry = it
780 if (entry.getValue().getKey().isClosed()) {
784 return Collections.unmodifiableMap(transactions);