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();
118 this.bundleContext = bundleContext;
119 this.configMBeanServer = configMBeanServer;
120 this.baseJMXRegistrator = baseJMXRegistrator;
121 this.registryMBeanServer = MBeanServerFactory
122 .createMBeanServer("ConfigRegistry" + configMBeanServer.getDefaultDomain());
123 this.transactionsMBeanServer = MBeanServerFactory
124 .createMBeanServer("ConfigTransactions" + configMBeanServer.getDefaultDomain());
128 * Create new {@link ConfigTransactionControllerImpl }
131 public synchronized ObjectName beginConfig() {
132 return beginConfigInternal().getControllerObjectName();
135 private synchronized ConfigTransactionControllerInternal beginConfigInternal() {
137 String transactionName = "ConfigTransaction-" + version + "-" + versionCounter;
138 TransactionJMXRegistrator transactionRegistrator = baseJMXRegistrator
139 .createTransactionJMXRegistrator(transactionName);
140 Map<String, Map.Entry<ModuleFactory, BundleContext>> allCurrentFactories = Collections.unmodifiableMap(resolver.getAllFactories());
141 ConfigTransactionControllerInternal transactionController = new ConfigTransactionControllerImpl(
142 transactionName, transactionRegistrator, version,
143 versionCounter, allCurrentFactories, transactionsMBeanServer, configMBeanServer, bundleContext);
145 transactionRegistrator.registerMBean(transactionController, transactionController.getControllerObjectName());
146 } catch (InstanceAlreadyExistsException e) {
147 throw new IllegalStateException(e);
150 transactionController.copyExistingModulesAndProcessFactoryDiff(currentConfig.getEntries(), lastListOfFactories);
152 transactionsHolder.add(transactionName, transactionController);
153 return transactionController;
160 public synchronized CommitStatus commitConfig(ObjectName transactionControllerON)
161 throws ConflictingVersionException, ValidationException {
162 final String transactionName = ObjectNameUtil
163 .getTransactionName(transactionControllerON);
164 logger.info("About to commit {}. Current parentVersion: {}, versionCounter {}", transactionName, version, versionCounter);
166 // find ConfigTransactionController
167 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder.getCurrentTransactions();
168 ConfigTransactionControllerInternal configTransactionController = transactions.get(transactionName);
169 if (configTransactionController == null) {
170 throw new IllegalArgumentException(String.format(
171 "Transaction with name '%s' not found", transactionName));
173 // check optimistic lock
174 if (version != configTransactionController.getParentVersion()) {
175 throw new ConflictingVersionException(
177 "Optimistic lock failed. Expected parent version %d, was %d",
179 configTransactionController.getParentVersion()));
181 // optimistic lock ok
183 CommitInfo commitInfo = configTransactionController.validateBeforeCommitAndLockTransaction();
184 lastListOfFactories = Collections.unmodifiableList(configTransactionController.getCurrentlyRegisteredFactories());
185 // non recoverable from here:
187 return secondPhaseCommit(
188 configTransactionController, commitInfo);
189 } catch (Throwable t) { // some libs throw Errors: e.g.
190 // javax.xml.ws.spi.FactoryFinder$ConfigurationError
192 logger.error("Configuration Transaction failed on 2PC, server is unhealthy", t);
193 if (t instanceof RuntimeException) {
194 throw (RuntimeException) t;
195 } else if (t instanceof Error) {
198 throw new RuntimeException(t);
203 private CommitStatus secondPhaseCommit(ConfigTransactionControllerInternal configTransactionController,
204 CommitInfo commitInfo) {
206 // close instances which were destroyed by the user, including
207 // (hopefully) runtime beans
208 for (DestroyedModule toBeDestroyed : commitInfo
209 .getDestroyedFromPreviousTransactions()) {
210 toBeDestroyed.close(); // closes instance (which should close
211 // runtime jmx registrator),
212 // also closes osgi registration and ModuleJMXRegistrator
214 currentConfig.remove(toBeDestroyed.getIdentifier());
217 // set RuntimeBeanRegistrators on beans implementing
218 // RuntimeBeanRegistratorAwareModule, each module
219 // should have exactly one runtime jmx registrator.
220 Map<ModuleIdentifier, RootRuntimeBeanRegistratorImpl> runtimeRegistrators = new HashMap<>();
221 for (ModuleInternalTransactionalInfo entry : commitInfo.getCommitted()
223 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator;
224 if (entry.hasOldModule() == false) {
225 runtimeBeanRegistrator = baseJMXRegistrator
226 .createRuntimeBeanRegistrator(entry.getName());
228 // reuse old JMX registrator
229 runtimeBeanRegistrator = entry.getOldInternalInfo()
230 .getRuntimeBeanRegistrator();
232 // set runtime jmx registrator if required
233 Module module = entry.getModule();
234 if (module instanceof RuntimeBeanRegistratorAwareModule) {
235 ((RuntimeBeanRegistratorAwareModule) module)
236 .setRuntimeBeanRegistrator(runtimeBeanRegistrator);
238 // save it to info so it is accessible afterwards
239 runtimeRegistrators.put(entry.getName(), runtimeBeanRegistrator);
242 // can register runtime beans
243 List<ModuleIdentifier> orderedModuleIdentifiers = configTransactionController
244 .secondPhaseCommit();
246 // copy configuration to read only mode
247 List<ObjectName> newInstances = new LinkedList<>();
248 List<ObjectName> reusedInstances = new LinkedList<>();
249 List<ObjectName> recreatedInstances = new LinkedList<>();
251 Map<Module, ModuleInternalInfo> newConfigEntries = new HashMap<>();
254 for (ModuleIdentifier moduleIdentifier : orderedModuleIdentifiers) {
255 ModuleInternalTransactionalInfo entry = commitInfo.getCommitted()
256 .get(moduleIdentifier);
258 throw new NullPointerException("Module not found "
260 Module module = entry.getModule();
261 ObjectName primaryReadOnlyON = ObjectNameUtil
262 .createReadOnlyModuleON(moduleIdentifier);
264 // determine if current instance was recreated or reused or is new
266 // rules for closing resources:
267 // osgi registration - will be (re)created every time, so it needs
269 // module jmx registration - will be (re)created every time, needs
271 // runtime jmx registration - should be taken care of by module
273 // instance - is closed only if it was destroyed
274 ModuleJMXRegistrator newModuleJMXRegistrator = baseJMXRegistrator
275 .createModuleJMXRegistrator();
277 OsgiRegistration osgiRegistration = null;
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(module.getInstance())) {
286 // reused old instance:
287 // wrap in readable dynamic mbean
288 reusedInstances.add(primaryReadOnlyON);
289 osgiRegistration = oldInternalInfo.getOsgiRegistration();
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
297 oldInternalInfo.getOsgiRegistration().close();
300 // close old module jmx registrator
301 oldInternalInfo.getModuleJMXRegistrator().close();
304 // wrap in readable dynamic mbean
305 newInstances.add(primaryReadOnlyON);
308 DynamicReadableWrapper newReadableConfigBean = new DynamicReadableWrapper(
309 module, module.getInstance(), moduleIdentifier,
310 registryMBeanServer, configMBeanServer);
314 newModuleJMXRegistrator.registerMBean(newReadableConfigBean,
316 } catch (InstanceAlreadyExistsException e) {
317 throw new IllegalStateException(e);
321 if (osgiRegistration == null) {
322 ModuleFactory moduleFactory = entry.getModuleFactory();
323 if(moduleFactory != null) {
324 BundleContext bc = configTransactionController.
325 getModuleFactoryBundleContext(moduleFactory.getImplementationName());
326 osgiRegistration = beanToOsgiServiceManager.registerToOsgi(module.getClass(),
327 newReadableConfigBean.getInstance(), entry.getName(), bc);
329 throw new NullPointerException(entry.getIdentifier().getFactoryName() + " ModuleFactory not found.");
334 RootRuntimeBeanRegistratorImpl runtimeBeanRegistrator = runtimeRegistrators
335 .get(entry.getName());
336 ModuleInternalInfo newInfo = new ModuleInternalInfo(
337 entry.getName(), newReadableConfigBean, osgiRegistration,
338 runtimeBeanRegistrator, newModuleJMXRegistrator,
341 newConfigEntries.put(module, newInfo);
344 currentConfig.addAll(newConfigEntries.values());
347 version = configTransactionController.getVersion();
348 return new CommitStatus(newInstances, reusedInstances,
356 public synchronized List<ObjectName> getOpenConfigs() {
357 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
358 .getCurrentTransactions();
359 List<ObjectName> result = new ArrayList<>(transactions.size());
360 for (ConfigTransactionControllerInternal configTransactionController : transactions
362 result.add(configTransactionController.getControllerObjectName());
368 * Abort open transactions and unregister read only modules. Since this
369 * class is not responsible for registering itself under
370 * {@link ConfigRegistryMXBean#OBJECT_NAME}, it will not unregister itself
374 public synchronized void close() {
375 // abort transactions
376 Map<String, ConfigTransactionControllerInternal> transactions = transactionsHolder
377 .getCurrentTransactions();
378 for (ConfigTransactionControllerInternal configTransactionController : transactions
381 configTransactionController.abortConfig();
382 } catch (RuntimeException e) {
383 logger.warn("Ignoring exception while aborting {}",
384 configTransactionController, e);
388 // destroy all live objects one after another in order of the dependency
390 List<DestroyedModule> destroyedModules = currentConfig
391 .getModulesToBeDestroyed();
392 for (DestroyedModule destroyedModule : destroyedModules) {
393 destroyedModule.close();
395 // unregister MBeans that failed to unregister properly
396 baseJMXRegistrator.close();
397 // remove jmx servers
398 MBeanServerFactory.releaseMBeanServer(registryMBeanServer);
399 MBeanServerFactory.releaseMBeanServer(transactionsMBeanServer);
407 public long getVersion() {
415 public Set<String> getAvailableModuleNames() {
416 return new HierarchicalConfigMBeanFactoriesHolder(
417 resolver.getAllFactories()).getModuleNames();
424 public boolean isHealthy() {
434 public Set<ObjectName> lookupConfigBeans() {
435 return lookupConfigBeans("*", "*");
442 public Set<ObjectName> lookupConfigBeans(String moduleName) {
443 return lookupConfigBeans(moduleName, "*");
450 public ObjectName lookupConfigBean(String moduleName, String instanceName)
451 throws InstanceNotFoundException {
452 return LookupBeansUtil.lookupConfigBean(this, moduleName, instanceName);
459 public Set<ObjectName> lookupConfigBeans(String moduleName,
460 String instanceName) {
461 ObjectName namePattern = ObjectNameUtil.createModulePattern(moduleName,
463 return baseJMXRegistrator.queryNames(namePattern, null);
470 public Set<ObjectName> lookupRuntimeBeans() {
471 return lookupRuntimeBeans("*", "*");
478 public Set<ObjectName> lookupRuntimeBeans(String moduleName,
479 String instanceName) {
480 if (moduleName == null)
482 if (instanceName == null)
484 ObjectName namePattern = ObjectNameUtil.createRuntimeBeanPattern(
485 moduleName, instanceName);
486 return baseJMXRegistrator.queryNames(namePattern, null);
492 * Holds currently running modules
496 private final Map<ModuleIdentifier, ModuleInternalInfo> currentConfig = new HashMap<>();
499 * Add all modules to the internal map. Also add service instance to OSGi
502 public void addAll(Collection<ModuleInternalInfo> configInfos) {
503 if (currentConfig.size() > 0) {
504 throw new IllegalStateException(
505 "Error - some config entries were not removed: "
508 for (ModuleInternalInfo configInfo : configInfos) {
513 private void add(ModuleInternalInfo configInfo) {
514 ModuleInternalInfo oldValue = currentConfig.put(configInfo.getName(),
516 if (oldValue != null) {
517 throw new IllegalStateException(
518 "Cannot overwrite module with same name:"
519 + configInfo.getName() + ":" + configInfo);
524 * Remove entry from current config.
526 public void remove(ModuleIdentifier name) {
527 ModuleInternalInfo removed = currentConfig.remove(name);
528 if (removed == null) {
529 throw new IllegalStateException(
530 "Cannot remove from ConfigHolder - name not found:" + name);
534 public Collection<ModuleInternalInfo> getEntries() {
535 return currentConfig.values();
538 public List<DestroyedModule> getModulesToBeDestroyed() {
539 List<DestroyedModule> result = new ArrayList<>();
540 for (ModuleInternalInfo moduleInternalInfo : getEntries()) {
541 result.add(moduleInternalInfo.toDestroyedModule());
543 Collections.sort(result);
549 * Holds Map<transactionName, transactionController> and purges it each time its
550 * content is requested.
553 class TransactionsHolder {
555 * This map keeps transaction names and
556 * {@link ConfigTransactionControllerInternal} instances, because platform
557 * MBeanServer transforms mbeans into another representation. Map is cleaned
558 * every time current transactions are requested.
561 @GuardedBy("ConfigRegistryImpl.this")
562 private final Map<String /* transactionName */, ConfigTransactionControllerInternal> transactions = new HashMap<>();
565 * Can only be called from within synchronized method.
567 public void add(String transactionName,
568 ConfigTransactionControllerInternal transactionController) {
569 Object oldValue = transactions.put(transactionName,
570 transactionController);
571 if (oldValue != null) {
572 throw new IllegalStateException(
573 "Error: two transactions with same name");
578 * Purges closed transactions from transactions map. Can only be called from
579 * within synchronized method. Calling this method more than once within the
580 * method can modify the resulting map that was obtained in previous calls.
582 * @return current view on transactions map.
584 public Map<String, ConfigTransactionControllerInternal> getCurrentTransactions() {
585 // first, remove closed transaction
586 for (Iterator<Entry<String, ConfigTransactionControllerInternal>> it = transactions
587 .entrySet().iterator(); it.hasNext();) {
588 Entry<String, ConfigTransactionControllerInternal> entry = it
590 if (entry.getValue().isClosed()) {
594 return Collections.unmodifiableMap(transactions);