Search in sources :

Example 1 with VersionConflictEngineException

use of org.opensearch.index.engine.VersionConflictEngineException in project OpenSearch by opensearch-project.

the class IndexStatsIT method testSimpleStats.

public void testSimpleStats() throws Exception {
    createIndex("test1", "test2");
    ensureGreen();
    client().prepareIndex("test1").setId(Integer.toString(1)).setSource("field", "value").execute().actionGet();
    client().prepareIndex("test1").setId(Integer.toString(2)).setSource("field", "value").execute().actionGet();
    client().prepareIndex("test2").setId(Integer.toString(1)).setSource("field", "value").execute().actionGet();
    refresh();
    NumShards test1 = getNumShards("test1");
    long test1ExpectedWrites = 2 * test1.dataCopies;
    NumShards test2 = getNumShards("test2");
    long test2ExpectedWrites = test2.dataCopies;
    long totalExpectedWrites = test1ExpectedWrites + test2ExpectedWrites;
    IndicesStatsResponse stats = client().admin().indices().prepareStats().execute().actionGet();
    assertThat(stats.getPrimaries().getDocs().getCount(), equalTo(3L));
    assertThat(stats.getTotal().getDocs().getCount(), equalTo(totalExpectedWrites));
    assertThat(stats.getPrimaries().getIndexing().getTotal().getIndexCount(), equalTo(3L));
    assertThat(stats.getPrimaries().getIndexing().getTotal().getIndexFailedCount(), equalTo(0L));
    assertThat(stats.getPrimaries().getIndexing().getTotal().isThrottled(), equalTo(false));
    assertThat(stats.getPrimaries().getIndexing().getTotal().getThrottleTime().millis(), equalTo(0L));
    assertThat(stats.getTotal().getIndexing().getTotal().getIndexCount(), equalTo(totalExpectedWrites));
    assertThat(stats.getTotal().getStore(), notNullValue());
    assertThat(stats.getTotal().getMerge(), notNullValue());
    assertThat(stats.getTotal().getFlush(), notNullValue());
    assertThat(stats.getTotal().getRefresh(), notNullValue());
    assertThat(stats.getIndex("test1").getPrimaries().getDocs().getCount(), equalTo(2L));
    assertThat(stats.getIndex("test1").getTotal().getDocs().getCount(), equalTo(test1ExpectedWrites));
    assertThat(stats.getIndex("test1").getPrimaries().getStore(), notNullValue());
    assertThat(stats.getIndex("test1").getPrimaries().getMerge(), notNullValue());
    assertThat(stats.getIndex("test1").getPrimaries().getFlush(), notNullValue());
    assertThat(stats.getIndex("test1").getPrimaries().getRefresh(), notNullValue());
    assertThat(stats.getIndex("test2").getPrimaries().getDocs().getCount(), equalTo(1L));
    assertThat(stats.getIndex("test2").getTotal().getDocs().getCount(), equalTo(test2ExpectedWrites));
    // make sure that number of requests in progress is 0
    assertThat(stats.getIndex("test1").getTotal().getIndexing().getTotal().getIndexCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test1").getTotal().getIndexing().getTotal().getDeleteCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test1").getTotal().getSearch().getTotal().getFetchCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test1").getTotal().getSearch().getTotal().getQueryCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test2").getTotal().getIndexing().getTotal().getIndexCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test2").getTotal().getIndexing().getTotal().getDeleteCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test2").getTotal().getSearch().getTotal().getFetchCurrent(), equalTo(0L));
    assertThat(stats.getIndex("test2").getTotal().getSearch().getTotal().getQueryCurrent(), equalTo(0L));
    // check flags
    stats = client().admin().indices().prepareStats().clear().setFlush(true).setRefresh(true).setMerge(true).execute().actionGet();
    assertThat(stats.getTotal().getDocs(), nullValue());
    assertThat(stats.getTotal().getStore(), nullValue());
    assertThat(stats.getTotal().getIndexing(), nullValue());
    assertThat(stats.getTotal().getMerge(), notNullValue());
    assertThat(stats.getTotal().getFlush(), notNullValue());
    assertThat(stats.getTotal().getRefresh(), notNullValue());
    // check get
    GetResponse getResponse = client().prepareGet("test2", "1").execute().actionGet();
    assertThat(getResponse.isExists(), equalTo(true));
    stats = client().admin().indices().prepareStats().execute().actionGet();
    assertThat(stats.getTotal().getGet().getCount(), equalTo(1L));
    assertThat(stats.getTotal().getGet().getExistsCount(), equalTo(1L));
    assertThat(stats.getTotal().getGet().getMissingCount(), equalTo(0L));
    // missing get
    getResponse = client().prepareGet("test2", "2").execute().actionGet();
    assertThat(getResponse.isExists(), equalTo(false));
    stats = client().admin().indices().prepareStats().execute().actionGet();
    assertThat(stats.getTotal().getGet().getCount(), equalTo(2L));
    assertThat(stats.getTotal().getGet().getExistsCount(), equalTo(1L));
    assertThat(stats.getTotal().getGet().getMissingCount(), equalTo(1L));
    // clear all
    stats = client().admin().indices().prepareStats().setDocs(false).setStore(false).setIndexing(false).setFlush(true).setRefresh(true).setMerge(true).clear().execute().actionGet();
    assertThat(stats.getTotal().getDocs(), nullValue());
    assertThat(stats.getTotal().getStore(), nullValue());
    assertThat(stats.getTotal().getIndexing(), nullValue());
    assertThat(stats.getTotal().getGet(), nullValue());
    assertThat(stats.getTotal().getSearch(), nullValue());
    // index failed
    try {
        client().prepareIndex("test1").setId(Integer.toString(1)).setSource("field", "value").setVersion(1).setVersionType(VersionType.EXTERNAL).execute().actionGet();
        fail("Expected a version conflict");
    } catch (VersionConflictEngineException e) {
    }
    try {
        client().prepareIndex("test2").setId(Integer.toString(1)).setSource("field", "value").setVersion(1).setVersionType(VersionType.EXTERNAL).execute().actionGet();
        fail("Expected a version conflict");
    } catch (VersionConflictEngineException e) {
    }
    try {
        client().prepareIndex("test2").setId(Integer.toString(1)).setSource("field", "value").setVersion(1).setVersionType(VersionType.EXTERNAL).execute().actionGet();
        fail("Expected a version conflict");
    } catch (VersionConflictEngineException e) {
    }
    stats = client().admin().indices().prepareStats().execute().actionGet();
    assertThat(stats.getIndex("test2").getPrimaries().getIndexing().getTotal().getIndexFailedCount(), equalTo(2L));
    assertThat(stats.getPrimaries().getIndexing().getTotal().getIndexFailedCount(), equalTo(3L));
}
Also used : IndicesStatsResponse(org.opensearch.action.admin.indices.stats.IndicesStatsResponse) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) GetResponse(org.opensearch.action.get.GetResponse)

Example 2 with VersionConflictEngineException

use of org.opensearch.index.engine.VersionConflictEngineException in project OpenSearch by opensearch-project.

the class TransportShardBulkActionTests method testRetries.

public void testRetries() throws Exception {
    IndexSettings indexSettings = new IndexSettings(indexMetadata(), Settings.EMPTY);
    UpdateRequest writeRequest = new UpdateRequest("index", "id").doc(Requests.INDEX_CONTENT_TYPE, "field", "value");
    // the beating will continue until success has come.
    writeRequest.retryOnConflict(Integer.MAX_VALUE);
    BulkItemRequest primaryRequest = new BulkItemRequest(0, writeRequest);
    IndexRequest updateResponse = new IndexRequest("index").id("id").source(Requests.INDEX_CONTENT_TYPE, "field", "value");
    Exception err = new VersionConflictEngineException(shardId, "id", "I'm conflicted <(;_;)>");
    Engine.IndexResult conflictedResult = new Engine.IndexResult(err, 0);
    Engine.IndexResult mappingUpdate = new Engine.IndexResult(new Mapping(null, mock(RootObjectMapper.class), new MetadataFieldMapper[0], Collections.emptyMap()));
    Translog.Location resultLocation = new Translog.Location(42, 42, 42);
    Engine.IndexResult success = new FakeIndexResult(1, 1, 13, true, resultLocation);
    IndexShard shard = mock(IndexShard.class);
    when(shard.applyIndexOperationOnPrimary(anyLong(), any(), any(), anyLong(), anyLong(), anyLong(), anyBoolean())).thenAnswer(ir -> {
        if (randomBoolean()) {
            return conflictedResult;
        }
        if (randomBoolean()) {
            return mappingUpdate;
        } else {
            return success;
        }
    });
    when(shard.indexSettings()).thenReturn(indexSettings);
    when(shard.shardId()).thenReturn(shardId);
    when(shard.mapperService()).thenReturn(mock(MapperService.class));
    UpdateHelper updateHelper = mock(UpdateHelper.class);
    when(updateHelper.prepare(any(), eq(shard), any())).thenReturn(new UpdateHelper.Result(updateResponse, randomBoolean() ? DocWriteResponse.Result.CREATED : DocWriteResponse.Result.UPDATED, Collections.singletonMap("field", "value"), Requests.INDEX_CONTENT_TYPE));
    BulkItemRequest[] items = new BulkItemRequest[] { primaryRequest };
    BulkShardRequest bulkShardRequest = new BulkShardRequest(shardId, RefreshPolicy.NONE, items);
    final CountDownLatch latch = new CountDownLatch(1);
    TransportShardBulkAction.performOnPrimary(bulkShardRequest, shard, updateHelper, threadPool::absoluteTimeInMillis, new NoopMappingUpdatePerformer(), listener -> listener.onResponse(null), new LatchedActionListener<>(ActionTestUtils.assertNoFailureListener(result -> {
        assertThat(((WritePrimaryResult<BulkShardRequest, BulkShardResponse>) result).location, equalTo(resultLocation));
        BulkItemResponse primaryResponse = result.replicaRequest().items()[0].getPrimaryResponse();
        assertThat(primaryResponse.getItemId(), equalTo(0));
        assertThat(primaryResponse.getId(), equalTo("id"));
        assertThat(primaryResponse.getOpType(), equalTo(DocWriteRequest.OpType.UPDATE));
        DocWriteResponse response = primaryResponse.getResponse();
        assertThat(response.status(), equalTo(RestStatus.CREATED));
        assertThat(response.getSeqNo(), equalTo(13L));
    }), latch), threadPool, Names.WRITE);
    latch.await();
}
Also used : IndexSettings(org.opensearch.index.IndexSettings) Mapping(org.opensearch.index.mapper.Mapping) IndexRequest(org.opensearch.action.index.IndexRequest) Translog(org.opensearch.index.translog.Translog) UpdateHelper(org.opensearch.action.update.UpdateHelper) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) Engine(org.opensearch.index.engine.Engine) UpdateRequest(org.opensearch.action.update.UpdateRequest) IndexShard(org.opensearch.index.shard.IndexShard) DocWriteResponse(org.opensearch.action.DocWriteResponse) CountDownLatch(java.util.concurrent.CountDownLatch) OpenSearchRejectedExecutionException(org.opensearch.common.util.concurrent.OpenSearchRejectedExecutionException) OpenSearchStatusException(org.opensearch.OpenSearchStatusException) OpenSearchException(org.opensearch.OpenSearchException) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) MetadataFieldMapper(org.opensearch.index.mapper.MetadataFieldMapper) MapperService(org.opensearch.index.mapper.MapperService)

Example 3 with VersionConflictEngineException

use of org.opensearch.index.engine.VersionConflictEngineException in project job-scheduler by opensearch-project.

the class LockService method acquireLock.

/**
 * Attempts to acquire lock the job. If the lock does not exists it attempts to create the lock document.
 * If the Lock document exists, it will try to update and acquire lock.
 *
 * @param jobParameter a {@code ScheduledJobParameter} containing the lock duration.
 * @param context a {@code JobExecutionContext} containing job index name and job id.
 * @param listener an {@code ActionListener} that has onResponse and onFailure that is used to return the lock if it was acquired
 *                 or else null. Passes {@code IllegalArgumentException} to onFailure if the {@code ScheduledJobParameter} does not
 *                 have {@code LockDurationSeconds}.
 */
public void acquireLock(final ScheduledJobParameter jobParameter, final JobExecutionContext context, ActionListener<LockModel> listener) {
    final String jobIndexName = context.getJobIndexName();
    final String jobId = context.getJobId();
    if (jobParameter.getLockDurationSeconds() == null) {
        listener.onFailure(new IllegalArgumentException("Job LockDuration should not be null"));
    } else {
        final long lockDurationSecond = jobParameter.getLockDurationSeconds();
        createLockIndex(ActionListener.wrap(created -> {
            if (created) {
                try {
                    findLock(LockModel.generateLockId(jobIndexName, jobId), ActionListener.wrap(existingLock -> {
                        if (existingLock != null) {
                            if (isLockReleasedOrExpired(existingLock)) {
                                // Lock is expired. Attempt to acquire lock.
                                logger.debug("lock is released or expired: " + existingLock);
                                LockModel updateLock = new LockModel(existingLock, getNow(), lockDurationSecond, false);
                                updateLock(updateLock, listener);
                            } else {
                                logger.debug("Lock is NOT released or expired. " + existingLock);
                                // Lock is still not expired. Return null as we cannot acquire lock.
                                listener.onResponse(null);
                            }
                        } else {
                            // There is no lock object and it is first time. Create new lock.
                            LockModel tempLock = new LockModel(jobIndexName, jobId, getNow(), lockDurationSecond, false);
                            logger.debug("Lock does not exist. Creating new lock" + tempLock);
                            createLock(tempLock, listener);
                        }
                    }, listener::onFailure));
                } catch (VersionConflictEngineException e) {
                    logger.debug("could not acquire lock {}", e.getMessage());
                    listener.onResponse(null);
                }
            } else {
                listener.onResponse(null);
            }
        }, listener::onFailure));
    }
}
Also used : SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) ToXContent(org.opensearch.common.xcontent.ToXContent) XContentParser(org.opensearch.common.xcontent.XContentParser) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) LockModel(org.opensearch.jobscheduler.spi.LockModel) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) DeleteRequest(org.opensearch.action.delete.DeleteRequest) Client(org.opensearch.client.Client) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) GetRequest(org.opensearch.action.get.GetRequest) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) IOException(java.io.IOException) DocumentMissingException(org.opensearch.index.engine.DocumentMissingException) Instant(java.time.Instant) ScheduledJobParameter(org.opensearch.jobscheduler.spi.ScheduledJobParameter) InputStreamReader(java.io.InputStreamReader) StandardCharsets(java.nio.charset.StandardCharsets) Logger(org.apache.logging.log4j.Logger) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterService(org.opensearch.cluster.service.ClusterService) VisibleForTesting(com.cronutils.utils.VisibleForTesting) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) DocWriteResponse(org.opensearch.action.DocWriteResponse) UpdateRequest(org.opensearch.action.update.UpdateRequest) XContentType(org.opensearch.common.xcontent.XContentType) JobExecutionContext(org.opensearch.jobscheduler.spi.JobExecutionContext) BufferedReader(java.io.BufferedReader) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) LockModel(org.opensearch.jobscheduler.spi.LockModel)

Example 4 with VersionConflictEngineException

use of org.opensearch.index.engine.VersionConflictEngineException in project bw-calendar-engine by Bedework.

the class BwIndexEsImpl method index.

/* Return the response after indexing */
private IndexResponse index(final Object rec, final boolean waitForIt, final boolean forTouch) throws CalFacadeException {
    EsDocInfo di = null;
    try {
        if (rec instanceof EventInfo) {
            mustBe(docTypeEvent);
            return indexEvent((EventInfo) rec, waitForIt);
        }
        final DocBuilder db = getDocBuilder();
        if (rec instanceof BwCalendar) {
            mustBe(docTypeCollection);
            di = db.makeDoc((BwCalendar) rec);
        }
        if (rec instanceof BwCategory) {
            mustBe(docTypeCategory);
            di = db.makeDoc((BwCategory) rec);
        }
        if (rec instanceof BwContact) {
            mustBe(docTypeContact);
            di = db.makeDoc((BwContact) rec);
        }
        if (rec instanceof BwLocation) {
            mustBe(docTypeLocation);
            di = db.makeDoc((BwLocation) rec);
        }
        if (rec instanceof BwPrincipal) {
            mustBe(docTypePrincipal);
            di = db.makeDoc((BwPrincipal) rec);
        }
        if (rec instanceof BwPreferences) {
            mustBe(docTypePreferences);
            di = db.makeDoc((BwPreferences) rec);
        }
        if (rec instanceof BwResource) {
            mustBe(docTypeResource);
            di = db.makeDoc((BwResource) rec);
        }
        if (rec instanceof BwResourceContent) {
            mustBe(docTypeResourceContent);
            di = db.makeDoc((BwResourceContent) rec);
        }
        if (rec instanceof BwFilterDef) {
            mustBe(docTypeFilter);
            di = db.makeDoc((BwFilterDef) rec);
        }
        if (di != null) {
            return indexDoc(di, waitForIt);
        }
        throw new CalFacadeException(new IndexException(IndexException.unknownRecordType, rec.getClass().getName()));
    } catch (final CalFacadeException cfe) {
        throw cfe;
    } catch (final VersionConflictEngineException vcee) {
        if (forTouch) {
            // Ignore - already touched
            return null;
        }
        error(vcee);
        throw new CalFacadeException(vcee);
    /* Can't do this any more
      if (vcee.currentVersion() == vcee.getProvidedVersion()) {
        warn("Failed index with equal version for type " + 
                     di.getType() +
                     " and id " + di.getId());
      }

      return null;
      */
    } catch (final Throwable t) {
        throw new CalFacadeException(t);
    }
}
Also used : BwLocation(org.bedework.calfacade.BwLocation) BwPreferences(org.bedework.calfacade.svc.BwPreferences) EventInfo(org.bedework.calfacade.svc.EventInfo) IndexException(org.bedework.util.indexing.IndexException) BwResource(org.bedework.calfacade.BwResource) BwCategory(org.bedework.calfacade.BwCategory) BwResourceContent(org.bedework.calfacade.BwResourceContent) BwCalendar(org.bedework.calfacade.BwCalendar) BwContact(org.bedework.calfacade.BwContact) CalFacadeException(org.bedework.calfacade.exc.CalFacadeException) BwPrincipal(org.bedework.calfacade.BwPrincipal) VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) EsDocInfo(org.bedework.util.opensearch.EsDocInfo) BwFilterDef(org.bedework.calfacade.BwFilterDef)

Example 5 with VersionConflictEngineException

use of org.opensearch.index.engine.VersionConflictEngineException in project bw-calendar-engine by Bedework.

the class BwIndexEsImpl method indexEvent.

private IndexResponse indexEvent(final EventInfo ei, final ItemKind kind, final BwDateTime start, final BwDateTime end, final String recurid, final boolean waitForIt) throws CalFacadeException {
    try {
        final DocBuilder db = getDocBuilder();
        final EsDocInfo di = db.makeDoc(ei, kind, start, end, recurid);
        // ei.getEvent().getTombstoned());
        return indexDoc(di, waitForIt);
    } catch (final CalFacadeException cfe) {
        throw cfe;
    } catch (final VersionConflictEngineException vcee) {
        error(vcee);
        throw new CalFacadeException(vcee);
    /* Can't do this any more
      if (vcee.currentVersion() == vcee.getProvidedVersion()) {
        warn("Failed index with equal version for type " +
                     di.getType() +
                     " and id " + di.getId());
      }

      return null;
      */
    } catch (final Throwable t) {
        throw new CalFacadeException(t);
    }
}
Also used : VersionConflictEngineException(org.opensearch.index.engine.VersionConflictEngineException) EsDocInfo(org.bedework.util.opensearch.EsDocInfo) CalFacadeException(org.bedework.calfacade.exc.CalFacadeException)

Aggregations

VersionConflictEngineException (org.opensearch.index.engine.VersionConflictEngineException)13 IOException (java.io.IOException)5 IndexRequest (org.opensearch.action.index.IndexRequest)5 UpdateRequest (org.opensearch.action.update.UpdateRequest)5 DocWriteResponse (org.opensearch.action.DocWriteResponse)4 VisibleForTesting (com.cronutils.utils.VisibleForTesting)3 BufferedReader (java.io.BufferedReader)3 InputStream (java.io.InputStream)3 InputStreamReader (java.io.InputStreamReader)3 StandardCharsets (java.nio.charset.StandardCharsets)3 Instant (java.time.Instant)3 LogManager (org.apache.logging.log4j.LogManager)3 Logger (org.apache.logging.log4j.Logger)3 ResourceAlreadyExistsException (org.opensearch.ResourceAlreadyExistsException)3 ActionListener (org.opensearch.action.ActionListener)3 CreateIndexRequest (org.opensearch.action.admin.indices.create.CreateIndexRequest)3 DeleteRequest (org.opensearch.action.delete.DeleteRequest)3 GetRequest (org.opensearch.action.get.GetRequest)3 GetResponse (org.opensearch.action.get.GetResponse)3 Client (org.opensearch.client.Client)3