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