Cleans up the background Threads associated with TURN candidates more explicitly/aggressively/thoroughly in an attempt to mitigate a leak of such reported by Enrico Marocco.

This commit is contained in:
lubomir.marinov 2014-04-29 20:28:28 +00:00
parent 6370fbca8f
commit b8b11d13b5
6 changed files with 288 additions and 135 deletions

View File

@ -320,6 +320,7 @@ public abstract class LocalCandidate
* *
* @return local ufrag * @return local ufrag
*/ */
@Override
public String getUfrag() public String getUfrag()
{ {
return ufrag; return ufrag;
@ -374,6 +375,7 @@ public abstract class LocalCandidate
* - null for a peer reflexive candidate : there is no way to know the * - null for a peer reflexive candidate : there is no way to know the
* related address. * related address.
*/ */
@Override
protected LocalCandidate findRelatedCandidate( protected LocalCandidate findRelatedCandidate(
TransportAddress relatedAddress) TransportAddress relatedAddress)
{ {

View File

@ -100,6 +100,7 @@ public class ServerReflexiveCandidate
* <tt>Candidate</tt> * <tt>Candidate</tt>
* @see LocalCandidate#getIceSocketWrapper() * @see LocalCandidate#getIceSocketWrapper()
*/ */
@Override
public IceSocketWrapper getIceSocketWrapper() public IceSocketWrapper getIceSocketWrapper()
{ {
return getBase().getIceSocketWrapper(); return getBase().getIceSocketWrapper();
@ -111,13 +112,12 @@ public class ServerReflexiveCandidate
* <tt>LocalCandidate</tt> is closed only if it is not the <tt>socket</tt> * <tt>LocalCandidate</tt> is closed only if it is not the <tt>socket</tt>
* of the <tt>base</tt> of this <tt>LocalCandidate</tt>. * of the <tt>base</tt> of this <tt>LocalCandidate</tt>.
*/ */
protected void free() @Override
public void free()
{ {
super.free(); super.free();
if(stunHarvest != null) if(stunHarvest != null)
{
stunHarvest.close(); stunHarvest.close();
}
} }
} }

View File

@ -72,10 +72,8 @@ public class GoogleTurnCandidateHarvester
protected GoogleTurnCandidateHarvest createHarvest( protected GoogleTurnCandidateHarvest createHarvest(
HostCandidate hostCandidate) HostCandidate hostCandidate)
{ {
return new GoogleTurnCandidateHarvest( return
this, new GoogleTurnCandidateHarvest(this, hostCandidate, getPassword());
hostCandidate,
this.password);
} }
/** /**

View File

@ -105,10 +105,8 @@ public class GoogleTurnSSLCandidateHarvester
protected GoogleTurnCandidateHarvest createHarvest( protected GoogleTurnCandidateHarvest createHarvest(
HostCandidate hostCandidate) HostCandidate hostCandidate)
{ {
return new GoogleTurnCandidateHarvest( return
this, new GoogleTurnCandidateHarvest(this, hostCandidate, getPassword());
hostCandidate,
this.getPassword());
} }
/** /**

View File

@ -8,6 +8,7 @@
package org.ice4j.ice.harvest; package org.ice4j.ice.harvest;
import java.io.*; import java.io.*;
import java.lang.ref.*;
import java.util.*; import java.util.*;
import java.util.logging.*; import java.util.logging.*;
@ -121,12 +122,12 @@ public class StunCandidateHarvest
private Thread sendKeepAliveMessageThread; private Thread sendKeepAliveMessageThread;
/** /**
* The time stamp of the last call to {@link #sendKeepAliveMessage()} which * The time (stamp) in milliseconds of the last call to
* completed without throwing an exception (note: it doesn't mean that the * {@link #sendKeepAliveMessage()} which completed without throwing an
* keep-alive message was a STUN <tt>Request</tt> and it received a success * exception. <b>Note</b>: It doesn't mean that the keep-alive message was a
* STUN <tt>Response</tt>). * STUN <tt>Request</tt> and it received a success STUN <tt>Response</tt>.
*/ */
private long sendKeepAliveMessageTimeStamp = -1; private long sendKeepAliveMessageTime = -1;
/** /**
* Initializes a new <tt>StunCandidateHarvest</tt> which is to represent the * Initializes a new <tt>StunCandidateHarvest</tt> which is to represent the
@ -155,18 +156,26 @@ public class StunCandidateHarvest
* @param candidate the <tt>LocalCandidate</tt> to be added to the list of * @param candidate the <tt>LocalCandidate</tt> to be added to the list of
* <tt>LocalCandidate</tt>s harvested for {@link #hostCandidate} by this * <tt>LocalCandidate</tt>s harvested for {@link #hostCandidate} by this
* harvest * harvest
* @return <tt>true</tt> if the list of <tt>LocalCandidate</tt>s changed as
* a result of the method invocation; otherwise, <tt>false</tt>
*/ */
protected void addCandidate(LocalCandidate candidate) protected boolean addCandidate(LocalCandidate candidate)
{ {
if (!candidates.contains(candidate)) boolean added;
//try to add the candidate to the component and then only add it to the
//harvest if it wasn't deemed redundant
if (!candidates.contains(candidate)
&& hostCandidate.getParentComponent().addLocalCandidate(
candidate))
{ {
//try to add the candidate to the component and then only add it to added = candidates.add(candidate);
//the harvest if it wasn't deemed redundant
if( hostCandidate.getParentComponent().addLocalCandidate(candidate))
{
candidates.add(candidate);
}
} }
else
{
added = false;
}
return added;
} }
/** /**
@ -245,6 +254,35 @@ public class StunCandidateHarvest
return completedResolvingCandidate; return completedResolvingCandidate;
} }
/**
* Determines whether a specific <tt>LocalCandidate</tt> is contained in the
* list of <tt>LocalCandidate</tt>s harvested for {@link #hostCandidate} by
* this harvest.
*
* @param candidate the <tt>LocalCandidate</tt> to look for in the list of
* <tt>LocalCandidate</tt>s harvested for {@link #hostCandidate} by this
* harvest
* @return <tt>true</tt> if the list of <tt>LocalCandidate</tt>s contains
* the specified <tt>candidate</tt>; otherwise, <tt>false</tt>
*/
protected boolean containsCandidate(LocalCandidate candidate)
{
if (candidate != null)
{
LocalCandidate[] candidates = getCandidates();
if ((candidates != null) && (candidates.length != 0))
{
for (LocalCandidate c : candidates)
{
if (candidate.equals(c))
return true;
}
}
}
return false;
}
/** /**
* Creates new <tt>Candidate</tt>s determined by a specific STUN * Creates new <tt>Candidate</tt>s determined by a specific STUN
* <tt>Response</tt>. * <tt>Response</tt>.
@ -338,16 +376,25 @@ public class StunCandidateHarvest
{ {
synchronized (sendKeepAliveMessageSyncRoot) synchronized (sendKeepAliveMessageSyncRoot)
{ {
sendKeepAliveMessageThread Thread t = new SendKeepAliveMessageThread(this);
= new Thread() t.setDaemon(true);
{ t.setName(
@Override getClass().getName() + ".sendKeepAliveMessageThread: "
public void run() + hostCandidate);
{
runInSendKeepAliveMessageThread(); boolean started = false;
}
}; sendKeepAliveMessageThread = t;
sendKeepAliveMessageThread.start(); try
{
t.start();
started = true;
}
finally
{
if (!started && (sendKeepAliveMessageThread == t))
sendKeepAliveMessageThread = null;
}
} }
} }
@ -371,7 +418,35 @@ public class StunCandidateHarvest
= createServerReflexiveCandidate(addr); = createServerReflexiveCandidate(addr);
if (srvrRflxCand != null) if (srvrRflxCand != null)
addCandidate(srvrRflxCand); {
try
{
addCandidate(srvrRflxCand);
}
finally
{
// Free srvrRflxCand if it has not been consumed.
if (!containsCandidate(srvrRflxCand))
{
try
{
srvrRflxCand.free();
}
catch (Exception ex)
{
if (logger.isLoggable(Level.FINE))
{
logger.log(
Level.FINE,
"Failed to free"
+ " ServerReflexiveCandidate: "
+ srvrRflxCand,
ex);
}
}
}
}
}
} }
} }
@ -399,6 +474,32 @@ public class StunCandidateHarvest
CandidateExtendedType.STUN_SERVER_REFLEXIVE_CANDIDATE); CandidateExtendedType.STUN_SERVER_REFLEXIVE_CANDIDATE);
} }
/**
* Runs in {@link #sendKeepAliveMessageThread} to notify this instance that
* <tt>sendKeepAliveMessageThread</tt> is about to exit.
*/
private void exitSendKeepAliveMessageThread()
{
synchronized (sendKeepAliveMessageSyncRoot)
{
if (sendKeepAliveMessageThread == Thread.currentThread())
sendKeepAliveMessageThread = null;
/*
* Well, if the currentThread is finishing and this instance is
* still to send keep-alive messages, we'd better start another
* Thread for the purpose to continue the work that the
* currentThread was supposed to carry out.
*/
if ((sendKeepAliveMessageThread == null)
&& (sendKeepAliveMessageInterval
!= SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED))
{
createSendKeepAliveMessageThread();
}
}
}
/** /**
* Gets the number of <tt>Candidate</tt>s harvested for * Gets the number of <tt>Candidate</tt>s harvested for
* {@link #hostCandidate} during this harvest. * {@link #hostCandidate} during this harvest.
@ -708,6 +809,7 @@ public class StunCandidateHarvest
* transaction and the runtime type of which specifies the failure reason * transaction and the runtime type of which specifies the failure reason
* @see AbstractResponseCollector#processFailure(BaseStunMessageEvent) * @see AbstractResponseCollector#processFailure(BaseStunMessageEvent)
*/ */
@Override
protected void processFailure(BaseStunMessageEvent event) protected void processFailure(BaseStunMessageEvent event)
{ {
TransactionID transactionID = event.getTransactionID(); TransactionID transactionID = event.getTransactionID();
@ -754,6 +856,7 @@ public class StunCandidateHarvest
* STUN response * STUN response
* @see ResponseCollector#processResponse(StunResponseEvent) * @see ResponseCollector#processResponse(StunResponseEvent)
*/ */
@Override
public void processResponse(StunResponseEvent event) public void processResponse(StunResponseEvent event)
{ {
TransactionID transactionID = event.getTransactionID(); TransactionID transactionID = event.getTransactionID();
@ -1007,97 +1110,74 @@ public class StunCandidateHarvest
/** /**
* Runs in {@link #sendKeepAliveMessageThread} and sends STUN * Runs in {@link #sendKeepAliveMessageThread} and sends STUN
* keep-alive <tt>Message</tt>s to the STUN server associated with the * keep-alive <tt>Message</tt>s to the STUN server associated with the
* <tt>StunCandidateHarvester</tt> of this instance * <tt>StunCandidateHarvester</tt> of this instance.
*
* @return <tt>true</tt> if the method is to be invoked again; otherwise,
* <tt>false</tt>
*/ */
private void runInSendKeepAliveMessageThread() private boolean runInSendKeepAliveMessageThread()
{ {
try synchronized (sendKeepAliveMessageSyncRoot)
{ {
while (true) // Since we're going to #wait, make sure we're not canceled yet.
if (sendKeepAliveMessageThread != Thread.currentThread())
return false;
if (sendKeepAliveMessageInterval
== SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)
{ {
synchronized (sendKeepAliveMessageSyncRoot) return false;
{ }
/*
* Since we're going to #wait, make sure we're not canceled
* yet.
*/
if (sendKeepAliveMessageInterval
== SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED)
break;
/* // Determine the amount of milliseconds that we'll have to #wait.
* Determine the amount of milliseconds that we'll have to long timeout;
* #wait.
*/
long timeout;
if (sendKeepAliveMessageTimeStamp == -1) if (sendKeepAliveMessageTime == -1)
{ {
/* /*
* If we're just starting, don't just go and send a new * If we're just starting, don't just go and send a new STUN
* STUN keep-alive message but rather wait for the whole * keep-alive message but rather wait for the whole interval.
* interval. */
*/ timeout = sendKeepAliveMessageInterval;
timeout = sendKeepAliveMessageInterval; }
} else
else {
{ timeout
timeout = sendKeepAliveMessageTime
= sendKeepAliveMessageTimeStamp + sendKeepAliveMessageInterval
+ sendKeepAliveMessageInterval - System.currentTimeMillis();
- System.currentTimeMillis(); }
} // At long last, #wait if necessary.
// At long last, #wait if necessary. if (timeout > 0)
if (timeout > 0) {
{
try
{
sendKeepAliveMessageSyncRoot.wait(timeout);
}
catch (InterruptedException iex)
{
}
/*
* Apart from being the time to send the STUN keep-alive
* message, it could be that we've experienced a
* spurious wake-up or that we've been canceled.
*/
continue;
}
}
sendKeepAliveMessageTimeStamp = System.currentTimeMillis();
try try
{ {
sendKeepAliveMessage(); sendKeepAliveMessageSyncRoot.wait(timeout);
} }
catch (StunException sex) catch (InterruptedException iex)
{ {
logger.log(
Level.INFO,
"Failed to send STUN keep-alive message.",
sex);
} }
}
}
finally
{
synchronized (sendKeepAliveMessageSyncRoot)
{
if (sendKeepAliveMessageThread == Thread.currentThread())
sendKeepAliveMessageThread = null;
/* /*
* Well, if the currentThread is finishing and this instance is * Apart from being the time to send the STUN keep-alive
* still to send keep-alive messages, we'd better start another * message, it could be that we've experienced a spurious
* Thread for the purpose to continue the work that the * wake-up or that we've been canceled.
* currentThread was supposed to carry out.
*/ */
if ((sendKeepAliveMessageThread == null) return true;
&& (sendKeepAliveMessageInterval
!= SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED))
createSendKeepAliveMessageThread();
} }
} }
sendKeepAliveMessageTime = System.currentTimeMillis();
try
{
sendKeepAliveMessage();
}
catch (StunException sex)
{
logger.log(
Level.INFO,
"Failed to send STUN keep-alive message.",
sex);
}
return true;
} }
/** /**
@ -1141,19 +1221,19 @@ public class StunCandidateHarvest
* not be utilized. * not be utilized.
*/ */
if (keepAliveMessage == null) if (keepAliveMessage == null)
{
return false; return false;
if (keepAliveMessage instanceof Request) }
else if (keepAliveMessage instanceof Request)
{ {
return return
(sendRequest((Request) keepAliveMessage, false, null) != null); (sendRequest((Request) keepAliveMessage, false, null) != null);
} }
else else
{ {
throw throw new StunException(
new StunException( StunException.ILLEGAL_ARGUMENT,
StunException.ILLEGAL_ARGUMENT, "Failed to create keep-alive STUN message for candidate: "
"Failed to create keep-alive STUN message "
+ "for candidate: "
+ candidate); + candidate);
} }
} }
@ -1330,4 +1410,61 @@ public class StunCandidateHarvest
setSendKeepAliveMessageInterval( setSendKeepAliveMessageInterval(
SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED); SEND_KEEP_ALIVE_MESSAGE_INTERVAL_NOT_SPECIFIED);
} }
/**
* Sends STUN keep-alive <tt>Message</tt>s to the STUN server associated
* with the <tt>StunCandidateHarvester</tt> of this instance.
*
* @author Lyubomir Marinov
*/
private static class SendKeepAliveMessageThread
extends Thread
{
/**
* The <tt>StunCandidateHarvest</tt> which has initialized this
* instance. The <tt>StunCandidateHarvest</tt> is referenced by a
* <tt>WeakReference</tt> in an attempt to reduce the risk that the
* <tt>Thread</tt> may live regardless of the fact that the specified
* <tt>StunCandidateHarvest<tt> may no longer be reachable.
*/
private final WeakReference<StunCandidateHarvest> harvest;
/**
* Initializes a new <tt>SendKeepAliveMessageThread</tt> instance with a
* specific <tt>StunCandidateHarvest</tt>.
*
* @param harvest the <tt>StunCandidateHarvest</tt> to initialize the
* new instance with
*/
public SendKeepAliveMessageThread(StunCandidateHarvest harvest)
{
this.harvest = new WeakReference<StunCandidateHarvest>(harvest);
}
@Override
public void run()
{
try
{
do
{
StunCandidateHarvest harvest = this.harvest.get();
if ((harvest == null)
|| !harvest.runInSendKeepAliveMessageThread())
{
break;
}
}
while (true);
}
finally
{
StunCandidateHarvest harvest = this.harvest.get();
if (harvest != null)
harvest.exitSendKeepAliveMessageThread();
}
}
}
} }

View File

@ -124,8 +124,8 @@ public class StunCandidateHarvester
{ {
startedHarvests.remove(harvest); startedHarvests.remove(harvest);
//if this was the last candidate, we are done with the STUN // If this was the last candidate, we are done with the STUN
//resolution and need to notify the waiters. // resolution and need to notify the waiters.
if (startedHarvests.isEmpty()) if (startedHarvests.isEmpty())
doNotify = true; doNotify = true;
} }
@ -254,13 +254,11 @@ public class StunCandidateHarvester
LocalCandidate[] completedHarvestCandidates LocalCandidate[] completedHarvestCandidates
= completedHarvest.getCandidates(); = completedHarvest.getCandidates();
if (completedHarvestCandidates != null) if ((completedHarvestCandidates != null)
&& (completedHarvestCandidates.length != 0))
{ {
if(completedHarvestCandidates.length != 0) candidates.addAll(
{
candidates.addAll(
Arrays.asList(completedHarvestCandidates)); Arrays.asList(completedHarvestCandidates));
}
} }
} }
@ -268,10 +266,9 @@ public class StunCandidateHarvester
} }
logger.finest( logger.finest(
"Completed " + component.toShortString() + " harvest: " + toString() "Completed " + component.toShortString() + " harvest: "
+ ". Found " + candidates.size() + toString() + ". Found " + candidates.size()
+ " candidates: " + listCandidates(candidates)); + " candidates: " + listCandidates(candidates));
return candidates; return candidates;
} }
@ -304,8 +301,9 @@ public class StunCandidateHarvester
if(cand == null) if(cand == null)
{ {
logger.info("server/candidate address type mismatch, skipping " + logger.info(
"candidate in this harvester"); "server/candidate address type mismatch,"
+ " skipping candidate in this harvester");
return; return;
} }
@ -343,9 +341,26 @@ public class StunCandidateHarvester
{ {
if (!started) if (!started)
{ {
startedHarvests.remove(harvest); try
logger.warning("harvest did not start, removed: " + {
harvest); startedHarvests.remove(harvest);
logger.warning(
"harvest did not start, removed: " + harvest);
}
finally
{
/*
* For the sake of completeness, explicitly close the
* harvest.
*/
try
{
harvest.close();
}
catch (Exception ex)
{
}
}
} }
} }
} }
@ -363,6 +378,7 @@ public class StunCandidateHarvester
// Handle spurious wakeups. // Handle spurious wakeups.
while (!startedHarvests.isEmpty()) while (!startedHarvests.isEmpty())
{
try try
{ {
startedHarvests.wait(); startedHarvests.wait();
@ -370,10 +386,12 @@ public class StunCandidateHarvester
catch (InterruptedException iex) catch (InterruptedException iex)
{ {
logger.info( logger.info(
"interrupted waiting for harvests to complete, no. " + "interrupted waiting for harvests to complete,"
"startedHarvests = " + startedHarvests.size()); + " no. startedHarvests = "
+ startedHarvests.size());
interrupted = true; interrupted = true;
} }
}
// Restore the interrupted status. // Restore the interrupted status.
if (interrupted) if (interrupted)
Thread.currentThread().interrupt(); Thread.currentThread().interrupt();