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;
}
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();
}
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);
}
}
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;
}
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;
}
Aggregations