Search in sources :

Example 1 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project elasticsearch by elastic.

the class RemoteScrollableHitSourceTests method sourceWithMockedClient.

private RemoteScrollableHitSource sourceWithMockedClient(boolean mockRemoteVersion, CloseableHttpAsyncClient httpClient) throws Exception {
    HttpAsyncClientBuilder clientBuilder = mock(HttpAsyncClientBuilder.class);
    when(clientBuilder.build()).thenReturn(httpClient);
    RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).setHttpClientConfigCallback(httpClientBuilder -> clientBuilder).build();
    TestRemoteScrollableHitSource hitSource = new TestRemoteScrollableHitSource(restClient) {

        @Override
        void lookupRemoteVersion(Consumer<Version> onVersion) {
            if (mockRemoteVersion) {
                onVersion.accept(Version.CURRENT);
            } else {
                super.lookupRemoteVersion(onVersion);
            }
        }
    };
    if (mockRemoteVersion) {
        hitSource.remoteVersion = Version.CURRENT;
    }
    return hitSource;
}
Also used : Response(org.elasticsearch.action.bulk.byscroll.ScrollableHitSource.Response) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) ScheduledFuture(java.util.concurrent.ScheduledFuture) URL(java.net.URL) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) StatusLine(org.apache.http.StatusLine) HeapBufferedAsyncResponseConsumer(org.elasticsearch.client.HeapBufferedAsyncResponseConsumer) Future(java.util.concurrent.Future) After(org.junit.After) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) Streams(org.elasticsearch.common.io.Streams) ThreadPool(org.elasticsearch.threadpool.ThreadPool) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) StandardCharsets(java.nio.charset.StandardCharsets) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) Matchers.any(org.mockito.Matchers.any) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) Version(org.elasticsearch.Version) RestStatus(org.elasticsearch.rest.RestStatus) TimeValue.timeValueMinutes(org.elasticsearch.common.unit.TimeValue.timeValueMinutes) Matchers.containsString(org.hamcrest.Matchers.containsString) Mockito.mock(org.mockito.Mockito.mock) RestClient(org.elasticsearch.client.RestClient) ContentTooLongException(org.apache.http.ContentTooLongException) ParsingException(org.elasticsearch.common.ParsingException) BasicStatusLine(org.apache.http.message.BasicStatusLine) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SearchRequest(org.elasticsearch.action.search.SearchRequest) BackoffPolicy(org.elasticsearch.action.bulk.BackoffPolicy) BytesArray(org.elasticsearch.common.bytes.BytesArray) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) Answer(org.mockito.stubbing.Answer) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) TimeValue(org.elasticsearch.common.unit.TimeValue) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) TimeValue.timeValueMillis(org.elasticsearch.common.unit.TimeValue.timeValueMillis) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ESTestCase(org.elasticsearch.test.ESTestCase) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) Matchers.empty(org.hamcrest.Matchers.empty) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) FutureCallback(org.apache.http.concurrent.FutureCallback) IOException(java.io.IOException) Mockito.when(org.mockito.Mockito.when) InputStreamReader(java.io.InputStreamReader) Consumer(java.util.function.Consumer) ProtocolVersion(org.apache.http.ProtocolVersion) EsRejectedExecutionException(org.elasticsearch.common.util.concurrent.EsRejectedExecutionException) HttpResponse(org.apache.http.HttpResponse) InputStreamEntity(org.apache.http.entity.InputStreamEntity) HttpHost(org.apache.http.HttpHost) HeapBufferedAsyncResponseConsumer(org.elasticsearch.client.HeapBufferedAsyncResponseConsumer) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) Consumer(java.util.function.Consumer) HttpHost(org.apache.http.HttpHost) RestClient(org.elasticsearch.client.RestClient) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder)

Example 2 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project elasticsearch by elastic.

the class IndexingIT method testSeqNoCheckpoints.

public void testSeqNoCheckpoints() throws Exception {
    Nodes nodes = buildNodeAndVersions();
    assumeFalse("new nodes is empty", nodes.getNewNodes().isEmpty());
    logger.info("cluster discovered: {}", nodes.toString());
    final List<String> bwcNamesList = nodes.getBWCNodes().stream().map(Node::getNodeName).collect(Collectors.toList());
    final String bwcNames = bwcNamesList.stream().collect(Collectors.joining(","));
    Settings.Builder settings = Settings.builder().put(IndexMetaData.INDEX_NUMBER_OF_SHARDS_SETTING.getKey(), 1).put(IndexMetaData.INDEX_NUMBER_OF_REPLICAS_SETTING.getKey(), 2).put("index.routing.allocation.include._name", bwcNames);
    final boolean checkGlobalCheckpoints = nodes.getMaster().getVersion().onOrAfter(Version.V_6_0_0_alpha1_UNRELEASED);
    logger.info("master version is [{}], global checkpoints will be [{}]", nodes.getMaster().getVersion(), checkGlobalCheckpoints ? "checked" : "not be checked");
    if (checkGlobalCheckpoints) {
        settings.put(IndexSettings.INDEX_SEQ_NO_CHECKPOINT_SYNC_INTERVAL.getKey(), "100ms");
    }
    final String index = "test";
    createIndex(index, settings.build());
    try (RestClient newNodeClient = buildClient(restClientSettings(), nodes.getNewNodes().stream().map(Node::getPublishAddress).toArray(HttpHost[]::new))) {
        int numDocs = 0;
        final int numberOfInitialDocs = 1 + randomInt(5);
        logger.info("indexing [{}] docs initially", numberOfInitialDocs);
        numDocs += indexDocs(index, 0, numberOfInitialDocs);
        assertSeqNoOnShards(nodes, checkGlobalCheckpoints, 0, newNodeClient);
        logger.info("allowing shards on all nodes");
        updateIndexSetting(index, Settings.builder().putNull("index.routing.allocation.include._name"));
        ensureGreen();
        assertOK(client().performRequest("POST", index + "/_refresh"));
        for (final String bwcName : bwcNamesList) {
            assertCount(index, "_only_nodes:" + bwcName, numDocs);
        }
        final int numberOfDocsAfterAllowingShardsOnAllNodes = 1 + randomInt(5);
        logger.info("indexing [{}] docs after allowing shards on all nodes", numberOfDocsAfterAllowingShardsOnAllNodes);
        numDocs += indexDocs(index, numDocs, numberOfDocsAfterAllowingShardsOnAllNodes);
        assertSeqNoOnShards(nodes, checkGlobalCheckpoints, 0, newNodeClient);
        Shard primary = buildShards(nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get();
        logger.info("moving primary to new node by excluding {}", primary.getNode().getNodeName());
        updateIndexSetting(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.getNode().getNodeName()));
        ensureGreen();
        int numDocsOnNewPrimary = 0;
        final int numberOfDocsAfterMovingPrimary = 1 + randomInt(5);
        logger.info("indexing [{}] docs after moving primary", numberOfDocsAfterMovingPrimary);
        numDocsOnNewPrimary += indexDocs(index, numDocs, numberOfDocsAfterMovingPrimary);
        numDocs += numberOfDocsAfterMovingPrimary;
        assertSeqNoOnShards(nodes, checkGlobalCheckpoints, numDocsOnNewPrimary, newNodeClient);
        /*
             * Dropping the number of replicas to zero, and then increasing it to one triggers a recovery thus exercising any BWC-logic in
             * the recovery code.
             */
        logger.info("setting number of replicas to 0");
        updateIndexSetting(index, Settings.builder().put("index.number_of_replicas", 0));
        final int numberOfDocsAfterDroppingReplicas = 1 + randomInt(5);
        logger.info("indexing [{}] docs after setting number of replicas to 0", numberOfDocsAfterDroppingReplicas);
        numDocsOnNewPrimary += indexDocs(index, numDocs, numberOfDocsAfterDroppingReplicas);
        numDocs += numberOfDocsAfterDroppingReplicas;
        logger.info("setting number of replicas to 1");
        updateIndexSetting(index, Settings.builder().put("index.number_of_replicas", 1));
        ensureGreen();
        assertOK(client().performRequest("POST", index + "/_refresh"));
        // the number of documents on the primary and on the recovered replica should match the number of indexed documents
        assertCount(index, "_primary", numDocs);
        assertCount(index, "_replica", numDocs);
        assertSeqNoOnShards(nodes, checkGlobalCheckpoints, numDocsOnNewPrimary, newNodeClient);
    }
}
Also used : HttpHost(org.apache.http.HttpHost) RestClient(org.elasticsearch.client.RestClient) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Example 3 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project elasticsearch by elastic.

the class RestClientMultipleHostsIntegTests method startHttpServer.

@BeforeClass
public static void startHttpServer() throws Exception {
    String pathPrefixWithoutLeadingSlash;
    if (randomBoolean()) {
        pathPrefixWithoutLeadingSlash = "testPathPrefix/" + randomAsciiOfLengthBetween(1, 5);
        pathPrefix = "/" + pathPrefixWithoutLeadingSlash;
    } else {
        pathPrefix = pathPrefixWithoutLeadingSlash = "";
    }
    int numHttpServers = randomIntBetween(2, 4);
    httpServers = new HttpServer[numHttpServers];
    HttpHost[] httpHosts = new HttpHost[numHttpServers];
    for (int i = 0; i < numHttpServers; i++) {
        HttpServer httpServer = createHttpServer();
        httpServers[i] = httpServer;
        httpHosts[i] = new HttpHost(httpServer.getAddress().getHostString(), httpServer.getAddress().getPort());
    }
    RestClientBuilder restClientBuilder = RestClient.builder(httpHosts);
    if (pathPrefix.length() > 0) {
        restClientBuilder.setPathPrefix((randomBoolean() ? "/" : "") + pathPrefixWithoutLeadingSlash);
    }
    restClient = restClientBuilder.build();
}
Also used : HttpHost(org.apache.http.HttpHost) HttpServer(com.sun.net.httpserver.HttpServer) MockHttpServer(org.elasticsearch.mocksocket.MockHttpServer) BeforeClass(org.junit.BeforeClass)

Example 4 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project elasticsearch by elastic.

the class RestClientMultipleHostsTests method createRestClient.

@Before
@SuppressWarnings("unchecked")
public void createRestClient() throws IOException {
    CloseableHttpAsyncClient httpClient = mock(CloseableHttpAsyncClient.class);
    when(httpClient.<HttpResponse>execute(any(HttpAsyncRequestProducer.class), any(HttpAsyncResponseConsumer.class), any(HttpClientContext.class), any(FutureCallback.class))).thenAnswer(new Answer<Future<HttpResponse>>() {

        @Override
        public Future<HttpResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
            HttpAsyncRequestProducer requestProducer = (HttpAsyncRequestProducer) invocationOnMock.getArguments()[0];
            HttpUriRequest request = (HttpUriRequest) requestProducer.generateRequest();
            HttpHost httpHost = requestProducer.getTarget();
            HttpClientContext context = (HttpClientContext) invocationOnMock.getArguments()[2];
            assertThat(context.getAuthCache().get(httpHost), instanceOf(BasicScheme.class));
            FutureCallback<HttpResponse> futureCallback = (FutureCallback<HttpResponse>) invocationOnMock.getArguments()[3];
            //return the desired status code or exception depending on the path
            if (request.getURI().getPath().equals("/soe")) {
                futureCallback.failed(new SocketTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/coe")) {
                futureCallback.failed(new ConnectTimeoutException(httpHost.toString()));
            } else if (request.getURI().getPath().equals("/ioe")) {
                futureCallback.failed(new IOException(httpHost.toString()));
            } else {
                int statusCode = Integer.parseInt(request.getURI().getPath().substring(1));
                StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, "");
                futureCallback.completed(new BasicHttpResponse(statusLine));
            }
            return null;
        }
    });
    int numHosts = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    httpHosts = new HttpHost[numHosts];
    for (int i = 0; i < numHosts; i++) {
        httpHosts[i] = new HttpHost("localhost", 9200 + i);
    }
    failureListener = new HostsTrackingFailureListener();
    restClient = new RestClient(httpClient, 10000, new Header[0], httpHosts, null, failureListener);
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) ProtocolVersion(org.apache.http.ProtocolVersion) BasicStatusLine(org.apache.http.message.BasicStatusLine) BasicStatusLine(org.apache.http.message.BasicStatusLine) StatusLine(org.apache.http.StatusLine) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) SocketTimeoutException(java.net.SocketTimeoutException) Header(org.apache.http.Header) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) HttpHost(org.apache.http.HttpHost) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) Future(java.util.concurrent.Future) FutureCallback(org.apache.http.concurrent.FutureCallback) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) Before(org.junit.Before)

Example 5 with HttpHost

use of org.graylog.shaded.elasticsearch7.org.apache.http.HttpHost in project elasticsearch by elastic.

the class RestClientMultipleHostsTests method testRoundRobinRetryErrors.

public void testRoundRobinRetryErrors() throws IOException {
    String retryEndpoint = randomErrorRetryEndpoint();
    try {
        restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint);
        fail("request should have failed");
    } catch (ResponseException e) {
        Set<HttpHost> hostsSet = new HashSet<>();
        Collections.addAll(hostsSet, httpHosts);
        //first request causes all the hosts to be blacklisted, the returned exception holds one suppressed exception each
        failureListener.assertCalled(httpHosts);
        do {
            Response response = e.getResponse();
            assertEquals(Integer.parseInt(retryEndpoint.substring(1)), response.getStatusLine().getStatusCode());
            assertTrue("host [" + response.getHost() + "] not found, most likely used multiple times", hostsSet.remove(response.getHost()));
            if (e.getSuppressed().length > 0) {
                assertEquals(1, e.getSuppressed().length);
                Throwable suppressed = e.getSuppressed()[0];
                assertThat(suppressed, instanceOf(ResponseException.class));
                e = (ResponseException) suppressed;
            } else {
                e = null;
            }
        } while (e != null);
        assertEquals("every host should have been used but some weren't: " + hostsSet, 0, hostsSet.size());
    } catch (IOException e) {
        Set<HttpHost> hostsSet = new HashSet<>();
        Collections.addAll(hostsSet, httpHosts);
        //first request causes all the hosts to be blacklisted, the returned exception holds one suppressed exception each
        failureListener.assertCalled(httpHosts);
        do {
            HttpHost httpHost = HttpHost.create(e.getMessage());
            assertTrue("host [" + httpHost + "] not found, most likely used multiple times", hostsSet.remove(httpHost));
            if (e.getSuppressed().length > 0) {
                assertEquals(1, e.getSuppressed().length);
                Throwable suppressed = e.getSuppressed()[0];
                assertThat(suppressed, instanceOf(IOException.class));
                e = (IOException) suppressed;
            } else {
                e = null;
            }
        } while (e != null);
        assertEquals("every host should have been used but some weren't: " + hostsSet, 0, hostsSet.size());
    }
    int numIters = RandomNumbers.randomIntBetween(getRandom(), 2, 5);
    for (int i = 1; i <= numIters; i++) {
        //check that one different host is resurrected at each new attempt
        Set<HttpHost> hostsSet = new HashSet<>();
        Collections.addAll(hostsSet, httpHosts);
        for (int j = 0; j < httpHosts.length; j++) {
            retryEndpoint = randomErrorRetryEndpoint();
            try {
                restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint);
                fail("request should have failed");
            } catch (ResponseException e) {
                Response response = e.getResponse();
                assertThat(response.getStatusLine().getStatusCode(), equalTo(Integer.parseInt(retryEndpoint.substring(1))));
                assertTrue("host [" + response.getHost() + "] not found, most likely used multiple times", hostsSet.remove(response.getHost()));
                //after the first request, all hosts are blacklisted, a single one gets resurrected each time
                failureListener.assertCalled(response.getHost());
                assertEquals(0, e.getSuppressed().length);
            } catch (IOException e) {
                HttpHost httpHost = HttpHost.create(e.getMessage());
                assertTrue("host [" + httpHost + "] not found, most likely used multiple times", hostsSet.remove(httpHost));
                //after the first request, all hosts are blacklisted, a single one gets resurrected each time
                failureListener.assertCalled(httpHost);
                assertEquals(0, e.getSuppressed().length);
            }
        }
        assertEquals("every host should have been used but some weren't: " + hostsSet, 0, hostsSet.size());
        if (getRandom().nextBoolean()) {
            //mark one host back alive through a successful request and check that all requests after that are sent to it
            HttpHost selectedHost = null;
            int iters = RandomNumbers.randomIntBetween(getRandom(), 2, 10);
            for (int y = 0; y < iters; y++) {
                int statusCode = randomErrorNoRetryStatusCode(getRandom());
                Response response;
                try {
                    response = restClient.performRequest(randomHttpMethod(getRandom()), "/" + statusCode);
                } catch (ResponseException e) {
                    response = e.getResponse();
                }
                assertThat(response.getStatusLine().getStatusCode(), equalTo(statusCode));
                if (selectedHost == null) {
                    selectedHost = response.getHost();
                } else {
                    assertThat(response.getHost(), equalTo(selectedHost));
                }
            }
            failureListener.assertNotCalled();
            //selected to be retried earlier (due to lower number of failures) till all the hosts have the same number of failures
            for (int y = 0; y < i + 1; y++) {
                retryEndpoint = randomErrorRetryEndpoint();
                try {
                    restClient.performRequest(randomHttpMethod(getRandom()), retryEndpoint);
                    fail("request should have failed");
                } catch (ResponseException e) {
                    Response response = e.getResponse();
                    assertThat(response.getStatusLine().getStatusCode(), equalTo(Integer.parseInt(retryEndpoint.substring(1))));
                    assertThat(response.getHost(), equalTo(selectedHost));
                    failureListener.assertCalled(selectedHost);
                } catch (IOException e) {
                    HttpHost httpHost = HttpHost.create(e.getMessage());
                    assertThat(httpHost, equalTo(selectedHost));
                    failureListener.assertCalled(selectedHost);
                }
            }
        }
    }
}
Also used : BasicHttpResponse(org.apache.http.message.BasicHttpResponse) HttpResponse(org.apache.http.HttpResponse) HashSet(java.util.HashSet) Set(java.util.Set) HttpHost(org.apache.http.HttpHost) IOException(java.io.IOException) HashSet(java.util.HashSet)

Aggregations

HttpHost (org.apache.http.HttpHost)598 IOException (java.io.IOException)111 CredentialsProvider (org.apache.http.client.CredentialsProvider)105 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)102 HttpResponse (org.apache.http.HttpResponse)101 AuthScope (org.apache.http.auth.AuthScope)101 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)99 Test (org.junit.Test)86 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)84 URI (java.net.URI)68 HttpGet (org.apache.http.client.methods.HttpGet)66 HttpRequest (org.apache.http.HttpRequest)60 Header (org.apache.http.Header)56 HttpClientBuilder (org.apache.http.impl.client.HttpClientBuilder)56 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)48 HttpEntity (org.apache.http.HttpEntity)47 RequestConfig (org.apache.http.client.config.RequestConfig)45 BasicScheme (org.apache.http.impl.auth.BasicScheme)45 URISyntaxException (java.net.URISyntaxException)44 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)43