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.ServiceReferenceReadableRegistry;
14 import org.opendaylight.controller.config.api.ServiceReferenceWritableRegistry;
15 import org.opendaylight.controller.config.api.ValidationException;
16 import org.opendaylight.controller.config.api.jmx.CommitStatus;
17 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
18 import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
19 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HierarchicalConfigMBeanFactoriesHolder;
20 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
21 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
22 import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
23 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
24 import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
25 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager;
26 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
27 import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
28 import org.opendaylight.controller.config.manager.impl.util.ModuleQNameUtil;
29 import org.opendaylight.controller.config.spi.Module;
30 import org.opendaylight.controller.config.spi.ModuleFactory;
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;
66 private long version = 0;
68 private long versionCounter = 0;
71 * Contains current configuration in form of {moduleName:{instanceName,read
72 * only module}} for copying state to new transaction. Each running module
73 * is present just once, no matter how many interfaces it exposes.
76 private final ConfigHolder currentConfig = new ConfigHolder();
79 * Will return true unless there was a transaction that succeeded during
80 * validation but failed in second phase of commit. In this case the server
81 * is unstable and its state is undefined.
84 private boolean isHealthy = true;
87 * Holds Map<transactionName, transactionController> and purges it each time
88 * its content is requested.
91 private final TransactionsHolder transactionsHolder = new TransactionsHolder();
93 private final BaseJMXRegistrator baseJMXRegistrator;
95 private final BeanToOsgiServiceManager beanToOsgiServiceManager;
97 // internal jmx server for read only beans
98 private final MBeanServer registryMBeanServer;
99 // internal jmx server shared by all transactions
100 private final MBeanServer transactionsMBeanServer;
102 // Used for finding new factory instances for default module functionality
104 private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
106 @GuardedBy("this") // switched in every 2ndPC
107 private ServiceReferenceReadableRegistry readableSRRegistry = ServiceReferenceRegistryImpl.createInitialSRLookupRegistry();
110 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
111 MBeanServer configMBeanServer) {
112 this(resolver, configMBeanServer,
113 new BaseJMXRegistrator(configMBeanServer));
117 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
118 MBeanServer configMBeanServer,
119 BaseJMXRegistrator baseJMXRegistrator) {
120 this.resolver = resolver;
121 this.beanToOsgiServiceManager = new BeanToOsgiServiceManager();
122 this.configMBeanServer = configMBeanServer;
123 this.baseJMXRegistrator = baseJMXRegistrator;
124 this.registryMBeanServer = MBeanServerFactory
125 .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
126 this.transactionsMBeanServer = MBeanServerFactory
127 .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
131 * Create new {@link ConfigTransactionControllerImpl }
134 public synchronized ObjectName beginConfig() {
135 return beginConfig(false);
139 * @param blankTransaction true if this transaction is created automatically by
140 * org.opendaylight.controller.config.manager.impl.osgi.BlankTransactionServiceTracker
142 public synchronized ObjectName beginConfig(boolean blankTransaction) {
143 return beginConfigInternal(blankTransaction).getControllerObjectName();
146 private synchronized ConfigTransactionControllerInternal beginConfigInternal(boolean blankTransaction) {
148 final String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
150 TransactionJMXRegistratorFactory factory = new TransactionJMXRegistratorFactory() {
152 public TransactionJMXRegistrator create() {
153 return baseJMXRegistrator.createTransactionJMXRegistrator(transactionName);
157 Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = Collections.unmodifiableMap(
158 resolver.getAllFactories());
159 ConfigTransactionLookupRegistry txLookupRegistry = new ConfigTransactionLookupRegistry(new TransactionIdentifier(
160 transactionName), factory, allCurrentFactories);
161 ServiceReferenceWritableRegistry writableRegistry = ServiceReferenceRegistryImpl.createSRWritableRegistry(
162 readableSRRegistry, txLookupRegistry, allCurrentFactories);
164 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
165 txLookupRegistry, version,
166 versionCounter, allCurrentFactories, transactionsMBeanServer,
167 configMBeanServer, blankTransaction, writableRegistry);
169 txLookupRegistry.registerMBean(transactionController, transactionController.getControllerObjectName());
170 } catch (InstanceAlreadyExistsException e) {
171 throw new IllegalStateException(e);
173 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
174 transactionsHolder.add(transactionName, transactionController);
175 return transactionController;
182 public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
183 throws ConflictingVersionException, ValidationException {
184 final String transactionName = ObjectNameUtil
185 .getTransactionName(transactionControllerON);
186 logger.info("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
188 // find ConfigTransactionController
189 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder.getCurrentTransactions();
190 ConfigTransactionControllerInternal configTransactionController = transactions.get(transactionName);
191 if (configTransactionController == null) {
192 throw new IllegalArgumentException(String.format(
193 "Transaction with name '%s' not found", transactionName));
195 // check optimistic lock
196 if (version != configTransactionController.getParentVersion()) {
197 throw new ConflictingVersionException(
199 "Optimistic lock failed. Expected parent version %d, was %d",
201 configTransactionController.getParentVersion()));
203 // optimistic lock ok
205 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
206 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
207 // non recoverable from here:
209 return secondPhaseCommit(
210 configTransactionController, commitInfo);
211 } catch (Throwable t) { // some libs throw Errors: e.g.
212 // javax.xml.ws.spi.FactoryFinder$ConfigurationError
214 logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
215 if (t instanceof RuntimeException) {
216 throw (RuntimeException) t;
217 } else if (t instanceof Error) {
220 throw new RuntimeException(t);
225 private CommitStatus secondPhaseCommit(ConfigTransactionControllerInternal configTransactionController,
226 CommitInfo commitInfo) {
228 // close instances which were destroyed by the user, including
229 // (hopefully) runtime beans
230 for (DestroyedModule toBeDestroyed : commitInfo
231 .getDestroyedFromPreviousTransactions()) {
232 toBeDestroyed.close(); // closes instance (which should close
233 // runtime jmx registrator),
234 // also closes osgi registration and ModuleJMXRegistrator
236 currentConfig.remove(toBeDestroyed.getIdentifier());
239 // set RuntimeBeanRegistrators on beans implementing
240 // RuntimeBeanRegistratorAwareModule, each module
241 // should have exactly one runtime jmx registrator.
242 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
243 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
245 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
246 if (entry.hasOldModule() == false) {
247 runtimeBeanRegistrator = baseJMXRegistrator
248 .createRuntimeBeanRegistrator(entry.getIdentifier());
250 // reuse old JMX registrator
251 runtimeBeanRegistrator = entry.getOldInternalInfo()
252 .getRuntimeBeanRegistrator();
254 // set runtime jmx registrator if required
255 Module module = entry.getModule();
256 if (module instanceof RuntimeBeanRegistratorAwareModule) {
257 ((RuntimeBeanRegistratorAwareModule) module)
258 .setRuntimeBeanRegistrator(runtimeBeanRegistrator);
260 // save it to info so it is accessible afterwards
261 runtimeRegistrators.put(entry.getIdentifier(), runtimeBeanRegistrator);
264 // can register runtime beans
265 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController
266 .secondPhaseCommit();
268 // copy configuration to read only mode
269 List<ObjectName> newInstances = new LinkedList<>();
270 List<ObjectName> reusedInstances = new LinkedList<>();
271 List<ObjectName> recreatedInstances = new LinkedList<>();
273 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
276 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
277 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
278 .get(moduleIdentifier);
280 throw new NullPointerException("Module not found "
282 Module module = entry.getModule();
283 ObjectName primaryReadOnlyON = ObjectNameUtil
284 .createReadOnlyModuleON(moduleIdentifier);
286 // determine if current instance was recreated or reused or is new
288 // rules for closing resources:
289 // osgi registration - will be reused if possible.
290 // module jmx registration - will be (re)created every time, needs
292 // runtime jmx registration - should be taken care of by module
294 // instance - is closed only if it was destroyed
295 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
296 .createModuleJMXRegistrator();
298 OsgiRegistration osgiRegistration = null;
299 if (entry.hasOldModule()) {
300 ModuleInternalInfo oldInternalInfo = entry.getOldInternalInfo();
301 DynamicReadableWrapper oldReadableConfigBean = oldInternalInfo
302 .getReadableModule();
303 currentConfig.remove(entry.getIdentifier());
305 // test if old instance == new instance
306 if (oldReadableConfigBean.getInstance().equals(module.getInstance())) {
307 // reused old instance:
308 // wrap in readable dynamic mbean
309 reusedInstances.add(primaryReadOnlyON);
310 osgiRegistration = oldInternalInfo.getOsgiRegistration();
312 // recreated instance:
313 // it is responsibility of module to call the old instance -
314 // we just need to unregister configbean
315 recreatedInstances.add(primaryReadOnlyON);
317 // close old osgi registration
318 oldInternalInfo.getOsgiRegistration().close();
321 // close old module jmx registrator
322 oldInternalInfo.getModuleJMXRegistrator().close();
325 // wrap in readable dynamic mbean
326 newInstances.add(primaryReadOnlyON);
329 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
330 module, module.getInstance(), moduleIdentifier,
331 registryMBeanServer, configMBeanServer);
335 newModuleJMXRegistrator.registerMBean(newReadableConfigBean,
337 } catch (InstanceAlreadyExistsException e) {
338 throw new IllegalStateException(e);
342 if (osgiRegistration == null) {
343 ModuleFactory moduleFactory = entry.getModuleFactory();
344 if(moduleFactory != null) {
345 BundleContext bc = configTransactionController.
346 getModuleFactoryBundleContext(moduleFactory.getImplementationName());
347 osgiRegistration = beanToOsgiServiceManager.registerToOsgi(module.getClass(),
348 newReadableConfigBean.getInstance(), entry.getIdentifier(), bc);
350 throw new NullPointerException(entry.getIdentifier().getFactoryName() + " ModuleFactory not found.");
355 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
356 .get(entry.getIdentifier());
357 ModuleInternalInfo newInfo = new ModuleInternalInfo(
358 entry.getIdentifier(), newReadableConfigBean, osgiRegistration,
359 runtimeBeanRegistrator, newModuleJMXRegistrator,
360 orderingIdx, entry.isDefaultBean());
362 newConfigEntries.put(module, newInfo);
365 currentConfig.addAll(newConfigEntries.values());
368 version = configTransactionController.getVersion();
370 // switch readable Service Reference Registry
371 this.readableSRRegistry = ServiceReferenceRegistryImpl.createSRReadableRegistry(configTransactionController.getWritableRegistry(), this);
373 return new CommitStatus(newInstances, reusedInstances,
381 public synchronized List<ObjectName> getOpenConfigs() {
382 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
383 .getCurrentTransactions();
384 List<ObjectName> result = new ArrayList<>(transactions.size());
385 for (ConfigTransactionControllerInternal configTransactionController : transactions
387 result.add(configTransactionController.getControllerObjectName());
393 * Abort open transactions and unregister read only modules. Since this
394 * class is not responsible for registering itself under
395 * {@link org.opendaylight.controller.config.api.ConfigRegistry#OBJECT_NAME}, it will not unregister itself
399 public synchronized void close() {
400 // abort transactions
401 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
402 .getCurrentTransactions();
403 for (ConfigTransactionControllerInternal configTransactionController : transactions
406 configTransactionController.abortConfig();
407 } catch (RuntimeException e) {
408 logger.warn("Ignoring exception while aborting {}",
409 configTransactionController, e);
413 // destroy all live objects one after another in order of the dependency
415 List<DestroyedModule> destroyedModules = currentConfig
416 .getModulesToBeDestroyed();
417 for (DestroyedModule destroyedModule : destroyedModules) {
418 destroyedModule.close();
420 // unregister MBeans that failed to unregister properly
421 baseJMXRegistrator.close();
422 // remove jmx servers
423 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
424 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
432 public long getVersion() {
440 public Set<String> getAvailableModuleNames() {
441 return new HierarchicalConfigMBeanFactoriesHolder(
442 resolver.getAllFactories()).getModuleNames();
449 public boolean isHealthy() {
459 public Set<ObjectName> lookupConfigBeans() {
460 return lookupConfigBeans("*", "*");
467 public Set<ObjectName> lookupConfigBeans(String moduleName) {
468 return lookupConfigBeans(moduleName, "*");
475 public ObjectName lookupConfigBean(String moduleName, String instanceName)
476 throws InstanceNotFoundException {
477 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
484 public Set<ObjectName> lookupConfigBeans(String moduleName,
485 String instanceName) {
486 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
488 return baseJMXRegistrator.queryNames(namePattern, null);
495 public Set<ObjectName> lookupRuntimeBeans() {
496 return lookupRuntimeBeans("*", "*");
503 public Set<ObjectName> lookupRuntimeBeans(String moduleName,
504 String instanceName) {
505 if (moduleName == null)
507 if (instanceName == null)
509 ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
510 moduleName, instanceName);
511 return baseJMXRegistrator.queryNames(namePattern, null);
515 public void checkConfigBeanExists(ObjectName objectName) throws InstanceNotFoundException {
516 ObjectNameUtil.checkDomain(objectName);
517 ObjectNameUtil.checkType(objectName, ObjectNameUtil.TYPE_MODULE);
518 String transactionName = ObjectNameUtil.getTransactionName(objectName);
519 if (transactionName != null) {
520 throw new IllegalArgumentException("Transaction attribute not supported in registry, wrong ObjectName: " + objectName);
522 // make sure exactly one match is found:
523 LookupBeansUtil.lookupConfigBean(this, ObjectNameUtil.getFactoryName(objectName), ObjectNameUtil.getInstanceName(objectName));
526 // service reference functionality:
528 public synchronized ObjectName lookupConfigBeanByServiceInterfaceName(String serviceInterfaceName, String refName) {
529 return readableSRRegistry.lookupConfigBeanByServiceInterfaceName(serviceInterfaceName, refName);
533 public synchronized Map<String, Map<String, ObjectName>> getServiceMapping() {
534 return readableSRRegistry.getServiceMapping();
538 public synchronized Map<String, ObjectName> lookupServiceReferencesByServiceInterfaceName(String serviceInterfaceName) {
539 return readableSRRegistry.lookupServiceReferencesByServiceInterfaceName(serviceInterfaceName);
543 public synchronized Set<String> lookupServiceInterfaceNames(ObjectName objectName) throws InstanceNotFoundException {
544 return readableSRRegistry.lookupServiceInterfaceNames(objectName);
548 public synchronized String getServiceInterfaceName(String namespace, String localName) {
549 return readableSRRegistry.getServiceInterfaceName(namespace, localName);
553 public Set<String> getAvailableModuleFactoryQNames() {
554 return ModuleQNameUtil.getQNames(resolver.getAllFactories());
560 * Holds currently running modules
564 private final Map<ModuleIdentifier, ModuleInternalInfo> currentConfig = new HashMap<>();
567 * Add all modules to the internal map. Also add service instance to OSGi
570 public void addAll(Collection<ModuleInternalInfo> configInfos) {
571 if (currentConfig.size() > 0) {
572 throw new IllegalStateException(
573 "Error - some config entries were not removed: "
576 for (ModuleInternalInfo configInfo : configInfos) {
581 private void add(ModuleInternalInfo configInfo) {
582 ModuleInternalInfo oldValue = currentConfig.put(configInfo.getName(),
584 if (oldValue != null) {
585 throw new IllegalStateException(
586 "Cannot overwrite module with same name:"
587 + configInfo.getName() + ":" + configInfo);
592 * Remove entry from current config.
594 public void remove(ModuleIdentifier name) {
595 ModuleInternalInfo removed = currentConfig.remove(name);
596 if (removed == null) {
597 throw new IllegalStateException(
598 "Cannot remove from ConfigHolder - name not found:" + name);
602 public Collection<ModuleInternalInfo> getEntries() {
603 return currentConfig.values();
606 public List<DestroyedModule> getModulesToBeDestroyed() {
607 List<DestroyedModule> result = new ArrayList<>();
608 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
609 result.add(moduleInternalInfo.toDestroyedModule());
611 Collections.sort(result);
619 * Holds Map<transactionName, transactionController> and purges it each time its
620 * content is requested.
623 class TransactionsHolder {
625 * This map keeps transaction names and
626 * {@link ConfigTransactionControllerInternal} instances, because platform
627 * MBeanServer transforms mbeans into another representation. Map is cleaned
628 * every time current transactions are requested.
631 @GuardedBy("ConfigRegistryImpl.this")
632 private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
635 * Can only be called from within synchronized method.
637 public void add(String transactionName,
638 ConfigTransactionControllerInternal transactionController) {
639 Object oldValue = transactions.put(transactionName,
640 transactionController);
641 if (oldValue != null) {
642 throw new IllegalStateException(
643 "Error: two transactions with same name");
648 * Purges closed transactions from transactions map. Can only be called from
649 * within synchronized method. Calling this method more than once within the
650 * method can modify the resulting map that was obtained in previous calls.
652 * @return current view on transactions map.
654 public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
655 // first, remove closed transaction
656 for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
657 .entrySet().iterator(); it.hasNext();) {
658 Entry<String, ConfigTransactionControllerInternal> entry = it
660 if (entry.getValue().isClosed()) {
664 return Collections.unmodifiableMap(transactions);