use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.
the class IgniteCacheOffheapManagerImpl method reservedIterator.
/**
* {@inheritDoc}
*/
@Override
public GridCloseableIterator<CacheDataRow> reservedIterator(int part, AffinityTopologyVersion topVer) {
GridDhtLocalPartition loc = grp.topology().localPartition(part, topVer, false);
if (loc == null || !loc.reserve())
return null;
// It is necessary to check state after reservation to avoid race conditions.
if (loc.state() != OWNING) {
loc.release();
return null;
}
CacheDataStore data = dataStore(loc);
return new GridCloseableIteratorAdapter<CacheDataRow>() {
/**
*/
private CacheDataRow next;
/**
*/
private GridCursor<? extends CacheDataRow> cur;
@Override
protected CacheDataRow onNext() {
CacheDataRow res = next;
next = null;
return res;
}
@Override
protected boolean onHasNext() throws IgniteCheckedException {
if (cur == null)
cur = data.cursor(CacheDataRowAdapter.RowData.FULL_WITH_HINTS);
if (next != null)
return true;
if (cur.next())
next = cur.get();
boolean hasNext = next != null;
if (!hasNext)
cur = null;
return hasNext;
}
@Override
protected void onClose() throws IgniteCheckedException {
assert loc != null && loc.state() == OWNING && loc.reservations() > 0 : "Partition should be in OWNING state and has at least 1 reservation: " + loc;
loc.release();
cur = null;
}
};
}
use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.
the class IgniteSnapshotManager method partitionRowIterator.
/**
* @param snpName Snapshot name.
* @param folderName The node folder name, usually it's the same as the U.maskForFileName(consistentId).
* @param grpName Cache group name.
* @param partId Partition id.
* @return Iterator over partition.
* @throws IgniteCheckedException If and error occurs.
*/
public GridCloseableIterator<CacheDataRow> partitionRowIterator(GridKernalContext ctx, String snpName, String folderName, String grpName, int partId) throws IgniteCheckedException {
File snpDir = resolveSnapshotDir(snpName);
File nodePath = new File(snpDir, databaseRelativePath(folderName));
if (!nodePath.exists())
throw new IgniteCheckedException("Consistent id directory doesn't exists: " + nodePath.getAbsolutePath());
List<File> grps = cacheDirectories(nodePath, name -> name.equals(grpName));
if (F.isEmpty(grps)) {
throw new IgniteCheckedException("The snapshot cache group not found [dir=" + snpDir.getAbsolutePath() + ", grpName=" + grpName + ']');
}
if (grps.size() > 1) {
throw new IgniteCheckedException("The snapshot cache group directory cannot be uniquely identified [dir=" + snpDir.getAbsolutePath() + ", grpName=" + grpName + ']');
}
File snpPart = getPartitionFile(new File(snapshotLocalDir(snpName), databaseRelativePath(folderName)), grps.get(0).getName(), partId);
int grpId = CU.cacheId(grpName);
FilePageStore pageStore = (FilePageStore) storeMgr.getPageStoreFactory(grpId, cctx.cache().isEncrypted(grpId)).createPageStore(getTypeByPartId(partId), snpPart::toPath, val -> {
});
GridCloseableIterator<CacheDataRow> partIter = partitionRowIterator(ctx, grpName, partId, pageStore);
return new GridCloseableIteratorAdapter<CacheDataRow>() {
/**
* {@inheritDoc}
*/
@Override
protected CacheDataRow onNext() throws IgniteCheckedException {
return partIter.nextX();
}
/**
* {@inheritDoc}
*/
@Override
protected boolean onHasNext() throws IgniteCheckedException {
return partIter.hasNextX();
}
/**
* {@inheritDoc}
*/
@Override
protected void onClose() {
U.closeQuiet(pageStore);
}
};
}
use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.
the class GridCacheAdapter method getAllAsync0.
/**
* @param keys Keys.
* @param readerArgs Near cache reader will be added if not null.
* @param readThrough Read-through flag.
* @param checkTx Check local transaction flag.
* @param taskName Task name/
* @param deserializeBinary Deserialize binary flag.
* @param expiry Expiry policy.
* @param skipVals Skip values flag.
* @param keepCacheObjects Keep cache objects.
* @param needVer If {@code true} returns values as tuples containing value and version.
* @param txLbl Transaction label.
* @param mvccSnapshot MVCC snapshot.
* @return Future.
*/
protected final <K1, V1> IgniteInternalFuture<Map<K1, V1>> getAllAsync0(@Nullable final Collection<KeyCacheObject> keys, @Nullable final ReaderArguments readerArgs, final boolean readThrough, boolean checkTx, final String taskName, final boolean deserializeBinary, @Nullable final IgniteCacheExpiryPolicy expiry, final boolean skipVals, final boolean keepCacheObjects, final boolean recovery, final ReadRepairStrategy readRepairStrategy, final boolean needVer, @Nullable String txLbl, MvccSnapshot mvccSnapshot) {
if (F.isEmpty(keys))
return new GridFinishedFuture<>(Collections.<K1, V1>emptyMap());
GridNearTxLocal tx = null;
if (checkTx) {
try {
checkJta();
} catch (IgniteCheckedException e) {
return new GridFinishedFuture<>(e);
}
tx = checkCurrentTx();
}
if (ctx.mvccEnabled() || tx == null || tx.implicit()) {
assert (mvccSnapshot == null) == !ctx.mvccEnabled();
Map<KeyCacheObject, EntryGetResult> misses = null;
Set<GridCacheEntryEx> newLocalEntries = null;
final AffinityTopologyVersion topVer = tx == null ? ctx.affinity().affinityTopologyVersion() : tx.topologyVersion();
ctx.shared().database().checkpointReadLock();
try {
int keysSize = keys.size();
GridDhtTopologyFuture topFut = ctx.shared().exchange().lastFinishedFuture();
Throwable ex = topFut != null ? topFut.validateCache(ctx, recovery, /*read*/
true, null, keys) : null;
if (ex != null)
return new GridFinishedFuture<>(ex);
final Map<K1, V1> map = keysSize == 1 ? (Map<K1, V1>) new IgniteBiTuple<>() : U.<K1, V1>newHashMap(keysSize);
final boolean storeEnabled = !skipVals && readThrough && ctx.readThrough();
boolean readNoEntry = ctx.readNoEntry(expiry, readerArgs != null);
for (KeyCacheObject key : keys) {
while (true) {
try {
EntryGetResult res = null;
boolean evt = !skipVals;
boolean updateMetrics = !skipVals;
GridCacheEntryEx entry = null;
boolean skipEntry = readNoEntry;
if (readNoEntry) {
CacheDataRow row = mvccSnapshot != null ? ctx.offheap().mvccRead(ctx, key, mvccSnapshot) : ctx.offheap().read(ctx, key);
if (row != null) {
long expireTime = row.expireTime();
if (expireTime != 0) {
if (expireTime > U.currentTimeMillis()) {
res = new EntryGetWithTtlResult(row.value(), row.version(), false, expireTime, 0);
} else
skipEntry = false;
} else
res = new EntryGetResult(row.value(), row.version(), false);
}
if (res != null) {
if (evt) {
ctx.events().readEvent(key, null, txLbl, row.value(), taskName, !deserializeBinary);
}
if (updateMetrics && ctx.statisticsEnabled())
ctx.cache().metrics0().onRead(true);
} else if (storeEnabled)
skipEntry = false;
}
if (!skipEntry) {
boolean isNewLocalEntry = this.map.getEntry(ctx, key) == null;
entry = entryEx(key);
if (entry == null) {
if (!skipVals && ctx.statisticsEnabled())
ctx.cache().metrics0().onRead(false);
break;
}
if (isNewLocalEntry) {
if (newLocalEntries == null)
newLocalEntries = new HashSet<>();
newLocalEntries.add(entry);
}
if (storeEnabled) {
res = entry.innerGetAndReserveForLoad(updateMetrics, evt, taskName, expiry, !deserializeBinary, readerArgs);
assert res != null;
if (res.value() == null) {
if (misses == null)
misses = new HashMap<>();
misses.put(key, res);
res = null;
}
} else {
res = entry.innerGetVersioned(null, null, updateMetrics, evt, null, taskName, expiry, !deserializeBinary, readerArgs);
if (res == null)
entry.touch();
}
}
if (res != null) {
ctx.addResult(map, key, res, skipVals, keepCacheObjects, deserializeBinary, true, needVer);
if (entry != null && (tx == null || (!tx.implicit() && tx.isolation() == READ_COMMITTED)))
entry.touch();
if (keysSize == 1)
// Safe to return because no locks are required in READ_COMMITTED mode.
return new GridFinishedFuture<>(map);
}
break;
} catch (GridCacheEntryRemovedException ignored) {
if (log.isDebugEnabled())
log.debug("Got removed entry in getAllAsync(..) method (will retry): " + key);
}
}
}
if (storeEnabled && misses != null) {
final Map<KeyCacheObject, EntryGetResult> loadKeys = misses;
final IgniteTxLocalAdapter tx0 = tx;
final Collection<KeyCacheObject> loaded = new HashSet<>();
return new GridEmbeddedFuture(ctx.closures().callLocalSafe(ctx.projectSafe(new GPC<Map<K1, V1>>() {
@Override
public Map<K1, V1> call() throws Exception {
ctx.store().loadAll(null, /*tx*/
loadKeys.keySet(), new CI2<KeyCacheObject, Object>() {
@Override
public void apply(KeyCacheObject key, Object val) {
EntryGetResult res = loadKeys.get(key);
if (res == null || val == null)
return;
loaded.add(key);
CacheObject cacheVal = ctx.toCacheObject(val);
while (true) {
GridCacheEntryEx entry = null;
try {
ctx.shared().database().ensureFreeSpace(ctx.dataRegion());
} catch (IgniteCheckedException e) {
// Wrap errors (will be unwrapped).
throw new GridClosureException(e);
}
ctx.shared().database().checkpointReadLock();
try {
entry = entryEx(key);
entry.unswap();
GridCacheVersion newVer = nextVersion();
EntryGetResult verVal = entry.versionedValue(cacheVal, res.version(), newVer, expiry, readerArgs);
if (log.isDebugEnabled())
log.debug("Set value loaded from store into entry [" + "oldVer=" + res.version() + ", newVer=" + verVal.version() + ", " + "entry=" + entry + ']');
// Don't put key-value pair into result map if value is null.
if (verVal.value() != null) {
ctx.addResult(map, key, verVal, skipVals, keepCacheObjects, deserializeBinary, true, needVer);
} else {
ctx.addResult(map, key, new EntryGetResult(cacheVal, res.version()), skipVals, keepCacheObjects, deserializeBinary, false, needVer);
}
if (tx0 == null || (!tx0.implicit() && tx0.isolation() == READ_COMMITTED))
entry.touch();
break;
} catch (GridCacheEntryRemovedException ignore) {
if (log.isDebugEnabled())
log.debug("Got removed entry during getAllAsync (will retry): " + entry);
} catch (IgniteCheckedException e) {
// Wrap errors (will be unwrapped).
throw new GridClosureException(e);
} finally {
ctx.shared().database().checkpointReadUnlock();
}
}
}
});
clearReservationsIfNeeded(topVer, loadKeys, loaded, tx0);
return map;
}
}), true), new C2<Map<K, V>, Exception, IgniteInternalFuture<Map<K, V>>>() {
@Override
public IgniteInternalFuture<Map<K, V>> apply(Map<K, V> map, Exception e) {
if (e != null) {
clearReservationsIfNeeded(topVer, loadKeys, loaded, tx0);
return new GridFinishedFuture<>(e);
}
if (tx0 == null || (!tx0.implicit() && tx0.isolation() == READ_COMMITTED)) {
Collection<KeyCacheObject> notFound = new HashSet<>(loadKeys.keySet());
notFound.removeAll(loaded);
// Touch entries that were not found in store.
for (KeyCacheObject key : notFound) {
GridCacheEntryEx entry = peekEx(key);
if (entry != null)
entry.touch();
}
}
// There were no misses.
return new GridFinishedFuture<>(Collections.<K, V>emptyMap());
}
}, new C2<Map<K1, V1>, Exception, Map<K1, V1>>() {
@Override
public Map<K1, V1> apply(Map<K1, V1> loaded, Exception e) {
if (e == null)
map.putAll(loaded);
return map;
}
});
} else
// Misses can be non-zero only if store is enabled.
assert misses == null;
return new GridFinishedFuture<>(map);
} catch (RuntimeException | AssertionError e) {
if (misses != null) {
for (KeyCacheObject key0 : misses.keySet()) {
GridCacheEntryEx entry = peekEx(key0);
if (entry != null)
entry.touch();
}
}
if (newLocalEntries != null) {
for (GridCacheEntryEx entry : newLocalEntries) removeEntry(entry);
}
return new GridFinishedFuture<>(e);
} catch (IgniteCheckedException e) {
return new GridFinishedFuture<>(e);
} finally {
ctx.shared().database().checkpointReadUnlock();
}
} else {
return asyncOp(tx, new AsyncOp<Map<K1, V1>>(keys) {
@Override
public IgniteInternalFuture<Map<K1, V1>> op(GridNearTxLocal tx, AffinityTopologyVersion readyTopVer) {
return tx.getAllAsync(ctx, readyTopVer, keys, deserializeBinary, skipVals, false, !readThrough, recovery, readRepairStrategy, needVer);
}
}, ctx.operationContextPerCall(), /*retry*/
false);
}
}
use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.
the class GridCommandHandlerIndexingUtils method breakCacheDataTree.
/**
* Deleting a rows from the cache without updating indexes.
*
* @param log Logger.
* @param internalCache Cache.
* @param partId Partition number.
* @param filter Entry filter.
*/
static <K, V> void breakCacheDataTree(IgniteLogger log, IgniteInternalCache<K, V> internalCache, int partId, @Nullable BiPredicate<Integer, Entry<K, V>> filter) {
requireNonNull(log);
requireNonNull(internalCache);
GridCacheContext<K, V> cacheCtx = internalCache.context();
CacheDataStore cacheDataStore = cacheCtx.dht().topology().localPartition(partId).dataStore();
String delegate = "delegate";
if (hasField(cacheDataStore, delegate))
cacheDataStore = field(cacheDataStore, delegate);
CacheDataRowStore cacheDataRowStore = field(cacheDataStore, "rowStore");
CacheDataTree cacheDataTree = field(cacheDataStore, "dataTree");
String cacheName = internalCache.name();
QueryCursor<Entry<K, V>> qryCursor = cacheCtx.kernalContext().grid().cache(cacheName).withKeepBinary().query(new ScanQuery<>(partId));
Iterator<Entry<K, V>> cacheEntryIter = qryCursor.iterator();
IgniteCacheDatabaseSharedManager db = cacheCtx.shared().database();
int cacheId = CU.cacheId(cacheName);
int i = 0;
while (cacheEntryIter.hasNext()) {
Entry<K, V> entry = cacheEntryIter.next();
if (nonNull(filter) && !filter.test(i++, entry))
continue;
db.checkpointReadLock();
try {
CacheDataRow oldRow = cacheDataTree.remove(new SearchRow(cacheId, cacheCtx.toCacheKeyObject(entry.getKey())));
if (nonNull(oldRow))
cacheDataRowStore.removeRow(oldRow.link(), INSTANCE);
} catch (IgniteCheckedException e) {
throw new IgniteException("Failed to remove key skipping indexes: " + entry, e);
} finally {
db.checkpointReadUnlock();
}
}
}
use of org.apache.ignite.internal.processors.cache.persistence.CacheDataRow in project ignite by apache.
the class GridDhtPartitionDemander method preloadEntries.
/**
* Adds entries to partition p.
*
* @param topVer Topology version.
* @param part Local partition.
* @param infos Entries info for preload.
* @throws IgniteCheckedException If failed.
*/
private void preloadEntries(AffinityTopologyVersion topVer, GridDhtLocalPartition part, Iterator<GridCacheEntryInfo> infos) throws IgniteCheckedException {
// Received keys by caches, for statistics.
IntHashMap<GridMutableLong> receivedKeys = new IntHashMap<>();
grp.offheap().storeEntries(part, infos, new IgnitePredicateX<CacheDataRow>() {
/**
* {@inheritDoc}
*/
@Override
public boolean applyx(CacheDataRow row) throws IgniteCheckedException {
receivedKeys.computeIfAbsent(row.cacheId(), cid -> new GridMutableLong()).incrementAndGet();
return preloadEntry(row, topVer);
}
});
updateKeyReceivedMetrics(grp, receivedKeys);
}
Aggregations