Search in sources :

Example 21 with Manager

use of org.apache.catalina.Manager in project tomcat by apache.

the class ManagerServlet method sessions.

/**
 * Session information for the web application at the specified context path.
 * Displays a profile of session thisAccessedTime listing number
 * of sessions for each 10 minute interval up to 10 hours.
 *
 * @param writer Writer to render to
 * @param cn Name of the application to list session information for
 * @param idle Expire all sessions with idle time > idle for this context
 * @param smClient i18n support for current client's locale
 */
protected void sessions(PrintWriter writer, ContextName cn, int idle, StringManager smClient) {
    if (debug >= 1) {
        log("sessions: Session information for web application '" + cn + "'");
        if (idle >= 0) {
            log("sessions: Session expiration for " + idle + " minutes '" + cn + "'");
        }
    }
    if (!validateContextName(cn, writer, smClient)) {
        return;
    }
    String displayPath = cn.getDisplayName();
    try {
        Context context = (Context) host.findChild(cn.getName());
        if (context == null) {
            writer.println(smClient.getString("managerServlet.noContext", Escape.htmlElementContent(displayPath)));
            return;
        }
        Manager manager = context.getManager();
        if (manager == null) {
            writer.println(smClient.getString("managerServlet.noManager", Escape.htmlElementContent(displayPath)));
            return;
        }
        int maxCount = 60;
        int histoInterval = 1;
        int maxInactiveInterval = context.getSessionTimeout();
        if (maxInactiveInterval > 0) {
            histoInterval = maxInactiveInterval / maxCount;
            if (histoInterval * maxCount < maxInactiveInterval) {
                histoInterval++;
            }
            if (0 == histoInterval) {
                histoInterval = 1;
            }
            maxCount = maxInactiveInterval / histoInterval;
            if (histoInterval * maxCount < maxInactiveInterval) {
                maxCount++;
            }
        }
        writer.println(smClient.getString("managerServlet.sessions", displayPath));
        writer.println(smClient.getString("managerServlet.sessiondefaultmax", "" + maxInactiveInterval));
        Session[] sessions = manager.findSessions();
        int[] timeout = new int[maxCount + 1];
        int notimeout = 0;
        int expired = 0;
        for (Session session : sessions) {
            int time = (int) (session.getIdleTimeInternal() / 1000L);
            if (idle >= 0 && time >= idle * 60) {
                session.expire();
                expired++;
            }
            time = time / 60 / histoInterval;
            if (time < 0) {
                notimeout++;
            } else if (time >= maxCount) {
                timeout[maxCount]++;
            } else {
                timeout[time]++;
            }
        }
        if (timeout[0] > 0) {
            writer.println(smClient.getString("managerServlet.sessiontimeout", "<" + histoInterval, "" + timeout[0]));
        }
        for (int i = 1; i < maxCount; i++) {
            if (timeout[i] > 0) {
                writer.println(smClient.getString("managerServlet.sessiontimeout", "" + (i) * histoInterval + " - <" + (i + 1) * histoInterval, "" + timeout[i]));
            }
        }
        if (timeout[maxCount] > 0) {
            writer.println(smClient.getString("managerServlet.sessiontimeout", ">=" + maxCount * histoInterval, "" + timeout[maxCount]));
        }
        if (notimeout > 0) {
            writer.println(smClient.getString("managerServlet.sessiontimeout.unlimited", "" + notimeout));
        }
        if (idle >= 0) {
            writer.println(smClient.getString("managerServlet.sessiontimeout.expired", ">" + idle, "" + expired));
        }
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log(sm.getString("managerServlet.error.sessions", displayPath), t);
        writer.println(smClient.getString("managerServlet.exception", t.toString()));
    }
}
Also used : SSLContext(org.apache.tomcat.util.net.SSLContext) ServletContext(jakarta.servlet.ServletContext) Context(org.apache.catalina.Context) StringManager(org.apache.tomcat.util.res.StringManager) Manager(org.apache.catalina.Manager) Session(org.apache.catalina.Session)

Example 22 with Manager

use of org.apache.catalina.Manager in project tomcat by apache.

the class StandardContextSF method storeChildren.

/**
 * Store the specified context element children.
 *
 * @param aWriter Current output writer
 * @param indent Indentation level
 * @param aContext Context to store
 * @param parentDesc The element description
 * @throws Exception Configuration storing error
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aContext, StoreDescription parentDesc) throws Exception {
    if (aContext instanceof StandardContext) {
        StandardContext context = (StandardContext) aContext;
        // Store nested <Listener> elements
        LifecycleListener[] listeners = context.findLifecycleListeners();
        List<LifecycleListener> listenersArray = new ArrayList<>();
        for (LifecycleListener listener : listeners) {
            if (!(listener instanceof ThreadLocalLeakPreventionListener)) {
                listenersArray.add(listener);
            }
        }
        storeElementArray(aWriter, indent, listenersArray.toArray());
        // Store nested <Valve> elements
        Valve[] valves = context.getPipeline().getValves();
        storeElementArray(aWriter, indent, valves);
        // Store nested <Loader> elements
        Loader loader = context.getLoader();
        storeElement(aWriter, indent, loader);
        // Store nested <Manager> elements
        if (context.getCluster() == null || !context.getDistributable()) {
            Manager manager = context.getManager();
            storeElement(aWriter, indent, manager);
        }
        // Store nested <Realm> element
        Realm realm = context.getRealm();
        if (realm != null) {
            Realm parentRealm = null;
            // @TODO is this case possible?
            if (context.getParent() != null) {
                parentRealm = context.getParent().getRealm();
            }
            if (realm != parentRealm) {
                storeElement(aWriter, indent, realm);
            }
        }
        // Store nested resources
        WebResourceRoot resources = context.getResources();
        storeElement(aWriter, indent, resources);
        // Store nested <WrapperListener> elements
        String[] wLifecycles = context.findWrapperLifecycles();
        getStoreAppender().printTagArray(aWriter, "WrapperListener", indent + 2, wLifecycles);
        // Store nested <WrapperLifecycle> elements
        String[] wListeners = context.findWrapperListeners();
        getStoreAppender().printTagArray(aWriter, "WrapperLifecycle", indent + 2, wListeners);
        // Store nested <Parameter> elements
        ApplicationParameter[] appParams = context.findApplicationParameters();
        storeElementArray(aWriter, indent, appParams);
        // Store nested naming resources elements (EJB,Resource,...)
        NamingResourcesImpl nresources = context.getNamingResources();
        storeElement(aWriter, indent, nresources);
        // Store nested watched resources <WatchedResource>
        String[] wresources = context.findWatchedResources();
        wresources = filterWatchedResources(context, wresources);
        getStoreAppender().printTagArray(aWriter, "WatchedResource", indent + 2, wresources);
        // Store nested <JarScanner> elements
        JarScanner jarScanner = context.getJarScanner();
        storeElement(aWriter, indent, jarScanner);
        // Store nested <CookieProcessor> elements
        CookieProcessor cookieProcessor = context.getCookieProcessor();
        storeElement(aWriter, indent, cookieProcessor);
    }
}
Also used : ApplicationParameter(org.apache.tomcat.util.descriptor.web.ApplicationParameter) ArrayList(java.util.ArrayList) Loader(org.apache.catalina.Loader) LifecycleListener(org.apache.catalina.LifecycleListener) Manager(org.apache.catalina.Manager) JarScanner(org.apache.tomcat.JarScanner) ThreadLocalLeakPreventionListener(org.apache.catalina.core.ThreadLocalLeakPreventionListener) CookieProcessor(org.apache.tomcat.util.http.CookieProcessor) StandardContext(org.apache.catalina.core.StandardContext) Valve(org.apache.catalina.Valve) NamingResourcesImpl(org.apache.catalina.deploy.NamingResourcesImpl) Realm(org.apache.catalina.Realm) WebResourceRoot(org.apache.catalina.WebResourceRoot)

Example 23 with Manager

use of org.apache.catalina.Manager in project tomcat by apache.

the class StandardContext method stopInternal.

/**
 * Stop this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void stopInternal() throws LifecycleException {
    // Send j2ee.state.stopping notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    // Context has been removed from Mapper at this point (so no new
    // requests will be mapped) but is still available.
    // Give the in progress async requests a chance to complete
    long limit = System.currentTimeMillis() + unloadDelay;
    while (inProgressAsyncCount.get() > 0 && System.currentTimeMillis() < limit) {
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            log.info(sm.getString("standardContext.stop.asyncWaitInterrupted"), e);
            break;
        }
    }
    // Once the state is set to STOPPING, the Context will report itself as
    // not available and any in progress async requests will timeout
    setState(LifecycleState.STOPPING);
    // Binding thread
    ClassLoader oldCCL = bindThread();
    try {
        // Stop our child containers, if any
        final Container[] children = findChildren();
        // Stop ContainerBackgroundProcessor thread
        threadStop();
        for (Container child : children) {
            child.stop();
        }
        // Stop our filters
        filterStop();
        Manager manager = getManager();
        if (manager instanceof Lifecycle && ((Lifecycle) manager).getState().isAvailable()) {
            ((Lifecycle) manager).stop();
        }
        // Stop our application listeners
        listenerStop();
        // Finalize our character set mapper
        setCharsetMapper(null);
        // Normal container shutdown processing
        if (log.isDebugEnabled()) {
            log.debug("Processing standard container shutdown");
        }
        // after the application has finished with the resource
        if (namingResources != null) {
            namingResources.stop();
        }
        fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null);
        // Stop the Valves in our pipeline (including the basic), if any
        if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) {
            ((Lifecycle) pipeline).stop();
        }
        // Clear all application-originated servlet context attributes
        if (context != null) {
            context.clearAttributes();
        }
        Realm realm = getRealmInternal();
        if (realm instanceof Lifecycle) {
            ((Lifecycle) realm).stop();
        }
        Loader loader = getLoader();
        if (loader instanceof Lifecycle) {
            ClassLoader classLoader = loader.getClassLoader();
            ((Lifecycle) loader).stop();
            if (classLoader != null) {
                InstanceManagerBindings.unbind(classLoader);
            }
        }
        // Stop resources
        resourcesStop();
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    // Send j2ee.state.stopped notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    // Reset application context
    context = null;
    // This object will no longer be visible or used.
    try {
        resetContext();
    } catch (Exception ex) {
        log.error("Error resetting context " + this + " " + ex, ex);
    }
    // reset the instance manager
    setInstanceManager(null);
    if (log.isDebugEnabled()) {
        log.debug("Stopping complete");
    }
}
Also used : Container(org.apache.catalina.Container) Lifecycle(org.apache.catalina.Lifecycle) WebappLoader(org.apache.catalina.loader.WebappLoader) Loader(org.apache.catalina.Loader) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager) StandardManager(org.apache.catalina.session.StandardManager) Realm(org.apache.catalina.Realm) Notification(javax.management.Notification) ServletException(jakarta.servlet.ServletException) LifecycleException(org.apache.catalina.LifecycleException) ListenerNotFoundException(javax.management.ListenerNotFoundException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) MalformedURLException(java.net.MalformedURLException)

Example 24 with Manager

use of org.apache.catalina.Manager in project tomcat by apache.

the class StandardContext method startInternal.

/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {
    if (log.isDebugEnabled()) {
        log.debug("Starting " + getBaseName());
    }
    // Send j2ee.state.starting notification
    if (this.getObjectName() != null) {
        Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    setConfigured(false);
    boolean ok = true;
    // ensure the NamingResources follows the correct lifecycle
    if (namingResources != null) {
        namingResources.start();
    }
    // Post work directory
    postWorkDirectory();
    // Add missing components as necessary
    if (getResources() == null) {
        // (1) Required by Loader
        if (log.isDebugEnabled()) {
            log.debug("Configuring default Resources");
        }
        try {
            setResources(new StandardRoot(this));
        } catch (IllegalArgumentException e) {
            log.error(sm.getString("standardContext.resourcesInit"), e);
            ok = false;
        }
    }
    if (ok) {
        resourcesStart();
    }
    if (getLoader() == null) {
        WebappLoader webappLoader = new WebappLoader();
        webappLoader.setDelegate(getDelegate());
        setLoader(webappLoader);
    }
    // An explicit cookie processor hasn't been specified; use the default
    if (cookieProcessor == null) {
        cookieProcessor = new Rfc6265CookieProcessor();
    }
    // Initialize character set mapper
    getCharsetMapper();
    // Reading the "catalina.useNaming" environment variable
    String useNamingProperty = System.getProperty("catalina.useNaming");
    if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) {
        useNaming = false;
    }
    if (ok && isUseNaming()) {
        if (getNamingContextListener() == null) {
            NamingContextListener ncl = new NamingContextListener();
            ncl.setName(getNamingContextName());
            ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite());
            addLifecycleListener(ncl);
            setNamingContextListener(ncl);
        }
    }
    // Standard container startup
    if (log.isDebugEnabled()) {
        log.debug("Processing standard container startup");
    }
    // Binding thread
    ClassLoader oldCCL = bindThread();
    try {
        if (ok) {
            // Start our subordinate components, if any
            Loader loader = getLoader();
            if (loader instanceof Lifecycle) {
                ((Lifecycle) loader).start();
            }
            // created.
            if (loader.getClassLoader() instanceof WebappClassLoaderBase) {
                WebappClassLoaderBase cl = (WebappClassLoaderBase) loader.getClassLoader();
                cl.setClearReferencesRmiTargets(getClearReferencesRmiTargets());
                cl.setClearReferencesStopThreads(getClearReferencesStopThreads());
                cl.setClearReferencesStopTimerThreads(getClearReferencesStopTimerThreads());
                cl.setClearReferencesHttpClientKeepAliveThread(getClearReferencesHttpClientKeepAliveThread());
                cl.setClearReferencesObjectStreamClassCaches(getClearReferencesObjectStreamClassCaches());
                cl.setClearReferencesThreadLocals(getClearReferencesThreadLocals());
            }
            // By calling unbindThread and bindThread in a row, we setup the
            // current Thread CCL to be the webapp classloader
            unbindThread(oldCCL);
            oldCCL = bindThread();
            // Initialize logger again. Other components might have used it
            // too early, so it should be reset.
            logger = null;
            getLogger();
            Realm realm = getRealmInternal();
            if (null != realm) {
                if (realm instanceof Lifecycle) {
                    ((Lifecycle) realm).start();
                }
                // Place the CredentialHandler into the ServletContext so
                // applications can have access to it. Wrap it in a "safe"
                // handler so application's can't modify it.
                CredentialHandler safeHandler = new CredentialHandler() {

                    @Override
                    public boolean matches(String inputCredentials, String storedCredentials) {
                        return getRealmInternal().getCredentialHandler().matches(inputCredentials, storedCredentials);
                    }

                    @Override
                    public String mutate(String inputCredentials) {
                        return getRealmInternal().getCredentialHandler().mutate(inputCredentials);
                    }
                };
                context.setAttribute(Globals.CREDENTIAL_HANDLER, safeHandler);
            }
            // Notify our interested LifecycleListeners
            fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null);
            // Start our child containers, if not already started
            for (Container child : findChildren()) {
                if (!child.getState().isAvailable()) {
                    child.start();
                }
            }
            // if any
            if (pipeline instanceof Lifecycle) {
                ((Lifecycle) pipeline).start();
            }
            // Acquire clustered manager
            Manager contextManager = null;
            Manager manager = getManager();
            if (manager == null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable)));
                }
                if ((getCluster() != null) && distributable) {
                    try {
                        contextManager = getCluster().createManager(getName());
                    } catch (Exception ex) {
                        log.error(sm.getString("standardContext.cluster.managerError"), ex);
                        ok = false;
                    }
                } else {
                    contextManager = new StandardManager();
                }
            }
            // Configure default manager if none was specified
            if (contextManager != null) {
                if (log.isDebugEnabled()) {
                    log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName()));
                }
                setManager(contextManager);
            }
            if (manager != null && (getCluster() != null) && distributable) {
                // let the cluster know that there is a context that is distributable
                // and that it has its own manager
                getCluster().registerManager(manager);
            }
        }
        if (!getConfigured()) {
            log.error(sm.getString("standardContext.configurationFail"));
            ok = false;
        }
        // We put the resources into the servlet context
        if (ok) {
            getServletContext().setAttribute(Globals.RESOURCES_ATTR, getResources());
            if (getInstanceManager() == null) {
                setInstanceManager(createInstanceManager());
            }
            getServletContext().setAttribute(InstanceManager.class.getName(), getInstanceManager());
            InstanceManagerBindings.bind(getLoader().getClassLoader(), getInstanceManager());
            // Create context attributes that will be required
            getServletContext().setAttribute(JarScanner.class.getName(), getJarScanner());
            // Make the version info available
            getServletContext().setAttribute(Globals.WEBAPP_VERSION, getWebappVersion());
        }
        // Set up the context init params
        mergeParameters();
        // Call ServletContainerInitializers
        for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) {
            try {
                entry.getKey().onStartup(entry.getValue(), getServletContext());
            } catch (ServletException e) {
                log.error(sm.getString("standardContext.sciFail"), e);
                ok = false;
                break;
            }
        }
        // Configure and call application event listeners
        if (ok) {
            if (!listenerStart()) {
                log.error(sm.getString("standardContext.listenerFail"));
                ok = false;
            }
        }
        // change constraints
        if (ok) {
            checkConstraintsForUncoveredMethods(findConstraints());
        }
        try {
            // Start manager
            Manager manager = getManager();
            if (manager instanceof Lifecycle) {
                ((Lifecycle) manager).start();
            }
        } catch (Exception e) {
            log.error(sm.getString("standardContext.managerFail"), e);
            ok = false;
        }
        // Configure and call application filters
        if (ok) {
            if (!filterStart()) {
                log.error(sm.getString("standardContext.filterFail"));
                ok = false;
            }
        }
        // Load and initialize all "load on startup" servlets
        if (ok) {
            if (!loadOnStartup(findChildren())) {
                log.error(sm.getString("standardContext.servletFail"));
                ok = false;
            }
        }
        // Start ContainerBackgroundProcessor thread
        super.threadStart();
    } finally {
        // Unbinding thread
        unbindThread(oldCCL);
    }
    // Set available status depending upon startup success
    if (ok) {
        if (log.isDebugEnabled()) {
            log.debug("Starting completed");
        }
    } else {
        log.error(sm.getString("standardContext.startFailed", getName()));
    }
    startTime = System.currentTimeMillis();
    // Send j2ee.state.running notification
    if (ok && (this.getObjectName() != null)) {
        Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement());
        broadcaster.sendNotification(notification);
    }
    // The WebResources implementation caches references to JAR files. On
    // some platforms these references may lock the JAR files. Since web
    // application start is likely to have read from lots of JARs, trigger
    // a clean-up now.
    getResources().gc();
    // Reinitializing if something went wrong
    if (!ok) {
        setState(LifecycleState.FAILED);
        // Send j2ee.object.failed notification
        if (this.getObjectName() != null) {
            Notification notification = new Notification("j2ee.object.failed", this.getObjectName(), sequenceNumber.getAndIncrement());
            broadcaster.sendNotification(notification);
        }
    } else {
        setState(LifecycleState.STARTING);
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) CredentialHandler(org.apache.catalina.CredentialHandler) InstanceManager(org.apache.tomcat.InstanceManager) StandardRoot(org.apache.catalina.webresources.StandardRoot) WebappLoader(org.apache.catalina.loader.WebappLoader) Loader(org.apache.catalina.Loader) Manager(org.apache.catalina.Manager) InstanceManager(org.apache.tomcat.InstanceManager) StandardManager(org.apache.catalina.session.StandardManager) StandardJarScanner(org.apache.tomcat.util.scan.StandardJarScanner) JarScanner(org.apache.tomcat.JarScanner) Notification(javax.management.Notification) ServletContainerInitializer(jakarta.servlet.ServletContainerInitializer) ServletException(jakarta.servlet.ServletException) Container(org.apache.catalina.Container) Rfc6265CookieProcessor(org.apache.tomcat.util.http.Rfc6265CookieProcessor) Realm(org.apache.catalina.Realm) Lifecycle(org.apache.catalina.Lifecycle) StandardManager(org.apache.catalina.session.StandardManager) ServletException(jakarta.servlet.ServletException) LifecycleException(org.apache.catalina.LifecycleException) ListenerNotFoundException(javax.management.ListenerNotFoundException) IOException(java.io.IOException) NamingException(javax.naming.NamingException) MalformedURLException(java.net.MalformedURLException) WebappClassLoaderBase(org.apache.catalina.loader.WebappClassLoaderBase) WebappLoader(org.apache.catalina.loader.WebappLoader) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 25 with Manager

use of org.apache.catalina.Manager in project tomcat by apache.

the class StoreBase method setManager.

/**
 * Set the Manager with which this Store is associated.
 *
 * @param manager The newly associated Manager
 */
@Override
public void setManager(Manager manager) {
    Manager oldManager = this.manager;
    this.manager = manager;
    support.firePropertyChange("manager", oldManager, this.manager);
}
Also used : StringManager(org.apache.tomcat.util.res.StringManager) Manager(org.apache.catalina.Manager)

Aggregations

Manager (org.apache.catalina.Manager)54 StringManager (org.apache.tomcat.util.res.StringManager)26 IOException (java.io.IOException)22 Session (org.apache.catalina.Session)22 Context (org.apache.catalina.Context)19 Container (org.apache.catalina.Container)13 LifecycleException (org.apache.catalina.LifecycleException)12 Lifecycle (org.apache.catalina.Lifecycle)11 Loader (org.apache.catalina.Loader)11 InstanceManager (org.apache.tomcat.InstanceManager)11 StandardManager (org.apache.catalina.session.StandardManager)10 Realm (org.apache.catalina.Realm)9 ServletException (javax.servlet.ServletException)7 ArrayList (java.util.ArrayList)6 NamingException (javax.naming.NamingException)6 Cluster (org.apache.catalina.Cluster)6 DistributedManager (org.apache.catalina.DistributedManager)6 StandardContext (org.apache.catalina.core.StandardContext)6 WebappLoader (org.apache.catalina.loader.WebappLoader)6 ServletException (jakarta.servlet.ServletException)5