Search in sources :

Example 6 with ClusterGroup

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;
}
Also used : IgniteBiTuple(org.apache.ignite.lang.IgniteBiTuple) ClusterGroup(org.apache.ignite.cluster.ClusterGroup) IgniteInternalFuture(org.apache.ignite.internal.IgniteInternalFuture) GridClientTaskResultBean(org.apache.ignite.internal.processors.rest.client.message.GridClientTaskResultBean) GridRestTaskRequest(org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteUuid(org.apache.ignite.lang.IgniteUuid) IgniteException(org.apache.ignite.IgniteException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) List(java.util.List) UUID(java.util.UUID) ComputeTaskInternalFuture(org.apache.ignite.internal.ComputeTaskInternalFuture) StringTokenizer(java.util.StringTokenizer) ClusterGroupEmptyCheckedException(org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException) GridRestResponse(org.apache.ignite.internal.processors.rest.GridRestResponse) IgniteInClosure(org.apache.ignite.lang.IgniteInClosure) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Example 7 with ClusterGroup

use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.

the class GridCacheCommandHandler method executeCommand.

/**
     * Executes command on flagged cache projection. 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 skipStore Skip store.
     * @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 boolean skipStore, final Object key, final CacheProjectionCommand op) throws IgniteCheckedException {
    final boolean locExec = destId == null || destId.equals(ctx.localNodeId()) || replicatedCacheAvailable(cacheName);
    if (locExec) {
        IgniteInternalCache<?, ?> prj = localCache(cacheName).forSubjectId(clientId).setSkipStore(skipStore);
        return op.apply((IgniteInternalCache<Object, Object>) prj, ctx).chain(resultWrapper((IgniteInternalCache<Object, Object>) prj, key));
    } else {
        ClusterGroup prj = ctx.grid().cluster().forPredicate(F.nodeForNodeId(destId));
        ctx.task().setThreadContext(TC_NO_FAILOVER, true);
        return ctx.closure().callAsync(BALANCE, new FlaggedCacheOperationCallable(clientId, cacheName, skipStore, op, key), prj.nodes());
    }
}
Also used : IgniteInternalCache(org.apache.ignite.internal.processors.cache.IgniteInternalCache) ClusterGroup(org.apache.ignite.cluster.ClusterGroup)

Example 8 with ClusterGroup

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());
    }
}
Also used : ClusterGroup(org.apache.ignite.cluster.ClusterGroup)

Example 9 with ClusterGroup

use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.

the class ClusterGroupSelfTest method testClientServer.

/**
     * @throws Exception If failed.
     */
public void testClientServer() throws Exception {
    ClusterGroup srv = ignite.cluster().forServers();
    assertEquals(2, srv.nodes().size());
    assertTrue(srv.nodes().contains(ignite(0).cluster().localNode()));
    assertTrue(srv.nodes().contains(ignite(1).cluster().localNode()));
    ClusterGroup cli = ignite.cluster().forClients();
    assertEquals(2, srv.nodes().size());
    assertTrue(cli.nodes().contains(ignite(2).cluster().localNode()));
    assertTrue(cli.nodes().contains(ignite(3).cluster().localNode()));
}
Also used : ClusterGroup(org.apache.ignite.cluster.ClusterGroup)

Example 10 with ClusterGroup

use of org.apache.ignite.cluster.ClusterGroup in project ignite by apache.

the class ClusterGroupSelfTest method testOldest.

/**
     * @throws Exception If failed.
     */
public void testOldest() throws Exception {
    ClusterGroup oldest = ignite.cluster().forOldest();
    ClusterNode node = null;
    long minOrder = Long.MAX_VALUE;
    for (ClusterNode n : ignite.cluster().nodes()) {
        if (n.order() < minOrder) {
            node = n;
            minOrder = n.order();
        }
    }
    assertEquals(oldest.node(), ignite.cluster().forNode(node).node());
    ClusterGroup emptyGrp = ignite.cluster().forAttribute("nonExistent", "val");
    assertEquals(0, emptyGrp.forOldest().nodes().size());
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) ClusterGroup(org.apache.ignite.cluster.ClusterGroup)

Aggregations

ClusterGroup (org.apache.ignite.cluster.ClusterGroup)80 Ignite (org.apache.ignite.Ignite)42 UUID (java.util.UUID)21 CountDownLatch (java.util.concurrent.CountDownLatch)16 ClusterNode (org.apache.ignite.cluster.ClusterNode)14 IgniteException (org.apache.ignite.IgniteException)8 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)6 IgniteCompute (org.apache.ignite.IgniteCompute)5 GridConcurrentHashSet (org.apache.ignite.internal.util.GridConcurrentHashSet)5 ArrayList (java.util.ArrayList)4 IgniteConfiguration (org.apache.ignite.configuration.IgniteConfiguration)4 IgniteEx (org.apache.ignite.internal.IgniteEx)4 Map (java.util.Map)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)3 IgniteClusterEx (org.apache.ignite.internal.cluster.IgniteClusterEx)3 GridAbsPredicate (org.apache.ignite.internal.util.lang.GridAbsPredicate)3 List (java.util.List)2 CacheException (javax.cache.CacheException)2 IgniteClientDisconnectedException (org.apache.ignite.IgniteClientDisconnectedException)2 IgniteCluster (org.apache.ignite.IgniteCluster)2