Java Code Examples for com.datastax.driver.core.Cluster#close()

The following examples show how to use com.datastax.driver.core.Cluster#close() . 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: DefaultCommandContext.java    From titus-control-plane with Apache License 2.0 7 votes vote down vote up
public static CommandContext newCommandContext(CommandLine commandLine) {
    List<String> ips = StringExt.splitByComma(commandLine.getOptionValue("H"));
    int sourcePort = Integer.parseInt(commandLine.getOptionValue("p"));

    QueryOptions queryOptions = new QueryOptions()
            .setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);

    Cluster cluster = Cluster.builder()
            .addContactPoints((String[]) ips.toArray())
            .withPort(sourcePort)
            .withQueryOptions(queryOptions)
            .build();

    return new DefaultCommandContext(
            commandLine,
            cluster.newSession(),
            sourceKeySpace -> cluster.connect('"' + sourceKeySpace + '"'),
            targetKeySpace -> cluster.connect('"' + targetKeySpace + '"')
    ) {
        @Override
        public void shutdown() {
            cluster.close();
        }
    };
}
 
Example 2
Source File: CassandraSinkIT.java    From ingestion with Apache License 2.0 6 votes vote down vote up
@Test
public void initializeCqlTwice() throws TTransportException, IOException, InterruptedException {
  final InetSocketAddress contactPoint = CassandraTestHelper.getCassandraContactPoint();
  Cluster cluster = Cluster.builder()
      .addContactPointsWithPorts(Collections.singletonList(contactPoint))
      .build();
  Session session = cluster.connect();

  session.execute("DROP KEYSPACE IF EXISTS keyspaceTestCassandraSinkIT");
  Assert.assertNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT"));
  _do();
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT"));
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT")
      .getTable("tableTestCassandraSinkIT"));
  _do();
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT"));
  Assert.assertNotNull(session.getCluster().getMetadata().getKeyspace("keyspaceTestCassandraSinkIT")
      .getTable("tableTestCassandraSinkIT"));
  session.execute("DROP KEYSPACE IF EXISTS keyspaceTestCassandraSinkIT");

  session.close();
  cluster.close();
}
 
Example 3
Source File: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/cassandra")
@ResponseBody
public String testcase() {
    logger.info("cassandra contact points: {}:{}", host, port);

    Cluster cluster = null;
    Session session = null;
    try {
        cluster = Cluster.builder().addContactPoint(host).withPort(port).withoutJMXReporting().build();
        session = cluster.connect();
        logger.info("cassandra connection open");

        execute(session);
        executeAsync(session);

        return SUCCESS;
    } finally {
        if (session != null) {
            session.close();
        }
        if (cluster != null) {
            cluster.close();
        }
        logger.info("cassandra connection close");
    }
}
 
Example 4
Source File: CaseController.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/healthCheck")
@ResponseBody
public String healthCheck() {
    Cluster cluster = null;
    Session session = null;
    try {
        cluster = Cluster.builder().addContactPoint(host).withPort(port).withoutJMXReporting().build();
        session = cluster.connect();
        logger.info("cassandra connection open");

        PreparedStatement testPreparedStatement = session.prepare(TEST_EXIST_SQL);
        logger.info("Test result:" + testPreparedStatement.toString());
    } finally {
        if (session != null) {
            session.close();
        }
        if (cluster != null) {
            cluster.close();
        }
        logger.info("cassandra connection close");
    }
    return SUCCESS;
}
 
Example 5
Source File: SchemaUpgradeIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static void backup(String keyspace) throws Exception {
    String cqlsh =
            "cassandra/apache-cassandra-" + CassandraWrapper.CASSANDRA_VERSION + "/bin/cqlsh";
    if (System.getProperty("os.name").startsWith("Windows")) {
        cqlsh += ".bat";
    }
    String backupFolder = "src/test/resources/backup-0.9.1/";
    Cluster cluster = Clusters.newCluster();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    for (TableMetadata table : cluster.getMetadata().getKeyspace(keyspace).getTables()) {
        ProcessBuilder processBuilder = new ProcessBuilder(cqlsh, "-e",
                "copy " + keyspace + "." + table.getName() + " to '" + backupFolder
                        + table.getName() + ".csv' with NULL='NULL.NULL.NULL.NULL' and"
                        + " NUMPROCESSES = 1");
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();
        executor.submit(new ConsoleOutputPipe(process.getInputStream(), System.out));
        process.waitFor();
    }
    executor.shutdown();
    cluster.close();
}
 
Example 6
Source File: CQLSession.java    From cassandra-sidecar with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a Session connected only to the local node from configuration. If null it means the the connection was
 * not able to be established. The session still might throw a NoHostAvailableException if the local host goes
 * offline or otherwise unavailable.
 *
 * @return Session
 */
@Nullable
public synchronized Session getLocalCql()
{
    Cluster cluster = null;
    try
    {
        if (localSession == null)
        {
            cluster = Cluster.builder()
                             .addContactPointsWithPorts(inet)
                             .withLoadBalancingPolicy(wlp)
                             .withQueryOptions(queryOptions)
                             .withReconnectionPolicy(reconnectionPolicy)
                             .withoutMetrics()
                             // tests can create a lot of these Cluster objects, to avoid creating HWTs and
                             // event thread pools for each we have the override
                             .withNettyOptions(nettyOptions)
                             .build();
            localSession = cluster.connect();
        }
    }
    catch (Exception e)
    {
        logger.debug("Failed to reach Cassandra", e);
        if (cluster != null)
        {
            try
            {
                cluster.close();
            }
            catch (Exception ex)
            {
                logger.debug("Failed to close cluster in cleanup", ex);
            }
        }
    }
    return localSession;
}
 
Example 7
Source File: WebDriverSetup.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static WebDriverSetup createSetup(boolean shared) throws Exception {
    int uiPort = getAvailablePort();
    File testDir = Files.createTempDir();
    CentralModule centralModule;
    Container container;
    if (useCentral) {
        CassandraWrapper.start();
        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
        Session session = new Session(cluster.newSession(), "glowroot_unit_tests", null,
                PoolingOptions.DEFAULT_MAX_QUEUE_SIZE);
        session.updateSchemaWithRetry("drop table if exists agent_config");
        session.updateSchemaWithRetry("drop table if exists user");
        session.updateSchemaWithRetry("drop table if exists role");
        session.updateSchemaWithRetry("drop table if exists central_config");
        session.updateSchemaWithRetry("drop table if exists agent");
        session.close();
        cluster.close();
        int grpcPort = getAvailablePort();
        centralModule = createCentralModule(uiPort, grpcPort);
        container = createContainerReportingToCentral(grpcPort, testDir);
    } else {
        centralModule = null;
        container = createContainer(uiPort, testDir);
    }
    if (SauceLabs.useSauceLabs()) {
        return new WebDriverSetup(centralModule, container, uiPort, shared, null);
    } else {
        return new WebDriverSetup(centralModule, container, uiPort, shared, createWebDriver());
    }
}
 
Example 8
Source File: CassandraWrapper.java    From glowroot with Apache License 2.0 5 votes vote down vote up
private static void waitForCassandra() throws InterruptedException {
    while (true) {
        Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
        try {
            cluster.connect();
            cluster.close();
            return;
        } catch (NoHostAvailableException e) {
            cluster.close();
            SECONDS.sleep(1);
        }
    }
}
 
Example 9
Source File: CassandraSessionFactory.java    From jmeter-cassandra with Apache License 2.0 5 votes vote down vote up
public static synchronized void destroyClusters() {
    for (Session session : instance.sessions.values()) {
        Cluster cluster = session.getCluster();
        session.close();
        cluster.close();
    }
    instance.sessions.clear();
}
 
Example 10
Source File: MiscToolIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
    SharedSetupRunListener.startCassandra();
    Cluster cluster = Clusters.newCluster();
    SchemaUpgradeIT.updateSchemaWithRetry(cluster.newSession(),
            "drop keyspace if exists glowroot_tools_test");
    cluster.close();

    System.setProperty("glowroot.cassandra.keyspace", "glowroot_tools_test");
    Main.main(new String[] {"create-schema"});
}
 
Example 11
Source File: Installer.java    From hawkular-metrics with Apache License 2.0 5 votes vote down vote up
private Session createSession() {
    Cluster.Builder clusterBuilder = new Cluster.Builder();
    clusterBuilder.addContactPoints(cassandraNodes.toArray(new String[] {}));
    if (useSSL) {
        SSLOptions sslOptions = null;
        try {
            String[] defaultCipherSuites = {"TLS_RSA_WITH_AES_128_CBC_SHA", "TLS_RSA_WITH_AES_256_CBC_SHA"};
            sslOptions = JdkSSLOptions.builder().withSSLContext(SSLContext.getDefault())
                    .withCipherSuites(defaultCipherSuites).build();
            clusterBuilder.withSSL(sslOptions);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SSL support is required but is not available in the JVM.", e);
        }
    }

    clusterBuilder.withoutJMXReporting();

    Cluster cluster = clusterBuilder.build();
    cluster.init();
    Session createdSession = null;
    try {
        createdSession = cluster.connect("system");
        return createdSession;
    } finally {
        if (createdSession == null) {
            cluster.close();
        }
    }
}
 
Example 12
Source File: ClusterFactory.java    From james-project with Apache License 2.0 5 votes vote down vote up
public static Cluster create(ClusterConfiguration configuration) {
    Preconditions.checkState(configuration.getUsername().isPresent() == configuration.getPassword().isPresent(), "If you specify username, you must specify password");

    Cluster.Builder clusterBuilder = Cluster.builder()
        .withoutJMXReporting();
    configuration.getHosts().forEach(server -> clusterBuilder
        .addContactPoint(server.getHostName())
        .withPort(server.getPort()));

    configuration.getUsername().ifPresent(username ->
        configuration.getPassword().ifPresent(password ->
            clusterBuilder.withCredentials(username, password)));

    clusterBuilder.withQueryOptions(queryOptions());

    SocketOptions socketOptions = new SocketOptions();
    socketOptions.setReadTimeoutMillis(configuration.getReadTimeoutMillis());
    socketOptions.setConnectTimeoutMillis(configuration.getConnectTimeoutMillis());
    clusterBuilder.withSocketOptions(socketOptions);
    clusterBuilder.withRetryPolicy(new LogConsistencyAllRetryPolicy());
    configuration.getPoolingOptions().ifPresent(clusterBuilder::withPoolingOptions);

    if (configuration.useSsl()) {
        clusterBuilder.withSSL();
    }

    Cluster cluster = clusterBuilder.build();
    try {
        configuration.getQueryLoggerConfiguration().map(queryLoggerConfiguration ->
            cluster.register(queryLoggerConfiguration.getQueryLogger()));
        ensureContactable(cluster);
        return cluster;
    } catch (Exception e) {
        cluster.close();
        throw e;
    }
}
 
Example 13
Source File: ResilientClusterProvider.java    From james-project with Apache License 2.0 5 votes vote down vote up
private Callable<Cluster> getClusterRetryCallable(ClusterConfiguration configuration) {
    LOGGER.info("Trying to connect to Cassandra service at {} (list {})", LocalDateTime.now(),
        ImmutableList.copyOf(configuration.getHosts()).toString());

    return () -> {
        Cluster cluster = ClusterFactory.create(configuration);
        try {
            keyspaceExist(cluster, "any"); // plays a sample query to ensure we can contact the cluster
            return cluster;
        } catch (Exception e) {
            cluster.close();
            throw e;
        }
    };
}
 
Example 14
Source File: HintsPollerTest.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Test
public void oldestHintIsPickedFromOneNode() {

    long hintTimestamp = System.currentTimeMillis();

    Cluster cluster = Cluster.builder()
            .addContactPoint("127.0.0.1")
            .withPort(9164)
            .withClusterName("Test Cluster")
            .build();

    Session clusterSession = cluster.connect("system");

    // Insert two hints with different timestamps on the same node.
    clusterSession.execute(getInsertHintsQuery(hintTimestamp));
    clusterSession.execute(getInsertHintsQuery(hintTimestamp + 10000));

    // Get oldestHint
    ClusterHintsPoller clusterHintsPoller = new ClusterHintsPoller();
    HintsPollerResult oldestHintsInfo = clusterHintsPoller.getOldestHintsInfo(clusterSession);
    Assert.assertNotNull(oldestHintsInfo);

    // Since we know there should be only one entry
    long retrievedHintTimeStamp = oldestHintsInfo.getOldestHintTimestamp().or(Long.MAX_VALUE);

    Assert.assertEquals(retrievedHintTimeStamp, hintTimestamp);

    cluster.close();
    clusterSession.close();
}
 
Example 15
Source File: BackupSchema.java    From dcos-cassandra-service with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    Cluster cluster = null;

    try {
        // Send TASK_RUNNING
        sendStatus(driver, Protos.TaskState.TASK_RUNNING,
                "Started taking schema backup");

        cluster = Cluster.builder().addContactPoint(daemon.getProbe().getEndpoint()).build();
        final List<String> keyspaces = StorageUtil.filterSystemKeyspaces(daemon.getNonSystemKeySpaces());

        if (keyspaces.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (String keyspace : keyspaces) {
                LOGGER.info("Taking schema backup for keyspace: {}", keyspace);
                KeyspaceMetadata ksm = cluster.getMetadata().getKeyspace(keyspace);
                sb.append(ksm.exportAsString()).append(System.getProperty("line.separator"));
            }
            backupStorageDriver.uploadSchema(context, sb.toString());
        }

        // Send TASK_FINISHED
        sendStatus(driver, Protos.TaskState.TASK_FINISHED,
                "Finished taking schema backup for keyspaces: " + keyspaces);
    } catch (Throwable t){
        LOGGER.error("Schema backup failed. Reason: ", t);
        sendStatus(driver, Protos.TaskState.TASK_FAILED, t.getMessage());
    } finally {
        if (cluster != null)
            cluster.close();
    }
}
 
Example 16
Source File: CassandraConnectorFactory.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void stop() {
    super.stop();
    // Stop the cassandra cluster
    final Cluster cluster = this.getInjector().getInstance(Cluster.class);
    if (cluster != null) {
        cluster.close();
    }
}
 
Example 17
Source File: CassTest.java    From jelectrum with MIT License 4 votes vote down vote up
public static void main(String args[]) throws Exception
{
  Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();

  Session session = cluster.connect("demo");

  byte[] data = new byte[86];

  Random rnd = new Random();
  rnd.nextBytes(data);

  {

  PreparedStatement ps = session.prepare("UPDATE maptable set data=? where key=?");
  session.execute(ps.bind(ByteBuffer.wrap(data), "zing"));
  }

  session.execute(session.prepare("INSERT into mapset (key,value) values (?,?)").bind("a","b" + rnd.nextInt()));



  cluster.close();

}
 
Example 18
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 19
Source File: ExecutionEngine.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public void execute() throws CommandExecutionException, XMLStreamException, ChecksumInvalidException {
   try {
      if(!metadataTablesExist()) {
         createMetadataTables();
      }

      ChangeLogSet xmlChanges = loadXML();
      ChangeLogSet dbState = loadDB();

      try {
      	xmlChanges.verify(dbState);
      }
      catch(ChecksumInvalidException e) {
      	if(context.getManagerContext().isAuto()) {
      		throw e;
      	}
      	else {
       	System.out.println("Invalid checksum: " + e.getMessage());
       	System.out.println("WARNING: This schema appears to be corrupt, continuing execution could result in data loss, are you sure you want to continue?");
       	if(promptToContinue()) {
       		xmlChanges = loadXML();
       		xmlChanges.verify(dbState, false);
       	}
       	else {
       		System.exit(0);
       	}
      	}
      }

      List<ChangeLog> changesToApply = identifyChanges(xmlChanges, dbState);

      dumpChanges(changesToApply);

      if(!promptToContinue()) {
         System.exit(0);
      }

      List<ExecutionCommand> commands = new LinkedList<ExecutionCommand>();
      for(ChangeLog cl : changesToApply) {
         commands.add(new ChangeLogExecutionCommand(cl));
      }
      commands.add(new ImportLocalizationKeysCommand());

      System.out.println("\nExecuting...");

      executeCommands(commands);

      // if we've rolled back make sure that the target version is now the latest version installed
      if(context.getManagerContext().getOperation() == Operation.ROLLBACK) {
         VersionHistory history = new VersionHistory();
         history.setStatus(Status.APPLIED);
         history.setTimestamp(new Date());
         history.setUsername(context.getManagerContext().getProfile().getUsername());
         history.setVersion(context.getManagerContext().getRollbackTarget());
         context.getVersionHistoryDAO().insert(history);
      }


      System.out.println("...Done!");

   } finally {
      Session session = context.getSession();
      if(session != null) {
         Cluster cluster = session.getCluster();
         session.close();
         cluster.close();
      }
   }
}
 
Example 20
Source File: DataStaxClusterTest.java    From usergrid with Apache License 2.0 4 votes vote down vote up
@Test
public void testConnectCloseCluster() {

    Cluster cluster = dataStaxCluster.getCluster();

    assertTrue(!cluster.isClosed());

    cluster.close();
    assertTrue(cluster.isClosed());

    // validate getCluster will re-init the cluster
    cluster = dataStaxCluster.getCluster();
    assertTrue(!cluster.isClosed());


}