8fa7fdfddef8b61922bf71accc0327ccc616bfe1
[controller.git] / opendaylight / config / config-manager / src / main / java / org / opendaylight / controller / config / manager / impl / dependencyresolver / DependencyResolverImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.controller.config.manager.impl.dependencyresolver;
9
10 import com.google.common.base.Preconditions;
11 import java.util.HashSet;
12 import java.util.LinkedHashSet;
13 import java.util.Set;
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;
38
39 /**
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.
43  */
44 final class DependencyResolverImpl implements DependencyResolver,
45         Comparable<DependencyResolverImpl> {
46     private static final Logger LOG = LoggerFactory.getLogger(DependencyResolverImpl.class);
47
48     private final ModulesHolder modulesHolder;
49     private final ModuleIdentifier name;
50     private final TransactionStatus transactionStatus;
51     @GuardedBy("this")
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;
58
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;
70     }
71
72     /**
73      * {@inheritDoc}
74      */
75     //TODO: check for cycles
76     @Override
77     public void validateDependency(
78             final Class<? extends AbstractServiceInterface> expectedServiceInterface,
79             final ObjectName dependentReadOnlyON, final JmxAttribute jmxAttribute) {
80
81         this.transactionStatus.checkNotCommitted();
82         if (expectedServiceInterface == null) {
83             throw new NullPointerException(
84                     "Parameter 'expectedServiceInterface' is null");
85         }
86         if (jmxAttribute == null) {
87             throw new NullPointerException("Parameter 'jmxAttribute' is null");
88         }
89
90         JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
91                 "is null, expected dependency implementing "
92                         + expectedServiceInterface, jmxAttribute
93         );
94
95
96         // check that objectName belongs to this transaction - this should be
97         // stripped
98         // in DynamicWritableWrapper
99         final boolean hasTransaction = ObjectNameUtil
100                 .getTransactionName(dependentReadOnlyON) != null;
101         JmxAttributeValidationException.checkCondition(
102                 !hasTransaction,
103                 String.format("ObjectName should not contain "
104                                 + "transaction name. %s set to %s. ", jmxAttribute,
105                         dependentReadOnlyON
106             ), jmxAttribute
107         );
108
109         final ObjectName newDependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
110
111         final ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(newDependentReadOnlyON, ObjectNameUtil
112                 .TYPE_MODULE);
113
114         final ModuleFactory foundFactory = this.modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
115
116         final boolean implementsSI = foundFactory
117                 .isModuleImplementingServiceInterface(expectedServiceInterface);
118         if (!implementsSI) {
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 , "
122                             + "attribute %s",
123                     foundFactory.getImplementationName(), foundFactory,
124                     expectedServiceInterface, newDependentReadOnlyON,
125                     jmxAttribute
126             );
127             throw new JmxAttributeValidationException(message, jmxAttribute);
128         }
129         synchronized (this) {
130             this.dependencies.add(moduleIdentifier);
131         }
132     }
133
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));
142         }
143         return translatedDependentReadOnlyON;
144     }
145
146     //TODO: check for cycles
147     @Override
148     public <T> T resolveInstance(final Class<T> expectedType, final ObjectName dependentReadOnlyON,
149                                  final JmxAttribute jmxAttribute) {
150         final Module module = resolveModuleInstance(dependentReadOnlyON, jmxAttribute);
151
152         synchronized (this) {
153             this.dependencies.add(module.getIdentifier());
154         }
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);
161         }
162         try {
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);
169         }
170     }
171
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();
179
180         final ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(
181                 translatedDependentReadOnlyON, ObjectNameUtil.TYPE_MODULE);
182
183         return Preconditions.checkNotNull(this.modulesHolder.findModule(dependentModuleIdentifier, jmxAttribute));
184     }
185
186     @Override
187     public boolean canReuseDependency(final ObjectName objectName, final JmxAttribute jmxAttribute) {
188         Preconditions.checkNotNull(objectName);
189         Preconditions.checkNotNull(jmxAttribute);
190
191         final Module currentModule = resolveModuleInstance(objectName, jmxAttribute);
192         final ModuleIdentifier identifier = currentModule.getIdentifier();
193         final ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = this.modulesHolder
194                 .findModuleInternalTransactionalInfo(identifier);
195
196         if (moduleInternalTransactionalInfo.hasOldModule()) {
197             final Module oldModule = moduleInternalTransactionalInfo.getOldInternalInfo().getReadableModule().getModule();
198             return currentModule.canReuse(oldModule);
199         }
200         return false;
201     }
202
203     @Override
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());
211         }
212         if (expectedBaseClass.isAssignableFrom(deserialized)) {
213             return (Class<T>) deserialized;
214         }
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);
218     }
219
220     @Override
221     public <T extends BaseIdentity> void validateIdentity(final IdentityAttributeRef identityRef,
222             final Class<T> expectedBaseClass, final JmxAttribute jmxAttribute) {
223         try {
224             resolveIdentity(identityRef, expectedBaseClass);
225         } catch (final Exception e) {
226             throw JmxAttributeValidationException.wrap(e, jmxAttribute);
227         }
228     }
229
230     @Override
231     public int compareTo(final DependencyResolverImpl o) {
232         this.transactionStatus.checkCommitStarted();
233         return Integer.compare(getMaxDependencyDepth(),
234                 o.getMaxDependencyDepth());
235     }
236
237     int getMaxDependencyDepth() {
238         if (this.maxDependencyDepth == null) {
239             throw new IllegalStateException("Dependency depth was not computed");
240         }
241         return this.maxDependencyDepth;
242     }
243
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<>());
253         }
254     }
255
256     private static int getMaxDepth(final DependencyResolverImpl impl,
257                                    final DependencyResolverManager manager,
258                                    final LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
259         int maxDepth = 0;
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));
270             }
271             int subDepth;
272             if (dependentDRI.maxDependencyDepth != null) {
273                 subDepth = dependentDRI.maxDependencyDepth;
274             } else {
275                 subDepth = getMaxDepth(dependentDRI, manager,
276                         chainForDetectingCycles2);
277                 dependentDRI.maxDependencyDepth = subDepth;
278             }
279             if (subDepth + 1 > maxDepth) {
280                 maxDepth = subDepth + 1;
281             }
282         }
283         impl.maxDependencyDepth = maxDepth;
284         return maxDepth;
285     }
286
287     @Override
288     public ModuleIdentifier getIdentifier() {
289         return this.name;
290     }
291
292     @Override
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);
299     }
300
301     @Override
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);
307     }
308 }