Stun client transaction re-transmission based on ScheduledThreadPoolExecutor (#153)

* Hide Runnable interface in StunClientTransaction class.

* Use CustomizableThreadFactory to give custom names to threads.

* Extracted retransmission logic into separate class.

* Re-implement Retransmitter with ScheduledThreadPoolExecutor.

* Fixed retransmissionCounter increment.

* Directly call logger fine methods instead overload with Level.
This commit is contained in:
Yury Yaroshevich 2018-10-31 20:53:41 +03:00 committed by bbaldino
parent 3fe34dcb97
commit 513fb588d6

View File

@ -19,11 +19,12 @@ package org.ice4j.stack;
import java.io.*;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.message.*;
import org.ice4j.util.*;
/**
* The {@code StunClientTransaction} class retransmits requests as specified by
@ -46,13 +47,12 @@ import org.ice4j.message.*;
* @author Lyubomir Marinov
*/
public class StunClientTransaction
implements Runnable
{
/**
* Our class logger.
*/
private static final Logger logger
= Logger.getLogger(StunClientTransaction.class.getName());
private static final java.util.logging.Logger logger
= java.util.logging.Logger.getLogger(StunClientTransaction.class.getName());
/**
* The number of times to retransmit a request if no explicit value has been
@ -77,40 +77,20 @@ public class StunClientTransaction
* The pool of <tt>Thread</tt>s which retransmit
* <tt>StunClientTransaction</tt>s.
*/
private static final ExecutorService retransmissionThreadPool
= Executors.newCachedThreadPool(
new ThreadFactory()
{
/**
* The default {@code ThreadFactory} implementation which is
* augmented by this instance to create daemon
* {@code Thread}s.
*/
private final ThreadFactory defaultThreadFactory
= Executors.defaultThreadFactory();
private static final ScheduledExecutorService retransmissionThreadPool;
@Override
public Thread newThread(Runnable r)
{
Thread t = defaultThreadFactory.newThread(r);
static {
CustomizableThreadFactory threadFactory
= new CustomizableThreadFactory("ice4j.StunClientTransaction-", true);
if (t != null)
{
t.setDaemon(true);
// Additionally, make it known through the name of
// the Thread that it is associated with the
// StunClientTransaction class for
// debugging/informational purposes.
String name = t.getName();
if (name == null)
name = "";
t.setName("StunClientTransaction-" + name);
}
return t;
}
});
final ScheduledThreadPoolExecutor terminationExecutor
= new ScheduledThreadPoolExecutor(0, threadFactory);
terminationExecutor.setKeepAliveTime(60, TimeUnit.SECONDS);
terminationExecutor.setRemoveOnCancelPolicy(true);
retransmissionThreadPool
= Executors.unconfigurableScheduledExecutorService(
terminationExecutor);
}
/**
* Maximum number of retransmissions. Once this number is reached and if no
@ -166,25 +146,12 @@ public class StunClientTransaction
/**
* Determines whether the transaction is active or not.
*/
private boolean cancelled = false;
private final AtomicBoolean cancelled = new AtomicBoolean(false);
/**
* The <tt>Lock</tt> which synchronizes the access to the state of this
* instance. Introduced along with {@link #lockCondition} in order to allow
* the invocation of {@link #cancel(boolean)} without a requirement to
* acquire the synchronization root. Otherwise, callers of
* <tt>cancel(boolean)</tt> may (and have be reported multiple times to)
* fall into a deadlock merely because they want to cancel this
* <tt>StunClientTransaction</tt>.
* A transaction request retransmitter
*/
private final Lock lock = new ReentrantLock();
/**
* The <tt>Condition</tt> of {@link #lock} which this instance uses to wait
* for either the next retransmission interval or the cancellation of this
* <tt>StunClientTransaction</tt>.
*/
private final Condition lockCondition = lock.newCondition();
private final Retransmitter retransmitter = new Retransmitter();
/**
* Creates a client transaction.
@ -256,102 +223,6 @@ public class StunClientTransaction
}
}
/**
* Implements the retransmissions algorithm. Retransmits the request
* starting with an interval of 100ms, doubling every retransmit until the
* interval reaches 1.6s. Retransmissions continue with intervals of 1.6s
* until a response is received, or a total of 7 requests have been sent.
* If no response is received by 1.6 seconds after the last request has been
* sent, we consider the transaction to have failed.
* <p>
* The method acquires {@link #lock} and invokes {@link #runLocked()}.
* </p>
*/
@Override
public void run()
{
lock.lock();
try
{
runLocked();
}
finally
{
lock.unlock();
}
}
/**
* Implements the retransmissions algorithm. Retransmits the request
* starting with an interval of 100ms, doubling every retransmit until the
* interval reaches 1.6s. Retransmissions continue with intervals of 1.6s
* until a response is received, or a total of 7 requests have been sent.
* If no response is received by 1.6 seconds after the last request has been
* sent, we consider the transaction to have failed.
* <p>
* The method assumes that the current thread has already acquired
* {@link #lock}.
* </p>
*/
private void runLocked()
{
// Indicates how many times we have retransmitted so far.
int retransmissionCounter = 0;
// How much did we wait after our last retransmission?
int nextWaitInterval = originalWaitInterval;
for (retransmissionCounter = 0;
retransmissionCounter < maxRetransmissions;
retransmissionCounter ++)
{
waitFor(nextWaitInterval);
//did someone tell us to get lost?
if(cancelled)
return;
int curWaitInterval = nextWaitInterval;
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
try
{
logger.fine(
"retrying STUN tid " + transactionID + " from "
+ localAddress + " to " + requestDestination
+ " waited " + curWaitInterval + " ms retrans "
+ (retransmissionCounter + 1) + " of "
+ maxRetransmissions);
sendRequest0();
}
catch (Exception ex)
{
//I wonder whether we should notify anyone that a retransmission
// has failed
logger.log(
Level.INFO,
"A client tran retransmission failed",
ex);
}
}
//before stating that a transaction has timeout-ed we should first wait
//for a reception of the response
if(nextWaitInterval < maxWaitInterval)
nextWaitInterval *= 2;
waitFor(nextWaitInterval);
if(cancelled)
return;
stackCallback.removeClientTransaction(this);
responseCollector.processTimeout(
new StunTimeoutEvent(
stackCallback,
this.request, getLocalAddress(), transactionID));
}
/**
* Sends the request and schedules the first retransmission for after
* {@link #originalWaitInterval} and thus starts the retransmission
@ -371,7 +242,7 @@ public class StunClientTransaction
+ localAddress + " to " + requestDestination);
sendRequest0();
retransmissionThreadPool.execute(this);
this.retransmitter.schedule();
}
/**
@ -385,7 +256,7 @@ public class StunClientTransaction
private void sendRequest0()
throws IllegalArgumentException, IOException
{
if(cancelled)
if (cancelled.get())
{
logger.finer("Trying to resend a cancelled transaction.");
}
@ -408,74 +279,18 @@ public class StunClientTransaction
return this.request;
}
/**
* Waits until next retransmission is due or until the transaction is
* cancelled (whichever comes first).
*
* @param millis the number of milliseconds to wait for.
*/
void waitFor(long millis)
{
lock.lock();
try
{
lockCondition.await(millis, TimeUnit.MILLISECONDS);
}
catch (InterruptedException ex)
{
throw new RuntimeException(ex);
}
finally
{
lock.unlock();
}
}
/**
* Cancels the transaction. Once this method is called the transaction is
* considered terminated and will stop retransmissions.
*
* @param waitForResponse indicates whether we should wait for the current
* RTO to expire before ending the transaction or immediately terminate.
*/
void cancel(boolean waitForResponse)
{
// XXX The cancelled field is initialized to false and then the one and
// only write access to it is here to set it to true. The rest of the
// code just checks whether it has become true. Consequently, there
// shouldn't be a problem if the set is outside a synchronized block.
// However, it being outside a synchronized block will decrease the risk
// of deadlocks.
cancelled = true;
if(!waitForResponse)
{
// Try to interrupt #waitFor(long) if possible. But don't risk a
// deadlock. It is not a problem if it is not possible to interrupt
// #waitFor(long) here because it will complete in finite time and
// this StunClientTransaction will eventually notice that it has
// been cancelled.
if (lock.tryLock())
{
try
{
lockCondition.signal();
}
finally
{
lock.unlock();
}
}
}
}
/**
* Cancels the transaction. Once this method is called the transaction is
* considered terminated and will stop retransmissions.
*/
void cancel()
{
cancel(false);
// The cancelled field is initialized to false and then the one and
// only write access to it is here to set it to true. The rest of the
// code just checks whether it has become true.
cancelled.set(true);
this.retransmitter.cancel();
}
/**
@ -486,27 +301,21 @@ public class StunClientTransaction
*/
public void handleResponse(StunMessageEvent evt)
{
lock.lock();
try
{
TransactionID transactionID = getTransactionID();
TransactionID transactionID = getTransactionID();
logger.log(Level.FINE, "handleResponse tid " + transactionID);
if(!Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE))
cancel();
responseCollector.processResponse(
new StunResponseEvent(
stackCallback,
evt.getRawMessage(),
(Response) evt.getMessage(),
request,
transactionID));
}
finally
logger.fine("handleResponse tid " + transactionID);
if(!Boolean.getBoolean(StackProperties.KEEP_CRANS_AFTER_A_RESPONSE))
{
lock.unlock();
cancel();
}
responseCollector.processResponse(
new StunResponseEvent(
stackCallback,
evt.getRawMessage(),
(Response) evt.getMessage(),
request,
transactionID));
}
/**
@ -608,4 +417,152 @@ public class StunClientTransaction
{
return requestDestination;
}
/**
* Implements the retransmissions algorithm. Retransmits the request
* starting with an interval of 100ms, doubling every retransmit until the
* interval reaches 1.6s. Retransmissions continue with intervals of 1.6s
* until a response is received, or a total of 7 requests have been sent.
* If no response is received by 1.6 seconds after the last request has been
* sent, we consider the transaction to have failed.
*/
private final class Retransmitter
{
/**
* Current number of retransmission attempts
*/
private int retransmissionCounter = 0;
/**
* Delay before attempting next retransmission
*/
private int nextRetransmissionDelay = originalWaitInterval;
/**
* Currently scheduled retransmission task
*/
private ScheduledFuture<?> retransmissionFuture;
/**
* The scheduled runnable that perform retransmit attempt
*/
private final Runnable retransmissionAttempt = new Runnable()
{
@Override
public void run()
{
if (cancelled.get())
{
return;
}
retransmissionCounter++;
int curWaitInterval = nextRetransmissionDelay;
nextRetransmissionDelay
= Math.min(maxWaitInterval, 2 * nextRetransmissionDelay);
try
{
logger.fine(
"retrying STUN tid " + transactionID + " from "
+ localAddress + " to " + requestDestination
+ " waited " + curWaitInterval + " ms retrans "
+ retransmissionCounter + " of "
+ maxRetransmissions);
sendRequest0();
}
catch (Exception ex)
{
//I wonder whether we should notify anyone that a retransmission
// has failed
logger.log(
Level.INFO,
"A client tran retransmission failed",
ex);
}
if(!cancelled.get())
{
reschedule();
}
}
private void reschedule()
{
if (retransmissionCounter < maxRetransmissions)
{
retransmissionFuture = retransmissionThreadPool.schedule(
retransmissionAttempt,
nextRetransmissionDelay,
TimeUnit.MILLISECONDS);
}
else
{
// before stating that a transaction has timeout-ed we
// should first wait for a reception of the response
nextRetransmissionDelay =
Math.min(maxWaitInterval, 2* nextRetransmissionDelay);
retransmissionFuture = retransmissionThreadPool.schedule(
transactionTimedOut,
nextRetransmissionDelay,
TimeUnit.MILLISECONDS);
}
}
};
/**
* Scheduled runnable to time-out STUN transaction
*/
private final Runnable transactionTimedOut = new Runnable()
{
@Override
public void run()
{
if (cancelled.get())
{
return;
}
stackCallback.removeClientTransaction(
StunClientTransaction.this);
responseCollector.processTimeout(
new StunTimeoutEvent(
stackCallback,
getRequest(), getLocalAddress(), getTransactionID()));
}
};
/**
* Schedules STUN transaction retransmission
*/
void schedule()
{
if (retransmissionFuture != null)
{
return;
}
retransmissionFuture = retransmissionThreadPool.schedule(
retransmissionAttempt,
nextRetransmissionDelay,
TimeUnit.MILLISECONDS);
}
/**
* Cancels the transaction. Once this method is called the transaction
* is considered terminated and will stop retransmissions.
*/
void cancel()
{
final ScheduledFuture<?> retransmissionFuture =
this.retransmissionFuture;
if (retransmissionFuture != null)
{
retransmissionFuture.cancel(true);
}
}
}
}