You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2015/12/11 22:23:03 UTC
[29/50] [abbrv] incubator-geode git commit: GEODE-563: Moving gfsh
tests from closed
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/eddef322/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommandsDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommandsDUnitTest.java
new file mode 100644
index 0000000..54aed63
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/QueueCommandsDUnitTest.java
@@ -0,0 +1,385 @@
+/*
+ * 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 com.gemstone.gemfire.management.internal.cli.commands;
+
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.asyncqueue.AsyncEventQueue;
+import com.gemstone.gemfire.distributed.Locator;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.InternalLocator;
+import com.gemstone.gemfire.distributed.internal.SharedConfiguration;
+import com.gemstone.gemfire.internal.AvailablePort;
+import com.gemstone.gemfire.internal.ClassBuilder;
+import com.gemstone.gemfire.internal.FileUtil;
+import com.gemstone.gemfire.management.cli.Result;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
+import com.gemstone.gemfire.management.internal.cli.result.CommandResult;
+import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import dunit.DistributedTestCase;
+import dunit.Host;
+import dunit.SerializableRunnable;
+import dunit.VM;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.List;
+import java.util.Properties;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+/**
+ * A distributed test suite of test cases for testing the queue commands that are part of Gfsh.
+ *
+ * @author David Hoots
+ * @since 8.0
+ */
+public class QueueCommandsDUnitTest extends CliCommandTestBase {
+ private static final long serialVersionUID = 1L;
+
+ final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+
+ public QueueCommandsDUnitTest(final String testName) {
+ super(testName);
+ }
+
+ public void testAsyncEventQueue() throws IOException {
+ final String queue1Name = "testAsyncEventQueue1";
+ final String queue2Name = "testAsyncEventQueue2";
+ final String diskStoreName = "testAsyncEventQueueDiskStore";
+
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.GROUPS_NAME, "Group0");
+ createDefaultSetup(localProps);
+
+ CommandResult cmdResult = executeCommand(CliStrings.LIST_ASYNC_EVENT_QUEUES);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertTrue(commandResultToString(cmdResult).contains("No Async Event Queues Found"));
+
+ final VM vm1 = Host.getHost(0).getVM(1);
+ final String vm1Name = "VM" + vm1.getPid();
+ final File diskStoreDir = new File(new File(".").getAbsolutePath(), diskStoreName);
+ this.filesToBeDeleted.add(diskStoreDir.getAbsolutePath());
+ vm1.invoke(new SerializableRunnable() {
+ public void run() {
+ diskStoreDir.mkdirs();
+
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.NAME_NAME, vm1Name);
+ localProps.setProperty(DistributionConfig.GROUPS_NAME, "Group1");
+ getSystem(localProps);
+ getCache();
+ }
+ });
+
+ final VM vm2 = Host.getHost(0).getVM(2);
+ final String vm2Name = "VM" + vm2.getPid();
+ vm2.invoke(new SerializableRunnable() {
+ public void run() {
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.NAME_NAME, vm2Name);
+ localProps.setProperty(DistributionConfig.GROUPS_NAME, "Group2");
+ getSystem(localProps);
+ getCache();
+ }
+ });
+
+ // Deploy a JAR file with an AsyncEventListener/GatewayEventFilter/GatewayEventSubstitutionFilter
+ // that can be instantiated on each server
+ final File jarFile = new File(new File(".").getAbsolutePath(), "QueueCommandsDUnit.jar");
+ QueueCommandsDUnitTest.this.filesToBeDeleted.add(jarFile.getAbsolutePath());
+
+ ClassBuilder classBuilder = new ClassBuilder();
+ byte[] jarBytes = classBuilder.createJarFromClassContent("com/qcdunit/QueueCommandsDUnitTestHelper",
+ "package com.qcdunit;" +
+ "import java.util.List; import java.util.Properties;" +
+ "import com.gemstone.gemfire.internal.cache.xmlcache.Declarable2; import com.gemstone.gemfire.cache.asyncqueue.AsyncEvent;" +
+ "import com.gemstone.gemfire.cache.wan.GatewayEventFilter; import com.gemstone.gemfire.cache.wan.GatewayEventSubstitutionFilter;" +
+ "import com.gemstone.gemfire.cache.asyncqueue.AsyncEventListener; import com.gemstone.gemfire.cache.wan.GatewayQueueEvent;" +
+ "import com.gemstone.gemfire.cache.EntryEvent;" +
+ "public class QueueCommandsDUnitTestHelper implements Declarable2, GatewayEventFilter, GatewayEventSubstitutionFilter, AsyncEventListener {" +
+ "Properties props;" +
+ "public boolean processEvents(List<AsyncEvent> events) { return true; }" +
+ "public void afterAcknowledgement(GatewayQueueEvent event) {}" +
+ "public boolean beforeEnqueue(GatewayQueueEvent event) { return true; }" +
+ "public boolean beforeTransmit(GatewayQueueEvent event) { return true; }" +
+ "public Object getSubstituteValue(EntryEvent event) { return null; }" +
+ "public void close() {}" +
+ "public void init(final Properties props) {this.props = props;}" +
+ "public Properties getConfig() {return this.props;}}");
+ writeJarBytesToFile(jarFile, jarBytes);
+
+ cmdResult = executeCommand("deploy --jar=QueueCommandsDUnit.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_DISK_STORE);
+ commandStringBuilder.addOption(CliStrings.CREATE_DISK_STORE__NAME, diskStoreName);
+ commandStringBuilder.addOption(CliStrings.CREATE_DISK_STORE__GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE, diskStoreDir.getAbsolutePath());
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertEquals(3, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult, vm1Name + ".*Success"));
+
+ commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_ASYNC_EVENT_QUEUE);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, queue1Name);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE, "514");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT, "true");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE, diskStoreName);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY, "213");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL, "946");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL, "true");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION, "true");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS, "2");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY, "PARTITION");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER,
+ "com.qcdunit.QueueCommandsDUnitTestHelper");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER,
+ "com.qcdunit.QueueCommandsDUnitTestHelper");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS, "false");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER,
+ "com.qcdunit.QueueCommandsDUnitTestHelper");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE, "param1");
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE, "param2#value2");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(3, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult, vm1Name + ".*Success"));
+
+ // Verify that the queue was created on the correct member
+ cmdResult = executeCommand(CliStrings.LIST_ASYNC_EVENT_QUEUES);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(3, countLinesInString(stringResult, false));
+ assertTrue(stringContainsLine(stringResult,
+ vm1Name + " .*" + queue1Name + " .*514 .*true .*" + diskStoreName + " .*213 .*" + " .*com.qcdunit.QueueCommandsDUnitTestHelper" + ".*"));
+ assertTrue(stringContainsLine(stringResult, vm1Name + ".*param2=value2.*"));
+ assertTrue(stringContainsLine(stringResult, vm1Name + ".*param1=[^\\w].*"));
+ assertFalse(stringContainsLine(stringResult, vm2Name + ".*" + queue1Name + ".*"));
+
+ vm1.invoke(new SerializableRunnable() {
+ public void run() {
+ Cache cache = getCache();
+ AsyncEventQueue queue = cache.getAsyncEventQueue(queue1Name);
+ assertEquals(queue.getBatchSize(), 514);
+ assertEquals(queue.isPersistent(), true);
+ assertEquals(queue.getDiskStoreName(), diskStoreName);
+ assertEquals(queue.getMaximumQueueMemory(), 213);
+ assertEquals(queue.getBatchTimeInterval(), 946);
+ assertEquals(queue.isParallel(), true);
+ assertEquals(queue.isBatchConflationEnabled(), true);
+ assertEquals(queue.getDispatcherThreads(), 2);
+ assertEquals(queue.getOrderPolicy().toString(), "PARTITION");
+ assertEquals(queue.getGatewayEventFilters().size(), 1);
+ assertEquals(queue.getGatewayEventFilters().get(0).getClass().getName(),
+ "com.qcdunit.QueueCommandsDUnitTestHelper");
+ assertEquals(queue.getGatewayEventSubstitutionFilter().getClass().getName(),
+ "com.qcdunit.QueueCommandsDUnitTestHelper");
+ assertEquals(queue.isDiskSynchronous(), false);
+ assertEquals(queue.getAsyncEventListener().getClass().getName(), "com.qcdunit.QueueCommandsDUnitTestHelper");
+ }
+ });
+
+ commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_ASYNC_EVENT_QUEUE);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, queue2Name);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER,
+ "com.qcdunit.QueueCommandsDUnitTestHelper");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(5, countLinesInString(stringResult, false));
+ assertTrue(stringContainsLine(stringResult, "Manager.*Success"));
+ assertTrue(stringContainsLine(stringResult, vm2Name + ".*Success"));
+ assertTrue(stringContainsLine(stringResult, vm1Name + ".*Success"));
+
+ // Verify that the queue was created on the correct members
+ cmdResult = executeCommand(CliStrings.LIST_ASYNC_EVENT_QUEUES);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(6, countLinesInString(stringResult, false));
+ assertTrue(stringContainsLine(stringResult,
+ "Manager .*" + queue2Name + " .*100 .*false .*null .*100 .*" + " .*com.qcdunit.QueueCommandsDUnitTestHelper"));
+ assertTrue(stringContainsLine(stringResult,
+ vm1Name + " .*" + queue1Name + " .*514 .*true .*" + diskStoreName + " .*213 .*" + " .*com.qcdunit.QueueCommandsDUnitTestHelper" + ".*"));
+ assertTrue(stringContainsLine(stringResult,
+ vm1Name + " .*" + queue2Name + " .*100 .*false .*null .*100 .*" + " .*com.qcdunit.QueueCommandsDUnitTestHelper"));
+ assertTrue(stringContainsLine(stringResult,
+ vm2Name + " .*" + queue2Name + " .*100 .*false .*null .*100 .*" + " .*com.qcdunit.QueueCommandsDUnitTestHelper"));
+ }
+
+ /**
+ * Asserts that creating async event queues correctly updates the shared configuration.
+ */
+ public void testCreateUpdatesSharedConfig() throws IOException {
+ disconnectAllFromDS();
+
+ final String queueName = "testAsyncEventQueueQueue";
+ final String groupName = "testAsyncEventQueueSharedConfigGroup";
+
+ // Start the Locator and wait for shared configuration to be available
+ final int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+ Host.getHost(0).getVM(3).invoke(new SerializableRunnable() {
+ @Override
+ public void run() {
+
+ final File locatorLogFile = new File("locator-" + locatorPort + ".log");
+ final Properties locatorProps = new Properties();
+ locatorProps.setProperty(DistributionConfig.NAME_NAME, "Locator");
+ locatorProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ locatorProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "fine");
+ locatorProps.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "true");
+ try {
+ final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort, locatorLogFile, null,
+ locatorProps);
+
+ DistributedTestCase.WaitCriterion wc = new DistributedTestCase.WaitCriterion() {
+ @Override
+ public boolean done() {
+ return locator.isSharedConfigurationRunning();
+ }
+
+ @Override
+ public String description() {
+ return "Waiting for shared configuration to be started";
+ }
+ };
+ DistributedTestCase.waitForCriterion(wc, 5000, 500, true);
+ } catch (IOException ioex) {
+ fail("Unable to create a locator with a shared configuration");
+ }
+ }
+ });
+
+ // Start the default manager
+ Properties managerProps = new Properties();
+ managerProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ managerProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locatorPort);
+ createDefaultSetup(managerProps);
+
+ // Create a cache in VM 1
+ VM vm = Host.getHost(0).getVM(1);
+ vm.invoke(new SerializableRunnable() {
+ @Override
+ public void run() {
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ localProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locatorPort);
+ localProps.setProperty(DistributionConfig.GROUPS_NAME, groupName);
+ getSystem(localProps);
+ assertNotNull(getCache());
+ }
+ });
+
+ // Deploy a JAR file with an AsyncEventListener that can be instantiated on each server
+ final File jarFile = new File(new File(".").getAbsolutePath(), "QueueCommandsDUnit.jar");
+ QueueCommandsDUnitTest.this.filesToBeDeleted.add(jarFile.getAbsolutePath());
+
+ ClassBuilder classBuilder = new ClassBuilder();
+ byte[] jarBytes = classBuilder.createJarFromClassContent("com/qcdunit/QueueCommandsDUnitTestListener",
+ "package com.qcdunit;" +
+ "import java.util.List; import java.util.Properties;" +
+ "import com.gemstone.gemfire.internal.cache.xmlcache.Declarable2; import com.gemstone.gemfire.cache.asyncqueue.AsyncEvent;" +
+ "import com.gemstone.gemfire.cache.asyncqueue.AsyncEventListener;" +
+ "public class QueueCommandsDUnitTestListener implements Declarable2, AsyncEventListener {" +
+ "Properties props;" +
+ "public boolean processEvents(List<AsyncEvent> events) { return true; }" +
+ "public void close() {}" +
+ "public void init(final Properties props) {this.props = props;}" +
+ "public Properties getConfig() {return this.props;}}");
+ writeJarBytesToFile(jarFile, jarBytes);
+
+ CommandResult cmdResult = executeCommand("deploy --jar=QueueCommandsDUnit.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ // Test creating the queue
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_ASYNC_EVENT_QUEUE);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, queueName);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP, groupName);
+ commandStringBuilder.addOption(CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER,
+ "com.qcdunit.QueueCommandsDUnitTestListener");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ // Make sure the queue exists in the shared config
+ Host.getHost(0).getVM(3).invoke(new SerializableRunnable() {
+ @Override
+ public void run() {
+ SharedConfiguration sharedConfig = ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
+ String xmlFromConfig;
+ try {
+ xmlFromConfig = sharedConfig.getConfiguration(groupName).getCacheXmlContent();
+ assertTrue(xmlFromConfig.contains(queueName));
+ } catch (Exception e) {
+ fail("Error occurred in cluster configuration service", e);
+ }
+ }
+ });
+
+ //Close cache in the vm1 and restart it to get the shared configuration
+ vm = Host.getHost(0).getVM(1);
+ vm.invoke(new SerializableRunnable() {
+ @Override
+ public void run() {
+ Cache cache = getCache();
+ assertNotNull(cache);
+ cache.close();
+
+ assertTrue(cache.isClosed());
+
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ localProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locatorPort);
+ localProps.setProperty(DistributionConfig.GROUPS_NAME, groupName);
+ localProps.setProperty(DistributionConfig.USE_CLUSTER_CONFIGURATION_NAME, "true");
+ getSystem(localProps);
+ cache = getCache();
+ assertNotNull(cache);
+ AsyncEventQueue aeq = cache.getAsyncEventQueue(queueName);
+
+ assertNotNull(aeq);
+ }
+ });
+ }
+
+ @Override
+ public void tearDown2() throws Exception {
+ for (String path : this.filesToBeDeleted) {
+ try {
+ final File fileToDelete = new File(path);
+ FileUtil.delete(fileToDelete);
+ if (path.endsWith(".jar")) {
+ executeCommand("undeploy --jar=" + fileToDelete.getName());
+ }
+ } catch (IOException e) {
+ getLogWriter().error("Unable to delete file", e);
+ }
+ }
+ this.filesToBeDeleted.clear();
+ super.tearDown2();
+ }
+
+ private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
+ final OutputStream outStream = new FileOutputStream(jarFile);
+ outStream.write(jarBytes);
+ outStream.close();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/eddef322/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/SharedConfigurationCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/SharedConfigurationCommandsDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/SharedConfigurationCommandsDUnitTest.java
new file mode 100644
index 0000000..adf5b5f
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/SharedConfigurationCommandsDUnitTest.java
@@ -0,0 +1,338 @@
+/*
+ * 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 com.gemstone.gemfire.management.internal.cli.commands;
+
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.CacheFactory;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.distributed.Locator;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.InternalLocator;
+import com.gemstone.gemfire.distributed.internal.SharedConfiguration;
+import com.gemstone.gemfire.internal.AvailablePortHelper;
+import com.gemstone.gemfire.internal.ClassBuilder;
+import com.gemstone.gemfire.management.cli.Result;
+import com.gemstone.gemfire.management.cli.Result.Status;
+import com.gemstone.gemfire.management.internal.cli.CliUtil;
+import com.gemstone.gemfire.management.internal.cli.HeadlessGfsh;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
+import com.gemstone.gemfire.management.internal.cli.result.CommandResult;
+import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import com.gemstone.gemfire.management.internal.configuration.SharedConfigurationDUnitTest;
+import com.gemstone.gemfire.management.internal.configuration.domain.Configuration;
+import dunit.DistributedTestCase;
+import dunit.Host;
+import dunit.SerializableCallable;
+import dunit.SerializableRunnable;
+import dunit.VM;
+import org.apache.commons.io.FileUtils;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Properties;
+import java.util.Set;
+
+/***
+ * DUnit test to test export and import of shared configuration.
+ *
+ * @author bansods
+ */
+public class SharedConfigurationCommandsDUnitTest extends CliCommandTestBase {
+
+ private static final long serialVersionUID = 1L;
+ private static final int TIMEOUT = 10000;
+ private static final int INTERVAL = 500;
+
+ public SharedConfigurationCommandsDUnitTest(String name) {
+ super(name);
+ }
+
+ File newDeployableJarFile = new File("DeployCommandsDUnit1.jar");
+ private transient ClassBuilder classBuilder = new ClassBuilder();
+
+ @SuppressWarnings("unchecked")
+ public void testExportImportSharedConfiguration() {
+ disconnectAllFromDS();
+
+ final String region1Name = "r1";
+ final String region2Name = "r2";
+ final String groupName = "testRegionSharedConfigGroup";
+ final String sharedConfigZipFileName = "sharedConfig.zip";
+ final String deployedJarName = "DeployCommandsDUnit1.jar";
+ final String logLevel = "info";
+ final String startArchiveFileName = "stats.gfs";
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(3);
+
+ // TODO Sourabh - the code below is similar to CliCommandTestBase.createDefaultSetup(..); we may want to consider
+ // refactoring this and combine the duplicate code blocks using either the Template Method and/or Strategy design
+ // patterns. We can talk about this.
+ // Start the Locator and wait for shared configuration to be available
+ final int locator1Port = ports[0];
+ final String locator1Name = "locator1-" + locator1Port;
+ VM locatorAndMgr = Host.getHost(0).getVM(3);
+ Object[] result = (Object[]) locatorAndMgr.invoke(new SerializableCallable() {
+ @Override
+ public Object call() {
+ int httpPort;
+ int jmxPort;
+ String jmxHost;
+
+ try {
+ jmxHost = InetAddress.getLocalHost().getHostName();
+ } catch (UnknownHostException ignore) {
+ jmxHost = "localhost";
+ }
+
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+
+ jmxPort = ports[0];
+ httpPort = ports[1];
+
+ final File locatorLogFile = new File("locator-" + locator1Port + ".log");
+
+ final Properties locatorProps = new Properties();
+ locatorProps.setProperty(DistributionConfig.NAME_NAME, locator1Name);
+ locatorProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ locatorProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "config");
+ locatorProps.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "true");
+ locatorProps.setProperty(DistributionConfig.JMX_MANAGER_NAME, "true");
+ locatorProps.setProperty(DistributionConfig.JMX_MANAGER_START_NAME, "true");
+ locatorProps.setProperty(DistributionConfig.JMX_MANAGER_BIND_ADDRESS_NAME, String.valueOf(jmxHost));
+ locatorProps.setProperty(DistributionConfig.JMX_MANAGER_PORT_NAME, String.valueOf(jmxPort));
+ locatorProps.setProperty(DistributionConfig.HTTP_SERVICE_PORT_NAME, String.valueOf(httpPort));
+
+ try {
+ final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locator1Port, locatorLogFile,
+ null, locatorProps);
+ DistributedTestCase.WaitCriterion wc = new DistributedTestCase.WaitCriterion() {
+ @Override
+ public boolean done() {
+ return locator.isSharedConfigurationRunning();
+ }
+
+ @Override
+ public String description() {
+ return "Waiting for shared configuration to be started";
+ }
+ };
+ DistributedTestCase.waitForCriterion(wc, TIMEOUT, INTERVAL, true);
+ } catch (IOException ioex) {
+ fail("Unable to create a locator with a shared configuration");
+ }
+
+ final Object[] result = new Object[4];
+ result[0] = jmxHost;
+ result[1] = jmxPort;
+ result[2] = httpPort;
+ result[3] = CliUtil.getAllNormalMembers(CacheFactory.getAnyInstance());
+
+ return result;
+ }
+ });
+
+ HeadlessGfsh gfsh = getDefaultShell();
+ String jmxHost = (String) result[0];
+ int jmxPort = (Integer) result[1];
+ int httpPort = (Integer) result[2];
+ Set<DistributedMember> normalMembers1 = (Set<DistributedMember>) result[3];
+
+ shellConnect(jmxHost, jmxPort, httpPort, gfsh);
+ // Create a cache in VM 1
+ VM dataMember = Host.getHost(0).getVM(1);
+ normalMembers1 = (Set<DistributedMember>) dataMember.invoke(new SerializableCallable() {
+ @Override
+ public Object call() {
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ localProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locator1Port);
+ localProps.setProperty(DistributionConfig.GROUPS_NAME, groupName);
+ localProps.setProperty(DistributionConfig.NAME_NAME, "DataMember");
+ getSystem(localProps);
+ Cache cache = getCache();
+ assertNotNull(cache);
+ return CliUtil.getAllNormalMembers(cache);
+ }
+ });
+ // Create a JAR file
+ try {
+ this.classBuilder.writeJarFromName("DeployCommandsDUnitA", this.newDeployableJarFile);
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ // Deploy the JAR
+ CommandResult cmdResult = executeCommand("deploy --jar=" + deployedJarName);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ //Create the region1 on the group
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, region1Name);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__GROUP, groupName);
+
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, region2Name);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ //Alter runtime configuration
+ commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_RUNTIME_CONFIG);
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL, logLevel);
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, "50");
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT, "32");
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT, "49");
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, "120");
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, startArchiveFileName);
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED, "true");
+ commandStringBuilder.addOption(CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, "10");
+ cmdResult = executeCommand(commandStringBuilder.getCommandString());
+ String resultString = commandResultToString(cmdResult);
+
+ getLogWriter().info("#SB Result\n");
+ getLogWriter().info(resultString);
+ assertEquals(true, cmdResult.getStatus().equals(Status.OK));
+
+ commandStringBuilder = new CommandStringBuilder(CliStrings.STATUS_SHARED_CONFIG);
+ cmdResult = executeCommand(commandStringBuilder.getCommandString());
+ resultString = commandResultToString(cmdResult);
+ getLogWriter().info("#SB Result\n");
+ getLogWriter().info(resultString);
+ assertEquals(Status.OK, cmdResult.getStatus());
+
+ commandStringBuilder = new CommandStringBuilder(CliStrings.EXPORT_SHARED_CONFIG);
+ commandStringBuilder.addOption(CliStrings.EXPORT_SHARED_CONFIG__FILE, sharedConfigZipFileName);
+ cmdResult = executeCommand(commandStringBuilder.getCommandString());
+ resultString = commandResultToString(cmdResult);
+ getLogWriter().info("#SB Result\n");
+ getLogWriter().info(resultString);
+ assertEquals(Status.OK, cmdResult.getStatus());
+
+ //Import into a running system should fail
+ commandStringBuilder = new CommandStringBuilder(CliStrings.IMPORT_SHARED_CONFIG);
+ commandStringBuilder.addOption(CliStrings.IMPORT_SHARED_CONFIG__ZIP, sharedConfigZipFileName);
+ cmdResult = executeCommand(commandStringBuilder.getCommandString());
+ assertEquals(Status.ERROR, cmdResult.getStatus());
+
+ //Stop the data members and remove the shared configuration in the locator.
+ dataMember.invoke(new SerializableCallable() {
+ @Override
+ public Object call() throws Exception {
+ Cache cache = getCache();
+ cache.close();
+ assertTrue(cache.isClosed());
+ disconnectFromDS();
+ return null;
+ }
+ });
+
+ //Clear shared configuration in this locator to test the import shared configuration
+ locatorAndMgr.invoke(new SerializableCallable() {
+ @Override
+ public Object call() throws Exception {
+ InternalLocator locator = InternalLocator.getLocator();
+ SharedConfiguration sc = locator.getSharedConfiguration();
+ assertNotNull(sc);
+ sc.clearSharedConfiguration();
+ return null;
+ }
+ });
+
+ //Now execute import shared configuration
+ //Now import the shared configuration and it should succeed.
+ commandStringBuilder = new CommandStringBuilder(CliStrings.IMPORT_SHARED_CONFIG);
+ commandStringBuilder.addOption(CliStrings.IMPORT_SHARED_CONFIG__ZIP, sharedConfigZipFileName);
+ cmdResult = executeCommand(commandStringBuilder.getCommandString());
+ assertEquals(Status.OK, cmdResult.getStatus());
+
+ //Start a new locator , test if it has all the imported shared configuration artifacts
+ VM newLocator = Host.getHost(0).getVM(2);
+ final int locator2Port = ports[1];
+ final String locator2Name = "Locator2-" + locator2Port;
+
+ newLocator.invoke(new SerializableRunnable() {
+ @Override
+ public void run() {
+ final File locatorLogFile = new File("locator-" + locator2Port + ".log");
+ final Properties locatorProps = new Properties();
+ locatorProps.setProperty(DistributionConfig.NAME_NAME, locator2Name);
+ locatorProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ locatorProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "fine");
+ locatorProps.setProperty(DistributionConfig.ENABLE_CLUSTER_CONFIGURATION_NAME, "true");
+ locatorProps.setProperty(DistributionConfig.LOCATORS_NAME, "localhost:" + locator1Port);
+
+ try {
+ final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locator2Port, locatorLogFile,
+ null, locatorProps);
+
+ DistributedTestCase.WaitCriterion wc = new DistributedTestCase.WaitCriterion() {
+ @Override
+ public boolean done() {
+ return locator.isSharedConfigurationRunning();
+ }
+
+ @Override
+ public String description() {
+ return "Waiting for shared configuration to be started";
+ }
+ };
+ DistributedTestCase.waitForCriterion(wc, 5000, 500, true);
+
+ SharedConfiguration sc = locator.getSharedConfiguration();
+ assertNotNull(sc);
+ Configuration groupConfig = sc.getConfiguration(groupName);
+ assertNotNull(groupConfig);
+ assertTrue(groupConfig.getCacheXmlContent().contains(region1Name));
+
+ Configuration clusterConfig = sc.getConfiguration(SharedConfiguration.CLUSTER_CONFIG);
+ assertNotNull(clusterConfig);
+ assertTrue(clusterConfig.getCacheXmlContent().contains(region2Name));
+ assertTrue(clusterConfig.getJarNames().contains(deployedJarName));
+ assertTrue(
+ clusterConfig.getGemfireProperties().getProperty(DistributionConfig.LOG_LEVEL_NAME).equals(logLevel));
+ assertTrue(
+ clusterConfig.getGemfireProperties().getProperty(DistributionConfig.STATISTIC_ARCHIVE_FILE_NAME).equals(
+ startArchiveFileName));
+ } catch (IOException ioex) {
+ fail("Unable to create a locator with a shared configuration");
+ } catch (Exception e) {
+ fail("Error occurred in cluster configuration service", e);
+ }
+ }
+ });
+
+ //Clean up
+ File sharedConfigZipFile = new File(sharedConfigZipFileName);
+ FileUtils.deleteQuietly(sharedConfigZipFile);
+ FileUtils.deleteQuietly(newDeployableJarFile);
+ }
+
+ @Override
+ public void tearDown2() throws Exception {
+ super.tearDown2();
+ for (int i = 0; i < 4; i++) {
+ Host.getHost(0).getVM(i).invoke(SharedConfigurationDUnitTest.locatorCleanup);
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/eddef322/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommandsDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommandsDUnitTest.java
new file mode 100644
index 0000000..0fc6be4
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShellCommandsDUnitTest.java
@@ -0,0 +1,365 @@
+/*
+ * 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 com.gemstone.gemfire.management.internal.cli.commands;
+
+import com.gemstone.gemfire.distributed.AbstractLauncher.Status;
+import com.gemstone.gemfire.distributed.LocatorLauncher;
+import com.gemstone.gemfire.distributed.LocatorLauncher.LocatorState;
+import com.gemstone.gemfire.internal.AvailablePortHelper;
+import com.gemstone.gemfire.internal.lang.StringUtils;
+import com.gemstone.gemfire.internal.util.IOUtils;
+import com.gemstone.gemfire.management.cli.Result;
+import com.gemstone.gemfire.management.internal.cli.domain.DataCommandRequest;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
+import com.gemstone.gemfire.management.internal.cli.result.CommandResult;
+import com.gemstone.gemfire.management.internal.cli.shell.Gfsh;
+import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import org.junit.Before;
+
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+public class ShellCommandsDUnitTest extends CliCommandTestBase {
+
+ private static final long serialVersionUID = 1L;
+
+ public ShellCommandsDUnitTest(String name) {
+ super(name);
+ }
+
+ @Before
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ getDefaultShell();
+ }
+
+ protected CommandResult connectToLocator(final int locatorPort) {
+ return executeCommand(new CommandStringBuilder(CliStrings.CONNECT).addOption(CliStrings.CONNECT__LOCATOR,
+ "localhost[" + locatorPort + "]").toString());
+ }
+
+ public void testConnectToLocatorBecomesManager() {
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+
+ final int jmxManagerPort = ports[0];
+ final int locatorPort = ports[1];
+
+ System.setProperty("gemfire.jmx-manager-port", String.valueOf(jmxManagerPort));
+ System.setProperty("gemfire.jmx-manager-http-port", "0");
+
+ assertEquals(String.valueOf(jmxManagerPort), System.getProperty("gemfire.jmx-manager-port"));
+ assertEquals("0", System.getProperty("gemfire.jmx-manager-http-port"));
+
+ final String pathname = (getClass().getSimpleName() + "_" + getTestName());
+ final File workingDirectory = new File(pathname);
+
+ workingDirectory.mkdir();
+
+ assertTrue(workingDirectory.isDirectory());
+
+ final LocatorLauncher locatorLauncher = new LocatorLauncher.Builder().setBindAddress(null).setForce(
+ true).setMemberName(pathname).setPort(locatorPort).setWorkingDirectory(
+ IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDirectory)).build();
+
+ assertNotNull(locatorLauncher);
+ assertEquals(locatorPort, locatorLauncher.getPort().intValue());
+
+ try {
+ // fix for bug 46729
+ locatorLauncher.start();
+
+ final LocatorState locatorState = locatorLauncher.waitOnStatusResponse(60, 10, TimeUnit.SECONDS);
+
+ assertNotNull(locatorState);
+ assertEquals(Status.ONLINE, locatorState.getStatus());
+
+ final Result result = connectToLocator(locatorPort);
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+ } finally {
+ assertEquals(Status.STOPPED, locatorLauncher.stop().getStatus());
+ assertEquals(Status.NOT_RESPONDING, locatorLauncher.status().getStatus());
+ }
+ }
+
+ public void testEchoWithVariableAtEnd() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+ getLogWriter().info("Gsh " + gfshInstance);
+
+ gfshInstance.setEnvProperty("TESTSYS", "SYS_VALUE");
+ printAllEnvs(gfshInstance);
+
+ String command = "echo --string=\"Hello World! This is ${TESTSYS}\"";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertEquals("Hello World! This is SYS_VALUE", StringUtils.trim(stringResult));
+ } else {
+ fail("testEchoWithVariableAtEnd failed");
+ }
+ }
+
+ public void testEchoWithNoVariable() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+
+ gfshInstance.setEnvProperty("TESTSYS", "SYS_VALUE");
+ printAllEnvs(gfshInstance);
+
+ String command = "echo --string=\"Hello World! This is Pivotal\"";
+
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertTrue(stringResult.contains("Hello World! This is Pivotal"));
+ } else {
+ fail("testEchoWithNoVariable failed");
+ }
+ }
+
+ public void testEchoWithVariableAtStart() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+
+ gfshInstance.setEnvProperty("TESTSYS", "SYS_VALUE");
+ printAllEnvs(gfshInstance);
+
+ String command = "echo --string=\"${TESTSYS} Hello World! This is Pivotal\"";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertTrue(stringResult.contains("SYS_VALUE Hello World! This is Pivotal"));
+ } else {
+ fail("testEchoWithVariableAtStart failed");
+ }
+ }
+
+ public void testEchoWithMultipleVariables() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+
+ gfshInstance.setEnvProperty("TESTSYS", "SYS_VALUE");
+ printAllEnvs(gfshInstance);
+
+ String command = "echo --string=\"${TESTSYS} Hello World! This is Pivotal ${TESTSYS}\"";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertTrue(stringResult.contains("SYS_VALUE Hello World! This is Pivotal SYS_VALUE"));
+ } else {
+ fail("testEchoWithMultipleVariables failed");
+ }
+ }
+
+ public void testEchoAllPropertyVariables() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+
+ String command = "echo --string=\"$*\"";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ } else {
+ fail("testEchoAllPropertyVariables failed");
+ }
+ }
+
+ public void testEchoForSingleVariable() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+
+ gfshInstance.setEnvProperty("TESTSYS", "SYS_VALUE");
+ printAllEnvs(gfshInstance);
+
+ String command = "echo --string=${TESTSYS}";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertTrue(stringResult.contains("SYS_VALUE"));
+ } else {
+ fail("testEchoForSingleVariable failed");
+ }
+ }
+
+ public void testEchoForSingleVariable2() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testEcho command gfshInstance is null");
+ }
+
+ gfshInstance.setEnvProperty("TESTSYS", "SYS_VALUE");
+ printAllEnvs(gfshInstance);
+
+ String command = "echo --string=\"${TESTSYS} ${TESTSYS}\"";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertTrue(stringResult.contains("SYS_VALUE"));
+ } else {
+ fail("testEchoForSingleVariable2 failed");
+ }
+ }
+
+ public void testDebug() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testDebug command gfshInstance is null");
+ }
+
+ gfshInstance.setDebug(false);
+ String command = "debug --state=ON";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ } else {
+ fail("testDebug failed");
+ }
+ assertEquals(gfshInstance.getDebug(), true);
+
+ }
+
+ public void testHistory() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testHistory command gfshInstance is null");
+ }
+
+ gfshInstance.setDebug(false);
+ String command = "history";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ } else {
+ fail("testHistory failed");
+ }
+ }
+
+ public void testHistoryWithFileName() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testHistory command gfshInstance is null");
+ }
+
+ String historyFileName = gfshInstance.getGfshConfig().getHistoryFileName();
+ File historyFile = new File(historyFileName);
+ String fileName = historyFile.getParent();
+ fileName = fileName + File.separator + getClass().getSimpleName() + "_" + getName() + "-exported.history";
+
+ String command = "history --file=" + fileName;
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ } else {
+ fail("testHistory failed");
+ }
+ }
+
+ public void testClearHistory() {
+ Gfsh gfshInstance = Gfsh.getCurrentInstance();
+
+ if (gfshInstance == null) {
+ fail("In testClearHistory command gfshInstance is null");
+ }
+
+ gfshInstance.setDebug(false);
+ String command = "history --clear";
+ CommandResult cmdResult = executeCommand(command);
+ printCommandOutput(cmdResult);
+
+ if (cmdResult != null) {
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ getLogWriter().info("testClearHistory cmdResult=" + commandResultToString(cmdResult));
+ String resultString = commandResultToString(cmdResult);
+ getLogWriter().info("testClearHistory resultString=" + resultString);
+ assertTrue(resultString.contains(CliStrings.HISTORY__MSG__CLEARED_HISTORY));
+ assertTrue(gfshInstance.getGfshHistory().getHistoryList().size() <= 1);
+ } else {
+ fail("testClearHistory failed");
+ }
+ }
+
+ private static void printCommandOutput(CommandResult cmdResult) {
+ assertNotNull(cmdResult);
+ getLogWriter().info("Command Output : ");
+ StringBuilder sb = new StringBuilder();
+ cmdResult.resetToFirstLine();
+ while (cmdResult.hasNextLine()) {
+ sb.append(cmdResult.nextLine()).append(DataCommandRequest.NEW_LINE);
+ }
+ getLogWriter().info(sb.toString());
+ getLogWriter().info("");
+ }
+
+ private void printAllEnvs(Gfsh gfsh) {
+ getLogWriter().info("printAllEnvs : " + StringUtils.objectToString(gfsh.getEnv(), false, 0));
+ /*
+ getLogWriter().info("Gfsh printAllEnvs : " + HydraUtil.ObjectToString(getDefaultShell().getEnv()));
+ getLogWriter().info("gfsh " + gfsh + " default shell " + getDefaultShell());*/
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/eddef322/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowDeadlockDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowDeadlockDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowDeadlockDUnitTest.java
new file mode 100644
index 0000000..2d67129
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowDeadlockDUnitTest.java
@@ -0,0 +1,271 @@
+/*
+ * 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 com.gemstone.gemfire.management.internal.cli.commands;
+
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.execute.Function;
+import com.gemstone.gemfire.cache.execute.FunctionContext;
+import com.gemstone.gemfire.cache.execute.FunctionService;
+import com.gemstone.gemfire.cache.execute.ResultCollector;
+import com.gemstone.gemfire.cache30.CacheTestCase;
+import com.gemstone.gemfire.distributed.DistributedLockService;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.distributed.internal.deadlock.GemFireDeadlockDetector;
+import com.gemstone.gemfire.distributed.internal.membership.InternalDistributedMember;
+import com.gemstone.gemfire.management.cli.Result;
+import com.gemstone.gemfire.management.cli.Result.Status;
+import com.gemstone.gemfire.management.internal.cli.CliUtil;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
+import com.gemstone.gemfire.management.internal.cli.remote.CommandProcessor;
+import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import dunit.Host;
+import dunit.SerializableCallable;
+import dunit.SerializableRunnable;
+import dunit.VM;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * This DUnit tests uses same code as GemFireDeadlockDetectorDUnitTest and uses the command processor for executing the
+ * "show deadlock" command
+ */
+public class ShowDeadlockDUnitTest extends CacheTestCase {
+
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+ private static final Set<Thread> stuckThreads = Collections.synchronizedSet(new HashSet<Thread>());
+ private static final Map<String, String> EMPTY_ENV = Collections.emptyMap();
+
+ @Override
+ public void setUp() throws Exception {
+ super.setUp();
+ // This test does not require an actual Gfsh connection to work, however when run as part of a suite, prior tests
+ // may mess up the environment causing this test to fail. Setting this prevents false failures.
+ CliUtil.isGfshVM = false;
+ }
+
+ @Override
+ public void tearDown2() throws Exception {
+ invokeInEveryVM(new SerializableRunnable() {
+ private static final long serialVersionUID = 1L;
+
+ public void run() {
+ for (Thread thread : stuckThreads) {
+ thread.interrupt();
+ }
+ }
+ });
+ CliUtil.isGfshVM = true;
+ }
+
+ public ShowDeadlockDUnitTest(String name) {
+ super(name);
+ }
+
+ public void testNoDeadlock() throws ClassNotFoundException, IOException {
+ Host host = Host.getHost(0);
+ VM vm0 = host.getVM(0);
+ VM vm1 = host.getVM(1);
+
+ //Make sure a deadlock from a previous test is cleared.
+ disconnectAllFromDS();
+
+ createCache(vm0);
+ createCache(vm1);
+ createCache(new Properties());
+
+ String fileName = "dependency.txt";
+ GemFireDeadlockDetector detect = new GemFireDeadlockDetector();
+ assertEquals(null, detect.find().findCycle());
+
+ CommandProcessor commandProcessor = new CommandProcessor();
+ CommandStringBuilder csb = new CommandStringBuilder(CliStrings.SHOW_DEADLOCK);
+ csb.addOption(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE, fileName);
+ Result result = commandProcessor.createCommandStatement(csb.toString(), EMPTY_ENV).process();
+
+ String deadLockOutputFromCommand = getResultAsString(result);
+
+ getLogWriter().info("output = " + deadLockOutputFromCommand);
+ assertEquals(true, result.hasIncomingFiles());
+ assertEquals(true, result.getStatus().equals(Status.OK));
+ assertEquals(true, deadLockOutputFromCommand.startsWith(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK));
+ result.saveIncomingFiles(null);
+ File file = new File(fileName);
+ assertTrue(file.exists());
+ file.delete();
+
+ disconnectAllFromDS();
+ }
+
+ private static final Lock lock = new ReentrantLock();
+
+
+ public void testDistributedDeadlockWithFunction() throws InterruptedException, ClassNotFoundException, IOException {
+ Host host = Host.getHost(0);
+ VM vm0 = host.getVM(0);
+ VM vm1 = host.getVM(1);
+ String filename = "gfeDependency.txt";
+ InternalDistributedMember member1 = createCache(vm0);
+ final InternalDistributedMember member2 = createCache(vm1);
+ createCache(new Properties());
+ //Have two threads lock locks on different members in different orders.
+ //This thread locks the lock member1 first, then member2.
+ lockTheLocks(vm0, member2);
+ //This thread locks the lock member2 first, then member1.
+ lockTheLocks(vm1, member1);
+
+ Thread.sleep(5000);
+ CommandProcessor commandProcessor = new CommandProcessor();
+ CommandStringBuilder csb = new CommandStringBuilder(CliStrings.SHOW_DEADLOCK);
+ csb.addOption(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE, filename);
+ Result result = commandProcessor.createCommandStatement(csb.toString(), EMPTY_ENV).process();
+
+ String deadLockOutputFromCommand = getResultAsString(result);
+ getLogWriter().info("Deadlock = " + deadLockOutputFromCommand);
+ result.saveIncomingFiles(null);
+ assertEquals(true, deadLockOutputFromCommand.startsWith(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED));
+ assertEquals(true, result.getStatus().equals(Status.OK));
+ File file = new File(filename);
+ assertTrue(file.exists());
+ file.delete();
+
+ }
+
+
+ private void createCache(Properties props) {
+ getSystem(props);
+ final Cache cache = getCache();
+ }
+
+ private Properties createProperties(Host host, int locatorPort) {
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+// props.setProperty(DistributionConfig.LOCATORS_NAME, getServerHostName(host) + "[" + locatorPort + "]");
+ props.setProperty(DistributionConfig.LOG_LEVEL_NAME, "info");
+ props.setProperty(DistributionConfig.STATISTIC_SAMPLING_ENABLED_NAME, "true");
+ props.setProperty(DistributionConfig.ENABLE_TIME_STATISTICS_NAME, "true");
+ props.put(DistributionConfig.ENABLE_NETWORK_PARTITION_DETECTION_NAME, "true");
+ return props;
+ }
+
+ private void lockTheLocks(VM vm0, final InternalDistributedMember member) {
+ vm0.invokeAsync(new SerializableRunnable() {
+
+ private static final long serialVersionUID = 1L;
+
+ public void run() {
+ lock.lock();
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ fail("interrupted", e);
+ }
+ ResultCollector collector = FunctionService.onMember(system, member).execute(new TestFunction());
+ //wait the function to lock the lock on member.
+ collector.getResult();
+ lock.unlock();
+ }
+ });
+ }
+
+ private void lockTheDLocks(VM vm, final String first, final String second) {
+ vm.invokeAsync(new SerializableRunnable() {
+
+ private static final long serialVersionUID = 1L;
+
+ public void run() {
+ getCache();
+ DistributedLockService dls = DistributedLockService.create("deadlock_test", getSystem());
+ dls.lock(first, 10 * 1000, -1);
+
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ dls.lock(second, 10 * 1000, -1);
+ }
+ });
+ }
+
+ private InternalDistributedMember createCache(VM vm) {
+ return (InternalDistributedMember) vm.invoke(new SerializableCallable() {
+ /**
+ *
+ */
+ private static final long serialVersionUID = 1L;
+
+ public Object call() {
+ getCache();
+ return getSystem().getDistributedMember();
+ }
+ });
+ }
+
+ private String getResultAsString(Result result) {
+ StringBuilder sb = new StringBuilder();
+ while (result.hasNextLine()) {
+ sb.append(result.nextLine());
+ }
+
+ return sb.toString();
+ }
+
+ private static class TestFunction implements Function {
+
+ private static final long serialVersionUID = 1L;
+ private static final int LOCK_WAIT_TIME = 1000;
+
+ public boolean hasResult() {
+ return true;
+ }
+
+ public void execute(FunctionContext context) {
+ try {
+ stuckThreads.add(Thread.currentThread());
+ lock.tryLock(LOCK_WAIT_TIME, TimeUnit.SECONDS);
+ } catch (InterruptedException e) {
+ //ingore
+ }
+ context.getResultSender().lastResult(null);
+ }
+
+ public String getId() {
+ return getClass().getCanonicalName();
+ }
+
+ public boolean optimizeForWrite() {
+ return false;
+ }
+
+ public boolean isHA() {
+ return false;
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/eddef322/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowMetricsDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowMetricsDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowMetricsDUnitTest.java
new file mode 100644
index 0000000..a69c35a
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowMetricsDUnitTest.java
@@ -0,0 +1,347 @@
+/*
+ * 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 com.gemstone.gemfire.management.internal.cli.commands;
+
+import com.gemstone.gemfire.cache.Cache;
+import com.gemstone.gemfire.cache.Region;
+import com.gemstone.gemfire.cache.RegionFactory;
+import com.gemstone.gemfire.cache.RegionShortcut;
+import com.gemstone.gemfire.cache.server.CacheServer;
+import com.gemstone.gemfire.distributed.DistributedMember;
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.internal.AvailablePortHelper;
+import com.gemstone.gemfire.management.CacheServerMXBean;
+import com.gemstone.gemfire.management.DistributedRegionMXBean;
+import com.gemstone.gemfire.management.DistributedSystemMXBean;
+import com.gemstone.gemfire.management.ManagementService;
+import com.gemstone.gemfire.management.MemberMXBean;
+import com.gemstone.gemfire.management.RegionMXBean;
+import com.gemstone.gemfire.management.cli.Result;
+import com.gemstone.gemfire.management.cli.Result.Status;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
+import com.gemstone.gemfire.management.internal.cli.remote.CommandProcessor;
+import com.gemstone.gemfire.management.internal.cli.result.CommandResult;
+import dunit.Host;
+import dunit.SerializableCallable;
+import dunit.SerializableRunnable;
+import dunit.VM;
+
+import javax.management.ObjectName;
+import java.io.File;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Properties;
+
+/****
+ * @author bansods
+ */
+public class ShowMetricsDUnitTest extends CliCommandTestBase {
+
+ private static final long serialVersionUID = 1L;
+
+ public ShowMetricsDUnitTest(String name) {
+ super(name);
+ // TODO Auto-generated constructor stub
+ }
+
+ private void createLocalSetUp() {
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.NAME_NAME, "Controller");
+ getSystem(localProps);
+ Cache cache = getCache();
+ RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ Region region1 = dataRegionFactory.create("REGION1");
+ Region region2 = dataRegionFactory.create("REGION2");
+ }
+
+ /*
+ * tests the default version of "show metrics"
+ */
+ public void testShowMetricsDefault() {
+ createDefaultSetup(null);
+ createLocalSetUp();
+ final VM vm1 = Host.getHost(0).getVM(1);
+ final String vm1Name = "VM" + vm1.getPid();
+
+ vm1.invoke(new SerializableRunnable() {
+ public void run() {
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.NAME_NAME, vm1Name);
+ getSystem(localProps);
+
+ Cache cache = getCache();
+ RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ Region region = dataRegionFactory.create("REGION1");
+ }
+ });
+
+ SerializableCallable showMetricCmd = new SerializableCallable() {
+
+ @Override
+ public Object call() throws Exception {
+ WaitCriterion wc = createMBeanWaitCriterion(1, "", null, 0);
+ waitForCriterion(wc, 5000, 500, true);
+ CommandProcessor commandProcessor = new CommandProcessor();
+ Result result = commandProcessor.createCommandStatement("show metrics", Collections.EMPTY_MAP).process();
+ String resultStr = commandResultToString((CommandResult) result);
+ getLogWriter().info(resultStr);
+ assertEquals(resultStr, true, result.getStatus().equals(Status.OK));
+ return resultStr;
+ }
+ };
+
+ //Invoke the command in the Manager VM
+ final VM managerVm = Host.getHost(0).getVM(0);
+ Object managerResultObj = managerVm.invoke(showMetricCmd);
+
+ String managerResult = (String) managerResultObj;
+
+ getLogWriter().info("#SB Manager");
+ getLogWriter().info(managerResult);
+ }
+
+ public void systemSetUp() {
+ createDefaultSetup(null);
+ createLocalSetUp();
+ final VM vm1 = Host.getHost(0).getVM(1);
+ final String vm1Name = "VM" + vm1.getPid();
+
+ vm1.invoke(new SerializableRunnable() {
+ public void run() {
+ Properties localProps = new Properties();
+ localProps.setProperty(DistributionConfig.NAME_NAME, vm1Name);
+ getSystem(localProps);
+
+ Cache cache = getCache();
+ RegionFactory<Integer, Integer> dataRegionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ Region region = dataRegionFactory.create("REGION1");
+ }
+ });
+ }
+
+ public void testShowMetricsRegion() throws InterruptedException {
+ systemSetUp();
+ final String regionName = "REGION1";
+ SerializableCallable showMetricCmd = new SerializableCallable() {
+
+ @Override
+ public Object call() throws Exception {
+ WaitCriterion wc = createMBeanWaitCriterion(2, regionName, null, 0);
+ waitForCriterion(wc, 5000, 500, true);
+ CommandProcessor commandProcessor = new CommandProcessor();
+ Result result = commandProcessor.createCommandStatement("show metrics --region=REGION1",
+ Collections.EMPTY_MAP).process();
+ String resultAsString = commandResultToString((CommandResult) result);
+ assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
+ return resultAsString;
+ }
+ };
+
+ //Invoke the command in the Manager VM
+ final VM managerVm = Host.getHost(0).getVM(0);
+ Object managerResultObj = managerVm.invoke(showMetricCmd);
+
+ String managerResult = (String) managerResultObj;
+
+ getLogWriter().info("#SB Manager");
+ getLogWriter().info(managerResult);
+ }
+
+ /***
+ * Creates WaitCriterion based on creation of different types of MBeans
+ *
+ * @param beanType
+ * @param regionName
+ * @param memberName
+ * @return
+ */
+ private WaitCriterion createMBeanWaitCriterion(final int beanType, final String regionName,
+ final DistributedMember distributedMember, final int cacheServerPort) {
+
+ WaitCriterion waitCriterion = new WaitCriterion() {
+
+ @Override
+ public boolean done() {
+ boolean done = false;
+ Cache cache = getCache();
+ ManagementService mgmtService = ManagementService.getManagementService(cache);
+ if (beanType == 1) {
+ DistributedSystemMXBean dsMxBean = mgmtService.getDistributedSystemMXBean();
+ if (dsMxBean != null) done = true;
+ } else if (beanType == 2) {
+ DistributedRegionMXBean dsRegionMxBean = mgmtService.getDistributedRegionMXBean("/" + regionName);
+ if (dsRegionMxBean != null) done = true;
+ } else if (beanType == 3) {
+ ObjectName memberMBeanName = mgmtService.getMemberMBeanName(distributedMember);
+ MemberMXBean memberMxBean = mgmtService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+
+ if (memberMxBean != null) done = true;
+ } else if (beanType == 4) {
+ ObjectName regionMBeanName = mgmtService.getRegionMBeanName(distributedMember, "/" + regionName);
+ RegionMXBean regionMxBean = mgmtService.getMBeanInstance(regionMBeanName, RegionMXBean.class);
+
+ if (regionMxBean != null) done = true;
+ } else if (beanType == 5) {
+ ObjectName csMxBeanName = mgmtService.getCacheServerMBeanName(cacheServerPort, distributedMember);
+ CacheServerMXBean csMxBean = mgmtService.getMBeanInstance(csMxBeanName, CacheServerMXBean.class);
+
+ if (csMxBean != null) {
+ done = true;
+ }
+ }
+
+ return done;
+ }
+
+ @Override
+ public String description() {
+ return "Waiting for the mbean to be created";
+ }
+ };
+
+ return waitCriterion;
+ }
+
+ public void testShowMetricsMember() throws ClassNotFoundException, IOException, InterruptedException {
+ systemSetUp();
+ Cache cache = getCache();
+ final DistributedMember distributedMember = cache.getDistributedSystem().getDistributedMember();
+ final String exportFileName = "memberMetricReport.csv";
+
+ int ports[] = AvailablePortHelper.getRandomAvailableTCPPorts(1);
+ CacheServer cs = getCache().addCacheServer();
+ cs.setPort(ports[0]);
+ cs.start();
+ final int cacheServerPort = cs.getPort();
+
+ SerializableCallable showMetricCmd = new SerializableCallable() {
+ @Override
+ public Object call() throws Exception {
+
+ WaitCriterion wc = createMBeanWaitCriterion(3, "", distributedMember, 0);
+ waitForCriterion(wc, 5000, 500, true);
+ wc = createMBeanWaitCriterion(5, "", distributedMember, cacheServerPort);
+ waitForCriterion(wc, 10000, 500, true);
+
+ final String command = CliStrings.SHOW_METRICS + " --" + CliStrings.SHOW_METRICS__MEMBER + "=" + distributedMember.getId() + " --" + CliStrings.SHOW_METRICS__CACHESERVER__PORT + "=" + cacheServerPort + " --" + CliStrings.SHOW_METRICS__FILE + "=" + exportFileName;
+
+ CommandProcessor commandProcessor = new CommandProcessor();
+ Result result = commandProcessor.createCommandStatement(command, Collections.EMPTY_MAP).process();
+ String resultAsString = commandResultToString((CommandResult) result);
+ assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
+ assertTrue(result.hasIncomingFiles());
+ result.saveIncomingFiles(null);
+ File file = new File(exportFileName);
+ file.deleteOnExit();
+ assertTrue(file.exists());
+ file.delete();
+ return resultAsString;
+
+ }
+ };
+
+ //Invoke the command in the Manager VM
+ final VM managerVm = Host.getHost(0).getVM(0);
+ Object managerResultObj = managerVm.invoke(showMetricCmd);
+
+ String managerResult = (String) managerResultObj;
+
+ getLogWriter().info("#SB Manager");
+ getLogWriter().info(managerResult);
+ cs.stop();
+ }
+
+ public void testShowMetricsRegionFromMember() throws ClassNotFoundException, IOException, InterruptedException {
+ systemSetUp();
+ Cache cache = getCache();
+ final DistributedMember distributedMember = cache.getDistributedSystem().getDistributedMember();
+ final String exportFileName = "regionOnAMemberReport.csv";
+ final String regionName = "REGION1";
+
+ SerializableCallable showMetricCmd = new SerializableCallable() {
+
+ @Override
+ public Object call() throws Exception {
+
+ WaitCriterion wc = createMBeanWaitCriterion(4, regionName, distributedMember, 0);
+ waitForCriterion(wc, 5000, 500, true);
+ CommandProcessor commandProcessor = new CommandProcessor();
+ Result result = commandProcessor.createCommandStatement(
+ "show metrics --region=" + regionName + " --member=" + distributedMember.getName() + " --file=" + exportFileName,
+ Collections.EMPTY_MAP).process();
+ String resultAsString = commandResultToString((CommandResult) result);
+ assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
+ assertTrue(result.hasIncomingFiles());
+ result.saveIncomingFiles(null);
+ File file = new File(exportFileName);
+ file.deleteOnExit();
+ assertTrue(file.exists());
+ file.delete();
+ return resultAsString;
+ }
+ };
+
+ //Invoke the command in the Manager VM
+ final VM managerVm = Host.getHost(0).getVM(0);
+ Object managerResultObj = managerVm.invoke(showMetricCmd);
+
+ String managerResult = (String) managerResultObj;
+
+ getLogWriter().info("#SB Manager");
+ getLogWriter().info(managerResult);
+ }
+
+ public void testShowMetricsRegionFromMemberWithCategories() throws ClassNotFoundException, IOException, InterruptedException {
+ systemSetUp();
+ Cache cache = getCache();
+ final DistributedMember distributedMember = cache.getDistributedSystem().getDistributedMember();
+ final String exportFileName = "regionOnAMemberReport.csv";
+ final String regionName = "REGION1";
+
+ SerializableCallable showMetricCmd = new SerializableCallable() {
+
+ @Override
+ public Object call() throws Exception {
+
+ WaitCriterion wc = createMBeanWaitCriterion(4, regionName, distributedMember, 0);
+ waitForCriterion(wc, 5000, 500, true);
+ CommandProcessor commandProcessor = new CommandProcessor();
+ Result result = commandProcessor.createCommandStatement(
+ "show metrics --region=" + regionName + " --member=" + distributedMember.getName() + " --file=" + exportFileName + " --categories=region,eviction",
+ Collections.EMPTY_MAP).process();
+ String resultAsString = commandResultToString((CommandResult) result);
+ assertEquals(resultAsString, true, result.getStatus().equals(Status.OK));
+ assertTrue(result.hasIncomingFiles());
+ result.saveIncomingFiles(null);
+ File file = new File(exportFileName);
+ file.deleteOnExit();
+ assertTrue(file.exists());
+ file.delete();
+ return resultAsString;
+ }
+ };
+
+ //Invoke the command in the Manager VM
+ final VM managerVm = Host.getHost(0).getVM(0);
+ Object managerResultObj = managerVm.invoke(showMetricCmd);
+
+ String managerResult = (String) managerResultObj;
+
+ getLogWriter().info("#SB Manager");
+ getLogWriter().info(managerResult);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-geode/blob/eddef322/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowStackTraceDUnitTest.java
----------------------------------------------------------------------
diff --git a/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowStackTraceDUnitTest.java b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowStackTraceDUnitTest.java
new file mode 100644
index 0000000..d1dc87f
--- /dev/null
+++ b/gemfire-core/src/test/java/com/gemstone/gemfire/management/internal/cli/commands/ShowStackTraceDUnitTest.java
@@ -0,0 +1,149 @@
+/*
+ * 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 com.gemstone.gemfire.management.internal.cli.commands;
+
+import com.gemstone.gemfire.distributed.internal.DistributionConfig;
+import com.gemstone.gemfire.management.cli.Result.Status;
+import com.gemstone.gemfire.management.internal.cli.i18n.CliStrings;
+import com.gemstone.gemfire.management.internal.cli.result.CommandResult;
+import com.gemstone.gemfire.management.internal.cli.util.CommandStringBuilder;
+import dunit.Host;
+import dunit.SerializableRunnable;
+import dunit.VM;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Properties;
+
+/***
+ * DUnit test for 'show stack-trace' command
+ *
+ * @author bansods
+ */
+public class ShowStackTraceDUnitTest extends CliCommandTestBase {
+
+ private static final long serialVersionUID = 1L;
+
+ public ShowStackTraceDUnitTest(String name) {
+ super(name);
+ }
+
+ private void createCache(Properties props) {
+ getSystem(props);
+ getCache();
+ }
+
+ private Properties createProperties(Host host, String name, String groups) {
+ Properties props = new Properties();
+ props.setProperty(DistributionConfig.MCAST_PORT_NAME, "0");
+ props.setProperty(DistributionConfig.LOG_LEVEL_NAME, "info");
+ props.setProperty(DistributionConfig.STATISTIC_SAMPLING_ENABLED_NAME, "true");
+ props.setProperty(DistributionConfig.ENABLE_TIME_STATISTICS_NAME, "true");
+ props.setProperty(DistributionConfig.NAME_NAME, name);
+ props.setProperty(DistributionConfig.GROUPS_NAME, groups);
+ return props;
+ }
+
+ /***
+ * Sets up a system of 3 peers
+ */
+ private void setupSystem() {
+ disconnectAllFromDS();
+ final Host host = Host.getHost(0);
+ final VM[] servers = {host.getVM(0), host.getVM(1)};
+
+ final Properties propsManager = createProperties(host, "Manager", "G1");
+ final Properties propsServer2 = createProperties(host, "Server", "G2");
+
+ createDefaultSetup(propsManager);
+
+ servers[1].invoke(new SerializableRunnable("Create cache for server1") {
+ public void run() {
+ createCache(propsServer2);
+ }
+ });
+ }
+
+ /***
+ * Tests the default behavior of the show stack-trace command
+ *
+ * @throws ClassNotFoundException
+ * @throws IOException
+ */
+ public void testExportStacktrace() throws ClassNotFoundException, IOException {
+ setupSystem();
+
+ File allStacktracesFile = new File("allStackTraces.txt");
+ allStacktracesFile.createNewFile();
+ allStacktracesFile.deleteOnExit();
+ CommandStringBuilder csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, allStacktracesFile.getCanonicalPath());
+ String commandString = csb.toString();
+ getLogWriter().info("CommandString : " + commandString);
+ CommandResult commandResult = executeCommand(commandString);
+ getLogWriter().info("Output : \n" + commandResultToString(commandResult));
+ assertTrue(commandResult.getStatus().equals(Status.OK));
+
+ File mgrStacktraceFile = new File("managerStacktrace.txt");
+ mgrStacktraceFile.createNewFile();
+ mgrStacktraceFile.deleteOnExit();
+ csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, mgrStacktraceFile.getCanonicalPath());
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, "Manager");
+ commandString = csb.toString();
+ getLogWriter().info("CommandString : " + commandString);
+ commandResult = executeCommand(commandString);
+ getLogWriter().info("Output : \n" + commandResultToString(commandResult));
+ assertTrue(commandResult.getStatus().equals(Status.OK));
+
+ File serverStacktraceFile = new File("serverStacktrace.txt");
+ serverStacktraceFile.createNewFile();
+ serverStacktraceFile.deleteOnExit();
+ csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, serverStacktraceFile.getCanonicalPath());
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, "Server");
+ commandString = csb.toString();
+ getLogWriter().info("CommandString : " + commandString);
+ commandResult = executeCommand(commandString);
+ getLogWriter().info("Output : \n" + commandResultToString(commandResult));
+ assertTrue(commandResult.getStatus().equals(Status.OK));
+
+ File groupStacktraceFile = new File("groupstacktrace.txt");
+ groupStacktraceFile.createNewFile();
+ groupStacktraceFile.deleteOnExit();
+ csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, groupStacktraceFile.getCanonicalPath());
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__GROUP, "G2");
+ commandString = csb.toString();
+ getLogWriter().info("CommandString : " + commandString);
+ commandResult = executeCommand(commandString);
+ getLogWriter().info("Output : \n" + commandResultToString(commandResult));
+ assertTrue(commandResult.getStatus().equals(Status.OK));
+
+ File wrongStackTraceFile = new File("wrongStackTrace.txt");
+ wrongStackTraceFile.createNewFile();
+ wrongStackTraceFile.deleteOnExit();
+ csb = new CommandStringBuilder(CliStrings.EXPORT_STACKTRACE);
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__FILE, wrongStackTraceFile.getCanonicalPath());
+ csb.addOption(CliStrings.EXPORT_STACKTRACE__MEMBER, "WrongMember");
+ commandString = csb.toString();
+ getLogWriter().info("CommandString : " + commandString);
+ commandResult = executeCommand(commandString);
+ getLogWriter().info("Output : \n" + commandResultToString(commandResult));
+ assertFalse(commandResult.getStatus().equals(Status.OK));
+ }
+}