Search
Calendar
March 2024
S M T W T F S
« Sep    
 12
3456789
10111213141516
17181920212223
24252627282930
31  
Your widget title
Archives

Posts Tagged ‘Mule ESB’

PostHeaderIcon MissingResourceException / Mule / i18n

The following error is among of the most hated ones in Mule ESB:

java.util.MissingResourceException: Can't find bundle for base name META-INF.services.org.mule.i18n.core-messages, locale en_US

.

I am not going to describe how to fix it, since several and various reasons may induce it. Anyway, here is an action plan to track and isolate the bug when it happens.

Usually, this MissingResourceException hides the actual error, instead of encapsulating and throwing it. For instance, consider the following stacktrace:

Can't find bundle for base name META-INF.services.org.mule.i18n.core-messages, locale en_USjava.util.MissingResourceException: Can't find bundle for base name META-INF.services.org.mule.i18n.core-messages, locale en_US
	at java.util.ResourceBundle.throwMissingResourceException(ResourceBundle.java:1427)
	at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1250)
	at java.util.ResourceBundle.getBundle(ResourceBundle.java:952)
	at org.mule.config.i18n.MessageFactory.getBundle(MessageFactory.java:211)
	at org.mule.config.i18n.MessageFactory.getString(MessageFactory.java:181)
	at org.mule.config.i18n.MessageFactory.createMessage(MessageFactory.java:108)
	at org.mule.config.i18n.MessageFactory.createMessage(MessageFactory.java:59)
	at org.mule.config.i18n.CoreMessages.initialisationFailure(CoreMessages.java:400)
	at org.mule.module.scripting.expression.AbstractScriptExpressionEvaluator.getScript(AbstractScriptExpressionEvaluator.java:93)
	at org.mule.module.scripting.expression.AbstractScriptExpressionEvaluator.evaluate(AbstractScriptExpressionEvaluator.java:54)
	at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:274)
	at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:210)
	at org.mule.expression.DefaultExpressionManager.evaluate(DefaultExpressionManager.java:170)
	at org.mule.transformer.simple.MessagePropertiesTransformer.addProperties(MessagePropertiesTransformer.java:165)
	at org.mule.transformer.simple.MessagePropertiesTransformer.transformMessage(MessagePropertiesTransformer.java:93)
	at org.mule.transformer.AbstractMessageTransformer.transform(AbstractMessageTransformer.java:145)
	at org.mule.transformer.AbstractMessageTransformer.transform(AbstractMessageTransformer.java:93)
	at org.mule.DefaultMuleMessage.applyAllTransformers(DefaultMuleMessage.java:1305)
	at org.mule.DefaultMuleMessage.applyTransformers(DefaultMuleMessage.java:1265)
	at org.mule.DefaultMuleMessage.applyTransformers(DefaultMuleMessage.java:1258)
	at org.mule.transformer.AbstractTransformer.process(AbstractTransformer.java:118)
	at org.mule.processor.ExceptionHandlingMessageProcessor.process(ExceptionHandlingMessageProcessor.java:25)
	at org.mule.transport.AbstractMessageReceiver.routeMessage(AbstractMessageReceiver.java:185)
	at org.mule.transport.AbstractReceiverWorker$1.doInTransaction(AbstractReceiverWorker.java:126)
	at org.mule.transaction.TransactionTemplate.execute(TransactionTemplate.java:116)
	at org.mule.transport.AbstractReceiverWorker.doRun(AbstractReceiverWorker.java:149)
	at org.mule.transport.AbstractReceiverWorker.run(AbstractReceiverWorker.java:64)
	at org.mule.work.WorkerContext.run(WorkerContext.java:309)
	at org.mule.work.SyncWorkExecutor.doExecute(SyncWorkExecutor.java:41)
	at org.mule.work.MuleWorkManager.executeWork(MuleWorkManager.java:251)
	at org.mule.work.MuleWorkManager.doWork(MuleWorkManager.java:175)
	at org.mule.transport.jms.MultiConsumerJmsMessageReceiver$SubReceiver.onMessage(MultiConsumerJmsMessageReceiver.java:326)
	at com.ibm.mq.jms.MQMessageConsumer$FacadeMessageListener.onMessage(MQMessageConsumer.java:399)
	at com.ibm.msg.client.jms.internal.JmsMessageConsumerImpl$JmsProviderMessageListener.onMessage(JmsMessageConsumerImpl.java:1023)
	at com.ibm.msg.client.wmq.internal.WMQAsyncConsumerShadow.honourNoLocal(WMQAsyncConsumerShadow.java:566)
	at com.ibm.msg.client.wmq.internal.WMQAsyncConsumerShadow.consumer(WMQAsyncConsumerShadow.java:400)
	at com.ibm.mq.jmqi.remote.internal.RemoteAsyncConsume.driveConsumer(RemoteAsyncConsume.java:1527)
	at com.ibm.mq.jmqi.remote.internal.RemoteDispatchThread.run(RemoteDispatchThread.java:395)
	at com.ibm.msg.client.commonservices.workqueue.WorkQueueItem.runTask(WorkQueueItem.java:209)
	at com.ibm.msg.client.commonservices.workqueue.SimpleWorkQueueItem.runItem(SimpleWorkQueueItem.java:100)
	at com.ibm.msg.client.commonservices.workqueue.WorkQueueItem.run(WorkQueueItem.java:224)
	at com.ibm.msg.client.commonservices.workqueue.WorkQueueManager.runWorkQueueItem(WorkQueueManager.java:298)
	at com.ibm.msg.client.commonservices.j2se.workqueue.WorkQueueManagerImplementation$ThreadPoolWorker.run(WorkQueueManagerImplementation.java:1220)V.

In IntelliJ IDEA, do Analyse > Analyse Stacktrace... > paste the trace (I have been shown the same tool for Eclipse, somewhere in the Console view). Now you can navigate easily in the code. Then you can notice, line #11, that the Exception you receive is raised by AbstractScriptExpressionEvaluator.
The corresponding piece of code is:

            try
            {
                script.initialise();
            }
            catch (InitialisationException e)
            {
                throw new MuleRuntimeException(
                    CoreMessages.initialisationFailure("An error occurred initialising script."), e);
            }

Add a breakpoint at the level of the throw. Start the debugger, reproduce the bug. In the debugger, you can see the actual error, that is hidden in the stacktrace. In my case, it was a:

org.mule.api.lifecycle.InitialisationException: Scripting engine 'groovy' not found.  Available engines are: [com.sun.script.javascript.RhinoScriptEngineFactory@3d2227]

. Without the debugger, it would have been hard to guess that the original MissingResourceException was linked to a missing Groovy resource ;-).

PostHeaderIcon Spring / Mule / CheckExclusiveAttributesException: The attributes of Element … do not match the exclusive groups …

Case

I have the following block in my Mule config file:

<servlet:inbound-endpoint path="authenticationService" address="http://localhost:1234">

. Even though this block matches XSD constraints, it is illegal from a functionnal point of view.

I get the following stacktrace:

Offending resource: mule-config.xml; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from class path resource [lalou/jonathan/mule-config.xml]; nested exception is org.mule.config.spring.parsers.processors.CheckExclusiveAttributes$CheckExclusiveAttributesException: The attributes of Element servlet:inbound-endpoint{address=http://localhost:1234, name=.authenticationService:inbound.157:inbound-endpoint.158, path=authenticationService} do not match the exclusive groups [address] [ref] [path]

Explanation and Fix

The exception is meaningful: for the tag <servlet:inbound-endpoint>, only one among the three following attributes is needed: path, ref and address.

To fix the issue, keep only the relevant attribute.

PostHeaderIcon Spring: Failed to read schema document

Case

I try to deploy a Mule ESB configuration, using this XML:

<?xml version="1.0" encoding="UTF-8"?>
<mule xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:pattern="http://www.mulesoft.org/schema/mule/pattern"
 xsi:schemaLocation="http://www.mulesoft.org/schema/mule/core
 http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd
 http://www.mulesoft.org/schema/mule/pattern
 http://www.mulesoft.org/schema/mule/pattern/3.1/mule-pattern.xsd
 ">
 <pattern:simple-service name="authenticationService"
 address="http://localhost:1234/authenticationService"
 component-class="lalou.jonathan.esb.components.AuthenticationComponent"
 type="direct" />
</mule>

I get the following error:

Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.mulesoft.org/schema/mule/pattern/3.1/mule-pattern.xsd'

Extended Stacktrace

2011-11-22 16:10:25,375 WARN  xml.XmlBeanDefinitionReader         - Ignored XML validation warning
org.xml.sax.SAXParseException: schema_reference.4: Failed to read schema document 'http://www.mulesoft.org/schema/mule/pattern/3.1/mule-pattern.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
 at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
 at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.warning(ErrorHandlerWrapper.java:96)
 at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:380)

Notice that Mule ESB files are similar to classic Spring files. Of course, I first checked the pointed XSD was actually reachable.
Anyway, this error should be raised when your application, for any reason -firewall, proxies, network interruption-, cannot access the remote site where the XSD is hosted.

Fix

  • Copy the XSD to a local folder
  • Create a file spring.schemas
  • Make it available in the classpath in META-INF.
  • Add the following line
  • http\://www.mulesoft.org/schema/mule/pattern/3.1/mule-pattern.xsd=WEB-INF/classes/mule-pattern.xsd

    The pattern is: missing resource (beware of escaping colon) = path in classpath of the local XSD

  • Rebuild, pack and run!

PostHeaderIcon Thread leaks in Mule ESB 2.2.1

Abstract

The application I work on packages Mule ESB 2.2.1 in a WAR and deploys it under a WebLogic 10.3 server. My team mates and I noticed that, on multiple deploy/undeploy cycles, the PermGen size dramatically decreased. The cause of this was the number of threads, which hardly decreased on undeployment phases, unlike the expected behaviour.
Indeed, Mule is seldom deployed as a WebApp. Rather, it is designed to be run as a standalone application, within a Tanuki wrapper. When the JVM is killed, all the threads are killed, too, and therefore no thread survives ; hence, the memory is freed and there is no reason to fear a thread leak.

Moreover, when the application is redeployed, new threads -with the same names as the “old” threads- are created. The risk is that, for any reason, a thread-name-based communication between threads may fail, because the communication pipe may be read by the wrong thread.

In my case: on WebLogic startup, there are 31 threads ; when the application is deployed, there are 150 ; when the application works (receives and handles messages), the number of threads climbs to 800 ; when the application is undeployed, only 12 threads are killed, the other remaining alive.

The question is: how to kill Mule-created threads, in order to avoid a Thread leak?

WebLogic Threads

I performed a thread dump at WebLogic startup. Here are WebLogic threads, created before any deployment occurs:

Attach Listener
DoSManager
DynamicListenThread[Default[1]]
DynamicListenThread[Default]
ExecuteThread: '0' for queue: 'weblogic.socket.Muxer'
ExecuteThread: '1' for queue: 'weblogic.socket.Muxer'
ExecuteThread: '2' for queue: 'weblogic.socket.Muxer'
Finalizer
JMX server connection timeout 42
RMI Scheduler(0)
RMI TCP Accept-0
RMI TCP Connection(1)-127.0.0.1
RMI TCP Connection(2)-127.0.0.1
Reference Handler
Signal Dispatcher
Thread-10
Thread-11
Timer-0
Timer-1
VDE Transaction Processor Thread
[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'
[ACTIVE] ExecuteThread: '2' for queue: 'weblogic.kernel.Default (self-tuning)'
[STANDBY] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'
[STANDBY] ExecuteThread: '3' for queue: 'weblogic.kernel.Default (self-tuning)'
[STANDBY] ExecuteThread: '4' for queue: 'weblogic.kernel.Default (self-tuning)'
[STANDBY] ExecuteThread: '5' for queue: 'weblogic.kernel.Default (self-tuning)'
main
weblogic.GCMonitor
weblogic.cluster.MessageReceiver
weblogic.time.TimeEventGenerator
weblogic.timers.TimerThread

Dispose Disposables, Stop Stoppables…

The application being deployed in a WAR, I created a servlet implementing ServletContextListener. In the method contextDestroyed(), I destroy Mule objects (Disposable, Stoppable, Model, Service, etc.) one per one.
Eg#1:

        final Collection<Model> allModels;
        try {
            allModels = MuleServer.getMuleContext().getRegistry().lookupObjects(Model.class);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Disposing models " + allModels.size());
            }
            for (Model model : allModels) {
                model.dispose();
            }
            allModels.clear();
        } catch (Exception e) {
            LOGGER.error(e);
        }

Eg#2:

    private void stopStoppables() {
        final Collection<Stoppable> allStoppables;
        try {
            allStoppables = MuleServer.getMuleContext().getRegistry().lookupObjects(Stoppable.class);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Stopping stoppables " + allStoppables.size());
            }
            for (Stoppable stoppable : allStoppables) {
                stoppable.stop();
            }
            allStoppables.clear();
        } catch (MuleException e) {
            LOGGER.error(e);
        }
    }

This first step is needed because default mechanism is flawed: Mule re-creates objects that were destroyed.

Kill Threads

The general idea to kill Mule threads is the following: perform a Unix-style “diff” between WebLogic native threads, and the threads still alive once all Mule objects have been stopped and disposed.

On Application Startup

In the ServletContextListener, I add a field that will be set in a method called in the constructor:

    private List<String> threadsAtStartup;
(...)
/**
     * This method retrieves the Threads present at startup: mainly speaking, they are Threads related to WebLogic.
     */
    private void retrieveThreadsOnStartup() {
        final Thread[] threads;
        final ThreadGroup threadGroup;
        threadGroup = Thread.currentThread().getThreadGroup();
        try {
            threads = retrieveCurrentActiveThreads(threadGroup);
        } catch (NoSuchFieldException e) {
            LOGGER.error("Could not retrieve initial Threads list. The application may be unstable on shutting down ", e);
            threadsAtStartup = new ArrayList<String>();
            return;
        } catch (IllegalAccessException e) {
            LOGGER.error("Could not retrieve initial Threads list. The application may be unstable on shutting down ", e);
            threadsAtStartup = new ArrayList<String>();
            return;
        }

        threadsAtStartup = new ArrayList<String>(threads.length);
        for (int i = 0; i < threads.length; i++) {
            final Thread thread;
            try {
                thread = threads[i];
                if (null != thread) {
                    threadsAtStartup.add(thread.getName());
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("This Thread was available at startup: " + thread.getName());
                    }
                }
            } catch (RuntimeException e) {
                LOGGER.error("An error occured on initial Thread statement: ", e);
            }
        }
    }
    /**
     * Hack to retrieve the field ThreadGroup.threads, which is package-protected and therefore not accessible 
     *
     * @param threadGroup
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private Thread[] retrieveCurrentActiveThreads(ThreadGroup threadGroup) throws NoSuchFieldException, IllegalAccessException {
        final Thread[] threads;
        final Field privateThreadsField;
        privateThreadsField = ThreadGroup.class.getDeclaredField("threads");
        privateThreadsField.setAccessible(true);

        threads = (Thread[]) privateThreadsField.get(threadGroup);
        return threads;
    }

On application shutdown

In the method ServletContextListener.contextDestroyed(), let’s call this method:

    /**
     * Cleanses the Threads on shutdown: theorically, when the WebApp is undeployed, should remain only the threads
     * that were present before the WAR was deployed. Unfornately, Mule leaves alive many threads on shutdown, reducing
     * PermGen size and recreating new threads with the same names as the old ones, inducing a kind of instability.
     */
    private void cleanseThreadsOnShutdown() {
        final Thread[] threads;
        final ThreadGroup threadGroup;
        final String currentThreadName;

        currentThreadName = Thread.currentThread().getName();

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("On shutdown, currentThreadName is: " + currentThreadName);
        }

        threadGroup = Thread.currentThread().getThreadGroup();
        try {
            threads = retrieveCurrentActiveThreads(threadGroup);
        } catch (NoSuchFieldException e) {
            LOGGER.error("An error occured on Threads cleaning at shutdown", e);
            return;
        } catch (IllegalAccessException e) {
            LOGGER.error("An error occured on Threads cleaning at shutdown", e);
            return;
        }

        for (Thread thread : threads) {
            final String threadName = thread.getName();
            final Boolean shouldThisThreadBeKilled;

            shouldThisThreadBeKilled = isThisThreadToBeKilled(currentThreadName, threadName);
            if (LOGGER.isDebugEnabled()) {
                LOGGER.info("should the thread named " + threadName + " be killed? " + shouldThisThreadBeKilled);
            }
            if (shouldThisThreadBeKilled) {
                thread.interrupt();
                thread = null;
            }
        }

    }

    /**
     * Says whether a thread is to be killed<br/>
     * Rules:
     * <ul><li>a Thread must NOT be killed if:</li>
     * <ol>
     * <li>it was among the threads available at startup</li>
     * <li>it is a Thread belonging to WebLogic (normally, WebLogic threads are among the list in the previous case</li>
     * <li>it is the current Thread (simple protection against unlikely situation)</li>
     * </ol>
     * <li>a Thread must be killed: in all other cases</li>
     * </ul>
     *
     * @param currentThreadName
     * @param threadName
     * @return
     */
    private Boolean isThisThreadToBeKilled(String currentThreadName, String threadName) {
        final Boolean toBeKilled;
        toBeKilled = !threadsAtStartup.contains(threadName)
                &amp;&amp; !StringUtils.contains(threadName, "weblogic")
                &amp;&amp; !threadName.equalsIgnoreCase(currentThreadName);
        return toBeKilled;
    }

EhCache

My application uses an EhCache. Its threads names usually end with “.data”. They are not killed by the previous actions. To get rid of them, the most elegant way is to add this block in the web.xml:

     <listener>
          <listener-class>net.sf.ehcache.constructs.web.ShutdownListener</listener-class>
     </listener>

cf EhCache documentation

With all these operations, almost all threads are killed. But Java VisualVM still displays 34, vs. 31 at startup.

Tough Threads

A thread dump confirms that, at this point, 3 rebellious threads still refuse to be kill:

MuleServer.1
SocketTimeoutMonitor-Monitor.1
SocketTimeoutMonitor-Monitor.1

Let’s examine them:

  • MuleServer.1: This thread is an instance of the inner class MuleServer.ShutdownThread. Indeed, this is the first thread created by Mule, and therefore appears among the threads available at startup, before the ServletContextListener is called… I did not succeed in killing it, even why trying to kill it namely, which makes sense: killing the father thread looks like suiciding the ServletContextListener.
  • SocketTimeoutMonitor-Monitor.1: This thread is created by Mule’s TcpConnector and its daughter classes: HttpConnector, SslConnector, etc. Again, I could not kill them.

Conclusion

We have seen Mule suffers of major thread leaks when deployed as a WAR. Anyway, most of these leaks may be sealed.
I assume MuleSoft was aware of this issue: in the version 3 of Mule, the deployment of webapps was refactored.

PostHeaderIcon Start Mule ESB as an NT service under a Windows server

Case

You would like to start a Mule ESB instance as an NT service, under a Windows server. You would also like to give a specific name and description

Fix

  • add an environment variable MULE_HOME, with value the path of Mule install, for instance: C:\jonathan\mule-standalone-3.0.1
  • edit the file %MULE_HOME%\conf\wrapper.conf
  • replace the following properties default values:
    wrapper.ntservice.name=%MULE_APP%
    wrapper.ntservice.displayname=%MULE_APP_LONG%
    wrapper.ntservice.description=%MULE_APP_LONG%
  • (you can also set other properties related to NT service configuration)
  • launch the command:
  • %MULE_HOME%\bin\mule.bat install -config %MULE_HOME%\bin\mule-conf.xml
  • then you can see in the administration services that the service has started
  • to remove the service, only launch the following command
  • %MULE_HOME%\bin\mule.bat remove

Known issue:

On certain installations (among them the servers on which CygWin is installed), a conflict may happen between the files %MULE_HOME%\bin\mule (standard launcher for Unix and Linux) and %MULE_HOME%\bin\mule.bat (standard launcher for Windows). In this case, rename %MULE_HOME%\bin\mule as %MULE_HOME%\bin\mule.OLD