Partially implements termination procedures

This commit is contained in:
emcho 2010-05-08 21:38:48 +00:00
parent 3476b9194d
commit ce396fc993
10 changed files with 384 additions and 120 deletions

View File

@ -105,6 +105,14 @@ public class StackProperties
public static final String REQUIRE_MESSAGE_INTEGRITY
= "org.ice4j.REQUIRE_MESSAGE_INTEGRITY";
/**
* The name of the property that can be used to specify the number of
* milliseconds that we must wait after ICE processing enters a COMPLTED
* state and before we free candidates and move into the TERMINATED state.
*/
public static final String TERMINATION_DELAY
= "org.ice4j.TERMINATION_DELAY";
/**
* Returns the String value of the specified property (minus all
* encompassing whitespaces)and null in case no property value was mapped

View File

@ -113,6 +113,8 @@ public class AttributeDecoder
decodedAttribute = new IceControllingAttribute(); break;
case Attribute.ICE_CONTROLLED:
decodedAttribute = new IceControlledAttribute(); break;
case Attribute.USE_CANDIDATE:
decodedAttribute = new UseCandidateAttribute(); break;
//According to rfc3489 we should silently ignore unknown attributes.
default: decodedAttribute

View File

@ -13,14 +13,16 @@ import java.math.*;
import java.net.*;
import java.security.*;
import java.util.*;
import java.util.logging.*;
import org.ice4j.*;
import org.ice4j.attribute.*;
import org.ice4j.ice.checks.*;
import org.ice4j.ice.harvest.*;
import org.ice4j.message.*;
import org.ice4j.stack.*;
import sun.management.resources.*;
/**
* An <tt>Agent</tt> could be described as the main class (i.e. the chef d'orchestre)
* of an ICE implementation.
@ -39,6 +41,20 @@ public class Agent
*/
public static final int DEFAULT_MAX_CHECK_LIST_SIZE = 100;
/**
* The default number of milliseconds we should wait before moving from
* {@link IceProcessingState#COMPLETED} into {@link
* IceProcessingState#TERMINATED}.
*/
public static final int DEFAULT_TERMINATION_DELAY = 3000;
/**
* The <tt>Logger</tt> used by the <tt>Agent</tt>
* class and its instances for logging output.
*/
private static final Logger logger = Logger
.getLogger(Agent.class.getName());
/**
* The LinkedHashMap used to store the media streams
* This map preserves the insertion order of the media streams.
@ -155,6 +171,11 @@ public class Agent
private List<PropertyChangeListener> stateListeners
= new LinkedList<PropertyChangeListener>();
/**
* The thread that we use for moving from COMPLETED into a TERMINATED state.
*/
private TerminationThread terminationThread;
/**
* Creates an empty <tt>Agent</tt> with no streams, and no address
*/
@ -299,8 +320,8 @@ public class Agent
synchronized(startLock)
{
initCheckLists();
setState(IceProcessingState.RUNNING);
connCheckClient.startChecks();
iceStarted = true;
}
}
@ -404,8 +425,8 @@ public class Agent
{
IceProcessingState oldState = state;
this.state = state;
fireStateChange(oldState, newState)
this.state = newState;
fireStateChange(oldState, newState);
}
/**
@ -995,8 +1016,15 @@ public class Agent
*/
public void validatePair(CandidatePair validPair)
{
IceMediaStream parentStream
= validPair.getParentComponent().getParentStream();
parentStream.addValidPair(validPair);
System.out.println("valid pair was nominated " + validPair);
validPair.nominate();
validPair.getParentComponent().getParentStream()
.addValidPair(validPair);
.getCheckList().scheduleTriggeredCheck(validPair);
}
/**
@ -1010,7 +1038,7 @@ public class Agent
public void nominationConfirmed(CandidatePair pairToNominate)
{
pairToNominate.nominate();
System.out.println("pair nomination confirmed");
Component parentComponent = pairToNominate.getParentComponent();
IceMediaStream parentStream = parentComponent.getParentStream();
CheckList checkList = parentStream.getCheckList();
@ -1027,45 +1055,51 @@ public class Agent
//The agent MUST change the state of processing for its check
//list for that media stream to Completed.
checkList.setState(CheckListState.COMPLETED);
System.out.println("checklist " + checkList.getName() + " became " + checkList.getState());
}
/*
o Once the state of each check list is Completed:
}
* The agent sets the state of ICE processing overall to
Completed.
/**
* After updating check list states as a result of an incoming response
* or a timeout event the method goes through all checklists and tries
* to assess the state of ICE processing.
*/
public void checkListStateUpdated()
{
boolean allListsEnded = true;
boolean atLeastOneListSucceeded = false;
* If an agent is controlling, it examines the highest-priority
nominated candidate pair for each component of each media
stream. If any of those candidate pairs differ from the
default candidate pairs in the most recent offer/answer
exchange, the controlling agent MUST generate an updated offer
as described in Section 9. If the controlling agent is using
an aggressive nomination algorithm, this may result in several
updated offers as the pairs selected for media change. An
agent MAY delay sending the offer for a brief interval (one
second is RECOMMENDED) in order to allow the selected pairs to
stabilize.
o If the state of the check list is Failed, ICE has not been able to
complete for this media stream. The correct behavior depends on
the state of the check lists for other media streams:
* If all check lists are Failed, ICE processing overall is
considered to be in the Failed state, and the agent SHOULD
consider the session a failure, SHOULD NOT restart ICE, and the
controlling agent SHOULD terminate the entire session.
* If at least one of the check lists for other media streams is
Completed, the controlling agent SHOULD remove the failed media
stream from the session in its updated offer.
* If none of the check lists for other media streams are
Completed, but at least one is Running, the agent SHOULD let
ICE continue.
*/
List<IceMediaStream> streams = getStreams();
for(IceMediaStream stream : streams)
{
CheckList checkList = stream.getCheckList();
if(checkList.getState() == CheckListState.RUNNING)
{
allListsEnded = false;
break;
}
else if(stream.getCheckList().getState() == CheckListState.COMPLETED)
{
atLeastOneListSucceeded = true;
}
}
//Once the state of each check list is Completed:
//The agent sets the state of ICE processing overall to Completed.
if(allListsEnded)
{
if(atLeastOneListSucceeded)
{
setState(IceProcessingState.COMPLETED);
scheduleTermination();
}
else
{
setState(IceProcessingState.FAILED);
}
}
}
/**
@ -1203,4 +1237,81 @@ public class Agent
*/
return 100;
}
/**
* Initializes and starts the {@link TerminationThread}
*/
private void scheduleTermination()
{
if (terminationThread == null)
terminationThread = new TerminationThread(this);
terminationThread.start();
}
/**
* RFC 5245 says: Once ICE processing has reached the Completed state for
* all peers for media streams using those candidates, the agent SHOULD
* wait an additional three seconds, and then it MAY cease responding to
* checks or generating triggered checks on that candidate. It MAY free
* the candidate at that time.
* <p>
* This <tt>TerminationThread</tt> is scheduling such a termination and
* garbage collection in three seconds.
*/
private static class TerminationThread
extends Thread
{
/**
* The parent agent that created us.
*/
private final Agent parentAgent;
/**
* Creates a new termination timer.
*
* @param parentAgent the <tt>Agent</tt> that created us.
*/
private TerminationThread(Agent parentAgent)
{
super("TerminationThread");
this.parentAgent = parentAgent;
}
/**
* Waits for a period of three seconds (or whatever termination
* interval the user has specified) and then moves this <tt>Agent</tt>
* into the terminated state and frees all non-nominated candidates.
*/
public void run()
{
long waitFor = Integer.getInteger(
StackProperties.TERMINATION_DELAY,
DEFAULT_TERMINATION_DELAY);
try
{
wait(waitFor);
}
catch (Exception e)
{
logger.log(Level.FINEST,
"Interrupted while waiting. Will speed up termination", e);
}
parentAgent.terminate();
}
}
/**
* Prepares everything associated with this {@link Agent} for garbage
* collection and moves it into the terminated state.
*/
private void terminate()
{
// free candidates
// stop listening for checks
setState(IceProcessingState.TERMINATED);
}
}

View File

@ -40,6 +40,21 @@ public class CheckList
private final List<CandidatePair> triggeredCheckQueue
= new LinkedList<CandidatePair>();
/**
* A name for this check list which we use for debugging purposes
*/
private final String name;
/**
* Creates a check list with the specified name.
*
* @param name the name of the check list.
*/
public CheckList(String name)
{
this.name = name;
}
/**
* Returns the state of this check list.
*
@ -114,33 +129,36 @@ public class CheckList
if (size() < 1)
return null;
CandidatePair highestPriorityWaitingPair = null;
CandidatePair highestPriorityFrozenPair = null;
CandidatePair highestPriorityPair = null;
for (CandidatePair pair : this)
{
if (pair.getState() == CandidatePairState.WAITING)
{
if(highestPriorityWaitingPair == null
|| pair.getPriority()
> highestPriorityWaitingPair.getPriority())
if(highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority())
{
highestPriorityWaitingPair = pair;
highestPriorityPair = pair;
}
}
else if (pair.getState() == CandidatePairState.FROZEN)
{
if(highestPriorityFrozenPair == null
|| pair.getPriority()
> highestPriorityFrozenPair.getPriority())
highestPriorityFrozenPair = pair;
}
}
if(highestPriorityWaitingPair != null)
return highestPriorityWaitingPair;
else
return highestPriorityFrozenPair; //return even if null
if(highestPriorityPair != null)
return highestPriorityPair;
for (CandidatePair pair : this)
{
if (pair.getState() == CandidatePairState.FROZEN)
{
if(highestPriorityPair == null
|| pair.getPriority() > highestPriorityPair.getPriority())
{
highestPriorityPair = pair;
}
}
}
return highestPriorityPair; //return even if null
}
/**
@ -332,4 +350,16 @@ public class CheckList
}
}
}
/**
* Returns the name of this check list so that we could use it for debugging
* purposes.
*
* @return a name for this check list that we could use to distinguish it
* from other check lists while debugging.
*/
public String getName()
{
return name;
}
}

View File

@ -88,6 +88,11 @@ public class Component
*/
private LocalCandidate defaultCandidate = null;
/**
* The pair that has been selected for use by ICE processing
*/
private CandidatePair selectedPair;
/**
* The default <tt>RemoteCandidate</tt> for this component or in other
* words, the candidate that we would have used to communicate with the
@ -642,4 +647,18 @@ public class Component
return num;
}
/**
* Returns the {@link CandidatePair} selected for use by ICE processing or
* <tt>null</tt> if no pair has been selected so far or if ICE processing
* has failed.
*
* @return the {@link CandidatePair} selected for use by ICE processing or
* <tt>null</tt> if no pair has been selected so far or if ICE processing
* has failed.
*/
public CandidatePair getSelectedPair()
{
return selectedPair;
}
}

View File

@ -62,7 +62,7 @@ public class IceMediaStream
* is one check list per in-use media stream resulting from the offer/answer
* exchange.
*/
private final CheckList checkList = new CheckList();
private final CheckList checkList;
/**
* The agent that this media stream belongs to.
@ -91,6 +91,7 @@ public class IceMediaStream
{
this.name = name;
this.parentAgent = parentAgent;
checkList = new CheckList(name);
}
/**

View File

@ -11,9 +11,17 @@ package org.ice4j.ice;
* state associated with it. This state is equal to <tt>Running</tt> while ICE
* processing is under way. The state is Completed when ICE processing is
* complete and Failed if it failed without success. For convenience reasons
* we are also adding an extra <tt>Waiting</tt> state that reflects the state
* of an {@link Agent} before it starts processing. This is also an {@link
* Agent}'s default state.
* we are also adding two extra states. The first one is the <tt>Waiting</tt>
* state that reflects the state of an {@link Agent} before it starts
* processing. This is also an {@link Agent }'s default state. The second one
* is the "Terminated" state. RFC 5245 says that once ICE processing
* has reached the Completed state for all peers for media streams using
* those candidates, the agent SHOULD wait an additional three seconds,
* and then it MAY cease responding to checks or generating triggered
* checks on that candidate. It MAY free the candidate at that time.
* which reflects the state where an Agent does not need to handle incoming
* checks any more and is ready for garbage collection. This is the state we
* refer to with "Terminated".
*
* @author Emil Ivov
*/
@ -39,7 +47,17 @@ public enum IceProcessingState
* The state is Completed when ICE processing is Failed if processing
* failed without success.
*/
FAILED("Failed");
FAILED("Failed"),
/**
* Once ICE processing has reached the Completed state for all peers for
* media streams using those candidates, the agent SHOULD wait an
* additional three seconds, and then it MAY cease responding to checks
* or generating triggered checks on that candidate. It MAY free the
* candidate at that time. This is also when an agent would enter the
* terminated state.
*/
TERMINATED("Terminated");
/**
* The name of this <tt>IceProcessingState</tt> instance.

View File

@ -221,12 +221,24 @@ public class ConnectivityCheckClient
processSuccessResponse(evt);
}
//7.1.3.3. Check List and Timer State Updates
CandidatePair checkedPair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
//Regardless of whether the check was successful or failed, the
//completion of the transaction may require updating of check list and
//timer states.
CandidatePair checkedPair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
updateCheckListAndTimerStates(checkedPair);
}
/**
* Updates all check list and timer states after a check has completed
* (both if completion was successful or not). The method implements
* section "7.1.3.3. Check List and Timer State Updates"
*
* @param checkedPair the pair whose check has just completed.
*/
private void updateCheckListAndTimerStates(CandidatePair checkedPair)
{
IceMediaStream stream = checkedPair.getParentComponent()
.getParentStream();
CheckList checkList = stream.getCheckList();
@ -234,10 +246,17 @@ public class ConnectivityCheckClient
//If all of the pairs in the check list are now either in the Failed or
//Succeeded state:
boolean allPairsDone = true;
for(CandidatePair pair : checkList)
if(pair.getState() != CandidatePairState.FAILED
&& pair.getState() != CandidatePairState.SUCCEEDED)
allPairsDone = false;
synchronized(checkList)
{
for(CandidatePair pair : checkList)
{
if(pair.getState() != CandidatePairState.FAILED
&& pair.getState() != CandidatePairState.SUCCEEDED)
{
allPairsDone = false;
}
}
}
if (allPairsDone)
{
@ -265,6 +284,8 @@ public class ConnectivityCheckClient
}
}
}
parentAgent.checkListStatesUpdated();
}
/**
@ -280,7 +301,6 @@ public class ConnectivityCheckClient
CandidatePair checkedPair = ((CandidatePair)evt.getTransactionID()
.getApplicationData());
if(! response.contains(Attribute.XOR_MAPPED_ADDRESS))
{
logger.fine("Received a success response with no "
@ -347,10 +367,14 @@ public class ConnectivityCheckClient
// by a STUN connectivity check.
CandidatePair validPair;
if(existingPair != null)
{
validPair = existingPair;
}
else
{
validPair = new CandidatePair(validLocalCandidate,
validRemoteCandidate);
}
parentAgent.validatePair(validPair);
@ -381,10 +405,17 @@ public class ConnectivityCheckClient
CheckList checkList = stream.getCheckList();
boolean wasFrozen = checkList.isFrozen();
for(CandidatePair pair : checkList)
if (parentStream.validListContainsFoundation(pair.getFoundation())
&& pair.getState() == CandidatePairState.FROZEN)
pair.setStateWaiting();
synchronized (checkList)
{
for(CandidatePair pair : checkList)
{
if (parentStream.validListContainsFoundation(pair.getFoundation())
&& pair.getState() == CandidatePairState.FROZEN)
{
pair.setStateWaiting();
}
}
}
//if the checklList is still frozen after the above operations,
//the agent groups together all of the pairs with the same
@ -492,35 +523,26 @@ public class ConnectivityCheckClient
}
}
/**
* Sets the state of the corresponding {@link CandidatePair} to
* {@link CandidatePairState#FAILED} and updates check list and timer
* states.
*
* @param event the {@link StunTimeoutEvent} containing the original
* transaction and hence {@link CandidatePair} that's being checked.
*/
public void processTimeout(StunTimeoutEvent event)
{
System.out.println("timeout for pair=" + event.getTransactionID().getApplicationData());
CandidatePair pair = ((CandidatePair)event.getTransactionID()
.getApplicationData());
logger.fine("timeout for pair=" + pair);
System.out.println("timeout for pair=" + pair);
pair.setStateFailed();
updateCheckListAndTimerStates(pair);
}
/**
* Removes the corresponding local candidate from the list of candidates
* that we are waiting on in order to complete the harvest.
*
* @param transactionID the ID of the transaction that has just ended.
*/
/*
private void processFailure(TransactionID transactionID)
{
synchronized (resolveMap)
{
Candidate localCand = resolveMap.remove(transactionID);
//if this was the last candidate, we are done with the STUN
//resolution and need to notify the waiters.
if(resolveMap.isEmpty())
resolveMap.notify();
logger.finest("a tran expired tranid=" + transactionID);
logger.finest("localAddr=" + localCand);
}
}
*/
/**
* The thread that actually sends the checks for a particular check list
* in the pace defined in RFC 5245.
@ -561,6 +583,28 @@ public class ConnectivityCheckClient
this.checkList = checkList;
}
/**
* Returns the number milliseconds to wait before we send the next
* check.
*
* @return the number milliseconds to wait before we send the next
* check.
*/
private long getNextWaitInterval()
{
int activeCheckLists = parentClient
.parentAgent.getActiveCheckListCount();
if (activeCheckLists < 1)
{
//don't multiply by 0. even when we no longer have active check
//lists we may still have nomination checks to
activeCheckLists = 1;
}
return parentClient.parentAgent.calculateTa() * activeCheckLists;
}
/**
* Sends connectivity checks at the pace determined by the {@link
* Agent#calculateTa()} method and using either the trigger check queue
@ -570,8 +614,8 @@ public class ConnectivityCheckClient
{
while(isRunning)
{
long waitFor = parentClient.parentAgent.calculateTa()
* parentClient.parentAgent.getActiveCheckListCount();
long waitFor = getNextWaitInterval();
System.out.println("will wait for " + waitFor + " active clist cound="+parentClient.parentAgent.getActiveCheckListCount());
if(waitFor > 0)
{
@ -587,7 +631,7 @@ public class ConnectivityCheckClient
}
if (!isRunning)
return;
break;
}
CandidatePair pairToCheck = checkList.popTriggeredCheck();
@ -595,21 +639,34 @@ public class ConnectivityCheckClient
//if there are no triggered checks, go for an ordinary one.
if(pairToCheck == null)
{
System.out.println("checklist " + checkList.getName() + " did not return triggered check");
pairToCheck = checkList.getNextOrdinaryPairToCheck();
}
else
{
System.out.println("checklist " + checkList.getName() + " returned triggered check");
}
if(pairToCheck != null)
transactionID = parentClient.startCheckForPair(pairToCheck);
if(pairToCheck == null)
{
//we are done sending checks for this list. we'll send its
System.out.println("checklist " + checkList.getName() + " returned regular check in state " + pairToCheck.getState());
transactionID = parentClient.startCheckForPair(pairToCheck);
}
else
{
logger.fine("checklist " + checkList.getName() + " ran out of checks");
//we are done sending checks for this list. we'll set its
//final state in either the processResponse()
//processTimeout() or processFailure() method.
logger.finest("finished a checklist");
isRunning = false;
return;
//maybe do this if the list is in the completed state.
//isRunning = false;
//break;
continue;
}
if(transactionID == null)

View File

@ -740,7 +740,7 @@ t.printStackTrace();
{
Response error = MessageFactory.createBindingErrorResponse(
ErrorCodeAttribute.UNKNOWN_ATTRIBUTE,
"missing username", sBuff.toString().toCharArray());
"unknown attribute ", sBuff.toString().toCharArray());
sendResponse(request.getTransactionID(), error,
evt.getLocalAddress(),

View File

@ -23,6 +23,16 @@ import org.ice4j.ice.harvest.*;
*/
public class Ice
{
/**
* Start time for debugging purposes.
*/
static long startTime;
/**
* Our local agent.
*/
static Agent localAgent;
/**
* Runs the test
* @param args command line arguments
@ -31,16 +41,16 @@ public class Ice
*/
public static void main(String[] args) throws Throwable
{
long startTime = System.currentTimeMillis();
startTime = System.currentTimeMillis();
Agent localAgent = createAgent(9090);
localAgent = createAgent(9090);
Agent remotePeer = createAgent(6060);
localAgent.addStateChangeListener(new IceProcessingListener());
//let them fight ... fights forge character.
//localAgent.setControlling(true);
//remotePeer.setControlling(false);
localAgent.setControlling(true);
remotePeer.setControlling(false);
long endTime = System.currentTimeMillis();
@ -59,11 +69,12 @@ public class Ice
System.out.println("Local audio clist:\n"
+ localAgent.getStream("audio").getCheckList());
System.out.println("Local video clist:\n"
+ localAgent.getStream("video").getCheckList());
System.out.println("Total execution time: "
+ (endTime - startTime) + "ms");
IceMediaStream videoStream = localAgent.getStream("video");
if(videoStream != null)
System.out.println("Local video clist:\n"
+ videoStream.getCheckList());
//Give processing enough time to finish. We'll System.exit() anyway
//as soon as localAgent enters a final state.
@ -85,9 +96,16 @@ public class Ice
*/
public void propertyChange(PropertyChangeEvent evt)
{
long processingEndTime = System.currentTimeMillis();
System.out.println("Agent entered the " + evt.getNewValue()
+ " state.");
if(evt.getNewValue() == IceProcessingState.COMPLETED
|| evt.getNewValue() == IceProcessingState.FAILED)
{
System.out.println("Total execution time: "
+ (processingEndTime - startTime) + "ms");
IceMediaStream mediaStream = localAgent.
System.exit(0);
}
}
@ -199,11 +217,11 @@ public class Ice
new TransportAddress("ipv6.sip-communicator.net",
3478, Transport.UDP));
agent.addCandidateHarvester(stunHarv);
agent.addCandidateHarvester(stun6Harv);
//agent.addCandidateHarvester(stunHarv);
//agent.addCandidateHarvester(stun6Harv);
createStream(rtpPort, "audio", agent);
createStream(rtpPort + 2, "video", agent);
//createStream(rtpPort + 2, "video", agent);
return agent;
}
@ -243,8 +261,8 @@ public class Ice
+ (endTime - startTime) +" ms");
startTime = endTime;
//rtcpComp
agent.createComponent(
stream, Transport.UDP, rtpPort + 1, rtpPort + 1, rtpPort + 101);
//agent.createComponent(
// stream, Transport.UDP, rtpPort + 1, rtpPort + 1, rtpPort + 101);
endTime = System.currentTimeMillis();
System.out.println("RTCP Component created in "