FetchingEventRelay.java 14.2 KB
Newer Older
1
/*
X
xdono 已提交
2
 * Copyright 2007-2008 Sun Microsystems, Inc.  All Rights Reserved.
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
 * 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 javax.management.event;

import com.sun.jmx.event.DaemonThreadFactory;
import com.sun.jmx.event.RepeatedSingletonJob;
import com.sun.jmx.remote.util.ClassLogger;
import java.io.IOException;
import java.io.NotSerializableException;
import java.util.concurrent.Executor;
34 35
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
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
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.management.MBeanException;
import javax.management.remote.NotificationResult;

/**
 * This class is an implementation of the {@link EventRelay} interface. It calls
 * {@link EventClientDelegateMBean#fetchNotifications
 * fetchNotifications(String, long, int, long)} to get
 * notifications and then forwards them to an {@link EventReceiver} object.
 *
 * @since JMX 2.0
 */
public class FetchingEventRelay implements EventRelay {
    /**
     * The default buffer size: {@value #DEFAULT_BUFFER_SIZE}.
     */
    public final static int DEFAULT_BUFFER_SIZE = 1000;

    /**
     * The default waiting timeout: {@value #DEFAULT_WAITING_TIMEOUT}
     * in millseconds when fetching notifications from
     * an {@code EventClientDelegateMBean}.
     */
    public final static long DEFAULT_WAITING_TIMEOUT = 60000;

    /**
     * The default maximum notifications to fetch every time:
     * {@value #DEFAULT_MAX_NOTIFICATIONS}.
     */
    public final static int DEFAULT_MAX_NOTIFICATIONS = DEFAULT_BUFFER_SIZE;

    /**
     * Constructs a default {@code FetchingEventRelay} object by using the default
     * configuration: {@code DEFAULT_BUFFER_SIZE}, {@code DEFAULT_WAITING_TIMEOUT}
     * {@code DEFAULT_MAX_NOTIFICATIONS}. A single thread is created
     * to do fetching.
     *
     * @param delegate The {@code EventClientDelegateMBean} to work with.
     * @throws IOException If failed to work with the {@code delegate}.
     * @throws MBeanException if unable to add a client to the remote
     * {@code EventClientDelegateMBean} (see {@link
     * EventClientDelegateMBean#addClient(String, Object[], String[])
     * EventClientDelegateMBean.addClient}).
     * @throws IllegalArgumentException If {@code delegate} is {@code null}.
     */
    public FetchingEventRelay(EventClientDelegateMBean delegate)
    throws IOException, MBeanException {
        this(delegate, null);
    }

    /**
     * Constructs a {@code FetchingEventRelay} object by using the default
     * configuration: {@code DEFAULT_BUFFER_SIZE}, {@code DEFAULT_WAITING_TIMEOUT}
     * {@code DEFAULT_MAX_NOTIFICATIONS}, with a user-specific executor to do
     * the fetching.
     *
     * @param delegate The {@code EventClientDelegateMBean} to work with.
     * @param executor Used to do the fetching. A new thread is created if
     * {@code null}.
     * @throws IOException If failed to work with the {@code delegate}.
     * @throws MBeanException if unable to add a client to the remote
     * {@code EventClientDelegateMBean} (see {@link
     * EventClientDelegateMBean#addClient(String, Object[], String[])
     * EventClientDelegateMBean.addClient}).
     * @throws IllegalArgumentException If {@code delegate} is {@code null}.
     */
    public FetchingEventRelay(EventClientDelegateMBean delegate,
            Executor executor) throws IOException, MBeanException {
        this(delegate,
                DEFAULT_BUFFER_SIZE,
                DEFAULT_WAITING_TIMEOUT,
                DEFAULT_MAX_NOTIFICATIONS,
                executor);
    }

    /**
     * Constructs a {@code FetchingEventRelay} object with user-specific
     * configuration and executor to fetch notifications via the
     * {@link EventClientDelegateMBean}.
     *
     * @param delegate The {@code EventClientDelegateMBean} to work with.
     * @param bufferSize The buffer size for saving notifications in
     * {@link EventClientDelegateMBean} before they are fetched.
     * @param timeout The waiting time in millseconds when fetching
     * notifications from an {@code EventClientDelegateMBean}.
     * @param maxNotifs The maximum notifications to fetch every time.
     * @param executor Used to do the fetching. A new thread is created if
     * {@code null}.
     * @throws IOException if failed to communicate with the {@code delegate}.
     * @throws MBeanException if unable to add a client to the remote
     * {@code EventClientDelegateMBean} (see {@link
     * EventClientDelegateMBean#addClient(String, Object[], String[])
     * EventClientDelegateMBean.addClient}).
     * @throws IllegalArgumentException If {@code delegate} is {@code null}.
     */
    public FetchingEventRelay(EventClientDelegateMBean delegate,
            int bufferSize,
            long timeout,
            int maxNotifs,
            Executor executor) throws IOException, MBeanException {
        this(delegate,
                bufferSize,
                timeout,
                maxNotifs,
                executor,
                FetchingEventForwarder.class.getName(),
                new Object[] {bufferSize},
                new String[] {int.class.getName()});
    }

    /**
     * Constructs a {@code FetchingEventRelay} object with user-specific
     * configuration and executor to fetch notifications via the
     * {@link EventClientDelegateMBean}.
     *
     * @param delegate The {@code EventClientDelegateMBean} to work with.
     * @param bufferSize The buffer size for saving notifications in
     * {@link EventClientDelegateMBean} before they are fetched.
     * @param timeout The waiting time in millseconds when fetching
     * notifications from an {@code EventClientDelegateMBean}.
     * @param maxNotifs The maximum notifications to fetch every time.
     * @param executor Used to do the fetching.
     * @param forwarderName the class name of a user specific EventForwarder
     * to create in server to forward notifications to this object. The class
     * should be a subclass of the class {@link FetchingEventForwarder}.
     * @param params the parameters passed to create {@code forwarderName}
     * @param sig the signature of the {@code params}
     * @throws IOException if failed to communicate with the {@code delegate}.
     * @throws MBeanException if unable to add a client to the remote
     * {@code EventClientDelegateMBean} (see {@link
     * EventClientDelegateMBean#addClient(String, Object[], String[])
     * EventClientDelegateMBean.addClient}).
     * @throws IllegalArgumentException if {@code bufferSize} or
     * {@code maxNotifs} is less than {@code 1}
     * @throws NullPointerException if {@code delegate} is {@code null}.
     */
    public FetchingEventRelay(EventClientDelegateMBean delegate,
            int bufferSize,
            long timeout,
            int maxNotifs,
            Executor executor,
            String forwarderName,
            Object[] params,
            String[] sig) throws IOException, MBeanException {

        if (logger.traceOn()) {
            logger.trace("FetchingEventRelay", "delegateMBean "+
                    bufferSize+" "+
                    timeout+" "+
                    maxNotifs+" "+
                    executor+" "+
                    forwarderName+" ");
        }

        if(delegate == null) {
            throw new NullPointerException("Null EventClientDelegateMBean!");
        }


        if (bufferSize<=1) {
            throw new IllegalArgumentException(
                    "The bufferSize cannot be less than 1, no meaning.");
        }

        if (maxNotifs<=1) {
            throw new IllegalArgumentException(
                    "The maxNotifs cannot be less than 1, no meaning.");
        }

        clientId = delegate.addClient(
                forwarderName,
                params,
                sig);

        this.delegate = delegate;
        this.timeout = timeout;
        this.maxNotifs = maxNotifs;

        if (executor == null) {
216
            ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(1,
217
                    daemonThreadFactory);
218 219 220 221 222 223
            stpe.setKeepAliveTime(1, TimeUnit.SECONDS);
            stpe.allowCoreThreadTimeOut(true);
            executor = stpe;
            this.defaultExecutor = stpe;
        } else
            this.defaultExecutor = null;
224 225 226 227 228 229
        this.executor = executor;

        startSequenceNumber = 0;
        fetchingJob = new MyJob();
    }

230
    public synchronized void setEventReceiver(EventReceiver eventReceiver) {
231 232 233 234 235
        if (logger.traceOn()) {
            logger.trace("setEventReceiver", ""+eventReceiver);
        }

        EventReceiver old = this.eventReceiver;
236 237 238
        this.eventReceiver = eventReceiver;
        if (old == null && eventReceiver != null)
            fetchingJob.resume();
239 240 241 242 243 244
    }

    public String getClientId() {
        return clientId;
    }

245
    public synchronized void stop() {
246 247 248
        if (logger.traceOn()) {
            logger.trace("stop", "");
        }
249 250
        if (stopped) {
            return;
251
        }
252 253 254 255 256

        stopped = true;
        clientId = null;
        if (defaultExecutor != null)
            defaultExecutor.shutdown();
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
    }

    private class MyJob extends RepeatedSingletonJob {
        public MyJob() {
            super(executor);
        }

        public boolean isSuspended() {
            boolean b;
            synchronized(FetchingEventRelay.this) {
                b = stopped ||
                        (eventReceiver == null) ||
                        (clientId == null);
            }

            if (logger.traceOn()) {
                logger.trace("-MyJob-isSuspended", ""+b);
            }
            return b;
        }

        public void task() {
            logger.trace("MyJob-task", "");
            long fetchTimeout = timeout;
            NotificationResult nr = null;
            Throwable failedExcep = null;
            try {
                nr = delegate.fetchNotifications(
                        clientId,
                        startSequenceNumber,
                        maxNotifs,
                        fetchTimeout);
            } catch (Exception e) {
                if (isSerialOrClassNotFound(e)) {
                    try {
                        nr = fetchOne();
                    } catch (Exception ee) {
                        failedExcep = e;
                    }
                } else {
                    failedExcep = e;
                }
            }

            if (failedExcep != null &&
                    !isSuspended()) {
                logger.fine("MyJob-task",
                        "Failed to fetch notification, stopping...", failedExcep);
                try {
                    eventReceiver.failed(failedExcep);
                } catch (Exception e) {
                    logger.trace(
                            "MyJob-task", "exception from eventReceiver.failed", e);
                }

                stop();
            } else if (nr != null) {
                try {
                    eventReceiver.receive(nr);
                } catch (RuntimeException e) {
                    logger.trace(
                            "MyJob-task",
                            "exception delivering notifs to EventClient", e);
                } finally {
                    startSequenceNumber = nr.getNextSequenceNumber();
                }
            }
        }
    }

    private NotificationResult fetchOne() throws Exception {
        logger.trace("fetchOne", "");

        while (true) {
            try {
                // 1 notif to skip possible missing class
                return delegate.fetchNotifications(
                        clientId,
                        startSequenceNumber,
                        1,
                        timeout);
            } catch (Exception e) {
                if (isSerialOrClassNotFound(e)) { // skip and continue
                    if (logger.traceOn()) {
                        logger.trace("fetchOne", "Ignore", e);
                    }
                    eventReceiver.nonFatal(e);
                    startSequenceNumber++;
                } else {
                    throw e;
                }
            }
        }
    }

    static boolean isSerialOrClassNotFound(Exception e) {
        Throwable cause = e.getCause();

        while (cause != null &&
                !(cause instanceof ClassNotFoundException) &&
                !(cause instanceof NotSerializableException)) {
            cause = cause.getCause();
        }

        return (cause instanceof ClassNotFoundException ||
                cause instanceof NotSerializableException);
    }

    private long startSequenceNumber = 0;
    private EventReceiver eventReceiver = null;
    private final EventClientDelegateMBean delegate;
    private String clientId;
    private boolean stopped = false;

    private final Executor executor;
372
    private final ExecutorService defaultExecutor;
373 374 375 376 377 378 379 380 381
    private final MyJob fetchingJob;

    private final long timeout;
    private final int maxNotifs;

    private static final ClassLogger logger =
            new ClassLogger("javax.management.event",
            "FetchingEventRelay");
    private static final ThreadFactory daemonThreadFactory =
382
                    new DaemonThreadFactory("JMX FetchingEventRelay executor %d");
383
}