2 * Copyright (c) 2015, 2017 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.ovsdb.hwvtepsouthbound.transactions.md;
10 import com.google.common.util.concurrent.FutureCallback;
11 import com.google.common.util.concurrent.Futures;
12 import com.google.common.util.concurrent.ListenableFuture;
13 import com.google.common.util.concurrent.MoreExecutors;
14 import com.google.common.util.concurrent.ThreadFactoryBuilder;
15 import java.util.ArrayList;
16 import java.util.HashMap;
17 import java.util.Iterator;
18 import java.util.List;
20 import java.util.concurrent.BlockingQueue;
21 import java.util.concurrent.ExecutorService;
22 import java.util.concurrent.Executors;
23 import java.util.concurrent.LinkedBlockingQueue;
24 import java.util.concurrent.ThreadFactory;
25 import org.checkerframework.checker.lock.qual.GuardedBy;
26 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
27 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
28 import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
29 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
30 import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
31 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
36 * Copied over as-is from southbound plugin. Good candidate to be common
37 * when refactoring code.
39 public class TransactionInvokerImpl implements TransactionInvoker,TransactionChainListener, Runnable, AutoCloseable,
40 Thread.UncaughtExceptionHandler {
41 private static final Logger LOG = LoggerFactory.getLogger(TransactionInvokerImpl.class);
42 private static final int QUEUE_SIZE = 10000;
44 private final DataBroker db;
45 private final BlockingQueue<TransactionCommand> inputQueue = new LinkedBlockingQueue<>(QUEUE_SIZE);
46 private final BlockingQueue<AsyncTransaction<?, ?>> failedTransactionQueue = new LinkedBlockingQueue<>(QUEUE_SIZE);
47 private final ExecutorService executor;
50 private final Map<ReadWriteTransaction,TransactionCommand> transactionToCommand = new HashMap<>();
52 private final List<ReadWriteTransaction> pendingTransactions = new ArrayList<>();
54 private BindingTransactionChain chain;
55 //This is made volatile as it is accessed from uncaught exception handler thread also
56 private volatile ReadWriteTransaction transactionInFlight = null;
57 private Iterator<TransactionCommand> commandIterator = null;
59 public TransactionInvokerImpl(final DataBroker db) {
61 this.chain = db.createTransactionChain(this);
62 ThreadFactory threadFact = new ThreadFactoryBuilder().setNameFormat("transaction-invoker-impl-%d")
63 .setUncaughtExceptionHandler(this).build();
64 executor = Executors.newSingleThreadExecutor(threadFact);
65 //Using the execute method here so that un caught exception handler gets triggered upon exception.
66 //The other way to do it is using submit method and wait on the future to catch any exceptions
67 executor.execute(this);
71 public void invoke(final TransactionCommand command) {
72 // TODO what do we do if queue is full?
73 if (!inputQueue.offer(command)) {
74 LOG.error("inputQueue is full (size: {}) - could not offer {}", inputQueue.size(), command);
79 public void onTransactionChainFailed(final TransactionChain<?, ?> txChain,
80 final AsyncTransaction<?, ?> transaction, final Throwable cause) {
81 offerFailedTransaction(transaction);
85 public void onTransactionChainSuccessful(final TransactionChain<?, ?> txChain) {
92 final List<TransactionCommand> commands;
94 commands = extractCommands();
95 } catch (InterruptedException e) {
96 LOG.warn("Extracting commands was interrupted.", e);
99 commandIterator = commands.iterator();
101 while (commandIterator.hasNext()) {
102 executeCommand(commandIterator.next());
104 transactionInFlight = null;
105 } catch (IllegalStateException e) {
106 if (transactionInFlight != null) {
107 // TODO: This method should distinguish exceptions on which the command should be
108 // retried from exceptions on which the command should NOT be retried.
109 // Then it should retry only the commands which should be retried, otherwise
110 // this method will retry commands which will never be successful forever.
111 offerFailedTransaction(transactionInFlight);
113 transactionInFlight = null;
114 LOG.warn("Failed to process an update notification from OVS.", e);
119 private synchronized void executeCommand(final TransactionCommand command) {
120 final ReadWriteTransaction transaction = chain.newReadWriteTransaction();
121 transactionInFlight = transaction;
122 recordPendingTransaction(command, transaction);
123 command.execute(transaction);
124 ListenableFuture<Void> ft = transaction.submit();
125 command.setTransactionResultFuture(ft);
126 Futures.addCallback(ft, new FutureCallback<Void>() {
128 public void onSuccess(final Void result) {
129 forgetSuccessfulTransaction(transaction);
133 public void onFailure(final Throwable throwable) {
134 // NOOP - handled by failure of transaction chain
136 }, MoreExecutors.directExecutor());
139 private void offerFailedTransaction(final AsyncTransaction<?, ?> transaction) {
140 if (!failedTransactionQueue.offer(transaction)) {
141 LOG.warn("failedTransactionQueue is full (size: {})", failedTransactionQueue.size());
145 private List<TransactionCommand> extractResubmitCommands() {
146 List<TransactionCommand> commands = new ArrayList<>();
147 synchronized (this) {
148 AsyncTransaction<?, ?> transaction = failedTransactionQueue.poll();
149 if (transaction != null) {
150 int index = pendingTransactions.lastIndexOf(transaction);
151 //This logic needs to be revisited. Is it ok to resubmit these things again ?
152 //are these operations idempotent ?
153 //Does the transaction chain execute n+1th if nth one threw error ?
154 List<ReadWriteTransaction> transactions =
155 pendingTransactions.subList(index, pendingTransactions.size() - 1);
156 for (ReadWriteTransaction tx: transactions) {
157 commands.add(transactionToCommand.get(tx));
159 resetTransactionQueue();
162 if (commandIterator != null) {
163 while (commandIterator.hasNext()) {
164 commands.add(commandIterator.next());
170 private void resetTransactionQueue() {
172 chain = db.createTransactionChain(this);
173 pendingTransactions.clear();
174 transactionToCommand.clear();
175 failedTransactionQueue.clear();
178 synchronized void forgetSuccessfulTransaction(final ReadWriteTransaction transaction) {
179 pendingTransactions.remove(transaction);
180 transactionToCommand.remove(transaction);
183 private synchronized void recordPendingTransaction(final TransactionCommand command,
184 final ReadWriteTransaction transaction) {
185 transactionToCommand.put(transaction, command);
186 pendingTransactions.add(transaction);
189 private List<TransactionCommand> extractCommands() throws InterruptedException {
190 List<TransactionCommand> commands = extractResubmitCommands();
191 if (!commands.isEmpty() && inputQueue.isEmpty()) {
192 //we got some commands to be executed let us not sit and wait on empty queue
195 //pull commands from queue if not empty , otherwise wait for commands to be placed in queue.
196 commands.addAll(extractCommandsFromQueue());
200 private List<TransactionCommand> extractCommandsFromQueue() throws InterruptedException {
201 List<TransactionCommand> result = new ArrayList<>();
202 TransactionCommand command = inputQueue.take();
204 inputQueue.drainTo(result);
209 public void close() throws Exception {
211 this.executor.shutdown();
215 public void uncaughtException(final Thread thread, final Throwable ex) {
216 LOG.error("Failed to execute hwvtep transact command, re-submitting the transaction again", ex);
217 if (transactionInFlight != null) {
218 offerFailedTransaction(transactionInFlight);
220 transactionInFlight = null;
221 executor.execute(this);