* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.netconf.mdsal.connector.ops;
-import com.google.common.base.Optional;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Collections;
+import com.google.common.base.Preconditions;
import java.util.List;
import java.util.ListIterator;
-import org.opendaylight.controller.config.util.xml.DocumentedException;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
-import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
-import org.opendaylight.controller.config.util.xml.XmlElement;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.netconf.api.NetconfDocumentedException;
+import java.util.concurrent.ExecutionException;
+import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
+import org.opendaylight.netconf.api.DocumentedException;
+import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
+import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
+import org.opendaylight.netconf.api.DocumentedException.ErrorType;
+import org.opendaylight.netconf.api.ModifyAction;
+import org.opendaylight.netconf.api.xml.XmlElement;
import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
import org.opendaylight.netconf.mdsal.connector.TransactionProvider;
-import org.opendaylight.netconf.mdsal.connector.ops.DataTreeChangeTracker.DataTreeChange;
-import org.opendaylight.netconf.util.mapping.AbstractSingletonNetconfOperation;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
-public class EditConfig extends AbstractSingletonNetconfOperation {
+public final class EditConfig extends AbstractEdit {
private static final Logger LOG = LoggerFactory.getLogger(EditConfig.class);
private static final String OPERATION_NAME = "edit-config";
- private static final String CONFIG_KEY = "config";
- private static final String TARGET_KEY = "target";
private static final String DEFAULT_OPERATION_KEY = "default-operation";
- private final CurrentSchemaContext schemaContext;
private final TransactionProvider transactionProvider;
- public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) {
- super(netconfSessionIdForReporting);
- this.schemaContext = schemaContext;
+ public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext,
+ final TransactionProvider transactionProvider) {
+ super(netconfSessionIdForReporting, schemaContext);
this.transactionProvider = transactionProvider;
}
@Override
- protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
- final Datastore targetDatastore = extractTargetParameter(operationElement);
+ protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
+ throws DocumentedException {
+ final XmlElement targetElement = extractTargetElement(operationElement, OPERATION_NAME);
+ final Datastore targetDatastore = Datastore.valueOf(targetElement.getName());
if (targetDatastore == Datastore.running) {
throw new DocumentedException("edit-config on running datastore is not supported",
- ErrorType.protocol,
- ErrorTag.operation_not_supported,
- ErrorSeverity.error);
+ ErrorType.PROTOCOL,
+ ErrorTag.OPERATION_NOT_SUPPORTED,
+ ErrorSeverity.ERROR);
}
final ModifyAction defaultAction = getDefaultOperation(operationElement);
- final XmlElement configElement = getElement(operationElement, CONFIG_KEY);
+ final XmlElement configElement = getConfigElement(operationElement);
for (final XmlElement element : configElement.getChildElements()) {
final String ns = element.getNamespace();
- final DataSchemaNode schemaNode = getSchemaNodeFromNamespace(ns, element).get();
-
- final DataTreeChangeTracker changeTracker = new DataTreeChangeTracker(defaultAction);
- final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider = new EditOperationStrategyProvider(changeTracker);
+ final DataSchemaNode schemaNode = getSchemaNodeFromNamespace(ns, element);
- parseIntoNormalizedNode(schemaNode, element, editOperationStrategyProvider);
- executeOperations(changeTracker);
+ final SplittingNormalizedNodeMetadataStreamWriter writer = new SplittingNormalizedNodeMetadataStreamWriter(
+ defaultAction);
+ parseIntoNormalizedNode(schemaNode, element, writer);
+ executeOperations(writer.getDataTreeChanges());
}
- return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
+ return document.createElement(XmlNetconfConstants.OK);
}
- private void executeOperations(final DataTreeChangeTracker changeTracker) throws DocumentedException {
- final DOMDataReadWriteTransaction rwTx = transactionProvider.getOrCreateTransaction();
- final List<DataTreeChange> aa = changeTracker.getDataTreeChanges();
- final ListIterator<DataTreeChange> iterator = aa.listIterator(aa.size());
+ private void executeOperations(final List<DataTreeChange> changes) throws DocumentedException {
+ final DOMDataTreeReadWriteTransaction rwTx = transactionProvider.getOrCreateTransaction();
+ final ListIterator<DataTreeChange> iterator = changes.listIterator(changes.size());
while (iterator.hasPrevious()) {
final DataTreeChange dtc = iterator.previous();
}
}
- private void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) throws DocumentedException {
- final YangInstanceIdentifier path = YangInstanceIdentifier.create(change.getPath());
- final NormalizedNode<?, ?> changeData = change.getChangeRoot();
+ private void executeChange(final DOMDataTreeReadWriteTransaction rwtx, final DataTreeChange change)
+ throws DocumentedException {
+ final YangInstanceIdentifier path = change.getPath();
+ final NormalizedNode changeData = change.getChangeRoot();
switch (change.getAction()) {
- case NONE:
- return;
- case MERGE:
- createMapNodeIfNonExistent(rwtx, path, changeData);
- rwtx.merge(LogicalDatastoreType.CONFIGURATION, path, changeData);
- break;
- case CREATE:
- try {
- final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
- if (readResult.isPresent()) {
- throw new DocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.protocol, ErrorTag.data_exists, ErrorSeverity.error);
+ case NONE:
+ return;
+ case MERGE:
+ mergeParentMixin(rwtx, path, changeData);
+ rwtx.merge(LogicalDatastoreType.CONFIGURATION, path, changeData);
+ break;
+ case CREATE:
+ try {
+ if (rwtx.exists(LogicalDatastoreType.CONFIGURATION, path).get()) {
+ throw new DocumentedException("Data already exists, cannot execute CREATE operation",
+ ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR);
+ }
+ mergeParentMixin(rwtx, path, changeData);
+ rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
+ } catch (final InterruptedException | ExecutionException e) {
+ LOG.warn("Read from datastore failed when trying to read data for create operation {}", change, e);
}
- createMapNodeIfNonExistent(rwtx, path, changeData);
+ break;
+ case REPLACE:
+ mergeParentMixin(rwtx, path, changeData);
rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
- } catch (final ReadFailedException e) {
- LOG.warn("Read from datastore failed when trying to read data for create operation", change, e);
- }
- break;
- case REPLACE:
- createMapNodeIfNonExistent(rwtx, path, changeData);
- rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData);
- break;
- case DELETE:
- try {
- final Optional<NormalizedNode<?, ?>> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet();
- if (!readResult.isPresent()) {
- throw new DocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
+ break;
+ case DELETE:
+ try {
+ if (!rwtx.exists(LogicalDatastoreType.CONFIGURATION, path).get()) {
+ throw new DocumentedException("Data is missing, cannot execute DELETE operation",
+ ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
+ }
+ rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
+ } catch (final InterruptedException | ExecutionException e) {
+ LOG.warn("Read from datastore failed when trying to read data for delete operation {}", change, e);
}
+ break;
+ case REMOVE:
rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
- } catch (final ReadFailedException e) {
- LOG.warn("Read from datastore failed when trying to read data for delete operation", change, e);
- }
- break;
- case REMOVE:
- rwtx.delete(LogicalDatastoreType.CONFIGURATION, path);
- break;
- default:
- LOG.warn("Unknown/not implemented operation, not executing");
+ break;
+ default:
+ LOG.warn("Unknown/not implemented operation, not executing");
}
}
- private void createMapNodeIfNonExistent(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path,
- final NormalizedNode change) throws DocumentedException {
- if (!(change instanceof MapEntryNode)) {
- return;
- }
- final YangInstanceIdentifier mapNodeYid = path.getParent();
- try {
- final Boolean mapNodeExists = rwtx.exists(LogicalDatastoreType.CONFIGURATION, mapNodeYid).checkedGet();
- if (!mapNodeExists) {
- final MapNode mixinNode = Builders.mapBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(mapNodeYid.getLastPathArgument().getNodeType()))
+ private void mergeParentMixin(final DOMDataTreeReadWriteTransaction rwtx, final YangInstanceIdentifier path,
+ final NormalizedNode change) {
+ final YangInstanceIdentifier parentNodeYid = path.getParent();
+ if (change instanceof MapEntryNode) {
+ final DataSchemaNode schemaNode = DataSchemaContextTree.from(schemaContext.getCurrentContext())
+ .findChild(parentNodeYid)
+ .orElseThrow(() -> new IllegalStateException("Cannot find schema for " + parentNodeYid))
+ .getDataSchemaNode();
+
+ // we should have the schema node that points to the parent list now, enforce it
+ Preconditions.checkState(schemaNode instanceof ListSchemaNode, "Schema node is not pointing to a list.");
+
+ //merge empty ordered or unordered map
+ if (((ListSchemaNode) schemaNode).isUserOrdered()) {
+ final MapNode mixinNode = Builders.orderedMapBuilder()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(
+ parentNodeYid.getLastPathArgument().getNodeType()))
.build();
- rwtx.put(LogicalDatastoreType.CONFIGURATION, mapNodeYid, mixinNode);
+ rwtx.merge(LogicalDatastoreType.CONFIGURATION, parentNodeYid, mixinNode);
+ return;
}
- } catch (final ReadFailedException e) {
- throw new DocumentedException("List node existence check failed", e, ErrorType.protocol, ErrorTag.data_missing, ErrorSeverity.error);
-
- }
- }
-
- private NormalizedNode parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element,
- final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) {
-
-
- if (schemaNode instanceof ContainerSchemaNode) {
- return DomToNormalizedNodeParserFactory
- .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
- .getContainerNodeParser()
- .parse(Collections.singletonList(element.getDomElement()), (ContainerSchemaNode) schemaNode);
- } else if (schemaNode instanceof ListSchemaNode) {
- return DomToNormalizedNodeParserFactory
- .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider)
- .getMapNodeParser()
- .parse(Collections.singletonList(element.getDomElement()), (ListSchemaNode) schemaNode);
- } else {
- //this should never happen since edit-config on any other node type should not be possible nor makes sense
- LOG.debug("DataNode from module is not ContainerSchemaNode nor ListSchemaNode, aborting..");
- }
- throw new UnsupportedOperationException("implement exception if parse fails");
- }
- private Optional<DataSchemaNode> getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws DocumentedException{
- Optional<DataSchemaNode> dataSchemaNode = Optional.absent();
- try {
- //returns module with newest revision since findModuleByNamespace returns a set of modules and we only need the newest one
- final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null);
- if (module == null) {
- // no module is present with this namespace
- throw new NetconfDocumentedException("Unable to find module by namespace: " + namespace,
- ErrorType.application, ErrorTag.unknown_namespace, ErrorSeverity.error);
- }
- final DataSchemaNode schemaNode =
- module.getDataChildByName(QName.create(module.getQNameModule(), element.getName()));
- if (schemaNode != null) {
- dataSchemaNode = Optional.of(schemaNode);
- } else {
- throw new DocumentedException("Unable to find node with namespace: " + namespace + "in module: " + module.toString(),
- ErrorType.application,
- ErrorTag.unknown_namespace,
- ErrorSeverity.error);
- }
- } catch (final URISyntaxException e) {
- LOG.debug("Unable to create URI for namespace : {}", namespace);
+ final MapNode mixinNode = Builders.mapBuilder()
+ .withNodeIdentifier(
+ new YangInstanceIdentifier.NodeIdentifier(
+ parentNodeYid.getLastPathArgument().getNodeType()))
+ .build();
+ rwtx.merge(LogicalDatastoreType.CONFIGURATION, parentNodeYid, mixinNode);
+ } else if (parentNodeYid.getLastPathArgument() instanceof YangInstanceIdentifier.AugmentationIdentifier) {
+ // merge empty augmentation node
+ final YangInstanceIdentifier.AugmentationIdentifier augmentationYid =
+ (YangInstanceIdentifier.AugmentationIdentifier) parentNodeYid.getLastPathArgument();
+ final AugmentationNode augmentationNode = Builders.augmentationBuilder()
+ .withNodeIdentifier(augmentationYid).build();
+ rwtx.merge(LogicalDatastoreType.CONFIGURATION, parentNodeYid, augmentationNode);
}
-
- return dataSchemaNode;
}
- private Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException {
- final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(TARGET_KEY);
- // Direct lookup instead of using XmlElement class due to performance
+ private static ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
+ final NodeList elementsByTagName = getElementsByTagName(operationElement, DEFAULT_OPERATION_KEY);
if (elementsByTagName.getLength() == 0) {
- throw new DocumentedException("Missing target element", ErrorType.rpc, ErrorTag.missing_attribute, ErrorSeverity.error);
- } else if (elementsByTagName.getLength() > 1) {
- throw new DocumentedException("Multiple target elements", ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
- } else {
- final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement();
- return Datastore.valueOf(targetChildNode.getName());
- }
- }
-
- private ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException {
- final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(DEFAULT_OPERATION_KEY);
- if(elementsByTagName.getLength() == 0) {
return ModifyAction.MERGE;
- } else if(elementsByTagName.getLength() > 1) {
- throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements",
- ErrorType.rpc, ErrorTag.unknown_attribute, ErrorSeverity.error);
+ } else if (elementsByTagName.getLength() > 1) {
+ throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements", ErrorType.RPC,
+ ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR);
} else {
return ModifyAction.fromXmlValue(elementsByTagName.item(0).getTextContent());
}
}
- private XmlElement getElement(final XmlElement operationElement, final String elementName) throws DocumentedException {
- final Optional<XmlElement> childNode = operationElement.getOnlyChildElementOptionally(elementName);
- if (!childNode.isPresent()) {
- throw new DocumentedException(elementName + " element is missing",
- ErrorType.protocol,
- ErrorTag.missing_element,
- ErrorSeverity.error);
- }
-
- return childNode.get();
- }
-
@Override
protected String getOperationName() {
return OPERATION_NAME;
}
-
}