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