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 org.opendaylight.controller.config.api.ConflictingVersionException;
11 import org.opendaylight.controller.config.api.ModuleIdentifier;
12 import org.opendaylight.controller.config.api.RuntimeBeanRegistratorAwareModule;
13 import org.opendaylight.controller.config.api.ServiceReferenceWritableRegistry;
14 import org.opendaylight.controller.config.api.ValidationException;
15 import org.opendaylight.controller.config.api.jmx.CommitStatus;
16 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
17 import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
18 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HierarchicalConfigMBeanFactoriesHolder;
19 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
20 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
21 import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
22 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
23 import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
24 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager;
25 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
26 import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
27 import org.opendaylight.controller.config.manager.impl.util.ModuleQNameUtil;
28 import org.opendaylight.controller.config.spi.Module;
29 import org.opendaylight.controller.config.spi.ModuleFactory;
30 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
31 import org.osgi.framework.BundleContext;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
35 import javax.annotation.concurrent.GuardedBy;
36 import javax.annotation.concurrent.NotThreadSafe;
37 import javax.annotation.concurrent.ThreadSafe;
38 import javax.management.InstanceAlreadyExistsException;
39 import javax.management.InstanceNotFoundException;
40 import javax.management.MBeanServer;
41 import javax.management.MBeanServerFactory;
42 import javax.management.ObjectName;
43 import java.util.ArrayList;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.LinkedList;
49 import java.util.List;
51 import java.util.Map.Entry;
55 * Singleton that is responsible for creating and committing Config
56 * Transactions. It is registered in Platform MBean Server.
59 public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
60 private static final Logger logger = LoggerFactory.getLogger(ConfigRegistryImpl.class);
62 private final ModuleFactoriesResolver resolver;
63 private final MBeanServer configMBeanServer;
64 private final CodecRegistry codecRegistry;
67 private long version = 0;
69 private long versionCounter = 0;
72 * Contains current configuration in form of {moduleName:{instanceName,read
73 * only module}} for copying state to new transaction. Each running module
74 * is present just once, no matter how many interfaces it exposes.
77 private final ConfigHolder currentConfig = new ConfigHolder();
80 * Will return true unless there was a transaction that succeeded during
81 * validation but failed in second phase of commit. In this case the server
82 * is unstable and its state is undefined.
85 private boolean isHealthy = true;
88 * Holds Map<transactionName, transactionController> and purges it each time
89 * its content is requested.
92 private final TransactionsHolder transactionsHolder = new TransactionsHolder();
94 private final BaseJMXRegistrator baseJMXRegistrator;
96 private final BeanToOsgiServiceManager beanToOsgiServiceManager;
98 // internal jmx server for read only beans
99 private final MBeanServer registryMBeanServer;
100 // internal jmx server shared by all transactions
101 private final MBeanServer transactionsMBeanServer;
103 // Used for finding new factory instances for default module functionality
105 private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
107 @GuardedBy("this") // switched in every 2ndPC
108 private CloseableServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
111 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
112 MBeanServer configMBeanServer, CodecRegistry codecRegistry) {
113 this(resolver, configMBeanServer,
114 new BaseJMXRegistrator(configMBeanServer), codecRegistry);
118 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
119 MBeanServer configMBeanServer,
120 BaseJMXRegistrator baseJMXRegistrator, CodecRegistry codecRegistry) {
121 this.resolver = resolver;
122 this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
123 this.configMBeanServer = configMBeanServer;
124 this.baseJMXRegistrator = baseJMXRegistrator;
125 this.codecRegistry = codecRegistry;
126 this.registryMBeanServer = MBeanServerFactory
127 .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
128 this.transactionsMBeanServer = MBeanServerFactory
129 .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
133 * Create new {@link ConfigTransactionControllerImpl }
136 public synchronized ObjectName beginConfig() {
137 return beginConfig(false);
141 * @param blankTransaction true if this transaction is created automatically by
142 * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
144 public synchronized ObjectName beginConfig(boolean blankTransaction) {
145 return beginConfigInternal(blankTransaction).getControllerObjectName();
148 private synchronized ConfigTransactionControllerInternal beginConfigInternal(boolean blankTransaction) {
150 final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
152 TransactionJMXRegistratorFactory factory = new TransactionJMXRegistratorFactory() {
154 public TransactionJMXRegistrator create() {
155 return baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
159 Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = Collections.unmodifiableMap(
160 resolver.getAllFactories());
161 ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(new TransactionIdentifier(
162 transactionName), factory, allCurrentFactories);
163 ServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
164 readableSRRegistry, txLookupRegistry, allCurrentFactories);
166 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
167 txLookupRegistry, version, codecRegistry,
168 versionCounter, allCurrentFactories, transactionsMBeanServer,
169 configMBeanServer, blankTransaction, writableRegistry);
171 txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
172 } catch (InstanceAlreadyExistsException e) {
173 throw new IllegalStateException(e);
175 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
176 transactionsHolder.add(transactionName, transactionController);
177 return transactionController;
184 public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
185 throws ConflictingVersionException, ValidationException {
186 final String transactionName = ObjectNameUtil
187 .getTransactionName(transactionControllerON);
188 logger.trace("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
190 // find ConfigTransactionController
191 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder.getCurrentTransactions();
192 ConfigTransactionControllerInternal configTransactionController = transactions.get(transactionName);
193 if (configTransactionController == null) {
194 throw new IllegalArgumentException(String.format(
195 "Transaction with name '%s' not found", transactionName));
197 // check optimistic lock
198 if (version != configTransactionController.getParentVersion()) {
199 throw new ConflictingVersionException(
201 "Optimistic lock failed. Expected parent version %d, was %d",
203 configTransactionController.getParentVersion()));
205 // optimistic lock ok
207 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
208 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
209 // non recoverable from here:
211 return secondPhaseCommit(
212 configTransactionController, commitInfo);
213 } catch (Throwable t) { // some libs throw Errors: e.g.
214 // javax.xml.ws.spi.FactoryFinder$ConfigurationError
216 logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
217 if (t instanceof RuntimeException) {
218 throw (RuntimeException) t;
219 } else if (t instanceof Error) {
222 throw new RuntimeException(t);
227 private CommitStatus secondPhaseCommit(ConfigTransactionControllerInternal configTransactionController,
228 CommitInfo commitInfo) {
230 // close instances which were destroyed by the user, including
231 // (hopefully) runtime beans
232 for (DestroyedModule toBeDestroyed : commitInfo
233 .getDestroyedFromPreviousTransactions()) {
234 toBeDestroyed.close(); // closes instance (which should close
235 // runtime jmx registrator),
236 // also closes osgi registration and ModuleJMXRegistrator
238 currentConfig.remove(toBeDestroyed.getIdentifier());
241 // set RuntimeBeanRegistrators on beans implementing
242 // RuntimeBeanRegistratorAwareModule, each module
243 // should have exactly one runtime jmx registrator.
244 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
245 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
247 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
248 if (entry.hasOldModule() == false) {
249 runtimeBeanRegistrator = baseJMXRegistrator
250 .createRuntimeBeanRegistrator(entry.getIdentifier());
252 // reuse old JMX registrator
253 runtimeBeanRegistrator = entry.getOldInternalInfo()
254 .getRuntimeBeanRegistrator();
256 // set runtime jmx registrator if required
257 Module module = entry.getModule();
258 if (module instanceof RuntimeBeanRegistratorAwareModule) {
259 ((RuntimeBeanRegistratorAwareModule) module)
260 .setRuntimeBeanRegistrator(runtimeBeanRegistrator);
262 // save it to info so it is accessible afterwards
263 runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
266 // can register runtime beans
267 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController
268 .secondPhaseCommit();
270 // copy configuration to read only mode
271 List<ObjectName> newInstances = new LinkedList<>();
272 List<ObjectName> reusedInstances = new LinkedList<>();
273 List<ObjectName> recreatedInstances = new LinkedList<>();
275 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
278 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
279 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
280 .get(moduleIdentifier);
282 throw new NullPointerException("Module not found "
284 Module module = entry.getModule();
285 ObjectName primaryReadOnlyON = ObjectNameUtil
286 .createReadOnlyModuleON(moduleIdentifier);
288 // determine if current instance was recreated or reused or is new
290 // rules for closing resources:
291 // osgi registration - will be reused if possible.
292 // module jmx registration - will be (re)created every time, needs
294 // runtime jmx registration - should be taken care of by module
296 // instance - is closed only if it was destroyed
297 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
298 .createModuleJMXRegistrator();
300 OsgiRegistration osgiRegistration = null;
301 if (entry.hasOldModule()) {
302 ModuleInternalInfo oldInternalInfo = entry.getOldInternalInfo();
303 DynamicReadableWrapper oldReadableConfigBean = oldInternalInfo.getReadableModule();
304 currentConfig.remove(entry.getIdentifier());
306 // test if old instance == new instance
307 if (oldReadableConfigBean.getInstance().equals(module.getInstance())) {
308 // reused old instance:
309 // wrap in readable dynamic mbean
310 reusedInstances.add(primaryReadOnlyON);
311 osgiRegistration = oldInternalInfo.getOsgiRegistration();
313 // recreated instance:
314 // it is responsibility of module to call the old instance -
315 // we just need to unregister configbean
316 recreatedInstances.add(primaryReadOnlyON);
318 // close old osgi registration
319 oldInternalInfo.getOsgiRegistration().close();
322 // close old module jmx registrator
323 oldInternalInfo.getModuleJMXRegistrator().close();
326 // wrap in readable dynamic mbean
327 newInstances.add(primaryReadOnlyON);
330 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
331 module, module.getInstance(), moduleIdentifier,
332 registryMBeanServer, configMBeanServer);
336 newModuleJMXRegistrator.registerMBean(newReadableConfigBean,
338 } catch (InstanceAlreadyExistsException e) {
339 throw new IllegalStateException(e);
343 if (osgiRegistration == null) {
344 ModuleFactory moduleFactory = entry.getModuleFactory();
345 if(moduleFactory != null) {
346 BundleContext bc = configTransactionController.
347 getModuleFactoryBundleContext(moduleFactory.getImplementationName());
348 osgiRegistration = beanToOsgiServiceManager.registerToOsgi(module.getClass(),
349 newReadableConfigBean.getInstance(), entry.getIdentifier(), bc);
351 throw new NullPointerException(entry.getIdentifier().getFactoryName() + " ModuleFactory not found.");
356 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
357 .get(entry.getIdentifier());
358 ModuleInternalInfo newInfo = new ModuleInternalInfo(
359 entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
360 runtimeBeanRegistrator, newModuleJMXRegistrator,
361 orderingIdx, entry.isDefaultBean());
363 newConfigEntries.put(module, newInfo);
366 currentConfig.addAll(newConfigEntries.values());
369 version = configTransactionController.getVersion();
371 // switch readable Service Reference Registry
372 this.readableSRRegistry.close();
373 this.readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(
374 configTransactionController.getWritableRegistry(), this, baseJMXRegistrator);
376 return new CommitStatus(newInstances, reusedInstances,
384 public synchronized List<ObjectName> getOpenConfigs() {
385 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
386 .getCurrentTransactions();
387 List<ObjectName> result = new ArrayList<>(transactions.size());
388 for (ConfigTransactionControllerInternal configTransactionController : transactions
390 result.add(configTransactionController.getControllerObjectName());
396 * Abort open transactions and unregister read only modules. Since this
397 * class is not responsible for registering itself under
398 * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
402 public synchronized void close() {
403 // abort transactions
404 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
405 .getCurrentTransactions();
406 for (ConfigTransactionControllerInternal configTransactionController : transactions
409 configTransactionController.abortConfig();
410 } catch (RuntimeException e) {
411 logger.warn("Ignoring exception while aborting {}",
412 configTransactionController, e);
416 // destroy all live objects one after another in order of the dependency
418 List<DestroyedModule> destroyedModules = currentConfig
419 .getModulesToBeDestroyed();
420 for (DestroyedModule destroyedModule : destroyedModules) {
421 destroyedModule.close();
423 // unregister MBeans that failed to unregister properly
424 baseJMXRegistrator.close();
425 // remove jmx servers
426 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
427 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
435 public long getVersion() {
443 public Set<String> getAvailableModuleNames() {
444 return new HierarchicalConfigMBeanFactoriesHolder(
445 resolver.getAllFactories()).getModuleNames();
452 public boolean isHealthy() {
462 public Set<ObjectName> lookupConfigBeans() {
463 return lookupConfigBeans("*", "*");
470 public Set<ObjectName> lookupConfigBeans(String moduleName) {
471 return lookupConfigBeans(moduleName, "*");
478 public ObjectName lookupConfigBean(String moduleName, String instanceName)
479 throws InstanceNotFoundException {
480 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
487 public Set<ObjectName> lookupConfigBeans(String moduleName,
488 String instanceName) {
489 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
491 return baseJMXRegistrator.queryNames(namePattern, null);
498 public Set<ObjectName> lookupRuntimeBeans() {
499 return lookupRuntimeBeans("*", "*");
506 public Set<ObjectName> lookupRuntimeBeans(String moduleName,
507 String instanceName) {
508 if (moduleName == null)
510 if (instanceName == null)
512 ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
513 moduleName, instanceName);
514 return baseJMXRegistrator.queryNames(namePattern, null);
518 public void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException {
519 ObjectNameUtil.checkDomain(objectName);
520 ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
521 String transactionName = ObjectNameUtil.getTransactionName(objectName);
522 if (transactionName != null) {
523 throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
525 // make sure exactly one match is found:
526 LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
529 // service reference functionality:
531 public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceQName, String refName) {
532 return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceQName, refName);
536 public synchronized Map<String, Map<String, ObjectName>> getServiceMapping() {
537 return readableSRRegistry.getServiceMapping();
541 public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceQName) {
542 return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceQName);
546 public synchronized Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException {
547 return readableSRRegistry.lookupServiceInterfaceNames(objectName);
551 public synchronized String getServiceInterfaceName(String namespace, String localName) {
552 return readableSRRegistry.getServiceInterfaceName(namespace, localName);
556 public void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException {
557 readableSRRegistry.checkServiceReferenceExists(objectName);
561 public ObjectName getServiceReference(String serviceInterfaceQName, String refName) throws InstanceNotFoundException {
562 return readableSRRegistry.getServiceReference(serviceInterfaceQName, refName);
566 public Set<String> getAvailableModuleFactoryQNames() {
567 return ModuleQNameUtil.getQNames(resolver.getAllFactories());
571 public String toString() {
572 return "ConfigRegistryImpl{" +
573 "versionCounter=" + versionCounter +
574 ", version=" + version +
580 * Holds currently running modules
584 private final Map<ModuleIdentifier, ModuleInternalInfo> currentConfig = new HashMap<>();
587 * Add all modules to the internal map. Also add service instance to OSGi
590 public void addAll(Collection<ModuleInternalInfo> configInfos) {
591 if (currentConfig.size() > 0) {
592 throw new IllegalStateException(
593 "Error - some config entries were not removed: "
596 for (ModuleInternalInfo configInfo : configInfos) {
601 private void add(ModuleInternalInfo configInfo) {
602 ModuleInternalInfo oldValue = currentConfig.put(configInfo.getIdentifier(),
604 if (oldValue != null) {
605 throw new IllegalStateException(
606 "Cannot overwrite module with same name:"
607 + configInfo.getIdentifier() + ":" + configInfo);
612 * Remove entry from current config.
614 public void remove(ModuleIdentifier name) {
615 ModuleInternalInfo removed = currentConfig.remove(name);
616 if (removed == null) {
617 throw new IllegalStateException(
618 "Cannot remove from ConfigHolder - name not found:" + name);
622 public Collection<ModuleInternalInfo> getEntries() {
623 return currentConfig.values();
626 public List<DestroyedModule> getModulesToBeDestroyed() {
627 List<DestroyedModule> result = new ArrayList<>();
628 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
629 result.add(moduleInternalInfo.toDestroyedModule());
631 Collections.sort(result);
639 * Holds Map<transactionName, transactionController> and purges it each time its
640 * content is requested.
643 class TransactionsHolder {
645 * This map keeps transaction names and
646 * {@link ConfigTransactionControllerInternal} instances, because platform
647 * MBeanServer transforms mbeans into another representation. Map is cleaned
648 * every time current transactions are requested.
651 @GuardedBy("ConfigRegistryImpl.this")
652 private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
655 * Can only be called from within synchronized method.
657 public void add(String transactionName,
658 ConfigTransactionControllerInternal transactionController) {
659 Object oldValue = transactions.put(transactionName,
660 transactionController);
661 if (oldValue != null) {
662 throw new IllegalStateException(
663 "Error: two transactions with same name");
668 * Purges closed transactions from transactions map. Can only be called from
669 * within synchronized method. Calling this method more than once within the
670 * method can modify the resulting map that was obtained in previous calls.
672 * @return current view on transactions map.
674 public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
675 // first, remove closed transaction
676 for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
677 .entrySet().iterator(); it.hasNext();) {
678 Entry<String, ConfigTransactionControllerInternal> entry = it
680 if (entry.getValue().isClosed()) {
684 return Collections.unmodifiableMap(transactions);