Merge "Bug 451 - Fix netconf exception handling"
[controller.git] / opendaylight / netconf / config-netconf-connector / src / main / java / org / opendaylight / controller / netconf / confignetconfconnector / operations / runtimerpc / RuntimeRpc.java
1 /*
2  * Copyright (c) 2013 Cisco 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
9 package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Maps;
14 import org.opendaylight.controller.config.util.ConfigRegistryClient;
15 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
16 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
17 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
18 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
19 import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
20 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
21 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
22 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
23 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
24 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
25 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.InstanceRuntimeRpc;
26 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.ModuleRpcs;
27 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.Rpcs;
28 import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
29 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
30 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
31 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
32 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
33 import org.opendaylight.controller.netconf.util.xml.XmlElement;
34 import org.opendaylight.controller.netconf.util.xml.XmlNetconfConstants;
35 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.w3c.dom.Document;
39 import org.w3c.dom.Element;
40
41 import javax.management.ObjectName;
42 import javax.management.openmbean.OpenType;
43 import java.util.Map;
44
45 public class RuntimeRpc extends AbstractConfigNetconfOperation {
46
47     private static final Logger logger = LoggerFactory.getLogger(Commit.class);
48     public static final String CONTEXT_INSTANCE = "context-instance";
49
50     private final YangStoreSnapshot yangStoreSnapshot;
51
52     public RuntimeRpc(final YangStoreSnapshot yangStoreSnapshot, ConfigRegistryClient configRegistryClient,
53             String netconfSessionIdForReporting) {
54         super(configRegistryClient, netconfSessionIdForReporting);
55         this.yangStoreSnapshot = yangStoreSnapshot;
56     }
57
58     private Element toXml(Document doc, Object result, AttributeIfc returnType, String namespace, String elementName) throws NetconfDocumentedException {
59         AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper(null).prepareStrategy(returnType);
60         Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
61         Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, returnType.getOpenType());
62
63         // FIXME: multiple return values defined as leaf-list and list in yang should not be wrapped in output xml element,
64         // they need to be appended directly under rpc-reply element
65         //
66         // Either allow List of Elements to be returned from NetconfOperation or
67         // pass reference to parent output xml element for netconf operations to
68         // append result(s) on their own
69         Element tempParent = XmlUtil.createElement(doc, "output", Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
70         new ObjectXmlWriter().prepareWritingStrategy(elementName, returnType, doc).writeElement(tempParent, namespace, mappedAttributeOpt.get());
71
72         XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
73         return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
74     }
75
76     private Object executeOperation(final ConfigRegistryClient configRegistryClient, final ObjectName on,
77             final String name, final Map<String, AttributeConfigElement> attributes) {
78         final Object[] params = new Object[attributes.size()];
79         final String[] signature = new String[attributes.size()];
80
81         int i = 0;
82         for (final String attrName : attributes.keySet()) {
83             final AttributeConfigElement attribute = attributes.get(attrName);
84             final Optional<?> resolvedValueOpt = attribute.getResolvedValue();
85
86             params[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
87             signature[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName() : attribute
88                     .getResolvedDefaultValue().getClass().getName();
89             i++;
90         }
91
92         return configRegistryClient.invokeMethod(on, name, params, signature);
93     }
94
95     public NetconfOperationExecution fromXml(final XmlElement xml) throws NetconfDocumentedException {
96         final String namespace;
97         try {
98             namespace = xml.getNamespace();
99         } catch (MissingNameSpaceException e) {
100             logger.trace("Can't get namespace from xml element due to {}",e);
101             throw NetconfDocumentedException.wrap(e);
102         }
103         final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
104         final String operationName = xml.getName();
105
106         final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(
107                 contextInstanceElement.getTextContent(), operationName, namespace);
108
109         final Rpcs rpcs = mapRpcs(yangStoreSnapshot.getModuleMXBeanEntryMap());
110
111         final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
112         final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(), operationName);
113
114         // TODO move to Rpcs after xpath attribute is redesigned
115
116         final ObjectName on = id.getObjectName(rpcMapping);
117         Map<String, AttributeConfigElement> attributes = instanceRuntimeRpc.fromXml(xml);
118         attributes = sortAttributes(attributes, xml);
119
120         return new NetconfOperationExecution(on, instanceRuntimeRpc.getName(), attributes,
121                 instanceRuntimeRpc.getReturnType(), namespace);
122     }
123
124     @Override
125     public HandlingPriority canHandle(Document message) throws NetconfDocumentedException {
126         XmlElement requestElement = null;
127         requestElement = getRequestElementWithCheck(message);
128
129         XmlElement operationElement = requestElement.getOnlyChildElement();
130         final String netconfOperationName = operationElement.getName();
131         final String netconfOperationNamespace;
132         try {
133             netconfOperationNamespace = operationElement.getNamespace();
134         } catch (MissingNameSpaceException e) {
135             logger.debug("Cannot retrieve netconf operation namespace from message due to {}", e);
136             return HandlingPriority.CANNOT_HANDLE;
137         }
138
139         final Optional<XmlElement> contextInstanceElement = operationElement
140                 .getOnlyChildElementOptionally(CONTEXT_INSTANCE);
141
142         if (contextInstanceElement.isPresent() == false)
143             return HandlingPriority.CANNOT_HANDLE;
144
145         final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(contextInstanceElement.get()
146                 .getTextContent(), netconfOperationName, netconfOperationNamespace);
147
148         // TODO reuse rpcs instance in fromXml method
149         final Rpcs rpcs = mapRpcs(yangStoreSnapshot.getModuleMXBeanEntryMap());
150
151         try {
152
153             final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
154             final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(),
155                     netconfOperationName);
156             Preconditions.checkState(instanceRuntimeRpc != null, "No rpc found for %s:%s", netconfOperationNamespace,
157                     netconfOperationName);
158
159         } catch (IllegalStateException e) {
160             logger.debug("Cannot handle runtime operation {}:{}", netconfOperationNamespace, netconfOperationName, e);
161             return HandlingPriority.CANNOT_HANDLE;
162         }
163
164         return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
165     }
166
167     @Override
168     protected HandlingPriority canHandle(String netconfOperationName, String namespace) {
169         throw new UnsupportedOperationException(
170                 "This should not be used since it is not possible to provide check with these attributes");
171     }
172
173     @Override
174     protected String getOperationName() {
175         throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
176     }
177
178     @Override
179     protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
180         // TODO check for namespaces and unknown elements
181         final NetconfOperationExecution execution = fromXml(xml);
182
183         logger.debug("Invoking operation {} on {} with arguments {}", execution.operationName, execution.on,
184                 execution.attributes);
185         final Object result = executeOperation(configRegistryClient, execution.on, execution.operationName,
186                 execution.attributes);
187
188         logger.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.operationName,
189                 execution.on, execution.attributes, result);
190
191         if (execution.isVoid()) {
192             return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
193         } else {
194             return toXml(document, result, execution.returnType, execution.namespace,
195                     execution.returnType.getAttributeYangName());
196         }
197     }
198
199     private static class NetconfOperationExecution {
200
201         private final ObjectName on;
202         private final String operationName;
203         private final Map<String, AttributeConfigElement> attributes;
204         private final AttributeIfc returnType;
205         private final String namespace;
206
207         public NetconfOperationExecution(final ObjectName on, final String name,
208                 final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType, final String namespace) {
209             this.on = on;
210             this.operationName = name;
211             this.attributes = attributes;
212             this.returnType = returnType;
213             this.namespace = namespace;
214         }
215
216         boolean isVoid() {
217             return returnType == VoidAttribute.getInstance();
218         }
219
220     }
221
222     private static Map<String, AttributeConfigElement> sortAttributes(
223             final Map<String, AttributeConfigElement> attributes, final XmlElement xml) {
224         final Map<String, AttributeConfigElement> sorted = Maps.newLinkedHashMap();
225
226         for (XmlElement xmlElement : xml.getChildElements()) {
227             final String name = xmlElement.getName();
228             if (CONTEXT_INSTANCE.equals(name) == false) { // skip context
229                                                           // instance child node
230                                                           // because it
231                                                           // specifies
232                 // ObjectName
233                 final AttributeConfigElement value = attributes.get(name);
234                 if (value == null) {
235                     throw new IllegalArgumentException("Cannot find yang mapping for node " + xmlElement);
236                 }
237                 sorted.put(name, value);
238             }
239         }
240
241         return sorted;
242     }
243
244     private static Rpcs mapRpcs(final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries) {
245
246         final Map<String, Map<String, ModuleRpcs>> map = Maps.newHashMap();
247
248         for (final String namespace : mBeanEntries.keySet()) {
249
250             Map<String, ModuleRpcs> namespaceToModules = map.get(namespace);
251             if (namespaceToModules == null) {
252                 namespaceToModules = Maps.newHashMap();
253                 map.put(namespace, namespaceToModules);
254             }
255
256             for (final String moduleName : mBeanEntries.get(namespace).keySet()) {
257
258                 ModuleRpcs rpcMapping = namespaceToModules.get(moduleName);
259                 if (rpcMapping == null) {
260                     rpcMapping = new ModuleRpcs();
261                     namespaceToModules.put(moduleName, rpcMapping);
262                 }
263
264                 final ModuleMXBeanEntry entry = mBeanEntries.get(namespace).get(moduleName);
265
266                 for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
267                     rpcMapping.addNameMapping(runtimeEntry);
268                     for (final Rpc rpc : runtimeEntry.getRpcs()) {
269                         rpcMapping.addRpc(runtimeEntry, rpc);
270                     }
271                 }
272             }
273         }
274
275         return new Rpcs(map);
276     }
277
278 }