14ca14b69dcb35de9a251ad89c55b693b59a9b16
[controller.git] / opendaylight / blueprint / src / main / java / org / opendaylight / controller / blueprint / ext / OpendaylightNamespaceHandler.java
1 /*
2  * Copyright (c) 2016 Brocade Communications 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.blueprint.ext;
9
10 import com.google.common.base.Strings;
11 import java.io.StringReader;
12 import java.net.URL;
13 import java.util.Collections;
14 import java.util.Set;
15 import javax.xml.parsers.DocumentBuilderFactory;
16 import org.apache.aries.blueprint.ComponentDefinitionRegistry;
17 import org.apache.aries.blueprint.NamespaceHandler;
18 import org.apache.aries.blueprint.ParserContext;
19 import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
20 import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
21 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
22 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
23 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
24 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
25 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
26 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
27 import org.opendaylight.controller.md.sal.binding.api.NotificationService;
28 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
29 import org.osgi.service.blueprint.container.ComponentDefinitionException;
30 import org.osgi.service.blueprint.reflect.BeanMetadata;
31 import org.osgi.service.blueprint.reflect.ComponentMetadata;
32 import org.osgi.service.blueprint.reflect.Metadata;
33 import org.osgi.service.blueprint.reflect.RefMetadata;
34 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
35 import org.osgi.service.blueprint.reflect.ServiceMetadata;
36 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
37 import org.osgi.service.blueprint.reflect.ValueMetadata;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40 import org.w3c.dom.Attr;
41 import org.w3c.dom.Element;
42 import org.w3c.dom.Node;
43 import org.w3c.dom.NodeList;
44 import org.xml.sax.InputSource;
45
46 /**
47  * The NamespaceHandler for Opendaylight blueprint extensions.
48  *
49  * @author Thomas Pantelis
50  */
51 public class OpendaylightNamespaceHandler implements NamespaceHandler {
52     public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
53     static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
54     static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
55     static final String NOTIFICATION_SERVICE_NAME = "org.opendaylight.blueprint.NotificationService";
56     static final String TYPE_ATTR = "type";
57
58     private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
59     private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
60     private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
61     private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
62     private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
63     private static final String INTERFACE = "interface";
64     private static final String REF_ATTR = "ref";
65     private static final String ID_ATTR = "id";
66     private static final String RPC_SERVICE = "rpc-service";
67     private static final String SPECIFIC_SERVICE_REF_LIST = "specific-reference-list";
68     private static final String STATIC_REFERENCE = "static-reference";
69
70     @SuppressWarnings("rawtypes")
71     @Override
72     public Set<Class> getManagedClasses() {
73         return Collections.emptySet();
74     }
75
76     @Override
77     public URL getSchemaLocation(String namespace) {
78         if(NAMESPACE_1_0_0.equals(namespace)) {
79             URL url = getClass().getResource("/opendaylight-blueprint-ext-1.0.0.xsd");
80             LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
81             return url;
82         }
83
84         return null;
85     }
86
87     @Override
88     public Metadata parse(Element element, ParserContext context) {
89         LOG.debug("In parse for {}", element);
90
91         if (nodeNameEquals(element, RpcImplementationBean.RPC_IMPLEMENTATION)) {
92             return parseRpcImplementation(element, context);
93         } else if (nodeNameEquals(element, RoutedRpcMetadata.ROUTED_RPC_IMPLEMENTATION)) {
94             return parseRoutedRpcImplementation(element, context);
95         } else if (nodeNameEquals(element, RPC_SERVICE)) {
96             return parseRpcService(element, context);
97         } else if (nodeNameEquals(element, NotificationListenerBean.NOTIFICATION_LISTENER)) {
98             return parseNotificationListener(element, context);
99         } else if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
100             return parseClusteredAppConfig(element, context);
101         } else if (nodeNameEquals(element, SPECIFIC_SERVICE_REF_LIST)) {
102             return parseSpecificReferenceList(element, context);
103         } else if (nodeNameEquals(element, STATIC_REFERENCE)) {
104             return parseStaticReference(element, context);
105         }
106
107         throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
108     }
109
110     @Override
111     public ComponentMetadata decorate(Node node, ComponentMetadata component, ParserContext context) {
112         if(node instanceof Attr) {
113             if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
114                 return decorateRestartDependentsOnUpdates((Attr)node, component, context);
115             } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
116                 return decorateUseDefaultForReferenceTypes((Attr)node, component, context);
117             } else if (nodeNameEquals(node, TYPE_ATTR)) {
118                 if(component instanceof ServiceReferenceMetadata) {
119                     return decorateServiceReferenceType((Attr)node, component, context);
120                 } else if(component instanceof ServiceMetadata) {
121                     return decorateServiceType((Attr)node, component, context);
122                 }
123
124                 throw new ComponentDefinitionException("Attribute " + node.getNodeName() +
125                         " can only be used on a <reference>, <reference-list> or <service> element");
126             }
127
128             throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
129         } else {
130             throw new ComponentDefinitionException("Unsupported node type: " + node);
131         }
132     }
133
134     private ComponentMetadata decorateServiceType(Attr attr, ComponentMetadata component, ParserContext context) {
135         if (!(component instanceof MutableServiceMetadata)) {
136             throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
137         }
138
139         MutableServiceMetadata service = (MutableServiceMetadata)component;
140
141         LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
142
143         service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
144         return component;
145     }
146
147     private ComponentMetadata decorateServiceReferenceType(Attr attr, ComponentMetadata component, ParserContext context) {
148         if (!(component instanceof MutableServiceReferenceMetadata)) {
149             throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
150         }
151
152         // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
153         // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
154         // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
155         // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
156         // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
157         // but as long as there's at least one processor registered, it correctly uses the extended filter.
158         registerComponentProcessor(context);
159
160         MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
161         String oldFilter = serviceRef.getExtendedFilter() == null ? null :
162             serviceRef.getExtendedFilter().getStringValue();
163
164         String filter;
165         if(Strings.isNullOrEmpty(oldFilter)) {
166             filter = String.format("(type=%s)", attr.getValue());
167         } else {
168             filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
169         }
170
171         LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
172                 serviceRef.getId(), attr.getValue(), oldFilter, filter);
173
174         serviceRef.setExtendedFilter(createValue(context, filter));
175         return component;
176     }
177
178     private static ComponentMetadata decorateRestartDependentsOnUpdates(Attr attr, ComponentMetadata component,
179             ParserContext context) {
180         return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
181     }
182
183     private static ComponentMetadata decorateUseDefaultForReferenceTypes(Attr attr, ComponentMetadata component,
184             ParserContext context) {
185         return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
186     }
187
188     private static ComponentMetadata enableComponentProcessorProperty(Attr attr, ComponentMetadata component,
189             ParserContext context, String propertyName) {
190         if(component != null) {
191             throw new ComponentDefinitionException("Attribute " + attr.getNodeName() +
192                     " can only be used on the root <blueprint> element");
193         }
194
195         LOG.debug("{}: {}", propertyName, attr.getValue());
196
197         if(!Boolean.parseBoolean(attr.getValue())) {
198             return component;
199         }
200
201         MutableBeanMetadata metadata = registerComponentProcessor(context);
202         metadata.addProperty(propertyName, createValue(context, "true"));
203
204         return component;
205     }
206
207     private static MutableBeanMetadata registerComponentProcessor(ParserContext context) {
208         ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
209         MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
210         if(metadata == null) {
211             metadata = context.createMetadata(MutableBeanMetadata.class);
212             metadata.setProcessor(true);
213             metadata.setId(COMPONENT_PROCESSOR_NAME);
214             metadata.setActivation(BeanMetadata.ACTIVATION_EAGER);
215             metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
216             metadata.setRuntimeClass(ComponentProcessor.class);
217             metadata.setDestroyMethod("destroy");
218             metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
219             metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
220                     BlueprintContainerRestartService.class, null));
221
222             LOG.debug("Registering ComponentProcessor bean: {}", metadata);
223
224             registry.registerComponentDefinition(metadata);
225         }
226
227         return metadata;
228     }
229
230     private Metadata parseRpcImplementation(Element element, ParserContext context) {
231         registerRpcRegistryServiceRefBean(context);
232
233         MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
234         metadata.setId(context.generateId());
235         metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
236         metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
237         metadata.setRuntimeClass(RpcImplementationBean.class);
238         metadata.setInitMethod("init");
239         metadata.setDestroyMethod("destroy");
240         metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
241         metadata.addProperty("rpcRegistry", createRef(context, RPC_REGISTRY_NAME));
242         metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
243
244         if(element.hasAttribute(INTERFACE)) {
245             metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
246         }
247
248         LOG.debug("parseAddRpcImplementation returning {}", metadata);
249
250         return metadata;
251     }
252
253     private Metadata parseRoutedRpcImplementation(Element element, ParserContext context) {
254         registerRpcRegistryServiceRefBean(context);
255         registerRoutedRpcRegistrationConverter(context);
256
257         ComponentFactoryMetadata metadata = new RoutedRpcMetadata(getId(context, element),
258                 element.getAttribute(INTERFACE), element.getAttribute(REF_ATTR));
259
260         LOG.debug("parseRoutedRpcImplementation returning {}", metadata);
261
262         return metadata;
263     }
264
265     private Metadata parseRpcService(Element element, ParserContext context) {
266         ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
267                 element.getAttribute(INTERFACE));
268
269         LOG.debug("parseRpcService returning {}", metadata);
270
271         return metadata;
272     }
273
274     private void registerRoutedRpcRegistrationConverter(ParserContext context) {
275         ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
276         if(registry.getComponentDefinition(ROUTED_RPC_REG_CONVERTER_NAME) == null) {
277             MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
278             metadata.setId(ROUTED_RPC_REG_CONVERTER_NAME);
279             metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
280             metadata.setActivation(ReferenceMetadata.ACTIVATION_LAZY);
281             metadata.setRuntimeClass(RoutedRpcRegistrationConverter.class);
282             registry.registerTypeConverter(metadata);
283         }
284     }
285
286     private void registerRpcRegistryServiceRefBean(ParserContext context) {
287         ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
288         if(registry.getComponentDefinition(RPC_REGISTRY_NAME) == null) {
289             MutableReferenceMetadata metadata = createServiceRef(context, RpcProviderRegistry.class, null);
290             metadata.setId(RPC_REGISTRY_NAME);
291             registry.registerComponentDefinition(metadata);
292         }
293     }
294
295     private Metadata parseNotificationListener(Element element, ParserContext context) {
296         registerNotificationServiceRefBean(context);
297
298         MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
299         metadata.setId(context.generateId());
300         metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
301         metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
302         metadata.setRuntimeClass(NotificationListenerBean.class);
303         metadata.setInitMethod("init");
304         metadata.setDestroyMethod("destroy");
305         metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
306         metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
307         metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
308
309         LOG.debug("parseNotificationListener returning {}", metadata);
310
311         return metadata;
312     }
313
314     private void registerNotificationServiceRefBean(ParserContext context) {
315         ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
316         if(registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
317             MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
318             metadata.setId(NOTIFICATION_SERVICE_NAME);
319             registry.registerComponentDefinition(metadata);
320         }
321     }
322
323     private Metadata parseClusteredAppConfig(Element element, ParserContext context) {
324         LOG.debug("parseClusteredAppConfig");
325
326         // Find the default-config child element representing the default app config XML, if present.
327         Element defaultConfigElement = null;
328         NodeList children = element.getChildNodes();
329         for(int i = 0; i < children.getLength(); i++) {
330             Node child = children.item(i);
331             if(nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
332                 defaultConfigElement = (Element) child;
333                 break;
334             }
335         }
336
337         Element defaultAppConfigElement = null;
338         if(defaultConfigElement != null) {
339             // Find the CDATA element containing the default app config XML.
340             children = defaultConfigElement.getChildNodes();
341             for(int i = 0; i < children.getLength(); i++) {
342                 Node child = children.item(i);
343                 if(child.getNodeType() == Node.CDATA_SECTION_NODE) {
344                     defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG, child.getTextContent());
345                     break;
346                 }
347             }
348         }
349
350         return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
351                 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
352                         DataStoreAppConfigMetadata.LIST_KEY_VALUE), defaultAppConfigElement);
353     }
354
355     private Metadata parseSpecificReferenceList(Element element, ParserContext context) {
356         ComponentFactoryMetadata metadata = new SpecificReferenceListMetadata(getId(context, element),
357                 element.getAttribute(INTERFACE));
358
359         LOG.debug("parseSpecificReferenceList returning {}", metadata);
360
361         return metadata;
362     }
363
364     private Metadata parseStaticReference(Element element, ParserContext context) {
365         ComponentFactoryMetadata metadata = new StaticReferenceMetadata(getId(context, element),
366                 element.getAttribute(INTERFACE));
367
368         LOG.debug("parseStaticReference returning {}", metadata);
369
370         return metadata;
371     }
372
373     private Element parseXML(String name, String xml) {
374         DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
375         builderFactory.setNamespaceAware(true);
376         builderFactory.setCoalescing(true);
377         builderFactory.setIgnoringElementContentWhitespace(true);
378         builderFactory.setIgnoringComments(true);
379
380         try {
381             return builderFactory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
382         } catch(Exception e) {
383             throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml));
384         }
385     }
386
387     private static ValueMetadata createValue(ParserContext context, String value) {
388         MutableValueMetadata m = context.createMetadata(MutableValueMetadata.class);
389         m.setStringValue(value);
390         return m;
391     }
392
393     private static MutableReferenceMetadata createServiceRef(ParserContext context, Class<?> cls, String filter) {
394         MutableReferenceMetadata m = context.createMetadata(MutableReferenceMetadata.class);
395         m.setRuntimeInterface(cls);
396         m.setInterface(cls.getName());
397         m.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
398         m.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
399
400         if(filter != null) {
401             m.setFilter(filter);
402         }
403
404         return m;
405     }
406
407     private static RefMetadata createRef(ParserContext context, String id) {
408         MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
409         metadata.setComponentId(id);
410         return metadata;
411     }
412
413     private static String getId(ParserContext context, Element element) {
414         if(element.hasAttribute(ID_ATTR)) {
415             return element.getAttribute(ID_ATTR);
416         } else {
417             return context.generateId();
418         }
419     }
420
421     private static boolean nodeNameEquals(Node node, String name) {
422         return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
423     }
424 }