View Javadoc

1   /*
2    * $Id: WrapperManagerAgent.java 22392 2011-07-12 16:35:24Z dirk.olmes $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.module.management.agent;
12  
13  import org.mule.AbstractAgent;
14  import org.mule.api.MuleException;
15  import org.mule.api.lifecycle.InitialisationException;
16  import org.mule.config.i18n.CoreMessages;
17  import org.mule.module.management.i18n.ManagementMessages;
18  import org.mule.module.management.support.AutoDiscoveryJmxSupportFactory;
19  import org.mule.module.management.support.JmxSupport;
20  import org.mule.module.management.support.JmxSupportFactory;
21  
22  import java.util.List;
23  import java.util.concurrent.atomic.AtomicReference;
24  
25  import javax.management.InstanceNotFoundException;
26  import javax.management.MBeanRegistrationException;
27  import javax.management.MBeanServer;
28  import javax.management.MBeanServerFactory;
29  import javax.management.MalformedObjectNameException;
30  import javax.management.ObjectName;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.tanukisoftware.wrapper.WrapperSystemPropertyUtil;
35  import org.tanukisoftware.wrapper.jmx.WrapperManager;
36  import org.tanukisoftware.wrapper.jmx.WrapperManagerMBean;
37  import org.tanukisoftware.wrapper.security.WrapperPermission;
38  
39  /**
40   * This agent integrates Java Service Wrapper into Mule. See
41   * <a href="http://wrapper.tanukisoftware.org">http://wrapper.tanukisoftware.org</a>
42   * for more details.
43   */
44  public class WrapperManagerAgent extends AbstractAgent
45  {
46      /**
47       * MBean name to register under.
48       */
49      public static final String WRAPPER_JMX_NAME = "name=WrapperManager";
50  
51      /**
52       * For cases when Mule is embedded in another process and that external process
53       * had registered the MBean.
54       */
55      public static final String DEFAULT_WRAPPER_MBEAN_NAME = "org.tanukisoftware.wrapper:type=WrapperManager";
56  
57      private static final Log logger = LogFactory.getLog(WrapperManagerAgent.class);
58  
59      /**
60       * This property is set by the native launcher, used for extra checks.
61       */
62      private static final String WRAPPER_SYSTEM_PROPERTY_NAME = "wrapper.native_library";
63  
64      private MBeanServer mBeanServer;
65      private ObjectName wrapperName;
66  
67      private JmxSupportFactory jmxSupportFactory = AutoDiscoveryJmxSupportFactory.getInstance();
68      private JmxSupport jmxSupport = jmxSupportFactory.getJmxSupport();
69  
70      // atomic reference to avoid unnecessary construction calls
71      private final AtomicReference<WrapperManagerMBean> wrapperManagerRef = new AtomicReference<WrapperManagerMBean>();
72  
73  
74      public WrapperManagerAgent()
75      {
76          super("wrapper-manager");
77      }
78  
79      @Override
80      public void initialise() throws InitialisationException
81      {
82          try
83          {
84              List<?> servers = MBeanServerFactory.findMBeanServer(null);
85              if (servers.isEmpty())
86              {
87                  throw new InitialisationException(ManagementMessages.noMBeanServerAvailable(), this);
88              }
89  
90              mBeanServer = (MBeanServer) servers.get(0);
91  
92              /*
93                Perform an extra check ourselves. If 'wrapper.native_library' property has
94                not been set, which is the case for embedded scenarios, don't even try to
95                construct the wrapper manager bean, as it performs a number of checks internally
96                and outputs a very verbose warning.
97              */
98              boolean launchedByWrapper;
99              if (System.getProperty(WRAPPER_SYSTEM_PROPERTY_NAME) == null)
100             {
101                 launchedByWrapper = false;
102             }
103             // Check if an external process registered a wrapper MBean under default name.
104             else if (mBeanServer.isRegistered(jmxSupport.getObjectName(DEFAULT_WRAPPER_MBEAN_NAME)))
105             {
106                 logger.info("Mule is embedded in a container already launched by a wrapper." +
107                             "Duplicates will not be registered. Use the " + DEFAULT_WRAPPER_MBEAN_NAME + " MBean " +
108                             "instead for control.");
109                 unregisterMeQuietly();
110                 return;
111             }
112             else
113             {
114                 lazyInitWrapperManager();
115                 launchedByWrapper = wrapperManagerRef.get().isControlledByNativeWrapper();
116             }
117 
118             if (!launchedByWrapper)
119             {
120                 logger.info("This JVM hasn't been launched by the wrapper, the agent will not run.");
121                 unregisterMeQuietly();
122                 return;
123             }
124 
125             final boolean containerMode = muleContext.getConfiguration().isContainerMode();
126             if (containerMode)
127             {
128                 // container mode, register mbean under Mule domain, no duplicates under each app's domain
129                 wrapperName = jmxSupport.getObjectName(JmxSupport.DEFAULT_JMX_DOMAIN_PREFIX + ":" + WRAPPER_JMX_NAME);
130                 if (mBeanServer.isRegistered(wrapperName))
131                 {
132                     // ignore duplicate invocations when running in Mule container mode
133                     return;
134                 }
135             }
136             else
137             {
138                 // embedded case, use Mule's single domain
139                 wrapperName = jmxSupport.getObjectName(jmxSupport.getDomainName(muleContext) + ":" + WRAPPER_JMX_NAME);
140             }
141 
142             unregisterMBeansIfNecessary();
143             mBeanServer.registerMBean(wrapperManagerRef.get(), wrapperName);
144         }
145         catch (InitialisationException iex)
146         {
147             // rethrow
148             throw iex;
149         }
150         catch (Exception e)
151         {
152             throw new InitialisationException(CoreMessages.failedToStart("wrapper agent"), e, this);
153         }
154     }
155 
156     @Override
157     public void start() throws MuleException
158     {
159         // nothing to do
160     }
161 
162     @Override
163     public void stop() throws MuleException
164     {
165         // nothing to do
166     }
167 
168     @Override
169     public void dispose()
170     {
171         try
172         {
173             unregisterMBeansIfNecessary();
174         }
175         catch (Exception e)
176         {
177             logger.error("Couldn't unregister MBean: "
178                          + (wrapperName != null ? wrapperName.getCanonicalName() : "null"), e);
179         }
180     }
181 
182 
183     // /////////////////////////////////////////////////////////////////////////
184     // Getters and setters
185     // /////////////////////////////////////////////////////////////////////////
186 
187     @Override
188     public String getDescription()
189     {
190         WrapperManagerMBean wm = wrapperManagerRef.get();
191         if (wm == null)
192         {
193             return "Wrapper Manager";
194         }
195         else
196         {
197             return "Wrapper Manager: Mule PID #" + getJavaPID() + ", Wrapper PID #" + getWrapperPID();
198         }
199     }
200 
201     /**
202      * This method is a copy of the implementation of
203      * {@link WrapperManagerMBean#getJavaPID()} and it is here because that method is
204      * not present in the {@link WrapperManagerMBean} until version 3.2.3.
205      * SpringSource's TC Server uses The wrapper version 3.2.0 so having this method
206      * here allows us to be compatible with TC Server.
207      *
208      * @return The PID of the Java process.
209      * @see <a href="http://www.mulesoft.org/jira/browse/MULE-5106">MULE-5106</a>
210      */
211     public static int getJavaPID()
212     {
213         SecurityManager sm = System.getSecurityManager();
214         if (sm != null)
215         {
216             sm.checkPermission(new WrapperPermission("getJavaPID"));
217         }
218 
219         return WrapperSystemPropertyUtil.getIntProperty("wrapper.java.pid", 0);
220     }
221 
222     /**
223      * This method is a copy of the implementation of
224      * {@link WrapperManagerMBean#getWrapperPID()} and it is here because that method
225      * is not present in the {@link WrapperManagerMBean} until version 3.2.3.
226      * SpringSource's TC Server uses The wrapper version 3.2.0 so having this method
227      * here allows us to be compatible with TC Server.
228      *
229      * @return The PID of the Wrapper process.
230      * @see <a href="http://www.mulesoft.org/jira/browse/MULE-5106">MULE-5106</a>
231      */
232     public static int getWrapperPID()
233     {
234         SecurityManager sm = System.getSecurityManager();
235         if (sm != null)
236         {
237             sm.checkPermission(new WrapperPermission("getWrapperPID"));
238         }
239 
240         return WrapperSystemPropertyUtil.getIntProperty("wrapper.pid", 0);
241     }
242 
243     protected void lazyInitWrapperManager()
244     {
245         WrapperManagerMBean wm = wrapperManagerRef.get();
246 
247         if (wm != null)
248         {
249             return;
250         }
251 
252         wm = new WrapperManager();
253         wrapperManagerRef.compareAndSet(null, wm);
254     }
255 
256     /**
257      * Unregister all MBeans if there are any left over the old deployment
258      */
259     protected void unregisterMBeansIfNecessary()
260             throws MalformedObjectNameException, InstanceNotFoundException, MBeanRegistrationException
261     {
262         if (mBeanServer == null || wrapperName == null)
263         {
264             return;
265         }
266         if (mBeanServer.isRegistered(wrapperName))
267         {
268             mBeanServer.unregisterMBean(wrapperName);
269         }
270     }
271 
272 }