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