Bug 6681: Fix md-sal netconf edit-config behavior
[netconf.git] / netconf / mdsal-netconf-connector / src / main / java / org / opendaylight / 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.netconf.mdsal.connector.ops;
10
11 import com.google.common.base.Optional;
12 import java.net.URI;
13 import java.net.URISyntaxException;
14 import java.util.Collections;
15 import java.util.List;
16 import java.util.ListIterator;
17 import org.opendaylight.controller.config.util.xml.DocumentedException;
18 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
19 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
20 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
21 import org.opendaylight.controller.config.util.xml.XmlElement;
22 import org.opendaylight.controller.config.util.xml.XmlUtil;
23 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
24 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
25 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
26 import org.opendaylight.netconf.api.NetconfDocumentedException;
27 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
28 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
29 import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
30 import org.opendaylight.netconf.mdsal.connector.ops.DataTreeChangeTracker.DataTreeChange;
31 import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
39 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
40 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
41 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.w3c.dom.Document;
48 import org.w3c.dom.Element;
49 import org.w3c.dom.NodeList;
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     private final CurrentSchemaContext schemaContext;
60     private final TransactionProvider transactionProvider;
61
62     public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
63         super(netconfSessionIdForReporting);
64         this.schemaContext = schemaContext;
65         this.transactionProvider = transactionProvider;
66     }
67
68     @Override
69     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
70         final Datastore targetDatastore = extractTargetParameter(operationElement);
71         if (targetDatastore == Datastore.running) {
72             throw new DocumentedException("edit-config on running datastore is not supported",
73                     ErrorType.protocol,
74                     ErrorTag.operation_not_supported,
75                     ErrorSeverity.error);
76         }
77
78         final ModifyAction defaultAction = getDefaultOperation(operationElement);
79
80         final XmlElement configElement = getElement(operationElement, CONFIG_KEY);
81
82         for (final XmlElement element : configElement.getChildElements()) {
83             final String ns = element.getNamespace();
84             final DataSchemaNode schemaNode = getSchemaNodeFromNamespace(ns, element).get();
85
86             final DataTreeChangeTracker changeTracker = new DataTreeChangeTracker(defaultAction);
87             final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider = new EditOperationStrategyProvider(changeTracker);
88
89             parseIntoNormalizedNode(schemaNode, element, editOperationStrategyProvider);
90             executeOperations(changeTracker);
91         }
92
93         return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
94     }
95
96     private void executeOperations(final DataTreeChangeTracker changeTracker) throws DocumentedException {
97         final DOMDataReadWriteTransaction rwTx = transactionProvider.getOrCreateTransaction();
98         final List<DataTreeChange> aa = changeTracker.getDataTreeChanges();
99         final ListIterator<DataTreeChange> iterator = aa.listIterator(aa.size());
100
101         while (iterator.hasPrevious()) {
102             final DataTreeChange dtc = iterator.previous();
103             executeChange(rwTx, dtc);
104         }
105     }
106
107     private void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) throws DocumentedException {
108         final YangInstanceIdentifier path = YangInstanceIdentifier.create(change.getPath());
109         final NormalizedNode<?, ?> changeData = change.getChangeRoot();
110         switch (change.getAction()) {
111         case NONE:
112             return;
113         case MERGE:
114             createMapNodeIfNonExistent(rwtx, path, changeData);
115             rwtx.merge(LogicalDatastoreType.CONFIGURATION, path, changeData);
116             break;
117         case CREATE:
118             try {
119                 final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
120                 if (readResult.isPresent()) {
121                     throw new DocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.protocol, ErrorTag.data_exists, ErrorSeverity.error);
122                 }
123                 createMapNodeIfNonExistent(rwtx, path, changeData);
124                 rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
125             } catch (final ReadFailedException e) {
126                 LOG.warn("Read from datastore failed when trying to read data for create operation", change, e);
127             }
128             break;
129         case REPLACE:
130             createMapNodeIfNonExistent(rwtx, path, changeData);
131             rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
132             break;
133         case DELETE:
134             try {
135                 final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
136                 if (!readResult.isPresent()) {
137                     throw new DocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
138                 }
139                 rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
140             } catch (final ReadFailedException e) {
141                 LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e);
142             }
143             break;
144         case REMOVE:
145             rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
146             break;
147         default:
148             LOG.warn("Unknown/not implemented operation, not executing");
149         }
150     }
151
152     private void createMapNodeIfNonExistent(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path,
153                                             final NormalizedNode change) throws DocumentedException {
154         if (!(change instanceof MapEntryNode)) {
155             return;
156         }
157         final YangInstanceIdentifier mapNodeYid = path.getParent();
158         try {
159             final Boolean mapNodeExists = rwtx.exists(LogicalDatastoreType.CONFIGURATION, mapNodeYid).checkedGet();
160             if (!mapNodeExists) {
161                 final MapNode mixinNode = Builders.mapBuilder()
162                         .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(mapNodeYid.getLastPathArgument().getNodeType()))
163                         .build();
164                 rwtx.put(LogicalDatastoreType.CONFIGURATION, mapNodeYid, mixinNode);
165             }
166         } catch (final ReadFailedException e) {
167             throw new DocumentedException("List node existence check failed", e, ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
168
169         }
170     }
171
172     private NormalizedNode parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element,
173                                                    final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) {
174
175
176         if (schemaNode instanceof ContainerSchemaNode) {
177             return DomToNormalizedNodeParserFactory
178                     .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
179                     .getContainerNodeParser()
180                     .parse(Collections.singletonList(element.getDomElement()), (ContainerSchemaNode) schemaNode);
181         } else if (schemaNode instanceof ListSchemaNode) {
182             return DomToNormalizedNodeParserFactory
183                     .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
184                     .getMapNodeParser()
185                     .parse(Collections.singletonList(element.getDomElement()), (ListSchemaNode) schemaNode);
186         } else {
187             //this should never happen since edit-config on any other node type should not be possible nor makes sense
188             LOG.debug("DataNode from module is not ContainerSchemaNode nor ListSchemaNode, aborting..");
189         }
190         throw new UnsupportedOperationException("implement exception if parse fails");
191     }
192
193     private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws DocumentedException{
194         Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
195         try {
196             //returns module with newest revision since findModuleByNamespace returns a set of modules and we only need the newest one
197             final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
198             if (module == null) {
199                 // no module is present with this namespace
200                 throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
201                         ErrorType.application, ErrorTag.unknown_namespace, ErrorSeverity.error);
202             }
203             final DataSchemaNode schemaNode =
204                     module.getDataChildByName(QName.create(module.getQNameModule(), element.getName()));
205             if (schemaNode != null) {
206                 dataSchemaNode = Optional.of(schemaNode);
207             } else {
208                 throw new DocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
209                         ErrorType.application,
210                         ErrorTag.unknown_namespace,
211                         ErrorSeverity.error);
212             }
213         } catch (final URISyntaxException e) {
214             LOG.debug("Unable to create URI for namespace : {}", namespace);
215         }
216
217         return dataSchemaNode;
218     }
219
220     private Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
221         final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(TARGET_KEY);
222         // Direct lookup instead of using XmlElement class due to performance
223         if (elementsByTagName.getLength() == 0) {
224             throw new DocumentedException("Missing target element", ErrorType.rpc, ErrorTag.missing_attribute, ErrorSeverity.error);
225         } else if (elementsByTagName.getLength() > 1) {
226             throw new DocumentedException("Multiple target elements", ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
227         } else {
228             final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
229             return Datastore.valueOf(targetChildNode.getName());
230         }
231     }
232
233     private ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
234         final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(DEFAULT_OPERATION_KEY);
235         if(elementsByTagName.getLength() == 0) {
236             return ModifyAction.MERGE;
237         } else if(elementsByTagName.getLength() > 1) {
238             throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements",
239                     ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
240         } else {
241             return ModifyAction.fromXmlValue(elementsByTagName.item(0).getTextContent());
242         }
243
244     }
245
246     private XmlElement getElement(final XmlElement operationElement, final String elementName) throws DocumentedException {
247         final Optional<XmlElement> childNode = operationElement.getOnlyChildElementOptionally(elementName);
248         if (!childNode.isPresent()) {
249             throw new DocumentedException(elementName + " element is missing",
250                     ErrorType.protocol,
251                     ErrorTag.missing_element,
252                     ErrorSeverity.error);
253         }
254
255         return childNode.get();
256     }
257
258     @Override
259     protected String getOperationName() {
260         return OPERATION_NAME;
261     }
262
263 }