use of org.apache.ignite.lang.IgniteInClosure in project ignite by apache.
the class GridDiscoveryManager method start.
/** {@inheritDoc} */
@Override
public void start(boolean activeOnStart) throws IgniteCheckedException {
long totSysMemory = -1;
try {
totSysMemory = U.<Long>property(os, "totalPhysicalMemorySize");
} catch (RuntimeException ignored) {
// No-op.
}
ctx.addNodeAttribute(IgniteNodeAttributes.ATTR_PHY_RAM, totSysMemory);
DiscoverySpi spi = getSpi();
discoOrdered = discoOrdered();
histSupported = historySupported();
isLocDaemon = ctx.isDaemon();
hasRslvrs = !ctx.config().isClientMode() && !F.isEmpty(ctx.config().getSegmentationResolvers());
segChkFreq = ctx.config().getSegmentCheckFrequency();
if (hasRslvrs) {
if (segChkFreq < 0)
throw new IgniteCheckedException("Segment check frequency cannot be negative: " + segChkFreq);
if (segChkFreq > 0 && segChkFreq < 2000)
U.warn(log, "Configuration parameter 'segmentCheckFrequency' is too low " + "(at least 2000 ms recommended): " + segChkFreq);
int segResAttemp = ctx.config().getSegmentationResolveAttempts();
if (segResAttemp < 1)
throw new IgniteCheckedException("Segment resolve attempts cannot be negative or zero: " + segResAttemp);
checkSegmentOnStart();
}
metricsUpdateTask = ctx.timeout().schedule(new MetricsUpdater(), METRICS_UPDATE_FREQ, METRICS_UPDATE_FREQ);
spi.setMetricsProvider(createMetricsProvider());
if (ctx.security().enabled()) {
if (isSecurityCompatibilityMode())
ctx.addNodeAttribute(ATTR_SECURITY_COMPATIBILITY_MODE, true);
spi.setAuthenticator(new DiscoverySpiNodeAuthenticator() {
@Override
public SecurityContext authenticateNode(ClusterNode node, SecurityCredentials cred) {
try {
return ctx.security().authenticateNode(node, cred);
} catch (IgniteCheckedException e) {
throw U.convertException(e);
}
}
@Override
public boolean isGlobalNodeAuthentication() {
return ctx.security().isGlobalNodeAuthentication();
}
});
}
spi.setListener(new DiscoverySpiListener() {
private long gridStartTime;
/** {@inheritDoc} */
@Override
public void onLocalNodeInitialized(ClusterNode locNode) {
for (IgniteInClosure<ClusterNode> lsnr : localNodeInitLsnrs) lsnr.apply(locNode);
}
@Override
public void onDiscovery(final int type, final long topVer, final ClusterNode node, final Collection<ClusterNode> topSnapshot, final Map<Long, Collection<ClusterNode>> snapshots, @Nullable DiscoverySpiCustomMessage spiCustomMsg) {
DiscoveryCustomMessage customMsg = spiCustomMsg == null ? null : ((CustomMessageWrapper) spiCustomMsg).delegate();
if (skipMessage(type, customMsg))
return;
final ClusterNode locNode = localNode();
if (snapshots != null)
topHist = snapshots;
boolean verChanged;
if (type == EVT_NODE_METRICS_UPDATED)
verChanged = false;
else {
if (type != EVT_NODE_SEGMENTED && type != EVT_CLIENT_NODE_DISCONNECTED && type != EVT_CLIENT_NODE_RECONNECTED && type != DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) {
minorTopVer = 0;
verChanged = true;
} else
verChanged = false;
}
if (type == EVT_NODE_FAILED || type == EVT_NODE_LEFT) {
for (DiscoCache c : discoCacheHist.values()) c.updateAlives(node);
updateClientNodes(node.id());
}
final AffinityTopologyVersion nextTopVer;
if (type == DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) {
assert customMsg != null;
boolean incMinorTopVer = ctx.cache().onCustomEvent(customMsg, new AffinityTopologyVersion(topVer, minorTopVer));
if (incMinorTopVer) {
minorTopVer++;
verChanged = true;
}
nextTopVer = new AffinityTopologyVersion(topVer, minorTopVer);
if (verChanged)
ctx.cache().onDiscoveryEvent(type, node, nextTopVer);
} else {
nextTopVer = new AffinityTopologyVersion(topVer, minorTopVer);
ctx.cache().onDiscoveryEvent(type, node, nextTopVer);
}
if (type == DiscoveryCustomEvent.EVT_DISCOVERY_CUSTOM_EVT) {
for (Class cls = customMsg.getClass(); cls != null; cls = cls.getSuperclass()) {
List<CustomEventListener<DiscoveryCustomMessage>> list = customEvtLsnrs.get(cls);
if (list != null) {
for (CustomEventListener<DiscoveryCustomMessage> lsnr : list) {
try {
lsnr.onCustomEvent(nextTopVer, node, customMsg);
} catch (Exception e) {
U.error(log, "Failed to notify direct custom event listener: " + customMsg, e);
}
}
}
}
}
final DiscoCache discoCache;
// event notifications, since SPI notifies manager about all events from this listener.
if (verChanged) {
discoCache = createDiscoCache(locNode, topSnapshot);
discoCacheHist.put(nextTopVer, discoCache);
boolean set = updateTopologyVersionIfGreater(nextTopVer, discoCache);
assert set || topVer == 0 : "Topology version has not been updated [this.topVer=" + topSnap + ", topVer=" + topVer + ", node=" + node + ", evt=" + U.gridEventName(type) + ']';
} else
// Current version.
discoCache = discoCache();
// If this is a local join event, just save it and do not notify listeners.
if (type == EVT_NODE_JOINED && node.id().equals(locNode.id())) {
if (gridStartTime == 0)
gridStartTime = getSpi().getGridStartTime();
updateTopologyVersionIfGreater(new AffinityTopologyVersion(locNode.order()), discoCache);
startLatch.countDown();
DiscoveryEvent discoEvt = new DiscoveryEvent();
discoEvt.node(ctx.discovery().localNode());
discoEvt.eventNode(node);
discoEvt.type(EVT_NODE_JOINED);
discoEvt.topologySnapshot(topVer, new ArrayList<>(F.view(topSnapshot, FILTER_DAEMON)));
locJoin.onDone(new T2<>(discoEvt, discoCache));
return;
} else if (type == EVT_CLIENT_NODE_DISCONNECTED) {
assert locNode.isClient() : locNode;
assert node.isClient() : node;
((IgniteKernal) ctx.grid()).onDisconnected();
locJoin = new GridFutureAdapter<>();
registeredCaches.clear();
for (AffinityTopologyVersion histVer : discoCacheHist.keySet()) {
Object rmvd = discoCacheHist.remove(histVer);
assert rmvd != null : histVer;
}
topHist.clear();
topSnap.set(new Snapshot(AffinityTopologyVersion.ZERO, createDiscoCache(locNode, Collections.<ClusterNode>emptySet())));
} else if (type == EVT_CLIENT_NODE_RECONNECTED) {
assert locNode.isClient() : locNode;
assert node.isClient() : node;
boolean clusterRestarted = gridStartTime != getSpi().getGridStartTime();
gridStartTime = getSpi().getGridStartTime();
((IgniteKernal) ctx.grid()).onReconnected(clusterRestarted);
ctx.cluster().clientReconnectFuture().listen(new CI1<IgniteFuture<?>>() {
@Override
public void apply(IgniteFuture<?> fut) {
try {
fut.get();
discoWrk.addEvent(type, nextTopVer, node, discoCache, topSnapshot, null);
} catch (IgniteException ignore) {
// No-op.
}
}
});
return;
}
if (type == EVT_CLIENT_NODE_DISCONNECTED || type == EVT_NODE_SEGMENTED || !ctx.clientDisconnected())
discoWrk.addEvent(type, nextTopVer, node, discoCache, topSnapshot, customMsg);
}
});
spi.setDataExchange(new DiscoverySpiDataExchange() {
@Override
public DiscoveryDataBag collect(DiscoveryDataBag dataBag) {
assert dataBag != null;
assert dataBag.joiningNodeId() != null;
if (ctx.localNodeId().equals(dataBag.joiningNodeId())) {
for (GridComponent c : ctx.components()) c.collectJoiningNodeData(dataBag);
} else {
for (GridComponent c : ctx.components()) c.collectGridNodeData(dataBag);
}
return dataBag;
}
@Override
public void onExchange(DiscoveryDataBag dataBag) {
if (ctx.localNodeId().equals(dataBag.joiningNodeId())) {
//NodeAdded msg reached joining node after round-trip over the ring
for (GridComponent c : ctx.components()) {
if (c.discoveryDataType() != null)
c.onGridDataReceived(dataBag.gridDiscoveryData(c.discoveryDataType().ordinal()));
}
} else {
//discovery data from newly joined node has to be applied to the current old node
for (GridComponent c : ctx.components()) {
if (c.discoveryDataType() != null) {
JoiningNodeDiscoveryData data = dataBag.newJoinerDiscoveryData(c.discoveryDataType().ordinal());
if (data != null)
c.onJoiningNodeDataReceived(data);
}
}
}
}
});
startSpi();
registeredDiscoSpi = true;
try {
U.await(startLatch);
} catch (IgniteInterruptedException e) {
throw new IgniteCheckedException("Failed to start discovery manager (thread has been interrupted).", e);
}
// Start segment check worker only if frequency is greater than 0.
if (hasRslvrs && segChkFreq > 0) {
segChkWrk = new SegmentCheckWorker();
segChkThread = new IgniteThread(segChkWrk);
segChkThread.start();
}
locNode = spi.getLocalNode();
checkAttributes(discoCache().remoteNodes());
ctx.service().initCompatibilityMode(discoCache().remoteNodes());
// Start discovery worker.
new IgniteThread(discoWrk).start();
if (log.isDebugEnabled())
log.debug(startInfo());
}
use of org.apache.ignite.lang.IgniteInClosure 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();
}
}
use of org.apache.ignite.lang.IgniteInClosure in project ignite by apache.
the class ClusterCachesInfo method processCacheChangeRequests.
/**
* @param exchangeActions Exchange actions to update.
* @param reqs Requests.
* @param topVer Topology version.
* @param persistedCfgs {@code True} if process start of persisted caches during cluster activation.
* @return Process result.
*/
private CacheChangeProcessResult processCacheChangeRequests(ExchangeActions exchangeActions, Collection<DynamicCacheChangeRequest> reqs, AffinityTopologyVersion topVer, boolean persistedCfgs) {
CacheChangeProcessResult res = new CacheChangeProcessResult();
final List<T2<DynamicCacheChangeRequest, AffinityTopologyVersion>> reqsToComplete = new ArrayList<>();
for (DynamicCacheChangeRequest req : reqs) processCacheChangeRequest0(req, exchangeActions, topVer, persistedCfgs, res, reqsToComplete);
if (!F.isEmpty(res.addedDescs)) {
AffinityTopologyVersion startTopVer = res.needExchange ? topVer.nextMinorVersion() : topVer;
for (DynamicCacheDescriptor desc : res.addedDescs) {
assert desc.template() || res.needExchange;
desc.startTopologyVersion(startTopVer);
}
}
if (!F.isEmpty(reqsToComplete)) {
ctx.closure().callLocalSafe(new GridPlainCallable<Void>() {
@Override
public Void call() {
for (T2<DynamicCacheChangeRequest, AffinityTopologyVersion> t : reqsToComplete) {
final DynamicCacheChangeRequest req = t.get1();
AffinityTopologyVersion waitTopVer = t.get2();
IgniteInternalFuture<?> fut = waitTopVer != null ? ctx.cache().context().exchange().affinityReadyFuture(waitTopVer) : null;
if (fut == null || fut.isDone())
ctx.cache().completeCacheStartFuture(req, false, null);
else {
fut.listen(new IgniteInClosure<IgniteInternalFuture<?>>() {
@Override
public void apply(IgniteInternalFuture<?> fut) {
ctx.cache().completeCacheStartFuture(req, false, null);
}
});
}
}
return null;
}
});
}
return res;
}
use of org.apache.ignite.lang.IgniteInClosure in project ignite by apache.
the class GridNearTxLocal method chainFinishFuture.
/**
* @param fut Already started finish future.
* @param commit Commit flag.
* @param clearThreadMap Clear thread map.
* @return Finish future.
*/
private IgniteInternalFuture<IgniteInternalTx> chainFinishFuture(final NearTxFinishFuture fut, final boolean commit, final boolean clearThreadMap, final boolean onTimeout) {
assert fut != null;
if (fut.commit() != commit) {
final GridNearTxLocal tx = this;
if (!commit) {
final GridNearTxFinishFuture rollbackFut = new GridNearTxFinishFuture<>(cctx, this, false);
fut.listen(new IgniteInClosure<IgniteInternalFuture<IgniteInternalTx>>() {
@Override
public void apply(IgniteInternalFuture<IgniteInternalTx> fut0) {
if (FINISH_FUT_UPD.compareAndSet(tx, fut, rollbackFut)) {
switch(tx.state()) {
case COMMITTED:
if (log.isDebugEnabled())
log.debug("Failed to rollback, transaction is already committed: " + tx);
case ROLLED_BACK:
rollbackFut.forceFinish();
assert rollbackFut.isDone() : rollbackFut;
break;
default:
// First finish attempt was unsuccessful. Try again.
rollbackFut.finish(false, clearThreadMap, onTimeout);
}
} else {
finishFut.listen(new IgniteInClosure<IgniteInternalFuture<IgniteInternalTx>>() {
@Override
public void apply(IgniteInternalFuture<IgniteInternalTx> fut) {
try {
fut.get();
rollbackFut.markInitialized();
} catch (IgniteCheckedException e) {
rollbackFut.onDone(e);
}
}
});
}
}
});
return rollbackFut;
} else {
final GridFutureAdapter<IgniteInternalTx> fut0 = new GridFutureAdapter<>();
fut.listen(new IgniteInClosure<IgniteInternalFuture<IgniteInternalTx>>() {
@Override
public void apply(IgniteInternalFuture<IgniteInternalTx> fut) {
if (timedOut())
fut0.onDone(new IgniteTxTimeoutCheckedException("Failed to commit transaction, " + "transaction is concurrently rolled back on timeout: " + tx));
else
fut0.onDone(new IgniteTxRollbackCheckedException("Failed to commit transaction, " + "transaction is concurrently rolled back: " + tx));
}
});
return fut0;
}
}
return fut;
}
use of org.apache.ignite.lang.IgniteInClosure in project ignite by apache.
the class AbstractClientCompatibilityTest method testOldClientToCurrentServer.
/**
* @throws Exception If failed.
*/
@Test
public void testOldClientToCurrentServer() throws Exception {
try (Ignite ignite = startGrid(0)) {
initNode(ignite);
if (verFormatted.equals(IgniteVersionUtils.VER_STR))
testClient(verFormatted);
else {
String fileName = IgniteCompatibilityNodeRunner.storeToFile((IgniteInClosure<String>) this::testClient);
GridJavaProcess proc = GridJavaProcess.exec(RemoteClientRunner.class.getName(), IgniteVersionUtils.VER_STR + ' ' + fileName, log, log::info, null, null, getProcessProxyJvmArgs(verFormatted), null);
try {
GridTestUtils.waitForCondition(() -> !proc.getProcess().isAlive(), 5_000L);
assertEquals(0, proc.getProcess().exitValue());
} finally {
if (proc.getProcess().isAlive())
proc.kill();
}
}
}
}
Aggregations