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