use of org.apache.ignite.internal.processors.rest.GridRestResponse 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 IgniteInternalFuture<Object> taskFut;
if (locExec) {
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), 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.processors.rest.GridRestResponse in project ignite by apache.
the class GridCacheCommandHandler method handleAsync.
/**
* {@inheritDoc}
*/
@Override
public IgniteInternalFuture<GridRestResponse> handleAsync(final GridRestRequest req) {
assert req instanceof GridRestCacheRequest : "Invalid command for topology handler: " + req;
assert SUPPORTED_COMMANDS.contains(req.command());
if (log.isDebugEnabled())
log.debug("Handling cache REST request: " + req);
GridRestCacheRequest req0 = (GridRestCacheRequest) req;
final Object key = req0.key();
final Set<GridClientCacheFlag> cacheFlags = GridClientCacheFlag.parseCacheFlags(req0.cacheFlags());
try {
GridRestCommand cmd = req0.command();
if (req0.cacheName() == null && !CACHE_NAME_NOT_REQUIRED_REQUESTS.contains(cmd))
throw new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("cacheName"));
if (key == null && KEY_REQUIRED_REQUESTS.contains(cmd))
throw new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("key"));
final Long ttl = req0.ttl();
IgniteInternalFuture<GridRestResponse> fut;
switch(cmd) {
case DESTROY_CACHE:
{
// Do not check thread tx here since there can be active system cache txs.
fut = ((IgniteKernal) ctx.grid()).destroyCacheAsync(req0.cacheName(), false, false).chain(new CX1<IgniteInternalFuture<?>, GridRestResponse>() {
@Override
public GridRestResponse applyx(IgniteInternalFuture<?> f) throws IgniteCheckedException {
f.get();
return new GridRestResponse(null);
}
});
break;
}
case GET_OR_CREATE_CACHE:
{
String templateName = req0.templateName();
if (F.isEmpty(templateName))
templateName = TEMPLATE_PARTITIONED;
CacheConfigurationOverride cfgOverride = req0.configuration();
boolean dfltPartTemplate = F.isEmpty(templateName) || TEMPLATE_PARTITIONED.equalsIgnoreCase(templateName);
boolean dfltReplTemplate = TEMPLATE_REPLICATED.equalsIgnoreCase(templateName);
if (dfltPartTemplate || dfltReplTemplate) {
if (cfgOverride == null)
cfgOverride = new CacheConfigurationOverride();
cfgOverride.mode(dfltPartTemplate ? PARTITIONED : REPLICATED);
if (cfgOverride.writeSynchronizationMode() == null)
cfgOverride.writeSynchronizationMode(FULL_SYNC);
}
// Do not check thread tx here since there can be active system cache txs.
fut = ((IgniteKernal) ctx.grid()).getOrCreateCacheAsync(req0.cacheName(), templateName, cfgOverride, false).chain(new CX1<IgniteInternalFuture<?>, GridRestResponse>() {
@Override
public GridRestResponse applyx(IgniteInternalFuture<?> f) throws IgniteCheckedException {
f.get();
return new GridRestResponse(null);
}
});
break;
}
case CACHE_METADATA:
{
fut = ctx.task().execute(MetadataTask.class, req0.cacheName());
break;
}
case CACHE_CONTAINS_KEYS:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new ContainsKeysCommand(getKeys(req0)));
break;
}
case CACHE_CONTAINS_KEY:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new ContainsKeyCommand(key));
break;
}
case CACHE_GET:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new GetCommand(key));
break;
}
case CACHE_GET_AND_PUT:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new GetAndPutCommand(key, getValue(req0)));
break;
}
case CACHE_GET_AND_REPLACE:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new GetAndReplaceCommand(key, getValue(req0)));
break;
}
case CACHE_GET_AND_PUT_IF_ABSENT:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new GetAndPutIfAbsentCommand(key, getValue(req0)));
break;
}
case CACHE_PUT_IF_ABSENT:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new PutIfAbsentCommand(key, ttl, getValue(req0)));
break;
}
case CACHE_GET_ALL:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new GetAllCommand(getKeys(req0)));
break;
}
case CACHE_PUT:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new PutCommand(key, ttl, getValue(req0)));
break;
}
case CACHE_ADD:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new AddCommand(key, ttl, getValue(req0)));
break;
}
case CACHE_PUT_ALL:
{
Map<Object, Object> map = req0.values();
if (F.isEmpty(map))
throw new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("values"));
for (Map.Entry<Object, Object> e : map.entrySet()) {
if (e.getKey() == null)
throw new IgniteCheckedException("Failing putAll operation (null keys are not allowed).");
if (e.getValue() == null)
throw new IgniteCheckedException("Failing putAll operation (null values are not allowed).");
}
// HashMap wrapping for correct serialization
map = new HashMap<>(map);
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new PutAllCommand(map));
break;
}
case CACHE_REMOVE:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new RemoveCommand(key));
break;
}
case CACHE_REMOVE_VALUE:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new RemoveValueCommand(key, getValue(req0)));
break;
}
case CACHE_REPLACE_VALUE:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new ReplaceValueCommand(key, getValue(req0), req0.value2()));
break;
}
case CACHE_GET_AND_REMOVE:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new GetAndRemoveCommand(key));
break;
}
case CACHE_REMOVE_ALL:
{
Map<Object, Object> map = req0.values();
// HashSet wrapping for correct serialization
Set<Object> keys = map == null ? null : new HashSet<>(map.keySet());
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new RemoveAllCommand(keys));
break;
}
case CACHE_CLEAR:
{
Set<Object> cacheNames = getKeys(req0);
GridCompoundFuture compFut = new GridCompoundFuture();
for (Object cName : cacheNames) compFut.add(executeCommand(req.destinationId(), (String) cName, cacheFlags, key, new RemoveAllCommand(null)));
compFut.markInitialized();
fut = compFut.chain(new CX1<GridCompoundFuture<GridCacheRestResponse, ?>, GridRestResponse>() {
@Override
public GridRestResponse applyx(GridCompoundFuture<GridCacheRestResponse, ?> cf) throws IgniteCheckedException {
boolean success = true;
for (IgniteInternalFuture<GridCacheRestResponse> f : cf.futures()) if (!((Boolean) f.get().getResponse()))
success = false;
GridCacheRestResponse resp = new GridCacheRestResponse();
if (success)
resp.setResponse(true);
else
resp.setResponse(false);
return resp;
}
});
break;
}
case CACHE_REPLACE:
{
final Object val = req0.value();
if (val == null)
throw new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("val"));
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new ReplaceCommand(key, ttl, val));
break;
}
case CACHE_CAS:
{
final Object val1 = req0.value();
final Object val2 = req0.value2();
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new CasCommand(val2, val1, key));
break;
}
case CACHE_APPEND:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new AppendCommand(key, req0));
break;
}
case CACHE_PREPEND:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), cacheFlags, key, new PrependCommand(key, req0));
break;
}
case CACHE_METRICS:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), key, new MetricsCommand());
break;
}
case CACHE_SIZE:
{
fut = executeCommand(req.destinationId(), req0.cacheName(), key, new SizeCommand());
break;
}
case CACHE_UPDATE_TLL:
{
if (ttl == null)
throw new IgniteCheckedException(GridRestCommandHandlerAdapter.missingParameter("ttl"));
fut = executeCommand(req.destinationId(), req0.cacheName(), key, new UpdateTllCommand(key, ttl));
break;
}
default:
throw new IllegalArgumentException("Invalid command for cache handler: " + req);
}
return fut;
} catch (IgniteException | IgniteCheckedException e) {
U.error(log, "Failed to execute cache command: " + req, e);
return new GridFinishedFuture<>(e);
} finally {
if (log.isDebugEnabled())
log.debug("Handled cache REST request: " + req);
}
}
use of org.apache.ignite.internal.processors.rest.GridRestResponse in project ignite by apache.
the class GridChangeClusterStateCommandHandler method handleAsync.
/**
* {@inheritDoc}
*/
@Override
public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest restReq) {
GridRestClusterStateRequest req = (GridRestClusterStateRequest) restReq;
final GridFutureAdapter<GridRestResponse> fut = new GridFutureAdapter<>();
final GridRestResponse res = new GridRestResponse();
try {
switch(req.command()) {
case CLUSTER_STATE:
assert req.isReqCurrentMode() : req;
res.setResponse(ctx.grid().cluster().state());
break;
default:
assert req.state() != null : req;
U.log(log, "Received cluster state change request to " + req.state() + " state from client node with ID: " + req.clientId());
ctx.state().changeGlobalState(req.state(), req.forceDeactivation(), ctx.cluster().get().forServers().nodes(), false).get();
res.setResponse(req.command().key() + " done");
break;
}
fut.onDone(res);
} catch (Exception e) {
res.setError(errorMessage(e));
fut.onDone(res);
}
return fut;
}
use of org.apache.ignite.internal.processors.rest.GridRestResponse in project ignite by apache.
the class GridClusterNameCommandHandler method handleAsync.
/**
* {@inheritDoc}
*/
@Override
public IgniteInternalFuture<GridRestResponse> handleAsync(GridRestRequest restReq) {
assert restReq instanceof GridRestClusterNameRequest : restReq;
final GridFutureAdapter<GridRestResponse> fut = new GridFutureAdapter<>();
final GridRestResponse res = new GridRestResponse();
try {
res.setResponse(ctx.cluster().clusterName());
fut.onDone(res);
} catch (Exception e) {
res.setError(errorMessage(e));
fut.onDone(res);
}
return fut;
}
use of org.apache.ignite.internal.processors.rest.GridRestResponse 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 {
switch(req.command()) {
case CLUSTER_CURRENT_STATE:
Boolean currentState = ctx.state().publicApiActiveState(false);
res.setResponse(currentState);
break;
case CLUSTER_ACTIVE:
case CLUSTER_INACTIVE:
log.warning(req.command().key() + " is deprecated. Use newer commands.");
default:
ctx.state().changeGlobalState(req.active() ? ACTIVE : INACTIVE, req.forceDeactivation(), ctx.cluster().get().forServers().nodes(), false).get();
res.setResponse(req.command().key() + " started");
break;
}
fut.onDone(res);
} catch (Exception e) {
res.setError(errorMessage(e));
fut.onDone(res);
}
return fut;
}
Aggregations