BUG 2743 - Added support for runtime RPC's to netconf mdsal northbound.
[controller.git] / opendaylight / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / controller / netconf / mdsal / connector / ops / EditConfig.java
1 /*
2  * Copyright (c) 2015 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.mdsal.connector.ops;
10
11 import com.google.common.base.Optional;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import java.net.URI;
14 import java.net.URISyntaxException;
15 import java.util.Collections;
16 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
17 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
18 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
19 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
20 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
21 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
22 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
23 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
24 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
25 import org.opendaylight.controller.netconf.mdsal.connector.TransactionProvider;
26 import org.opendaylight.controller.netconf.util.exception.MissingNameSpaceException;
27 import org.opendaylight.controller.netconf.util.exception.UnexpectedNamespaceException;
28 import org.opendaylight.controller.netconf.util.mapping.AbstractSingletonNetconfOperation;
29 import org.opendaylight.controller.netconf.util.xml.XmlElement;
30 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
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.MapNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
36 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
37 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
38 import org.opendaylight.yangtools.yang.data.operations.DataModificationException;
39 import org.opendaylight.yangtools.yang.data.operations.DataModificationException.DataExistsException;
40 import org.opendaylight.yangtools.yang.data.operations.DataModificationException.DataMissingException;
41 import org.opendaylight.yangtools.yang.data.operations.DataOperations;
42 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48 import org.w3c.dom.Document;
49 import org.w3c.dom.Element;
50
51 public class EditConfig extends AbstractSingletonNetconfOperation {
52
53     private static final Logger LOG = LoggerFactory.getLogger(EditConfig.class);
54
55     private static final String OPERATION_NAME = "edit-config";
56     private static final String CONFIG_KEY = "config";
57     private static final String TARGET_KEY = "target";
58     private static final String DEFAULT_OPERATION_KEY = "default-operation";
59
60
61     private final CurrentSchemaContext schemaContext;
62     private final TransactionProvider transactionProvider;
63
64     public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
65         super(netconfSessionIdForReporting);
66         this.schemaContext = schemaContext;
67         this.transactionProvider = transactionProvider;
68     }
69
70     @Override
71     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws NetconfDocumentedException {
72         final Datastore targetDatastore = extractTargetParameter(operationElement);
73         if (targetDatastore == Datastore.running) {
74             throw new NetconfDocumentedException("edit-config on running datastore is not supported",
75                     ErrorType.protocol,
76                     ErrorTag.operation_not_supported,
77                     ErrorSeverity.error);
78         }
79
80         final ModifyAction defaultAction = getDefaultOperation(operationElement);
81
82         final XmlElement configElement = getElement(operationElement, CONFIG_KEY);
83
84         for (XmlElement element : configElement.getChildElements()) {
85             final String ns = element.getNamespace();
86             final DataSchemaNode schemaNode = getSchemaNodeFromNamespace(ns, element).get();
87             YangInstanceIdentifier ident = YangInstanceIdentifier.of(schemaNode.getQName());
88
89             final NormalizedNode storedNode = readStoredNode(LogicalDatastoreType.CONFIGURATION, ident);
90             try {
91                 final Optional<NormalizedNode<?, ?>> newNode = modifyNode(schemaNode, element, storedNode, defaultAction);
92                 final DOMDataReadWriteTransaction rwTx = transactionProvider.getOrCreateTransaction();
93                 if (newNode.isPresent()) {
94                     rwTx.put(LogicalDatastoreType.CONFIGURATION, ident, newNode.get());
95                 } else {
96                     rwTx.delete(LogicalDatastoreType.CONFIGURATION, ident);
97                 }
98             } catch (final DataExistsException e) {
99                 throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.protocol, ErrorTag.data_exists, ErrorSeverity.error);
100             } catch (final DataMissingException e) {
101                 throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
102             } catch (final DataModificationException e) {
103                 throw new NetconfDocumentedException(e.getMessage(), e, ErrorType.protocol, ErrorTag.operation_failed, ErrorSeverity.error);
104             }
105         }
106
107         return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
108     }
109
110     private NormalizedNode readStoredNode(final LogicalDatastoreType logicalDatastoreType, final YangInstanceIdentifier path) throws NetconfDocumentedException{
111         final  DOMDataReadWriteTransaction rwTx = transactionProvider.getOrCreateTransaction();
112         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> readFuture = rwTx.read(logicalDatastoreType, path);
113         try {
114             if (readFuture.checkedGet().isPresent()) {
115                 final NormalizedNode node = readFuture.checkedGet().get();
116                 return node;
117             } else {
118                 LOG.debug("Unable to read node : {} from {} datastore", path, logicalDatastoreType);
119             }
120         } catch (final ReadFailedException e) {
121             //only log this since DataOperations.modify will handle throwing an exception or writing the node.
122             LOG.debug("Unable to read stored data: {}", path, e);
123         }
124
125         //we can return null here since DataOperations.modify handles null as input
126         return null;
127     }
128
129     private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws NetconfDocumentedException{
130         Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
131         try {
132             //returns module with newest revision since findModuleByNamespace returns a set of modules and we only need the newest one
133             final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
134             DataSchemaNode schemaNode = module.getDataChildByName(element.getName());
135             if (schemaNode != null) {
136                 dataSchemaNode = Optional.of(module.getDataChildByName(element.getName()));
137             } else {
138                 throw new NetconfDocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
139                         ErrorType.application,
140                         ErrorTag.unknown_namespace,
141                         ErrorSeverity.error);
142             }
143
144         } catch (URISyntaxException e) {
145             LOG.debug("Unable to create URI for namespace : {}", namespace);
146         }
147
148         return dataSchemaNode;
149     }
150
151     private Optional<NormalizedNode<?, ?>> modifyNode(final DataSchemaNode schemaNode, final XmlElement element, final NormalizedNode storedNode, final ModifyAction defaultAction) throws DataModificationException{
152         if (schemaNode instanceof ContainerSchemaNode) {
153             final ContainerNode modifiedNode =
154                     DomToNormalizedNodeParserFactory
155                             .getInstance(DomUtils.defaultValueCodecProvider())
156                             .getContainerNodeParser()
157                             .parse(Collections.singletonList(element.getDomElement()), (ContainerSchemaNode) schemaNode);
158
159             final Optional<ContainerNode> oNode = DataOperations.modify((ContainerSchemaNode) schemaNode, (ContainerNode) storedNode, modifiedNode, defaultAction);
160             if (!oNode.isPresent()) {
161                 return Optional.absent();
162             }
163
164             final NormalizedNode<?,?> node = oNode.get();
165             return Optional.<NormalizedNode<?,?>>of(node);
166         } else if (schemaNode instanceof ListSchemaNode) {
167             final MapNode modifiedNode =
168                 DomToNormalizedNodeParserFactory
169                         .getInstance(DomUtils.defaultValueCodecProvider())
170                         .getMapNodeParser()
171                         .parse(Collections.singletonList(element.getDomElement()), (ListSchemaNode) schemaNode);
172
173             final Optional<MapNode> oNode = DataOperations.modify((ListSchemaNode) schemaNode, (MapNode) storedNode, modifiedNode, defaultAction);
174             if (!oNode.isPresent()) {
175                 return Optional.absent();
176             }
177
178             final NormalizedNode<?, ?> node = oNode.get();
179             return Optional.<NormalizedNode<?,?>>of(node);
180         } else {
181             //this should never happen since edit-config on any other node type should not be possible nor makes sense
182             LOG.debug("DataNode from module is not ContainerSchemaNode nor ListSchemaNode, aborting..");
183             return Optional.absent();
184         }
185
186     }
187
188     private Datastore extractTargetParameter(final XmlElement operationElement) throws NetconfDocumentedException {
189         final XmlElement targetChildNode;
190         try {
191             final XmlElement targetElement = operationElement.getOnlyChildElementWithSameNamespace(TARGET_KEY);
192             targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
193         } catch (final MissingNameSpaceException | UnexpectedNamespaceException e) {
194             LOG.trace("Can't get only child element with same namespace", e);
195             throw NetconfDocumentedException.wrap(e);
196         }
197
198         return Datastore.valueOf(targetChildNode.getName());
199     }
200
201     private ModifyAction getDefaultOperation(final XmlElement operationElement) throws NetconfDocumentedException{
202         try {
203             return ModifyAction.fromXmlValue(getElement(operationElement, DEFAULT_OPERATION_KEY).getTextContent());
204         } catch (NetconfDocumentedException e) {
205             if (e.getErrorType() == ErrorType.protocol
206                     && e.getErrorSeverity() == ErrorSeverity.error
207                     && e.getErrorTag() == ErrorTag.missing_element) {
208                 return ModifyAction.MERGE;
209             }
210             else {
211                 throw e;
212             }
213         }
214     }
215
216     private XmlElement getElement(final XmlElement operationElement, String elementName) throws NetconfDocumentedException {
217         final Optional<XmlElement> childNode = operationElement.getOnlyChildElementOptionally(elementName);
218         if (!childNode.isPresent()) {
219             throw new NetconfDocumentedException(elementName + " element is missing",
220                     ErrorType.protocol,
221                     ErrorTag.missing_element,
222                     ErrorSeverity.error);
223         }
224
225         return childNode.get();
226     }
227
228     @Override
229     protected String getOperationName() {
230         return OPERATION_NAME;
231     }
232
233 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.