summaryrefslogtreecommitdiff
path: root/qpid/java/broker-plugins/management-jmx/src/main/java/org/apache/qpid/server/jmx/JMXManagementPluginImpl.java
blob: 06558b9f9a7bce9aeaf5157f7dc69ded8e9c585d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
 *
 * 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.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.management.InstanceAlreadyExistsException;
import javax.management.JMException;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import org.apache.log4j.Logger;

import org.apache.qpid.server.configuration.IllegalConfigurationException;
import org.apache.qpid.server.jmx.mbeans.LoggingManagementMBean;
import org.apache.qpid.server.jmx.mbeans.ServerInformationMBean;
import org.apache.qpid.server.jmx.mbeans.Shutdown;
import org.apache.qpid.server.jmx.mbeans.UserManagementMBean;
import org.apache.qpid.server.jmx.mbeans.VirtualHostMBean;
import org.apache.qpid.server.logging.log4j.LoggingManagementFacade;
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.ManagedAttributeField;
import org.apache.qpid.server.model.ManagedObjectFactoryConstructor;
import org.apache.qpid.server.model.PasswordCredentialManagingAuthenticationProvider;
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.StateTransition;
import org.apache.qpid.server.model.VirtualHost;
import org.apache.qpid.server.model.VirtualHostNode;
import org.apache.qpid.server.model.adapter.AbstractPluginAdapter;
import org.apache.qpid.server.model.port.JmxPort;
import org.apache.qpid.server.model.port.PortManager;
import org.apache.qpid.server.model.port.RmiPort;
import org.apache.qpid.server.plugin.QpidServiceLoader;

public class JMXManagementPluginImpl
        extends AbstractPluginAdapter<JMXManagementPluginImpl> implements JMXManagementPlugin<JMXManagementPluginImpl>, PortManager
{
    private static final Logger LOGGER = Logger.getLogger(JMXManagementPluginImpl.class);

    public static final String NAME = "name";

    // default values
    public static final String DEFAULT_NAME = "JMXManagement";

    private JMXManagedObjectRegistry _objectRegistry;

    private final Object _childrenLock = new Object();
    private final Map<ConfiguredObject<?>, Map<MBeanProvider, ManagedObject>> _children = new HashMap<ConfiguredObject<?>, Map<MBeanProvider,ManagedObject>>();

    @ManagedAttributeField
    private boolean _usePlatformMBeanServer;

    private boolean _allowPortActivation;

    private final Set<MBeanProvider> _mBeanProviders;
    private final ChangeListener _changeListener;
    private final PluginMBeansProvider _pluginMBeanProvider;

    @ManagedObjectFactoryConstructor
    public JMXManagementPluginImpl(Map<String, Object> attributes, Broker<?> broker)
    {
        super(attributes, broker);
        _changeListener = new ChangeListener();
        _pluginMBeanProvider = new PluginMBeansProvider();
        _mBeanProviders = new HashSet<MBeanProvider>();
        QpidServiceLoader qpidServiceLoader = new QpidServiceLoader();
        for (MBeanProvider provider : qpidServiceLoader.instancesOf(MBeanProvider.class))
        {
            _mBeanProviders.add(provider);
        }
    }

    @Override
    public boolean getUsePlatformMBeanServer()
    {
        return _usePlatformMBeanServer;
    }

    @StateTransition(currentState = {State.UNINITIALIZED,State.ERRORED}, desiredState = State.ACTIVE)
    private ListenableFuture<Void> doStart() throws JMException, IOException
    {
        _allowPortActivation = true;
        Broker<?> broker = getBroker();
        JmxPort<?> connectorPort = null;
        RmiPort registryPort = null;
        Collection<Port<?>> ports = broker.getPorts();
        for (Port<?> port : ports)
        {
            if (port.getDesiredState() != State.ACTIVE)
            {
                continue;
            }

            if(isRegistryPort(port))
            {
                registryPort = (RmiPort) port;
                registryPort.setPortManager(this);
                if(port.getState() != State.ACTIVE)
                {
                    // TODO - RG
                    port.startAsync();
                }

            }
            else if(isConnectorPort(port))
            {
                connectorPort = (JmxPort<?>) port;
                connectorPort.setPortManager(this);
                if(port.getState() != State.ACTIVE)
                {
                    port.startAsync();
                }

            }
        }
        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(_changeListener);

        synchronized (_childrenLock)
        {
            for(VirtualHostNode<?> virtualHostNode : broker.getVirtualHostNodes())
            {
                createObjectMBeans(virtualHostNode);
            }

            Collection<AuthenticationProvider<?>> authenticationProviders = broker.getAuthenticationProviders();
            for (AuthenticationProvider<?> authenticationProvider : authenticationProviders)
            {
                createObjectMBeans(authenticationProvider);
            }
        }
        new Shutdown(_objectRegistry);
        new ServerInformationMBean(_objectRegistry, broker);
        if (LoggingManagementFacade.getCurrentInstance() != null)
        {
            new LoggingManagementMBean(LoggingManagementFacade.getCurrentInstance(), _objectRegistry);
        }
        _objectRegistry.start();
        setState(State.ACTIVE);
        _allowPortActivation = false;
        return Futures.immediateFuture(null);
    }

    @Override
    public boolean isActivationAllowed(final Port<?> port)
    {
        return _allowPortActivation;
    }

    private boolean isConnectorPort(Port<?> port)
    {
        return port.getProtocols().contains(Protocol.JMX_RMI);
    }

    private boolean isRegistryPort(Port<?> port)
    {
        return port.getProtocols().contains(Protocol.RMI);
    }

    @Override
    protected void onClose()
    {
        synchronized (_childrenLock)
        {
            for(ConfiguredObject<?> object : _children.keySet())
            {
                unregisterObjectMBeans(object);
            }
            _children.clear();
        }
        getBroker().removeChangeListener(_changeListener);
        closeObjectRegistry();
    }

    private void unregisterObjectMBeans(ConfiguredObject<?> object)
    {
        Map<?, ManagedObject> mbeans = _children.get(object);
        if (mbeans != null)
        {
            for (ManagedObject mbean : mbeans.values())
            {
                if (mbean instanceof ConfigurationChangeListener)
                {
                    object.removeChangeListener((ConfigurationChangeListener)mbean);
                }

                if (LOGGER.isDebugEnabled())
                {
                    String mbeanName = null;
                    try
                    {
                        mbeanName = mbean.getObjectName().toString();
                    }
                    catch(Exception e)
                    {
                        // ignore
                    }
                    LOGGER.debug("Unregistering MBean " + mbeanName + " for configured object " + object);
                }

                try
                {
                    mbean.unregister();
                }
                catch (Exception e)
                {
                    LOGGER.error("Exception while unregistering mbean for " + object.getClass().getSimpleName() + " " + object.getName(), e);
                }
            }
        }
    }

    private void createAdditionalMBeansFromProvidersIfNecessary(ConfiguredObject<?> child, ManagedObjectRegistry registry) throws JMException
    {
        for (MBeanProvider provider : _mBeanProviders)
        {
            if(LOGGER.isDebugEnabled())
            {
                LOGGER.debug("Consulting mbean provider : " + provider + " for child : " + child);
            }

            ManagedObject mBean = null;
            if (provider.isChildManageableByMBean(child) && !providerMBeanExists(child, provider))
            {
                if(LOGGER.isDebugEnabled())
                {
                    LOGGER.debug("Provider of type " + provider.getType() + " will create mbean for " + child);
                }

                mBean = provider.createMBean(child, registry);
                if (mBean != null)
                {
                    registerMBean(child, provider, mBean);
                }
            }

            if(LOGGER.isDebugEnabled())
            {
                LOGGER.debug("Provider " + provider + (mBean == null ? " did not create mBean" : " created mBean " + mBean)
                        + " for child " + child);
            }
        }
    }

    @Override
    protected void validateChange(final ConfiguredObject<?> proxyForValidation, final Set<String> changedAttributes)
    {
        super.validateChange(proxyForValidation, changedAttributes);
        if(changedAttributes.contains(NAME))
        {
            String newName = proxyForValidation.getName();
            if(!getName().equals(newName))
            {
                throw new IllegalConfigurationException("Changing the name of jmx management plugin is not allowed");
            }
        }
    }

    private void closeObjectRegistry()
    {
        if (_objectRegistry != null)
        {
            try
            {
                _objectRegistry.close();
            }
            finally
            {
                _objectRegistry = null;
            }
        }
    }

    private ManagedObject createObjectMBeansIfNecessary(ConfiguredObject<?> object) throws JMException
    {
        ManagedObject mbean = null;
        if (supportedConfiguredObject(object))
        {
            synchronized (_childrenLock)
            {
                if (!providerMBeanExists(object, _pluginMBeanProvider))
                {
                    if (object instanceof VirtualHostNode)
                    {
                        object.addChangeListener(_changeListener);
                        VirtualHostNode<?> virtualHostNode = (VirtualHostNode<?>) object;

                        // Virtual host nodes may or may not have a virtual host at this point.
                        // In the HA case, JE may spontaneously make the node a master causing it to create a virtual host.
                        // Creation of the virtual host uses the task executor (same thread that executes this code
                        // so there is no potential for a race here).
                        VirtualHost<?, ?, ?> host = virtualHostNode.getVirtualHost();
                        if (host != null)
                        {
                            createVirtualHostMBeanIfNecessary(host, _objectRegistry);
                        }
                    }
                    else if (object instanceof VirtualHost)
                    {
                        mbean = createVirtualHostMBeanIfNecessary((VirtualHost<?, ?, ?>) object, _objectRegistry);
                    }
                    else if (object instanceof PasswordCredentialManagingAuthenticationProvider)
                    {
                        object.addChangeListener(_changeListener);
                        mbean = new UserManagementMBean((PasswordCredentialManagingAuthenticationProvider<?>) object, _objectRegistry);
                        registerMBean(object, _pluginMBeanProvider, mbean);
                    }
                }
                createAdditionalMBeansFromProvidersIfNecessary(object, _objectRegistry);
            }
        }
        return mbean;
    }

    private VirtualHostMBean createVirtualHostMBeanIfNecessary(VirtualHost<?, ?, ?> host, ManagedObjectRegistry _objectRegistry) throws JMException
    {
        if (!providerMBeanExists(host, _pluginMBeanProvider))
        {
            host.addChangeListener(_changeListener);
            try
            {
                VirtualHostMBean mbean = new VirtualHostMBean(host, _objectRegistry);
                registerMBean(host, _pluginMBeanProvider, mbean);
                return mbean;
            }
            catch (InstanceAlreadyExistsException e)
            {
                VirtualHostNode parent = host.getParent(VirtualHostNode.class);
                Set<ConfiguredObject<?>> registered = _children.keySet();
                for (ConfiguredObject<?> object: registered)
                {
                    if (object instanceof VirtualHost && object.getParent(VirtualHostNode.class) == parent)
                    {
                        LOGGER.warn("Unexpected MBean is found for VirtualHost " + object + " belonging to node " +  parent);
                    }
                }

                throw e;
            }
        }
        return null;
    }

    private void registerMBean(ConfiguredObject<?> configuredObject, MBeanProvider mBeanProvider, ManagedObject mbean)
    {
        Map<MBeanProvider, ManagedObject> mbeans = _children.get(configuredObject);
        if (mbeans == null)
        {
            mbeans = new HashMap<MBeanProvider, ManagedObject>();
            _children.put(configuredObject, mbeans);
        }
        mbeans.put(mBeanProvider, mbean);
    }

    private boolean providerMBeanExists(ConfiguredObject<?> configuredObject, MBeanProvider mBeanProvider)
    {
        Map<MBeanProvider, ManagedObject> mbeans = _children.get(configuredObject);
        if (mbeans == null)
        {
            return false;
        }
        return mbeans.containsKey(mBeanProvider);
    }

    private void destroyObjectMBeans(ConfiguredObject<?> object, boolean removeListener)
    {
        if (supportedConfiguredObject(object))
        {
            synchronized (_childrenLock)
            {
                if (removeListener)
                {
                    object.removeChangeListener(_changeListener);
                }
                unregisterObjectMBeans(object);
                _children.remove(object);
                destroyChildrenMBeans(object);
            }
        }
    }

    private void destroyChildrenMBeans(ConfiguredObject<?> object)
    {
        for (Iterator<ConfiguredObject<?>> iterator = _children.keySet().iterator(); iterator.hasNext();)
        {
            ConfiguredObject<?> registeredObject = iterator.next();
            ConfiguredObject<?> parent = registeredObject.getParent(object.getCategoryClass());
            if (parent == object)
            {
                registeredObject.removeChangeListener(_changeListener);
                unregisterObjectMBeans(registeredObject);
                iterator.remove();
            }
        }
    }

    private void createObjectMBeans(ConfiguredObject<?> object)
    {
        try
        {
            createObjectMBeansIfNecessary(object);
        }
        catch (JMException e)
        {
            LOGGER.error("Cannot create MBean for " + object, e);
        }
    }

    private boolean supportedConfiguredObject(ConfiguredObject<?> object)
    {
        return object instanceof VirtualHostNode || object instanceof VirtualHost || object instanceof PasswordCredentialManagingAuthenticationProvider;
    }

    private class PluginMBeansProvider implements MBeanProvider
    {
        @Override
        public boolean isChildManageableByMBean(ConfiguredObject<?> object)
        {
            return supportedConfiguredObject(object);
        }

        @Override
        public ManagedObject createMBean(ConfiguredObject<?> object, ManagedObjectRegistry registry) throws JMException
        {
            return createObjectMBeansIfNecessary(object);
        }

        @Override
        public String getType()
        {
            return "INTERNAL";
        }

        @Override
        public String toString()
        {
            return DEFAULT_NAME;
        }
    }

    private class ChangeListener implements ConfigurationChangeListener
    {
        @Override
        public void stateChanged(ConfiguredObject<?> object, State oldState, State newState)
        {
            if (newState == State.DELETED || newState == State.STOPPED || newState == State.ERRORED)
            {
                destroyObjectMBeans(object, newState == State.DELETED);
            }
            else if (newState == State.ACTIVE)
            {
                createObjectMBeans(object);
            }
        }

        @Override
        public void childAdded(ConfiguredObject<?> object, ConfiguredObject<?> child)
        {
            createObjectMBeans(child);
        }

        @Override
        public void childRemoved(ConfiguredObject<?> object, ConfiguredObject<?> child)
        {
            destroyObjectMBeans(child, true);
        }

        @Override
        public void attributeSet(ConfiguredObject<?> object, String attributeName, Object oldAttributeValue, Object newAttributeValue)
        {
            // VH can be created after attribute change,
            // for instance, on role change in BDB HA VHN a VH could is recovered/created.
            // A call to createObjectMBeans is safe as it checks the existence of MBean before its creation.

            if (ConfiguredObject.DESIRED_STATE.equals(attributeName))
            {
                stateChanged(object, State.valueOf(String.valueOf(oldAttributeValue)), State.valueOf(String.valueOf(newAttributeValue)));
            }
            else
            {
                createObjectMBeans(object);
            }
        }
    }

}