Java Code Examples for com.datastax.driver.core.Metadata#getAllHosts()

The following examples show how to use com.datastax.driver.core.Metadata#getAllHosts() . 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: ClusterFactory.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected Cluster createCluster() {
   Cluster.Builder builder = Cluster.builder();

   if (this.contactPoints != null && !this.contactPoints.isEmpty()) {
      String[] values = new String[this.contactPoints.size()];
      this.contactPoints.toArray(values);
      builder.addContactPoints(values);
   }

   builder.withPort(this.port);

   Cluster cluster = builder.build();

   Metadata metadata = cluster.getMetadata();

   LOG.info("Connected to Cassandra cluster: " + metadata.getClusterName());
   for (Host host : metadata.getAllHosts()) {
      LOG.info("DataCenter: {}, Rack: {}, Host: {}",
               new Object[]{host.getDatacenter(), host.getRack(), host.getAddress()});
   }

   return cluster;
}
 
Example 2
Source File: CassandraConnector.java    From tutorials with MIT License 6 votes vote down vote up
public void connect(final String node, final Integer port) {

        Builder b = Cluster.builder().addContactPoint(node);

        if (port != null) {
            b.withPort(port);
        }
        cluster = b.build();

        Metadata metadata = cluster.getMetadata();
        LOG.info("Cluster name: " + metadata.getClusterName());

        for (Host host : metadata.getAllHosts()) {
            LOG.info("Datacenter: " + host.getDatacenter() + " Host: " + host.getAddress() + " Rack: " + host.getRack());
        }

        session = cluster.connect();
    }
 
Example 3
Source File: CQLService.java    From Doradus with Apache License 2.0 5 votes vote down vote up
private void displayClusterInfo() {
    Metadata metadata = m_cluster.getMetadata();
    m_logger.info("Connected to cluster with topography:");
    RoundRobinPolicy policy = new RoundRobinPolicy();
    for (Host host : metadata.getAllHosts()) {
        m_logger.info("   Host {}: datacenter: {}, rack: {}, distance: {}",
                      new Object[]{host.getAddress(), host.getDatacenter(), 
            host.getRack(), policy.distance(host)});
    }
    m_logger.info("Database contains {} keyspaces", metadata.getKeyspaces().size());
}
 
Example 4
Source File: CassandraRegistryConfig.java    From konker-platform with Apache License 2.0 4 votes vote down vote up
@Bean
public Session session() {

    try {

        final Cluster cluster = cluster();
        final Metadata metadata = cluster().getMetadata();

        LOGGER.info("Connected to cluster: {}\n", metadata.getClusterName());

        for (final Host host : metadata.getAllHosts()) {
            LOGGER.info("Datacenter: {}; Host: {}; Rack: {}\n", host.getDatacenter(), host.getAddress(),
                    host.getRack());
        }

        return cluster.connect(getKeyspace());

    } catch (NoHostAvailableException e) {
        LOGGER.info("NoHostAvailableException: {}", e.getMessage());

        return null;
    }

}
 
Example 5
Source File: HintsPollerTest.java    From emodb with Apache License 2.0 4 votes vote down vote up
@Ignore
@Test
public void queryIsExecutedOnAllClusterNodesAndAlsoTheOldestHintIsPicked() {

    // ***** TODO: Get a cluster with 2 nodes. (RUN WITH PERFTEST LATER.....) ******
    // Ignoring this test for now

    // Insert hints on all the cluster nodes.
    Cluster cluster = Cluster.builder()
            .addContactPoint("127.0.0.1")
            .withPort(9164)
            .withLoadBalancingPolicy(new SelectedHostLoadBalancingPolicyForTest())
            .build();
    Metadata metadata = cluster.getMetadata();
    Session clusterSession = cluster.connect();

    long hintTimestamp = System.currentTimeMillis();
    for (Host host : metadata.getAllHosts()) {
        SelectedHostStatement selectedHostStatement = new SelectedHostStatement(new SimpleStatement(getInsertHintsQuery(hintTimestamp)), host);
        clusterSession.execute(selectedHostStatement);
        hintTimestamp = hintTimestamp + 10000;
    }

    // Now check if the query ran on EVERY node of the cluster.
    Assert.assertEquals(ALL_SELECTED_HOSTS.size(), 2);

    // Get the oldest hint Timestamp of the cluster
    ClusterHintsPoller clusterHintsPoller = new ClusterHintsPoller();
    HintsPollerResult oldestHintsInfo = clusterHintsPoller.getOldestHintsInfo(clusterSession);

    // Note: ?? - This will make the test fail even if one node is down or a connection problem with just one node.
    Assert.assertNotNull(oldestHintsInfo);
    Assert.assertEquals(oldestHintsInfo.getAllPolledHosts().size(), 2);

    long retrievedHintTimeStamp = oldestHintsInfo.getOldestHintTimestamp().or(Long.MAX_VALUE);

    Assert.assertEquals(retrievedHintTimeStamp, hintTimestamp);

    cluster.close();
    clusterSession.close();
}
 
Example 6
Source File: CassandraIntervalCollectionPersistor.java    From brein-time-utilities with Apache License 2.0 4 votes vote down vote up
public void connect(final String node,
                    final int port) {
    this.sessionLock.lock();

    /*
     * 1. The session may have been closed in between. This may lead to several errors
     *    because the session may be in use by several others. Nevertheless, the
     *    implementation is assumed to be thread-safe, so let's assume that closing is
     *    too.
     * 2. The session may have never been created. In both cases, entering this block
     *    we have to create the instances.
     */
    try {

        // if we have a session meanwhile, just return
        if (this.session != null) {
            return;
        } else if (this.cluster == null) {
            this.cluster = Cluster.builder().addContactPoint(node).withPort(port).build();
            final Metadata metadata = this.cluster.getMetadata();

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(String.format("Connected to cluster: %s", metadata.getClusterName()));

                for (final Host host : metadata.getAllHosts()) {
                    LOGGER.info(String.format("Datacenter: %s; Host: %s; Rack: %s",
                            host.getDatacenter(), host.getAddress(), host.getRack()));
                }
            }
        }

        this.session = this.cluster.connect();
    } catch (final Exception e) {
        final String msg = String.format("Unable to open a connection at '%s:%d (%s)'.", node, port, this.keySpace);

        /*
         * Reset the cluster, normally the current one won't work:
         * Caused by: java.lang.IllegalStateException:
         * Can't use this cluster instance because it was previously closed
         * at com.datastax.driver.core.Cluster.checkNotClosed(Cluster.java:602)
         * at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:333)
         * at com.datastax.driver.core.Cluster.connectAsync(Cluster.java:309)
         * at com.datastax.driver.core.Cluster.connect(Cluster.java:251)
         * at com.brein.common.cassa.CassaSessionManager.setup(CassaSessionManager.java:94)
         */
        try {
            this.cluster.close();
        } catch (final Exception ignore) {
            // ignore
        }
        this.cluster = null;

        // now we can throw the exception
        throw new FailedConnection(msg, e);
    } finally {
        this.sessionLock.unlock();
    }

    createKeySpace();
    createColumnFamily();
}
 
Example 7
Source File: ConnectionStateManager.java    From attic-apex-malhar with Apache License 2.0 4 votes vote down vote up
private void establishSessionWithPolicies()
{
  Cluster.Builder clusterBuilder = Cluster.builder();
  String[] seedNodesSplit = seedNodesStr.split(";");
  Collection<InetAddress> allSeeds = new ArrayList<>();
  Set<String> allKnownPorts = new HashSet<>();
  for (String seedNode : seedNodesSplit) {
    String[] nodeAndPort = seedNode.split(":");
    if (nodeAndPort.length > 1) {
      allKnownPorts.add(nodeAndPort[1]);
    }
    try {
      allSeeds.add(InetAddress.getByName(nodeAndPort[0]));
    } catch (UnknownHostException e) {
      LOG.error(" Error while trying to initialize the seed brokers for the cassandra cluster " + e.getMessage(), e);
    }
  }
  clusterBuilder = clusterBuilder.addContactPoints(allSeeds);
  clusterBuilder
    .withClusterName(clusterName)
    // We can fail if all of the nodes die in the local DC
    .withLoadBalancingPolicy(loadBalancingPolicy)
    // Want Strong consistency
    .withRetryPolicy(retryPolicy)
    // Tolerate some nodes down
    .withQueryOptions(queryOptions)
    // Keep establishing connections after detecting a node down
    .withReconnectionPolicy(reconnectionPolicy);
  // Finally initialize the cluster info
  if (allKnownPorts.size() > 0) {
    int shortlistedPort = Integer.parseInt(allKnownPorts.iterator().next());
    clusterBuilder = clusterBuilder.withPort(shortlistedPort);
  }
  cluster = clusterBuilder.build();
  Metadata metadata = cluster.getMetadata();
  LOG.info("Connected to cluster: \n" + metadata.getClusterName());
  for (Host host : metadata.getAllHosts()) {
    LOG.info(String.format("Datacenter: %s; Host: %s; Rack: %s\n",
        host.getDatacenter(), host.getAddress(), host.getRack()));
  }
  session = cluster.connect(keyspaceName);
}