DomainDispatchInterceptor.java 13.0 KB
Newer Older
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
/*
 * Copyright 2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package com.sun.jmx.interceptor;

import com.sun.jmx.defaults.JmxProperties;
import com.sun.jmx.mbeanserver.MBeanInstantiator;
import com.sun.jmx.mbeanserver.Repository;
import com.sun.jmx.mbeanserver.Util;
import com.sun.jmx.namespace.DomainInterceptor;
import java.util.Queue;
import java.util.Set;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.namespace.JMXDomain;
import static javax.management.namespace.JMXNamespaces.NAMESPACE_SEPARATOR;

/**
 * A dispatcher that dispatch incoming MBeanServer requests to
 * DomainInterceptors.
 * <p><b>
 * This API is a Sun internal API and is subject to changes without notice.
 * </b></p>
 * @since 1.7
 */
//
// See comments in  DispatchInterceptor.
//
class DomainDispatchInterceptor
        extends DispatchInterceptor<DomainInterceptor, JMXDomain> {

    /**
     * A logger for this class.
     **/
    private static final Logger LOG = JmxProperties.NAMESPACE_LOGGER;

    private static final ObjectName ALL_DOMAINS =
            JMXDomain.getDomainObjectName("*");


    /**
     *  A QueryInterceptor that perform & aggregates queries spanning several
     *  domains.
     */
    final static class AggregatingQueryInterceptor extends QueryInterceptor {

        private final DomainDispatchInterceptor parent;
        AggregatingQueryInterceptor(DomainDispatchInterceptor dispatcher) {
77
            super(dispatcher.nextInterceptor);
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
            parent = dispatcher;
        }

        /**
         * Perform queryNames or queryMBeans, depending on which QueryInvoker
         * is passed as argument. This is closures without closures.
         **/
        @Override
        <T> Set<T> query(ObjectName pattern, QueryExp query,
                QueryInvoker<T> invoker, MBeanServer localNamespace) {
            final Set<T> local = invoker.query(localNamespace, pattern, query);

            // Add all matching MBeans from local namespace.
            final Set<T> res = Util.cloneSet(local);

            if (pattern == null) pattern = ObjectName.WILDCARD;
94
            final boolean all = pattern.getDomain().equals("*");
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

            final String domain = pattern.getDomain();

            // If there's no domain pattern, just include the pattern's domain.
            // Otherwiae, loop over all virtual domains (parent.getKeys()).
            final String[] keys =
                (pattern.isDomainPattern() ?
                    parent.getKeys() : new String[]{domain});

            // Add all matching MBeans from each virtual domain
            //
            for (String key : keys) {
                // Only invoke those virtual domain which are selected
                // by the domain pattern
                //
                if (!all && !Util.isDomainSelected(key, domain))
                    continue;

                try {
                    final MBeanServer mbs = parent.getInterceptor(key);

                    // mbs can be null if the interceptor was removed
                    // concurrently...
                    // See handlerMap and getKeys() in DispatchInterceptor
                    //
                    if (mbs == null) continue;

                    // If the domain is selected, we can replace the pattern
                    // by the actual domain. This is safer if we want to avoid
                    // a domain (which could be backed up by an MBeanServer) to
                    // return names from outside the domain.
                    // So instead of asking the domain handler for "foo" to
                    // return all names which match "?o*:type=Bla,*" we're
                    // going to ask it to return all names which match
                    // "foo:type=Bla,*"
                    //
                    final ObjectName subPattern = pattern.withDomain(key);
                    res.addAll(invoker.query(mbs, subPattern, query));
                } catch (Exception x) {
                    LOG.finest("Ignoring exception " +
                            "when attempting to query namespace "+key+": "+x);
                    continue;
                }
            }
            return res;
        }
    }

143
    private final DefaultMBeanServerInterceptor nextInterceptor;
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
    private final String mbeanServerName;
    private final MBeanServerDelegate delegate;

    /**
     * Creates a DomainDispatchInterceptor with the specified
     * repository instance.
     *
     * @param outer A pointer to the MBeanServer object that must be
     *        passed to the MBeans when invoking their
     *        {@link javax.management.MBeanRegistration} interface.
     * @param delegate A pointer to the MBeanServerDelegate associated
     *        with the new MBeanServer. The new MBeanServer must register
     *        this MBean in its MBean repository.
     * @param instantiator The MBeanInstantiator that will be used to
     *        instantiate MBeans and take care of class loading issues.
     * @param repository The repository to use for this MBeanServer
     */
    public DomainDispatchInterceptor(MBeanServer         outer,
                            MBeanServerDelegate delegate,
                            MBeanInstantiator   instantiator,
                            Repository          repository,
                            NamespaceDispatchInterceptor namespaces)  {
166
           nextInterceptor = new DefaultMBeanServerInterceptor(outer,
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
                   delegate, instantiator,repository,namespaces);
           mbeanServerName = Util.getMBeanServerSecurityName(delegate);
           this.delegate = delegate;
    }

    final boolean isLocalHandlerNameFor(String domain,
            ObjectName handlerName) {
        if (domain == null) return true;
        return handlerName.getDomain().equals(domain) &&
               JMXDomain.TYPE_ASSIGNMENT.equals(
               handlerName.getKeyPropertyListString());
    }

    @Override
    void validateHandlerNameFor(String key, ObjectName name) {
        super.validateHandlerNameFor(key,name);
183
        final String[] domains = nextInterceptor.getDomains();
184 185 186 187 188 189 190 191 192
        for (int i=0;i<domains.length;i++) {
            if (domains[i].equals(key))
                throw new IllegalArgumentException("domain "+key+
                        " is not empty");
        }
    }

    @Override
    final MBeanServer getInterceptorOrNullFor(ObjectName name) {
193 194 195

        if (name == null) return nextInterceptor;

196
        final String domain = name.getDomain();
197 198 199 200 201 202
        if (domain.endsWith(NAMESPACE_SEPARATOR))
            return nextInterceptor; // This can be a namespace handler.
        if (domain.contains(NAMESPACE_SEPARATOR))
            return null; // shouldn't reach here.
        if (isLocalHandlerNameFor(domain,name)) {
            // This is the name of a JMXDomain MBean. Return nextInterceptor.
203
            LOG.finer("dispatching to local namespace");
204
            return nextInterceptor;
205
        }
206 207

        final DomainInterceptor ns = getInterceptor(domain);
208
        if (ns == null) {
209
            // no JMXDomain found for that domain - return nextInterceptor.
210
            if (LOG.isLoggable(Level.FINER)) {
211
                LOG.finer("dispatching to local namespace: " + domain);
212 213 214
            }
            return getNextInterceptor();
        }
215

216
        if (LOG.isLoggable(Level.FINER)) {
217
            LOG.finer("dispatching to domain: " + domain);
218 219 220 221
        }
        return ns;
    }

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
    // This method returns true if the given pattern must be evaluated against
    // several interceptors. This happens when either:
    //
    //   a) the pattern can select several domains (it's null, or it's a
    //        domain pattern)
    //   or b) it's not a domain pattern, but it might select the name of a
    //        JMXDomain MBean in charge of that domain. Since the JMXDomain
    //        MBean is located in the nextInterceptor, the pattern might need
    //        to be evaluated on two interceptors.
    //
    // 1. When this method returns false, the query is evaluated on a single
    // interceptor:
    //    The interceptor for pattern.getDomain(), if there is one,
    //    or the next interceptor, if there is none.
    //
    // 2. When this method returns true, we loop over all the domain
    // interceptors:
    //    in the list, and if the domain pattern matches the interceptor domain
    //    we evaluate the query on that interceptor and aggregate the results.
    //    Eventually we also evaluate the pattern against the next interceptor.
    //
    // See getInterceptorForQuery below.
    //
245
    private boolean multipleQuery(ObjectName pattern) {
246
        // case a) above
247 248 249
        if (pattern == null) return true;
        if (pattern.isDomainPattern()) return true;

250 251 252 253 254 255 256 257 258 259 260
        // case b) above.
        //
        // This is a bit of a hack. If there's any chance that a JMXDomain
        // MBean name is selected by the given pattern then we must include
        // the local namespace in our search.
        //
        // Returning true will have this effect. see 2. above.
        //
        if (pattern.apply(ALL_DOMAINS.withDomain(pattern.getDomain())))
            return true;

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        return false;
    }

    @Override
    final QueryInterceptor getInterceptorForQuery(ObjectName pattern) {

        // Check if we need to aggregate.
        if (multipleQuery(pattern))
            return new AggregatingQueryInterceptor(this);

        // We don't need to aggregate: do the "simple" thing...
        final String domain = pattern.getDomain();

        // Do we have a virtual domain?
        final DomainInterceptor ns = getInterceptor(domain);
        if (ns != null) {
            if (LOG.isLoggable(Level.FINER))
                LOG.finer("dispatching to domain: " + domain);
            return new QueryInterceptor(ns);
        }

        // We don't have a virtual domain. Send to local domains.
        if (LOG.isLoggable(Level.FINER))
             LOG.finer("dispatching to local namespace: " + domain);
285
        return new QueryInterceptor(nextInterceptor);
286 287 288
    }

    @Override
289
    final ObjectName getHandlerNameFor(String key) {
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
        return JMXDomain.getDomainObjectName(key);
    }

    @Override
    final public String getHandlerKey(ObjectName name) {
        return name.getDomain();
    }

    @Override
    final DomainInterceptor createInterceptorFor(String key,
            ObjectName name, JMXDomain handler,
            Queue<Runnable> postRegisterQueue) {
        final DomainInterceptor ns =
                new DomainInterceptor(mbeanServerName,handler,key);
        ns.addPostRegisterTask(postRegisterQueue, delegate);
        if (LOG.isLoggable(Level.FINER)) {
            LOG.finer("DomainInterceptor created: "+ns);
        }
        return ns;
    }

    @Override
    final void interceptorReleased(DomainInterceptor interceptor,
            Queue<Runnable> postDeregisterQueue) {
        interceptor.addPostDeregisterTask(postDeregisterQueue, delegate);
    }

    @Override
    final DefaultMBeanServerInterceptor getNextInterceptor() {
319
        return nextInterceptor;
320 321 322 323 324 325 326 327 328
    }

    /**
     * Returns the list of domains in which any MBean is currently
     * registered.
     */
    @Override
    public String[] getDomains() {
        // A JMXDomain is registered in its own domain.
329 330
        // Therefore, nextInterceptor.getDomains() contains all domains.
        // In addition, nextInterceptor will perform the necessary
331 332
        // MBeanPermission checks for getDomains().
        //
333
        return nextInterceptor.getDomains();
334 335 336 337 338 339 340
    }

    /**
     * Returns the number of MBeans registered in the MBean server.
     */
    @Override
    public Integer getMBeanCount() {
341
        int count = getNextInterceptor().getMBeanCount();
342 343 344 345
        final String[] keys = getKeys();
        for (String key:keys) {
            final MBeanServer mbs = getInterceptor(key);
            if (mbs == null) continue;
346
            count += mbs.getMBeanCount();
347
        }
348
        return count;
349 350
    }
}