Search in sources :

Example 36 with IndicesOptions

use of org.elasticsearch.action.support.IndicesOptions in project crate by crate.

the class SnapshotRestoreDDLDispatcher method dispatch.

public CompletableFuture<Long> dispatch(final RestoreSnapshotAnalyzedStatement analysis) {
    boolean waitForCompletion = analysis.settings().getAsBoolean(WAIT_FOR_COMPLETION.settingName(), WAIT_FOR_COMPLETION.defaultValue());
    boolean ignoreUnavailable = analysis.settings().getAsBoolean(IGNORE_UNAVAILABLE.settingName(), IGNORE_UNAVAILABLE.defaultValue());
    // ignore_unavailable as set by statement
    IndicesOptions indicesOptions = IndicesOptions.fromOptions(ignoreUnavailable, true, true, false, IndicesOptions.lenientExpandOpen());
    FutureActionListener<RestoreSnapshotResponse, Long> listener = new FutureActionListener<>(Functions.constant(1L));
    resolveIndexNames(analysis.restoreTables(), ignoreUnavailable, transportActionProvider.transportGetSnapshotsAction(), analysis.repositoryName()).whenComplete((List<String> indexNames, Throwable t) -> {
        if (t == null) {
            RestoreSnapshotRequest request = new RestoreSnapshotRequest(analysis.repositoryName(), analysis.snapshotName()).indices(indexNames).indicesOptions(indicesOptions).settings(analysis.settings()).waitForCompletion(waitForCompletion).includeGlobalState(false).includeAliases(true);
            transportActionProvider.transportRestoreSnapshotAction().execute(request, listener);
        } else {
            listener.onFailure(t);
        }
    });
    return listener;
}
Also used : RestoreSnapshotRequest(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) FutureActionListener(io.crate.action.FutureActionListener) RestoreSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse)

Example 37 with IndicesOptions

use of org.elasticsearch.action.support.IndicesOptions in project engine by craftercms.

the class SiteAwareElasticsearchService method updateIndex.

/**
 * {@inheritDoc}
 */
@Override
protected void updateIndex(final SearchRequest request) {
    SiteContext siteContext = SiteContext.getCurrent();
    if (siteContext == null) {
        throw new IllegalStateException("Current site context not found");
    }
    // Generate the default alias for the current site
    String aliasName = String.format(indexIdFormat, siteContext.getSiteName());
    // Get the requested indices
    String[] currentIndices = request.indices();
    String[] updatedIndices;
    if (ArrayUtils.isNotEmpty(currentIndices)) {
        updatedIndices = new String[currentIndices.length + 1];
        // Add the site name prefix for all indices
        for (int i = 0; i < currentIndices.length; i++) {
            updatedIndices[i] = addPrefix(siteContext, currentIndices[i]);
        }
        // Also add the default index
        updatedIndices[currentIndices.length] = aliasName;
        // Add the site name prefix for the boosting if needed
        List<SearchSourceBuilder.IndexBoost> indexBoosts = new ArrayList<>(request.source().indexBoosts());
        if (isNotEmpty(indexBoosts)) {
            indexBoosts.forEach(indexBoost -> request.source().indexBoost(addPrefix(siteContext, indexBoost.getIndex()), indexBoost.getBoost()));
            // Prevent missing index errors, this is needed because the original index boost can't be removed
            IndicesOptions originalOptions = request.indicesOptions();
            request.indicesOptions(IndicesOptions.fromOptions(true, originalOptions.allowNoIndices(), originalOptions.expandWildcardsOpen(), originalOptions.expandWildcardsClosed(), originalOptions.allowAliasesToMultipleIndices(), originalOptions.forbidClosedIndices(), originalOptions.ignoreAliases(), originalOptions.ignoreThrottled()));
        }
    } else {
        // Only query the default index
        updatedIndices = new String[] { aliasName };
    }
    request.indices(updatedIndices);
}
Also used : SiteContext(org.craftercms.engine.service.context.SiteContext) ArrayList(java.util.ArrayList) IndicesOptions(org.elasticsearch.action.support.IndicesOptions)

Example 38 with IndicesOptions

use of org.elasticsearch.action.support.IndicesOptions in project crate by crate.

the class RestoreSnapshotPlan method executeOrFail.

@Override
public void executeOrFail(DependencyCarrier dependencies, PlannerContext plannerContext, RowConsumer consumer, Row parameters, SubQueryResults subQueryResults) {
    BoundRestoreSnapshot stmt = bind(restoreSnapshot, plannerContext.transactionContext(), dependencies.nodeContext(), parameters, subQueryResults, dependencies.schemas());
    var settings = stmt.settings();
    boolean ignoreUnavailable = IGNORE_UNAVAILABLE.get(settings);
    var transportActionProvider = dependencies.transportActionProvider();
    resolveIndexNames(restoreSnapshot.repository(), stmt.restoreTables(), ignoreUnavailable, transportActionProvider.transportGetSnapshotsAction()).whenComplete((ResolveIndicesAndTemplatesContext ctx, Throwable t) -> {
        if (t == null) {
            String[] indexNames = ctx.resolvedIndices().toArray(new String[0]);
            String[] templateNames = stmt.includeTables() && stmt.restoreTables().isEmpty() ? new String[] { ALL_TEMPLATES } : ctx.resolvedTemplates().toArray(new String[0]);
            // ignore_unavailable as set by statement
            IndicesOptions indicesOptions = IndicesOptions.fromOptions(ignoreUnavailable, true, true, false, IndicesOptions.lenientExpandOpen());
            RestoreSnapshotRequest request = new RestoreSnapshotRequest(restoreSnapshot.repository(), restoreSnapshot.snapshot()).indices(indexNames).templates(templateNames).indicesOptions(indicesOptions).settings(settings).waitForCompletion(WAIT_FOR_COMPLETION.get(settings)).includeIndices(stmt.includeTables()).includeAliases(stmt.includeTables()).includeCustomMetadata(stmt.includeCustomMetadata()).customMetadataTypes(stmt.customMetadataTypes()).includeGlobalSettings(stmt.includeGlobalSettings()).globalSettings(stmt.globalSettings());
            transportActionProvider.transportRestoreSnapshotAction().execute(request, new OneRowActionListener<>(consumer, r -> new Row1(r == null ? -1L : 1L)));
        }
    });
}
Also used : BoundRestoreSnapshot(io.crate.analyze.BoundRestoreSnapshot) PartitionAlreadyExistsException(io.crate.exceptions.PartitionAlreadyExistsException) IndexParts(io.crate.metadata.IndexParts) RelationName(io.crate.metadata.RelationName) CompletableFuture(java.util.concurrent.CompletableFuture) Operation(io.crate.metadata.table.Operation) GetSnapshotsRequest(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) Function(java.util.function.Function) PartitionName(io.crate.metadata.PartitionName) ArrayList(java.util.ArrayList) DependencyCarrier(io.crate.planner.DependencyCarrier) HashSet(java.util.HashSet) WAIT_FOR_COMPLETION(io.crate.analyze.SnapshotSettings.WAIT_FOR_COMPLETION) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) Settings(org.elasticsearch.common.settings.Settings) RestoreSnapshotRequest(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) SchemaUnknownException(io.crate.exceptions.SchemaUnknownException) BoundRestoreSnapshot(io.crate.analyze.BoundRestoreSnapshot) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) GenericPropertiesConverter(io.crate.analyze.GenericPropertiesConverter) OneRowActionListener(io.crate.execution.support.OneRowActionListener) FutureActionListener(io.crate.action.FutureActionListener) PartitionPropertiesAnalyzer.toPartitionName(io.crate.analyze.PartitionPropertiesAnalyzer.toPartitionName) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) DocTableInfo(io.crate.metadata.doc.DocTableInfo) AnalyzedRestoreSnapshot(io.crate.analyze.AnalyzedRestoreSnapshot) NodeContext(io.crate.metadata.NodeContext) Table(io.crate.sql.tree.Table) Set(java.util.Set) Lists2(io.crate.common.collections.Lists2) SnapshotSettings(io.crate.analyze.SnapshotSettings) RowConsumer(io.crate.data.RowConsumer) List(java.util.List) Row(io.crate.data.Row) RelationAlreadyExists(io.crate.exceptions.RelationAlreadyExists) Symbol(io.crate.expression.symbol.Symbol) PlannerContext(io.crate.planner.PlannerContext) IGNORE_UNAVAILABLE(io.crate.analyze.SnapshotSettings.IGNORE_UNAVAILABLE) Plan(io.crate.planner.Plan) SubQueryResults(io.crate.planner.operators.SubQueryResults) Schemas(io.crate.metadata.Schemas) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) RelationUnknown(io.crate.exceptions.RelationUnknown) TransportGetSnapshotsAction(org.elasticsearch.action.admin.cluster.snapshots.get.TransportGetSnapshotsAction) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) Row1(io.crate.data.Row1) RestoreSnapshotRequest(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest) IndicesOptions(org.elasticsearch.action.support.IndicesOptions)

Example 39 with IndicesOptions

use of org.elasticsearch.action.support.IndicesOptions in project crate by crate.

the class CreateSnapshotPlan method createRequest.

@VisibleForTesting
public static CreateSnapshotRequest createRequest(AnalyzedCreateSnapshot createSnapshot, CoordinatorTxnCtx txnCtx, NodeContext nodeCtx, Row parameters, SubQueryResults subQueryResults, Schemas schemas) {
    Function<? super Symbol, Object> eval = x -> SymbolEvaluator.evaluate(txnCtx, nodeCtx, x, parameters, subQueryResults);
    Settings settings = GenericPropertiesConverter.genericPropertiesToSettings(createSnapshot.properties().map(eval), SnapshotSettings.SETTINGS);
    boolean ignoreUnavailable = IGNORE_UNAVAILABLE.get(settings);
    final HashSet<String> snapshotIndices;
    final HashSet<String> templates = new HashSet<>();
    if (createSnapshot.tables().isEmpty()) {
        for (SchemaInfo schemaInfo : schemas) {
            for (TableInfo tableInfo : schemaInfo.getTables()) {
                // only check for user generated tables
                if (tableInfo instanceof DocTableInfo) {
                    Operation.blockedRaiseException(tableInfo, Operation.READ);
                }
            }
        }
        snapshotIndices = new HashSet<>(AnalyzedCreateSnapshot.ALL_INDICES);
    } else {
        snapshotIndices = new HashSet<>(createSnapshot.tables().size());
        for (Table<Symbol> table : createSnapshot.tables()) {
            DocTableInfo docTableInfo;
            try {
                docTableInfo = (DocTableInfo) schemas.resolveTableInfo(table.getName(), Operation.CREATE_SNAPSHOT, txnCtx.sessionContext().sessionUser(), txnCtx.sessionContext().searchPath());
            } catch (Exception e) {
                if (ignoreUnavailable && e instanceof ResourceUnknownException) {
                    LOGGER.info("Ignore unknown relation '{}' for the '{}' snapshot'", table.getName(), createSnapshot.snapshot());
                    continue;
                } else {
                    throw e;
                }
            }
            if (docTableInfo.isPartitioned()) {
                templates.add(PartitionName.templateName(docTableInfo.ident().schema(), docTableInfo.ident().name()));
            }
            if (table.partitionProperties().isEmpty()) {
                snapshotIndices.addAll(Arrays.asList(docTableInfo.concreteIndices()));
            } else {
                var partitionName = toPartitionName(docTableInfo, Lists2.map(table.partitionProperties(), x -> x.map(eval)));
                if (!docTableInfo.partitions().contains(partitionName)) {
                    if (!ignoreUnavailable) {
                        throw new PartitionUnknownException(partitionName);
                    } else {
                        LOGGER.info("ignoring unknown partition of table '{}' with ident '{}'", partitionName.relationName(), partitionName.ident());
                    }
                } else {
                    snapshotIndices.add(partitionName.asIndexName());
                }
            }
        }
    }
    return new CreateSnapshotRequest(createSnapshot.snapshot().getRepository(), createSnapshot.snapshot().getSnapshotId().getName()).includeGlobalState(createSnapshot.tables().isEmpty()).waitForCompletion(WAIT_FOR_COMPLETION.get(settings)).indices(snapshotIndices.toArray(new String[0])).indicesOptions(IndicesOptions.fromOptions(ignoreUnavailable, true, true, false, IndicesOptions.lenientExpandOpen())).templates(templates.stream().toList()).settings(settings);
}
Also used : Arrays(java.util.Arrays) Operation(io.crate.metadata.table.Operation) SnapshotInfo(org.elasticsearch.snapshots.SnapshotInfo) Function(java.util.function.Function) PartitionName(io.crate.metadata.PartitionName) DependencyCarrier(io.crate.planner.DependencyCarrier) HashSet(java.util.HashSet) WAIT_FOR_COMPLETION(io.crate.analyze.SnapshotSettings.WAIT_FOR_COMPLETION) SymbolEvaluator(io.crate.analyze.SymbolEvaluator) Settings(org.elasticsearch.common.settings.Settings) AnalyzedCreateSnapshot(io.crate.analyze.AnalyzedCreateSnapshot) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) GenericPropertiesConverter(io.crate.analyze.GenericPropertiesConverter) SnapshotState(org.elasticsearch.snapshots.SnapshotState) OneRowActionListener(io.crate.execution.support.OneRowActionListener) PartitionUnknownException(io.crate.exceptions.PartitionUnknownException) PartitionPropertiesAnalyzer.toPartitionName(io.crate.analyze.PartitionPropertiesAnalyzer.toPartitionName) SchemaInfo(io.crate.metadata.table.SchemaInfo) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) NodeContext(io.crate.metadata.NodeContext) CreateSnapshotException(io.crate.exceptions.CreateSnapshotException) Table(io.crate.sql.tree.Table) ResourceUnknownException(io.crate.exceptions.ResourceUnknownException) CreateSnapshotRequest(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest) Lists2(io.crate.common.collections.Lists2) SnapshotSettings(io.crate.analyze.SnapshotSettings) RowConsumer(io.crate.data.RowConsumer) Logger(org.apache.logging.log4j.Logger) Row(io.crate.data.Row) Symbol(io.crate.expression.symbol.Symbol) PlannerContext(io.crate.planner.PlannerContext) IGNORE_UNAVAILABLE(io.crate.analyze.SnapshotSettings.IGNORE_UNAVAILABLE) Plan(io.crate.planner.Plan) SubQueryResults(io.crate.planner.operators.SubQueryResults) Schemas(io.crate.metadata.Schemas) VisibleForTesting(io.crate.common.annotations.VisibleForTesting) LogManager(org.apache.logging.log4j.LogManager) Row1(io.crate.data.Row1) CoordinatorTxnCtx(io.crate.metadata.CoordinatorTxnCtx) DocTableInfo(io.crate.metadata.doc.DocTableInfo) PartitionUnknownException(io.crate.exceptions.PartitionUnknownException) Symbol(io.crate.expression.symbol.Symbol) ResourceUnknownException(io.crate.exceptions.ResourceUnknownException) PartitionUnknownException(io.crate.exceptions.PartitionUnknownException) CreateSnapshotException(io.crate.exceptions.CreateSnapshotException) ResourceUnknownException(io.crate.exceptions.ResourceUnknownException) CreateSnapshotRequest(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest) DocTableInfo(io.crate.metadata.doc.DocTableInfo) TableInfo(io.crate.metadata.table.TableInfo) Settings(org.elasticsearch.common.settings.Settings) SnapshotSettings(io.crate.analyze.SnapshotSettings) HashSet(java.util.HashSet) SchemaInfo(io.crate.metadata.table.SchemaInfo) VisibleForTesting(io.crate.common.annotations.VisibleForTesting)

Example 40 with IndicesOptions

use of org.elasticsearch.action.support.IndicesOptions in project crate by crate.

the class DeleteAllPartitions method executeOrFail.

@Override
public void executeOrFail(DependencyCarrier executor, PlannerContext plannerContext, RowConsumer consumer, Row params, SubQueryResults subQueryResults) {
    if (partitions.isEmpty()) {
        consumer.accept(InMemoryBatchIterator.of(new Row1(0L), SentinelRow.SENTINEL), null);
    } else {
        /*
             * table is partitioned, in case of concurrent "delete from partitions"
             * it could be that some partitions are already deleted,
             * so ignore it if some are missing
             */
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(partitions().toArray(new String[0])).indicesOptions(IndicesOptions.lenientExpandOpen());
        executor.transportActionProvider().transportDeleteIndexAction().execute(deleteIndexRequest, new OneRowActionListener<>(consumer, r -> Row1.ROW_COUNT_UNKNOWN));
    }
}
Also used : DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) InMemoryBatchIterator(io.crate.data.InMemoryBatchIterator) RowConsumer(io.crate.data.RowConsumer) DependencyCarrier(io.crate.planner.DependencyCarrier) List(java.util.List) Row(io.crate.data.Row) PlannerContext(io.crate.planner.PlannerContext) Plan(io.crate.planner.Plan) SubQueryResults(io.crate.planner.operators.SubQueryResults) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) OneRowActionListener(io.crate.execution.support.OneRowActionListener) SentinelRow(io.crate.data.SentinelRow) Row1(io.crate.data.Row1) Row1(io.crate.data.Row1) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest)

Aggregations

IndicesOptions (org.elasticsearch.action.support.IndicesOptions)39 ClusterState (org.elasticsearch.cluster.ClusterState)11 IndexNotFoundException (org.elasticsearch.index.IndexNotFoundException)11 ClusterName (org.elasticsearch.cluster.ClusterName)9 Matchers.containsString (org.hamcrest.Matchers.containsString)9 HashSet (java.util.HashSet)6 Set (java.util.Set)6 Arrays (java.util.Arrays)5 List (java.util.List)5 ArrayList (java.util.ArrayList)4 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)4 Row (io.crate.data.Row)3 Row1 (io.crate.data.Row1)3 RowConsumer (io.crate.data.RowConsumer)3 OneRowActionListener (io.crate.execution.support.OneRowActionListener)3 DependencyCarrier (io.crate.planner.DependencyCarrier)3 Plan (io.crate.planner.Plan)3 PlannerContext (io.crate.planner.PlannerContext)3 SubQueryResults (io.crate.planner.operators.SubQueryResults)3 IOException (java.io.IOException)3