use of java.net.SocketTimeoutException in project beam by apache.
the class DataflowPipelineJob method waitUntilFinish.
/**
* Waits until the pipeline finishes and returns the final status.
*
* @param duration The time to wait for the job to finish.
* Provide a value less than 1 ms for an infinite wait.
*
* @param messageHandler If non null this handler will be invoked for each
* batch of messages received.
* @param sleeper A sleeper to use to sleep between attempts.
* @param nanoClock A nanoClock used to time the total time taken.
* @return The final state of the job or null on timeout.
* @throws IOException If there is a persistent problem getting job
* information.
* @throws InterruptedException if the thread is interrupted.
*/
@Nullable
@VisibleForTesting
State waitUntilFinish(Duration duration, @Nullable MonitoringUtil.JobMessagesHandler messageHandler, Sleeper sleeper, NanoClock nanoClock, MonitoringUtil monitor) throws IOException, InterruptedException {
BackOff backoff;
if (!duration.isLongerThan(Duration.ZERO)) {
backoff = BackOffAdapter.toGcpBackOff(MESSAGES_BACKOFF_FACTORY.backoff());
} else {
backoff = BackOffAdapter.toGcpBackOff(MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(duration).backoff());
}
// This function tracks the cumulative time from the *first request* to enforce the wall-clock
// limit. Any backoff instance could, at best, track the the time since the first attempt at a
// given request. Thus, we need to track the cumulative time ourselves.
long startNanos = nanoClock.nanoTime();
State state;
do {
// Get the state of the job before listing messages. This ensures we always fetch job
// messages after the job finishes to ensure we have all them.
state = getStateWithRetries(BackOffAdapter.toGcpBackOff(STATUS_BACKOFF_FACTORY.withMaxRetries(0).backoff()), sleeper);
boolean hasError = state == State.UNKNOWN;
if (messageHandler != null && !hasError) {
// Process all the job messages that have accumulated so far.
try {
List<JobMessage> allMessages = monitor.getJobMessages(jobId, lastTimestamp);
if (!allMessages.isEmpty()) {
lastTimestamp = fromCloudTime(allMessages.get(allMessages.size() - 1).getTime()).getMillis();
messageHandler.process(allMessages);
}
} catch (GoogleJsonResponseException | SocketTimeoutException e) {
hasError = true;
LOG.warn("There were problems getting current job messages: {}.", e.getMessage());
LOG.debug("Exception information:", e);
}
}
if (!hasError) {
// We can stop if the job is done.
if (state.isTerminal()) {
switch(state) {
case DONE:
case CANCELLED:
LOG.info("Job {} finished with status {}.", getJobId(), state);
break;
case UPDATED:
LOG.info("Job {} has been updated and is running as the new job with id {}. " + "To access the updated job on the Dataflow monitoring console, " + "please navigate to {}", getJobId(), getReplacedByJob().getJobId(), MonitoringUtil.getJobMonitoringPageURL(getReplacedByJob().getProjectId(), getReplacedByJob().getJobId()));
break;
default:
LOG.info("Job {} failed with status {}.", getJobId(), state);
}
return state;
}
// The job is not done, so we must keep polling.
backoff.reset();
// allotted time.
if (duration.isLongerThan(Duration.ZERO)) {
long nanosConsumed = nanoClock.nanoTime() - startNanos;
Duration consumed = Duration.millis((nanosConsumed + 999999) / 1000000);
Duration remaining = duration.minus(consumed);
if (remaining.isLongerThan(Duration.ZERO)) {
backoff = BackOffAdapter.toGcpBackOff(MESSAGES_BACKOFF_FACTORY.withMaxCumulativeBackoff(remaining).backoff());
} else {
// If there is no time remaining, don't bother backing off.
backoff = BackOff.STOP_BACKOFF;
}
}
}
} while (BackOffUtils.next(sleeper, backoff));
LOG.warn("No terminal state was returned. State value {}", state);
// Timed out.
return null;
}
use of java.net.SocketTimeoutException in project robovm by robovm.
the class OldAndroidDatagramTest method testDatagramSocketSetSOTimeout.
// Regression test for issue 1018003: DatagramSocket ignored a set timeout.
public void testDatagramSocketSetSOTimeout() throws Exception {
DatagramSocket sock = null;
int timeout = 5000;
long start = System.currentTimeMillis();
try {
sock = new DatagramSocket();
DatagramPacket pack = new DatagramPacket(new byte[100], 100);
sock.setSoTimeout(timeout);
sock.receive(pack);
} catch (SocketTimeoutException e) {
// expected
long delay = System.currentTimeMillis() - start;
if (Math.abs(delay - timeout) > 1000) {
fail("timeout was not accurate. expected: " + timeout + " actual: " + delay + " miliseconds.");
}
} finally {
if (sock != null) {
sock.close();
}
}
}
use of java.net.SocketTimeoutException in project robovm by robovm.
the class SSLSocketTest method test_SSLSocket_setSoTimeout_wrapper.
public void test_SSLSocket_setSoTimeout_wrapper() throws Exception {
if (StandardNames.IS_RI) {
// RI cannot handle this case
return;
}
ServerSocket listening = new ServerSocket(0);
// setSoTimeout applies to read, not connect, so connect first
Socket underlying = new Socket(listening.getInetAddress(), listening.getLocalPort());
Socket server = listening.accept();
SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
Socket clientWrapping = sf.createSocket(underlying, null, -1, false);
underlying.setSoTimeout(1);
try {
clientWrapping.getInputStream().read();
fail();
} catch (SocketTimeoutException expected) {
}
clientWrapping.close();
server.close();
underlying.close();
listening.close();
}
use of java.net.SocketTimeoutException in project robovm by robovm.
the class PlainSocketImpl method accept.
@Override
protected void accept(SocketImpl newImpl) throws IOException {
if (usingSocks()) {
((PlainSocketImpl) newImpl).socksBind();
((PlainSocketImpl) newImpl).socksAccept();
return;
}
try {
// RovmVM note: accept() on Darwin does not honor the SO_RCVTIMEO
// set using setSoTimeout() on blocking sockets. As a work around we
// do poll() if a timeout has been set followed by an accept().
int timeout = (Integer) getOption(SO_TIMEOUT);
int flags = Libcore.os.fcntlVoid(fd, F_GETFL);
if (timeout > 0 && (flags & O_NONBLOCK) == 0) {
StructPollfd pfd = new StructPollfd();
pfd.fd = fd;
pfd.events = (short) (POLLIN | POLLERR);
StructPollfd[] pfds = new StructPollfd[] { pfd };
long start = System.currentTimeMillis();
long deadline = start + timeout;
while (true) {
try {
if (timeout <= 0 || Libcore.os.poll(pfds, timeout) == 0) {
throw new SocketTimeoutException("accept() timed out");
}
break;
} catch (ErrnoException e) {
if (e.errno == EINTR) {
long now = System.currentTimeMillis();
timeout = (int) (deadline - now);
} else {
throw e;
}
}
}
}
InetSocketAddress peerAddress = new InetSocketAddress();
FileDescriptor clientFd = Libcore.os.accept(fd, peerAddress);
// TODO: we can't just set newImpl.fd to clientFd because a nio SocketChannel may
// be sharing the FileDescriptor. http://b//4452981.
newImpl.fd.setInt$(clientFd.getInt$());
newImpl.address = peerAddress.getAddress();
newImpl.port = peerAddress.getPort();
} catch (ErrnoException errnoException) {
if (errnoException.errno == EAGAIN) {
throw new SocketTimeoutException(errnoException);
}
throw errnoException.rethrowAsSocketException();
}
// Reset the client's inherited read timeout to the Java-specified default of 0.
newImpl.setOption(SocketOptions.SO_TIMEOUT, Integer.valueOf(0));
newImpl.localport = IoBridge.getSocketLocalPort(newImpl.fd);
}
use of java.net.SocketTimeoutException in project robovm by robovm.
the class SSLSocketTest method test_SSLSocket_setUseClientMode.
private void test_SSLSocket_setUseClientMode(final boolean clientClientMode, final boolean serverClientMode) throws Exception {
TestSSLContext c = TestSSLContext.create();
SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket(c.host, c.port);
final SSLSocket server = (SSLSocket) c.serverSocket.accept();
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<IOException> future = executor.submit(new Callable<IOException>() {
@Override
public IOException call() throws Exception {
try {
if (!serverClientMode) {
server.setSoTimeout(1 * 1000);
}
server.setUseClientMode(serverClientMode);
server.startHandshake();
return null;
} catch (SSLHandshakeException e) {
return e;
} catch (SocketTimeoutException e) {
return e;
}
}
});
executor.shutdown();
if (!clientClientMode) {
client.setSoTimeout(1 * 1000);
}
client.setUseClientMode(clientClientMode);
client.startHandshake();
IOException ioe = future.get();
if (ioe != null) {
throw ioe;
}
client.close();
server.close();
c.close();
}
Aggregations