diff options
| author | Alex Rudyy <orudyy@apache.org> | 2013-02-19 09:35:28 +0000 |
|---|---|---|
| committer | Alex Rudyy <orudyy@apache.org> | 2013-02-19 09:35:28 +0000 |
| commit | a973713561140fe7395368ae53def8f7edfa18a3 (patch) | |
| tree | 7bda80afada592df681fb73908400e7a189f015f /qpid/java/broker-plugins/management-jmx | |
| parent | 1b0f1d06188e73e9440dc1789c28ee65e24d539d (diff) | |
| download | qpid-python-a973713561140fe7395368ae53def8f7edfa18a3.tar.gz | |
QPID-4390: Introduce a configuration store in java broker allowing runtime modifications and replace existing xml file configuration with json configuration store
git-svn-id: https://svn.apache.org/repos/asf/qpid/trunk@1447646 13f79535-47bb-0310-9956-ffa450edef68
Diffstat (limited to 'qpid/java/broker-plugins/management-jmx')
13 files changed, 829 insertions, 505 deletions
diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/CustomRMIServerSocketFactory.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/CustomRMIServerSocketFactory.java new file mode 100644 index 0000000000..b7aab78e45 --- /dev/null +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/CustomRMIServerSocketFactory.java @@ -0,0 +1,68 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.jmx; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.rmi.server.RMIServerSocketFactory; + +/** + * Custom RMIServerSocketFactory class, used to prevent updates to the RMI registry. + * Supplied to the registry at creation, this will prevent RMI-based operations on the + * registry such as attempting to bind a new object, thereby securing it from tampering. + * This is accomplished by always returning null when attempting to determine the address + * of the caller, thus ensuring the registry will refuse the attempt. Calls to bind etc + * made using the object reference will not be affected and continue to operate normally. + */ +class CustomRMIServerSocketFactory implements RMIServerSocketFactory +{ + + public ServerSocket createServerSocket(int port) throws IOException + { + return new NoLocalAddressServerSocket(port); + } + + private static class NoLocalAddressServerSocket extends ServerSocket + { + NoLocalAddressServerSocket(int port) throws IOException + { + super(port); + } + + @Override + public Socket accept() throws IOException + { + Socket s = new NoLocalAddressSocket(); + super.implAccept(s); + return s; + } + } + + private static class NoLocalAddressSocket extends Socket + { + @Override + public InetAddress getInetAddress() + { + return null; + } + } +}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java index cf7a83a54e..a045683de1 100644 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagedObjectRegistry.java @@ -20,56 +20,44 @@ */ package org.apache.qpid.server.jmx; -import org.apache.commons.configuration.ConfigurationException; import org.apache.log4j.Logger; -import org.apache.qpid.AMQException; -import org.apache.qpid.server.configuration.ServerConfiguration; +import org.apache.qpid.server.configuration.BrokerProperties; +import org.apache.qpid.server.configuration.IllegalConfigurationException; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.Port; +import org.apache.qpid.server.model.Transport; - -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; import org.apache.qpid.server.security.auth.rmi.RMIPasswordAuthenticator; + import javax.management.JMException; import javax.management.MBeanServer; import javax.management.MBeanServerFactory; -import javax.management.Notification; -import javax.management.NotificationFilterSupport; -import javax.management.NotificationListener; import javax.management.ObjectName; -import javax.management.remote.JMXConnectionNotification; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXServiceURL; import javax.management.remote.MBeanServerForwarder; -import javax.management.remote.rmi.RMIConnection; import javax.management.remote.rmi.RMIConnectorServer; -import javax.management.remote.rmi.RMIJRMPServerImpl; -import javax.management.remote.rmi.RMIServerImpl; import javax.rmi.ssl.SslRMIClientSocketFactory; import javax.rmi.ssl.SslRMIServerSocketFactory; -import javax.security.auth.Subject; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.management.ManagementFactory; -import java.lang.reflect.Proxy; import java.net.InetAddress; import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.net.Socket; import java.net.UnknownHostException; import java.rmi.AlreadyBoundException; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; +import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.rmi.server.UnicastRemoteObject; import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; /** * This class starts up an MBeanserver. If out of the box agent has been enabled then there are no @@ -82,34 +70,32 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry private static final String OPERATIONAL_LOGGING_NAME = "JMX"; private final MBeanServer _mbeanServer; + private JMXConnectorServer _cs; private Registry _rmiRegistry; - private boolean _useCustomSocketFactory; - private final int _jmxPortRegistryServer; - private final int _jmxPortConnectorServer; + private final Broker _broker; + private final Port _registryPort; + private final Port _connectorPort; - private final ServerConfiguration _serverConfiguration; - - public JMXManagedObjectRegistry(ServerConfiguration serverConfiguration) throws AMQException + public JMXManagedObjectRegistry( + Broker broker, + Port connectorPort, Port registryPort, + JMXManagement jmxManagement) { - _log.info("Initialising managed object registry using platform MBean server"); - - _serverConfiguration = serverConfiguration; + _broker = broker; + _registryPort = registryPort; + _connectorPort = connectorPort; - // Retrieve the config parameters - _useCustomSocketFactory = _serverConfiguration.getUseCustomRMISocketFactory(); - boolean platformServer = _serverConfiguration.getPlatformMbeanserver(); + boolean usePlatformServer = (Boolean)jmxManagement.getAttribute(JMXManagement.USE_PLATFORM_MBEAN_SERVER); _mbeanServer = - platformServer ? ManagementFactory.getPlatformMBeanServer() + usePlatformServer ? ManagementFactory.getPlatformMBeanServer() : MBeanServerFactory.createMBeanServer(ManagedObject.DOMAIN); + } - _jmxPortRegistryServer = _serverConfiguration.getJMXPortRegistryServer(); - _jmxPortConnectorServer = _serverConfiguration.getJMXConnectorServerPort(); - } - - public void start() throws IOException, ConfigurationException + @Override + public void start() throws IOException { CurrentActor.get().message(ManagementConsoleMessages.STARTUP(OPERATIONAL_LOGGING_NAME)); @@ -117,59 +103,31 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry if (areOutOfTheBoxJMXOptionsSet()) { CurrentActor.get().message(ManagementConsoleMessages.READY(OPERATIONAL_LOGGING_NAME)); - return; } + else + { + startRegistryAndConnector(); + } + } - //Socket factories for the RMIConnectorServer, either default or SLL depending on configuration + private void startRegistryAndConnector() throws IOException + { + //Socket factories for the RMIConnectorServer, either default or SSL depending on configuration RMIClientSocketFactory csf; RMIServerSocketFactory ssf; - //check ssl enabled option in config, default to true if option is not set - boolean sslEnabled = _serverConfiguration.getManagementSSLEnabled(); + //check ssl enabled option on connector port (note we don't provide ssl for registry server at + //moment). + boolean connectorSslEnabled = _connectorPort.getTransports().contains(Transport.SSL); - if (sslEnabled) + if (connectorSslEnabled) { - //set the SSL related system properties used by the SSL RMI socket factories to the values - //given in the configuration file - String keyStorePath = _serverConfiguration.getManagementKeyStorePath(); + String keyStorePath = System.getProperty("javax.net.ssl.keyStore"); + String keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword"); - //check the keystore path value is valid - if (keyStorePath == null) - { - throw new ConfigurationException("JMX management SSL keystore path not defined, " + - "unable to start SSL protected JMX ConnectorServer"); - } - else - { - //ensure the system property is set (for use by SslRMIClientSocketFactory and SslRMIServerSocketFactory) - System.setProperty("javax.net.ssl.keyStore", keyStorePath); + validateKeyStoreProperties(keyStorePath, keyStorePassword); - //check the file is usable - File ksf = new File(keyStorePath); - - if (!ksf.exists()) - { - throw new FileNotFoundException("Cannot find JMX management SSL keystore file: " + ksf); - } - if (!ksf.canRead()) - { - throw new FileNotFoundException("Cannot read JMX management SSL keystore file: " - + ksf + ". Check permissions."); - } - - CurrentActor.get().message(ManagementConsoleMessages.SSL_KEYSTORE(ksf.getAbsolutePath())); - } - - if (_serverConfiguration.getManagementKeyStorePassword() == null) - { - throw new ConfigurationException("JMX management SSL keystore password not defined, " + - "unable to start requested SSL protected JMX server"); - } - else - { - System.setProperty("javax.net.ssl.keyStorePassword", - _serverConfiguration.getManagementKeyStorePassword()); - } + CurrentActor.get().message(ManagementConsoleMessages.SSL_KEYSTORE(keyStorePath)); //create the SSL RMI socket factories csf = new SslRMIClientSocketFactory(); @@ -182,29 +140,23 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry ssf = null; } + int jmxPortRegistryServer = _registryPort.getPort(); + int jmxPortConnectorServer = _connectorPort.getPort(); + //add a JMXAuthenticator implementation the env map to authenticate the RMI based JMX connector server - RMIPasswordAuthenticator rmipa = new RMIPasswordAuthenticator(ApplicationRegistry.getInstance(), new InetSocketAddress(_jmxPortRegistryServer)); - HashMap<String,Object> env = new HashMap<String,Object>(); - env.put(JMXConnectorServer.AUTHENTICATOR, rmipa); + RMIPasswordAuthenticator rmipa = new RMIPasswordAuthenticator(_broker, new InetSocketAddress(jmxPortConnectorServer)); + HashMap<String,Object> connectorEnv = new HashMap<String,Object>(); + connectorEnv.put(JMXConnectorServer.AUTHENTICATOR, rmipa); + + System.setProperty("java.rmi.server.randomIDs", "true"); + boolean useCustomSocketFactory = Boolean.parseBoolean(System.getProperty(BrokerProperties.PROPERTY_USE_CUSTOM_RMI_SOCKET_FACTORY, Boolean.TRUE.toString())); /* * Start a RMI registry on the management port, to hold the JMX RMI ConnectorServer stub. * Using custom socket factory to prevent anyone (including us unfortunately) binding to the registry using RMI. * As a result, only binds made using the object reference will succeed, thus securing it from external change. */ - System.setProperty("java.rmi.server.randomIDs", "true"); - if(_useCustomSocketFactory) - { - _log.debug("Using custom RMIServerSocketFactory"); - _rmiRegistry = LocateRegistry.createRegistry(_jmxPortRegistryServer, null, new CustomRMIServerSocketFactory()); - } - else - { - _log.debug("Using default RMIServerSocketFactory"); - _rmiRegistry = LocateRegistry.createRegistry(_jmxPortRegistryServer, null, null); - } - - CurrentActor.get().message(ManagementConsoleMessages.LISTENING("RMI Registry", _jmxPortRegistryServer)); + _rmiRegistry = createRmiRegistry(jmxPortRegistryServer, useCustomSocketFactory); /* * We must now create the RMI ConnectorServer manually, as the JMX Factory methods use RMI calls @@ -212,57 +164,16 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry * locked it from any RMI based modifications, including our own. Instead, we will manually bind * the RMIConnectorServer stub to the registry using its object reference, which will still succeed. * - * The registry is exported on the defined management port 'port'. We will export the RMIConnectorServer - * on 'port +1'. Use of these two well-defined ports will ease any navigation through firewall's. + * The registry is exported on the defined management port 'port'. */ - final Map<String, String> connectionIdUsernameMap = new ConcurrentHashMap<String, String>(); - final RMIServerImpl rmiConnectorServerStub = new RMIJRMPServerImpl(_jmxPortConnectorServer, csf, ssf, env) - { - - /** - * Override makeClient so we can cache the username of the client in a Map keyed by connectionId. - * ConnectionId is guaranteed to be unique per client connection, according to the JMX spec. - * An instance of NotificationListener (mapCleanupListener) will be responsible for removing these Map - * entries. - * - * @see javax.management.remote.rmi.RMIJRMPServerImpl#makeClient(String, javax.security.auth.Subject) - */ - @Override - protected RMIConnection makeClient(String connectionId, Subject subject) throws IOException - { - final RMIConnection makeClient = super.makeClient(connectionId, subject); - final AuthenticatedPrincipal authenticatedPrincipalFromSubject = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); - connectionIdUsernameMap.put(connectionId, authenticatedPrincipalFromSubject.getName()); - return makeClient; - } - }; - - // Create a Listener responsible for removing the map entries add by the #makeClient entry above. - final NotificationListener mapCleanupListener = new NotificationListener() - { + final UsernameCachingRMIJRMPServer usernameCachingRmiServer = new UsernameCachingRMIJRMPServer(jmxPortConnectorServer, csf, ssf, connectorEnv); - public void handleNotification(Notification notification, Object handback) - { - final String connectionId = ((JMXConnectionNotification) notification).getConnectionId(); - connectionIdUsernameMap.remove(connectionId); - } - }; - - String localHost; - try - { - localHost = InetAddress.getLocalHost().getHostName(); - } - catch(UnknownHostException ex) - { - localHost="127.0.0.1"; - } - final String hostname = localHost; + final String localHostName = getLocalhost(); final JMXServiceURL externalUrl = new JMXServiceURL( - "service:jmx:rmi://"+hostname+":"+(_jmxPortConnectorServer)+"/jndi/rmi://"+hostname+":"+_jmxPortRegistryServer+"/jmxrmi"); + "service:jmx:rmi://"+localHostName+":"+(jmxPortConnectorServer)+"/jndi/rmi://"+localHostName+":"+jmxPortRegistryServer+"/jmxrmi"); - final JMXServiceURL internalUrl = new JMXServiceURL("rmi", hostname, _jmxPortConnectorServer); - _cs = new RMIConnectorServer(internalUrl, env, rmiConnectorServerStub, _mbeanServer) + final JMXServiceURL internalUrl = new JMXServiceURL("rmi", localHostName, jmxPortConnectorServer); + _cs = new RMIConnectorServer(internalUrl, connectorEnv, usernameCachingRmiServer, _mbeanServer) { @Override public synchronized void start() throws IOException @@ -270,7 +181,7 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry try { //manually bind the connector server to the registry at key 'jmxrmi', like the out-of-the-box agent - _rmiRegistry.bind("jmxrmi", rmiConnectorServerStub); + _rmiRegistry.bind("jmxrmi", usernameCachingRmiServer); } catch (AlreadyBoundException abe) { @@ -298,7 +209,6 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry } catch (NotBoundException nbe) { - // TODO consider if we want to keep new logging _log.error("Failed to unbind jmxrmi", nbe); //ignore } @@ -313,97 +223,100 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry //must return our pre-crafted url that includes the full details, inc JNDI details return externalUrl; } - }; - //Add the custom invoker as an MBeanServerForwarder, and start the RMIConnectorServer. - MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance(); + MBeanServerForwarder mbsf = MBeanInvocationHandlerImpl.newProxyInstance(_broker); _cs.setMBeanServerForwarder(mbsf); + // Install a ManagementLogonLogoffReporter so we can report as users logon/logoff + ManagementLogonLogoffReporter jmxManagementUserLogonLogoffReporter = new ManagementLogonLogoffReporter(_broker.getRootMessageLogger(), usernameCachingRmiServer); + _cs.addNotificationListener(jmxManagementUserLogonLogoffReporter, jmxManagementUserLogonLogoffReporter, null); - // Get the handler that is used by the above MBInvocationHandler Proxy. - // which is the MBeanInvocationHandlerImpl and so also a NotificationListener. - final NotificationListener invocationHandler = (NotificationListener) Proxy.getInvocationHandler(mbsf); - - // Install a notification listener on OPENED, CLOSED, and FAILED, - // passing the map of connection-ids to usernames as hand-back data. - final NotificationFilterSupport invocationHandlerFilter = new NotificationFilterSupport(); - invocationHandlerFilter.enableType(JMXConnectionNotification.OPENED); - invocationHandlerFilter.enableType(JMXConnectionNotification.CLOSED); - invocationHandlerFilter.enableType(JMXConnectionNotification.FAILED); - _cs.addNotificationListener(invocationHandler, invocationHandlerFilter, connectionIdUsernameMap); - - // Install a second notification listener on CLOSED AND FAILED only to remove the entry from the - // Map. Here we rely on the fact that JMX will call the listeners in the order in which they are - // installed. - final NotificationFilterSupport mapCleanupHandlerFilter = new NotificationFilterSupport(); - mapCleanupHandlerFilter.enableType(JMXConnectionNotification.CLOSED); - mapCleanupHandlerFilter.enableType(JMXConnectionNotification.FAILED); - _cs.addNotificationListener(mapCleanupListener, mapCleanupHandlerFilter, null); + // Install the usernameCachingRmiServer as a listener so it may cleanup as clients disconnect + _cs.addNotificationListener(usernameCachingRmiServer, usernameCachingRmiServer, null); _cs.start(); - String connectorServer = (sslEnabled ? "SSL " : "") + "JMX RMIConnectorServer"; - CurrentActor.get().message(ManagementConsoleMessages.LISTENING(connectorServer, _jmxPortConnectorServer)); - + String connectorServer = (connectorSslEnabled ? "SSL " : "") + "JMX RMIConnectorServer"; + CurrentActor.get().message(ManagementConsoleMessages.LISTENING(connectorServer, jmxPortConnectorServer)); CurrentActor.get().message(ManagementConsoleMessages.READY(OPERATIONAL_LOGGING_NAME)); } - /* - * Custom RMIServerSocketFactory class, used to prevent updates to the RMI registry. - * Supplied to the registry at creation, this will prevent RMI-based operations on the - * registry such as attempting to bind a new object, thereby securing it from tampering. - * This is accomplished by always returning null when attempting to determine the address - * of the caller, thus ensuring the registry will refuse the attempt. Calls to bind etc - * made using the object reference will not be affected and continue to operate normally. - */ - - private static class CustomRMIServerSocketFactory implements RMIServerSocketFactory + private Registry createRmiRegistry(int jmxPortRegistryServer, boolean useCustomRmiRegistry) + throws RemoteException { - - public ServerSocket createServerSocket(int port) throws IOException + Registry rmiRegistry; + if(useCustomRmiRegistry) { - return new NoLocalAddressServerSocket(port); + _log.debug("Using custom RMIServerSocketFactory"); + rmiRegistry = LocateRegistry.createRegistry(jmxPortRegistryServer, null, new CustomRMIServerSocketFactory()); } - - private static class NoLocalAddressServerSocket extends ServerSocket + else { - NoLocalAddressServerSocket(int port) throws IOException - { - super(port); - } + _log.debug("Using default RMIServerSocketFactory"); + rmiRegistry = LocateRegistry.createRegistry(jmxPortRegistryServer, null, null); + } - @Override - public Socket accept() throws IOException - { - Socket s = new NoLocalAddressSocket(); - super.implAccept(s); - return s; - } + CurrentActor.get().message(ManagementConsoleMessages.LISTENING("RMI Registry", jmxPortRegistryServer)); + return rmiRegistry; + } + + private void validateKeyStoreProperties(String keyStorePath, String keyStorePassword) throws FileNotFoundException + { + if (keyStorePath == null) + { + throw new IllegalConfigurationException("JVM system property 'javax.net.ssl.keyStore' is not set, " + + "unable to start requested SSL protected JMX connector"); + } + if (keyStorePassword == null) + { + throw new IllegalConfigurationException( "JVM system property 'javax.net.ssl.keyStorePassword' is not set, " + + "unable to start requested SSL protected JMX connector"); } - private static class NoLocalAddressSocket extends Socket + File ksf = new File(keyStorePath); + if (!ksf.exists()) { - @Override - public InetAddress getInetAddress() - { - return null; - } + throw new FileNotFoundException("Cannot find JMX management SSL keystore file: " + ksf); + } + if (!ksf.canRead()) + { + throw new FileNotFoundException("Cannot read JMX management SSL keystore file: " + + ksf + ". Check permissions."); } } - + @Override public void registerObject(ManagedObject managedObject) throws JMException { _mbeanServer.registerMBean(managedObject, managedObject.getObjectName()); } + @Override public void unregisterObject(ManagedObject managedObject) throws JMException { _mbeanServer.unregisterMBean(managedObject.getObjectName()); } + @Override + public void close() + { + _log.debug("close() called"); + + closeConnectorAndRegistryServers(); + + unregisterAllMbeans(); + + CurrentActor.get().message(ManagementConsoleMessages.STOPPED(OPERATIONAL_LOGGING_NAME)); + } + + private void closeConnectorAndRegistryServers() + { + closeConnectorServer(); + closeRegistryServer(); + } + // checks if the system properties are set which enable the JVM's out-of-the-box JMXAgent. private boolean areOutOfTheBoxJMXOptionsSet() { @@ -420,29 +333,26 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry return false; } - //Stops the JMXConnectorServer and RMIRegistry, then unregisters any remaining MBeans from the MBeanServer - public void close() + private String getLocalhost() { - _log.debug("close() called"); - - if (_cs != null) + String localHost; + try { - // Stopping the JMX ConnectorServer - try - { - CurrentActor.get().message(ManagementConsoleMessages.SHUTTING_DOWN("JMX RMIConnectorServer", _cs.getAddress().getPort())); - _cs.stop(); - } - catch (IOException e) - { - _log.error("Exception while closing the JMX ConnectorServer: ", e); - } + localHost = InetAddress.getLocalHost().getHostName(); } + catch(UnknownHostException ex) + { + localHost="127.0.0.1"; + } + return localHost; + } + private void closeRegistryServer() + { if (_rmiRegistry != null) { // Stopping the RMI registry - CurrentActor.get().message(ManagementConsoleMessages.SHUTTING_DOWN("RMI Registry", _jmxPortRegistryServer)); + CurrentActor.get().message(ManagementConsoleMessages.SHUTTING_DOWN("RMI Registry", _registryPort.getPort())); try { boolean success = UnicastRemoteObject.unexportObject(_rmiRegistry, false); @@ -455,8 +365,36 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry { _log.error("Exception while closing the RMI Registry: ", e); } + finally + { + _rmiRegistry = null; + } } + } + private void closeConnectorServer() + { + if (_cs != null) + { + // Stopping the JMX ConnectorServer + try + { + CurrentActor.get().message(ManagementConsoleMessages.SHUTTING_DOWN("JMX RMIConnectorServer", _cs.getAddress().getPort())); + _cs.stop(); + } + catch (IOException e) + { + _log.error("Exception while closing the JMX ConnectorServer: ", e); + } + finally + { + _cs = null; + } + } + } + + private void unregisterAllMbeans() + { //ObjectName query to gather all Qpid related MBeans ObjectName mbeanNameQuery = null; try @@ -479,8 +417,6 @@ public class JMXManagedObjectRegistry implements ManagedObjectRegistry _log.error("Exception unregistering MBean '"+ name +"': " + e.getMessage()); } } - - CurrentActor.get().message(ManagementConsoleMessages.STOPPED(OPERATIONAL_LOGGING_NAME)); } } diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagement.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagement.java index f529793118..f307f5118a 100644 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagement.java +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagement.java @@ -21,81 +21,214 @@ package org.apache.qpid.server.jmx; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.UUID; + import javax.management.JMException; -import javax.management.StandardMBean; import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.jmx.mbeans.LoggingManagementMBean; import org.apache.qpid.server.jmx.mbeans.UserManagementMBean; import org.apache.qpid.server.jmx.mbeans.ServerInformationMBean; import org.apache.qpid.server.jmx.mbeans.Shutdown; import org.apache.qpid.server.jmx.mbeans.VirtualHostMBean; import org.apache.qpid.server.logging.log4j.LoggingManagementFacade; -import org.apache.qpid.server.management.plugin.ManagementPlugin; +import org.apache.qpid.server.model.AuthenticationProvider; import org.apache.qpid.server.model.Broker; import org.apache.qpid.server.model.ConfigurationChangeListener; import org.apache.qpid.server.model.ConfiguredObject; import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider; +import org.apache.qpid.server.model.Plugin; +import org.apache.qpid.server.model.Port; +import org.apache.qpid.server.model.Protocol; import org.apache.qpid.server.model.State; import org.apache.qpid.server.model.VirtualHost; +import org.apache.qpid.server.model.adapter.AbstractPluginAdapter; +import org.apache.qpid.server.plugin.PluginFactory; import org.apache.qpid.server.plugin.QpidServiceLoader; +import org.apache.qpid.server.util.MapValueConverter; -public class JMXManagement implements ConfigurationChangeListener, ManagementPlugin +public class JMXManagement extends AbstractPluginAdapter implements ConfigurationChangeListener { private static final Logger LOGGER = Logger.getLogger(JMXManagement.class); + public static final String PLUGIN_TYPE = "MANAGEMENT-JMX"; + + // attributes + public static final String USE_PLATFORM_MBEAN_SERVER = "usePlatformMBeanServer"; + public static final String NAME = "name"; + + // default values + public static final String DEFAULT_NAME = "JMXManagement"; + public static final boolean DEFAULT_USE_PLATFORM_MBEAN_SERVER = true; + + @SuppressWarnings("serial") + private static final Collection<String> AVAILABLE_ATTRIBUTES = Collections.unmodifiableCollection(new HashSet<String>(Plugin.AVAILABLE_ATTRIBUTES){{ + add(NAME); + add(USE_PLATFORM_MBEAN_SERVER); + add(PluginFactory.PLUGIN_TYPE); + }}); + + @SuppressWarnings("serial") + private static final Map<String, Object> DEFAULTS = new HashMap<String, Object>(){{ + put(USE_PLATFORM_MBEAN_SERVER, DEFAULT_USE_PLATFORM_MBEAN_SERVER); + put(NAME, DEFAULT_NAME); + put(PluginFactory.PLUGIN_TYPE, PLUGIN_TYPE); + }}; + + @SuppressWarnings("serial") + private static final Map<String, Class<?>> ATTRIBUTE_TYPES = new HashMap<String, Class<?>>(){{ + put(USE_PLATFORM_MBEAN_SERVER, Boolean.class); + put(NAME, String.class); + put(PluginFactory.PLUGIN_TYPE, String.class); + }}; + private final Broker _broker; private JMXManagedObjectRegistry _objectRegistry; private final Map<ConfiguredObject, AMQManagedObject> _children = new HashMap<ConfiguredObject, AMQManagedObject>(); - private final ServerConfiguration _serverConfiguration; - - public JMXManagement(ServerConfiguration serverConfiguration, Broker broker) + public JMXManagement(UUID id, Broker broker, Map<String, Object> attributes) { + super(id, DEFAULTS, MapValueConverter.convert(attributes, ATTRIBUTE_TYPES), broker.getTaskExecutor()); _broker = broker; - _serverConfiguration = serverConfiguration; + addParent(Broker.class, broker); } @Override - public void start() throws Exception + protected boolean setState(State currentState, State desiredState) { - _objectRegistry = new JMXManagedObjectRegistry(_serverConfiguration); + if(desiredState == State.ACTIVE) + { + try + { + start(); + } + catch (JMException e) + { + throw new RuntimeException("Couldn't start JMX management", e); + } + catch (IOException e) + { + throw new RuntimeException("Couldn't start JMX management", e); + } + return true; + } + else if(desiredState == State.STOPPED) + { + stop(); + return true; + } + return false; + } + + private void start() throws JMException, IOException + { + Port connectorPort = null; + Port registryPort = null; + Collection<Port> ports = _broker.getPorts(); + for (Port port : ports) + { + if(isRegistryPort(port)) + { + registryPort = port; + } + else if(isConnectorPort(port)) + { + connectorPort = port; + } + } + if(connectorPort == null) + { + throw new IllegalStateException("No JMX connector port found supporting protocol " + Protocol.JMX_RMI); + } + if(registryPort == null) + { + throw new IllegalStateException("No JMX RMI port found supporting protocol " + Protocol.RMI); + } + + _objectRegistry = new JMXManagedObjectRegistry(_broker, connectorPort, registryPort, this); _broker.addChangeListener(this); + synchronized (_children) { for(VirtualHost virtualHost : _broker.getVirtualHosts()) { if(!_children.containsKey(virtualHost)) { - _children.put(virtualHost, new VirtualHostMBean(virtualHost, _objectRegistry)); + LOGGER.debug("Create MBean for virtual host:" + virtualHost.getName()); + VirtualHostMBean mbean = new VirtualHostMBean(virtualHost, _objectRegistry); + LOGGER.debug("Check for additional MBeans for virtual host:" + virtualHost.getName()); + createAdditionalMBeansFromProviders(virtualHost, mbean); + } + } + Collection<AuthenticationProvider> authenticationProviders = _broker.getAuthenticationProviders(); + for (AuthenticationProvider authenticationProvider : authenticationProviders) + { + if(authenticationProvider instanceof PasswordCredentialManagingAuthenticationProvider) + { + UserManagementMBean mbean = new UserManagementMBean( + (PasswordCredentialManagingAuthenticationProvider) authenticationProvider, + _objectRegistry); + _children.put(authenticationProvider, mbean); } } } new Shutdown(_objectRegistry); new ServerInformationMBean(_objectRegistry, _broker); new LoggingManagementMBean(LoggingManagementFacade.getCurrentInstance(), _objectRegistry); - _objectRegistry.start(); } - @Override - public void stop() + private boolean isConnectorPort(Port port) { - _broker.removeChangeListener(this); + return port.getProtocols().contains(Protocol.JMX_RMI); + } + private boolean isRegistryPort(Port port) + { + return port.getProtocols().contains(Protocol.RMI); + } + + private void stop() + { + synchronized (_children) + { + for(ConfiguredObject object : _children.keySet()) + { + AMQManagedObject mbean = _children.get(object); + if (mbean instanceof ConfigurationChangeListener) + { + object.removeChangeListener((ConfigurationChangeListener)mbean); + } + try + { + mbean.unregister(); + } + catch (JMException e) + { + LOGGER.error("Error unregistering mbean", e); + } + } + _children.clear(); + } + _broker.removeChangeListener(this); _objectRegistry.close(); } + @Override public void stateChanged(ConfiguredObject object, State oldState, State newState) { - + // no-op } + @Override public void childAdded(ConfiguredObject object, ConfiguredObject child) { synchronized (_children) @@ -130,7 +263,7 @@ public class JMXManagement implements ConfigurationChangeListener, ManagementPlu } } - + @Override public void childRemoved(ConfiguredObject object, ConfiguredObject child) { // TODO - implement vhost removal (possibly just removing the instanceof check below) @@ -157,6 +290,12 @@ public class JMXManagement implements ConfigurationChangeListener, ManagementPlu } } + @Override + public void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue) + { + // no-op + } + private void createAdditionalMBeansFromProviders(ConfiguredObject child, AMQManagedObject mbean) throws JMException { _children.put(child, mbean); @@ -168,7 +307,7 @@ public class JMXManagement implements ConfigurationChangeListener, ManagementPlu if (provider.isChildManageableByMBean(child)) { LOGGER.debug("Provider will create mbean "); - StandardMBean bean = provider.createMBean(child, mbean); + provider.createMBean(child, mbean); // TODO track the mbeans that have been created on behalf of a child in a map, then // if the child is ever removed, destroy these beans too. } @@ -181,9 +320,16 @@ public class JMXManagement implements ConfigurationChangeListener, ManagementPlu return _broker; } - /** Added for testing purposes */ - ServerConfiguration getServerConfiguration() + @Override + public String getName() { - return _serverConfiguration; + return (String)getAttribute(NAME); } + + @Override + public Collection<String> getAttributeNames() + { + return AVAILABLE_ATTRIBUTES; + } + } diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementFactory.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementFactory.java index 12d4711595..c2186c372b 100644 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementFactory.java +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementFactory.java @@ -18,27 +18,30 @@ */ package org.apache.qpid.server.jmx; +import java.util.Map; +import java.util.UUID; + import org.apache.log4j.Logger; -import org.apache.qpid.server.configuration.ServerConfiguration; import org.apache.qpid.server.model.Broker; -import org.apache.qpid.server.plugin.ManagementFactory; +import org.apache.qpid.server.model.Plugin; +import org.apache.qpid.server.plugin.PluginFactory; -public class JMXManagementFactory implements ManagementFactory +public class JMXManagementFactory implements PluginFactory { - private static final Logger _logger = Logger.getLogger(JMXManagementFactory.class); + private static final Logger LOGGER = Logger.getLogger(JMXManagementFactory.class); @Override - public JMXManagement createInstance(ServerConfiguration serverConfiguration, Broker broker) + public Plugin createInstance(UUID id, Map<String, Object> attributes, Broker broker) { - if (serverConfiguration.getJMXManagementEnabled()) + if (JMXManagement.PLUGIN_TYPE.equals(attributes.get(PLUGIN_TYPE))) { - return new JMXManagement(serverConfiguration, broker); + return new JMXManagement(id, broker, attributes); } else { - if(_logger.isDebugEnabled()) + if (LOGGER.isDebugEnabled()) { - _logger.debug("Skipping registration of JMX plugin as JMX Management disabled in config."); + LOGGER.debug("Skipping registration of JMX plugin as JMX Management disabled in config."); } return null; } diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java index 694b0b2913..8bc2afb176 100644 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/MBeanInvocationHandlerImpl.java @@ -22,12 +22,11 @@ package org.apache.qpid.server.jmx; import org.apache.log4j.Logger; -import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.configuration.BrokerProperties; import org.apache.qpid.server.logging.actors.CurrentActor; import org.apache.qpid.server.logging.actors.ManagementActor; -import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.registry.IApplicationRegistry; +import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.model.VirtualHost; import org.apache.qpid.server.security.SecurityManager; import org.apache.qpid.server.security.access.Operation; import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; @@ -37,11 +36,8 @@ import javax.management.JMException; import javax.management.MBeanInfo; import javax.management.MBeanOperationInfo; import javax.management.MBeanServer; -import javax.management.Notification; -import javax.management.NotificationListener; import javax.management.ObjectName; import javax.management.RuntimeErrorException; -import javax.management.remote.JMXConnectionNotification; import javax.management.remote.MBeanServerForwarder; import javax.security.auth.Subject; import java.lang.reflect.InvocationHandler; @@ -51,26 +47,32 @@ import java.lang.reflect.Proxy; import java.security.AccessControlContext; import java.security.AccessController; import java.util.Arrays; -import java.util.Map; /** * This class can be used by the JMXConnectorServer as an InvocationHandler for the mbean operations. It delegates * JMX access decisions to the SecurityPlugin. */ -public class MBeanInvocationHandlerImpl implements InvocationHandler, NotificationListener +public class MBeanInvocationHandlerImpl implements InvocationHandler { private static final Logger _logger = Logger.getLogger(MBeanInvocationHandlerImpl.class); - private final IApplicationRegistry _appRegistry = ApplicationRegistry.getInstance(); private final static String DELEGATE = "JMImplementation:type=MBeanServerDelegate"; private MBeanServer _mbs; - private final ManagementActor _logActor = new ManagementActor(_appRegistry.getRootMessageLogger()); - private final boolean _managementRightsInferAllAccess = - _appRegistry.getConfiguration().getManagementRightsInferAllAccess(); + private final ManagementActor _logActor; - public static MBeanServerForwarder newProxyInstance() + private final boolean _managementRightsInferAllAccess; + private final Broker _broker; + + MBeanInvocationHandlerImpl(Broker broker) + { + _managementRightsInferAllAccess = Boolean.valueOf(System.getProperty(BrokerProperties.PROPERTY_MANAGEMENT_RIGHTS_INFER_ALL_ACCESS, "true")); + _broker = broker; + _logActor = new ManagementActor(broker.getRootMessageLogger()); + } + + public static MBeanServerForwarder newProxyInstance(Broker broker) { - final InvocationHandler handler = new MBeanInvocationHandlerImpl(); + final InvocationHandler handler = new MBeanInvocationHandlerImpl(broker); final Class<?>[] interfaces = new Class[] { MBeanServerForwarder.class }; Object proxy = Proxy.newProxyInstance(MBeanServerForwarder.class.getClassLoader(), interfaces, handler); @@ -212,11 +214,16 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati SecurityManager security; if (vhost == null) { - security = _appRegistry.getSecurityManager(); + security = _broker.getSecurityManager(); } else { - security = _appRegistry.getVirtualHostRegistry().getVirtualHost(vhost).getSecurityManager(); + VirtualHost virtualHost = _broker.findVirtualHostByName(vhost); + if (virtualHost == null) + { + throw new IllegalArgumentException("Virtual host with name '" + vhost + "' is not found."); + } + security = virtualHost.getSecurityManager(); } methodName = getMethodName(method, args); @@ -361,51 +368,5 @@ public class MBeanInvocationHandlerImpl implements InvocationHandler, Notificati return (methodName.startsWith("query") || methodName.startsWith("get") || methodName.startsWith("is")); } - /** - * Receives notifications from the MBeanServer. - */ - public void handleNotification(final Notification notification, final Object handback) - { - assert notification instanceof JMXConnectionNotification; - - final String connectionId = ((JMXConnectionNotification) notification).getConnectionId(); - final String type = notification.getType(); - - if (_logger.isDebugEnabled()) - { - _logger.debug("Notification connectionId : " + connectionId + " type : " + type - + " Notification handback : " + handback); - } - - // Normally JMXManagedObjectRegistry provides a Map as handback data containing a map - // between connection id and username. - String user = null; - if (handback instanceof Map) - { - @SuppressWarnings("unchecked") - final Map<String, String> connectionIdUsernameMap = (Map<String, String>) handback; - user = connectionIdUsernameMap.get(connectionId); - } - - // If user is still null, fallback to an unordered list of Principals from the connection id. - if (user == null) - { - final String[] splitConnectionId = connectionId.split(" "); - user = splitConnectionId[1]; - } - - // use a separate instance of actor as subject is not set on connect/disconnect - // we need to pass principal name explicitly into log actor - LogActor logActor = new ManagementActor(_appRegistry.getRootMessageLogger(), user); - if (JMXConnectionNotification.OPENED.equals(type)) - { - logActor.message(ManagementConsoleMessages.OPEN(user)); - } - else if (JMXConnectionNotification.CLOSED.equals(type) || - JMXConnectionNotification.FAILED.equals(type)) - { - logActor.message(ManagementConsoleMessages.CLOSE(user)); - } - } } diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java new file mode 100644 index 0000000000..ae0574dc21 --- /dev/null +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporter.java @@ -0,0 +1,95 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.jmx; + +import static javax.management.remote.JMXConnectionNotification.CLOSED; +import static javax.management.remote.JMXConnectionNotification.FAILED; +import static javax.management.remote.JMXConnectionNotification.OPENED; + +import javax.management.Notification; +import javax.management.NotificationFilter; +import javax.management.NotificationListener; +import javax.management.remote.JMXConnectionNotification; + +import org.apache.log4j.Logger; +import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.logging.RootMessageLogger; +import org.apache.qpid.server.logging.actors.ManagementActor; +import org.apache.qpid.server.logging.messages.ManagementConsoleMessages; + +public class ManagementLogonLogoffReporter implements NotificationListener, NotificationFilter +{ + private static final Logger LOGGER = Logger.getLogger(ManagementLogonLogoffReporter.class); + private final RootMessageLogger _rootMessageLogger; + private final UsernameAccessor _usernameAccessor; + + public ManagementLogonLogoffReporter(RootMessageLogger rootMessageLogger, UsernameAccessor usernameAccessor) + { + _rootMessageLogger = rootMessageLogger; + _usernameAccessor = usernameAccessor; + } + + @Override + public void handleNotification(final Notification notification, final Object handback) + { + final String connectionId = ((JMXConnectionNotification) notification).getConnectionId(); + final String type = notification.getType(); + + if (LOGGER.isDebugEnabled()) + { + LOGGER.debug("Notification connectionId : " + connectionId + " type : " + type); + } + + String user = _usernameAccessor.getUsernameForConnectionId(connectionId); + + // If user is still null, fallback to an unordered list of Principals from the connection id. + if (user == null) + { + final String[] splitConnectionId = connectionId.split(" "); + user = splitConnectionId[1]; + } + + // use a separate instance of actor as subject is not set on connect/disconnect + // we need to pass principal name explicitly into log actor + LogActor logActor = new ManagementActor(_rootMessageLogger, user); + if (JMXConnectionNotification.OPENED.equals(type)) + { + logActor.message(ManagementConsoleMessages.OPEN(user)); + } + else if (JMXConnectionNotification.CLOSED.equals(type) || + JMXConnectionNotification.FAILED.equals(type)) + { + logActor.message(ManagementConsoleMessages.CLOSE(user)); + } + } + + @Override + public boolean isNotificationEnabled(Notification notification) + { + return notification instanceof JMXConnectionNotification && isLogonTypeEvent(notification); + } + + private boolean isLogonTypeEvent(Notification notification) + { + final String type = notification.getType(); + return CLOSED.equals(type) || FAILED.equals(type) || OPENED.equals(type); + } + +} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java new file mode 100644 index 0000000000..0cbb0d2687 --- /dev/null +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameAccessor.java @@ -0,0 +1,26 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.jmx; + +public interface UsernameAccessor +{ + public String getUsernameForConnectionId(String connectionId); + +} diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java new file mode 100644 index 0000000000..838e9e5664 --- /dev/null +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/UsernameCachingRMIJRMPServer.java @@ -0,0 +1,100 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.jmx; + +import static javax.management.remote.JMXConnectionNotification.CLOSED; +import static javax.management.remote.JMXConnectionNotification.FAILED; + +import java.io.IOException; +import java.rmi.server.RMIClientSocketFactory; +import java.rmi.server.RMIServerSocketFactory; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import javax.management.Notification; +import javax.management.NotificationFilter; +import javax.management.NotificationListener; +import javax.management.remote.JMXConnectionNotification; +import javax.management.remote.JMXConnectorServer; +import javax.management.remote.rmi.RMIConnection; +import javax.management.remote.rmi.RMIJRMPServerImpl; +import javax.security.auth.Subject; + +import org.apache.qpid.server.security.auth.AuthenticatedPrincipal; + +/** + * An implementation of RMIJRMPServerImpl that caches the usernames of users as they log-on + * and makes the same available via {@link UsernameAccessor#getUsernameForConnectionId(String)}. + * + * Caller is responsible for installing this object as a {@link NotificationListener} of the + * {@link JMXConnectorServer} so the cache entries are removed as the clients disconnect. + * + */ +public class UsernameCachingRMIJRMPServer extends RMIJRMPServerImpl implements NotificationListener, NotificationFilter, UsernameAccessor +{ + // ConnectionId is guaranteed to be unique per client connection, according to the JMX spec. + private final Map<String, String> _connectionIdUsernameMap = new ConcurrentHashMap<String, String>(); + + UsernameCachingRMIJRMPServer(int port, RMIClientSocketFactory csf, RMIServerSocketFactory ssf, + Map<String, ?> env) throws IOException + { + super(port, csf, ssf, env); + } + + @Override + protected RMIConnection makeClient(String connectionId, Subject subject) throws IOException + { + final RMIConnection makeClient = super.makeClient(connectionId, subject); + final AuthenticatedPrincipal authenticatedPrincipalFromSubject = AuthenticatedPrincipal.getAuthenticatedPrincipalFromSubject(subject); + _connectionIdUsernameMap.put(connectionId, authenticatedPrincipalFromSubject.getName()); + return makeClient; + } + + @Override + public String getUsernameForConnectionId(String connectionId) + { + return _connectionIdUsernameMap.get(connectionId); + } + + @Override + public void handleNotification(Notification notification, Object handback) + { + final String connectionId = ((JMXConnectionNotification) notification).getConnectionId(); + removeConnectionIdFromCache(connectionId); + } + + @Override + public boolean isNotificationEnabled(Notification notification) + { + return isClientDisconnectEvent(notification); + } + + private void removeConnectionIdFromCache(String connectionId) + { + _connectionIdUsernameMap.remove(connectionId); + } + + private boolean isClientDisconnectEvent(Notification notification) + { + final String type = notification.getType(); + return CLOSED.equals(type) || FAILED.equals(type); + } + +}
\ No newline at end of file diff --git a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java index 6990a40dee..51dea92775 100644 --- a/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java +++ b/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/mbeans/VirtualHostMBean.java @@ -65,7 +65,7 @@ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtual _managerMBean = new VirtualHostManagerMBean(this); } - private void initQueues() throws JMException + private void initQueues() { synchronized (_children) { @@ -73,13 +73,20 @@ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtual { if(!_children.containsKey(queue)) { - _children.put(queue, new QueueMBean(queue, this)); + try + { + _children.put(queue, new QueueMBean(queue, this)); + } + catch(Exception e) + { + LOGGER.error("Cannot create queue mbean for queue " + queue.getName(), e); + } } } } } - private void initExchanges() throws JMException + private void initExchanges() { synchronized (_children) { @@ -87,13 +94,20 @@ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtual { if(!_children.containsKey(exchange)) { - _children.put(exchange, new ExchangeMBean(exchange, this)); + try + { + _children.put(exchange, new ExchangeMBean(exchange, this)); + } + catch(Exception e) + { + LOGGER.error("Cannot create exchange mbean for exchange " + exchange.getName(), e); + } } } } } - private void initConnections() throws JMException + private void initConnections() { synchronized (_children) { @@ -101,7 +115,14 @@ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtual { if(!_children.containsKey(conn)) { - _children.put(conn, new ConnectionMBean(conn, this)); + try + { + _children.put(conn, new ConnectionMBean(conn, this)); + } + catch(Exception e) + { + LOGGER.error("Cannot create connection mbean for connection " + conn.getName(), e); + } } } } @@ -119,7 +140,7 @@ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtual public void stateChanged(ConfiguredObject object, State oldState, State newState) { - // ignore + // no-op } public void childAdded(ConfiguredObject object, ConfiguredObject child) @@ -208,4 +229,35 @@ public class VirtualHostMBean extends AMQManagedObject implements ManagedVirtual return queues; } + + @Override + public void unregister() throws JMException + { + synchronized (_children) + { + for (AMQManagedObject mbean : _children.values()) + { + if(mbean != null) + { + try + { + mbean.unregister(); + } + catch(JMException e) + { + LOGGER.error("Failed to remove mbean for child : " + mbean, e); + } + } + } + _children.clear(); + } + _managerMBean.unregister(); + } + + @Override + public void attributeSet(ConfiguredObject object, String attributeName, Object oldAttributeValue, Object newAttributeValue) + { + // no-op + } + } diff --git a/qpid/java/broker-plugins/management-jmx/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.ManagementFactory b/qpid/java/broker-plugins/management-jmx/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.PluginFactory index 8fa778269e..8fa778269e 100644 --- a/qpid/java/broker-plugins/management-jmx/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.ManagementFactory +++ b/qpid/java/broker-plugins/management-jmx/src/main/resources/META-INF/services/org.apache.qpid.server.plugin.PluginFactory diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/JMXManagementFactoryTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/JMXManagementFactoryTest.java index 6b6d4018aa..5af1369239 100644 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/JMXManagementFactoryTest.java +++ b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/JMXManagementFactoryTest.java @@ -19,33 +19,42 @@ package org.apache.qpid.server.jmx; import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import org.apache.qpid.server.configuration.ServerConfiguration; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + import org.apache.qpid.server.model.Broker; +import org.apache.qpid.server.plugin.PluginFactory; import org.apache.qpid.test.utils.QpidTestCase; public class JMXManagementFactoryTest extends QpidTestCase { private final JMXManagementFactory _jmxManagementFactory = new JMXManagementFactory(); - private final ServerConfiguration _serverConfiguration = mock(ServerConfiguration.class); + private final Map<String, Object> _attributes = new HashMap<String, Object>(); private final Broker _broker = mock(Broker.class); + private UUID _id = UUID.randomUUID(); public void testJMXConfigured() throws Exception { - when(_serverConfiguration.getJMXManagementEnabled()).thenReturn(true); + _attributes.put(PluginFactory.PLUGIN_TYPE, JMXManagement.PLUGIN_TYPE); - JMXManagement jmxManagement = _jmxManagementFactory.createInstance(_serverConfiguration, _broker); + JMXManagement jmxManagement = (JMXManagement) _jmxManagementFactory.createInstance(_id, _attributes, _broker); assertNotNull(jmxManagement); + assertEquals("Unexpected plugin type", JMXManagement.PLUGIN_TYPE, jmxManagement.getAttribute(JMXManagementFactory.PLUGIN_TYPE)); + assertEquals("Unexpected default mbean platform", JMXManagement.DEFAULT_USE_PLATFORM_MBEAN_SERVER, jmxManagement.getAttribute(JMXManagement.USE_PLATFORM_MBEAN_SERVER)); + assertEquals("Unexpected default name", JMXManagement.DEFAULT_NAME, jmxManagement.getAttribute(JMXManagement.NAME)); } - public void testJMXNotConfigured() throws Exception + public void testCreateInstanceReturnsNullWhenPluginTypeMissing() { - when(_serverConfiguration.getJMXManagementEnabled()).thenReturn(false); - - JMXManagement jmxManagement = _jmxManagementFactory.createInstance(_serverConfiguration, _broker); + assertNull(_jmxManagementFactory.createInstance(_id, _attributes, _broker)); + } - assertNull(jmxManagement); + public void testCreateInstanceReturnsNullWhenPluginTypeNotJmx() + { + _attributes.put(PluginFactory.PLUGIN_TYPE, "notJmx"); + assertNull(_jmxManagementFactory.createInstance(_id, _attributes, _broker)); } } diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogActorTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogActorTest.java deleted file mode 100644 index b055cc476f..0000000000 --- a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogActorTest.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ -package org.apache.qpid.server.jmx; - -import java.util.HashMap; -import java.util.Map; - -import javax.management.JMException; -import javax.management.MBeanServerConnection; -import javax.management.MBeanServerInvocationHandler; -import javax.management.ObjectName; -import javax.management.remote.JMXConnector; -import javax.management.remote.JMXConnectorFactory; -import javax.management.remote.JMXServiceURL; - -import org.apache.commons.configuration.XMLConfiguration; -import org.apache.qpid.server.configuration.ServerConfiguration; -import org.apache.qpid.server.logging.actors.CurrentActor; -import org.apache.qpid.server.registry.ApplicationRegistry; -import org.apache.qpid.server.security.Result; -import org.apache.qpid.server.security.AccessControl; -import org.apache.qpid.server.security.access.ObjectProperties; -import org.apache.qpid.server.security.access.ObjectType; -import org.apache.qpid.server.security.access.Operation; -import org.apache.qpid.server.util.TestApplicationRegistry; -import org.apache.qpid.test.utils.QpidTestCase; - -public class ManagementLogActorTest extends QpidTestCase -{ - private ApplicationRegistry _registry; - private JMXManagedObjectRegistry _objectRegistry; - private int _registryPort; - private int _connectorPort; - private TestPlugin _plugin; - - @Override - public void setUp() throws Exception - { - super.setUp(); - - _registryPort = findFreePort(); - _connectorPort = getNextAvailable(_registryPort + 1); - - //Start a TestApplicationRegistry with (JMX) management disabled, because we - //will instantiate our own directly in order to manipulate it for the test. - XMLConfiguration config = new XMLConfiguration(); - config.addProperty("management.enabled", "false"); - _registry = new TestApplicationRegistry(new ServerConfiguration(config)); - ApplicationRegistry.initialise(_registry); - - _plugin = new TestPlugin(); - _registry.getSecurityManager().addHostPlugin(_plugin); - - //Now start up a test JMXManagedObjectRegistry directly - XMLConfiguration jmxConfig = new XMLConfiguration(); - jmxConfig.addProperty(ServerConfiguration.MGMT_JMXPORT_REGISTRYSERVER, _registryPort + ""); - jmxConfig.addProperty(ServerConfiguration.MGMT_JMXPORT_CONNECTORSERVER, _connectorPort + ""); - - _objectRegistry = new JMXManagedObjectRegistry(new ServerConfiguration(jmxConfig)); - new TestMBean(_objectRegistry); - _objectRegistry.start(); - } - - public void tearDown() throws Exception - { - _objectRegistry.close(); - ApplicationRegistry.remove(); - super.tearDown(); - } - - public void testPrincipalInLogMessage() throws Throwable - { - Map<String, Object> environment = new HashMap<String, Object>(); - environment.put(JMXConnector.CREDENTIALS, new String[] { "admin", "admin" }); - String urlString = "service:jmx:rmi:///jndi/rmi://localhost:" + _registryPort + "/jmxrmi"; - JMXServiceURL url = new JMXServiceURL(urlString); - JMXConnector jmxConnector = JMXConnectorFactory.connect(url, environment); - MBeanServerConnection mbsc = jmxConnector.getMBeanServerConnection(); - ObjectName mbeanObject = new ObjectName("org.apache.qpid:type=TestMBean,name=test"); - - CurrentActorRetriever mbean = MBeanServerInvocationHandler.newProxyInstance(mbsc, - mbeanObject, CurrentActorRetriever.class, false); - String actorLogMessage = mbean.getActorLogMessage(); - - assertTrue("Unexpected log principal in security plugin", _plugin.getLogMessage().startsWith("[mng:admin")); - assertTrue("Unexpected log principal in MBean", actorLogMessage.startsWith("[mng:admin")); - } - - public static class TestMBean extends DefaultManagedObject implements CurrentActorRetriever - { - - public TestMBean(ManagedObjectRegistry registry) throws JMException - { - super(CurrentActorRetriever.class, "TestMBean", registry); - register(); - } - - @Override - public String getObjectInstanceName() - { - return "test"; - } - - @Override - public ManagedObject getParentObject() - { - return null; - } - - @Override - public String getActorLogMessage() - { - return CurrentActor.get().getLogMessage(); - } - - } - - public static interface CurrentActorRetriever - { - String getActorLogMessage(); - } - - public static class TestPlugin implements AccessControl - { - private String _logMessage; - - @Override - public Result getDefault() - { - return Result.ALLOWED; - } - - @Override - public Result access(ObjectType objectType, Object instance) - { - return Result.ALLOWED; - } - - @Override - public Result authorise(Operation operation, ObjectType objectType, ObjectProperties properties) - { - // set thread name to work around logic in MangementActor - Thread.currentThread().setName("RMI TCP Connection(1)-" + System.currentTimeMillis()); - _logMessage = CurrentActor.get().getLogMessage(); - return Result.ALLOWED; - } - - public String getLogMessage() - { - return _logMessage; - } - - } - -} diff --git a/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java new file mode 100644 index 0000000000..ba9c2cdaa5 --- /dev/null +++ b/qpid/java/broker-plugins/management-jmx/src/test/java/org/apache/qpid/server/jmx/ManagementLogonLogoffReporterTest.java @@ -0,0 +1,101 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ +package org.apache.qpid.server.jmx; + +import static javax.management.remote.JMXConnectionNotification.OPENED; +import static javax.management.remote.JMXConnectionNotification.CLOSED; +import static javax.management.remote.JMXConnectionNotification.FAILED; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.mockito.Mockito.verify; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyString; + +import javax.management.remote.JMXConnectionNotification; + +import org.apache.qpid.server.logging.LogActor; +import org.apache.qpid.server.logging.RootMessageLogger; + +import junit.framework.TestCase; + +public class ManagementLogonLogoffReporterTest extends TestCase +{ + private static final String TEST_JMX_UNIQUE_CONNECTION_ID = "jmxconnectionid1 jmxuser,group"; + private static final String TEST_USER = "jmxuser"; + + private ManagementLogonLogoffReporter _reporter; + private UsernameAccessor _usernameAccessor; + private RootMessageLogger _rootMessageLogger; + + @Override + protected void setUp() throws Exception + { + super.setUp(); + _usernameAccessor = mock(UsernameAccessor.class); + _rootMessageLogger = mock(RootMessageLogger.class); + // Enable messaging so we can valid the generated strings + when(_rootMessageLogger.isMessageEnabled(any(LogActor.class), anyString())).thenReturn(true); + + _reporter = new ManagementLogonLogoffReporter(_rootMessageLogger, _usernameAccessor); + } + + public void testOpenedNotification() + { + when(_usernameAccessor.getUsernameForConnectionId(TEST_JMX_UNIQUE_CONNECTION_ID)).thenReturn(TEST_USER); + JMXConnectionNotification openNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, OPENED); + + _reporter.handleNotification(openNotification, null); + + verify(_rootMessageLogger).rawMessage("[main] MNG-1007 : Open : User jmxuser", "qpid.message.managementconsole.open"); + } + + public void testClosedNotification() + { + when(_usernameAccessor.getUsernameForConnectionId(TEST_JMX_UNIQUE_CONNECTION_ID)).thenReturn(TEST_USER); + JMXConnectionNotification closeNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, CLOSED); + + _reporter.handleNotification(closeNotification, null); + + verify(_rootMessageLogger).rawMessage("[main] MNG-1008 : Close : User jmxuser", "qpid.message.managementconsole.close"); + } + + public void tesNotifiedForLogOnTypeEvents() + { + JMXConnectionNotification openNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, OPENED); + JMXConnectionNotification closeNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, CLOSED); + JMXConnectionNotification failedNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, FAILED); + + assertTrue(_reporter.isNotificationEnabled(openNotification)); + assertTrue(_reporter.isNotificationEnabled(closeNotification)); + assertTrue(_reporter.isNotificationEnabled(failedNotification)); + + JMXConnectionNotification otherNotification = createMockNotification(TEST_JMX_UNIQUE_CONNECTION_ID, "other"); + assertFalse(_reporter.isNotificationEnabled(otherNotification)); + } + + private JMXConnectionNotification createMockNotification(String connectionId, String notificationType) + { + JMXConnectionNotification notification = mock(JMXConnectionNotification.class); + when(notification.getConnectionId()).thenReturn(connectionId); + when(notification.getType()).thenReturn(notificationType); + return notification; + } +} |
