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