@Override protected void closeConnectionQuietly(Session session) { try { session.getCluster().close(); } catch (Exception e) { log.error("Could not close cassandra connection", e); } } }
@Override public List<String> getCaseSensitiveSchemaNames() { ImmutableList.Builder<String> builder = ImmutableList.builder(); List<KeyspaceMetadata> keyspaces = executeWithSession(session -> session.getCluster().getMetadata().getKeyspaces()); for (KeyspaceMetadata meta : keyspaces) { builder.add(meta.getName()); } return builder.build(); }
@Override public Set<Host> getReplicas(String caseSensitiveSchemaName, TokenRange tokenRange) { requireNonNull(caseSensitiveSchemaName, "keyspace is null"); requireNonNull(tokenRange, "tokenRange is null"); return executeWithSession(session -> session.getCluster().getMetadata().getReplicas(validSchemaName(caseSensitiveSchemaName), tokenRange)); }
@Override public Set<Host> getReplicas(String caseSensitiveSchemaName, ByteBuffer partitionKey) { requireNonNull(caseSensitiveSchemaName, "keyspace is null"); requireNonNull(partitionKey, "partitionKey is null"); return executeWithSession(session -> session.getCluster().getMetadata().getReplicas(validSchemaName(caseSensitiveSchemaName), partitionKey)); }
@Override public Set<TokenRange> getTokenRanges() { return executeWithSession(session -> session.getCluster().getMetadata().getTokenRanges()); }
@Override public String getPartitioner() { return executeWithSession(session -> session.getCluster().getMetadata().getPartitioner()); }
private void checkSizeEstimatesTableExist() { KeyspaceMetadata keyspaceMetadata = executeWithSession(session -> session.getCluster().getMetadata().getKeyspace(SYSTEM)); checkState(keyspaceMetadata != null, "system keyspace metadata must not be null"); TableMetadata table = keyspaceMetadata.getTable(SIZE_ESTIMATES); if (table == null) { throw new PrestoException(NOT_SUPPORTED, "Cassandra versions prior to 2.1.5 are not supported"); } }
private MappingManager getMappingManager(Session session) { synchronized (mappingManagers) { MappingManager mappingManager = mappingManagers.get(session); if (mappingManager == null) { mappingManager = new MappingManager(session); mappingManagers.put(session, mappingManager); CodecRegistry codecRegistry = session.getCluster().getConfiguration().getCodecRegistry(); for (TypeCodec<?> codec : codecs) { codecRegistry.register(codec); } for (Class<?> udtClass : udtClasses) { mappingManager.udtCodec(udtClass); } } return mappingManager; } } }
/** * Wait until all Cassandra nodes agree on the schema. Sleeps 100ms between checks. * */ public void waitForSchemaAgreement() { while ( true ) { if( getClusterSession().getCluster().getMetadata().checkSchemaAgreement() ){ return; } //sleep and try it again try { Thread.sleep( 100 ); } catch ( InterruptedException e ) { //swallow } } }
private KeyspaceMetadata getKeyspaceByCaseInsensitiveName(String caseInsensitiveSchemaName) throws SchemaNotFoundException { List<KeyspaceMetadata> keyspaces = executeWithSession(session -> session.getCluster().getMetadata().getKeyspaces()); KeyspaceMetadata result = null; // Ensure that the error message is deterministic List<KeyspaceMetadata> sortedKeyspaces = Ordering.from(comparing(KeyspaceMetadata::getName)).immutableSortedCopy(keyspaces); for (KeyspaceMetadata keyspace : sortedKeyspaces) { if (keyspace.getName().equalsIgnoreCase(caseInsensitiveSchemaName)) { if (result != null) { throw new PrestoException( NOT_SUPPORTED, format("More than one keyspace has been found for the case insensitive schema name: %s -> (%s, %s)", caseInsensitiveSchemaName, result.getName(), keyspace.getName())); } result = keyspace; } } if (result == null) { throw new SchemaNotFoundException(caseInsensitiveSchemaName); } return result; }
public void prepare() { LOG.info("Preparing state for {}", options.toString()); Preconditions.checkNotNull(options.getMapper, "CassandraBackingMap.Options should have getMapper"); Preconditions.checkNotNull(options.putMapper, "CassandraBackingMap.Options should have putMapper"); client = options.clientProvider.getClient(conf); session = client.connect(); if (options.maxParallelism == null || options.maxParallelism <= 0) { PoolingOptions po = session.getCluster().getConfiguration().getPoolingOptions(); Integer maxRequestsPerHost = Math.min( po.getMaxConnectionsPerHost(HostDistance.LOCAL) * po.getMaxRequestsPerConnection(HostDistance.LOCAL), po.getMaxConnectionsPerHost(HostDistance.REMOTE) * po.getMaxRequestsPerConnection(HostDistance.REMOTE) ); options.maxParallelism = maxRequestsPerHost / 2; LOG.info("Parallelism default set to {}", options.maxParallelism); } throttle = new Semaphore(options.maxParallelism, false); this.getResultMapper = new TridentAyncCQLResultSetValuesMapper(options.stateMapper.getStateFields(), throttle); this.putResultMapper = new TridentAyncCQLResultSetValuesMapper(null, throttle); }
/** Closes Cassandra driver session. */ public static void closeSession(Session driverSes) { if (driverSes == null) return; Cluster cluster = driverSes.getCluster(); if (!driverSes.isClosed()) U.closeQuiet(driverSes); if (!cluster.isClosed()) U.closeQuiet(cluster); }
.getCluster() .getConfiguration() .getCodecRegistry()
protected UserType getUserType(String userType) { return getSession().getCluster().getMetadata().getKeyspace(KAA).getUserType(userType); }
private void createTable(TableDefinition tableDefinition, boolean forceCheckSchema) throws Exception { boolean exists; if(!forceCheckSchema){ exists = dataStaxCluster.getClusterSession().getCluster() .getMetadata() .getKeyspace(CQLUtils.quote( tableDefinition.getKeyspace() ) ) .getTable( tableDefinition.getTableName() ) != null; }else{ exists = dataStaxCluster.getClusterSession() .execute("select * from system.schema_columnfamilies where keyspace_name='"+tableDefinition.getKeyspace() +"' and columnfamily_name='"+CQLUtils.unquote(tableDefinition.getTableName())+"'").one() != null; } if( exists ){ logger.info("Not creating table {}, it already exists.", tableDefinition.getTableName()); return; } String CQL = tableDefinition.getTableCQL(cassandraFig, TableDefinition.ACTION.CREATE); if (logger.isDebugEnabled()) { logger.debug(CQL); } if ( tableDefinition.getKeyspace().equals( cassandraFig.getApplicationKeyspace() )) { dataStaxCluster.getApplicationSession().execute( CQL ); } else { dataStaxCluster.getApplicationLocalSession().execute( CQL ); } logger.info("Created table: {} in keyspace {}", tableDefinition.getTableName(), tableDefinition.getKeyspace()); }
/** * Execute CQL that will create the keyspace if it doesn't exist and alter it if it does. * @throws Exception * @param forceCheck */ @Override public synchronized void createApplicationKeyspace(boolean forceCheck) throws Exception { boolean exists; if(!forceCheck) { // this gets info from client's metadata exists = getClusterSession().getCluster().getMetadata() .getKeyspace(CQLUtils.quote(cassandraConfig.getApplicationKeyspace())) != null; }else{ exists = getClusterSession() .execute("select * from system.schema_keyspaces where keyspace_name = '"+cassandraConfig.getApplicationKeyspace()+"'") .one() != null; } if(exists){ logger.info("Not creating keyspace {}, it already exists.", cassandraConfig.getApplicationKeyspace()); return; } final String createApplicationKeyspace = String.format( "CREATE KEYSPACE IF NOT EXISTS %s WITH replication = %s", CQLUtils.quote( cassandraConfig.getApplicationKeyspace()), CQLUtils.getFormattedReplication( cassandraConfig.getStrategy(), cassandraConfig.getStrategyOptions()) ); getClusterSession().execute(createApplicationKeyspace); waitForSchemaAgreement(); logger.info("Created keyspace: {}", cassandraConfig.getApplicationKeyspace()); }
if(!forceCheck) { exists = getClusterSession().getCluster().getMetadata() .getKeyspace(CQLUtils.quote(cassandraConfig.getApplicationLocalKeyspace())) != null; }else{
@SuppressWarnings("unchecked") private UDTValue convertValue(Object value, CassandraEntityMapper<?> mapper, CassandraClient cassandraClient) { String keyspace = cassandraClient.getSession().getLoggedKeyspace(); UserType userType = cassandraClient.getSession() .getCluster() .getMetadata() .getKeyspace(keyspace) .getUserType(mapper.getName()); UDTValue udtValue = userType.newValue(); for (String name : mapper.getNonKeyColumnNames()) { Object fieldValue = mapper.getColumnValueForName(name, value, cassandraClient); if (fieldValue != null) { udtValue.set(name, fieldValue, (Class<Object>) fieldValue.getClass()); } else { udtValue.setToNull(name); } } return udtValue; } }
@Test public void testGetClusterSession() { Session session = dataStaxCluster.getClusterSession(); String clusterName = session.getCluster().getClusterName(); String keyspaceName = session.getLoggedKeyspace(); // cluster session is not logged to a keyspace assertNull(keyspaceName); assertNotNull(clusterName); }
stopWatch.stop(); long duration = stopWatch.getDuration(TimeUnit.MILLISECONDS); String transitUri = "cassandra://" + connectionSession.getCluster().getMetadata().getClusterName() + "." + cassandraTable;