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