Search in sources :

Example 1 with CREATED

use of org.opensearch.action.DocWriteResponse.Result.CREATED in project OpenSearch by opensearch-project.

the class ClusterDisruptionIT method testAckedIndexing.

/**
 * Test that we do not loose document whose indexing request was successful, under a randomly selected disruption scheme
 * We also collect & report the type of indexing failures that occur.
 * <p>
 * This test is a superset of tests run in the Jepsen test suite, with the exception of versioned updates
 */
@TestIssueLogging(value = "_root:DEBUG,org.opensearch.action.bulk:TRACE,org.opensearch.action.get:TRACE," + "org.opensearch.discovery:TRACE,org.opensearch.action.support.replication:TRACE," + "org.opensearch.cluster.service:TRACE,org.opensearch.indices.recovery:TRACE," + "org.opensearch.indices.cluster:TRACE,org.opensearch.index.shard:TRACE", issueUrl = "https://github.com/elastic/elasticsearch/issues/41068")
public void testAckedIndexing() throws Exception {
    final int seconds = !(TEST_NIGHTLY && rarely()) ? 1 : 5;
    final String timeout = seconds + "s";
    final List<String> nodes = startCluster(rarely() ? 5 : 3);
    assertAcked(prepareCreate("test").setSettings(Settings.builder().put(indexSettings()).put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1 + randomInt(2)).put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, randomInt(2))));
    ensureGreen();
    ServiceDisruptionScheme disruptionScheme = addRandomDisruptionScheme();
    logger.info("disruption scheme [{}] added", disruptionScheme);
    // id -> node sent.
    final ConcurrentHashMap<String, String> ackedDocs = new ConcurrentHashMap<>();
    final AtomicBoolean stop = new AtomicBoolean(false);
    List<Thread> indexers = new ArrayList<>(nodes.size());
    List<Semaphore> semaphores = new ArrayList<>(nodes.size());
    final AtomicInteger idGenerator = new AtomicInteger(0);
    final AtomicReference<CountDownLatch> countDownLatchRef = new AtomicReference<>();
    final List<Exception> exceptedExceptions = new CopyOnWriteArrayList<>();
    final ConflictMode conflictMode = ConflictMode.randomMode();
    final List<String> fieldNames = IntStream.rangeClosed(0, randomInt(10)).mapToObj(n -> "f" + n).collect(Collectors.toList());
    logger.info("starting indexers using conflict mode " + conflictMode);
    try {
        for (final String node : nodes) {
            final Semaphore semaphore = new Semaphore(0);
            semaphores.add(semaphore);
            final Client client = client(node);
            final String name = "indexer_" + indexers.size();
            final int numPrimaries = getNumShards("test").numPrimaries;
            Thread thread = new Thread(() -> {
                while (!stop.get()) {
                    String id = null;
                    try {
                        if (!semaphore.tryAcquire(10, TimeUnit.SECONDS)) {
                            continue;
                        }
                        logger.info("[{}] Acquired semaphore and it has {} permits left", name, semaphore.availablePermits());
                        try {
                            id = Integer.toString(idGenerator.incrementAndGet());
                            int shard = Math.floorMod(Murmur3HashFunction.hash(id), numPrimaries);
                            logger.trace("[{}] indexing id [{}] through node [{}] targeting shard [{}]", name, id, node, shard);
                            IndexRequestBuilder indexRequestBuilder = client.prepareIndex("test").setId(id).setSource(Collections.singletonMap(randomFrom(fieldNames), randomNonNegativeLong()), XContentType.JSON).setTimeout(timeout);
                            if (conflictMode == ConflictMode.external) {
                                indexRequestBuilder.setVersion(randomIntBetween(1, 10)).setVersionType(VersionType.EXTERNAL);
                            } else if (conflictMode == ConflictMode.create) {
                                indexRequestBuilder.setCreate(true);
                            }
                            IndexResponse response = indexRequestBuilder.get(timeout);
                            assertThat(response.getResult(), is(oneOf(CREATED, UPDATED)));
                            ackedDocs.put(id, node);
                            logger.trace("[{}] indexed id [{}] through node [{}], response [{}]", name, id, node, response);
                        } catch (OpenSearchException e) {
                            exceptedExceptions.add(e);
                            final String docId = id;
                            logger.trace(() -> new ParameterizedMessage("[{}] failed id [{}] through node [{}]", name, docId, node), e);
                        } finally {
                            countDownLatchRef.get().countDown();
                            logger.trace("[{}] decreased counter : {}", name, countDownLatchRef.get().getCount());
                        }
                    } catch (InterruptedException e) {
                    // fine - semaphore interrupt
                    } catch (AssertionError | Exception e) {
                        logger.info(() -> new ParameterizedMessage("unexpected exception in background thread of [{}]", node), e);
                    }
                }
            });
            thread.setName(name);
            thread.start();
            indexers.add(thread);
        }
        int docsPerIndexer = randomInt(3);
        logger.info("indexing {} docs per indexer before partition", docsPerIndexer);
        countDownLatchRef.set(new CountDownLatch(docsPerIndexer * indexers.size()));
        for (Semaphore semaphore : semaphores) {
            semaphore.release(docsPerIndexer);
        }
        assertTrue(countDownLatchRef.get().await(1, TimeUnit.MINUTES));
        for (int iter = 1 + randomInt(2); iter > 0; iter--) {
            logger.info("starting disruptions & indexing (iteration [{}])", iter);
            disruptionScheme.startDisrupting();
            docsPerIndexer = 1 + randomInt(5);
            logger.info("indexing {} docs per indexer during partition", docsPerIndexer);
            countDownLatchRef.set(new CountDownLatch(docsPerIndexer * indexers.size()));
            Collections.shuffle(semaphores, random());
            for (Semaphore semaphore : semaphores) {
                assertThat(semaphore.availablePermits(), equalTo(0));
                semaphore.release(docsPerIndexer);
            }
            logger.info("waiting for indexing requests to complete");
            assertTrue(countDownLatchRef.get().await(docsPerIndexer * seconds * 1000 + 2000, TimeUnit.MILLISECONDS));
            logger.info("stopping disruption");
            disruptionScheme.stopDisrupting();
            for (String node : internalCluster().getNodeNames()) {
                ensureStableCluster(nodes.size(), TimeValue.timeValueMillis(disruptionScheme.expectedTimeToHeal().millis() + DISRUPTION_HEALING_OVERHEAD.millis()), true, node);
            }
            // is the super-connected node and recovery source and target are on opposite sides of the bridge
            if (disruptionScheme instanceof NetworkDisruption && ((NetworkDisruption) disruptionScheme).getDisruptedLinks() instanceof Bridge) {
                assertBusy(() -> assertAcked(client().admin().cluster().prepareReroute().setRetryFailed(true)));
            }
            ensureGreen("test");
            logger.info("validating successful docs");
            assertBusy(() -> {
                for (String node : nodes) {
                    try {
                        logger.debug("validating through node [{}] ([{}] acked docs)", node, ackedDocs.size());
                        for (String id : ackedDocs.keySet()) {
                            assertTrue("doc [" + id + "] indexed via node [" + ackedDocs.get(id) + "] not found", client(node).prepareGet("test", id).setPreference("_local").get().isExists());
                        }
                    } catch (AssertionError | NoShardAvailableActionException e) {
                        throw new AssertionError(e.getMessage() + " (checked via node [" + node + "]", e);
                    }
                }
            }, 30, TimeUnit.SECONDS);
            logger.info("done validating (iteration [{}])", iter);
        }
    } finally {
        logger.info("shutting down indexers");
        stop.set(true);
        for (Thread indexer : indexers) {
            indexer.interrupt();
            indexer.join(60000);
        }
        if (exceptedExceptions.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (Exception e : exceptedExceptions) {
                sb.append("\n").append(e.getMessage());
            }
            logger.debug("Indexing exceptions during disruption: {}", sb);
        }
    }
}
Also used : IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) ClusterBootstrapService(org.opensearch.cluster.coordination.ClusterBootstrapService) IndexResponse(org.opensearch.action.index.IndexResponse) Matchers.not(org.hamcrest.Matchers.not) OpenSearchException(org.opensearch.OpenSearchException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) ConcurrentCollections(org.opensearch.common.util.concurrent.ConcurrentCollections) Bridge(org.opensearch.test.disruption.NetworkDisruption.Bridge) IndexShardTestCase(org.opensearch.index.shard.IndexShardTestCase) Matchers.everyItem(org.hamcrest.Matchers.everyItem) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) ShardStateAction(org.opensearch.cluster.action.shard.ShardStateAction) Client(org.opensearch.client.Client) TimeValue(org.opensearch.common.unit.TimeValue) IndicesService(org.opensearch.indices.IndicesService) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) Settings(org.opensearch.common.settings.Settings) ServiceDisruptionScheme(org.opensearch.test.disruption.ServiceDisruptionScheme) Collectors(java.util.stream.Collectors) CountDownLatch(java.util.concurrent.CountDownLatch) VersionType(org.opensearch.index.VersionType) List(java.util.List) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) CREATED(org.opensearch.action.DocWriteResponse.Result.CREATED) Matchers.equalTo(org.hamcrest.Matchers.equalTo) LagDetector(org.opensearch.cluster.coordination.LagDetector) XContentType(org.opensearch.common.xcontent.XContentType) Matchers.is(org.hamcrest.Matchers.is) OpenSearchIntegTestCase(org.opensearch.test.OpenSearchIntegTestCase) Matchers.in(org.hamcrest.Matchers.in) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) IntStream(java.util.stream.IntStream) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) InternalTestCluster(org.opensearch.test.InternalTestCluster) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) ClusterState(org.opensearch.cluster.ClusterState) IndexShard(org.opensearch.index.shard.IndexShard) Murmur3HashFunction(org.opensearch.cluster.routing.Murmur3HashFunction) ShardRoutingState(org.opensearch.cluster.routing.ShardRoutingState) TestIssueLogging(org.opensearch.test.junit.annotations.TestIssueLogging) OpenSearchAssertions.assertAcked(org.opensearch.test.hamcrest.OpenSearchAssertions.assertAcked) Matchers.oneOf(org.hamcrest.Matchers.oneOf) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Semaphore(java.util.concurrent.Semaphore) ShardRouting(org.opensearch.cluster.routing.ShardRouting) TimeUnit(java.util.concurrent.TimeUnit) TwoPartitions(org.opensearch.test.disruption.NetworkDisruption.TwoPartitions) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) Collections(java.util.Collections) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) ServiceDisruptionScheme(org.opensearch.test.disruption.ServiceDisruptionScheme) Semaphore(java.util.concurrent.Semaphore) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Client(org.opensearch.client.Client) NetworkDisruption(org.opensearch.test.disruption.NetworkDisruption) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchException(org.opensearch.OpenSearchException) CorruptIndexException(org.apache.lucene.index.CorruptIndexException) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) IndexRequestBuilder(org.opensearch.action.index.IndexRequestBuilder) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) NoShardAvailableActionException(org.opensearch.action.NoShardAvailableActionException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IndexResponse(org.opensearch.action.index.IndexResponse) OpenSearchException(org.opensearch.OpenSearchException) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Bridge(org.opensearch.test.disruption.NetworkDisruption.Bridge) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TestIssueLogging(org.opensearch.test.junit.annotations.TestIssueLogging)

Example 2 with CREATED

use of org.opensearch.action.DocWriteResponse.Result.CREATED in project anomaly-detection by opensearch-project.

the class AnomalyDetectorJobRunner method stopAdJob.

private void stopAdJob(String detectorId, AnomalyDetectorFunction function) {
    GetRequest getRequest = new GetRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX).id(detectorId);
    ActionListener<GetResponse> listener = ActionListener.wrap(response -> {
        if (response.isExists()) {
            try (XContentParser parser = XContentType.JSON.xContent().createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, response.getSourceAsString())) {
                ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser);
                AnomalyDetectorJob job = AnomalyDetectorJob.parse(parser);
                if (job.isEnabled()) {
                    AnomalyDetectorJob newJob = new AnomalyDetectorJob(job.getName(), job.getSchedule(), job.getWindowDelay(), false, job.getEnabledTime(), Instant.now(), Instant.now(), job.getLockDurationSeconds(), job.getUser(), job.getResultIndex());
                    IndexRequest indexRequest = new IndexRequest(AnomalyDetectorJob.ANOMALY_DETECTOR_JOB_INDEX).setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).source(newJob.toXContent(XContentBuilder.builder(XContentType.JSON.xContent()), XCONTENT_WITH_TYPE)).id(detectorId);
                    client.index(indexRequest, ActionListener.wrap(indexResponse -> {
                        if (indexResponse != null && (indexResponse.getResult() == CREATED || indexResponse.getResult() == UPDATED)) {
                            log.info("AD Job was disabled by JobRunner for " + detectorId);
                        // function.execute();
                        } else {
                            log.warn("Failed to disable AD job for " + detectorId);
                        }
                    }, exception -> {
                        log.error("JobRunner failed to update AD job as disabled for " + detectorId, exception);
                    }));
                } else {
                    log.info("AD Job was disabled for " + detectorId);
                // function.execute();
                }
            } catch (IOException e) {
                log.error("JobRunner failed to stop detector job " + detectorId, e);
            }
        } else {
            log.info("AD Job was not found for " + detectorId);
        // function.execute();
        }
    }, exception -> log.error("JobRunner failed to get detector job " + detectorId, exception));
    client.get(getRequest, ActionListener.runAfter(listener, () -> function.execute()));
}
Also used : ResourceNotFoundException(org.opensearch.ad.common.exception.ResourceNotFoundException) ADTaskState(org.opensearch.ad.model.ADTaskState) AnomalyDetectionException(org.opensearch.ad.common.exception.AnomalyDetectionException) AnomalyDetectorFunction(org.opensearch.ad.rest.handler.AnomalyDetectorFunction) XContentParser(org.opensearch.common.xcontent.XContentParser) AD_THREAD_POOL_NAME(org.opensearch.ad.AnomalyDetectorPlugin.AD_THREAD_POOL_NAME) DiscoveryNode(org.opensearch.cluster.node.DiscoveryNode) WriteRequest(org.opensearch.action.support.WriteRequest) ADIndex(org.opensearch.ad.indices.ADIndex) ActionListener(org.opensearch.action.ActionListener) GetResponse(org.opensearch.action.get.GetResponse) Client(org.opensearch.client.Client) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) Set(java.util.Set) XContentParserUtils.ensureExpectedToken(org.opensearch.common.xcontent.XContentParserUtils.ensureExpectedToken) ADTaskManager(org.opensearch.ad.task.ADTaskManager) Settings(org.opensearch.common.settings.Settings) Instant(java.time.Instant) UPDATED(org.opensearch.action.DocWriteResponse.Result.UPDATED) List(java.util.List) AnomalyResultAction(org.opensearch.ad.transport.AnomalyResultAction) Logger(org.apache.logging.log4j.Logger) AnomalyResult(org.opensearch.ad.model.AnomalyResult) CAN_NOT_FIND_LATEST_TASK(org.opensearch.ad.constant.CommonErrorMessages.CAN_NOT_FIND_LATEST_TASK) CREATED(org.opensearch.action.DocWriteResponse.Result.CREATED) IntervalSchedule(org.opensearch.jobscheduler.spi.schedule.IntervalSchedule) XContentType(org.opensearch.common.xcontent.XContentType) InjectSecurity(org.opensearch.commons.InjectSecurity) JobExecutionContext(org.opensearch.jobscheduler.spi.JobExecutionContext) DiscoveryNodeFilterer(org.opensearch.ad.util.DiscoveryNodeFilterer) AnomalyIndexHandler(org.opensearch.ad.transport.handler.AnomalyIndexHandler) AnomalyResultRequest(org.opensearch.ad.transport.AnomalyResultRequest) ThreadPool(org.opensearch.threadpool.ThreadPool) FeatureData(org.opensearch.ad.model.FeatureData) AnomalyDetectorSettings(org.opensearch.ad.settings.AnomalyDetectorSettings) ArrayList(java.util.ArrayList) ProfileRequest(org.opensearch.ad.transport.ProfileRequest) XCONTENT_WITH_TYPE(org.opensearch.ad.util.RestHandlerUtils.XCONTENT_WITH_TYPE) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) LockModel(org.opensearch.jobscheduler.spi.LockModel) ExecutorService(java.util.concurrent.ExecutorService) EndRunException(org.opensearch.ad.common.exception.EndRunException) LockService(org.opensearch.jobscheduler.spi.utils.LockService) InternalFailure(org.opensearch.ad.common.exception.InternalFailure) GetRequest(org.opensearch.action.get.GetRequest) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) AnomalyDetectionIndices(org.opensearch.ad.indices.AnomalyDetectionIndices) DetectorProfileName(org.opensearch.ad.model.DetectorProfileName) ScheduledJobParameter(org.opensearch.jobscheduler.spi.ScheduledJobParameter) AnomalyResultTransportAction(org.opensearch.ad.transport.AnomalyResultTransportAction) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) User(org.opensearch.commons.authuser.User) AnomalyResultResponse(org.opensearch.ad.transport.AnomalyResultResponse) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ScheduledJobRunner(org.opensearch.jobscheduler.spi.ScheduledJobRunner) IndexRequest(org.opensearch.action.index.IndexRequest) IntervalTimeConfiguration(org.opensearch.ad.model.IntervalTimeConfiguration) LogManager(org.apache.logging.log4j.LogManager) ProfileAction(org.opensearch.ad.transport.ProfileAction) GetRequest(org.opensearch.action.get.GetRequest) IOException(java.io.IOException) AnomalyDetectorJob(org.opensearch.ad.model.AnomalyDetectorJob) IndexRequest(org.opensearch.action.index.IndexRequest) GetResponse(org.opensearch.action.get.GetResponse) XContentParser(org.opensearch.common.xcontent.XContentParser)

Aggregations

ArrayList (java.util.ArrayList)2 List (java.util.List)2 Set (java.util.Set)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 ActionListener (org.opensearch.action.ActionListener)2 CREATED (org.opensearch.action.DocWriteResponse.Result.CREATED)2 UPDATED (org.opensearch.action.DocWriteResponse.Result.UPDATED)2 GetResponse (org.opensearch.action.get.GetResponse)2 Client (org.opensearch.client.Client)2 Settings (org.opensearch.common.settings.Settings)2 XContentType (org.opensearch.common.xcontent.XContentType)2 Throwables (com.google.common.base.Throwables)1 ImmutableList (com.google.common.collect.ImmutableList)1 IOException (java.io.IOException)1 Instant (java.time.Instant)1 Collections (java.util.Collections)1 HashSet (java.util.HashSet)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutorService (java.util.concurrent.ExecutorService)1