org.apache.cassandra.utils.FBUtilities Java Examples

The following examples show how to use org.apache.cassandra.utils.FBUtilities. 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: MigrationManager.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
/**
 * actively announce a new version to active hosts via rpc
 * @param schema The schema mutation to be applied
 */
private static void announce(Mutation schema, boolean announceLocally)
{
    if (announceLocally)
    {
        try
        {
            DefsTables.mergeSchemaInternal(Collections.singletonList(schema), false);
        }
        catch (ConfigurationException | IOException e)
        {
            throw new RuntimeException(e);
        }
    }
    else
    {
        FBUtilities.waitOnFuture(announce(Collections.singletonList(schema)));
    }
}
 
Example #2
Source File: ColumnFamilyRecordReader.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private String getLocation()
{
    Collection<InetAddress> localAddresses = FBUtilities.getAllLocalAddresses();

    for (InetAddress address : localAddresses)
    {
        for (String location : split.getLocations())
        {
            InetAddress locationAddress = null;
            try
            {
                locationAddress = InetAddress.getByName(location);
            }
            catch (UnknownHostException e)
            {
                throw new AssertionError(e);
            }
            if (address.equals(locationAddress))
            {
                return location;
            }
        }
    }
    return split.getLocations()[0];
}
 
Example #3
Source File: BulkLoadConnectionFactory.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public Socket createConnection(InetAddress peer) throws IOException
{
    // Connect to secure port for all peers if ServerEncryptionOptions is configured other than 'none'
    // When 'all', 'dc' and 'rack', server nodes always have SSL port open, and since thin client like sstableloader
    // does not know which node is in which dc/rack, connecting to SSL port is always the option.
    if (encryptionOptions != null && encryptionOptions.internode_encryption != EncryptionOptions.ServerEncryptionOptions.InternodeEncryption.none)
    {
        if (outboundBindAny)
            return SSLFactory.getSocket(encryptionOptions, peer, secureStoragePort);
        else
            return SSLFactory.getSocket(encryptionOptions, peer, secureStoragePort, FBUtilities.getLocalAddress(), 0);
    }
    else
    {
        Socket socket = SocketChannel.open(new InetSocketAddress(peer, storagePort)).socket();
        if (outboundBindAny && !socket.isBound())
            socket.bind(new InetSocketAddress(FBUtilities.getLocalAddress(), 0));
        return socket;
    }
}
 
Example #4
Source File: LongCompactionsTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private void forceCompactions(ColumnFamilyStore cfs) throws ExecutionException, InterruptedException
{
    // re-enable compaction with thresholds low enough to force a few rounds
    cfs.setCompactionThresholds(2, 4);

    // loop submitting parallel compactions until they all return 0
    do
    {
        ArrayList<Future<?>> compactions = new ArrayList<Future<?>>();
        for (int i = 0; i < 10; i++)
            compactions.addAll(CompactionManager.instance.submitBackground(cfs));
        // another compaction attempt will be launched in the background by
        // each completing compaction: not much we can do to control them here
        FBUtilities.waitOnFutures(compactions);
    } while (CompactionManager.instance.getPendingTasks() > 0 || CompactionManager.instance.getActiveCompactions() > 0);

    if (cfs.getSSTables().size() > 1)
    {
        CompactionManager.instance.performMaximal(cfs);
    }
}
 
Example #5
Source File: NodeTool.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private static void printHistory(String... args)
{
    //don't bother to print if no args passed (meaning, nodetool is just printing out the sub-commands list)
    if (args.length == 0)
        return;

    String cmdLine = Joiner.on(" ").skipNulls().join(args);
    cmdLine = cmdLine.replaceFirst("(?<=(-pw|--password))\\s+\\S+", " <hidden>");

    try (FileWriter writer = new FileWriter(new File(FBUtilities.getToolsOutputDirectory(), HISTORYFILE), true))
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS");
        writer.append(sdf.format(new Date())).append(": ").append(cmdLine).append(System.lineSeparator());
    }
    catch (IOException | IOError ioe)
    {
        //quietly ignore any errors about not being able to write out history
    }
}
 
Example #6
Source File: SerializationsTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private void testValidationCompleteWrite() throws IOException
{
    IPartitioner p = new RandomPartitioner();
    // empty validation
    MerkleTree mt = new MerkleTree(p, FULL_RANGE, MerkleTree.RECOMMENDED_DEPTH, (int) Math.pow(2, 15));
    Validator v0 = new Validator(DESC, FBUtilities.getBroadcastAddress(),  -1);
    ValidationComplete c0 = new ValidationComplete(DESC, mt);

    // validation with a tree
    mt = new MerkleTree(p, FULL_RANGE, MerkleTree.RECOMMENDED_DEPTH, Integer.MAX_VALUE);
    for (int i = 0; i < 10; i++)
        mt.split(p.getRandomToken());
    Validator v1 = new Validator(DESC, FBUtilities.getBroadcastAddress(), -1);
    ValidationComplete c1 = new ValidationComplete(DESC, mt);

    // validation failed
    ValidationComplete c3 = new ValidationComplete(DESC);

    testRepairMessageWrite("service.ValidationComplete.bin", c0, c1, c3);
}
 
Example #7
Source File: YamlFileNetworkTopologySnitchTest.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
/**
 * A basic test case.
 * 
 * @throws Exception
 *             on failure
 */
@Test
public void testBasic() throws Exception
{
    final TestYamlFileNetworkTopologySnitch snitch = new TestYamlFileNetworkTopologySnitch(
            "cassandra-topology.yaml");
    checkEndpoint(snitch, FBUtilities.getBroadcastAddress()
            .getHostAddress(), "DC1", "RAC1");
    checkEndpoint(snitch, "192.168.1.100", "DC1", "RAC1");
    checkEndpoint(snitch, "10.0.0.12", "DC1", "RAC2");
    checkEndpoint(snitch, "127.0.0.3", "DC1", "RAC3");
    checkEndpoint(snitch, "10.20.114.10", "DC2", "RAC1");
    checkEndpoint(snitch, "127.0.0.8", "DC3", "RAC8");
    checkEndpoint(snitch, "6.6.6.6", "DC1", "r1");

}
 
Example #8
Source File: MultiCloudSnitch.java    From brooklyn-library with Apache License 2.0 6 votes vote down vote up
public MultiCloudSnitch() throws ConfigurationException
{
    reloadConfiguration();
    logger.info("CustomSnitch using datacenter: " + datacenter + ", rack: " + rack + ", publicip: " + public_ip + ", privateip: " + private_ip);

    try
    {
        FBUtilities.resourceToFile(SNITCH_PROPERTIES_FILENAME);
        Runnable runnable = new WrappedRunnable()
        {
            protected void runMayThrow() throws ConfigurationException
            {
                reloadConfiguration();
            }
        };
        ResourceWatcher.watch(SNITCH_PROPERTIES_FILENAME, runnable, 60 * 1000);
    }
    catch (ConfigurationException ex)
    {
        logger.debug(SNITCH_PROPERTIES_FILENAME + " found, but does not look like a plain file. Will not watch it for changes");
    }
}
 
Example #9
Source File: 986499_AddColumnFamily_0_t.java    From coming with MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example #10
Source File: Differencer.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
/**
 * Compares our trees, and triggers repairs for any ranges that mismatch.
 */
public void run()
{
    // compare trees, and collect differences
    differences.addAll(MerkleTree.difference(r1.tree, r2.tree));

    // choose a repair method based on the significance of the difference
    String format = String.format("[repair #%s] Endpoints %s and %s %%s for %s", desc.sessionId, r1.endpoint, r2.endpoint, desc.columnFamily);
    if (differences.isEmpty())
    {
        logger.info(String.format(format, "are consistent"));
        // send back sync complete message
        MessagingService.instance().sendOneWay(new SyncComplete(desc, r1.endpoint, r2.endpoint, true).createMessage(), FBUtilities.getLocalAddress());
        return;
    }

    // non-0 difference: perform streaming repair
    logger.info(String.format(format, "have " + differences.size() + " range(s) out of sync"));
    performStreamingRepair();
}
 
Example #11
Source File: 986499_AddColumnFamily_0_t.java    From coming with MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example #12
Source File: OutboundTcpConnectionPool.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public static Socket newSocket(InetAddress endpoint) throws IOException
{
    // zero means 'bind on any available port.'
    if (isEncryptedChannel(endpoint))
    {
        if (Config.getOutboundBindAny())
            return SSLFactory.getSocket(DatabaseDescriptor.getServerEncryptionOptions(), endpoint, DatabaseDescriptor.getSSLStoragePort());
        else
            return SSLFactory.getSocket(DatabaseDescriptor.getServerEncryptionOptions(), endpoint, DatabaseDescriptor.getSSLStoragePort(), FBUtilities.getLocalAddress(), 0);
    }
    else
    {
        Socket socket = SocketChannel.open(new InetSocketAddress(endpoint, DatabaseDescriptor.getStoragePort())).socket();
        if (Config.getOutboundBindAny() && !socket.isBound())
            socket.bind(new InetSocketAddress(FBUtilities.getLocalAddress(), 0));
        return socket;
    }
}
 
Example #13
Source File: Gossiper.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
/**
 * Start the gossiper with the generation number, preloading the map of application states before starting
 */
public void start(int generationNbr, Map<ApplicationState, VersionedValue> preloadLocalStates)
{
    buildSeedsList();
    /* initialize the heartbeat state for this localEndpoint */
    maybeInitializeLocalState(generationNbr);
    EndpointState localState = endpointStateMap.get(FBUtilities.getBroadcastAddress());
    for (Map.Entry<ApplicationState, VersionedValue> entry : preloadLocalStates.entrySet())
        localState.addApplicationState(entry.getKey(), entry.getValue());

    //notify snitches that Gossiper is about to start
    DatabaseDescriptor.getEndpointSnitch().gossiperStarting();
    if (logger.isTraceEnabled())
        logger.trace("gossip started with generation " + localState.getHeartBeatState().getGeneration());

    scheduledGossipTask = executor.scheduleWithFixedDelay(new GossipTask(),
                                                          Gossiper.intervalInMillis,
                                                          Gossiper.intervalInMillis,
                                                          TimeUnit.MILLISECONDS);
}
 
Example #14
Source File: CompactionHistoryTabularData.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public static TabularData from(UntypedResultSet resultSet) throws OpenDataException
{
    TabularDataSupport result = new TabularDataSupport(TABULAR_TYPE);
    for (UntypedResultSet.Row row : resultSet)
    {
        UUID id = row.getUUID(ITEM_NAMES[0]);
        String ksName = row.getString(ITEM_NAMES[1]);
        String cfName = row.getString(ITEM_NAMES[2]);
        long compactedAt = row.getLong(ITEM_NAMES[3]);
        long bytesIn = row.getLong(ITEM_NAMES[4]);
        long bytesOut = row.getLong(ITEM_NAMES[5]);
        Map<Integer, Long> rowMerged = row.getMap(ITEM_NAMES[6], Int32Type.instance, LongType.instance);

        result.put(new CompositeDataSupport(COMPOSITE_TYPE, ITEM_NAMES,
                   new Object[]{ id.toString(), ksName, cfName, compactedAt, bytesIn, bytesOut,
                                 "{" + FBUtilities.toString(rowMerged) + "}" }));
    }
    return result;
}
 
Example #15
Source File: AntiEntropyServiceTestAbstract.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetNeighborsTimesTwo() throws Throwable
{
    TokenMetadata tmd = StorageService.instance.getTokenMetadata();

    // generate rf*2 nodes, and ensure that only neighbors specified by the ARS are returned
    addTokens(2 * Keyspace.open(keyspaceName).getReplicationStrategy().getReplicationFactor());
    AbstractReplicationStrategy ars = Keyspace.open(keyspaceName).getReplicationStrategy();
    Set<InetAddress> expected = new HashSet<InetAddress>();
    for (Range<Token> replicaRange : ars.getAddressRanges().get(FBUtilities.getBroadcastAddress()))
    {
        expected.addAll(ars.getRangeAddresses(tmd.cloneOnlyTokenMap()).get(replicaRange));
    }
    expected.remove(FBUtilities.getBroadcastAddress());
    Collection<Range<Token>> ranges = StorageService.instance.getLocalRanges(keyspaceName);
    Set<InetAddress> neighbors = new HashSet<InetAddress>();
    for (Range<Token> range : ranges)
    {
        neighbors.addAll(ActiveRepairService.getNeighbors(keyspaceName, range, null, null));
    }
    assertEquals(expected, neighbors);
}
 
Example #16
Source File: MigrationManager.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private static Future<?> announce(final Collection<Mutation> schema)
{
    Future<?> f = StageManager.getStage(Stage.MIGRATION).submit(new WrappedRunnable()
    {
        protected void runMayThrow() throws IOException, ConfigurationException
        {
            DefsTables.mergeSchema(schema);
        }
    });

    for (InetAddress endpoint : Gossiper.instance.getLiveMembers())
    {
        // only push schema to nodes with known and equal versions
        if (!endpoint.equals(FBUtilities.getBroadcastAddress()) &&
                MessagingService.instance().knowsVersion(endpoint) &&
                MessagingService.instance().getRawVersion(endpoint) == MessagingService.current_version)
            pushSchemaMutation(endpoint, schema);
    }

    return f;
}
 
Example #17
Source File: Gossiper.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public void stop()
{
    EndpointState mystate = endpointStateMap.get(FBUtilities.getBroadcastAddress());
    if (mystate != null && !isSilentShutdownState(mystate))
    {
        logger.info("Announcing shutdown");
        addLocalApplicationState(ApplicationState.STATUS, StorageService.instance.valueFactory.shutdown(true));
        MessageOut message = new MessageOut(MessagingService.Verb.GOSSIP_SHUTDOWN);
        for (InetAddress ep : liveEndpoints)
            MessagingService.instance().sendOneWay(message, ep);
        Uninterruptibles.sleepUninterruptibly(Integer.getInteger("cassandra.shutdown_announce_in_ms", 2000), TimeUnit.MILLISECONDS);
    }
    else
        logger.warn("No local state or state is in silent shutdown, not announcing shutdown");
    if (scheduledGossipTask != null)
        scheduledGossipTask.cancel(false);
}
 
Example #18
Source File: 986499_AddColumnFamily_0_s.java    From coming with MIT License 6 votes vote down vote up
public AddColumnFamily(CFMetaData cfm) throws ConfigurationException, IOException
{
    super(UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()), DatabaseDescriptor.getDefsVersion());
    this.cfm = cfm;
    KSMetaData ksm = DatabaseDescriptor.getTableDefinition(cfm.tableName);
    
    if (ksm == null)
        throw new ConfigurationException("Keyspace does not already exist.");
    else if (ksm.cfMetaData().containsKey(cfm.cfName))
        throw new ConfigurationException("CF is already defined in that keyspace.");
    else if (!Migration.isLegalName(cfm.cfName))
        throw new ConfigurationException("Invalid column family name: " + cfm.cfName);
    
    KSMetaData newKsm = makeNewKeyspaceDefinition(ksm);
    
    rm = Migration.makeDefinitionMutation(newKsm, null, newVersion);
}
 
Example #19
Source File: StorageService.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
private void bootstrap(Collection<Token> tokens)
{
    isBootstrapMode = true;
    SystemKeyspace.updateTokens(tokens); // DON'T use setToken, that makes us part of the ring locally which is incorrect until we are done bootstrapping
    if (!DatabaseDescriptor.isReplacing())
    {
        // if not an existing token then bootstrap
        List<Pair<ApplicationState, VersionedValue>> states = new ArrayList<Pair<ApplicationState, VersionedValue>>();
        states.add(Pair.create(ApplicationState.TOKENS, valueFactory.tokens(tokens)));
        states.add(Pair.create(ApplicationState.STATUS, valueFactory.bootstrapping(tokens)));
        Gossiper.instance.addLocalApplicationStates(states);
        setMode(Mode.JOINING, "sleeping " + RING_DELAY + " ms for pending range setup", true);
        Uninterruptibles.sleepUninterruptibly(RING_DELAY, TimeUnit.MILLISECONDS);
    }
    else
    {
        // Dont set any state for the node which is bootstrapping the existing token...
        tokenMetadata.updateNormalTokens(tokens, FBUtilities.getBroadcastAddress());
        SystemKeyspace.removeEndpoint(DatabaseDescriptor.getReplaceAddress());
    }
    if (!Gossiper.instance.seenAnySeed())
        throw new IllegalStateException("Unable to contact any seeds!");
    setMode(Mode.JOINING, "Starting to bootstrap...", true);
    new BootStrapper(FBUtilities.getBroadcastAddress(), tokens, tokenMetadata).bootstrap(); // handles token update
    logger.info("Bootstrap completed! for the tokens {}", tokens);
}
 
Example #20
Source File: StorageService.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public int forceRepairAsync(String keyspace, RepairParallelism parallelismDegree, Collection<String> dataCenters, Collection<String> hosts, Collection<Range<Token>> ranges, boolean fullRepair, String... columnFamilies)
{
    if (ranges.isEmpty() || Keyspace.open(keyspace).getReplicationStrategy().getReplicationFactor() < 2)
        return 0;

    int cmd = nextRepairCommand.incrementAndGet();
    if (ranges.size() > 0)
    {
        if (FBUtilities.isWindows() && parallelismDegree != RepairParallelism.PARALLEL)
        {
            logger.warn("Snapshot-based repair is not yet supported on Windows.  Reverting to parallel repair.");
            parallelismDegree = RepairParallelism.PARALLEL;
        }
        new Thread(createRepairTask(cmd, keyspace, ranges, parallelismDegree, dataCenters, hosts, fullRepair, columnFamilies)).start();
    }
    return cmd;
}
 
Example #21
Source File: SSTableWriter.java    From stratio-cassandra with Apache License 2.0 6 votes vote down vote up
public void append(DecoratedKey decoratedKey, ColumnFamily cf)
{
    if (decoratedKey.getKey().remaining() > FBUtilities.MAX_UNSIGNED_SHORT)
    {
        logger.error("Key size {} exceeds maximum of {}, skipping row",
                     decoratedKey.getKey().remaining(),
                     FBUtilities.MAX_UNSIGNED_SHORT);
        return;
    }

    long startPosition = beforeAppend(decoratedKey);
    long endPosition;
    try
    {
        RowIndexEntry entry = rawAppend(cf, startPosition, decoratedKey, dataFile.stream);
        endPosition = dataFile.getFilePointer();
        afterAppend(decoratedKey, endPosition, entry);
    }
    catch (IOException e)
    {
        throw new FSWriteError(e, dataFile.getPath());
    }
    sstableMetadataCollector.update(endPosition - startPosition, cf.getColumnStats());
}
 
Example #22
Source File: CassandraUtils.java    From sstable-tools with Apache License 2.0 6 votes vote down vote up
public static Cluster loadTablesFromRemote(String host, int port, String cfidOverrides) throws IOException {
    Map<String, UUID> cfs = parseOverrides(cfidOverrides);
    Cluster.Builder builder = Cluster.builder().addContactPoints(host).withPort(port);
    Cluster cluster = builder.build();
    Metadata metadata = cluster.getMetadata();
    IPartitioner partitioner = FBUtilities.newPartitioner(metadata.getPartitioner());
    if (DatabaseDescriptor.getPartitioner() == null)
        DatabaseDescriptor.setPartitionerUnsafe(partitioner);
    for (com.datastax.driver.core.KeyspaceMetadata ksm : metadata.getKeyspaces()) {
        if (!ksm.getName().equals("system")) {
            for (TableMetadata tm : ksm.getTables()) {
                String name = ksm.getName()+"."+tm.getName();
                try {
                    CassandraUtils.tableFromCQL(
                            new ByteArrayInputStream(tm.asCQLQuery().getBytes()),
                            cfs.get(name) != null ? cfs.get(name) : tm.getId());
                } catch(SyntaxException e) {
                    // ignore tables that we cant parse (probably dse)
                    logger.debug("Ignoring table " + name + " due to syntax exception " + e.getMessage());
                }
            }
        }
    }
    return cluster;
}
 
Example #23
Source File: StorageService.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
/**
 * #{@inheritDoc}
 */
public List<String> sampleKeyRange() // do not rename to getter - see CASSANDRA-4452 for details
{
    List<DecoratedKey> keys = new ArrayList<>();
    for (Keyspace keyspace : Keyspace.nonSystem())
    {
        for (Range<Token> range : getPrimaryRangesForEndpoint(keyspace.getName(), FBUtilities.getBroadcastAddress()))
            keys.addAll(keySamples(keyspace.getColumnFamilyStores(), range));
    }

    List<String> sampledKeys = new ArrayList<>(keys.size());
    for (DecoratedKey key : keys)
        sampledKeys.add(key.getToken().toString());
    return sampledKeys;
}
 
Example #24
Source File: StorageService.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
private List<DecoratedKey> keySamples(Iterable<ColumnFamilyStore> cfses, Range<Token> range)
{
    List<DecoratedKey> keys = new ArrayList<>();
    for (ColumnFamilyStore cfs : cfses)
        Iterables.addAll(keys, cfs.keySamples(range));
    FBUtilities.sortSampledKeys(keys, range);
    return keys;
}
 
Example #25
Source File: GoogleCloudSnitch.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public String getRack(InetAddress endpoint)
{
    if (endpoint.equals(FBUtilities.getBroadcastAddress()))
        return gceZone;
    EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
    if (state == null || state.getApplicationState(ApplicationState.RACK) == null)
    {
        if (savedEndpoints == null)
            savedEndpoints = SystemKeyspace.loadDcRackInfo();
        if (savedEndpoints.containsKey(endpoint))
            return savedEndpoints.get(endpoint).get("rack");
        return DEFAULT_RACK;
    }
    return state.getApplicationState(ApplicationState.RACK).value;
}
 
Example #26
Source File: NativeCounterCell.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@Override
public void updateDigest(MessageDigest digest)
{
    updateWithName(digest);

    // We don't take the deltas into account in a digest
    contextManager.updateDigest(digest, value());

    FBUtilities.updateWithLong(digest, timestamp());
    FBUtilities.updateWithByte(digest, serializationFlags());
    FBUtilities.updateWithLong(digest, timestampOfLastDelete());
}
 
Example #27
Source File: CloudstackSnitch.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public String getDatacenter(InetAddress endpoint)
{
    if (endpoint.equals(FBUtilities.getBroadcastAddress()))
        return csZoneDc;
    EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
    if (state == null || state.getApplicationState(ApplicationState.DC) == null) 
    {
        if (savedEndpoints == null)
            savedEndpoints = SystemKeyspace.loadDcRackInfo();
        if (savedEndpoints.containsKey(endpoint))
            return savedEndpoints.get(endpoint).get("data_center");
        return DEFAULT_DC;
    }
    return state.getApplicationState(ApplicationState.DC).value;
}
 
Example #28
Source File: CloudstackSnitch.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public String getRack(InetAddress endpoint)
{
    if (endpoint.equals(FBUtilities.getBroadcastAddress()))
        return csZoneRack;
    EndpointState state = Gossiper.instance.getEndpointStateForEndpoint(endpoint);
    if (state == null || state.getApplicationState(ApplicationState.RACK) == null) 
    {
        if (savedEndpoints == null)
            savedEndpoints = SystemKeyspace.loadDcRackInfo();
        if (savedEndpoints.containsKey(endpoint))
            return savedEndpoints.get(endpoint).get("rack");
        return DEFAULT_RACK;
    }
    return state.getApplicationState(ApplicationState.RACK).value;
}
 
Example #29
Source File: DatabaseDescriptor.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static Config loadConfig() throws ConfigurationException
{
    String loaderClass = System.getProperty("cassandra.config.loader");
    ConfigurationLoader loader = loaderClass == null
                               ? new YamlConfigurationLoader()
                               : FBUtilities.<ConfigurationLoader>construct(loaderClass, "configuration loading");
    return loader.loadConfig();
}
 
Example #30
Source File: SerDeserTest.java    From stratio-cassandra with Apache License 2.0 5 votes vote down vote up
public void eventSerDeserTest(int version) throws Exception
{
    List<Event> events = new ArrayList<>();

    events.add(TopologyChange.newNode(FBUtilities.getBroadcastAddress(), 42));
    events.add(TopologyChange.removedNode(FBUtilities.getBroadcastAddress(), 42));
    events.add(TopologyChange.movedNode(FBUtilities.getBroadcastAddress(), 42));

    events.add(StatusChange.nodeUp(FBUtilities.getBroadcastAddress(), 42));
    events.add(StatusChange.nodeDown(FBUtilities.getBroadcastAddress(), 42));

    events.add(new SchemaChange(SchemaChange.Change.CREATED, "ks"));
    events.add(new SchemaChange(SchemaChange.Change.UPDATED, "ks"));
    events.add(new SchemaChange(SchemaChange.Change.DROPPED, "ks"));

    events.add(new SchemaChange(SchemaChange.Change.CREATED, SchemaChange.Target.TABLE, "ks", "table"));
    events.add(new SchemaChange(SchemaChange.Change.UPDATED, SchemaChange.Target.TABLE, "ks", "table"));
    events.add(new SchemaChange(SchemaChange.Change.DROPPED, SchemaChange.Target.TABLE, "ks", "table"));

    if (version >= 3)
    {
        events.add(new SchemaChange(SchemaChange.Change.CREATED, SchemaChange.Target.TYPE, "ks", "type"));
        events.add(new SchemaChange(SchemaChange.Change.UPDATED, SchemaChange.Target.TYPE, "ks", "type"));
        events.add(new SchemaChange(SchemaChange.Change.DROPPED, SchemaChange.Target.TYPE, "ks", "type"));
    }

    for (Event ev : events)
    {
        ByteBuf buf = Unpooled.buffer(ev.serializedSize(version));
        ev.serialize(buf, version);
        assertEquals(ev, Event.deserialize(buf, version));
    }
}