Search in sources :

Example 76 with SocketTimeoutException

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;
}
Also used : GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) SocketTimeoutException(java.net.SocketTimeoutException) JobMessage(com.google.api.services.dataflow.model.JobMessage) Duration(org.joda.time.Duration) BackOff(com.google.api.client.util.BackOff) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Nullable(javax.annotation.Nullable)

Example 77 with SocketTimeoutException

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();
        }
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) DatagramSocket(java.net.DatagramSocket) DatagramPacket(java.net.DatagramPacket)

Example 78 with SocketTimeoutException

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();
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) SSLServerSocket(javax.net.ssl.SSLServerSocket)

Example 79 with SocketTimeoutException

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);
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) ErrnoException(libcore.io.ErrnoException) InetSocketAddress(java.net.InetSocketAddress) StructPollfd(libcore.io.StructPollfd) FileDescriptor(java.io.FileDescriptor)

Example 80 with SocketTimeoutException

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();
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) SSLSocket(javax.net.ssl.SSLSocket) ExecutorService(java.util.concurrent.ExecutorService) IOException(java.io.IOException) SocketException(java.net.SocketException) SocketTimeoutException(java.net.SocketTimeoutException) SSLProtocolException(javax.net.ssl.SSLProtocolException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SSLException(javax.net.ssl.SSLException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) SSLHandshakeException(javax.net.ssl.SSLHandshakeException)

Aggregations

SocketTimeoutException (java.net.SocketTimeoutException)721 IOException (java.io.IOException)420 Test (org.junit.Test)139 Socket (java.net.Socket)103 SocketException (java.net.SocketException)99 ServerSocket (java.net.ServerSocket)79 InputStream (java.io.InputStream)77 ConnectException (java.net.ConnectException)70 UnknownHostException (java.net.UnknownHostException)64 InetSocketAddress (java.net.InetSocketAddress)60 URL (java.net.URL)51 EOFException (java.io.EOFException)48 HttpURLConnection (java.net.HttpURLConnection)47 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)42 InterruptedIOException (java.io.InterruptedIOException)40 ArrayList (java.util.ArrayList)40 MalformedURLException (java.net.MalformedURLException)38 InputStreamReader (java.io.InputStreamReader)37 HashMap (java.util.HashMap)36 OutputStream (java.io.OutputStream)35