Search in sources :

Example 1 with MasterService

use of org.elasticsearch.cluster.service.MasterService in project crate by crate.

the class NodeJoinTests method setupMasterServiceAndCoordinator.

private void setupMasterServiceAndCoordinator(long term, ClusterState initialState, MasterService masterService, ThreadPool threadPool, Random random) {
    if (this.masterService != null || coordinator != null) {
        throw new IllegalStateException("method setupMasterServiceAndCoordinator can only be called once");
    }
    this.masterService = masterService;
    CapturingTransport capturingTransport = new CapturingTransport() {

        @Override
        protected void onSendRequest(long requestId, String action, TransportRequest request, DiscoveryNode destination) {
            if (action.equals(HANDSHAKE_ACTION_NAME)) {
                handleResponse(requestId, new TransportService.HandshakeResponse(destination, initialState.getClusterName(), destination.getVersion()));
            } else if (action.equals(JoinHelper.VALIDATE_JOIN_ACTION_NAME)) {
                handleResponse(requestId, new TransportResponse.Empty());
            } else {
                super.onSendRequest(requestId, action, request, destination);
            }
        }
    };
    final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    TransportService transportService = capturingTransport.createTransportService(Settings.EMPTY, threadPool, x -> initialState.nodes().getLocalNode(), clusterSettings);
    coordinator = new Coordinator("test_node", Settings.EMPTY, clusterSettings, transportService, writableRegistry(), ESAllocationTestCase.createAllocationService(Settings.EMPTY), masterService, () -> new InMemoryPersistedState(term, initialState), r -> emptyList(), new NoOpClusterApplier(), Collections.emptyList(), random, (s, p, r) -> {
    });
    transportService.start();
    transportService.acceptIncomingRequests();
    transport = capturingTransport;
    coordinator.start();
    coordinator.startInitialJoin();
}
Also used : ESAllocationTestCase(org.elasticsearch.cluster.ESAllocationTestCase) HANDSHAKE_ACTION_NAME(org.elasticsearch.transport.TransportService.HANDSHAKE_ACTION_NAME) TransportRequest(org.elasticsearch.transport.TransportRequest) Random(java.util.Random) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) Collections.singletonList(java.util.Collections.singletonList) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) After(org.junit.After) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) AfterClass(org.junit.AfterClass) CyclicBarrier(java.util.concurrent.CyclicBarrier) Transport(org.elasticsearch.transport.Transport) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) Version(org.elasticsearch.Version) Stream(java.util.stream.Stream) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) DiscoveryNodeRole(org.elasticsearch.cluster.node.DiscoveryNodeRole) Matchers.containsString(org.hamcrest.Matchers.containsString) IntStream(java.util.stream.IntStream) BeforeClass(org.junit.BeforeClass) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RequestHandlerRegistry(org.elasticsearch.transport.RequestHandlerRegistry) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) BaseFuture(org.elasticsearch.common.util.concurrent.BaseFuture) Metadata(org.elasticsearch.cluster.metadata.Metadata) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Node(org.elasticsearch.node.Node) TestTransportChannel(org.elasticsearch.transport.TestTransportChannel) VotingConfiguration(org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfiguration) TransportResponse(org.elasticsearch.transport.TransportResponse) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) MasterServiceTests(org.elasticsearch.cluster.service.MasterServiceTests) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) FutureUtils(org.elasticsearch.common.util.concurrent.FutureUtils) MasterService(org.elasticsearch.cluster.service.MasterService) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) TimeUnit(java.util.concurrent.TimeUnit) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) FakeThreadPoolMasterService(org.elasticsearch.cluster.service.FakeThreadPoolMasterService) ClusterServiceUtils(org.elasticsearch.test.ClusterServiceUtils) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) Randomness(org.elasticsearch.common.Randomness) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) TransportRequest(org.elasticsearch.transport.TransportRequest) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) Matchers.containsString(org.hamcrest.Matchers.containsString) TransportService(org.elasticsearch.transport.TransportService)

Example 2 with MasterService

use of org.elasticsearch.cluster.service.MasterService in project crate by crate.

the class NodeJoinTests method testConcurrentJoining.

public void testConcurrentJoining() {
    List<DiscoveryNode> masterNodes = IntStream.rangeClosed(1, randomIntBetween(2, 5)).mapToObj(nodeId -> newNode(nodeId, true)).collect(Collectors.toList());
    List<DiscoveryNode> otherNodes = IntStream.rangeClosed(masterNodes.size() + 1, masterNodes.size() + 1 + randomIntBetween(0, 5)).mapToObj(nodeId -> newNode(nodeId, false)).collect(Collectors.toList());
    List<DiscoveryNode> allNodes = Stream.concat(masterNodes.stream(), otherNodes.stream()).collect(Collectors.toList());
    DiscoveryNode localNode = masterNodes.get(0);
    VotingConfiguration votingConfiguration = new VotingConfiguration(randomValueOtherThan(singletonList(localNode), () -> randomSubsetOf(randomIntBetween(1, masterNodes.size()), masterNodes)).stream().map(DiscoveryNode::getId).collect(Collectors.toSet()));
    logger.info("Voting configuration: {}", votingConfiguration);
    long initialTerm = randomLongBetween(1, 10);
    long initialVersion = randomLongBetween(1, 10);
    setupRealMasterServiceAndCoordinator(initialTerm, initialState(localNode, initialTerm, initialVersion, votingConfiguration));
    long newTerm = initialTerm + randomLongBetween(1, 10);
    // we need at least a quorum of voting nodes with a correct term and worse state
    List<DiscoveryNode> successfulNodes;
    do {
        successfulNodes = randomSubsetOf(allNodes);
    } while (votingConfiguration.hasQuorum(successfulNodes.stream().map(DiscoveryNode::getId).collect(Collectors.toList())) == false);
    logger.info("Successful voting nodes: {}", successfulNodes);
    List<JoinRequest> correctJoinRequests = successfulNodes.stream().map(node -> new JoinRequest(node, Optional.of(new Join(node, localNode, newTerm, initialTerm, initialVersion)))).collect(Collectors.toList());
    List<DiscoveryNode> possiblyUnsuccessfulNodes = new ArrayList<>(allNodes);
    possiblyUnsuccessfulNodes.removeAll(successfulNodes);
    logger.info("Possibly unsuccessful voting nodes: {}", possiblyUnsuccessfulNodes);
    List<JoinRequest> possiblyFailingJoinRequests = possiblyUnsuccessfulNodes.stream().map(node -> {
        if (randomBoolean()) {
            // a correct request
            return new JoinRequest(node, Optional.of(new Join(node, localNode, newTerm, initialTerm, initialVersion)));
        } else if (randomBoolean()) {
            // term too low
            return new JoinRequest(node, Optional.of(new Join(node, localNode, randomLongBetween(0, initialTerm), initialTerm, initialVersion)));
        } else {
            // better state
            return new JoinRequest(node, Optional.of(new Join(node, localNode, newTerm, initialTerm, initialVersion + randomLongBetween(1, 10))));
        }
    }).collect(Collectors.toList());
    // duplicate some requests, which will be unsuccessful
    possiblyFailingJoinRequests.addAll(randomSubsetOf(possiblyFailingJoinRequests));
    CyclicBarrier barrier = new CyclicBarrier(correctJoinRequests.size() + possiblyFailingJoinRequests.size() + 1);
    final Runnable awaitBarrier = () -> {
        try {
            barrier.await();
        } catch (InterruptedException | BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    };
    final AtomicBoolean stopAsserting = new AtomicBoolean();
    final Thread assertionThread = new Thread(() -> {
        awaitBarrier.run();
        while (stopAsserting.get() == false) {
            coordinator.invariant();
        }
    }, "assert invariants");
    final List<Thread> joinThreads = Stream.concat(correctJoinRequests.stream().map(joinRequest -> new Thread(() -> {
        awaitBarrier.run();
        joinNode(joinRequest);
    }, "process " + joinRequest)), possiblyFailingJoinRequests.stream().map(joinRequest -> new Thread(() -> {
        awaitBarrier.run();
        try {
            joinNode(joinRequest);
        } catch (CoordinationStateRejectedException e) {
        // ignore - these requests are expected to fail
        }
    }, "process " + joinRequest))).collect(Collectors.toList());
    assertionThread.start();
    joinThreads.forEach(Thread::start);
    joinThreads.forEach(t -> {
        try {
            t.join();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    });
    stopAsserting.set(true);
    try {
        assertionThread.join();
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    assertTrue(MasterServiceTests.discoveryState(masterService).nodes().isLocalNodeElectedMaster());
    for (DiscoveryNode successfulNode : successfulNodes) {
        assertTrue(successfulNode + " joined cluster", clusterStateHasNode(successfulNode));
        assertFalse(successfulNode + " voted for master", coordinator.missingJoinVoteFrom(successfulNode));
    }
}
Also used : ESAllocationTestCase(org.elasticsearch.cluster.ESAllocationTestCase) HANDSHAKE_ACTION_NAME(org.elasticsearch.transport.TransportService.HANDSHAKE_ACTION_NAME) TransportRequest(org.elasticsearch.transport.TransportRequest) Random(java.util.Random) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) CapturingTransport(org.elasticsearch.test.transport.CapturingTransport) Collections.singletonList(java.util.Collections.singletonList) ClusterState(org.elasticsearch.cluster.ClusterState) Settings(org.elasticsearch.common.settings.Settings) After(org.junit.After) ThreadPool(org.elasticsearch.threadpool.ThreadPool) ClusterName(org.elasticsearch.cluster.ClusterName) AfterClass(org.junit.AfterClass) CyclicBarrier(java.util.concurrent.CyclicBarrier) Transport(org.elasticsearch.transport.Transport) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) Version(org.elasticsearch.Version) Stream(java.util.stream.Stream) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) DiscoveryNodeRole(org.elasticsearch.cluster.node.DiscoveryNodeRole) Matchers.containsString(org.hamcrest.Matchers.containsString) IntStream(java.util.stream.IntStream) BeforeClass(org.junit.BeforeClass) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) RequestHandlerRegistry(org.elasticsearch.transport.RequestHandlerRegistry) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) BaseFuture(org.elasticsearch.common.util.concurrent.BaseFuture) Metadata(org.elasticsearch.cluster.metadata.Metadata) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) Node(org.elasticsearch.node.Node) TestTransportChannel(org.elasticsearch.transport.TestTransportChannel) VotingConfiguration(org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfiguration) TransportResponse(org.elasticsearch.transport.TransportResponse) ESTestCase(org.elasticsearch.test.ESTestCase) TransportService(org.elasticsearch.transport.TransportService) MasterServiceTests(org.elasticsearch.cluster.service.MasterServiceTests) Collections.emptyMap(java.util.Collections.emptyMap) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) FutureUtils(org.elasticsearch.common.util.concurrent.FutureUtils) MasterService(org.elasticsearch.cluster.service.MasterService) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) TimeUnit(java.util.concurrent.TimeUnit) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) FakeThreadPoolMasterService(org.elasticsearch.cluster.service.FakeThreadPoolMasterService) ClusterServiceUtils(org.elasticsearch.test.ClusterServiceUtils) Collections(java.util.Collections) ActionListener(org.elasticsearch.action.ActionListener) Randomness(org.elasticsearch.common.Randomness) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ArrayList(java.util.ArrayList) VotingConfiguration(org.elasticsearch.cluster.coordination.CoordinationMetadata.VotingConfiguration) CyclicBarrier(java.util.concurrent.CyclicBarrier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 3 with MasterService

use of org.elasticsearch.cluster.service.MasterService in project crate by crate.

the class NodeJoinTests method setupRealMasterServiceAndCoordinator.

private void setupRealMasterServiceAndCoordinator(long term, ClusterState initialState) {
    MasterService masterService = new MasterService(Settings.builder().put(Node.NODE_NAME_SETTING.getKey(), "test_node").build(), new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), threadPool);
    AtomicReference<ClusterState> clusterStateRef = new AtomicReference<>(initialState);
    masterService.setClusterStatePublisher((event, publishListener, ackListener) -> {
        clusterStateRef.set(event.state());
        publishListener.onResponse(null);
    });
    setupMasterServiceAndCoordinator(term, initialState, masterService, threadPool, new Random(Randomness.get().nextLong()));
    masterService.setClusterStateSupplier(clusterStateRef::get);
    masterService.start();
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) Random(java.util.Random) AtomicReference(java.util.concurrent.atomic.AtomicReference) MasterService(org.elasticsearch.cluster.service.MasterService) FakeThreadPoolMasterService(org.elasticsearch.cluster.service.FakeThreadPoolMasterService)

Example 4 with MasterService

use of org.elasticsearch.cluster.service.MasterService in project crate by crate.

the class CrateDummyClusterServiceUnitTest method createClusterService.

protected ClusterService createClusterService(Collection<Setting<?>> additionalClusterSettings, Version version) {
    Set<Setting<?>> clusterSettingsSet = new HashSet<>(ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
    clusterSettingsSet.addAll(additionalClusterSettings);
    ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, clusterSettingsSet);
    ClusterService clusterService = new ClusterService(Settings.builder().put("cluster.name", "ClusterServiceTests").put(Node.NODE_NAME_SETTING.getKey(), NODE_NAME).build(), clusterSettings, THREAD_POOL);
    clusterService.setNodeConnectionsService(createNoOpNodeConnectionsService());
    DiscoveryNode discoveryNode = new DiscoveryNode(NODE_NAME, NODE_ID, buildNewFakeTransportAddress(), Collections.emptyMap(), DiscoveryNodeRole.BUILT_IN_ROLES, version);
    DiscoveryNodes nodes = DiscoveryNodes.builder().add(discoveryNode).localNodeId(NODE_ID).masterNodeId(NODE_ID).build();
    ClusterState clusterState = ClusterState.builder(new ClusterName(this.getClass().getSimpleName())).nodes(nodes).blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).build();
    ClusterApplierService clusterApplierService = clusterService.getClusterApplierService();
    clusterApplierService.setInitialState(clusterState);
    MasterService masterService = clusterService.getMasterService();
    masterService.setClusterStatePublisher(createClusterStatePublisher(clusterApplierService));
    masterService.setClusterStateSupplier(clusterApplierService::state);
    clusterService.start();
    return clusterService;
}
Also used : ClusterState(org.elasticsearch.cluster.ClusterState) DiscoveryNode(org.elasticsearch.cluster.node.DiscoveryNode) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) ClusterService(org.elasticsearch.cluster.service.ClusterService) Setting(org.elasticsearch.common.settings.Setting) ClusterName(org.elasticsearch.cluster.ClusterName) ClusterApplierService(org.elasticsearch.cluster.service.ClusterApplierService) MasterService(org.elasticsearch.cluster.service.MasterService) DiscoveryNodes(org.elasticsearch.cluster.node.DiscoveryNodes) HashSet(java.util.HashSet)

Aggregations

ClusterState (org.elasticsearch.cluster.ClusterState)4 MasterService (org.elasticsearch.cluster.service.MasterService)4 ClusterSettings (org.elasticsearch.common.settings.ClusterSettings)4 Random (java.util.Random)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 ClusterName (org.elasticsearch.cluster.ClusterName)3 DiscoveryNode (org.elasticsearch.cluster.node.DiscoveryNode)3 DiscoveryNodes (org.elasticsearch.cluster.node.DiscoveryNodes)3 FakeThreadPoolMasterService (org.elasticsearch.cluster.service.FakeThreadPoolMasterService)3 ArrayList (java.util.ArrayList)2 Collections (java.util.Collections)2 Collections.emptyList (java.util.Collections.emptyList)2 Collections.emptyMap (java.util.Collections.emptyMap)2 Collections.singletonList (java.util.Collections.singletonList)2 List (java.util.List)2 Optional (java.util.Optional)2 Set (java.util.Set)2 BrokenBarrierException (java.util.concurrent.BrokenBarrierException)2 CyclicBarrier (java.util.concurrent.CyclicBarrier)2 TimeUnit (java.util.concurrent.TimeUnit)2