Search in sources :

Example 6 with ResourceAlreadyExistsException

use of org.opensearch.ResourceAlreadyExistsException in project OpenSearch by opensearch-project.

the class IndicesService method createIndex.

/**
 * Creates a new {@link IndexService} for the given metadata.
 *
 * @param indexMetadata          the index metadata to create the index for
 * @param builtInListeners       a list of built-in lifecycle {@link IndexEventListener} that should should be used along side with the
 *                               per-index listeners
 * @throws ResourceAlreadyExistsException if the index already exists.
 */
@Override
public synchronized IndexService createIndex(final IndexMetadata indexMetadata, final List<IndexEventListener> builtInListeners, final boolean writeDanglingIndices) throws IOException {
    ensureChangesAllowed();
    if (indexMetadata.getIndexUUID().equals(IndexMetadata.INDEX_UUID_NA_VALUE)) {
        throw new IllegalArgumentException("index must have a real UUID found value: [" + indexMetadata.getIndexUUID() + "]");
    }
    final Index index = indexMetadata.getIndex();
    if (hasIndex(index)) {
        throw new ResourceAlreadyExistsException(index);
    }
    List<IndexEventListener> finalListeners = new ArrayList<>(builtInListeners);
    final IndexEventListener onStoreClose = new IndexEventListener() {

        @Override
        public void onStoreCreated(ShardId shardId) {
            indicesRefCount.incRef();
        }

        @Override
        public void onStoreClosed(ShardId shardId) {
            try {
                indicesQueryCache.onClose(shardId);
            } finally {
                indicesRefCount.decRef();
            }
        }
    };
    finalListeners.add(onStoreClose);
    finalListeners.add(oldShardsStats);
    final IndexService indexService = createIndexService(CREATE_INDEX, indexMetadata, indicesQueryCache, indicesFieldDataCache, finalListeners, indexingMemoryController);
    boolean success = false;
    try {
        if (writeDanglingIndices && nodeWriteDanglingIndicesInfo) {
            indexService.addMetadataListener(imd -> updateDanglingIndicesInfo(index));
        }
        indexService.getIndexEventListener().afterIndexCreated(indexService);
        indices = newMapBuilder(indices).put(index.getUUID(), indexService).immutableMap();
        if (writeDanglingIndices) {
            if (nodeWriteDanglingIndicesInfo) {
                updateDanglingIndicesInfo(index);
            } else {
                indexService.deleteDanglingIndicesInfo();
            }
        }
        success = true;
        return indexService;
    } finally {
        if (success == false) {
            indexService.close("plugins_failed", true);
        }
    }
}
Also used : ShardId(org.opensearch.index.shard.ShardId) IndexEventListener(org.opensearch.index.shard.IndexEventListener) IndexService(org.opensearch.index.IndexService) ArrayList(java.util.ArrayList) CollectionUtils.arrayAsArrayList(org.opensearch.common.util.CollectionUtils.arrayAsArrayList) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) Index(org.opensearch.index.Index)

Example 7 with ResourceAlreadyExistsException

use of org.opensearch.ResourceAlreadyExistsException in project OpenSearch by opensearch-project.

the class IndicesService method withTempIndexService.

public <T, E extends Exception> T withTempIndexService(final IndexMetadata indexMetadata, CheckedFunction<IndexService, T, E> indexServiceConsumer) throws IOException, E {
    final Index index = indexMetadata.getIndex();
    if (hasIndex(index)) {
        throw new ResourceAlreadyExistsException(index);
    }
    List<IndexEventListener> finalListeners = Collections.singletonList(// double check that shard is not created.
    new IndexEventListener() {

        @Override
        public void beforeIndexShardCreated(ShardId shardId, Settings indexSettings) {
            assert false : "temp index should not trigger shard creation";
            throw new OpenSearchException("temp index should not trigger shard creation [{}]", index);
        }

        @Override
        public void onStoreCreated(ShardId shardId) {
            assert false : "temp index should not trigger store creation";
            throw new OpenSearchException("temp index should not trigger store creation [{}]", index);
        }
    });
    final IndexService indexService = createIndexService(CREATE_INDEX, indexMetadata, indicesQueryCache, indicesFieldDataCache, finalListeners, indexingMemoryController);
    try (Closeable dummy = () -> indexService.close("temp", false)) {
        return indexServiceConsumer.apply(indexService);
    }
}
Also used : ShardId(org.opensearch.index.shard.ShardId) IndexEventListener(org.opensearch.index.shard.IndexEventListener) IndexService(org.opensearch.index.IndexService) Closeable(java.io.Closeable) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) Index(org.opensearch.index.Index) OpenSearchException(org.opensearch.OpenSearchException) IndexScopedSettings(org.opensearch.common.settings.IndexScopedSettings) Settings(org.opensearch.common.settings.Settings) IndexSettings(org.opensearch.index.IndexSettings)

Example 8 with ResourceAlreadyExistsException

use of org.opensearch.ResourceAlreadyExistsException in project OpenSearch by opensearch-project.

the class RolloverIT method testRolloverOnExistingIndex.

public void testRolloverOnExistingIndex() throws Exception {
    assertAcked(prepareCreate("test_index-0").addAlias(new Alias("test_alias")).get());
    index("test_index-0", "type1", "1", "field", "value");
    assertAcked(prepareCreate("test_index-000001").get());
    index("test_index-000001", "type1", "1", "field", "value");
    flush("test_index-0", "test_index-000001");
    try {
        client().admin().indices().prepareRolloverIndex("test_alias").get();
        fail("expected failure due to existing rollover index");
    } catch (ResourceAlreadyExistsException e) {
        assertThat(e.getIndex().getName(), equalTo("test_index-000001"));
    }
}
Also used : Alias(org.opensearch.action.admin.indices.alias.Alias) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException)

Example 9 with ResourceAlreadyExistsException

use of org.opensearch.ResourceAlreadyExistsException in project OpenSearch by opensearch-project.

the class MetadataCreateDataStreamService method createDataStream.

static ClusterState createDataStream(MetadataCreateIndexService metadataCreateIndexService, ClusterState currentState, CreateDataStreamClusterStateUpdateRequest request) throws Exception {
    if (currentState.nodes().getMinNodeVersion().before(LegacyESVersion.V_7_9_0)) {
        throw new IllegalStateException("data streams require minimum node version of " + LegacyESVersion.V_7_9_0);
    }
    if (currentState.metadata().dataStreams().containsKey(request.name)) {
        throw new ResourceAlreadyExistsException("data_stream [" + request.name + "] already exists");
    }
    MetadataCreateIndexService.validateIndexOrAliasName(request.name, (s1, s2) -> new IllegalArgumentException("data_stream [" + s1 + "] " + s2));
    if (request.name.toLowerCase(Locale.ROOT).equals(request.name) == false) {
        throw new IllegalArgumentException("data_stream [" + request.name + "] must be lowercase");
    }
    if (request.name.startsWith(".")) {
        throw new IllegalArgumentException("data_stream [" + request.name + "] must not start with '.'");
    }
    ComposableIndexTemplate template = lookupTemplateForDataStream(request.name, currentState.metadata());
    String firstBackingIndexName = DataStream.getDefaultBackingIndexName(request.name, 1);
    CreateIndexClusterStateUpdateRequest createIndexRequest = new CreateIndexClusterStateUpdateRequest("initialize_data_stream", firstBackingIndexName, firstBackingIndexName).dataStreamName(request.name).settings(Settings.builder().put("index.hidden", true).build());
    try {
        currentState = metadataCreateIndexService.applyCreateIndexRequest(currentState, createIndexRequest, false);
    } catch (ResourceAlreadyExistsException e) {
        // (otherwise bulk execution fails later, because data stream will also not have been created)
        throw new OpenSearchStatusException("data stream could not be created because backing index [{}] already exists", RestStatus.BAD_REQUEST, e, firstBackingIndexName);
    }
    IndexMetadata firstBackingIndex = currentState.metadata().index(firstBackingIndexName);
    assert firstBackingIndex != null;
    assert firstBackingIndex.mapping() != null : "no mapping found for backing index [" + firstBackingIndexName + "]";
    String fieldName = template.getDataStreamTemplate().getTimestampField().getName();
    DataStream.TimestampField timestampField = new DataStream.TimestampField(fieldName);
    DataStream newDataStream = new DataStream(request.name, timestampField, Collections.singletonList(firstBackingIndex.getIndex()));
    Metadata.Builder builder = Metadata.builder(currentState.metadata()).put(newDataStream);
    logger.info("adding data stream [{}]", request.name);
    return ClusterState.builder(currentState).metadata(builder).build();
}
Also used : ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) CreateIndexClusterStateUpdateRequest(org.opensearch.action.admin.indices.create.CreateIndexClusterStateUpdateRequest) OpenSearchStatusException(org.opensearch.OpenSearchStatusException)

Example 10 with ResourceAlreadyExistsException

use of org.opensearch.ResourceAlreadyExistsException in project job-scheduler by opensearch-project.

the class LockService method createLockIndex.

@VisibleForTesting
void createLockIndex(ActionListener<Boolean> listener) {
    if (lockIndexExist()) {
        listener.onResponse(true);
    } else {
        final CreateIndexRequest request = new CreateIndexRequest(LOCK_INDEX_NAME).mapping(lockMapping());
        client.admin().indices().create(request, ActionListener.wrap(response -> listener.onResponse(response.isAcknowledged()), exception -> {
            if (exception instanceof ResourceAlreadyExistsException || exception.getCause() instanceof ResourceAlreadyExistsException) {
                listener.onResponse(true);
            } else {
                listener.onFailure(exception);
            }
        }));
    }
}
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) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) VisibleForTesting(com.cronutils.utils.VisibleForTesting)

Aggregations

ResourceAlreadyExistsException (org.opensearch.ResourceAlreadyExistsException)19 CreateIndexResponse (org.opensearch.action.admin.indices.create.CreateIndexResponse)10 CreateIndexRequest (org.opensearch.action.admin.indices.create.CreateIndexRequest)6 ActionListener (org.opensearch.action.ActionListener)5 IOException (java.io.IOException)4 LogManager (org.apache.logging.log4j.LogManager)4 Logger (org.apache.logging.log4j.Logger)4 OpenSearchException (org.opensearch.OpenSearchException)4 ClusterState (org.opensearch.cluster.ClusterState)4 ClusterService (org.opensearch.cluster.service.ClusterService)4 Index (org.opensearch.index.Index)3 ShardId (org.opensearch.index.shard.ShardId)3 InputStream (java.io.InputStream)2 StandardCharsets (java.nio.charset.StandardCharsets)2 ArrayList (java.util.ArrayList)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 Set (java.util.Set)2 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)2 ExceptionsHelper (org.opensearch.ExceptionsHelper)2