Search in sources :

Example 6 with OperationSecurityContext

use of org.apache.ignite.internal.processors.security.OperationSecurityContext in project ignite by apache.

the class GridJobWorker method execute0.

/**
 * @param skipNtf {@code True} to skip job processor {@code onUnheld()}
 *      notification (only from {@link #body()}).
 */
private void execute0(boolean skipNtf) {
    // Make sure flag is not set for current thread.
    HOLD.set(false);
    SqlFieldsQuery.setThreadedQueryInitiatorId("task:" + ses.getTaskName() + ":" + getJobId());
    try (OperationSecurityContext ignored = ctx.security().withContext(secCtx)) {
        if (partsReservation != null) {
            try {
                if (!partsReservation.reserve()) {
                    finishJob(null, null, true, true);
                    return;
                }
            } catch (Exception e) {
                IgniteException ex = new IgniteException("Failed to lock partitions " + "[jobId=" + ses.getJobId() + ", ses=" + ses + ']', e);
                U.error(log, "Failed to lock partitions [jobId=" + ses.getJobId() + ", ses=" + ses + ']', e);
                ;
                finishJob(null, ex, true);
                return;
            }
        }
        if (isCancelled())
            // If job was cancelled prior to assigning runner to it?
            super.cancel();
        if (!skipNtf) {
            if (holdLsnr.onUnheld(this)) {
                if (held.decrementAndGet() == 0)
                    status = RUNNING;
            } else {
                if (log.isDebugEnabled())
                    log.debug("Ignoring job execution (job was not held).");
                return;
            }
        }
        boolean sndRes = true;
        Object res = null;
        IgniteException ex = null;
        try {
            ctx.job().currentTaskSession(ses);
            if (reqTopVer != null)
                GridQueryProcessor.setRequestAffinityTopologyVersion(reqTopVer);
            // avoid computation altogether.
            if (isTimedOut())
                sndRes = false;
            else {
                res = U.wrapThreadLoader(dep.classLoader(), new Callable<Object>() {

                    @Nullable
                    @Override
                    public Object call() {
                        try {
                            if (internal && ctx.config().isPeerClassLoadingEnabled())
                                ctx.job().internal(true);
                            return job.execute();
                        } finally {
                            if (internal && ctx.config().isPeerClassLoadingEnabled())
                                ctx.job().internal(false);
                        }
                    }
                });
                if (log.isDebugEnabled()) {
                    log.debug(S.toString("Job execution has successfully finished", "job", job, false, "res", res, true));
                }
            }
        } catch (IgniteException e) {
            if (sysStopping && e.hasCause(IgniteInterruptedCheckedException.class, InterruptedException.class)) {
                ex = handleThrowable(e);
                assert ex != null;
            } else {
                if (X.hasCause(e, InterruptedException.class)) {
                    if (log.isDebugEnabled()) {
                        U.error(log, "Job was cancelled [jobId=" + ses.getJobId() + ", ses=" + ses + ']', e);
                    }
                } else if (X.hasCause(e, GridServiceNotFoundException.class) || X.hasCause(e, ClusterTopologyCheckedException.class)) {
                    if (log.isDebugEnabled()) {
                        // Should be throttled, because GridServiceProxy continuously retry getting service.
                        LT.error(log, e, "Failed to execute job [jobId=" + ses.getJobId() + ", ses=" + ses + ']');
                    }
                } else {
                    String msg = "Failed to execute job [jobId=" + ses.getJobId() + ", ses=" + ses + ']';
                    if (X.hasCause(e, OutOfMemoryError.class)) {
                        U.error(log, msg, e);
                        ctx.failure().process(new FailureContext(FailureType.CRITICAL_ERROR, e));
                    } else if (log.isDebugEnabled())
                        U.error(log, msg, e);
                }
                ex = e;
            }
        }// InterruptedException if job is being cancelled.
         catch (Throwable e) {
            ex = handleThrowable(e);
            assert ex != null;
            if (e instanceof Error)
                throw (Error) e;
        } finally {
            // Finish here only if not held by this thread.
            if (!HOLD.get())
                finishJob(res, ex, sndRes);
            else
                // Make sure flag is not set for current thread.
                // This may happen in case of nested internal task call with continuation.
                HOLD.set(false);
            ctx.job().currentTaskSession(null);
            if (reqTopVer != null)
                GridQueryProcessor.setRequestAffinityTopologyVersion(null);
        }
    } finally {
        SqlFieldsQuery.resetThreadedQueryInitiatorId();
        if (partsReservation != null)
            partsReservation.release();
    }
}
Also used : GridServiceNotFoundException(org.apache.ignite.internal.processors.service.GridServiceNotFoundException) ComputeExecutionRejectedException(org.apache.ignite.compute.ComputeExecutionRejectedException) GridServiceNotFoundException(org.apache.ignite.internal.processors.service.GridServiceNotFoundException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) NodeStoppingException(org.apache.ignite.internal.NodeStoppingException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException) ComputeUserUndeclaredException(org.apache.ignite.compute.ComputeUserUndeclaredException) Callable(java.util.concurrent.Callable) IgniteException(org.apache.ignite.IgniteException) FailureContext(org.apache.ignite.failure.FailureContext) GridTimeoutObject(org.apache.ignite.internal.processors.timeout.GridTimeoutObject) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) ClusterTopologyCheckedException(org.apache.ignite.internal.cluster.ClusterTopologyCheckedException)

Example 7 with OperationSecurityContext

use of org.apache.ignite.internal.processors.security.OperationSecurityContext in project ignite by apache.

the class GridJobWorker method cancel.

/**
 * @param sys System flag.
 */
public void cancel(boolean sys) {
    try {
        final ComputeJob job0 = job;
        if (sys)
            sysCancelled = true;
        if (job0 != null) {
            if (log.isDebugEnabled())
                log.debug("Cancelling job: " + ses);
            status = CANCELLED;
            U.wrapThreadLoader(dep.classLoader(), (IgniteRunnable) () -> {
                try (OperationSecurityContext c = ctx.security().withContext(secCtx)) {
                    job0.cancel();
                }
            });
        }
        // Interrupting only when all 'cancelled' flags are set.
        // This allows the 'job' to determine it's a cancellation.
        super.cancel();
        if (!internal && ctx.event().isRecordable(EVT_JOB_CANCELLED))
            recordEvent(EVT_JOB_CANCELLED, "Job was cancelled: " + job0);
    }// Catch throwable to protect against bad user code.
     catch (Throwable e) {
        U.error(log, "Failed to cancel job due to undeclared user exception [jobId=" + ses.getJobId() + ", ses=" + ses + ']', e);
        if (e instanceof Error)
            throw e;
    }
}
Also used : ComputeJob(org.apache.ignite.compute.ComputeJob) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext)

Example 8 with OperationSecurityContext

use of org.apache.ignite.internal.processors.security.OperationSecurityContext in project ignite by apache.

the class GridRestProcessor method handleRequest.

/**
 * @param req Request.
 * @return Future.
 */
private IgniteInternalFuture<GridRestResponse> handleRequest(final GridRestRequest req) {
    if (req instanceof GridRestNodeStateBeforeStartRequest) {
        if (startLatch.getCount() == 0)
            return new GridFinishedFuture<>(new IgniteCheckedException("Node has already started."));
    } else if (!(req instanceof GridRestAuthenticationRequest) && startLatch.getCount() > 0) {
        try {
            startLatch.await();
        } catch (InterruptedException e) {
            return new GridFinishedFuture<>(new IgniteCheckedException("Failed to handle request " + "(protocol handler was interrupted when awaiting grid start).", e));
        }
    }
    if (log.isDebugEnabled())
        log.debug("Received request from client: " + req);
    if (securityEnabled) {
        Session ses;
        try {
            ses = session(req);
        } catch (IgniteAuthenticationException e) {
            return new GridFinishedFuture<>(new GridRestResponse(STATUS_AUTH_FAILED, e.getMessage()));
        } catch (IgniteCheckedException e) {
            return new GridFinishedFuture<>(new GridRestResponse(STATUS_FAILED, e.getMessage()));
        }
        assert ses != null;
        req.clientId(ses.clientId);
        req.sessionToken(U.uuidToBytes(ses.sesId));
        if (log.isDebugEnabled())
            log.debug("Next clientId and sessionToken were extracted according to request: " + "[clientId=" + req.clientId() + ", sesTok=" + Arrays.toString(req.sessionToken()) + "]");
        SecurityContext secCtx0 = ses.secCtx;
        try {
            if (secCtx0 == null || ses.isTokenExpired(sesTokTtl))
                ses.secCtx = secCtx0 = authenticate(req, ses);
            try (OperationSecurityContext s = ctx.security().withContext(secCtx0)) {
                authorize(req);
                return handleRequest0(req);
            }
        } catch (SecurityException e) {
            assert secCtx0 != null;
            return new GridFinishedFuture<>(new GridRestResponse(STATUS_SECURITY_CHECK_FAILED, e.getMessage()));
        } catch (IgniteCheckedException e) {
            return new GridFinishedFuture<>(new GridRestResponse(STATUS_AUTH_FAILED, e.getMessage()));
        }
    } else
        return handleRequest0(req);
}
Also used : IgniteAuthenticationException(org.apache.ignite.IgniteAuthenticationException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) SecurityContext(org.apache.ignite.internal.processors.security.SecurityContext) GridRestAuthenticationRequest(org.apache.ignite.internal.processors.rest.request.GridRestAuthenticationRequest) SecurityException(org.apache.ignite.plugin.security.SecurityException) GridRestNodeStateBeforeStartRequest(org.apache.ignite.internal.processors.rest.request.GridRestNodeStateBeforeStartRequest) OperationSecurityContext(org.apache.ignite.internal.processors.security.OperationSecurityContext) GridFinishedFuture(org.apache.ignite.internal.util.future.GridFinishedFuture)

Aggregations

OperationSecurityContext (org.apache.ignite.internal.processors.security.OperationSecurityContext)8 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)4 SecurityContext (org.apache.ignite.internal.processors.security.SecurityContext)3 UUID (java.util.UUID)2 IgniteException (org.apache.ignite.IgniteException)2 IgniteInterruptedCheckedException (org.apache.ignite.internal.IgniteInterruptedCheckedException)2 NodeStoppingException (org.apache.ignite.internal.NodeStoppingException)2 SecurityUtils.nodeSecurityContext (org.apache.ignite.internal.processors.security.SecurityUtils.nodeSecurityContext)2 SecurityException (org.apache.ignite.plugin.security.SecurityException)2 ArrayList (java.util.ArrayList)1 List (java.util.List)1 Callable (java.util.concurrent.Callable)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 IgniteAuthenticationException (org.apache.ignite.IgniteAuthenticationException)1 IgniteClientDisconnectedException (org.apache.ignite.IgniteClientDisconnectedException)1 IgniteInterruptedException (org.apache.ignite.IgniteInterruptedException)1 QueryEntity (org.apache.ignite.cache.QueryEntity)1 ClusterNode (org.apache.ignite.cluster.ClusterNode)1 ComputeExecutionRejectedException (org.apache.ignite.compute.ComputeExecutionRejectedException)1