use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.
the class IgniteTxManager method txsPreparedOrCommitted.
/**
* @param nearVer Near version ID.
* @param txNum Number of transactions.
* @param fut Result future.
* @param processedVers Processed versions.
* @return Future for flag indicating if transactions were prepared or committed or {@code null} for success future.
*/
@Nullable
private IgniteInternalFuture<Boolean> txsPreparedOrCommitted(final GridCacheVersion nearVer, int txNum, @Nullable GridFutureAdapter<Boolean> fut, @Nullable Collection<GridCacheVersion> processedVers) {
for (final IgniteInternalTx tx : txs()) {
if (nearVer.equals(tx.nearXidVersion())) {
IgniteInternalFuture<?> prepFut = tx.currentPrepareFuture();
if (prepFut != null && !prepFut.isDone()) {
if (log.isDebugEnabled())
log.debug("Transaction is preparing (will wait): " + tx);
final GridFutureAdapter<Boolean> fut0 = fut != null ? fut : new GridFutureAdapter<Boolean>();
final int txNum0 = txNum;
final Collection<GridCacheVersion> processedVers0 = processedVers;
prepFut.listen(new CI1<IgniteInternalFuture<?>>() {
@Override
public void apply(IgniteInternalFuture<?> prepFut) {
if (log.isDebugEnabled())
log.debug("Transaction prepare future finished: " + tx);
IgniteInternalFuture<Boolean> fut = txsPreparedOrCommitted(nearVer, txNum0, fut0, processedVers0);
assert fut == fut0;
}
});
return fut0;
}
TransactionState state = tx.state();
if (state == PREPARED || state == COMMITTING || state == COMMITTED) {
if (--txNum == 0) {
if (fut != null)
fut.onDone(true);
return fut;
}
} else {
if (tx.state(MARKED_ROLLBACK) || tx.state() == UNKNOWN) {
tx.rollbackAsync();
if (log.isDebugEnabled())
log.debug("Transaction was not prepared (rolled back): " + tx);
if (fut == null)
fut = new GridFutureAdapter<>();
fut.onDone(false);
return fut;
} else {
if (tx.state() == COMMITTED) {
if (--txNum == 0) {
if (fut != null)
fut.onDone(true);
return fut;
}
} else {
if (log.isDebugEnabled())
log.debug("Transaction is not prepared: " + tx);
if (fut == null)
fut = new GridFutureAdapter<>();
fut.onDone(false);
return fut;
}
}
}
if (processedVers == null)
processedVers = new HashSet<>(txNum, 1.0f);
processedVers.add(tx.xidVersion());
}
}
// if transaction was already committed.
for (Map.Entry<GridCacheVersion, Object> e : completedVersHashMap.entrySet()) {
if (e.getValue().equals(Boolean.FALSE))
continue;
GridCacheVersion ver = e.getKey();
if (processedVers != null && processedVers.contains(ver))
continue;
if (ver instanceof CommittedVersion) {
CommittedVersion commitVer = (CommittedVersion) ver;
if (commitVer.nearVer.equals(nearVer)) {
if (--txNum == 0) {
if (fut != null)
fut.onDone(true);
return fut;
}
}
}
}
if (fut == null)
fut = new GridFutureAdapter<>();
fut.onDone(false);
return fut;
}
use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.
the class DataStreamProcessor method localUpdate.
/**
* @param nodeId Node id.
* @param req Request.
* @param updater Updater.
* @param topic Topic.
*/
private void localUpdate(final UUID nodeId, final DataStreamerRequest req, final StreamReceiver<K, V> updater, final Object topic) {
final boolean allowOverwrite = !(updater instanceof DataStreamerImpl.IsolatedUpdater);
try {
GridCacheAdapter cache = ctx.cache().internalCache(req.cacheName());
if (cache == null)
throw new IgniteCheckedException("Cache not created or already destroyed.");
GridCacheContext cctx = cache.context();
DataStreamerUpdateJob job = null;
GridFutureAdapter waitFut = null;
if (!allowOverwrite)
cctx.topology().readLock();
GridDhtTopologyFuture topWaitFut = null;
try {
GridDhtTopologyFuture fut = cctx.topologyVersionFuture();
AffinityTopologyVersion topVer = fut.topologyVersion();
if (!allowOverwrite && !topVer.equals(req.topologyVersion())) {
Exception err = new IgniteCheckedException("DataStreamer will retry data transfer at stable topology " + "[reqTop=" + req.topologyVersion() + ", topVer=" + topVer + ", node=remote]");
sendResponse(nodeId, topic, req.requestId(), err, req.forceLocalDeployment());
} else if (allowOverwrite || fut.isDone()) {
job = new DataStreamerUpdateJob(ctx, log, req.cacheName(), req.entries(), req.ignoreDeploymentOwnership(), req.skipStore(), req.keepBinary(), updater);
waitFut = allowOverwrite ? null : cctx.mvcc().addDataStreamerFuture(topVer);
} else
topWaitFut = fut;
} finally {
if (!allowOverwrite)
cctx.topology().readUnlock();
}
if (topWaitFut != null) {
// Need call 'listen' after topology read lock is released.
topWaitFut.listen(new IgniteInClosure<IgniteInternalFuture<AffinityTopologyVersion>>() {
@Override
public void apply(IgniteInternalFuture<AffinityTopologyVersion> e) {
localUpdate(nodeId, req, updater, topic);
}
});
return;
}
if (job != null) {
try {
job.call();
sendResponse(nodeId, topic, req.requestId(), null, req.forceLocalDeployment());
} finally {
if (waitFut != null)
waitFut.onDone();
}
}
} catch (Throwable e) {
sendResponse(nodeId, topic, req.requestId(), e, req.forceLocalDeployment());
if (e instanceof Error)
throw (Error) e;
}
}
use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.
the class DataStreamerImpl method addData.
/** {@inheritDoc} */
@Override
public IgniteFuture<?> addData(Collection<? extends Map.Entry<K, V>> entries) {
A.notEmpty(entries, "entries");
checkSecurityPermission(SecurityPermission.CACHE_PUT);
enterBusy();
try {
GridFutureAdapter<Object> resFut = new GridFutureAdapter<>();
resFut.listen(rmvActiveFut);
activeFuts.add(resFut);
Collection<KeyCacheObjectWrapper> keys = new GridConcurrentHashSet<>(entries.size(), U.capacity(entries.size()), 1);
Collection<DataStreamerEntry> entries0 = new ArrayList<>(entries.size());
for (Map.Entry<K, V> entry : entries) {
KeyCacheObject key = cacheObjProc.toCacheKeyObject(cacheObjCtx, null, entry.getKey(), true);
CacheObject val = cacheObjProc.toCacheObject(cacheObjCtx, entry.getValue(), true);
keys.add(new KeyCacheObjectWrapper(key));
entries0.add(new DataStreamerEntry(key, val));
}
load0(entries0, resFut, keys, 0);
return new IgniteCacheFutureImpl<>(resFut);
} catch (IgniteDataStreamerTimeoutException e) {
throw e;
} catch (IgniteException e) {
return new IgniteFinishedFutureImpl<>(e);
} finally {
leaveBusy();
}
}
use of org.apache.ignite.internal.util.future.GridFutureAdapter 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.future.GridFutureAdapter in project ignite by apache.
the class ClientImpl method pingNode.
/** {@inheritDoc} */
@Override
public boolean pingNode(@NotNull final UUID nodeId) {
if (nodeId.equals(getLocalNodeId()))
return true;
TcpDiscoveryNode node = rmtNodes.get(nodeId);
if (node == null || !node.visible())
return false;
GridFutureAdapter<Boolean> fut = pingFuts.get(nodeId);
if (fut == null) {
fut = new GridFutureAdapter<>();
GridFutureAdapter<Boolean> oldFut = pingFuts.putIfAbsent(nodeId, fut);
if (oldFut != null)
fut = oldFut;
else {
State state = this.state;
if (spi.getSpiContext().isStopping() || state == STOPPED || state == SEGMENTED) {
if (pingFuts.remove(nodeId, fut))
fut.onDone(false);
return false;
} else if (state == DISCONNECTED) {
if (pingFuts.remove(nodeId, fut))
fut.onDone(new IgniteClientDisconnectedCheckedException(null, "Failed to ping node, client node disconnected."));
} else {
final GridFutureAdapter<Boolean> finalFut = fut;
timer.schedule(new TimerTask() {
@Override
public void run() {
if (pingFuts.remove(nodeId, finalFut)) {
if (ClientImpl.this.state == DISCONNECTED)
finalFut.onDone(new IgniteClientDisconnectedCheckedException(null, "Failed to ping node, client node disconnected."));
else
finalFut.onDone(false);
}
}
}, spi.netTimeout);
sockWriter.sendMessage(new TcpDiscoveryClientPingRequest(getLocalNodeId(), nodeId));
}
}
}
try {
return fut.get();
} catch (IgniteInterruptedCheckedException ignored) {
return false;
} catch (IgniteCheckedException e) {
throw new IgniteSpiException(e);
}
}
Aggregations