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.ValidationException;
14 import org.opendaylight.controller.config.api.jmx.CommitStatus;
15 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
16 import org.opendaylight.controller.config.manager.impl.dynamicmbean.DynamicReadableWrapper;
17 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HierarchicalConfigMBeanFactoriesHolder;
18 import org.opendaylight.controller.config.manager.impl.factoriesresolver.ModuleFactoriesResolver;
19 import org.opendaylight.controller.config.manager.impl.jmx.BaseJMXRegistrator;
20 import org.opendaylight.controller.config.manager.impl.jmx.ModuleJMXRegistrator;
21 import org.opendaylight.controller.config.manager.impl.jmx.RootRuntimeBeanRegistratorImpl;
22 import org.opendaylight.controller.config.manager.impl.jmx.TransactionJMXRegistrator;
23 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager;
24 import org.opendaylight.controller.config.manager.impl.osgi.BeanToOsgiServiceManager.OsgiRegistration;
25 import org.opendaylight.controller.config.manager.impl.util.LookupBeansUtil;
26 import org.opendaylight.controller.config.spi.Module;
27 import org.opendaylight.controller.config.spi.ModuleFactory;
28 import org.osgi.framework.BundleContext;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
32 import javax.annotation.concurrent.GuardedBy;
33 import javax.annotation.concurrent.NotThreadSafe;
34 import javax.annotation.concurrent.ThreadSafe;
35 import javax.management.InstanceAlreadyExistsException;
36 import javax.management.InstanceNotFoundException;
37 import javax.management.MBeanServer;
38 import javax.management.MBeanServerFactory;
39 import javax.management.ObjectName;
40 import java.util.ArrayList;
41 import java.util.Collection;
42 import java.util.Collections;
43 import java.util.HashMap;
44 import java.util.Iterator;
45 import java.util.LinkedList;
46 import java.util.List;
48 import java.util.Map.Entry;
52 * Singleton that is responsible for creating and committing Config
53 * Transactions. It is registered in Platform MBean Server.
56 public class ConfigRegistryImpl implements AutoCloseable, ConfigRegistryImplMXBean {
57 private static final Logger logger = LoggerFactory.getLogger(ConfigRegistryImpl.class);
59 private final ModuleFactoriesResolver resolver;
60 private final MBeanServer configMBeanServer;
63 private final BundleContext bundleContext;
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;
103 private List<ModuleFactory> lastListOfFactories = Collections.emptyList();
106 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
107 BundleContext bundleContext, MBeanServer configMBeanServer) {
108 this(resolver, bundleContext, configMBeanServer,
109 new BaseJMXRegistrator(configMBeanServer));
113 public ConfigRegistryImpl(ModuleFactoriesResolver resolver,
114 BundleContext bundleContext, MBeanServer configMBeanServer,
115 BaseJMXRegistrator baseJMXRegistrator) {
116 this.resolver = resolver;
117 this.beanToOsgiServiceManager = new BeanToOsgiServiceManager(
119 this.bundleContext = bundleContext;
120 this.configMBeanServer = configMBeanServer;
121 this.baseJMXRegistrator = baseJMXRegistrator;
122 this.registryMBeanServer = MBeanServerFactory
123 .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
124 this.transactionsMBeanServer = MBeanServerFactory
125 .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
129 * Create new {@link ConfigTransactionControllerImpl }
132 public synchronized ObjectName beginConfig() {
133 return beginConfigInternal().getControllerObjectName();
136 private synchronized ConfigTransactionControllerInternal beginConfigInternal() {
138 String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
139 TransactionJMXRegistrator transactionRegistrator = baseJMXRegistrator
140 .createTransactionJMXRegistrator(transactionName);
141 List<ModuleFactory> allCurrentFactories = Collections.unmodifiableList(resolver.getAllFactories());
142 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
143 transactionName, transactionRegistrator, version,
144 versionCounter, allCurrentFactories, transactionsMBeanServer, configMBeanServer, bundleContext);
146 transactionRegistrator.registerMBean(transactionController, transactionController.getControllerObjectName());
147 } catch (InstanceAlreadyExistsException e) {
148 throw new IllegalStateException(e);
151 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
153 transactionsHolder.add(transactionName, transactionController);
154 return transactionController;
161 public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
162 throws ConflictingVersionException, ValidationException {
163 final String transactionName = ObjectNameUtil
164 .getTransactionName(transactionControllerON);
165 logger.info("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
167 // find ConfigTransactionController
168 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder.getCurrentTransactions();
169 ConfigTransactionControllerInternal configTransactionController = transactions.get(transactionName);
170 if (configTransactionController == null) {
171 throw new IllegalArgumentException(String.format(
172 "Transaction with name '%s' not found", transactionName));
174 // check optimistic lock
175 if (version != configTransactionController.getParentVersion()) {
176 throw new ConflictingVersionException(
178 "Optimistic lock failed. Expected parent version %d, was %d",
180 configTransactionController.getParentVersion()));
182 // optimistic lock ok
184 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
185 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
186 // non recoverable from here:
188 return secondPhaseCommit(
189 configTransactionController, commitInfo);
190 } catch (Throwable t) { // some libs throw Errors: e.g.
191 // javax.xml.ws.spi.FactoryFinder$ConfigurationError
193 logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
194 if (t instanceof RuntimeException) {
195 throw (RuntimeException) t;
196 } else if (t instanceof Error) {
199 throw new RuntimeException(t);
204 private CommitStatus secondPhaseCommit(ConfigTransactionControllerInternal configTransactionController,
205 CommitInfo commitInfo) {
207 // close instances which were destroyed by the user, including
208 // (hopefully) runtime beans
209 for (DestroyedModule toBeDestroyed : commitInfo
210 .getDestroyedFromPreviousTransactions()) {
211 toBeDestroyed.close(); // closes instance (which should close
212 // runtime jmx registrator),
213 // also closes osgi registration and ModuleJMXRegistrator
215 currentConfig.remove(toBeDestroyed.getIdentifier());
218 // set RuntimeBeanRegistrators on beans implementing
219 // RuntimeBeanRegistratorAwareModule, each module
220 // should have exactly one runtime jmx registrator.
221 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
222 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
224 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
225 if (entry.hasOldModule() == false) {
226 runtimeBeanRegistrator = baseJMXRegistrator
227 .createRuntimeBeanRegistrator(entry.getName());
229 // reuse old JMX registrator
230 runtimeBeanRegistrator = entry.getOldInternalInfo()
231 .getRuntimeBeanRegistrator();
233 // set runtime jmx registrator if required
234 Module module = entry.getModule();
235 if (module instanceof RuntimeBeanRegistratorAwareModule) {
236 ((RuntimeBeanRegistratorAwareModule) module)
237 .setRuntimeBeanRegistrator(runtimeBeanRegistrator);
239 // save it to info so it is accessible afterwards
240 runtimeRegistrators.put(entry.getName(), runtimeBeanRegistrator);
243 // can register runtime beans
244 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController
245 .secondPhaseCommit();
247 // copy configuration to read only mode
248 List<ObjectName> newInstances = new LinkedList<>();
249 List<ObjectName> reusedInstances = new LinkedList<>();
250 List<ObjectName> recreatedInstances = new LinkedList<>();
252 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
255 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
256 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
257 .get(moduleIdentifier);
259 throw new NullPointerException("Module not found "
261 Module module = entry.getModule();
262 ObjectName primaryReadOnlyON = ObjectNameUtil
263 .createReadOnlyModuleON(moduleIdentifier);
265 // determine if current instance was recreated or reused or is new
267 // rules for closing resources:
268 // osgi registration - will be (re)created every time, so it needs
270 // module jmx registration - will be (re)created every time, needs
272 // runtime jmx registration - should be taken care of by module
274 // instance - is closed only if it was destroyed
275 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
276 .createModuleJMXRegistrator();
278 if (entry.hasOldModule()) {
279 ModuleInternalInfo oldInternalInfo = entry.getOldInternalInfo();
280 DynamicReadableWrapper oldReadableConfigBean = oldInternalInfo
281 .getReadableModule();
282 currentConfig.remove(entry.getName());
284 // test if old instance == new instance
285 if (oldReadableConfigBean.getInstance().equals(
286 module.getInstance())) {
287 // reused old instance:
288 // wrap in readable dynamic mbean
289 reusedInstances.add(primaryReadOnlyON);
291 // recreated instance:
292 // it is responsibility of module to call the old instance -
293 // we just need to unregister configbean
294 recreatedInstances.add(primaryReadOnlyON);
296 // close old osgi registration in any case
297 oldInternalInfo.getOsgiRegistration().close();
298 // close old module jmx registrator
299 oldInternalInfo.getModuleJMXRegistrator().close();
302 // wrap in readable dynamic mbean
303 newInstances.add(primaryReadOnlyON);
306 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
307 module, module.getInstance(), moduleIdentifier,
308 registryMBeanServer, configMBeanServer);
312 newModuleJMXRegistrator.registerMBean(newReadableConfigBean,
314 } catch (InstanceAlreadyExistsException e) {
315 throw new IllegalStateException(e);
319 OsgiRegistration osgiRegistration = beanToOsgiServiceManager
320 .registerToOsgi(module.getClass(),
321 newReadableConfigBean.getInstance(),
324 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
325 .get(entry.getName());
326 ModuleInternalInfo newInfo = new ModuleInternalInfo(
327 entry.getName(), newReadableConfigBean, osgiRegistration,
328 runtimeBeanRegistrator, newModuleJMXRegistrator,
331 newConfigEntries.put(module, newInfo);
334 currentConfig.addAll(newConfigEntries.values());
337 version = configTransactionController.getVersion();
338 return new CommitStatus(newInstances, reusedInstances,
346 public synchronized List<ObjectName> getOpenConfigs() {
347 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
348 .getCurrentTransactions();
349 List<ObjectName> result = new ArrayList<>(transactions.size());
350 for (ConfigTransactionControllerInternal configTransactionController : transactions
352 result.add(configTransactionController.getControllerObjectName());
358 * Abort open transactions and unregister read only modules. Since this
359 * class is not responsible for registering itself under
360 * {@link ConfigRegistryMXBean#OBJECT_NAME}, it will not unregister itself
364 public synchronized void close() {
365 // abort transactions
366 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
367 .getCurrentTransactions();
368 for (ConfigTransactionControllerInternal configTransactionController : transactions
371 configTransactionController.abortConfig();
372 } catch (RuntimeException e) {
373 logger.warn("Ignoring exception while aborting {}",
374 configTransactionController, e);
378 // destroy all live objects one after another in order of the dependency
380 List<DestroyedModule> destroyedModules = currentConfig
381 .getModulesToBeDestroyed();
382 for (DestroyedModule destroyedModule : destroyedModules) {
383 destroyedModule.close();
385 // unregister MBeans that failed to unregister properly
386 baseJMXRegistrator.close();
387 // remove jmx servers
388 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
389 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
397 public long getVersion() {
405 public Set<String> getAvailableModuleNames() {
406 return new HierarchicalConfigMBeanFactoriesHolder(
407 resolver.getAllFactories()).getModuleNames();
414 public boolean isHealthy() {
424 public Set<ObjectName> lookupConfigBeans() {
425 return lookupConfigBeans("*", "*");
432 public Set<ObjectName> lookupConfigBeans(String moduleName) {
433 return lookupConfigBeans(moduleName, "*");
440 public ObjectName lookupConfigBean(String moduleName, String instanceName)
441 throws InstanceNotFoundException {
442 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
449 public Set<ObjectName> lookupConfigBeans(String moduleName,
450 String instanceName) {
451 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
453 return baseJMXRegistrator.queryNames(namePattern, null);
460 public Set<ObjectName> lookupRuntimeBeans() {
461 return lookupRuntimeBeans("*", "*");
468 public Set<ObjectName> lookupRuntimeBeans(String moduleName,
469 String instanceName) {
470 if (moduleName == null)
472 if (instanceName == null)
474 ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
475 moduleName, instanceName);
476 return baseJMXRegistrator.queryNames(namePattern, null);
482 * Holds currently running modules
486 private final Map<ModuleIdentifier, ModuleInternalInfo> currentConfig = new HashMap<>();
489 * Add all modules to the internal map. Also add service instance to OSGi
492 public void addAll(Collection<ModuleInternalInfo> configInfos) {
493 if (currentConfig.size() > 0) {
494 throw new IllegalStateException(
495 "Error - some config entries were not removed: "
498 for (ModuleInternalInfo configInfo : configInfos) {
503 private void add(ModuleInternalInfo configInfo) {
504 ModuleInternalInfo oldValue = currentConfig.put(configInfo.getName(),
506 if (oldValue != null) {
507 throw new IllegalStateException(
508 "Cannot overwrite module with same name:"
509 + configInfo.getName() + ":" + configInfo);
514 * Remove entry from current config.
516 public void remove(ModuleIdentifier name) {
517 ModuleInternalInfo removed = currentConfig.remove(name);
518 if (removed == null) {
519 throw new IllegalStateException(
520 "Cannot remove from ConfigHolder - name not found:" + name);
524 public Collection<ModuleInternalInfo> getEntries() {
525 return currentConfig.values();
528 public List<DestroyedModule> getModulesToBeDestroyed() {
529 List<DestroyedModule> result = new ArrayList<>();
530 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
531 result.add(moduleInternalInfo.toDestroyedModule());
533 Collections.sort(result);
539 * Holds Map<transactionName, transactionController> and purges it each time its
540 * content is requested.
543 class TransactionsHolder {
545 * This map keeps transaction names and
546 * {@link ConfigTransactionControllerInternal} instances, because platform
547 * MBeanServer transforms mbeans into another representation. Map is cleaned
548 * every time current transactions are requested.
551 @GuardedBy("ConfigRegistryImpl.this")
552 private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
555 * Can only be called from within synchronized method.
557 public void add(String transactionName,
558 ConfigTransactionControllerInternal transactionController) {
559 Object oldValue = transactions.put(transactionName,
560 transactionController);
561 if (oldValue != null) {
562 throw new IllegalStateException(
563 "Error: two transactions with same name");
568 * Purges closed transactions from transactions map. Can only be called from
569 * within synchronized method. Calling this method more than once within the
570 * method can modify the resulting map that was obtained in previous calls.
572 * @return current view on transactions map.
574 public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
575 // first, remove closed transaction
576 for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
577 .entrySet().iterator(); it.hasNext();) {
578 Entry<String, ConfigTransactionControllerInternal> entry = it
580 if (entry.getValue().isClosed()) {
584 return Collections.unmodifiableMap(transactions);