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