use of org.apache.ignite.internal.util.typedef.CX1 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, 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 ? ctx.affinity().affinityTopologyVersion() : 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, needVer, /*keepCacheObjects*/
false, opCtx != null && opCtx.recovery());
fut.init();
return (IgniteInternalFuture<V>) fut;
}
use of org.apache.ignite.internal.util.typedef.CX1 in project ignite by apache.
the class GridNearTxLocal method removeAllAsync0.
/**
* @param cacheCtx Cache context.
* @param keys Keys to remove.
* @param drMap DR map.
* @param retval Flag indicating whether a value should be returned.
* @param filter Filter.
* @param singleRmv {@code True} for single key remove operation ({@link Cache#remove(Object)}.
* @return Future for asynchronous remove.
*/
@SuppressWarnings("unchecked")
private <K, V> IgniteInternalFuture<GridCacheReturn> removeAllAsync0(final GridCacheContext cacheCtx, @Nullable AffinityTopologyVersion entryTopVer, @Nullable final Collection<? extends K> keys, @Nullable Map<KeyCacheObject, GridCacheVersion> drMap, final boolean retval, @Nullable final CacheEntryPredicate filter, boolean singleRmv) {
if (cacheCtx.mvccEnabled())
return mvccRemoveAllAsync0(cacheCtx, keys, retval, filter);
try {
checkUpdatesAllowed(cacheCtx);
} catch (IgniteCheckedException e) {
return new GridFinishedFuture(e);
}
cacheCtx.checkSecurity(SecurityPermission.CACHE_REMOVE);
if (retval)
needReturnValue(true);
final Collection<?> keys0;
if (drMap != null) {
assert keys == null;
keys0 = drMap.keySet();
} else
keys0 = keys;
CacheOperationContext opCtx = cacheCtx.operationContextPerCall();
final Byte dataCenterId;
if (opCtx != null && opCtx.hasDataCenterId()) {
assert drMap == null : drMap;
dataCenterId = opCtx.dataCenterId();
} else
dataCenterId = null;
assert keys0 != null;
if (log.isDebugEnabled())
log.debug(S.toString("Called removeAllAsync(...)", "tx", this, false, "keys", keys0, true, "implicit", implicit, false, "retval", retval, false));
try {
checkValid();
} catch (IgniteCheckedException e) {
return new GridFinishedFuture<>(e);
}
final GridCacheReturn ret = new GridCacheReturn(localResult(), false);
if (F.isEmpty(keys0)) {
if (implicit()) {
try {
commit();
} catch (IgniteCheckedException e) {
return new GridFinishedFuture<>(e);
}
}
return new GridFinishedFuture<>(ret.success(true));
}
init();
final Collection<KeyCacheObject> enlisted = new ArrayList<>();
ExpiryPolicy plc;
final CacheEntryPredicate[] filters = CU.filterArray(filter);
if (!F.isEmpty(filters))
plc = opCtx != null ? opCtx.expiry() : null;
else
plc = null;
final boolean keepBinary = opCtx != null && opCtx.isKeepBinary();
final IgniteInternalFuture<Void> loadFut = enlistWrite(cacheCtx, entryTopVer, keys0, plc, /*lookup map*/
null, /*invoke map*/
null, /*invoke arguments*/
null, retval, /*lock only*/
false, filters, ret, enlisted, null, drMap, opCtx != null && opCtx.skipStore(), singleRmv, keepBinary, opCtx != null && opCtx.recovery(), dataCenterId);
try {
loadFut.get();
} catch (IgniteCheckedException e) {
return new GridFinishedFuture(e);
}
long timeout = remainingTime();
if (timeout == -1)
return new GridFinishedFuture<>(timeoutException());
if (isRollbackOnly())
return new GridFinishedFuture<>(rollbackException());
if (log.isDebugEnabled())
log.debug("Remove keys: " + enlisted);
// to be rolled back.
if (pessimistic()) {
if (log.isDebugEnabled())
log.debug("Before acquiring transaction lock for remove on keys: " + enlisted);
IgniteInternalFuture<Boolean> fut = cacheCtx.cache().txLockAsync(enlisted, timeout, this, false, retval, isolation, isInvalidate(), -1L, -1L);
PLC1<GridCacheReturn> plc1 = new PLC1<GridCacheReturn>(ret) {
/**
* {@inheritDoc}
*/
@Override
protected GridCacheReturn postLock(GridCacheReturn ret) throws IgniteCheckedException {
if (log.isDebugEnabled())
log.debug("Acquired transaction lock for remove on keys: " + enlisted);
postLockWrite(cacheCtx, enlisted, ret, /*remove*/
true, retval, /*read*/
false, -1L, filters, /*computeInvoke*/
false);
return ret;
}
};
if (fut.isDone()) {
try {
return nonInterruptable(plc1.apply(fut.get(), null));
} catch (GridClosureException e) {
return new GridFinishedFuture<>(e.unwrap());
} catch (IgniteCheckedException e) {
try {
return nonInterruptable(plc1.apply(false, e));
} catch (Exception e1) {
return new GridFinishedFuture<>(e1);
}
}
} else
return nonInterruptable(new GridEmbeddedFuture<>(fut, plc1));
} else {
if (implicit()) {
// with prepare response, if required.
assert loadFut.isDone();
return nonInterruptable(commitNearTxLocalAsync().chain(new CX1<IgniteInternalFuture<IgniteInternalTx>, GridCacheReturn>() {
@Override
public GridCacheReturn applyx(IgniteInternalFuture<IgniteInternalTx> txFut) throws IgniteCheckedException {
try {
txFut.get();
return new GridCacheReturn(cacheCtx, true, keepBinary, U.deploymentClassLoader(cctx.kernalContext(), deploymentLdrId), implicitRes.value(), implicitRes.success());
} catch (IgniteCheckedException | RuntimeException e) {
rollbackNearTxLocalAsync();
throw e;
}
}
}));
} else {
return nonInterruptable(loadFut.chain(new CX1<IgniteInternalFuture<Void>, GridCacheReturn>() {
@Override
public GridCacheReturn applyx(IgniteInternalFuture<Void> f) throws IgniteCheckedException {
f.get();
return ret;
}
}));
}
}
}
use of org.apache.ignite.internal.util.typedef.CX1 in project ignite by apache.
the class GridNearTxLocal method optimisticPutFuture.
/**
* @param cacheCtx Cache context.
* @param loadFut Missing keys load future.
* @param ret Future result.
* @param keepBinary Keep binary flag.
* @return Future.
*/
private IgniteInternalFuture optimisticPutFuture(final GridCacheContext cacheCtx, IgniteInternalFuture<Void> loadFut, final GridCacheReturn ret, final boolean keepBinary) {
if (implicit()) {
// with prepare response, if required.
assert loadFut.isDone();
return nonInterruptable(commitNearTxLocalAsync().chain(new CX1<IgniteInternalFuture<IgniteInternalTx>, GridCacheReturn>() {
@Override
public GridCacheReturn applyx(IgniteInternalFuture<IgniteInternalTx> txFut) throws IgniteCheckedException {
try {
txFut.get();
Object res = implicitRes.value();
if (implicitRes.invokeResult()) {
assert res == null || res instanceof Map : implicitRes;
res = cacheCtx.unwrapInvokeResult((Map) res, keepBinary);
}
return new GridCacheReturn(cacheCtx, true, keepBinary, U.deploymentClassLoader(cctx.kernalContext(), deploymentLdrId), res, implicitRes.success());
} catch (IgniteCheckedException | RuntimeException e) {
if (!(e instanceof NodeStoppingException))
rollbackNearTxLocalAsync();
throw e;
}
}
}));
} else {
return nonInterruptable(loadFut.chain(new CX1<IgniteInternalFuture<Void>, GridCacheReturn>() {
@Override
public GridCacheReturn applyx(IgniteInternalFuture<Void> f) throws IgniteCheckedException {
f.get();
return ret;
}
}));
}
}
use of org.apache.ignite.internal.util.typedef.CX1 in project ignite by apache.
the class IgfsDataManager method dataBlock.
/**
* Get data block for specified file ID and block index.
*
* @param fileInfo File info.
* @param path Path reading from.
* @param blockIdx Block index.
* @param secReader Optional secondary file system reader.
* @return Requested data block or {@code null} if nothing found.
* @throws IgniteCheckedException If failed.
*/
@Nullable
public IgniteInternalFuture<byte[]> dataBlock(final IgfsEntryInfo fileInfo, final IgfsPath path, final long blockIdx, @Nullable final IgfsSecondaryFileSystemPositionedReadable secReader) throws IgniteCheckedException {
assert fileInfo != null;
assert blockIdx >= 0;
// Schedule block request BEFORE prefetch requests.
final IgfsBlockKey key = blockKey(blockIdx, fileInfo);
if (log.isDebugEnabled() && dataCache.affinity().isPrimaryOrBackup(igfsCtx.kernalContext().discovery().localNode(), key)) {
log.debug("Reading non-local data block [path=" + path + ", fileInfo=" + fileInfo + ", blockIdx=" + blockIdx + ']');
}
IgniteInternalFuture<byte[]> fut = dataCachePrj.getAsync(key);
if (secReader != null) {
Executor exec = igfsCtx.kernalContext().pools().poolForPolicy(GridIoPolicy.IGFS_POOL);
fut = fut.chain(new CX1<IgniteInternalFuture<byte[]>, byte[]>() {
@Override
public byte[] applyx(IgniteInternalFuture<byte[]> fut) throws IgniteCheckedException {
byte[] res = fut.get();
if (res == null) {
GridFutureAdapter<byte[]> rmtReadFut = new GridFutureAdapter<>();
IgniteInternalFuture<byte[]> oldRmtReadFut = rmtReadFuts.putIfAbsent(key, rmtReadFut);
if (oldRmtReadFut == null) {
try {
res = secondaryDataBlock(path, blockIdx, secReader, fileInfo.blockSize());
rmtReadFut.onDone(res);
putBlock(fileInfo.blockSize(), key, res);
} catch (IgniteCheckedException e) {
rmtReadFut.onDone(e);
throw e;
} finally {
boolean rmv = rmtReadFuts.remove(key, rmtReadFut);
assert rmv;
}
} else {
// Wait for existing future to finish and get it's result.
res = oldRmtReadFut.get();
igfsCtx.metrics().addReadBlocks(1, 0);
}
} else
igfsCtx.metrics().addReadBlocks(1, 0);
return res;
}
}, exec);
} else
igfsCtx.metrics().addReadBlocks(1, 0);
return fut;
}
use of org.apache.ignite.internal.util.typedef.CX1 in project ignite by apache.
the class GridCacheAdapter method asyncOp.
/**
* @param tx Transaction.
* @param op Cache operation.
* @param opCtx Cache operation context.
* @param <T> Return type.
* @return Future.
*/
@SuppressWarnings("unchecked")
protected <T> IgniteInternalFuture<T> asyncOp(GridNearTxLocal tx, final AsyncOp<T> op, final CacheOperationContext opCtx, final boolean retry) {
IgniteInternalFuture<T> fail = asyncOpAcquire(retry);
if (fail != null)
return fail;
FutureHolder holder = lastFut.get();
holder.lock();
try {
IgniteInternalFuture fut = holder.future();
final GridNearTxLocal tx0 = tx;
final CX1 clo = new CX1<IgniteInternalFuture<T>, T>() {
@Override
public T applyx(IgniteInternalFuture<T> tFut) throws IgniteCheckedException {
try {
return tFut.get();
} catch (IgniteTxTimeoutCheckedException | IgniteTxRollbackCheckedException | NodeStoppingException | IgniteConsistencyViolationException e) {
throw e;
} catch (IgniteCheckedException e1) {
try {
tx0.rollbackNearTxLocalAsync();
} catch (Throwable e2) {
if (e1 != e2)
e1.addSuppressed(e2);
}
throw e1;
} finally {
ctx.shared().txContextReset();
}
}
};
if (fut != null && !fut.isDone()) {
IgniteInternalFuture<T> f = new GridEmbeddedFuture(fut, (IgniteOutClosure<IgniteInternalFuture>) () -> {
GridFutureAdapter resFut = new GridFutureAdapter();
ctx.kernalContext().closure().runLocalSafe((GridPlainRunnable) () -> {
IgniteInternalFuture fut0;
if (ctx.kernalContext().isStopping())
fut0 = new GridFinishedFuture<>(new IgniteCheckedException("Operation has been cancelled (node or cache is stopping)."));
else if (ctx.gate().isStopped())
fut0 = new GridFinishedFuture<>(new CacheStoppedException(ctx.name()));
else {
ctx.operationContextPerCall(opCtx);
ctx.shared().txContextReset();
try {
fut0 = op.op(tx0).chain(clo);
} finally {
// It is necessary to clear tx context in this thread as well.
ctx.shared().txContextReset();
ctx.operationContextPerCall(null);
}
}
fut0.listen((IgniteInClosure<IgniteInternalFuture>) fut01 -> {
try {
resFut.onDone(fut01.get());
} catch (Throwable ex) {
resFut.onDone(ex);
}
});
}, true);
return resFut;
});
saveFuture(holder, f, retry);
return f;
}
/**
* Wait for concurrent tx operation to finish.
* See {@link GridDhtTxLocalAdapter#updateLockFuture(IgniteInternalFuture, IgniteInternalFuture)}
*/
if (!tx0.txState().implicitSingle())
tx0.txState().awaitLastFuture(ctx.shared());
IgniteInternalFuture<T> f;
try {
f = op.op(tx).chain(clo);
} finally {
// It is necessary to clear tx context in this thread as well.
ctx.shared().txContextReset();
}
saveFuture(holder, f, retry);
if (tx.implicit())
ctx.tm().resetContext();
return f;
} finally {
holder.unlock();
}
}
Aggregations