e3bb3cd1000c662ee57b42423f9e899a7584eb63
[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 = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
130                 if (readResult.isPresent()) {
131                     throw new DocumentedException("Data already exists, cannot execute CREATE operation",
132                         ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
133                 }
134                 mergeParentMap(rwtx, path, changeData);
135                 rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
136             } catch (final ReadFailedException e) {
137                 LOG.warn("Read from datastore failed when trying to read data for create operation", change, e);
138             }
139             break;
140         case REPLACE:
141             mergeParentMap(rwtx, path, changeData);
142             rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
143             break;
144         case DELETE:
145             try {
146                 final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
147                 if (!readResult.isPresent()) {
148                     throw new DocumentedException("Data is missing, cannot execute DELETE operation",
149                         ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
150                 }
151                 rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
152             } catch (final ReadFailedException e) {
153                 LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e);
154             }
155             break;
156         case REMOVE:
157             rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
158             break;
159         default:
160             LOG.warn("Unknown/not implemented operation, not executing");
161         }
162     }
163
164     private void mergeParentMap(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path,
165                                 final NormalizedNode<?, ?> change) {
166         if (change instanceof MapEntryNode) {
167             final YangInstanceIdentifier mapNodeYid = path.getParent();
168
169             final SchemaNode schemaNode = SchemaContextUtil.findNodeInSchemaContext(
170                     schemaContext.getCurrentContext(),
171                     mapNodeYid.getPathArguments().stream()
172                             // filter out identifiers not present in the schema tree
173                             .filter(arg -> !(arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates))
174                             .filter(arg -> !(arg instanceof YangInstanceIdentifier.AugmentationIdentifier))
175                             .map(YangInstanceIdentifier.PathArgument::getNodeType).collect(Collectors.toList()));
176
177             // we should have the schema node that points to the parent list now, enforce it
178             Preconditions.checkState(schemaNode instanceof ListSchemaNode, "Schema node is not pointing to a list.");
179
180             //merge empty ordered or unordered map
181             if (((ListSchemaNode) schemaNode).isUserOrdered()) {
182                 final MapNode mixinNode = Builders.orderedMapBuilder()
183                         .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(mapNodeYid.getLastPathArgument().getNodeType()))
184                         .build();
185                 rwtx.merge(LogicalDatastoreType.CONFIGURATION, mapNodeYid, mixinNode);
186                 return;
187             }
188
189             final MapNode mixinNode = Builders.mapBuilder()
190                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(mapNodeYid.getLastPathArgument().getNodeType()))
191                     .build();
192             rwtx.merge(LogicalDatastoreType.CONFIGURATION, mapNodeYid, mixinNode);
193         }
194     }
195
196     private NormalizedNode<?, ?> parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element,
197             final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) {
198         if (schemaNode instanceof ContainerSchemaNode) {
199             return DomToNormalizedNodeParserFactory
200                     .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
201                     .getContainerNodeParser()
202                     .parse(Collections.singletonList(element.getDomElement()), (ContainerSchemaNode) schemaNode);
203         } else if (schemaNode instanceof ListSchemaNode) {
204             return DomToNormalizedNodeParserFactory
205                     .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
206                     .getMapNodeParser()
207                     .parse(Collections.singletonList(element.getDomElement()), (ListSchemaNode) schemaNode);
208         } else {
209             //this should never happen since edit-config on any other node type should not be possible nor makes sense
210             LOG.debug("DataNode from module is not ContainerSchemaNode nor ListSchemaNode, aborting..");
211         }
212         throw new UnsupportedOperationException("implement exception if parse fails");
213     }
214
215     private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element)
216             throws DocumentedException {
217         Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
218         try {
219             // returns module with newest revision since findModuleByNamespace returns a set of modules and we only
220             // need the newest one
221             final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
222             if (module == null) {
223                 // no module is present with this namespace
224                 throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
225                         ErrorType.APPLICATION, ErrorTag.UNKNOWN_NAMESPACE, ErrorSeverity.ERROR);
226             }
227             final DataSchemaNode schemaNode =
228                     module.getDataChildByName(QName.create(module.getQNameModule(), element.getName()));
229             if (schemaNode != null) {
230                 dataSchemaNode = Optional.of(schemaNode);
231             } else {
232                 throw new DocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
233                         ErrorType.APPLICATION,
234                         ErrorTag.UNKNOWN_NAMESPACE,
235                         ErrorSeverity.ERROR);
236             }
237         } catch (final URISyntaxException e) {
238             LOG.debug("Unable to create URI for namespace : {}", namespace);
239         }
240
241         return dataSchemaNode;
242     }
243
244     private static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
245         final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(TARGET_KEY);
246         // Direct lookup instead of using XmlElement class due to performance
247         if (elementsByTagName.getLength() == 0) {
248             final Map<String, String> errorInfo = ImmutableMap.of("bad-attribute", TARGET_KEY, "bad-element",
249                 OPERATION_NAME);
250             throw new DocumentedException("Missing target element", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE,
251                 ErrorSeverity.ERROR, errorInfo);
252         } else if (elementsByTagName.getLength() > 1) {
253             throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE,
254                 ErrorSeverity.ERROR);
255         } else {
256             final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
257             return Datastore.valueOf(targetChildNode.getName());
258         }
259     }
260
261     private static ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
262         final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(DEFAULT_OPERATION_KEY);
263         if (elementsByTagName.getLength() == 0) {
264             return ModifyAction.MERGE;
265         } else if (elementsByTagName.getLength() > 1) {
266             throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements", ErrorType.RPC,
267                 ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR);
268         } else {
269             return ModifyAction.fromXmlValue(elementsByTagName.item(0).getTextContent());
270         }
271
272     }
273
274     private static XmlElement getElement(final XmlElement operationElement, final String elementName)
275             throws DocumentedException {
276         final Optional<XmlElement> childNode = operationElement.getOnlyChildElementOptionally(elementName);
277         if (!childNode.isPresent()) {
278             throw new DocumentedException(elementName + " element is missing",
279                     ErrorType.PROTOCOL,
280                     ErrorTag.MISSING_ELEMENT,
281                     ErrorSeverity.ERROR);
282         }
283
284         return childNode.get();
285     }
286
287     @Override
288     protected String getOperationName() {
289         return OPERATION_NAME;
290     }
291
292 }