Merge "Trigger a GC once initial configuration has been pushed"
[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 static java.lang.String.format;
11
12 import java.util.HashSet;
13 import java.util.LinkedHashSet;
14 import java.util.Set;
15 import javax.annotation.concurrent.GuardedBy;
16 import javax.management.AttributeNotFoundException;
17 import javax.management.InstanceNotFoundException;
18 import javax.management.JMX;
19 import javax.management.MBeanException;
20 import javax.management.MBeanServer;
21 import javax.management.ObjectName;
22 import javax.management.ReflectionException;
23 import org.opendaylight.controller.config.api.DependencyResolver;
24 import org.opendaylight.controller.config.api.IdentityAttributeRef;
25 import org.opendaylight.controller.config.api.JmxAttribute;
26 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
27 import org.opendaylight.controller.config.api.ModuleIdentifier;
28 import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
29 import org.opendaylight.controller.config.api.annotations.AbstractServiceInterface;
30 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
31 import org.opendaylight.controller.config.manager.impl.TransactionStatus;
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.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
37 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 /**
42  * Protect {@link org.opendaylight.controller.config.spi.Module#getInstance()}
43  * by creating proxy that would throw exception if those methods are called
44  * during validation. Tracks dependencies for ordering purposes.
45  */
46 final class DependencyResolverImpl implements DependencyResolver,
47         Comparable<DependencyResolverImpl> {
48     private static final Logger logger = LoggerFactory.getLogger(DependencyResolverImpl.class);
49
50     private final ModulesHolder modulesHolder;
51     private final ModuleIdentifier name;
52     private final TransactionStatus transactionStatus;
53     @GuardedBy("this")
54     private final Set<ModuleIdentifier> dependencies = new HashSet<>();
55     private final ServiceReferenceReadableRegistry readableRegistry;
56     private final CodecRegistry codecRegistry;
57     private final String transactionName;
58     private final MBeanServer mBeanServer;
59
60     DependencyResolverImpl(ModuleIdentifier currentModule,
61                            TransactionStatus transactionStatus, ModulesHolder modulesHolder,
62                            ServiceReferenceReadableRegistry readableRegistry, CodecRegistry codecRegistry,
63                            String transactionName, MBeanServer mBeanServer) {
64         this.codecRegistry = codecRegistry;
65         this.name = currentModule;
66         this.transactionStatus = transactionStatus;
67         this.modulesHolder = modulesHolder;
68         this.readableRegistry = readableRegistry;
69         this.transactionName = transactionName;
70         this.mBeanServer = mBeanServer;
71     }
72
73     /**
74      * {@inheritDoc}
75      */
76     //TODO: check for cycles
77     @Override
78     public void validateDependency(
79             Class<? extends AbstractServiceInterface> expectedServiceInterface,
80             ObjectName dependentReadOnlyON, JmxAttribute jmxAttribute) {
81
82         transactionStatus.checkNotCommitted();
83         if (expectedServiceInterface == null) {
84             throw new NullPointerException(
85                     "Parameter 'expectedServiceInterface' is null");
86         }
87         if (jmxAttribute == null) {
88             throw new NullPointerException("Parameter 'jmxAttribute' is null");
89         }
90
91         JmxAttributeValidationException.checkNotNull(dependentReadOnlyON,
92                 "is null, expected dependency implementing "
93                         + expectedServiceInterface, jmxAttribute
94         );
95
96
97         // check that objectName belongs to this transaction - this should be
98         // stripped
99         // in DynamicWritableWrapper
100         boolean hasTransaction = ObjectNameUtil
101                 .getTransactionName(dependentReadOnlyON) != null;
102         JmxAttributeValidationException.checkCondition(
103                 hasTransaction == false,
104                 format("ObjectName should not contain "
105                                 + "transaction name. %s set to %s. ", jmxAttribute,
106                         dependentReadOnlyON
107                 ), jmxAttribute
108         );
109
110         dependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
111
112         ModuleIdentifier moduleIdentifier = ObjectNameUtil.fromON(dependentReadOnlyON, ObjectNameUtil
113                 .TYPE_MODULE);
114
115         ModuleFactory foundFactory = modulesHolder.findModuleFactory(moduleIdentifier, jmxAttribute);
116
117         boolean implementsSI = foundFactory
118                 .isModuleImplementingServiceInterface(expectedServiceInterface);
119         if (implementsSI == false) {
120             String message = format(
121                     "Found module factory does not expose expected service interface. "
122                             + "Module name is %s : %s, expected service interface %s, dependent module ON %s , "
123                             + "attribute %s",
124                     foundFactory.getImplementationName(), foundFactory,
125                     expectedServiceInterface, dependentReadOnlyON,
126                     jmxAttribute
127             );
128             throw new JmxAttributeValidationException(message, jmxAttribute);
129         }
130         synchronized (this) {
131             dependencies.add(moduleIdentifier);
132         }
133     }
134
135     // translate from serviceref to module ON
136     private ObjectName translateServiceRefIfPossible(ObjectName dependentReadOnlyON) {
137         if (ObjectNameUtil.isServiceReference(dependentReadOnlyON)) {
138             String serviceQName = ObjectNameUtil.getServiceQName(dependentReadOnlyON);
139             String refName = ObjectNameUtil.getReferenceName(dependentReadOnlyON);
140             dependentReadOnlyON = ObjectNameUtil.withoutTransactionName( // strip again of transaction name
141                     readableRegistry.lookupConfigBeanByServiceInterfaceName(serviceQName, refName));
142         }
143         return dependentReadOnlyON;
144     }
145
146     /**
147      * {@inheritDoc}
148      */
149     //TODO: check for cycles
150     @Override
151     public <T> T resolveInstance(Class<T> expectedType, ObjectName dependentReadOnlyON,
152                                  JmxAttribute jmxAttribute) {
153         if (expectedType == null || dependentReadOnlyON == null || jmxAttribute == null) {
154             throw new IllegalArgumentException(format(
155                     "Null parameters not allowed, got %s %s %s", expectedType,
156                     dependentReadOnlyON, jmxAttribute));
157         }
158         dependentReadOnlyON = translateServiceRefIfPossible(dependentReadOnlyON);
159         transactionStatus.checkCommitStarted();
160         transactionStatus.checkNotCommitted();
161
162         ModuleIdentifier dependentModuleIdentifier = ObjectNameUtil.fromON(
163                 dependentReadOnlyON, ObjectNameUtil.TYPE_MODULE);
164         Module module = modulesHolder.findModule(dependentModuleIdentifier,
165                 jmxAttribute);
166         synchronized (this) {
167             dependencies.add(dependentModuleIdentifier);
168         }
169         AutoCloseable instance = module.getInstance();
170         if (instance == null) {
171             String message = format(
172                     "Error while %s resolving instance %s. getInstance() returned null. "
173                             + "Expected type %s , attribute %s", name,
174                     dependentModuleIdentifier, expectedType, jmxAttribute
175             );
176             throw new JmxAttributeValidationException(message, jmxAttribute);
177         }
178         try {
179             return expectedType.cast(instance);
180         } catch (ClassCastException e) {
181             String message = format(
182                     "Instance cannot be cast to expected type. Instance class is %s , "
183                             + "expected type %s , attribute %s",
184                     instance.getClass(), expectedType, jmxAttribute
185             );
186             throw new JmxAttributeValidationException(message, e, jmxAttribute);
187         }
188     }
189
190     @Override
191     public <T extends BaseIdentity> Class<? extends T> resolveIdentity(IdentityAttributeRef identityRef, Class<T> expectedBaseClass) {
192         final QName qName = QName.create(identityRef.getqNameOfIdentity());
193         IdentityCodec<?> identityCodec = codecRegistry.getIdentityCodec();
194         Class<? extends BaseIdentity> deserialized = identityCodec.deserialize(qName);
195         if (deserialized == null) {
196             throw new IllegalStateException("Unable to retrieve identity class for " + qName + ", null response from "
197                     + codecRegistry);
198         }
199         if (expectedBaseClass.isAssignableFrom(deserialized)) {
200             return (Class<T>) deserialized;
201         } else {
202             logger.error("Cannot resolve class of identity {} : deserialized class {} is not a subclass of {}.",
203                     identityRef, deserialized, expectedBaseClass);
204             throw new IllegalArgumentException("Deserialized identity " + deserialized + " cannot be cast to " + expectedBaseClass);
205         }
206     }
207
208     @Override
209     public <T extends BaseIdentity> void validateIdentity(IdentityAttributeRef identityRef, Class<T> expectedBaseClass, JmxAttribute jmxAttribute) {
210         try {
211             resolveIdentity(identityRef, expectedBaseClass);
212         } catch (Exception e) {
213             throw JmxAttributeValidationException.wrap(e, jmxAttribute);
214         }
215     }
216
217     @Override
218     public int compareTo(DependencyResolverImpl o) {
219         transactionStatus.checkCommitted();
220         return Integer.compare(getMaxDependencyDepth(),
221                 o.getMaxDependencyDepth());
222     }
223
224     private Integer maxDependencyDepth;
225
226     int getMaxDependencyDepth() {
227         if (maxDependencyDepth == null) {
228             throw new IllegalStateException("Dependency depth was not computed");
229         }
230         return maxDependencyDepth;
231     }
232
233     void countMaxDependencyDepth(DependencyResolverManager manager) {
234         transactionStatus.checkCommitted();
235         if (maxDependencyDepth == null) {
236             maxDependencyDepth = getMaxDepth(this, manager,
237                     new LinkedHashSet<ModuleIdentifier>());
238         }
239     }
240
241     private static int getMaxDepth(DependencyResolverImpl impl,
242                                    DependencyResolverManager manager,
243                                    LinkedHashSet<ModuleIdentifier> chainForDetectingCycles) {
244         int maxDepth = 0;
245         LinkedHashSet<ModuleIdentifier> chainForDetectingCycles2 = new LinkedHashSet<>(
246                 chainForDetectingCycles);
247         chainForDetectingCycles2.add(impl.getIdentifier());
248         for (ModuleIdentifier dependencyName : impl.dependencies) {
249             DependencyResolverImpl dependentDRI = manager
250                     .getOrCreate(dependencyName);
251             if (chainForDetectingCycles2.contains(dependencyName)) {
252                 throw new IllegalStateException(format(
253                         "Cycle detected, %s contains %s",
254                         chainForDetectingCycles2, dependencyName));
255             }
256             int subDepth;
257             if (dependentDRI.maxDependencyDepth != null) {
258                 subDepth = dependentDRI.maxDependencyDepth;
259             } else {
260                 subDepth = getMaxDepth(dependentDRI, manager,
261                         chainForDetectingCycles2);
262                 dependentDRI.maxDependencyDepth = subDepth;
263             }
264             if (subDepth + 1 > maxDepth) {
265                 maxDepth = subDepth + 1;
266             }
267         }
268         impl.maxDependencyDepth = maxDepth;
269         return maxDepth;
270     }
271
272     @Override
273     public ModuleIdentifier getIdentifier() {
274         return name;
275     }
276
277     @Override
278     public Object getAttribute(ObjectName name, String attribute)
279             throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException {
280         name = translateServiceRefIfPossible(name);
281         // add transaction name
282         name = ObjectNameUtil.withTransactionName(name, transactionName);
283         return mBeanServer.getAttribute(name, attribute);
284     }
285
286     @Override
287     public <T> T newMXBeanProxy(ObjectName name, Class<T> interfaceClass) {
288         name = translateServiceRefIfPossible(name);
289         // add transaction name
290         name = ObjectNameUtil.withTransactionName(name, transactionName);
291         return JMX.newMXBeanProxy(mBeanServer, name, interfaceClass);
292     }
293 }