You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by up...@apache.org on 2018/07/17 16:50:27 UTC
[geode] branch develop updated: GEODE-3530: refactor to not use
CliCommandTestBase (#2125)
This is an automated email from the ASF dual-hosted git repository.
upthewaterspout pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push:
new 72c2f3d GEODE-3530: refactor to not use CliCommandTestBase (#2125)
72c2f3d is described below
commit 72c2f3dabef457a5812d0faf14c4822018e5f7d2
Author: Helena Bales <hb...@pivotal.io>
AuthorDate: Tue Jul 17 09:50:20 2018 -0700
GEODE-3530: refactor to not use CliCommandTestBase (#2125)
Use the GfshCommandRule and ClusterStarterRule to replace the
CliCommandTestBase in order to make the test less flaky.
* extract rebalance tests to new class
* extract region membership from MBean tests
* extract tests for region membership from MBeans and Function context to
their own class and add more tests
* fix serialization filter and remove eviction rules
* finish extracting tests from GemFireDataCommandsDUnit
Co-authored-by: Finn Southerland <fs...@pivotal.io>
Co-authored-by: Helena A. Bales <hb...@pivotal.io>
---
.../geode/internal/lang/SystemPropertyHelper.java | 2 +
.../management/internal/cli/CliUtilDUnitTest.java | 48 +
.../CreateAlterDestroyRegionCommandsDUnitTest.java | 275 -----
.../cli/commands/GemfireDataCommandsDUnitTest.java | 1246 +++-----------------
.../cli/commands/QueryCommandDUnitTest.java | 319 +++++
.../cli/commands/RebalanceCommandDUnitTest.java | 349 ++++++
...ersistThroughClusterConfigurationDUnitTest.java | 171 +++
.../commands/RegionMembershipMBeanDUnitTest.java | 382 ++++++
.../commands/DurableClientCommandsDUnitTest.java | 388 ++----
.../cli/commands/CommandOverHttpDUnitTest.java | 10 +-
10 files changed, 1561 insertions(+), 1629 deletions(-)
diff --git a/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java b/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java
index 7f1848b..4b4685a 100644
--- a/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java
+++ b/geode-core/src/main/java/org/apache/geode/internal/lang/SystemPropertyHelper.java
@@ -69,6 +69,8 @@ public class SystemPropertyHelper {
public static final String PERSISTENT_VIEW_RETRY_TIMEOUT_SECONDS =
"PERSISTENT_VIEW_RETRY_TIMEOUT_SECONDS";
+ public static final String USE_HTTP_SYSTEM_PROPERTY = "useHTTP";
+
/**
* a comma separated string to list out the packages to scan. If not specified, the entire
* classpath is scanned.
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/CliUtilDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/CliUtilDUnitTest.java
index 70e7d6d..dbcc845 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/CliUtilDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/CliUtilDUnitTest.java
@@ -19,6 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.Arrays;
+import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;
@@ -178,6 +179,53 @@ public class CliUtilDUnitTest {
}
@Test
+ public void getRegionsAssociatedMembersInvalidRegion() {
+ locator.invoke(() -> {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Set<String> regions = new HashSet<String>();
+ regions.add("/asdfghjkl");
+
+ members = CliUtil.getQueryRegionsAssociatedMembers(regions, cache, true);
+ assertThat(members).isEmpty();
+
+ members = CliUtil.getQueryRegionsAssociatedMembers(regions, cache, false);
+ assertThat(members).isEmpty();
+ });
+ }
+
+ @Test
+ public void getRegionsAssociatedMembersInvalidRegions() {
+ locator.invoke(() -> {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Set<String> regions = new HashSet<String>();
+ regions.add("/asdfghjkl");
+ regions.add("/asdfghjklmn");
+
+ members = CliUtil.getQueryRegionsAssociatedMembers(regions, cache, true);
+ assertThat(members).isEmpty();
+
+ members = CliUtil.getQueryRegionsAssociatedMembers(regions, cache, false);
+ assertThat(members).isEmpty();
+ });
+ }
+
+ @Test
+ public void getRegionsAssociatedMembersInvalidAndValidRegions() {
+ locator.invoke(() -> {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Set<String> regions = new HashSet<String>();
+ regions.add("/asdfghjkl");
+ regions.add("/commonRegion");
+
+ members = CliUtil.getQueryRegionsAssociatedMembers(regions, cache, true);
+ assertThat(members).isEmpty();
+
+ members = CliUtil.getQueryRegionsAssociatedMembers(regions, cache, false);
+ assertThat(members).isEmpty();
+ });
+ }
+
+ @Test
public void getMemberByNameOrId() throws Exception {
locator.invoke(() -> {
DistributedMember member =
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
deleted file mode 100644
index d08d3c0..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * 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 org.apache.geode.management.internal.cli.commands;
-
-import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION;
-import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
-import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_BIND_ADDRESS;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.JMX_MANAGER_START;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
-import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.NAME;
-import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
-import static org.apache.geode.test.dunit.Assert.assertEquals;
-import static org.apache.geode.test.dunit.Assert.assertNotNull;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.Assert.fail;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.awaitility.Awaitility.waitAtMost;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.text.MessageFormat;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.Callable;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.commons.io.FileUtils;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.Region;
-import org.apache.geode.distributed.Locator;
-import org.apache.geode.distributed.internal.InternalConfigurationPersistenceService;
-import org.apache.geode.distributed.internal.InternalLocator;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.AvailablePortHelper;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.RegionsTest;
-
-@Category({DistributedTest.class, RegionsTest.class})
-@SuppressWarnings("serial")
-public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBase {
-
- private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<>();
-
- private void waitForRegionMBeanCreation(final String regionPath) {
- Host.getHost(0).getVM(0)
- .invoke(() -> waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath)));
- }
-
- private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath) {
- return () -> {
- try {
- MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
- String queryExp =
- MessageFormat.format(ManagementConstants.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
- ObjectName queryExpON = new ObjectName(queryExp);
- return mbeanServer.queryNames(null, queryExpON).size() == 1;
- } catch (MalformedObjectNameException mone) {
- getLogWriter().error(mone);
- fail(mone.getMessage());
- return false;
- }
- };
- }
-
- /**
- * Asserts that creating, altering and destroying regions correctly updates the shared
- * configuration.
- */
- @Test // FlakyTest: GEODE-2009
- public void testCreateAlterDestroyUpdatesSharedConfig() throws Exception {
- disconnectAllFromDS();
- final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
- jmxPort = ports[0];
- httpPort = ports[1];
- try {
- jmxHost = InetAddress.getLocalHost().getHostName();
- } catch (UnknownHostException ignore) {
- jmxHost = "localhost";
- }
-
- final String regionName = "testRegionSharedConfigRegion";
- final String regionPath = "/" + regionName;
- final String groupName = "testRegionSharedConfigGroup";
-
- // Start the Locator and wait for shared configuration to be available
- final int locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
-
- final Properties locatorProps = new Properties();
- locatorProps.setProperty(NAME, "Locator");
- locatorProps.setProperty(MCAST_PORT, "0");
- locatorProps.setProperty(LOG_LEVEL, "fine");
- locatorProps.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
- locatorProps.setProperty(JMX_MANAGER, "true");
- locatorProps.setProperty(JMX_MANAGER_START, "true");
- locatorProps.setProperty(JMX_MANAGER_BIND_ADDRESS, String.valueOf(jmxHost));
- locatorProps.setProperty(JMX_MANAGER_PORT, String.valueOf(jmxPort));
- locatorProps.setProperty(HTTP_SERVICE_PORT, String.valueOf(httpPort));
-
- Host.getHost(0).getVM(0).invoke(() -> {
- final File locatorLogFile = new File("locator-" + locatorPort + ".log");
- try {
- final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort,
- locatorLogFile, null, locatorProps);
-
- waitAtMost(5, TimeUnit.SECONDS).until(locator::isSharedConfigurationRunning);
-
- ManagementService managementService =
- ManagementService.getExistingManagementService(GemFireCacheImpl.getInstance());
- assertNotNull(managementService);
- assertTrue(managementService.isManager());
- assertTrue(checkIfCommandsAreLoadedOrNot());
-
- } catch (IOException ioex) {
- fail("Unable to create a locator with a shared configuration");
- }
- });
-
- connect(jmxHost, jmxPort, httpPort, getDefaultShell());
-
- // Create a cache in VM 1
- VM vm = Host.getHost(0).getVM(1);
- vm.invoke(() -> {
- Properties localProps = new Properties();
- localProps.setProperty(MCAST_PORT, "0");
- localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
- localProps.setProperty(GROUPS, groupName);
- getSystem(localProps);
- assertNotNull(getCache());
- });
-
- // Test creating the region
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, regionName);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__STATISTICSENABLED, "true");
- commandStringBuilder.addOption(CliStrings.GROUP, groupName);
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- // Make sure that the region has been registered with the Manager MXBean
- waitForRegionMBeanCreation(regionPath);
-
- // Make sure the region exists in the shared config
- Host.getHost(0).getVM(0).invoke(() -> {
- InternalConfigurationPersistenceService sharedConfig =
- ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService();
- try {
- assertTrue(
- sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
- } catch (Exception e) {
- fail("Error in cluster configuration service", e);
- }
- });
-
- // Restart the data vm to make sure the changes are in place
- vm = Host.getHost(0).getVM(1);
- vm.invoke(() -> {
- Cache cache = getCache();
- assertNotNull(cache);
- cache.close();
- assertTrue(cache.isClosed());
-
- Properties localProps = new Properties();
- localProps.setProperty(MCAST_PORT, "0");
- localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
- localProps.setProperty(GROUPS, groupName);
- localProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
- getSystem(localProps);
- cache = getCache();
- assertNotNull(cache);
- Region region = cache.getRegion(regionName);
- assertNotNull(region);
- });
-
-
- // Test altering the region
- commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, regionName);
- commandStringBuilder.addOption(CliStrings.GROUP, groupName);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, "45635");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, "DESTROY");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- // Make sure the region was altered in the shared config
- Host.getHost(0).getVM(0).invoke(() -> {
- InternalConfigurationPersistenceService sharedConfig =
- ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService();
- try {
- assertTrue(sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains("45635"));
- } catch (Exception e) {
- fail("Error in cluster configuration service");
- }
- });
-
- // Restart the data vm to make sure the changes are in place
- vm = Host.getHost(0).getVM(1);
- vm.invoke(new SerializableCallable() {
- @Override
- public Object call() {
- Cache cache = getCache();
- assertNotNull(cache);
- cache.close();
- assertTrue(cache.isClosed());
-
- Properties localProps = new Properties();
- localProps.setProperty(MCAST_PORT, "0");
- localProps.setProperty(LOCATORS, "localhost[" + locatorPort + "]");
- localProps.setProperty(GROUPS, groupName);
- localProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
- getSystem(localProps);
- cache = getCache();
- assertNotNull(cache);
- Region region = cache.getRegion(regionName);
- assertNotNull(region);
-
- return null;
- }
- });
- }
-
- @Override
- protected final void preTearDownCliCommandTestBase() throws Exception {
- for (String path : this.filesToBeDeleted) {
- try {
- final File fileToDelete = new File(path);
- FileUtils.forceDelete(fileToDelete);
- if (path.endsWith(".jar")) {
- executeCommand("undeploy --jar=" + fileToDelete.getName());
- }
- } catch (IOException e) {
- getLogWriter().error("Unable to delete file", e);
- }
- }
- this.filesToBeDeleted.clear();
- }
-}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
index b27bfc3..2071758 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GemfireDataCommandsDUnitTest.java
@@ -15,55 +15,33 @@
package org.apache.geode.management.internal.cli.commands;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.distributed.ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER;
import static org.apache.geode.test.dunit.Assert.assertEquals;
import static org.apache.geode.test.dunit.Assert.assertNotNull;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
import static org.apache.geode.test.dunit.Assert.fail;
-import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
import static org.assertj.core.api.Java6Assertions.assertThat;
import java.io.Serializable;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
import java.util.Properties;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicInteger;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.EntryEvent;
import org.apache.geode.cache.PartitionAttributes;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.query.QueryInvalidException;
-import org.apache.geode.cache.query.data.Portfolio;
-import org.apache.geode.cache.query.internal.CompiledValue;
-import org.apache.geode.cache.query.internal.QCompiler;
-import org.apache.geode.cache.util.CacheListenerAdapter;
import org.apache.geode.distributed.ConfigurationProperties;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.management.DistributedRegionMXBean;
import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.ManagerMXBean;
-import org.apache.geode.management.MemberMXBean;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.HeadlessGfsh;
-import org.apache.geode.management.internal.cli.domain.DataCommandRequest;
import org.apache.geode.management.internal.cli.domain.DataCommandResult;
import org.apache.geode.management.internal.cli.dto.Value1;
import org.apache.geode.management.internal.cli.dto.Value2;
@@ -71,25 +49,20 @@ import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.management.internal.cli.result.ResultData;
import org.apache.geode.management.internal.cli.result.model.DataResultModel;
import org.apache.geode.management.internal.cli.result.model.ResultModel;
-import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.IgnoredException;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
-import org.apache.geode.test.dunit.VM;
-import org.apache.geode.test.dunit.WaitCriterion;
+import org.apache.geode.test.dunit.SerializableRunnableIF;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
/**
- * Dunit class for testing gemfire data commands : get, put, remove, select, rebalance
+ * Dunit class for testing gemfire data commands : get, put, remove
*/
-@Category({DistributedTest.class, FlakyTest.class}) // See GEODE-3530 description
+@Category({DistributedTest.class})
@SuppressWarnings("serial")
-public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
+public class GemfireDataCommandsDUnitTest {
+
- private static final String REGION_NAME = "FunctionCommandsReplicatedRegion";
- private static final String REBALANCE_REGION_NAME = "GemfireDataCommandsDUnitTestRegion";
- private static final String REBALANCE_REGION2_NAME = "GemfireDataCommandsDUnitTestRegion2";
private static final String DATA_REGION_NAME = "GemfireDataCommandsTestRegion";
private static final String DATA_REGION_NAME_VM1 = "GemfireDataCommandsTestRegion_Vm1";
private static final String DATA_REGION_NAME_VM2 = "GemfireDataCommandsTestRegion_Vm2";
@@ -107,492 +80,114 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
"/GemfireDataCommandsTestParRegion_Vm2";
private static final String DATA_REGION_NAME_CHILD_1 = "ChildRegionRegion1";
- private static final String DATA_REGION_NAME_CHILD_1_PATH =
- "/GemfireDataCommandsTestRegion/ChildRegionRegion1";
private static final String DATA_REGION_NAME_CHILD_1_2 = "ChildRegionRegion12";
- private static final String DATA_REGION_NAME_CHILD_1_2_PATH =
- "/GemfireDataCommandsTestRegion/ChildRegionRegion1/ChildRegionRegion12";
+ private static final String SERIALIZATION_FILTER =
+ "org.apache.geode.management.internal.cli.**";
- private static final String keyTemplate = "('id':'?','name':'name?')";
- private static final String valueTemplate =
- "('stateName':'State?','population':?1,'capitalCity':'capital?','areaInSqKm':?2)";
- private static final String carTemplate =
- "\"('attributes':?map,'make':'?make','model':'?model','colors':?list,'attributeSet':?set)\"";
- static final int COUNT = 5;
+ @Rule
+ public GfshCommandRule gfsh = new GfshCommandRule();
- public String getMemberId() {
- InternalCache cache = getCache();
- return cache.getDistributedSystem().getDistributedMember().getId();
- }
+ @Rule
+ public ClusterStartupRule cluster = new ClusterStartupRule();
- @Override
- public Properties getDistributedSystemProperties() {
- Properties properties = super.getDistributedSystemProperties();
- properties.put(ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER,
- "org.apache.geode.management.internal.cli.dto.**");
- return properties;
- }
+ private MemberVM locator, server1, server2;
- void setupForGetPutRemoveLocateEntry(String testName) {
- final VM vm1 = Host.getHost(0).getVM(1);
- final VM vm2 = Host.getHost(0).getVM(2);
- Properties props = getDistributedSystemProperties();
- props.setProperty(NAME, testName + "Manager");
- HeadlessGfsh gfsh = setUpJmxManagerOnVm0ThenConnect(props);
- assertNotNull(gfsh);
- assertEquals(true, gfsh.isConnectedAndReady());
-
- vm1.invoke(new SerializableRunnable() {
- public void run() {
- InternalCache cache = getCache();
- RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
- Region dataRegion = regionFactory.create(DATA_REGION_NAME);
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- dataRegion =
- dataRegion.createSubregion(DATA_REGION_NAME_CHILD_1, dataRegion.getAttributes());
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- dataRegion =
- dataRegion.createSubregion(DATA_REGION_NAME_CHILD_1_2, dataRegion.getAttributes());
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- dataRegion = regionFactory.create(DATA_REGION_NAME_VM1);
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- PartitionAttributes partitionAttrs =
- new PartitionAttributesFactory().setRedundantCopies(2).create();
- RegionFactory<Object, Object> partitionRegionFactory =
- cache.createRegionFactory(RegionShortcut.PARTITION);
- partitionRegionFactory.setPartitionAttributes(partitionAttrs);
- Region dataParRegion = partitionRegionFactory.create(DATA_PAR_REGION_NAME);
- assertNotNull(dataParRegion);
- getLogWriter().info("Created Region " + dataParRegion);
- dataParRegion = partitionRegionFactory.create(DATA_PAR_REGION_NAME_VM1);
- assertNotNull(dataParRegion);
- getLogWriter().info("Created Region " + dataParRegion);
-
- }
- });
+ public void before() throws Exception {
+ locator = cluster.startLocatorVM(0, locatorProperties());
+ server1 = cluster.startServerVM(1, locator.getPort());
+ server2 = cluster.startServerVM(2, locator.getPort());
- vm2.invoke(new SerializableRunnable() {
- public void run() {
- InternalCache cache = getCache();
- RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
- Region dataRegion = regionFactory.create(DATA_REGION_NAME);
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- dataRegion =
- dataRegion.createSubregion(DATA_REGION_NAME_CHILD_1, dataRegion.getAttributes());
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- dataRegion =
- dataRegion.createSubregion(DATA_REGION_NAME_CHILD_1_2, dataRegion.getAttributes());
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
- dataRegion = regionFactory.create(DATA_REGION_NAME_VM2);
- assertNotNull(dataRegion);
- getLogWriter().info("Created Region " + dataRegion);
-
-
- PartitionAttributes partitionAttrs =
- new PartitionAttributesFactory().setRedundantCopies(2).create();
- RegionFactory<Object, Object> partitionRegionFactory =
- cache.createRegionFactory(RegionShortcut.PARTITION);
- partitionRegionFactory.setPartitionAttributes(partitionAttrs);
- Region dataParRegion = partitionRegionFactory.create(DATA_PAR_REGION_NAME);
- assertNotNull(dataParRegion);
- getLogWriter().info("Created Region " + dataParRegion);
- dataParRegion = partitionRegionFactory.create(DATA_PAR_REGION_NAME_VM2);
- assertNotNull(dataParRegion);
- getLogWriter().info("Created Region " + dataParRegion);
+ gfsh.connectAndVerify(locator);
+ }
- }
- });
+ private static void setupRegions(String regionName, String parRegionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ RegionFactory regionFactory =
+ cache.createRegionFactory(RegionShortcut.REPLICATE);
- final String vm1MemberId = vm1.invoke(() -> getMemberId());
- final String vm2MemberId = vm2.invoke(() -> getMemberId());
- getLogWriter().info("Vm1 ID : " + vm1MemberId);
- getLogWriter().info("Vm2 ID : " + vm2MemberId);
-
- final VM manager = Host.getHost(0).getVM(0);
-
- SerializableRunnable checkRegionMBeans = new SerializableRunnable() {
- @Override
- public void run() {
- InternalCache cache = getCache();
- final ManagementService service = ManagementService.getManagementService(cache);
-
- final WaitCriterion waitForMaangerMBean = new WaitCriterion() {
- @Override
- public boolean done() {
- ManagerMXBean bean1 = service.getManagerMXBean();
- DistributedRegionMXBean bean2 =
- service.getDistributedRegionMXBean(DATA_REGION_NAME_PATH);
- if (bean1 == null) {
- getLogWriter().info("Still probing for ManagerMBean");
- return false;
- } else {
- getLogWriter().info("Still probing for DistributedRegionMXBean=" + bean2);
- return (bean2 != null);
- }
- }
-
- @Override
- public String description() {
- return "Probing for ManagerMBean";
- }
- };
-
- waitForCriterion(waitForMaangerMBean, 30000, 2000, true);
-
- assertNotNull(service.getMemberMXBean());
- assertNotNull(service.getManagerMXBean());
- DistributedRegionMXBean bean = service.getDistributedRegionMXBean(DATA_REGION_NAME_PATH);
- assertNotNull(bean);
+ Region dataRegion = regionFactory.create(DATA_REGION_NAME);
+ assertNotNull(dataRegion);
- WaitCriterion waitForRegionMBeans = new WaitCriterion() {
- @Override
- public boolean done() {
-
- DistributedRegionMXBean beans[] = new DistributedRegionMXBean[6];
- beans[0] = service.getDistributedRegionMXBean(DATA_REGION_NAME_PATH);
- beans[1] = service.getDistributedRegionMXBean(DATA_REGION_NAME_VM1_PATH);
- beans[2] = service.getDistributedRegionMXBean(DATA_REGION_NAME_VM2_PATH);
- beans[3] = service.getDistributedRegionMXBean(DATA_PAR_REGION_NAME_PATH);
- beans[4] = service.getDistributedRegionMXBean(DATA_PAR_REGION_NAME_VM1_PATH);
- beans[5] = service.getDistributedRegionMXBean(DATA_PAR_REGION_NAME_VM2_PATH);
- // SubRegion Bug : Proxy creation has some issues.
- // beans[6] = service.getDistributedRegionMXBean(DATA_REGION_NAME_CHILD_1_PATH);
- // beans[7] = service.getDistributedRegionMXBean(DATA_REGION_NAME_CHILD_1_2_PATH);
- boolean flag = true;
- for (DistributedRegionMXBean b : beans) {
- if (b == null) {
- flag = false;
- break;
- }
- }
-
- if (!flag) {
- getLogWriter().info("Still probing for regionMbeans " + DATA_REGION_NAME_PATH + "="
- + beans[0] + " " + DATA_REGION_NAME_VM1_PATH + "=" + beans[1] + " "
- + DATA_REGION_NAME_VM2_PATH + "=" + beans[2] + " " + DATA_PAR_REGION_NAME_PATH
- + "=" + beans[3] + " " + DATA_PAR_REGION_NAME_VM1_PATH + "=" + beans[4] + " "
- + DATA_PAR_REGION_NAME_VM2_PATH + "=" + beans[5] + " "
- // + DATA_REGION_NAME_CHILD_1_PATH
- // +"="+ beans[6] + " " + DATA_REGION_NAME_CHILD_1_2_PATH
- // +"=" + beans[7]
- );
- return false;
- } else {
- getLogWriter().info("Probing complete for regionMbeans " + DATA_REGION_NAME_PATH + "="
- + beans[0] + " " + DATA_REGION_NAME_VM1_PATH + "=" + beans[1] + " "
- + DATA_REGION_NAME_VM2_PATH + "=" + beans[2] + " " + DATA_PAR_REGION_NAME_PATH
- + "=" + beans[3] + " " + DATA_PAR_REGION_NAME_VM1_PATH + "=" + beans[4] + " "
- + DATA_PAR_REGION_NAME_VM2_PATH + "=" + beans[5] + " "
- // + DATA_REGION_NAME_CHILD_1_PATH
- // +"="+ beans[6] + " " + DATA_REGION_NAME_CHILD_1_2_PATH
- // +"=" + beans[7]
- );
- // Fails here Rishi Need Fix here
- // if(bean1.getMemberCount()==2 && bean1.getMemberCount()==1 &&
- // bean1.getMemberCount()==1)
- return true;
- // else{
- // getLogWriter().info("Still probing for regionMbeans for aggregation bean1=" +
- // bean1.getMemberCount() + " bean2="+ bean2.getMemberCount() + " bean3" +
- // bean3.getMemberCount());
- // return false;
- // }
- }
- }
-
- @Override
- public String description() {
- return "Probing for regionMbeans";
- }
- };
-
- waitForCriterion(waitForRegionMBeans, 30000, 2000, true);
-
- String regions[] = {DATA_REGION_NAME_PATH, DATA_REGION_NAME_VM1_PATH,
- DATA_REGION_NAME_VM2_PATH, DATA_PAR_REGION_NAME_PATH, DATA_PAR_REGION_NAME_VM1_PATH,
- DATA_PAR_REGION_NAME_VM2_PATH, /*
- * DATA_REGION_NAME_CHILD_1_PATH,
- * DATA_REGION_NAME_CHILD_1_2_PATH
- */};
-
- for (String region : regions) {
- bean = service.getDistributedRegionMXBean(region);
- assertNotNull(bean);
- String[] membersName = bean.getMembers();
- getLogWriter().info("Members Array for region " + region + " : "
- + StringUtils.objectToString(membersName, true, 10));
- if (bean.getMemberCount() < 1)
- fail("Even after waiting mbean reports number of member hosting region "
- + DATA_REGION_NAME_VM1_PATH + " is less than one");
- // assertIndexDetailsEquals(1, membersName.length); //exists in one members vm1
- }
- }
- };
- manager.invoke(checkRegionMBeans);
- }
+ dataRegion =
+ dataRegion.createSubregion(DATA_REGION_NAME_CHILD_1, dataRegion.getAttributes());
+ assertNotNull(dataRegion);
- void setupForSelect() {
- setupForGetPutRemoveLocateEntry("setupForSelect");
- final VM vm1 = Host.getHost(0).getVM(1);
- final VM vm2 = Host.getHost(0).getVM(2);
-
- // To avoid pagination issues and Gfsh waiting for user input
- executeCommand("set variable --name=APP_FETCH_SIZE --value=" + COUNT);
-
- vm1.invoke(new SerializableRunnable() {
- public void run() {
- Cache cache = CacheFactory.getAnyInstance();
- String regions[] = {DATA_PAR_REGION_NAME_PATH, DATA_PAR_REGION_NAME_VM1_PATH,
- DATA_REGION_NAME_CHILD_1_PATH, DATA_REGION_NAME_CHILD_1_2_PATH};
- for (String r : regions) {
- Region dataRegion = cache.getRegion(r);
- for (int j = 0; j < 10; j++) {
- dataRegion.put(new Integer(j), new Portfolio(j));
- }
- }
- Region dataRegion = cache.getRegion(DATA_REGION_NAME_PATH);
- for (int j = 0; j < 10; j++) {
- dataRegion.put(new Integer(j), new Value1(j));
- }
+ dataRegion =
+ dataRegion.createSubregion(DATA_REGION_NAME_CHILD_1_2, dataRegion.getAttributes());
+ assertNotNull(dataRegion);
- dataRegion = cache.getRegion(DATA_REGION_NAME_VM1_PATH);
- for (int j = 0; j < 10; j++) {
- dataRegion.put(new Integer(j), new Value1WithValue2(j));
- }
- }
- });
+ dataRegion = regionFactory.create(regionName);
+ assertNotNull(dataRegion);
- vm2.invoke(new SerializableRunnable() {
- public void run() {
- Cache cache = CacheFactory.getAnyInstance();
- String regions[] = {DATA_REGION_NAME_VM2_PATH, DATA_PAR_REGION_NAME_VM2_PATH};
- for (String r : regions) {
- Region dataRegion = cache.getRegion(r);
- for (int j = 0; j < 10; j++) {
- dataRegion.put(new Integer(j), new Portfolio(j));
- }
- }
- }
- });
+ PartitionAttributes partitionAttrs =
+ new PartitionAttributesFactory().setRedundantCopies(2).create();
+ RegionFactory<Object, Object> partitionRegionFactory =
+ cache.createRegionFactory(RegionShortcut.PARTITION);
+ partitionRegionFactory.setPartitionAttributes(partitionAttrs);
+ Region dataParRegion = partitionRegionFactory.create(DATA_PAR_REGION_NAME);
+ assertNotNull(dataParRegion);
+ dataParRegion = partitionRegionFactory.create(parRegionName);
+ assertNotNull(dataParRegion);
}
- private void doQueryRegionsAssociatedMembers(String queryTemplate, int expectedMembers,
- boolean returnAll, String... regions) {
- InternalCache cache = getCache();
- String query = queryTemplate;
- int i = 1;
- for (String r : regions) {
- query = query.replace("?" + i, r);
- i++;
- }
- getLogWriter().info("Checking members for query : " + query);
- QCompiler compiler = new QCompiler();
- Set<String> regionsInQuery = null;
- try {
- CompiledValue compiledQuery = compiler.compileQuery(query);
- Set regionSet = new HashSet();
- compiledQuery.getRegionsInQuery(regionSet, null);// GFSH ENV VARIBLES
- regionsInQuery = Collections.unmodifiableSet(regionSet);
- getLogWriter().info("Region in query : " + regionsInQuery);
- if (regionsInQuery.size() > 0) {
- Set<DistributedMember> members =
- CliUtil.getQueryRegionsAssociatedMembers(regionsInQuery, cache, returnAll);
- getLogWriter().info("Members for Region in query : " + members);
- if (expectedMembers != -1) {
- assertNotNull(members);
- assertEquals(expectedMembers, members.size());
- } else
- assertEquals(0, members.size());
- } else {
- assertEquals(-1, expectedMembers);// Regions do not exist at all
- }
- } catch (QueryInvalidException qe) {
- fail("Invalid Query", qe);
- }
- }
- public void doTestGetRegionAssociatedMembersForSelect() {
- final VM manager = Host.getHost(0).getVM(0);
- final String queryTemplate1 = "select * from ?1, ?2 ";
- // final String queryTemplate2 = "select * from ?1, ?2, ?3";
- manager.invoke(new SerializableRunnable() {
- @Override
- public void run() {
- doQueryRegionsAssociatedMembers(queryTemplate1, 0, true, DATA_REGION_NAME_VM1_PATH,
- DATA_REGION_NAME_VM2_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 2, true, DATA_REGION_NAME_PATH,
- DATA_REGION_NAME_CHILD_1_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 1, false, DATA_REGION_NAME_PATH,
- DATA_REGION_NAME_CHILD_1_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 1, true, DATA_REGION_NAME_VM1_PATH,
- DATA_REGION_NAME_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 1, false, DATA_REGION_NAME_VM1_PATH,
- DATA_REGION_NAME_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 1, true, DATA_REGION_NAME_VM2_PATH,
- DATA_REGION_NAME_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 1, false, DATA_REGION_NAME_VM2_PATH,
- DATA_REGION_NAME_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 0, true, DATA_PAR_REGION_NAME_VM2_PATH,
- DATA_PAR_REGION_NAME_VM1_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, 0, false, DATA_PAR_REGION_NAME_VM2_PATH,
- DATA_PAR_REGION_NAME_VM1_PATH);
- doQueryRegionsAssociatedMembers(queryTemplate1, -1, true, DATA_PAR_REGION_NAME_VM2_PATH,
- "/jfgkdfjgkd"); // one wrong region
- doQueryRegionsAssociatedMembers(queryTemplate1, -1, false, DATA_PAR_REGION_NAME_VM2_PATH,
- "/jfgkdfjgkd"); // one wrong region
- doQueryRegionsAssociatedMembers(queryTemplate1, -1, true, "/dhgfdhgf", "/dhgddhd"); // both
- // regions
- // wrong
- doQueryRegionsAssociatedMembers(queryTemplate1, -1, false, "/dhgfdhgf", "/dhgddhd"); // both
- // regions
- // wrong
- }
- });
- }
+ void setupForGetPutRemoveLocateEntry(String testName) throws Exception {
+ Properties props = locatorProperties();
+ props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER);
+ props.setProperty(NAME, testName + "Manager");
- public void doTestSelectProjection() {
- Random random = new Random(System.nanoTime());
- int randomInteger = random.nextInt(COUNT);
- String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from "
- + DATA_PAR_REGION_NAME_PATH + " where ID <= " + randomInteger + "\" --interactive=false";
- CommandResult cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- validateSelectResult(cmdResult, true, (randomInteger + 1),
- new String[] {"ID", "status", "createTime", "pk", "floatMinValue"});
- }
+ Properties serverProps = new Properties();
+ serverProps.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER);
+ locator = cluster.startLocatorVM(0, props);
+ server1 = cluster.startServerVM(1, serverProps, locator.getPort());
+ server2 = cluster.startServerVM(2, serverProps, locator.getPort());
- public void doTestSelectProjectionProcessCommand() {
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(new SerializableRunnable() {
- @Override
- public void run() {
- Random random = new Random(System.nanoTime());
- int randomInteger = random.nextInt(COUNT);
- String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from "
- + DATA_PAR_REGION_NAME_PATH + " where ID <= " + randomInteger
- + "\" --interactive=false";
- ManagementService service = ManagementService.getExistingManagementService(getCache());
- MemberMXBean member = service.getMemberMXBean();
- String cmdResult = member.processCommand(query);
- assertNotNull(cmdResult);
- getLogWriter().info("Text Command Output : " + cmdResult);
- }
- });
- }
+ gfsh.connectAndVerify(locator);
- public void doTestSelectProjectionWithNestedField() {
- Random random = new Random(System.nanoTime());
- int randomInteger = random.nextInt(COUNT);
- String query = "query --query=\"select employeeId, name, department, value2 from "
- + DATA_REGION_NAME_VM1_PATH + " where employeeId <= " + randomInteger
- + "\" --interactive=false";
- CommandResult cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- String expectedCols[] = {"employeeId", "name", "department", "value2"};
- validateSelectResult(cmdResult, true, (randomInteger + 1), expectedCols);
-
- // Test with collections
- query =
- "query --query=\"select ID , status , createTime , pk, floatMinValue, collectionHolderMap from "
- + DATA_PAR_REGION_NAME_PATH + " where ID <= " + randomInteger
- + "\" --interactive=false";
- cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- expectedCols =
- new String[] {"ID", "status", "createTime", "pk", "floatMinValue", "collectionHolderMap"};
- validateSelectResult(cmdResult, true, (randomInteger + 1), expectedCols);
- }
+ server1.invoke(() -> setupRegions(DATA_REGION_NAME_VM1, DATA_PAR_REGION_NAME_VM1));
- public void doTestSelectBeansAsResult() {
- Random random = new Random(System.nanoTime());
- int randomInteger = random.nextInt(COUNT);
- String query = "query --query=\"select * from " + DATA_REGION_NAME_PATH
- + " where employeeId <= " + randomInteger + "\" --interactive=false";
- CommandResult cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- String expectedCols[] = {"name", "lastName", "department", "age", "employeeId"};
- validateSelectResult(cmdResult, true, (randomInteger + 1), expectedCols);
- }
+ server2.invoke(() -> {
+ setupRegions(DATA_REGION_NAME_VM2, DATA_PAR_REGION_NAME_VM2);
+ });
- public void doTestSelectBeansWithNestedFieldAsResult() {
- Random random = new Random(System.nanoTime());
- int randomInteger = random.nextInt(COUNT);
- String query = "query --query=\"select employeeId, name, department, value2 from "
- + DATA_REGION_NAME_VM1_PATH + " where employeeId <= " + randomInteger
- + "\" --interactive=false";
- CommandResult cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- String expectedCols[] = {"employeeId", "name", "department", "value2"};
- validateSelectResult(cmdResult, true, (randomInteger + 1), expectedCols);
- }
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_VM1_PATH, 1);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_VM2_PATH, 1);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_VM1_PATH, 1);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_VM2_PATH, 1);
+
+ locator.invoke(() -> {
+ InternalCache cache = ClusterStartupRule.getCache();
+ final ManagementService service = ManagementService.getManagementService(cache);
+
+ assertNotNull(service.getMemberMXBean());
+ assertNotNull(service.getManagerMXBean());
+ DistributedRegionMXBean bean = service.getDistributedRegionMXBean(DATA_REGION_NAME_PATH);
+ assertNotNull(bean);
- public void doTestSelectWithGfshEnvVariables(boolean statusActive) {
- Random random = new Random(System.nanoTime());
- int randomInteger = random.nextInt(COUNT);
- String query =
- "query --query=\"select ID , status , createTime , pk, floatMinValue from ${DATA_REGION} where ID <= ${PORTFOLIO_ID}"
- + " and status=${STATUS}" + "\" --interactive=false";
- executeCommand("set variable --name=DATA_REGION --value=" + DATA_REGION_NAME_PATH);
- executeCommand("set variable --name=PORTFOLIO_ID --value=" + randomInteger);
- executeCommand("set variable --name=STATUS --value=" + (statusActive ? "active" : "inactive"));
- CommandResult cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- validateSelectResult(cmdResult, true, -1, null);
- IgnoredException ex =
- addIgnoredException(QueryInvalidException.class.getSimpleName(), Host.getHost(0).getVM(0));
- try {
- query =
- "query --query=\"select ID , status , createTime , pk, floatMinValue from ${DATA_REGION2} where ID <= ${PORTFOLIO_ID2}"
- + " and status=${STATUS2}" + "\" --interactive=false";
- cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- validateSelectResult(cmdResult, false, 0, null);
- } finally {
- ex.remove();
- }
- }
+ String regions[] = {DATA_REGION_NAME_PATH, DATA_REGION_NAME_VM1_PATH,
+ DATA_REGION_NAME_VM2_PATH, DATA_PAR_REGION_NAME_PATH, DATA_PAR_REGION_NAME_VM1_PATH,
+ DATA_PAR_REGION_NAME_VM2_PATH};
- public void doTestBug48013() {
- String query = "query --query=\"SELECT e FROM " + DATA_REGION_NAME_PATH
- + ".entries e\" --interactive=false";
- CommandResult cmdResult = executeCommand(query);
- printCommandOutput(cmdResult);
- validateResult(cmdResult, true);
- }
+ for (String region : regions) {
+ bean = service.getDistributedRegionMXBean(region);
+ assertNotNull(bean);
- @Test
- public void testSelectCommand() {
- setupForSelect();
- doTestGetRegionAssociatedMembersForSelect();
- doTestSelectWithGfshEnvVariables(true);
- doTestSelectWithGfshEnvVariables(false);
- doTestSelectProjection();
- doTestBug48013();
- doTestSelectProjectionProcessCommand();
- doTestSelectProjectionWithNestedField();
- doTestSelectBeansAsResult();
- doTestSelectBeansWithNestedFieldAsResult();
+ if (bean.getMemberCount() < 1) {
+ fail("Even after waiting mbean reports number of member hosting region "
+ + DATA_REGION_NAME_VM1_PATH + " is less than one");
+ }
+ }
+ });
}
@Test
- public void testPrimitivesWithDataCommands() {
+ public void testPrimitivesWithDataCommands() throws Exception {
setupForGetPutRemoveLocateEntry("testPrimitives");
Byte byteKey = Byte.parseByte("41");
Byte byteValue = Byte.parseByte("31");
@@ -601,151 +196,128 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
Integer integerKey = Integer.parseInt("123456");
Integer integerValue = Integer.parseInt("12345678");
Float floatKey = Float.valueOf("12432.2325");
- Float flaotValue = Float.valueOf("111111.1111");
+ Float floatValue = Float.valueOf("111111.1111");
Double doubleKey = Double.valueOf("12432.235425");
Double doubleValue = Double.valueOf("111111.111111");
- getLogWriter().info("Testing Byte Wrappers");
+ // Testing Byte Wrappers
testGetPutLocateEntryFromShellAndGemfire(byteKey, byteValue, Byte.class, true, true);
- getLogWriter().info("Testing Short Wrappers");
+ // Testing Short Wrappers
testGetPutLocateEntryFromShellAndGemfire(shortKey, shortValue, Short.class, true, true);
- getLogWriter().info("Testing Integer Wrappers");
+ // Testing Integer Wrappers
testGetPutLocateEntryFromShellAndGemfire(integerKey, integerValue, Integer.class, true, true);
- getLogWriter().info("Testing Float Wrappers");
- testGetPutLocateEntryFromShellAndGemfire(floatKey, flaotValue, Float.class, true, true);
- getLogWriter().info("Testing Double Wrappers");
+ // Testing Float Wrappers
+ testGetPutLocateEntryFromShellAndGemfire(floatKey, floatValue, Float.class, true, true);
+ // Testing Double Wrappers
testGetPutLocateEntryFromShellAndGemfire(doubleKey, doubleValue, Double.class, true, true);
}
+
+
private void testGetPutLocateEntryFromShellAndGemfire(final Serializable key,
final Serializable value, Class klass, boolean addRegionPath, boolean expResult) {
- final VM vm1 = Host.getHost(0).getVM(1);
-
- SerializableRunnable putTask = new SerializableRunnable() {
- @Override
- public void run() {
- Cache cache = getCache();
- Region region = cache.getRegion(DATA_REGION_NAME_PATH);
- assertNotNull(region);
- region.clear();
- region.put(key, value);
- }
+ SerializableRunnableIF putTask = () -> {
+ Cache cache = ClusterStartupRule.getCache();
+ Region region = cache.getRegion(DATA_REGION_NAME_PATH);
+ assertNotNull(region);
+ region.clear();
+ region.put(key, value);
};
- SerializableRunnable getTask = new SerializableRunnable() {
- @Override
- public void run() {
- Cache cache = getCache();
- Region region = cache.getRegion(DATA_REGION_NAME_PATH);
- assertNotNull(region);
- assertEquals(true, region.containsKey(key));
- assertEquals(value, region.get(key));
- }
+ SerializableRunnableIF getTask = () -> {
+ Cache cache = ClusterStartupRule.getCache();
+ Region region = cache.getRegion(DATA_REGION_NAME_PATH);
+ assertNotNull(region);
+ assertEquals(true, region.containsKey(key));
+ assertEquals(value, region.get(key));
};
- SerializableRunnable removeTask = new SerializableRunnable() {
- @Override
- public void run() {
- Cache cache = getCache();
- Region region = cache.getRegion(DATA_REGION_NAME_PATH);
- assertNotNull(region);
- assertEquals(true, region.containsKey(key));
- region.remove(key);
- }
+ SerializableRunnableIF removeTask = () -> {
+ Cache cache = ClusterStartupRule.getCache();
+ Region region = cache.getRegion(DATA_REGION_NAME_PATH);
+ assertNotNull(region);
+ assertEquals(true, region.containsKey(key));
+ region.remove(key);
};
- SerializableRunnable clearTask = new SerializableRunnable() {
- @Override
- public void run() {
- Cache cache = getCache();
- Region region = cache.getRegion(DATA_REGION_NAME_PATH);
- assertNotNull(region);
- region.clear();
- }
+ SerializableRunnableIF clearTask = () -> {
+ Cache cache = ClusterStartupRule.getCache();
+ Region region = cache.getRegion(DATA_REGION_NAME_PATH);
+ assertNotNull(region);
+ region.clear();
};
- String getCommand = "get --key=" + key + " --key-class=" + klass.getCanonicalName()
- + " --value-class=" + klass.getCanonicalName();
+ String canonicalName = klass.getCanonicalName();
+ String getCommand = "get --key=" + key + " --key-class=" + canonicalName
+ + " --value-class=" + canonicalName;
if (addRegionPath)
getCommand += " --region=" + DATA_REGION_NAME_PATH;
String locateEntryCommand = "locate entry --key=" + key + " --key-class="
- + klass.getCanonicalName() + " --value-class=" + klass.getCanonicalName();
+ + canonicalName + " --value-class=" + canonicalName;
if (addRegionPath)
locateEntryCommand += " --region=" + DATA_REGION_NAME_PATH;
- String removeCommand = "remove --key=" + key + " --key-class=" + klass.getCanonicalName();
+ String removeCommand = "remove --key=" + key + " --key-class=" + canonicalName;
if (addRegionPath)
removeCommand += " --region=" + DATA_REGION_NAME_PATH;
- String putCommand = "put --key=" + key + " --key-class=" + klass.getCanonicalName()
- + " --value=" + value + " --value-class=" + klass.getCanonicalName();
+ String putCommand = "put --key=" + key + " --key-class=" + canonicalName
+ + " --value=" + value + " --value-class=" + canonicalName;
if (addRegionPath)
putCommand += " --region=" + DATA_REGION_NAME_PATH;
if (expResult) {
// Do put from shell check gemfire get do gemfire remove
- CommandResult cmdResult = executeCommand(putCommand);
- printCommandOutput(cmdResult);
+ CommandResult cmdResult = gfsh.executeCommand(putCommand);
validateResult(cmdResult, true);
- vm1.invoke(getTask);
- vm1.invoke(removeTask);
+ server1.invoke(getTask);
+ server1.invoke(removeTask);
- vm1.invoke(clearTask);
+ server1.invoke(clearTask);
// Do put from gemfire check from shell do gemfire remove
- vm1.invoke(putTask);
- cmdResult = executeCommand(getCommand);
- printCommandOutput(cmdResult);
+ server1.invoke(putTask);
+ cmdResult = gfsh.executeCommand(getCommand);
validateResult(cmdResult, true);
- cmdResult = executeCommand(locateEntryCommand);
- printCommandOutput(cmdResult);
+ cmdResult = gfsh.executeCommand(locateEntryCommand);
validateResult(cmdResult, true);
- vm1.invoke(removeTask);
+ server1.invoke(removeTask);
- vm1.invoke(clearTask);
+ server1.invoke(clearTask);
// Do put from shell check from gemfire do remove from shell get from shell expect false
- cmdResult = executeCommand(putCommand);
- printCommandOutput(cmdResult);
+ cmdResult = gfsh.executeCommand(putCommand);
validateResult(cmdResult, true);
- vm1.invoke(getTask);
- cmdResult = executeCommand(removeCommand);
- printCommandOutput(cmdResult);
+ server1.invoke(getTask);
+ cmdResult = gfsh.executeCommand(removeCommand);
validateResult(cmdResult, true);
- cmdResult = executeCommand(getCommand);
- printCommandOutput(cmdResult);
+ cmdResult = gfsh.executeCommand(getCommand);
validateResult(cmdResult, false);
- cmdResult = executeCommand(locateEntryCommand);
- printCommandOutput(cmdResult);
+ cmdResult = gfsh.executeCommand(locateEntryCommand);
validateResult(cmdResult, false);
} else {
// Do put from shell check gemfire get do gemfire remove
- CommandResult cmdResult = executeCommand(putCommand);
- printCommandOutput(cmdResult);
+ CommandResult cmdResult = gfsh.executeCommand(putCommand);
validateResult(cmdResult, false);
- vm1.invoke(clearTask);
+ server1.invoke(clearTask);
// Do put from gemfire check from shell do gemfire remove
- vm1.invoke(putTask);
- cmdResult = executeCommand(getCommand);
- printCommandOutput(cmdResult);
+ server1.invoke(putTask);
+ cmdResult = gfsh.executeCommand(getCommand);
validateResult(cmdResult, false);
- cmdResult = executeCommand(locateEntryCommand);
- printCommandOutput(cmdResult);
+ cmdResult = gfsh.executeCommand(locateEntryCommand);
validateResult(cmdResult, false);
- vm1.invoke(removeTask);
- vm1.invoke(clearTask);
+ server1.invoke(removeTask);
+ server1.invoke(clearTask);
// Do put from shell check from gemfire do remove from shell get from shell exepct false
- cmdResult = executeCommand(putCommand);
- printCommandOutput(cmdResult);
+ cmdResult = gfsh.executeCommand(putCommand);
validateResult(cmdResult, false);
}
}
-
private void validateResult(CommandResult cmdResult, Boolean expected) {
if (ResultData.TYPE_MODEL.equals(cmdResult.getType())) {
ResultModel rd = (ResultModel) cmdResult.getResultData();
@@ -755,339 +327,15 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
fail("Expected CompositeResult Returned Result Type " + cmdResult.getType());
}
- private void validateSelectResult(CommandResult cmdResult, Boolean expectedFlag,
- Integer expectedRows, String[] cols) {
- if (ResultData.TYPE_MODEL.equals(cmdResult.getType())) {
- ResultModel rd = (ResultModel) cmdResult.getResultData();
- Map<String, String> data =
- rd.getDataSection(DataCommandResult.DATA_INFO_SECTION).getContent();
- assertThat(data.get("Result")).isEqualTo(expectedFlag.toString());
- if (expectedFlag && expectedRows != -1) {
- assertThat(data.get("Rows")).isEqualTo(expectedRows.toString());
- if (expectedRows > 0 && cols != null) {
- Map<String, List<String>> table =
- rd.getTableSection(DataCommandResult.QUERY_SECTION).getContent();
- assertThat(table.keySet()).contains(cols);
- }
- }
- } else
- fail("Expected CompositeResult Returned Result Type " + cmdResult.getType());
- }
-
- void setupWith2Regions() {
- final VM vm1 = Host.getHost(0).getVM(1);
- final VM vm2 = Host.getHost(0).getVM(2);
- setUpJmxManagerOnVm0ThenConnect(null);
-
- vm1.invoke(new SerializableRunnable() {
- public void run() {
-
- // no need to close cache as it will be closed as part of teardown2
- Cache cache = getCache();
-
- RegionFactory<Integer, Integer> dataRegionFactory =
- cache.createRegionFactory(RegionShortcut.PARTITION);
- Region region = dataRegionFactory.create(REBALANCE_REGION_NAME);
- for (int i = 0; i < 10; i++) {
- region.put("key" + (i + 200), "value" + (i + 200));
- }
- region = dataRegionFactory.create(REBALANCE_REGION2_NAME);
- for (int i = 0; i < 50; i++) {
- region.put("key" + (i + 200), "value" + (i + 200));
- }
- }
- });
-
- vm2.invoke(new SerializableRunnable() {
- public void run() {
-
- // no need to close cache as it will be closed as part of teardown2
- Cache cache = getCache();
-
- RegionFactory<Integer, Integer> dataRegionFactory =
- cache.createRegionFactory(RegionShortcut.PARTITION);
- Region region = dataRegionFactory.create(REBALANCE_REGION_NAME);
- for (int i = 0; i < 150; i++) {
- region.put("key" + (i + 400), "value" + (i + 400));
- }
- region = dataRegionFactory.create(REBALANCE_REGION2_NAME);
- for (int i = 0; i < 100; i++) {
- region.put("key" + (i + 200), "value" + (i + 200));
- }
- }
- });
- }
-
- SerializableRunnable checkRegionMBeans = new SerializableRunnable() {
- @Override
- public void run() {
- final WaitCriterion waitForMaangerMBean = new WaitCriterion() {
- @Override
- public boolean done() {
- final ManagementService service = ManagementService.getManagementService(getCache());
- final DistributedRegionMXBean bean =
- service.getDistributedRegionMXBean(Region.SEPARATOR + REBALANCE_REGION_NAME);
- if (bean == null) {
- getLogWriter().info("Still probing for checkRegionMBeans ManagerMBean");
- return false;
- } else {
- // verify that bean is proper before executing tests
- return bean.getMembers() != null && bean.getMembers().length > 1
- && bean.getMemberCount() > 0
- && service.getDistributedSystemMXBean().listRegions().length >= 2;
- }
- }
-
- @Override
- public String description() {
- return "Probing for testRebalanceCommandForSimulateWithNoMember ManagerMBean";
- }
- };
- waitForCriterion(waitForMaangerMBean, 2 * 60 * 1000, 2000, true);
- DistributedRegionMXBean bean = ManagementService.getManagementService(getCache())
- .getDistributedRegionMXBean("/" + REBALANCE_REGION_NAME);
- assertNotNull(bean);
- }
- };
-
- @Test
- public void testRebalanceCommandForTimeOut() {
- setupTestRebalanceForEntireDS();
-
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
- getLogWriter().info("testRebalanceCommandForTimeOut verified Mbean and executin command");
- String command = "rebalance --time-out=1";
- CommandResult cmdResult = executeCommand(command);
- getLogWriter().info("testRebalanceCommandForTimeOut just after executing " + cmdResult);
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testRebalanceCommandForTimeOut stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceCommandForTimeOut failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testRebalanceCommandForTimeOutForRegion() {
- setupTestRebalanceForEntireDS();
-
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
-
- getLogWriter()
- .info("testRebalanceCommandForTimeOutForRegion verified Mbean and executin command");
-
- String command = "rebalance --time-out=1 --include-region=" + "/" + REBALANCE_REGION_NAME;
- CommandResult cmdResult = executeCommand(command);
-
- getLogWriter()
- .info("testRebalanceCommandForTimeOutForRegion just after executing " + cmdResult);
-
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testRebalanceCommandForTimeOutForRegion stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceCommandForTimeOut failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testRebalanceCommandForSimulate() {
- setupTestRebalanceForEntireDS();
-
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
-
- getLogWriter().info("testRebalanceCommandForSimulate verified Mbean and executing command");
- String command = "rebalance --simulate=true --include-region=" + "/" + REBALANCE_REGION_NAME;
- CommandResult cmdResult = executeCommand(command);
- getLogWriter().info("testRebalanceCommandForSimulate just after executing " + cmdResult);
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testRebalanceCommandForSimulate stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceCommandForSimulate failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testRebalanceCommandForSimulateWithNoMember() {
- setupTestRebalanceForEntireDS();
-
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
-
- getLogWriter()
- .info("testRebalanceCommandForSimulateWithNoMember verified Mbean and executin command");
-
- String command = "rebalance --simulate=true";
- CommandResult cmdResult = executeCommand(command);
-
- getLogWriter()
- .info("testRebalanceCommandForSimulateWithNoMember just after executing " + cmdResult);
-
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter()
- .info("testRebalanceCommandForSimulateWithNoMember stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceCommandForSimulateWithNoMember failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testRebalanceForIncludeRegionFunction() {
- // setup();
- setupWith2Regions();
-
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
- getLogWriter()
- .info("testRebalanceForIncludeRegionFunction verified Mbean and executin command");
- String command =
- "rebalance --include-region=" + "/" + REBALANCE_REGION_NAME + ",/" + REBALANCE_REGION2_NAME;
- CommandResult cmdResult = executeCommand(command);
- getLogWriter().info("testRebalanceForIncludeRegionFunction just after executing " + cmdResult);
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testRebalanceForIncludeRegionFunction stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceForIncludeRegionFunction failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testSimulateForEntireDS() {
- setupTestRebalanceForEntireDS();
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
-
- getLogWriter().info("testSimulateForEntireDS verified MBean and executing command");
-
- String command = "rebalance --simulate=true";
-
- CommandResult cmdResult = executeCommand(command);
-
- getLogWriter().info("testSimulateForEntireDS just after executing " + cmdResult);
-
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testSimulateForEntireDS stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceForIncludeRegionFunction failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testSimulateForEntireDSWithTimeout() {
- setupTestRebalanceForEntireDS();
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
-
- getLogWriter().info("testSimulateForEntireDS verified MBean and executing command");
-
- String command = "rebalance --simulate=true --time-out=-1";
-
- CommandResult cmdResult = executeCommand(command);
-
- getLogWriter().info("testSimulateForEntireDS just after executing " + cmdResult);
+ private Properties locatorProperties() {
+ int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOG_LEVEL, "fine");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort);
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testSimulateForEntireDS stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceForIncludeRegionFunction failed as did not get CommandResult");
- }
- }
-
- @Test
- public void testRebalanceForEntireDS() {
- setupTestRebalanceForEntireDS();
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
- getLogWriter().info("testRebalanceForEntireDS verified Mbean and executin command");
- String command = "rebalance";
- CommandResult cmdResult = executeCommand(command);
- getLogWriter().info("testRebalanceForEntireDS just after executing " + cmdResult);
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testRebalanceForEntireDS stringResult : " + stringResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceForIncludeRegionFunction failed as did not get CommandResult");
- }
- }
-
- void setupTestRebalanceForEntireDS() {
- final VM vm1 = Host.getHost(0).getVM(1);
- final VM vm2 = Host.getHost(0).getVM(2);
- setUpJmxManagerOnVm0ThenConnect(null);
-
- vm1.invoke(new SerializableRunnable() {
- public void run() {
-
- // no need to close cache as it will be closed as part of teardown2
- Cache cache = getCache();
-
- RegionFactory<Integer, Integer> dataRegionFactory =
- cache.createRegionFactory(RegionShortcut.PARTITION);
- Region region = dataRegionFactory.create(REBALANCE_REGION_NAME);
- for (int i = 0; i < 10; i++) {
- region.put("key" + (i + 200), "value" + (i + 200));
- }
- region = dataRegionFactory.create(REBALANCE_REGION_NAME + "Another1");
- for (int i = 0; i < 100; i++) {
- region.put("key" + (i + 200), "value" + (i + 200));
- }
- }
- });
-
- vm2.invoke(new SerializableRunnable() {
- public void run() {
-
- // no need to close cache as it will be closed as part of teardown2
- Cache cache = getCache();
-
- RegionFactory<Integer, Integer> dataRegionFactory =
- cache.createRegionFactory(RegionShortcut.PARTITION);
- Region region = dataRegionFactory.create(REBALANCE_REGION_NAME);
- for (int i = 0; i < 100; i++) {
- region.put("key" + (i + 400), "value" + (i + 400));
- }
- region = dataRegionFactory.create(REBALANCE_REGION_NAME + "Another2");
- for (int i = 0; i < 10; i++) {
- region.put("key" + (i + 200), "value" + (i + 200));
- }
- }
- });
- }
-
- 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("");
+ return props;
}
public static class Value1WithValue2 extends Value1 {
@@ -1107,176 +355,4 @@ public class GemfireDataCommandsDUnitTest extends CliCommandTestBase {
}
}
- @Test
- public void testRebalanceForExcludeRegionFunction() {
- setupWith2Regions();
-
- // check if DistributedRegionMXBean is available so that command will not fail
- final VM manager = Host.getHost(0).getVM(0);
- manager.invoke(checkRegionMBeans);
-
- getLogWriter()
- .info("testRebalanceForExcludeRegionFunction verified Mbean and executing command");
-
- String command = "rebalance --exclude-region=" + "/" + REBALANCE_REGION2_NAME;
- getLogWriter().info("testRebalanceForExcludeRegionFunction command : " + command);
- CommandResult cmdResult = executeCommand(command);
- getLogWriter().info("testRebalanceForExcludeRegionFunction just after executing " + cmdResult);
- if (cmdResult != null) {
- String stringResult = commandResultToString(cmdResult);
- getLogWriter().info("testRebalanceForExcludeRegionFunction stringResult : " + stringResult);
- assertEquals("CommandResult=" + cmdResult, Result.Status.OK, cmdResult.getStatus());
- } else {
- fail("testRebalanceForIncludeRegionFunction failed as did not get CommandResult");
- }
- }
-
- public void waitForListClientMbean(final String regionName) {
- final VM manager = Host.getHost(0).getVM(0);
-
- manager.invoke(new SerializableRunnable() {
- @Override
- public void run() {
- Cache cache = getCache();
- final ManagementService service = ManagementService.getManagementService(cache);
-
- final WaitCriterion waitForMaangerMBean = new WaitCriterion() {
- @Override
- public boolean done() {
- ManagerMXBean bean1 = service.getManagerMXBean();
- DistributedRegionMXBean bean2 = service.getDistributedRegionMXBean(regionName);
- if (bean1 == null) {
- getLogWriter().info("waitForListClientMbean Still probing for ManagerMBean");
- return false;
- } else {
- getLogWriter().info(
- "waitForListClientMbean Still probing for DistributedRegionMXBean=" + bean2);
- if (bean2 == null) {
- bean2 = service.getDistributedRegionMXBean(Region.SEPARATOR + regionName);
- }
- if (bean2 == null) {
- getLogWriter().info(
- "waitForListClientMbean Still probing for DistributedRegionMXBean with separator = "
- + bean2);
- return false;
- } else {
- getLogWriter().info(
- "waitForListClientMbean Still probing for DistributedRegionMXBean with separator Not null "
- + bean2.getMembers().length);
- return bean2.getMembers().length > 1;
- }
- }
- }
-
- @Override
- public String description() {
- return "waitForListClientMbean Probing for ManagerMBean";
- }
- };
-
- waitForCriterion(waitForMaangerMBean, 30000, 2000, true);
- DistributedRegionMXBean bean = service.getDistributedRegionMXBean(regionName);
- if (bean == null) {
- bean = service.getDistributedRegionMXBean(Region.SEPARATOR + regionName);
- }
- assertNotNull(bean);
- }
- });
-
- }
-
- @Test
- public void testRegionsViaMbeanAndFunctions() {
- setupForGetPutRemoveLocateEntry("tesSimplePut");
- waitForListClientMbean(DATA_REGION_NAME_PATH);
- final VM manager = Host.getHost(0).getVM(0);
-
- String memSizeFromMbean = (String) manager.invoke(new SerializableCallable() {
- public Object call() {
- Cache cache = GemFireCacheImpl.getInstance();
- DistributedRegionMXBean bean = ManagementService.getManagementService(cache)
- .getDistributedRegionMXBean(DATA_REGION_NAME_PATH);
-
- if (bean == null)// try with slash ahead
- bean = ManagementService.getManagementService(cache)
- .getDistributedRegionMXBean(Region.SEPARATOR + DATA_REGION_NAME_PATH);
-
- if (bean == null) {
- return null;
- }
-
- String[] membersName = bean.getMembers();
- return "" + membersName.length;
- }
- });
-
- getLogWriter().info("testRegionsViaMbeanAndFunctions memSizeFromMbean= " + memSizeFromMbean);
-
- String memSizeFromFunctionCall = (String) manager.invoke(new SerializableCallable() {
- public Object call() {
- InternalCache cache = GemFireCacheImpl.getInstance();
- CliUtil.getRegionAssociatedMembers(DATA_REGION_NAME_PATH, cache, true);
- return "" + CliUtil.getRegionAssociatedMembers(DATA_REGION_NAME_PATH, cache, true).size();
- }
- });
-
- getLogWriter().info(
- "testRegionsViaMbeanAndFunctions memSizeFromFunctionCall= " + memSizeFromFunctionCall);
- assertTrue(memSizeFromFunctionCall.equals(memSizeFromMbean));
- }
-
- @Test
- public void testRegionsViaMbeanAndFunctionsForPartRgn() {
- setupWith2Regions();
- waitForListClientMbean(REBALANCE_REGION_NAME);
- final VM manager = Host.getHost(0).getVM(0);
-
- String memSizeFromMbean = (String) manager.invoke(new SerializableCallable() {
- public Object call() {
- Cache cache = GemFireCacheImpl.getInstance();
- DistributedRegionMXBean bean = ManagementService.getManagementService(cache)
- .getDistributedRegionMXBean(REBALANCE_REGION_NAME);
-
- if (bean == null) {
- bean = ManagementService.getManagementService(cache)
- .getDistributedRegionMXBean(Region.SEPARATOR + REBALANCE_REGION_NAME);
- }
-
- if (bean == null) {
- return null;
- }
-
- String[] membersName = bean.getMembers();
- return "" + membersName.length;
- }
- });
-
- getLogWriter()
- .info("testRegionsViaMbeanAndFunctionsForPartRgn memSizeFromMbean= " + memSizeFromMbean);
-
- String memSizeFromFunctionCall = (String) manager.invoke(new SerializableCallable() {
- public Object call() {
- InternalCache cache = GemFireCacheImpl.getInstance();
- return "" + CliUtil.getRegionAssociatedMembers(REBALANCE_REGION_NAME, cache, true).size();
- }
- });
-
- getLogWriter().info("testRegionsViaMbeanAndFunctionsForPartRgn memSizeFromFunctionCall= "
- + memSizeFromFunctionCall);
- assertTrue(memSizeFromFunctionCall.equals(memSizeFromMbean));
- }
-
- private static class CountingCacheListener extends CacheListenerAdapter {
-
- private final AtomicInteger events = new AtomicInteger();
-
- @Override
- public void afterCreate(EntryEvent event) {
- events.incrementAndGet();
- }
-
- private int getEvents() {
- return events.get();
- }
- }
}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueryCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueryCommandDUnitTest.java
new file mode 100644
index 0000000..0e88350
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/QueryCommandDUnitTest.java
@@ -0,0 +1,319 @@
+/*
+ * 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 org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER;
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.fail;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Random;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.EvictionAction;
+import org.apache.geode.cache.EvictionAlgorithm;
+import org.apache.geode.cache.PartitionAttributes;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.query.QueryInvalidException;
+import org.apache.geode.cache.query.data.Portfolio;
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.cache.EvictionAttributesImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.i18n.LocalizedStrings;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.MemberMXBean;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.domain.DataCommandResult;
+import org.apache.geode.management.internal.cli.dto.Value1;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.management.internal.cli.result.ResultData;
+import org.apache.geode.management.internal.cli.result.model.ResultModel;
+import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
+
+@Category({DistributedTest.class})
+@SuppressWarnings("serial")
+public class QueryCommandDUnitTest {
+ private static final String DATA_REGION_NAME = "GemfireDataCommandsTestRegion";
+ private static final String DATA_REGION_NAME_PATH = "/" + DATA_REGION_NAME;
+ private static final String DATA_REGION_WITH_EVICTION_NAME =
+ "GemfireDataCommandsTestRegionWithEviction";
+ private static final String DATA_REGION_WITH_EVICTION_NAME_PATH =
+ "/" + DATA_REGION_WITH_EVICTION_NAME;
+ private static final String DATA_PAR_REGION_NAME = "GemfireDataCommandsTestParRegion";
+ private static final String DATA_PAR_REGION_NAME_PATH = "/" + DATA_PAR_REGION_NAME;
+
+ private static final String SERIALIZATION_FILTER =
+ "org.apache.geode.management.internal.cli.dto.**";
+
+ static final int COUNT = 5;
+
+ @Rule
+ public GfshCommandRule gfsh = new GfshCommandRule();
+
+ @Rule
+ public ClusterStartupRule cluster = new ClusterStartupRule();
+
+ private MemberVM locator, server1, server2;
+
+ @Before
+ public void before() throws Exception {
+ locator = cluster.startLocatorVM(0, locatorProperties());
+ server1 = cluster.startServerVM(1, serverProperties(), locator.getPort());
+ server2 = cluster.startServerVM(2, serverProperties(), locator.getPort());
+
+ server1.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME));
+ server2.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME));
+ server1.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 1);
+
+ gfsh.connectAndVerify(locator);
+ }
+
+ @Test
+ public void testWithGfshEnvironmentVariables() {
+ String query =
+ "query --query=\"select ID , status , createTime , pk, floatMinValue from ${DATA_REGION} where ID <= ${PORTFOLIO_ID}"
+ + " and status=${STATUS}" + "\" --interactive=false";
+ gfsh.executeCommand("set variable --name=DATA_REGION --value=" + DATA_REGION_NAME_PATH);
+ gfsh.executeCommand("set variable --name=PORTFOLIO_ID --value=3");
+ gfsh.executeCommand("set variable --name=STATUS --value=inactive");
+ CommandResult cmdResult = gfsh.executeCommand(query);
+ assertThat(cmdResult.getStatus()).isEqualTo(Result.Status.OK);
+ }
+
+ @Test
+ public void testWithUnsetGfshEnvironmentVariables() {
+ IgnoredException ex =
+ addIgnoredException(QueryInvalidException.class.getSimpleName(), locator.getVM());
+ try {
+ String query =
+ "query --query=\"select ID , status , createTime , pk, floatMinValue from ${UNSET_REGION} where ID <= ${UNSET_PORTFOLIO_ID}"
+ + " and status=${UNSET_STATUS}" + "\" --interactive=false";
+ CommandResult result = gfsh.executeCommand(query);
+ assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
+ assertThat(result.getResultData().toString())
+ .contains(LocalizedStrings.QCompiler_SYNTAX_ERROR_IN_QUERY_0.toLocalizedString(""));
+ } finally {
+ ex.remove();
+ }
+ }
+
+ @Test
+ public void testSimpleQuery() {
+ server1.invoke(() -> prepareDataForRegion(DATA_PAR_REGION_NAME_PATH));
+ Random random = new Random(System.nanoTime());
+ int randomInteger = random.nextInt(COUNT);
+ String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from "
+ + DATA_PAR_REGION_NAME_PATH + " where ID <= " + randomInteger + "\" --interactive=false";
+ CommandResult commandResult = gfsh.executeCommand(query);
+ validateSelectResult(commandResult, true, (randomInteger + 1),
+ new String[] {"ID", "status", "createTime", "pk", "floatMinValue"});
+ }
+
+ @Test
+ public void testSimpleQueryOnLocator() {
+ server1.invoke(() -> prepareDataForRegion(DATA_PAR_REGION_NAME_PATH));
+
+ locator.invoke(() -> {
+ String query = "query --query=\"select ID , status , createTime , pk, floatMinValue from "
+ + DATA_PAR_REGION_NAME_PATH + " where ID <= 4"
+ + "\" --interactive=false";
+ ManagementService service =
+ ManagementService.getExistingManagementService(ClusterStartupRule.getCache());
+ MemberMXBean member = service.getMemberMXBean();
+ String cmdResult = member.processCommand(query);
+
+ assertThat(cmdResult).contains("ID");
+ assertThat(cmdResult).contains("status");
+ assertThat(cmdResult).contains("createTime");
+ assertThat(cmdResult).contains("pk");
+ assertThat(cmdResult).contains("floatMinValue");
+ assertThat(cmdResult).contains("\"Rows\":\"5\"");
+ });
+ }
+
+ @Test
+ public void testQueryEvictedDataDeserializable() {
+ server1.invoke(() -> setupReplicatedRegionWithEviction(DATA_REGION_WITH_EVICTION_NAME));
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_EVICTION_NAME_PATH, 1);
+ server1.invoke(() -> prepareDeserializableDataForRegion(DATA_REGION_WITH_EVICTION_NAME_PATH));
+
+ String query = "query --query=\"select Value from " + DATA_REGION_WITH_EVICTION_NAME_PATH
+ + "\" --interactive=false";
+ CommandResult commandResult = gfsh.executeCommand(query);
+ validateSelectResult(commandResult, Boolean.TRUE, 10, new String[] {"Value"});
+ }
+
+ @Test
+ public void testQueryEvictedDataNotDeserializable() {
+ IgnoredException ex =
+ addIgnoredException(Exception.class.getSimpleName(), locator.getVM());
+
+ server1.invoke(() -> setupReplicatedRegionWithEviction(DATA_REGION_WITH_EVICTION_NAME));
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_WITH_EVICTION_NAME_PATH, 1);
+ server1
+ .invoke(() -> prepareNotDeserializableDataForRegion(DATA_REGION_WITH_EVICTION_NAME_PATH));
+
+ String query = "query --query=\"select Value from " + DATA_REGION_WITH_EVICTION_NAME_PATH
+ + "\" --interactive=false";
+ CommandResult commandResult = gfsh.executeCommand(query);
+ validateSelectResult(commandResult, Boolean.FALSE, -1, new String[] {"Value"});
+ assertThat(commandResult.getResultData().toString())
+ .contains(LocalizedStrings.EntryEventImpl_AN_IOEXCEPTION_WAS_THROWN_WHILE_DESERIALIZING
+ .toLocalizedString());
+
+ ex.remove();
+ }
+
+ private static void prepareDataForRegion(String regionPath) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Region dataRegion = cache.getRegion(regionPath);
+
+ for (int j = 0; j < 10; j++) {
+ dataRegion.put(new Integer(j), new Portfolio(j));
+ }
+ }
+
+ private static void prepareNotDeserializableDataForRegion(String regionPath) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Region dataRegion = cache.getRegion(regionPath);
+
+ for (int j = 0; j < 10; j++) {
+ dataRegion.put(new Integer(j), new shouldFailSerializationFilter(j));
+ }
+ }
+
+ private static void prepareDeserializableDataForRegion(String regionPath) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Region dataRegion = cache.getRegion(regionPath);
+
+ for (int j = 0; j < 10; j++) {
+ dataRegion.put(new Integer(j), new Value1(j));
+ }
+ }
+
+ private static void setupReplicatedRegionWithEviction(String regionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ EvictionAttributesImpl evictionAttributes = new EvictionAttributesImpl();
+ evictionAttributes.setMaximum(1).setAction(EvictionAction.OVERFLOW_TO_DISK)
+ .setAlgorithm(EvictionAlgorithm.LRU_ENTRY);
+ RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE)
+ .setEvictionAttributes(evictionAttributes);
+
+ Region dataRegion = regionFactory.create(regionName);
+ assertThat(dataRegion).isNotNull();
+ assertThat(dataRegion.getFullPath()).contains(regionName);
+ }
+
+ private static void setupPartitionedRegion(String regionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ PartitionAttributes partitionAttrs =
+ new PartitionAttributesFactory().setRedundantCopies(2).create();
+ RegionFactory<Object, Object> partitionRegionFactory =
+ cache.createRegionFactory(RegionShortcut.PARTITION);
+
+ partitionRegionFactory.setPartitionAttributes(partitionAttrs);
+ Region dataParRegion = partitionRegionFactory.create(regionName);
+
+ assertThat(dataParRegion).isNotNull();
+ assertThat(dataParRegion.getFullPath()).contains(regionName);
+ }
+
+ private static void setupReplicatedRegion(String regionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+
+ Region dataRegion = regionFactory.create(regionName);
+ assertThat(dataRegion).isNotNull();
+ assertThat(dataRegion.getFullPath()).contains(regionName);
+ }
+
+ private void validateSelectResult(CommandResult cmdResult, Boolean expectSuccess,
+ Integer expectedRows, String[] cols) {
+ if (ResultData.TYPE_MODEL.equals(cmdResult.getType())) {
+ ResultModel rd = (ResultModel) cmdResult.getResultData();
+
+ Map<String, String> data =
+ rd.getDataSection(DataCommandResult.DATA_INFO_SECTION).getContent();
+ assertThat(data.get("Result")).isEqualTo(expectSuccess.toString());
+
+ if (expectSuccess && expectedRows != -1) {
+ assertThat(data.get("Rows")).isEqualTo(expectedRows.toString());
+
+ if (expectedRows > 0 && cols != null) {
+ Map<String, List<String>> table =
+ rd.getTableSection(DataCommandResult.QUERY_SECTION).getContent();
+ assertThat(table.keySet()).contains(cols);
+ }
+ }
+ } else {
+ fail("Expected CompositeResult Returned Result Type " + cmdResult.getType());
+ }
+ }
+
+ private Properties locatorProperties() {
+ int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOG_LEVEL, "fine");
+ props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER);
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort);
+
+ return props;
+ }
+
+ private Properties serverProperties() {
+ Properties props = new Properties();
+ props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER);
+
+ return props;
+ }
+
+ public static class shouldFailSerializationFilter extends Value1 {
+ private Value1 value1 = null;
+
+ public shouldFailSerializationFilter(int i) {
+ super(i);
+ }
+
+ public Value1 getValue1() {
+ return value1;
+ }
+
+ public void setValue1(Value1 value1) {
+ this.value1 = value1;
+ }
+ }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDUnitTest.java
new file mode 100644
index 0000000..1c5e279
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RebalanceCommandDUnitTest.java
@@ -0,0 +1,349 @@
+/*
+ * 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 org.apache.geode.management.internal.cli.commands;
+
+import static java.lang.Math.abs;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
+
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+
+import org.awaitility.Awaitility;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.partition.PartitionRegionHelper;
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.result.CommandResult;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
+
+@Category({DistributedTest.class})
+public class RebalanceCommandDUnitTest {
+ private static final String SHARED_REGION_NAME = "GemfireDataCommandsDUnitTestRegion";
+ private static final String REGION1_NAME = "GemfireDataCommandsDUnitTestRegion1";
+ private static final String REGION2_NAME = "GemfireDataCommandsDUnitTestRegion2";
+
+ private static final Integer SERVER1_SHARED_REGION_SIZE = 10;
+ private static final Integer SERVER2_SHARED_REGION_SIZE = 100;
+ private static final Integer SERVER1_REGION1_SIZE = 100;
+ private static final Integer SERVER2_REGION2_SIZE = 10;
+
+ @Rule
+ public GfshCommandRule gfsh = new GfshCommandRule();
+
+ @Rule
+ public ClusterStartupRule cluster = new ClusterStartupRule();
+
+ private MemberVM locator, server1, server2;
+ private static int server1SharedRegionInitialSize, server2SharedRegionInitialSize,
+ server1Region1InitialSize, server2Region2InitialSize;
+
+ @Before
+ public void before() throws Exception {
+ locator = cluster.startLocatorVM(0, locatorProperties());
+ server1 = cluster.startServerVM(1, locator.getPort());
+ server2 = cluster.startServerVM(2, locator.getPort());
+
+ gfsh.connectAndVerify(locator);
+
+ server1.invoke(() -> {
+ Cache cache = ClusterStartupRule.getCache();
+
+ RegionFactory<Integer, Integer> dataRegionFactory =
+ cache.createRegionFactory(RegionShortcut.PARTITION);
+ Region region = dataRegionFactory.create(SHARED_REGION_NAME);
+ for (int i = 0; i < SERVER1_SHARED_REGION_SIZE; i++) {
+ region.put("key" + (i + 200), "value" + (i + 200));
+ }
+ region = dataRegionFactory.create(REGION1_NAME);
+ for (int i = 0; i < SERVER1_REGION1_SIZE; i++) {
+ region.put("key" + (i + 200), "value" + (i + 200));
+ }
+ });
+
+ server2.invoke(() -> {
+ Cache cache = ClusterStartupRule.getCache();
+ RegionFactory<Integer, Integer> dataRegionFactory =
+ cache.createRegionFactory(RegionShortcut.PARTITION);
+
+ Region region = dataRegionFactory.create(SHARED_REGION_NAME);
+ for (int i = 0; i < SERVER2_SHARED_REGION_SIZE; i++) {
+ region.put("key" + (i + 400), "value" + (i + 400));
+ }
+
+ region = dataRegionFactory.create(REGION2_NAME);
+ for (int i = 0; i < SERVER2_REGION2_SIZE; i++) {
+ region.put("key" + (i + 200), "value" + (i + 200));
+ }
+ });
+
+ // check if DistributedRegionMXBean is available so that command will not fail
+ locator.invoke(() -> waitForManagerMBean());
+
+ server1SharedRegionInitialSize =
+ server1.invoke(() -> getLocalDataSizeForRegion(SHARED_REGION_NAME));
+ server2SharedRegionInitialSize =
+ server2.invoke(() -> getLocalDataSizeForRegion(SHARED_REGION_NAME));
+ server1Region1InitialSize = server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME));
+ server2Region2InitialSize = server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME));
+ }
+
+ @Test
+ public void testWithTimeOut() {
+ String command = "rebalance --time-out=1";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertRegionBalanced(SHARED_REGION_NAME);
+ }
+
+ @Test
+ public void testWithTimeOutAndRegion() {
+ String command = "rebalance --time-out=1 --include-region=" + "/" + SHARED_REGION_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertRegionBalanced(SHARED_REGION_NAME);
+ }
+
+ @Test
+ public void testWithSimulateAndRegion() {
+ String command = "rebalance --simulate=true --include-region=" + "/" + SHARED_REGION_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ assertAllRegionsUnchanged();
+ }
+
+ @Test
+ public void testWithSimulate() {
+ String command = "rebalance --simulate=true";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ assertAllRegionsUnchanged();
+ }
+
+ @Test
+ public void testWithTwoRegions() {
+ String command =
+ "rebalance --include-region=" + "/" + SHARED_REGION_NAME + ",/" + REGION2_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ assertRegionBalanced(SHARED_REGION_NAME);
+ assertThat(server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME)))
+ .isEqualTo(server2Region2InitialSize);
+ }
+
+ @Test
+ public void testWithTwoSharedRegions() {
+ server1.invoke(() -> {
+ InternalCache cache = ClusterStartupRule.getCache();
+ RegionFactory<Integer, Integer> dataRegionFactory =
+ cache.createRegionFactory(RegionShortcut.PARTITION);
+ Region region = dataRegionFactory.create(REGION2_NAME);
+ for (int i = 0; i < 15; i++) {
+ region.put("key" + (i + 210), "value" + (i + 210));
+ }
+ });
+
+ String command =
+ "rebalance --include-region=" + "/" + SHARED_REGION_NAME + ",/" + REGION2_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ assertRegionBalanced(SHARED_REGION_NAME);
+ assertRegionBalanced(REGION2_NAME);
+ assertThat(server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME)))
+ .isEqualTo(server1Region1InitialSize);
+ }
+
+ @Test
+ public void testWithBadRegionNames() {
+ String command =
+ "rebalance --include-region=" + "/" + "randomGarbageString" + ",/" + "otherRandomGarbage";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+ assertAllRegionsUnchanged();
+ }
+
+ @Test
+ public void testWithOneGoodAndOneBadRegionName() {
+ String command =
+ "rebalance --include-region=" + "/" + SHARED_REGION_NAME + ",/" + "otherRandomGarbage";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertRegionBalanced(SHARED_REGION_NAME);
+ assertThat(server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME)))
+ .isEqualTo(server1Region1InitialSize);
+ assertThat(server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME)))
+ .isEqualTo(server2Region2InitialSize);
+ }
+
+ @Test
+ public void testWithNonSharedRegions() {
+ String command = "rebalance --include-region=" + "/" + REGION1_NAME + ",/" + REGION2_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ assertAllRegionsUnchanged();
+ }
+
+ @Test
+ public void testWithSimulateAndTimeout() {
+ String command = "rebalance --simulate=true --time-out=1";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertAllRegionsUnchanged();
+ }
+
+ @Test
+ public void testWithNoArgs() {
+ String command = "rebalance";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertRegionBalanced(SHARED_REGION_NAME);
+ assertThat(server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME)))
+ .isEqualTo(server1Region1InitialSize);
+ assertThat(server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME)))
+ .isEqualTo(server2Region2InitialSize);
+ }
+
+ @Test
+ public void testWithExcludedRegion() {
+ String command = "rebalance --exclude-region=" + "/" + REGION2_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertRegionBalanced(SHARED_REGION_NAME);
+ assertThat(server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME)))
+ .isEqualTo(server1Region1InitialSize);
+ assertThat(server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME)))
+ .isEqualTo(server2Region2InitialSize);
+ }
+
+ @Test
+ public void testWithExcludedSharedRegion() {
+ String command = "rebalance --exclude-region=" + "/" + SHARED_REGION_NAME;
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertAllRegionsUnchanged();
+ }
+
+ @Test
+ public void testWithExcludedBadRegion() {
+ String command = "rebalance --exclude-region=/asdf";
+ CommandResult cmdResult = gfsh.executeCommand(command);
+
+ assertThat(cmdResult).isNotNull();
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertRegionBalanced(SHARED_REGION_NAME);
+ assertThat(server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME)))
+ .isEqualTo(server1Region1InitialSize);
+ assertThat(server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME)))
+ .isEqualTo(server2Region2InitialSize);
+ }
+
+ private void assertAllRegionsUnchanged() {
+ Integer sharedServer1Size = server1.invoke(() -> getLocalDataSizeForRegion(SHARED_REGION_NAME));
+ Integer sharedServer2Size = server2.invoke(() -> getLocalDataSizeForRegion(SHARED_REGION_NAME));
+ Integer region1Server1Size = server1.invoke(() -> getLocalDataSizeForRegion(REGION1_NAME));
+ Integer region2Server2Size = server2.invoke(() -> getLocalDataSizeForRegion(REGION2_NAME));
+
+ assertThat(sharedServer1Size).isEqualTo(server1SharedRegionInitialSize);
+ assertThat(sharedServer2Size).isEqualTo(server2SharedRegionInitialSize);
+ assertThat(region1Server1Size).isEqualTo(server1Region1InitialSize);
+ assertThat(region2Server2Size).isEqualTo(server2Region2InitialSize);
+ }
+
+ private void assertRegionBalanced(String regionName) {
+ Integer size1 = server1.invoke(() -> getLocalDataSizeForRegion(regionName));
+ Integer size2 = server2.invoke(() -> getLocalDataSizeForRegion(regionName));
+
+ assertThat(abs(size1 - size2)).isLessThanOrEqualTo(1);
+ }
+
+ private static Integer getLocalDataSizeForRegion(String regionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Region region = cache.getRegionByPath("/" + regionName);
+ return PartitionRegionHelper.getLocalData(region).size();
+ }
+
+ private static void waitForManagerMBean() {
+ Awaitility.waitAtMost(120, TimeUnit.SECONDS).until(() -> {
+ final ManagementService service =
+ ManagementService.getManagementService(ClusterStartupRule.getCache());
+ final DistributedRegionMXBean bean =
+ service.getDistributedRegionMXBean("/" + SHARED_REGION_NAME);
+
+
+ return bean != null && bean.getMembers() != null && bean.getMembers().length > 1
+ && bean.getMemberCount() > 0
+ && service.getDistributedSystemMXBean().listRegions().length >= 2;
+ });
+ }
+
+ private Properties locatorProperties() {
+ int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOG_LEVEL, "fine");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort);
+
+ return props;
+ }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RegionChangesPersistThroughClusterConfigurationDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RegionChangesPersistThroughClusterConfigurationDUnitTest.java
new file mode 100644
index 0000000..6e1a155
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RegionChangesPersistThroughClusterConfigurationDUnitTest.java
@@ -0,0 +1,171 @@
+/*
+ * 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 org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION;
+import static org.assertj.core.api.Assertions.assertThat;
+
+import java.util.Properties;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.distributed.Locator;
+import org.apache.geode.distributed.internal.InternalConfigurationPersistenceService;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.InternalLocator;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.test.dunit.IgnoredException;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.categories.RegionsTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
+
+@Category({DistributedTest.class, RegionsTest.class}) // GEODE-973 GEODE-2009
+@SuppressWarnings("serial")
+public class RegionChangesPersistThroughClusterConfigurationDUnitTest {
+
+ @Rule
+ public GfshCommandRule gfsh = new GfshCommandRule();
+
+ @Rule
+ public ClusterStartupRule lsRule = new ClusterStartupRule();
+
+ private MemberVM locator, server1, server2;
+
+ private static final String REGION_NAME = "testRegionSharedConfigRegion";
+ private static final String REGION_PATH = "/" + REGION_NAME;
+ private static final String GROUP_NAME = "cluster";
+
+ @Before
+ public void setup() throws Exception {
+ int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ int httpPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOG_LEVEL, "fine");
+ props.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort);
+ props.setProperty(ConfigurationProperties.MAX_WAIT_TIME_RECONNECT, "5000");
+ props.setProperty(HTTP_SERVICE_PORT, "" + httpPort);
+
+ locator = lsRule.startLocatorVM(0, props);
+
+ IgnoredException
+ .addIgnoredException("Possible loss of quorum due to the loss of 1 cache processes");
+
+ gfsh.connectAndVerify(locator);
+
+ Properties serverProps = new Properties();
+ serverProps.setProperty(MCAST_PORT, "0");
+ serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true");
+ server1 = lsRule.startServerVM(1, serverProps, locator.getPort());
+ server2 = lsRule.startServerVM(2, serverProps, locator.getPort());
+
+ gfsh.executeAndAssertThat(
+ "create region --type=REPLICATE --enable-statistics=true --name=" + REGION_PATH)
+ .statusIsSuccess();
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(REGION_PATH, 2);
+
+ }
+
+ @Test
+ public void createdRegionPersistsThroughCacheConfig() {
+ locator.invoke(() -> {
+ InternalConfigurationPersistenceService sharedConfig =
+ ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService();
+
+ assertThat(sharedConfig.getConfiguration(GROUP_NAME).getCacheXmlContent())
+ .contains(REGION_NAME);
+ });
+
+ server2.forceDisconnectMember();
+
+ server2.waitTilServerFullyReconnected();
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(REGION_PATH, 2);
+
+ server2.invoke(() -> {
+ InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
+ InternalCache cache = system.getCache();
+ assertThat(cache.getRegionByPath(REGION_PATH)).isNotNull();
+ });
+ }
+
+ @Test
+ public void regionUpdatePersistsThroughClusterConfig() {
+ server2.invoke(() -> {
+ InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
+ InternalCache cache = system.getCache();
+ assertThat(cache.getRegionByPath(REGION_PATH).isEntryExpiryPossible()).isFalse();
+ });
+
+ gfsh.executeAndAssertThat(
+ "alter region --name=" + REGION_PATH + " --entry-time-to-live-expiration=45635 " +
+ "--entry-time-to-live-expiration-action=destroy")
+ .statusIsSuccess();
+
+ locator.invoke(() -> {
+ InternalConfigurationPersistenceService sharedConfig =
+ ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService();
+
+ assertThat(sharedConfig.getConfiguration(GROUP_NAME).getCacheXmlContent()).contains("45635");
+ });
+
+ server2.forceDisconnectMember();
+
+ server2.waitTilServerFullyReconnected();
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(REGION_PATH, 2);
+
+ server2.invoke(() -> {
+ InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
+ InternalCache cache = system.getCache();
+ assertThat(cache.getRegionByPath(REGION_PATH)).isNotNull();
+ assertThat(cache.getRegionByPath(REGION_PATH).isEntryExpiryPossible()).isTrue();
+ });
+ }
+
+ @Test
+ public void destroyRegionPersistsThroughClusterConfig() {
+ gfsh.executeAndAssertThat("destroy region --name=" + REGION_PATH).statusIsSuccess();
+
+ locator.invoke(() -> {
+ InternalConfigurationPersistenceService sharedConfig =
+ ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService();
+
+ assertThat(sharedConfig.getConfiguration(GROUP_NAME).getCacheXmlContent())
+ .doesNotContain(REGION_NAME);
+ });
+
+ server2.forceDisconnectMember();
+
+ server2.waitTilServerFullyReconnected();
+
+ server2.invoke(() -> {
+ InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
+ InternalCache cache = system.getCache();
+ assertThat(cache.getRegionByPath(REGION_PATH)).isNull();
+ });
+ }
+}
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RegionMembershipMBeanDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RegionMembershipMBeanDUnitTest.java
new file mode 100644
index 0000000..eb4b621
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/RegionMembershipMBeanDUnitTest.java
@@ -0,0 +1,382 @@
+/*
+ * 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 org.apache.geode.management.internal.cli.commands;
+
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
+import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.NAME;
+import static org.apache.geode.distributed.ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import org.awaitility.Awaitility;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.PartitionAttributes;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
+import org.apache.geode.test.junit.categories.DistributedTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
+
+@Category({DistributedTest.class})
+@SuppressWarnings("serial")
+public class RegionMembershipMBeanDUnitTest {
+ private static final String DATA_REGION_NAME = "GemfireDataCommandsTestRegion";
+ private static final String DATA_REGION_NAME_VM1 = "GemfireDataCommandsTestRegion_Vm1";
+ private static final String DATA_REGION_NAME_VM2 = "GemfireDataCommandsTestRegion_Vm2";
+ private static final String DATA_REGION_NAME_PATH = "/GemfireDataCommandsTestRegion";
+ private static final String DATA_REGION_NAME_VM1_PATH = "/GemfireDataCommandsTestRegion_Vm1";
+ private static final String DATA_REGION_NAME_VM2_PATH = "/GemfireDataCommandsTestRegion_Vm2";
+
+ private static final String DATA_PAR_REGION_NAME = "GemfireDataCommandsTestParRegion";
+ private static final String DATA_PAR_REGION_NAME_VM1 = "GemfireDataCommandsTestParRegion_Vm1";
+ private static final String DATA_PAR_REGION_NAME_VM2 = "GemfireDataCommandsTestParRegion_Vm2";
+ private static final String DATA_PAR_REGION_NAME_PATH = "/GemfireDataCommandsTestParRegion";
+ private static final String DATA_PAR_REGION_NAME_VM1_PATH =
+ "/GemfireDataCommandsTestParRegion_Vm1";
+ private static final String DATA_PAR_REGION_NAME_VM2_PATH =
+ "/GemfireDataCommandsTestParRegion_Vm2";
+ private static final String DATA_REGION_NAME_CHILD_1 = "ChildRegionRegion1";
+ private static final String DATA_REGION_NAME_CHILD_1_PATH =
+ "/GemfireDataCommandsTestRegion/ChildRegionRegion1";
+ private static final String DATA_REGION_NAME_CHILD_1_2 = "ChildRegionRegion12";
+ private static final String DATA_REGION_NAME_CHILD_1_2_PATH =
+ "/GemfireDataCommandsTestRegion/ChildRegionRegion1/ChildRegionRegion12";
+
+ private static final String SERIALIZATION_FILTER =
+ "org.apache.geode.management.internal.cli.**";
+
+ @Rule
+ public GfshCommandRule gfsh = new GfshCommandRule();
+
+ @Rule
+ public ClusterStartupRule cluster = new ClusterStartupRule();
+
+ private MemberVM locator, server1, server2;
+
+ @Before
+ public void before() throws Exception {
+ Properties props = locatorProperties();
+ props.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER);
+ props.setProperty(NAME, "locator");
+
+ Properties serverProps = new Properties();
+ serverProps.setProperty(SERIALIZABLE_OBJECT_FILTER, SERIALIZATION_FILTER);
+ locator = cluster.startLocatorVM(0, props);
+ server1 = cluster.startServerVM(1, serverProps, locator.getPort());
+ server2 = cluster.startServerVM(2, serverProps, locator.getPort());
+
+ gfsh.connectAndVerify(locator);
+ }
+
+ private static void setupDataRegionAndSubregions() {
+ InternalCache cache = ClusterStartupRule.getCache();
+ RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+
+ Region dataRegion = regionFactory.create(DATA_REGION_NAME);
+ assertThat(dataRegion).isNotNull();
+
+ Region dataSubRegion = regionFactory.createSubregion(dataRegion, DATA_REGION_NAME_CHILD_1);
+ assertThat(dataSubRegion).isNotNull();
+
+ dataSubRegion = regionFactory.createSubregion(dataSubRegion, DATA_REGION_NAME_CHILD_1_2);
+ assertThat(dataSubRegion).isNotNull();
+ assertThat(dataRegion).isNotNull();
+ }
+
+ private static void setupReplicatedRegion(String regionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ RegionFactory regionFactory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+
+ Region dataRegion = regionFactory.create(regionName);
+ assertThat(dataRegion).isNotNull();
+ assertThat(dataRegion.getFullPath()).contains(regionName);
+ }
+
+ private static void setupPartitionedRegion(String regionName) {
+ InternalCache cache = ClusterStartupRule.getCache();
+ PartitionAttributes partitionAttrs =
+ new PartitionAttributesFactory().setRedundantCopies(2).create();
+ RegionFactory<Object, Object> partitionRegionFactory =
+ cache.createRegionFactory(RegionShortcut.PARTITION);
+
+ partitionRegionFactory.setPartitionAttributes(partitionAttrs);
+ Region dataParRegion = partitionRegionFactory.create(regionName);
+
+ assertThat(dataParRegion).isNotNull();
+ assertThat(dataParRegion.getFullPath()).contains(regionName);
+ }
+
+ @Test
+ public void testReplicatedRegionOnOneMember() {
+ server1.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME));
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 1);
+
+ Integer memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_PATH);
+ Integer memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean).isEqualTo(1);
+ }
+
+ @Test
+ public void testMultipleReplicatedRegionsAndSubregions() {
+ server1.invoke(() -> setupDataRegionAndSubregions());
+ server1.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME_VM1));
+
+ server2.invoke(() -> setupDataRegionAndSubregions());
+ server2.invoke(() -> setupReplicatedRegion(DATA_REGION_NAME_VM2));
+
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_2_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_VM1_PATH, 1);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_VM2_PATH, 1);
+
+ Integer memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_PATH);
+ Integer memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+
+ memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_PATH);
+ memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+
+ memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_2_PATH);
+ memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_2_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+
+ memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_VM1_PATH);
+ memSizeFromFunctionCall = distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_VM1_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+
+ memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_VM2_PATH);
+ memSizeFromFunctionCall = distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_VM2_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+ }
+
+ @Test
+ public void testAddRmNewMemberWithReplicatedRegionsAndSubregions() {
+ server1.invoke(() -> setupDataRegionAndSubregions());
+ server2.invoke(() -> setupDataRegionAndSubregions());
+
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_2_PATH, 2);
+
+ Integer initialMemberSizeFromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_PATH);
+ Integer initialMemberSizeFromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_PATH);
+ assertThat(initialMemberSizeFromFunction).isEqualTo(initialMemberSizeFromMBean);
+
+ Integer initialMemberSizeChild1FromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_PATH);
+ Integer initialMemberSizeChild1FromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_PATH);
+ assertThat(initialMemberSizeChild1FromFunction).isEqualTo(initialMemberSizeChild1FromMBean);
+
+ Integer initialMemberSizeChild2FromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_2_PATH);
+ Integer initialMemberSizeChild2FromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_2_PATH);
+ assertThat(initialMemberSizeChild2FromFunction).isEqualTo(initialMemberSizeChild2FromMBean);
+
+ MemberVM server3 = cluster.startServerVM(3, locator.getPort());
+ server3.invoke(() -> setupDataRegionAndSubregions());
+
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 3);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_PATH, 3);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_2_PATH, 3);
+
+ Integer intermediateMemberSizeFromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_PATH);
+ Integer intermediateMemberSizeFromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_PATH);
+ assertThat(intermediateMemberSizeFromFunction).isEqualTo(intermediateMemberSizeFromMBean)
+ .isEqualTo(initialMemberSizeFromFunction + 1);
+
+ Integer intermediateMemberSizeChild1FromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_PATH);
+ Integer intermediateMemberSizeChild1FromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_PATH);
+ assertThat(intermediateMemberSizeChild1FromMBean)
+ .isEqualTo(intermediateMemberSizeChild1FromFunction)
+ .isEqualTo(initialMemberSizeChild1FromFunction + 1);
+
+ Integer intermediateMemberSizeChild2FromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_2_PATH);
+ Integer intermediateMemberSizeChild2FromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_2_PATH);
+ assertThat(intermediateMemberSizeChild2FromFunction)
+ .isEqualTo(intermediateMemberSizeChild2FromMBean)
+ .isEqualTo(initialMemberSizeChild2FromMBean + 1);
+
+ server3.stopMember(Boolean.TRUE);
+
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_REGION_NAME_CHILD_1_2_PATH, 2);
+
+ Integer finalMemberSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_PATH);
+ Integer finalMemberSizeFromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_PATH);
+ assertThat(finalMemberSizeFromFunction).isEqualTo(finalMemberSizeFromMBean)
+ .isEqualTo(initialMemberSizeFromFunction);
+
+ Integer finalMemberSizeChild1FromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_PATH);
+ Integer finalMemberSizeChild1FromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_PATH);
+ assertThat(finalMemberSizeChild1FromMBean).isEqualTo(finalMemberSizeChild1FromFunction)
+ .isEqualTo(initialMemberSizeChild1FromFunction);
+
+ Integer finalMemberSizeChild2FromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_REGION_NAME_CHILD_1_2_PATH);
+ Integer finalMemberSizeChild2FromFunction =
+ distributedRegionMembersSizeFromFunction(DATA_REGION_NAME_CHILD_1_2_PATH);
+ assertThat(finalMemberSizeChild2FromFunction).isEqualTo(finalMemberSizeChild2FromMBean)
+ .isEqualTo(initialMemberSizeChild2FromMBean);
+ }
+
+ @Test
+ public void testPartitionedRegionOnOneMember() {
+ server1.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 1);
+
+ Integer memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_PATH);
+ Integer memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean).isEqualTo(1);
+ }
+
+ @Test
+ public void testMultiplePartitionedRegions() {
+ server1.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+ server1.invoke(() -> setupReplicatedRegion(DATA_PAR_REGION_NAME_VM1));
+
+ server2.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+ server2.invoke(() -> setupReplicatedRegion(DATA_PAR_REGION_NAME_VM2));
+
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 2);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_VM1_PATH, 1);
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_VM2_PATH, 1);
+
+ Integer memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_PATH);
+ Integer memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+
+ memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_VM1_PATH);
+ memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_VM1_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+
+ memSizeFromMBean = distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_VM2_PATH);
+ memSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_VM2_PATH);
+ assertThat(memSizeFromFunctionCall).isEqualTo(memSizeFromMBean);
+ }
+
+ @Test
+ public void testAddRmNewMemberWithPartitionedRegions() {
+ server1.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+ server2.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 2);
+
+ Integer initialMemberSizeFromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_PATH);
+ Integer initialMemberSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_PATH);
+ assertThat(initialMemberSizeFromFunctionCall).isEqualTo(initialMemberSizeFromMBean);
+
+ MemberVM server3 = cluster.startServerVM(3, locator.getPort());
+ server3.invoke(() -> setupPartitionedRegion(DATA_PAR_REGION_NAME));
+ locator.waitUntilRegionIsReadyOnExactlyThisManyServers(DATA_PAR_REGION_NAME_PATH, 3);
+
+ Integer intermediateMemberSizeFromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_PATH);
+ Integer intermediateMemberSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_PATH);
+ assertThat(intermediateMemberSizeFromFunctionCall).isEqualTo(intermediateMemberSizeFromMBean)
+ .isEqualTo(initialMemberSizeFromMBean + 1);
+
+ server3.stopMember(Boolean.TRUE);
+
+ Integer finalMemberSizeFromMBean =
+ distributedRegionMembersSizeFromMBean(DATA_PAR_REGION_NAME_PATH);
+ Integer finalMemberSizeFromFunctionCall =
+ distributedRegionMembersSizeFromFunction(DATA_PAR_REGION_NAME_PATH);
+ assertThat(finalMemberSizeFromFunctionCall).isEqualTo(finalMemberSizeFromMBean)
+ .isEqualTo(initialMemberSizeFromFunctionCall);
+ }
+
+ private Integer distributedRegionMembersSizeFromFunction(String regionName) {
+ return locator.invoke(() -> {
+ InternalCache cache = ClusterStartupRule.getCache();
+ Set<DistributedMember> distributedMembers =
+ CliUtil.getRegionAssociatedMembers(regionName, cache, true);
+
+ return distributedMembers.size();
+ });
+ }
+
+ private Integer distributedRegionMembersSizeFromMBean(String regionPath) {
+ return locator.invoke(() -> {
+ Cache cache = ClusterStartupRule.getCache();
+
+ Awaitility.waitAtMost(20, TimeUnit.SECONDS).until(() -> {
+ DistributedRegionMXBean bean = ManagementService.getManagementService(cache)
+ .getDistributedRegionMXBean(regionPath);
+ assertThat(bean).isNotNull();
+ });
+
+ DistributedRegionMXBean bean = ManagementService.getManagementService(cache)
+ .getDistributedRegionMXBean(regionPath);
+ String[] membersName = bean.getMembers();
+ return membersName.length;
+ });
+ }
+
+ private Properties locatorProperties() {
+ int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ Properties props = new Properties();
+ props.setProperty(MCAST_PORT, "0");
+ props.setProperty(LOG_LEVEL, "fine");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort);
+
+ return props;
+ }
+}
diff --git a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
index 49694af..382a09a 100644
--- a/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
+++ b/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
@@ -16,25 +16,20 @@ package org.apache.geode.management.internal.cli.commands;
import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_ID;
import static org.apache.geode.distributed.ConfigurationProperties.DURABLE_CLIENT_TIMEOUT;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.DistributedTestUtils.getDUnitLocatorPort;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.NetworkUtils.getServerHostName;
import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import org.awaitility.Awaitility;
+import org.junit.Before;
+import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import org.apache.geode.cache.AttributesFactory;
-import org.apache.geode.cache.CacheException;
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
-import org.apache.geode.cache.Scope;
-import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.query.CqAttributesFactory;
import org.apache.geode.cache.query.CqException;
@@ -42,27 +37,25 @@ import org.apache.geode.cache.query.CqExistsException;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.RegionNotFoundException;
import org.apache.geode.cache.query.data.Portfolio;
-import org.apache.geode.cache.server.CacheServer;
-import org.apache.geode.cache30.CacheSerializableRunnable;
-import org.apache.geode.internal.cache.DistributedRegion;
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.cache.PartitionedRegion;
-import org.apache.geode.internal.cache.tier.sockets.CacheServerTestUtil;
-import org.apache.geode.management.cli.Result.Status;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResult;
import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.apache.geode.test.dunit.Host;
-import org.apache.geode.test.dunit.SerializableCallable;
-import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
+import org.apache.geode.test.dunit.rules.ClientVM;
+import org.apache.geode.test.dunit.rules.ClusterStartupRule;
+import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
import org.apache.geode.test.junit.categories.GfshTest;
+import org.apache.geode.test.junit.rules.GfshCommandRule;
-@Category({DistributedTest.class, FlakyTest.class, GfshTest.class}) // See GEODE-3530
+@Category({DistributedTest.class, GfshTest.class}) // GEODE-1705 GEODE-3404
+ // GEODE-3359
@SuppressWarnings("serial")
-public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
+public class DurableClientCommandsDUnitTest {
private static final String REGION_NAME = "stocks";
private static final String CQ1 = "cq1";
@@ -70,29 +63,49 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
private static final String CQ3 = "cq3";
private static final String CLIENT_NAME = "dc1";
- @Override
- public final void postTearDownCacheTestCase() throws Exception {
- Host.getHost(0).getVM(0).invoke(() -> CacheServerTestUtil.closeCache());
- Host.getHost(0).getVM(1).invoke(() -> CacheServerTestUtil.closeCache());
- Host.getHost(0).getVM(2).invoke(() -> CacheServerTestUtil.closeCache());
+ private MemberVM locator, server;
+
+ private ClientVM client;
+
+ @Rule
+ public GfshCommandRule gfsh = new GfshCommandRule();
+
+ @Rule
+ public ClusterStartupRule lsRule = new ClusterStartupRule();
+
+ @Before
+ public void setup() throws Exception {
+ int jmxPort = AvailablePortHelper.getRandomAvailableTCPPort();
+ Properties props = new Properties();
+ props.setProperty(LOG_LEVEL, "fine");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost");
+ props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort);
+ locator = lsRule.startLocatorVM(0, props);
+
+ int locatorPort = locator.getPort();
+ server = lsRule.startServerVM(1,
+ thisServer -> thisServer.withRegion(RegionShortcut.REPLICATE, REGION_NAME)
+ .withConnectionToLocator(locatorPort));
+
+ client = lsRule.startClientVM(2, getClientProps(CLIENT_NAME, "300"), (ccf) -> {
+ ccf.setPoolSubscriptionEnabled(true);
+ ccf.addPoolLocator("localhost", locatorPort);
+ });
+
+ gfsh.connectAndVerify(locator);
}
+
@Test
- public void testListDurableClientCqs() throws Exception {
- setupSystem();
+ public void testListDurableClientCqs() {
setupCqs();
CommandStringBuilder csb = new CommandStringBuilder(CliStrings.LIST_DURABLE_CQS);
csb.addOption(CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, CLIENT_NAME);
String commandString = csb.toString();
- writeToLog("Command String :\n ", commandString);
- CommandResult commandResult = executeCommand(commandString);
- String resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.OK.equals(commandResult.getStatus()));
- assertTrue(resultAsString.contains(CQ1));
- assertTrue(resultAsString.contains(CQ2));
- assertTrue(resultAsString.contains(CQ3));
+
+ gfsh.executeAndAssertThat(commandString).statusIsSuccess().containsOutput(CQ1)
+ .containsOutput(CQ2).containsOutput(CQ3);
closeCq(CQ1);
closeCq(CQ2);
@@ -101,19 +114,13 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
csb = new CommandStringBuilder(CliStrings.LIST_DURABLE_CQS);
csb.addOption(CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, CLIENT_NAME);
commandString = csb.toString();
- writeToLog("Command String :\n ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.ERROR.equals(commandResult.getStatus()));
String errorMessage =
CliStrings.format(CliStrings.LIST_DURABLE_CQS__NO__CQS__FOR__CLIENT, CLIENT_NAME);
- assertTrue(resultAsString.contains(errorMessage));
+ gfsh.executeAndAssertThat(commandString).statusIsError().containsOutput(errorMessage);
}
@Test
- public void testCloseDurableClients() throws Exception {
- setupSystem();
+ public void testCloseDurableClients() {
setupCqs();
closeDurableClient();
@@ -121,84 +128,53 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
csb.addOption(CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, CLIENT_NAME);
String commandString = csb.toString();
- long giveUpTime = System.currentTimeMillis() + 20000;
- CommandResult commandResult = null;
- String resultAsString = null;
-
- do {
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- } while (resultAsString.contains("Cannot close a running durable client")
- && giveUpTime > System.currentTimeMillis());
-
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.OK.equals(commandResult.getStatus()));
-
- // Execute again to see the error condition
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.ERROR.equals(commandResult.getStatus()));
+ Awaitility.waitAtMost(20, TimeUnit.SECONDS).until(() -> {
+ gfsh.executeAndAssertThat(commandString).statusIsSuccess();
+ });
+
String errorMessage = CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, CLIENT_NAME);
- assertTrue(resultAsString.contains(errorMessage));
+ gfsh.executeAndAssertThat(commandString).statusIsError().containsOutput(errorMessage);
}
@Test
- public void testCloseDurableCQ() throws Exception {
- setupSystem();
+ public void testCloseDurableCQ() {
setupCqs();
-
closeDurableClient();
CommandStringBuilder csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CQS);
csb.addOption(CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID, CLIENT_NAME);
csb.addOption(CliStrings.CLOSE_DURABLE_CQS__NAME, CQ1);
String commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- CommandResult commandResult = executeCommand(commandString);
- String resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.OK.equals(commandResult.getStatus()));
+
+ gfsh.executeAndAssertThat(commandString).statusIsSuccess();
csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CQS);
csb.addOption(CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID, CLIENT_NAME);
csb.addOption(CliStrings.CLOSE_DURABLE_CQS__NAME, CQ1);
commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result : ", resultAsString);
- assertTrue(Status.ERROR.equals(commandResult.getStatus()));
+ gfsh.executeAndAssertThat(commandString).statusIsError();
}
@Test
- public void testCountSubscriptionQueueSize() throws Exception {
- setupSystem();
+ public void testCountSubscriptionQueueSize() {
setupCqs();
+
doPuts(REGION_NAME, Host.getHost(0).getVM(1));
CommandStringBuilder csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
String commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- CommandResult commandResult = executeCommand(commandString);
- String resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.OK.equals(commandResult.getStatus()));
- assertTrue(resultAsString.contains("4"));
+
+ gfsh.executeAndAssertThat(commandString).statusIsSuccess().containsOutput("4");
+
csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, CQ3);
commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.OK.equals(commandResult.getStatus()));
+
+ gfsh.executeAndAssertThat(commandString).statusIsSuccess();
// CLOSE all the cqs
closeCq(CQ1);
@@ -210,23 +186,16 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME, CQ1);
commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.ERROR.equals(commandResult.getStatus()));
+
String errorMessage = CliStrings
.format(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE_CQ_NOT_FOUND, CLIENT_NAME, CQ1);
- assertTrue(resultAsString.contains(errorMessage));
+ gfsh.executeAndAssertThat(commandString).statusIsError().containsOutput(errorMessage);
csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.OK.equals(commandResult.getStatus()));
+
+ gfsh.executeAndAssertThat(commandString).statusIsSuccess();
// Disconnect the client
closeDurableClient();
@@ -234,48 +203,19 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
// Close the client
csb = new CommandStringBuilder(CliStrings.CLOSE_DURABLE_CLIENTS);
csb.addOption(CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, CLIENT_NAME);
- commandString = csb.toString();
+ String commandString1 = csb.toString();
- // since it can take the server a bit to know that the client has disconnected
- // we loop here
- long giveUpTime = System.currentTimeMillis() + 20000;
- do {
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- } while (resultAsString.contains("Cannot close a running durable client")
- && giveUpTime > System.currentTimeMillis());
-
- writeToLog("Command Result :\n", resultAsString);
- assertTrue("failed executing" + commandString + "; result = " + resultAsString,
- Status.OK.equals(commandResult.getStatus()));
+ Awaitility.waitAtMost(20, TimeUnit.SECONDS).until(() -> {
+ gfsh.executeAndAssertThat(commandString1).statusIsSuccess();
+ });
csb = new CommandStringBuilder(CliStrings.COUNT_DURABLE_CQ_EVENTS);
csb.addOption(CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, CLIENT_NAME);
commandString = csb.toString();
- writeToLog("Command String : ", commandString);
- commandResult = executeCommand(commandString);
- resultAsString = commandResultToString(commandResult);
- writeToLog("Command Result :\n", resultAsString);
- assertTrue(Status.ERROR.equals(commandResult.getStatus()));
- assertTrue(resultAsString
- .contains(CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, CLIENT_NAME)));
- }
- private void writeToLog(String text, String resultAsString) {
- getLogWriter().info(getUniqueName() + ": " + text + "\n" + resultAsString);
- }
-
- private void setupSystem() throws Exception {
- disconnectAllFromDS();
- setUpJmxManagerOnVm0ThenConnect(getServerProperties());
-
- VM manager = Host.getHost(0).getVM(0);
- VM server1 = Host.getHost(0).getVM(1);
- VM client1 = Host.getHost(0).getVM(2);
+ errorMessage = CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, CLIENT_NAME);
- int listeningPort = startCacheServer(server1, 0, false, REGION_NAME);
- startDurableClient(client1, server1, listeningPort, CLIENT_NAME, "300");
+ gfsh.executeAndAssertThat(commandString).statusIsError().containsOutput(errorMessage);
}
/**
@@ -284,94 +224,31 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
* @param cqName , Name of the cq which is to be close.
*/
private void closeCq(final String cqName) {
- VM vm2 = Host.getHost(0).getVM(2);
- vm2.invoke(new SerializableCallable() {
- @Override
- public Object call() {
- QueryService qs = getCache().getQueryService();
- CqAttributesFactory cqAf = new CqAttributesFactory();
-
- try {
- qs.getCq(cqName).close();
- } catch (CqException e) {
- throw new RuntimeException(e);
- }
-
- return true;
+ client.invoke(() -> {
+ QueryService qs =
+ InternalDistributedSystem.getConnectedInstance().getCache().getQueryService();
+
+ try {
+ qs.getCq(cqName).close();
+ } catch (CqException e) {
+ throw new RuntimeException(e);
}
});
}
private void setupCqs() {
- VM vm2 = Host.getHost(0).getVM(2);
-
- vm2.invoke(new SerializableCallable() {
- @Override
- public Object call() {
- QueryService qs = getCache().getQueryService();
- CqAttributesFactory cqAf = new CqAttributesFactory();
-
- try {
- qs.newCq(CQ1, "select * from /" + REGION_NAME, cqAf.create(), true).execute();
- qs.newCq(CQ2, "select * from /" + REGION_NAME + " where id = 1", cqAf.create(), true)
- .execute();
- qs.newCq(CQ3, "select * from /" + REGION_NAME + " where id > 2", cqAf.create(), true)
- .execute();
- } catch (CqException | CqExistsException | RegionNotFoundException e) {
- throw new RuntimeException(e);
- }
-
- return true;
- }
- });
- }
-
- private int startCacheServer(final VM serverVM, final int port, final boolean createPR,
- final String regionName) {
- return serverVM.invoke(() -> {
- getSystem(getServerProperties());
-
- InternalCache cache = getCache();
- AttributesFactory factory = new AttributesFactory();
-
- if (createPR) {
- PartitionAttributesFactory paf = new PartitionAttributesFactory();
- paf.setRedundantCopies(1);
- paf.setTotalNumBuckets(11);
- factory.setPartitionAttributes(paf.create());
- } else {
- factory.setScope(Scope.DISTRIBUTED_ACK);
- factory.setDataPolicy(DataPolicy.REPLICATE);
- }
-
- Region region = createRootRegion(regionName, factory.create());
- if (createPR) {
- assertTrue(region instanceof PartitionedRegion);
- } else {
- assertTrue(region instanceof DistributedRegion);
- }
-
- CacheServer cacheServer = getCache().addCacheServer();
- cacheServer.setPort(port);
- cacheServer.start();
-
- return cacheServer.getPort();
- });
- }
-
- private void startDurableClient(final VM clientVM, final VM serverVM, final int port,
- final String durableClientId, final String durableClientTimeout) {
- clientVM.invoke(new CacheSerializableRunnable("Start client") {
- @Override
- public void run2() throws CacheException {
- Properties props = getClientProps(durableClientId, durableClientTimeout);
- getSystem(props);
-
- ClientCacheFactory ccf = new ClientCacheFactory(props);
- ccf.addPoolServer(getServerHostName(serverVM.getHost()), port);
- ccf.setPoolSubscriptionEnabled(true);
-
- ClientCache cache = getClientCache(ccf);
+ client.invoke(() -> {
+ QueryService qs = ClusterStartupRule.getClientCache().getQueryService();
+ CqAttributesFactory cqAf = new CqAttributesFactory();
+
+ try {
+ qs.newCq(CQ1, "select * from /" + REGION_NAME, cqAf.create(), true).execute();
+ qs.newCq(CQ2, "select * from /" + REGION_NAME + " where id = 1", cqAf.create(), true)
+ .execute();
+ qs.newCq(CQ3, "select * from /" + REGION_NAME + " where id > 2", cqAf.create(), true)
+ .execute();
+ } catch (CqException | CqExistsException | RegionNotFoundException e) {
+ throw new RuntimeException(e);
}
});
}
@@ -380,60 +257,43 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
* Does few puts on the region on the server
*/
private void doPuts(final String regionName, final VM serverVM) {
- serverVM.invoke(new SerializableRunnable() {
- @Override
- public void run() {
- InternalCache cache = getCache();
- Region region = cache.getRegion(regionName);
-
- Portfolio p1 = new Portfolio();
- p1.ID = 1;
- p1.names = new String[] {"AAPL", "VMW"};
-
- Portfolio p2 = new Portfolio();
- p2.ID = 2;
- p2.names = new String[] {"EMC", "IBM"};
-
- Portfolio p3 = new Portfolio();
- p3.ID = 5;
- p3.names = new String[] {"DOW", "TON"};
-
- Portfolio p4 = new Portfolio();
- p4.ID = 5;
- p4.names = new String[] {"ABC", "EBAY"};
-
- region.put("p1", p1);
- region.put("p2", p2);
- region.put("p3", p3);
- region.put("p4", p4);
- }
+ serverVM.invoke(() -> {
+ InternalCache cache = InternalDistributedSystem.getConnectedInstance().getCache();
+ Region region = cache.getRegion(regionName);
+
+ Portfolio p1 = new Portfolio();
+ p1.ID = 1;
+ p1.names = new String[] {"AAPL", "VMW"};
+
+ Portfolio p2 = new Portfolio();
+ p2.ID = 2;
+ p2.names = new String[] {"EMC", "IBM"};
+
+ Portfolio p3 = new Portfolio();
+ p3.ID = 5;
+ p3.names = new String[] {"DOW", "TON"};
+
+ Portfolio p4 = new Portfolio();
+ p4.ID = 5;
+ p4.names = new String[] {"ABC", "EBAY"};
+
+ region.put("p1", p1);
+ region.put("p2", p2);
+ region.put("p3", p3);
+ region.put("p4", p4);
});
}
- // Closes the durable-client from the client side.
private void closeDurableClient() {
- VM clientVM = Host.getHost(0).getVM(2);
-
- clientVM.invoke(new CacheSerializableRunnable("Stop client") {
- @Override
- public void run2() throws CacheException {
- ClientCacheFactory.getAnyInstance().close(true);
- }
- });
+ client.invoke(() -> ClientCacheFactory.getAnyInstance().close(true));
}
protected Properties getClientProps(String durableClientId, String durableClientTimeout) {
Properties config = new Properties();
config.setProperty(MCAST_PORT, "0");
- config.setProperty(LOCATORS, "");
config.setProperty(DURABLE_CLIENT_ID, durableClientId);
config.setProperty(DURABLE_CLIENT_TIMEOUT, String.valueOf(durableClientTimeout));
return config;
}
- protected Properties getServerProperties() {
- Properties config = new Properties();
- config.setProperty(LOCATORS, "localhost[" + getDUnitLocatorPort() + "]");
- return config;
- }
}
diff --git a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java
index 5639258..5cf8e13 100644
--- a/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java
+++ b/geode-web/src/test/java/org/apache/geode/management/internal/cli/commands/CommandOverHttpDUnitTest.java
@@ -20,19 +20,19 @@ import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
+import org.apache.geode.internal.lang.SystemPropertyHelper;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.GfshTest;
import org.apache.geode.test.junit.categories.SecurityTest;
import org.apache.geode.test.junit.runners.SuiteRunner;
-/**
- * Only commands that extends CliCommandTestBase needs to be in this test suite
- */
@Category({DistributedTest.class, SecurityTest.class, GfshTest.class})
@RunWith(SuiteRunner.class)
-@Suite.SuiteClasses({GemfireDataCommandsDUnitTest.class})
+@Suite.SuiteClasses({GemfireDataCommandsDUnitTest.class,
+ RebalanceCommandDUnitTest.class, RegionMembershipMBeanDUnitTest.class,
+ QueryCommandDUnitTest.class})
public class CommandOverHttpDUnitTest {
@ClassRule
public static ProvideSystemProperty provideSystemProperty =
- new ProvideSystemProperty(CliCommandTestBase.USE_HTTP_SYSTEM_PROPERTY, "true");
+ new ProvideSystemProperty(SystemPropertyHelper.USE_HTTP_SYSTEM_PROPERTY, "true");
}