6fb91d21f4e7e3dec55bfd404c03c2119740d43e
[transportpce.git] / common / src / main / java / org / opendaylight / transportpce / common / device / DeviceTransaction.java
1 /*
2  * Copyright © 2017 Orange, 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.transportpce.common.device;
10
11 import com.google.common.util.concurrent.FluentFuture;
12 import com.google.common.util.concurrent.FutureCallback;
13 import com.google.common.util.concurrent.ListenableFuture;
14 import java.util.Optional;
15 import java.util.concurrent.CountDownLatch;
16 import java.util.concurrent.Executors;
17 import java.util.concurrent.ScheduledExecutorService;
18 import java.util.concurrent.TimeUnit;
19 import java.util.concurrent.atomic.AtomicBoolean;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
22 import org.opendaylight.mdsal.common.api.CommitInfo;
23 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
24 import org.opendaylight.yangtools.util.concurrent.FluentFutures;
25 import org.opendaylight.yangtools.yang.binding.DataObject;
26 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * Represents read-write transaction on netconf device.
32  * This transaction can be obtained by {@link DeviceTransactionManager}.
33  *
34  * <p>
35  * WARNING: Only one transaction can be opened at the same time on device!
36  * It's important to close (cancel/submit) transaction when work is done with it
37  * (so others can access the device).
38  * </p>
39  */
40 public class DeviceTransaction {
41
42     private static final Logger LOG = LoggerFactory.getLogger(DeviceTransaction.class);
43
44     private final ReadWriteTransaction rwTx;
45     private final CountDownLatch deviceLock;
46     private final ScheduledExecutorService scheduledExecutorService;
47     private final AtomicBoolean wasSubmittedOrCancelled = new AtomicBoolean(false);
48
49     DeviceTransaction(ReadWriteTransaction rwTx, CountDownLatch deviceLock) {
50         this.rwTx = rwTx;
51         this.deviceLock = deviceLock;
52         this.scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
53         LOG.debug("Device transaction created. Lock: {}", deviceLock);
54     }
55
56     public <T extends DataObject> ListenableFuture<Optional<T>> read(LogicalDatastoreType store,
57             InstanceIdentifier<T> path) {
58         return rwTx.read(store, path);
59     }
60
61     public <T extends DataObject> void put(LogicalDatastoreType store, InstanceIdentifier<T> path, T data) {
62         rwTx.put(store, path, data);
63     }
64
65     @Deprecated
66     public <T extends DataObject> void put(LogicalDatastoreType store, InstanceIdentifier<T> path, T data,
67             boolean createMissingParents) {
68         rwTx.put(store, path, data, createMissingParents);
69     }
70
71     public <T extends DataObject> void merge(LogicalDatastoreType store, InstanceIdentifier<T> path, T data) {
72         rwTx.merge(store, path, data);
73     }
74
75     @Deprecated
76     public <T extends DataObject> void merge(LogicalDatastoreType store, InstanceIdentifier<T> path, T data,
77             boolean createMissingParents) {
78         rwTx.merge(store, path, data, createMissingParents);
79     }
80
81     public void delete(LogicalDatastoreType store, InstanceIdentifier<?> path) {
82         rwTx.delete(store, path);
83     }
84
85     /**
86      * Cancels transaction and unlocks it.
87      * @return true if cancel was successful.
88      */
89     public boolean cancel() {
90         if (wasSubmittedOrCancelled.get()) {
91             LOG.warn("Transaction was already submitted or canceled!");
92             return false;
93         }
94
95         LOG.debug("Transaction cancelled. Lock: {}", deviceLock);
96         wasSubmittedOrCancelled.set(true);
97         afterClose();
98         return rwTx.cancel();
99     }
100
101     /**
102      * Submits data changed in transaction to device with defined timeout to commit. If time from timeout runs out then
103      * the commit will be interrupted and the device will be unlocked.
104      *
105      * @param timeout a timeout
106      * @param timeUnit a time unit
107      * @return FluentFuture which indicates when the commit is completed.
108      */
109     public FluentFuture<? extends @NonNull CommitInfo> commit(long timeout, TimeUnit timeUnit) {
110         if (wasSubmittedOrCancelled.get()) {
111             String msg = "Transaction was already submitted or canceled!";
112             LOG.error(msg);
113             return FluentFutures.immediateFailedFluentFuture(new IllegalStateException(msg));
114         }
115
116         LOG.debug("Transaction committed. Lock: {}", deviceLock);
117         wasSubmittedOrCancelled.set(true);
118         FluentFuture<? extends @NonNull CommitInfo> future =
119                 rwTx.commit().withTimeout(timeout, timeUnit, scheduledExecutorService);
120
121         future.addCallback(new FutureCallback<CommitInfo>() {
122             @Override
123             public void onSuccess(CommitInfo result) {
124                 LOG.debug("Transaction with lock {} successfully committed: {}", deviceLock, result);
125                 afterClose();
126             }
127
128             @Override
129             public void onFailure(Throwable throwable) {
130                 LOG.error("Device transaction commit failed or submit took longer than {} {}! Unlocking device.",
131                     timeout, timeUnit, throwable);
132                 afterClose();
133             }
134         }, scheduledExecutorService);
135         return future;
136     }
137
138     /**
139      * Returns state of transaction.
140      * @return true if transaction was closed; otherwise false
141      */
142     public AtomicBoolean wasSubmittedOrCancelled() {
143         return wasSubmittedOrCancelled;
144     }
145
146     private void afterClose() {
147         scheduledExecutorService.shutdown();
148         deviceLock.countDown();
149     }
150 }