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