Added support for timeout on read and write operations for PseudoTcpSocket

This commit is contained in:
paweldomas 2012-08-25 09:04:03 +00:00
parent 71e4dec419
commit 40e8c691e1
4 changed files with 287 additions and 36 deletions

View File

@ -30,4 +30,12 @@ public enum Option
* Set the send buffer size, in bytes. * Set the send buffer size, in bytes.
*/ */
OPT_SNDBUF, OPT_SNDBUF,
/**
* Timeout in ms for read operations(0 - no timeout)
*/
OPT_READ_TIMEOUT,
/**
* Timeout in ms for write operations(0 - no timeout)
*/
OPT_WRITE_TIMEOUT
}; };

View File

@ -70,8 +70,8 @@ public class PseudoTCPBase
// TODO: Make JINGLE_HEADER_SIZE transparent to this code? // TODO: Make JINGLE_HEADER_SIZE transparent to this code?
static final int JINGLE_HEADER_SIZE = 64; // when relay framing is in use static final int JINGLE_HEADER_SIZE = 64; // when relay framing is in use
// Default size for receive and send buffer. // Default size for receive and send buffer.
static final int DEFAULT_RCV_BUF_SIZE = 60 * 1024; public static final int DEFAULT_RCV_BUF_SIZE = 60 * 1024;
static final int DEFAULT_SND_BUF_SIZE = 90 * 1024; public static final int DEFAULT_SND_BUF_SIZE = 90 * 1024;
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
// Global Constants and Functions // Global Constants and Functions
////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////
@ -1124,13 +1124,15 @@ public class PseudoTCPBase
//setM_snd_wnd(seg.wnd << m_swnd_scale); //setM_snd_wnd(seg.wnd << m_swnd_scale);
long nAcked = seg.ack - m_snd_una; long nAcked = seg.ack - m_snd_una;
synchronized (ack_notify)
{
m_snd_una = seg.ack; m_snd_una = seg.ack;
m_rto_base = (m_snd_una == m_snd_nxt) ? 0 : now; m_rto_base = (m_snd_una == m_snd_nxt) ? 0 : now;
m_sbuf.consumeReadData((int) nAcked); m_sbuf.consumeReadData((int) nAcked);
synchronized (ack_notify)
{
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, logger.log(Level.FINER,

View File

@ -64,6 +64,14 @@ class PseudoTcpSocketImpl
* threads blocked on any operations. * threads blocked on any operations.
*/ */
private IOException exception; private IOException exception;
/**
* Read operations timeout in ms
*/
private long writeTimeout;
/**
* Write operations timeout in ms
*/
private long readTimeout;
/** /**
@ -264,14 +272,36 @@ class PseudoTcpSocketImpl
} }
public long getPTCPOption(Option opt) public long getPTCPOption(Option opt)
{
if(Option.OPT_READ_TIMEOUT == opt)
{
return this.readTimeout;
}
else if(Option.OPT_WRITE_TIMEOUT == opt)
{
return this.writeTimeout;
}
else
{ {
return pseudoTcp.getOption(opt); return pseudoTcp.getOption(opt);
} }
}
public void setPTCPOption(Option opt, long optValue) public void setPTCPOption(Option opt, long optValue)
{
if(Option.OPT_WRITE_TIMEOUT == opt)
{
this.writeTimeout = optValue >= 0 ? optValue : 0;
}
else if(Option.OPT_READ_TIMEOUT == opt)
{
this.readTimeout = optValue >= 0 ? optValue : 0;
}
else
{ {
pseudoTcp.setOption(opt, optValue); pseudoTcp.setOption(opt, optValue);
} }
}
/** /**
@ -483,7 +513,7 @@ class PseudoTcpSocketImpl
{ {
if (e != null) if (e != null)
{ {
e.printStackTrace(); //e.printStackTrace();
logger.log(Level.SEVERE, "PseudoTcp closed: " + e); logger.log(Level.SEVERE, "PseudoTcp closed: " + e);
} }
else else
@ -799,11 +829,12 @@ class PseudoTcpSocketImpl
* @param offset destination buffer's offset * @param offset destination buffer's offset
* @param length maximum count of bytes that can be read * @param length maximum count of bytes that can be read
* @return byte count actually read * @return byte count actually read
* @throws IOException * @throws IOException in case of error or if timeout occurs
*/ */
@Override @Override
public int read(byte[] buffer, int offset, int length) throws IOException public int read(byte[] buffer, int offset, int length) throws IOException
{ {
long start = System.currentTimeMillis();
int read; int read;
while (true) while (true)
{ {
@ -822,10 +853,28 @@ class PseudoTcpSocketImpl
return read; return read;
} }
logger.log(Level.FINER, "Read wait for data available"); logger.log(Level.FINER, "Read wait for data available");
if(readTimeout > 0)
{
//Check for timeout
long elapsed = System.currentTimeMillis() - start;
long left = readTimeout - elapsed;
if(left <= 0)
{
IOException exc =
new IOException("Read operation timeout");
pseudoTcp.closedown(exc);
throw exc;
}
read_notify.wait(left);
}
else
{
read_notify.wait(); read_notify.wait();
}
if (logger.isLoggable(Level.FINER)) if (logger.isLoggable(Level.FINER))
{ {
logger.log(Level.FINER, logger.log(
Level.FINER,
"Read notified: " + pseudoTcp.getAvailable()); "Read notified: " + pseudoTcp.getAvailable());
} }
} }
@ -880,19 +929,20 @@ class PseudoTcpSocketImpl
} }
/** /**
* This method blocks until all data has been written or an exception * This method blocks until all data has been written.
* occurs
* *
* @param buffer source buffer * @param buffer source buffer
* @param offset source buffer's offset * @param offset source buffer's offset
* @param length byte count to be written * @param length byte count to be written
* @throws IOException * @throws IOException in case of error or if timeout occurs
*
*/ */
@Override @Override
public void write(byte[] buffer, int offset, int length) throws IOException public void write(byte[] buffer, int offset, int length) throws IOException
{ {
int toSend = length; int toSend = length;
int sent; int sent;
long start = System.currentTimeMillis();
while (toSend > 0) while (toSend > 0)
{ {
synchronized (pseudoTcp) synchronized (pseudoTcp)
@ -909,9 +959,25 @@ class PseudoTcpSocketImpl
{ {
logger.log(Level.FINER, "Write wait for notify"); logger.log(Level.FINER, "Write wait for notify");
synchronized (write_notify) synchronized (write_notify)
{
if(writeTimeout > 0)
{
long elapsed = System.currentTimeMillis() - start;
long left = writeTimeout - elapsed;
if(left <= 0)
{
IOException exc =
new IOException("Write operation timeout");
pseudoTcp.closedown(exc);
throw exc;
}
write_notify.wait(left);
}
else
{ {
write_notify.wait(); write_notify.wait();
} }
}
logger.log(Level.FINER, logger.log(Level.FINER,
"Write notified, available: " "Write notified, available: "
+ pseudoTcp.getAvailableSendBuffer()); + pseudoTcp.getAvailableSendBuffer());
@ -938,21 +1004,39 @@ class PseudoTcpSocketImpl
/** /**
* This method block until all buffered data has been written * This method block until all buffered data has been written
* *
* @throws IOException * @throws IOException in case of error or if timeout occurs
*/ */
@Override @Override
public synchronized void flush() throws IOException public synchronized void flush() throws IOException
{ {
logger.log(Level.FINE, "Flushing..."); logger.log(Level.FINE, "Flushing...");
long start = System.currentTimeMillis();
final Object ackNotify = pseudoTcp.getAckNotify(); final Object ackNotify = pseudoTcp.getAckNotify();
while (pseudoTcp.getBytesBufferedNotSent() > 0)
{
synchronized (ackNotify) synchronized (ackNotify)
{
while (pseudoTcp.getBytesBufferedNotSent() > 0)
{ {
try try
{
if(writeTimeout > 0)
{
//Check write timeout
long elapsed = System.currentTimeMillis() - start;
long left = writeTimeout - elapsed;
if(left <= 0)
{
IOException e =
new IOException("Flush operation timeout");
pseudoTcp.closedown(e);
throw e;
}
ackNotify.wait(left);
}
else
{ {
ackNotify.wait(); ackNotify.wait();
} }
}
catch (InterruptedException ex) catch (InterruptedException ex)
{ {
throw new IOException("Flush stream interrupted", ex); throw new IOException("Flush stream interrupted", ex);

View File

@ -32,13 +32,10 @@ public class PseudoTcpStreamTest
/** /**
* Test one-way transfer with @link(PseudoTcpStream) * Test one-way transfer with @link(PseudoTcpStream)
* * @throws IOException
* @throws SocketException
* @throws UnknownHostException
*/ */
public void testConnectTransferClose() public void testConnectTransferClose()
throws SocketException, throws IOException
UnknownHostException
{ {
Thread.setDefaultUncaughtExceptionHandler(this); Thread.setDefaultUncaughtExceptionHandler(this);
final int server_port = 49999; final int server_port = 49999;
@ -50,10 +47,12 @@ public class PseudoTcpStreamTest
PseudoTcpTestBase.createDummyData(singleStepCount); PseudoTcpTestBase.createDummyData(singleStepCount);
final int sizeA = 138746; final int sizeA = 138746;
final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA); final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA);
final int sizeB = 4803746; final int sizeB = 983746;
final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB); final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB);
final InetSocketAddress serverAddress = final InetSocketAddress serverAddress =
new InetSocketAddress(InetAddress.getLocalHost(), server_port); new InetSocketAddress(InetAddress.getLocalHost(), server_port);
final PseudoTcpSocket server =
new PseudoTcpSocketFactory().createSocket();
Thread serverThread = new Thread(new Runnable() Thread serverThread = new Thread(new Runnable()
{ {
@Override @Override
@ -61,9 +60,6 @@ public class PseudoTcpStreamTest
{ {
try try
{ {
final PseudoTcpSocket server =
new PseudoTcpSocketFactory().
createSocket();
server.setDebugName("L"); server.setDebugName("L");
server.bind(serverAddress); server.bind(serverAddress);
server.accept(5000); server.accept(5000);
@ -151,6 +147,7 @@ public class PseudoTcpStreamTest
{ {
clientThread.join(); clientThread.join();
serverThread.join(); serverThread.join();
server.close();
} }
else else
{ {
@ -197,4 +194,164 @@ public class PseudoTcpStreamTest
// success // success
} }
} }
/**
* Interface used to pass timeout test function
* @author Pawel Domas
*
*/
private interface TimeoutOperationTest
{
void testTimeout(PseudoTcpSocketImpl socket) throws IOException;
}
/**
*
* @param testOperation
* @throws UnknownHostException
*/
private void doTestTimeout(final TimeoutOperationTest testOperation)
throws Exception
{
Thread.setDefaultUncaughtExceptionHandler(this);
final PseudoTcpSocketImpl server;
final PseudoTcpSocketImpl client;
final int server_port = 49998;
final InetSocketAddress serverAddress =
new InetSocketAddress(InetAddress.getLocalHost(), server_port);
server =
new PseudoTcpSocketImpl(0,new DatagramSocket(serverAddress));
client = new PseudoTcpSocketImpl(0);
//Servers thread waiting for connection
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
server.accept(2000);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
try
{
testOperation.testTimeout(server);
fail("No expected timeout occured on operation");
}
catch (IOException e)
{
//success
try
{
server.close();
}
catch (IOException exc)
{
throw new RuntimeException(exc);
}
}
}
}).start();
//Clients thread connects and closes socket
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
client.connect(serverAddress, 2000);
Thread.sleep(500);
client.close();
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}).start();
//Waits for server to close socket
boolean done = assert_wait_until(new WaitUntilDone()
{
@Override
public boolean isDone()
{
return server.getState() == PseudoTcpState.TCP_CLOSED;
}
}, 3000);
if(!done)
{
fail("Test timed out");
}
}
/**
* Tests timeout on read method
* @throws UnknownHostException
*/
public void testReadTimeout() throws Exception
{
doTestTimeout(new TimeoutOperationTest()
{
@Override
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
{
socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300);
socket.getInputStream().read(new byte[500]);
}
});
}
/**
* Tests timeout on write method
* @throws UnknownHostException
*/
public void testWriteTimeout() throws Exception
{
doTestTimeout(new TimeoutOperationTest()
{
@Override
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
{
//buffer that will exceed stack's buffer size
byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2];
socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
socket.getOutputStream().write(bigBuffer);
}
});
}
/**
* Tests timeout on flush method
* @throws UnknownHostException
*/
public void testFlushTimeout() throws Exception
{
doTestTimeout(new TimeoutOperationTest()
{
@Override
public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
{
//buffer that will exceed stack's buffer size
byte[] buffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE];
socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
try
{
socket.getOutputStream().write(buffer);
}
catch(IOException e)
{
throw new RuntimeException("Unexpected exception: "+e);
}
socket.getOutputStream().flush();
}
});
}
} }