251e4dc6bc0f7c55d09b9c169cee97d2d45e6e23
[ovsdb.git] / hwvtepsouthbound / hwvtepsouthbound-impl / src / main / java / org / opendaylight / ovsdb / hwvtepsouthbound / transactions / md / TransactionInvokerImpl.java
1 /*
2  * Copyright (c) 2015, 2017 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 package org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md;
9
10 import com.google.common.util.concurrent.FluentFuture;
11 import com.google.common.util.concurrent.FutureCallback;
12 import com.google.common.util.concurrent.MoreExecutors;
13 import com.google.common.util.concurrent.ThreadFactoryBuilder;
14 import java.util.ArrayList;
15 import java.util.HashMap;
16 import java.util.Iterator;
17 import java.util.List;
18 import java.util.Map;
19 import java.util.concurrent.BlockingQueue;
20 import java.util.concurrent.ExecutorService;
21 import java.util.concurrent.Executors;
22 import java.util.concurrent.LinkedBlockingQueue;
23 import java.util.concurrent.ThreadFactory;
24 import org.checkerframework.checker.lock.qual.GuardedBy;
25 import org.opendaylight.mdsal.binding.api.DataBroker;
26 import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
27 import org.opendaylight.mdsal.binding.api.Transaction;
28 import org.opendaylight.mdsal.binding.api.TransactionChain;
29 import org.opendaylight.mdsal.binding.api.TransactionChainListener;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 /*  TODO:
34  * Copied over as-is from southbound plugin. Good candidate to be common
35  * when refactoring code.
36  */
37 public class TransactionInvokerImpl implements TransactionInvoker,TransactionChainListener, Runnable, AutoCloseable,
38         Thread.UncaughtExceptionHandler {
39     private static final Logger LOG = LoggerFactory.getLogger(TransactionInvokerImpl.class);
40     private static final int QUEUE_SIZE = 10000;
41
42     private final DataBroker db;
43     private final BlockingQueue<TransactionCommand> inputQueue = new LinkedBlockingQueue<>(QUEUE_SIZE);
44     private final BlockingQueue<Transaction> failedTransactionQueue = new LinkedBlockingQueue<>(QUEUE_SIZE);
45     private final ExecutorService executor;
46
47     @GuardedBy("this")
48     private final Map<ReadWriteTransaction,TransactionCommand> transactionToCommand = new HashMap<>();
49     @GuardedBy("this")
50     private final List<ReadWriteTransaction> pendingTransactions = new ArrayList<>();
51
52     private TransactionChain chain;
53     //This is made volatile as it is accessed from uncaught exception handler thread also
54     private volatile ReadWriteTransaction transactionInFlight = null;
55     private Iterator<TransactionCommand> commandIterator = null;
56
57     public TransactionInvokerImpl(final DataBroker db) {
58         this.db = db;
59         this.chain = db.createTransactionChain(this);
60         ThreadFactory threadFact = new ThreadFactoryBuilder().setNameFormat("transaction-invoker-impl-%d")
61                 .setUncaughtExceptionHandler(this).build();
62         executor = Executors.newSingleThreadExecutor(threadFact);
63         //Using the execute method here so that un caught exception handler gets triggered upon exception.
64         //The other way to do it is using submit method and wait on the future to catch any exceptions
65         executor.execute(this);
66     }
67
68     @Override
69     public void invoke(final TransactionCommand command) {
70         // TODO what do we do if queue is full?
71         if (!inputQueue.offer(command)) {
72             LOG.error("inputQueue is full (size: {}) - could not offer {}", inputQueue.size(), command);
73         }
74     }
75
76     @Override
77     public void onTransactionChainFailed(final TransactionChain txChain,
78             final Transaction transaction, final Throwable cause) {
79         offerFailedTransaction(transaction);
80     }
81
82     @Override
83     public void onTransactionChainSuccessful(final TransactionChain txChain) {
84         // NO OP
85     }
86
87     @Override
88     public void run() {
89         while (true) {
90             final List<TransactionCommand> commands;
91             try {
92                 commands = extractCommands();
93             } catch (InterruptedException e) {
94                 LOG.warn("Extracting commands was interrupted.", e);
95                 continue;
96             }
97             commandIterator = commands.iterator();
98             try {
99                 while (commandIterator.hasNext()) {
100                     executeCommand(commandIterator.next());
101                 }
102                 transactionInFlight = null;
103             } catch (IllegalStateException e) {
104                 if (transactionInFlight != null) {
105                     // TODO: This method should distinguish exceptions on which the command should be
106                     // retried from exceptions on which the command should NOT be retried.
107                     // Then it should retry only the commands which should be retried, otherwise
108                     // this method will retry commands which will never be successful forever.
109                     offerFailedTransaction(transactionInFlight);
110                 }
111                 transactionInFlight = null;
112                 LOG.warn("Failed to process an update notification from OVS.", e);
113             }
114         }
115     }
116
117     private synchronized void executeCommand(final TransactionCommand command) {
118         final ReadWriteTransaction transaction = chain.newReadWriteTransaction();
119         transactionInFlight = transaction;
120         recordPendingTransaction(command, transaction);
121         command.execute(transaction);
122         FluentFuture<?> ft = transaction.commit();
123         command.setTransactionResultFuture(ft);
124         ft.addCallback(new FutureCallback<Object>() {
125             @Override
126             public void onSuccess(final Object result) {
127                 forgetSuccessfulTransaction(transaction);
128             }
129
130             @Override
131             public void onFailure(final Throwable throwable) {
132                 // NOOP - handled by failure of transaction chain
133             }
134         }, MoreExecutors.directExecutor());
135     }
136
137     private void offerFailedTransaction(final Transaction transaction) {
138         if (!failedTransactionQueue.offer(transaction)) {
139             LOG.warn("failedTransactionQueue is full (size: {})", failedTransactionQueue.size());
140         }
141     }
142
143     private List<TransactionCommand> extractResubmitCommands() {
144         List<TransactionCommand> commands = new ArrayList<>();
145         synchronized (this) {
146             Transaction transaction = failedTransactionQueue.poll();
147             if (transaction != null) {
148                 int index = pendingTransactions.lastIndexOf(transaction);
149                 //This logic needs to be revisited. Is it ok to resubmit these things again ?
150                 //are these operations idempotent ?
151                 //Does the transaction chain execute n+1th if nth one threw error ?
152                 List<ReadWriteTransaction> transactions =
153                         pendingTransactions.subList(index, pendingTransactions.size() - 1);
154                 for (ReadWriteTransaction tx: transactions) {
155                     commands.add(transactionToCommand.get(tx));
156                 }
157                 resetTransactionQueue();
158             }
159         }
160         if (commandIterator != null) {
161             while (commandIterator.hasNext()) {
162                 commands.add(commandIterator.next());
163             }
164         }
165         return commands;
166     }
167
168     private void resetTransactionQueue() {
169         chain.close();
170         chain = db.createTransactionChain(this);
171         pendingTransactions.clear();
172         transactionToCommand.clear();
173         failedTransactionQueue.clear();
174     }
175
176     synchronized void forgetSuccessfulTransaction(final ReadWriteTransaction transaction) {
177         pendingTransactions.remove(transaction);
178         transactionToCommand.remove(transaction);
179     }
180
181     private synchronized void recordPendingTransaction(final TransactionCommand command,
182             final ReadWriteTransaction transaction) {
183         transactionToCommand.put(transaction, command);
184         pendingTransactions.add(transaction);
185     }
186
187     private List<TransactionCommand> extractCommands() throws InterruptedException {
188         List<TransactionCommand> commands = extractResubmitCommands();
189         if (!commands.isEmpty() && inputQueue.isEmpty()) {
190             //we got some commands to be executed let us not sit and wait on empty queue
191             return commands;
192         }
193         //pull commands from queue if not empty , otherwise wait for commands to be placed in queue.
194         commands.addAll(extractCommandsFromQueue());
195         return commands;
196     }
197
198     private List<TransactionCommand> extractCommandsFromQueue() throws InterruptedException {
199         List<TransactionCommand> result = new ArrayList<>();
200         TransactionCommand command = inputQueue.take();
201         result.add(command);
202         inputQueue.drainTo(result);
203         return result;
204     }
205
206     @Override
207     public void close() throws Exception {
208         this.chain.close();
209         this.executor.shutdown();
210     }
211
212     @Override
213     public void uncaughtException(final Thread thread, final Throwable ex) {
214         LOG.error("Failed to execute hwvtep transact command, re-submitting the transaction again", ex);
215         if (transactionInFlight != null) {
216             offerFailedTransaction(transactionInFlight);
217         }
218         transactionInFlight = null;
219         executor.execute(this);
220     }
221 }