Merge "Remove use of controller/checkstyle.xml (use odl-parent's new Checkstyle)"
[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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.Lists;
14 import com.google.common.util.concurrent.FutureCallback;
15 import com.google.common.util.concurrent.Futures;
16 import com.google.common.util.concurrent.ListenableFuture;
17 import com.google.common.util.concurrent.SettableFuture;
18 import java.util.List;
19 import org.opendaylight.controller.config.util.xml.DocumentedException;
20 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
21 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
22 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
23 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
24 import org.opendaylight.netconf.api.NetconfDocumentedException;
25 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfBaseOps;
26 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
27 import org.opendaylight.yangtools.yang.common.RpcResult;
28 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
29 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
32 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 public abstract class AbstractWriteTx implements DOMDataWriteTransaction {
38
39     private static final Logger LOG  = LoggerFactory.getLogger(AbstractWriteTx.class);
40
41     protected final RemoteDeviceId id;
42     protected final NetconfBaseOps netOps;
43     protected final boolean rollbackSupport;
44     protected final List<ListenableFuture<DOMRpcResult>> resultsFutures;
45     // Allow commit to be called only once
46     protected boolean finished = false;
47
48     public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) {
49         this.netOps = netOps;
50         this.id = id;
51         this.rollbackSupport = rollbackSupport;
52         this.resultsFutures = Lists.newArrayList();
53         init();
54     }
55
56     protected static boolean isSuccess(final DOMRpcResult result) {
57         return result.getErrors().isEmpty();
58     }
59
60     protected void checkNotFinished() {
61         Preconditions.checkState(!isFinished(), "%s: Transaction %s already finished", id, getIdentifier());
62     }
63
64     protected boolean isFinished() {
65         return finished;
66     }
67
68     @Override
69     public synchronized boolean cancel() {
70         if(isFinished()) {
71             return false;
72         }
73
74         finished = true;
75         cleanup();
76         return true;
77     }
78
79     protected abstract void init();
80
81     protected abstract void cleanup();
82
83     @Override
84     public Object getIdentifier() {
85         return this;
86     }
87
88     @Override
89     public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
90         checkEditable(store);
91
92         // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
93         if(containsOnlyNonVisibleData(path, data)) {
94             LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data);
95             return;
96         }
97
98         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.of(ModifyAction.REPLACE), path);
99         editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put");
100     }
101
102     @Override
103     public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
104         checkEditable(store);
105
106         // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc
107         if (containsOnlyNonVisibleData(path, data)) {
108             LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data);
109             return;
110         }
111
112         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>fromNullable(data), Optional.<ModifyAction>absent(), path);
113         editConfig(path, Optional.fromNullable(data), editStructure, Optional.<ModifyAction>absent(), "merge");
114     }
115
116     /**
117      * Check whether the data to be written consists only from mixins
118      */
119     private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
120         // There's only one such case:top level list (pathArguments == 1 && data is Mixin)
121         // any other mixin nodes are contained by a "regular" node thus visible when serialized
122         return path.getPathArguments().size() == 1 && data instanceof MixinNode;
123     }
124
125     @Override
126     public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
127         checkEditable(store);
128         final DataContainerChild<?, ?> editStructure = netOps.createEditConfigStrcture(Optional.<NormalizedNode<?, ?>>absent(), Optional.of(ModifyAction.DELETE), path);
129         editConfig(path, Optional.<NormalizedNode<?, ?>>absent(), editStructure, Optional.of(ModifyAction.NONE), "delete");
130     }
131
132     @Override
133     public final ListenableFuture<RpcResult<TransactionStatus>> commit() {
134         checkNotFinished();
135         finished = true;
136
137         return performCommit();
138     }
139
140     protected abstract ListenableFuture<RpcResult<TransactionStatus>> performCommit();
141
142     private void checkEditable(final LogicalDatastoreType store) {
143         checkNotFinished();
144         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store);
145     }
146
147     protected abstract void editConfig(final YangInstanceIdentifier path, final Optional<NormalizedNode<?, ?>> data, final DataContainerChild<?, ?> editStructure, final Optional<ModifyAction> defaultOperation, final String operation);
148
149     protected ListenableFuture<RpcResult<TransactionStatus>> resultsToTxStatus() {
150         final SettableFuture<RpcResult<TransactionStatus>> transformed = SettableFuture.create();
151
152         Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback<List<DOMRpcResult>>() {
153             @Override
154             public void onSuccess(final List<DOMRpcResult> domRpcResults) {
155                 domRpcResults.forEach(domRpcResult -> {
156                     if(!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
157                         NetconfDocumentedException exception =
158                                 new NetconfDocumentedException(id + ":RPC during tx failed",
159                                         DocumentedException.ErrorType.application,
160                                         DocumentedException.ErrorTag.operation_failed,
161                                         DocumentedException.ErrorSeverity.error);
162                         transformed.setException(exception);
163                     }
164                 });
165
166                 if(!transformed.isDone()) {
167                     transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
168                 }
169             }
170
171             @Override
172             public void onFailure(Throwable throwable) {
173                 NetconfDocumentedException exception =
174                         new NetconfDocumentedException(
175                                 new DocumentedException(id + ":RPC during tx returned an exception",
176                                         new Exception(throwable),
177                                         DocumentedException.ErrorType.application,
178                                         DocumentedException.ErrorTag.operation_failed,
179                                         DocumentedException.ErrorSeverity.error) );
180                 transformed.setException(exception);
181             }
182         });
183
184         return transformed;
185     }
186 }