Search in sources :

Example 1 with GridifyArgument

use of org.apache.ignite.compute.gridify.GridifyArgument in project ignite by apache.

the class GridifyAspectJAspect method gridify.

/**
 * Aspect implementation which executes grid-enabled methods on remote
 * nodes.
 *
 * @param joinPnt Join point provided by AspectJ AOP.
 * @return Method execution result.
 * @throws Throwable If execution failed.
 */
@SuppressWarnings({ "ProhibitedExceptionDeclared", "ProhibitedExceptionThrown", "unchecked" })
@Around("execution(@org.apache.ignite.compute.gridify.Gridify * *(..)) && !cflow(call(* org.apache.ignite.compute.ComputeJob.*(..)))")
public Object gridify(ProceedingJoinPoint joinPnt) throws Throwable {
    Method mtd = ((MethodSignature) joinPnt.getSignature()).getMethod();
    Gridify ann = mtd.getAnnotation(Gridify.class);
    assert ann != null : "Intercepted method does not have gridify annotation.";
    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended Ignite instance name.
    // NOTE: the 'ann.igniteInstanceName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String igniteInstanceName = F.isEmpty(ann.igniteInstanceName()) ? ann.gridName() : ann.igniteInstanceName();
    if (F.isEmpty(igniteInstanceName))
        igniteInstanceName = null;
    if (G.state(igniteInstanceName) != STARTED)
        throw new IgniteCheckedException("Grid is not locally started: " + igniteInstanceName);
    // Initialize defaults.
    GridifyArgument arg = new GridifyArgumentAdapter(mtd.getDeclaringClass(), mtd.getName(), mtd.getParameterTypes(), joinPnt.getArgs(), joinPnt.getTarget());
    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
        // Check interceptor first.
        if (!ann.interceptor().newInstance().isGridify(ann, arg))
            return joinPnt.proceed();
    }
    if (!ann.taskClass().equals(GridifyDefaultTask.class) && !ann.taskName().isEmpty()) {
        throw new IgniteCheckedException("Gridify annotation must specify either Gridify.taskName() or " + "Gridify.taskClass(), but not both: " + ann);
    }
    try {
        Ignite ignite = G.ignite(igniteInstanceName);
        // If task class was specified.
        if (!ann.taskClass().equals(GridifyDefaultTask.class)) {
            return ignite.compute().withTimeout(ann.timeout()).execute((Class<? extends ComputeTask<GridifyArgument, Object>>) ann.taskClass(), arg);
        }
        // If task name was not specified.
        if (ann.taskName().isEmpty()) {
            return ignite.compute().withTimeout(ann.timeout()).execute(new GridifyDefaultTask(joinPnt.getSignature().getDeclaringType()), arg);
        }
        // If task name was specified.
        return ignite.compute().withTimeout(ann.timeout()).execute(ann.taskName(), arg);
    } catch (Exception e) {
        for (Class<?> ex : ((MethodSignature) joinPnt.getSignature()).getMethod().getExceptionTypes()) {
            // Descend all levels down.
            Throwable cause = e.getCause();
            while (cause != null) {
                if (ex.isAssignableFrom(cause.getClass()))
                    throw cause;
                cause = cause.getCause();
            }
            if (ex.isAssignableFrom(e.getClass()))
                throw e;
        }
        throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
}
Also used : MethodSignature(org.aspectj.lang.reflect.MethodSignature) Method(java.lang.reflect.Method) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridifyRuntimeException(org.apache.ignite.compute.gridify.GridifyRuntimeException) Gridify(org.apache.ignite.compute.gridify.Gridify) GridifyInterceptor(org.apache.ignite.compute.gridify.GridifyInterceptor) GridifyArgument(org.apache.ignite.compute.gridify.GridifyArgument) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridifyDefaultTask(org.apache.ignite.compute.gridify.aop.GridifyDefaultTask) GridifyArgumentAdapter(org.apache.ignite.compute.gridify.aop.GridifyArgumentAdapter) Ignite(org.apache.ignite.Ignite) GridifyRuntimeException(org.apache.ignite.compute.gridify.GridifyRuntimeException) Around(org.aspectj.lang.annotation.Around)

Example 2 with GridifyArgument

use of org.apache.ignite.compute.gridify.GridifyArgument in project ignite by apache.

the class GridifyDefaultRangeTask method map.

/**
 * {@inheritDoc}
 */
@NotNull
@Override
public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, GridifyRangeArgument arg) {
    assert !subgrid.isEmpty() : "Subgrid should not be empty: " + subgrid;
    assert ignite != null : "Grid instance could not be injected";
    if (splitSize < threshold && splitSize != 0 && threshold != 0) {
        throw new IgniteException("Incorrect Gridify annotation parameters. Value for parameter " + "'splitSize' should not be less than parameter 'threshold' [splitSize=" + splitSize + ", threshold=" + threshold + ']');
    }
    Collection<ClusterNode> exclNodes = new LinkedList<>();
    // Filter nodes.
    if (nodeFilter != null) {
        for (ClusterNode node : subgrid) {
            if (!nodeFilter.apply(node, ses))
                exclNodes.add(node);
        }
        if (exclNodes.size() == subgrid.size())
            throw new IgniteException("Failed to execute on grid where all nodes excluded.");
    }
    int inputPerNode = splitSize;
    // Calculate input elements size per node for default annotation splitSize parameter.
    if (splitSize <= 0) {
        // For iterable input splitSize will be assigned with threshold value.
        if (threshold > 0 && arg.getInputSize() == UNKNOWN_SIZE)
            inputPerNode = threshold;
        else // Otherwise, splitSize equals (inputSize / nodesCount)
        {
            assert arg.getInputSize() != UNKNOWN_SIZE;
            int gridSize = subgrid.size() - exclNodes.size();
            gridSize = (gridSize <= 0 ? subgrid.size() : gridSize);
            inputPerNode = calculateInputSizePerNode(gridSize, arg.getInputSize(), threshold, limitedSplit);
            if (log.isDebugEnabled()) {
                log.debug("Calculated input elements size per node [inputSize=" + arg.getInputSize() + ", gridSize=" + gridSize + ", threshold=" + threshold + ", limitedSplit=" + limitedSplit + ", inputPerNode=" + inputPerNode + ']');
            }
        }
    }
    GridifyArgumentBuilder argBuilder = new GridifyArgumentBuilder();
    Iterator<?> inputIter = arg.getInputIterator();
    while (inputIter.hasNext()) {
        Collection<Object> nodeInput = new LinkedList<>();
        for (int i = 0; i < inputPerNode && inputIter.hasNext(); i++) nodeInput.add(inputIter.next());
        // Create job argument.
        GridifyArgument jobArg = argBuilder.createJobArgument(arg, nodeInput);
        ComputeJob job = new GridifyJobAdapter(jobArg);
        mapper.send(job, balancer.getBalancedNode(job, exclNodes));
    }
    // Map method can return null because job already sent by continuous mapper.
    return null;
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) GridifyArgument(org.apache.ignite.compute.gridify.GridifyArgument) ComputeJob(org.apache.ignite.compute.ComputeJob) IgniteException(org.apache.ignite.IgniteException) GridifyJobAdapter(org.apache.ignite.internal.util.gridify.GridifyJobAdapter) GridifyArgumentBuilder(org.apache.ignite.internal.util.gridify.GridifyArgumentBuilder) LinkedList(java.util.LinkedList) NotNull(org.jetbrains.annotations.NotNull)

Example 3 with GridifyArgument

use of org.apache.ignite.compute.gridify.GridifyArgument in project ignite by apache.

the class GridifyJobAdapter method execute.

/**
 * Provides default implementation for execution of grid-enabled methods.
 * This method assumes that argument passed in is of {@link GridifyArgument}
 * type. It attempts to reflectively execute a method based on information
 * provided in the argument and returns the return value of the method.
 * <p>
 * If some exception occurred during execution, then it will be thrown
 * out of this method.
 *
 * @return {@inheritDoc}
 */
@Override
public Object execute() {
    GridifyArgument arg = argument(0);
    try {
        // Get public, package, protected, or private method.
        Method mtd = arg.getMethodClass().getDeclaredMethod(arg.getMethodName(), arg.getMethodParameterTypes());
        // non-accessible method. Subject to security manager setting.
        if (!mtd.isAccessible())
            try {
                mtd.setAccessible(true);
            } catch (SecurityException e) {
                throw new IgniteException("Got security exception when attempting to soften access control for " + "@Gridify method: " + mtd, e);
            }
        Object obj = null;
        // No need to create an instance for static methods.
        if (!Modifier.isStatic(mtd.getModifiers()))
            // Obtain instance to execute method on.
            obj = arg.getTarget();
        return mtd.invoke(obj, arg.getMethodParameters());
    } catch (InvocationTargetException e) {
        if (e.getTargetException() instanceof IgniteException)
            throw (IgniteException) e.getTargetException();
        throw new IgniteException("Failed to invoke a method due to user exception.", e.getTargetException());
    } catch (IllegalAccessException e) {
        throw new IgniteException("Failed to access method for execution.", e);
    } catch (NoSuchMethodException e) {
        throw new IgniteException("Failed to find method for execution.", e);
    }
}
Also used : GridifyArgument(org.apache.ignite.compute.gridify.GridifyArgument) IgniteException(org.apache.ignite.IgniteException) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 4 with GridifyArgument

use of org.apache.ignite.compute.gridify.GridifyArgument in project ignite by apache.

the class GridifySpringAspect method invoke.

/**
 * Aspect implementation which executes grid-enabled methods on remote
 * nodes.
 *
 * {@inheritDoc}
 */
@SuppressWarnings({ "ProhibitedExceptionDeclared", "ProhibitedExceptionThrown", "unchecked" })
@Override
public Object invoke(MethodInvocation invoc) throws Throwable {
    Method mtd = invoc.getMethod();
    Gridify ann = mtd.getAnnotation(Gridify.class);
    assert ann != null : "Intercepted method does not have gridify annotation.";
    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended Ignite instance name.
    // NOTE: the 'ann.igniteInstanceName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String igniteInstanceName = F.isEmpty(ann.igniteInstanceName()) ? ann.gridName() : ann.igniteInstanceName();
    if (F.isEmpty(igniteInstanceName))
        igniteInstanceName = null;
    if (G.state(igniteInstanceName) != STARTED)
        throw new IgniteCheckedException("Grid is not locally started: " + igniteInstanceName);
    // Initialize defaults.
    GridifyArgument arg = new GridifyArgumentAdapter(mtd.getDeclaringClass(), mtd.getName(), mtd.getParameterTypes(), invoc.getArguments(), invoc.getThis());
    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
        // Check interceptor first.
        if (!ann.interceptor().newInstance().isGridify(ann, arg))
            return invoc.proceed();
    }
    if (!ann.taskClass().equals(GridifyDefaultTask.class) && !ann.taskName().isEmpty())
        throw new IgniteCheckedException("Gridify annotation must specify either Gridify.taskName() or " + "Gridify.taskClass(), but not both: " + ann);
    try {
        Ignite ignite = G.ignite(igniteInstanceName);
        if (!ann.taskClass().equals(GridifyDefaultTask.class))
            return ignite.compute().withTimeout(ann.timeout()).execute((Class<? extends ComputeTask<GridifyArgument, Object>>) ann.taskClass(), arg);
        // If task name was not specified.
        if (ann.taskName().isEmpty())
            return ignite.compute().withTimeout(ann.timeout()).execute(new GridifyDefaultTask(invoc.getMethod().getDeclaringClass()), arg);
        // If task name was specified.
        return ignite.compute().withTimeout(ann.timeout()).execute(ann.taskName(), arg);
    } catch (Exception e) {
        for (Class<?> ex : invoc.getMethod().getExceptionTypes()) {
            // Descend all levels down.
            Throwable cause = e.getCause();
            while (cause != null) {
                if (ex.isAssignableFrom(cause.getClass()))
                    throw cause;
                cause = cause.getCause();
            }
            if (ex.isAssignableFrom(e.getClass()))
                throw e;
        }
        throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
}
Also used : ComputeTask(org.apache.ignite.compute.ComputeTask) Method(java.lang.reflect.Method) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridifyRuntimeException(org.apache.ignite.compute.gridify.GridifyRuntimeException) Gridify(org.apache.ignite.compute.gridify.Gridify) GridifyInterceptor(org.apache.ignite.compute.gridify.GridifyInterceptor) GridifyArgument(org.apache.ignite.compute.gridify.GridifyArgument) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridifyDefaultTask(org.apache.ignite.compute.gridify.aop.GridifyDefaultTask) GridifyArgumentAdapter(org.apache.ignite.compute.gridify.aop.GridifyArgumentAdapter) Ignite(org.apache.ignite.Ignite) GridifyRuntimeException(org.apache.ignite.compute.gridify.GridifyRuntimeException)

Example 5 with GridifyArgument

use of org.apache.ignite.compute.gridify.GridifyArgument in project ignite by apache.

the class GridP2PTestTask method map.

/**
 * {@inheritDoc}
 */
@NotNull
@Override
public Map<? extends ComputeJob, ClusterNode> map(List<ClusterNode> subgrid, Object arg) {
    assert subgrid != null;
    assert !subgrid.isEmpty();
    Integer arg1 = null;
    if (arg instanceof GridifyArgument)
        arg1 = (Integer) ((GridifyArgument) arg).getMethodParameters()[0];
    else if (arg instanceof Integer)
        arg1 = (Integer) arg;
    else
        assert false : "Failed to map task (unknown argument type) [type=" + arg.getClass() + ", val=" + arg + ']';
    Map<ComputeJob, ClusterNode> map = new HashMap<>(subgrid.size());
    UUID nodeId = ignite != null ? ignite.configuration().getNodeId() : null;
    for (ClusterNode node : subgrid) if (!node.id().equals(nodeId))
        map.put(new GridP2PTestJob(arg1), node);
    return map;
}
Also used : GridifyArgument(org.apache.ignite.compute.gridify.GridifyArgument) ClusterNode(org.apache.ignite.cluster.ClusterNode) ComputeJob(org.apache.ignite.compute.ComputeJob) HashMap(java.util.HashMap) UUID(java.util.UUID) NotNull(org.jetbrains.annotations.NotNull)

Aggregations

GridifyArgument (org.apache.ignite.compute.gridify.GridifyArgument)5 Method (java.lang.reflect.Method)3 Ignite (org.apache.ignite.Ignite)2 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)2 IgniteException (org.apache.ignite.IgniteException)2 ClusterNode (org.apache.ignite.cluster.ClusterNode)2 ComputeJob (org.apache.ignite.compute.ComputeJob)2 Gridify (org.apache.ignite.compute.gridify.Gridify)2 GridifyInterceptor (org.apache.ignite.compute.gridify.GridifyInterceptor)2 GridifyRuntimeException (org.apache.ignite.compute.gridify.GridifyRuntimeException)2 GridifyArgumentAdapter (org.apache.ignite.compute.gridify.aop.GridifyArgumentAdapter)2 GridifyDefaultTask (org.apache.ignite.compute.gridify.aop.GridifyDefaultTask)2 NotNull (org.jetbrains.annotations.NotNull)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 UUID (java.util.UUID)1 ComputeTask (org.apache.ignite.compute.ComputeTask)1 GridifyArgumentBuilder (org.apache.ignite.internal.util.gridify.GridifyArgumentBuilder)1 GridifyJobAdapter (org.apache.ignite.internal.util.gridify.GridifyJobAdapter)1