Java Code Examples for javax.management.Notification#getUserData()

The following examples show how to use javax.management.Notification#getUserData() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cassandra-reaper   File: JmxProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Handles notifications from the old repair API (forceRepairAsync)
 */
private void processOldApiNotification(Notification notification) {
  try {
    int[] data = (int[]) notification.getUserData();
    // get the repair sequence number
    int repairNo = data[0];
    // get the repair status
    ActiveRepairService.Status status = ActiveRepairService.Status.values()[data[1]];
    // this is some text message like "Starting repair...", "Finished repair...", etc.
    String message = notification.getMessage();
    // let the handler process the even
    if (repairStatusHandlers.containsKey(repairNo)) {
      LOG.debug("Handling notification {} with repair handler {}", notification, repairStatusHandlers.get(repairNo));

      repairStatusHandlers
          .get(repairNo)
          .handle(repairNo, Optional.of(status), Optional.empty(), message, this);
    }
  } catch (RuntimeException e) {
    LOG.error("Error while processing JMX notification", e);
  }
}
 
Example 2
Source Project: cassandra-reaper   File: JmxProxyImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Handles notifications from the new repair API (repairAsync)
 */
private void processNewApiNotification(Notification notification) {
  Map<String, Integer> data = (Map<String, Integer>) notification.getUserData();
  try {
    // get the repair sequence number
    int repairNo = Integer.parseInt(((String) notification.getSource()).split(":")[1]);
    // get the progress status
    ProgressEventType progress = ProgressEventType.values()[data.get("type")];
    // this is some text message like "Starting repair...", "Finished repair...", etc.
    String message = notification.getMessage();
    // let the handler process the even
    if (repairStatusHandlers.containsKey(repairNo)) {
      LOG.debug("Handling notification {} with repair handler {}", notification, repairStatusHandlers.get(repairNo));

      repairStatusHandlers
          .get(repairNo)
          .handle(repairNo, Optional.empty(), Optional.of(progress), message, this);
    }
  } catch (NumberFormatException e) {
    LOG.error("Error while processing JMX notification", e);
  }
}
 
Example 3
Source Project: spectator   File: GcLogger.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void handleNotification(Notification notification, Object ref) {
  final String type = notification.getType();
  if (type.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
    CompositeData cd = (CompositeData) notification.getUserData();
    GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(cd);
    processGcEvent(info);
  }
}
 
Example 4
private NotificationListener createJMXNotificationListener() {
	return new NotificationListener() {
		@Override
		public void handleNotification(Notification notification, Object handback) {
			if (CloverJMX.GRAPH_FINISHED.equals(notification.getType())) {
				JMXNotificationMessage notificationMessage = (JMXNotificationMessage) notification.getUserData();					
				CloverJMX.getInstance().releaseJob(notificationMessage.getRunId());
			}
		}
	};
}
 
Example 5
@Override
public void handleNotification(Notification notification, Object handback) {
    val type = notification.getType();
    if(type.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
        val userData = (CompositeData) notification.getUserData();
        val info = GarbageCollectionNotificationInfo.from(userData);
        processGCEvent(info);
    }
}
 
Example 6
@Override
public boolean isNotificationEnabled(Notification notification) {
	Object userData = notification.getUserData();
	if (userData instanceof JMXNotificationMessage) {
		JMXNotificationMessage message = (JMXNotificationMessage) userData;
		return runId == message.getRunId();
	} else {
		return false;
	}
}
 
Example 7
Source Project: gossip   File: GossipManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * All timers associated with a member will trigger this method when it goes off. The timer will
 * go off if we have not heard from this member in <code> _settings.T_CLEANUP </code> time.
 */
@Override
public void handleNotification(Notification notification, Object handback) {
  LocalGossipMember deadMember = (LocalGossipMember) notification.getUserData();
  GossipService.LOGGER.debug("Dead member detected: " + deadMember);
  members.put(deadMember, GossipState.DOWN);
  if (listener != null) {
    listener.gossipEvent(deadMember, GossipState.DOWN);
  }
}
 
Example 8
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 9
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 10
@Override
public void handleNotification(final Notification notification, final Object handback) {
    if (!notification.getType().equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION)) {
        return;
    }

    final CompositeData compositeData = (CompositeData) notification.getUserData();
    final GarbageCollectionNotificationInfo gcNotification = GarbageCollectionNotificationInfo.from(compositeData);
    final GcInfo gcInfo = gcNotification.getGcInfo();

    final String gcName = gcNotification.getGcName();
    final String action = gcNotification.getGcAction();
    final String cause = gcNotification.getGcCause();

    final long startTime = jvmStartTime + gcInfo.getStartTime();
    final long endTime = jvmStartTime + gcInfo.getEndTime();

    final Map<String, MemoryUsage> usageAfter = gcInfo.getMemoryUsageAfterGc();
    final Map<String, MemoryUsage> usageBefore = gcInfo.getMemoryUsageBeforeGc();

    final List<GarbageCollectionEvent.GarbageCollectionHeapSize> heapSizes = new ArrayList<>();
    for (final Map.Entry<String, MemoryUsage> entry : usageAfter.entrySet()) {
        final MemoryUsage before = usageBefore.get(entry.getKey());
        if (before == null) {
            continue;
        }

        final MemoryUsage after = entry.getValue();
        if (after.getUsed() == before.getUsed()) {
            continue;
        }

        heapSizes.add(new StandardGarbageCollectionEvent.StandardGarbageCollectionHeapSize(entry.getKey(), before.getUsed(), after.getUsed()));
    }

    final GarbageCollectionEvent event = new StandardGarbageCollectionEvent(gcName, action, cause, startTime, endTime, heapSizes);

    if (gcInfo.getDuration() >= minDurationThreshold) {
        events.add(event);
    }

    synchronized (this) {
        final Tuple<Long, Long> previousTuple = timeAndCountPerAction.get(action);
        if (previousTuple == null){
            timeAndCountPerAction.put(action, new Tuple<>(gcInfo.getDuration(), 1L));
        } else {
            timeAndCountPerAction.put(action, new Tuple<>(gcInfo.getDuration() + previousTuple.getKey(), 1L + previousTuple.getValue()));
        }

        if (maxDurationEvent == null || event.getDuration() > maxDurationEvent.getDuration()) {
            maxDurationEvent = event;
        }
    }
}
 
Example 11
Source Project: stratio-cassandra   File: GCInspector.java    License: Apache License 2.0 4 votes vote down vote up
public void handleNotification(Notification notification, Object handback)
{
    String type = notification.getType();
    if (type.equals(GarbageCollectionNotificationInfo.GARBAGE_COLLECTION_NOTIFICATION))
    {
        // retrieve the garbage collection notification information
        CompositeData cd = (CompositeData) notification.getUserData();
        GarbageCollectionNotificationInfo info = GarbageCollectionNotificationInfo.from(cd);

        long duration = info.getGcInfo().getDuration();

        StringBuilder sb = new StringBuilder();
        sb.append(info.getGcName()).append(" GC in ").append(duration).append("ms.  ");

        long bytes = 0;
        List<String> keys = new ArrayList<>(info.getGcInfo().getMemoryUsageBeforeGc().keySet());
        Collections.sort(keys);
        for (String key : keys)
        {
            MemoryUsage before = info.getGcInfo().getMemoryUsageBeforeGc().get(key);
            MemoryUsage after = info.getGcInfo().getMemoryUsageAfterGc().get(key);
            if (after != null && after.getUsed() != before.getUsed())
            {
                sb.append(key).append(": ").append(before.getUsed());
                sb.append(" -> ");
                sb.append(after.getUsed());
                if (!key.equals(keys.get(keys.size() - 1)))
                    sb.append("; ");
                bytes += before.getUsed() - after.getUsed();
            }
        }

        while (true)
        {
            State prev = state.get();
            if (state.compareAndSet(prev, new State(duration, bytes, prev)))
                break;
        }

        String st = sb.toString();
        if (duration > MIN_LOG_DURATION)
            logger.info(st);
        else if (logger.isDebugEnabled())
            logger.debug(st);

        if (duration > MIN_LOG_DURATION_TPSTATS)
            StatusLogger.log();

        // if we just finished a full collection and we're still using a lot of memory, try to reduce the pressure
        if (info.getGcName().equals("ConcurrentMarkSweep"))
            SSTableDeletingTask.rescheduleFailedTasks();
    }
}
 
Example 12
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 13
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 14
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 15
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 16
@Override
public void handleNotification(final Notification notification, final Object handback) {
    if (!"repair".equals(notification.getType())) {
        return;
    }

    final int[] result = (int[]) notification.getUserData();
    final int repairCommandNo = result[0];
    final ActiveRepairService.Status status = ActiveRepairService.Status.values()[result[1]];

    final String keyspace = commandToKeyspace.get(repairCommandNo);

    switch (status) {
        case STARTED:
            LOGGER.info("Received STARTED notification about repair for keyspace {} with cmd#{}, timetamp={}, message={}",
                    keyspace, repairCommandNo, notification.getTimeStamp(), notification.getMessage());
            keyspaceStarted();
            break;
        case SESSION_SUCCESS:
            LOGGER.debug("Received SESSION_SUCCESS notification about repair for keyspace {} with cmd#{}, timetamp={}, message={}",
                    keyspace, repairCommandNo, notification.getTimeStamp(), notification.getMessage());
            break;
        case SESSION_FAILED:
            LOGGER.warn("Received SESSION_FAILED notification about repair for keyspace {} with cmd#{}, timetamp={}, message={}",
                    keyspace, repairCommandNo, notification.getTimeStamp(), notification.getMessage());
            break;
        case FINISHED:
            LOGGER.info("Received FINISHED notification about repair for keyspace {} with cmd#{}, timetamp={}, message={}",
                    keyspace, repairCommandNo, notification.getTimeStamp(), notification.getMessage());

            keyspaceFinished(status.name(), keyspace);

            startNextKeyspace();

            break;
    }

    // TODO also allow StorageServiceMBean.forceTerminateAllRepairSessions

    /*
    TODO handle these, too !!!

    else if (JMXConnectionNotification.NOTIFS_LOST.equals(notification.getType()))
    {
        String message = String.format("[%s] Lost notification. You should check server log for repair status of keyspace %s",
                                       format.format(notification.getTimeStamp()),
                                       keyspace);
        out.println(message);
    }
    else if (JMXConnectionNotification.FAILED.equals(notification.getType())
             || JMXConnectionNotification.CLOSED.equals(notification.getType()))
    {
        String message = String.format("JMX connection closed. You should check server log for repair status of keyspace %s"
                                       + "(Subsequent keyspaces are not going to be repaired).",
                                       keyspace);
        error = new IOException(message);
        condition.signalAll();
    }

     */
}
 
Example 17
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 18
private static String notificationString(Notification n) {
    return n.getClass().getName() + "/" + n.getType() + " \"" +
        n.getMessage() + "\" <" + n.getUserData() + ">";
}
 
Example 19
private static GarbageCollectionNotificationInfo getInfo(Notification notification) {
    CompositeData cd = (CompositeData) notification.getUserData();
    return GarbageCollectionNotificationInfo.from(cd);
}
 
Example 20
/**
 * Installs a listener that will publish all full GC events as {@link FullGarbageCollectionEvent} objects.
 */
public void start() {
  // This code only works with Oracle HotSpot JVM as there is no standard API to retrieve information about GC events
  if (!isHotSpotVM()) {
    return;
  }

  long vmStartTime = getApproximateNanoStartTime();

  for (GarbageCollectorMXBean gcBean : ManagementFactory.getGarbageCollectorMXBeans()) {
    Class<? extends TraceEvent> eventType = gcBean.getName().equals("ConcurrentMarkSweep") || gcBean.getName().equals("MarkSweepCompact") //$NON-NLS-1$ //$NON-NLS-2$
        ? FullGarbageCollectionEvent.class
        : MinorGarbageCollectionEvent.class;
    NotificationEmitter emitter = (NotificationEmitter) gcBean;
    NotificationListener listener = new NotificationListener() {

      @Override
      public void handleNotification(final Notification notification, final Object handback) {
        try {
          // we only handle GARBAGE_COLLECTION_NOTIFICATION notifications here
          if (notification.getType().equals("com.sun.management.gc.notification")) { //$NON-NLS-1$
            CompositeData cd = (CompositeData) notification.getUserData();
            String gcAction = (String) cd.get("gcAction"); //$NON-NLS-1$
            String gcCause = (String) cd.get("gcCause"); //$NON-NLS-1$
            CompositeData gcInfo = (CompositeData) cd.get("gcInfo"); //$NON-NLS-1$
            long startTime = TimeUnit.NANOSECONDS.convert((Long) gcInfo.get("startTime"), TimeUnit.MILLISECONDS); //$NON-NLS-1$
            long duration = TimeUnit.NANOSECONDS.convert((Long) gcInfo.get("duration"), TimeUnit.MILLISECONDS); //$NON-NLS-1$
            if (duration > 0) {
              // "startTime" and "duration" are relative to VM start time
              traceSet.started(eventType, vmStartTime + startTime, gcAction, gcCause);
              traceSet.ended(eventType, vmStartTime + startTime + duration);
            }
          }
        } catch (InvalidKeyException e) {
          // ignore
        }
      };
    };
    emitter.addNotificationListener(listener, null, null);
    gcListenerMap.put(emitter, listener);
  }
}