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