com.netflix.astyanax.connectionpool.OperationResult Java Examples

The following examples show how to use com.netflix.astyanax.connectionpool.OperationResult. 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: CassandraStoreImpl.java    From recipes-rss with Apache License 2.0 6 votes vote down vote up
/**
 * Get the feed urls from Cassandra
 */
@Override
public List<String> getSubscribedUrls(String userId) throws Exception{
    OperationResult<ColumnList<String>> response;
    try {
        response = getKeyspace().prepareQuery(CF_SUBSCRIPTIONS).getKey(userId).execute();
    } catch (NotFoundException e) {
        logger.error("No record found for this user: " + userId);
        throw e;
    } catch (Exception t) {
        logger.error("Exception occurred when fetching from Cassandra: " + t);
        throw t;
    }

    final List<String> items = new ArrayList<String>();
    if (response != null) {
        final ColumnList<String> columns = response.getResult();
        for (Column<String> column : columns) {
            items.add(column.getName());
        }
    }

    return items;
}
 
Example #2
Source File: CassandraMutagenImplTest.java    From mutagen-cassandra with Apache License 2.0 6 votes vote down vote up
private static void createKeyspace()
		throws ConnectionException {

	System.out.println("Creating keyspace "+keyspace+"...");

	int keyspaceReplicationFactor=1;

	Map<String, Object> keyspaceConfig=
		new HashMap<String, Object>();
	keyspaceConfig.put("strategy_options",
		ImmutableMap.<String, Object>builder()
			.put("replication_factor",
				""+keyspaceReplicationFactor)
			.build());

	String keyspaceStrategyClass="SimpleStrategy";
	keyspaceConfig.put("strategy_class",keyspaceStrategyClass);

	OperationResult<SchemaChangeResult> result=
		keyspace.createKeyspace(
			Collections.unmodifiableMap(keyspaceConfig));

	System.out.println("Created keyspace "+keyspace);
}
 
Example #3
Source File: EntityCollectionManagerImpl.java    From usergrid with Apache License 2.0 6 votes vote down vote up
@Override
public Health getHealth() {

    try {
        ColumnFamily<String, String> CF_SYSTEM_LOCAL =
            new ColumnFamily<String, String>( "system.local", StringSerializer.get(), StringSerializer.get(),
                StringSerializer.get() );

        OperationResult<CqlResult<String, String>> result =
            keyspace.prepareQuery( CF_SYSTEM_LOCAL )
                .setConsistencyLevel(ConsistencyLevel.CL_ONE)
                .withCql( "SELECT now() FROM system.local;" )
                .execute();

        if ( result.getResult().getRows().size() > 0 ) {
            return Health.GREEN;
        }
    }
    catch ( ConnectionException ex ) {
        logger.error( "Error connecting to Cassandra", ex );
    }

    return Health.RED;
}
 
Example #4
Source File: MetaDaoImpl.java    From staash with Apache License 2.0 6 votes vote down vote up
@Override
public void writeMetaEntity(Entity entity) {
    // TODO Auto-generated method stub
    Keyspace ks = kscp.acquireKeyspace("meta");
    ks.prepareMutationBatch();
    MutationBatch m;
    OperationResult<Void> result;
    m = ks.prepareMutationBatch();
    m.withRow(dbcf, entity.getRowKey()).putColumn(entity.getName(), entity.getPayLoad(), null);
    try {
        result = m.execute();
        if (entity instanceof PaasTableEntity) {
            String schemaName = ((PaasTableEntity)entity).getSchemaName();
            Keyspace schemaks = kscp.acquireKeyspace(schemaName);
            ColumnFamily<String, String> cf = ColumnFamily.newColumnFamily(entity.getName(), StringSerializer.get(), StringSerializer.get());
            schemaks.createColumnFamily(cf, null);
        }
        int i = 0;
    } catch (ConnectionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
 
Example #5
Source File: CassandraHealthCheck.java    From emodb with Apache License 2.0 6 votes vote down vote up
private Result pingAll() {
    try {
        StringBuilder message = new StringBuilder();

        OperationResult<CqlStatementResult> astyanaxResult = pingAstyanax();
        message.append("Astyanax: ").append(astyanaxResult.getHost()).append(" ")
                .append(astyanaxResult.getLatency(TimeUnit.MICROSECONDS)).append("us");

        if (astyanaxResult.getAttemptsCount() != 1) {
            message.append(", ").append(astyanaxResult.getAttemptsCount()).append(" attempts");
        }

        Stopwatch cqlTimer = Stopwatch.createStarted();
        ResultSet cqlResult = pingCql();
        long queryDurationMicros = cqlTimer.elapsed(TimeUnit.MICROSECONDS);

        Host host = cqlResult.getExecutionInfo().getQueriedHost();
        message.append(" | CQL: ").append(host).append(" ").append(queryDurationMicros).append("us");

        return Result.healthy(message.toString());
    } catch (Throwable t) {
        return Result.unhealthy(t);
    }
}
 
Example #6
Source File: CassandraStorage.java    From greycat with Apache License 2.0 6 votes vote down vote up
@Override
public void put(Buffer stream, Callback<Boolean> callback) {
    MutationBatch m = keyspace.prepareMutationBatch();
    BufferIterator it = stream.iterator();
    while (it.hasNext()) {
        Buffer keyView = it.next();
        Buffer valueView = it.next();
        if (valueView != null) {
            m.withRow(MWG, keyView.data()).putColumn(0, valueView.data());
        }
    }
    try {
        @SuppressWarnings("unused")
        OperationResult<Void> result = m.execute();
        callback.on(true);
    } catch (ConnectionException e) {
        callback.on(false);
    }
}
 
Example #7
Source File: AstyanaxKeyColumnValueStore.java    From titan1withtp3.1 with Apache License 2.0 5 votes vote down vote up
@Override
public KeyIterator getKeys(KeyRangeQuery query, StoreTransaction txh) throws BackendException {
    // this query could only be done when byte-ordering partitioner is used
    // because Cassandra operates on tokens internally which means that even contiguous
    // range of keys (e.g. time slice) with random partitioner could produce disjoint set of tokens
    // returning ambiguous results to the user.
    Partitioner partitioner = storeManager.getPartitioner();
    if (partitioner != Partitioner.BYTEORDER)
        throw new PermanentBackendException("getKeys(KeyRangeQuery could only be used with byte-ordering partitioner.");

    ByteBuffer start = query.getKeyStart().asByteBuffer(), end = query.getKeyEnd().asByteBuffer();

    RowSliceQuery rowSlice = keyspace.prepareQuery(columnFamily)
            .setConsistencyLevel(getTx(txh).getReadConsistencyLevel().getAstyanax())
            .withRetryPolicy(retryPolicy.duplicate())
            .getKeyRange(start, end, null, null, Integer.MAX_VALUE);

    // Astyanax is bad at builder pattern :(
    rowSlice.withColumnRange(query.getSliceStart().asByteBuffer(),
            query.getSliceEnd().asByteBuffer(),
            false,
            query.getLimit());

    // Omit final the query's keyend from the result, if present in result
    final Rows<ByteBuffer, ByteBuffer> r;
    try {
        r = ((OperationResult<Rows<ByteBuffer, ByteBuffer>>) rowSlice.execute()).getResult();
    } catch (ConnectionException e) {
        throw new TemporaryBackendException(e);
    }
    Iterator<Row<ByteBuffer, ByteBuffer>> i =
            Iterators.filter(r.iterator(), new KeySkipPredicate(query.getKeyEnd().asByteBuffer()));
    return new RowIterator(i, query);
}
 
Example #8
Source File: CassandraStoreImpl.java    From recipes-rss with Apache License 2.0 5 votes vote down vote up
/**
 * Delete feed url from Cassandra
 */
@Override
public void unsubscribeUrl(String userId, String url) throws Exception{
    try {
        OperationResult<Void> opr = getKeyspace().prepareColumnMutation(CF_SUBSCRIPTIONS, userId, url)
            .deleteColumn().execute();
        logger.info("Time taken to delete from Cassandra (in ms): " + opr.getLatency(TimeUnit.MILLISECONDS));
    } catch (Exception e) {
        logger.error("Exception occurred when writing to Cassandra: " + e);
        throw e;
    }
}
 
Example #9
Source File: CassandraStoreImpl.java    From recipes-rss with Apache License 2.0 5 votes vote down vote up
/**
 * Add feed url into Cassandra
 */
@Override
public void subscribeUrl(String userId, String url) throws Exception{
    try {
        OperationResult<Void> opr = getKeyspace().prepareColumnMutation(CF_SUBSCRIPTIONS, userId, url)
            .putValue("1", null).execute();
        logger.info("Time taken to add to Cassandra (in ms): " + opr.getLatency(TimeUnit.MILLISECONDS));
    } catch (Exception e) {
        logger.error("Exception occurred when writing to Cassandra: " + e);
        throw e;
    }
}
 
Example #10
Source File: AstyanaxReader.java    From blueflood with Apache License 2.0 5 votes vote down vote up
protected Map<Locator, ColumnList<Long>> getColumnsFromDB(List<Locator> locators, ColumnFamily<Locator, Long> CF,
                                                        Range range) {
    if (range.getStart() > range.getStop()) {
        throw new RuntimeException(String.format("Invalid rollup range: ", range.toString()));
    }
    boolean isBatch = locators.size() != 1;

    final Map<Locator, ColumnList<Long>> columns = new HashMap<Locator, ColumnList<Long>>();
    final RangeBuilder rangeBuilder = new RangeBuilder().setStart(range.getStart()).setEnd(range.getStop());

    Timer.Context ctx = isBatch ? Instrumentation.getBatchReadTimerContext(CF.getName()) : Instrumentation.getReadTimerContext(CF.getName());
    try {
        // We don't paginate this call. So we should make sure the number of reads is tolerable.
        // TODO: Think about paginating this call.
        OperationResult<Rows<Locator, Long>> query = keyspace
                .prepareQuery(CF)
                .getKeySlice(locators)
                .withColumnRange(rangeBuilder.build())
                .execute();
        for (Row<Locator, Long> row : query.getResult()) {
            columns.put(row.getKey(), row.getColumns());
        }

    } catch (ConnectionException e) {
        if (e instanceof NotFoundException) { // TODO: Not really sure what happens when one of the keys is not found.
            Instrumentation.markNotFound(CF.getName());
        } else {
            if (isBatch) { Instrumentation.markBatchReadError(e); }
            else { Instrumentation.markReadError(e); }
        }
        log.error((isBatch ? "Batch " : "") + " read query failed for column family " + CF.getName() + " for locators: " + StringUtils.join(locators, ","), e);
    } finally {
        ctx.stop();
    }

    return columns;
}
 
Example #11
Source File: AstyanaxReader.java    From blueflood with Apache License 2.0 5 votes vote down vote up
public Table<Locator, String, String> getMetadataValues(Set<Locator> locators) {
    ColumnFamily CF = CassandraModel.CF_METRICS_METADATA;
    boolean isBatch = locators.size() > 1;
    Table<Locator, String, String> metaTable = HashBasedTable.create();

    Timer.Context ctx = isBatch ? Instrumentation.getBatchReadTimerContext(CF.getName()) : Instrumentation.getReadTimerContext(CF.getName());
    try {
        // We don't paginate this call. So we should make sure the number of reads is tolerable.
        // TODO: Think about paginating this call.
        OperationResult<Rows<Locator, String>> query = keyspace
                .prepareQuery(CF)
                .getKeySlice(locators)
                .execute();

        for (Row<Locator, String> row : query.getResult()) {
            ColumnList<String> columns = row.getColumns();
            for (Column<String> column : columns) {
                String metaValue = column.getValue(StringMetadataSerializer.get());
                String metaKey = column.getName();
                metaTable.put(row.getKey(), metaKey, metaValue);
            }
        }
    } catch (ConnectionException e) {
        if (e instanceof NotFoundException) { // TODO: Not really sure what happens when one of the keys is not found.
            Instrumentation.markNotFound(CF.getName());
        } else {
            if (isBatch) { Instrumentation.markBatchReadError(e); }
            else { Instrumentation.markReadError(e); }
        }
        log.error((isBatch ? "Batch " : "") + " read query failed for column family " + CF.getName() + " for locators: " + StringUtils.join(locators, ","), e);
    } finally {
        ctx.stop();
    }

    return metaTable;
}
 
Example #12
Source File: AstyanaxMetaDaoImpl.java    From staash with Apache License 2.0 5 votes vote down vote up
public Map<String, JsonObject> runQuery(String key, String col) {
	OperationResult<CqlStatementResult> rs;
	Map<String, JsonObject> resultMap = new HashMap<String, JsonObject>();
	try {
		String queryStr = "";
		if (col != null && !col.equals("*")) {
			queryStr = "select column1, value from "+MetaConstants.META_KEY_SPACE + "." + MetaConstants.META_COLUMN_FAMILY +" where key='"
					+ key + "' and column1='" + col + "';";
		} else {
			queryStr = "select column1, value from "+MetaConstants.META_KEY_SPACE + "." + MetaConstants.META_COLUMN_FAMILY +" where key='"
					+ key + "';";
		}
		rs = keyspace.prepareCqlStatement().withCql(queryStr).execute();
		for (Row<String, String> row : rs.getResult().getRows(METACF)) {

			ColumnList<String> columns = row.getColumns();

			String key1 = columns.getStringValue("column1", null);
			String val1 = columns.getStringValue("value", null);
			resultMap.put(key1, new JsonObject(val1));
		}
	} catch (ConnectionException e) {
		e.printStackTrace();
		throw new RuntimeException(e.getMessage());
	}

	return resultMap;
}
 
Example #13
Source File: InstanceDataDAOCassandra.java    From Raigad with Apache License 2.0 5 votes vote down vote up
public String findKey(String cluster, String instanceId, String dc) {
    try {
        final String selectClause = String.format(
                "SELECT * FROM %s WHERE %s = '%s' and %s = '%s' and %s = '%s'  ", CF_NAME_INSTANCES,
                CN_CLUSTER, cluster, CN_INSTANCEID, instanceId, CN_LOCATION, dc);

        logger.info(selectClause);

        final ColumnFamily<String, String> CF_INSTANCES_NEW = ColumnFamily.newColumnFamily(KS_NAME,
                StringSerializer.get(), StringSerializer.get());

        OperationResult<CqlResult<String, String>> result = bootKeyspace.prepareQuery(CF_INSTANCES_NEW)
                .withCql(selectClause).execute();

        if (result == null || result.getResult().getRows().size() == 0) {
            return null;
        }

        Row<String, String> row = result.getResult().getRows().getRowByIndex(0);
        return row.getKey();

    }
    catch (Exception e) {
        logger.warn("Caught an Unknown Exception during find a row matching cluster[" + cluster +
                "], id[" + instanceId + "], and region[" + dc + "]  ... -> "
                + e.getMessage());
        throw new RuntimeException(e);
    }
}
 
Example #14
Source File: InstanceDataDAOCassandra.java    From Raigad with Apache License 2.0 5 votes vote down vote up
private void getLock(RaigadInstance instance) throws Exception {
    String choosingkey = getChoosingKey(instance);
    MutationBatch m = bootKeyspace.prepareMutationBatch();
    ColumnListMutation<String> clm = m.withRow(CF_LOCKS, choosingkey);

    // Expire in 6 sec
    clm.putColumn(instance.getInstanceId(), instance.getInstanceId(), new Integer(6));
    m.execute();
    int count = bootKeyspace.prepareQuery(CF_LOCKS).getKey(choosingkey).getCount().execute().getResult();
    if (count > 1) {
        // Need to delete my entry
        m.withRow(CF_LOCKS, choosingkey).deleteColumn(instance.getInstanceId());
        m.execute();
        throw new Exception(String.format("More than 1 contender for lock %s %d", choosingkey, count));
    }

    String lockKey = getLockingKey(instance);
    OperationResult<ColumnList<String>> result = bootKeyspace.prepareQuery(CF_LOCKS).getKey(lockKey).execute();
    if (result.getResult().size() > 0 && !result.getResult().getColumnByIndex(0).getName().equals(instance.getInstanceId())) {
        throw new Exception(String.format("Lock already taken %s", lockKey));
    }

    clm = m.withRow(CF_LOCKS, lockKey);
    clm.putColumn(instance.getInstanceId(), instance.getInstanceId(), new Integer(600));
    m.execute();
    Thread.sleep(100);
    result = bootKeyspace.prepareQuery(CF_LOCKS).getKey(lockKey).execute();
    if (result.getResult().size() == 1 && result.getResult().getColumnByIndex(0).getName().equals(instance.getInstanceId())) {
        logger.info("Got lock " + lockKey);
        return;
    }
    else {
        throw new Exception(String.format("Cannot insert lock %s", lockKey));
    }
}
 
Example #15
Source File: AstyanaxSupport.java    From brooklyn-library with Apache License 2.0 5 votes vote down vote up
/**
 * Read from a {@link CassandraNode} using the Astyanax API.
 * @throws ConnectionException 
 */
public void readData(String keyspaceName) throws ConnectionException {
    // Create context
    AstyanaxContext<Keyspace> context = newAstyanaxContextForKeyspace(keyspaceName);
    try {
        Keyspace keyspace = context.getEntity();

        // Query data
        OperationResult<ColumnList<String>> query = keyspace.prepareQuery(sampleColumnFamily)
                .getKey("one")
                .execute();
        assertEquals(query.getHost().getHostName(), hostname);
        assertTrue(query.getLatency() > 0L);

        ColumnList<String> columns = query.getResult();
        assertEquals(columns.size(), 2);

        // Lookup columns in response by name
        String name = columns.getColumnByName("name").getStringValue();
        assertEquals(name, "Alice");

        // Iterate through the columns
        for (Column<String> c : columns) {
            assertTrue(ImmutableList.of("name", "company").contains(c.getName()));
        }
    } finally {
        context.shutdown();
    }
}
 
Example #16
Source File: TestCassandraHealthCheck.java    From emodb with Apache License 2.0 5 votes vote down vote up
private OperationResult createPositiveOperationResult(String hostName) {
    OperationResult operationResult = mock(OperationResult.class);
    com.netflix.astyanax.connectionpool.Host host = mock(com.netflix.astyanax.connectionpool.Host.class);
    when(host.toString()).thenReturn(hostName);
    when(operationResult.getHost()).thenReturn(host);
    when(operationResult.getAttemptsCount()).thenReturn(1);
    return operationResult;
}
 
Example #17
Source File: TestCassandraHealthCheck.java    From emodb with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testHealthCheckCaching() throws Exception {
    // Perform one positive health check to get it cached.
    OperationResult operationResult = createPositiveOperationResult("host1");
    ResultSet resultSet = createPositiveResultSet("host1");
    when(_astyanaxStatement.execute()).thenReturn(operationResult);
    when(_cqlSession.execute(_queryString)).thenReturn(resultSet);

    long now = 1478789200000L;
    when(_clock.millis()).thenReturn(now);

    HealthCheck.Result result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    assertTrue(result.getMessage().contains("host1"));

    // Change the health checks to return a different host
    operationResult = createPositiveOperationResult("host2");
    resultSet = createPositiveResultSet("host2");
    when(_astyanaxStatement.execute()).thenReturn(operationResult);
    when(_cqlSession.execute(_queryString)).thenReturn(resultSet);

    // Move time forward 4.9 seconds to ensure the cached result is still returned
    when(_clock.millis()).thenReturn(now = now + 4900L);
    result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    // Since the cached value should have been returned the old hosts should still be included in the message
    assertTrue(result.getMessage().contains("host1"));
    assertFalse(result.getMessage().contains("host2"));

    // Move time forward another 0.1 seconds for a total of 5.
    when(_clock.millis()).thenReturn(now + 100L);
    // Now the health check should perform the ping queries again
    result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    assertTrue(result.getMessage().contains("host2"));
    assertFalse(result.getMessage().contains("host1"));
}
 
Example #18
Source File: PinnedConnectionPool.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Override
public <R> OperationResult<R> executeWithFailover(Operation<T, R> operation, RetryPolicy retryPolicy)
        throws ConnectionException, OperationException {
    Operation<T, R> pinnedOperation = new AbstractOperationFilter<T, R>(operation) {
        @Override
        public Host getPinnedHost() {
            return _host;
        }
    };

    return _delegate.executeWithFailover(pinnedOperation, retryPolicy);
}
 
Example #19
Source File: AstyanaxBlockedDataReaderDAO.java    From emodb with Apache License 2.0 5 votes vote down vote up
private <R> R execute(Execution<R> execution, String operation, Object... operationArguments) {
    OperationResult<R> operationResult;
    try {
        operationResult = execution.execute();
    } catch (ConnectionException e) {
        for (int i = 0; i < operationArguments.length; i++) {
            if (operationArguments[i] instanceof ByteBuffer) {
                operationArguments[i] = ByteBufferUtil.bytesToHex((ByteBuffer) operationArguments[i]);
            }
        }
        String message = "Failed to " + String.format(operation, operationArguments);
        throw new RuntimeException(message, e);
    }
    return operationResult.getResult();
}
 
Example #20
Source File: AstyanaxDataWriterDAO.java    From emodb with Apache License 2.0 5 votes vote down vote up
private <R> R execute(Execution<R> execution, String operation, Object... operationArguments) {
    OperationResult<R> operationResult;
    try {
        operationResult = execution.execute();
    } catch (ConnectionException e) {
        String message = String.format(operation, operationArguments);
        if (isThriftFramedTransportSizeOverrun(execution, e)) {
            throw new ThriftFramedTransportSizeException("Thrift request to large to " + message, e);
        }
        throw new RuntimeException("Failed to " + message, e);
    }
    return operationResult.getResult();
}
 
Example #21
Source File: AstyanaxEventReaderDAO.java    From emodb with Apache License 2.0 5 votes vote down vote up
private <R> R execute(Execution<R> execution) {
    OperationResult<R> operationResult;
    try {
        operationResult = execution.execute();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
    return operationResult.getResult();
}
 
Example #22
Source File: BatchUpdate.java    From emodb with Apache License 2.0 5 votes vote down vote up
private <R> Future<OperationResult<R>> executeAsync(Execution<R> execution) {
    try {
        return execution.executeAsync();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
}
 
Example #23
Source File: BatchUpdate.java    From emodb with Apache License 2.0 5 votes vote down vote up
public void finish() {
    _open = false;
    flushIf(true);
    // Wait for writes to complete and check that they all succeeded
    for (Future<OperationResult<Void>> future : _futures) {
        Futures.getUnchecked(future);
    }
}
 
Example #24
Source File: AstyanaxManifestPersister.java    From emodb with Apache License 2.0 5 votes vote down vote up
private <R> R execute(Execution<R> execution) {
    OperationResult<R> operationResult;
    try {
        operationResult = execution.execute();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
    return operationResult.getResult();
}
 
Example #25
Source File: AstyanaxQueueDAO.java    From emodb with Apache License 2.0 5 votes vote down vote up
private <R> R execute(Execution<R> execution) {
    OperationResult<R> operationResult;
    try {
        operationResult = execution.execute();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
    return operationResult.getResult();
}
 
Example #26
Source File: AstyanaxStorageProvider.java    From emodb with Apache License 2.0 5 votes vote down vote up
private static <R> R execute(Execution<R> execution) {
    OperationResult<R> operationResult;
    try {
        operationResult = execution.execute();
    } catch (ConnectionException e) {
        throw Throwables.propagate(e);
    }
    return operationResult.getResult();
}
 
Example #27
Source File: TestCassandraHealthCheck.java    From emodb with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "unchecked"})
@Test(timeOut = 15000L)
public void testConcurrentHealthChecks() throws Exception {
    // Perform one positive health check to get it cached.
    OperationResult operationResult = createPositiveOperationResult("host1");
    ResultSet resultSet = createPositiveResultSet("host1");
    when(_astyanaxStatement.execute()).thenReturn(operationResult);
    when(_cqlSession.execute(_queryString)).thenReturn(resultSet);

    long now = 1478789200000L;
    when(_clock.millis()).thenReturn(now);

    HealthCheck.Result result = _healthCheck.execute();
    assertTrue(result.isHealthy());
    assertTrue(result.getMessage().contains("host1"));

    // Change the CQL health check to block for a controlled amount of time

    final CountDownLatch cqlBlocked = new CountDownLatch(1);
    final CountDownLatch raiseConnectionException = new CountDownLatch(1);

    when(_cqlSession.execute(_queryString)).thenAnswer(new Answer<ResultSet>() {
        @Override
        public ResultSet answer(InvocationOnMock invocationOnMock) throws Throwable {
            // Let the main thread know we are blocked
            cqlBlocked.countDown();
            // Wait for the main thread to give the signal to raise the connection exception
            raiseConnectionException.await();
            // Raise the exception
            throw new OperationException("simulated cassandra exception");
        }
    });

    // Move time forward 5 seconds to ensure the cached value isn't being returned.
    when(_clock.millis()).thenReturn(now = now + TimeUnit.SECONDS.toMillis(5));

    ExecutorService service = Executors.newFixedThreadPool(1);
    try {
        // In a new thread perform a health check
        Future<HealthCheck.Result> blockedThreadResult = service.submit(() -> _healthCheck.execute());
        // Wait for the thread's CQL call to be blocked
        assertTrue(cqlBlocked.await(5, TimeUnit.SECONDS), "Thread taking too long to make CQL call");

        // Make a call to the health check.  It should return immediately with the old healthy value
        result = _healthCheck.execute();
        assertTrue(result.isHealthy());
        assertTrue(result.getMessage().contains("host1"));

        // Move time forward 29 seconds and check again
        when(_clock.millis()).thenReturn(now = now + TimeUnit.SECONDS.toMillis(29));
        result = _healthCheck.execute();
        assertTrue(result.isHealthy());
        assertTrue(result.getMessage().contains("host1"));

        // Now move time forward one more second for a total of 30.   At this point this health check should return
        // unhealthy because the other health check is taking too long.
        when(_clock.millis()).thenReturn(now + TimeUnit.SECONDS.toMillis(1));
        Stopwatch stopWatch = Stopwatch.createStarted();
        result = _healthCheck.execute();
        stopWatch.stop();
        // Health check shouldn't have taken long
        assertTrue(stopWatch.elapsed(TimeUnit.SECONDS) < 1, "Heath check should not have been blocked");
        assertFalse(result.isHealthy());
        assertEquals(result.getMessage(), "Asynchronous health check update is taking too long");

        // Unblock the thread's health check and let it finish
        raiseConnectionException.countDown();

        result = blockedThreadResult.get(2, TimeUnit.SECONDS);
        assertFalse(result.isHealthy());
        assertTrue(result.getError() instanceof OperationException);

    } catch (Exception e) {
        // Always ensure the thread completes
        raiseConnectionException.countDown();
        service.shutdownNow();
    }
}
 
Example #28
Source File: InstanceDataDAOCassandra.java    From Raigad with Apache License 2.0 4 votes vote down vote up
public List<RaigadInstance> getAllInstances(String cluster) {
    List<RaigadInstance> list = new ArrayList<RaigadInstance>();

    try {
        String selectClause;

        if (config.isMultiDC() || config.amISourceClusterForTribeNodeInMultiDC()) {
            selectClause = String.format("SELECT * FROM %s WHERE %s = '%s' ",
                    CF_NAME_INSTANCES, CN_CLUSTER, cluster);
        }
        else {
            selectClause = String.format("SELECT * FROM %s WHERE %s = '%s' AND %s = '%s' ",
                    CF_NAME_INSTANCES, CN_CLUSTER, cluster, CN_LOCATION, config.getDC());
        }

        if (config.isDebugEnabled()) {
            logger.debug("Getting nodes for {}: {}", cluster, selectClause);
        }

        final ColumnFamily<String, String> CF_INSTANCES_NEW = ColumnFamily.newColumnFamily(
                KS_NAME, StringSerializer.get(), StringSerializer.get());

        OperationResult<CqlResult<String, String>> result =
                bootKeyspace.prepareQuery(CF_INSTANCES_NEW).withCql(selectClause).execute();

        for (Row<String, String> row : result.getResult().getRows()) {
            list.add(transform(row.getColumns()));
        }
    }
    catch (Exception e) {
        logger.warn("Caught unknown exception while reading: {}", e.getMessage());
        throw new RuntimeException(e);
    }

    if (config.isDebugEnabled()) {
        for (RaigadInstance instance : list) {
            logger.debug("Read instance: {}", instance.toString());
        }
    }

    return list;
}
 
Example #29
Source File: CassandraHealthCheck.java    From emodb with Apache License 2.0 4 votes vote down vote up
private OperationResult<CqlStatementResult> pingAstyanax() throws Exception {
    return _keyspace.getAstyanaxKeyspace().prepareCqlStatement()
            .withCql(_healthCheckCql)
            .withConsistencyLevel(CL_ONE)
            .execute();
}
 
Example #30
Source File: CassandraSubject.java    From mutagen-cassandra with Apache License 2.0 4 votes vote down vote up
/**
 *
 *
 */
private void createSchemaVersionTable()
		throws ConnectionException {
	OperationResult<SchemaChangeResult> result=
		getKeyspace().createColumnFamily(VERSION_CF,null);
}