org.elasticsearch.common.Priority Java Examples

The following examples show how to use org.elasticsearch.common.Priority. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PrioritizedEsThreadPoolExecutor.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public void execute(Runnable command, final ScheduledExecutorService timer, final TimeValue timeout, final Runnable timeoutCallback) {
    if (command instanceof PrioritizedRunnable) {
        command = new TieBreakingPrioritizedRunnable((PrioritizedRunnable) command, insertionOrder.incrementAndGet());
    } else if (!(command instanceof PrioritizedFutureTask)) { // it might be a callable wrapper...
        command = new TieBreakingPrioritizedRunnable(command, Priority.NORMAL, insertionOrder.incrementAndGet());
    }
    super.execute(command);
    if (timeout.nanos() >= 0) {
        if (command instanceof TieBreakingPrioritizedRunnable) {
            ((TieBreakingPrioritizedRunnable) command).scheduleTimeout(timer, timeoutCallback, timeout);
        } else {
            // We really shouldn't be here. The only way we can get here if somebody created PrioritizedFutureTask
            // and passed it to execute, which doesn't make much sense
            throw new UnsupportedOperationException("Execute with timeout is not supported for future tasks");
        }
    }
}
 
Example #2
Source File: MetaDataDeleteIndexService.java    From crate with Apache License 2.0 6 votes vote down vote up
public void deleteIndices(final DeleteIndexClusterStateUpdateRequest request,
        final ActionListener<ClusterStateUpdateResponse> listener) {
    if (request.indices() == null || request.indices().length == 0) {
        throw new IllegalArgumentException("Index name is required");
    }

    clusterService.submitStateUpdateTask(
        "delete-index " + Arrays.toString(request.indices()),
        new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(Priority.URGENT, request, listener) {

            @Override
            protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
                return new ClusterStateUpdateResponse(acknowledged);
            }

            @Override
            public ClusterState execute(final ClusterState currentState) {
                return deleteIndices(currentState, Sets.newHashSet(request.indices()));
            }
        }
    );
}
 
Example #3
Source File: TransportPrivilegesAction.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
protected void masterOperation(PrivilegesRequest request, ClusterState state, ActionListener<PrivilegesResponse> listener) throws Exception {
    clusterService.submitStateUpdateTask("grant_privileges",
        new AckedClusterStateUpdateTask<PrivilegesResponse>(Priority.IMMEDIATE, request, listener) {

            long affectedRows = -1;
            List<String> unknownUserNames = null;

            @Override
            public ClusterState execute(ClusterState currentState) throws Exception {
                MetaData currentMetaData = currentState.metaData();
                MetaData.Builder mdBuilder = MetaData.builder(currentMetaData);
                unknownUserNames = validateUserNames(currentMetaData, request.userNames());
                if (unknownUserNames.isEmpty()) {
                    affectedRows = applyPrivileges(mdBuilder, request);
                }
                return ClusterState.builder(currentState).metaData(mdBuilder).build();
            }

            @Override
            protected PrivilegesResponse newResponse(boolean acknowledged) {
                return new PrivilegesResponse(acknowledged, affectedRows, unknownUserNames);
            }
        });

}
 
Example #4
Source File: ESIntegTestCase.java    From crate with Apache License 2.0 6 votes vote down vote up
protected void ensureStableCluster(int nodeCount, TimeValue timeValue, boolean local, @Nullable String viaNode) {
    if (viaNode == null) {
        viaNode = randomFrom(internalCluster().getNodeNames());
    }
    logger.debug("ensuring cluster is stable with [{}] nodes. access node: [{}]. timeout: [{}]", nodeCount, viaNode, timeValue);
    ClusterHealthResponse clusterHealthResponse = client(viaNode).admin().cluster().prepareHealth()
        .setWaitForEvents(Priority.LANGUID)
        .setWaitForNodes(Integer.toString(nodeCount))
        .setTimeout(timeValue)
        .setLocal(local)
        .setWaitForNoRelocatingShards(true)
        .get();
    if (clusterHealthResponse.isTimedOut()) {
        ClusterStateResponse stateResponse = client(viaNode).admin().cluster().prepareState().get();
        fail("failed to reach a stable cluster of [" + nodeCount + "] nodes. Tried via [" + viaNode + "]. last cluster state:\n"
             + stateResponse.getState());
    }
    assertThat(clusterHealthResponse.isTimedOut(), is(false));
    ensureFullyConnectedCluster();
}
 
Example #5
Source File: TransportCreatePartitionsAction.java    From crate with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
void createIndices(final CreatePartitionsRequest request,
                   final ActionListener<ClusterStateUpdateResponse> listener) {
    clusterService.submitStateUpdateTask(
        "bulk-create-indices",
        request,
        ClusterStateTaskConfig.build(Priority.URGENT, request.masterNodeTimeout()),
        executor,
        new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(request, listener) {
            @Override
            public ClusterState execute(ClusterState currentState) throws Exception {
                return executeCreateIndices(currentState, request);
            }

            @Override
            protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
                return new ClusterStateUpdateResponse(acknowledged);
            }
        }
    );
}
 
Example #6
Source File: ClusterHealthRequest.java    From crate with Apache License 2.0 6 votes vote down vote up
public ClusterHealthRequest(StreamInput in) throws IOException {
    super(in);
    int size = in.readVInt();
    if (size == 0) {
        indices = Strings.EMPTY_ARRAY;
    } else {
        indices = new String[size];
        for (int i = 0; i < indices.length; i++) {
            indices[i] = in.readString();
        }
    }
    timeout = in.readTimeValue();
    if (in.readBoolean()) {
        waitForStatus = ClusterHealthStatus.fromValue(in.readByte());
    }
    waitForNoRelocatingShards = in.readBoolean();
    waitForActiveShards = ActiveShardCount.readFrom(in);
    waitForNodes = in.readString();
    if (in.readBoolean()) {
        waitForEvents = Priority.readFrom(in);
    }
    waitForNoInitializingShards = in.readBoolean();
}
 
Example #7
Source File: ClusterHealthRequest.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    int size = in.readVInt();
    if (size == 0) {
        indices = Strings.EMPTY_ARRAY;
    } else {
        indices = new String[size];
        for (int i = 0; i < indices.length; i++) {
            indices[i] = in.readString();
        }
    }
    timeout = readTimeValue(in);
    if (in.readBoolean()) {
        waitForStatus = ClusterHealthStatus.fromValue(in.readByte());
    }
    waitForRelocatingShards = in.readInt();
    waitForActiveShards = in.readInt();
    waitForNodes = in.readString();
    if (in.readBoolean()) {
        waitForEvents = Priority.readFrom(in);
    }
}
 
Example #8
Source File: MetaDataMappingService.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Refreshes mappings if they are not the same between original and parsed version
 */
public void refreshMapping(final String index, final String indexUUID) {
    final RefreshTask refreshTask = new RefreshTask(index, indexUUID);
    clusterService.submitStateUpdateTask("refresh-mapping",
        refreshTask,
        ClusterStateTaskConfig.build(Priority.HIGH),
        refreshExecutor,
        (source, e) -> LOGGER.warn(() -> new ParameterizedMessage("failure during [{}]", source), e)
    );
}
 
Example #9
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
/**
 * Wait for yellow state of a cluster.
 *
 * @param indices indices to check status
 * @return cluster health status
 */
public ClusterHealthStatus ensureYellow(final String... indices) {
    final ClusterHealthResponse actionGet = client().admin().cluster().health(Requests.clusterHealthRequest(indices)
            .waitForNoRelocatingShards(true).waitForYellowStatus().waitForEvents(Priority.LANGUID)).actionGet();
    if (actionGet.isTimedOut()) {
        onFailure("ensureYellow timed out, cluster state:\n" + "\n" + client().admin().cluster().prepareState().get().getState() + "\n"
                + client().admin().cluster().preparePendingClusterTasks().get(), actionGet);
    }
    return actionGet.getStatus();
}
 
Example #10
Source File: MetaDataCreateIndexService.java    From crate with Apache License 2.0 5 votes vote down vote up
IndexCreationTask(Logger logger, AllocationService allocationService, CreateIndexClusterStateUpdateRequest request,
                  ActionListener<ClusterStateUpdateResponse> listener, IndicesService indicesService,
                  AliasValidator aliasValidator, NamedXContentRegistry xContentRegistry,
                  Settings settings, IndexValidator validator, IndexScopedSettings indexScopedSettings) {
    super(Priority.URGENT, request, listener);
    this.request = request;
    this.logger = logger;
    this.allocationService = allocationService;
    this.indicesService = indicesService;
    this.aliasValidator = aliasValidator;
    this.xContentRegistry = xContentRegistry;
    this.settings = settings;
    this.validator = validator;
    this.indexScopedSettings = indexScopedSettings;
}
 
Example #11
Source File: ClusterApplierService.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void onNewClusterState(final String source, final Supplier<ClusterState> clusterStateSupplier,
                              final ClusterApplyListener listener) {
    Function<ClusterState, ClusterState> applyFunction = currentState -> {
        ClusterState nextState = clusterStateSupplier.get();
        if (nextState != null) {
            return nextState;
        } else {
            return currentState;
        }
    };
    submitStateUpdateTask(source, ClusterStateTaskConfig.build(Priority.HIGH), applyFunction, listener);
}
 
Example #12
Source File: PrioritizedEsThreadPoolExecutor.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    if (!(runnable instanceof PrioritizedRunnable)) {
        runnable = PrioritizedRunnable.wrap(runnable, Priority.NORMAL);
    }
    Priority priority = ((PrioritizedRunnable) runnable).priority();
    return new PrioritizedFutureTask<>(runnable, priority, value, insertionOrder.incrementAndGet());
}
 
Example #13
Source File: ESIntegTestCase.java    From crate with Apache License 2.0 5 votes vote down vote up
private ClusterHealthStatus ensureColor(ClusterHealthStatus clusterHealthStatus, TimeValue timeout, boolean waitForNoInitializingShards,
                                        String... indices) {
    String color = clusterHealthStatus.name().toLowerCase(Locale.ROOT);
    String method = "ensure" + Strings.capitalize(color);

    ClusterHealthRequest healthRequest = Requests.clusterHealthRequest(indices)
        .timeout(timeout)
        .waitForStatus(clusterHealthStatus)
        .waitForEvents(Priority.LANGUID)
        .waitForNoRelocatingShards(true)
        .waitForNoInitializingShards(waitForNoInitializingShards)
        // We currently often use ensureGreen or ensureYellow to check whether the cluster is back in a good state after shutting down
        // a node. If the node that is stopped is the master node, another node will become master and publish a cluster state where it
        // is master but where the node that was stopped hasn't been removed yet from the cluster state. It will only subsequently
        // publish a second state where the old master is removed. If the ensureGreen/ensureYellow is timed just right, it will get to
        // execute before the second cluster state update removes the old master and the condition ensureGreen / ensureYellow will
        // trivially hold if it held before the node was shut down. The following "waitForNodes" condition ensures that the node has
        // been removed by the master so that the health check applies to the set of nodes we expect to be part of the cluster.
        .waitForNodes(Integer.toString(cluster().size()));

    ClusterHealthResponse actionGet = client().admin().cluster().health(healthRequest).actionGet();
    if (actionGet.isTimedOut()) {
        logger.info("{} timed out, cluster state:\n{}\n{}",
            method,
            client().admin().cluster().prepareState().get().getState(),
            client().admin().cluster().preparePendingClusterTasks().get());
        fail("timed out waiting for " + color + " state");
    }
    assertThat("Expected at least " + clusterHealthStatus + " but got " + actionGet.getStatus(),
        actionGet.getStatus().value(), lessThanOrEqualTo(clusterHealthStatus.value()));
    logger.debug("indices {} are {}", indices.length == 0 ? "[_all]" : indices, color);
    return actionGet.getStatus();
}
 
Example #14
Source File: ShardStateAction.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(StartedShardEntry request, TransportChannel channel, Task task) throws Exception {
    logger.debug("{} received shard started for [{}]", request.shardId, request);
    clusterService.submitStateUpdateTask(
        "shard-started " + request,
        request,
        ClusterStateTaskConfig.build(Priority.URGENT),
        shardStartedClusterStateTaskExecutor,
        shardStartedClusterStateTaskExecutor);
    channel.sendResponse(TransportResponse.Empty.INSTANCE);
}
 
Example #15
Source File: TransportClusterRerouteAction.java    From crate with Apache License 2.0 5 votes vote down vote up
ClusterRerouteResponseAckedClusterStateUpdateTask(Logger logger, AllocationService allocationService, ClusterRerouteRequest request,
                                                  ActionListener<ClusterRerouteResponse> listener) {
    super(Priority.IMMEDIATE, request, listener);
    this.request = request;
    this.listener = listener;
    this.logger = logger;
    this.allocationService = allocationService;
}
 
Example #16
Source File: MockSinglePrioritizingExecutorTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public void testPrioritizedEsThreadPoolExecutor() {
    final DeterministicTaskQueue taskQueue = DeterministicTaskQueueTests.newTaskQueue();
    final PrioritizedEsThreadPoolExecutor executor = new MockSinglePrioritizingExecutor("test", taskQueue);
    final AtomicBoolean called1 = new AtomicBoolean();
    final AtomicBoolean called2 = new AtomicBoolean();
    executor.execute(new PrioritizedRunnable(Priority.NORMAL) {
        @Override
        public void run() {
            assertTrue(called1.compareAndSet(false, true)); // check that this is only called once
        }

    });
    executor.execute(new PrioritizedRunnable(Priority.HIGH) {
        @Override
        public void run() {
            assertTrue(called2.compareAndSet(false, true)); // check that this is only called once
        }
    });
    assertFalse(called1.get());
    assertFalse(called2.get());
    taskQueue.runRandomTask();
    assertFalse(called1.get());
    assertTrue(called2.get());
    taskQueue.runRandomTask();
    assertTrue(called1.get());
    assertTrue(called2.get());
    taskQueue.runRandomTask();
    assertFalse(taskQueue.hasRunnableTasks());
}
 
Example #17
Source File: ExtendedAnalyzeActionTests.java    From elasticsearch-extended-analyze with Apache License 2.0 5 votes vote down vote up
@Test
public void analyzeWithMultiValues() throws Exception {

    try {
        client().admin().indices().prepareDelete("test2").execute().actionGet();
    } catch (Exception e) {
        // ignore
    }

    //only analyzer =
    client().admin().indices().prepareCreate("test2").get();
    client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();

    client().admin().indices().preparePutMapping("test2")
        .setType("document").setSource("simple", "type=string,analyzer=simple,position_increment_gap=100").get();


    String[] texts = new String[]{"THIS IS A TEST", "THE SECOND TEXT"};
    ExtendedAnalyzeResponse analyzeResponse = prepareAnalyzeNoText(node.client().admin().indices(), "test2")
        .setField("simple").setShortAttributeName(true).setText(texts).execute().get();


    assertThat(analyzeResponse.analyzer().getName(), equalTo("simple"));
    assertThat(analyzeResponse.analyzer().getTokens().size(), equalTo(7));
    ExtendedAnalyzeResponse.ExtendedAnalyzeToken token = analyzeResponse.analyzer().getTokens().get(3);

    assertThat(token.getTerm(), equalTo("test"));
    assertThat(token.getPosition(), equalTo(3));
    assertThat(token.getStartOffset(), equalTo(10));
    assertThat(token.getEndOffset(), equalTo(14));

    token = analyzeResponse.analyzer().getTokens().get(5);
    assertThat(token.getTerm(), equalTo("second"));
    assertThat(token.getPosition(), equalTo(105));
    assertThat(token.getStartOffset(), equalTo(19));
    assertThat(token.getEndOffset(), equalTo(25));

}
 
Example #18
Source File: PendingClusterTask.java    From crate with Apache License 2.0 5 votes vote down vote up
public PendingClusterTask(long insertOrder, Priority priority, Text source, long timeInQueue, boolean executing) {
    assert timeInQueue >= 0 : "got a negative timeInQueue [" + timeInQueue + "]";
    assert insertOrder >= 0 : "got a negative insertOrder [" + insertOrder + "]";
    this.insertOrder = insertOrder;
    this.priority = priority;
    this.source = source;
    this.timeInQueue = timeInQueue;
    this.executing = executing;
}
 
Example #19
Source File: PendingClusterTask.java    From crate with Apache License 2.0 5 votes vote down vote up
public PendingClusterTask(StreamInput in) throws IOException {
    insertOrder = in.readVLong();
    priority = Priority.readFrom(in);
    source = in.readText();
    timeInQueue = in.readLong();
    executing = in.readBoolean();
}
 
Example #20
Source File: TestHelpers.java    From anomaly-detection with Apache License 2.0 5 votes vote down vote up
public static void waitForIndexCreationToComplete(Client client, final String indexName) {
    ClusterHealthResponse clusterHealthResponse = client
        .admin()
        .cluster()
        .prepareHealth(indexName)
        .setWaitForEvents(Priority.URGENT)
        .get();
    logger.info("Status of " + indexName + ": " + clusterHealthResponse.getStatus());
}
 
Example #21
Source File: PendingClusterTask.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    out.writeVLong(insertOrder);
    Priority.writeTo(priority, out);
    out.writeText(source);
    out.writeLong(timeInQueue);
    out.writeBoolean(executing);
}
 
Example #22
Source File: ExtendedAnalyzeActionTests.java    From elasticsearch-extended-analyze with Apache License 2.0 5 votes vote down vote up
@Test
public void simpleAnalyzerTests() throws Exception {
    try {
        client().admin().indices().prepareDelete("test").execute().actionGet();
    } catch (Exception e) {
        // ignore
    }

    client().admin().indices().prepareCreate("test").execute().actionGet();
    client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForGreenStatus().execute().actionGet();

    for (int i = 0; i < 10; i++) {
        ExtendedAnalyzeResponse analyzeResponse = prepareAnalyze(client().admin().indices(), "test", "THIS IS A PHISH").setCharFilters("my_mapping").setTokenizer("keyword").setTokenFilters("lowercase").execute().actionGet();

        assertThat(analyzeResponse.analyzer(), IsNull.nullValue());
        //charfilters
        // global charfilter is not change text.
        assertThat(analyzeResponse.charfilters().size(), equalTo(1));
        assertThat(analyzeResponse.charfilters().get(0).getName(), equalTo("my_mapping"));
        assertThat(analyzeResponse.charfilters().get(0).getTexts().size(), equalTo(1));
        assertThat(analyzeResponse.charfilters().get(0).getTexts().get(0), equalTo("THIS IS A FISH"));
        //tokenizer
        assertThat(analyzeResponse.tokenizer().getName(), equalTo("keyword"));
        assertThat(analyzeResponse.tokenizer().getTokens().size(), equalTo(1));
        assertThat(analyzeResponse.tokenizer().getTokens().get(0).getTerm(), equalTo("THIS IS A FISH"));
        assertThat(analyzeResponse.tokenizer().getTokens().get(0).getStartOffset(), equalTo(0));
        assertThat(analyzeResponse.tokenizer().getTokens().get(0).getEndOffset(), equalTo(15));
        //tokenfilters
        assertThat(analyzeResponse.tokenfilters().size(), equalTo(1));
        assertThat(analyzeResponse.tokenfilters().get(0).getName(), equalTo("lowercase"));
        assertThat(analyzeResponse.tokenfilters().get(0).getTokens().size(), equalTo(1));
        assertThat(analyzeResponse.tokenfilters().get(0).getTokens().get(0).getTerm(), equalTo("this is a fish"));
        assertThat(analyzeResponse.tokenfilters().get(0).getTokens().get(0).getPosition(), equalTo(0));
        assertThat(analyzeResponse.tokenfilters().get(0).getTokens().get(0).getStartOffset(), equalTo(0));
        assertThat(analyzeResponse.tokenfilters().get(0).getTokens().get(0).getEndOffset(), equalTo(15));

    }
}
 
Example #23
Source File: ClusterHealthRequest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(StreamOutput out) throws IOException {
    super.writeTo(out);
    if (indices == null) {
        out.writeVInt(0);
    } else {
        out.writeVInt(indices.length);
        for (String index : indices) {
            out.writeString(index);
        }
    }
    out.writeTimeValue(timeout);
    if (waitForStatus == null) {
        out.writeBoolean(false);
    } else {
        out.writeBoolean(true);
        out.writeByte(waitForStatus.value());
    }
    out.writeBoolean(waitForNoRelocatingShards);
    waitForActiveShards.writeTo(out);
    out.writeString(waitForNodes);
    if (waitForEvents == null) {
        out.writeBoolean(false);
    } else {
        out.writeBoolean(true);
        Priority.writeTo(waitForEvents, out);
    }
    out.writeBoolean(waitForNoInitializingShards);
}
 
Example #24
Source File: ElasticsearchClusterRunner.java    From elasticsearch-cluster-runner with Apache License 2.0 5 votes vote down vote up
/**
 * Wait for green state of a cluster.
 *
 * @param indices indices to check status
 * @return cluster health status
 */
public ClusterHealthStatus ensureGreen(final String... indices) {
    final ClusterHealthResponse actionGet = client().admin().cluster().health(
            Requests.clusterHealthRequest(indices).waitForGreenStatus().waitForEvents(Priority.LANGUID).waitForNoRelocatingShards(true))
            .actionGet();
    if (actionGet.isTimedOut()) {
        onFailure("ensureGreen timed out, cluster state:\n" + client().admin().cluster().prepareState().get().getState() + "\n"
                + client().admin().cluster().preparePendingClusterTasks().get(), actionGet);
    }
    return actionGet.getStatus();
}
 
Example #25
Source File: TransportClusterRerouteAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected void masterOperation(final ClusterRerouteRequest request, final ClusterState state, final ActionListener<ClusterRerouteResponse> listener) {
    clusterService.submitStateUpdateTask("cluster_reroute (api)", new AckedClusterStateUpdateTask<ClusterRerouteResponse>(Priority.IMMEDIATE, request, listener) {

        private volatile ClusterState clusterStateToSend;
        private volatile RoutingExplanations explanations;

        @Override
        protected ClusterRerouteResponse newResponse(boolean acknowledged) {
            return new ClusterRerouteResponse(acknowledged, clusterStateToSend, explanations);
        }

        @Override
        public void onAckTimeout() {
            listener.onResponse(new ClusterRerouteResponse(false, clusterStateToSend, new RoutingExplanations()));
        }

        @Override
        public void onFailure(String source, Throwable t) {
            logger.debug("failed to perform [{}]", t, source);
            super.onFailure(source, t);
        }

        @Override
        public ClusterState execute(ClusterState currentState) {
            RoutingAllocation.Result routingResult = allocationService.reroute(currentState, request.commands, request.explain());
            ClusterState newState = ClusterState.builder(currentState).routingResult(routingResult).build();
            clusterStateToSend = newState;
            explanations = routingResult.explanations();
            if (request.dryRun) {
                return currentState;
            }
            return newState;
        }
    });
}
 
Example #26
Source File: TransportSwapRelationsAction.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
protected void masterOperation(SwapRelationsRequest request, ClusterState state, ActionListener<AcknowledgedResponse> listener) throws Exception {
    AtomicReference<String[]> indexNamesAfterRelationSwap = new AtomicReference<>(null);
    ActionListener<AcknowledgedResponse> waitForShardsListener = ActionListeners.waitForShards(
        listener,
        activeShardsObserver,
        request.ackTimeout(),
        () -> logger.info("Switched name of relations, but the operation timed out waiting for enough shards to be started"),
        indexNamesAfterRelationSwap::get
    );
    AckedClusterStateUpdateTask<AcknowledgedResponse> updateTask =
        new AckedClusterStateUpdateTask<AcknowledgedResponse>(Priority.HIGH, request, waitForShardsListener) {

            @Override
            public ClusterState execute(ClusterState currentState) throws Exception {
                if (logger.isInfoEnabled()) {
                    Iterable<String> swapActions = request.swapActions().stream()
                        .map(x -> x.source().fqn() + " <-> " + x.target().fqn())
                        ::iterator;
                    logger.info("Swapping tables [{}]", String.join(", ", swapActions));
                }
                SwapRelationsOperation.UpdatedState newState = swapRelationsOperation.execute(currentState, request);
                indexNamesAfterRelationSwap.set(newState.newIndices.toArray(new String[0]));
                return newState.newState;
            }

            @Override
            protected AcknowledgedResponse newResponse(boolean acknowledged) {
                return new AcknowledgedResponse(acknowledged);
            }
        };
    clusterService.submitStateUpdateTask("swap-relations", updateTask);
}
 
Example #27
Source File: PrioritizedEsThreadPoolExecutor.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> RunnableFuture<T> newTaskFor(Callable<T> callable) {
    if (!(callable instanceof PrioritizedCallable)) {
        callable = PrioritizedCallable.wrap(callable, Priority.NORMAL);
    }
    return new PrioritizedFutureTask<>((PrioritizedCallable<T>) callable, insertionOrder.incrementAndGet());
}
 
Example #28
Source File: PrioritizedEsThreadPoolExecutor.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
protected <T> RunnableFuture<T> newTaskFor(Runnable runnable, T value) {
    if (!(runnable instanceof PrioritizedRunnable)) {
        runnable = PrioritizedRunnable.wrap(runnable, Priority.NORMAL);
    }
    return new PrioritizedFutureTask<>((PrioritizedRunnable) runnable, value, insertionOrder.incrementAndGet());
}
 
Example #29
Source File: PrioritizedEsThreadPoolExecutor.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Runnable command) {
    if (command instanceof PrioritizedRunnable) {
        command = new TieBreakingPrioritizedRunnable((PrioritizedRunnable) command, insertionOrder.incrementAndGet());
    } else if (!(command instanceof PrioritizedFutureTask)) { // it might be a callable wrapper...
        command = new TieBreakingPrioritizedRunnable(command, Priority.NORMAL, insertionOrder.incrementAndGet());
    }
    super.execute(command);
}
 
Example #30
Source File: TransportDropViewAction.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
protected void masterOperation(DropViewRequest request, ClusterState state, ActionListener<DropViewResponse> listener) {
    clusterService.submitStateUpdateTask("views/drop",
        new AckedClusterStateUpdateTask<DropViewResponse>(Priority.HIGH, request, listener) {

            private List<RelationName> missing;

            @Override
            public ClusterState execute(ClusterState currentState) {
                ViewsMetaData views = currentState.metaData().custom(ViewsMetaData.TYPE);
                if (views == null) {
                    missing = request.names();
                    return currentState;
                }
                ViewsMetaData.RemoveResult removeResult = views.remove(request.names());
                missing = removeResult.missing();
                if (!removeResult.missing().isEmpty() && !request.ifExists()) {
                    // We missed a view -> This is an error case so we must not update the cluster state
                    return currentState;
                }
                currentState = ddlClusterStateService.onDropView(currentState, request.names());
                return ClusterState.builder(currentState)
                    .metaData(
                        MetaData.builder(currentState.metaData())
                            .putCustom(ViewsMetaData.TYPE, removeResult.updatedViews())
                            .build()
                    )
                    .build();
            }

            @Override
            protected DropViewResponse newResponse(boolean acknowledged) {
                return new DropViewResponse(missing);
            }
        });
}