BUG-3604 Ignore empty edits in netconf connector
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / main / java / org / opendaylight / controller / sal / connect / netconf / sal / tx / AbstractWriteTx.java
1 package org.opendaylight.controller.sal.connect.netconf.sal.tx;
2
3 import com.google.common.base.Function;
4 import com.google.common.base.Optional;
5 import com.google.common.base.Preconditions;
6 import com.google.common.util.concurrent.ListenableFuture;
7 import java.util.concurrent.ExecutionException;
8 import java.util.concurrent.TimeUnit;
9 import java.util.concurrent.TimeoutException;
10 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
11 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
12 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
13 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
14 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
15 import org.opendaylight.controller.sal.connect.netconf.util.NetconfBaseOps;
16 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
17 import org.opendaylight.yangtools.yang.common.RpcResult;
18 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
19 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
20 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
21 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
22 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
23 import org.slf4j.Logger;
24 import org.slf4j.LoggerFactory;
25
26 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
27
28     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
29
30     private final long defaultRequestTimeoutMillis;
31     protected final RemoteDeviceId id;
32     protected final NetconfBaseOps netOps;
33     protected final boolean rollbackSupport;
34     // Allow commit to be called only once
35     protected boolean finished = false;
36
37     public AbstractWriteTx(final long requestTimeoutMillis, final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
38         this.defaultRequestTimeoutMillis = requestTimeoutMillis;
39         this.netOps = netOps;
40         this.id = id;
41         this.rollbackSupport = rollbackSupport;
42         init();
43     }
44
45     static boolean isSuccess(final DOMRpcResult result) {
46         return result.getErrors().isEmpty();
47     }
48
49     protected void checkNotFinished() {
50         Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
51     }
52
53     protected boolean isFinished() {
54         return finished;
55     }
56
57     protected void invokeBlocking(final String msg, final Function<NetconfBaseOps, ListenableFuture<DOMRpcResult>> op) throws NetconfDocumentedException {
58         try {
59             final DOMRpcResult compositeNodeRpcResult = op.apply(netOps).get(defaultRequestTimeoutMillis, TimeUnit.MILLISECONDS);
60             if(isSuccess(compositeNodeRpcResult) == false) {
61                 throw new NetconfDocumentedException(id + ": " + msg + " failed: " + compositeNodeRpcResult.getErrors(), NetconfDocumentedException.ErrorType.application,
62                         NetconfDocumentedException.ErrorTag.operation_failed, NetconfDocumentedException.ErrorSeverity.warning);
63             }
64         } catch (final InterruptedException e) {
65             Thread.currentThread().interrupt();
66             throw new RuntimeException(e);
67         } catch (final ExecutionException | TimeoutException e) {
68             throw new NetconfDocumentedException(id + ": " + msg + " failed: " + e.getMessage(), e, NetconfDocumentedException.ErrorType.application,
69                     NetconfDocumentedException.ErrorTag.operation_failed, NetconfDocumentedException.ErrorSeverity.warning);
70         }
71     }
72
73     @Override
74     public synchronized boolean cancel() {
75         if(isFinished()) {
76             return false;
77         }
78
79         finished = true;
80         cleanup();
81         return true;
82     }
83
84     protected abstract void init();
85
86     protected abstract void cleanup();
87
88     @Override
89     public Object getIdentifier() {
90         return this;
91     }
92
93     @Override
94     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
95         checkEditable(store);
96
97         // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
98         if(containsOnlyNonVisibleData(path, data)) {
99             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
100             return;
101         }
102
103         try {
104             editConfig(
105                     netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.of(ModifyAction.REPLACE), path), Optional.of(ModifyAction.NONE));
106         } catch (final NetconfDocumentedException e) {
107             handleEditException(path, data, e, "putting");
108         }
109     }
110
111     protected abstract void handleEditException(YangInstanceIdentifier path, NormalizedNode<?, ?> data, NetconfDocumentedException e, String editType);
112     protected abstract void handleDeleteException(YangInstanceIdentifier path, NetconfDocumentedException e);
113
114     @Override
115     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
116         checkEditable(store);
117
118         // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
119         if (containsOnlyNonVisibleData(path, data)) {
120             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
121             return;
122         }
123
124         try {
125             editConfig(
126                     netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.<ModifyAction>absent(), path), Optional.<ModifyAction>absent());
127         } catch (final NetconfDocumentedException e) {
128             handleEditException(path, data, e, "merge");
129         }
130     }
131
132     /**
133      * Check whether the data to be written consists only from mixins
134      */
135     private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
136         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
137         // any other mixin nodes are contained by a "regular" node thus visible when serialized
138         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
139     }
140
141     @Override
142     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
143         checkEditable(store);
144
145         try {
146             editConfig(
147                     netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(), Optional.of(ModifyAction.DELETE), path), Optional.of(ModifyAction.NONE));
148         } catch (final NetconfDocumentedException e) {
149             handleDeleteException(path, e);
150         }
151     }
152
153     @Override
154     public final ListenableFuture<RpcResult<TransactionStatus>> commit() {
155         checkNotFinished();
156         finished = true;
157
158         return performCommit();
159     }
160
161     protected abstract ListenableFuture<RpcResult<TransactionStatus>> performCommit();
162
163     private void checkEditable(final LogicalDatastoreType store) {
164         checkNotFinished();
165         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store);
166     }
167
168     protected abstract void editConfig(DataContainerChild<?, ?> editStructure, Optional<ModifyAction> defaultOperation) throws NetconfDocumentedException;
169 }