List of usage examples for org.apache.cassandra.transport.messages QueryMessage QueryMessage
public QueryMessage(String query, QueryOptions options)
From source file:com.datastax.driver.core.Connection.java
License:Apache License
public void setKeyspace(String keyspace) throws ConnectionException { if (keyspace == null) return;//from www . ja v a2 s . c om if (this.keyspace != null && this.keyspace.equals(keyspace)) return; try { logger.trace("[{}] Setting keyspace {}", name, keyspace); // Note: we quote the keyspace below, because the name is the one coming from Cassandra, so it's in the right case already long timeout = factory.getConnectTimeoutMillis(); Future future = write( new QueryMessage("USE \"" + keyspace + "\"", ConsistencyLevel.DEFAULT_CASSANDRA_CL)); Message.Response response = Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); switch (response.type) { case RESULT: this.keyspace = keyspace; break; default: // The code set the keyspace only when a successful 'use' // has been perform, so there shouldn't be any error here. // It can happen however that the node we're connecting to // is not up on the schema yet. In that case, defuncting // the connection is not a bad choice. defunct(new ConnectionException(address, String.format("Problem while setting keyspace, got %s as response", response))); break; } } catch (ConnectionException e) { throw defunct(e); } catch (TimeoutException e) { logger.warn(String.format( "Timeout while setting keyspace on connection to %s. This should not happen but is not critical (it will retried)", address)); } catch (BusyConnectionException e) { logger.warn(String.format( "Tried to set the keyspace on busy connection to %s. This should not happen but is not critical (it will retried)", address)); } catch (ExecutionException e) { throw defunct(new ConnectionException(address, "Error while setting keyspace", e)); } }
From source file:com.datastax.driver.core.ControlConnection.java
License:Apache License
static void refreshSchema(Connection connection, String keyspace, String table, Cluster.Manager cluster) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { // Make sure we're up to date on schema String whereClause = ""; if (keyspace != null) { whereClause = " WHERE keyspace_name = '" + keyspace + "'"; if (table != null) whereClause += " AND columnfamily_name = '" + table + "'"; }//from w w w. j av a 2s. c o m ResultSetFuture ksFuture = table == null ? new ResultSetFuture(null, new QueryMessage(SELECT_KEYSPACES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL)) : null; ResultSetFuture cfFuture = new ResultSetFuture(null, new QueryMessage(SELECT_COLUMN_FAMILIES + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture colsFuture = new ResultSetFuture(null, new QueryMessage(SELECT_COLUMNS + whereClause, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); if (ksFuture != null) connection.write(ksFuture.callback); connection.write(cfFuture.callback); connection.write(colsFuture.callback); cluster.metadata.rebuildSchema(keyspace, table, ksFuture == null ? null : ksFuture.get(), cfFuture.get(), colsFuture.get()); }
From source file:com.datastax.driver.core.ControlConnection.java
License:Apache License
private void refreshNodeListAndTokenMap(Connection connection) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { // Make sure we're up to date on nodes and tokens ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); connection.write(peersFuture.callback); connection.write(localFuture.callback); String partitioner = null;/*from w ww .j a va 2 s.c o m*/ Map<Host, Collection<String>> tokenMap = new HashMap<Host, Collection<String>>(); // Update cluster name, DC and rack for the one node we are connected to Row localRow = localFuture.get().one(); if (localRow != null) { String clusterName = localRow.getString("cluster_name"); if (clusterName != null) cluster.metadata.clusterName = clusterName; partitioner = localRow.getString("partitioner"); Host host = cluster.metadata.getHost(connection.address); // In theory host can't be null. However there is no point in risking a NPE in case we // have a race between a node removal and this. if (host == null) { logger.debug("Host in local system table ({}) unknown to us (ok if said host just got removed)", connection.address); } else { updateLocationInfo(host, localRow.getString("data_center"), localRow.getString("rack")); Set<String> tokens = localRow.getSet("tokens", String.class); if (partitioner != null && !tokens.isEmpty()) tokenMap.put(host, tokens); } } List<InetAddress> foundHosts = new ArrayList<InetAddress>(); List<String> dcs = new ArrayList<String>(); List<String> racks = new ArrayList<String>(); List<Set<String>> allTokens = new ArrayList<Set<String>>(); for (Row row : peersFuture.get()) { InetAddress addr = row.getInet("rpc_address"); if (addr == null) { addr = row.getInet("peer"); logger.error( "No rpc_address found for host {} in {}'s peers system table. That should not happen but using address {} instead", addr, connection.address, addr); } else if (addr.equals(bindAllAddress)) { addr = row.getInet("peer"); } foundHosts.add(addr); dcs.add(row.getString("data_center")); racks.add(row.getString("rack")); allTokens.add(row.getSet("tokens", String.class)); } for (int i = 0; i < foundHosts.size(); i++) { Host host = cluster.metadata.getHost(foundHosts.get(i)); if (host == null) { // We don't know that node, add it. host = cluster.addHost(foundHosts.get(i), true); } updateLocationInfo(host, dcs.get(i), racks.get(i)); if (partitioner != null && !allTokens.get(i).isEmpty()) tokenMap.put(host, allTokens.get(i)); } // Removes all those that seems to have been removed (since we lost the control connection) Set<InetAddress> foundHostsSet = new HashSet<InetAddress>(foundHosts); for (Host host : cluster.metadata.allHosts()) if (!host.getAddress().equals(connection.address) && !foundHostsSet.contains(host.getAddress())) cluster.removeHost(host); if (partitioner != null) cluster.metadata.rebuildTokenMap(partitioner, tokenMap); }
From source file:com.datastax.driver.core.ControlConnection.java
License:Apache License
static boolean waitForSchemaAgreement(Connection connection, Metadata metadata) throws ConnectionException, BusyConnectionException, ExecutionException, InterruptedException { long start = System.nanoTime(); long elapsed = 0; while (elapsed < MAX_SCHEMA_AGREEMENT_WAIT_MS) { ResultSetFuture peersFuture = new ResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_PEERS, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); ResultSetFuture localFuture = new ResultSetFuture(null, new QueryMessage(SELECT_SCHEMA_LOCAL, ConsistencyLevel.DEFAULT_CASSANDRA_CL)); connection.write(peersFuture.callback); connection.write(localFuture.callback); Set<UUID> versions = new HashSet<UUID>(); Row localRow = localFuture.get().one(); if (localRow != null && !localRow.isNull("schema_version")) versions.add(localRow.getUUID("schema_version")); for (Row row : peersFuture.get()) { if (row.isNull("rpc_address") || row.isNull("schema_version")) continue; InetAddress rpc = row.getInet("rpc_address"); if (rpc.equals(bindAllAddress)) rpc = row.getInet("peer"); Host peer = metadata.getHost(rpc); if (peer != null && peer.isUp()) versions.add(row.getUUID("schema_version")); }//from w w w . j a va 2 s. c om logger.debug("Checking for schema agreement: versions are {}", versions); if (versions.size() <= 1) return true; // let's not flood the node too much Thread.sleep(200); elapsed = Cluster.timeSince(start, TimeUnit.MILLISECONDS); } return false; }
From source file:com.datastax.driver.core.QueryTrace.java
License:Apache License
private void doFetchTrace() { int tries = 0; try {//w w w.ja v a 2 s . c o m // We cannot guarantee the trace is complete. But we can't at least wait until we have all the information // the coordinator log in the trace. Since the duration is the last thing the coordinator log, that's // what we check to know if the trace is "complete" (again, it may not contain the log of replicas). while (duration == Integer.MIN_VALUE && tries <= MAX_TRIES) { ++tries; ResultSetFuture sessionsFuture = session .executeQuery(new QueryMessage(String.format(SELECT_SESSIONS_FORMAT, traceId), ConsistencyLevel.DEFAULT_CASSANDRA_CL), Query.DEFAULT); ResultSetFuture eventsFuture = session .executeQuery(new QueryMessage(String.format(SELECT_EVENTS_FORMAT, traceId), ConsistencyLevel.DEFAULT_CASSANDRA_CL), Query.DEFAULT); Row sessRow = sessionsFuture.get().one(); if (sessRow != null && !sessRow.isNull("duration")) { requestType = sessRow.getString("request"); coordinator = sessRow.getInet("coordinator"); if (!sessRow.isNull("parameters")) parameters = Collections .unmodifiableMap(sessRow.getMap("parameters", String.class, String.class)); startedAt = sessRow.getDate("started_at").getTime(); events = new ArrayList<Event>(); for (Row evRow : eventsFuture.get()) { events.add(new Event(evRow.getString("activity"), evRow.getUUID("event_id").timestamp(), evRow.getInet("source"), evRow.getInt("source_elapsed"), evRow.getString("thread"))); } events = Collections.unmodifiableList(events); // Set the duration last as it's our test to know if the trace is complete duration = sessRow.getInt("duration"); } else { // The trace is not ready. Give it a few milliseconds before trying again. // Notes: granted, sleeping uninterruptibly is bad, but having all method propagate // InterruptedException bothers me. Uninterruptibles.sleepUninterruptibly(tries * BASE_SLEEP_BETWEEN_TRIES_IN_MS, TimeUnit.MILLISECONDS); } } } catch (Exception e) { throw new TraceRetrievalException("Unexpected exception while fetching query trace", e); } if (tries > MAX_TRIES) throw new TraceRetrievalException( String.format("Unable to retrieve complete query trace after %d tries", MAX_TRIES)); }
From source file:com.datastax.driver.core.RequestHandler.java
License:Apache License
@Override public Message.Request request() { Message.Request request = callback.request(); if (retryConsistencyLevel != null) { org.apache.cassandra.db.ConsistencyLevel cl = ConsistencyLevel.toCassandraCL(retryConsistencyLevel); if (request instanceof QueryMessage) { QueryMessage qm = (QueryMessage) request; if (qm.consistency != cl) request = new QueryMessage(qm.query, cl); } else if (request instanceof ExecuteMessage) { ExecuteMessage em = (ExecuteMessage) request; if (em.consistency != cl) request = new ExecuteMessage(em.statementId, em.values, cl); }//from w w w. j a v a 2s .co m } return request; }
From source file:com.datastax.driver.core.RetryingCallback.java
License:Apache License
public Message.Request request() { Message.Request request = callback.request(); if (retryConsistencyLevel != null) { org.apache.cassandra.db.ConsistencyLevel cl = ConsistencyLevel.toCassandraCL(retryConsistencyLevel); if (request instanceof QueryMessage) { QueryMessage qm = (QueryMessage) request; if (qm.consistency != cl) request = new QueryMessage(qm.query, cl); } else if (request instanceof ExecuteMessage) { ExecuteMessage em = (ExecuteMessage) request; if (em.consistency != cl) request = new ExecuteMessage(em.statementId, em.values, cl); }//from w w w .j a va 2 s. co m } return request; }
From source file:com.datastax.driver.core.Session.java
License:Apache License
/** * Executes the provided query asynchronously. * * This method does not block. It returns as soon as the query has been * passed to the underlying network stack. In particular, returning from * this method does not guarantee that the query is valid or has even been * submitted to a live node. Any exception pertaining to the failure of the * query will be thrown when accessing the {@link ResultSetFuture}. * * Note that for queries that doesn't return a result (INSERT, UPDATE and * DELETE), you will need to access the ResultSetFuture (that is call one of * its get method to make sure the query was successful. * * @param query the CQL query to execute (that can be either a {@code * Statement} or a {@code BoundStatement}). If it is a {@code * BoundStatement}, all variables must have been bound (the statement must * be ready)./* ww w .j a v a2s . c o m*/ * @return a future on the result of the query. * * @throws IllegalStateException if {@code query} is a {@code BoundStatement} * but {@code !query.isReady()}. */ public ResultSetFuture executeAsync(Query query) { if (query instanceof Statement) { return manager.executeQuery(new QueryMessage(((Statement) query).getQueryString(), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query); } else { assert query instanceof BoundStatement : query; BoundStatement bs = (BoundStatement) query; return manager.executeQuery(new ExecuteMessage(bs.statement.id, Arrays.asList(bs.values), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query); } }
From source file:com.datastax.driver.core.SessionManager.java
License:Apache License
public ResultSetFuture executeAsync(Query query) { if (query instanceof Statement) { return executeQuery(new QueryMessage(((Statement) query).getQueryString(), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query); } else {//from w w w . j a va2 s .com assert query instanceof BoundStatement : query; BoundStatement bs = (BoundStatement) query; return executeQuery(new ExecuteMessage(bs.statement.id, Arrays.asList(bs.values), ConsistencyLevel.toCassandraCL(query.getConsistencyLevel())), query); } }
From source file:com.datastax.driver.core.SessionManager.java
License:Apache License
void setKeyspace(String keyspace) { long timeout = configuration().getSocketOptions().getConnectTimeoutMillis(); try {/*from w ww . jav a 2s.c om*/ Future<?> future = executeQuery( new QueryMessage("use " + keyspace, ConsistencyLevel.DEFAULT_CASSANDRA_CL), Query.DEFAULT); // Note: using the connection timeout isn't perfectly correct, we should probably change that someday Uninterruptibles.getUninterruptibly(future, timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { throw new DriverInternalError(String.format( "No responses after %d milliseconds while setting current keyspace. This should not happen, unless you have setup a very low connection timeout.", timeout)); } catch (ExecutionException e) { DefaultResultSetFuture.extractCauseFromExecutionException(e); } }