org.elasticsearch.cluster.ClusterName Java Examples

The following examples show how to use org.elasticsearch.cluster.ClusterName. 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: NodesFailureDetectionService.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public NodesFailureDetectionService(Settings settings, ThreadPool threadPool, TransportService transportService, ClusterName clusterName, ClusterService clusterService, 
        RoutingService routingService, JoinClusterAction joinClusterAction, ClusterStateOpLog clusterStateOpLog) {
    super(settings);
    this.pingInterval = settings.getAsTime(SETTING_PING_INTERVAL, timeValueSeconds(1));
    this.pingTimeout = settings.getAsTime(SETTING_PING_TIMEOUT, timeValueSeconds(5));
    this.pingRetryCount = settings.getAsInt(SETTING_PING_RETRIES, 3);
    this.threadPool = threadPool;
    this.transportService = transportService;
    this.clusterName = clusterName;
    this.clusterService = clusterService;
    this.routingService = routingService;
    this.joinClusterAction = joinClusterAction;
    this.clusterStateOpLog = clusterStateOpLog;
    this.localNode = clusterService.localNode();
    logger.debug("[node  ] uses ping_interval [{}], ping_timeout [{}], ping_retries [{}]", pingInterval, pingTimeout, pingRetryCount);
    transportService.registerRequestHandler(PING_ACTION_NAME, PingRequest.class, ThreadPool.Names.SAME, new PingRequestHandler());
}
 
Example #2
Source File: MockAuditMessageFactory.java    From deprecated-security-advanced-modules with Apache License 2.0 6 votes vote down vote up
public static AuditMessage validAuditMessage(Category category) {

	    ClusterService cs = mock(ClusterService.class);
	    DiscoveryNode dn = mock(DiscoveryNode.class);

        when(dn.getHostAddress()).thenReturn("hostaddress");
        when(dn.getId()).thenReturn("hostaddress");
        when(dn.getHostName()).thenReturn("hostaddress");
        when(cs.localNode()).thenReturn(dn);
        when(cs.getClusterName()).thenReturn(new ClusterName("testcluster"));

		TransportAddress ta = new TransportAddress(new InetSocketAddress("8.8.8.8",80));

		AuditMessage msg = new AuditMessage(category, cs, Origin.TRANSPORT, Origin.TRANSPORT);
		msg.addEffectiveUser("John Doe");
		msg.addRemoteAddress(ta);
		msg.addRequestType("IndexRequest");
		return msg;
	}
 
Example #3
Source File: ADStatsResponseTests.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
@Test
public void testToXContent() throws IOException {
    ADStatsResponse adStatsResponse = new ADStatsResponse();
    Map<String, Object> testClusterStats = new HashMap<>();
    testClusterStats.put("test_stat", 1);
    adStatsResponse.setClusterStats(testClusterStats);
    List<ADStatsNodeResponse> responses = Collections.emptyList();
    List<FailedNodeException> failures = Collections.emptyList();
    ADStatsNodesResponse adStatsNodesResponse = new ADStatsNodesResponse(ClusterName.DEFAULT, responses, failures);
    adStatsResponse.setADStatsNodesResponse(adStatsNodesResponse);

    XContentBuilder builder = XContentFactory.jsonBuilder();
    adStatsResponse.toXContent(builder);
    XContentParser parser = createParser(builder);
    assertEquals(1, parser.map().get("test_stat"));
}
 
Example #4
Source File: NodeTestConfig.java    From elastic-crud with Apache License 2.0 6 votes vote down vote up
@Bean(destroyMethod="close")
Node newNode() throws NodeValidationException {
  final Path tempDir = createTempDir().toPath();
  final Settings settings = Settings.builder()
    .put(ClusterName.CLUSTER_NAME_SETTING.getKey(), new ClusterName("single-node-cluster" + System.nanoTime()))
    .put(Environment.PATH_HOME_SETTING.getKey(), tempDir)
    .put(Environment.PATH_REPO_SETTING.getKey(), tempDir.resolve("repo"))
    .put(Environment.PATH_SHARED_DATA_SETTING.getKey(), createTempDir().getParent())
    .put("node.name", "single-node")
    .put("script.inline", "true")
    .put("script.stored", "true")
    .put(ScriptService.SCRIPT_MAX_COMPILATIONS_PER_MINUTE.getKey(), 1000)
    .put(EsExecutors.PROCESSORS_SETTING.getKey(), 1)
    .put(NetworkModule.HTTP_ENABLED.getKey(), false)
    .put("discovery.type", "zen")
    .put("transport.type", "local")
    .put(Node.NODE_DATA_SETTING.getKey(), true)
    .put(NODE_ID_SEED_SETTING.getKey(), System.nanoTime())
    .build();
  return new Node(settings).start(); // NOSONAR
}
 
Example #5
Source File: InternalTestCluster.java    From crate with Apache License 2.0 6 votes vote down vote up
private Settings getSettings(int nodeOrdinal, long nodeSeed, Settings others) {
    Builder builder = Settings.builder().put(defaultSettings)
        .put(getRandomNodeSettings(nodeSeed));
    Settings settings = nodeConfigurationSource.nodeSettings(nodeOrdinal);
    if (settings != null) {
        if (settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) != null) {
            throw new IllegalStateException("Tests must not set a '" + ClusterName.CLUSTER_NAME_SETTING.getKey()
                    + "' as a node setting set '" + ClusterName.CLUSTER_NAME_SETTING.getKey() + "': ["
                    + settings.get(ClusterName.CLUSTER_NAME_SETTING.getKey()) + "]");
        }
        builder.put(settings);
    }
    if (others != null) {
        builder.put(others);
    }
    builder.put(ClusterName.CLUSTER_NAME_SETTING.getKey(), clusterName);
    return builder.build();
}
 
Example #6
Source File: Coordinator.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart() {
    synchronized (mutex) {
        CoordinationState.PersistedState persistedState = persistedStateSupplier.get();
        coordinationState.set(new CoordinationState(settings, getLocalNode(), persistedState));
        peerFinder.setCurrentTerm(getCurrentTerm());
        configuredHostsResolver.start();
        VotingConfiguration votingConfiguration = coordinationState.get().getLastAcceptedState().getLastCommittedConfiguration();
        if (singleNodeDiscovery &&
            votingConfiguration.isEmpty() == false &&
            votingConfiguration.hasQuorum(Collections.singleton(getLocalNode().getId())) == false) {
            throw new IllegalStateException("cannot start with [" + DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey() + "] set to [" +
                DiscoveryModule.SINGLE_NODE_DISCOVERY_TYPE + "] when local node " + getLocalNode() +
                " does not have quorum in voting configuration " + votingConfiguration);
        }
        ClusterState initialState = ClusterState.builder(ClusterName.CLUSTER_NAME_SETTING.get(settings))
            .blocks(ClusterBlocks.builder()
                .addGlobalBlock(STATE_NOT_RECOVERED_BLOCK)
                .addGlobalBlock(noMasterBlockService.getNoMasterBlock()))
            .nodes(DiscoveryNodes.builder().add(getLocalNode()).localNodeId(getLocalNode().getId()))
            .build();
        applierState = initialState;
        clusterApplier.setInitialState(initialState);
    }
}
 
Example #7
Source File: TestHelpers.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
public static ClusterState createIndexBlockedState(String indexName, Settings hackedSettings, String alias) {
    ClusterState blockedClusterState = null;
    IndexMetadata.Builder builder = IndexMetadata.builder(indexName);
    if (alias != null) {
        builder.putAlias(AliasMetadata.builder(alias));
    }
    IndexMetadata indexMetaData = builder
        .settings(
            Settings
                .builder()
                .put(IndexMetadata.SETTING_INDEX_UUID, UUIDs.randomBase64UUID())
                .put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1)
                .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0)
                .put(IndexMetadata.SETTING_VERSION_CREATED, Version.CURRENT)
                .put(hackedSettings)
        )
        .build();
    Metadata metaData = Metadata.builder().put(indexMetaData, false).build();
    blockedClusterState = ClusterState
        .builder(new ClusterName("test cluster"))
        .metadata(metaData)
        .blocks(ClusterBlocks.builder().addBlocks(indexMetaData))
        .build();
    return blockedClusterState;
}
 
Example #8
Source File: MasterServiceTests.java    From crate with Apache License 2.0 6 votes vote down vote up
private TimedMasterService createTimedMasterService(boolean makeMaster) throws InterruptedException {
    DiscoveryNode localNode = new DiscoveryNode("node1", buildNewFakeTransportAddress(), emptyMap(),
        emptySet(), Version.CURRENT);
    TimedMasterService timedMasterService = new TimedMasterService(Settings.builder().put("cluster.name",
        MasterServiceTests.class.getSimpleName()).build(), threadPool);
    ClusterState initialClusterState = ClusterState.builder(new ClusterName(MasterServiceTests.class.getSimpleName()))
        .nodes(DiscoveryNodes.builder()
            .add(localNode)
            .localNodeId(localNode.getId())
            .masterNodeId(makeMaster ? localNode.getId() : null))
        .blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).build();
    AtomicReference<ClusterState> clusterStateRef = new AtomicReference<>(initialClusterState);
    timedMasterService.setClusterStatePublisher((event, publishListener, ackListener) -> {
        clusterStateRef.set(event.state());
        publishListener.onResponse(null);
    });
    timedMasterService.setClusterStateSupplier(clusterStateRef::get);
    timedMasterService.start();
    return timedMasterService;
}
 
Example #9
Source File: NodeRemovalClusterStateTaskExecutorTests.java    From crate with Apache License 2.0 6 votes vote down vote up
public void testRemovingNonExistentNodes() throws Exception {
    final NodeRemovalClusterStateTaskExecutor executor =
            new NodeRemovalClusterStateTaskExecutor(null, logger);
    final DiscoveryNodes.Builder builder = DiscoveryNodes.builder();
    final int nodes = randomIntBetween(2, 16);
    for (int i = 0; i < nodes; i++) {
        builder.add(node(i));
    }
    final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(builder).build();

    final DiscoveryNodes.Builder removeBuilder = DiscoveryNodes.builder();
    for (int i = nodes; i < nodes + randomIntBetween(1, 16); i++) {
        removeBuilder.add(node(i));
    }
    final List<NodeRemovalClusterStateTaskExecutor.Task> tasks =
            StreamSupport
                    .stream(removeBuilder.build().spliterator(), false)
                    .map(node -> new NodeRemovalClusterStateTaskExecutor.Task(node, randomBoolean() ? "left" : "failed"))
                    .collect(Collectors.toList());

    final ClusterStateTaskExecutor.ClusterTasksResult<NodeRemovalClusterStateTaskExecutor.Task> result
            = executor.execute(clusterState, tasks);
    assertThat(result.resultingState, equalTo(clusterState));
}
 
Example #10
Source File: LicenseServiceTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testThatMaxNumberOfNodesIsWithinLimit() {
    final ClusterState state = ClusterState.builder(ClusterName.DEFAULT)
        .nodes(DiscoveryNodes.builder()
            .add(new DiscoveryNode("n1", buildNewFakeTransportAddress(),
                Version.CURRENT))
            .add(new DiscoveryNode("n2", buildNewFakeTransportAddress(),
                Version.CURRENT))
            .add(new DiscoveryNode("n3", buildNewFakeTransportAddress(),
                Version.CURRENT))
            .localNodeId("n1")
        )
        .build();
    LicenseData licenseData = new LicenseData(UNLIMITED_EXPIRY_DATE_IN_MS, "test", 3);

    licenseService.onUpdatedLicense(state, licenseData);
    assertThat(licenseService.isMaxNumberOfNodesExceeded(), is(false));
}
 
Example #11
Source File: ClusterServiceUtils.java    From crate with Apache License 2.0 6 votes vote down vote up
public static ClusterService createClusterService(ThreadPool threadPool, DiscoveryNode localNode, ClusterSettings clusterSettings) {
    Settings settings = Settings.builder()
            .put("node.name", "test")
            .put("cluster.name", "ClusterServiceTests")
            .build();
    ClusterService clusterService = new ClusterService(settings, clusterSettings, threadPool);
    clusterService.setNodeConnectionsService(createNoOpNodeConnectionsService());
    ClusterState initialClusterState = ClusterState.builder(new ClusterName(ClusterServiceUtils.class.getSimpleName()))
        .nodes(DiscoveryNodes.builder()
            .add(localNode)
            .localNodeId(localNode.getId())
            .masterNodeId(localNode.getId()))
        .blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).build();
    clusterService.getClusterApplierService().setInitialState(initialClusterState);
    clusterService.getMasterService().setClusterStatePublisher(
        createClusterStatePublisher(clusterService.getClusterApplierService()));
    clusterService.getMasterService().setClusterStateSupplier(clusterService.getClusterApplierService()::state);
    clusterService.start();
    return clusterService;
}
 
Example #12
Source File: AnomalyDetectorProfileRunnerTests.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws Exception {
    super.setUp();
    client = mock(Client.class);
    nodeFilter = mock(DiscoveryNodeFilterer.class);
    calendar = mock(Calendar.class);
    resolver = mock(IndexNameExpressionResolver.class);
    clusterService = mock(ClusterService.class);
    when(resolver.concreteIndexNames(any(), any(), any()))
        .thenReturn(
            new String[] { indexWithRequiredError1, indexWithRequiredError2, ".opendistro-anomaly-results-history-2020.04.08-000003" }
        );
    when(clusterService.state()).thenReturn(ClusterState.builder(new ClusterName("test cluster")).build());

    runner = new AnomalyDetectorProfileRunner(client, xContentRegistry(), nodeFilter, resolver, clusterService, calendar);
}
 
Example #13
Source File: CreateDropRepositoryAnalyzerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare() {
    RepositoriesMetaData repositoriesMetaData = new RepositoriesMetaData(
        Collections.singletonList(
            new RepositoryMetaData(
                "my_repo",
                "fs",
                Settings.builder().put("location", "/tmp/my_repo").build()
            )));
    ClusterState clusterState = ClusterState.builder(new ClusterName("testing"))
        .metaData(MetaData.builder()
                      .putCustom(RepositoriesMetaData.TYPE, repositoriesMetaData))
        .build();
    ClusterServiceUtils.setState(clusterService, clusterState);
    e = SQLExecutor.builder(clusterService).build();
    plannerContext = e.getPlannerContext(clusterService.state());
    repositoryParamValidator = new RepositoryParamValidator(Map.of(
        "fs", new TypeSettings(FsRepository.mandatorySettings(), FsRepository.optionalSettings())
    ));
}
 
Example #14
Source File: NodeJoinTests.java    From crate with Apache License 2.0 6 votes vote down vote up
private static ClusterState initialState(DiscoveryNode localNode, long term, long version,
                                         VotingConfiguration config) {
    return ClusterState.builder(new ClusterName(ClusterServiceUtils.class.getSimpleName()))
        .nodes(DiscoveryNodes.builder()
            .add(localNode)
            .localNodeId(localNode.getId()))
        .metaData(MetaData.builder()
                .coordinationMetaData(
                    CoordinationMetaData.builder()
                    .term(term)
                    .lastAcceptedConfiguration(config)
                    .lastCommittedConfiguration(config)
                .build()))
        .version(version)
        .blocks(ClusterBlocks.EMPTY_CLUSTER_BLOCK).build();
}
 
Example #15
Source File: FakeNode.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
public static void connectNodes(FakeNode... nodes) {
    List<DiscoveryNode> discoveryNodes = new ArrayList<DiscoveryNode>(nodes.length);
    DiscoveryNode master = nodes[0].discoveryNode();
    for (int i = 0; i < nodes.length; i++) {
        discoveryNodes.add(nodes[i].discoveryNode());
    }

    for (FakeNode node : nodes) {
        setState(node.clusterService, ClusterCreation.state(new ClusterName("test"), node.discoveryNode(), master, discoveryNodes));
    }
    for (FakeNode nodeA : nodes) {
        for (FakeNode nodeB : nodes) {
            nodeA.transportService.connectToNode(nodeB.discoveryNode());
        }
    }
}
 
Example #16
Source File: TransportCancelTasksAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Inject
public TransportCancelTasksAction(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService,
                                  TransportService transportService, ActionFilters actionFilters, IndexNameExpressionResolver
                                      indexNameExpressionResolver) {
    super(settings, CancelTasksAction.NAME, clusterName, threadPool, clusterService, transportService, actionFilters,
        indexNameExpressionResolver, new Callable<CancelTasksRequest>() {
            @Override
            public CancelTasksRequest call() throws Exception {
                return new CancelTasksRequest();
            }
        }, ThreadPool.Names.MANAGEMENT);
    transportService.registerRequestHandler(BAN_PARENT_ACTION_NAME, new Callable<BanParentTaskRequest>() {
        @Override
        public BanParentTaskRequest call() throws Exception {
            return new BanParentTaskRequest();
        }
    }, ThreadPool.Names.SAME, new
        BanParentRequestHandler());
}
 
Example #17
Source File: ProfileResponse.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor
 *
 * @param clusterName name of cluster
 * @param nodes List of ProfileNodeResponse from nodes
 * @param failures List of failures from nodes
 */
public ProfileResponse(ClusterName clusterName, List<ProfileNodeResponse> nodes, List<FailedNodeException> failures) {
    super(clusterName, nodes, failures);
    totalSizeInBytes = 0L;
    List<ModelProfile> modelProfileList = new ArrayList<>();
    for (ProfileNodeResponse response : nodes) {
        String curNodeId = response.getNode().getId();
        if (response.getShingleSize() >= 0) {
            coordinatingNode = curNodeId;
            shingleSize = response.getShingleSize();
        }
        for (Map.Entry<String, Long> entry : response.getModelSize().entrySet()) {
            totalSizeInBytes += entry.getValue();
            modelProfileList.add(new ModelProfile(entry.getKey(), entry.getValue(), curNodeId));
        }

    }
    if (coordinatingNode == null) {
        coordinatingNode = "";
    }
    this.modelProfile = modelProfileList.toArray(new ModelProfile[0]);
}
 
Example #18
Source File: CreateAlterTableStatementAnalyzerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare() throws IOException {
    String analyzerSettings = FulltextAnalyzerResolver.encodeSettings(
        Settings.builder().put("search", "foobar").build()).utf8ToString();
    MetaData metaData = MetaData.builder()
        .persistentSettings(
            Settings.builder().put(ANALYZER.buildSettingName("ft_search"), analyzerSettings).build())
        .build();
    ClusterState state = ClusterState.builder(ClusterName.DEFAULT)
        .metaData(metaData)
        .build();
    ClusterServiceUtils.setState(clusterService, state);
    e = SQLExecutor.builder(clusterService, 3, Randomness.get(), List.of())
        .enableDefaultTables()
        .build();
    plannerContext = e.getPlannerContext(clusterService.state());
}
 
Example #19
Source File: TestElasticsearchAppender.java    From karaf-decanter with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    Collection plugins = Arrays.asList(Netty4Plugin.class);
    Settings settings = Settings.builder()
            .put(ClusterName.CLUSTER_NAME_SETTING.getKey(), CLUSTER_NAME)
            .put(Node.NODE_NAME_SETTING.getKey(), "test")
            .put(NetworkModule.HTTP_TYPE_KEY, Netty4Plugin.NETTY_HTTP_TRANSPORT_NAME)
            .put(Environment.PATH_HOME_SETTING.getKey(), "target/data")
            .put(Environment.PATH_DATA_SETTING.getKey(), "target/data")
            .put("network.host", HOST)
            .put("http.port", HTTP_PORT)
            .put(NetworkModule.TRANSPORT_TYPE_KEY, Netty4Plugin.NETTY_TRANSPORT_NAME)
            .put("transport.port", TRANSPORT_PORT)
            .build();
    node = new MockNode(settings, plugins);
    node.start();
}
 
Example #20
Source File: TransportClientNodesService.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Inject
public TransportClientNodesService(Settings settings, ClusterName clusterName, TransportService transportService,
                                   ThreadPool threadPool, Headers headers, Version version) {
    super(settings);
    this.clusterName = clusterName;
    this.transportService = transportService;
    this.threadPool = threadPool;
    this.minCompatibilityVersion = version.minimumCompatibilityVersion();
    this.headers = headers;

    this.nodesSamplerInterval = this.settings.getAsTime("client.transport.nodes_sampler_interval", timeValueSeconds(5));
    this.pingTimeout = this.settings.getAsTime("client.transport.ping_timeout", timeValueSeconds(5)).millis();
    this.ignoreClusterName = this.settings.getAsBoolean("client.transport.ignore_cluster_name", false);

    if (logger.isDebugEnabled()) {
        logger.debug("node_sampler_interval[" + nodesSamplerInterval + "]");
    }

    if (this.settings.getAsBoolean("client.transport.sniff", false)) {
        this.nodesSampler = new SniffNodesSampler();
    } else {
        this.nodesSampler = new SimpleNodeSampler();
    }
    this.nodesSamplerFuture = threadPool.schedule(nodesSamplerInterval, ThreadPool.Names.GENERIC, new ScheduledNodeSampler());
}
 
Example #21
Source File: TransportVerifyRepositoryAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public TransportVerifyRepositoryAction(Settings settings, ClusterName clusterName, TransportService transportService, ClusterService clusterService,
                                       RepositoriesService repositoriesService, ThreadPool threadPool, ActionFilters actionFilters,
                                       IndexNameExpressionResolver indexNameExpressionResolver) {
    super(settings, VerifyRepositoryAction.NAME, transportService, clusterService, threadPool, actionFilters, indexNameExpressionResolver, VerifyRepositoryRequest.class);
    this.repositoriesService = repositoriesService;
    this.clusterName = clusterName;
}
 
Example #22
Source File: LivenessResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    clusterName = ClusterName.readClusterName(in);
    if (in.readBoolean()) {
        node = DiscoveryNode.readNode(in);
    } else {
        node = null;
    }
}
 
Example #23
Source File: TransportNodesListShardStoreMetaData.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public TransportNodesListShardStoreMetaData(Settings settings, ClusterName clusterName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService,
                                            IndicesService indicesService, NodeEnvironment nodeEnv, ActionFilters actionFilters,
                                            IndexNameExpressionResolver indexNameExpressionResolver) {
    super(settings, ACTION_NAME, clusterName, threadPool, clusterService, transportService, actionFilters, indexNameExpressionResolver,
            Request.class, NodeRequest.class, ThreadPool.Names.FETCH_SHARD_STORE);
    this.indicesService = indicesService;
    this.nodeEnv = nodeEnv;
}
 
Example #24
Source File: TransportClient.java    From elasticsearch-helper with Apache License 2.0 5 votes vote down vote up
private TransportClient(Injector injector) {
    super(injector.getInstance(Settings.class), injector.getInstance(ThreadPool.class),
            injector.getInstance(Headers.class));
    this.injector = injector;
    this.clusterName = injector.getInstance(ClusterName.class);
    this.transportService = injector.getInstance(TransportService.class);
    this.minCompatibilityVersion = injector.getInstance(Version.class).minimumCompatibilityVersion();
    this.headers = injector.getInstance(Headers.class);
    this.pingTimeout = this.settings.getAsTime("client.transport.ping_timeout", timeValueSeconds(5)).millis();
    this.proxyActionMap = injector.getInstance(ProxyActionMap.class);
}
 
Example #25
Source File: CoordinationStateTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public static ClusterState clusterState(long term, long version, DiscoveryNodes discoveryNodes, VotingConfiguration lastCommittedConfig,
                                        VotingConfiguration lastAcceptedConfig, long value) {
    return setValue(ClusterState.builder(ClusterName.DEFAULT)
        .version(version)
        .nodes(discoveryNodes)
        .metaData(MetaData.builder()
            .clusterUUID(UUIDs.randomBase64UUID(random())) // generate cluster UUID deterministically for repeatable tests
            .coordinationMetaData(CoordinationMetaData.builder()
                    .term(term)
                    .lastCommittedConfiguration(lastCommittedConfig)
                    .lastAcceptedConfiguration(lastAcceptedConfig)
                    .build()))
        .stateUUID(UUIDs.randomBase64UUID(random())) // generate cluster state UUID deterministically for repeatable tests
        .build(), value);
}
 
Example #26
Source File: TransportClearVotingConfigExclusionsActionTests.java    From crate with Apache License 2.0 5 votes vote down vote up
@Before
public void setupForTest() {
    final MockTransport transport = new MockTransport();
    transportService = transport.createTransportService(
        Settings.EMPTY,
        threadPool,
        TransportService.NOOP_TRANSPORT_INTERCEPTOR,
        boundTransportAddress -> localNode,
        null
    );

    new TransportClearVotingConfigExclusionsAction(
        transportService, clusterService, threadPool, new IndexNameExpressionResolver()); // registers action

    transportService.start();
    transportService.acceptIncomingRequests();

    final ClusterState.Builder builder = builder(new ClusterName("cluster"))
        .nodes(new Builder().add(localNode).add(otherNode1).add(otherNode2)
            .localNodeId(localNode.getId()).masterNodeId(localNode.getId()));
    builder.metaData(MetaData.builder()
            .coordinationMetaData(CoordinationMetaData.builder()
                    .addVotingConfigExclusion(otherNode1Exclusion)
                    .addVotingConfigExclusion(otherNode2Exclusion)
            .build()));
    setState(clusterService, builder);
}
 
Example #27
Source File: ZenPing.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * @param node          the node which this ping describes
 * @param master        the current master of the node
 * @param clusterName   the cluster name of the node
 * @param hasJoinedOnce true if the joined has successfully joined the cluster before
 */
public PingResponse(DiscoveryNode node, DiscoveryNode master, ClusterName clusterName, boolean hasJoinedOnce) {
    this.id = idGenerator.incrementAndGet();
    this.node = node;
    this.master = master;
    this.clusterName = clusterName;
    this.hasJoinedOnce = hasJoinedOnce;
}
 
Example #28
Source File: SrvtestDiscovery.java    From elasticsearch-srv-discovery with MIT License 5 votes vote down vote up
@Inject
public SrvtestDiscovery(Settings settings, ClusterName clusterName, ThreadPool threadPool, TransportService transportService,
                    ClusterService clusterService, NodeSettingsService nodeSettingsService, ZenPingService pingService,
                    DiscoveryNodeService discoveryNodeService,DiscoverySettings discoverySettings,
                    ElectMasterService electMasterService, DynamicSettings dynamicSettings) {
    super(settings, clusterName, threadPool, transportService, clusterService, nodeSettingsService,
            discoveryNodeService, pingService, electMasterService, discoverySettings, dynamicSettings);
}
 
Example #29
Source File: NodeRemovalClusterStateTaskExecutorTests.java    From crate with Apache License 2.0 5 votes vote down vote up
public void testRerouteAfterRemovingNodes() throws Exception {
    final AllocationService allocationService = mock(AllocationService.class);
    when(allocationService.disassociateDeadNodes(any(ClusterState.class), eq(true), any(String.class)))
        .thenAnswer(im -> im.getArguments()[0]);

    final AtomicReference<ClusterState> remainingNodesClusterState = new AtomicReference<>();
    final NodeRemovalClusterStateTaskExecutor executor =
            new NodeRemovalClusterStateTaskExecutor(allocationService, logger) {
                @Override
                protected ClusterState remainingNodesClusterState(ClusterState currentState,
                                                                  DiscoveryNodes.Builder remainingNodesBuilder) {
                    remainingNodesClusterState.set(super.remainingNodesClusterState(currentState, remainingNodesBuilder));
                    return remainingNodesClusterState.get();
                }
            };

    final DiscoveryNodes.Builder builder = DiscoveryNodes.builder();
    final int nodes = randomIntBetween(2, 16);
    final List<NodeRemovalClusterStateTaskExecutor.Task> tasks = new ArrayList<>();
    // to ensure that there is at least one removal
    boolean first = true;
    for (int i = 0; i < nodes; i++) {
        final DiscoveryNode node = node(i);
        builder.add(node);
        if (first || randomBoolean()) {
            tasks.add(new NodeRemovalClusterStateTaskExecutor.Task(node, randomBoolean() ? "left" : "failed"));
        }
        first = false;
    }
    final ClusterState clusterState = ClusterState.builder(new ClusterName("test")).nodes(builder).build();

    final ClusterStateTaskExecutor.ClusterTasksResult<NodeRemovalClusterStateTaskExecutor.Task> result =
            executor.execute(clusterState, tasks);

    verify(allocationService).disassociateDeadNodes(eq(remainingNodesClusterState.get()), eq(true), any(String.class));

    for (final NodeRemovalClusterStateTaskExecutor.Task task : tasks) {
        assertNull(result.resultingState.nodes().get(task.node().getId()));
    }
}
 
Example #30
Source File: NodesFailureDetectionService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void readFrom(StreamInput in) throws IOException {
    super.readFrom(in);
    pingNode = DiscoveryNode.readNode(in);
    isDeadNode = in.readBoolean();
    clusterName = ClusterName.readClusterName(in);
    masterNode = DiscoveryNode.readNode(in);
    clusterStateVersion = in.readLong();
}