Search in sources :

Example 1 with GlobalManager

use of com.dexels.navajo.server.global.GlobalManager in project navajo by Dexels.

the class TmlContinuationRunner method run.

@Override
public void run() {
    try {
        final GlobalManagerRepository globalManagerInstance = GlobalManagerRepositoryFactory.getGlobalManagerInstance();
        if (globalManagerInstance == null) {
            logger.warn("No global manager found");
        }
        clearThreadLocal(true);
        String instance = getRequest().getInstance();
        if (instance != null && globalManagerInstance != null) {
            GlobalManager gm = globalManagerInstance.getGlobalManager(instance);
            if (gm != null) {
                gm.initGlobals(getRequest().getInputDocument());
            } else {
                logger.warn("No global manager found for instance: " + instance);
            }
        } else {
            logger.debug("Not using instance based GlobalManager: No instance found in request");
        }
        execute();
    } catch (Exception e) {
        logger.error("Continuation problem: ", e);
        getRequest().fail(e);
    }
}
Also used : GlobalManager(com.dexels.navajo.server.global.GlobalManager) GlobalManagerRepository(com.dexels.navajo.server.global.GlobalManagerRepository) FatalException(com.dexels.navajo.script.api.FatalException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 2 with GlobalManager

use of com.dexels.navajo.server.global.GlobalManager in project navajo by Dexels.

the class Dispatcher method processNavajo.

/**
 * Handle a webservice.
 *
 * @param inMessage
 * @param userCertificate
 * @param clientInfo
 * @param origRunnable
 * @param skipAuth
 *            , always skip authorization part.
 * @return
 * @throws FatalException
 */
private final Navajo processNavajo(Navajo inMessage, String instance, Object userCertificate, ClientInfo clientInfo, boolean skipAuth, TmlRunnable origRunnable, AfterWebServiceEmitter emit) throws FatalException {
    Access access = null;
    Navajo outMessage = null;
    String rpcName = "";
    String rpcUser = "";
    String rpcPassword = "";
    Throwable myException = null;
    String origThreadName = null;
    boolean scheduledWebservice = false;
    boolean afterWebServiceActivated = false;
    int accessSetSize = accessSet.size();
    setRequestRate(clientInfo, accessSetSize);
    Navajo result = handleCallbackPointers(inMessage, instance);
    if (result != null) {
        return result;
    }
    Header header = inMessage.getHeader();
    rpcName = header.getRPCName();
    rpcUser = header.getRPCUser();
    rpcPassword = header.getRPCPassword();
    boolean preventFinalize = false;
    try {
        /**
         * Phase II: Authorisation/Authentication of the user. Is the user
         * known and valid and may it use the specified service? Also log
         * the access.
         */
        long startAuth = System.currentTimeMillis();
        if (rpcName == null) {
            throw new FatalException("No script defined");
        }
        if (rpcName.equals("navajo_ping")) {
            // Ping!
            outMessage = NavajoFactory.getInstance().createNavajo();
            Header h = NavajoFactory.getInstance().createHeader(outMessage, "", "", "", -1);
            outMessage.addHeader(h);
            return outMessage;
        }
        access = new Access(1, 1, rpcUser, rpcName, "", "", "", userCertificate, false, null);
        access.setTenant(instance);
        access.rpcPwd = rpcPassword;
        access.setInDoc(inMessage);
        access.setClientDescription(header.getHeaderAttribute("clientdescription"));
        access.setApplication(header.getHeaderAttribute("application"));
        access.setOrganization(header.getHeaderAttribute("organization"));
        if (clientInfo != null) {
            access.ipAddress = clientInfo.getIP();
            access.hostName = clientInfo.getHost();
        }
        NavajoEventRegistry.getInstance().publishEvent(new NavajoRequestEvent(access));
        appendGlobals(inMessage, instance);
        if (useAuthorisation && !skipAuth) {
            try {
                if (navajoConfig == null) {
                    throw new FatalException("EMPTY NAVAJOCONFIG, INVALID STATE OF DISPATCHER!");
                }
                // if (instance == null) {
                // throw new SystemException(-1, "No tenant set -cannot authenticate!");
                // }
                // Determine authenticator
                final AuthenticationMethod authenticator;
                if (clientInfo == null) {
                    authenticator = authMethodBuilder.getInstanceForRequest(null);
                } else {
                    authenticator = authMethodBuilder.getInstanceForRequest(clientInfo.getAuthHeader());
                }
                if (authenticator == null) {
                    throw new FatalException("Missing authenticator");
                }
                authenticator.process(access);
            } catch (AuthorizationException ex) {
                outMessage = generateAuthorizationErrorMessage(access, ex, rpcName);
                AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + ex.getMessage(), Level.WARNING);
                access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                return outMessage;
            }/*catch (SystemException se) { //
                    logger.error("SystemException on authenticateUser  {} for {}: ", rpcUser, rpcName, se);
                    outMessage = generateErrorMessage(access, se.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
                    AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + se.getMessage(),
                            Level.WARNING);
                    access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                    return outMessage;
                }*/
             catch (Throwable t) {
                logger.error("Unexpected exception on authenticateUser  {} for {}: ", rpcUser, rpcName, t);
                outMessage = generateErrorMessage(access, t.getMessage(), SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
                access.setExitCode(Access.EXIT_AUTH_EXECPTION);
                access.setException(t);
                return outMessage;
            }
        }
        if (clientInfo != null) {
            access.ipAddress = clientInfo.getIP();
            access.hostName = clientInfo.getHost();
            access.parseTime = clientInfo.getParseTime();
            access.queueTime = clientInfo.getQueueTime();
            access.requestEncoding = clientInfo.getEncoding();
            access.compressedReceive = clientInfo.isCompressedRecv();
            access.compressedSend = clientInfo.isCompressedSend();
            access.contentLength = clientInfo.getContentLength();
            access.created = clientInfo.getCreated();
            access.queueId = clientInfo.getQueueId();
            access.queueSize = clientInfo.getQueueSize();
            // Set the name of this thread.
            origThreadName = Thread.currentThread().getName();
            Thread.currentThread().setName(getThreadName(access));
        }
        final GlobalManager gm;
        if (instance != null) {
            gm = globalManagers.get(instance);
        } else {
            gm = globalManagers.get("default");
        }
        if (gm != null) {
            gm.initGlobals(inMessage);
        }
        if (origRunnable != null) {
            access.setOriginalRunnable(origRunnable);
            // and vice versa, for the endTransaction
            origRunnable.setAttribute("access", access);
        }
        String fullLog = inMessage.getHeader().getHeaderAttribute("fullLog");
        if ("true".equals(fullLog)) {
            logger.info("Full debug detected. Accesshash: {}", access.hashCode());
            access.setDebugAll(true);
        }
        if ((access.userID == -1) || (access.serviceID == -1)) {
            // ACCESS NOTGRANTED.
            String errorMessage = "";
            if (access.userID == -1) {
                errorMessage = "Cannot authenticate user: " + rpcUser;
            } else {
                errorMessage = "Cannot authorise use of: " + rpcName;
            }
            outMessage = generateErrorMessage(access, errorMessage, SystemException.NOT_AUTHORISED, 1, new Exception("NOT AUTHORISED"));
            return outMessage;
        } else {
            // ACCESS GRANTED.
            access.authorisationTime = (int) (System.currentTimeMillis() - startAuth);
            accessSet.add(access);
            // username might've changed as the username might've been a placeholder while we're authenticating using a bearer token
            rpcUser = access.getRpcUser();
            // Be very defensive not to add null values to the MDC, as they will fail at unexpected moments
            if (access.accessID != null) {
                MDC.put("accessId", access.accessID);
            }
            if (access.getRpcName() != null) {
                MDC.put("rpcName", access.getRpcName());
            }
            if (access.getRpcUser() != null) {
                MDC.put("rpcUser", access.getRpcUser());
            }
            if (access.getTenant() != null) {
                MDC.put("tenant", access.getTenant());
            }
            if (getNavajoConfig().getRootPath() != null) {
                MDC.put("rootPath", getNavajoConfig().getRootPath());
            }
            if (getNavajoConfig().getInstanceName() != null) {
                MDC.put("instanceName", getNavajoConfig().getInstanceName());
            }
            if (getNavajoConfig().getInstanceGroup() != null) {
                MDC.put("instanceGroup", getNavajoConfig().getInstanceGroup());
            }
            if (inMessage.getHeader().getSchedule() != null && !inMessage.getHeader().getSchedule().equals("")) {
                if (validTimeSpecification(inMessage.getHeader().getSchedule())) {
                    scheduledWebservice = true;
                    logger.info("Scheduling webservice: {}  on {} ", inMessage.getHeader().getRPCName(), inMessage.getHeader().getSchedule());
                    TaskRunnerInterface trf = TaskRunnerFactory.getInstance();
                    TaskInterface ti = trf.createTask();
                    try {
                        ti.setTrigger(inMessage.getHeader().getSchedule());
                        ti.setNavajo(inMessage);
                        // Make sure task gets persisted in tasks.xml
                        ti.setPersisted(true);
                        if (inMessage.getHeader().getHeaderAttribute("keeprequestresponse") != null && inMessage.getHeader().getHeaderAttribute("keeprequestresponse").equals("true")) {
                            ti.setKeepRequestResponse(true);
                        }
                        trf.addTask(ti);
                        outMessage = generateScheduledMessage(inMessage.getHeader(), ti.getId(), false);
                    } catch (TriggerException e) {
                        logger.info("WARNING: Invalid trigger specified for task {}: {}", ti.getId(), inMessage.getHeader().getSchedule());
                        trf.removeTask(ti);
                        outMessage = generateErrorMessage(access, "Could not schedule task:" + e.getMessage(), -1, -1, e);
                    }
                } else {
                    // obsolete time specification
                    outMessage = generateScheduledMessage(inMessage.getHeader(), null, true);
                }
            } else {
                /**
                 * Phase VI: Dispatch to proper servlet.
                 */
                // Create beforeWebservice event.
                access.setInDoc(inMessage);
                long bstart = System.currentTimeMillis();
                Navajo useProxy = (WebserviceListenerFactory.getInstance() != null ? WebserviceListenerFactory.getInstance().beforeWebservice(rpcName, access) : null);
                access.setBeforeServiceTime((int) (System.currentTimeMillis() - bstart));
                if (useAuthorisation) {
                    if (useProxy == null) {
                        outMessage = dispatch(access);
                    } else {
                        rpcName = access.rpcName;
                        outMessage = useProxy;
                    }
                } else {
                    throw new UnsupportedOperationException("I've removed this code because I assumed it wasn't used any more");
                }
            }
        }
    } catch (AuthorizationException aee) {
        outMessage = generateAuthorizationErrorMessage(access, aee, rpcName);
        AuditLog.log(AuditLog.AUDIT_MESSAGE_AUTHORISATION, "(service=" + rpcName + ", user=" + rpcUser + ", message=" + aee.getMessage() + ")", Level.WARNING);
        myException = aee;
        access.setExitCode(Access.EXIT_AUTH_EXECPTION);
        return outMessage;
    } catch (UserException ue) {
        try {
            outMessage = generateErrorMessage(access, ue.getMessage(), ue.code, 1, (ue.getCause() != null ? ue.getCause() : ue));
            myException = ue;
            return outMessage;
        } catch (Exception ee) {
            logger.error("Error: ", ee);
            myException = ee;
            return errorHandler(access, ee, inMessage);
        }
    } catch (SystemException se) {
        logger.error("Error: ", se);
        myException = se;
        try {
            outMessage = generateErrorMessage(access, se.getMessage(), se.code, 1, (se.getCause() != null ? se.getCause() : se));
            return outMessage;
        } catch (Exception ee) {
            logger.error("Error: ", ee);
            return errorHandler(access, ee, inMessage);
        }
    } catch (Throwable e) {
        logger.error("Error: ", e);
        myException = e;
        return errorHandler(access, e, inMessage);
    } finally {
        if (!preventFinalize) {
            finalizeService(inMessage, access, rpcName, rpcUser, myException, origThreadName, scheduledWebservice, afterWebServiceActivated, emit);
        }
    }
    return access.getOutputDoc();
}
Also used : FatalException(com.dexels.navajo.script.api.FatalException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) Access(com.dexels.navajo.script.api.Access) Navajo(com.dexels.navajo.document.Navajo) AuthenticationMethod(com.dexels.navajo.authentication.api.AuthenticationMethod) NavajoRequestEvent(com.dexels.navajo.events.types.NavajoRequestEvent) FatalException(com.dexels.navajo.script.api.FatalException) NavajoException(com.dexels.navajo.document.NavajoException) AuthorizationException(com.dexels.navajo.script.api.AuthorizationException) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException) IOException(java.io.IOException) SystemException(com.dexels.navajo.script.api.SystemException) Header(com.dexels.navajo.document.Header) GlobalManager(com.dexels.navajo.server.global.GlobalManager) SystemException(com.dexels.navajo.script.api.SystemException) TaskRunnerInterface(com.dexels.navajo.server.enterprise.scheduler.TaskRunnerInterface) TaskInterface(com.dexels.navajo.server.enterprise.scheduler.TaskInterface) UserException(com.dexels.navajo.script.api.UserException) TriggerException(com.dexels.navajo.server.enterprise.scheduler.TriggerException)

Example 3 with GlobalManager

use of com.dexels.navajo.server.global.GlobalManager in project navajo by Dexels.

the class Dispatcher method appendGlobals.

private void appendGlobals(Navajo inMessage, String instance) {
    final GlobalManagerRepository globalManagerInstance = GlobalManagerRepositoryFactory.getGlobalManagerInstance();
    if (globalManagerInstance == null) {
        logger.debug("No global manager found");
    }
    GlobalManager gm = null;
    if (globalManagerInstance != null) {
        if (instance == null) {
            gm = globalManagerInstance.getGlobalManager("default");
        } else {
            gm = globalManagerInstance.getGlobalManager(instance);
        }
    }
    if (gm != null) {
        gm.initGlobals(inMessage);
    }
}
Also used : GlobalManager(com.dexels.navajo.server.global.GlobalManager) GlobalManagerRepository(com.dexels.navajo.server.global.GlobalManagerRepository)

Aggregations

GlobalManager (com.dexels.navajo.server.global.GlobalManager)3 FatalException (com.dexels.navajo.script.api.FatalException)2 GlobalManagerRepository (com.dexels.navajo.server.global.GlobalManagerRepository)2 IOException (java.io.IOException)2 AuthenticationMethod (com.dexels.navajo.authentication.api.AuthenticationMethod)1 Header (com.dexels.navajo.document.Header)1 Navajo (com.dexels.navajo.document.Navajo)1 NavajoException (com.dexels.navajo.document.NavajoException)1 NavajoRequestEvent (com.dexels.navajo.events.types.NavajoRequestEvent)1 Access (com.dexels.navajo.script.api.Access)1 AuthorizationException (com.dexels.navajo.script.api.AuthorizationException)1 SystemException (com.dexels.navajo.script.api.SystemException)1 UserException (com.dexels.navajo.script.api.UserException)1 TaskInterface (com.dexels.navajo.server.enterprise.scheduler.TaskInterface)1 TaskRunnerInterface (com.dexels.navajo.server.enterprise.scheduler.TaskRunnerInterface)1 TriggerException (com.dexels.navajo.server.enterprise.scheduler.TriggerException)1 ServletException (javax.servlet.ServletException)1