3e729149eb99a485c3026cbd7868304c1a20d057
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / NetconfMapping.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.sal.connect.netconf;
9
10 import java.net.URI;
11 import java.util.ArrayList;
12 import java.util.Collections;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Set;
16 import java.util.concurrent.atomic.AtomicInteger;
17
18 import javax.activation.UnsupportedDataTypeException;
19 import javax.annotation.Nullable;
20
21 import org.opendaylight.controller.netconf.api.NetconfMessage;
22 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
23 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
24 import org.opendaylight.controller.sal.common.util.Rpcs;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.RpcError;
27 import org.opendaylight.yangtools.yang.common.RpcResult;
28 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
29 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
32 import org.opendaylight.yangtools.yang.data.api.Node;
33 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
34 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
35 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
36 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
37 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
38 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.w3c.dom.Document;
42 import org.w3c.dom.Element;
43
44 import com.google.common.base.Optional;
45 import com.google.common.base.Preconditions;
46 import com.google.common.base.Predicate;
47 import com.google.common.collect.Collections2;
48 import com.google.common.collect.ImmutableList;
49 import com.google.common.collect.Iterables;
50 import com.google.common.collect.Lists;
51
52 public class NetconfMapping {
53
54     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
55     public static String NETCONF_MONITORING_URI = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
56     public static URI NETCONF_NOTIFICATION_URI = URI.create("urn:ietf:params:xml:ns:netconf:notification:1.0");
57     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI.create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
58
59     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
60     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
61     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
62     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
63     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
64     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
65     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
66     public static QName NETCONF_DELETE_CONFIG_QNAME = QName.create(NETCONF_QNAME, "delete-config");
67     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
68     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
69
70     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
71     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
72     public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
73
74     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
75     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
76
77     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
78     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
79
80     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
81     public static QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
82     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
83     public static QName NETCONF_CREATE_SUBSCRIPTION_QNAME = QName.create(NETCONF_NOTIFICATION_URI, null,
84             "create-subscription");
85     public static QName NETCONF_CANCEL_SUBSCRIPTION_QNAME = QName.create(NETCONF_NOTIFICATION_URI, null,
86             "cancel-subscription");
87     public static QName IETF_NETCONF_MONITORING_MODULE = QName.create(NETCONF_MONITORING_URI, "2010-10-04",
88             "ietf-netconf-monitoring");
89
90     static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl(NETCONF_RUNNING_QNAME,
91             null, null));
92
93     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
94
95     static AtomicInteger messageId = new AtomicInteger(0);
96
97     static Node<?> toFilterStructure(InstanceIdentifier identifier) {
98         Node<?> previous = null;
99         if (identifier.getPath().isEmpty()) {
100             return null;
101         }
102
103         for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument component : Lists
104                 .reverse(identifier.getPath())) {
105             previous = toNode(component, previous);
106         }
107         return filter("subtree", previous);
108     }
109
110     static Node<?> toNode(NodeIdentifierWithPredicates argument, Node<?> node) {
111         List<Node<?>> list = new ArrayList<>();
112         for (Map.Entry<QName, Object> arg : argument.getKeyValues().entrySet()) {
113             list.add(new SimpleNodeTOImpl(arg.getKey(), null, arg.getValue()));
114         }
115         if (node != null) {
116             list.add(node);
117         }
118         return new CompositeNodeTOImpl(argument.getNodeType(), null, list);
119     }
120
121     static Node<?> toNode(PathArgument argument, Node<?> node) {
122         if (node != null) {
123             return new CompositeNodeTOImpl(argument.getNodeType(), null, Collections.<Node<?>> singletonList(node));
124         } else {
125             return new SimpleNodeTOImpl(argument.getNodeType(), null, null);
126         }
127     }
128
129     static CompositeNode toCompositeNode(NetconfMessage message, Optional<SchemaContext> ctx) {
130         // TODO: implement general normalization to normalize incoming Netconf
131         // Message
132         // for Schema Context counterpart
133         return null;
134     }
135
136     static CompositeNode toNotificationNode(NetconfMessage message, Optional<SchemaContext> ctx) {
137         if (ctx.isPresent()) {
138             SchemaContext schemaContext = ctx.get();
139             Set<NotificationDefinition> notifications = schemaContext.getNotifications();
140             Document document = message.getDocument();
141             return XmlDocumentUtils.notificationToDomNodes(document, Optional.fromNullable(notifications));
142         }
143         return null;
144     }
145
146     static NetconfMessage toRpcMessage(QName rpc, CompositeNode node, Optional<SchemaContext> ctx) {
147         CompositeNodeTOImpl rpcPayload = wrap(NETCONF_RPC_QNAME, flattenInput(node));
148         Document w3cPayload = null;
149         try {
150             w3cPayload = XmlDocumentUtils.toDocument(rpcPayload, XmlDocumentUtils.defaultValueCodecProvider());
151         } catch (UnsupportedDataTypeException e) {
152             throw new IllegalArgumentException("Unable to create message", e);
153         }
154         w3cPayload.getDocumentElement().setAttribute("message-id", "m-" + messageId.getAndIncrement());
155         return new NetconfMessage(w3cPayload);
156     }
157
158     static CompositeNode flattenInput(final CompositeNode node) {
159         final QName inputQName = QName.create(node.getNodeType(), "input");
160         CompositeNode input = node.getFirstCompositeByName(inputQName);
161         if (input == null)
162             return node;
163         if (input instanceof CompositeNode) {
164
165             List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
166                     .addAll(input.getChildren()) //
167                     .addAll(Collections2.filter(node.getChildren(), new Predicate<Node<?>>() {
168                         @Override
169                         public boolean apply(@Nullable final Node<?> input) {
170                             return input.getNodeType() != inputQName;
171                         }
172                     })) //
173                     .build();
174
175             return ImmutableCompositeNode.create(node.getNodeType(), nodes);
176         }
177
178         return input;
179     }
180
181     static RpcResult<CompositeNode> toRpcResult(NetconfMessage message, final QName rpc, Optional<SchemaContext> context) {
182         CompositeNode rawRpc;
183         if (context.isPresent())
184             if (isDataRetrieQNameReply(rpc)) {
185
186                 Element xmlData = getDataSubtree(message.getDocument());
187
188                 List<org.opendaylight.yangtools.yang.data.api.Node<?>> dataNodes = XmlDocumentUtils.toDomNodes(xmlData,
189                         Optional.of(context.get().getDataDefinitions()));
190
191                 CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder();
192                 it.setQName(NETCONF_RPC_REPLY_QNAME);
193                 it.add(ImmutableCompositeNode.create(NETCONF_DATA_QNAME, dataNodes));
194
195                 rawRpc = it.toInstance();
196                 // sys(xmlData)
197             } else {
198                 RpcDefinition rpcSchema = Iterables.find(context.get().getOperations(), new Predicate<RpcDefinition>() {
199                     @Override
200                     public boolean apply(final RpcDefinition input) {
201                         return rpc == input.getQName();
202                     }
203                 });
204                 rawRpc = (CompositeNode) toCompositeNode(message.getDocument());
205             }
206         else {
207             rawRpc = (CompositeNode) toCompositeNode(message.getDocument());
208         }
209         // rawRpc.
210         return Rpcs.getRpcResult(true, rawRpc, Collections.<RpcError> emptySet());
211     }
212
213     static Element getDataSubtree(Document doc) {
214         return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
215     }
216
217     static boolean isDataRetrieQNameReply(QName it) {
218         return NETCONF_URI == it.getNamespace()
219                 && (it.getLocalName() == NETCONF_GET_CONFIG_QNAME.getLocalName() || it.getLocalName() == NETCONF_GET_QNAME
220                         .getLocalName());
221     }
222
223     static CompositeNodeTOImpl wrap(QName name, Node<?> node) {
224         if (node != null) {
225             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> singletonList(node));
226         } else {
227             return new CompositeNodeTOImpl(name, null, Collections.<Node<?>> emptyList());
228         }
229     }
230
231     static CompositeNodeTOImpl wrap(QName name, Node<?> additional, Node<?> node) {
232         if (node != null) {
233             return new CompositeNodeTOImpl(name, null, ImmutableList.of(additional, node));
234         } else {
235             return new CompositeNodeTOImpl(name, null, ImmutableList.<Node<?>> of(additional));
236         }
237     }
238
239     static ImmutableCompositeNode filter(String type, Node<?> node) {
240         CompositeNodeBuilder<ImmutableCompositeNode> it = ImmutableCompositeNode.builder(); //
241         it.setQName(NETCONF_FILTER_QNAME);
242         it.setAttribute(NETCONF_TYPE_QNAME, type);
243         if (node != null) {
244             return it.add(node).toInstance();
245         } else {
246             return it.toInstance();
247         }
248     }
249
250     public static Node<?> toCompositeNode(Document document) {
251         return XmlDocumentUtils.toDomNode(document);
252     }
253
254     public static void checkValidReply(NetconfMessage input, NetconfMessage output) {
255         String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
256         String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
257
258         if(inputMsgId.equals(outputMsgId) == false) {
259             String requestXml = XmlUtil.toString(input.getDocument());
260             String responseXml = XmlUtil.toString(output.getDocument());
261             throw new IllegalStateException(String.format("Rpc request and reply message IDs must be same. Request: %s, response: %s", requestXml, responseXml));
262         }
263     }
264
265     public static void checkSuccessReply(NetconfMessage output) {
266         if(NetconfMessageUtil.isErrorMessage(output)) {
267             throw new IllegalStateException(String.format("Response contains error: %s", XmlUtil.toString(output.getDocument())));
268         }
269     }
270 }