use of org.apache.ignite.internal.IgniteInternalFuture in project ignite by apache.
the class GridDhtTransactionalCacheAdapter method lockAllAsync.
/**
* @param cacheCtx Cache context.
* @param nearNode Near node.
* @param req Request.
* @param filter0 Filter.
* @return Future.
*/
public IgniteInternalFuture<GridNearLockResponse> lockAllAsync(final GridCacheContext<?, ?> cacheCtx, final ClusterNode nearNode, final GridNearLockRequest req, @Nullable final CacheEntryPredicate[] filter0) {
final List<KeyCacheObject> keys = req.keys();
CacheEntryPredicate[] filter = filter0;
// Set message into thread context.
GridDhtTxLocal tx = null;
try {
int cnt = keys.size();
if (req.inTx()) {
GridCacheVersion dhtVer = ctx.tm().mappedVersion(req.version());
if (dhtVer != null)
tx = ctx.tm().tx(dhtVer);
}
final List<GridCacheEntryEx> entries = new ArrayList<>(cnt);
// Unmarshal filter first.
if (filter == null)
filter = req.filter();
GridDhtLockFuture fut = null;
if (!req.inTx()) {
GridDhtPartitionTopology top = null;
if (req.firstClientRequest()) {
assert CU.clientNode(nearNode);
top = topology();
topology().readLock();
}
try {
if (top != null && needRemap(req.topologyVersion(), top.topologyVersion())) {
if (log.isDebugEnabled()) {
log.debug("Client topology version mismatch, need remap lock request [" + "reqTopVer=" + req.topologyVersion() + ", locTopVer=" + top.topologyVersion() + ", req=" + req + ']');
}
GridNearLockResponse res = sendClientLockRemapResponse(nearNode, req, top.topologyVersion());
return new GridFinishedFuture<>(res);
}
fut = new GridDhtLockFuture(ctx, nearNode.id(), req.version(), req.topologyVersion(), cnt, req.txRead(), req.needReturnValue(), req.timeout(), tx, req.threadId(), req.createTtl(), req.accessTtl(), filter, req.skipStore(), req.keepBinary());
// Add before mapping.
if (!ctx.mvcc().addFuture(fut))
throw new IllegalStateException("Duplicate future ID: " + fut);
} finally {
if (top != null)
top.readUnlock();
}
}
boolean timedout = false;
for (KeyCacheObject key : keys) {
if (timedout)
break;
while (true) {
// Specify topology version to make sure containment is checked
// based on the requested version, not the latest.
GridDhtCacheEntry entry = entryExx(key, req.topologyVersion());
try {
if (fut != null) {
// This method will add local candidate.
// Entry cannot become obsolete after this method succeeded.
fut.addEntry(key == null ? null : entry);
if (fut.isDone()) {
timedout = true;
break;
}
}
entries.add(entry);
break;
} catch (GridCacheEntryRemovedException ignore) {
if (log.isDebugEnabled())
log.debug("Got removed entry when adding lock (will retry): " + entry);
} catch (GridDistributedLockCancelledException e) {
if (log.isDebugEnabled())
log.debug("Got lock request for cancelled lock (will ignore): " + entry);
fut.onError(e);
return new GridDhtFinishedFuture<>(e);
}
}
}
// Handle implicit locks for pessimistic transactions.
if (req.inTx()) {
if (tx == null) {
GridDhtPartitionTopology top = null;
if (req.firstClientRequest()) {
assert CU.clientNode(nearNode);
top = topology();
topology().readLock();
}
try {
if (top != null && needRemap(req.topologyVersion(), top.topologyVersion())) {
if (log.isDebugEnabled()) {
log.debug("Client topology version mismatch, need remap lock request [" + "reqTopVer=" + req.topologyVersion() + ", locTopVer=" + top.topologyVersion() + ", req=" + req + ']');
}
GridNearLockResponse res = sendClientLockRemapResponse(nearNode, req, top.topologyVersion());
return new GridFinishedFuture<>(res);
}
tx = new GridDhtTxLocal(ctx.shared(), req.topologyVersion(), nearNode.id(), req.version(), req.futureId(), req.miniId(), req.threadId(), /*implicitTx*/
false, /*implicitSingleTx*/
false, ctx.systemTx(), false, ctx.ioPolicy(), PESSIMISTIC, req.isolation(), req.timeout(), req.isInvalidate(), !req.skipStore(), false, req.txSize(), null, req.subjectId(), req.taskNameHash());
if (req.syncCommit())
tx.syncMode(FULL_SYNC);
tx = ctx.tm().onCreated(null, tx);
if (tx == null || !tx.init()) {
String msg = "Failed to acquire lock (transaction has been completed): " + req.version();
U.warn(log, msg);
if (tx != null)
tx.rollbackDhtLocal();
return new GridDhtFinishedFuture<>(new IgniteCheckedException(msg));
}
tx.topologyVersion(req.topologyVersion());
} finally {
if (top != null)
top.readUnlock();
}
}
ctx.tm().txContext(tx);
if (log.isDebugEnabled())
log.debug("Performing DHT lock [tx=" + tx + ", entries=" + entries + ']');
IgniteInternalFuture<GridCacheReturn> txFut = tx.lockAllAsync(cacheCtx, entries, req.messageId(), req.txRead(), req.needReturnValue(), req.createTtl(), req.accessTtl(), req.skipStore(), req.keepBinary());
final GridDhtTxLocal t = tx;
return new GridDhtEmbeddedFuture(txFut, new C2<GridCacheReturn, Exception, IgniteInternalFuture<GridNearLockResponse>>() {
@Override
public IgniteInternalFuture<GridNearLockResponse> apply(GridCacheReturn o, Exception e) {
if (e != null)
e = U.unwrap(e);
assert !t.empty();
// Create response while holding locks.
final GridNearLockResponse resp = createLockReply(nearNode, entries, req, t, t.xidVersion(), e);
assert !t.implicit() : t;
assert !t.onePhaseCommit() : t;
sendLockReply(nearNode, t, req, resp);
return new GridFinishedFuture<>(resp);
}
});
} else {
assert fut != null;
// This will send remote messages.
fut.map();
final GridCacheVersion mappedVer = fut.version();
return new GridDhtEmbeddedFuture<>(new C2<Boolean, Exception, GridNearLockResponse>() {
@Override
public GridNearLockResponse apply(Boolean b, Exception e) {
if (e != null)
e = U.unwrap(e);
else if (!b)
e = new GridCacheLockTimeoutException(req.version());
GridNearLockResponse res = createLockReply(nearNode, entries, req, null, mappedVer, e);
sendLockReply(nearNode, null, req, res);
return res;
}
}, fut);
}
} catch (IgniteCheckedException | RuntimeException e) {
String err = "Failed to unmarshal at least one of the keys for lock request message: " + req;
U.error(log, err, e);
if (tx != null) {
try {
tx.rollbackDhtLocal();
} catch (IgniteCheckedException ex) {
U.error(log, "Failed to rollback the transaction: " + tx, ex);
}
}
return new GridDhtFinishedFuture<>(new IgniteCheckedException(err, e));
}
}
use of org.apache.ignite.internal.IgniteInternalFuture in project ignite by apache.
the class GridDhtGetSingleFuture method getAsync.
/**
*
*/
@SuppressWarnings({ "unchecked", "IfMayBeConditional" })
private void getAsync() {
assert part != -1;
String taskName0 = cctx.kernalContext().job().currentTaskName();
if (taskName0 == null)
taskName0 = cctx.kernalContext().task().resolveTaskName(taskNameHash);
final String taskName = taskName0;
IgniteInternalFuture<Boolean> rdrFut = null;
ClusterNode readerNode = cctx.discovery().node(reader);
ReaderArguments readerArgs = null;
if (readerNode != null && !readerNode.isLocal() && cctx.discovery().cacheNearNode(readerNode, cctx.name())) {
while (true) {
GridDhtCacheEntry e = cache().entryExx(key, topVer);
try {
if (e.obsolete())
continue;
boolean addReader = (!e.deleted() && this.addRdr && !skipVals);
if (addReader) {
e.unswap(false);
// we have to add reader again later.
if (readerArgs == null)
readerArgs = new ReaderArguments(reader, msgId, topVer);
}
// Register reader. If there are active transactions for this entry,
// then will wait for their completion before proceeding.
// TODO: IGNITE-3498:
// TODO: What if any transaction we wait for actually removes this entry?
// TODO: In this case seems like we will be stuck with untracked near entry.
// TODO: To fix, check that reader is contained in the list of readers once
// TODO: again after the returned future completes - if not, try again.
rdrFut = addReader ? e.addReader(reader, msgId, topVer) : null;
break;
} catch (IgniteCheckedException err) {
onDone(err);
return;
} catch (GridCacheEntryRemovedException ignore) {
if (log.isDebugEnabled())
log.debug("Got removed entry when getting a DHT value: " + e);
} finally {
cctx.evicts().touch(e, topVer);
}
}
}
IgniteInternalFuture<Map<KeyCacheObject, EntryGetResult>> fut;
if (rdrFut == null || rdrFut.isDone()) {
fut = cache().getDhtAllAsync(Collections.singleton(key), readerArgs, readThrough, subjId, taskName, expiryPlc, skipVals, /*can remap*/
true, recovery);
} else {
final ReaderArguments args = readerArgs;
rdrFut.listen(new IgniteInClosure<IgniteInternalFuture<Boolean>>() {
@Override
public void apply(IgniteInternalFuture<Boolean> fut) {
Throwable e = fut.error();
if (e != null) {
onDone(e);
return;
}
IgniteInternalFuture<Map<KeyCacheObject, EntryGetResult>> fut0 = cache().getDhtAllAsync(Collections.singleton(key), args, readThrough, subjId, taskName, expiryPlc, skipVals, /*can remap*/
true, recovery);
fut0.listen(createGetFutureListener());
}
});
return;
}
if (fut.isDone())
onResult(fut);
else
fut.listen(createGetFutureListener());
}
use of org.apache.ignite.internal.IgniteInternalFuture in project ignite by apache.
the class GridDhtColocatedCache method getAllAsync.
/** {@inheritDoc} */
@Override
public IgniteInternalFuture<Map<K, V>> getAllAsync(@Nullable final Collection<? extends K> keys, boolean forcePrimary, boolean skipTx, @Nullable UUID subjId, String taskName, final boolean deserializeBinary, final boolean recovery, final boolean skipVals, boolean canRemap, final boolean needVer) {
ctx.checkSecurity(SecurityPermission.CACHE_READ);
if (F.isEmpty(keys))
return new GridFinishedFuture<>(Collections.<K, V>emptyMap());
if (keyCheck)
validateCacheKeys(keys);
GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
final CacheOperationContext opCtx = ctx.operationContextPerCall();
if (tx != null && !tx.implicit() && !skipTx) {
return asyncOp(tx, new AsyncOp<Map<K, V>>(keys) {
@Override
public IgniteInternalFuture<Map<K, V>> op(GridNearTxLocal tx, AffinityTopologyVersion readyTopVer) {
return tx.getAllAsync(ctx, readyTopVer, ctx.cacheKeysView(keys), deserializeBinary, skipVals, false, opCtx != null && opCtx.skipStore(), recovery, needVer);
}
}, opCtx, /*retry*/
false);
}
AffinityTopologyVersion topVer = tx == null ? (canRemap ? ctx.affinity().affinityTopologyVersion() : ctx.shared().exchange().readyAffinityVersion()) : tx.topologyVersion();
subjId = ctx.subjectIdPerCall(subjId, opCtx);
return loadAsync(ctx.cacheKeysView(keys), opCtx == null || !opCtx.skipStore(), forcePrimary, topVer, subjId, taskName, deserializeBinary, recovery, skipVals ? null : expiryPolicy(opCtx != null ? opCtx.expiry() : null), skipVals, canRemap, needVer);
}
use of org.apache.ignite.internal.IgniteInternalFuture in project ignite by apache.
the class GridDhtColocatedCache method getAsync.
/** {@inheritDoc} */
@Override
protected IgniteInternalFuture<V> getAsync(final K key, boolean forcePrimary, boolean skipTx, @Nullable UUID subjId, String taskName, final boolean deserializeBinary, final boolean skipVals, boolean canRemap, final boolean needVer) {
ctx.checkSecurity(SecurityPermission.CACHE_READ);
if (keyCheck)
validateCacheKey(key);
GridNearTxLocal tx = ctx.tm().threadLocalTx(ctx);
final CacheOperationContext opCtx = ctx.operationContextPerCall();
final boolean recovery = opCtx != null && opCtx.recovery();
if (tx != null && !tx.implicit() && !skipTx) {
return asyncOp(tx, new AsyncOp<V>() {
@Override
public IgniteInternalFuture<V> op(GridNearTxLocal tx, AffinityTopologyVersion readyTopVer) {
IgniteInternalFuture<Map<Object, Object>> fut = tx.getAllAsync(ctx, readyTopVer, Collections.singleton(ctx.toCacheKeyObject(key)), deserializeBinary, skipVals, false, opCtx != null && opCtx.skipStore(), recovery, needVer);
return fut.chain(new CX1<IgniteInternalFuture<Map<Object, Object>>, V>() {
@SuppressWarnings("unchecked")
@Override
public V applyx(IgniteInternalFuture<Map<Object, Object>> e) throws IgniteCheckedException {
Map<Object, Object> map = e.get();
assert map.isEmpty() || map.size() == 1 : map.size();
if (skipVals) {
Boolean val = map.isEmpty() ? false : (Boolean) F.firstValue(map);
return (V) (val);
}
return (V) F.firstValue(map);
}
});
}
}, opCtx, /*retry*/
false);
}
AffinityTopologyVersion topVer = tx == null ? (canRemap ? ctx.affinity().affinityTopologyVersion() : ctx.shared().exchange().readyAffinityVersion()) : tx.topologyVersion();
subjId = ctx.subjectIdPerCall(subjId, opCtx);
GridPartitionedSingleGetFuture fut = new GridPartitionedSingleGetFuture(ctx, ctx.toCacheKeyObject(key), topVer, opCtx == null || !opCtx.skipStore(), forcePrimary, subjId, taskName, deserializeBinary, skipVals ? null : expiryPolicy(opCtx != null ? opCtx.expiry() : null), skipVals, canRemap, needVer, /*keepCacheObjects*/
false, opCtx != null && opCtx.recovery());
fut.init();
return (IgniteInternalFuture<V>) fut;
}
use of org.apache.ignite.internal.IgniteInternalFuture in project ignite by apache.
the class GridDhtTxPrepareFuture method onDone.
/** {@inheritDoc} */
@Override
public boolean onDone(GridNearTxPrepareResponse res0, Throwable err) {
assert err != null || (initialized() && !hasPending()) : "On done called for prepare future that has " + "pending mini futures: " + this;
ERR_UPD.compareAndSet(this, null, err);
// Must clear prepare future before response is sent or listeners are notified.
if (tx.optimistic())
tx.clearPrepareFuture(this);
// Do not commit one-phase commit transaction if originating node has near cache enabled.
if (tx.onePhaseCommit() && tx.commitOnPrepare()) {
assert last;
Throwable prepErr = this.err;
// Must create prepare response before transaction is committed to grab correct return value.
final GridNearTxPrepareResponse res = createPrepareResponse(prepErr);
onComplete(res);
if (tx.commitOnPrepare()) {
if (tx.markFinalizing(IgniteInternalTx.FinalizationStatus.USER_FINISH)) {
IgniteInternalFuture<IgniteInternalTx> fut = null;
CIX1<IgniteInternalFuture<IgniteInternalTx>> resClo = new CIX1<IgniteInternalFuture<IgniteInternalTx>>() {
@Override
public void applyx(IgniteInternalFuture<IgniteInternalTx> fut) {
if (REPLIED_UPD.compareAndSet(GridDhtTxPrepareFuture.this, 0, 1))
sendPrepareResponse(res);
}
};
if (prepErr == null) {
try {
fut = tx.commitAsync();
} catch (RuntimeException | Error e) {
Exception hEx = new IgniteTxHeuristicCheckedException("Commit produced a runtime " + "exception: " + CU.txString(tx), e);
res.error(hEx);
tx.systemInvalidate(true);
fut = tx.rollbackAsync();
fut.listen(resClo);
throw e;
}
} else if (!cctx.kernalContext().isStopping())
fut = tx.rollbackAsync();
if (fut != null)
fut.listen(resClo);
}
} else {
if (REPLIED_UPD.compareAndSet(this, 0, 1))
sendPrepareResponse(res);
}
return true;
} else {
if (REPLIED_UPD.compareAndSet(this, 0, 1)) {
GridNearTxPrepareResponse res = createPrepareResponse(this.err);
try {
sendPrepareResponse(res);
} finally {
// Will call super.onDone().
onComplete(res);
}
return true;
} else {
// Other thread is completing future. Wait for it to complete.
try {
if (err != null)
get();
} catch (IgniteInterruptedException e) {
onError(new IgniteCheckedException("Got interrupted while waiting for replies to be sent.", e));
} catch (IgniteCheckedException ignored) {
// No-op, get() was just synchronization.
}
return false;
}
}
}
Aggregations