Java Code Examples for org.apache.ignite.configuration.CacheConfiguration#getName()

The following examples show how to use org.apache.ignite.configuration.CacheConfiguration#getName() . 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: CacheJtaManager.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void registerCache(CacheConfiguration<?, ?> cfg) throws IgniteCheckedException {
    String cacheLookupClsName = cfg.getTransactionManagerLookupClassName();

    if (cacheLookupClsName != null) {
        CacheTmLookup tmLookup = tmLookupRef.get();

        if (tmLookup == null) {
            tmLookup = createTmLookup(cacheLookupClsName);

            if (tmLookupRef.compareAndSet(null, tmLookup))
                return;

            tmLookup = tmLookupRef.get();
        }

        if (!cacheLookupClsName.equals(tmLookup.getClass().getName()))
            throw new IgniteCheckedException("Failed to start cache with CacheTmLookup that specified in cache " +
                "configuration, because node uses another CacheTmLookup [cache" + cfg.getName() +
                ", tmLookupClassName=" + cacheLookupClsName + ", tmLookupUsedByNode="
                + tmLookup.getClass().getName() + ']');
    }
}
 
Example 2
Source File: JdbcThinWalModeChangeSelfTest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override protected void createCache(Ignite node, CacheConfiguration ccfg) throws IgniteCheckedException {
    String template = ccfg.getCacheMode() == CacheMode.PARTITIONED ?
        QueryUtils.TEMPLATE_PARTITIONED : QueryUtils.TEMPLATE_REPLICATED;

    String cmd = "CREATE TABLE IF NOT EXISTS " + ccfg.getName() + " (k BIGINT PRIMARY KEY, v BIGINT) WITH \"" +
        "TEMPLATE=" + template + ", " +
        "CACHE_NAME=" + ccfg.getName() + ", " +
        "ATOMICITY=" + ccfg.getAtomicityMode() +
        (ccfg.getGroupName() != null ? ", CACHE_GROUP=" + ccfg.getGroupName() : "") +
        (ccfg.getDataRegionName() != null ? ", DATA_REGION=" + ccfg.getDataRegionName() : "") +
        "\"";

    execute(node, cmd);

    alignCacheTopologyVersion(node);
}
 
Example 3
Source File: GridCacheStoreManagerAdapter.java    From ignite with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
private CacheStore cacheStoreWrapper(GridKernalContext ctx,
    @Nullable CacheStore cfgStore,
    CacheConfiguration cfg) {
    if (cfgStore == null || !cfg.isWriteBehindEnabled())
        return cfgStore;

    GridCacheWriteBehindStore store = new GridCacheWriteBehindStore(this,
        ctx.igniteInstanceName(),
        cfg.getName(),
        ctx.log(GridCacheWriteBehindStore.class),
        cfgStore);

    store.setFlushSize(cfg.getWriteBehindFlushSize());
    store.setFlushThreadCount(cfg.getWriteBehindFlushThreadCount());
    store.setFlushFrequency(cfg.getWriteBehindFlushFrequency());
    store.setBatchSize(cfg.getWriteBehindBatchSize());
    store.setWriteCoalescing(cfg.getWriteBehindCoalescing());

    return store;
}
 
Example 4
Source File: DynamicCacheChangeRequest.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * @param ctx Context.
 * @param cfg0 Template configuration.
 * @param splitCfg Cache configuration splitter.
 * @return Request to add template.
 */
static DynamicCacheChangeRequest addTemplateRequest(
    GridKernalContext ctx,
    CacheConfiguration<?, ?> cfg0,
    T2<CacheConfiguration, CacheConfigurationEnrichment> splitCfg
) {
    DynamicCacheChangeRequest req = new DynamicCacheChangeRequest(UUID.randomUUID(), cfg0.getName(), ctx.localNodeId());

    req.template(true);

    req.startCacheConfiguration(splitCfg.get1());
    req.cacheConfigurationEnrichment(splitCfg.get2());

    req.schema(new QuerySchema(cfg0.getQueryEntities()));
    req.deploymentId(IgniteUuid.randomUuid());

    return req;
}
 
Example 5
Source File: FilePageStoreManager.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void removeCacheData(StoredCacheData cacheData) throws IgniteCheckedException {
    chgLock.readLock().lock();

    try {
        CacheConfiguration<?, ?> ccfg = cacheData.config();
        File file = cacheConfigurationFile(ccfg);

        if (file.exists()) {
            for (BiConsumer<String, File> lsnr : lsnrs)
                lsnr.accept(ccfg.getName(), file);

            if (!file.delete())
                throw new IgniteCheckedException("Failed to delete cache configuration: " + ccfg.getName());
        }
    }
    finally {
        chgLock.readLock().unlock();
    }
}
 
Example 6
Source File: GridCacheSqlDdlClusterReadOnlyModeTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
@Test
public void testAlterTableAllowed() {
    createTables();

    grid(0).cluster().state(ClusterState.ACTIVE_READ_ONLY);

    for (CacheConfiguration cfg : cacheConfigurations()) {
        String cacheName = cfg.getName();

        if (cfg.getAtomicityMode() == CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT) {
            // Drop column doesn't support in MVCC mode.
            continue;
        }

        for (Ignite node : G.allGrids()) {
            String selectSql = "select city from " + tableName(cacheName);

            assertThrows(log, () -> execute(node, selectSql), IgniteSQLException.class, SQL_SELECT_ERROR_MSG);

            execute(node, "alter table " + tableName(cacheName) + " add column city varchar");

            assertNotNull(execute(node, selectSql));

            execute(node, "alter table " + tableName(cacheName) + " drop column city");

            assertThrows(log, () -> execute(node, selectSql), IgniteSQLException.class, SQL_SELECT_ERROR_MSG);
        }
    }
}
 
Example 7
Source File: IgniteKernal.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public <K, V> IgniteBiTuple<IgniteCache<K, V>, Boolean> getOrCreateCache0(
    CacheConfiguration<K, V> cacheCfg, boolean sql) {
    A.notNull(cacheCfg, "cacheCfg");
    String cacheName = cacheCfg.getName();

    CU.validateNewCacheName(cacheName);

    guard();

    try {
        checkClusterState();

        Boolean res = false;

        IgniteCacheProxy<K, V> cache = ctx.cache().publicJCache(cacheName, false, true);

        if (cache == null) {
            res =
                sql ? ctx.cache().dynamicStartSqlCache(cacheCfg).get() :
                    ctx.cache().dynamicStartCache(cacheCfg,
                        cacheName,
                        null,
                        false,
                        true,
                        true).get();

            return new IgniteBiTuple<>(ctx.cache().publicJCache(cacheName), res);
        }
        else
            return new IgniteBiTuple<>(cache, res);
    }
    catch (IgniteCheckedException e) {
        throw CU.convertToCacheException(e);
    }
    finally {
        unguard();
    }
}
 
Example 8
Source File: IgniteKernal.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Acknowledge that the rebalance configuration properties are setted correctly.
 *
 * @throws IgniteCheckedException If rebalance configuration validation fail.
 */
private void ackRebalanceConfiguration() throws IgniteCheckedException {
    if (cfg.isClientMode()) {
        if (cfg.getRebalanceThreadPoolSize() != IgniteConfiguration.DFLT_REBALANCE_THREAD_POOL_SIZE)
            U.warn(log, "Setting the rebalance pool size has no effect on the client mode");
    }
    else {
        if (cfg.getSystemThreadPoolSize() <= cfg.getRebalanceThreadPoolSize())
            throw new IgniteCheckedException("Rebalance thread pool size exceed or equals System thread pool size. " +
                "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start.");

        if (cfg.getRebalanceThreadPoolSize() < 1)
            throw new IgniteCheckedException("Rebalance thread pool size minimal allowed value is 1. " +
                "Change IgniteConfiguration.rebalanceThreadPoolSize property before next start.");

        if (cfg.getRebalanceBatchesPrefetchCount() < 1)
            throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " +
                "Change IgniteConfiguration.rebalanceBatchesPrefetchCount property before next start.");

        if (cfg.getRebalanceBatchSize() <= 0)
            throw new IgniteCheckedException("Rebalance batch size must be greater than zero. " +
                "Change IgniteConfiguration.rebalanceBatchSize property before next start.");

        if (cfg.getRebalanceThrottle() < 0)
            throw new IgniteCheckedException("Rebalance throttle can't have negative value. " +
                "Change IgniteConfiguration.rebalanceThrottle property before next start.");

        if (cfg.getRebalanceTimeout() < 0)
            throw new IgniteCheckedException("Rebalance message timeout can't have negative value. " +
                "Change IgniteConfiguration.rebalanceTimeout property before next start.");

        for (CacheConfiguration ccfg : cfg.getCacheConfiguration()) {
            if (ccfg.getRebalanceBatchesPrefetchCount() < 1)
                throw new IgniteCheckedException("Rebalance batches prefetch count minimal allowed value is 1. " +
                    "Change CacheConfiguration.rebalanceBatchesPrefetchCount property before next start. " +
                    "[cache=" + ccfg.getName() + "]");
        }
    }
}
 
Example 9
Source File: CacheConfigurationEnricher.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Enriches cache configuration fields with deserialized values from given @{code enrichment}.
 *
 * @param ccfg Cache configuration to enrich.
 * @param enrichment Cache configuration enrichment.
 * @param affinityNode {@code true} if enrichment is happened on affinity node.
 *
 * @return Enriched cache configuration.
 */
public CacheConfiguration<?, ?> enrich(
    CacheConfiguration<?, ?> ccfg,
    @Nullable CacheConfigurationEnrichment enrichment,
    boolean affinityNode
) {
    if (enrichment == null)
        return ccfg;

    CacheConfiguration<?, ?> enrichedCp = new CacheConfiguration<>(ccfg);

    try {
        for (Field field : CacheConfiguration.class.getDeclaredFields())
            if (field.getDeclaredAnnotation(SerializeSeparately.class) != null) {
                if (!affinityNode && skipDeserialization(ccfg, field))
                    continue;

                field.setAccessible(true);

                Object enrichedVal = deserialize(
                    field.getName(), enrichment.getFieldSerializedValue(field.getName()));

                field.set(enrichedCp, enrichedVal);
            }
    }
    catch (Exception e) {
        throw new IgniteException("Failed to enrich cache configuration [cacheName=" + ccfg.getName() + "]", e);
    }

    return enrichedCp;
}
 
Example 10
Source File: FilePageStoreManager.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param ccfg Cache configuration.
 * @return Cache configuration file with respect to {@link CacheConfiguration#getGroupName} value.
 */
private File cacheConfigurationFile(CacheConfiguration<?, ?> ccfg) {
    File cacheWorkDir = cacheWorkDir(ccfg);

    return ccfg.getGroupName() == null ? new File(cacheWorkDir, CACHE_DATA_FILENAME) :
        new File(cacheWorkDir, ccfg.getName() + CACHE_DATA_FILENAME);
}
 
Example 11
Source File: ValidationOnNodeJoinUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param node Joining node.
 * @param ctx Context.
 * @param map Cache descriptors.
 * @return Validation result or {@code null} in case of success.
 */
@Nullable static IgniteNodeValidationResult validateHashIdResolvers(
    ClusterNode node,
    GridKernalContext ctx,
    Map<String, DynamicCacheDescriptor> map
) {
    if (!node.isClient()) {
        for (DynamicCacheDescriptor desc : map.values()) {
            CacheConfiguration cfg = desc.cacheConfiguration();

            if (cfg.getAffinity() instanceof RendezvousAffinityFunction) {
                RendezvousAffinityFunction aff = (RendezvousAffinityFunction)cfg.getAffinity();

                Object nodeHashObj = aff.resolveNodeHash(node);

                for (ClusterNode topNode : ctx.discovery().aliveServerNodes()) {
                    Object topNodeHashObj = aff.resolveNodeHash(topNode);

                    if (nodeHashObj.hashCode() == topNodeHashObj.hashCode()) {
                        String errMsg = "Failed to add node to topology because it has the same hash code for " +
                            "partitioned affinity as one of existing nodes [cacheName=" +
                            cfg.getName() + ", existingNodeId=" + topNode.id() + ']';

                        String sndMsg = "Failed to add node to topology because it has the same hash code for " +
                            "partitioned affinity as one of existing nodes [cacheName=" +
                            cfg.getName() + ", existingNodeId=" + topNode.id() + ']';

                        return new IgniteNodeValidationResult(topNode.id(), errMsg, sndMsg);
                    }
                }
            }
        }
    }

    return null;
}
 
Example 12
Source File: MvccUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * Throws atomicity modes compatibility validation exception.
 *
 * @param ccfg1 Config 1.
 * @param ccfg2 Config 2.
 */
public static void throwAtomicityModesMismatchException(CacheConfiguration ccfg1, CacheConfiguration ccfg2) {
    throw new IgniteException("Caches with transactional_snapshot atomicity mode cannot participate in the same" +
        " transaction with caches having another atomicity mode. [cacheName=" + ccfg1.getName() +
        ", cacheMode=" + ccfg1.getAtomicityMode() + ", anotherCacheName=" + ccfg2.getName() +
        " anotherCacheMode=" + ccfg2.getAtomicityMode() + ']');
}
 
Example 13
Source File: GridCacheUtils.java    From ignite with Apache License 2.0 5 votes vote down vote up
/**
 * @param cfg1 Existing configuration.
 * @param cfg2 Cache configuration to start.
 * @param attrName Short attribute name for error message.
 * @param attrMsg Full attribute name for error message.
 * @param val1 Attribute value in existing configuration.
 * @param val2 Attribute value in starting configuration.
 * @param fail If true throws IgniteCheckedException in case of attribute values mismatch, otherwise logs warning.
 * @throws IgniteCheckedException If validation failed.
 */
public static void validateCacheGroupsAttributesMismatch(IgniteLogger log,
    CacheConfiguration cfg1,
    CacheConfiguration cfg2,
    String attrName,
    String attrMsg,
    Object val1,
    Object val2,
    boolean fail) throws IgniteCheckedException {
    if (F.eq(val1, val2))
        return;

    if (fail) {
        throw new IgniteCheckedException(attrMsg + " mismatch for caches related to the same group " +
            "[groupName=" + cfg1.getGroupName() +
            ", existingCache=" + cfg1.getName() +
            ", existing" + capitalize(attrName) + "=" + val1 +
            ", startingCache=" + cfg2.getName() +
            ", starting" + capitalize(attrName) + "=" + val2 + ']');
    }
    else {
        U.warn(log, attrMsg + " mismatch for caches related to the same group " +
            "[groupName=" + cfg1.getGroupName() +
            ", existingCache=" + cfg1.getName() +
            ", existing" + capitalize(attrName) + "=" + val1 +
            ", startingCache=" + cfg2.getName() +
            ", starting" + capitalize(attrName) + "=" + val2 + ']');
    }
}
 
Example 14
Source File: IgniteSqlNotNullConstraintTest.java    From ignite with Apache License 2.0 5 votes vote down vote up
/** */
private void executeForNodeAndCache(CacheConfiguration ccfg, Ignite ignite, TestClosure clo,
    TransactionConcurrency concurrency, TransactionIsolation isolation) throws Exception {
    String cacheName = ccfg.getName();

    IgniteCache cache;

    if (ignite.configuration().isClientMode() &&
        ccfg.getCacheMode() == CacheMode.PARTITIONED &&
        ccfg.getNearConfiguration() != null)
        cache = ignite.getOrCreateNearCache(ccfg.getName(), ccfg.getNearConfiguration());
    else
        cache = ignite.cache(ccfg.getName());

    cache.removeAll();

    assertEquals(0, cache.size());

    clo.configure(ignite, cache, concurrency, isolation);

    log.info("Running test with node " + ignite.name() + ", cache " + cacheName);

    clo.key1 = 1;
    clo.key2 = 4;

    clo.run();
}
 
Example 15
Source File: CacheGroupContext.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @return Group name if it is specified, otherwise cache name.
 */
public static String cacheOrGroupName(CacheConfiguration<?, ?> ccfg) {
    return ccfg.getGroupName() != null ? ccfg.getGroupName() : ccfg.getName();
}
 
Example 16
Source File: GridLocalConfigManager.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * @param cfg Cache configuration.
 * @param sql SQL flag.
 * @param caches Caches map.
 * @param templates Templates map.
 * @throws IgniteCheckedException If failed.
 */
private void addCacheFromConfiguration(
    CacheConfiguration<?, ?> cfg,
    boolean sql,
    Map<String, CacheJoinNodeDiscoveryData.CacheInfo> caches,
    Map<String, CacheJoinNodeDiscoveryData.CacheInfo> templates
) throws IgniteCheckedException {
    String cacheName = cfg.getName();

    CU.validateCacheName(cacheName);

    cacheProcessor.cloneCheckSerializable(cfg);

    CacheObjectContext cacheObjCtx = ctx.cacheObjects().contextForCache(cfg);

    // Initialize defaults.
    cacheProcessor.initialize(cfg, cacheObjCtx);

    StoredCacheData cacheData = new StoredCacheData(cfg);

    cacheData.sql(sql);

    T2<CacheConfiguration, CacheConfigurationEnrichment> splitCfg = cacheProcessor.splitter().split(cfg);

    cacheData.config(splitCfg.get1());
    cacheData.cacheConfigurationEnrichment(splitCfg.get2());

    cfg = splitCfg.get1();

    if (GridCacheUtils.isCacheTemplateName(cacheName))
        templates.put(cacheName, new CacheJoinNodeDiscoveryData.CacheInfo(cacheData, CacheType.USER, false, 0, true));
    else {
        if (caches.containsKey(cacheName)) {
            throw new IgniteCheckedException("Duplicate cache name found (check configuration and " +
                "assign unique name to each cache): " + cacheName);
        }

        CacheType cacheType = ctx.cache().cacheType(cacheName);

        if (cacheType != CacheType.USER && cfg.getDataRegionName() == null)
            cfg.setDataRegionName(cacheProcessor.context().database().systemDateRegionName());

        addStoredCache(caches, cacheData, cacheName, cacheType, false, true);
    }
}
 
Example 17
Source File: VisorCacheConfiguration.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Create data transfer object for cache configuration properties.
 *
 * @param ignite Grid.
 * @param ccfg Cache configuration.
 * @param dynamicDeploymentId Dynamic deployment ID.
 */
public VisorCacheConfiguration(IgniteEx ignite, CacheConfiguration ccfg, IgniteUuid dynamicDeploymentId) {
    name = ccfg.getName();
    grpName = ccfg.getGroupName();
    this.dynamicDeploymentId = dynamicDeploymentId;
    mode = ccfg.getCacheMode();
    atomicityMode = ccfg.getAtomicityMode();
    eagerTtl = ccfg.isEagerTtl();
    writeSynchronizationMode = ccfg.getWriteSynchronizationMode();
    invalidate = ccfg.isInvalidate();
    maxConcurrentAsyncOps = ccfg.getMaxConcurrentAsyncOperations();
    interceptor = compactClass(ccfg.getInterceptor());
    dfltLockTimeout = ccfg.getDefaultLockTimeout();
    qryEntities = VisorQueryEntity.list(ccfg.getQueryEntities());
    jdbcTypes = VisorCacheJdbcType.list(ccfg.getCacheStoreFactory());
    statisticsEnabled = ccfg.isStatisticsEnabled();
    mgmtEnabled = ccfg.isManagementEnabled();
    ldrFactory = compactClass(ccfg.getCacheLoaderFactory());
    writerFactory = compactClass(ccfg.getCacheWriterFactory());
    expiryPlcFactory = compactClass(ccfg.getExpiryPolicyFactory());

    sys = ignite.context().cache().systemCache(ccfg.getName());
    storeKeepBinary = ccfg.isStoreKeepBinary();
    onheapCache = ccfg.isOnheapCacheEnabled();
    partLossPlc = ccfg.getPartitionLossPolicy();
    qryParallelism = ccfg.getQueryParallelism();

    affinityCfg = new VisorCacheAffinityConfiguration(ccfg);
    rebalanceCfg = new VisorCacheRebalanceConfiguration(ccfg);
    evictCfg = new VisorCacheEvictionConfiguration(ccfg);
    nearCfg = new VisorCacheNearConfiguration(ccfg);

    storeCfg = new VisorCacheStoreConfiguration(ignite, ccfg);

    qryCfg = new VisorQueryConfiguration(ccfg);

    cpOnRead = ccfg.isCopyOnRead();
    evictFilter = compactClass(ccfg.getEvictionFilter());
    lsnrConfigurations = compactIterable(ccfg.getCacheEntryListenerConfigurations());
    loadPrevVal = ccfg.isLoadPreviousValue();
    dataRegName = ccfg.getDataRegionName();
    sqlIdxMaxInlineSize = ccfg.getSqlIndexMaxInlineSize();
    nodeFilter = compactClass(ccfg.getNodeFilter());
    qryDetailMetricsSz = ccfg.getQueryDetailMetricsSize();
    readFromBackup = ccfg.isReadFromBackup();
    tmLookupClsName = ccfg.getTransactionManagerLookupClassName();
    topValidator = compactClass(ccfg.getTopologyValidator());

    diskPageCompression = ccfg.getDiskPageCompression();
    diskPageCompressionLevel = ccfg.getDiskPageCompressionLevel();
}
 
Example 18
Source File: QuerySchema.java    From ignite with Apache License 2.0 4 votes vote down vote up
/**
 * Make query schema patch.
 *
 * @param targetCfg Cache configuration when it should be changed (enabling indexing dynamically).
 * @param target Query entity list to which current schema should be expanded.
 * @return Patch to achieve entity which is a result of merging current one and target.
 * @see QuerySchemaPatch
 */
public QuerySchemaPatch makePatch(CacheConfiguration<?, ?> targetCfg, Collection<QueryEntity> target) {
    synchronized (mux) {
        if (entities.isEmpty() && targetCfg != null) {
            SchemaAddQueryEntityOperation op = new SchemaAddQueryEntityOperation(
                UUID.randomUUID(),
                targetCfg.getName(),
                targetCfg.getSqlSchema(),
                target,
                targetCfg.getQueryParallelism(),
                targetCfg.isSqlEscapeAll()
            );

            return new QuerySchemaPatch(Collections.singletonList(op), Collections.emptyList(), "");
        }

        Map<String, QueryEntity> localEntities = new HashMap<>();

        for (QueryEntity entity : entities) {
            if (localEntities.put(entity.getTableName(), entity) != null)
                throw new IllegalStateException("Duplicate key");
        }

        Collection<SchemaAbstractOperation> patchOperations = new ArrayList<>();
        Collection<QueryEntity> entityToAdd = new ArrayList<>();

        StringBuilder conflicts = new StringBuilder();

        for (QueryEntity queryEntity : target) {
            if (localEntities.containsKey(queryEntity.getTableName())) {
                QueryEntity localEntity = localEntities.get(queryEntity.getTableName());

                QueryEntityPatch entityPatch = localEntity.makePatch(queryEntity);

                if (entityPatch.hasConflict()) {
                    if (conflicts.length() > 0)
                        conflicts.append("\n");

                    conflicts.append(entityPatch.getConflictsMessage());
                }

                if (!entityPatch.isEmpty())
                    patchOperations.addAll(entityPatch.getPatchOperations());
            }
            else
                entityToAdd.add(QueryUtils.copy(queryEntity));
        }

        return new QuerySchemaPatch(patchOperations, entityToAdd, conflicts.toString());
    }
}
 
Example 19
Source File: GridCacheFastNodeLeftForTransactionTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Test transaction rollback when one of the nodes drops out.
 *
 * @throws Exception If failed.
 */
@Test
public void testRollbackTransactions() throws Exception {
    int txCnt = TX_COUNT;

    int nodes = NODES;

    IgniteEx crd = createCluster(nodes);

    for (CacheConfiguration cacheConfig : createCacheConfigs()) {
        String cacheName = cacheConfig.getName();

        IgniteCache<Object, Object> cache = crd.cache(cacheName);

        List<Integer> keys = primaryKeys(cache, txCnt);

        Map<Integer, Integer> cacheValues = range(0, txCnt / 2).boxed().collect(toMap(keys::get, identity()));

        cache.putAll(cacheValues);

        Collection<Transaction> txs = createTxs(
            grid(nodes),
            cacheName,
            range(txCnt / 2, txCnt).mapToObj(keys::get).collect(toList())
        );

        int stoppedNodeId = 2;

        stopGrid(stoppedNodeId);

        LogListener logLsnr = newLogListener();

        listeningLog.registerListener(logLsnr);

        for (Transaction tx : txs)
            tx.rollback();

        awaitPartitionMapExchange();

        check(cacheValues, cacheName, logLsnr, stoppedNodeId);
    }
}
 
Example 20
Source File: GridCacheFastNodeLeftForTransactionTest.java    From ignite with Apache License 2.0 2 votes vote down vote up
/**
 * Test for rollback transactions when one of the nodes drops out,
 * with operations performed on keys outside the transaction.
 *
 * @throws Exception If failed.
 */
@Test
public void testRollbackTransactionsWithKeyOperationOutsideThem() throws Exception {
    int txCnt = TX_COUNT;

    int nodes = NODES;

    IgniteEx crd = createCluster(nodes);

    for (CacheConfiguration cacheConfig : createCacheConfigs()) {
        String cacheName = cacheConfig.getName();

        IgniteCache<Object, Object> cache = crd.cache(cacheName);

        List<Integer> keys = primaryKeys(cache, txCnt);

        Map<Integer, Integer> cacheValues = range(0, txCnt / 2).boxed().collect(toMap(keys::get, identity()));

        cache.putAll(cacheValues);

        List<Integer> txKeys = range(txCnt / 2, txCnt).mapToObj(keys::get).collect(toList());

        IgniteEx clientNode = grid(nodes);

        Collection<Transaction> txs = createTxs(clientNode, cacheName, txKeys);

        int stoppedNodeId = 2;

        stopGrid(stoppedNodeId);

        CountDownLatch latch = new CountDownLatch(1);

        GridTestUtils.runAsync(() -> {
            latch.countDown();

            IgniteCache<Object, Object> clientCache = clientNode.cache(DEFAULT_CACHE_NAME);

            txKeys.forEach(clientCache::get);
        });

        LogListener logLsnr = newLogListener();

        listeningLog.registerListener(logLsnr);

        latch.await();

        for (Transaction tx : txs)
            tx.rollback();

        awaitPartitionMapExchange();

        check(cacheValues, cacheName, logLsnr, stoppedNodeId);
    }
}