Fix namespace handling
[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.mutable.MutableBeanMetadata;
20 import org.apache.aries.blueprint.mutable.MutableRefMetadata;
21 import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
22 import org.apache.aries.blueprint.mutable.MutableServiceMetadata;
23 import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
24 import org.apache.aries.blueprint.mutable.MutableValueMetadata;
25 import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
26 import org.opendaylight.yangtools.util.xml.UntrustedXML;
27 import org.osgi.service.blueprint.container.ComponentDefinitionException;
28 import org.osgi.service.blueprint.reflect.BeanMetadata;
29 import org.osgi.service.blueprint.reflect.ComponentMetadata;
30 import org.osgi.service.blueprint.reflect.Metadata;
31 import org.osgi.service.blueprint.reflect.RefMetadata;
32 import org.osgi.service.blueprint.reflect.ReferenceMetadata;
33 import org.osgi.service.blueprint.reflect.ServiceMetadata;
34 import org.osgi.service.blueprint.reflect.ServiceReferenceMetadata;
35 import org.osgi.service.blueprint.reflect.ValueMetadata;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Attr;
39 import org.w3c.dom.Element;
40 import org.w3c.dom.Node;
41 import org.w3c.dom.NodeList;
42 import org.xml.sax.InputSource;
43 import org.xml.sax.SAXException;
44
45 /**
46  * The NamespaceHandler for Opendaylight blueprint extensions.
47  *
48  * @author Thomas Pantelis
49  */
50 public final class OpendaylightNamespaceHandler implements NamespaceHandler {
51     public static final String NAMESPACE_2_0_0 = "http://opendaylight.org/xmlns/blueprint/v2.0.0";
52     static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
53     static final String DOM_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.DOMRpcProviderService";
54     static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
55     static final String BINDING_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.RpcProviderService";
56     static final String SCHEMA_SERVICE_NAME = "org.opendaylight.blueprint.SchemaService";
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 ID_ATTR = "id";
67
68     @SuppressWarnings("rawtypes")
69     @Override
70     public Set<Class> getManagedClasses() {
71         return Collections.emptySet();
72     }
73
74     @Override
75     public URL getSchemaLocation(final String namespace) {
76         if (NAMESPACE_2_0_0.equals(namespace)) {
77             URL url = getClass().getResource("/opendaylight-blueprint-ext-2.0.0.xsd");
78             LOG.debug("getSchemaLocation for {} returning URL {}", namespace, url);
79             return url;
80         }
81
82         return null;
83     }
84
85     @Override
86     public Metadata parse(final Element element, final ParserContext context) {
87         LOG.debug("In parse for {}", element);
88
89         if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
90             return parseClusteredAppConfig(element, context);
91         }
92
93         throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
94     }
95
96     @Override
97     public ComponentMetadata decorate(final Node node, final ComponentMetadata component, final ParserContext context) {
98         if (node instanceof Attr) {
99             if (nodeNameEquals(node, RESTART_DEPENDENTS_ON_UPDATES)) {
100                 return decorateRestartDependentsOnUpdates((Attr) node, component, context);
101             } else if (nodeNameEquals(node, USE_DEFAULT_FOR_REFERENCE_TYPES)) {
102                 return decorateUseDefaultForReferenceTypes((Attr) node, component, context);
103             } else if (nodeNameEquals(node, TYPE_ATTR)) {
104                 if (component instanceof ServiceReferenceMetadata) {
105                     return decorateServiceReferenceType((Attr) node, component, context);
106                 } else if (component instanceof ServiceMetadata) {
107                     return decorateServiceType((Attr)node, component, context);
108                 }
109
110                 throw new ComponentDefinitionException("Attribute " + node.getNodeName()
111                         + " can only be used on a <reference>, <reference-list> or <service> element");
112             }
113
114             throw new ComponentDefinitionException("Unsupported attribute: " + node.getNodeName());
115         } else {
116             throw new ComponentDefinitionException("Unsupported node type: " + node);
117         }
118     }
119
120     private static ComponentMetadata decorateServiceType(final Attr attr, final ComponentMetadata component,
121             final ParserContext context) {
122         if (!(component instanceof MutableServiceMetadata service)) {
123             throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
124         }
125
126         LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
127
128         service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
129         return component;
130     }
131
132     private static ComponentMetadata decorateServiceReferenceType(final Attr attr, final ComponentMetadata component,
133             final ParserContext context) {
134         if (!(component instanceof MutableServiceReferenceMetadata)) {
135             throw new ComponentDefinitionException("Expected an instanceof MutableServiceReferenceMetadata");
136         }
137
138         // We don't actually need the ComponentProcessor for augmenting the OSGi filter here but we create it
139         // to workaround an issue in Aries where it doesn't use the extended filter unless there's a
140         // Processor or ComponentDefinitionRegistryProcessor registered. This may actually be working as
141         // designed in Aries b/c the extended filter was really added to allow the OSGi filter to be
142         // substituted by a variable via the "cm:property-placeholder" processor. If so, it's a bit funky
143         // but as long as there's at least one processor registered, it correctly uses the extended filter.
144         registerComponentProcessor(context);
145
146         MutableServiceReferenceMetadata serviceRef = (MutableServiceReferenceMetadata)component;
147         String oldFilter = serviceRef.getExtendedFilter() == null ? null :
148             serviceRef.getExtendedFilter().getStringValue();
149
150         String filter;
151         if (Strings.isNullOrEmpty(oldFilter)) {
152             filter = String.format("(type=%s)", attr.getValue());
153         } else {
154             filter = String.format("(&(%s)(type=%s))", oldFilter, attr.getValue());
155         }
156
157         LOG.debug("decorateServiceReferenceType for {} with type {}, old filter: {}, new filter: {}",
158                 serviceRef.getId(), attr.getValue(), oldFilter, filter);
159
160         serviceRef.setExtendedFilter(createValue(context, filter));
161         return component;
162     }
163
164     private static ComponentMetadata decorateRestartDependentsOnUpdates(final Attr attr,
165             final ComponentMetadata component, final ParserContext context) {
166         return enableComponentProcessorProperty(attr, component, context, "restartDependentsOnUpdates");
167     }
168
169     private static ComponentMetadata decorateUseDefaultForReferenceTypes(final Attr attr,
170             final ComponentMetadata component, final ParserContext context) {
171         return enableComponentProcessorProperty(attr, component, context, "useDefaultForReferenceTypes");
172     }
173
174     private static ComponentMetadata enableComponentProcessorProperty(final Attr attr,
175             final ComponentMetadata component, final ParserContext context, final String propertyName) {
176         if (component != null) {
177             throw new ComponentDefinitionException("Attribute " + attr.getNodeName()
178                     + " can only be used on the root <blueprint> element");
179         }
180
181         LOG.debug("Property {} = {}", propertyName, attr.getValue());
182
183         if (!Boolean.parseBoolean(attr.getValue())) {
184             return component;
185         }
186
187         MutableBeanMetadata metadata = registerComponentProcessor(context);
188         metadata.addProperty(propertyName, createValue(context, "true"));
189
190         return component;
191     }
192
193     private static MutableBeanMetadata registerComponentProcessor(final ParserContext context) {
194         ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
195         MutableBeanMetadata metadata = (MutableBeanMetadata) registry.getComponentDefinition(COMPONENT_PROCESSOR_NAME);
196         if (metadata == null) {
197             metadata = createBeanMetadata(context, COMPONENT_PROCESSOR_NAME, ComponentProcessor.class, false, true);
198             metadata.setProcessor(true);
199             addBlueprintBundleRefProperty(context, metadata);
200             metadata.addProperty("blueprintContainerRestartService", createServiceRef(context,
201                     BlueprintContainerRestartService.class, null));
202
203             LOG.debug("Registering ComponentProcessor bean: {}", metadata);
204
205             registry.registerComponentDefinition(metadata);
206         }
207
208         return metadata;
209     }
210
211     private static Metadata parseClusteredAppConfig(final Element element, final ParserContext context) {
212         LOG.debug("parseClusteredAppConfig");
213
214         // Find the default-config child element representing the default app config XML, if present.
215         Element defaultConfigElement = null;
216         NodeList children = element.getChildNodes();
217         for (int i = 0; i < children.getLength(); i++) {
218             Node child = children.item(i);
219             if (nodeNameEquals(child, DataStoreAppConfigMetadata.DEFAULT_CONFIG)) {
220                 defaultConfigElement = (Element) child;
221                 break;
222             }
223         }
224
225         Element defaultAppConfigElement = null;
226         if (defaultConfigElement != null) {
227             // Find the CDATA element containing the default app config XML.
228             children = defaultConfigElement.getChildNodes();
229             for (int i = 0; i < children.getLength(); i++) {
230                 Node child = children.item(i);
231                 if (child.getNodeType() == Node.CDATA_SECTION_NODE) {
232                     defaultAppConfigElement = parseXML(DataStoreAppConfigMetadata.DEFAULT_CONFIG,
233                             child.getTextContent());
234                     break;
235                 }
236             }
237         }
238
239         return new DataStoreAppConfigMetadata(getId(context, element), element.getAttribute(
240                 DataStoreAppConfigMetadata.BINDING_CLASS), element.getAttribute(
241                         DataStoreAppConfigMetadata.LIST_KEY_VALUE), element.getAttribute(
242                         DataStoreAppConfigMetadata.DEFAULT_CONFIG_FILE_NAME), parseUpdateStrategy(
243                         element.getAttribute(UPDATE_STRATEGY_ATTR)), defaultAppConfigElement);
244     }
245
246     private static UpdateStrategy parseUpdateStrategy(final String updateStrategyValue) {
247         if (Strings.isNullOrEmpty(updateStrategyValue)
248                 || updateStrategyValue.equalsIgnoreCase(UpdateStrategy.RELOAD.name())) {
249             return UpdateStrategy.RELOAD;
250         } else if (updateStrategyValue.equalsIgnoreCase(UpdateStrategy.NONE.name())) {
251             return UpdateStrategy.NONE;
252         } else {
253             LOG.warn("update-strategy {} not supported, using reload", updateStrategyValue);
254             return UpdateStrategy.RELOAD;
255         }
256     }
257
258     private static Element parseXML(final String name, final String xml) {
259         try {
260             return UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
261         } catch (SAXException | IOException e) {
262             throw new ComponentDefinitionException(String.format("Error %s parsing XML: %s", name, xml), e);
263         }
264     }
265
266     private static ValueMetadata createValue(final ParserContext context, final String value) {
267         MutableValueMetadata metadata = context.createMetadata(MutableValueMetadata.class);
268         metadata.setStringValue(value);
269         return metadata;
270     }
271
272     private static MutableReferenceMetadata createServiceRef(final ParserContext context, final Class<?> cls,
273             final String filter) {
274         MutableReferenceMetadata metadata = context.createMetadata(MutableReferenceMetadata.class);
275         metadata.setRuntimeInterface(cls);
276         metadata.setInterface(cls.getName());
277         metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
278         metadata.setAvailability(ReferenceMetadata.AVAILABILITY_MANDATORY);
279
280         if (filter != null) {
281             metadata.setFilter(filter);
282         }
283
284         return metadata;
285     }
286
287     private static RefMetadata createRef(final ParserContext context, final String id) {
288         MutableRefMetadata metadata = context.createMetadata(MutableRefMetadata.class);
289         metadata.setComponentId(id);
290         return metadata;
291     }
292
293     private static String getId(final ParserContext context, final Element element) {
294         if (element.hasAttribute(ID_ATTR)) {
295             return element.getAttribute(ID_ATTR);
296         } else {
297             return context.generateId();
298         }
299     }
300
301     private static boolean nodeNameEquals(final Node node, final String name) {
302         return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
303     }
304
305     private static void addBlueprintBundleRefProperty(final ParserContext context, final MutableBeanMetadata metadata) {
306         metadata.addProperty("bundle", createRef(context, "blueprintBundle"));
307     }
308
309     private static MutableBeanMetadata createBeanMetadata(final ParserContext context, final String id,
310             final Class<?> runtimeClass, final boolean initMethod, final boolean destroyMethod) {
311         MutableBeanMetadata metadata = context.createMetadata(MutableBeanMetadata.class);
312         metadata.setId(id);
313         metadata.setScope(BeanMetadata.SCOPE_SINGLETON);
314         metadata.setActivation(ReferenceMetadata.ACTIVATION_EAGER);
315         metadata.setRuntimeClass(runtimeClass);
316
317         if (initMethod) {
318             metadata.setInitMethod("init");
319         }
320
321         if (destroyMethod) {
322             metadata.setDestroyMethod("destroy");
323         }
324
325         return metadata;
326     }
327 }