88735932768b26f88a3a562d420660f5d00f6213
[netconf.git] / plugins / netconf-server-mdsal / src / main / java / org / opendaylight / netconf / server / mdsal / operations / 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 package org.opendaylight.netconf.server.mdsal.operations;
9
10 import static java.util.Objects.requireNonNull;
11
12 import java.util.List;
13 import java.util.concurrent.ExecutionException;
14 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
15 import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
16 import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteOperations;
17 import org.opendaylight.netconf.api.DocumentedException;
18 import org.opendaylight.netconf.api.EffectiveOperation;
19 import org.opendaylight.netconf.api.xml.XmlElement;
20 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
21 import org.opendaylight.netconf.server.mdsal.CurrentSchemaContext;
22 import org.opendaylight.netconf.server.mdsal.TransactionProvider;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.SessionIdType;
24 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
25 import org.opendaylight.yangtools.yang.common.ErrorTag;
26 import org.opendaylight.yangtools.yang.common.ErrorType;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
32 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36 import org.w3c.dom.Document;
37 import org.w3c.dom.Element;
38
39 public final class EditConfig extends AbstractEdit {
40     private static final Logger LOG = LoggerFactory.getLogger(EditConfig.class);
41     private static final String OPERATION_NAME = "edit-config";
42     private static final String DEFAULT_OPERATION = "default-operation";
43
44     private final TransactionProvider transactionProvider;
45
46     public EditConfig(final SessionIdType sessionId, final CurrentSchemaContext schemaContext,
47             final TransactionProvider transactionProvider) {
48         super(sessionId, schemaContext);
49         this.transactionProvider = requireNonNull(transactionProvider);
50     }
51
52     @Override
53     protected String getOperationName() {
54         return OPERATION_NAME;
55     }
56
57     @Override
58     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
59             throws DocumentedException {
60         if (Datastore.valueOf(extractTargetElement(operationElement, OPERATION_NAME).getName()) == Datastore.running) {
61             throw new DocumentedException("edit-config on running datastore is not supported",
62                     ErrorType.PROTOCOL, ErrorTag.OPERATION_NOT_SUPPORTED, ErrorSeverity.ERROR);
63         }
64
65         final var defaultAction = getDefaultOperation(operationElement);
66         for (var element : getConfigElement(operationElement).getChildElements()) {
67             final var writer = new SplittingNormalizedNodeMetadataStreamWriter(defaultAction);
68             parseIntoNormalizedNode(getSchemaNodeFromNamespace(element.getNamespace(), element), element, writer);
69             executeOperations(writer.getDataTreeChanges());
70         }
71
72         return document.createElement(XmlNetconfConstants.OK);
73     }
74
75     private void executeOperations(final List<DataTreeChange> changes) throws DocumentedException {
76         final var rwTx = transactionProvider.getOrCreateTransaction();
77         final var iterator = changes.listIterator(changes.size());
78         while (iterator.hasPrevious()) {
79             executeChange(rwTx, iterator.previous());
80         }
81     }
82
83     // FIXME: we should have proper ReadWriteOperations
84     private void executeChange(final DOMDataTreeReadWriteTransaction rwtx, final DataTreeChange change)
85             throws DocumentedException {
86         final var path = change.getPath();
87         final var changeData = change.getChangeRoot();
88         switch (change.getAction()) {
89             case NONE:
90                 return;
91             case MERGE:
92                 mergeParentMixin(rwtx, path, changeData);
93                 rwtx.merge(LogicalDatastoreType.CONFIGURATION, path, changeData);
94                 break;
95             case CREATE:
96                 try {
97                     // FIXME: synchronous operation: can we get a rwTx.create() with a per-operation result instead?
98                     if (rwtx.exists(LogicalDatastoreType.CONFIGURATION, path).get()) {
99                         throw new DocumentedException("Data already exists, cannot execute CREATE operation",
100                             ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
101                     }
102                     mergeParentMixin(rwtx, path, changeData);
103                     rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
104                 } catch (final InterruptedException | ExecutionException e) {
105                     LOG.warn("Read from datastore failed when trying to read data for create operation {}", change, e);
106                 }
107                 break;
108             case REPLACE:
109                 mergeParentMixin(rwtx, path, changeData);
110                 rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
111                 break;
112             case DELETE:
113                 try {
114                     // FIXME: synchronous operation: can we get a rwTx.delete() semantics with a per-operation result
115                     //        instead?
116                     if (!rwtx.exists(LogicalDatastoreType.CONFIGURATION, path).get()) {
117                         throw new DocumentedException("Data is missing, cannot execute DELETE operation",
118                             ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
119                     }
120                     rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
121                 } catch (final InterruptedException | ExecutionException e) {
122                     LOG.warn("Read from datastore failed when trying to read data for delete operation {}", change, e);
123                 }
124                 break;
125             case REMOVE:
126                 rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
127                 break;
128             default:
129                 LOG.warn("Unknown/not implemented operation, not executing");
130         }
131     }
132
133     private void mergeParentMixin(final DOMDataTreeWriteOperations rwtx, final YangInstanceIdentifier path,
134                                   final NormalizedNode change) {
135         final var parentNodeYid = path.getParent();
136         if (change instanceof MapEntryNode) {
137             final var dataSchemaNode = DataSchemaContextTree.from(schemaContext.getCurrentContext())
138                 .findChild(parentNodeYid)
139                 .orElseThrow(() -> new IllegalStateException("Cannot find schema for " + parentNodeYid))
140                 .dataSchemaNode();
141
142             // we should have the schema node that points to the parent list now, enforce it
143             if (!(dataSchemaNode instanceof ListSchemaNode listSchemaNode)) {
144                 throw new IllegalStateException("Schema node is not pointing to a list");
145             }
146
147             // merge empty ordered or unordered map
148             rwtx.merge(LogicalDatastoreType.CONFIGURATION, parentNodeYid,
149                 (listSchemaNode.isUserOrdered() ? Builders.orderedMapBuilder() : Builders.mapBuilder())
150                     .withNodeIdentifier(new NodeIdentifier(parentNodeYid.getLastPathArgument().getNodeType()))
151                     .build());
152         }
153     }
154
155     private static EffectiveOperation getDefaultOperation(final XmlElement operationElement)
156             throws DocumentedException {
157         final var elementsByTagName = getElementsByTagName(operationElement, DEFAULT_OPERATION);
158         return switch (elementsByTagName.getLength()) {
159             case 0 -> EffectiveOperation.MERGE;
160             case 1 ->  EffectiveOperation.ofXmlValue(elementsByTagName.item(0).getTextContent());
161             default -> throw new DocumentedException("Multiple " + DEFAULT_OPERATION + " elements", ErrorType.RPC,
162                 ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR);
163         };
164     }
165 }