Search in sources :

Example 1 with GridRestTaskRequest

use of org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest 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;
}
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 2 with GridRestTaskRequest

use of org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest in project ignite by apache.

the class GridRestProcessor method interceptRequest.

/**
 * Applies {@link ConnectorMessageInterceptor}
 * from {@link ConnectorConfiguration#getMessageInterceptor()} ()}
 * to all user parameters in the request.
 *
 * @param req Client request.
 */
private void interceptRequest(GridRestRequest req) {
    ConnectorMessageInterceptor interceptor = config().getMessageInterceptor();
    if (interceptor == null)
        return;
    if (req instanceof GridRestCacheRequest) {
        GridRestCacheRequest req0 = (GridRestCacheRequest) req;
        req0.key(interceptor.onReceive(req0.key()));
        req0.value(interceptor.onReceive(req0.value()));
        req0.value2(interceptor.onReceive(req0.value2()));
        Map<Object, Object> oldVals = req0.values();
        if (oldVals != null) {
            Map<Object, Object> newVals = U.newHashMap(oldVals.size());
            for (Map.Entry<Object, Object> e : oldVals.entrySet()) newVals.put(interceptor.onReceive(e.getKey()), interceptor.onReceive(e.getValue()));
            req0.values(U.sealMap(newVals));
        }
    } else if (req instanceof GridRestTaskRequest) {
        GridRestTaskRequest req0 = (GridRestTaskRequest) req;
        List<Object> oldParams = req0.params();
        if (oldParams != null) {
            Collection<Object> newParams = new ArrayList<>(oldParams.size());
            for (Object o : oldParams) newParams.add(interceptor.onReceive(o));
            req0.params(U.sealList(newParams));
        }
    }
}
Also used : GridRestCacheRequest(org.apache.ignite.internal.processors.rest.request.GridRestCacheRequest) GridRestTaskRequest(org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest) ConnectorMessageInterceptor(org.apache.ignite.configuration.ConnectorMessageInterceptor) Collection(java.util.Collection) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) EnumMap(java.util.EnumMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap)

Example 3 with GridRestTaskRequest

use of org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest in project ignite by apache.

the class GridJettyRestHandler method createRequest.

/**
 * Creates REST request.
 *
 * @param cmd Command.
 * @param params Parameters.
 * @param req Servlet request.
 * @return REST request.
 * @throws IgniteCheckedException If creation failed.
 */
@Nullable
private GridRestRequest createRequest(GridRestCommand cmd, Map<String, String> params, HttpServletRequest req) throws IgniteCheckedException {
    GridRestRequest restReq;
    switch(cmd) {
        case GET_OR_CREATE_CACHE:
            {
                GridRestCacheRequest restReq0 = new GridRestCacheRequest();
                restReq0.cacheName(params.get(CACHE_NAME_PARAM));
                String templateName = params.get(TEMPLATE_NAME_PARAM);
                if (!F.isEmpty(templateName))
                    restReq0.templateName(templateName);
                String backups = params.get(BACKUPS_PARAM);
                CacheConfigurationOverride cfg = new CacheConfigurationOverride();
                // Set cache backups.
                if (!F.isEmpty(backups)) {
                    try {
                        cfg.backups(Integer.parseInt(backups));
                    } catch (NumberFormatException e) {
                        throw new IgniteCheckedException("Failed to parse number of cache backups: " + backups, e);
                    }
                }
                // Set cache group name.
                String cacheGrp = params.get(CACHE_GROUP_PARAM);
                if (!F.isEmpty(cacheGrp))
                    cfg.cacheGroup(cacheGrp);
                // Set cache data region name.
                String dataRegion = params.get(DATA_REGION_PARAM);
                if (!F.isEmpty(dataRegion))
                    cfg.dataRegion(dataRegion);
                // Set cache write mode.
                String wrtSyncMode = params.get(WRITE_SYNCHRONIZATION_MODE_PARAM);
                if (!F.isEmpty(wrtSyncMode)) {
                    try {
                        cfg.writeSynchronizationMode(CacheWriteSynchronizationMode.valueOf(wrtSyncMode));
                    } catch (IllegalArgumentException e) {
                        throw new IgniteCheckedException("Failed to parse cache write synchronization mode: " + wrtSyncMode, e);
                    }
                }
                if (!cfg.isEmpty())
                    restReq0.configuration(cfg);
                restReq = restReq0;
                break;
            }
        case DESTROY_CACHE:
            {
                GridRestCacheRequest restReq0 = new GridRestCacheRequest();
                restReq0.cacheName(params.get(CACHE_NAME_PARAM));
                restReq = restReq0;
                break;
            }
        case ATOMIC_DECREMENT:
        case ATOMIC_INCREMENT:
            {
                DataStructuresRequest restReq0 = new DataStructuresRequest();
                restReq0.key(params.get("key"));
                restReq0.initial(longValue("init", params, null));
                restReq0.delta(longValue("delta", params, null));
                restReq = restReq0;
                break;
            }
        case CACHE_CONTAINS_KEY:
        case CACHE_CONTAINS_KEYS:
        case CACHE_GET:
        case CACHE_GET_ALL:
        case CACHE_GET_AND_PUT:
        case CACHE_GET_AND_REPLACE:
        case CACHE_PUT_IF_ABSENT:
        case CACHE_GET_AND_PUT_IF_ABSENT:
        case CACHE_PUT:
        case CACHE_PUT_ALL:
        case CACHE_REMOVE:
        case CACHE_REMOVE_VALUE:
        case CACHE_REPLACE_VALUE:
        case CACHE_GET_AND_REMOVE:
        case CACHE_REMOVE_ALL:
        case CACHE_CLEAR:
        case CACHE_ADD:
        case CACHE_CAS:
        case CACHE_METRICS:
        case CACHE_SIZE:
        case CACHE_UPDATE_TLL:
        case CACHE_METADATA:
        case CACHE_REPLACE:
        case CACHE_APPEND:
        case CACHE_PREPEND:
            {
                GridRestCacheRequest restReq0 = new GridRestCacheRequest();
                String cacheName = params.get(CACHE_NAME_PARAM);
                restReq0.cacheName(F.isEmpty(cacheName) ? null : cacheName);
                String keyType = params.get("keyType");
                String valType = params.get("valueType");
                Converter converter = new Converter(cacheName);
                restReq0.key(converter.convert(keyType, params.get("key")));
                restReq0.value(converter.convert(valType, params.get("val")));
                restReq0.value2(converter.convert(valType, params.get("val2")));
                Object val1 = converter.convert(valType, params.get("val1"));
                if (val1 != null)
                    restReq0.value(val1);
                // Cache operations via REST will use binary objects.
                restReq0.cacheFlags(intValue("cacheFlags", params, KEEP_BINARIES_MASK));
                restReq0.ttl(longValue("exp", params, null));
                if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL || cmd == CACHE_CONTAINS_KEYS) {
                    List<Object> keys = converter.values(keyType, "k", params);
                    List<Object> vals = converter.values(valType, "v", params);
                    if (keys.size() < vals.size())
                        throw new IgniteCheckedException("Number of keys must be greater or equals to number of values.");
                    Map<Object, Object> map = U.newHashMap(keys.size());
                    Iterator<Object> keyIt = keys.iterator();
                    Iterator<Object> valIt = vals.iterator();
                    while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);
                    restReq0.values(map);
                }
                restReq = restReq0;
                break;
            }
        case TOPOLOGY:
        case NODE:
            {
                GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();
                restReq0.includeMetrics(Boolean.parseBoolean(params.get("mtr")));
                restReq0.includeAttributes(Boolean.parseBoolean(params.get("attr")));
                String caches = params.get("caches");
                restReq0.includeCaches(caches == null || Boolean.parseBoolean(caches));
                restReq0.nodeIp(params.get("ip"));
                restReq0.nodeId(uuidValue("id", params));
                restReq = restReq0;
                break;
            }
        case EXE:
        case RESULT:
        case NOOP:
            {
                GridRestTaskRequest restReq0 = new GridRestTaskRequest();
                restReq0.taskId(params.get("id"));
                restReq0.taskName(params.get("name"));
                restReq0.params(new Converter().values(null, "p", params));
                restReq0.async(Boolean.parseBoolean(params.get("async")));
                restReq0.timeout(longValue("timeout", params, 0L));
                restReq = restReq0;
                break;
            }
        case LOG:
            {
                GridRestLogRequest restReq0 = new GridRestLogRequest();
                restReq0.path(params.get("path"));
                restReq0.from(intValue("from", params, -1));
                restReq0.to(intValue("to", params, -1));
                restReq = restReq0;
                break;
            }
        case DATA_REGION_METRICS:
        case DATA_STORAGE_METRICS:
        case NAME:
        case VERSION:
        case PROBE:
            {
                restReq = new GridRestRequest();
                break;
            }
        case CLUSTER_ACTIVE:
        case CLUSTER_INACTIVE:
        case CLUSTER_ACTIVATE:
        case CLUSTER_DEACTIVATE:
        case CLUSTER_CURRENT_STATE:
            {
                GridRestChangeStateRequest restReq0 = new GridRestChangeStateRequest();
                if (cmd == CLUSTER_CURRENT_STATE)
                    restReq0.reqCurrentState();
                else if (cmd == CLUSTER_ACTIVE || cmd == CLUSTER_ACTIVATE)
                    restReq0.active(true);
                else
                    restReq0.active(false);
                restReq0.forceDeactivation(booleanValue(GridRestClusterStateRequest.ARG_FORCE, params, false));
                restReq = restReq0;
                break;
            }
        case CLUSTER_STATE:
        case CLUSTER_SET_STATE:
            {
                GridRestClusterStateRequest restReq0 = new GridRestClusterStateRequest();
                if (cmd == CLUSTER_STATE)
                    restReq0.reqCurrentMode();
                else {
                    ClusterState newState = enumValue("state", params, ClusterState.class);
                    restReq0.state(newState);
                    restReq0.forceDeactivation(booleanValue(GridRestClusterStateRequest.ARG_FORCE, params, false));
                }
                restReq = restReq0;
                break;
            }
        case CLUSTER_NAME:
            {
                restReq = new GridRestClusterNameRequest();
                break;
            }
        case BASELINE_CURRENT_STATE:
        case BASELINE_SET:
        case BASELINE_ADD:
        case BASELINE_REMOVE:
            {
                GridRestBaselineRequest restReq0 = new GridRestBaselineRequest();
                restReq0.topologyVersion(longValue("topVer", params, null));
                restReq0.consistentIds(new Converter().values(null, "consistentId", params));
                restReq = restReq0;
                break;
            }
        case AUTHENTICATE:
            {
                restReq = new GridRestRequest();
                break;
            }
        case ADD_USER:
        case REMOVE_USER:
        case UPDATE_USER:
            {
                RestUserActionRequest restReq0 = new RestUserActionRequest();
                restReq0.user(params.get("user"));
                restReq0.password(params.get("password"));
                restReq = restReq0;
                break;
            }
        case EXECUTE_SQL_QUERY:
        case EXECUTE_SQL_FIELDS_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                String cacheName = params.get(CACHE_NAME_PARAM);
                restReq0.sqlQuery(params.get("qry"));
                restReq0.arguments(new Converter(cacheName).values(null, "arg", params).toArray());
                restReq0.typeName(params.get("type"));
                String pageSize = params.get("pageSize");
                if (pageSize != null)
                    restReq0.pageSize(Integer.parseInt(pageSize));
                String keepBinary = params.get("keepBinary");
                if (keepBinary != null)
                    restReq0.keepBinary(Boolean.parseBoolean(keepBinary));
                String distributedJoins = params.get("distributedJoins");
                if (distributedJoins != null)
                    restReq0.distributedJoins(Boolean.parseBoolean(distributedJoins));
                restReq0.cacheName(cacheName);
                if (cmd == EXECUTE_SQL_QUERY)
                    restReq0.queryType(RestQueryRequest.QueryType.SQL);
                else
                    restReq0.queryType(RestQueryRequest.QueryType.SQL_FIELDS);
                restReq = restReq0;
                break;
            }
        case EXECUTE_SCAN_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                restReq0.sqlQuery(params.get("qry"));
                String pageSize = params.get("pageSize");
                if (pageSize != null)
                    restReq0.pageSize(Integer.parseInt(pageSize));
                restReq0.cacheName(params.get(CACHE_NAME_PARAM));
                restReq0.className(params.get("className"));
                restReq0.queryType(RestQueryRequest.QueryType.SCAN);
                restReq = restReq0;
                break;
            }
        case FETCH_SQL_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                String qryId = params.get("qryId");
                if (qryId != null)
                    restReq0.queryId(Long.parseLong(qryId));
                String pageSize = params.get("pageSize");
                if (pageSize != null)
                    restReq0.pageSize(Integer.parseInt(pageSize));
                restReq0.cacheName(params.get(CACHE_NAME_PARAM));
                restReq = restReq0;
                break;
            }
        case CLOSE_SQL_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                String qryId = params.get("qryId");
                if (qryId != null)
                    restReq0.queryId(Long.parseLong(qryId));
                restReq0.cacheName(params.get(CACHE_NAME_PARAM));
                restReq = restReq0;
                break;
            }
        case NODE_STATE_BEFORE_START:
            {
                restReq = new GridRestNodeStateBeforeStartRequest();
                break;
            }
        case WARM_UP:
            {
                GridRestWarmUpRequest restReq0 = new GridRestWarmUpRequest();
                restReq0.stopWarmUp(Boolean.parseBoolean(String.valueOf(params.get("stopWarmUp"))));
                restReq = restReq0;
                break;
            }
        default:
            throw new IgniteCheckedException("Invalid command: " + cmd);
    }
    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));
    restReq.command(cmd);
    Object certs = req.getAttribute("javax.servlet.request.X509Certificate");
    if (certs instanceof X509Certificate[])
        restReq.certificates((X509Certificate[]) certs);
    // TODO: In IGNITE 3.0 we should check credentials only for AUTHENTICATE command.
    if (!credentials(params, IGNITE_LOGIN, IGNITE_PASSWORD, restReq))
        credentials(params, USER_PARAM, PWD_PARAM, restReq);
    String clientId = params.get("clientId");
    try {
        if (clientId != null)
            restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
    // Ignore invalid client id. Rest handler will process this logic.
    }
    String destId = params.get("destId");
    try {
        if (destId != null)
            restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
    // Don't fail - try to execute locally.
    }
    String sesTokStr = params.get("sessionToken");
    try {
        if (sesTokStr != null) {
            // Token is a UUID encoded as 16 bytes as HEX.
            byte[] bytes = U.hexString2ByteArray(sesTokStr);
            if (bytes.length == 16)
                restReq.sessionToken(bytes);
        }
    } catch (IllegalArgumentException ignored) {
    // Ignore invalid session token.
    }
    return restReq;
}
Also used : GridRestClusterStateRequest(org.apache.ignite.internal.processors.rest.request.GridRestClusterStateRequest) GridRestTopologyRequest(org.apache.ignite.internal.processors.rest.request.GridRestTopologyRequest) InetSocketAddress(java.net.InetSocketAddress) GridRestLogRequest(org.apache.ignite.internal.processors.rest.request.GridRestLogRequest) GridRestCacheRequest(org.apache.ignite.internal.processors.rest.request.GridRestCacheRequest) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridRestTaskRequest(org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest) RestQueryRequest(org.apache.ignite.internal.processors.rest.request.RestQueryRequest) Iterator(java.util.Iterator) DataStructuresRequest(org.apache.ignite.internal.processors.rest.request.DataStructuresRequest) List(java.util.List) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) GridRestRequest(org.apache.ignite.internal.processors.rest.request.GridRestRequest) ClusterState(org.apache.ignite.cluster.ClusterState) GridRestClusterNameRequest(org.apache.ignite.internal.processors.rest.request.GridRestClusterNameRequest) CacheConfigurationOverride(org.apache.ignite.internal.processors.cache.CacheConfigurationOverride) GridRestBaselineRequest(org.apache.ignite.internal.processors.rest.request.GridRestBaselineRequest) GridRestNodeStateBeforeStartRequest(org.apache.ignite.internal.processors.rest.request.GridRestNodeStateBeforeStartRequest) GridRestWarmUpRequest(org.apache.ignite.internal.processors.rest.request.GridRestWarmUpRequest) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) RestUserActionRequest(org.apache.ignite.internal.processors.rest.request.RestUserActionRequest) GridRestChangeStateRequest(org.apache.ignite.internal.processors.rest.request.GridRestChangeStateRequest) BinaryObject(org.apache.ignite.binary.BinaryObject) Map(java.util.Map) Nullable(org.jetbrains.annotations.Nullable)

Example 4 with GridRestTaskRequest

use of org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest in project ignite by apache.

the class GridJettyRestHandler method createRequest.

/**
 * Creates REST request.
 *
 * @param cmd Command.
 * @param params Parameters.
 * @param req Servlet request.
 * @return REST request.
 * @throws IgniteCheckedException If creation failed.
 */
@Nullable
private GridRestRequest createRequest(GridRestCommand cmd, Map<String, Object> params, HttpServletRequest req) throws IgniteCheckedException {
    GridRestRequest restReq;
    switch(cmd) {
        case GET_OR_CREATE_CACHE:
            {
                GridRestCacheRequest restReq0 = new GridRestCacheRequest();
                restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
                String templateName = (String) params.get(TEMPLATE_NAME_PARAM);
                if (!F.isEmpty(templateName))
                    restReq0.templateName(templateName);
                String backups = (String) params.get(BACKUPS_PARAM);
                CacheConfigurationOverride cfg = new CacheConfigurationOverride();
                // Set cache backups.
                if (!F.isEmpty(backups)) {
                    try {
                        cfg.backups(Integer.parseInt(backups));
                    } catch (NumberFormatException e) {
                        throw new IgniteCheckedException("Failed to parse number of cache backups: " + backups, e);
                    }
                }
                // Set cache group name.
                String cacheGrp = (String) params.get(CACHE_GROUP_PARAM);
                if (!F.isEmpty(cacheGrp))
                    cfg.cacheGroup(cacheGrp);
                // Set cache data region name.
                String dataRegion = (String) params.get(DATA_REGION_PARAM);
                if (!F.isEmpty(dataRegion))
                    cfg.dataRegion(dataRegion);
                // Set cache write mode.
                String wrtSyncMode = (String) params.get(WRITE_SYNCHRONIZATION_MODE_PARAM);
                if (!F.isEmpty(wrtSyncMode)) {
                    try {
                        cfg.writeSynchronizationMode(CacheWriteSynchronizationMode.valueOf(wrtSyncMode));
                    } catch (IllegalArgumentException e) {
                        throw new IgniteCheckedException("Failed to parse cache write synchronization mode: " + wrtSyncMode, e);
                    }
                }
                if (!cfg.isEmpty())
                    restReq0.configuration(cfg);
                restReq = restReq0;
                break;
            }
        case DESTROY_CACHE:
            {
                GridRestCacheRequest restReq0 = new GridRestCacheRequest();
                restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
                restReq = restReq0;
                break;
            }
        case ATOMIC_DECREMENT:
        case ATOMIC_INCREMENT:
            {
                DataStructuresRequest restReq0 = new DataStructuresRequest();
                restReq0.key(params.get("key"));
                restReq0.initial(longValue("init", params, null));
                restReq0.delta(longValue("delta", params, null));
                restReq = restReq0;
                break;
            }
        case CACHE_CONTAINS_KEY:
        case CACHE_CONTAINS_KEYS:
        case CACHE_GET:
        case CACHE_GET_ALL:
        case CACHE_GET_AND_PUT:
        case CACHE_GET_AND_REPLACE:
        case CACHE_PUT_IF_ABSENT:
        case CACHE_GET_AND_PUT_IF_ABSENT:
        case CACHE_PUT:
        case CACHE_PUT_ALL:
        case CACHE_REMOVE:
        case CACHE_REMOVE_VALUE:
        case CACHE_REPLACE_VALUE:
        case CACHE_GET_AND_REMOVE:
        case CACHE_REMOVE_ALL:
        case CACHE_CLEAR:
        case CACHE_ADD:
        case CACHE_CAS:
        case CACHE_METRICS:
        case CACHE_SIZE:
        case CACHE_METADATA:
        case CACHE_REPLACE:
        case CACHE_APPEND:
        case CACHE_PREPEND:
            {
                GridRestCacheRequest restReq0 = new GridRestCacheRequest();
                String cacheName = (String) params.get(CACHE_NAME_PARAM);
                restReq0.cacheName(F.isEmpty(cacheName) ? null : cacheName);
                String keyType = (String) params.get("keyType");
                String valType = (String) params.get("valueType");
                restReq0.key(convert(keyType, params.get("key")));
                restReq0.value(convert(valType, params.get("val")));
                restReq0.value2(convert(valType, params.get("val2")));
                Object val1 = convert(valType, params.get("val1"));
                if (val1 != null)
                    restReq0.value(val1);
                // Cache operations via REST will use binary objects.
                restReq0.cacheFlags(intValue("cacheFlags", params, KEEP_BINARIES_MASK));
                restReq0.ttl(longValue("exp", params, null));
                if (cmd == CACHE_GET_ALL || cmd == CACHE_PUT_ALL || cmd == CACHE_REMOVE_ALL || cmd == CACHE_CONTAINS_KEYS) {
                    List<Object> keys = values(keyType, "k", params);
                    List<Object> vals = values(valType, "v", params);
                    if (keys.size() < vals.size())
                        throw new IgniteCheckedException("Number of keys must be greater or equals to number of values.");
                    Map<Object, Object> map = U.newHashMap(keys.size());
                    Iterator<Object> keyIt = keys.iterator();
                    Iterator<Object> valIt = vals.iterator();
                    while (keyIt.hasNext()) map.put(keyIt.next(), valIt.hasNext() ? valIt.next() : null);
                    restReq0.values(map);
                }
                restReq = restReq0;
                break;
            }
        case TOPOLOGY:
        case NODE:
            {
                GridRestTopologyRequest restReq0 = new GridRestTopologyRequest();
                restReq0.includeMetrics(Boolean.parseBoolean((String) params.get("mtr")));
                restReq0.includeAttributes(Boolean.parseBoolean((String) params.get("attr")));
                restReq0.nodeIp((String) params.get("ip"));
                restReq0.nodeId(uuidValue("id", params));
                restReq = restReq0;
                break;
            }
        case EXE:
        case RESULT:
        case NOOP:
            {
                GridRestTaskRequest restReq0 = new GridRestTaskRequest();
                restReq0.taskId((String) params.get("id"));
                restReq0.taskName((String) params.get("name"));
                restReq0.params(values(null, "p", params));
                restReq0.async(Boolean.parseBoolean((String) params.get("async")));
                restReq0.timeout(longValue("timeout", params, 0L));
                restReq = restReq0;
                break;
            }
        case LOG:
            {
                GridRestLogRequest restReq0 = new GridRestLogRequest();
                restReq0.path((String) params.get("path"));
                restReq0.from(intValue("from", params, -1));
                restReq0.to(intValue("to", params, -1));
                restReq = restReq0;
                break;
            }
        case NAME:
        case VERSION:
            {
                restReq = new GridRestRequest();
                break;
            }
        case CLUSTER_ACTIVE:
        case CLUSTER_INACTIVE:
        case CLUSTER_CURRENT_STATE:
            {
                GridRestChangeStateRequest restReq0 = new GridRestChangeStateRequest();
                if (cmd == CLUSTER_CURRENT_STATE)
                    restReq0.reqCurrentState();
                else
                    restReq0.active(cmd == CLUSTER_ACTIVE);
                restReq = restReq0;
                break;
            }
        case ADD_USER:
        case REMOVE_USER:
        case UPDATE_USER:
            {
                RestUserActionRequest restReq0 = new RestUserActionRequest();
                restReq0.user((String) params.get("user"));
                restReq0.password((String) params.get("password"));
                restReq = restReq0;
                break;
            }
        case EXECUTE_SQL_QUERY:
        case EXECUTE_SQL_FIELDS_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                restReq0.sqlQuery((String) params.get("qry"));
                restReq0.arguments(values(null, "arg", params).toArray());
                restReq0.typeName((String) params.get("type"));
                String pageSize = (String) params.get("pageSize");
                if (pageSize != null)
                    restReq0.pageSize(Integer.parseInt(pageSize));
                String distributedJoins = (String) params.get("distributedJoins");
                if (distributedJoins != null)
                    restReq0.distributedJoins(Boolean.parseBoolean(distributedJoins));
                restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
                if (cmd == EXECUTE_SQL_QUERY)
                    restReq0.queryType(RestQueryRequest.QueryType.SQL);
                else
                    restReq0.queryType(RestQueryRequest.QueryType.SQL_FIELDS);
                restReq = restReq0;
                break;
            }
        case EXECUTE_SCAN_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                restReq0.sqlQuery((String) params.get("qry"));
                String pageSize = (String) params.get("pageSize");
                if (pageSize != null)
                    restReq0.pageSize(Integer.parseInt(pageSize));
                restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
                restReq0.className((String) params.get("className"));
                restReq0.queryType(RestQueryRequest.QueryType.SCAN);
                restReq = restReq0;
                break;
            }
        case FETCH_SQL_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                String qryId = (String) params.get("qryId");
                if (qryId != null)
                    restReq0.queryId(Long.parseLong(qryId));
                String pageSize = (String) params.get("pageSize");
                if (pageSize != null)
                    restReq0.pageSize(Integer.parseInt(pageSize));
                restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
                restReq = restReq0;
                break;
            }
        case CLOSE_SQL_QUERY:
            {
                RestQueryRequest restReq0 = new RestQueryRequest();
                String qryId = (String) params.get("qryId");
                if (qryId != null)
                    restReq0.queryId(Long.parseLong(qryId));
                restReq0.cacheName((String) params.get(CACHE_NAME_PARAM));
                restReq = restReq0;
                break;
            }
        default:
            throw new IgniteCheckedException("Invalid command: " + cmd);
    }
    restReq.address(new InetSocketAddress(req.getRemoteAddr(), req.getRemotePort()));
    restReq.command(cmd);
    if (params.containsKey(IGNITE_LOGIN) || params.containsKey(IGNITE_PASSWORD)) {
        SecurityCredentials cred = new SecurityCredentials((String) params.get(IGNITE_LOGIN), (String) params.get(IGNITE_PASSWORD));
        restReq.credentials(cred);
    }
    String clientId = (String) params.get("clientId");
    try {
        if (clientId != null)
            restReq.clientId(UUID.fromString(clientId));
    } catch (Exception ignored) {
    // Ignore invalid client id. Rest handler will process this logic.
    }
    String destId = (String) params.get("destId");
    try {
        if (destId != null)
            restReq.destinationId(UUID.fromString(destId));
    } catch (IllegalArgumentException ignored) {
    // Don't fail - try to execute locally.
    }
    String sesTokStr = (String) params.get("sessionToken");
    try {
        if (sesTokStr != null)
            restReq.sessionToken(U.hexString2ByteArray(sesTokStr));
    } catch (IllegalArgumentException ignored) {
    // Ignore invalid session token.
    }
    return restReq;
}
Also used : CacheConfigurationOverride(org.apache.ignite.internal.processors.cache.CacheConfigurationOverride) GridRestTopologyRequest(org.apache.ignite.internal.processors.rest.request.GridRestTopologyRequest) InetSocketAddress(java.net.InetSocketAddress) GridRestLogRequest(org.apache.ignite.internal.processors.rest.request.GridRestLogRequest) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) RestUserActionRequest(org.apache.ignite.internal.processors.rest.request.RestUserActionRequest) SecurityCredentials(org.apache.ignite.plugin.security.SecurityCredentials) GridRestCacheRequest(org.apache.ignite.internal.processors.rest.request.GridRestCacheRequest) GridRestChangeStateRequest(org.apache.ignite.internal.processors.rest.request.GridRestChangeStateRequest) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridRestTaskRequest(org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest) RestQueryRequest(org.apache.ignite.internal.processors.rest.request.RestQueryRequest) Iterator(java.util.Iterator) DataStructuresRequest(org.apache.ignite.internal.processors.rest.request.DataStructuresRequest) List(java.util.List) LinkedList(java.util.LinkedList) GridRestRequest(org.apache.ignite.internal.processors.rest.request.GridRestRequest) Map(java.util.Map) Nullable(org.jetbrains.annotations.Nullable)

Example 5 with GridRestTaskRequest

use of org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest in project ignite by apache.

the class GridTcpRestNioListener method createRestRequest.

/**
 * Creates a REST request object from client TCP binary packet.
 *
 * @param ses NIO session.
 * @param msg Request message.
 * @return REST request object.
 */
@Nullable
private GridRestRequest createRestRequest(GridNioSession ses, GridClientMessage msg) {
    GridRestRequest restReq = null;
    if (msg instanceof GridClientAuthenticationRequest) {
        GridClientAuthenticationRequest req = (GridClientAuthenticationRequest) msg;
        restReq = new GridRestAuthenticationRequest();
        restReq.command(NOOP);
        ses.addMeta(CREDS_KEY, req.credentials());
        ses.addMeta(USER_ATTR_KEY, req.userAttributes());
    } else if (msg instanceof GridClientCacheRequest) {
        GridClientCacheRequest req = (GridClientCacheRequest) msg;
        GridRestCacheRequest restCacheReq = new GridRestCacheRequest();
        restCacheReq.cacheName(req.cacheName());
        restCacheReq.cacheFlags(req.cacheFlagsOn());
        restCacheReq.key(req.key());
        restCacheReq.value(req.value());
        restCacheReq.value2(req.value2());
        Map vals = req.values();
        if (vals != null)
            restCacheReq.values(new HashMap<Object, Object>(vals));
        restCacheReq.command(cacheCmdMap.get(req.operation()));
        restReq = restCacheReq;
    } else if (msg instanceof GridClientTaskRequest) {
        GridClientTaskRequest req = (GridClientTaskRequest) msg;
        GridRestTaskRequest restTaskReq = new GridRestTaskRequest();
        restTaskReq.command(EXE);
        restTaskReq.taskName(req.taskName());
        restTaskReq.params(Arrays.asList(req.argument()));
        restReq = restTaskReq;
    } else if (msg instanceof GridClientTopologyRequest) {
        GridClientTopologyRequest req = (GridClientTopologyRequest) msg;
        GridRestTopologyRequest restTopReq = new GridRestTopologyRequest();
        restTopReq.includeMetrics(req.includeMetrics());
        restTopReq.includeAttributes(req.includeAttributes());
        if (req.nodeId() != null) {
            restTopReq.command(NODE);
            restTopReq.nodeId(req.nodeId());
        } else if (req.nodeIp() != null) {
            restTopReq.command(NODE);
            restTopReq.nodeIp(req.nodeIp());
        } else
            restTopReq.command(TOPOLOGY);
        restReq = restTopReq;
    } else if (msg instanceof GridClientStateRequest) {
        GridClientStateRequest req = (GridClientStateRequest) msg;
        GridRestChangeStateRequest restChangeReq = new GridRestChangeStateRequest();
        if (req.isReqCurrentState()) {
            restChangeReq.reqCurrentState();
            restChangeReq.command(CLUSTER_CURRENT_STATE);
        } else {
            restChangeReq.active(req.active());
            restChangeReq.command(req.active() ? CLUSTER_ACTIVATE : CLUSTER_DEACTIVATE);
        }
        restReq = restChangeReq;
    } else if (msg instanceof GridClientClusterStateRequest) {
        GridClientClusterStateRequest req = (GridClientClusterStateRequest) msg;
        boolean forceDeactivation = !(msg instanceof GridClientClusterStateRequestV2) || ((GridClientClusterStateRequestV2) msg).forceDeactivation();
        GridRestClusterStateRequest restChangeReq = new GridRestClusterStateRequest();
        if (req.isReqCurrentState()) {
            restChangeReq.reqCurrentMode();
            restChangeReq.command(CLUSTER_STATE);
        } else {
            restChangeReq.state(req.state());
            restChangeReq.command(CLUSTER_SET_STATE);
            restChangeReq.forceDeactivation(forceDeactivation);
        }
        restReq = restChangeReq;
    } else if (msg instanceof GridClientClusterNameRequest)
        restReq = new GridRestClusterNameRequest();
    else if (msg instanceof GridClientNodeStateBeforeStartRequest) {
        GridClientNodeStateBeforeStartRequest reqClient = (GridClientNodeStateBeforeStartRequest) msg;
        if (reqClient instanceof GridClientWarmUpRequest) {
            GridClientWarmUpRequest warmUpReqClient = (GridClientWarmUpRequest) reqClient;
            restReq = new GridRestWarmUpRequest().stopWarmUp(warmUpReqClient.stopWarmUp());
            restReq.command(WARM_UP);
        } else {
            restReq = new GridRestNodeStateBeforeStartRequest();
            restReq.command(NODE_STATE_BEFORE_START);
        }
    }
    if (restReq != null) {
        restReq.destinationId(msg.destinationId());
        restReq.clientId(msg.clientId());
        restReq.sessionToken(msg.sessionToken());
        restReq.address(ses.remoteAddress());
        restReq.certificates(ses.certificates());
        restReq.credentials(ses.meta(CREDS_KEY));
        restReq.userAttributes(ses.meta(USER_ATTR_KEY));
    }
    return restReq;
}
Also used : GridRestClusterStateRequest(org.apache.ignite.internal.processors.rest.request.GridRestClusterStateRequest) GridClientAuthenticationRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientAuthenticationRequest) GridRestClusterNameRequest(org.apache.ignite.internal.processors.rest.request.GridRestClusterNameRequest) GridClientWarmUpRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientWarmUpRequest) GridRestTopologyRequest(org.apache.ignite.internal.processors.rest.request.GridRestTopologyRequest) GridClientClusterNameRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientClusterNameRequest) GridClientNodeStateBeforeStartRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientNodeStateBeforeStartRequest) GridRestNodeStateBeforeStartRequest(org.apache.ignite.internal.processors.rest.request.GridRestNodeStateBeforeStartRequest) GridRestWarmUpRequest(org.apache.ignite.internal.processors.rest.request.GridRestWarmUpRequest) GridClientClusterStateRequestV2(org.apache.ignite.internal.processors.rest.client.message.GridClientClusterStateRequestV2) GridClientClusterStateRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientClusterStateRequest) GridRestCacheRequest(org.apache.ignite.internal.processors.rest.request.GridRestCacheRequest) GridRestChangeStateRequest(org.apache.ignite.internal.processors.rest.request.GridRestChangeStateRequest) GridRestTaskRequest(org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest) GridClientStateRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientStateRequest) GridRestAuthenticationRequest(org.apache.ignite.internal.processors.rest.request.GridRestAuthenticationRequest) GridClientTopologyRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientTopologyRequest) GridRestRequest(org.apache.ignite.internal.processors.rest.request.GridRestRequest) GridClientCacheRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientCacheRequest) Map(java.util.Map) EnumMap(java.util.EnumMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) GridClientTaskRequest(org.apache.ignite.internal.processors.rest.client.message.GridClientTaskRequest) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

GridRestTaskRequest (org.apache.ignite.internal.processors.rest.request.GridRestTaskRequest)7 List (java.util.List)4 Map (java.util.Map)4 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)4 GridRestCacheRequest (org.apache.ignite.internal.processors.rest.request.GridRestCacheRequest)4 GridRestChangeStateRequest (org.apache.ignite.internal.processors.rest.request.GridRestChangeStateRequest)3 GridRestRequest (org.apache.ignite.internal.processors.rest.request.GridRestRequest)3 GridRestTopologyRequest (org.apache.ignite.internal.processors.rest.request.GridRestTopologyRequest)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 IOException (java.io.IOException)2 InetSocketAddress (java.net.InetSocketAddress)2 ArrayList (java.util.ArrayList)2 EnumMap (java.util.EnumMap)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 LinkedList (java.util.LinkedList)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 IgniteInternalFuture (org.apache.ignite.internal.IgniteInternalFuture)2 CacheConfigurationOverride (org.apache.ignite.internal.processors.cache.CacheConfigurationOverride)2 DataStructuresRequest (org.apache.ignite.internal.processors.rest.request.DataStructuresRequest)2