2 * Copyright (c) 2014 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
8 package org.opendaylight.controller.sal.connect.netconf.util;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.Iterables;
14 import com.google.common.collect.Lists;
15 import com.google.common.collect.Sets;
17 import java.util.Collections;
19 import java.util.Map.Entry;
20 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
21 import org.opendaylight.controller.netconf.api.NetconfMessage;
22 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.edit.config.input.EditContent;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.CreateSubscriptionInput;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.monitoring.rev101004.NetconfState;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.NetconfCapabilityChange;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.common.RpcError;
29 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
30 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
31 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
37 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.w3c.dom.Document;
46 import org.w3c.dom.Element;
48 public class NetconfMessageTransformUtil {
50 public static final String MESSAGE_ID_ATTR = "message-id";
51 public static final QName CREATE_SUBSCRIPTION_RPC_QNAME = QName.cachedReference(QName.create(CreateSubscriptionInput.QNAME, "create-subscription"));
52 private static final String SUBTREE = "subtree";
54 private NetconfMessageTransformUtil() {}
56 public static final QName IETF_NETCONF_MONITORING = QName.create(NetconfState.QNAME, "ietf-netconf-monitoring");
57 public static final QName GET_DATA_QNAME = QName.create(IETF_NETCONF_MONITORING, "data");
58 public static final QName GET_SCHEMA_QNAME = QName.create(IETF_NETCONF_MONITORING, "get-schema");
59 public static final QName IETF_NETCONF_MONITORING_SCHEMA_FORMAT = QName.create(IETF_NETCONF_MONITORING, "format");
60 public static final QName IETF_NETCONF_MONITORING_SCHEMA_LOCATION = QName.create(IETF_NETCONF_MONITORING, "location");
61 public static final QName IETF_NETCONF_MONITORING_SCHEMA_IDENTIFIER = QName.create(IETF_NETCONF_MONITORING, "identifier");
62 public static final QName IETF_NETCONF_MONITORING_SCHEMA_VERSION = QName.create(IETF_NETCONF_MONITORING, "version");
63 public static final QName IETF_NETCONF_MONITORING_SCHEMA_NAMESPACE = QName.create(IETF_NETCONF_MONITORING, "namespace");
65 public static final QName IETF_NETCONF_NOTIFICATIONS = QName.create(NetconfCapabilityChange.QNAME, "ietf-netconf-notifications");
67 public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
68 public static QName NETCONF_QNAME = QName.create(NETCONF_URI.toString(), "2011-06-01", "netconf");
69 public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
70 public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
71 public static QName NETCONF_OK_QNAME = QName.create(NETCONF_QNAME, "ok");
72 public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
73 public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
74 public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
75 public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
76 public static QName NETCONF_TARGET_QNAME = QName.create(NETCONF_QNAME, "target");
77 public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
78 public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
79 public static QName NETCONF_VALIDATE_QNAME = QName.create(NETCONF_QNAME, "validate");
80 public static QName NETCONF_COPY_CONFIG_QNAME = QName.create(NETCONF_QNAME, "copy-config");
81 public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
82 public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
83 public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
84 public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
85 public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
86 public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
87 public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
88 public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
89 public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
91 public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
92 .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
93 public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
95 public static URI NETCONF_CANDIDATE_URI = URI
96 .create("urn:ietf:params:netconf:capability:candidate:1.0");
98 public static URI NETCONF_NOTIFICATONS_URI = URI
99 .create("urn:ietf:params:netconf:capability:notification:1.0");
101 public static URI NETCONF_RUNNING_WRITABLE_URI = URI
102 .create("urn:ietf:params:netconf:capability:writable-running:1.0");
104 public static QName NETCONF_LOCK_QNAME = QName.create(NETCONF_QNAME, "lock");
105 public static QName NETCONF_UNLOCK_QNAME = QName.create(NETCONF_QNAME, "unlock");
107 // Discard changes message
108 public static final ContainerNode DISCARD_CHANGES_RPC_CONTENT =
109 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_DISCARD_CHANGES_QNAME)).build();
111 // Commit changes message
112 public static final ContainerNode COMMIT_RPC_CONTENT =
113 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_COMMIT_QNAME)).build();
116 public static final ContainerNode GET_RPC_CONTENT =
117 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(NETCONF_GET_QNAME)).build();
119 // Create-subscription changes message
120 public static final ContainerNode CREATE_SUBSCRIPTION_RPC_CONTENT =
121 Builders.containerBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CREATE_SUBSCRIPTION_RPC_QNAME)).build();
123 public static DataContainerChild<?, ?> toFilterStructure(final YangInstanceIdentifier identifier, final SchemaContext ctx) {
124 final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> filterBuilder = Builders.containerBuilder().withNodeIdentifier(toId(NETCONF_FILTER_QNAME));
125 filterBuilder.withAttributes(Collections.singletonMap(NETCONF_TYPE_QNAME, SUBTREE));
127 if (Iterables.isEmpty(identifier.getPathArguments()) == false) {
128 filterBuilder.withChild((DataContainerChild<?, ?>) InstanceIdToNodes.serialize(ctx, identifier));
130 return filterBuilder.build();
133 public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
134 throws NetconfDocumentedException {
135 final String inputMsgId = input.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
136 final String outputMsgId = output.getDocument().getDocumentElement().getAttribute(MESSAGE_ID_ATTR);
138 if(inputMsgId.equals(outputMsgId) == false) {
139 final Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
140 .put( "actual-message-id", outputMsgId )
141 .put( "expected-message-id", inputMsgId )
144 throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
145 null, NetconfDocumentedException.ErrorType.protocol,
146 NetconfDocumentedException.ErrorTag.bad_attribute,
147 NetconfDocumentedException.ErrorSeverity.error, errorInfo );
151 public static void checkSuccessReply(final NetconfMessage output) throws NetconfDocumentedException {
152 if(NetconfMessageUtil.isErrorMessage(output)) {
153 throw NetconfDocumentedException.fromXMLDocument(output.getDocument());
157 public static RpcError toRpcError( final NetconfDocumentedException ex ) {
158 final StringBuilder infoBuilder = new StringBuilder();
159 final Map<String, String> errorInfo = ex.getErrorInfo();
160 if(errorInfo != null) {
161 for( final Entry<String,String> e: errorInfo.entrySet() ) {
162 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
163 .append( "</" ).append( e.getKey() ).append( '>' );
168 final ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
169 return severity == ErrorSeverity.ERROR ?
170 RpcResultBuilder.newError(
171 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
172 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
173 RpcResultBuilder.newWarning(
174 toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
175 ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
178 private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
181 return RpcError.ErrorSeverity.WARNING;
183 return RpcError.ErrorSeverity.ERROR;
187 private static RpcError.ErrorType toRpcErrorType(final NetconfDocumentedException.ErrorType type) {
190 return RpcError.ErrorType.PROTOCOL;
192 return RpcError.ErrorType.RPC;
194 return RpcError.ErrorType.TRANSPORT;
196 return RpcError.ErrorType.APPLICATION;
200 public static YangInstanceIdentifier.NodeIdentifier toId(final YangInstanceIdentifier.PathArgument qname) {
201 return toId(qname.getNodeType());
204 public static YangInstanceIdentifier.NodeIdentifier toId(final QName nodeType) {
205 return new YangInstanceIdentifier.NodeIdentifier(nodeType);
208 public static Element getDataSubtree(final Document doc) {
209 return (Element) doc.getElementsByTagNameNS(NETCONF_URI.toString(), "data").item(0);
212 public static boolean isDataRetrievalOperation(final QName rpc) {
213 return NETCONF_URI.equals(rpc.getNamespace())
214 && (rpc.getLocalName().equals(NETCONF_GET_CONFIG_QNAME.getLocalName()) || rpc.getLocalName().equals(
215 NETCONF_GET_QNAME.getLocalName()));
218 public static boolean isDataEditOperation(final QName rpc) {
219 return NETCONF_URI.equals(rpc.getNamespace())
220 && rpc.getLocalName().equals(NETCONF_EDIT_CONFIG_QNAME.getLocalName());
224 * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
230 * // All schema nodes from remote schema
237 * This makes the translation of rpc edit-config request(especially the config node)
238 * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
240 public static DataNodeContainer createSchemaForEdit(final SchemaContext schemaContext) {
241 final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "config");
242 final QName editConfig = QName.create(NETCONF_EDIT_CONFIG_QNAME, "edit-config");
243 final NodeContainerProxy configProxy = new NodeContainerProxy(config, schemaContext.getChildNodes());
244 final NodeContainerProxy editConfigProxy = new NodeContainerProxy(editConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
245 return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
248 public static ContainerSchemaNode createSchemaForDataRead(final SchemaContext schemaContext) {
249 final QName config = QName.create(NETCONF_EDIT_CONFIG_QNAME, "data");
250 return new NodeContainerProxy(config, schemaContext.getChildNodes());
254 public static ContainerSchemaNode createSchemaForNotification(final NotificationDefinition next) {
255 return new NodeContainerProxy(next.getQName(), next.getChildNodes(), next.getAvailableAugmentations());
259 * Creates artificial schema node for edit-config rpc. This artificial schema looks like:
265 * // All schema nodes from remote schema
272 * This makes the translation of rpc get request(especially the config node)
273 * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
275 public static DataNodeContainer createSchemaForGet(final SchemaContext schemaContext) {
276 final QName filter = QName.create(NETCONF_GET_QNAME, "filter");
277 final QName get = QName.create(NETCONF_GET_QNAME, "get");
278 final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
279 final NodeContainerProxy editConfigProxy = new NodeContainerProxy(get, Sets.<DataSchemaNode>newHashSet(configProxy));
280 return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
284 * Creates artificial schema node for get rpc. This artificial schema looks like:
290 * // All schema nodes from remote schema
297 * This makes the translation of rpc get-config request(especially the config node)
298 * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
300 public static DataNodeContainer createSchemaForGetConfig(final SchemaContext schemaContext) {
301 final QName filter = QName.create(NETCONF_GET_CONFIG_QNAME, "filter");
302 final QName getConfig = QName.create(NETCONF_GET_CONFIG_QNAME, "get-config");
303 final NodeContainerProxy configProxy = new NodeContainerProxy(filter, schemaContext.getChildNodes());
304 final NodeContainerProxy editConfigProxy = new NodeContainerProxy(getConfig, Sets.<DataSchemaNode>newHashSet(configProxy));
305 return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(editConfigProxy));
308 public static Optional<RpcDefinition> findSchemaForRpc(final QName rpcName, final SchemaContext schemaContext) {
309 Preconditions.checkNotNull(rpcName);
310 Preconditions.checkNotNull(schemaContext);
312 for (final RpcDefinition rpcDefinition : schemaContext.getOperations()) {
313 if(rpcDefinition.getQName().equals(rpcName)) {
314 return Optional.of(rpcDefinition);
318 return Optional.absent();
322 * Creates artificial schema node for schema defined rpc. This artificial schema looks like:
327 * // All schema nodes from remote schema
333 * This makes the translation of schema defined rpc request
334 * to xml use schema which is crucial for some types of nodes e.g. identity-ref.
336 public static DataNodeContainer createSchemaForRpc(final RpcDefinition rpcDefinition) {
337 final NodeContainerProxy rpcBodyProxy = new NodeContainerProxy(rpcDefinition.getQName(), rpcDefinition.getInput().getChildNodes());
338 return new NodeContainerProxy(NETCONF_RPC_QNAME, Sets.<DataSchemaNode>newHashSet(rpcBodyProxy));
341 public static ContainerNode wrap(final QName name, final DataContainerChild<?, ?>... node) {
342 return Builders.containerBuilder().withNodeIdentifier(toId(name)).withValue(Lists.newArrayList(node)).build();
345 public static DataContainerChild<?, ?> createEditConfigStructure(final SchemaContext ctx, final YangInstanceIdentifier dataPath,
346 final Optional<ModifyAction> operation, final Optional<NormalizedNode<?, ?>> lastChildOverride) {
347 // TODO The config element inside the EditContent should be AnyXml not Container, but AnyXml is based on outdated API
348 if(Iterables.isEmpty(dataPath.getPathArguments())) {
349 Preconditions.checkArgument(lastChildOverride.isPresent(), "Data has to be present when creating structure for top level element");
350 Preconditions.checkArgument(lastChildOverride.get() instanceof DataContainerChild<?, ?>,
351 "Data has to be either container or a list node when creating structure for top level element, but was: %s", lastChildOverride.get());
352 return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(
353 wrap(NETCONF_CONFIG_QNAME, ((DataContainerChild<?, ?>) lastChildOverride.get()))).build();
355 return Builders.choiceBuilder().withNodeIdentifier(toId(EditContent.QNAME)).withChild(
356 wrap(NETCONF_CONFIG_QNAME, (DataContainerChild<?, ?>) InstanceIdToNodes.serialize(ctx, dataPath, lastChildOverride, operation))).build();
360 public static void addPredicatesToCompositeNodeBuilder(final Map<QName, Object> predicates,
361 final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> builder) {
362 for (final Map.Entry<QName, Object> entry : predicates.entrySet()) {
363 builder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(entry.getKey())).withValue(entry.getValue()).build());
367 public static Map<QName, Object> getPredicates(final YangInstanceIdentifier.PathArgument arg) {
368 Map<QName, Object> predicates = Collections.emptyMap();
369 if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
370 predicates = ((YangInstanceIdentifier.NodeIdentifierWithPredicates) arg).getKeyValues();
375 public static SchemaPath toPath(final QName rpc) {
376 return SchemaPath.create(true, rpc);
379 public static String modifyOperationToXmlString(final ModifyAction operation) {
380 return operation.name().toLowerCase();