Search in sources :

Example 1 with AtomicBoolean

use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.

the class HTTP2ServerTest method testCommitFailure.

@Test
public void testCommitFailure() throws Exception {
    final long delay = 1000;
    final AtomicBoolean broken = new AtomicBoolean();
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                // Wait for the SETTINGS frames to be exchanged.
                Thread.sleep(delay);
                broken.set(true);
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
        }
    });
    server.stop();
    ServerConnector connector2 = new ServerConnector(server, new HTTP2ServerConnectionFactory(new HttpConfiguration())) {

        @Override
        protected ChannelEndPoint newEndPoint(SocketChannel channel, ManagedSelector selectSet, SelectionKey key) throws IOException {
            return new SocketChannelEndPoint(channel, selectSet, key, getScheduler()) {

                @Override
                public void write(Callback callback, ByteBuffer... buffers) throws IllegalStateException {
                    if (broken.get())
                        callback.failed(new IOException("explicitly_thrown_by_test"));
                    else
                        super.write(callback, buffers);
                }
            };
        }
    };
    server.addConnector(connector2);
    server.start();
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    try (Socket client = new Socket("localhost", connector2.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
        // The server will close the connection abruptly since it
        // cannot write and therefore cannot even send the GO_AWAY.
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter(), 4096, 8192);
        boolean closed = parseResponse(client, parser, 2 * delay);
        Assert.assertTrue(closed);
    }
}
Also used : ManagedSelector(org.eclipse.jetty.io.ManagedSelector) ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) InterruptedIOException(java.io.InterruptedIOException) SocketChannel(java.nio.channels.SocketChannel) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ServerConnector(org.eclipse.jetty.server.ServerConnector) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) SelectionKey(java.nio.channels.SelectionKey) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(org.eclipse.jetty.util.Callback) SocketChannelEndPoint(org.eclipse.jetty.io.SocketChannelEndPoint) Socket(java.net.Socket) Test(org.junit.Test)

Example 2 with AtomicBoolean

use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.

the class SelectChannelEndPointInterestsTest method testReadBlockedThenWriteBlockedThenReadableThenWritable.

@Test
public void testReadBlockedThenWriteBlockedThenReadableThenWritable() throws Exception {
    final AtomicInteger size = new AtomicInteger(1024 * 1024);
    final AtomicReference<Exception> failure = new AtomicReference<>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final AtomicBoolean writeBlocked = new AtomicBoolean();
    init(new Interested() {

        @Override
        public void onFillable(EndPoint endPoint, AbstractConnection connection) {
            ByteBuffer input = BufferUtil.allocate(2);
            int read = fill(endPoint, input);
            if (read == 1) {
                byte b = input.get();
                if (b == 1) {
                    connection.fillInterested();
                    ByteBuffer output = ByteBuffer.allocate(size.get());
                    endPoint.write(new Callback() {
                    }, output);
                    latch1.countDown();
                } else {
                    latch2.countDown();
                }
            } else {
                failure.set(new Exception("Unexpectedly read " + read + " bytes"));
            }
        }

        @Override
        public void onIncompleteFlush() {
            writeBlocked.set(true);
        }

        private int fill(EndPoint endPoint, ByteBuffer buffer) {
            try {
                return endPoint.fill(buffer);
            } catch (IOException x) {
                failure.set(x);
                return 0;
            }
        }
    });
    Socket client = new Socket();
    client.connect(connector.getLocalAddress());
    client.setSoTimeout(5000);
    SocketChannel server = connector.accept();
    server.configureBlocking(false);
    selectorManager.accept(server);
    OutputStream clientOutput = client.getOutputStream();
    clientOutput.write(1);
    clientOutput.flush();
    Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
    // We do not read to keep the socket write blocked
    clientOutput.write(2);
    clientOutput.flush();
    Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
    // Sleep before reading to allow waking up the server only for read
    Thread.sleep(1000);
    // Now read what was written, waking up the server for write
    InputStream clientInput = client.getInputStream();
    while (size.getAndDecrement() > 0) clientInput.read();
    client.close();
    Assert.assertNull(failure.get());
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Test(org.junit.Test)

Example 3 with AtomicBoolean

use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.

the class ProxyServletLoadTest method test.

@Test
public void test() throws Exception {
    startServer(new HttpServlet() {

        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            if (req.getHeader("Via") != null)
                resp.addHeader(PROXIED_HEADER, "true");
            IO.copy(req.getInputStream(), resp.getOutputStream());
        }
    });
    startProxy();
    startClient();
    // Number of clients to simulate
    int clientCount = Runtime.getRuntime().availableProcessors();
    // Latch for number of clients still active (used to terminate test)
    final CountDownLatch activeClientLatch = new CountDownLatch(clientCount);
    // Atomic Boolean to track that its OK to still continue looping.
    // When this goes false, that means one of the client threads has
    // encountered an error condition, and should allow all remaining
    // client threads to finish cleanly.
    final AtomicBoolean success = new AtomicBoolean(true);
    int iterations = 1000;
    // Start clients
    for (int i = 0; i < clientCount; i++) {
        ClientLoop r = new ClientLoop(activeClientLatch, success, client, "localhost", serverConnector.getLocalPort(), iterations);
        String name = "client-" + i;
        Thread thread = new Thread(r, name);
        thread.start();
    }
    Assert.assertTrue(activeClientLatch.await(Math.max(clientCount * iterations * 10, 5000), TimeUnit.MILLISECONDS));
    Assert.assertTrue(success.get());
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Test(org.junit.Test)

Example 4 with AtomicBoolean

use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.

the class HttpServerTestBase method testInterruptedRequest.

@Test
public void testInterruptedRequest() throws Exception {
    final AtomicBoolean fourBytesRead = new AtomicBoolean(false);
    final AtomicBoolean earlyEOFException = new AtomicBoolean(false);
    configureServer(new AbstractHandler.ErrorDispatchHandler() {

        @Override
        public void doNonErrorHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            baseRequest.setHandled(true);
            int contentLength = request.getContentLength();
            ServletInputStream inputStream = request.getInputStream();
            for (int i = 0; i < contentLength; i++) {
                try {
                    inputStream.read();
                } catch (EofException e) {
                    earlyEOFException.set(true);
                    throw new QuietServletException(e);
                }
                if (i == 3)
                    fourBytesRead.set(true);
            }
        }
    });
    StringBuffer request = new StringBuffer("GET / HTTP/1.0\n");
    request.append("Host: localhost\n");
    request.append("Content-length: 6\n\n");
    request.append("foo");
    Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort());
    OutputStream os = client.getOutputStream();
    os.write(request.toString().getBytes());
    os.flush();
    client.shutdownOutput();
    String response = readResponse(client);
    client.close();
    assertThat("response contains 500", response, Matchers.containsString(" 500 "));
    assertThat("The 4th byte (-1) has not been passed to the handler", fourBytesRead.get(), is(false));
    assertThat("EofException has been caught", earlyEOFException.get(), is(true));
}
Also used : EofException(org.eclipse.jetty.io.EofException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) Matchers.containsString(org.hamcrest.Matchers.containsString) IOException(java.io.IOException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ServletInputStream(javax.servlet.ServletInputStream) Socket(java.net.Socket) Test(org.junit.Test)

Example 5 with AtomicBoolean

use of java.util.concurrent.atomic.AtomicBoolean in project jetty.project by eclipse.

the class SslContextFactoryReloadTest method testReloadWhileServing.

@Test
public void testReloadWhileServing() throws Exception {
    start(new EchoHandler());
    Scheduler scheduler = new ScheduledExecutorScheduler();
    scheduler.start();
    try {
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        ctx.init(null, SslContextFactory.TRUST_ALL_CERTS, null);
        SSLSocketFactory socketFactory = ctx.getSocketFactory();
        // Perform 4 reloads while connections are being served.
        AtomicInteger reloads = new AtomicInteger(4);
        long reloadPeriod = 500;
        AtomicBoolean running = new AtomicBoolean(true);
        scheduler.schedule(new Runnable() {

            @Override
            public void run() {
                if (reloads.decrementAndGet() == 0) {
                    running.set(false);
                } else {
                    try {
                        sslContextFactory.reload(sslContextFactory -> {
                            if (sslContextFactory.getKeyStorePath().endsWith(KEYSTORE_1))
                                sslContextFactory.setKeyStorePath(KEYSTORE_2);
                            else
                                sslContextFactory.setKeyStorePath(KEYSTORE_1);
                        });
                        scheduler.schedule(this, reloadPeriod, TimeUnit.MILLISECONDS);
                    } catch (Exception x) {
                        running.set(false);
                        reloads.set(-1);
                    }
                }
            }
        }, reloadPeriod, TimeUnit.MILLISECONDS);
        byte[] content = new byte[16 * 1024];
        while (running.get()) {
            try (SSLSocket client = (SSLSocket) socketFactory.createSocket("localhost", connector.getLocalPort())) {
                // We need to invalidate the session every time we open a new SSLSocket.
                // This is because when the client uses session resumption, it caches
                // the server certificates and then checks that it is the same during
                // a new TLS handshake. If the SslContextFactory is reloaded during the
                // TLS handshake, the client will see the new certificate and blow up.
                // Note that browsers can handle this case better: they will just not
                // use session resumption and fallback to the normal TLS handshake.
                client.getSession().invalidate();
                String request1 = "" + "POST / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Content-Length: " + content.length + "\r\n" + "\r\n";
                OutputStream outputStream = client.getOutputStream();
                outputStream.write(request1.getBytes(StandardCharsets.UTF_8));
                outputStream.write(content);
                outputStream.flush();
                InputStream inputStream = client.getInputStream();
                HttpTester.Response response1 = HttpTester.parseResponse(HttpTester.from(inputStream));
                Assert.assertNotNull(response1);
                Assert.assertThat(response1.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
                String request2 = "" + "GET / HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n" + "\r\n";
                outputStream.write(request2.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
                HttpTester.Response response2 = HttpTester.parseResponse(HttpTester.from(inputStream));
                Assert.assertNotNull(response2);
                Assert.assertThat(response2.getStatus(), Matchers.equalTo(HttpStatus.OK_200));
            }
        }
        Assert.assertEquals(0, reloads.get());
    } finally {
        scheduler.stop();
    }
}
Also used : Request(org.eclipse.jetty.server.Request) HttpTester(org.eclipse.jetty.http.HttpTester) Handler(org.eclipse.jetty.server.Handler) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HttpVersion(org.eclipse.jetty.http.HttpVersion) Scheduler(org.eclipse.jetty.util.thread.Scheduler) SSLSocket(javax.net.ssl.SSLSocket) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) After(org.junit.After) HttpStatus(org.eclipse.jetty.http.HttpStatus) Server(org.eclipse.jetty.server.Server) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) Matchers(org.hamcrest.Matchers) IOException(java.io.IOException) Test(org.junit.Test) IO(org.eclipse.jetty.util.IO) StandardCharsets(java.nio.charset.StandardCharsets) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TimeUnit(java.util.concurrent.TimeUnit) HttpMethod(org.eclipse.jetty.http.HttpMethod) ServerConnector(org.eclipse.jetty.server.ServerConnector) Assert(org.junit.Assert) InputStream(java.io.InputStream) Scheduler(org.eclipse.jetty.util.thread.Scheduler) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) InputStream(java.io.InputStream) SSLSocket(javax.net.ssl.SSLSocket) OutputStream(java.io.OutputStream) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) SSLContext(javax.net.ssl.SSLContext) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) HttpTester(org.eclipse.jetty.http.HttpTester) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Test(org.junit.Test)

Aggregations

AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5984 Test (org.junit.Test)3016 CountDownLatch (java.util.concurrent.CountDownLatch)926 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)914 IOException (java.io.IOException)730 ArrayList (java.util.ArrayList)665 AtomicReference (java.util.concurrent.atomic.AtomicReference)664 List (java.util.List)474 Test (org.junit.jupiter.api.Test)340 AtomicLong (java.util.concurrent.atomic.AtomicLong)309 HashMap (java.util.HashMap)299 Map (java.util.Map)291 ExecutorService (java.util.concurrent.ExecutorService)237 Test (org.testng.annotations.Test)235 TimeUnit (java.util.concurrent.TimeUnit)216 File (java.io.File)210 HashSet (java.util.HashSet)200 ExecutionException (java.util.concurrent.ExecutionException)198 GridCommonAbstractTest (org.apache.ignite.testframework.junits.common.GridCommonAbstractTest)198 Collections (java.util.Collections)192