Search in sources :

Example 6 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class GridCachePartitionExchangeManager method forceRebalance.

/**
     * Forces preload exchange.
     *
     * @param exchFut Exchange future.
     */
public IgniteInternalFuture<Boolean> forceRebalance(GridDhtPartitionsExchangeFuture exchFut) {
    GridFutureAdapter<Boolean> fut = new GridFutureAdapter<>();
    exchWorker.addExchangeFuture(new GridDhtPartitionsExchangeFuture(cctx, exchFut.discoveryEvent(), exchFut.exchangeId(), fut));
    return fut;
}
Also used : GridDhtPartitionsExchangeFuture(org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionsExchangeFuture) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 7 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class GridCacheQueryManager method queryResult.

/**
     * @param qryInfo Info.
     * @param taskName Task name.
     * @return Iterator.
     * @throws IgniteCheckedException In case of error.
     */
@Nullable
private QueryResult<K, V> queryResult(final GridCacheQueryInfo qryInfo, String taskName) throws IgniteCheckedException {
    assert qryInfo != null;
    final UUID sndId = qryInfo.senderId();
    assert sndId != null;
    RequestFutureMap futs = qryIters.get(sndId);
    if (futs == null) {
        futs = new RequestFutureMap() {

            @Override
            protected boolean removeEldestEntry(Map.Entry<Long, GridFutureAdapter<QueryResult<K, V>>> e) {
                boolean rmv = size() > maxIterCnt;
                if (rmv) {
                    try {
                        e.getValue().get().closeIfNotShared(recipient(sndId, e.getKey()));
                    } catch (IgniteCheckedException ex) {
                        U.error(log, "Failed to close query iterator.", ex);
                    }
                }
                return rmv;
            }
        };
        RequestFutureMap old = qryIters.putIfAbsent(sndId, futs);
        if (old != null)
            futs = old;
    }
    assert futs != null;
    GridFutureAdapter<QueryResult<K, V>> fut;
    boolean exec = false;
    synchronized (futs) {
        if (futs.isCanceled(qryInfo.requestId()))
            return null;
        fut = futs.get(qryInfo.requestId());
        if (fut == null) {
            futs.put(qryInfo.requestId(), fut = new GridFutureAdapter<>());
            exec = true;
        }
    }
    if (exec) {
        try {
            fut.onDone(executeQuery(qryInfo.query(), qryInfo.arguments(), false, qryInfo.query().subjectId(), taskName, recipient(qryInfo.senderId(), qryInfo.requestId())));
        } catch (Throwable e) {
            fut.onDone(e);
            if (e instanceof Error)
                throw (Error) e;
        }
    }
    return fut.get();
}
Also used : IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) UUID(java.util.UUID) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) GridLeanMap(org.apache.ignite.internal.util.GridLeanMap) Nullable(org.jetbrains.annotations.Nullable)

Example 8 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class IgfsIpcHandler method handleAsync.

/** {@inheritDoc} */
@Override
public IgniteInternalFuture<IgfsMessage> handleAsync(final IgfsClientSession ses, final IgfsMessage msg, final DataInput in) {
    try {
        // Even if will be closed right after this call, response write error will be ignored.
        if (stopping)
            return null;
        final IgfsIpcCommand cmd = msg.command();
        IgniteInternalFuture<IgfsMessage> fut;
        switch(cmd) {
            // Execute not-blocking command synchronously in worker thread.
            case WRITE_BLOCK:
            case MAKE_DIRECTORIES:
            case LIST_FILES:
            case LIST_PATHS:
                {
                    fut = executeSynchronously(ses, cmd, msg, in);
                    break;
                }
            // Execute command asynchronously in pool.
            default:
                {
                    try {
                        final GridFutureAdapter<IgfsMessage> fut0 = new GridFutureAdapter<>();
                        pool.execute(new Runnable() {

                            @Override
                            public void run() {
                                try {
                                    fut0.onDone(execute(ses, cmd, msg, in));
                                } catch (Exception e) {
                                    fut0.onDone(e);
                                }
                            }
                        });
                        fut = fut0;
                    } catch (RejectedExecutionException ignored) {
                        fut = executeSynchronously(ses, cmd, msg, in);
                    }
                }
        }
        // Pack result object into response format.
        return fut;
    } catch (Exception e) {
        return new GridFinishedFuture<>(e);
    }
}
Also used : IgfsIpcCommand(org.apache.ignite.internal.igfs.common.IgfsIpcCommand) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) IgfsMessage(org.apache.ignite.internal.igfs.common.IgfsMessage) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) IgfsOutOfSpaceException(org.apache.ignite.igfs.IgfsOutOfSpaceException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) IOException(java.io.IOException) RejectedExecutionException(java.util.concurrent.RejectedExecutionException)

Example 9 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter 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 10 with GridFutureAdapter

use of org.apache.ignite.internal.util.future.GridFutureAdapter in project ignite by apache.

the class GridChangeStateCommandHandler method handleAsync.

/** {@inheritDoc} */
@Override
public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest restRest) {
    GridRestChangeStateRequest req = (GridRestChangeStateRequest) restRest;
    final GridFutureAdapter<GridRestResponse> fut = new GridFutureAdapter<>();
    final GridRestResponse res = new GridRestResponse();
    try {
        if (req.command().equals(CLUSTER_CURRENT_STATE)) {
            Boolean currentState = ctx.state().active();
            res.setResponse(currentState);
        } else
            ctx.state().changeGlobalState(req.active()).get();
        fut.onDone(res);
    } catch (Exception e) {
        SB sb = new SB();
        sb.a(e.getMessage()).a("\n").a("suppressed: \n");
        for (Throwable t : e.getSuppressed()) sb.a(t.getMessage()).a("\n");
        res.setError(sb.toString());
        fut.onDone(res);
    }
    return fut;
}
Also used : GridRestChangeStateRequest(org.apache.ignite.internal.processors.rest.request.GridRestChangeStateRequest) GridFutureAdapter(org.apache.ignite.internal.util.future.GridFutureAdapter) GridRestResponse(org.apache.ignite.internal.processors.rest.GridRestResponse) SB(org.apache.ignite.internal.util.typedef.internal.SB)

Aggregations

GridFutureAdapter (org.apache.ignite.internal.util.future.GridFutureAdapter)30 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)19 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)8 Map (java.util.Map)6 ConcurrentMap (java.util.concurrent.ConcurrentMap)6 HashMap (java.util.HashMap)5 UUID (java.util.UUID)5 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)5 AffinityTopologyVersion (org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion)5 IgniteException (org.apache.ignite.IgniteException)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 ClusterTopologyCheckedException (org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)3 CacheObject (org.apache.ignite.internal.processors.cache.CacheObject)3 KeyCacheObject (org.apache.ignite.internal.processors.cache.KeyCacheObject)3 GridCompoundFuture (org.apache.ignite.internal.util.future.GridCompoundFuture)3 Nullable (org.jetbrains.annotations.Nullable)3 LinkedHashMap (java.util.LinkedHashMap)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 Ignite (org.apache.ignite.Ignite)2