use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.
the class GridTaskCommandHandler method handleAsyncUnsafe.
/**
* @param req Request.
* @return Future.
* @throws IgniteCheckedException On any handling exception.
*/
private IgniteInternalFuture<GridRestResponse> handleAsyncUnsafe(final GridRestRequest req) throws IgniteCheckedException {
assert req instanceof GridRestTaskRequest : "Invalid command for topology handler: " + req;
assert SUPPORTED_COMMANDS.contains(req.command());
if (log.isDebugEnabled())
log.debug("Handling task REST request: " + req);
GridRestTaskRequest req0 = (GridRestTaskRequest) req;
final GridFutureAdapter<GridRestResponse> fut = new GridFutureAdapter<>();
final GridRestResponse res = new GridRestResponse();
final GridClientTaskResultBean taskRestRes = new GridClientTaskResultBean();
// Set ID placeholder for the case it wouldn't be available due to remote execution.
taskRestRes.setId('~' + ctx.localNodeId().toString());
final boolean locExec = req0.destinationId() == null || req0.destinationId().equals(ctx.localNodeId()) || ctx.discovery().node(req0.destinationId()) == null;
switch(req.command()) {
case EXE:
{
final boolean async = req0.async();
final String name = req0.taskName();
if (F.isEmpty(name))
throw new IgniteCheckedException(missingParameter("name"));
final List<Object> params = req0.params();
long timeout = req0.timeout();
final UUID clientId = req.clientId();
final IgniteInternalFuture<Object> taskFut;
if (locExec) {
ctx.task().setThreadContextIfNotNull(TC_SUBJ_ID, clientId);
ctx.task().setThreadContext(TC_TIMEOUT, timeout);
Object arg = !F.isEmpty(params) ? params.size() == 1 ? params.get(0) : params.toArray() : null;
taskFut = ctx.task().execute(name, arg);
} else {
// Using predicate instead of node intentionally
// in order to provide user well-structured EmptyProjectionException.
ClusterGroup prj = ctx.grid().cluster().forPredicate(F.nodeForNodeId(req.destinationId()));
ctx.task().setThreadContext(TC_NO_FAILOVER, true);
taskFut = ctx.closure().callAsync(BALANCE, new ExeCallable(name, params, timeout, clientId), prj.nodes());
}
if (async) {
if (locExec) {
IgniteUuid tid = ((ComputeTaskInternalFuture) taskFut).getTaskSession().getId();
taskDescs.put(tid, new TaskDescriptor(false, null, null));
taskRestRes.setId(tid.toString() + '~' + ctx.localNodeId().toString());
res.setResponse(taskRestRes);
} else
res.setError("Asynchronous task execution is not supported for routing request.");
fut.onDone(res);
}
taskFut.listen(new IgniteInClosure<IgniteInternalFuture<Object>>() {
@Override
public void apply(IgniteInternalFuture<Object> taskFut) {
try {
TaskDescriptor desc;
try {
desc = new TaskDescriptor(true, taskFut.get(), null);
} catch (IgniteCheckedException e) {
if (e.hasCause(ClusterTopologyCheckedException.class, ClusterGroupEmptyCheckedException.class))
U.warn(log, "Failed to execute task due to topology issues (are all mapped " + "nodes alive?) [name=" + name + ", clientId=" + req.clientId() + ", err=" + e + ']');
else {
if (!X.hasCause(e, VisorClusterGroupEmptyException.class))
U.error(log, "Failed to execute task [name=" + name + ", clientId=" + req.clientId() + ']', e);
}
desc = new TaskDescriptor(true, null, e);
}
if (async && locExec) {
assert taskFut instanceof ComputeTaskInternalFuture;
IgniteUuid tid = ((ComputeTaskInternalFuture) taskFut).getTaskSession().getId();
taskDescs.put(tid, desc);
}
if (!async) {
if (desc.error() == null) {
try {
taskRestRes.setFinished(true);
taskRestRes.setResult(desc.result());
res.setResponse(taskRestRes);
fut.onDone(res);
} catch (IgniteException e) {
fut.onDone(new IgniteCheckedException("Failed to marshal task result: " + desc.result(), e));
}
} else
fut.onDone(desc.error());
}
} finally {
if (!async && !fut.isDone())
fut.onDone(new IgniteCheckedException("Failed to execute task (see server logs for details)."));
}
}
});
break;
}
case RESULT:
{
String id = req0.taskId();
if (F.isEmpty(id))
throw new IgniteCheckedException(missingParameter("id"));
StringTokenizer st = new StringTokenizer(id, "~");
if (st.countTokens() != 2)
throw new IgniteCheckedException("Failed to parse id parameter: " + id);
String tidParam = st.nextToken();
String resHolderIdParam = st.nextToken();
taskRestRes.setId(id);
try {
IgniteUuid tid = !F.isEmpty(tidParam) ? IgniteUuid.fromString(tidParam) : null;
UUID resHolderId = !F.isEmpty(resHolderIdParam) ? UUID.fromString(resHolderIdParam) : null;
if (tid == null || resHolderId == null)
throw new IgniteCheckedException("Failed to parse id parameter: " + id);
if (ctx.localNodeId().equals(resHolderId)) {
TaskDescriptor desc = taskDescs.get(tid);
if (desc == null)
throw new IgniteCheckedException("Task with provided id has never been started on provided node" + " [taskId=" + tidParam + ", taskResHolderId=" + resHolderIdParam + ']');
taskRestRes.setFinished(desc.finished());
if (desc.error() != null)
throw new IgniteCheckedException(desc.error().getMessage());
taskRestRes.setResult(desc.result());
res.setResponse(taskRestRes);
} else {
IgniteBiTuple<String, GridTaskResultResponse> t = requestTaskResult(resHolderId, tid);
if (t.get1() != null)
throw new IgniteCheckedException(t.get1());
GridTaskResultResponse taskRes = t.get2();
assert taskRes != null;
if (!taskRes.found())
throw new IgniteCheckedException("Task with provided id has never been started on provided node " + "[taskId=" + tidParam + ", taskResHolderId=" + resHolderIdParam + ']');
taskRestRes.setFinished(taskRes.finished());
if (taskRes.error() != null)
throw new IgniteCheckedException(taskRes.error());
taskRestRes.setResult(taskRes.result());
res.setResponse(taskRestRes);
}
} catch (IllegalArgumentException e) {
String msg = "Failed to parse parameters [taskId=" + tidParam + ", taskResHolderId=" + resHolderIdParam + ", err=" + e.getMessage() + ']';
if (log.isDebugEnabled())
log.debug(msg);
throw new IgniteCheckedException(msg, e);
}
fut.onDone(res);
break;
}
case NOOP:
{
fut.onDone(new GridRestResponse());
break;
}
default:
assert false : "Invalid command for task handler: " + req;
}
if (log.isDebugEnabled())
log.debug("Handled task REST request [res=" + res + ", req=" + req + ']');
return fut;
}
use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.
the class GridCacheCommandHandler method executeCommand.
/**
* Executes command on cache. Checks {@code destId} to find if command could be performed locally or routed to a
* remote node.
*
* @param destId Target node Id for the operation. If {@code null} - operation could be executed anywhere.
* @param clientId Client ID.
* @param cacheName Cache name.
* @param key Key to set affinity mapping in the response.
* @param op Operation to perform.
* @return Operation result in future.
* @throws IgniteCheckedException If failed
*/
private IgniteInternalFuture<GridRestResponse> executeCommand(@Nullable UUID destId, UUID clientId, final String cacheName, final Object key, final CacheCommand op) throws IgniteCheckedException {
final boolean locExec = destId == null || destId.equals(ctx.localNodeId()) || ctx.cache().cache(cacheName) != null;
if (locExec) {
final IgniteInternalCache<Object, Object> cache = localCache(cacheName).forSubjectId(clientId);
return op.apply(cache, ctx).chain(resultWrapper(cache, key));
} else {
ClusterGroup prj = ctx.grid().cluster().forPredicate(F.nodeForNodeId(destId));
ctx.task().setThreadContext(TC_NO_FAILOVER, true);
return ctx.closure().callAsync(BALANCE, new CacheOperationCallable(clientId, cacheName, op, key), prj.nodes());
}
}
use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.
the class ServicePredicateAccessCacheTest method testPredicateAccessCache.
/**
* @throws Exception If failed.
*/
public void testPredicateAccessCache() throws Exception {
final Ignite ignite0 = startGrid(0);
ignite0.getOrCreateCache(new CacheConfiguration<>(DEFAULT_CACHE_NAME).setName("testCache").setAtomicityMode(ATOMIC).setCacheMode(REPLICATED).setWriteSynchronizationMode(FULL_SYNC));
latch = new CountDownLatch(1);
final ClusterGroup grp = ignite0.cluster().forPredicate(new IgnitePredicate<ClusterNode>() {
@Override
public boolean apply(ClusterNode node) {
System.out.println("Predicated started [thread=" + Thread.currentThread().getName() + ']');
latch.countDown();
try {
Thread.sleep(3000);
} catch (InterruptedException ignore) {
// No-op.
}
System.out.println("Call contains key [thread=" + Thread.currentThread().getName() + ']');
boolean ret = Ignition.localIgnite().cache("testCache").containsKey(node.id().toString());
System.out.println("After contains key [ret=" + ret + ", thread=" + Thread.currentThread().getName() + ']');
return ret;
}
});
IgniteInternalFuture<?> fut = GridTestUtils.runAsync(new Callable<Void>() {
@Override
public Void call() throws Exception {
info("Start deploy service.");
ignite0.services(grp).deployNodeSingleton("testService", new TestService());
info("Service deployed.");
return null;
}
}, "deploy-thread");
latch.await();
startGrid(1);
fut.get();
}
use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.
the class IgniteMessagingConfigVariationFullApiTest method clientClientOrderedMessage.
/**
* @throws Exception If fail.
*/
private void clientClientOrderedMessage() throws Exception {
Ignite ignite = grid(CLIENT_NODE_IDX);
ClusterGroup grp = ignite.cluster().forClients();
assert grp.nodes().size() > 0;
registerListenerAndSendOrderedMessages(ignite, grp);
}
use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.
the class IgniteMessagingConfigVariationFullApiTest method collectionMessage.
/**
* @throws Exception If fail.
*/
private void collectionMessage() throws Exception {
Ignite ignite = grid(SERVER_NODE_IDX);
ClusterGroup grp = gridCount() > 1 ? ignite.cluster().forRemotes() : ignite.cluster().forLocal();
assert grp.nodes().size() > 0;
int messages = MSGS;
LATCH = new CountDownLatch(grp.nodes().size() * messages);
UUID opId = ignite.message(grp).remoteListen(MESSAGE_TOPIC, new MessageListener());
try {
List<Object> msgs = new ArrayList<>();
for (int i = 0; i < messages; i++) msgs.add(value(i));
ignite.message(grp).send(MESSAGE_TOPIC, msgs);
assertTrue(LATCH.await(10, TimeUnit.SECONDS));
} finally {
ignite.message().stopRemoteListen(opId);
}
}
Aggregations