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