Search in sources :

Example 36 with RestClient

use of org.opensearch.client.RestClient in project OpenSearch by opensearch-project.

the class RemoteScrollableHitSourceTests method testCleanupSuccessful.

public void testCleanupSuccessful() throws Exception {
    AtomicBoolean cleanupCallbackCalled = new AtomicBoolean();
    RestClient client = mock(RestClient.class);
    TestRemoteScrollableHitSource hitSource = new TestRemoteScrollableHitSource(client);
    hitSource.cleanup(() -> cleanupCallbackCalled.set(true));
    verify(client).close();
    assertTrue(cleanupCallbackCalled.get());
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RestClient(org.opensearch.client.RestClient)

Example 37 with RestClient

use of org.opensearch.client.RestClient in project OpenSearch by opensearch-project.

the class RemoteScrollableHitSourceTests method sourceWithMockedClient.

private RemoteScrollableHitSource sourceWithMockedClient(boolean mockRemoteVersion, CloseableHttpAsyncClient httpClient) {
    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(RejectAwareActionListener<Version> listener) {
            if (mockRemoteVersion) {
                listener.onResponse(Version.CURRENT);
            } else {
                super.lookupRemoteVersion(listener);
            }
        }
    };
    if (mockRemoteVersion) {
        hitSource.remoteVersion = Version.CURRENT;
    }
    return hitSource;
}
Also used : OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) TimeValue.timeValueMinutes(org.opensearch.common.unit.TimeValue.timeValueMinutes) URL(java.net.URL) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) TestThreadPool(org.opensearch.threadpool.TestThreadPool) ByteSizeUnit(org.opensearch.common.unit.ByteSizeUnit) Version(org.opensearch.Version) FileSystemUtils(org.opensearch.common.io.FileSystemUtils) StatusLine(org.apache.http.StatusLine) Mockito.doThrow(org.mockito.Mockito.doThrow) Future(java.util.concurrent.Future) BackoffPolicy(org.opensearch.action.bulk.BackoffPolicy) After(org.junit.After) RestClient(org.opensearch.client.RestClient) HttpAsyncRequestProducer(org.apache.http.nio.protocol.HttpAsyncRequestProducer) ParsingException(org.opensearch.common.ParsingException) TimeValue(org.opensearch.common.unit.TimeValue) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) Response(org.opensearch.index.reindex.ScrollableHitSource.Response) StringEntity(org.apache.http.entity.StringEntity) CloseableHttpAsyncClient(org.apache.http.impl.nio.client.CloseableHttpAsyncClient) RestStatus(org.opensearch.rest.RestStatus) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) StandardCharsets(java.nio.charset.StandardCharsets) ScrollableHitSource(org.opensearch.index.reindex.ScrollableHitSource) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder) Stream(java.util.stream.Stream) BytesArray(org.opensearch.common.bytes.BytesArray) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) RejectAwareActionListener(org.opensearch.index.reindex.RejectAwareActionListener) Queue(java.util.Queue) Mockito.any(org.mockito.Mockito.any) Mockito.mock(org.mockito.Mockito.mock) TimeValue.timeValueMillis(org.opensearch.common.unit.TimeValue.timeValueMillis) ContentTooLongException(org.apache.http.ContentTooLongException) BasicStatusLine(org.apache.http.message.BasicStatusLine) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ByteSizeValue(org.opensearch.common.unit.ByteSizeValue) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) AtomicReference(java.util.concurrent.atomic.AtomicReference) HttpAsyncResponseConsumer(org.apache.http.nio.protocol.HttpAsyncResponseConsumer) Answer(org.mockito.stubbing.Answer) BasicHttpResponse(org.apache.http.message.BasicHttpResponse) InvocationOnMock(org.mockito.invocation.InvocationOnMock) LegacyESVersion(org.opensearch.LegacyESVersion) Streams(org.opensearch.common.io.Streams) SearchRequest(org.opensearch.action.search.SearchRequest) Matchers.hasSize(org.hamcrest.Matchers.hasSize) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) Matchers.empty(org.hamcrest.Matchers.empty) FutureCallback(org.apache.http.concurrent.FutureCallback) IOException(java.io.IOException) HeapBufferedAsyncResponseConsumer(org.opensearch.client.HeapBufferedAsyncResponseConsumer) Mockito.when(org.mockito.Mockito.when) InputStreamReader(java.io.InputStreamReader) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) ProtocolVersion(org.apache.http.ProtocolVersion) HttpResponse(org.apache.http.HttpResponse) InputStreamEntity(org.apache.http.entity.InputStreamEntity) HttpHost(org.apache.http.HttpHost) HttpHost(org.apache.http.HttpHost) RestClient(org.opensearch.client.RestClient) RejectAwareActionListener(org.opensearch.index.reindex.RejectAwareActionListener) HttpAsyncClientBuilder(org.apache.http.impl.nio.client.HttpAsyncClientBuilder)

Example 38 with RestClient

use of org.opensearch.client.RestClient in project OpenSearch by opensearch-project.

the class Zen2RestApiIT method testRollingRestartOfTwoNodeCluster.

public void testRollingRestartOfTwoNodeCluster() throws Exception {
    internalCluster().setBootstrapClusterManagerNodeIndex(1);
    final List<String> nodes = internalCluster().startNodes(2);
    createIndex("test", Settings.builder().put(UnassignedInfo.INDEX_DELAYED_NODE_LEFT_TIMEOUT_SETTING.getKey(), // assign shards
    TimeValue.ZERO).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, // causes rebalancing
    2).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1).build());
    ensureGreen("test");
    RestClient restClient = getRestClient();
    internalCluster().rollingRestart(new InternalTestCluster.RestartCallback() {

        @Override
        public void doAfterNodes(int n, Client client) throws IOException {
            ensureGreen("test");
            Response response = restClient.performRequest(new Request("POST", "/_cluster/voting_config_exclusions/" + internalCluster().getNodeNames()[n]));
            assertThat(response.getStatusLine().getStatusCode(), is(200));
        }

        @Override
        public Settings onNodeStopped(String nodeName) throws IOException {
            String viaNode = randomValueOtherThan(nodeName, () -> randomFrom(nodes));
            List<Node> allNodes = restClient.getNodes();
            try {
                restClient.setNodes(Collections.singletonList(new Node(HttpHost.create(internalCluster().getInstance(HttpServerTransport.class, viaNode).boundAddress().publishAddress().toString()))));
                Response deleteResponse = restClient.performRequest(new Request("DELETE", "/_cluster/voting_config_exclusions"));
                assertThat(deleteResponse.getStatusLine().getStatusCode(), is(200));
                ClusterHealthResponse clusterHealthResponse = client(viaNode).admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForNodes(Integer.toString(1)).setTimeout(TimeValue.timeValueSeconds(30L)).setWaitForYellowStatus().get();
                assertFalse(nodeName, clusterHealthResponse.isTimedOut());
                return Settings.EMPTY;
            } finally {
                restClient.setNodes(allNodes);
            }
        }
    });
    ensureStableCluster(2);
    ensureGreen("test");
    assertThat(internalCluster().size(), is(2));
}
Also used : ClusterHealthResponse(org.opensearch.action.admin.cluster.health.ClusterHealthResponse) Node(org.opensearch.client.Node) RestClient(org.opensearch.client.RestClient) Request(org.opensearch.client.Request) InternalTestCluster(org.opensearch.test.InternalTestCluster) IOException(java.io.IOException) ClusterHealthResponse(org.opensearch.action.admin.cluster.health.ClusterHealthResponse) Response(org.opensearch.client.Response) List(java.util.List) Client(org.opensearch.client.Client) RestClient(org.opensearch.client.RestClient) Settings(org.opensearch.common.settings.Settings)

Example 39 with RestClient

use of org.opensearch.client.RestClient in project OpenSearch by opensearch-project.

the class Reindexer method buildRestClient.

/**
 * Build the {@link RestClient} used for reindexing from remote clusters.
 *
 * @param remoteInfo connection information for the remote cluster
 * @param sslConfig configuration for potential outgoing HTTPS connections
 * @param taskId the id of the current task. This is added to the thread name for easier tracking
 * @param threadCollector a list in which we collect all the threads created by the client
 * @param restInterceptor an optional HttpRequestInterceptor
 */
static RestClient buildRestClient(RemoteInfo remoteInfo, ReindexSslConfig sslConfig, long taskId, List<Thread> threadCollector, Optional<HttpRequestInterceptor> restInterceptor) {
    Header[] clientHeaders = new Header[remoteInfo.getHeaders().size()];
    int i = 0;
    for (Map.Entry<String, String> header : remoteInfo.getHeaders().entrySet()) {
        clientHeaders[i++] = new BasicHeader(header.getKey(), header.getValue());
    }
    final RestClientBuilder builder = RestClient.builder(new HttpHost(remoteInfo.getHost(), remoteInfo.getPort(), remoteInfo.getScheme())).setDefaultHeaders(clientHeaders).setRequestConfigCallback(c -> {
        c.setConnectTimeout(Math.toIntExact(remoteInfo.getConnectTimeout().millis()));
        c.setSocketTimeout(Math.toIntExact(remoteInfo.getSocketTimeout().millis()));
        return c;
    }).setHttpClientConfigCallback(c -> {
        // Enable basic auth if it is configured
        if (remoteInfo.getUsername() != null) {
            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(remoteInfo.getUsername(), remoteInfo.getPassword());
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, creds);
            c.setDefaultCredentialsProvider(credentialsProvider);
        } else {
            restInterceptor.ifPresent(interceptor -> c.addInterceptorLast(interceptor));
        }
        // Stick the task id in the thread name so we can track down tasks from stack traces
        AtomicInteger threads = new AtomicInteger();
        c.setThreadFactory(r -> {
            String name = "es-client-" + taskId + "-" + threads.getAndIncrement();
            Thread t = new Thread(r, name);
            threadCollector.add(t);
            return t;
        });
        // Limit ourselves to one reactor thread because for now the search process is single threaded.
        c.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(1).build());
        c.setSSLStrategy(sslConfig.getStrategy());
        return c;
    });
    if (Strings.hasLength(remoteInfo.getPathPrefix()) && "/".equals(remoteInfo.getPathPrefix()) == false) {
        builder.setPathPrefix(remoteInfo.getPathPrefix());
    }
    return builder.build();
}
Also used : IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) BiFunction(java.util.function.BiFunction) RemoteScrollableHitSource(org.opensearch.index.reindex.remote.RemoteScrollableHitSource) Header(org.apache.http.Header) Strings(org.opensearch.common.Strings) XContentParser(org.opensearch.common.xcontent.XContentParser) RemoteReindexExtension(org.opensearch.index.reindex.spi.RemoteReindexExtension) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BackoffPolicy(org.opensearch.action.bulk.BackoffPolicy) BulkItemResponse(org.opensearch.action.bulk.BulkItemResponse) Map(java.util.Map) RestClient(org.opensearch.client.RestClient) RestClientBuilder(org.opensearch.client.RestClientBuilder) ActionListener(org.opensearch.action.ActionListener) HttpRequestInterceptor(org.apache.http.HttpRequestInterceptor) ScriptService(org.opensearch.script.ScriptService) Client(org.opensearch.client.Client) Collections.synchronizedList(java.util.Collections.synchronizedList) Collections.emptyList(java.util.Collections.emptyList) Script(org.opensearch.script.Script) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) VersionType(org.opensearch.index.VersionType) List(java.util.List) Logger(org.apache.logging.log4j.Logger) Optional(java.util.Optional) XContentType(org.opensearch.common.xcontent.XContentType) CredentialsProvider(org.apache.http.client.CredentialsProvider) BytesReference(org.opensearch.common.bytes.BytesReference) ThreadPool(org.opensearch.threadpool.ThreadPool) DocWriteRequest(org.opensearch.action.DocWriteRequest) ArrayList(java.util.ArrayList) Objects.requireNonNull(java.util.Objects.requireNonNull) VersionFieldMapper(org.opensearch.index.mapper.VersionFieldMapper) Versions(org.opensearch.common.lucene.uid.Versions) ParentTaskAssigningClient(org.opensearch.client.ParentTaskAssigningClient) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) INTERNAL(org.opensearch.index.VersionType.INTERNAL) AuthScope(org.apache.http.auth.AuthScope) BasicHeader(org.apache.http.message.BasicHeader) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) IndexRequest(org.opensearch.action.index.IndexRequest) HttpHost(org.apache.http.HttpHost) LogManager(org.apache.logging.log4j.LogManager) DeprecationHandler(org.opensearch.common.xcontent.DeprecationHandler) InputStream(java.io.InputStream) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) RestClientBuilder(org.opensearch.client.RestClientBuilder) BasicCredentialsProvider(org.apache.http.impl.client.BasicCredentialsProvider) CredentialsProvider(org.apache.http.client.CredentialsProvider) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpHost(org.apache.http.HttpHost) Map(java.util.Map) BasicHeader(org.apache.http.message.BasicHeader)

Example 40 with RestClient

use of org.opensearch.client.RestClient in project OpenSearch by opensearch-project.

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 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);
        boolean compat = nodes.getBWCVersion().compareTo(LegacyESVersion.fromId(6000000)) >= 0;
        assertSeqNoOnShards(index, nodes, compat ? numDocs : 0, newNodeClient);
        logger.info("allowing shards on all nodes");
        updateIndexSettings(index, Settings.builder().putNull("index.routing.allocation.include._name"));
        ensureGreen(index);
        assertOK(client().performRequest(new Request("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);
        compat = nodes.getBWCVersion().compareTo(LegacyESVersion.fromId(6000000)) >= 0;
        assertSeqNoOnShards(index, nodes, compat ? numDocs : 0, newNodeClient);
        Shard primary = buildShards(index, nodes, newNodeClient).stream().filter(Shard::isPrimary).findFirst().get();
        logger.info("moving primary to new node by excluding {}", primary.getNode().getNodeName());
        updateIndexSettings(index, Settings.builder().put("index.routing.allocation.exclude._name", primary.getNode().getNodeName()));
        ensureGreen(index);
        int numDocsOnNewPrimary = 0;
        final int numberOfDocsAfterMovingPrimary = 1 + randomInt(5);
        logger.info("indexing [{}] docs after moving primary", numberOfDocsAfterMovingPrimary);
        numDocsOnNewPrimary += indexDocs(index, numDocs, numberOfDocsAfterMovingPrimary);
        numDocs += numberOfDocsAfterMovingPrimary;
        compat = nodes.getBWCVersion().compareTo(LegacyESVersion.fromId(6000000)) >= 0;
        assertSeqNoOnShards(index, nodes, compat ? numDocs : 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");
        updateIndexSettings(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");
        updateIndexSettings(index, Settings.builder().put("index.number_of_replicas", 1));
        ensureGreen(index);
        assertOK(client().performRequest(new Request("POST", index + "/_refresh")));
        for (Shard shard : buildShards(index, nodes, newNodeClient)) {
            assertCount(index, "_only_nodes:" + shard.node.nodeName, numDocs);
        }
        compat = nodes.getBWCVersion().compareTo(LegacyESVersion.fromId(6000000)) >= 0;
        assertSeqNoOnShards(index, nodes, compat ? numDocs : numDocsOnNewPrimary, newNodeClient);
    }
}
Also used : HttpHost(org.apache.http.HttpHost) RestClient(org.opensearch.client.RestClient) Request(org.opensearch.client.Request) Settings(org.opensearch.common.settings.Settings)

Aggregations

RestClient (org.opensearch.client.RestClient)44 Request (org.opensearch.client.Request)20 Response (org.opensearch.client.Response)16 HttpHost (org.apache.http.HttpHost)13 IOException (java.io.IOException)9 ArrayList (java.util.ArrayList)7 Settings (org.opensearch.common.settings.Settings)7 List (java.util.List)6 DefaultScheduler (org.opensearch.client.sniff.Sniffer.DefaultScheduler)6 Scheduler (org.opensearch.client.sniff.Sniffer.Scheduler)6 CountDownLatch (java.util.concurrent.CountDownLatch)5 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)5 Node (org.opensearch.client.Node)5 Map (java.util.Map)4 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)4 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 ResponseException (org.opensearch.client.ResponseException)4 Environment (org.opensearch.env.Environment)4 TestEnvironment (org.opensearch.env.TestEnvironment)4