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