This commit is contained in:
Alejandro Murillo 2015-05-21 17:11:55 -07:00
commit d312bbb6ed
10 changed files with 451 additions and 70 deletions
jdk
src/java.management/share/classes/sun/management
test
TEST.groups
java/lang
instrument/PremainClass
management/ThreadMXBean
javax/management/remote/mandatory/notif
sun/management/jmxremote

@ -345,6 +345,7 @@ public class Agent {
if (jmxServer != null) {
ConnectorBootstrap.unexportRegistry();
ConnectorAddressLink.unexportRemote();
// Attempt to stop already stopped agent
// Don't cause any errors.

@ -1,5 +1,5 @@
/*
* Copyright (c) 2004, 2012, Oracle and/or its affiliates. All rights reserved.
* Copyright (c) 2004, 2015, Oracle and/or its affiliates. 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
@ -27,6 +27,7 @@ package sun.management;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@ -45,9 +46,26 @@ import sun.management.counter.perf.PerfInstrumentation;
* @since 1.5
*/
public class ConnectorAddressLink {
/**
* A simple wrapper for the perf-counter backing {@linkplain ByteBuffer}
*/
private static final class PerfHandle {
private ByteBuffer bb;
private PerfHandle(ByteBuffer bb) {
this.bb = bb.order(ByteOrder.nativeOrder());
}
private void putLong(long l) {
this.bb = bb.clear();
this.bb.asLongBuffer().put(l);
}
}
private static final String CONNECTOR_ADDRESS_COUNTER =
"sun.management.JMXConnectorServer.address";
private static final String REMOTE_CONNECTOR_STATE_COUNTER =
"sun.management.JMXConnectorServer.remote.enabled";
/*
* The format of the jvmstat counters representing the properties of
@ -78,7 +96,9 @@ public class ConnectorAddressLink {
* JMX remote connector counter (it will be incremented every
* time a new out-of-the-box JMX remote connector is created).
*/
private static AtomicInteger counter = new AtomicInteger();
private static final AtomicInteger counter = new AtomicInteger();
private static PerfHandle remotePerfHandle = null;
/**
* Exports the specified connector address to the instrumentation buffer
@ -93,7 +113,17 @@ public class ConnectorAddressLink {
}
Perf perf = Perf.getPerf();
perf.createString(
CONNECTOR_ADDRESS_COUNTER, 1, Units.STRING.intValue(), address);
CONNECTOR_ADDRESS_COUNTER, 1, Units.STRING.intValue(), address);
}
public static void unexportRemote() {
unexport(remotePerfHandle);
}
private static void unexport(PerfHandle ph) {
if (ph != null) {
ph.putLong(-1L);
}
}
/**
@ -143,6 +173,13 @@ public class ConnectorAddressLink {
perf.createString(REMOTE_CONNECTOR_COUNTER_PREFIX + index + "." +
entry.getKey(), 1, Units.STRING.intValue(), entry.getValue());
}
if (remotePerfHandle != null) {
remotePerfHandle.putLong(index);
} else {
remotePerfHandle = new PerfHandle(
perf.createLong(REMOTE_CONNECTOR_STATE_COUNTER, 1, Units.NONE.intValue(), (long)index)
);
}
}
/**

@ -598,6 +598,10 @@ needs_compact3 = \
sun/security/jgss \
sun/security/krb5 \
java/lang/annotation/AnnotationType/AnnotationTypeDeadlockTest.java \
java/lang/invoke/lambda/LambdaStackTrace.java \
java/lang/invoke/LFCaching/LFGarbageCollectedTest.java \
java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java \
java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java \
java/lang/System/MacEncoding/TestFileEncoding.java \
java/nio/channels/AsynchronousSocketChannel/Leaky.java \
java/security/PermissionCollection/Concurrent.java \

@ -33,7 +33,7 @@ import jdk.testlibrary.Utils;
* @modules java.management
* @run build jdk.testlibrary.* DummyMain
* @run shell ../MakeJAR3.sh NoPremainAgent
* @run main NoPremainAgentTest
* @run main/othervm -XX:-CreateCoredumpOnCrash NoPremainAgentTest
*/
public class NoPremainAgentTest {
// Use a javaagent without the premain() function.

@ -33,7 +33,7 @@ import jdk.testlibrary.Utils;
* @modules java.management
* @run build jdk.testlibrary.* DummyMain
* @run shell ../MakeJAR3.sh ZeroArgPremainAgent
* @run main ZeroArgPremainAgentTest
* @run main/othervm -XX:-CreateCoredumpOnCrash ZeroArgPremainAgentTest
*/
public class ZeroArgPremainAgentTest {
// Use a javaagent with a zero argument premain() function.

@ -32,9 +32,30 @@
*/
import java.lang.management.*;
import java.time.Instant;
import java.util.concurrent.Phaser;
import java.util.function.Supplier;
public class AllThreadIds {
/**
* A supplier wrapper for the delayed format printing.
* The supplied value will have to be formatted as <em>$s</em>
* @param <T> The wrapped type
*/
private static final class ArgWrapper<T> {
private final Supplier<T> val;
public ArgWrapper(Supplier<T> val) {
this.val = val;
}
@Override
public String toString() {
T resolved = val.get();
return resolved != null ? resolved.toString() : null;
}
}
final static int DAEMON_THREADS = 20;
final static int USER_THREADS = 5;
final static int ALL_THREADS = DAEMON_THREADS + USER_THREADS;
@ -47,15 +68,10 @@ public class AllThreadIds {
private static long prevTotalThreadCount = 0;
private static int prevLiveThreadCount = 0;
private static int prevPeakThreadCount = 0;
private static long curTotalThreadCount = 0;
private static int curLiveThreadCount = 0;
private static int curPeakThreadCount = 0;
private static final Phaser startupCheck = new Phaser(ALL_THREADS + 1);
private static void printThreadList() {
if (!trace) return;
long[] list = mbean.getAllThreadIds();
for (int i = 1; i <= list.length; i++) {
System.out.println(i + ": Thread id = " + list[i-1]);
@ -68,59 +84,13 @@ public class AllThreadIds {
}
}
private static void fail(String msg) {
trace = true;
printThreadList();
throw new RuntimeException(msg);
}
private static void checkThreadCount(int numNewThreads,
int numTerminatedThreads)
throws Exception {
prevTotalThreadCount = curTotalThreadCount;
prevLiveThreadCount = curLiveThreadCount;
prevPeakThreadCount = curPeakThreadCount;
curTotalThreadCount = mbean.getTotalStartedThreadCount();
curLiveThreadCount = mbean.getThreadCount();
curPeakThreadCount = mbean.getPeakThreadCount();
if ((curLiveThreadCount - prevLiveThreadCount) !=
(numNewThreads - numTerminatedThreads)) {
fail("Unexpected number of live threads: " +
" Prev live = " + prevLiveThreadCount +
" Current live = " + curLiveThreadCount +
" Threads added = " + numNewThreads +
" Threads terminated = " + numTerminatedThreads);
}
if (curPeakThreadCount - prevPeakThreadCount != numNewThreads) {
fail("Unexpected number of peak threads: " +
" Prev peak = " + prevPeakThreadCount +
" Current peak = " + curPeakThreadCount +
" Threads added = " + numNewThreads);
}
if (curTotalThreadCount - prevTotalThreadCount != numNewThreads) {
fail("Unexpected number of total threads: " +
" Prev Total = " + prevTotalThreadCount +
" Current Total = " + curTotalThreadCount +
" Threads added = " + numNewThreads);
}
long[] list = mbean.getAllThreadIds();
if (list.length != curLiveThreadCount) {
fail("Array length returned by " +
"getAllThreadIds() = " + list.length +
" not matched count = " + curLiveThreadCount);
}
}
public static void main(String args[]) throws Exception {
if (args.length > 0 && args[0].equals("trace")) {
trace = true;
}
curTotalThreadCount = mbean.getTotalStartedThreadCount();
curLiveThreadCount = mbean.getThreadCount();
curPeakThreadCount = mbean.getPeakThreadCount();
private static void checkInitialState() throws Exception {
updateCounters();
checkThreadCount(0, 0);
}
private static void checkAllThreadsAlive() throws Exception {
updateCounters();
// Start all threads and wait to be sure they all are alive
for (int i = 0; i < ALL_THREADS; i++) {
@ -133,8 +103,9 @@ public class AllThreadIds {
startupCheck.arriveAndAwaitAdvance();
checkThreadCount(ALL_THREADS, 0);
printThreadList();
if (trace) {
printThreadList();
}
// Check mbean now. All threads must appear in getAllThreadIds() list
long[] list = mbean.getAllThreadIds();
@ -165,6 +136,10 @@ public class AllThreadIds {
if (trace) {
System.out.println();
}
}
private static void checkDaemonThreadsDead() throws Exception {
updateCounters();
// Stop daemon threads, wait to be sure they all are dead, and check
// that they disappeared from getAllThreadIds() list
@ -179,7 +154,7 @@ public class AllThreadIds {
checkThreadCount(0, DAEMON_THREADS);
// Check mbean now
list = mbean.getAllThreadIds();
long[] list = mbean.getAllThreadIds();
for (int i = 0; i < ALL_THREADS; i++) {
long expectedId = allThreads[i].getId();
@ -208,6 +183,10 @@ public class AllThreadIds {
}
}
}
}
private static void checkAllThreadsDead() throws Exception {
updateCounters();
// Stop all threads and wait to be sure they all are dead
for (int i = DAEMON_THREADS; i < ALL_THREADS; i++) {
@ -219,6 +198,127 @@ public class AllThreadIds {
// and check the thread count
checkThreadCount(0, ALL_THREADS - DAEMON_THREADS);
}
private static void checkThreadCount(int numNewThreads,
int numTerminatedThreads)
throws Exception {
checkLiveThreads(numNewThreads, numTerminatedThreads);
checkPeakThreads(numNewThreads);
checkTotalThreads(numNewThreads);
checkThreadIds();
}
private static void checkLiveThreads(int numNewThreads,
int numTerminatedThreads)
throws InterruptedException {
int diff = numNewThreads - numTerminatedThreads;
waitTillEquals(
diff + prevLiveThreadCount,
()->(long)mbean.getThreadCount(),
"Unexpected number of live threads: " +
" Prev live = %1$d Current live = ${provided} Threads added = %2$d" +
" Threads terminated = %3$d",
()->prevLiveThreadCount,
()->numNewThreads,
()->numTerminatedThreads
);
}
private static void checkPeakThreads(int numNewThreads)
throws InterruptedException {
waitTillEquals(numNewThreads + prevPeakThreadCount,
()->(long)mbean.getPeakThreadCount(),
"Unexpected number of peak threads: " +
" Prev peak = %1$d Current peak = ${provided} Threads added = %2$d",
()->prevPeakThreadCount,
()->numNewThreads
);
}
private static void checkTotalThreads(int numNewThreads)
throws InterruptedException {
waitTillEquals(numNewThreads + prevTotalThreadCount,
()->mbean.getTotalStartedThreadCount(),
"Unexpected number of total threads: " +
" Prev Total = %1$d Current Total = ${provided} Threads added = %2$d",
()->prevTotalThreadCount,
()->numNewThreads
);
}
private static void checkThreadIds() throws InterruptedException {
long[] list = mbean.getAllThreadIds();
waitTillEquals(
list.length,
()->(long)mbean.getThreadCount(),
"Array length returned by " +
"getAllThreadIds() = %1$d not matched count = ${provided}",
()->list.length
);
}
/**
* Waits till the <em>expectedVal</em> equals to the <em>retrievedVal</em>.
* It will report a status message on the first occasion of the value mismatch
* and then, subsequently, when the <em>retrievedVal</em> value changes.
* @param expectedVal The value to wait for
* @param retrievedVal The supplier of the value to check against the <em>expectedVal</em>
* @param msgFormat The formatted message to be printed in case of mismatch
* @param msgArgs The parameters to the formatted message
* @throws InterruptedException
*/
private static void waitTillEquals(long expectedVal, Supplier<Long> retrievedVal,
String msgFormat, Supplier<Object> ... msgArgs)
throws InterruptedException {
Object[] args = null;
long countPrev = -1;
while (true) {
Long count = retrievedVal.get();
if (count == expectedVal) break;
if (countPrev == -1 || countPrev != count) {
if (args == null) {
args = new Object[msgArgs.length];
for(int i=0; i < msgArgs.length; i++) {
args[i] = new ArgWrapper<>((Supplier<Object>)msgArgs[i]);
}
}
System.err.format("TS: %s\n", Instant.now());
System.err.format(
msgFormat
.replace("${provided}", String.valueOf(count))
.replace("$d", "$s"),
args
).flush();
printThreadList();
System.err.println("\nRetrying ...\n");
}
countPrev = count;
Thread.sleep(1);
}
}
private static void updateCounters() {
prevTotalThreadCount = mbean.getTotalStartedThreadCount();
prevLiveThreadCount = mbean.getThreadCount();
prevPeakThreadCount = mbean.getPeakThreadCount();
}
public static void main(String args[]) throws Exception {
if (args.length > 0 && args[0].equals("trace")) {
trace = true;
}
checkInitialState();
checkAllThreadsAlive();
checkDaemonThreadsDead();
checkAllThreadsDead();
if (testFailed)
throw new RuntimeException("TEST FAILED.");

@ -21,12 +21,16 @@
* questions.
*/
/*
/**
* @test
* @bug 6338874
* @summary Check that notification dispatch is not linear in number of MBeans.
* @author Eamonn McManus
* @modules java.management
*
* @library /lib/testlibrary
* @run build jdk.testlibrary.* ListenerScaleTest
* @run main ListenerScaleTest
*/
/*
@ -67,6 +71,8 @@ import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import jdk.testlibrary.Platform;
public class ListenerScaleTest {
private static final int WARMUP_WITH_ONE_MBEAN = 1000;
private static final int NOTIFS_TO_TIME = 100;
@ -126,6 +132,10 @@ public class ListenerScaleTest {
};
public static void main(String[] args) throws Exception {
if (Platform.isDebugBuild()) {
System.out.println("Running on a debug build. Performance test not applicable. Skipping.");
return;
}
MBeanServer mbs = MBeanServerFactory.newMBeanServer();
Sender sender = new Sender();
mbs.registerMBean(sender, testObjectName);

@ -116,10 +116,10 @@ public class JvmstatCountersTest {
throw new IllegalArgumentException("Test case 3 failed");
}
for (String key : remoteData.keySet()) {
if (!key.startsWith("sun.management.JMXConnectorServer.0.")) {
if (!isKeyAcceptable(key)) {
System.out.println("Test FAILED! The OOTB management " +
"agent shouldn't publish anything which isn't " +
"related to the remote connector.");
"related to the remote connector (" + key + ").");
throw new IllegalArgumentException("Test case 3 failed");
}
}
@ -165,10 +165,10 @@ public class JvmstatCountersTest {
throw new IllegalArgumentException("Test case 4 failed");
}
for (String key : remoteData2.keySet()) {
if (!key.startsWith("sun.management.JMXConnectorServer.0.")) {
if (!isKeyAcceptable(key)) {
System.out.println("Test FAILED! The OOTB management " +
"agent shouldn't publish anything which isn't " +
"related to the remote connector.");
"related to the remote connector (" + key + ").");
throw new IllegalArgumentException("Test case 4 failed");
}
}
@ -184,4 +184,9 @@ public class JvmstatCountersTest {
}
System.out.println("Bye! Bye!");
}
private static boolean isKeyAcceptable(String key) {
return key.startsWith("sun.management.JMXConnectorServer.0.") ||
key.startsWith("sun.management.JMXConnectorServer.remote.enabled");
}
}

@ -0,0 +1,188 @@
/*
* Copyright (c) 2015, Oracle and/or its affiliates. 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.
*
* 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.IOException;
import java.net.BindException;
import java.util.Properties;
import java.util.function.Predicate;
import static org.testng.Assert.*;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import jdk.testlibrary.ProcessTools;
/**
* @test
* @bug 8075926
* @summary Makes sure that the current management agent status is reflected
* in the related performance counters.
* @library /lib/testlibrary
* @build jdk.testlibrary.* PortAllocator TestApp ManagementAgentJcmd
* @run testng/othervm -XX:+UsePerfData JMXStatusPerfCountersTest
*/
public class JMXStatusPerfCountersTest {
private final static String TEST_APP_NAME = "TestApp";
private final static String REMOTE_STATUS_KEY = "sun.management.JMXConnectorServer.remote.enabled";
private static ProcessBuilder testAppPb;
private Process testApp;
private ManagementAgentJcmd jcmd;
@BeforeClass
public static void setupClass() throws Exception {
testAppPb = ProcessTools.createJavaProcessBuilder(
"-XX:+UsePerfData",
"-cp", System.getProperty("test.class.path"),
TEST_APP_NAME
);
}
@BeforeTest
public void setup() {
jcmd = new ManagementAgentJcmd(TEST_APP_NAME, false);
}
@BeforeMethod
public void startTestApp() throws Exception {
testApp = ProcessTools.startProcess(
TEST_APP_NAME, testAppPb,
(Predicate<String>)l->l.trim().equals("main enter")
);
}
@AfterMethod
public void stopTestApp() throws Exception {
testApp.getOutputStream().write(1);
testApp.getOutputStream().flush();
testApp.waitFor();
testApp = null;
}
/**
* The 'sun.management.JMXConnectorServer.remote.enabled' counter must not be
* exported if the remote agent is not enabled.
* @throws Exception
*/
@Test
public void testNotInitializedRemote() throws Exception {
assertFalse(
getCounters().containsKey(REMOTE_STATUS_KEY),
"Unexpected occurrence of " + REMOTE_STATUS_KEY + " in perf counters"
);
}
/**
* After enabling the remote agent the 'sun.management.JMXConnectorServer.remote.enabled'
* counter will be exported with value of '0' - corresponding to the actual
* version of the associated remote connector perf counters.
* @throws Exception
*/
@Test
public void testRemoteEnabled() throws Exception {
while (true) {
try {
int[] ports = PortAllocator.allocatePorts(1);
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
String v = getCounters().getProperty(REMOTE_STATUS_KEY);
assertNotNull(v);
assertEquals("0", v);
return;
} catch (BindException e) {
System.out.println("Failed to allocate ports. Retrying ...");
}
}
}
/**
* After disabling the remote agent the value of 'sun.management.JMXConnectorServer.remote.enabled'
* counter will become '-1'.
* @throws Exception
*/
@Test
public void testRemoteDisabled() throws Exception {
while (true) {
try {
int[] ports = PortAllocator.allocatePorts(1);
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
jcmd.stop();
String v = getCounters().getProperty(REMOTE_STATUS_KEY);
assertNotNull(v);
assertEquals("-1", v);
return;
} catch (BindException e) {
System.out.println("Failed to allocate ports. Retrying ...");
}
}
}
/**
* Each subsequent re-enablement of the remote agent must keep the value of
* 'sun.management.JMXConnectorServer.remote.enabled' counter in sync with
* the actual version of the associated remote connector perf counters.
* @throws Exception
*/
@Test
public void testRemoteReEnabled() throws Exception {
while (true) {
try {
int[] ports = PortAllocator.allocatePorts(1);
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
jcmd.stop();
jcmd.start(
"jmxremote.port=" + ports[0],
"jmxremote.authenticate=false",
"jmxremote.ssl=false"
);
String v = getCounters().getProperty(REMOTE_STATUS_KEY);
assertNotNull(v);
assertEquals("1", v);
return;
} catch (BindException e) {
System.out.println("Failed to allocate ports. Retrying ...");
}
}
}
private Properties getCounters() throws IOException, InterruptedException {
return jcmd.perfCounters("sun\\.management\\.JMXConnectorServer\\..*");
}
}

@ -25,8 +25,10 @@ import java.net.BindException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import sun.management.Agent;
import sun.management.AgentConfigurationError;
@ -43,6 +45,7 @@ final class ManagementAgentJcmd {
private static final String CMD_START = "ManagementAgent.start";
private static final String CMD_START_LOCAL = "ManagementAgent.start_local";
private static final String CMD_STATUS = "ManagementAgent.status";
private static final String CMD_PRINTPERF = "PerfCounter.print";
private final String id;
private final boolean verbose;
@ -62,6 +65,39 @@ final class ManagementAgentJcmd {
return jcmd();
}
/**
* `jcmd PerfCounter.print`
* @return Returns the available performance counters with their values as
* {@linkplain Properties} instance
* @throws IOException
* @throws InterruptedException
*/
public Properties perfCounters() throws IOException, InterruptedException {
return perfCounters(".*");
}
/**
* `jcmd PerfCounter.print | grep {exp}>`
* @param regex Regular expression for including perf counters in the result
* @return Returns the matching performance counters with their values
* as {@linkplain Properties} instance
* @throws IOException
* @throws InterruptedException
*/
public Properties perfCounters(String regex) throws IOException, InterruptedException {
Pattern pat = Pattern.compile(regex);
Properties p = new Properties();
for(String l : jcmd(CMD_PRINTPERF).split("\\n")) {
String[] kv = l.split("=");
if (kv.length > 1) {
if (pat.matcher(kv[0]).matches()) {
p.setProperty(kv[0], kv[1].replace("\"", ""));
}
}
}
return p;
}
/**
* `jcmd <app> ManagementAgent.stop`
* @return The JCMD output