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