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.dependencyresolver;
10 import com.google.common.base.Preconditions;
11 import java.util.HashSet;
12 import java.util.LinkedHashSet;
14 import javax.annotation.concurrent.GuardedBy;
15 import javax.management.AttributeNotFoundException;
16 import javax.management.InstanceNotFoundException;
17 import javax.management.JMX;
18 import javax.management.MBeanException;
19 import javax.management.MBeanServer;
20 import javax.management.ObjectName;
21 import javax.management.ReflectionException;
22 import org.opendaylight.controller.config.api.DependencyResolver;
23 import org.opendaylight.controller.config.api.IdentityAttributeRef;
24 import org.opendaylight.controller.config.api.JmxAttribute;
25 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
26 import org.opendaylight.controller.config.api.ModuleIdentifier;
27 import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
28 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
29 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
30 import org.opendaylight.controller.config.manager.impl.TransactionStatus;
31 import org.opendaylight.controller.config.manager.impl.osgi.mapping.BindingContextProvider;
32 import org.opendaylight.controller.config.spi.Module;
33 import org.opendaylight.controller.config.spi.ModuleFactory;
34 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * Protect {@link org.opendaylight.controller.config.spi.Module#getInstance()}
41 * by creating proxy that would throw exception if those methods are called
42 * during validation. Tracks dependencies for ordering purposes.
44 final class DependencyResolverImpl implements DependencyResolver,
45 Comparable<DependencyResolverImpl> {
46 private static final Logger LOG = LoggerFactory.getLogger(DependencyResolverImpl.class);
48 private final ModulesHolder modulesHolder;
49 private final ModuleIdentifier name;
50 private final TransactionStatus transactionStatus;
52 private final Set<ModuleIdentifier> dependencies = new HashSet<>();
53 private final ServiceReferenceReadableRegistry readableRegistry;
54 private final BindingContextProvider bindingContextProvider;
55 private final String transactionName;
56 private final MBeanServer mBeanServer;
57 private Integer maxDependencyDepth;
59 DependencyResolverImpl(final ModuleIdentifier currentModule,
60 final TransactionStatus transactionStatus, final ModulesHolder modulesHolder,
61 final ServiceReferenceReadableRegistry readableRegistry, final BindingContextProvider bindingContextProvider,
62 final String transactionName, final MBeanServer mBeanServer) {
63 this.bindingContextProvider = bindingContextProvider;
64 this.name = currentModule;
65 this.transactionStatus = transactionStatus;
66 this.modulesHolder = modulesHolder;
67 this.readableRegistry = readableRegistry;
68 this.transactionName = transactionName;
69 this.mBeanServer = mBeanServer;
75 //TODO: check for cycles
77 public void validateDependency(
78 final Class<? extends AbstractServiceInterface> expectedServiceInterface,
79 final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
81 this.transactionStatus.checkNotCommitted();
82 if (expectedServiceInterface == null) {
83 throw new NullPointerException(
84 "Parameter 'expectedServiceInterface' is null");
86 if (jmxAttribute == null) {
87 throw new NullPointerException("Parameter 'jmxAttribute' is null");
90 JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
91 "is null, expected dependency implementing "
92 + expectedServiceInterface, jmxAttribute
96 // check that objectName belongs to this transaction - this should be
98 // in DynamicWritableWrapper
99 final boolean hasTransaction = ObjectNameUtil
100 .getTransactionName(dependentReadOnlyON) != null;
101 JmxAttributeValidationException.checkCondition(
103 String.format("ObjectName should not contain "
104 + "transaction name. %s set to %s. ", jmxAttribute,
109 final ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
111 final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON, ObjectNameUtil
114 final ModuleFactory foundFactory = this.modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
116 final boolean implementsSI = foundFactory
117 .isModuleImplementingServiceInterface(expectedServiceInterface);
119 final String message = String.format(
120 "Found module factory does not expose expected service interface. "
121 + "Module name is %s : %s, expected service interface %s, dependent module ON %s , "
123 foundFactory.getImplementationName(), foundFactory,
124 expectedServiceInterface, newDependentReadOnlyON,
127 throw new JmxAttributeValidationException(message, jmxAttribute);
129 synchronized (this) {
130 this.dependencies.add(moduleIdentifier);
134 // translate from serviceref to module ON
135 private ObjectName translateServiceRefIfPossible(final ObjectName dependentReadOnlyON) {
136 ObjectName translatedDependentReadOnlyON = dependentReadOnlyON;
137 if (ObjectNameUtil.isServiceReference(translatedDependentReadOnlyON)) {
138 final String serviceQName = ObjectNameUtil.getServiceQName(translatedDependentReadOnlyON);
139 final String refName = ObjectNameUtil.getReferenceName(translatedDependentReadOnlyON);
140 translatedDependentReadOnlyON = ObjectNameUtil.withoutTransactionName( // strip again of transaction name
141 this.readableRegistry.lookupConfigBeanByServiceInterfaceName(serviceQName, refName));
143 return translatedDependentReadOnlyON;
146 //TODO: check for cycles
148 public <T> T resolveInstance(final Class<T> expectedType, final ObjectName dependentReadOnlyON,
149 final JmxAttribute jmxAttribute) {
150 final Module module = resolveModuleInstance(dependentReadOnlyON, jmxAttribute);
152 synchronized (this) {
153 this.dependencies.add(module.getIdentifier());
155 final AutoCloseable instance = module.getInstance();
156 if (instance == null) {
157 final String message = String.format(
158 "Error while %s resolving instance %s. getInstance() returned null. Expected type %s, attribute %s",
159 this.name, module.getIdentifier(), expectedType, jmxAttribute);
160 throw new JmxAttributeValidationException(message, jmxAttribute);
163 return expectedType.cast(instance);
164 } catch (final ClassCastException e) {
165 final String message = String.format(
166 "Instance cannot be cast to expected type. Instance class is %s, expected type %s , attribute %s",
167 instance.getClass(), expectedType, jmxAttribute);
168 throw new JmxAttributeValidationException(message, e, jmxAttribute);
172 private Module resolveModuleInstance(final ObjectName dependentReadOnlyON,
173 final JmxAttribute jmxAttribute) {
174 Preconditions.checkArgument(dependentReadOnlyON != null ,"dependentReadOnlyON");
175 Preconditions.checkArgument(jmxAttribute != null, "jmxAttribute");
176 final ObjectName translatedDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
177 this.transactionStatus.checkCommitStarted();
178 this.transactionStatus.checkNotCommitted();
180 final ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(
181 translatedDependentReadOnlyON, ObjectNameUtil.TYPE_MODULE);
183 return Preconditions.checkNotNull(this.modulesHolder.findModule(dependentModuleIdentifier, jmxAttribute));
187 public boolean canReuseDependency(final ObjectName objectName, final JmxAttribute jmxAttribute) {
188 Preconditions.checkNotNull(objectName);
189 Preconditions.checkNotNull(jmxAttribute);
191 final Module currentModule = resolveModuleInstance(objectName, jmxAttribute);
192 final ModuleIdentifier identifier = currentModule.getIdentifier();
193 final ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = this.modulesHolder
194 .findModuleInternalTransactionalInfo(identifier);
196 if (moduleInternalTransactionalInfo.hasOldModule()) {
197 final Module oldModule = moduleInternalTransactionalInfo.getOldInternalInfo().getReadableModule().getModule();
198 return currentModule.canReuse(oldModule);
204 public <T extends BaseIdentity> Class<? extends T> resolveIdentity(final IdentityAttributeRef identityRef,
205 final Class<T> expectedBaseClass) {
206 final QName qName = QName.create(identityRef.getqNameOfIdentity());
207 final Class<?> deserialized = this.bindingContextProvider.getBindingContext().getIdentityClass(qName);
208 if (deserialized == null) {
209 throw new IllegalStateException("Unable to retrieve identity class for " + qName + ", null response from "
210 + this.bindingContextProvider.getBindingContext());
212 if (expectedBaseClass.isAssignableFrom(deserialized)) {
213 return (Class<T>) deserialized;
215 LOG.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.", identityRef,
216 deserialized, expectedBaseClass);
217 throw new IllegalArgumentException("Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
221 public <T extends BaseIdentity> void validateIdentity(final IdentityAttributeRef identityRef,
222 final Class<T> expectedBaseClass, final JmxAttribute jmxAttribute) {
224 resolveIdentity(identityRef, expectedBaseClass);
225 } catch (final Exception e) {
226 throw JmxAttributeValidationException.wrap(e, jmxAttribute);
231 public int compareTo(final DependencyResolverImpl o) {
232 this.transactionStatus.checkCommitStarted();
233 return Integer.compare(getMaxDependencyDepth(),
234 o.getMaxDependencyDepth());
237 int getMaxDependencyDepth() {
238 if (this.maxDependencyDepth == null) {
239 throw new IllegalStateException("Dependency depth was not computed");
241 return this.maxDependencyDepth;
244 void countMaxDependencyDepth(final DependencyResolverManager manager) {
245 // We can calculate the dependency after second phase commit was started
246 // Second phase commit starts after validation and validation adds the dependencies into the dependency resolver, which are necessary for the calculation
247 // FIXME generated code for abstract module declares validate method as non-final
248 // Overriding the validate would cause recreate every time instead of reuse + also possibly wrong close order if there is another module depending
249 this.transactionStatus.checkCommitStarted();
250 if (this.maxDependencyDepth == null) {
251 this.maxDependencyDepth = getMaxDepth(this, manager,
252 new LinkedHashSet<>());
256 private static int getMaxDepth(final DependencyResolverImpl impl,
257 final DependencyResolverManager manager,
258 final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
260 final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(
261 chainForDetectingCycles);
262 chainForDetectingCycles2.add(impl.getIdentifier());
263 for (final ModuleIdentifier dependencyName : impl.dependencies) {
264 final DependencyResolverImpl dependentDRI = manager
265 .getOrCreate(dependencyName);
266 if (chainForDetectingCycles2.contains(dependencyName)) {
267 throw new IllegalStateException(String.format(
268 "Cycle detected, %s contains %s",
269 chainForDetectingCycles2, dependencyName));
272 if (dependentDRI.maxDependencyDepth != null) {
273 subDepth = dependentDRI.maxDependencyDepth;
275 subDepth = getMaxDepth(dependentDRI, manager,
276 chainForDetectingCycles2);
277 dependentDRI.maxDependencyDepth = subDepth;
279 if (subDepth + 1 > maxDepth) {
280 maxDepth = subDepth + 1;
283 impl.maxDependencyDepth = maxDepth;
288 public ModuleIdentifier getIdentifier() {
293 public Object getAttribute(final ObjectName name, final String attribute)
294 throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
295 ObjectName newName = translateServiceRefIfPossible(name);
296 // add transaction name
297 newName = ObjectNameUtil.withTransactionName(newName, this.transactionName);
298 return this.mBeanServer.getAttribute(newName, attribute);
302 public <T> T newMXBeanProxy(final ObjectName name, final Class<T> interfaceClass) {
303 ObjectName newName = translateServiceRefIfPossible(name);
304 // add transaction name
305 newName = ObjectNameUtil.withTransactionName(newName, this.transactionName);
306 return JMX.newMXBeanProxy(this.mBeanServer, newName, interfaceClass);