2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.controller.netconf.confignetconfconnector.operations.runtimerpc;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Maps;
15 import org.opendaylight.controller.config.util.ConfigRegistryClient;
16 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
17 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry;
18 import org.opendaylight.controller.config.yangjmxgenerator.RuntimeBeanEntry.Rpc;
19 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
20 import org.opendaylight.controller.config.yangjmxgenerator.attribute.VoidAttribute;
21 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
22 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
23 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
24 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.AttributeMappingStrategy;
25 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.mapping.ObjectMapper;
26 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.toxml.ObjectXmlWriter;
27 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.InstanceRuntimeRpc;
28 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.ModuleRpcs;
29 import org.opendaylight.controller.netconf.confignetconfconnector.mapping.rpc.Rpcs;
30 import org.opendaylight.controller.netconf.confignetconfconnector.operations.AbstractConfigNetconfOperation;
31 import org.opendaylight.controller.netconf.confignetconfconnector.operations.Commit;
32 import org.opendaylight.controller.netconf.confignetconfconnector.osgi.YangStoreSnapshot;
33 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
34 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
35 import org.opendaylight.controller.netconf.util.xml.XmlElement;
36 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39 import org.w3c.dom.Document;
40 import org.w3c.dom.Element;
42 import javax.management.ObjectName;
43 import javax.management.openmbean.OpenType;
47 public class RuntimeRpc extends AbstractConfigNetconfOperation {
49 private static final Logger logger = LoggerFactory.getLogger(Commit.class);
50 public static final String CONTEXT_INSTANCE = "context-instance";
52 private final YangStoreSnapshot yangStoreSnapshot;
54 public RuntimeRpc(final YangStoreSnapshot yangStoreSnapshot, ConfigRegistryClient configRegistryClient,
55 String netconfSessionIdForReporting) {
56 super(configRegistryClient, netconfSessionIdForReporting);
57 this.yangStoreSnapshot = yangStoreSnapshot;
60 private Element toXml(Document doc, Object result, AttributeIfc returnType, String namespace, String elementName) throws NetconfDocumentedException {
61 AttributeMappingStrategy<?, ? extends OpenType<?>> mappingStrategy = new ObjectMapper().prepareStrategy(returnType);
62 Optional<?> mappedAttributeOpt = mappingStrategy.mapAttribute(result);
63 Preconditions.checkState(mappedAttributeOpt.isPresent(), "Unable to map return value %s as %s", result, returnType.getOpenType());
65 // FIXME: multiple return values defined as leaf-list and list in yang should not be wrapped in output xml element,
66 // they need to be appended directly under rpc-reply element
68 // Either allow List of Elements to be returned from NetconfOperation or
69 // pass reference to parent output xml element for netconf operations to
70 // append result(s) on their own
71 Element tempParent = XmlUtil.createElement(doc, "output", Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
72 new ObjectXmlWriter().prepareWritingStrategy(elementName, returnType, doc).writeElement(tempParent, namespace, mappedAttributeOpt.get());
74 XmlElement xmlElement = XmlElement.fromDomElement(tempParent);
75 return xmlElement.getChildElements().size() > 1 ? tempParent : xmlElement.getOnlyChildElement().getDomElement();
78 private Object executeOperation(final ConfigRegistryClient configRegistryClient, final ObjectName on,
79 final String name, final Map<String, AttributeConfigElement> attributes) {
80 final Object[] params = new Object[attributes.size()];
81 final String[] signature = new String[attributes.size()];
84 for (final String attrName : attributes.keySet()) {
85 final AttributeConfigElement attribute = attributes.get(attrName);
86 final Optional<?> resolvedValueOpt = attribute.getResolvedValue();
88 params[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get() : attribute.getResolvedDefaultValue();
89 signature[i] = resolvedValueOpt.isPresent() ? resolvedValueOpt.get().getClass().getName() : attribute
90 .getResolvedDefaultValue().getClass().getName();
94 return configRegistryClient.invokeMethod(on, name, params, signature);
97 public NetconfOperationExecution fromXml(final XmlElement xml) throws NetconfDocumentedException {
98 final String namespace;
100 namespace = xml.getNamespace();
101 } catch (MissingNameSpaceException e) {
102 logger.trace("Can't get namespace from xml element due to {}",e);
103 throw NetconfDocumentedException.wrap(e);
105 final XmlElement contextInstanceElement = xml.getOnlyChildElement(CONTEXT_INSTANCE);
106 final String operationName = xml.getName();
108 final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(
109 contextInstanceElement.getTextContent(), operationName, namespace);
111 final Rpcs rpcs = mapRpcs(yangStoreSnapshot.getModuleMXBeanEntryMap());
113 final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
114 final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(), operationName);
116 // TODO move to Rpcs after xpath attribute is redesigned
118 final ObjectName on = id.getObjectName(rpcMapping);
119 Map<String, AttributeConfigElement> attributes = instanceRuntimeRpc.fromXml(xml);
120 attributes = sortAttributes(attributes, xml);
122 return new NetconfOperationExecution(on, instanceRuntimeRpc.getName(), attributes,
123 instanceRuntimeRpc.getReturnType(), namespace);
127 public HandlingPriority canHandle(Document message) throws NetconfDocumentedException {
128 XmlElement requestElement = null;
129 requestElement = getRequestElementWithCheck(message);
131 XmlElement operationElement = requestElement.getOnlyChildElement();
132 final String netconfOperationName = operationElement.getName();
133 final String netconfOperationNamespace;
135 netconfOperationNamespace = operationElement.getNamespace();
136 } catch (MissingNameSpaceException e) {
137 logger.debug("Cannot retrieve netconf operation namespace from message due to {}", e);
138 return HandlingPriority.CANNOT_HANDLE;
141 final Optional<XmlElement> contextInstanceElement = operationElement
142 .getOnlyChildElementOptionally(CONTEXT_INSTANCE);
144 if (!contextInstanceElement.isPresent()){
145 return HandlingPriority.CANNOT_HANDLE;
148 final RuntimeRpcElementResolved id = RuntimeRpcElementResolved.fromXpath(contextInstanceElement.get()
149 .getTextContent(), netconfOperationName, netconfOperationNamespace);
151 // TODO reuse rpcs instance in fromXml method
152 final Rpcs rpcs = mapRpcs(yangStoreSnapshot.getModuleMXBeanEntryMap());
156 final ModuleRpcs rpcMapping = rpcs.getRpcMapping(id);
157 final InstanceRuntimeRpc instanceRuntimeRpc = rpcMapping.getRpc(id.getRuntimeBeanName(),
158 netconfOperationName);
159 Preconditions.checkState(instanceRuntimeRpc != null, "No rpc found for %s:%s", netconfOperationNamespace,
160 netconfOperationName);
162 } catch (IllegalStateException e) {
163 logger.debug("Cannot handle runtime operation {}:{}", netconfOperationNamespace, netconfOperationName, e);
164 return HandlingPriority.CANNOT_HANDLE;
167 return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY;
171 protected HandlingPriority canHandle(String netconfOperationName, String namespace) {
172 throw new UnsupportedOperationException(
173 "This should not be used since it is not possible to provide check with these attributes");
177 protected String getOperationName() {
178 throw new UnsupportedOperationException("Runtime rpc does not have a stable name");
182 protected Element handleWithNoSubsequentOperations(Document document, XmlElement xml) throws NetconfDocumentedException {
183 // TODO check for namespaces and unknown elements
184 final NetconfOperationExecution execution = fromXml(xml);
186 logger.debug("Invoking operation {} on {} with arguments {}", execution.operationName, execution.on,
187 execution.attributes);
188 final Object result = executeOperation(getConfigRegistryClient(), execution.on, execution.operationName,
189 execution.attributes);
191 logger.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.operationName,
192 execution.on, execution.attributes, result);
194 if (execution.isVoid()) {
195 return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
197 return toXml(document, result, execution.returnType, execution.namespace,
198 execution.returnType.getAttributeYangName());
202 private static class NetconfOperationExecution {
204 private final ObjectName on;
205 private final String operationName;
206 private final Map<String, AttributeConfigElement> attributes;
207 private final AttributeIfc returnType;
208 private final String namespace;
210 public NetconfOperationExecution(final ObjectName on, final String name,
211 final Map<String, AttributeConfigElement> attributes, final AttributeIfc returnType, final String namespace) {
213 this.operationName = name;
214 this.attributes = attributes;
215 this.returnType = returnType;
216 this.namespace = namespace;
220 return returnType == VoidAttribute.getInstance();
225 private static Map<String, AttributeConfigElement> sortAttributes(
226 final Map<String, AttributeConfigElement> attributes, final XmlElement xml) {
227 final Map<String, AttributeConfigElement> sorted = Maps.newLinkedHashMap();
229 for (XmlElement xmlElement : xml.getChildElements()) {
230 final String name = xmlElement.getName();
231 if (!CONTEXT_INSTANCE.equals(name)) { // skip context
232 // instance child node
236 final AttributeConfigElement value = attributes.get(name);
238 throw new IllegalArgumentException("Cannot find yang mapping for node " + xmlElement);
240 sorted.put(name, value);
247 private static Rpcs mapRpcs(final Map<String, Map<String, ModuleMXBeanEntry>> mBeanEntries) {
249 final Map<String, Map<String, ModuleRpcs>> map = Maps.newHashMap();
251 for (final String namespace : mBeanEntries.keySet()) {
253 Map<String, ModuleRpcs> namespaceToModules = map.get(namespace);
254 if (namespaceToModules == null) {
255 namespaceToModules = Maps.newHashMap();
256 map.put(namespace, namespaceToModules);
259 for (final String moduleName : mBeanEntries.get(namespace).keySet()) {
261 ModuleRpcs rpcMapping = namespaceToModules.get(moduleName);
262 if (rpcMapping == null) {
263 rpcMapping = new ModuleRpcs();
264 namespaceToModules.put(moduleName, rpcMapping);
267 final ModuleMXBeanEntry entry = mBeanEntries.get(namespace).get(moduleName);
269 for (final RuntimeBeanEntry runtimeEntry : entry.getRuntimeBeans()) {
270 rpcMapping.addNameMapping(runtimeEntry);
271 for (final Rpc rpc : runtimeEntry.getRpcs()) {
272 rpcMapping.addRpc(runtimeEntry, rpc);
278 return new Rpcs(map);