Search in sources :

Example 1 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 2 with ResourceAlreadyExistsException

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

the class TransportBulkAction method doInternalExecute.

protected void doInternalExecute(Task task, BulkRequest bulkRequest, String executorName, ActionListener<BulkResponse> listener) {
    final long startTime = relativeTime();
    final AtomicArray<BulkItemResponse> responses = new AtomicArray<>(bulkRequest.requests.size());
    boolean hasIndexRequestsWithPipelines = false;
    final Metadata metadata = clusterService.state().getMetadata();
    final Version minNodeVersion = clusterService.state().getNodes().getMinNodeVersion();
    for (DocWriteRequest<?> actionRequest : bulkRequest.requests) {
        IndexRequest indexRequest = getIndexWriteRequest(actionRequest);
        if (indexRequest != null) {
            // Each index request needs to be evaluated, because this method also modifies the IndexRequest
            boolean indexRequestHasPipeline = IngestService.resolvePipelines(actionRequest, indexRequest, metadata);
            hasIndexRequestsWithPipelines |= indexRequestHasPipeline;
        }
        if (actionRequest instanceof IndexRequest) {
            IndexRequest ir = (IndexRequest) actionRequest;
            ir.checkAutoIdWithOpTypeCreateSupportedByVersion(minNodeVersion);
            if (ir.getAutoGeneratedTimestamp() != IndexRequest.UNSET_AUTO_GENERATED_TIMESTAMP) {
                throw new IllegalArgumentException("autoGeneratedTimestamp should not be set externally");
            }
        }
    }
    if (hasIndexRequestsWithPipelines) {
        // this path is never taken.
        try {
            if (Assertions.ENABLED) {
                final boolean arePipelinesResolved = bulkRequest.requests().stream().map(TransportBulkAction::getIndexWriteRequest).filter(Objects::nonNull).allMatch(IndexRequest::isPipelineResolved);
                assert arePipelinesResolved : bulkRequest;
            }
            if (clusterService.localNode().isIngestNode()) {
                processBulkIndexIngestRequest(task, bulkRequest, executorName, listener);
            } else {
                ingestForwarder.forwardIngestRequest(BulkAction.INSTANCE, bulkRequest, listener);
            }
        } catch (Exception e) {
            listener.onFailure(e);
        }
        return;
    }
    final boolean includesSystem = includesSystem(bulkRequest, clusterService.state().metadata().getIndicesLookup(), systemIndices);
    if (includesSystem || needToCheck()) {
        // Attempt to create all the indices that we're going to need during the bulk before we start.
        // Step 1: collect all the indices in the request
        final Map<String, Boolean> indices = bulkRequest.requests.stream().filter(request -> request.opType() != DocWriteRequest.OpType.DELETE || request.versionType() == VersionType.EXTERNAL || request.versionType() == VersionType.EXTERNAL_GTE).collect(Collectors.toMap(DocWriteRequest::index, DocWriteRequest::isRequireAlias, (v1, v2) -> v1 || v2));
        /* Step 2: filter that to indices that don't exist and we can create. At the same time build a map of indices we can't create
             * that we'll use when we try to run the requests. */
        final Map<String, IndexNotFoundException> indicesThatCannotBeCreated = new HashMap<>();
        Set<String> autoCreateIndices = new HashSet<>();
        ClusterState state = clusterService.state();
        for (Map.Entry<String, Boolean> indexAndFlag : indices.entrySet()) {
            boolean shouldAutoCreate;
            final String index = indexAndFlag.getKey();
            try {
                shouldAutoCreate = shouldAutoCreate(index, state);
            } catch (IndexNotFoundException e) {
                shouldAutoCreate = false;
                indicesThatCannotBeCreated.put(index, e);
            }
            // We should only auto create if we are not requiring it to be an alias
            if (shouldAutoCreate && (indexAndFlag.getValue() == false)) {
                autoCreateIndices.add(index);
            }
        }
        // Step 3: create all the indices that are missing, if there are any missing. start the bulk after all the creates come back.
        if (autoCreateIndices.isEmpty()) {
            executeBulk(task, bulkRequest, startTime, listener, responses, indicesThatCannotBeCreated);
        } else {
            final AtomicInteger counter = new AtomicInteger(autoCreateIndices.size());
            for (String index : autoCreateIndices) {
                createIndex(index, bulkRequest.timeout(), minNodeVersion, new ActionListener<CreateIndexResponse>() {

                    @Override
                    public void onResponse(CreateIndexResponse result) {
                        if (counter.decrementAndGet() == 0) {
                            threadPool.executor(executorName).execute(new ActionRunnable<BulkResponse>(listener) {

                                @Override
                                protected void doRun() {
                                    executeBulk(task, bulkRequest, startTime, listener, responses, indicesThatCannotBeCreated);
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(Exception e) {
                        if (!(ExceptionsHelper.unwrapCause(e) instanceof ResourceAlreadyExistsException)) {
                            // fail all requests involving this index, if create didn't work
                            for (int i = 0; i < bulkRequest.requests.size(); i++) {
                                DocWriteRequest<?> request = bulkRequest.requests.get(i);
                                if (request != null && setResponseFailureIfIndexMatches(responses, i, request, index, e)) {
                                    bulkRequest.requests.set(i, null);
                                }
                            }
                        }
                        if (counter.decrementAndGet() == 0) {
                            final ActionListener<BulkResponse> wrappedListener = ActionListener.wrap(listener::onResponse, inner -> {
                                inner.addSuppressed(e);
                                listener.onFailure(inner);
                            });
                            threadPool.executor(executorName).execute(new ActionRunnable<BulkResponse>(wrappedListener) {

                                @Override
                                protected void doRun() {
                                    executeBulk(task, bulkRequest, startTime, wrappedListener, responses, indicesThatCannotBeCreated);
                                }

                                @Override
                                public void onRejection(Exception rejectedException) {
                                    rejectedException.addSuppressed(e);
                                    super.onRejection(rejectedException);
                                }
                            });
                        }
                    }
                });
            }
        }
    } else {
        executeBulk(task, bulkRequest, startTime, listener, responses, emptyMap());
    }
}
Also used : SequenceNumbers(org.opensearch.index.seqno.SequenceNumbers) IndexAbstraction(org.opensearch.cluster.metadata.IndexAbstraction) Metadata(org.opensearch.cluster.metadata.Metadata) LongSupplier(java.util.function.LongSupplier) DataStream(org.opensearch.cluster.metadata.DataStream) Version(org.opensearch.Version) TransportUpdateAction(org.opensearch.action.update.TransportUpdateAction) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Assertions(org.opensearch.Assertions) Map(java.util.Map) NodeClosedException(org.opensearch.node.NodeClosedException) AutoCreateAction(org.opensearch.action.admin.indices.create.AutoCreateAction) Inject(org.opensearch.common.inject.Inject) ActionListener(org.opensearch.action.ActionListener) AtomicIntegerArray(java.util.concurrent.atomic.AtomicIntegerArray) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) TimeValue(org.opensearch.common.unit.TimeValue) NodeClient(org.opensearch.client.node.NodeClient) Index(org.opensearch.index.Index) IndexingPressureService(org.opensearch.index.IndexingPressureService) OpenSearchParseException(org.opensearch.OpenSearchParseException) ExceptionsHelper(org.opensearch.ExceptionsHelper) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) Set(java.util.Set) Task(org.opensearch.tasks.Task) TransportService(org.opensearch.transport.TransportService) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ActionFilters(org.opensearch.action.support.ActionFilters) VersionType(org.opensearch.index.VersionType) List(java.util.List) Logger(org.apache.logging.log4j.Logger) SparseFixedBitSet(org.apache.lucene.util.SparseFixedBitSet) EXCLUDED_DATA_STREAMS_KEY(org.opensearch.cluster.metadata.IndexNameExpressionResolver.EXCLUDED_DATA_STREAMS_KEY) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) DocWriteResponse(org.opensearch.action.DocWriteResponse) UpdateRequest(org.opensearch.action.update.UpdateRequest) SortedMap(java.util.SortedMap) IndexNameExpressionResolver(org.opensearch.cluster.metadata.IndexNameExpressionResolver) Names(org.opensearch.threadpool.ThreadPool.Names) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) HandledTransportAction(org.opensearch.action.support.HandledTransportAction) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) ActionRunnable(org.opensearch.action.ActionRunnable) UpdateResponse(org.opensearch.action.update.UpdateResponse) ThreadPool(org.opensearch.threadpool.ThreadPool) RoutingMissingException(org.opensearch.action.RoutingMissingException) DocWriteRequest(org.opensearch.action.DocWriteRequest) HashMap(java.util.HashMap) Releasable(org.opensearch.common.lease.Releasable) ArrayList(java.util.ArrayList) AutoCreateIndex(org.opensearch.action.support.AutoCreateIndex) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) UNASSIGNED_SEQ_NO(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_SEQ_NO) LegacyESVersion(org.opensearch.LegacyESVersion) IndexClosedException(org.opensearch.indices.IndexClosedException) ClusterStateObserver(org.opensearch.cluster.ClusterStateObserver) Collections.emptyMap(java.util.Collections.emptyMap) IngestService(org.opensearch.ingest.IngestService) Iterator(java.util.Iterator) IngestActionForwarder(org.opensearch.action.ingest.IngestActionForwarder) ClusterBlockLevel(org.opensearch.cluster.block.ClusterBlockLevel) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) UNASSIGNED_PRIMARY_TERM(org.opensearch.index.seqno.SequenceNumbers.UNASSIGNED_PRIMARY_TERM) ShardId(org.opensearch.index.shard.ShardId) TimeUnit(java.util.concurrent.TimeUnit) SystemIndices(org.opensearch.indices.SystemIndices) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) ClusterService(org.opensearch.cluster.service.ClusterService) IndexRequest(org.opensearch.action.index.IndexRequest) LogManager(org.apache.logging.log4j.LogManager) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) ActionRunnable(org.opensearch.action.ActionRunnable) HashMap(java.util.HashMap) Metadata(org.opensearch.cluster.metadata.Metadata) MappingMetadata(org.opensearch.cluster.metadata.MappingMetadata) IndexMetadata(org.opensearch.cluster.metadata.IndexMetadata) CreateIndexRequest(org.opensearch.action.admin.indices.create.CreateIndexRequest) IndexRequest(org.opensearch.action.index.IndexRequest) Version(org.opensearch.Version) LegacyESVersion(org.opensearch.LegacyESVersion) CreateIndexResponse(org.opensearch.action.admin.indices.create.CreateIndexResponse) HashSet(java.util.HashSet) ClusterState(org.opensearch.cluster.ClusterState) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) NodeClosedException(org.opensearch.node.NodeClosedException) OpenSearchParseException(org.opensearch.OpenSearchParseException) ClusterBlockException(org.opensearch.cluster.block.ClusterBlockException) ResourceAlreadyExistsException(org.opensearch.ResourceAlreadyExistsException) RoutingMissingException(org.opensearch.action.RoutingMissingException) IndexClosedException(org.opensearch.indices.IndexClosedException) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) ActionListener(org.opensearch.action.ActionListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IndexNotFoundException(org.opensearch.index.IndexNotFoundException) DocWriteRequest(org.opensearch.action.DocWriteRequest) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) Collections.emptyMap(java.util.Collections.emptyMap)

Example 3 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 4 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 5 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)

Aggregations

ResourceAlreadyExistsException (org.opensearch.ResourceAlreadyExistsException)10 IOException (java.io.IOException)4 ClusterState (org.opensearch.cluster.ClusterState)4 LogManager (org.apache.logging.log4j.LogManager)3 Logger (org.apache.logging.log4j.Logger)3 OpenSearchException (org.opensearch.OpenSearchException)3 ActionListener (org.opensearch.action.ActionListener)3 CreateIndexRequest (org.opensearch.action.admin.indices.create.CreateIndexRequest)3 ClusterService (org.opensearch.cluster.service.ClusterService)3 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 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)2 DocWriteResponse (org.opensearch.action.DocWriteResponse)2 IndexRequest (org.opensearch.action.index.IndexRequest)2 UpdateRequest (org.opensearch.action.update.UpdateRequest)2