You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by kl...@apache.org on 2017/08/13 22:45:53 UTC
[01/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Repository: geode
Updated Branches:
refs/heads/develop 44fb3f299 -> 645a32d04
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandUnitTest.java
deleted file mode 100644
index 3550638..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandUnitTest.java
+++ /dev/null
@@ -1,59 +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.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.spy;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.test.dunit.rules.GfshParserRule;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-@Category(UnitTest.class)
-public class StartLocatorCommandUnitTest {
- @Rule
- public GfshParserRule gfshRule = new GfshParserRule();
-
- private StartLocatorCommand command;
- private CommandResult result;
-
- @Before
- public void before() throws Exception {
- command = spy(StartLocatorCommand.class);
- }
-
- @Test
- public void failsOnMissingGemFirePropertiesFile() throws Exception {
- result =
- gfshRule.executeCommandWithInstance(command, "start locator --properties-file=notExist");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains("notExist could not be found");
- }
-
- @Test
- public void failsOnMissingGemFireSecurityPropertiesFile() throws Exception {
- result = gfshRule.executeCommandWithInstance(command,
- "start locator --security-properties-file=notExist");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains("notExist could not be found");
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberCommandTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberCommandTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberCommandTest.java
deleted file mode 100644
index 911e752..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartMemberCommandTest.java
+++ /dev/null
@@ -1,335 +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.HTTP_SERVICE_BIND_ADDRESS;
-import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
-import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
-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.START_DEV_REST_API;
-import static org.assertj.core.api.Java6Assertions.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Properties;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.StringUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
-import org.junit.rules.TestName;
-
-import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.internal.util.IOUtils;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-@Category(UnitTest.class)
-public class StartMemberCommandTest {
- private StartMemberCommand startMemberCommand;
-
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- @Rule
- public TestName testName = new TestName();
-
- @Before
- public void before() {
- startMemberCommand = new StartMemberCommand();
- }
-
- @Test
- public void testAddGemFirePropertyFileToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFirePropertyFile(commandLine, null);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFirePropertyFile(commandLine, null);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFirePropertyFile(commandLine, null);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFirePropertyFile(commandLine, new File("/path/to/gemfire.properties"));
- assertFalse(commandLine.isEmpty());
- assertTrue(commandLine.contains("-DgemfirePropertyFile=/path/to/gemfire.properties"));
- }
-
- @Test
- public void testAddGemFireSystemPropertiesToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFireSystemProperties(commandLine, new Properties());
- assertTrue(commandLine.isEmpty());
-
- final Properties gemfireProperties = new Properties();
- gemfireProperties.setProperty(LOCATORS, "localhost[11235]");
- gemfireProperties.setProperty(LOG_LEVEL, "config");
- gemfireProperties.setProperty(LOG_FILE, org.apache.commons.lang.StringUtils.EMPTY);
- gemfireProperties.setProperty(MCAST_PORT, "0");
- gemfireProperties.setProperty(NAME, "machine");
- startMemberCommand.addGemFireSystemProperties(commandLine, gemfireProperties);
-
- assertFalse(commandLine.isEmpty());
- assertEquals(4, commandLine.size());
-
- for (final String propertyName : gemfireProperties.stringPropertyNames()) {
- final String propertyValue = gemfireProperties.getProperty(propertyName);
- if (org.apache.commons.lang.StringUtils.isBlank(propertyValue)) {
- for (final String systemProperty : commandLine) {
- assertFalse(systemProperty.startsWith(
- "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=")));
- }
- } else {
- assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX
- + "".concat(propertyName).concat("=").concat(propertyValue)));
- }
- }
- }
-
- @Test
- public void testAddGemFireSystemPropertiesToCommandLineWithRestAPI() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFireSystemProperties(commandLine, new Properties());
- assertTrue(commandLine.isEmpty());
- final Properties gemfireProperties = new Properties();
- gemfireProperties.setProperty(LOCATORS, "localhost[11235]");
- gemfireProperties.setProperty(LOG_LEVEL, "config");
- gemfireProperties.setProperty(LOG_FILE, "");
- gemfireProperties.setProperty(MCAST_PORT, "0");
- gemfireProperties.setProperty(NAME, "machine");
- gemfireProperties.setProperty(START_DEV_REST_API, "true");
- gemfireProperties.setProperty(HTTP_SERVICE_PORT, "8080");
- gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, "localhost");
-
- startMemberCommand.addGemFireSystemProperties(commandLine, gemfireProperties);
-
- assertFalse(commandLine.isEmpty());
- assertEquals(7, commandLine.size());
-
- for (final String propertyName : gemfireProperties.stringPropertyNames()) {
- final String propertyValue = gemfireProperties.getProperty(propertyName);
- if (StringUtils.isBlank(propertyValue)) {
- for (final String systemProperty : commandLine) {
- assertFalse(systemProperty.startsWith(
- "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=")));
- }
- } else {
- assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX
- + "".concat(propertyName).concat("=").concat(propertyValue)));
- }
- }
- }
-
- @Test
- public void testAddInitialHeapToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addInitialHeap(commandLine, null);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addInitialHeap(commandLine, org.apache.commons.lang.StringUtils.EMPTY);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addInitialHeap(commandLine, " ");
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addInitialHeap(commandLine, "512M");
- assertFalse(commandLine.isEmpty());
- assertEquals("-Xms512M", commandLine.get(0));
- }
-
- @Test
- public void testAddJvmArgumentsAndOptionsToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addJvmArgumentsAndOptions(commandLine, null);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addJvmArgumentsAndOptions(commandLine, new String[] {});
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addJvmArgumentsAndOptions(commandLine,
- new String[] {"-DmyProp=myVal", "-d64", "-server", "-Xprof"});
- assertFalse(commandLine.isEmpty());
- assertEquals(4, commandLine.size());
- assertEquals("-DmyProp=myVal", commandLine.get(0));
- assertEquals("-d64", commandLine.get(1));
- assertEquals("-server", commandLine.get(2));
- assertEquals("-Xprof", commandLine.get(3));
- }
-
- @Test
- public void testAddMaxHeapToCommandLine() {
- final List<String> commandLine = new ArrayList<>();
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addMaxHeap(commandLine, null);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addMaxHeap(commandLine, org.apache.commons.lang.StringUtils.EMPTY);
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addMaxHeap(commandLine, " ");
- assertTrue(commandLine.isEmpty());
- startMemberCommand.addMaxHeap(commandLine, "1024M");
- assertFalse(commandLine.isEmpty());
- assertEquals(3, commandLine.size());
- assertEquals("-Xmx1024M", commandLine.get(0));
- assertEquals("-XX:+UseConcMarkSweepGC", commandLine.get(1));
- assertEquals(
- "-XX:CMSInitiatingOccupancyFraction=" + StartMemberCommand.CMS_INITIAL_OCCUPANCY_FRACTION,
- commandLine.get(2));
- }
-
- @Test(expected = AssertionError.class)
- public void testReadPidWithNull() {
- try {
- startMemberCommand.readPid(null);
- } catch (AssertionError expected) {
- assertEquals("The file from which to read the process ID (pid) cannot be null!",
- expected.getMessage());
- throw expected;
- }
- }
-
- @Test
- public void testReadPidWithNonExistingFile() {
- assertEquals(StartMemberCommand.INVALID_PID,
- startMemberCommand.readPid(new File("/path/to/non_existing/pid.file")));
- }
-
- @Test
- public void testGetSystemClasspath() {
- assertEquals(System.getProperty("java.class.path"), startMemberCommand.getSystemClasspath());
- }
-
- @Test
- public void testToClasspath() {
- final boolean EXCLUDE_SYSTEM_CLASSPATH = false;
- final boolean INCLUDE_SYSTEM_CLASSPATH = true;
- String[] jarFilePathnames =
- {"/path/to/user/libs/A.jar", "/path/to/user/libs/B.jar", "/path/to/user/libs/C.jar"};
- String[] userClasspaths = {"/path/to/classes:/path/to/libs/1.jar:/path/to/libs/2.jar",
- "/path/to/ext/libs/1.jar:/path/to/ext/classes:/path/to/ext/lib/10.jar"};
- String expectedClasspath = StartMemberCommand.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
- .concat(toClasspath(userClasspaths)).concat(File.pathSeparator)
- .concat(toClasspath(jarFilePathnames));
- assertEquals(expectedClasspath,
- startMemberCommand.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, jarFilePathnames, userClasspaths));
- expectedClasspath = StartMemberCommand.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
- .concat(toClasspath(userClasspaths)).concat(File.pathSeparator)
- .concat(System.getProperty("java.class.path")).concat(File.pathSeparator)
- .concat(toClasspath(jarFilePathnames));
- assertEquals(expectedClasspath,
- startMemberCommand.toClasspath(INCLUDE_SYSTEM_CLASSPATH, jarFilePathnames, userClasspaths));
- expectedClasspath = StartMemberCommand.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
- .concat(System.getProperty("java.class.path"));
- assertEquals(expectedClasspath,
- startMemberCommand.toClasspath(INCLUDE_SYSTEM_CLASSPATH, null, (String[]) null));
- assertEquals(StartMemberCommand.GEODE_JAR_PATHNAME,
- startMemberCommand.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, null, (String[]) null));
- assertEquals(StartMemberCommand.GEODE_JAR_PATHNAME,
- startMemberCommand.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, new String[0], ""));
- }
-
- @Test
- public void testToClassPathOrder() {
- String userClasspathOne = "/path/to/user/lib/a.jar:/path/to/user/classes";
- String userClasspathTwo =
- "/path/to/user/lib/x.jar:/path/to/user/lib/y.jar:/path/to/user/lib/z.jar";
-
- String expectedClasspath = startMemberCommand.getGemFireJarPath().concat(File.pathSeparator)
- .concat(userClasspathOne).concat(File.pathSeparator).concat(userClasspathTwo)
- .concat(File.pathSeparator).concat(System.getProperty("java.class.path"))
- .concat(File.pathSeparator).concat(StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME)
- .concat(File.pathSeparator).concat(StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME);
-
- String actualClasspath =
- startMemberCommand.toClasspath(true,
- new String[] {StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME,
- StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME},
- userClasspathOne, userClasspathTwo);
-
- assertEquals(expectedClasspath, actualClasspath);
- }
-
- @Test
- public void workingDirDefaultsToMemberName() {
- String workingDir = startMemberCommand.resolveWorkingDir(null, "server1");
- assertThat(new File(workingDir)).exists();
- assertThat(workingDir).endsWith("server1");
- }
-
- @Test
- public void workingDirGetsCreatedIfNecessary() throws Exception {
- File workingDir = temporaryFolder.newFolder("foo");
- FileUtils.deleteQuietly(workingDir);
- String workingDirString = workingDir.getAbsolutePath();
- String resolvedWorkingDir = startMemberCommand.resolveWorkingDir(workingDirString, "server1");
- assertThat(new File(resolvedWorkingDir)).exists();
- assertThat(workingDirString).endsWith("foo");
- }
-
- @Test
- public void testWorkingDirWithRelativePath() throws Exception {
- Path relativePath = Paths.get("some").resolve("relative").resolve("path");
- assertThat(relativePath.isAbsolute()).isFalse();
- String resolvedWorkingDir =
- startMemberCommand.resolveWorkingDir(relativePath.toString(), "server1");
- assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString());
- }
-
-
- @Test
- public void testReadPid() throws IOException {
- final int expectedPid = 12345;
- File folder = temporaryFolder.newFolder();
- File pidFile =
- new File(folder, getClass().getSimpleName() + "_" + testName.getMethodName() + ".pid");
- assertTrue(pidFile.createNewFile());
- pidFile.deleteOnExit();
- writePid(pidFile, expectedPid);
-
- final int actualPid = startMemberCommand.readPid(pidFile);
-
- assertEquals(expectedPid, actualPid);
- }
-
- private String toClasspath(final String... jarFilePathnames) {
- StringBuilder classpath = new StringBuilder(StringUtils.EMPTY);
- if (jarFilePathnames != null) {
- for (final String jarFilePathname : jarFilePathnames) {
- classpath.append((classpath.length() == 0) ? StringUtils.EMPTY : File.pathSeparator);
- classpath.append(jarFilePathname);
- }
- }
- return classpath.toString();
- }
-
- private void writePid(final File pidFile, final int pid) throws IOException {
- final FileWriter fileWriter = new FileWriter(pidFile, false);
- fileWriter.write(String.valueOf(pid));
- fileWriter.write("\n");
- fileWriter.flush();
- IOUtils.close(fileWriter);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandUnitTest.java
deleted file mode 100644
index 41a6eb8..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandUnitTest.java
+++ /dev/null
@@ -1,78 +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.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.test.dunit.rules.GfshParserRule;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-@Category(UnitTest.class)
-public class StartServerCommandUnitTest {
- @Rule
- public GfshParserRule gfshRule = new GfshParserRule();
-
- private StartServerCommand command;
- private CommandResult result;
-
- @Before
- public void before() throws Exception {
- command = spy(StartServerCommand.class);
- Gfsh gfsh = mock(Gfsh.class);
- when(command.getGfsh()).thenReturn(gfsh);
- }
-
- @Test
- public void failsFastOnMissingCacheXmlFile() throws Exception {
- result = gfshRule.executeCommandWithInstance(command, "start server --cache-xml-file=notExist");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains("notExist could not be found.");
- }
-
- @Test
- public void failsFastOnMissingGemFirePropertiesFile() throws Exception {
- result =
- gfshRule.executeCommandWithInstance(command, "start server --properties-file=notExist");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains("notExist could not be found.");
- }
-
- @Test
- public void failsFastOnMissingGemFireSecurityPropertiesFile() throws Exception {
- result = gfshRule.executeCommandWithInstance(command,
- "start server --security-properties-file=notExist");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains("notExist could not be found.");
- }
-
- @Test
- public void failsFastOnMissingPassword() throws Exception {
- result = gfshRule.executeCommandWithInstance(command, "start server --user=test");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains("password must be specified.");
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorCommandUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorCommandUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorCommandUnitTest.java
deleted file mode 100644
index 4c2dbdb..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/StatusLocatorCommandUnitTest.java
+++ /dev/null
@@ -1,53 +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.assertj.core.api.Assertions.assertThat;
-import static org.mockito.Mockito.spy;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.commands.lifecycle.StatusLocatorCommand;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CommandResult;
-import org.apache.geode.test.dunit.rules.GfshParserRule;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-@Category(UnitTest.class)
-public class StatusLocatorCommandUnitTest {
- @Rule
- public GfshParserRule gfshRule = new GfshParserRule();
-
- private StatusLocatorCommand command;
-
- @Before
- public void before() throws Exception {
- command = spy(StatusLocatorCommand.class);
- }
-
- @Test
- public void usesMemberNameIDWhenGfshIsNotConnected() {
- CommandResult result =
- gfshRule.executeCommandWithInstance(command, "status locator --name=myLocator");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains(
- CliStrings.format(CliStrings.STATUS_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Locator"));
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommandUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommandUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommandUnitTest.java
deleted file mode 100644
index 8b79444..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommandUnitTest.java
+++ /dev/null
@@ -1,74 +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.lifecycle;
-
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.management.cli.Result;
-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.shell.Gfsh;
-import org.apache.geode.test.dunit.rules.GfshParserRule;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-@Category(UnitTest.class)
-public class StopLocatorCommandUnitTest {
- @Rule
- public GfshParserRule gfshRule = new GfshParserRule();
-
- private StopLocatorCommand stopLocatorCommand;
- private CommandResult result;
- private Gfsh gfsh;
-
- @Before
- public void before() throws Exception {
- stopLocatorCommand = spy(StopLocatorCommand.class);
- gfsh = mock(Gfsh.class);
- }
-
- @Test
- public void usesMemberNameIDWhenNotConnected() {
- when(stopLocatorCommand.isConnectedAndReady()).thenReturn(false);
- result =
- gfshRule.executeCommandWithInstance(stopLocatorCommand, "stop locator --name=myLocator");
- assertThat(result.getStatus()).isEqualTo(Result.Status.ERROR);
- assertThat(result.toString()).contains(
- CliStrings.format(CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Locator"));
- }
-
- @Test
- public void usesMemberNameIDWhenConnected() throws IOException {
- when(stopLocatorCommand.isConnectedAndReady()).thenReturn(true);
- when(gfsh.isConnectedAndReady()).thenReturn(true);
- doReturn(null).when(stopLocatorCommand).getMemberMXBean(anyString());
- result = gfshRule.executeCommandWithInstance(stopLocatorCommand,
- "stop locator --name=invalidLocator");
- assertThat(result.toString()).contains(CliStrings.format(
- CliStrings.STOP_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE, "invalidLocator"));
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
index e44465f..48ad499 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/help/HelperIntegrationTest.java
@@ -15,22 +15,16 @@
package org.apache.geode.management.internal.cli.help;
-import static org.apache.geode.management.internal.cli.i18n.CliStrings.HINT__MSG__TOPICS_AVAILABLE;
-import static org.apache.geode.management.internal.cli.i18n.CliStrings.HINT__MSG__UNKNOWN_TOPIC;
-import static org.apache.geode.management.internal.cli.i18n.CliStrings.TOPIC_CLIENT__DESC;
import static org.assertj.core.api.Assertions.assertThat;
-import java.lang.reflect.Method;
-
+import org.apache.geode.management.internal.cli.commands.GfshHelpCommands;
+import org.apache.geode.test.junit.categories.IntegrationTest;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.springframework.shell.core.annotation.CliCommand;
-import org.apache.geode.management.internal.cli.commands.GfshHelpCommand;
-import org.apache.geode.management.internal.cli.commands.GfshHintCommand;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.test.junit.categories.IntegrationTest;
+import java.lang.reflect.Method;
@Category(IntegrationTest.class)
public class HelperIntegrationTest {
@@ -39,20 +33,8 @@ public class HelperIntegrationTest {
@BeforeClass
public static void beforeClass() {
helper = new Helper();
- }
-
- private void getHelpCommand() {
- Method[] methods = GfshHelpCommand.class.getMethods();
- for (Method method : methods) {
- CliCommand cliCommand = method.getDeclaredAnnotation(CliCommand.class);
- if (cliCommand != null) {
- helper.addCommand(cliCommand, method);
- }
- }
- }
-
- private void getHintCommand() {
- Method[] methods = GfshHintCommand.class.getMethods();
+ // use GfshHelpCommand for testing
+ Method[] methods = GfshHelpCommands.class.getMethods();
for (Method method : methods) {
CliCommand cliCommand = method.getDeclaredAnnotation(CliCommand.class);
if (cliCommand != null) {
@@ -63,52 +45,19 @@ public class HelperIntegrationTest {
@Test
public void testHelpWithNoInput() {
- getHelpCommand();
- String testNoInput = helper.getHelp(null, -1);
- String[] helpLines = testNoInput.split("\n");
- assertThat(helpLines).hasSize(2);
+ String test = helper.getHelp(null, -1);
+ String[] helpLines = test.split("\n");
+ assertThat(helpLines).hasSize(4);
assertThat(helpLines[0]).isEqualTo("help (Available)");
- assertThat(helpLines[1]).isEqualTo(CliStrings.HELP__HELP);
+ assertThat(helpLines[2]).isEqualTo("hint (Available)");
}
@Test
public void testHelpWithInput() {
- getHelpCommand();
- String testInput = helper.getHelp("help", -1);
- String[] helpLines = testInput.split("\n");
+ String test = helper.getHelp("help", -1);
+ String[] helpLines = test.split("\n");
assertThat(helpLines).hasSize(12);
assertThat(helpLines[0]).isEqualTo("NAME");
assertThat(helpLines[1]).isEqualTo("help");
}
-
- @Test
- public void testHelpWithInvalidInput() {
- getHelpCommand();
- String testInvalidInput = helper.getHelp("InvalidTopic", -1);
- assertThat(testInvalidInput).isEqualTo("no help exists for this command.");
- }
-
- @Test
- public void testHintWithNoInput() {
- getHintCommand();
- String testNoInput = helper.getHint(null);
- String[] hintLines = testNoInput.split("\n");
- assertThat(hintLines).hasSize(21);
- assertThat(hintLines[0]).isEqualTo(HINT__MSG__TOPICS_AVAILABLE);
- }
-
- @Test
- public void testHintWithInput() {
- getHintCommand();
- String testInput = helper.getHint("Client");
- assertThat(testInput).contains(TOPIC_CLIENT__DESC);
- }
-
- @Test
- public void testHintWithInvalidInput() {
- getHintCommand();
- String testInvalidInput = helper.getHint("InvalidTopic");
- assertThat(testInvalidInput)
- .isEqualTo(CliStrings.format(HINT__MSG__UNKNOWN_TOPIC, "InvalidTopic"));
- }
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
index 3aca001..f380d88 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/security/TestCommand.java
@@ -123,12 +123,12 @@ public class TestCommand {
createTestCommand("list clients", clusterRead);
createTestCommand("describe client --clientID=172.16.196.144", clusterRead);
- // AlterRuntimeConfigCommand, DescribeConfigCommand, ExportConfigCommand (config commands)
+ // ConfigCommands
createTestCommand("alter runtime", clusterManage);
createTestCommand("describe config --member=Member1", clusterRead);
createTestCommand("export config --member=member1", clusterRead);
- // CreateRegionCommand, AlterRegionCommand, DestroyRegionCommand
+ // CreateAlterDestroyRegionCommands
createTestCommand("alter region --name=RegionA --eviction-max=5000", regionAManage);
createTestCommand("create region --name=region12 --type=REPLICATE", dataManage);
createTestCommand("create region --name=region123 --type=PARTITION_PERSISTENT", dataManage,
@@ -171,30 +171,28 @@ public class TestCommand {
createTestCommand("alter disk-store --name=foo --region=xyz --disk-dirs=bar");
createTestCommand("destroy disk-store --name=foo", clusterManageDisk);
- // CloseDurableClientCommand, CloseDurableCQsCommand, CountDurableCQEventsCommand,
- // ListDurableClientCQsCommand
+ // DurableClientCommands
createTestCommand("close durable-client --durable-client-id=client1", clusterManageQuery);
createTestCommand("close durable-cq --durable-client-id=client1 --durable-cq-name=cq1",
clusterManageQuery);
createTestCommand("show subscription-queue-size --durable-client-id=client1", clusterRead);
createTestCommand("list durable-cqs --durable-client-id=client1", clusterRead);
- // ExportImportSharedConfigurationCommands
+ // ExportIMportSharedConfigurationCommands
createTestCommand("export cluster-configuration --zip-file-name=mySharedConfig.zip",
clusterRead);
createTestCommand("import cluster-configuration --zip-file-name=value.zip", clusterManage);
- // DestroyFunctionCommand, ExecuteFunctionCommand, ListFunctionCommand
- createTestCommand("destroy function --id=InterestCalculations", dataManage);
+ // FunctionCommands
+ // createTestCommand("destroy function --id=InterestCalculations", dataManage);
createTestCommand("execute function --id=InterestCalculations --groups=Group1", dataWrite);
createTestCommand("list functions", clusterRead);
- // GfshHelpCommand, GfshHintCommand
+ // GfshHelpCommands
createTestCommand("hint");
createTestCommand("help");
- // ClearDefinedIndexesCommand, CreateDefinedIndexesCommand, CreateIndexCommand,
- // DefineIndexCommand, DestroyIndexCommand, ListIndexCommand
+ // IndexCommands
createTestCommand("clear defined indexes", clusterManageQuery);
createTestCommand("create defined indexes", clusterManageQuery);
createTestCommand(
@@ -218,7 +216,7 @@ public class TestCommand {
// createTestCommand("stop locator --name=locator1", clusterManage);
// createTestCommand("stop server --name=server1", clusterManage);
- // DescribeMemberCommand, ListMemberCommand
+ // MemberCommands
createTestCommand("describe member --name=server1", clusterRead);
createTestCommand("list members", clusterRead);
@@ -247,11 +245,11 @@ public class TestCommand {
createTestCommand("list async-event-queues", clusterRead);
- // DescribeRegionCommand, ListRegionCommand
+ // RegionCommands
createTestCommand("describe region --name=value", clusterRead);
createTestCommand("list regions", clusterRead);
- // StatusClusterConfigServiceCommand
+ // StatusCommands
createTestCommand("status cluster-config-service", clusterRead);
// Shell Commands
@@ -280,5 +278,8 @@ public class TestCommand {
// ShellCommand
createTestCommand("disconnect");
+
+ // Misc commands
+ // createTestCommand("shutdown", clusterManage);
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/redis/SetsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/redis/SetsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/redis/SetsJUnitTest.java
index 2122570..aaa7724 100755
--- a/geode-core/src/test/java/org/apache/geode/redis/SetsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/redis/SetsJUnitTest.java
@@ -20,23 +20,22 @@ import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Random;
-import java.util.Set;
-
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.GemFireCache;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.test.junit.categories.IntegrationTest;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
-import redis.clients.jedis.Jedis;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.GemFireCache;
-import org.apache.geode.internal.AvailablePortHelper;
-import org.apache.geode.test.junit.categories.IntegrationTest;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Random;
+import java.util.Set;
+import redis.clients.jedis.Jedis;
@Category(IntegrationTest.class)
public class SetsJUnitTest {
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/redis/SortedSetsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/redis/SortedSetsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/redis/SortedSetsJUnitTest.java
index d88bc15..633cb3d 100755
--- a/geode-core/src/test/java/org/apache/geode/redis/SortedSetsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/redis/SortedSetsJUnitTest.java
@@ -14,26 +14,12 @@
*/
package org.apache.geode.redis;
-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.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.util.AbstractMap;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Random;
-import java.util.Set;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.GemFireCache;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.redis.GeodeRedisServer;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -42,10 +28,12 @@ import org.junit.experimental.categories.Category;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.GemFireCache;
-import org.apache.geode.internal.AvailablePortHelper;
-import org.apache.geode.test.junit.categories.IntegrationTest;
+import java.io.IOException;
+import java.util.*;
+import java.util.Map.Entry;
+
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.junit.Assert.*;
@Category(IntegrationTest.class)
public class SortedSetsJUnitTest {
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-cq/src/test/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsDUnitTest.java
----------------------------------------------------------------------
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 877f7e7..e15d2cc 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
@@ -233,7 +233,7 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
writeToLog("Command Result :\n", resultAsString);
assertTrue(Status.ERROR.equals(commandResult.getStatus()));
assertTrue(resultAsString
- .contains(CliStrings.format(CliStrings.DURABLE_CQ_CLIENT_NOT_FOUND, clientName)));
+ .contains(CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, clientName)));
}
private void writeToLog(String text, String resultAsString) {
@@ -350,7 +350,7 @@ public class DurableClientCommandsDUnitTest extends CliCommandTestBase {
ccf.addPoolServer(getServerHostName(server.getHost()), port);
ccf.setPoolSubscriptionEnabled(true);
- ClientCache cache = getClientCache(ccf);
+ ClientCache cache = (ClientCache) getClientCache(ccf);
}
});
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-junit/src/test/java/org/apache/geode/test/junit/rules/RetryRuleLocalWithErrorTest.java
----------------------------------------------------------------------
diff --git a/geode-junit/src/test/java/org/apache/geode/test/junit/rules/RetryRuleLocalWithErrorTest.java b/geode-junit/src/test/java/org/apache/geode/test/junit/rules/RetryRuleLocalWithErrorTest.java
index cd18695..b04a6e0 100755
--- a/geode-junit/src/test/java/org/apache/geode/test/junit/rules/RetryRuleLocalWithErrorTest.java
+++ b/geode-junit/src/test/java/org/apache/geode/test/junit/rules/RetryRuleLocalWithErrorTest.java
@@ -14,7 +14,7 @@
*/
package org.apache.geode.test.junit.rules;
-import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.*;
import static org.junit.Assert.fail;
import java.util.List;
[18/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusCommandsTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusCommandsTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusCommandsTest.java
new file mode 100755
index 0000000..bc309dd
--- /dev/null
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusCommandsTest.java
@@ -0,0 +1,391 @@
+/*
+ * 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.shell;
+
+import static java.util.concurrent.TimeUnit.MINUTES;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import junitparams.JUnitParamsRunner;
+import junitparams.Parameters;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runner.RunWith;
+
+import org.apache.geode.internal.AvailablePort;
+import org.apache.geode.internal.ExitCode;
+import org.apache.geode.internal.process.PidFile;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.management.internal.cli.util.ThreePhraseGenerator;
+import org.apache.geode.test.dunit.rules.gfsh.GfshExecution;
+import org.apache.geode.test.dunit.rules.gfsh.GfshRule;
+import org.apache.geode.test.dunit.rules.gfsh.GfshScript;
+import org.apache.geode.test.junit.categories.AcceptanceTest;
+
+// Originally created in response to GEODE-2971
+
+@Category(AcceptanceTest.class)
+@RunWith(JUnitParamsRunner.class)
+public class GfshExitCodeStatusCommandsTest {
+ private static File toolsJar;
+ private static final ThreePhraseGenerator nameGenerator = new ThreePhraseGenerator();
+ private static final String memberControllerName = "member-controller";
+
+ @Rule
+ public GfshRule gfsh = new GfshRule();
+ private String locatorName;
+ private String serverName;
+
+ private int locatorPort;
+
+ // Some test configuration shorthands
+ private static final TestConfiguration LOCATOR_ONLINE_BUT_NOT_CONNECTED =
+ new TestConfiguration(true, false, false);
+ private static final TestConfiguration LOCATOR_ONLINE_AND_CONNECTED =
+ new TestConfiguration(true, false, true);
+ private static final TestConfiguration BOTH_ONLINE_BUT_NOT_CONNECTED =
+ new TestConfiguration(true, true, false);
+ private static final TestConfiguration BOTH_ONLINE_AND_CONNECTED =
+ new TestConfiguration(true, true, true);
+
+ @BeforeClass
+ public static void classSetup() {
+ File javaHome = new File(System.getProperty("java.home"));
+ String toolsPath =
+ javaHome.getName().equalsIgnoreCase("jre") ? "../lib/tools.jar" : "lib/tools.jar";
+ toolsJar = new File(javaHome, toolsPath);
+ }
+
+ @Before
+ public void setup() {
+ locatorName = "locator-" + nameGenerator.generate('-');
+ serverName = "server-" + nameGenerator.generate('-');
+ locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
+ }
+
+ @Test
+ @Parameters(
+ value = {"status locator --port=-10", "status locator --pid=-1", "status server --pid=-1"})
+ public void statusCommandWithInvalidOptionValueShouldFail(String cmd) {
+ GfshScript.of(cmd).withName("test-frame").awaitAtMost(1, MINUTES)
+ .expectExitCode(ExitCode.FATAL.getValue()).execute(gfsh);
+ }
+
+
+ @Test
+ @Parameters(value = {"status locator --host=somehostname", "status locator --port=10334",
+ "status locator --dir=.", "status server --dir=.", "status locator --name=some-locator-name",
+ "status server --name=some-server-name", "status locator --pid=100",
+ "status server --pid=100"})
+ public void statusCommandWithValidOptionValueShouldFailWithNoMembers(String cmd) {
+ GfshScript.of(cmd).withName("test-frame").awaitAtMost(1, MINUTES)
+ .expectExitCode(ExitCode.FATAL.getValue()).execute(gfsh);
+ }
+
+
+ @Test
+ public void onlineStatusCommandShouldFailWhenNotConnected_locator_name() {
+ TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByName();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.FATAL);
+ }
+
+
+ @Test
+ public void onlineStatusCommandShouldFailWhenNotConnected_server_name() {
+ TestConfiguration config = BOTH_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusServerCommandByName();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.FATAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedWhenNotConnected_locator_port() {
+ // --host defaults to localhost, so `status locator --port=xxx` should still succeed.
+ TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByPort();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedWhenNotConnected_locator_host_and_port() {
+ // Since this is still local to the testing VM's machine, `status locator --host=localhost
+ // --port=xxx` should succeed
+ TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByHostAndPort();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+
+
+ @Test
+ public void onlineStatusCommandShouldSucceedWhenConnected_locator_name() {
+ TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByName();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+
+ @Test
+ public void onlineStatusCommandShouldSucceedWhenConnected_server_name() {
+ TestConfiguration config = BOTH_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusServerCommandByName();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void onlineStatusCommandShouldSucceedWhenConnected_locator_port() {
+ TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByPort();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void onlineStatusCommandShouldSucceedWhenConnected_locator_host_and_port() {
+ TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByHostAndPort();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+
+
+ @Test
+ public void offlineStatusCommandShouldSucceedWhenConnected_locator_dir() {
+ TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByDir();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedWhenConnected_server_dir() {
+ TestConfiguration config = BOTH_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusServerCommandByDir();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedWhenConnected_locator_pid() throws IOException {
+ Assume.assumeTrue(toolsJar.exists());
+ TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByPid();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedWhenConnected_server_pid() throws IOException {
+ Assume.assumeTrue(toolsJar.exists());
+ TestConfiguration config = BOTH_ONLINE_AND_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusServerCommandByPid();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+
+
+ @Test
+ public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_locator_dir() {
+ TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByDir();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_server_dir() {
+ TestConfiguration config = BOTH_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusServerCommandByDir();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_locator_pid()
+ throws IOException {
+ Assume.assumeTrue(toolsJar.exists());
+ TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusLocatorCommandByPid();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+ @Test
+ public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_server_pid()
+ throws IOException {
+ Assume.assumeTrue(toolsJar.exists());
+ TestConfiguration config = BOTH_ONLINE_BUT_NOT_CONNECTED;
+ config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
+
+ String statusCommand = statusServerCommandByPid();
+ executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
+ }
+
+
+
+ private String startLocatorCommand() {
+ return new CommandStringBuilder("start locator").addOption("name", locatorName)
+ .addOption("port", String.valueOf(locatorPort)).toString();
+ }
+
+
+ private String startServerCommand() {
+ return new CommandStringBuilder("start server").addOption("name", serverName).toString();
+ }
+
+
+ private String connectCommand() {
+ return new CommandStringBuilder("connect")
+ .addOption("locator", String.format("localhost[%d]", locatorPort)).toString();
+ }
+
+
+ private String statusServerCommandByName() {
+ return new CommandStringBuilder("status server").addOption("name", serverName).toString();
+ }
+
+ private String statusServerCommandByDir() {
+ String serverDir = gfsh.getTemporaryFolder().getRoot().toPath().resolve(memberControllerName)
+ .resolve(serverName).toAbsolutePath().toString();
+ return new CommandStringBuilder("status server").addOption("dir", serverDir).toString();
+ }
+
+
+ private String statusServerCommandByPid() throws IOException {
+ int serverPid = snoopMemberFile(serverName, "server.pid");
+ return new CommandStringBuilder("status server").addOption("pid", String.valueOf(serverPid))
+ .toString();
+ }
+
+ private String statusLocatorCommandByName() {
+ return new CommandStringBuilder("status locator").addOption("name", locatorName).toString();
+ }
+
+ private String statusLocatorCommandByPort() {
+ return new CommandStringBuilder("status locator").addOption("port", String.valueOf(locatorPort))
+ .toString();
+ }
+
+ private String statusLocatorCommandByHostAndPort() {
+ return new CommandStringBuilder("status locator").addOption("host", "localhost")
+ .addOption("port", String.valueOf(locatorPort)).toString();
+ }
+
+ private String statusLocatorCommandByDir() {
+ String locatorDir = gfsh.getTemporaryFolder().getRoot().toPath().resolve(memberControllerName)
+ .resolve(locatorName).toAbsolutePath().toString();
+ return new CommandStringBuilder("status locator").addOption("dir", locatorDir).toString();
+ }
+
+
+ private String statusLocatorCommandByPid() throws IOException {
+ int locatorPid = snoopMemberFile(locatorName, "locator.pid");
+ return new CommandStringBuilder("status locator").addOption("pid", String.valueOf(locatorPid))
+ .toString();
+ }
+
+ private int snoopMemberFile(String memberName, String pidFileEndsWith) throws IOException {
+ File directory = gfsh.getTemporaryFolder().getRoot().toPath().resolve(memberControllerName)
+ .resolve(memberName).toFile();
+ File[] files = directory.listFiles();
+ if (files == null) {
+ throw new RuntimeException(String.format(
+ "Expected directory ('%s') for member '%s' either does not denote a directory, or an I/O error occurred.",
+ directory.toString(), memberName));
+ }
+ File pidFile = Arrays.stream(files).filter(file -> file.getName().endsWith(pidFileEndsWith))
+ .findFirst().orElseThrow(() -> new RuntimeException(String
+ .format("Expected member '%s' to have pid file but could not find it.", memberName)));
+ return new PidFile(pidFile).readPid();
+ }
+
+ private void executeScriptWithExpectedExitCode(String statusCommand, TestConfiguration config,
+ ExitCode expectedExit) {
+
+ String[] gfshScriptCommands = config.connectedToLocator
+ ? new String[] {connectCommand(), statusCommand} : new String[] {statusCommand};
+ GfshScript gfshScript = GfshScript.of(gfshScriptCommands).withName("test-frame")
+ .awaitAtMost(1, MINUTES).expectExitCode(expectedExit.getValue());
+ if (toolsJar.exists()) {
+ gfshScript.addToClasspath(toolsJar.getAbsolutePath());
+ }
+ gfshScript.execute(gfsh);
+ }
+
+
+ private static class TestConfiguration {
+ TestConfiguration(boolean locatorStarted, boolean serverStarted, boolean connectedToLocator) {
+ this.locatorStarted = locatorStarted;
+ this.serverStarted = serverStarted;
+ this.connectedToLocator = connectedToLocator;
+ }
+
+ private boolean locatorStarted;
+ private boolean serverStarted;
+ private boolean connectedToLocator;
+
+ void startNecessaryMembers(String startLocator, String startServer, GfshRule gfsh) {
+ if (!locatorStarted && !serverStarted) {
+ return;
+ }
+
+ List<String> commands = new ArrayList<>();
+ if (locatorStarted) {
+ commands.add(startLocator);
+ }
+ if (serverStarted) {
+ commands.add(startServer);
+ }
+
+ GfshExecution exec = GfshScript.of(commands.toArray(new String[] {}))
+ .withName(memberControllerName).awaitAtMost(1, MINUTES).execute(gfsh);
+ if (exec.getProcess().exitValue() != 0) {
+ throw new RuntimeException(
+ "The locator and server launcher exited with non-zero exit code. This failure is beyond the scope of this test.");
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/gfsh/ProcessLogger.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/gfsh/ProcessLogger.java b/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/gfsh/ProcessLogger.java
index 85a94fa..47f0304 100644
--- a/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/gfsh/ProcessLogger.java
+++ b/geode-assembly/src/test/java/org/apache/geode/test/dunit/rules/gfsh/ProcessLogger.java
@@ -36,14 +36,14 @@ public class ProcessLogger {
private final Queue<String> stdOutLines = new ConcurrentLinkedQueue<>();
private final Queue<String> stdErrorLines = new ConcurrentLinkedQueue<>();
+ private final StreamGobbler stdOutGobbler;
+ private final StreamGobbler stdErrGobbler;
public ProcessLogger(Process process, String name) {
this.logger = LOGGER_CONTEXT.getLogger(name);
- StreamGobbler stdOutGobbler =
- new StreamGobbler(process.getInputStream(), this::consumeInfoMessage);
- StreamGobbler stdErrGobbler =
- new StreamGobbler(process.getErrorStream(), this::consumeErrorMessage);
+ this.stdOutGobbler = new StreamGobbler(process.getInputStream(), this::consumeInfoMessage);
+ this.stdErrGobbler = new StreamGobbler(process.getErrorStream(), this::consumeErrorMessage);
stdOutGobbler.startInNewThread();
stdErrGobbler.startInNewThread();
@@ -84,7 +84,7 @@ public class ProcessLogger {
}
public List<String> getStdErrLines() {
- return Lists.newArrayList(stdErrorLines.iterator());
+ return Lists.newArrayList(stdOutLines.iterator());
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
index dc8f5f1..157bb91 100755
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/Launcher.java
@@ -100,6 +100,7 @@ public class Launcher {
this.allowedCommandLineCommands.add(CliStrings.START_JCONSOLE);
this.allowedCommandLineCommands.add(CliStrings.START_JVISUALVM);
this.allowedCommandLineCommands.add(CliStrings.START_LOCATOR);
+ this.allowedCommandLineCommands.add(CliStrings.START_MANAGER);
this.allowedCommandLineCommands.add(CliStrings.START_SERVER);
this.allowedCommandLineCommands.add(CliStrings.START_VSD);
this.allowedCommandLineCommands.add(CliStrings.STATUS_LOCATOR);
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java
deleted file mode 100644
index ce7594e..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterOfflineDiskStoreCommand.java
+++ /dev/null
@@ -1,141 +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 java.io.File;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.CacheExistsException;
-import org.apache.geode.cache.Region;
-import org.apache.geode.internal.cache.DiskStoreImpl;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-
-public class AlterOfflineDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.ALTER_DISK_STORE, help = CliStrings.ALTER_DISK_STORE__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- public Result alterOfflineDiskStore(
- @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKSTORENAME, mandatory = true,
- help = CliStrings.ALTER_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__REGIONNAME, mandatory = true,
- help = CliStrings.ALTER_DISK_STORE__REGIONNAME__HELP) String regionName,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKDIRS,
- help = CliStrings.ALTER_DISK_STORE__DISKDIRS__HELP, mandatory = true) String[] diskDirs,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__COMPRESSOR, specifiedDefaultValue = "none",
- help = CliStrings.ALTER_DISK_STORE__COMPRESSOR__HELP) String compressorClassName,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL,
- help = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL__HELP) Integer concurrencyLevel,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED,
- help = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED__HELP) Boolean statisticsEnabled,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY,
- help = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY__HELP) Integer initialCapacity,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR,
- help = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR__HELP) Float loadFactor,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION,
- help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION__HELP) String lruEvictionAction,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM,
- help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM__HELP) String lruEvictionAlgo,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT,
- help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT__HELP) Integer lruEvictionLimit,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__OFF_HEAP,
- help = CliStrings.ALTER_DISK_STORE__OFF_HEAP__HELP) Boolean offHeap,
- @CliOption(key = CliStrings.ALTER_DISK_STORE__REMOVE,
- help = CliStrings.ALTER_DISK_STORE__REMOVE__HELP, specifiedDefaultValue = "true",
- unspecifiedDefaultValue = "false") boolean remove) {
-
- Result result;
-
- try {
- File[] dirs = null;
-
- if (diskDirs != null) {
- dirs = new File[diskDirs.length];
- for (int i = 0; i < diskDirs.length; i++) {
- dirs[i] = new File((diskDirs[i]));
- }
- }
-
- if (regionName.equals(Region.SEPARATOR)) {
- return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
- }
-
- if ((lruEvictionAlgo != null) || (lruEvictionAction != null) || (lruEvictionLimit != null)
- || (concurrencyLevel != null) || (initialCapacity != null) || (loadFactor != null)
- || (compressorClassName != null) || (offHeap != null) || (statisticsEnabled != null)) {
- if (!remove) {
- String lruEvictionLimitString =
- lruEvictionLimit == null ? null : lruEvictionLimit.toString();
- String concurrencyLevelString =
- concurrencyLevel == null ? null : concurrencyLevel.toString();
- String initialCapacityString =
- initialCapacity == null ? null : initialCapacity.toString();
- String loadFactorString = loadFactor == null ? null : loadFactor.toString();
- String statisticsEnabledString =
- statisticsEnabled == null ? null : statisticsEnabled.toString();
- String offHeapString = offHeap == null ? null : offHeap.toString();
-
- if ("none".equals(compressorClassName)) {
- compressorClassName = "";
- }
-
- String resultMessage = DiskStoreImpl.modifyRegion(diskStoreName, dirs, "/" + regionName,
- lruEvictionAlgo, lruEvictionAction, lruEvictionLimitString, concurrencyLevelString,
- initialCapacityString, loadFactorString, compressorClassName, statisticsEnabledString,
- offHeapString, false);
-
- result = ResultBuilder.createInfoResult(resultMessage);
- } else {
- result = ResultBuilder.createParsingErrorResult(
- "Cannot use the --remove=true parameter with any other parameters");
- }
- } else {
- if (remove) {
- DiskStoreImpl.destroyRegion(diskStoreName, dirs, "/" + regionName);
- result = ResultBuilder.createInfoResult("The region " + regionName
- + " was successfully removed from the disk store " + diskStoreName);
- } else {
- // Please provide an option
- result = ResultBuilder.createParsingErrorResult("Please provide a relevant parameter");
- }
- }
- // Catch the IllegalArgumentException thrown by the modifyDiskStore function and sent the
- } catch (IllegalArgumentException e) {
- String message = "Please check the parameters";
- message += "\n" + e.getMessage();
- result = ResultBuilder.createGemFireErrorResult(message);
- } catch (IllegalStateException e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- } catch (CacheExistsException e) {
- // Indicates that the command is being used when a cache is open
- result = ResultBuilder.createGemFireErrorResult("Cannot execute "
- + CliStrings.ALTER_DISK_STORE + " when a cache exists (Offline command)");
- } catch (Exception e) {
- result = createErrorResult(e.getMessage());
- }
- return result;
- }
-
- private Result createErrorResult(String message) {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(message);
- return ResultBuilder.buildResult(erd);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java
deleted file mode 100644
index 0f9b5d8..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommand.java
+++ /dev/null
@@ -1,229 +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 java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.ExpirationAttributes;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.RegionAlterFunction;
-import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-
-public class AlterRegionCommand implements GfshCommand {
- @CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- public Result alterRegion(
- @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true,
- help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups,
- @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME,
- specifiedDefaultValue = "-1",
- help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
- @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
- specifiedDefaultValue = "INVALIDATE",
- help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
- @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE,
- specifiedDefaultValue = "-1",
- help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
- @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION,
- specifiedDefaultValue = "INVALIDATE",
- help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
- @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME,
- specifiedDefaultValue = "-1",
- help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
- @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
- specifiedDefaultValue = "INVALIDATE",
- help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
- @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1",
- help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
- @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION,
- specifiedDefaultValue = "INVALIDATE",
- help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
- @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "",
- help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners,
- @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "",
- help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader,
- @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "",
- help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter,
- @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "",
- help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
- @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "",
- help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
- @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false",
- help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
- @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0",
- help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) {
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
- getSecurityService().authorizeRegionManage(regionPath);
-
- try {
- InternalCache cache = getCache();
-
- if (groups != null) {
- RegionCommandsUtils.validateGroups(cache, groups);
- }
-
- RegionFunctionArgs.ExpirationAttrs entryIdle = null;
- if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) {
- if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) {
- entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
- }
- if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) {
- entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
- }
- entryIdle = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
- entryExpirationIdleTimeAction);
- }
- RegionFunctionArgs.ExpirationAttrs entryTTL = null;
- if (entryExpirationTTL != null || entryExpirationTTLAction != null) {
- if (entryExpirationTTL != null && entryExpirationTTL == -1) {
- entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
- }
- if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) {
- entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
- }
- entryTTL = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
- entryExpirationTTLAction);
- }
- RegionFunctionArgs.ExpirationAttrs regionIdle = null;
- if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) {
- if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) {
- regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
- }
- if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) {
- regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
- }
- regionIdle = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
- regionExpirationIdleTimeAction);
- }
- RegionFunctionArgs.ExpirationAttrs regionTTL = null;
- if (regionExpirationTTL != null || regionExpirationTTLAction != null) {
- if (regionExpirationTTL != null && regionExpirationTTL == -1) {
- regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
- }
- if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) {
- regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
- }
- regionTTL = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
- regionExpirationTTLAction);
- }
-
- cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY);
- cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY);
-
- RegionFunctionArgs regionFunctionArgs;
- regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null,
- entryIdle, entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners,
- cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled,
- null, null, null, null, null, null, null, null, evictionMax, null, null, null, null);
-
- Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners();
- if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) {
- for (String cacheListener : cacheListenersSet) {
- if (!RegionCommandsUtils.isClassNameValid(cacheListener)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
- new Object[] {cacheListener}));
- }
- }
- }
-
- if (cacheLoader != null && !RegionCommandsUtils.isClassNameValid(cacheLoader)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
- new Object[] {cacheLoader}));
- }
-
- if (cacheWriter != null && !RegionCommandsUtils.isClassNameValid(cacheWriter)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
- new Object[] {cacheWriter}));
- }
-
- if (evictionMax != null && evictionMax < 0) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID,
- new Object[] {evictionMax}));
- }
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> resultCollector =
- CliUtil.executeFunction(new RegionAlterFunction(), regionFunctionArgs, targetMembers);
- List<CliFunctionResult> regionAlterResults =
- (List<CliFunctionResult>) resultCollector.getResult();
-
- TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
- final String errorPrefix = "ERROR: ";
- for (CliFunctionResult regionAlterResult : regionAlterResults) {
- boolean success = regionAlterResult.isSuccessful();
- tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName());
- if (success) {
- tabularResultData.accumulate("Status", regionAlterResult.getMessage());
- xmlEntity.set(regionAlterResult.getXmlEntity());
- } else {
- tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage());
- tabularResultData.setStatus(Result.Status.ERROR);
- }
- }
- result = ResultBuilder.buildResult(tabularResultData);
- } catch (IllegalArgumentException | IllegalStateException e) {
- LogWrapper.getInstance().info(e.getMessage());
- result = ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (RuntimeException e) {
- LogWrapper.getInstance().info(e.getMessage(), e);
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
-
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
- }
- return result;
- }
-
-
-
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java
deleted file mode 100644
index 4415968..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeConfigCommand.java
+++ /dev/null
@@ -1,246 +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.STATISTIC_SAMPLING_ENABLED;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.logging.log4j.Logger;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.internal.logging.log4j.LogLevel;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.AlterRuntimeConfigFunction;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class AlterRuntimeConfigCommand implements GfshCommand {
- private final AlterRuntimeConfigFunction alterRunTimeConfigFunction =
- new AlterRuntimeConfigFunction();
- private static Logger logger = LogService.getLogger();
-
- @CliCommand(value = {CliStrings.ALTER_RUNTIME_CONFIG},
- help = CliStrings.ALTER_RUNTIME_CONFIG__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG},
- interceptor = "org.apache.geode.management.internal.cli.commands.AlterRuntimeConfigCommand$AlterRuntimeInterceptor")
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE)
- public Result alterRuntimeConfig(
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] memberNameOrId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.ALTER_RUNTIME_CONFIG__GROUP__HELP) String[] group,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT},
- help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT__HELP) Integer archiveDiskSpaceLimit,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT},
- help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT__HELP) Integer archiveFileSizeLimit,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT},
- help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT__HELP) Integer logDiskSpaceLimit,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT},
- help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT__HELP) Integer logFileSizeLimit,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL},
- optionContext = ConverterHint.LOG_LEVEL,
- help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL__HELP) String logLevel,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE},
- help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE__HELP) String statisticArchiveFile,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE},
- help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE__HELP) Integer statisticSampleRate,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED},
- help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED__HELP) Boolean statisticSamplingEnabled,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ},
- specifiedDefaultValue = "false",
- help = CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ__HELP) Boolean setCopyOnRead,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE},
- help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE__HELP) Integer lockLease,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT},
- help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT__HELP) Integer lockTimeout,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL},
- help = CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL__HELP) Integer messageSyncInterval,
- @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT},
- help = CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT__HELP) Integer searchTimeout) {
-
- Map<String, String> runTimeDistributionConfigAttributes = new HashMap<>();
- Map<String, String> rumTimeCacheAttributes = new HashMap<>();
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- if (archiveDiskSpaceLimit != null) {
- runTimeDistributionConfigAttributes.put(
- CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT,
- archiveDiskSpaceLimit.toString());
- }
-
- if (archiveFileSizeLimit != null) {
- runTimeDistributionConfigAttributes.put(
- CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT,
- archiveFileSizeLimit.toString());
- }
-
- if (logDiskSpaceLimit != null) {
- runTimeDistributionConfigAttributes.put(
- CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, logDiskSpaceLimit.toString());
- }
-
- if (logFileSizeLimit != null) {
- runTimeDistributionConfigAttributes.put(
- CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, logFileSizeLimit.toString());
- }
-
- if (logLevel != null && !logLevel.isEmpty()) {
- runTimeDistributionConfigAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL,
- logLevel);
- }
-
- if (statisticArchiveFile != null && !statisticArchiveFile.isEmpty()) {
- runTimeDistributionConfigAttributes
- .put(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, statisticArchiveFile);
- }
-
- if (statisticSampleRate != null) {
- runTimeDistributionConfigAttributes.put(
- CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, statisticSampleRate.toString());
- }
-
- if (statisticSamplingEnabled != null) {
- runTimeDistributionConfigAttributes.put(STATISTIC_SAMPLING_ENABLED,
- statisticSamplingEnabled.toString());
- }
-
-
- // Attributes that are set on the cache.
- if (setCopyOnRead != null) {
- rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ,
- setCopyOnRead.toString());
- }
-
- if (lockLease != null && lockLease > 0 && lockLease < Integer.MAX_VALUE) {
- rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE,
- lockLease.toString());
- }
-
- if (lockTimeout != null && lockTimeout > 0 && lockTimeout < Integer.MAX_VALUE) {
- rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT,
- lockTimeout.toString());
- }
-
- if (messageSyncInterval != null && messageSyncInterval > 0
- && messageSyncInterval < Integer.MAX_VALUE) {
- rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL,
- messageSyncInterval.toString());
- }
-
- if (searchTimeout != null && searchTimeout > 0 && searchTimeout < Integer.MAX_VALUE) {
- rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT,
- searchTimeout.toString());
- }
-
- if (runTimeDistributionConfigAttributes.isEmpty() && rumTimeCacheAttributes.isEmpty()) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.ALTER_RUNTIME_CONFIG__RELEVANT__OPTION__MESSAGE);
- }
-
- Map<String, String> allRunTimeAttributes = new HashMap<>();
- allRunTimeAttributes.putAll(runTimeDistributionConfigAttributes);
- allRunTimeAttributes.putAll(rumTimeCacheAttributes);
-
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(alterRunTimeConfigFunction, allRunTimeAttributes, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
- Set<String> successfulMembers = new TreeSet<>();
- Set<String> errorMessages = new TreeSet<>();
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- logger.info("Function failed: " + result.getThrowable());
- errorMessages.add(result.getThrowable().getMessage());
- } else {
- successfulMembers.add(result.getMemberIdOrName());
- }
- }
- final String lineSeparator = System.getProperty("line.separator");
- if (!successfulMembers.isEmpty()) {
- StringBuilder successMessageBuilder = new StringBuilder();
-
- successMessageBuilder.append(CliStrings.ALTER_RUNTIME_CONFIG__SUCCESS__MESSAGE);
- successMessageBuilder.append(lineSeparator);
-
- for (String member : successfulMembers) {
- successMessageBuilder.append(member);
- successMessageBuilder.append(lineSeparator);
- }
-
- Properties properties = new Properties();
- properties.putAll(runTimeDistributionConfigAttributes);
-
- Result result = ResultBuilder.createInfoResult(successMessageBuilder.toString());
-
- // Set the Cache attributes to be modified
- final XmlEntity xmlEntity = XmlEntity.builder().withType(CacheXml.CACHE)
- .withAttributes(rumTimeCacheAttributes).build();
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().modifyXmlAndProperties(properties, xmlEntity, group));
- return result;
- } else {
- StringBuilder errorMessageBuilder = new StringBuilder();
- errorMessageBuilder.append("Following errors occurred while altering runtime config");
- errorMessageBuilder.append(lineSeparator);
-
- for (String errorMessage : errorMessages) {
- errorMessageBuilder.append(errorMessage);
- errorMessageBuilder.append(lineSeparator);
- }
- return ResultBuilder.createUserErrorResult(errorMessageBuilder.toString());
- }
- }
-
- public static class AlterRuntimeInterceptor extends AbstractCliAroundInterceptor {
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- Map<String, String> arguments = parseResult.getParamValueStrings();
- // validate log level
- String logLevel = arguments.get("log-level");
- if (StringUtils.isNotBlank(logLevel) && (LogLevel.getLevel(logLevel) == null)) {
- return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
- }
- return ResultBuilder.createInfoResult("");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeInterceptor.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeInterceptor.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeInterceptor.java
deleted file mode 100644
index 37d4dbb..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/AlterRuntimeInterceptor.java
+++ /dev/null
@@ -1,39 +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 java.util.Map;
-
-import org.apache.commons.lang.StringUtils;
-
-import org.apache.geode.internal.logging.log4j.LogLevel;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-
-public class AlterRuntimeInterceptor extends AbstractCliAroundInterceptor {
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- Map<String, String> arguments = parseResult.getParamValueStrings();
- // validate log level
- String logLevel = arguments.get("log-level");
- if (StringUtils.isNotBlank(logLevel) && (LogLevel.getLevel(logLevel) == null)) {
- return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
- }
- return ResultBuilder.createInfoResult("");
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java
deleted file mode 100644
index 6fc5df1..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/BackupDiskStoreCommand.java
+++ /dev/null
@@ -1,142 +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 java.io.File;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.admin.BackupStatus;
-import org.apache.geode.admin.internal.AdminDistributedSystemImpl;
-import org.apache.geode.cache.persistence.PersistentID;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DM;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class BackupDiskStoreCommand implements GfshCommand {
- /**
- * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
- * is persistent
- */
- @CliCommand(value = CliStrings.BACKUP_DISK_STORE, help = CliStrings.BACKUP_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.DATA,
- operation = ResourcePermission.Operation.READ)
- public Result backupDiskStore(
- @CliOption(key = CliStrings.BACKUP_DISK_STORE__DISKDIRS,
- help = CliStrings.BACKUP_DISK_STORE__DISKDIRS__HELP, mandatory = true) String targetDir,
- @CliOption(key = CliStrings.BACKUP_DISK_STORE__BASELINEDIR,
- help = CliStrings.BACKUP_DISK_STORE__BASELINEDIR__HELP) String baselineDir) {
-
- getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
- ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
- Result result;
- try {
- InternalCache cache = getCache();
- DM dm = cache.getDistributionManager();
- BackupStatus backupStatus;
-
- if (baselineDir != null && !baselineDir.isEmpty()) {
- backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir),
- new File(baselineDir));
- } else {
- backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir), null);
- }
-
- Map<DistributedMember, Set<PersistentID>> backedupMemberDiskstoreMap =
- backupStatus.getBackedUpDiskStores();
-
- Set<DistributedMember> backedupMembers = backedupMemberDiskstoreMap.keySet();
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
-
- if (!backedupMembers.isEmpty()) {
- CompositeResultData.SectionResultData backedupDiskStoresSection = crd.addSection();
- backedupDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_BACKED_UP_DISK_STORES);
- TabularResultData backedupDiskStoresTable = backedupDiskStoresSection.addTable();
-
- for (DistributedMember member : backedupMembers) {
- Set<PersistentID> backedupDiskStores = backedupMemberDiskstoreMap.get(member);
- boolean printMember = true;
- String memberName = member.getName();
-
- if (memberName == null || memberName.isEmpty()) {
- memberName = member.getId();
- }
- for (PersistentID persistentId : backedupDiskStores) {
- if (persistentId != null) {
-
- String UUID = persistentId.getUUID().toString();
- String hostName = persistentId.getHost().getHostName();
- String directory = persistentId.getDirectory();
-
- if (printMember) {
- writeToBackupDiskStoreTable(backedupDiskStoresTable, memberName, UUID, hostName,
- directory);
- printMember = false;
- } else {
- writeToBackupDiskStoreTable(backedupDiskStoresTable, "", UUID, hostName, directory);
- }
- }
- }
- }
- } else {
- CompositeResultData.SectionResultData noMembersBackedUp = crd.addSection();
- noMembersBackedUp.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_NO_DISKSTORES_BACKED_UP);
- }
-
- Set<PersistentID> offlineDiskStores = backupStatus.getOfflineDiskStores();
-
- if (!offlineDiskStores.isEmpty()) {
- CompositeResultData.SectionResultData offlineDiskStoresSection = crd.addSection();
- TabularResultData offlineDiskStoresTable = offlineDiskStoresSection.addTable();
-
- offlineDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_OFFLINE_DISK_STORES);
- for (PersistentID offlineDiskStore : offlineDiskStores) {
- offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID,
- offlineDiskStore.getUUID().toString());
- offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST,
- offlineDiskStore.getHost().getHostName());
- offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY,
- offlineDiskStore.getDirectory());
- }
- }
- result = ResultBuilder.buildResult(crd);
-
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-
- private void writeToBackupDiskStoreTable(TabularResultData backedupDiskStoreTable,
- String memberId, String UUID, String host, String directory) {
- backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_MEMBER, memberId);
- backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID, UUID);
- backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY, directory);
- backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST, host);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java
deleted file mode 100644
index 823c113..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ChangeLogLevelCommand.java
+++ /dev/null
@@ -1,163 +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 java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.LogWriter;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.logging.log4j.LogLevel;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.ChangeLogLevelFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ChangeLogLevelCommand implements GfshCommand {
- @CliCommand(value = CliStrings.CHANGE_LOGLEVEL, help = CliStrings.CHANGE_LOGLEVEL__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_LOGS},
- interceptor = "org.apache.geode.management.internal.cli.commands.ChangeLogLevelCommand$ChangeLogLevelCommandInterceptor")
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.WRITE)
- public Result changeLogLevel(
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- help = CliStrings.CHANGE_LOGLEVEL__MEMBER__HELP) String[] memberIds,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, unspecifiedDefaultValue = "",
- help = CliStrings.CHANGE_LOGLEVEL__GROUPS__HELP) String[] grps,
- @CliOption(key = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL,
- optionContext = ConverterHint.LOG_LEVEL, mandatory = true, unspecifiedDefaultValue = "",
- help = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL__HELP) String logLevel) {
- try {
- if ((memberIds == null || memberIds.length == 0) && (grps == null || grps.length == 0)) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__SPECIFY_GRP_OR_MEMBER);
- }
-
- InternalCache cache = GemFireCacheImpl.getInstance();
- LogWriter logger = cache.getLogger();
-
- Set<DistributedMember> dsMembers = new HashSet<>();
- Set<DistributedMember> ds = CliUtil.getAllMembers(cache);
-
- if (grps != null && grps.length > 0) {
- for (String grp : grps) {
- dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
- }
- }
-
- if (memberIds != null && memberIds.length > 0) {
- for (String member : memberIds) {
- for (DistributedMember mem : ds) {
- if (mem.getName() != null
- && (mem.getName().equals(member) || mem.getId().equals(member))) {
- dsMembers.add(mem);
- break;
- }
- }
- }
- }
-
- if (dsMembers.size() == 0) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG_NO_MEMBERS);
- }
-
- Function logFunction = new ChangeLogLevelFunction();
- FunctionService.registerFunction(logFunction);
- Object[] functionArgs = new Object[1];
- functionArgs[0] = logLevel;
-
- CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
- CompositeResultData.SectionResultData section = compositeResultData.addSection("section");
- TabularResultData resultTable = section.addTable("ChangeLogLevel");
- resultTable = resultTable.setHeader("Summary");
-
- Execution execution = FunctionService.onMembers(dsMembers).setArguments(functionArgs);
- if (execution == null) {
- return ResultBuilder.createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__CANNOT_EXECUTE);
- }
- List<?> resultList = (List<?>) execution.execute(logFunction).getResult();
-
- for (Object object : resultList) {
- try {
- if (object instanceof Throwable) {
- logger.warning(
- "Exception in ChangeLogLevelFunction " + ((Throwable) object).getMessage(),
- ((Throwable) object));
- continue;
- }
-
- if (object != null) {
- Map<String, String> resultMap = (Map<String, String>) object;
- Map.Entry<String, String> entry = resultMap.entrySet().iterator().next();
-
- if (entry.getValue().contains("ChangeLogLevelFunction exception")) {
- resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
- resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "false");
- } else {
- resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
- resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "true");
- }
-
- }
- } catch (Exception ex) {
- LogWrapper.getInstance().warning("change log level command exception " + ex);
- }
- }
-
- Result result = ResultBuilder.buildResult(compositeResultData);
- logger.info("change log-level command result=" + result);
- return result;
- } catch (Exception ex) {
- GemFireCacheImpl.getInstance().getLogger().error("GFSH Changeloglevel exception: " + ex);
- return ResultBuilder.createUserErrorResult(ex.getMessage());
- }
- }
-
- public static class ChangeLogLevelCommandInterceptor extends AbstractCliAroundInterceptor {
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- Map<String, String> arguments = parseResult.getParamValueStrings();
- // validate log level
- String logLevel = arguments.get("loglevel");
- if (StringUtils.isBlank(logLevel) || LogLevel.getLevel(logLevel) == null) {
- return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
- }
-
- return ResultBuilder.createInfoResult("");
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java
deleted file mode 100644
index 2795bf0..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ClearDefinedIndexesCommand.java
+++ /dev/null
@@ -1,40 +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 org.springframework.shell.core.annotation.CliCommand;
-
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ClearDefinedIndexesCommand implements GfshCommand {
- @CliCommand(value = CliStrings.CLEAR_DEFINED_INDEXES, help = CliStrings.CLEAR_DEFINED__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- // TODO : Add optionContext for indexName
- public Result clearDefinedIndexes() {
- IndexDefinition.indexDefinitions.clear();
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.CLEAR_DEFINED_INDEX__SUCCESS__MSG);
- return ResultBuilder.buildResult(infoResult);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java
deleted file mode 100644
index 61dd914..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableCQsCommand.java
+++ /dev/null
@@ -1,83 +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 java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.MemberResult;
-import org.apache.geode.management.internal.cli.functions.CloseDurableCqFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CloseDurableCQsCommand implements GfshCommand {
- DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
-
- @CliCommand(value = CliStrings.CLOSE_DURABLE_CQS, help = CliStrings.CLOSE_DURABLE_CQS__HELP)
- @CliMetaData()
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result closeDurableCqs(@CliOption(key = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID,
- mandatory = true,
- help = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
-
- @CliOption(key = CliStrings.CLOSE_DURABLE_CQS__NAME, mandatory = true,
- help = CliStrings.CLOSE_DURABLE_CQS__NAME__HELP) final String cqName,
-
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- help = CliStrings.CLOSE_DURABLE_CQS__MEMBER__HELP,
- optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.CLOSE_DURABLE_CQS__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
- Result result;
- try {
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- String[] params = new String[2];
- params[0] = durableClientId;
- params[1] = cqName;
-
- final ResultCollector<?, ?> rc =
- CliUtil.executeFunction(new CloseDurableCqFunction(), params, targetMembers);
- final List<MemberResult> results = (List<MemberResult>) rc.getResult();
- String failureHeader =
- CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__FAILURE__HEADER, cqName, durableClientId);
- String successHeader =
- CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__SUCCESS, cqName, durableClientId);
- result = builder.buildResult(results, successHeader, failureHeader);
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java
deleted file mode 100644
index 14c9731..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CloseDurableClientCommand.java
+++ /dev/null
@@ -1,77 +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 java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.MemberResult;
-import org.apache.geode.management.internal.cli.functions.CloseDurableClientFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CloseDurableClientCommand implements GfshCommand {
- DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
-
- @CliCommand(value = CliStrings.CLOSE_DURABLE_CLIENTS,
- help = CliStrings.CLOSE_DURABLE_CLIENTS__HELP)
- @CliMetaData()
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result closeDurableClient(
- @CliOption(key = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, mandatory = true,
- help = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID__HELP) final String durableClientId,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- help = CliStrings.CLOSE_DURABLE_CLIENTS__MEMBER__HELP,
- optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
-
- Result result;
- try {
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- final ResultCollector<?, ?> rc =
- CliUtil.executeFunction(new CloseDurableClientFunction(), durableClientId, targetMembers);
- final List<MemberResult> results = (List<MemberResult>) rc.getResult();
- String failureHeader =
- CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__FAILURE__HEADER, durableClientId);
- String successHeader =
- CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__SUCCESS, durableClientId);
- result = builder.buildResult(results, successHeader, failureHeader);
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-}
[11/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java
deleted file mode 100644
index 4884d6d..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GCCommand.java
+++ /dev/null
@@ -1,131 +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 java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.GarbageCollectionFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class GCCommand implements GfshCommand {
- @CliCommand(value = CliStrings.GC, help = CliStrings.GC__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE)
- public Result gc(
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.GC__GROUP__HELP) String[] groups,
- @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.GC__MEMBER__HELP) String memberId) {
- InternalCache cache = getCache();
- Result result;
- CompositeResultData gcResultTable = ResultBuilder.createCompositeResultData();
- TabularResultData resultTable = gcResultTable.addSection().addTable("Table1");
- String headerText = "GC Summary";
- resultTable.setHeader(headerText);
- Set<DistributedMember> dsMembers = new HashSet<>();
- if (memberId != null && memberId.length() > 0) {
- DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberId);
- if (member == null) {
- return ResultBuilder
- .createGemFireErrorResult(memberId + CliStrings.GC__MSG__MEMBER_NOT_FOUND);
- }
- dsMembers.add(member);
- result = executeAndBuildResult(resultTable, dsMembers);
- } else if (groups != null && groups.length > 0) {
- for (String group : groups) {
- dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(group));
- }
- result = executeAndBuildResult(resultTable, dsMembers);
-
- } else {
- // gc on entire cluster
- // exclude locators
- dsMembers = CliUtil.getAllNormalMembers(cache);
- result = executeAndBuildResult(resultTable, dsMembers);
-
- }
- return result;
- }
-
- private Result executeAndBuildResult(TabularResultData resultTable,
- Set<DistributedMember> dsMembers) {
- try {
- List<?> resultList;
- Function garbageCollectionFunction = new GarbageCollectionFunction();
- resultList =
- (List<?>) CliUtil.executeFunction(garbageCollectionFunction, null, dsMembers).getResult();
-
- for (Object object : resultList) {
- if (object instanceof Exception) {
- LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
- ((Throwable) object));
- continue;
- } else if (object instanceof Throwable) {
- LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
- ((Throwable) object));
- continue;
- }
-
- if (object != null) {
- if (object instanceof String) {
- // unexpected exception string - cache may be closed or something
- return ResultBuilder.createUserErrorResult((String) object);
- } else {
- Map<String, String> resultMap = (Map<String, String>) object;
- toTabularResultData(resultTable, resultMap.get("MemberId"),
- resultMap.get("HeapSizeBeforeGC"), resultMap.get("HeapSizeAfterGC"),
- resultMap.get("TimeSpentInGC"));
- }
- } else {
- LogWrapper.getInstance().fine("ResultMap was null ");
- }
- }
- } catch (Exception e) {
- String stack = CliUtil.stackTraceAsString(e);
- LogWrapper.getInstance().info("GC exception is " + stack);
- return ResultBuilder.createGemFireErrorResult(e.getMessage() + ": " + stack);
- }
- return ResultBuilder.buildResult(resultTable);
- }
-
- private void toTabularResultData(TabularResultData table, String memberId, String heapSizeBefore,
- String heapSizeAfter, String timeTaken) {
- table.accumulate(CliStrings.GC__MSG__MEMBER_NAME, memberId);
- table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_BEFORE_GC, heapSizeBefore);
- table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_AFTER_GC, heapSizeAfter);
- table.accumulate(CliStrings.GC__MSG__TOTAL_TIME_IN_GC, timeTaken);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
deleted file mode 100644
index 4cb6194..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommand.java
+++ /dev/null
@@ -1,51 +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 org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CommandManager;
-import org.apache.geode.management.internal.cli.CommandManagerAware;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-
-public class GfshHelpCommand implements GfshCommand, CommandManagerAware {
- private CommandManager commandManager = null;
-
- public void setCommandManager(CommandManager commandManager) {
- this.commandManager = commandManager;
- }
-
- @CliCommand(value = CliStrings.HELP, help = CliStrings.HELP__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
- public Result obtainHelp(
- @CliOption(key = {"", CliStrings.SH__COMMAND}, optionContext = ConverterHint.HELP,
- help = "Command name to provide help for") String buffer) {
- return ResultBuilder.createInfoResult(commandManager.obtainHelp(buffer));
- }
-
- @CliCommand(value = CliStrings.HINT, help = CliStrings.HINT__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
- public Result hint(
- @CliOption(key = {"", CliStrings.HINT__TOPICNAME}, optionContext = ConverterHint.HINT,
- help = CliStrings.HINT__TOPICNAME__HELP) String topicName) {
- return ResultBuilder.createInfoResult(commandManager.obtainHint(topicName));
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java
new file mode 100644
index 0000000..5fd7988
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHelpCommands.java
@@ -0,0 +1,55 @@
+/*
+ * 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 org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CommandManager;
+import org.apache.geode.management.internal.cli.CommandManagerAware;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.springframework.shell.core.CommandMarker;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+/**
+ * @since GemFire 7.0
+ */
+public class GfshHelpCommands implements GfshCommand, CommandManagerAware {
+ private CommandManager commandManager = null;
+
+ public void setCommandManager(CommandManager commandManager) {
+ this.commandManager = commandManager;
+ }
+
+ @CliCommand(value = CliStrings.HELP, help = CliStrings.HELP__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
+ public Result obtainHelp(
+ @CliOption(key = {"", CliStrings.SH__COMMAND}, optionContext = ConverterHint.HELP,
+ help = "Command name to provide help for") String buffer) {
+
+ return ResultBuilder.createInfoResult(commandManager.obtainHelp(buffer));
+ }
+
+ @CliCommand(value = CliStrings.HINT, help = CliStrings.HINT__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
+ public Result hint(@CliOption(key = {"", CliStrings.HINT__TOPICNAME},
+ optionContext = ConverterHint.HINT, help = CliStrings.HINT__TOPICNAME) String topicName) {
+
+ return ResultBuilder.createInfoResult(commandManager.obtainHint(topicName));
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java
deleted file mode 100644
index ccc1900..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/GfshHintCommand.java
+++ /dev/null
@@ -1,42 +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 org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CommandManager;
-import org.apache.geode.management.internal.cli.CommandManagerAware;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-
-public class GfshHintCommand implements GfshCommand, CommandManagerAware {
- private CommandManager commandManager = null;
-
- public void setCommandManager(CommandManager commandManager) {
- this.commandManager = commandManager;
- }
-
- @CliCommand(value = CliStrings.HINT, help = CliStrings.HINT__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_HELP})
- public Result hint(@CliOption(key = {"", CliStrings.HINT__TOPICNAME},
- optionContext = ConverterHint.HINT, help = CliStrings.HINT__TOPICNAME) String topicName) {
- return ResultBuilder.createInfoResult(commandManager.obtainHint(topicName));
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
new file mode 100644
index 0000000..4734b4c
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexCommands.java
@@ -0,0 +1,668 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.Cache;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.IndexDetails;
+import org.apache.geode.management.internal.cli.domain.IndexDetails.IndexStatisticsDetails;
+import org.apache.geode.management.internal.cli.domain.IndexInfo;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateDefinedIndexesFunction;
+import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
+import org.apache.geode.management.internal.cli.functions.DestroyIndexFunction;
+import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+/**
+ * The IndexCommands class encapsulates all GemFire shell (Gfsh) commands related to indexes defined
+ * in GemFire.
+ *
+ * @see GfshCommand
+ * @see org.apache.geode.management.internal.cli.domain.IndexDetails
+ * @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
+ * @since GemFire 7.0
+ */
+@SuppressWarnings("unused")
+public class IndexCommands implements GfshCommand {
+
+ private static final CreateIndexFunction createIndexFunction = new CreateIndexFunction();
+ private static final DestroyIndexFunction destroyIndexFunction = new DestroyIndexFunction();
+ private static final CreateDefinedIndexesFunction createDefinedIndexesFunction =
+ new CreateDefinedIndexesFunction();
+ private static final Set<IndexInfo> indexDefinitions =
+ Collections.synchronizedSet(new HashSet<IndexInfo>());
+
+ @CliCommand(value = CliStrings.LIST_INDEX, help = CliStrings.LIST_INDEX__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ, target = Target.QUERY)
+ public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS,
+ specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
+ help = CliStrings.LIST_INDEX__STATS__HELP) final boolean showStats) {
+ try {
+ return toTabularResult(getIndexListing(), showStats);
+ } catch (FunctionInvocationTargetException ignore) {
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_INDEX));
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ getCache().getLogger().error(t);
+ return ResultBuilder.createGemFireErrorResult(
+ String.format(CliStrings.LIST_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected List<IndexDetails> getIndexListing() {
+ final Execution functionExecutor = getMembersFunctionExecutor(getMembers(getCache()));
+
+ if (functionExecutor instanceof AbstractExecution) {
+ ((AbstractExecution) functionExecutor).setIgnoreDepartedMembers(true);
+ }
+
+ final ResultCollector<?, ?> resultsCollector =
+ functionExecutor.execute(new ListIndexFunction());
+
+ final List<?> results = (List<?>) resultsCollector.getResult();
+ final List<IndexDetails> indexDetailsList = new ArrayList<>(results.size());
+
+ for (Object result : results) {
+ if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other Exceptions
+ indexDetailsList.addAll((Set<IndexDetails>) result);
+ }
+ }
+
+ Collections.sort(indexDetailsList);
+
+ return indexDetailsList;
+ }
+
+ protected Result toTabularResult(final List<IndexDetails> indexDetailsList,
+ final boolean showStats) {
+ if (!indexDetailsList.isEmpty()) {
+ final TabularResultData indexData = ResultBuilder.createTabularResultData();
+
+ for (final IndexDetails indexDetails : indexDetailsList) {
+ indexData.accumulate("Member Name",
+ StringUtils.defaultString(indexDetails.getMemberName()));
+ indexData.accumulate("Member ID", indexDetails.getMemberId());
+ indexData.accumulate("Region Path", indexDetails.getRegionPath());
+ indexData.accumulate("Name", indexDetails.getIndexName());
+ indexData.accumulate("Type", StringUtils.defaultString(indexDetails.getIndexType()));
+ indexData.accumulate("Indexed Expression", indexDetails.getIndexedExpression());
+ indexData.accumulate("From Clause", indexDetails.getFromClause());
+
+ if (showStats) {
+ final IndexStatisticsDetailsAdapter adapter =
+ new IndexStatisticsDetailsAdapter(indexDetails.getIndexStatisticsDetails());
+
+ indexData.accumulate("Uses", adapter.getTotalUses());
+ indexData.accumulate("Updates", adapter.getNumberOfUpdates());
+ indexData.accumulate("Update Time", adapter.getTotalUpdateTime());
+ indexData.accumulate("Keys", adapter.getNumberOfKeys());
+ indexData.accumulate("Values", adapter.getNumberOfValues());
+ }
+ }
+
+ return ResultBuilder.buildResult(indexData);
+ } else {
+ return ResultBuilder.createInfoResult(CliStrings.LIST_INDEX__INDEXES_NOT_FOUND_MESSAGE);
+ }
+ }
+
+ @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ // TODO : Add optionContext for indexName
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ public Result createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
+ help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,
+
+ @CliOption(key = CliStrings.CREATE_INDEX__EXPRESSION, mandatory = true,
+ help = CliStrings.CREATE_INDEX__EXPRESSION__HELP) final String indexedExpression,
+
+ @CliOption(key = CliStrings.CREATE_INDEX__REGION, mandatory = true,
+ optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,
+
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,
+
+ @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
+ optionContext = ConverterHint.INDEX_TYPE,
+ help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType,
+
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
+
+ Result result;
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+ try {
+ final Cache cache = CacheFactory.getAnyInstance();
+
+ int idxType;
+
+ // Index type check
+ if ("range".equalsIgnoreCase(indexType)) {
+ idxType = IndexInfo.RANGE_INDEX;
+ } else if ("hash".equalsIgnoreCase(indexType)) {
+ idxType = IndexInfo.HASH_INDEX;
+ } else if ("key".equalsIgnoreCase(indexType)) {
+ idxType = IndexInfo.KEY_INDEX;
+ } else {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
+ }
+
+ if (indexName == null || indexName.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__NAME);
+ }
+
+ if (indexedExpression == null || indexedExpression.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__EXPRESSION);
+ }
+
+ if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
+ return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__REGIONPATH);
+ }
+
+ if (!regionPath.startsWith(Region.SEPARATOR)) {
+ regionPath = Region.SEPARATOR + regionPath;
+ }
+
+ IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
+
+ final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ final ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(createIndexFunction, indexInfo, targetMembers);
+
+ final List<Object> funcResults = (List<Object>) rc.getResult();
+ final Set<String> successfulMembers = new TreeSet<>();
+ final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
+
+ for (final Object funcResult : funcResults) {
+ if (funcResult instanceof CliFunctionResult) {
+ final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
+
+ if (cliFunctionResult.isSuccessful()) {
+ successfulMembers.add(cliFunctionResult.getMemberIdOrName());
+
+ if (xmlEntity.get() == null) {
+ xmlEntity.set(cliFunctionResult.getXmlEntity());
+ }
+ } else {
+ final String exceptionMessage = cliFunctionResult.getMessage();
+ Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
+
+ if (failedMembers == null) {
+ failedMembers = new TreeSet<>();
+ }
+ failedMembers.add(cliFunctionResult.getMemberIdOrName());
+ indexOpFailMap.put(exceptionMessage, failedMembers);
+ }
+ }
+ }
+
+ if (!successfulMembers.isEmpty()) {
+
+ final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+ infoResult.addLine(CliStrings.CREATE_INDEX__SUCCESS__MSG);
+ infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__NAME__MSG, indexName));
+ infoResult.addLine(
+ CliStrings.format(CliStrings.CREATE_INDEX__EXPRESSION__MSG, indexedExpression));
+ infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__REGIONPATH__MSG, regionPath));
+ infoResult.addLine(CliStrings.CREATE_INDEX__MEMBER__MSG);
+
+ int num = 0;
+
+ for (final String memberId : successfulMembers) {
+ ++num;
+ infoResult.addLine(
+ CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
+ }
+ result = ResultBuilder.buildResult(infoResult);
+
+ } else {
+ // Group members by the exception thrown.
+ final ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(CliStrings.format(CliStrings.CREATE_INDEX__FAILURE__MSG, indexName));
+
+ final Set<String> exceptionMessages = indexOpFailMap.keySet();
+
+ for (final String exceptionMessage : exceptionMessages) {
+ erd.addLine(exceptionMessage);
+ erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
+ final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
+
+ int num = 0;
+ for (final String memberId : memberIds) {
+ ++num;
+ erd.addLine(
+ CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
+ }
+ }
+ result = ResultBuilder.buildResult(erd);
+ }
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
+ }
+
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ public Result destroyIndex(
+ @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "",
+ help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,
+
+ @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath,
+
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID,
+
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {
+
+ Result result;
+
+ if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath)
+ && ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
+ }
+
+ final Cache cache = CacheFactory.getAnyInstance();
+ String regionName = null;
+ if (regionPath != null) {
+ regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
+ }
+ IndexInfo indexInfo = new IndexInfo(indexName, regionName);
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
+ List<Object> funcResults = (List<Object>) rc.getResult();
+
+ Set<String> successfulMembers = new TreeSet<>();
+ Map<String, Set<String>> indexOpFailMap = new HashMap<>();
+
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+ for (Object funcResult : funcResults) {
+ if (!(funcResult instanceof CliFunctionResult)) {
+ continue;
+ }
+
+ CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
+
+ if (cliFunctionResult.isSuccessful()) {
+ successfulMembers.add(cliFunctionResult.getMemberIdOrName());
+ if (xmlEntity.get() == null) {
+ xmlEntity.set(cliFunctionResult.getXmlEntity());
+ }
+ } else {
+ String exceptionMessage = cliFunctionResult.getMessage();
+ Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
+
+ if (failedMembers == null) {
+ failedMembers = new TreeSet<>();
+ }
+ failedMembers.add(cliFunctionResult.getMemberIdOrName());
+ indexOpFailMap.put(exceptionMessage, failedMembers);
+ }
+ }
+
+ if (!successfulMembers.isEmpty()) {
+ InfoResultData infoResult = ResultBuilder.createInfoResultData();
+
+ if (StringUtils.isNotBlank(indexName)) {
+ if (StringUtils.isNotBlank(regionPath)) {
+ infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG,
+ indexName, regionPath));
+ } else {
+ infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName));
+ }
+ } else {
+ if (StringUtils.isNotBlank(regionPath)) {
+ infoResult.addLine(CliStrings
+ .format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG, regionPath));
+ } else {
+ infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG);
+ }
+ }
+
+ int num = 0;
+ for (String memberId : successfulMembers) {
+ infoResult.addLine(CliStrings.format(
+ CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
+ }
+ result = ResultBuilder.buildResult(infoResult);
+
+ } else {
+
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ if (StringUtils.isNotBlank(indexName)) {
+ erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName));
+ } else {
+ erd.addLine("Indexes could not be destroyed for following reasons");
+ }
+
+ Set<String> exceptionMessages = indexOpFailMap.keySet();
+
+ for (String exceptionMessage : exceptionMessages) {
+ erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage));
+ erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON);
+
+ Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
+ int num = 0;
+
+ for (String memberId : memberIds) {
+ erd.addLine(CliStrings.format(
+ CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
+ }
+ erd.addLine("");
+ }
+ result = ResultBuilder.buildResult(erd);
+ }
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group));
+ }
+
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ // TODO : Add optionContext for indexName
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ public Result defineIndex(@CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true,
+ help = CliStrings.DEFINE_INDEX__HELP) final String indexName,
+
+ @CliOption(key = CliStrings.DEFINE_INDEX__EXPRESSION, mandatory = true,
+ help = CliStrings.DEFINE_INDEX__EXPRESSION__HELP) final String indexedExpression,
+
+ @CliOption(key = CliStrings.DEFINE_INDEX__REGION, mandatory = true,
+ optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath,
+
+ @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, unspecifiedDefaultValue = "range",
+ optionContext = ConverterHint.INDEX_TYPE,
+ help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
+
+ Result result;
+ XmlEntity xmlEntity = null;
+
+ int idxType;
+
+ // Index type check
+ if ("range".equalsIgnoreCase(indexType)) {
+ idxType = IndexInfo.RANGE_INDEX;
+ } else if ("hash".equalsIgnoreCase(indexType)) {
+ idxType = IndexInfo.HASH_INDEX;
+ } else if ("key".equalsIgnoreCase(indexType)) {
+ idxType = IndexInfo.KEY_INDEX;
+ } else {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
+ }
+
+ if (indexName == null || indexName.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__NAME);
+ }
+
+ if (indexedExpression == null || indexedExpression.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__EXPRESSION);
+ }
+
+ if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
+ return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__REGIONPATH);
+ }
+
+ if (!regionPath.startsWith(Region.SEPARATOR)) {
+ regionPath = Region.SEPARATOR + regionPath;
+ }
+
+ IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
+ indexDefinitions.add(indexInfo);
+
+ final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+ infoResult.addLine(CliStrings.DEFINE_INDEX__SUCCESS__MSG);
+ infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__NAME__MSG, indexName));
+ infoResult
+ .addLine(CliStrings.format(CliStrings.DEFINE_INDEX__EXPRESSION__MSG, indexedExpression));
+ infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__REGIONPATH__MSG, regionPath));
+ result = ResultBuilder.buildResult(infoResult);
+
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ // TODO : Add optionContext for indexName
+ public Result createDefinedIndexes(
+
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.CREATE_DEFINED_INDEXES__MEMBER__HELP) final String[] memberNameOrID,
+
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.CREATE_DEFINED_INDEXES__GROUP__HELP) final String[] group) {
+
+ Result result;
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+ if (indexDefinitions.isEmpty()) {
+ final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+ infoResult.addLine(CliStrings.DEFINE_INDEX__FAILURE__MSG);
+ return ResultBuilder.buildResult(infoResult);
+ }
+
+ try {
+ final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ final Cache cache = CacheFactory.getAnyInstance();
+ final ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(createDefinedIndexesFunction, indexDefinitions, targetMembers);
+
+ final List<Object> funcResults = (List<Object>) rc.getResult();
+ final Set<String> successfulMembers = new TreeSet<>();
+ final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
+
+ for (final Object funcResult : funcResults) {
+ if (funcResult instanceof CliFunctionResult) {
+ final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
+
+ if (cliFunctionResult.isSuccessful()) {
+ successfulMembers.add(cliFunctionResult.getMemberIdOrName());
+
+ if (xmlEntity.get() == null) {
+ xmlEntity.set(cliFunctionResult.getXmlEntity());
+ }
+ } else {
+ final String exceptionMessage = cliFunctionResult.getMessage();
+ Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
+
+ if (failedMembers == null) {
+ failedMembers = new TreeSet<>();
+ }
+ failedMembers.add(cliFunctionResult.getMemberIdOrName());
+ indexOpFailMap.put(exceptionMessage, failedMembers);
+ }
+ }
+ }
+
+ if (!successfulMembers.isEmpty()) {
+ final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+ infoResult.addLine(CliStrings.CREATE_DEFINED_INDEXES__SUCCESS__MSG);
+
+ int num = 0;
+
+ for (final String memberId : successfulMembers) {
+ ++num;
+ infoResult.addLine(CliStrings
+ .format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER, num, memberId));
+ }
+ result = ResultBuilder.buildResult(infoResult);
+
+ } else {
+ // Group members by the exception thrown.
+ final ErrorResultData erd = ResultBuilder.createErrorResultData();
+
+ final Set<String> exceptionMessages = indexOpFailMap.keySet();
+
+ for (final String exceptionMessage : exceptionMessages) {
+ erd.addLine(exceptionMessage);
+ erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
+ final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
+
+ int num = 0;
+ for (final String memberId : memberIds) {
+ ++num;
+ erd.addLine(CliStrings.format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER,
+ num, memberId));
+ }
+ }
+ result = ResultBuilder.buildResult(erd);
+ }
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
+ }
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.CLEAR_DEFINED_INDEXES, help = CliStrings.CLEAR_DEFINED__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ // TODO : Add optionContext for indexName
+ public Result clearDefinedIndexes() {
+ indexDefinitions.clear();
+ final InfoResultData infoResult = ResultBuilder.createInfoResultData();
+ infoResult.addLine(CliStrings.CLEAR_DEFINED_INDEX__SUCCESS__MSG);
+ return ResultBuilder.buildResult(infoResult);
+ }
+
+ protected static class IndexStatisticsDetailsAdapter {
+
+ private final IndexStatisticsDetails indexStatisticsDetails;
+
+ protected IndexStatisticsDetailsAdapter(final IndexStatisticsDetails indexStatisticsDetails) {
+ this.indexStatisticsDetails = indexStatisticsDetails;
+ }
+
+ public IndexStatisticsDetails getIndexStatisticsDetails() {
+ return indexStatisticsDetails;
+ }
+
+ public String getNumberOfKeys() {
+ return getIndexStatisticsDetails() != null
+ ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfKeys()) : "";
+ }
+
+ public String getNumberOfUpdates() {
+ return getIndexStatisticsDetails() != null
+ ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfUpdates()) : "";
+ }
+
+ public String getNumberOfValues() {
+ return getIndexStatisticsDetails() != null
+ ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfValues()) : "";
+ }
+
+ public String getTotalUpdateTime() {
+ return getIndexStatisticsDetails() != null
+ ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUpdateTime()) : "";
+ }
+
+ public String getTotalUses() {
+ return getIndexStatisticsDetails() != null
+ ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUses()) : "";
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java
deleted file mode 100644
index 3d0e392..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexDefinition.java
+++ /dev/null
@@ -1,27 +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 java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-
-public class IndexDefinition {
- static final Set<IndexInfo> indexDefinitions =
- Collections.synchronizedSet(new HashSet<IndexInfo>());
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexStatisticsDetailsAdapter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexStatisticsDetailsAdapter.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexStatisticsDetailsAdapter.java
deleted file mode 100644
index 30d8157..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/IndexStatisticsDetailsAdapter.java
+++ /dev/null
@@ -1,58 +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 org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.domain.IndexDetails;
-
-public class IndexStatisticsDetailsAdapter {
-
- private final IndexDetails.IndexStatisticsDetails indexStatisticsDetails;
-
- public IndexStatisticsDetailsAdapter(
- final IndexDetails.IndexStatisticsDetails indexStatisticsDetails) {
- this.indexStatisticsDetails = indexStatisticsDetails;
- }
-
- public IndexDetails.IndexStatisticsDetails getIndexStatisticsDetails() {
- return indexStatisticsDetails;
- }
-
- public String getNumberOfKeys() {
- return getIndexStatisticsDetails() != null
- ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfKeys()) : "";
- }
-
- public String getNumberOfUpdates() {
- return getIndexStatisticsDetails() != null
- ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfUpdates()) : "";
- }
-
- public String getNumberOfValues() {
- return getIndexStatisticsDetails() != null
- ? StringUtils.defaultString(getIndexStatisticsDetails().getNumberOfValues()) : "";
- }
-
- public String getTotalUpdateTime() {
- return getIndexStatisticsDetails() != null
- ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUpdateTime()) : "";
- }
-
- public String getTotalUses() {
- return getIndexStatisticsDetails() != null
- ? StringUtils.defaultString(getIndexStatisticsDetails().getTotalUses()) : "";
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java
deleted file mode 100644
index 8b3d1bd..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListAsyncEventQueuesCommand.java
+++ /dev/null
@@ -1,118 +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 java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.AsyncEventQueueDetails;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ListAsyncEventQueuesFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListAsyncEventQueuesCommand implements GfshCommand {
- @CliCommand(value = CliStrings.LIST_ASYNC_EVENT_QUEUES,
- help = CliStrings.LIST_ASYNC_EVENT_QUEUES__HELP)
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listAsyncEventQueues() {
- try {
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(null, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> rc = CliUtil.executeFunction(new ListAsyncEventQueuesFunction(),
- new Object[] {}, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
- + ": " + result.getThrowable().getMessage());
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else {
- AsyncEventQueueDetails[] details = (AsyncEventQueueDetails[]) result.getSerializables();
- for (AsyncEventQueueDetails detail : details) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("ID", detail.getId());
- tabularData.accumulate("Batch Size", detail.getBatchSize());
- tabularData.accumulate("Persistent", detail.isPersistent());
- tabularData.accumulate("Disk Store", detail.getDiskStoreName());
- tabularData.accumulate("Max Memory", detail.getMaxQueueMemory());
-
- Properties listenerProperties = detail.getListenerProperties();
- if (listenerProperties == null || listenerProperties.size() == 0) {
- tabularData.accumulate("Listener", detail.getListener());
- } else {
- StringBuilder propsStringBuilder = new StringBuilder();
- propsStringBuilder.append('(');
- boolean firstProperty = true;
- for (Map.Entry<Object, Object> property : listenerProperties.entrySet()) {
- if (!firstProperty) {
- propsStringBuilder.append(',');
- } else {
- firstProperty = false;
- }
- propsStringBuilder.append(property.getKey()).append('=')
- .append(property.getValue());
- }
- propsStringBuilder.append(')');
-
- tabularData.accumulate("Listener",
- detail.getListener() + propsStringBuilder.toString());
- }
- accumulatedData = true;
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder
- .createInfoResult(CliStrings.LIST_ASYNC_EVENT_QUEUES__NO_QUEUES_FOUND_MESSAGE);
- }
-
- return ResultBuilder.buildResult(tabularData);
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.LIST_ASYNC_EVENT_QUEUES__ERROR_WHILE_LISTING_REASON_0,
- new Object[] {th.getMessage()}));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java
deleted file mode 100644
index 4c2bc53..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDeployedCommand.java
+++ /dev/null
@@ -1,102 +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 java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ListDeployedFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListDeployedCommand implements GfshCommand {
- private final ListDeployedFunction listDeployedFunction = new ListDeployedFunction();
-
- /**
- * List all currently deployed JARs for members of a group or for all members.
- *
- * @param group Group for which to list JARs or null for all members
- * @return List of deployed JAR files
- */
- @CliCommand(value = {CliStrings.LIST_DEPLOYED}, help = CliStrings.LIST_DEPLOYED__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listDeployed(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.LIST_DEPLOYED__GROUP__HELP) String[] group) {
-
- try {
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(this.listDeployedFunction, null, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("JAR", "");
- tabularData.accumulate("JAR Location",
- "ERROR: " + result.getThrowable().getClass().getName() + ": "
- + result.getThrowable().getMessage());
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else {
- String[] strings = (String[]) result.getSerializables();
- for (int i = 0; i < strings.length; i += 2) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("JAR", strings[i]);
- tabularData.accumulate("JAR Location", strings[i + 1]);
- accumulatedData = true;
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder.createInfoResult(CliStrings.LIST_DEPLOYED__NO_JARS_FOUND_MESSAGE);
- }
- return ResultBuilder.buildResult(tabularData);
-
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult("Exception while attempting to list deployed: "
- + th.getClass().getName() + ": " + th.getMessage());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java
deleted file mode 100644
index c7d5a1e..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDiskStoresCommand.java
+++ /dev/null
@@ -1,113 +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 java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
-import org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.ResultDataException;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListDiskStoresCommand implements GfshCommand {
- @CliCommand(value = CliStrings.LIST_DISK_STORE, help = CliStrings.LIST_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listDiskStores() {
- try {
- Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers(getCache());
-
- if (dataMembers.isEmpty()) {
- return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
- }
-
- return toTabularResult(getDiskStoreListing(dataMembers));
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_DISK_STORE));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(
- String.format(CliStrings.LIST_DISK_STORE__ERROR_MESSAGE, toString(t, isDebugging())));
- }
- }
-
- @SuppressWarnings("unchecked")
- public List<DiskStoreDetails> getDiskStoreListing(Set<DistributedMember> members) {
- final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
- if (membersFunctionExecutor instanceof AbstractExecution) {
- ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
- }
-
- final ResultCollector<?, ?> resultCollector =
- membersFunctionExecutor.execute(new ListDiskStoresFunction());
-
- final List<?> results = (List<?>) resultCollector.getResult();
- final List<DiskStoreDetails> distributedSystemMemberDiskStores =
- new ArrayList<>(results.size());
-
- for (final Object result : results) {
- if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
- // Exceptions...
- distributedSystemMemberDiskStores.addAll((Set<DiskStoreDetails>) result);
- }
- }
-
- Collections.sort(distributedSystemMemberDiskStores);
-
- return distributedSystemMemberDiskStores;
- }
-
- private Result toTabularResult(final List<DiskStoreDetails> diskStoreList)
- throws ResultDataException {
- if (!diskStoreList.isEmpty()) {
- final TabularResultData diskStoreData = ResultBuilder.createTabularResultData();
-
- for (final DiskStoreDetails diskStoreDetails : diskStoreList) {
- diskStoreData.accumulate("Member Name", diskStoreDetails.getMemberName());
- diskStoreData.accumulate("Member Id", diskStoreDetails.getMemberId());
- diskStoreData.accumulate("Disk Store Name", diskStoreDetails.getName());
- diskStoreData.accumulate("Disk Store ID", diskStoreDetails.getId());
- }
-
- return ResultBuilder.buildResult(diskStoreData);
- } else {
- return ResultBuilder
- .createInfoResult(CliStrings.LIST_DISK_STORE__DISK_STORES_NOT_FOUND_MESSAGE);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java
deleted file mode 100644
index 011bfde..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListDurableClientCQsCommand.java
+++ /dev/null
@@ -1,121 +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 java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.DurableCqNamesResult;
-import org.apache.geode.management.internal.cli.functions.ListDurableCqNamesFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListDurableClientCQsCommand implements GfshCommand {
- DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
-
- @CliCommand(value = CliStrings.LIST_DURABLE_CQS, help = CliStrings.LIST_DURABLE_CQS__HELP)
- @CliMetaData()
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listDurableClientCQs(
- @CliOption(key = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, mandatory = true,
- help = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID__HELP) final String durableClientId,
-
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- help = CliStrings.LIST_DURABLE_CQS__MEMBER__HELP,
- optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.LIST_DURABLE_CQS__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
- Result result;
- try {
-
- boolean noResults = true;
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- final ResultCollector<?, ?> rc =
- CliUtil.executeFunction(new ListDurableCqNamesFunction(), durableClientId, targetMembers);
- final List<DurableCqNamesResult> results = (List<DurableCqNamesResult>) rc.getResult();
- Map<String, List<String>> memberCqNamesMap = new TreeMap<>();
- Map<String, List<String>> errorMessageNodes = new HashMap<>();
- Map<String, List<String>> exceptionMessageNodes = new HashMap<>();
-
- for (DurableCqNamesResult memberResult : results) {
- if (memberResult != null) {
- if (memberResult.isSuccessful()) {
- memberCqNamesMap.put(memberResult.getMemberNameOrId(), memberResult.getCqNamesList());
- } else {
- if (memberResult.isOpPossible()) {
- builder.groupByMessage(memberResult.getExceptionMessage(),
- memberResult.getMemberNameOrId(), exceptionMessageNodes);
- } else {
- builder.groupByMessage(memberResult.getErrorMessage(),
- memberResult.getMemberNameOrId(), errorMessageNodes);
- }
- }
- }
- }
-
- if (!memberCqNamesMap.isEmpty()) {
- TabularResultData table = ResultBuilder.createTabularResultData();
- Set<String> members = memberCqNamesMap.keySet();
-
- for (String member : members) {
- boolean isFirst = true;
- List<String> cqNames = memberCqNamesMap.get(member);
- for (String cqName : cqNames) {
- if (isFirst) {
- isFirst = false;
- table.accumulate(CliStrings.MEMBER, member);
- } else {
- table.accumulate(CliStrings.MEMBER, "");
- }
- table.accumulate(CliStrings.LIST_DURABLE_CQS__NAME, cqName);
- }
- }
- result = ResultBuilder.buildResult(table);
- } else {
- String errorHeader =
- CliStrings.format(CliStrings.LIST_DURABLE_CQS__FAILURE__HEADER, durableClientId);
- result = ResultBuilder.buildResult(
- builder.buildFailureData(null, exceptionMessageNodes, errorMessageNodes, errorHeader));
- }
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
deleted file mode 100644
index 81ef437..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListFunctionCommand.java
+++ /dev/null
@@ -1,100 +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 java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ListFunctionFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListFunctionCommand implements GfshCommand {
- private final ListFunctionFunction listFunctionFunction = new ListFunctionFunction();
-
- @CliCommand(value = CliStrings.LIST_FUNCTION, help = CliStrings.LIST_FUNCTION__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listFunction(
- @CliOption(key = CliStrings.LIST_FUNCTION__MATCHES,
- help = CliStrings.LIST_FUNCTION__MATCHES__HELP) String matches,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.LIST_FUNCTION__GROUP__HELP) String[] groups,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.LIST_FUNCTION__MEMBER__HELP) String[] members) {
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
- Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, members);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- try {
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(this.listFunctionFunction, new Object[] {matches}, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Function", "<ERROR: " + result.getThrowable().getMessage() + ">");
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else if (result.isSuccessful()) {
- String[] strings = (String[]) result.getSerializables();
- Arrays.sort(strings);
- for (String string : strings) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Function", string);
- accumulatedData = true;
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder
- .createInfoResult(CliStrings.LIST_FUNCTION__NO_FUNCTIONS_FOUND_ERROR_MESSAGE);
- }
- return ResultBuilder.buildResult(tabularData);
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(
- "Exception while attempting to list functions: " + th.getMessage());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java
deleted file mode 100644
index 358cebd..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListIndexCommand.java
+++ /dev/null
@@ -1,119 +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 java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.domain.IndexDetails;
-import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListIndexCommand implements GfshCommand {
- @CliCommand(value = CliStrings.LIST_INDEX, help = CliStrings.LIST_INDEX__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ, target = ResourcePermission.Target.QUERY)
- public Result listIndex(@CliOption(key = CliStrings.LIST_INDEX__STATS,
- specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
- help = CliStrings.LIST_INDEX__STATS__HELP) final boolean showStats) {
- try {
- return toTabularResult(getIndexListing(), showStats);
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_INDEX));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- getCache().getLogger().error(t);
- return ResultBuilder.createGemFireErrorResult(
- String.format(CliStrings.LIST_INDEX__ERROR_MESSAGE, toString(t, isDebugging())));
- }
- }
-
- private Result toTabularResult(final List<IndexDetails> indexDetailsList,
- final boolean showStats) {
- if (!indexDetailsList.isEmpty()) {
- final TabularResultData indexData = ResultBuilder.createTabularResultData();
-
- for (final IndexDetails indexDetails : indexDetailsList) {
- indexData.accumulate("Member Name",
- StringUtils.defaultString(indexDetails.getMemberName()));
- indexData.accumulate("Member ID", indexDetails.getMemberId());
- indexData.accumulate("Region Path", indexDetails.getRegionPath());
- indexData.accumulate("Name", indexDetails.getIndexName());
- indexData.accumulate("Type", StringUtils.defaultString(indexDetails.getIndexType()));
- indexData.accumulate("Indexed Expression", indexDetails.getIndexedExpression());
- indexData.accumulate("From Clause", indexDetails.getFromClause());
-
- if (showStats) {
- final IndexStatisticsDetailsAdapter adapter =
- new IndexStatisticsDetailsAdapter(indexDetails.getIndexStatisticsDetails());
-
- indexData.accumulate("Uses", adapter.getTotalUses());
- indexData.accumulate("Updates", adapter.getNumberOfUpdates());
- indexData.accumulate("Update Time", adapter.getTotalUpdateTime());
- indexData.accumulate("Keys", adapter.getNumberOfKeys());
- indexData.accumulate("Values", adapter.getNumberOfValues());
- }
- }
-
- return ResultBuilder.buildResult(indexData);
- } else {
- return ResultBuilder.createInfoResult(CliStrings.LIST_INDEX__INDEXES_NOT_FOUND_MESSAGE);
- }
- }
-
- List<IndexDetails> getIndexListing() {
- final Execution functionExecutor = getMembersFunctionExecutor(getMembers(getCache()));
-
- if (functionExecutor instanceof AbstractExecution) {
- ((AbstractExecution) functionExecutor).setIgnoreDepartedMembers(true);
- }
-
- final ResultCollector<?, ?> resultsCollector =
- functionExecutor.execute(new ListIndexFunction());
- final List<?> results = (List<?>) resultsCollector.getResult();
- final List<IndexDetails> indexDetailsList = new ArrayList<>(results.size());
-
- for (Object result : results) {
- if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other Exceptions
- indexDetailsList.addAll((Set<IndexDetails>) result);
- }
- }
- Collections.sort(indexDetailsList);
- return indexDetailsList;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java
deleted file mode 100644
index ea88c69..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListMemberCommand.java
+++ /dev/null
@@ -1,77 +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 java.util.Set;
-import java.util.TreeSet;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListMemberCommand implements GfshCommand {
- @CliCommand(value = {CliStrings.LIST_MEMBER}, help = CliStrings.LIST_MEMBER__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listMember(@CliOption(key = {CliStrings.GROUP}, unspecifiedDefaultValue = "",
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.LIST_MEMBER__GROUP__HELP) String group) {
- Result result;
-
- // TODO: Add the code for identifying the system services
- try {
- Set<DistributedMember> memberSet = new TreeSet<>();
- InternalCache cache = getCache();
-
- // default get all the members in the DS
- if (group.isEmpty()) {
- memberSet.addAll(CliUtil.getAllMembers(cache));
- } else {
- memberSet.addAll(cache.getDistributedSystem().getGroupMembers(group));
- }
-
- if (memberSet.isEmpty()) {
- result = ResultBuilder.createInfoResult(CliStrings.LIST_MEMBER__MSG__NO_MEMBER_FOUND);
- } else {
- TabularResultData resultData = ResultBuilder.createTabularResultData();
- for (DistributedMember member : memberSet) {
- resultData.accumulate("Name", member.getName());
- resultData.accumulate("Id", member.getId());
- }
-
- result = ResultBuilder.buildResult(resultData);
- }
- } catch (Exception e) {
- result = ResultBuilder
- .createGemFireErrorResult("Could not fetch the list of members. " + e.getMessage());
- LogWrapper.getInstance().warning(e.getMessage(), e);
- }
- return result;
- }
-}
[19/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
GEODE-3436: revert recent refactoring of GFSH commands
Revert "GEODE-3264: Refactoring MemberCommands"
This reverts commit d27f8b956de7d9c5d95ebdc68dfc67ee8b2d7b51.
Revert "GEODE-3259: Refactoring DurableClientCommands"
This reverts commit 440c87f81fab96f9ce38a2d53ded75e5fe8390d7.
Revert "GEODE-3254: Refactoring ConfigCommands"
This reverts commit 97c4e9a59f17c7bc914e39dd048b0a4cd96293c4.
Revert "GEODE-3262: Refactoring IndexCommands"
This reverts commit ed293e817e547fb5ecd399bf4ba10d694af51e0a.
Revert "GEODE-3260: Refactoring FunctionCommands"
This reverts commit 90f5440de8ec747f301a309a0a34101e8defcd29.
Revert "GEODE-3258: Refactoring DiskStoreCommands"
This reverts commit 5d6cad7755ec3c4fe931e3d0f8e89fb181038543.
Revert "GEODE-3337: Refactoring LauncherLifecycleCommandsDUnitTest"
This reverts commit 210ff9f15460c993f2bf7fd682d50ee65462cd23.
Revert "GEODE-3265: Refactoring MiscellaneousCommands"
This reverts commit 63169699e933f6e0fdd90b95ed039e4e3c92c32c.
Revert "GEODE-3261: Refactoring GfshHelpCommands"
This reverts commit cf91426692349d0c81ce77394935576d9cc336e8.
Revert "GEODE-3267: Refactoring QueueCommands"
This reverts commit fd47ed660168864a6f81b2a4cd7dbceebc99a282.
Revert "GEODE-3270: Refactoring (renaming) StatusCommands"
This reverts commit 359e3fff6482ecfb375939d387f4dad3a636246b.
Revert "GEODE-3267: Refactoring QueueCommands - updated based on feedback"
This reverts commit 957d583e54dc34c029885f32a54f0b25a3ac1094.
Revert "GEODE-3268: Refactoring RegionCommands"
This reverts commit 64de3b69c2aecb4930bcfd0a1161569b1d5fda89.
Revert "GEODE-3266: Refactoring PDXCommands"
This reverts commit 67185abcdd68b908dea6888cb94286b8aa9ea49f.
Revert "GEODE-3257: Refactoring DeployCommands"
This reverts commit 9d967446a44a78b612f605b6a8f8eedcfc625b3a.
Revert "GEODE-3255: Refactor CreateAlterDestroyRegionCommands and tests"
This reverts commit 756efe77c86bb03ac9984655e7bd040659e85890.
Revert "GEODE-3230: Cleaning up unused (Cli)Strings"
This reverts commit a7f29525df2981c1c99abac96ea83cb965295970.
This closes #711
Project: http://git-wip-us.apache.org/repos/asf/geode/repo
Commit: http://git-wip-us.apache.org/repos/asf/geode/commit/645a32d0
Tree: http://git-wip-us.apache.org/repos/asf/geode/tree/645a32d0
Diff: http://git-wip-us.apache.org/repos/asf/geode/diff/645a32d0
Branch: refs/heads/develop
Commit: 645a32d045958ff859967240416a57f6c570a00f
Parents: 44fb3f2
Author: Kirk Lund <kl...@apache.org>
Authored: Sat Aug 12 09:38:20 2017 -0700
Committer: Kirk Lund <kl...@apache.org>
Committed: Sun Aug 13 15:43:27 2017 -0700
----------------------------------------------------------------------
.../org/apache/geode/BundledJarsJUnitTest.java | 44 +-
.../commands/GfshCommandIntegrationTest.java | 69 +-
.../LauncherLifecycleCommandsDUnitTest.java | 1115 ++++++++++
.../cli/commands/StartLocatorCommandTest.java | 4 +-
.../cli/commands/StartServerCommandTest.java | 4 +-
...deStatusClusterConfigServiceCommandTest.java | 391 ----
.../shell/GfshExitCodeStatusCommandsTest.java | 391 ++++
.../test/dunit/rules/gfsh/ProcessLogger.java | 10 +-
.../geode/management/internal/cli/Launcher.java | 1 +
.../commands/AlterOfflineDiskStoreCommand.java | 141 --
.../cli/commands/AlterRegionCommand.java | 229 ---
.../cli/commands/AlterRuntimeConfigCommand.java | 246 ---
.../cli/commands/AlterRuntimeInterceptor.java | 39 -
.../cli/commands/BackupDiskStoreCommand.java | 142 --
.../cli/commands/ChangeLogLevelCommand.java | 163 --
.../commands/ClearDefinedIndexesCommand.java | 40 -
.../cli/commands/CloseDurableCQsCommand.java | 83 -
.../cli/commands/CloseDurableClientCommand.java | 77 -
.../cli/commands/CompactDiskStoreCommand.java | 185 --
.../CompactOfflineDiskStoreCommand.java | 176 --
.../internal/cli/commands/ConfigCommands.java | 490 +++++
.../cli/commands/ConfigurePDXCommand.java | 138 --
.../commands/CountDurableCQEventsCommand.java | 88 -
.../CreateAlterDestroyRegionCommands.java | 1146 +++++++++++
.../commands/CreateAsyncEventQueueCommand.java | 171 --
.../commands/CreateDefinedIndexesCommand.java | 154 --
.../cli/commands/CreateDiskStoreCommand.java | 166 --
.../cli/commands/CreateIndexCommand.java | 196 --
.../cli/commands/CreateRegionCommand.java | 741 -------
.../cli/commands/DefineIndexCommand.java | 95 -
.../internal/cli/commands/DeployCommand.java | 190 --
.../internal/cli/commands/DeployCommands.java | 336 +++
.../cli/commands/DescribeConfigCommand.java | 153 --
.../cli/commands/DescribeDiskStoreCommand.java | 179 --
.../cli/commands/DescribeMemberCommand.java | 133 --
.../DescribeOfflineDiskStoreCommand.java | 75 -
.../cli/commands/DescribeRegionCommand.java | 364 ----
.../cli/commands/DestroyDiskStoreCommand.java | 106 -
.../cli/commands/DestroyFunctionCommand.java | 163 --
.../cli/commands/DestroyIndexCommand.java | 174 --
.../cli/commands/DestroyRegionCommand.java | 222 --
.../cli/commands/DiskStoreCommands.java | 1433 +++++++++++++
.../cli/commands/DiskStoreCommandsUtils.java | 60 -
.../cli/commands/DurableClientCommands.java | 420 ++++
.../DurableClientCommandsResultBuilder.java | 164 --
.../cli/commands/ExecuteFunctionCommand.java | 330 ---
.../cli/commands/ExportConfigCommand.java | 159 --
.../commands/ExportOfflineDiskStoreCommand.java | 68 -
.../cli/commands/ExportStackTraceCommand.java | 157 --
.../internal/cli/commands/FunctionCommands.java | 537 +++++
.../internal/cli/commands/GCCommand.java | 131 --
.../internal/cli/commands/GfshHelpCommand.java | 51 -
.../internal/cli/commands/GfshHelpCommands.java | 55 +
.../internal/cli/commands/GfshHintCommand.java | 42 -
.../internal/cli/commands/IndexCommands.java | 668 ++++++
.../internal/cli/commands/IndexDefinition.java | 27 -
.../commands/IndexStatisticsDetailsAdapter.java | 58 -
.../commands/ListAsyncEventQueuesCommand.java | 118 --
.../cli/commands/ListDeployedCommand.java | 102 -
.../cli/commands/ListDiskStoresCommand.java | 113 -
.../commands/ListDurableClientCQsCommand.java | 121 --
.../cli/commands/ListFunctionCommand.java | 100 -
.../internal/cli/commands/ListIndexCommand.java | 119 --
.../cli/commands/ListMemberCommand.java | 77 -
.../cli/commands/ListRegionCommand.java | 86 -
.../internal/cli/commands/MemberCommands.java | 197 ++
.../cli/commands/MiscellaneousCommands.java | 1926 ++++++++++++++++++
.../internal/cli/commands/NetstatCommand.java | 212 --
.../internal/cli/commands/PDXCommands.java | 195 ++
.../internal/cli/commands/PDXRenameCommand.java | 81 -
.../internal/cli/commands/QueueCommands.java | 259 +++
.../internal/cli/commands/RegionCommands.java | 474 +++++
.../cli/commands/RegionCommandsUtils.java | 59 -
.../commands/RevokeMissingDiskStoreCommand.java | 61 -
.../internal/cli/commands/ShellCommands.java | 5 +-
.../cli/commands/ShowDeadlockCommand.java | 92 -
.../internal/cli/commands/ShowLogCommand.java | 102 -
.../cli/commands/ShowMetricsCommand.java | 1085 ----------
.../commands/ShowMissingDiskStoreCommand.java | 150 --
.../internal/cli/commands/ShutdownCommand.java | 209 --
.../cli/commands/StartLocatorCommand.java | 67 +-
.../cli/commands/StartMemberCommand.java | 248 ---
.../internal/cli/commands/StartMemberUtils.java | 251 +++
.../cli/commands/StartServerCommand.java | 117 +-
.../StatusClusterConfigServiceCommand.java | 82 -
.../internal/cli/commands/StatusCommands.java | 82 +
.../internal/cli/commands/UndeployCommand.java | 114 --
.../UpgradeOfflineDiskStoreCommand.java | 177 --
.../cli/commands/ValidateDiskStoreCommand.java | 105 -
.../commands/lifecycle/StopLocatorCommand.java | 16 +-
.../internal/cli/converters/HelpConverter.java | 25 +-
.../functions/CreateDefinedIndexesFunction.java | 3 +-
.../cli/functions/DataCommandFunction.java | 8 +-
.../GetSubscriptionQueueSizeFunction.java | 2 +-
.../cli/functions/RegionCreateFunction.java | 8 +-
.../management/internal/cli/help/Helper.java | 20 +-
.../internal/cli/i18n/CliStrings.java | 397 +++-
.../controllers/ConfigCommandsController.java | 17 +-
.../controllers/DeployCommandsController.java | 24 +-
.../DiskStoreCommandsController.java | 18 +-
.../DurableClientCommandsController.java | 15 +-
.../controllers/FunctionCommandsController.java | 13 +-
.../controllers/IndexCommandsController.java | 13 +-
.../controllers/MemberCommandsController.java | 23 +-
.../MiscellaneousCommandsController.java | 16 +-
.../web/controllers/PdxCommandsController.java | 11 +-
.../controllers/QueueCommandsController.java | 10 +-
.../controllers/RegionCommandsController.java | 14 +-
.../geode/redis/internal/RegionProvider.java | 15 +-
.../commands/AlterRegionCommandDUnitTest.java | 641 ------
...eateAlterDestroyRegionCommandsDUnitTest.java | 1211 ++++++++++-
.../CreateAlterDestroyRegionCommandsTest.java | 53 +
.../commands/CreateRegionCommandDUnitTest.java | 318 ---
.../cli/commands/CreateRegionCommandTest.java | 58 -
.../cli/commands/DeployCommandsDUnitTest.java | 2 +-
.../commands/DestroyRegionCommandDUnitTest.java | 388 ----
.../commands/DiskStoreCommandsDUnitTest.java | 46 +-
.../commands/DiskStoreCommandsJUnitTest.java | 112 +-
.../cli/commands/GfshCommandJUnitTest.java | 219 +-
.../cli/commands/IndexCommandsJUnitTest.java | 223 ++
...stAndDescribeDiskStoreCommandsDUnitTest.java | 36 +-
.../cli/commands/ListIndexCommandDUnitTest.java | 38 +-
.../cli/commands/ListIndexCommandJUnitTest.java | 223 --
.../cli/commands/LogLevelInterceptorTest.java | 21 +-
.../MiscellaneousCommandsDUnitTest.java | 136 +-
.../cli/commands/ShowStackTraceDUnitTest.java | 23 +-
.../commands/StartLocatorCommandUnitTest.java | 59 -
.../cli/commands/StartMemberCommandTest.java | 335 ---
.../commands/StartServerCommandUnitTest.java | 78 -
.../commands/StatusLocatorCommandUnitTest.java | 53 -
.../lifecycle/StopLocatorCommandUnitTest.java | 74 -
.../cli/help/HelperIntegrationTest.java | 73 +-
.../internal/security/TestCommand.java | 27 +-
.../org/apache/geode/redis/SetsJUnitTest.java | 21 +-
.../apache/geode/redis/SortedSetsJUnitTest.java | 34 +-
.../DurableClientCommandsDUnitTest.java | 4 +-
.../rules/RetryRuleLocalWithErrorTest.java | 2 +-
137 files changed, 12540 insertions(+), 13212 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
index 3a5538c..3f0e2c0 100644
--- a/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/BundledJarsJUnitTest.java
@@ -16,6 +16,14 @@ package org.apache.geode;
import static org.junit.Assert.assertTrue;
+import org.apache.commons.io.FileUtils;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+import org.apache.geode.test.junit.categories.RestAPITest;
+import org.apache.geode.util.test.TestUtil;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -28,20 +36,11 @@ import java.util.jar.JarFile;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import org.apache.commons.io.FileUtils;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.test.junit.categories.IntegrationTest;
-import org.apache.geode.test.junit.categories.RestAPITest;
-import org.apache.geode.util.test.TestUtil;
-
@Category({IntegrationTest.class, RestAPITest.class})
public class BundledJarsJUnitTest {
private static final String VERSION_PATTERN = "[0-9-_.v]{3,}.*\\.jar$";
- private static final String GEODE_HOME = System.getenv("GEODE_HOME");
+ protected static final String GEODE_HOME = System.getenv("GEODE_HOME");
private Set<String> expectedJars;
@Before
@@ -66,22 +65,27 @@ public class BundledJarsJUnitTest {
TreeSet<String> missingJars = new TreeSet<String>(expectedJars);
missingJars.removeAll(bundledJarNames);
- String message =
- "The bundled jars have changed. Please make sure you update the licence and notice"
- + "\nas described in https://cwiki.apache.org/confluence/display/GEODE/License+Guide+for+Contributors"
- + "\nWhen fixed, copy geode-assembly/build/test/bundled_jars.txt"
- + "\nto src/test/resources/expected_jars.txt" + "\nRemoved Jars\n--------------\n"
- + String.join("\n", missingJars) + "\n\nAdded Jars\n--------------\n"
- + String.join("\n", newJars) + "\n\n";
-
- assertTrue(message, expectedJars.equals(bundledJarNames));
+ StringBuilder message = new StringBuilder();
+ message.append(
+ "The bundled jars have changed. Please make sure you update the licence and notice");
+ message.append(
+ "\nas described in https://cwiki.apache.org/confluence/display/GEODE/License+Guide+for+Contributors");
+ message.append("\nWhen fixed, copy geode-assembly/build/test/bundled_jars.txt");
+ message.append("\nto src/test/resources/expected_jars.txt");
+ message.append("\nRemoved Jars\n--------------\n");
+ message.append(String.join("\n", missingJars));
+ message.append("\n\nAdded Jars\n--------------\n");
+ message.append(String.join("\n", newJars));
+ message.append("\n\n");
+
+ assertTrue(message.toString(), expectedJars.equals(bundledJarNames));
}
/**
* Find all of the jars bundled with the project. Key is the name of the jar, value is the path.
*/
- private TreeMap<String, String> getBundledJars() {
+ protected TreeMap<String, String> getBundledJars() {
File geodeHomeDirectory = new File(GEODE_HOME);
assertTrue(
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
index a191905..263b12c 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandIntegrationTest.java
@@ -15,11 +15,16 @@
package org.apache.geode.management.internal.cli.commands;
+import static org.assertj.core.api.Java6Assertions.assertThat;
+import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
+import java.io.FileWriter;
import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -28,12 +33,14 @@ import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
+import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.junit.rules.TestName;
+import org.apache.geode.internal.util.IOUtils;
import org.apache.geode.test.junit.categories.IntegrationTest;
@Category(IntegrationTest.class)
@@ -45,8 +52,60 @@ public class GfshCommandIntegrationTest {
public TestName testName = new TestName();
@Test
+ public void workingDirDefaultsToMemberName() {
+ StartServerCommand startServer = new StartServerCommand();
+ String workingDir = StartMemberUtils.resolveWorkingDir(null, "server1");
+ assertThat(new File(workingDir)).exists();
+ assertThat(workingDir).endsWith("server1");
+ }
+
+ @Test
+ public void workingDirGetsCreatedIfNecessary() throws Exception {
+ File workingDir = temporaryFolder.newFolder("foo");
+ FileUtils.deleteQuietly(workingDir);
+ String workingDirString = workingDir.getAbsolutePath();
+
+ StartServerCommand startServer = new StartServerCommand();
+
+ String resolvedWorkingDir = StartMemberUtils.resolveWorkingDir(workingDirString, "server1");
+ assertThat(new File(resolvedWorkingDir)).exists();
+ assertThat(workingDirString).endsWith("foo");
+ }
+
+ @Test
+ public void testWorkingDirWithRelativePath() throws Exception {
+ Path relativePath = Paths.get("some").resolve("relative").resolve("path");
+ assertThat(relativePath.isAbsolute()).isFalse();
+
+ StartServerCommand startServer = new StartServerCommand();
+
+ String resolvedWorkingDir =
+ StartMemberUtils.resolveWorkingDir(relativePath.toString(), "server1");
+
+ assertThat(resolvedWorkingDir).isEqualTo(relativePath.toAbsolutePath().toString());
+ }
+
+ @Test
+ public void testReadPid() throws IOException {
+ final int expectedPid = 12345;
+
+ File folder = temporaryFolder.newFolder();
+ File pidFile =
+ new File(folder, getClass().getSimpleName() + "_" + testName.getMethodName() + ".pid");
+
+ assertTrue(pidFile.createNewFile());
+
+ pidFile.deleteOnExit();
+ writePid(pidFile, expectedPid);
+
+ final int actualPid = StartMemberUtils.readPid(pidFile);
+
+ assertEquals(expectedPid, actualPid);
+ }
+
+ @Test
public void testGemFireCoreClasspath() throws IOException {
- File coreDependenciesJar = new File(StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME);
+ File coreDependenciesJar = new File(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
assertNotNull(coreDependenciesJar);
assertTrue(coreDependenciesJar + " is not a file", coreDependenciesJar.isFile());
Collection<String> expectedJarDependencies =
@@ -108,5 +167,11 @@ public class GfshCommandIntegrationTest {
missingExpectedJarDependenciesList.isEmpty());
}
-
+ private void writePid(final File pidFile, final int pid) throws IOException {
+ final FileWriter fileWriter = new FileWriter(pidFile, false);
+ fileWriter.write(String.valueOf(pid));
+ fileWriter.write("\n");
+ fileWriter.flush();
+ IOUtils.close(fileWriter);
+ }
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
new file mode 100644
index 0000000..6e5d17c
--- /dev/null
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/LauncherLifecycleCommandsDUnitTest.java
@@ -0,0 +1,1115 @@
+/*
+ * 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.DURABLE_CLIENT_ID;
+import static org.apache.geode.distributed.ConfigurationProperties.START_LOCATOR;
+import static org.apache.geode.test.dunit.Assert.assertEquals;
+import static org.apache.geode.test.dunit.Assert.assertFalse;
+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.Wait.waitForCriterion;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.lang.management.ManagementFactory;
+import java.net.InetAddress;
+import java.nio.charset.Charset;
+import java.text.DateFormat;
+import java.text.MessageFormat;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Queue;
+import java.util.Set;
+import java.util.concurrent.ConcurrentLinkedDeque;
+import java.util.concurrent.TimeUnit;
+
+import javax.management.MBeanServerConnection;
+import javax.management.ObjectName;
+import javax.management.Query;
+import javax.management.QueryExp;
+import javax.management.remote.JMXConnector;
+import javax.management.remote.JMXConnectorFactory;
+import javax.management.remote.JMXServiceURL;
+
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.runners.MethodSorters;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.client.ClientCache;
+import org.apache.geode.cache.client.ClientCacheFactory;
+import org.apache.geode.cache.client.ClientRegionFactory;
+import org.apache.geode.cache.client.ClientRegionShortcut;
+import org.apache.geode.cache.client.Pool;
+import org.apache.geode.cache.client.PoolFactory;
+import org.apache.geode.cache.client.PoolManager;
+import org.apache.geode.distributed.AbstractLauncher.ServiceState;
+import org.apache.geode.distributed.AbstractLauncher.Status;
+import org.apache.geode.distributed.LocatorLauncher;
+import org.apache.geode.distributed.LocatorLauncher.Builder;
+import org.apache.geode.distributed.LocatorLauncher.Command;
+import org.apache.geode.distributed.LocatorLauncher.LocatorState;
+import org.apache.geode.distributed.ServerLauncher;
+import org.apache.geode.distributed.ServerLauncher.ServerState;
+import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.lang.ObjectUtils;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.internal.lang.SystemUtils;
+import org.apache.geode.internal.process.ProcessType;
+import org.apache.geode.internal.process.ProcessUtils;
+import org.apache.geode.internal.util.IOUtils;
+import org.apache.geode.management.cli.Result;
+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.WaitCriterion;
+import org.apache.geode.test.junit.categories.DistributedTest;
+
+/**
+ * The LauncherLifecycleCommandsDUnitTest class is a test suite of integration tests testing the
+ * contract and functionality of the GemFire launcher lifecycle commands inside Gfsh.
+ *
+ * @see javax.management.MBeanServerConnection
+ * @see javax.management.remote.JMXConnector
+ * @see org.apache.geode.distributed.AbstractLauncher
+ * @see org.apache.geode.distributed.LocatorLauncher
+ * @see org.apache.geode.distributed.ServerLauncher
+ * @see org.apache.geode.internal.AvailablePortHelper
+ * @see org.apache.geode.management.internal.cli.shell.Gfsh
+ * @see org.apache.geode.management.internal.cli.commands.CliCommandTestBase
+ * @see org.apache.geode.management.internal.cli.util.CommandStringBuilder
+ * @since GemFire 7.0
+ */
+@Category(DistributedTest.class)
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+public class LauncherLifecycleCommandsDUnitTest extends CliCommandTestBase {
+
+ protected static final DateFormat TIMESTAMP = new SimpleDateFormat("yyyyMMddHHmmssSSS");
+
+ private final Queue<Integer> processIds = new ConcurrentLinkedDeque<>();
+
+ protected static String getMemberId(final int jmxManagerPort, final String memberName)
+ throws Exception {
+ return getMemberId(InetAddress.getLocalHost().getHostName(), jmxManagerPort, memberName);
+ }
+
+ protected static String getMemberId(final String jmxManagerHost, final int jmxManagerPort,
+ final String memberName) throws Exception {
+ JMXConnector connector = null;
+
+ try {
+ connector = JMXConnectorFactory.connect(new JMXServiceURL(String.format(
+ "service:jmx:rmi://%1$s/jndi/rmi://%1$s:%2$d/jmxrmi", jmxManagerHost, jmxManagerPort)));
+
+ MBeanServerConnection connection = connector.getMBeanServerConnection();
+
+ ObjectName objectNamePattern = ObjectName.getInstance("GemFire:type=Member,*");
+
+ QueryExp query = Query.eq(Query.attr("Name"), Query.value(memberName));
+
+ Set<ObjectName> objectNames = connection.queryNames(objectNamePattern, query);
+
+ assertNotNull(objectNames);
+ assertFalse(objectNames.isEmpty());
+ assertEquals(1, objectNames.size());
+
+ // final ObjectName objectName = ObjectName.getInstance("GemFire:type=Member,Name=" +
+ // memberName);
+ ObjectName objectName = objectNames.iterator().next();
+
+ // System.err.printf("ObjectName for Member with Name (%1$s) is %2$s%n", memberName,
+ // objectName);
+
+ return ObjectUtils.toString(connection.getAttribute(objectName, "Id"));
+ } finally {
+ IOUtils.close(connector);
+ }
+ }
+
+ @Override
+ public final void postTearDown() throws Exception {
+ Integer pid;
+
+ while ((pid = processIds.poll()) != null) {
+ if (ProcessUtils.isProcessAlive(pid)) {
+ try {
+ String killCommand = String.format("%1$s %2$d",
+ SystemUtils.isWindows() ? "taskkill /F /PID" : "kill -9", pid);
+ Runtime.getRuntime().exec(killCommand);
+ } catch (Throwable ignore) {
+ }
+ }
+ }
+ }
+
+ @SuppressWarnings("unused")
+ protected void assertStatus(final LocatorState expectedStatus, final LocatorState actualStatus) {
+ assertEquals(expectedStatus.getStatus(), actualStatus.getStatus());
+ assertEquals(expectedStatus.getTimestamp(), actualStatus.getTimestamp());
+ assertEquals(expectedStatus.getServiceLocation(), actualStatus.getServiceLocation());
+ assertTrue(ObjectUtils.equalsIgnoreNull(expectedStatus.getPid(), actualStatus.getPid()));
+ assertEquals(expectedStatus.getUptime(), actualStatus.getUptime());
+ assertEquals(expectedStatus.getWorkingDirectory(), actualStatus.getWorkingDirectory());
+ assertEquals(expectedStatus.getJvmArguments(), actualStatus.getJvmArguments());
+ assertEquals(expectedStatus.getClasspath(), actualStatus.getClasspath());
+ assertEquals(expectedStatus.getGemFireVersion(), actualStatus.getGemFireVersion());
+ assertEquals(expectedStatus.getJavaVersion(), actualStatus.getJavaVersion());
+ }
+
+ protected Integer readPid(final File workingDirectory) throws IOException {
+ assertTrue(String.format("The working directory (%1$s) must exist!", workingDirectory),
+ workingDirectory != null && workingDirectory.isDirectory());
+
+ File[] files = workingDirectory.listFiles(pathname -> (pathname != null && pathname.isFile()
+ && pathname.getAbsolutePath().endsWith(".pid")));
+
+ assertNotNull(files);
+ assertTrue(files.length > 0);
+
+ File pidFile = files[0];
+
+ BufferedReader fileReader = null;
+
+ try {
+ fileReader = new BufferedReader(new FileReader(pidFile), 1024);
+ return Integer.parseInt(fileReader.readLine().trim());
+ } catch (Exception ignore) {
+ return null;
+ } finally {
+ IOUtils.close(fileReader);
+ }
+ }
+
+ protected String serviceStateStatusStringNormalized(final ServiceState serviceState) {
+ return serviceStateStatusStringNormalized(serviceState.toString());
+ }
+
+ protected String serviceStateStatusStringNormalized(final String serviceStateStatus) {
+ assertNotNull(serviceStateStatus);
+ assertTrue("serviceStateStatus is missing 'Uptime': " + serviceStateStatus,
+ serviceStateStatus.contains("Uptime"));
+ assertTrue("serviceStateStatus is missing 'JVM Arguments': " + serviceStateStatus,
+ serviceStateStatus.contains("JVM Arguments"));
+
+ return serviceStateStatus.substring(0, serviceStateStatus.indexOf("Uptime"))
+ .concat(serviceStateStatus.substring(serviceStateStatus.indexOf("JVM Arguments")));
+ }
+
+ protected Status stopLocator(final File workingDirectory) {
+ return stopLocator(IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDirectory));
+ }
+
+ protected Status stopLocator(final String workingDirectory) {
+ return waitForGemFireProcessToStop(
+ new Builder().setCommand(Command.STOP).setWorkingDirectory(workingDirectory).build().stop(),
+ workingDirectory);
+ }
+
+ protected Status stopServer(final String workingDirectory) {
+ return waitForGemFireProcessToStop(
+ new ServerLauncher.Builder().setCommand(ServerLauncher.Command.STOP)
+ .setWorkingDirectory(workingDirectory).build().stop(),
+ workingDirectory);
+ }
+
+ protected String toString(final Result result) {
+ assert result != null : "The Result object from the command execution cannot be null!";
+
+ StringBuilder buffer = new StringBuilder(StringUtils.LINE_SEPARATOR);
+
+ while (result.hasNextLine()) {
+ buffer.append(result.nextLine());
+ buffer.append(StringUtils.LINE_SEPARATOR);
+ }
+
+ return buffer.toString();
+ }
+
+ protected Status waitForGemFireProcessToStop(final ServiceState serviceState,
+ final String workingDirectory) {
+ if (!Status.STOPPED.equals(serviceState.getStatus())) {
+ try {
+ final Integer pid = readPid(new File(workingDirectory));
+
+ if (pid != null) {
+ WaitCriterion waitCriteria = new WaitCriterion() {
+ @Override
+ public boolean done() {
+ return !ProcessUtils.isProcessAlive(pid);
+ }
+
+ @Override
+ public String description() {
+ return String.format("Waiting for GemFire Process with PID (%1$d) to stop.", pid);
+ }
+ };
+
+ waitForCriterion(waitCriteria, TimeUnit.SECONDS.toMillis(15),
+ TimeUnit.SECONDS.toMillis(5), false);
+
+ if (!waitCriteria.done()) {
+ processIds.offer(pid);
+ }
+ }
+ } catch (IOException ignore) {
+ }
+ }
+
+ return serviceState.getStatus();
+ }
+
+ protected void writePid(final File pidFile, final int pid) throws IOException {
+ assertTrue("The PID file must actually exist!", pidFile != null && pidFile.isFile());
+
+ FileWriter writer = null;
+
+ try {
+ writer = new FileWriter(pidFile, false);
+ writer.write(String.valueOf(pid));
+ writer.write(System.getProperty("line.separator"));
+ writer.flush();
+ } finally {
+ IOUtils.close(writer);
+ }
+ }
+
+ @Test
+ public void test000StartLocatorCapturesOutputOnError() throws IOException {
+ final int locatorPort = AvailablePortHelper.getRandomAvailableTCPPort();
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ File workingDirectory = temporaryFolder.newFolder(pathname);
+
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ File pidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
+
+ assertTrue(pidFile.createNewFile());
+
+ writePid(pidFile, getPidOrOne());
+ pidFile.deleteOnExit();
+
+ assertTrue(pidFile.isFile());
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathname);
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+ command.addOption(CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION,
+ Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J, "-D" + DistributionConfig.GEMFIRE_PREFIX
+ + "jmx-manager-port=" + AvailablePortHelper.getRandomAvailableTCPPort());
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString,
+ resultString.contains(
+ "Exception in thread \"main\" java.lang.RuntimeException: A PID file already exists and a Locator may be running in "
+ + IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(workingDirectory)));
+ assertTrue(resultString,
+ resultString.contains(
+ "Caused by: org.apache.geode.internal.process.FileAlreadyExistsException: Pid file already exists: "
+ + IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(pidFile)));
+ }
+
+ /*
+ * This method makes an effort to get the PID of the running process. If it is unable to determine
+ * accurately, it simply returns 1.
+ */
+ private int getPidOrOne() {
+ int pid = 1;
+ String[] name = ManagementFactory.getRuntimeMXBean().getName().split("@");
+ if (name.length > 1) {
+ try {
+ pid = Integer.parseInt(name[0]);
+ } catch (NumberFormatException nex) {
+ // Ignored
+ }
+ }
+
+ return pid;
+ }
+
+ @Test
+ public void test001StartLocatorFailsFastOnMissingGemFirePropertiesFile() throws IOException {
+ String gemfirePropertiesPathname = "/path/to/missing/gemfire.properties";
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+ String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ final File workingDirectory = temporaryFolder.newFolder(pathName);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathName);
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, "0");
+ command.addOption(CliStrings.START_LOCATOR__PROPERTIES, gemfirePropertiesPathname);
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager=false");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-start=false");
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString,
+ resultString
+ .contains(MessageFormat.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE,
+ StringUtils.EMPTY, gemfirePropertiesPathname)));
+ }
+
+ /**
+ * Test to verify GEODE-2138
+ *
+ * @throws IOException
+ */
+ @Test
+ public void testVersionTitleForStartServerAndLocator() throws IOException {
+ final int locatorPort = AvailablePortHelper.getRandomAvailableTCPPort();
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ String pathnameLoc = pathname + "_loc";
+ String pathnameSer = pathname + "_ser";
+
+ File workingDirectoryLoc = temporaryFolder.newFolder(pathnameLoc);
+ File workingDirectorySer = temporaryFolder.newFolder(pathnameSer);
+
+ assertTrue(workingDirectoryLoc.isDirectory() || workingDirectoryLoc.mkdir());
+ assertTrue(workingDirectorySer.isDirectory() || workingDirectorySer.mkdir());
+
+ try {
+ // verify the start locator output does not contain string "gemfire"
+ CommandStringBuilder locCommand = new CommandStringBuilder(CliStrings.START_LOCATOR);
+ locCommand.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathnameLoc);
+ locCommand.addOption(CliStrings.START_LOCATOR__CONNECT, Boolean.FALSE.toString());
+ locCommand.addOption(CliStrings.START_LOCATOR__DIR, workingDirectoryLoc.getCanonicalPath());
+ locCommand.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+
+ CommandResult locResult = executeCommand(locCommand.toString());
+ assertNotNull(locResult);
+ assertEquals(Result.Status.OK, locResult.getStatus());
+ String locatorOutput = toString(locResult);
+ assertNotNull(locatorOutput);
+ assertTrue("Locator output was: " + locatorOutput, !locatorOutput.contains("Gemfire"));
+
+ // verify the start server output does not contain string "gemfire"
+ CommandStringBuilder serCommand = new CommandStringBuilder(CliStrings.START_SERVER);
+ serCommand.addOption(CliStrings.START_SERVER__NAME, pathnameSer);
+ serCommand.addOption(CliStrings.START_SERVER__DIR, workingDirectorySer.getCanonicalPath());
+
+ CommandResult serResult = executeCommand(serCommand.toString());
+ assertNotNull(serResult);
+ assertEquals(Result.Status.OK, serResult.getStatus());
+ String serverOutput = toString(serResult);
+
+ assertTrue("Server start output was: " + serverOutput, !serverOutput.contains("Gemfire"));
+ } finally {
+ stopLocator(workingDirectoryLoc);
+ stopServer(IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDirectorySer));
+ }
+ }
+
+ @Test
+ public void test002StartLocatorFailsFastOnMissingGemFireSecurityPropertiesFile()
+ throws IOException {
+ String gemfireSecurityPropertiesPathname = "/path/to/missing/gemfire-security.properties";
+ String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ final File workingDirectory = temporaryFolder.newFolder(pathName);
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathName);
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, "0");
+ command.addOption(CliStrings.START_LOCATOR__SECURITY_PROPERTIES,
+ gemfireSecurityPropertiesPathname);
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager=false");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-start=false");
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString,
+ resultString
+ .contains(MessageFormat.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE,
+ "Security ", gemfireSecurityPropertiesPathname)));
+ }
+
+ @Test
+ public void test003StartServerFailsFastOnMissingCacheXmlFile() throws IOException {
+ String cacheXmlPathname = "/path/to/missing/cache.xml";
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);
+ String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ final File workingDirectory = temporaryFolder.newFolder(pathName);
+
+ command.addOption(CliStrings.START_SERVER__NAME, pathName);
+ command.addOption(CliStrings.START_SERVER__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_SERVER__CACHE_XML_FILE, cacheXmlPathname);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString, resultString
+ .contains(MessageFormat.format(CliStrings.CACHE_XML_NOT_FOUND_MESSAGE, cacheXmlPathname)));
+ }
+
+ @Test
+ public void test004StartServerFailsFastOnMissingGemFirePropertiesFile() throws IOException {
+ String gemfirePropertiesFile = "/path/to/missing/gemfire.properties";
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);
+
+ String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ final File workingDirectory = temporaryFolder.newFolder(pathName);
+
+ command.addOption(CliStrings.START_SERVER__NAME, pathName);
+ command.addOption(CliStrings.START_SERVER__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_SERVER__PROPERTIES, gemfirePropertiesFile);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString,
+ resultString
+ .contains(MessageFormat.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE,
+ StringUtils.EMPTY, gemfirePropertiesFile)));
+ }
+
+ @Test
+ public void testStartServerFailsFastOnMissingPassword() throws IOException {
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);
+
+ String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ final File workingDirectory = temporaryFolder.newFolder(pathName);
+
+ command.addOption(CliStrings.START_SERVER__NAME, pathName);
+ command.addOption(CliStrings.START_SERVER__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_SERVER__USERNAME, "test");
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString, resultString.contains("password must be specified"));
+ }
+
+ @Test
+ public void test005StartServerFailsFastOnMissingGemFireSecurityPropertiesFile()
+ throws IOException {
+ String gemfireSecuritiesPropertiesFile = "/path/to/missing/gemfire-securities.properties";
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);
+
+ String pathName = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ final File workingDirectory = temporaryFolder.newFolder(pathName);
+
+ command.addOption(CliStrings.START_SERVER__NAME, pathName);
+ command.addOption(CliStrings.START_SERVER__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_SERVER__SECURITY_PROPERTIES,
+ gemfireSecuritiesPropertiesFile);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+
+ String resultString = toString(result);
+
+ assertTrue(resultString,
+ resultString
+ .contains(MessageFormat.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE,
+ "Security ", gemfireSecuritiesPropertiesFile)));
+ }
+
+ @Test
+ public void test006StartLocatorInRelativeDirectory() {
+ final int locatorPort = AvailablePortHelper.getRandomAvailableTCPPort();
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ File workingDirectory = new File(pathname);
+
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ try {
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathname);
+ command.addOption(CliStrings.START_LOCATOR__CONNECT, Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__DIR, pathname);
+ command.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+ command.addOption(CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION,
+ Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J, "-D" + DistributionConfig.GEMFIRE_PREFIX
+ + "jmx-manager-port=" + AvailablePortHelper.getRandomAvailableTCPPort());
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ String locatorOutput = toString(result);
+
+ assertNotNull(locatorOutput);
+ assertTrue("Locator output was: " + locatorOutput, locatorOutput.contains(
+ "Locator in " + IOUtils.tryGetCanonicalFileElseGetAbsoluteFile(workingDirectory)));
+ } finally {
+ stopLocator(workingDirectory);
+ }
+ }
+
+ @Test
+ public void test007StatusLocatorUsingMemberNameIDWhenGfshIsNotConnected() {
+ CommandResult result =
+ executeCommand(CliStrings.STATUS_LOCATOR + " --name=" + getTestMethodName());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+ assertEquals(
+ CliStrings.format(CliStrings.STATUS_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Locator"),
+ StringUtils.trim(toString(result)));
+ }
+
+ @Test
+ public void test008StatusLocatorUsingMemberName() throws IOException {
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+
+ final int jmxManagerPort = ports[0];
+ final int locatorPort = ports[1];
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ File workingDirectory = temporaryFolder.newFolder(pathname);
+
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ try {
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathname);
+ command.addOption(CliStrings.START_LOCATOR__CONNECT, Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+ command.addOption(CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION,
+ Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__FORCE, Boolean.TRUE.toString());
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-port=" + jmxManagerPort);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ LocatorLauncher locatorLauncher = new LocatorLauncher.Builder()
+ .setCommand(LocatorLauncher.Command.STATUS).setBindAddress(null).setPort(locatorPort)
+ .setWorkingDirectory(workingDirectory.getPath()).build();
+
+ assertNotNull(locatorLauncher);
+
+ LocatorState expectedLocatorState =
+ locatorLauncher.waitOnStatusResponse(60, 10, TimeUnit.SECONDS);
+
+ assertNotNull(expectedLocatorState);
+ assertEquals(Status.ONLINE, expectedLocatorState.getStatus());
+
+ result = executeCommand(
+ String.format("%1$s --locator=localhost[%2$d]", CliStrings.CONNECT, locatorPort));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ result = executeCommand(
+ String.format("%1$s --name=invalidLocatorMemberName", CliStrings.STATUS_LOCATOR));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+ assertEquals(
+ CliStrings.format(CliStrings.STATUS_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE,
+ "invalidLocatorMemberName"),
+ StringUtils.trim(toString(result)));
+
+ result =
+ executeCommand(String.format("%1$s --name=%2$s", CliStrings.STATUS_LOCATOR, pathname));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+ assertTrue(serviceStateStatusStringNormalized(toString(result))
+ .contains(serviceStateStatusStringNormalized(expectedLocatorState)));
+ } finally {
+ stopLocator(workingDirectory);
+ }
+ }
+
+ @Test
+ public void test009StatusLocatorUsingMemberId() throws Exception {
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+
+ final int jmxManagerPort = ports[0];
+ final int locatorPort = ports[1];
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ File workingDirectory = temporaryFolder.newFolder(pathname);
+
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ try {
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathname);
+ command.addOption(CliStrings.START_LOCATOR__CONNECT, Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+ command.addOption(CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION,
+ Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__FORCE, Boolean.TRUE.toString());
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-port=" + jmxManagerPort);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ LocatorLauncher locatorLauncher = new LocatorLauncher.Builder()
+ .setCommand(LocatorLauncher.Command.STATUS).setBindAddress(null).setPort(locatorPort)
+ .setWorkingDirectory(workingDirectory.getPath()).build();
+
+ assertNotNull(locatorLauncher);
+
+ LocatorState expectedLocatorState =
+ locatorLauncher.waitOnStatusResponse(60, 10, TimeUnit.SECONDS);
+
+ assertNotNull(expectedLocatorState);
+ assertEquals(Status.ONLINE, expectedLocatorState.getStatus());
+
+ result = executeCommand(
+ String.format("%1$s --locator=localhost[%2$d]", CliStrings.CONNECT, locatorPort));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ result = executeCommand(String.format("%1$s --name=%2$s", CliStrings.STATUS_LOCATOR,
+ getMemberId(jmxManagerPort, pathname)));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+ assertTrue(serviceStateStatusStringNormalized(toString(result))
+ .contains(serviceStateStatusStringNormalized(expectedLocatorState)));
+ } finally {
+ stopLocator(workingDirectory);
+ }
+ }
+
+ @Test
+ public void test010StopLocatorUsingMemberNameIDWhenGfshIsNotConnected() {
+ CommandResult result =
+ executeCommand(CliStrings.STOP_LOCATOR + " --name=" + getTestMethodName());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+ assertEquals(
+ CliStrings.format(CliStrings.STOP_SERVICE__GFSH_NOT_CONNECTED_ERROR_MESSAGE, "Locator"),
+ StringUtils.trim(toString(result)));
+ }
+
+ @Test
+ public void test011StopLocatorUsingMemberName() throws IOException {
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+
+ final int jmxManagerPort = ports[0];
+ final int locatorPort = ports[1];
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ File workingDirectory = temporaryFolder.newFolder(pathname);
+
+ try {
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathname);
+ command.addOption(CliStrings.START_LOCATOR__CONNECT, Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+ command.addOption(CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION,
+ Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__FORCE, Boolean.TRUE.toString());
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-port=" + jmxManagerPort);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ final LocatorLauncher locatorLauncher =
+ new Builder().setCommand(Command.STOP).setBindAddress(null).setPort(locatorPort)
+ .setWorkingDirectory(workingDirectory.getPath()).build();
+
+ assertNotNull(locatorLauncher);
+
+ LocatorState locatorStatus = locatorLauncher.waitOnStatusResponse(60, 10, TimeUnit.SECONDS);
+
+ assertNotNull(locatorStatus);
+ assertEquals(Status.ONLINE, locatorStatus.getStatus());
+
+ result = executeCommand(
+ String.format("%1$s --locator=localhost[%2$d]", CliStrings.CONNECT, locatorPort));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ result = executeCommand(
+ String.format("%1$s --name=invalidLocatorMemberName", CliStrings.STOP_LOCATOR));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.ERROR, result.getStatus());
+ assertEquals(
+ CliStrings.format(CliStrings.STOP_LOCATOR__NO_LOCATOR_FOUND_FOR_MEMBER_ERROR_MESSAGE,
+ "invalidLocatorMemberName"),
+ StringUtils.trim(toString(result)));
+
+ locatorStatus = locatorLauncher.status();
+
+ assertNotNull(locatorStatus);
+ assertEquals(Status.ONLINE, locatorStatus.getStatus());
+
+ result = executeCommand(String.format("%1$s --name=%2$s", CliStrings.STOP_LOCATOR, pathname));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ // TODO figure out what output to assert and validate on now that 'stop locator' uses Gfsh's
+ // logger
+ // and standard err/out...
+ // assertIndexDetailsEquals(CliStrings.format(CliStrings.STOP_LOCATOR__SHUTDOWN_MEMBER_MESSAGE,
+ // pathname),
+ // StringUtils.trim(toString(result)));
+
+ WaitCriterion waitCriteria = new WaitCriterion() {
+ @Override
+ public boolean done() {
+ final LocatorState locatorStatus = locatorLauncher.status();
+ return (locatorStatus != null && Status.NOT_RESPONDING.equals(locatorStatus.getStatus()));
+ }
+
+ @Override
+ public String description() {
+ return "wait for the Locator to stop; the Locator will no longer respond after it stops";
+ }
+ };
+
+ waitForCriterion(waitCriteria, 15 * 1000, 5000, true);
+
+ locatorStatus = locatorLauncher.status();
+
+ assertNotNull(locatorStatus);
+ assertEquals(Status.NOT_RESPONDING, locatorStatus.getStatus());
+ } finally {
+ }
+
+ }
+
+ // @see Trac Bug # 46760
+ @Test
+ public void test012StopLocatorUsingMemberId() throws Exception {
+ final int[] ports = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+
+ final int jmxManagerPort = ports[0];
+ final int locatorPort = ports[1];
+
+ String pathname = (getClass().getSimpleName() + "_" + getTestMethodName());
+ File workingDirectory = temporaryFolder.newFolder(pathname);
+
+ try {
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_LOCATOR);
+
+ command.addOption(CliStrings.START_LOCATOR__MEMBER_NAME, pathname);
+ command.addOption(CliStrings.START_LOCATOR__CONNECT, Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_LOCATOR__PORT, String.valueOf(locatorPort));
+ command.addOption(CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION,
+ Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_LOCATOR__FORCE, Boolean.TRUE.toString());
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "http-service-port=0");
+ command.addOption(CliStrings.START_LOCATOR__J,
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "jmx-manager-port=" + jmxManagerPort);
+
+ CommandResult result = executeCommand(command.toString());
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ final LocatorLauncher locatorLauncher =
+ new Builder().setCommand(Command.STOP).setBindAddress(null).setPort(locatorPort)
+ .setWorkingDirectory(workingDirectory.getPath()).build();
+
+ assertNotNull(locatorLauncher);
+
+ LocatorState locatorState = locatorLauncher.waitOnStatusResponse(60, 10, TimeUnit.SECONDS);
+
+ assertNotNull(locatorState);
+ assertEquals(Status.ONLINE, locatorState.getStatus());
+
+ result = executeCommand(
+ String.format("%1$s --locator=localhost[%2$d]", CliStrings.CONNECT, locatorPort));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ String memberId = getMemberId(jmxManagerPort, pathname);
+
+ result = executeCommand(String.format("%1$s --name=%2$s", CliStrings.STOP_LOCATOR, memberId));
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ // TODO figure out what output to assert and validate on now that 'stop locator' uses Gfsh's
+ // logger
+ // and standard err/out...
+ // assertIndexDetailsEquals(CliStrings.format(CliStrings.STOP_LOCATOR__SHUTDOWN_MEMBER_MESSAGE,
+ // memberId),
+ // StringUtils.trim(toString(result)));
+
+ WaitCriterion waitCriteria = new WaitCriterion() {
+ @Override
+ public boolean done() {
+ LocatorState locatorState = locatorLauncher.status();
+ return (locatorState != null && Status.NOT_RESPONDING.equals(locatorState.getStatus()));
+ }
+
+ @Override
+ public String description() {
+ return "wait for the Locator to stop; the Locator will no longer respond after it stops";
+ }
+ };
+
+ waitForCriterion(waitCriteria, 15 * 1000, 5000, true);
+
+ locatorState = locatorLauncher.status();
+
+ assertNotNull(locatorState);
+ assertEquals(Status.NOT_RESPONDING, locatorState.getStatus());
+ } finally {
+ }
+ }
+
+ @Test
+ public void test014GemFireServerJvmProcessTerminatesOnOutOfMemoryError() throws Exception {
+ int ports[] = AvailablePortHelper.getRandomAvailableTCPPorts(2);
+ final int serverPort = ports[0];
+ final int locatorPort = ports[1];
+
+ String pathname = getClass().getSimpleName().concat("_").concat(getTestMethodName());
+ File workingDirectory = temporaryFolder.newFolder(pathname);
+
+ assertTrue(workingDirectory.isDirectory() || workingDirectory.mkdir());
+
+ CommandStringBuilder command = new CommandStringBuilder(CliStrings.START_SERVER);
+
+ command.addOption(CliStrings.START_SERVER__NAME,
+ pathname + TIMESTAMP.format(Calendar.getInstance().getTime()));
+ command.addOption(CliStrings.START_SERVER__SERVER_PORT, String.valueOf(serverPort));
+ command.addOption(CliStrings.START_SERVER__USE_CLUSTER_CONFIGURATION, Boolean.FALSE.toString());
+ command.addOption(CliStrings.START_SERVER__MAXHEAP, "10M");
+ command.addOption(CliStrings.START_SERVER__LOG_LEVEL, "config");
+ command.addOption(CliStrings.START_SERVER__DIR, workingDirectory.getCanonicalPath());
+ command.addOption(CliStrings.START_SERVER__CACHE_XML_FILE,
+ IOUtils.tryGetCanonicalPathElseGetAbsolutePath(writeAndGetCacheXmlFile(workingDirectory)));
+ command.addOption(CliStrings.START_SERVER__INCLUDE_SYSTEM_CLASSPATH);
+ command.addOption(CliStrings.START_SERVER__J, "-D" + DistributionConfig.GEMFIRE_PREFIX + ""
+ + START_LOCATOR + "=localhost[" + locatorPort + "]");
+
+
+ CommandResult result = executeCommand(command.toString());
+ System.out.println("result=" + result);
+
+ assertNotNull(result);
+ assertEquals(Result.Status.OK, result.getStatus());
+
+ ServerLauncher serverLauncher =
+ new ServerLauncher.Builder().setCommand(ServerLauncher.Command.STATUS)
+ .setWorkingDirectory(IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDirectory))
+ .build();
+
+ assertNotNull(serverLauncher);
+
+ ServerState serverState = serverLauncher.status();
+
+ assertNotNull(serverState);
+ assertEquals(Status.ONLINE, serverState.getStatus());
+
+ // Verify our GemFire Server JVM process is running!
+ assertTrue(serverState.isVmWithProcessIdRunning());
+
+ ClientCache clientCache = setupClientCache(pathname + String.valueOf(serverPort), serverPort);
+
+ assertNotNull(clientCache);
+
+ try {
+ Region<Long, String> exampleRegion = clientCache.getRegion("/Example");
+ // run the GemFire Server "out-of-town" with an OutOfMemoryError!
+ for (long index = 0; index < Long.MAX_VALUE; index++) {
+ exampleRegion.put(index, String.valueOf(index));
+ }
+ } catch (Exception ignore) {
+ System.err.printf("%1$s: %2$s%n", ignore.getClass().getName(), ignore.getMessage());
+ } finally {
+ clientCache.close();
+
+ final int serverPid = serverState.getPid();
+
+ WaitCriterion waitCriteria = new WaitCriterion() {
+ @Override
+ public boolean done() {
+ return !ProcessUtils.isProcessAlive(serverPid);
+ }
+
+ @Override
+ public String description() {
+ return "Wait for the GemFire Server JVM process that ran out-of-memory to exit.";
+ }
+ };
+
+ waitForCriterion(waitCriteria, TimeUnit.SECONDS.toMillis(30), TimeUnit.SECONDS.toMillis(10),
+ true);
+
+ // Verify our GemFire Server JVM process is was terminated!
+ assertFalse(serverState.isVmWithProcessIdRunning());
+
+ serverState = serverLauncher.status();
+
+ assertNotNull(serverState);
+ assertEquals(Status.NOT_RESPONDING, serverState.getStatus());
+ }
+ }
+
+ private File writeAndGetCacheXmlFile(final File workingDirectory) throws IOException {
+ File cacheXml = new File(workingDirectory, "cache.xml");
+ StringBuilder buffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
+
+ buffer.append(StringUtils.LINE_SEPARATOR);
+ buffer.append(
+ "<!DOCTYPE cache PUBLIC \"-//GemStone Systems, Inc.//GemFire Declarative Caching 7.0//EN\"");
+ buffer.append(StringUtils.LINE_SEPARATOR);
+ buffer.append(" \"http://www.gemstone.com/dtd/cache7_0.dtd\">");
+ buffer.append(StringUtils.LINE_SEPARATOR);
+ buffer.append("<cache>");
+ buffer.append(StringUtils.LINE_SEPARATOR);
+ buffer.append(" <region name=\"Example\" refid=\"REPLICATE\"/>");
+ buffer.append(StringUtils.LINE_SEPARATOR);
+ buffer.append("</cache>");
+
+ BufferedWriter fileWriter = null;
+
+ try {
+ fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(cacheXml, false),
+ Charset.forName("UTF-8").newEncoder()));
+ fileWriter.write(buffer.toString());
+ fileWriter.flush();
+ } finally {
+ IOUtils.close(fileWriter);
+ }
+
+ return cacheXml;
+ }
+
+ private ClientCache setupClientCache(final String durableClientId, final int serverPort) {
+ ClientCache clientCache =
+ new ClientCacheFactory().set(DURABLE_CLIENT_ID, durableClientId).create();
+
+ PoolFactory poolFactory = PoolManager.createFactory();
+
+ poolFactory.setMaxConnections(10);
+ poolFactory.setMinConnections(1);
+ poolFactory.setReadTimeout(5000);
+ poolFactory.addServer("localhost", serverPort);
+
+ Pool pool = poolFactory.create("serverConnectionPool");
+
+ assertNotNull("The 'serverConnectionPool' was not properly configured and initialized!", pool);
+
+ ClientRegionFactory<Long, String> regionFactory =
+ clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY);
+
+ regionFactory.setPoolName(pool.getName());
+ regionFactory.setKeyConstraint(Long.class);
+ regionFactory.setValueConstraint(String.class);
+
+ Region<Long, String> exampleProxy = regionFactory.create("Example");
+
+ assertNotNull("The 'Example' Client Region was not properly configured and initialized",
+ exampleProxy);
+
+ return clientCache;
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandTest.java
index e9ca6dc..5a7c11c 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommandTest.java
@@ -56,9 +56,9 @@ public class StartLocatorCommandTest {
public void testLocatorClasspathOrder() {
String userClasspath = "/path/to/user/lib/app.jar:/path/to/user/classes";
String expectedClasspath =
- locatorCommands.getGemFireJarPath().concat(File.pathSeparator).concat(userClasspath)
+ StartMemberUtils.getGemFireJarPath().concat(File.pathSeparator).concat(userClasspath)
.concat(File.pathSeparator).concat(System.getProperty("java.class.path"))
- .concat(File.pathSeparator).concat(StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME);
+ .concat(File.pathSeparator).concat(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
String actualClasspath = locatorCommands.getLocatorClasspath(true, userClasspath);
assertEquals(expectedClasspath, actualClasspath);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandTest.java
index a5012f3..e704248 100644
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandTest.java
+++ b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/commands/StartServerCommandTest.java
@@ -54,8 +54,8 @@ public class StartServerCommandTest {
public void testServerClasspathOrder() {
String userClasspath = "/path/to/user/lib/app.jar:/path/to/user/classes";
String expectedClasspath =
- serverCommands.getGemFireJarPath().concat(File.pathSeparator).concat(userClasspath)
- .concat(File.pathSeparator).concat(StartMemberCommand.CORE_DEPENDENCIES_JAR_PATHNAME);
+ StartMemberUtils.getGemFireJarPath().concat(File.pathSeparator).concat(userClasspath)
+ .concat(File.pathSeparator).concat(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
String actualClasspath = serverCommands.getServerClasspath(false, userClasspath);
assertEquals(expectedClasspath, actualClasspath);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusClusterConfigServiceCommandTest.java
----------------------------------------------------------------------
diff --git a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusClusterConfigServiceCommandTest.java b/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusClusterConfigServiceCommandTest.java
deleted file mode 100755
index 15b4f8b..0000000
--- a/geode-assembly/src/test/java/org/apache/geode/management/internal/cli/shell/GfshExitCodeStatusClusterConfigServiceCommandTest.java
+++ /dev/null
@@ -1,391 +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.shell;
-
-import static java.util.concurrent.TimeUnit.MINUTES;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import junitparams.JUnitParamsRunner;
-import junitparams.Parameters;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.runner.RunWith;
-
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.ExitCode;
-import org.apache.geode.internal.process.PidFile;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.management.internal.cli.util.ThreePhraseGenerator;
-import org.apache.geode.test.dunit.rules.gfsh.GfshExecution;
-import org.apache.geode.test.dunit.rules.gfsh.GfshRule;
-import org.apache.geode.test.dunit.rules.gfsh.GfshScript;
-import org.apache.geode.test.junit.categories.AcceptanceTest;
-
-// Originally created in response to GEODE-2971
-
-@Category(AcceptanceTest.class)
-@RunWith(JUnitParamsRunner.class)
-public class GfshExitCodeStatusClusterConfigServiceCommandTest {
- private static File toolsJar;
- private static final ThreePhraseGenerator nameGenerator = new ThreePhraseGenerator();
- private static final String memberControllerName = "member-controller";
-
- @Rule
- public GfshRule gfsh = new GfshRule();
- private String locatorName;
- private String serverName;
-
- private int locatorPort;
-
- // Some test configuration shorthands
- private static final TestConfiguration LOCATOR_ONLINE_BUT_NOT_CONNECTED =
- new TestConfiguration(true, false, false);
- private static final TestConfiguration LOCATOR_ONLINE_AND_CONNECTED =
- new TestConfiguration(true, false, true);
- private static final TestConfiguration BOTH_ONLINE_BUT_NOT_CONNECTED =
- new TestConfiguration(true, true, false);
- private static final TestConfiguration BOTH_ONLINE_AND_CONNECTED =
- new TestConfiguration(true, true, true);
-
- @BeforeClass
- public static void classSetup() {
- File javaHome = new File(System.getProperty("java.home"));
- String toolsPath =
- javaHome.getName().equalsIgnoreCase("jre") ? "../lib/tools.jar" : "lib/tools.jar";
- toolsJar = new File(javaHome, toolsPath);
- }
-
- @Before
- public void setup() {
- locatorName = "locator-" + nameGenerator.generate('-');
- serverName = "server-" + nameGenerator.generate('-');
- locatorPort = AvailablePort.getRandomAvailablePort(AvailablePort.SOCKET);
- }
-
- @Test
- @Parameters(
- value = {"status locator --port=-10", "status locator --pid=-1", "status server --pid=-1"})
- public void statusCommandWithInvalidOptionValueShouldFail(String cmd) {
- GfshScript.of(cmd).withName("test-frame").awaitAtMost(1, MINUTES)
- .expectExitCode(ExitCode.FATAL.getValue()).execute(gfsh);
- }
-
-
- @Test
- @Parameters(value = {"status locator --host=somehostname", "status locator --port=10334",
- "status locator --dir=.", "status server --dir=.", "status locator --name=some-locator-name",
- "status server --name=some-server-name", "status locator --pid=100",
- "status server --pid=100"})
- public void statusCommandWithValidOptionValueShouldFailWithNoMembers(String cmd) {
- GfshScript.of(cmd).withName("test-frame").awaitAtMost(1, MINUTES)
- .expectExitCode(ExitCode.FATAL.getValue()).execute(gfsh);
- }
-
-
- @Test
- public void onlineStatusCommandShouldFailWhenNotConnected_locator_name() {
- TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByName();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.FATAL);
- }
-
-
- @Test
- public void onlineStatusCommandShouldFailWhenNotConnected_server_name() {
- TestConfiguration config = BOTH_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusServerCommandByName();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.FATAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedWhenNotConnected_locator_port() {
- // --host defaults to localhost, so `status locator --port=xxx` should still succeed.
- TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByPort();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedWhenNotConnected_locator_host_and_port() {
- // Since this is still local to the testing VM's machine, `status locator --host=localhost
- // --port=xxx` should succeed
- TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByHostAndPort();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
-
-
- @Test
- public void onlineStatusCommandShouldSucceedWhenConnected_locator_name() {
- TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByName();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
-
- @Test
- public void onlineStatusCommandShouldSucceedWhenConnected_server_name() {
- TestConfiguration config = BOTH_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusServerCommandByName();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void onlineStatusCommandShouldSucceedWhenConnected_locator_port() {
- TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByPort();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void onlineStatusCommandShouldSucceedWhenConnected_locator_host_and_port() {
- TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByHostAndPort();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
-
-
- @Test
- public void offlineStatusCommandShouldSucceedWhenConnected_locator_dir() {
- TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByDir();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedWhenConnected_server_dir() {
- TestConfiguration config = BOTH_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusServerCommandByDir();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedWhenConnected_locator_pid() throws IOException {
- Assume.assumeTrue(toolsJar.exists());
- TestConfiguration config = LOCATOR_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByPid();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedWhenConnected_server_pid() throws IOException {
- Assume.assumeTrue(toolsJar.exists());
- TestConfiguration config = BOTH_ONLINE_AND_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusServerCommandByPid();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
-
-
- @Test
- public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_locator_dir() {
- TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByDir();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_server_dir() {
- TestConfiguration config = BOTH_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusServerCommandByDir();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_locator_pid()
- throws IOException {
- Assume.assumeTrue(toolsJar.exists());
- TestConfiguration config = LOCATOR_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusLocatorCommandByPid();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
- @Test
- public void offlineStatusCommandShouldSucceedEvenWhenNotConnected_server_pid()
- throws IOException {
- Assume.assumeTrue(toolsJar.exists());
- TestConfiguration config = BOTH_ONLINE_BUT_NOT_CONNECTED;
- config.startNecessaryMembers(startLocatorCommand(), startServerCommand(), gfsh);
-
- String statusCommand = statusServerCommandByPid();
- executeScriptWithExpectedExitCode(statusCommand, config, ExitCode.NORMAL);
- }
-
-
-
- private String startLocatorCommand() {
- return new CommandStringBuilder("start locator").addOption("name", locatorName)
- .addOption("port", String.valueOf(locatorPort)).toString();
- }
-
-
- private String startServerCommand() {
- return new CommandStringBuilder("start server").addOption("name", serverName).toString();
- }
-
-
- private String connectCommand() {
- return new CommandStringBuilder("connect")
- .addOption("locator", String.format("localhost[%d]", locatorPort)).toString();
- }
-
-
- private String statusServerCommandByName() {
- return new CommandStringBuilder("status server").addOption("name", serverName).toString();
- }
-
- private String statusServerCommandByDir() {
- String serverDir = gfsh.getTemporaryFolder().getRoot().toPath().resolve(memberControllerName)
- .resolve(serverName).toAbsolutePath().toString();
- return new CommandStringBuilder("status server").addOption("dir", serverDir).toString();
- }
-
-
- private String statusServerCommandByPid() throws IOException {
- int serverPid = snoopMemberFile(serverName, "server.pid");
- return new CommandStringBuilder("status server").addOption("pid", String.valueOf(serverPid))
- .toString();
- }
-
- private String statusLocatorCommandByName() {
- return new CommandStringBuilder("status locator").addOption("name", locatorName).toString();
- }
-
- private String statusLocatorCommandByPort() {
- return new CommandStringBuilder("status locator").addOption("port", String.valueOf(locatorPort))
- .toString();
- }
-
- private String statusLocatorCommandByHostAndPort() {
- return new CommandStringBuilder("status locator").addOption("host", "localhost")
- .addOption("port", String.valueOf(locatorPort)).toString();
- }
-
- private String statusLocatorCommandByDir() {
- String locatorDir = gfsh.getTemporaryFolder().getRoot().toPath().resolve(memberControllerName)
- .resolve(locatorName).toAbsolutePath().toString();
- return new CommandStringBuilder("status locator").addOption("dir", locatorDir).toString();
- }
-
-
- private String statusLocatorCommandByPid() throws IOException {
- int locatorPid = snoopMemberFile(locatorName, "locator.pid");
- return new CommandStringBuilder("status locator").addOption("pid", String.valueOf(locatorPid))
- .toString();
- }
-
- private int snoopMemberFile(String memberName, String pidFileEndsWith) throws IOException {
- File directory = gfsh.getTemporaryFolder().getRoot().toPath().resolve(memberControllerName)
- .resolve(memberName).toFile();
- File[] files = directory.listFiles();
- if (files == null) {
- throw new RuntimeException(String.format(
- "Expected directory ('%s') for member '%s' either does not denote a directory, or an I/O error occurred.",
- directory.toString(), memberName));
- }
- File pidFile = Arrays.stream(files).filter(file -> file.getName().endsWith(pidFileEndsWith))
- .findFirst().orElseThrow(() -> new RuntimeException(String
- .format("Expected member '%s' to have pid file but could not find it.", memberName)));
- return new PidFile(pidFile).readPid();
- }
-
- private void executeScriptWithExpectedExitCode(String statusCommand, TestConfiguration config,
- ExitCode expectedExit) {
-
- String[] gfshScriptCommands = config.connectedToLocator
- ? new String[] {connectCommand(), statusCommand} : new String[] {statusCommand};
- GfshScript gfshScript = GfshScript.of(gfshScriptCommands).withName("test-frame")
- .awaitAtMost(1, MINUTES).expectExitCode(expectedExit.getValue());
- if (toolsJar.exists()) {
- gfshScript.addToClasspath(toolsJar.getAbsolutePath());
- }
- gfshScript.execute(gfsh);
- }
-
-
- private static class TestConfiguration {
- TestConfiguration(boolean locatorStarted, boolean serverStarted, boolean connectedToLocator) {
- this.locatorStarted = locatorStarted;
- this.serverStarted = serverStarted;
- this.connectedToLocator = connectedToLocator;
- }
-
- private boolean locatorStarted;
- private boolean serverStarted;
- private boolean connectedToLocator;
-
- void startNecessaryMembers(String startLocator, String startServer, GfshRule gfsh) {
- if (!locatorStarted && !serverStarted) {
- return;
- }
-
- List<String> commands = new ArrayList<>();
- if (locatorStarted) {
- commands.add(startLocator);
- }
- if (serverStarted) {
- commands.add(startServer);
- }
-
- GfshExecution exec = GfshScript.of(commands.toArray(new String[] {}))
- .withName(memberControllerName).awaitAtMost(1, MINUTES).execute(gfsh);
- if (exec.getProcess().exitValue() != 0) {
- throw new RuntimeException(
- "The locator and server launcher exited with non-zero exit code. This failure is beyond the scope of this test.");
- }
- }
- }
-}
[13/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
new file mode 100644
index 0000000..84326c0
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommands.java
@@ -0,0 +1,1433 @@
+/*
+ * 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 java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.GemFireIOException;
+import org.apache.geode.SystemFailure;
+import org.apache.geode.admin.BackupStatus;
+import org.apache.geode.admin.internal.AdminDistributedSystemImpl;
+import org.apache.geode.cache.CacheExistsException;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.cache.persistence.PersistentID;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.DM;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
+import org.apache.geode.internal.cache.DiskStoreAttributes;
+import org.apache.geode.internal.cache.DiskStoreImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.internal.cache.partitioned.ColocatedRegionDetails;
+import org.apache.geode.internal.cache.persistence.PersistentMemberPattern;
+import org.apache.geode.internal.lang.ClassUtils;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateDiskStoreFunction;
+import org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction;
+import org.apache.geode.management.internal.cli.functions.DestroyDiskStoreFunction;
+import org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction;
+import org.apache.geode.management.internal.cli.functions.ShowMissingDiskStoresFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.ResultDataException;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+import org.apache.geode.management.internal.cli.util.DiskStoreCompacter;
+import org.apache.geode.management.internal.cli.util.DiskStoreNotFoundException;
+import org.apache.geode.management.internal.cli.util.DiskStoreUpgrader;
+import org.apache.geode.management.internal.cli.util.DiskStoreValidater;
+import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.messages.CompactRequest;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+/**
+ * The DiskStoreCommands class encapsulates all GemFire Disk Store commands in Gfsh.
+ *
+ * @see GfshCommand
+ * @since GemFire 7.0
+ */
+@SuppressWarnings("unused")
+public class DiskStoreCommands implements GfshCommand {
+
+ protected Set<DistributedMember> getNormalMembers(final InternalCache cache) {
+ // TODO determine what this does (as it is untested and unmockable!)
+ return CliUtil.getAllNormalMembers(cache);
+ }
+
+ /**
+ * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
+ * is persistent
+ */
+ @CliCommand(value = CliStrings.BACKUP_DISK_STORE, help = CliStrings.BACKUP_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.DATA, operation = Operation.READ)
+ public Result backupDiskStore(
+ @CliOption(key = CliStrings.BACKUP_DISK_STORE__DISKDIRS,
+ help = CliStrings.BACKUP_DISK_STORE__DISKDIRS__HELP, mandatory = true) String targetDir,
+ @CliOption(key = CliStrings.BACKUP_DISK_STORE__BASELINEDIR,
+ help = CliStrings.BACKUP_DISK_STORE__BASELINEDIR__HELP) String baselineDir) {
+
+ getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
+ Result result;
+ try {
+ InternalCache cache = getCache();
+ DM dm = cache.getDistributionManager();
+ BackupStatus backupStatus;
+
+ if (baselineDir != null && !baselineDir.isEmpty()) {
+ backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir),
+ new File(baselineDir));
+ } else {
+ backupStatus = AdminDistributedSystemImpl.backupAllMembers(dm, new File(targetDir), null);
+ }
+
+ Map<DistributedMember, Set<PersistentID>> backedupMemberDiskstoreMap =
+ backupStatus.getBackedUpDiskStores();
+
+ Set<DistributedMember> backedupMembers = backedupMemberDiskstoreMap.keySet();
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+
+ if (!backedupMembers.isEmpty()) {
+ SectionResultData backedupDiskStoresSection = crd.addSection();
+ backedupDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_BACKED_UP_DISK_STORES);
+ TabularResultData backedupDiskStoresTable = backedupDiskStoresSection.addTable();
+
+ for (DistributedMember member : backedupMembers) {
+ Set<PersistentID> backedupDiskStores = backedupMemberDiskstoreMap.get(member);
+ boolean printMember = true;
+ String memberName = member.getName();
+
+ if (memberName == null || memberName.isEmpty()) {
+ memberName = member.getId();
+ }
+ for (PersistentID persistentId : backedupDiskStores) {
+ if (persistentId != null) {
+
+ String UUID = persistentId.getUUID().toString();
+ String hostName = persistentId.getHost().getHostName();
+ String directory = persistentId.getDirectory();
+
+ if (printMember) {
+ writeToBackupDiskStoreTable(backedupDiskStoresTable, memberName, UUID, hostName,
+ directory);
+ printMember = false;
+ } else {
+ writeToBackupDiskStoreTable(backedupDiskStoresTable, "", UUID, hostName, directory);
+ }
+ }
+ }
+ }
+ } else {
+ SectionResultData noMembersBackedUp = crd.addSection();
+ noMembersBackedUp.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_NO_DISKSTORES_BACKED_UP);
+ }
+
+ Set<PersistentID> offlineDiskStores = backupStatus.getOfflineDiskStores();
+
+ if (!offlineDiskStores.isEmpty()) {
+ SectionResultData offlineDiskStoresSection = crd.addSection();
+ TabularResultData offlineDiskStoresTable = offlineDiskStoresSection.addTable();
+
+ offlineDiskStoresSection.setHeader(CliStrings.BACKUP_DISK_STORE_MSG_OFFLINE_DISK_STORES);
+ for (PersistentID offlineDiskStore : offlineDiskStores) {
+ offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID,
+ offlineDiskStore.getUUID().toString());
+ offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST,
+ offlineDiskStore.getHost().getHostName());
+ offlineDiskStoresTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY,
+ offlineDiskStore.getDirectory());
+ }
+ }
+ result = ResultBuilder.buildResult(crd);
+
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+ return result;
+ }
+
+ private void writeToBackupDiskStoreTable(TabularResultData backedupDiskStoreTable,
+ String memberId, String UUID, String host, String directory) {
+ backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_MEMBER, memberId);
+ backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_UUID, UUID);
+ backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_DIRECTORY, directory);
+ backedupDiskStoreTable.accumulate(CliStrings.BACKUP_DISK_STORE_MSG_HOST, host);
+ }
+
+ @CliCommand(value = CliStrings.LIST_DISK_STORE, help = CliStrings.LIST_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listDiskStore() {
+ try {
+ Set<DistributedMember> dataMembers = getNormalMembers(getCache());
+
+ if (dataMembers.isEmpty()) {
+ return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
+ }
+
+ return toTabularResult(getDiskStoreListing(dataMembers));
+ } catch (FunctionInvocationTargetException ignore) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_DISK_STORE));
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(
+ String.format(CliStrings.LIST_DISK_STORE__ERROR_MESSAGE, toString(t, isDebugging())));
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected List<DiskStoreDetails> getDiskStoreListing(Set<DistributedMember> members) {
+ final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
+ if (membersFunctionExecutor instanceof AbstractExecution) {
+ ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
+ }
+
+ final ResultCollector<?, ?> resultCollector =
+ membersFunctionExecutor.execute(new ListDiskStoresFunction());
+
+ final List<?> results = (List<?>) resultCollector.getResult();
+ final List<DiskStoreDetails> distributedSystemMemberDiskStores =
+ new ArrayList<>(results.size());
+
+ for (final Object result : results) {
+ if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
+ // Exceptions...
+ distributedSystemMemberDiskStores.addAll((Set<DiskStoreDetails>) result);
+ }
+ }
+
+ Collections.sort(distributedSystemMemberDiskStores);
+
+ return distributedSystemMemberDiskStores;
+ }
+
+ protected Result toTabularResult(final List<DiskStoreDetails> diskStoreList)
+ throws ResultDataException {
+ if (!diskStoreList.isEmpty()) {
+ final TabularResultData diskStoreData = ResultBuilder.createTabularResultData();
+
+ for (final DiskStoreDetails diskStoreDetails : diskStoreList) {
+ diskStoreData.accumulate("Member Name", diskStoreDetails.getMemberName());
+ diskStoreData.accumulate("Member Id", diskStoreDetails.getMemberId());
+ diskStoreData.accumulate("Disk Store Name", diskStoreDetails.getName());
+ diskStoreData.accumulate("Disk Store ID", diskStoreDetails.getId());
+ }
+
+ return ResultBuilder.buildResult(diskStoreData);
+ } else {
+ return ResultBuilder
+ .createInfoResult(CliStrings.LIST_DISK_STORE__DISK_STORES_NOT_FOUND_MESSAGE);
+ }
+ }
+
+ @CliCommand(value = CliStrings.CREATE_DISK_STORE, help = CliStrings.CREATE_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ public Result createDiskStore(
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__NAME, mandatory = true,
+ optionContext = ConverterHint.DISKSTORE,
+ help = CliStrings.CREATE_DISK_STORE__NAME__HELP) String name,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION,
+ specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
+ help = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION__HELP) boolean allowForceCompaction,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT, specifiedDefaultValue = "true",
+ unspecifiedDefaultValue = "true",
+ help = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT__HELP) boolean autoCompact,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD,
+ unspecifiedDefaultValue = "50",
+ help = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD__HELP) int compactionThreshold,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE,
+ unspecifiedDefaultValue = "1024",
+ help = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE__HELP) int maxOplogSize,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE, unspecifiedDefaultValue = "0",
+ help = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE__HELP) int queueSize,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL,
+ unspecifiedDefaultValue = "1000",
+ help = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL__HELP) long timeInterval,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE,
+ unspecifiedDefaultValue = "32768",
+ help = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE__HELP) int writeBufferSize,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE, mandatory = true,
+ help = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE__HELP) String[] directoriesAndSizes,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.CREATE_DISK_STORE__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT,
+ unspecifiedDefaultValue = "90",
+ help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT__HELP) float diskUsageWarningPercentage,
+ @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT,
+ unspecifiedDefaultValue = "99",
+ help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT__HELP) float diskUsageCriticalPercentage) {
+
+ try {
+ DiskStoreAttributes diskStoreAttributes = new DiskStoreAttributes();
+ diskStoreAttributes.allowForceCompaction = allowForceCompaction;
+ diskStoreAttributes.autoCompact = autoCompact;
+ diskStoreAttributes.compactionThreshold = compactionThreshold;
+ diskStoreAttributes.maxOplogSizeInBytes = maxOplogSize * (1024 * 1024);
+ diskStoreAttributes.queueSize = queueSize;
+ diskStoreAttributes.timeInterval = timeInterval;
+ diskStoreAttributes.writeBufferSize = writeBufferSize;
+
+ File[] directories = new File[directoriesAndSizes.length];
+ int[] sizes = new int[directoriesAndSizes.length];
+ for (int i = 0; i < directoriesAndSizes.length; i++) {
+ final int hashPosition = directoriesAndSizes[i].indexOf('#');
+ if (hashPosition == -1) {
+ directories[i] = new File(directoriesAndSizes[i]);
+ sizes[i] = Integer.MAX_VALUE;
+ } else {
+ directories[i] = new File(directoriesAndSizes[i].substring(0, hashPosition));
+ sizes[i] = Integer.parseInt(directoriesAndSizes[i].substring(hashPosition + 1));
+ }
+ }
+ diskStoreAttributes.diskDirs = directories;
+ diskStoreAttributes.diskDirSizes = sizes;
+
+ diskStoreAttributes.setDiskUsageWarningPercentage(diskUsageWarningPercentage);
+ diskStoreAttributes.setDiskUsageCriticalPercentage(diskUsageCriticalPercentage);
+
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc = CliUtil.executeFunction(new CreateDiskStoreFunction(),
+ new Object[] {name, diskStoreAttributes}, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+ + ": " + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else if (result.isSuccessful()) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", result.getMessage());
+ accumulatedData = true;
+
+ if (xmlEntity.get() == null) {
+ xmlEntity.set(result.getXmlEntity());
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult("Unable to create disk store(s).");
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+ }
+
+ return ResultBuilder.buildResult(tabularData);
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.CREATE_DISK_STORE__ERROR_WHILE_CREATING_REASON_0,
+ new Object[] {th.getMessage()}));
+ }
+ }
+
+ @CliCommand(value = CliStrings.COMPACT_DISK_STORE, help = CliStrings.COMPACT_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ public Result compactDiskStore(
+ @CliOption(key = CliStrings.COMPACT_DISK_STORE__NAME, mandatory = true,
+ optionContext = ConverterHint.DISKSTORE,
+ help = CliStrings.COMPACT_DISK_STORE__NAME__HELP) String diskStoreName,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.COMPACT_DISK_STORE__GROUP__HELP) String[] groups) {
+ Result result;
+
+ try {
+ // disk store exists validation
+ if (!diskStoreExists(diskStoreName)) {
+ result = ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.COMPACT_DISK_STORE__DISKSTORE_0_DOES_NOT_EXIST,
+ new Object[] {diskStoreName}));
+ } else {
+ InternalDistributedSystem ds = getCache().getInternalDistributedSystem();
+
+ Map<DistributedMember, PersistentID> overallCompactInfo = new HashMap<>();
+
+ Set<?> otherMembers = ds.getDistributionManager().getOtherNormalDistributionManagerIds();
+ Set<InternalDistributedMember> allMembers = new HashSet<>();
+
+ for (Object member : otherMembers) {
+ allMembers.add((InternalDistributedMember) member);
+ }
+ allMembers.add(ds.getDistributedMember());
+
+ String groupInfo = "";
+ // if groups are specified, find members in the specified group
+ if (groups != null && groups.length > 0) {
+ groupInfo = CliStrings.format(CliStrings.COMPACT_DISK_STORE__MSG__FOR_GROUP,
+ new Object[] {Arrays.toString(groups) + "."});
+ final Set<InternalDistributedMember> selectedMembers = new HashSet<>();
+ List<String> targetedGroups = Arrays.asList(groups);
+ for (InternalDistributedMember member : allMembers) {
+ List<String> memberGroups = member.getGroups();
+ if (!Collections.disjoint(targetedGroups, memberGroups)) {
+ selectedMembers.add(member);
+ }
+ }
+
+ allMembers = selectedMembers;
+ }
+
+ // allMembers should not be empty when groups are not specified - it'll
+ // have at least one member
+ if (allMembers.isEmpty()) {
+ result = ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.COMPACT_DISK_STORE__NO_MEMBERS_FOUND_IN_SPECIFED_GROUP,
+ new Object[] {Arrays.toString(groups)}));
+ } else {
+ // first invoke on local member if it exists in the targeted set
+ if (allMembers.remove(ds.getDistributedMember())) {
+ PersistentID compactedDiskStoreId = CompactRequest.compactDiskStore(diskStoreName);
+ if (compactedDiskStoreId != null) {
+ overallCompactInfo.put(ds.getDistributedMember(), compactedDiskStoreId);
+ }
+ }
+
+ // was this local member the only one? Then don't try to send
+ // CompactRequest. Otherwise, send the request to others
+ if (!allMembers.isEmpty()) {
+ // Invoke compact on all 'other' members
+ Map<DistributedMember, PersistentID> memberCompactInfo =
+ CompactRequest.send(ds.getDistributionManager(), diskStoreName, allMembers);
+ if (memberCompactInfo != null && !memberCompactInfo.isEmpty()) {
+ overallCompactInfo.putAll(memberCompactInfo);
+ memberCompactInfo.clear();
+ }
+ String notExecutedMembers = CompactRequest.getNotExecutedMembers();
+ if (notExecutedMembers != null && !notExecutedMembers.isEmpty()) {
+ LogWrapper.getInstance()
+ .info("compact disk-store \"" + diskStoreName
+ + "\" message was scheduled to be sent to but was not send to "
+ + notExecutedMembers);
+ }
+ }
+
+ // If compaction happened at all, then prepare the summary
+ if (overallCompactInfo != null && !overallCompactInfo.isEmpty()) {
+ CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
+ SectionResultData section;
+
+ Set<Entry<DistributedMember, PersistentID>> entries = overallCompactInfo.entrySet();
+
+ for (Entry<DistributedMember, PersistentID> entry : entries) {
+ String memberId = entry.getKey().getId();
+ section = compositeResultData.addSection(memberId);
+ section.addData("On Member", memberId);
+
+ PersistentID persistentID = entry.getValue();
+ if (persistentID != null) {
+ SectionResultData subSection = section.addSection("DiskStore" + memberId);
+ subSection.addData("UUID", persistentID.getUUID());
+ subSection.addData("Host", persistentID.getHost().getHostName());
+ subSection.addData("Directory", persistentID.getDirectory());
+ }
+ }
+ compositeResultData.setHeader("Compacted " + diskStoreName + groupInfo);
+ result = ResultBuilder.buildResult(compositeResultData);
+ } else {
+ result = ResultBuilder.createInfoResult(
+ CliStrings.COMPACT_DISK_STORE__COMPACTION_ATTEMPTED_BUT_NOTHING_TO_COMPACT);
+ }
+ } // all members' if
+ } // disk store exists' if
+ } catch (RuntimeException e) {
+ LogWrapper.getInstance().info(e.getMessage(), e);
+ result = ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.COMPACT_DISK_STORE__ERROR_WHILE_COMPACTING_REASON_0,
+ new Object[] {e.getMessage()}));
+ }
+
+ return result;
+ }
+
+ private boolean diskStoreExists(String diskStoreName) {
+ InternalCache cache = getCache();
+ ManagementService managementService = ManagementService.getExistingManagementService(cache);
+ DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
+ Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
+
+ Set<Entry<String, String[]>> entrySet = diskstore.entrySet();
+
+ for (Entry<String, String[]> entry : entrySet) {
+ String[] value = entry.getValue();
+ if (CliUtil.contains(value, diskStoreName)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ @CliCommand(value = CliStrings.COMPACT_OFFLINE_DISK_STORE,
+ help = CliStrings.COMPACT_OFFLINE_DISK_STORE__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ public Result compactOfflineDiskStore(
+ @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME, mandatory = true,
+ help = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
+ @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+ help = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+ @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
+ unspecifiedDefaultValue = "-1",
+ help = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
+ @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__J,
+ help = CliStrings.COMPACT_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps) {
+ Result result;
+ LogWrapper logWrapper = LogWrapper.getInstance();
+
+ StringBuilder output = new StringBuilder();
+ StringBuilder error = new StringBuilder();
+ StringBuilder errorMessage = new StringBuilder();
+ Process compacterProcess = null;
+
+ try {
+ String validatedDirectories = validatedDirectories(diskDirs);
+ if (validatedDirectories != null) {
+ throw new IllegalArgumentException(
+ "Could not find " + CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + ": \""
+ + validatedDirectories + "\"");
+ }
+
+ List<String> commandList = new ArrayList<>();
+ commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+ + File.separatorChar + "java");
+
+ configureLogging(commandList);
+
+ if (jvmProps != null && jvmProps.length != 0) {
+ commandList.addAll(Arrays.asList(jvmProps));
+ }
+ commandList.add("-classpath");
+ commandList.add(System.getProperty("java.class.path", "."));
+ commandList.add(DiskStoreCompacter.class.getName());
+
+ commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
+
+ if (diskDirs != null && diskDirs.length != 0) {
+ StringBuilder builder = new StringBuilder();
+ int arrayLength = diskDirs.length;
+ for (int i = 0; i < arrayLength; i++) {
+ if (File.separatorChar == '\\') {
+ builder.append(diskDirs[i].replace("\\", "/")); // see 46120
+ } else {
+ builder.append(diskDirs[i]);
+ }
+ if (i + 1 != arrayLength) {
+ builder.append(',');
+ }
+ }
+ commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
+ }
+ // -1 is ignore as maxOplogSize
+ commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
+
+ ProcessBuilder procBuilder = new ProcessBuilder(commandList);
+ compacterProcess = procBuilder.start();
+ InputStream inputStream = compacterProcess.getInputStream();
+ InputStream errorStream = compacterProcess.getErrorStream();
+ BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
+ BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
+
+ String line;
+ while ((line = inputReader.readLine()) != null) {
+ output.append(line).append(GfshParser.LINE_SEPARATOR);
+ }
+
+ boolean switchToStackTrace = false;
+ while ((line = errorReader.readLine()) != null) {
+ if (!switchToStackTrace && DiskStoreCompacter.STACKTRACE_START.equals(line)) {
+ switchToStackTrace = true;
+ } else if (switchToStackTrace) {
+ error.append(line).append(GfshParser.LINE_SEPARATOR);
+ } else {
+ errorMessage.append(line);
+ }
+ }
+
+ if (errorMessage.length() > 0) {
+ throw new GemFireIOException(errorMessage.toString());
+ }
+
+ // do we have to waitFor??
+ compacterProcess.destroy();
+ result = ResultBuilder.createInfoResult(output.toString());
+ } catch (IOException e) {
+ if (output.length() != 0) {
+ Gfsh.println(output.toString());
+ }
+ String fieldsMessage = (maxOplogSize != -1
+ ? CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
+ fieldsMessage += CliUtil.arrayToString(diskDirs);
+ String errorString = CliStrings.format(
+ CliStrings.COMPACT_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
+ diskStoreName, fieldsMessage);
+ result = ResultBuilder.createUserErrorResult(errorString);
+ if (logWrapper.fineEnabled()) {
+ logWrapper.fine(e.getMessage(), e);
+ }
+ } catch (GemFireIOException e) {
+ if (output.length() != 0) {
+ Gfsh.println(output.toString());
+ }
+ result = ResultBuilder.createUserErrorResult(errorMessage.toString());
+ if (logWrapper.fineEnabled()) {
+ logWrapper.fine(error.toString());
+ }
+ } catch (IllegalArgumentException e) {
+ if (output.length() != 0) {
+ Gfsh.println(output.toString());
+ }
+ result = ResultBuilder.createUserErrorResult(e.getMessage());
+ } finally {
+ if (compacterProcess != null) {
+ try {
+ // just to check whether the process has exited
+ // Process.exitValue() throws IllegalThreadStateException if Process
+ // is alive
+ compacterProcess.exitValue();
+ } catch (IllegalThreadStateException ise) {
+ // not yet terminated, destroy the process
+ compacterProcess.destroy();
+ }
+ }
+ }
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.UPGRADE_OFFLINE_DISK_STORE,
+ help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ public Result upgradeOfflineDiskStore(
+ @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, mandatory = true,
+ help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
+ @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+ help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+ @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
+ unspecifiedDefaultValue = "-1",
+ help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
+ @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J,
+ help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps)
+ throws InterruptedException {
+
+ Result result;
+ LogWrapper logWrapper = LogWrapper.getInstance();
+
+ StringBuilder output = new StringBuilder();
+ StringBuilder error = new StringBuilder();
+ StringBuilder errorMessage = new StringBuilder();
+ Process upgraderProcess = null;
+
+ try {
+ String validatedDirectories = validatedDirectories(diskDirs);
+ if (validatedDirectories != null) {
+ throw new IllegalArgumentException(
+ "Could not find " + CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + ": \""
+ + validatedDirectories + "\"");
+ }
+
+ List<String> commandList = new ArrayList<>();
+ commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+ + File.separatorChar + "java");
+
+ configureLogging(commandList);
+
+ if (jvmProps != null && jvmProps.length != 0) {
+ commandList.addAll(Arrays.asList(jvmProps));
+ }
+ commandList.add("-classpath");
+ commandList.add(System.getProperty("java.class.path", "."));
+ commandList.add(DiskStoreUpgrader.class.getName());
+
+ commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
+
+ if (diskDirs != null && diskDirs.length != 0) {
+ StringBuilder builder = new StringBuilder();
+ int arrayLength = diskDirs.length;
+ for (int i = 0; i < arrayLength; i++) {
+ if (File.separatorChar == '\\') {
+ builder.append(diskDirs[i].replace("\\", "/")); // see 46120
+ } else {
+ builder.append(diskDirs[i]);
+ }
+ if (i + 1 != arrayLength) {
+ builder.append(',');
+ }
+ }
+ commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
+ }
+ // -1 is ignore as maxOplogSize
+ commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
+
+ ProcessBuilder procBuilder = new ProcessBuilder(commandList);
+ // procBuilder.redirectErrorStream(true);
+ upgraderProcess = procBuilder.start();
+ InputStream inputStream = upgraderProcess.getInputStream();
+ InputStream errorStream = upgraderProcess.getErrorStream();
+ BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
+ BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
+
+ String line;
+ while ((line = inputReader.readLine()) != null) {
+ output.append(line).append(GfshParser.LINE_SEPARATOR);
+ }
+
+ boolean switchToStackTrace = false;
+ while ((line = errorReader.readLine()) != null) {
+ if (!switchToStackTrace && DiskStoreUpgrader.STACKTRACE_START.equals(line)) {
+ switchToStackTrace = true;
+ } else if (switchToStackTrace) {
+ error.append(line).append(GfshParser.LINE_SEPARATOR);
+ } else {
+ errorMessage.append(line);
+ }
+ }
+
+ if (errorMessage.length() > 0) {
+ throw new GemFireIOException(errorMessage.toString());
+ }
+
+ upgraderProcess.destroy();
+ result = ResultBuilder.createInfoResult(output.toString());
+ } catch (IOException e) {
+ if (output.length() != 0) {
+ Gfsh.println(output.toString());
+ }
+ String fieldsMessage = (maxOplogSize != -1
+ ? CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
+ fieldsMessage += CliUtil.arrayToString(diskDirs);
+ String errorString = CliStrings.format(
+ CliStrings.UPGRADE_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
+ diskStoreName, fieldsMessage);
+ result = ResultBuilder.createUserErrorResult(errorString);
+ if (logWrapper.fineEnabled()) {
+ logWrapper.fine(e.getMessage(), e);
+ }
+ } catch (GemFireIOException e) {
+ if (output.length() != 0) {
+ Gfsh.println(output.toString());
+ }
+ result = ResultBuilder.createUserErrorResult(errorMessage.toString());
+ if (logWrapper.fineEnabled()) {
+ logWrapper.fine(error.toString());
+ }
+ } catch (IllegalArgumentException e) {
+ if (output.length() != 0) {
+ Gfsh.println(output.toString());
+ }
+ result = ResultBuilder.createUserErrorResult(e.getMessage());
+ } finally {
+ if (upgraderProcess != null) {
+ try {
+ // just to check whether the process has exited
+ // Process.exitValue() throws IllegalStateException if Process is alive
+ upgraderProcess.exitValue();
+ } catch (IllegalThreadStateException itse) {
+ // not yet terminated, destroy the process
+ upgraderProcess.destroy();
+ }
+ }
+ }
+ return result;
+ }
+
+ private String validatedDirectories(String[] diskDirs) {
+ String invalidDirectories = null;
+ StringBuilder builder = null;
+ File diskDir;
+ for (String diskDirPath : diskDirs) {
+ diskDir = new File(diskDirPath);
+ if (!diskDir.exists()) {
+ if (builder == null) {
+ builder = new StringBuilder();
+ } else if (builder.length() != 0) {
+ builder.append(", ");
+ }
+ builder.append(diskDirPath);
+ }
+ }
+ if (builder != null) {
+ invalidDirectories = builder.toString();
+ }
+
+ return invalidDirectories;
+ }
+
+ @CliCommand(value = CliStrings.DESCRIBE_DISK_STORE, help = CliStrings.DESCRIBE_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result describeDiskStore(
+ @CliOption(key = CliStrings.MEMBER, mandatory = true,
+ optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.DESCRIBE_DISK_STORE__MEMBER__HELP) final String memberName,
+ @CliOption(key = CliStrings.DESCRIBE_DISK_STORE__NAME, mandatory = true,
+ optionContext = ConverterHint.DISKSTORE,
+ help = CliStrings.DESCRIBE_DISK_STORE__NAME__HELP) final String diskStoreName) {
+ try {
+ return toCompositeResult(getDiskStoreDescription(memberName, diskStoreName));
+ } catch (DiskStoreNotFoundException | MemberNotFoundException e) {
+ return ResultBuilder.createShellClientErrorResult(e.getMessage());
+ } catch (FunctionInvocationTargetException ignore) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_DISK_STORE));
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ return ResultBuilder
+ .createGemFireErrorResult(String.format(CliStrings.DESCRIBE_DISK_STORE__ERROR_MESSAGE,
+ memberName, diskStoreName, toString(t, isDebugging())));
+ }
+ }
+
+ protected DiskStoreDetails getDiskStoreDescription(final String memberName,
+ final String diskStoreName) {
+ final DistributedMember member = getMember(getCache(), memberName); // may throw a
+ // MemberNotFoundException
+
+ final ResultCollector<?, ?> resultCollector =
+ getMembersFunctionExecutor(Collections.singleton(member)).setArguments(diskStoreName)
+ .execute(new DescribeDiskStoreFunction());
+
+ final Object result = ((List<?>) resultCollector.getResult()).get(0);
+
+ if (result instanceof DiskStoreDetails) { // disk store details in hand...
+ return (DiskStoreDetails) result;
+ } else if (result instanceof DiskStoreNotFoundException) { // bad disk store name...
+ throw (DiskStoreNotFoundException) result;
+ } else { // unknown and unexpected return type...
+ final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);
+
+ if (isLogging()) {
+ if (cause != null) {
+ getGfsh().logSevere(String.format(
+ "Exception (%1$s) occurred while executing '%2$s' on member (%3$s) with disk store (%4$s).",
+ ClassUtils.getClassName(cause), CliStrings.DESCRIBE_DISK_STORE, memberName,
+ diskStoreName), cause);
+ } else {
+ getGfsh().logSevere(String.format(
+ "Received an unexpected result of type (%1$s) while executing '%2$s' on member (%3$s) with disk store (%4$s).",
+ ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE, memberName,
+ diskStoreName), null);
+ }
+ }
+
+ throw new RuntimeException(
+ CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
+ ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE),
+ cause);
+ }
+ }
+
+ protected Result toCompositeResult(final DiskStoreDetails diskStoreDetails) {
+ final CompositeResultData diskStoreData = ResultBuilder.createCompositeResultData();
+
+ final CompositeResultData.SectionResultData diskStoreSection = diskStoreData.addSection();
+
+ diskStoreSection.addData("Disk Store ID", diskStoreDetails.getId());
+ diskStoreSection.addData("Disk Store Name", diskStoreDetails.getName());
+ diskStoreSection.addData("Member ID", diskStoreDetails.getMemberId());
+ diskStoreSection.addData("Member Name", diskStoreDetails.getMemberName());
+ diskStoreSection.addData("Allow Force Compaction",
+ toString(diskStoreDetails.isAllowForceCompaction(), "Yes", "No"));
+ diskStoreSection.addData("Auto Compaction",
+ toString(diskStoreDetails.isAutoCompact(), "Yes", "No"));
+ diskStoreSection.addData("Compaction Threshold", diskStoreDetails.getCompactionThreshold());
+ diskStoreSection.addData("Max Oplog Size", diskStoreDetails.getMaxOplogSize());
+ diskStoreSection.addData("Queue Size", diskStoreDetails.getQueueSize());
+ diskStoreSection.addData("Time Interval", diskStoreDetails.getTimeInterval());
+ diskStoreSection.addData("Write Buffer Size", diskStoreDetails.getWriteBufferSize());
+ diskStoreSection.addData("Disk Usage Warning Percentage",
+ diskStoreDetails.getDiskUsageWarningPercentage());
+ diskStoreSection.addData("Disk Usage Critical Percentage",
+ diskStoreDetails.getDiskUsageCriticalPercentage());
+ diskStoreSection.addData("PDX Serialization Meta-Data Stored",
+ toString(diskStoreDetails.isPdxSerializationMetaDataStored(), "Yes", "No"));
+
+ final TabularResultData diskDirTable = diskStoreData.addSection().addTable();
+
+ for (DiskStoreDetails.DiskDirDetails diskDirDetails : diskStoreDetails) {
+ diskDirTable.accumulate("Disk Directory", diskDirDetails.getAbsolutePath());
+ diskDirTable.accumulate("Size", diskDirDetails.getSize());
+ }
+
+ final TabularResultData regionTable = diskStoreData.addSection().addTable();
+
+ for (DiskStoreDetails.RegionDetails regionDetails : diskStoreDetails.iterateRegions()) {
+ regionTable.accumulate("Region Path", regionDetails.getFullPath());
+ regionTable.accumulate("Region Name", regionDetails.getName());
+ regionTable.accumulate("Persistent", toString(regionDetails.isPersistent(), "Yes", "No"));
+ regionTable.accumulate("Overflow To Disk",
+ toString(regionDetails.isOverflowToDisk(), "Yes", "No"));
+ }
+
+ final TabularResultData cacheServerTable = diskStoreData.addSection().addTable();
+
+ for (DiskStoreDetails.CacheServerDetails cacheServerDetails : diskStoreDetails
+ .iterateCacheServers()) {
+ cacheServerTable.accumulate("Bind Address", cacheServerDetails.getBindAddress());
+ cacheServerTable.accumulate("Hostname for Clients", cacheServerDetails.getHostName());
+ cacheServerTable.accumulate("Port", cacheServerDetails.getPort());
+ }
+
+ final TabularResultData gatewayTable = diskStoreData.addSection().addTable();
+
+ for (DiskStoreDetails.GatewayDetails gatewayDetails : diskStoreDetails.iterateGateways()) {
+ gatewayTable.accumulate("Gateway ID", gatewayDetails.getId());
+ gatewayTable.accumulate("Persistent", toString(gatewayDetails.isPersistent(), "Yes", "No"));
+ }
+
+ final TabularResultData asyncEventQueueTable = diskStoreData.addSection().addTable();
+
+ for (DiskStoreDetails.AsyncEventQueueDetails asyncEventQueueDetails : diskStoreDetails
+ .iterateAsyncEventQueues()) {
+ asyncEventQueueTable.accumulate("Async Event Queue ID", asyncEventQueueDetails.getId());
+ }
+
+ return ResultBuilder.buildResult(diskStoreData);
+ }
+
+ @CliCommand(value = CliStrings.REVOKE_MISSING_DISK_STORE,
+ help = CliStrings.REVOKE_MISSING_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ public Result revokeMissingDiskStore(@CliOption(key = CliStrings.REVOKE_MISSING_DISK_STORE__ID,
+ mandatory = true, help = CliStrings.REVOKE_MISSING_DISK_STORE__ID__HELP) String id) {
+
+ try {
+ DistributedSystemMXBean dsMXBean =
+ ManagementService.getManagementService(getCache()).getDistributedSystemMXBean();
+ if (dsMXBean.revokeMissingDiskStores(id)) {
+ return ResultBuilder.createInfoResult("Missing disk store successfully revoked");
+ }
+
+ return ResultBuilder.createUserErrorResult("Unable to find missing disk store to revoke");
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ if (th.getMessage() == null) {
+ return ResultBuilder.createGemFireErrorResult(
+ "An error occurred while revoking missing disk stores: " + th);
+ }
+ return ResultBuilder.createGemFireErrorResult(
+ "An error occurred while revoking missing disk stores: " + th.getMessage());
+ }
+ }
+
+ @CliCommand(value = CliStrings.SHOW_MISSING_DISK_STORE,
+ help = CliStrings.SHOW_MISSING_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result showMissingDiskStore() {
+
+ try {
+ Set<DistributedMember> dataMembers = getNormalMembers(getCache());
+
+ if (dataMembers.isEmpty()) {
+ return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
+ }
+ List<Object> results = getMissingDiskStoresList(dataMembers);
+ return toMissingDiskStoresTabularResult(results);
+ } catch (FunctionInvocationTargetException ignore) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+ CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.SHOW_MISSING_DISK_STORE));
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ if (t.getMessage() == null) {
+ return ResultBuilder.createGemFireErrorResult(
+ String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t));
+ }
+ return ResultBuilder.createGemFireErrorResult(
+ String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t.getMessage()));
+ }
+ }
+
+ protected List<Object> getMissingDiskStoresList(Set<DistributedMember> members) {
+ final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
+ if (membersFunctionExecutor instanceof AbstractExecution) {
+ ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
+ }
+
+ final ResultCollector<?, ?> resultCollector =
+ membersFunctionExecutor.execute(new ShowMissingDiskStoresFunction());
+
+ final List<?> results = (List<?>) resultCollector.getResult();
+ final List<Object> distributedPersistentRecoveryDetails = new ArrayList<>(results.size());
+ for (final Object result : results) {
+ if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
+ // Exceptions...
+ distributedPersistentRecoveryDetails.addAll((Set<Object>) result);
+ }
+ }
+ return distributedPersistentRecoveryDetails;
+ }
+
+ protected Result toMissingDiskStoresTabularResult(final List<Object> resultDetails)
+ throws ResultDataException {
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+ List<PersistentMemberPattern> missingDiskStores = new ArrayList<>();
+ List<ColocatedRegionDetails> missingColocatedRegions = new ArrayList<>();
+
+ for (Object detail : resultDetails) {
+ if (detail instanceof PersistentMemberPattern) {
+ missingDiskStores.add((PersistentMemberPattern) detail);
+ } else if (detail instanceof ColocatedRegionDetails) {
+ missingColocatedRegions.add((ColocatedRegionDetails) detail);
+ } else {
+ throw new ResultDataException("Unknown type of PersistentRecoveryFailures result");
+ }
+ }
+
+ boolean hasMissingDiskStores = !missingDiskStores.isEmpty();
+ boolean hasMissingColocatedRegions = !missingColocatedRegions.isEmpty();
+ if (hasMissingDiskStores) {
+ SectionResultData missingDiskStoresSection = crd.addSection();
+ missingDiskStoresSection.setHeader("Missing Disk Stores");
+ TabularResultData missingDiskStoreData = missingDiskStoresSection.addTable();
+
+ for (PersistentMemberPattern persistentMemberDetails : missingDiskStores) {
+ missingDiskStoreData.accumulate("Disk Store ID", persistentMemberDetails.getUUID());
+ missingDiskStoreData.accumulate("Host", persistentMemberDetails.getHost());
+ missingDiskStoreData.accumulate("Directory", persistentMemberDetails.getDirectory());
+ }
+ } else {
+ SectionResultData noMissingDiskStores = crd.addSection();
+ noMissingDiskStores.setHeader("No missing disk store found");
+ }
+ if (hasMissingDiskStores || hasMissingColocatedRegions) {
+ // For clarity, separate disk store and colocated region information
+ crd.addSection().setHeader("\n");
+ }
+
+ if (hasMissingColocatedRegions) {
+ SectionResultData missingRegionsSection = crd.addSection();
+ missingRegionsSection.setHeader("Missing Colocated Regions");
+ TabularResultData missingRegionData = missingRegionsSection.addTable();
+
+ for (ColocatedRegionDetails colocatedRegionDetails : missingColocatedRegions) {
+ missingRegionData.accumulate("Host", colocatedRegionDetails.getHost());
+ missingRegionData.accumulate("Distributed Member", colocatedRegionDetails.getMember());
+ missingRegionData.accumulate("Parent Region", colocatedRegionDetails.getParent());
+ missingRegionData.accumulate("Missing Colocated Region", colocatedRegionDetails.getChild());
+ }
+ } else {
+ SectionResultData noMissingColocatedRegions = crd.addSection();
+ noMissingColocatedRegions.setHeader("No missing colocated region found");
+ }
+
+ return ResultBuilder.buildResult(crd);
+ }
+
+ @CliCommand(value = CliStrings.DESCRIBE_OFFLINE_DISK_STORE,
+ help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ public Result describeOfflineDiskStore(
+ @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
+ help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
+ @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+ help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+ @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES,
+ help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES__HELP) Boolean listPdxTypes,
+ @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME,
+ help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME__HELP) String regionName) {
+
+ try {
+ final File[] dirs = new File[diskDirs.length];
+ for (int i = 0; i < diskDirs.length; i++) {
+ dirs[i] = new File((diskDirs[i]));
+ }
+
+ if (Region.SEPARATOR.equals(regionName)) {
+ return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
+ }
+
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outputStream);
+
+ DiskStoreImpl.dumpInfo(printStream, diskStoreName, dirs, regionName, listPdxTypes);
+ return ResultBuilder.createInfoResult(outputStream.toString());
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ if (th.getMessage() == null) {
+ return ResultBuilder.createGemFireErrorResult(
+ "An error occurred while describing offline disk stores: " + th);
+ }
+ return ResultBuilder.createGemFireErrorResult(
+ "An error occurred while describing offline disk stores: " + th.getMessage());
+ }
+ }
+
+ @CliCommand(value = CliStrings.EXPORT_OFFLINE_DISK_STORE,
+ help = CliStrings.EXPORT_OFFLINE_DISK_STORE__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ public Result exportOfflineDiskStore(
+ @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
+ help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
+ @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
+ help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+ @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR, mandatory = true,
+ help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR__HELP) String dir) {
+
+ try {
+ final File[] dirs = new File[diskDirs.length];
+ for (int i = 0; i < diskDirs.length; i++) {
+ dirs[i] = new File((diskDirs[i]));
+ }
+
+ File output = new File(dir);
+
+ // Note, this can consume a lot of memory, so this should
+ // not be moved to a separate process unless we provide a way for the user
+ // to configure the size of that process.
+ DiskStoreImpl.exportOfflineSnapshot(diskStoreName, dirs, output);
+ String resultString =
+ CliStrings.format(CliStrings.EXPORT_OFFLINE_DISK_STORE__SUCCESS, diskStoreName, dir);
+ return ResultBuilder.createInfoResult(resultString);
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ LogWrapper.getInstance().warning(th.getMessage(), th);
+ return ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.EXPORT_OFFLINE_DISK_STORE__ERROR, diskStoreName, th.toString()));
+ }
+ }
+
+ private void configureLogging(final List<String> commandList) {
+ URL configUrl = LogService.class.getResource(LogService.CLI_CONFIG);
+ String configFilePropertyValue = configUrl.toString();
+ commandList.add("-Dlog4j.configurationFile=" + configFilePropertyValue);
+ }
+
+ @CliCommand(value = CliStrings.VALIDATE_DISK_STORE, help = CliStrings.VALIDATE_DISK_STORE__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE}) // offline
+ // command
+ public Result validateDiskStore(
+ @CliOption(key = CliStrings.VALIDATE_DISK_STORE__NAME, mandatory = true,
+ help = CliStrings.VALIDATE_DISK_STORE__NAME__HELP) String diskStoreName,
+ @CliOption(key = CliStrings.VALIDATE_DISK_STORE__DISKDIRS, mandatory = true,
+ help = CliStrings.VALIDATE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
+ @CliOption(key = CliStrings.VALIDATE_DISK_STORE__J,
+ help = CliStrings.VALIDATE_DISK_STORE__J__HELP) String[] jvmProps) {
+ try {
+ // create a new process ...bug 46075
+ StringBuilder dirList = new StringBuilder();
+ for (String diskDir : diskDirs) {
+ dirList.append(diskDir);
+ dirList.append(";");
+ }
+
+ List<String> commandList = new ArrayList<>();
+ commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
+ + File.separatorChar + "java");
+
+ configureLogging(commandList);
+
+ if (jvmProps != null && jvmProps.length != 0) {
+ commandList.addAll(Arrays.asList(jvmProps));
+ }
+
+ // Pass any java options on to the command
+ String opts = System.getenv("JAVA_OPTS");
+ if (opts != null) {
+ commandList.add(opts);
+ }
+ commandList.add("-classpath");
+ commandList.add(System.getProperty("java.class.path", "."));
+ commandList.add(DiskStoreValidater.class.getName());
+ commandList.add(diskStoreName);
+ commandList.add(dirList.toString());
+
+ ProcessBuilder procBuilder = new ProcessBuilder(commandList);
+ StringBuilder output = new StringBuilder();
+ String errorString = "";
+
+ Process validateDiskStoreProcess = procBuilder.redirectErrorStream(true).start();
+ InputStream inputStream = validateDiskStoreProcess.getInputStream();
+ BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
+ String line;
+
+ while ((line = br.readLine()) != null) {
+ output.append(line).append(GfshParser.LINE_SEPARATOR);
+ }
+ validateDiskStoreProcess.destroy();
+
+ output.append(errorString).append(GfshParser.LINE_SEPARATOR);
+ String resultString =
+ "Validating " + diskStoreName + GfshParser.LINE_SEPARATOR + output.toString();
+ return ResultBuilder.createInfoResult(resultString);
+ } catch (IOException ex) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.VALIDATE_DISK_STORE__MSG__IO_ERROR, diskStoreName, ex.getMessage()));
+ } catch (Exception ex) {
+ // StringPrintWriter s = new StringPrintWriter();
+ // ex.printStackTrace(s);
+ return ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.VALIDATE_DISK_STORE__MSG__ERROR, diskStoreName, ex.getMessage()));
+ }
+ }
+
+ @CliCommand(value = CliStrings.ALTER_DISK_STORE, help = CliStrings.ALTER_DISK_STORE__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ public Result alterOfflineDiskStore(
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKSTORENAME, mandatory = true,
+ help = CliStrings.ALTER_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__REGIONNAME, mandatory = true,
+ help = CliStrings.ALTER_DISK_STORE__REGIONNAME__HELP) String regionName,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__DISKDIRS,
+ help = CliStrings.ALTER_DISK_STORE__DISKDIRS__HELP, mandatory = true) String[] diskDirs,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__COMPRESSOR, specifiedDefaultValue = "none",
+ help = CliStrings.ALTER_DISK_STORE__COMPRESSOR__HELP) String compressorClassName,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL,
+ help = CliStrings.ALTER_DISK_STORE__CONCURRENCY__LEVEL__HELP) Integer concurrencyLevel,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED,
+ help = CliStrings.ALTER_DISK_STORE__STATISTICS__ENABLED__HELP) Boolean statisticsEnabled,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY,
+ help = CliStrings.ALTER_DISK_STORE__INITIAL__CAPACITY__HELP) Integer initialCapacity,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR,
+ help = CliStrings.ALTER_DISK_STORE__LOAD__FACTOR__HELP) Float loadFactor,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION,
+ help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ACTION__HELP) String lruEvictionAction,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM,
+ help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__ALGORITHM__HELP) String lruEvictionAlgo,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT,
+ help = CliStrings.ALTER_DISK_STORE__LRU__EVICTION__LIMIT__HELP) Integer lruEvictionLimit,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__OFF_HEAP,
+ help = CliStrings.ALTER_DISK_STORE__OFF_HEAP__HELP) Boolean offHeap,
+ @CliOption(key = CliStrings.ALTER_DISK_STORE__REMOVE,
+ help = CliStrings.ALTER_DISK_STORE__REMOVE__HELP, specifiedDefaultValue = "true",
+ unspecifiedDefaultValue = "false") boolean remove) {
+
+ Result result;
+
+ try {
+ File[] dirs = null;
+
+ if (diskDirs != null) {
+ dirs = new File[diskDirs.length];
+ for (int i = 0; i < diskDirs.length; i++) {
+ dirs[i] = new File((diskDirs[i]));
+ }
+ }
+
+ if (regionName.equals(Region.SEPARATOR)) {
+ return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
+ }
+
+ if ((lruEvictionAlgo != null) || (lruEvictionAction != null) || (lruEvictionLimit != null)
+ || (concurrencyLevel != null) || (initialCapacity != null) || (loadFactor != null)
+ || (compressorClassName != null) || (offHeap != null) || (statisticsEnabled != null)) {
+ if (!remove) {
+ String lruEvictionLimitString =
+ lruEvictionLimit == null ? null : lruEvictionLimit.toString();
+ String concurrencyLevelString =
+ concurrencyLevel == null ? null : concurrencyLevel.toString();
+ String initialCapacityString =
+ initialCapacity == null ? null : initialCapacity.toString();
+ String loadFactorString = loadFactor == null ? null : loadFactor.toString();
+ String statisticsEnabledString =
+ statisticsEnabled == null ? null : statisticsEnabled.toString();
+ String offHeapString = offHeap == null ? null : offHeap.toString();
+
+ if ("none".equals(compressorClassName)) {
+ compressorClassName = "";
+ }
+
+ String resultMessage = DiskStoreImpl.modifyRegion(diskStoreName, dirs, "/" + regionName,
+ lruEvictionAlgo, lruEvictionAction, lruEvictionLimitString, concurrencyLevelString,
+ initialCapacityString, loadFactorString, compressorClassName, statisticsEnabledString,
+ offHeapString, false);
+
+ result = ResultBuilder.createInfoResult(resultMessage);
+ } else {
+ result = ResultBuilder.createParsingErrorResult(
+ "Cannot use the --remove=true parameter with any other parameters");
+ }
+ } else {
+ if (remove) {
+ DiskStoreImpl.destroyRegion(diskStoreName, dirs, "/" + regionName);
+ result = ResultBuilder.createInfoResult("The region " + regionName
+ + " was successfully removed from the disk store " + diskStoreName);
+ } else {
+ // Please provide an option
+ result = ResultBuilder.createParsingErrorResult("Please provide a relevant parameter");
+ }
+ }
+ // Catch the IllegalArgumentException thrown by the modifyDiskStore function and sent the
+ } catch (IllegalArgumentException e) {
+ String message = "Please check the parameters";
+ message += "\n" + e.getMessage();
+ result = ResultBuilder.createGemFireErrorResult(message);
+ } catch (IllegalStateException e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ } catch (CacheExistsException e) {
+ // Indicates that the command is being used when a cache is open
+ result = ResultBuilder.createGemFireErrorResult("Cannot execute "
+ + CliStrings.ALTER_DISK_STORE + " when a cache exists (Offline command)");
+ } catch (Exception e) {
+ result = createErrorResult(e.getMessage());
+ }
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.DESTROY_DISK_STORE, help = CliStrings.DESTROY_DISK_STORE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.DISK)
+ public Result destroyDiskStore(
+ @CliOption(key = CliStrings.DESTROY_DISK_STORE__NAME, mandatory = true,
+ help = CliStrings.DESTROY_DISK_STORE__NAME__HELP) String name,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.DESTROY_DISK_STORE__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) String[] groups) {
+ try {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc = CliUtil.executeFunction(new DestroyDiskStoreFunction(),
+ new Object[] {name}, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+ + ": " + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else if (result.getMessage() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", result.getMessage());
+ accumulatedData = true;
+
+ if (xmlEntity.get() == null) {
+ xmlEntity.set(result.getXmlEntity());
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult("No matching disk stores found.");
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), groups));
+ }
+
+ return result;
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.DESTROY_DISK_STORE__ERROR_WHILE_DESTROYING_REASON_0,
+ new Object[] {th.getMessage()}));
+ }
+ }
+
+ private Result createErrorResult(String message) {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(message);
+ return ResultBuilder.buildResult(erd);
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java
deleted file mode 100644
index 14aedf9..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsUtils.java
+++ /dev/null
@@ -1,60 +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 java.io.File;
-import java.net.URL;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.management.internal.cli.CliUtil;
-
-class DiskStoreCommandsUtils {
- static void configureLogging(final List<String> commandList) {
- URL configUrl = LogService.class.getResource(LogService.CLI_CONFIG);
- String configFilePropertyValue = configUrl.toString();
- commandList.add("-Dlog4j.configurationFile=" + configFilePropertyValue);
- }
-
- static String validatedDirectories(String[] diskDirs) {
- String invalidDirectories = null;
- StringBuilder builder = null;
- File diskDir;
- for (String diskDirPath : diskDirs) {
- diskDir = new File(diskDirPath);
- if (!diskDir.exists()) {
- if (builder == null) {
- builder = new StringBuilder();
- } else if (builder.length() != 0) {
- builder.append(", ");
- }
- builder.append(diskDirPath);
- }
- }
- if (builder != null) {
- invalidDirectories = builder.toString();
- }
- return invalidDirectories;
- }
-
- static Set<DistributedMember> getNormalMembers(final InternalCache cache) {
- // TODO determine what this does (as it is untested and unmockable!)
- return CliUtil.getAllNormalMembers(cache);
- }
-}
[04/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
index ad3de8f..fd28fed 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MiscellaneousCommandsController.java
@@ -14,6 +14,9 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -21,23 +24,12 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
* The MiscellaneousCommandsController class implements GemFire Management REST API web service
* endpoints for the Gfsh Miscellaneous Commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.ChangeLogLevelCommand
- * @see org.apache.geode.management.internal.cli.commands.ExportStackTraceCommand
- * @see org.apache.geode.management.internal.cli.commands.GCCommand
- * @see org.apache.geode.management.internal.cli.commands.NetstatCommand
- * @see org.apache.geode.management.internal.cli.commands.ShowDeadlockCommand
- * @see org.apache.geode.management.internal.cli.commands.ShowLogCommand
- * @see org.apache.geode.management.internal.cli.commands.ShowMetricsCommand
- * @see org.apache.geode.management.internal.cli.commands.ShutdownCommand
+ * @see org.apache.geode.management.internal.cli.commands.MiscellaneousCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
index 864001e..c757fd3 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/PdxCommandsController.java
@@ -14,22 +14,20 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
* The PdxCommandsController class implements GemFire Management REST API web service endpoints for
* Gfsh PDX Commands.
*
- * @see org.apache.geode.management.internal.cli.commands.PDXRenameCommand
- * @see org.apache.geode.management.internal.cli.commands.ConfigurePDXCommand
+ * @see org.apache.geode.management.internal.cli.commands.PDXCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.RequestMapping
@@ -100,6 +98,7 @@ public class PdxCommandsController extends AbstractCommandsController {
command.addOption(CliStrings.PDX_DISKDIR,
StringUtils.join(diskDirs, StringUtils.COMMA_DELIMITER));
}
+
return processCommand(command.toString());
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
index 9fea79a..02d9bcb 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/QueueCommandsController.java
@@ -14,23 +14,21 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
* The QueueCommandsController class implements GemFire Management REST API web service endpoints
* for the Gfsh Queue Commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.CreateAsyncEventQueueCommand
- * @see org.apache.geode.management.internal.cli.commands.ListAsyncEventQueuesCommand
+ * @see org.apache.geode.management.internal.cli.commands.QueueCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
index 815bc47..21f85bf 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/RegionCommandsController.java
@@ -14,6 +14,9 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -22,17 +25,12 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
- * The ListRegionCommand and DescribeRegionCommand classes implement GemFire Management REST API web
- * service endpoints for the Gfsh Region Commands.
+ * The RegionCommands class implements GemFire Management REST API web service endpoints for the
+ * Gfsh Region Commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.ListRegionCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeRegionCommand
+ * @see org.apache.geode.management.internal.cli.commands.RegionCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java b/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
index a626c62..94ff50c 100644
--- a/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
+++ b/geode-core/src/main/java/org/apache/geode/redis/internal/RegionProvider.java
@@ -40,14 +40,14 @@ import org.apache.geode.cache.query.QueryInvalidException;
import org.apache.geode.cache.query.QueryService;
import org.apache.geode.cache.query.RegionNotFoundException;
import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.redis.internal.executor.ExpirationExecutor;
+import org.apache.geode.redis.internal.executor.ListQuery;
+import org.apache.geode.redis.internal.executor.SortedSetQuery;
import org.apache.geode.internal.hll.HyperLogLogPlus;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.commands.CreateRegionCommand;
+import org.apache.geode.management.internal.cli.commands.CreateAlterDestroyRegionCommands;
import org.apache.geode.redis.GeodeRedisServer;
-import org.apache.geode.redis.internal.executor.ExpirationExecutor;
-import org.apache.geode.redis.internal.executor.ListQuery;
-import org.apache.geode.redis.internal.executor.SortedSetQuery;
/**
* This class stands between {@link Executor} and {@link Cache#getRegion(String)}. This is needed
@@ -85,7 +85,8 @@ public class RegionProvider implements Closeable {
private final ConcurrentMap<ByteArrayWrapper, ScheduledFuture<?>> expirationsMap;
private final ScheduledExecutorService expirationExecutor;
private final RegionShortcut defaultRegionType;
- private static final CreateRegionCommand createRegionCmd = new CreateRegionCommand();
+ private static final CreateAlterDestroyRegionCommands cliCmds =
+ new CreateAlterDestroyRegionCommands();
private final ConcurrentHashMap<String, Lock> locks;
public RegionProvider(Region<ByteArrayWrapper, ByteArrayWrapper> stringsRegion,
@@ -399,10 +400,10 @@ public class RegionProvider implements Closeable {
if (r != null)
return r;
do {
- Result result = createRegionCmd.createRegion(key, defaultRegionType, null, null, true, null,
+ Result result = cliCmds.createRegion(key, defaultRegionType, null, null, true, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
null, null, null, null, null, null, null, null, null, null, null, null, null, null, null,
- null, null, null);
+ null, null);
r = cache.getRegion(key);
if (result.getStatus() == Status.ERROR && r == null) {
String err = "";
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
deleted file mode 100644
index 30e8728..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/AlterRegionCommandDUnitTest.java
+++ /dev/null
@@ -1,641 +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.GROUPS;
-import static org.apache.geode.distributed.ConfigurationProperties.NAME;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.RegionAttributes;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.asyncqueue.AsyncEvent;
-import org.apache.geode.cache.asyncqueue.AsyncEventListener;
-import org.apache.geode.cache.wan.GatewaySenderFactory;
-import org.apache.geode.internal.ClassBuilder;
-import org.apache.geode.management.cli.Result;
-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.VM;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
-
-@Category(DistributedTest.class)
-public class AlterRegionCommandDUnitTest extends CliCommandTestBase {
- private final String alterRegionName = "testAlterRegionRegion";
- private final String alterAsyncEventQueueId1 = "testAlterRegionQueue1";
- private final String alterAsyncEventQueueId2 = "testAlterRegionQueue2";
- private final String alterAsyncEventQueueId3 = "testAlterRegionQueue3";
- private final String alterGatewaySenderId1 = "testAlterRegionSender1";
- private final String alterGatewaySenderId2 = "testAlterRegionSender2";
- private final String alterGatewaySenderId3 = "testAlterRegionSender3";
- private VM alterVm1;
- private String alterVm1Name;
- private VM alterVm2;
- private String alterVm2Name;
-
- private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
-
- @Ignore("bug51924")
- @Test
- public void testAlterRegion() throws IOException {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
-
- Host.getHost(0).getVM(0).invoke(() -> {
- Cache cache = getCache();
- cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
- .create(alterRegionName);
- });
-
- this.alterVm1 = Host.getHost(0).getVM(1);
- this.alterVm1Name = "VM" + this.alterVm1.getPid();
- this.alterVm1.invoke(() -> {
- Properties localProps = new Properties();
- localProps.setProperty(NAME, alterVm1Name);
- localProps.setProperty(GROUPS, "Group1");
- getSystem(localProps);
- Cache cache = getCache();
-
- // Setup queues and gateway senders to be used by all tests
- cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
- .create(alterRegionName);
- AsyncEventListener listener = new AsyncEventListener() {
- @Override
- public void close() {
- // Nothing to do
- }
-
- @Override
- public boolean processEvents(List<AsyncEvent> events) {
- return true;
- }
- };
- cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId1, listener);
- cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId2, listener);
- cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId3, listener);
-
- GatewaySenderFactory gatewaySenderFactory = cache.createGatewaySenderFactory();
- gatewaySenderFactory.setManualStart(true);
- gatewaySenderFactory.create(alterGatewaySenderId1, 2);
- gatewaySenderFactory.create(alterGatewaySenderId2, 3);
- gatewaySenderFactory.create(alterGatewaySenderId3, 4);
- });
-
- this.alterVm2 = Host.getHost(0).getVM(2);
- this.alterVm2Name = "VM" + this.alterVm2.getPid();
- this.alterVm2.invoke(() -> {
- Properties localProps = new Properties();
- localProps.setProperty(NAME, alterVm2Name);
- localProps.setProperty(GROUPS, "Group1,Group2");
- getSystem(localProps);
- Cache cache = getCache();
-
- cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
- .create(alterRegionName);
- });
-
- deployJarFilesForRegionAlter();
- regionAlterGroupTest();
- regionAlterSetAllTest();
- regionAlterNoChangeTest();
- regionAlterSetDefaultsTest();
- regionAlterManipulatePlugInsTest();
-
- this.alterVm1.invoke(() -> {
- getCache().getRegion(alterRegionName).destroyRegion();
- });
- }
-
- @Category(FlakyTest.class) // GEODE-3018
- @Test
- public void testAlterRegionResetCacheListeners() throws IOException {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
-
- Host.getHost(0).getVM(0).invoke(() -> {
- Cache cache = getCache();
- cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
- .create(alterRegionName);
- });
-
- this.alterVm1 = Host.getHost(0).getVM(1);
- this.alterVm1Name = "VM" + this.alterVm1.getPid();
- this.alterVm1.invoke(() -> {
- Properties localProps = new Properties();
- localProps.setProperty(NAME, alterVm1Name);
- localProps.setProperty(GROUPS, "Group1");
- getSystem(localProps);
- Cache cache = getCache();
-
- // Setup queues and gateway senders to be used by all tests
- cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
- .create(alterRegionName);
- });
-
- this.alterVm2 = Host.getHost(0).getVM(2);
- this.alterVm2Name = "VM" + this.alterVm2.getPid();
- this.alterVm2.invoke(() -> {
- Properties localProps = new Properties();
- localProps.setProperty(NAME, alterVm2Name);
- localProps.setProperty(GROUPS, "Group1,Group2");
- getSystem(localProps);
- Cache cache = getCache();
-
- cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
- .create(alterRegionName);
- });
-
- deployJarFilesForRegionAlter();
-
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerA,com.cadrdunit.RegionAlterCacheListenerB,com.cadrdunit.RegionAlterCacheListenerC");
-
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- String stringResult = commandResultToString(cmdResult);
-
- assertEquals(5, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(3, attributes.getCacheListeners().length);
- assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
- attributes.getCacheListeners()[0].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
- attributes.getCacheListeners()[1].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
- attributes.getCacheListeners()[2].getClass().getName());
- });
-
- // Add 1 back to each of the sets
- commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER, "''");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- stringResult = commandResultToString(cmdResult);
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(0, attributes.getCacheListeners().length);
- });
- }
-
- private void deployJarFilesForRegionAlter() throws IOException {
- ClassBuilder classBuilder = new ClassBuilder();
- final File jarFile1 = new File(new File(".").getAbsolutePath(), "testAlterRegion1.jar");
- this.filesToBeDeleted.add(jarFile1.getAbsolutePath());
- final File jarFile2 = new File(new File(".").getAbsolutePath(), "testAlterRegion2.jar");
- this.filesToBeDeleted.add(jarFile2.getAbsolutePath());
- final File jarFile3 = new File(new File(".").getAbsolutePath(), "testAlterRegion3.jar");
- this.filesToBeDeleted.add(jarFile3.getAbsolutePath());
- final File jarFile4 = new File(new File(".").getAbsolutePath(), "testAlterRegion4.jar");
- this.filesToBeDeleted.add(jarFile4.getAbsolutePath());
- final File jarFile5 = new File(new File(".").getAbsolutePath(), "testAlterRegion5.jar");
- this.filesToBeDeleted.add(jarFile5.getAbsolutePath());
-
- byte[] jarBytes =
- classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerA",
- "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
- + "public class RegionAlterCacheListenerA extends CacheListenerAdapter {}");
- writeJarBytesToFile(jarFile1, jarBytes);
- CommandResult cmdResult = executeCommand("deploy --jar=testAlterRegion1.jar");
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerB",
- "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
- + "public class RegionAlterCacheListenerB extends CacheListenerAdapter {}");
- writeJarBytesToFile(jarFile2, jarBytes);
- cmdResult = executeCommand("deploy --jar=testAlterRegion2.jar");
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerC",
- "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
- + "public class RegionAlterCacheListenerC extends CacheListenerAdapter {}");
- writeJarBytesToFile(jarFile3, jarBytes);
- cmdResult = executeCommand("deploy --jar=testAlterRegion3.jar");
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheLoader",
- "package com.cadrdunit;" + "import org.apache.geode.cache.CacheLoader;"
- + "import org.apache.geode.cache.CacheLoaderException;"
- + "import org.apache.geode.cache.LoaderHelper;"
- + "public class RegionAlterCacheLoader implements CacheLoader {"
- + "public void close() {}"
- + "public Object load(LoaderHelper helper) throws CacheLoaderException {return null;}}");
- writeJarBytesToFile(jarFile4, jarBytes);
- cmdResult = executeCommand("deploy --jar=testAlterRegion4.jar");
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheWriter",
- "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheWriterAdapter;"
- + "public class RegionAlterCacheWriter extends CacheWriterAdapter {}");
- writeJarBytesToFile(jarFile5, jarBytes);
- cmdResult = executeCommand("deploy --jar=testAlterRegion5.jar");
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- }
-
- private void regionAlterGroupTest() {
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "5764");
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- String stringResult = commandResultToString(cmdResult);
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
- });
-
- this.alterVm2.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
- });
-
- commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group2");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "6963");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- stringResult = commandResultToString(cmdResult);
- assertEquals(3, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertFalse(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
- });
-
- this.alterVm2.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(6963, attributes.getEvictionAttributes().getMaximum());
- });
- }
-
- private void regionAlterSetAllTest() {
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "35464");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, "3453");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
- "DESTROY");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, "7563");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, "DESTROY");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerA");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER,
- "com.cadrdunit.RegionAlterCacheLoader");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER,
- "com.cadrdunit.RegionAlterCacheWriter");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, "6234");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
- "DESTROY");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, "4562");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, "DESTROY");
-
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- String stringResult = commandResultToString(cmdResult);
- assertEquals(5, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- "Manager.*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
- assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
- assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
- assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
- assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
- assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
- assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
- assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
- assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
- assertEquals(1, attributes.getAsyncEventQueueIds().size());
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
- assertEquals(1, attributes.getGatewaySenderIds().size());
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
- assertEquals(1, attributes.getCacheListeners().length);
- assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
- attributes.getCacheListeners()[0].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheWriter",
- attributes.getCacheWriter().getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheLoader",
- attributes.getCacheLoader().getClass().getName());
- });
- }
-
- private void regionAlterNoChangeTest() {
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
-
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- String stringResult = commandResultToString(cmdResult);
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm2.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
- assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
- assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
- assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
- assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
- assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
- assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
- assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
- assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
- assertEquals(1, attributes.getAsyncEventQueueIds().size());
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
- assertEquals(1, attributes.getGatewaySenderIds().size());
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
- assertEquals(1, attributes.getCacheListeners().length);
- assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
- attributes.getCacheListeners()[0].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheWriter",
- attributes.getCacheWriter().getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheLoader",
- attributes.getCacheLoader().getClass().getName());
- });
- }
-
- private void regionAlterSetDefaultsTest() {
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION);
-
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- String stringResult = commandResultToString(cmdResult);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(0, attributes.getEvictionAttributes().getMaximum());
- assertEquals(0, attributes.getEntryIdleTimeout().getTimeout());
- assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
- assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
- assertTrue(attributes.getEntryTimeToLive().getAction().isInvalidate());
- assertEquals(0, attributes.getRegionIdleTimeout().getTimeout());
- assertTrue(attributes.getRegionIdleTimeout().getAction().isInvalidate());
- assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
- assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
- assertEquals(0, attributes.getAsyncEventQueueIds().size());
- assertEquals(0, attributes.getGatewaySenderIds().size());
- assertEquals(0, attributes.getCacheListeners().length);
- });
- }
-
- private void regionAlterManipulatePlugInsTest() {
-
- // Start out by putting 3 entries into each of the plug-in sets
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId2);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId3);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId2);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId3);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerA");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerB");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerC");
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- String stringResult = commandResultToString(cmdResult);
-
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(3, attributes.getAsyncEventQueueIds().size());
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
- assertEquals(3, attributes.getGatewaySenderIds().size());
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
- assertEquals(3, attributes.getCacheListeners().length);
- assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
- attributes.getCacheListeners()[0].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
- attributes.getCacheListeners()[1].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
- attributes.getCacheListeners()[2].getClass().getName());
- });
-
- // Now take 1 entry out of each of the sets
- commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId2);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId3);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerB");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerC");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- stringResult = commandResultToString(cmdResult);
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm2.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(2, attributes.getAsyncEventQueueIds().size());
- Iterator iterator = attributes.getAsyncEventQueueIds().iterator();
- assertEquals(alterAsyncEventQueueId1, iterator.next());
- assertEquals(alterAsyncEventQueueId2, iterator.next());
- assertEquals(2, attributes.getGatewaySenderIds().size());
- iterator = attributes.getGatewaySenderIds().iterator();
- assertEquals(alterGatewaySenderId1, iterator.next());
- assertEquals(alterGatewaySenderId3, iterator.next());
- assertEquals(2, attributes.getCacheListeners().length);
- assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
- attributes.getCacheListeners()[0].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
- attributes.getCacheListeners()[1].getClass().getName());
- });
-
- // Add 1 back to each of the sets
- commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
- commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId2);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
- this.alterAsyncEventQueueId3);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId1);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId3);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
- this.alterGatewaySenderId2);
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerB");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerC");
- commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
- "com.cadrdunit.RegionAlterCacheListenerA");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- stringResult = commandResultToString(cmdResult);
- assertEquals(4, countLinesInString(stringResult, false));
- assertEquals(false, stringResult.contains("ERROR"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
- assertTrue(stringContainsLine(stringResult,
- this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
-
- this.alterVm1.invoke(() -> {
- RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
- assertEquals(3, attributes.getAsyncEventQueueIds().size());
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
- assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
- assertEquals(3, attributes.getGatewaySenderIds().size());
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
- assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
- assertEquals(3, attributes.getCacheListeners().length);
- assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
- attributes.getCacheListeners()[0].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
- attributes.getCacheListeners()[1].getClass().getName());
- assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
- attributes.getCacheListeners()[2].getClass().getName());
- });
- }
-
- private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
- final OutputStream outStream = new FileOutputStream(jarFile);
- outStream.write(jarBytes);
- outStream.flush();
- outStream.close();
- }
-}
[06/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
new file mode 100644
index 0000000..3e1053a
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberUtils.java
@@ -0,0 +1,251 @@
+/*
+ * 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.LOCATORS;
+import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getDistributedSystemMXBean;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+
+import javax.management.MalformedObjectNameException;
+
+import org.apache.commons.lang.ArrayUtils;
+
+import org.apache.geode.distributed.internal.DistributionConfig;
+import org.apache.geode.internal.GemFireVersion;
+import org.apache.geode.internal.process.ProcessLauncherContext;
+import org.apache.geode.internal.util.IOUtils;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.internal.cli.util.ThreePhraseGenerator;
+
+/**
+ * Encapsulates methods used by StartServerCommand and StartLocatorCommand and their associated
+ * tests.
+ *
+ * @see StartLocatorCommand
+ * @see StartServerCommand
+ */
+public class StartMemberUtils {
+ public static final String GEODE_HOME = System.getenv("GEODE_HOME");
+
+ private static final String JAVA_HOME = System.getProperty("java.home");
+ static final int CMS_INITIAL_OCCUPANCY_FRACTION = 60;
+ private static final ThreePhraseGenerator nameGenerator = new ThreePhraseGenerator();
+
+ static final String CORE_DEPENDENCIES_JAR_PATHNAME =
+ IOUtils.appendToPath(GEODE_HOME, "lib", "geode-dependencies.jar");
+ static final String GEODE_JAR_PATHNAME =
+ IOUtils.appendToPath(GEODE_HOME, "lib", GemFireVersion.getGemFireJarFileName());
+ static final long PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS = 5 * 1000;
+ static final int INVALID_PID = -1;
+
+ static ThreePhraseGenerator getNameGenerator() {
+ return nameGenerator;
+ }
+
+ static void setPropertyIfNotNull(Properties properties, String key, Object value) {
+ if (key != null && value != null) {
+ properties.setProperty(key, value.toString());
+ }
+ }
+
+ static String resolveWorkingDir(String userSpecifiedDir, String memberName) {
+ File workingDir =
+ (userSpecifiedDir == null) ? new File(memberName) : new File(userSpecifiedDir);
+ String workingDirPath = IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDir);
+ if (!workingDir.exists()) {
+ if (!workingDir.mkdirs()) {
+ throw new IllegalStateException(String.format(
+ "Could not create directory %s. Please verify directory path or user permissions.",
+ workingDirPath));
+ }
+ }
+ return workingDirPath;
+ }
+
+ static void addGemFirePropertyFile(final List<String> commandLine,
+ final File gemfirePropertiesFile) {
+ if (gemfirePropertiesFile != null) {
+ commandLine.add("-DgemfirePropertyFile=" + gemfirePropertiesFile.getAbsolutePath());
+ }
+ }
+
+ static void addGemFireSecurityPropertyFile(final List<String> commandLine,
+ final File gemfireSecurityPropertiesFile) {
+ if (gemfireSecurityPropertiesFile != null) {
+ commandLine
+ .add("-DgemfireSecurityPropertyFile=" + gemfireSecurityPropertiesFile.getAbsolutePath());
+ }
+ }
+
+ static void addGemFireSystemProperties(final List<String> commandLine,
+ final Properties gemfireProperties) {
+ for (final Object property : gemfireProperties.keySet()) {
+ final String propertyName = property.toString();
+ final String propertyValue = gemfireProperties.getProperty(propertyName);
+ if (org.apache.geode.internal.lang.StringUtils.isNotBlank(propertyValue)) {
+ commandLine.add(
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "" + propertyName + "=" + propertyValue);
+ }
+ }
+ }
+
+ static void addJvmArgumentsAndOptions(final List<String> commandLine,
+ final String[] jvmArgsOpts) {
+ if (jvmArgsOpts != null) {
+ commandLine.addAll(Arrays.asList(jvmArgsOpts));
+ }
+ }
+
+ static void addInitialHeap(final List<String> commandLine, final String initialHeap) {
+ if (org.apache.geode.internal.lang.StringUtils.isNotBlank(initialHeap)) {
+ commandLine.add("-Xms" + initialHeap);
+ }
+ }
+
+ static void addMaxHeap(final List<String> commandLine, final String maxHeap) {
+ if (org.apache.geode.internal.lang.StringUtils.isNotBlank(maxHeap)) {
+ commandLine.add("-Xmx" + maxHeap);
+ commandLine.add("-XX:+UseConcMarkSweepGC");
+ commandLine.add("-XX:CMSInitiatingOccupancyFraction=" + CMS_INITIAL_OCCUPANCY_FRACTION);
+ // commandLine.add("-XX:MinHeapFreeRatio=" + MINIMUM_HEAP_FREE_RATIO);
+ }
+ }
+
+ static void addCurrentLocators(GfshCommand gfshCommand, final List<String> commandLine,
+ final Properties gemfireProperties) throws MalformedObjectNameException {
+ if (org.apache.geode.internal.lang.StringUtils
+ .isBlank(gemfireProperties.getProperty(LOCATORS))) {
+ String currentLocators = getCurrentLocators(gfshCommand);
+ if (org.apache.geode.internal.lang.StringUtils.isNotBlank(currentLocators)) {
+ commandLine.add("-D".concat(ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX)
+ .concat(LOCATORS).concat("=").concat(currentLocators));
+ }
+ }
+ }
+
+ private static String getCurrentLocators(GfshCommand gfshCommand)
+ throws MalformedObjectNameException {
+ String delimitedLocators = "";
+ try {
+ if (gfshCommand.isConnectedAndReady()) {
+ final DistributedSystemMXBean dsMBeanProxy = getDistributedSystemMXBean();
+ if (dsMBeanProxy != null) {
+ final String[] locators = dsMBeanProxy.listLocators();
+ if (locators != null && locators.length > 0) {
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < locators.length; i++) {
+ if (i > 0) {
+ sb.append(",");
+ }
+ sb.append(locators[i]);
+ }
+ delimitedLocators = sb.toString();
+ }
+ }
+ }
+ } catch (IOException e) { // thrown by getDistributedSystemMXBean
+ // leave delimitedLocators = ""
+ gfshCommand.getGfsh().logWarning("DistributedSystemMXBean is unavailable\n", e);
+ }
+ return delimitedLocators;
+ }
+
+ public static int readPid(final File pidFile) {
+ assert pidFile != null : "The file from which to read the process ID (pid) cannot be null!";
+ if (pidFile.isFile()) {
+ BufferedReader fileReader = null;
+ try {
+ fileReader = new BufferedReader(new FileReader(pidFile));
+ return Integer.parseInt(fileReader.readLine());
+ } catch (IOException | NumberFormatException ignore) {
+ } finally {
+ IOUtils.close(fileReader);
+ }
+ }
+ return INVALID_PID;
+ }
+
+ static String getJavaPath() {
+ return new File(new File(JAVA_HOME, "bin"), "java").getPath();
+ }
+
+ static String getSystemClasspath() {
+ return System.getProperty("java.class.path");
+ }
+
+ static String toClasspath(final boolean includeSystemClasspath, String[] jarFilePathnames,
+ String... userClasspaths) {
+ // gemfire jar must absolutely be the first JAR file on the CLASSPATH!!!
+ StringBuilder classpath = new StringBuilder(getGemFireJarPath());
+
+ userClasspaths = (userClasspaths != null ? userClasspaths : ArrayUtils.EMPTY_STRING_ARRAY);
+
+ // Then, include user-specified classes on CLASSPATH to enable the user to override GemFire JAR
+ // dependencies
+ // with application-specific versions; this logic/block corresponds to classes/jar-files
+ // specified with the
+ // --classpath option to the 'start locator' and 'start server commands'; also this will
+ // override any
+ // System CLASSPATH environment variable setting, which is consistent with the Java platform
+ // behavior...
+ for (String userClasspath : userClasspaths) {
+ if (org.apache.geode.internal.lang.StringUtils.isNotBlank(userClasspath)) {
+ classpath.append((classpath.length() == 0)
+ ? org.apache.geode.internal.lang.StringUtils.EMPTY : File.pathSeparator);
+ classpath.append(userClasspath);
+ }
+ }
+
+ // Now, include any System-specified CLASSPATH environment variable setting...
+ if (includeSystemClasspath) {
+ classpath.append(File.pathSeparator);
+ classpath.append(getSystemClasspath());
+ }
+
+ jarFilePathnames =
+ (jarFilePathnames != null ? jarFilePathnames : ArrayUtils.EMPTY_STRING_ARRAY);
+
+ // And finally, include all GemFire dependencies on the CLASSPATH...
+ for (String jarFilePathname : jarFilePathnames) {
+ if (org.apache.geode.internal.lang.StringUtils.isNotBlank(jarFilePathname)) {
+ classpath.append((classpath.length() == 0)
+ ? org.apache.geode.internal.lang.StringUtils.EMPTY : File.pathSeparator);
+ classpath.append(jarFilePathname);
+ }
+ }
+ return classpath.toString();
+ }
+
+ static String getGemFireJarPath() {
+ String classpath = getSystemClasspath();
+ String gemfireJarPath = GEODE_JAR_PATHNAME;
+ for (String classpathElement : classpath.split(File.pathSeparator)) {
+ // MUST CHANGE THIS TO REGEX SINCE VERSION CHANGES IN JAR NAME
+ if (classpathElement.endsWith("gemfire-core-8.2.0.0-SNAPSHOT.jar")) {
+ gemfireJarPath = classpathElement;
+ break;
+ }
+ }
+ return gemfireJarPath;
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
index 035a8c1..8080e3f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartServerCommand.java
@@ -48,7 +48,7 @@ import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.shell.Gfsh;
import org.apache.geode.management.internal.security.ResourceConstants;
-public class StartServerCommand extends StartMemberCommand implements GfshCommand {
+public class StartServerCommand implements GfshCommand {
private static final String SERVER_TERM_NAME = "Server";
@CliCommand(value = CliStrings.START_SERVER, help = CliStrings.START_SERVER__HELP)
@@ -181,7 +181,7 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
try {
if (StringUtils.isBlank(memberName)) {
// when the user doesn't give us a name, we make one up!
- memberName = getNameGenerator().generate('-');
+ memberName = StartMemberUtils.getNameGenerator().generate('-');
}
// prompt for password is username is specified in the command
@@ -195,7 +195,7 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
}
}
- workingDirectory = resolveWorkingDir(workingDirectory, memberName);
+ workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
cacheXmlPathname = CliUtil.resolvePathname(cacheXmlPathname);
@@ -219,49 +219,56 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
File serverPidFile = new File(workingDirectory, ProcessType.SERVER.getPidFileName());
- readPid(serverPidFile);
+ final int oldPid = StartMemberUtils.readPid(serverPidFile);
Properties gemfireProperties = new Properties();
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.BIND_ADDRESS, bindAddress);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.CACHE_XML_FILE,
- cacheXmlPathname);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.ENABLE_TIME_STATISTICS,
- enableTimeStatistics);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS, group);
- setPropertyIfNotNull(gemfireProperties,
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.BIND_ADDRESS,
+ bindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.CACHE_XML_FILE, cacheXmlPathname);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.ENABLE_TIME_STATISTICS, enableTimeStatistics);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS,
+ group);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, jmxManagerHostnameForClients);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS, locators);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATOR_WAIT_TIME,
- locatorWaitTime);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOG_LEVEL, logLevel);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_ADDRESS,
- mcastBindAddress);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_PORT, mcastPort);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MEMCACHED_PORT,
- memcachedPort);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MEMCACHED_PROTOCOL,
- memcachedProtocol);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MEMCACHED_BIND_ADDRESS,
- memcachedBindAddress);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_PORT, redisPort);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_BIND_ADDRESS,
- redisBindAddress);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_PASSWORD,
- redisPassword);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.STATISTIC_ARCHIVE_FILE,
- statisticsArchivePathname);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.USE_CLUSTER_CONFIGURATION,
- requestSharedConfiguration);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCK_MEMORY, lockMemory);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.OFF_HEAP_MEMORY_SIZE,
- offHeapMemorySize);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.START_DEV_REST_API,
- startRestApi);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.HTTP_SERVICE_PORT,
- httpServicePort);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS,
- httpServiceBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS,
+ locators);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.LOCATOR_WAIT_TIME, locatorWaitTime);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOG_LEVEL,
+ logLevel);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MCAST_ADDRESS, mcastBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_PORT,
+ mcastPort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MEMCACHED_PORT, memcachedPort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MEMCACHED_PROTOCOL, memcachedProtocol);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MEMCACHED_BIND_ADDRESS, memcachedBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.REDIS_PORT,
+ redisPort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.REDIS_BIND_ADDRESS, redisBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.REDIS_PASSWORD, redisPassword);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.STATISTIC_ARCHIVE_FILE, statisticsArchivePathname);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.USE_CLUSTER_CONFIGURATION, requestSharedConfiguration);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCK_MEMORY,
+ lockMemory);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.OFF_HEAP_MEMORY_SIZE, offHeapMemorySize);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.START_DEV_REST_API, startRestApi);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.HTTP_SERVICE_PORT, httpServicePort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS, httpServiceBindAddress);
// if username is specified in the command line, it will overwrite what's set in the
// properties file
if (StringUtils.isNotBlank(userName)) {
@@ -370,9 +377,9 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
} while (!(registeredServerSignalListener && serverSignalListener.isSignaled())
&& serverState.isStartingOrNotResponding());
} finally {
- stderrReader.stopAsync(PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS); // stop
- // will
- // close
+ stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS); // stop
+ // will
+ // close
// ErrorStream
getGfsh().getSignalHandler().unregisterListener(serverSignalListener);
}
@@ -417,16 +424,16 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
throws MalformedObjectNameException {
List<String> commandLine = new ArrayList<>();
- commandLine.add(getJavaPath());
+ commandLine.add(StartMemberUtils.getJavaPath());
commandLine.add("-server");
commandLine.add("-classpath");
commandLine.add(getServerClasspath(Boolean.TRUE.equals(includeSystemClasspath), userClasspath));
- addCurrentLocators(this, commandLine, gemfireProperties);
- addGemFirePropertyFile(commandLine, gemfirePropertiesFile);
- addGemFireSecurityPropertyFile(commandLine, gemfireSecurityPropertiesFile);
- addGemFireSystemProperties(commandLine, gemfireProperties);
- addJvmArgumentsAndOptions(commandLine, jvmArgsOpts);
+ StartMemberUtils.addCurrentLocators(this, commandLine, gemfireProperties);
+ StartMemberUtils.addGemFirePropertyFile(commandLine, gemfirePropertiesFile);
+ StartMemberUtils.addGemFireSecurityPropertyFile(commandLine, gemfireSecurityPropertiesFile);
+ StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
+ StartMemberUtils.addJvmArgumentsAndOptions(commandLine, jvmArgsOpts);
// NOTE asserting not equal to true rather than equal to false handles the null case and ensures
// the user
@@ -435,8 +442,8 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
addJvmOptionsForOutOfMemoryErrors(commandLine);
}
- addInitialHeap(commandLine, initialHeap);
- addMaxHeap(commandLine, maxHeap);
+ StartMemberUtils.addInitialHeap(commandLine, initialHeap);
+ StartMemberUtils.addMaxHeap(commandLine, maxHeap);
commandLine.add(
"-D".concat(AbstractLauncher.SIGNAL_HANDLER_REGISTRATION_SYSTEM_PROPERTY.concat("=true")));
@@ -544,9 +551,9 @@ public class StartServerCommand extends StartMemberCommand implements GfshComman
String getServerClasspath(final boolean includeSystemClasspath, final String userClasspath) {
List<String> jarFilePathnames = new ArrayList<>();
- jarFilePathnames.add(CORE_DEPENDENCIES_JAR_PATHNAME);
+ jarFilePathnames.add(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
- return toClasspath(includeSystemClasspath,
+ return StartMemberUtils.toClasspath(includeSystemClasspath,
jarFilePathnames.toArray(new String[jarFilePathnames.size()]), userClasspath);
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
deleted file mode 100644
index 6a0fc1e..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusClusterConfigServiceCommand.java
+++ /dev/null
@@ -1,82 +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 java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.GemFireCacheImpl;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.cli.Result.Status;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.FetchSharedConfigurationStatusFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.SharedConfigurationStatus;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission.Operation;
-import org.apache.geode.security.ResourcePermission.Resource;
-
-public class StatusClusterConfigServiceCommand implements GfshCommand {
- private static final FetchSharedConfigurationStatusFunction fetchSharedConfigStatusFunction =
- new FetchSharedConfigurationStatusFunction();
-
- @SuppressWarnings("unchecked")
- @CliCommand(value = CliStrings.STATUS_SHARED_CONFIG, help = CliStrings.STATUS_SHARED_CONFIG_HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_LOCATOR)
- @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
- public Result statusSharedConfiguration() {
- final InternalCache cache = GemFireCacheImpl.getInstance();
- final Set<DistributedMember> locators = new HashSet<DistributedMember>(
- cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration().keySet());
- if (locators.isEmpty()) {
- return ResultBuilder.createInfoResult(CliStrings.NO_LOCATORS_WITH_SHARED_CONFIG);
- } else {
- return ResultBuilder.buildResult(getSharedConfigurationStatus(locators));
- }
- }
-
- private TabularResultData getSharedConfigurationStatus(Set<DistributedMember> locators) {
- boolean isSharedConfigRunning = false;
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(fetchSharedConfigStatusFunction, null, locators);
- List<CliFunctionResult> results = (List<CliFunctionResult>) rc.getResult();
- TabularResultData table = ResultBuilder.createTabularResultData();
- table.setHeader("Status of shared configuration on locators");
-
- for (CliFunctionResult result : results) {
- table.accumulate(CliStrings.STATUS_SHARED_CONFIG_NAME_HEADER, result.getMemberIdOrName());
- String status = (String) result.getSerializables()[0];
- table.accumulate(CliStrings.STATUS_SHARED_CONFIG_STATUS, status);
- if (SharedConfigurationStatus.RUNNING.name().equals(status)) {
- isSharedConfigRunning = true;
- }
- }
-
- if (!isSharedConfigRunning) {
- table.setStatus(Status.ERROR);
- }
- return table;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java
new file mode 100644
index 0000000..0b0b78b
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StatusCommands.java
@@ -0,0 +1,82 @@
+/*
+ * 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 org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.FetchSharedConfigurationStatusFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.SharedConfigurationStatus;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.springframework.shell.core.CommandMarker;
+import org.springframework.shell.core.annotation.CliCommand;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+public class StatusCommands implements GfshCommand {
+ static final FetchSharedConfigurationStatusFunction fetchSharedConfigStatusFunction =
+ new FetchSharedConfigurationStatusFunction();
+
+ @SuppressWarnings("unchecked")
+ @CliCommand(value = CliStrings.STATUS_SHARED_CONFIG, help = CliStrings.STATUS_SHARED_CONFIG_HELP)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_LOCATOR)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result statusSharedConfiguration() {
+ final InternalCache cache = GemFireCacheImpl.getInstance();
+ final Set<DistributedMember> locators = new HashSet<DistributedMember>(
+ cache.getDistributionManager().getAllHostedLocatorsWithSharedConfiguration().keySet());
+ if (locators.isEmpty()) {
+ return ResultBuilder.createInfoResult(CliStrings.NO_LOCATORS_WITH_SHARED_CONFIG);
+ } else {
+ return ResultBuilder.buildResult(getSharedConfigurationStatus(locators));
+ }
+ }
+
+ private TabularResultData getSharedConfigurationStatus(Set<DistributedMember> locators) {
+ boolean isSharedConfigRunning = false;
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(fetchSharedConfigStatusFunction, null, locators);
+ List<CliFunctionResult> results = (List<CliFunctionResult>) rc.getResult();
+ TabularResultData table = ResultBuilder.createTabularResultData();
+ table.setHeader("Status of shared configuration on locators");
+
+ for (CliFunctionResult result : results) {
+ table.accumulate(CliStrings.STATUS_SHARED_CONFIG_NAME_HEADER, result.getMemberIdOrName());
+ String status = (String) result.getSerializables()[0];
+ table.accumulate(CliStrings.STATUS_SHARED_CONFIG_STATUS, status);
+ if (SharedConfigurationStatus.RUNNING.name().equals(status)) {
+ isSharedConfigRunning = true;
+ }
+ }
+
+ if (!isSharedConfigRunning) {
+ table.setStatus(Status.ERROR);
+ }
+ return table;
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java
deleted file mode 100644
index 5df7ac7..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UndeployCommand.java
+++ /dev/null
@@ -1,114 +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 java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.UndeployFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class UndeployCommand implements GfshCommand {
- private final UndeployFunction undeployFunction = new UndeployFunction();
-
- /**
- * Undeploy one or more JAR files from members of a group or all members.
- *
- * @param groups Group(s) to undeploy the JAR from or null for all members
- * @param jars JAR(s) to undeploy (separated by comma)
- * @return The result of the attempt to undeploy
- */
- @CliCommand(value = {CliStrings.UNDEPLOY}, help = CliStrings.UNDEPLOY__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
- public Result undeploy(
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.UNDEPLOY__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) String[] groups,
- @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
- help = CliStrings.UNDEPLOY__JAR__HELP) String[] jars) {
-
- try {
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(this.undeployFunction, new Object[] {jars}, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- for (CliFunctionResult result : results) {
-
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Un-Deployed JAR", "");
- tabularData.accumulate("Un-Deployed JAR Location",
- "ERROR: " + result.getThrowable().getClass().getName() + ": "
- + result.getThrowable().getMessage());
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else {
- String[] strings = (String[]) result.getSerializables();
- for (int i = 0; i < strings.length; i += 2) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Un-Deployed JAR", strings[i]);
- tabularData.accumulate("Un-Deployed From JAR Location", strings[i + 1]);
- accumulatedData = true;
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder.createInfoResult(CliStrings.UNDEPLOY__NO_JARS_FOUND_MESSAGE);
- }
-
- Result result = ResultBuilder.buildResult(tabularData);
- if (tabularData.getStatus().equals(Result.Status.OK)) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().removeJars(jars, groups));
- }
- return result;
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult("Exception while attempting to un-deploy: "
- + th.getClass().getName() + ": " + th.getMessage());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java
deleted file mode 100644
index 85b86db..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/UpgradeOfflineDiskStoreCommand.java
+++ /dev/null
@@ -1,177 +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 java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.GemFireIOException;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.cli.util.DiskStoreUpgrader;
-
-public class UpgradeOfflineDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.UPGRADE_OFFLINE_DISK_STORE,
- help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- public Result upgradeOfflineDiskStore(
- @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME, mandatory = true,
- help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
- @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
- help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
- @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
- unspecifiedDefaultValue = "-1",
- help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
- @CliOption(key = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J,
- help = CliStrings.UPGRADE_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps)
- throws InterruptedException {
-
- Result result;
- LogWrapper logWrapper = LogWrapper.getInstance();
-
- StringBuilder output = new StringBuilder();
- StringBuilder error = new StringBuilder();
- StringBuilder errorMessage = new StringBuilder();
- Process upgraderProcess = null;
-
- try {
- String validatedDirectories = DiskStoreCommandsUtils.validatedDirectories(diskDirs);
- if (validatedDirectories != null) {
- throw new IllegalArgumentException(
- "Could not find " + CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + ": \""
- + validatedDirectories + "\"");
- }
-
- List<String> commandList = new ArrayList<>();
- commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
- + File.separatorChar + "java");
-
- DiskStoreCommandsUtils.configureLogging(commandList);
-
- if (jvmProps != null && jvmProps.length != 0) {
- commandList.addAll(Arrays.asList(jvmProps));
- }
- commandList.add("-classpath");
- commandList.add(System.getProperty("java.class.path", "."));
- commandList.add(DiskStoreUpgrader.class.getName());
-
- commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
-
- if (diskDirs != null && diskDirs.length != 0) {
- StringBuilder builder = new StringBuilder();
- int arrayLength = diskDirs.length;
- for (int i = 0; i < arrayLength; i++) {
- if (File.separatorChar == '\\') {
- builder.append(diskDirs[i].replace("\\", "/")); // see 46120
- } else {
- builder.append(diskDirs[i]);
- }
- if (i + 1 != arrayLength) {
- builder.append(',');
- }
- }
- commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
- }
- // -1 is ignore as maxOplogSize
- commandList.add(CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
-
- ProcessBuilder procBuilder = new ProcessBuilder(commandList);
- // procBuilder.redirectErrorStream(true);
- upgraderProcess = procBuilder.start();
- InputStream inputStream = upgraderProcess.getInputStream();
- InputStream errorStream = upgraderProcess.getErrorStream();
- BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
- BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
-
- String line;
- while ((line = inputReader.readLine()) != null) {
- output.append(line).append(GfshParser.LINE_SEPARATOR);
- }
-
- boolean switchToStackTrace = false;
- while ((line = errorReader.readLine()) != null) {
- if (!switchToStackTrace && DiskStoreUpgrader.STACKTRACE_START.equals(line)) {
- switchToStackTrace = true;
- } else if (switchToStackTrace) {
- error.append(line).append(GfshParser.LINE_SEPARATOR);
- } else {
- errorMessage.append(line);
- }
- }
-
- if (errorMessage.length() > 0) {
- throw new GemFireIOException(errorMessage.toString());
- }
-
- upgraderProcess.destroy();
- result = ResultBuilder.createInfoResult(output.toString());
- } catch (IOException e) {
- if (output.length() != 0) {
- Gfsh.println(output.toString());
- }
- String fieldsMessage = (maxOplogSize != -1
- ? CliStrings.UPGRADE_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
- fieldsMessage += CliUtil.arrayToString(diskDirs);
- String errorString = CliStrings.format(
- CliStrings.UPGRADE_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
- diskStoreName, fieldsMessage);
- result = ResultBuilder.createUserErrorResult(errorString);
- if (logWrapper.fineEnabled()) {
- logWrapper.fine(e.getMessage(), e);
- }
- } catch (GemFireIOException e) {
- if (output.length() != 0) {
- Gfsh.println(output.toString());
- }
- result = ResultBuilder.createUserErrorResult(errorMessage.toString());
- if (logWrapper.fineEnabled()) {
- logWrapper.fine(error.toString());
- }
- } catch (IllegalArgumentException e) {
- if (output.length() != 0) {
- Gfsh.println(output.toString());
- }
- result = ResultBuilder.createUserErrorResult(e.getMessage());
- } finally {
- if (upgraderProcess != null) {
- try {
- // just to check whether the process has exited
- // Process.exitValue() throws IllegalStateException if Process is alive
- upgraderProcess.exitValue();
- } catch (IllegalThreadStateException itse) {
- // not yet terminated, destroy the process
- upgraderProcess.destroy();
- }
- }
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java
deleted file mode 100644
index 26954ba..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ValidateDiskStoreCommand.java
+++ /dev/null
@@ -1,105 +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 java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.util.DiskStoreValidater;
-
-public class ValidateDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.VALIDATE_DISK_STORE, help = CliStrings.VALIDATE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE}) // offline
- // command
- public Result validateDiskStore(
- @CliOption(key = CliStrings.VALIDATE_DISK_STORE__NAME, mandatory = true,
- help = CliStrings.VALIDATE_DISK_STORE__NAME__HELP) String diskStoreName,
- @CliOption(key = CliStrings.VALIDATE_DISK_STORE__DISKDIRS, mandatory = true,
- help = CliStrings.VALIDATE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
- @CliOption(key = CliStrings.VALIDATE_DISK_STORE__J,
- help = CliStrings.VALIDATE_DISK_STORE__J__HELP) String[] jvmProps) {
- try {
- // create a new process ...bug 46075
- StringBuilder dirList = new StringBuilder();
- for (String diskDir : diskDirs) {
- dirList.append(diskDir);
- dirList.append(";");
- }
-
- List<String> commandList = new ArrayList<>();
- commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
- + File.separatorChar + "java");
-
- DiskStoreCommandsUtils.configureLogging(commandList);
-
- if (jvmProps != null && jvmProps.length != 0) {
- commandList.addAll(Arrays.asList(jvmProps));
- }
-
- // Pass any java options on to the command
- String opts = System.getenv("JAVA_OPTS");
- if (opts != null) {
- commandList.add(opts);
- }
- commandList.add("-classpath");
- commandList.add(System.getProperty("java.class.path", "."));
- commandList.add(DiskStoreValidater.class.getName());
- commandList.add(diskStoreName);
- commandList.add(dirList.toString());
-
- ProcessBuilder procBuilder = new ProcessBuilder(commandList);
- StringBuilder output = new StringBuilder();
- String errorString = "";
-
- Process validateDiskStoreProcess = procBuilder.redirectErrorStream(true).start();
- InputStream inputStream = validateDiskStoreProcess.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
- String line;
-
- while ((line = br.readLine()) != null) {
- output.append(line).append(GfshParser.LINE_SEPARATOR);
- }
- validateDiskStoreProcess.destroy();
-
- output.append(errorString).append(GfshParser.LINE_SEPARATOR);
- String resultString =
- "Validating " + diskStoreName + GfshParser.LINE_SEPARATOR + output.toString();
- return ResultBuilder.createInfoResult(resultString);
- } catch (IOException ex) {
- return ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.VALIDATE_DISK_STORE__MSG__IO_ERROR, diskStoreName, ex.getMessage()));
- } catch (Exception ex) {
- // StringPrintWriter s = new StringPrintWriter();
- // ex.printStackTrace(s);
- return ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.VALIDATE_DISK_STORE__MSG__ERROR, diskStoreName, ex.getMessage()));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
index da50912..5dfb54e 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/lifecycle/StopLocatorCommand.java
@@ -15,12 +15,7 @@
package org.apache.geode.management.internal.cli.commands.lifecycle;
import static org.apache.geode.management.internal.cli.i18n.CliStrings.LOCATOR_TERM_NAME;
-
-import java.io.IOException;
-import java.util.concurrent.TimeUnit;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
+import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getMemberMXBean;
import org.apache.geode.SystemFailure;
import org.apache.geode.distributed.AbstractLauncher;
@@ -35,7 +30,10 @@ import org.apache.geode.management.internal.cli.commands.GfshCommand;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.result.ResultBuilder;
import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.cli.shell.MXBeanProvider;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import java.util.concurrent.TimeUnit;
public class StopLocatorCommand implements GfshCommand {
private static final long WAITING_FOR_STOP_TO_MAKE_PID_GO_AWAY_TIMEOUT_MILLIS = 30 * 1000;
@@ -123,8 +121,4 @@ public class StopLocatorCommand implements GfshCommand {
Gfsh.redirectInternalJavaLoggers();
}
}
-
- MemberMXBean getMemberMXBean(String member) throws IOException {
- return MXBeanProvider.getMemberMXBean(member);
- }
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
index 502eddd..88fd758 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/converters/HelpConverter.java
@@ -14,20 +14,19 @@
*/
package org.apache.geode.management.internal.cli.converters;
-import java.util.List;
-import java.util.Set;
-
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.internal.cli.CommandManager;
+import org.apache.geode.management.internal.cli.CommandManagerAware;
+import org.apache.geode.management.internal.cli.commands.GfshHelpCommands;
import org.springframework.shell.core.Completion;
import org.springframework.shell.core.Converter;
import org.springframework.shell.core.MethodTarget;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.internal.cli.CommandManager;
-import org.apache.geode.management.internal.cli.CommandManagerAware;
-import org.apache.geode.management.internal.cli.commands.GfshHelpCommand;
+import java.util.List;
+import java.util.Set;
/**
- * {@link Converter} for {@link GfshHelpCommand#obtainHelp(String)}
+ * {@link Converter} for {@link GfshHelpCommands#obtainHelp(String)}
*
*
* @since GemFire 7.0
@@ -49,12 +48,18 @@ public class HelpConverter implements Converter<String>, CommandManagerAware {
completionCandidates.add(new Completion(string));
}
- return completionCandidates.size() > 0;
+ if (completionCandidates.size() > 0) {
+ return true;
+ }
+ return false;
}
@Override
public boolean supports(Class<?> arg0, String optionContext) {
- return String.class.isAssignableFrom(arg0) && optionContext.contains(ConverterHint.HELP);
+ if (String.class.isAssignableFrom(arg0) && optionContext.contains(ConverterHint.HELP)) {
+ return true;
+ }
+ return false;
}
@Override
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
index 47cdb27..742840c 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/CreateDefinedIndexesFunction.java
@@ -14,6 +14,7 @@
*/
package org.apache.geode.management.internal.cli.functions;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -37,7 +38,7 @@ public class CreateDefinedIndexesFunction extends FunctionAdapter implements Int
public void execute(FunctionContext context) {
String memberId = null;
List<Index> indexes = null;
- Cache cache;
+ Cache cache = null;
try {
cache = CacheFactory.getAnyInstance();
memberId = cache.getDistributedSystem().getDistributedMember().getId();
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
index d0a6e72..96f8815 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/DataCommandFunction.java
@@ -14,8 +14,10 @@
*/
package org.apache.geode.management.internal.cli.functions;
+import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -24,6 +26,7 @@ import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.Logger;
+import org.apache.shiro.subject.Subject;
import org.json.JSONArray;
import org.apache.geode.cache.CacheFactory;
@@ -499,7 +502,6 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
return DataCommandResult.createLocateEntryResult(key, null, null,
CliStrings.LOCATE_ENTRY__MSG__KEY_EMPTY, false);
}
-
List<Region> listOfRegionsStartingWithRegionPath = new ArrayList<>();
if (recursive) {
@@ -631,8 +633,8 @@ public class DataCommandFunction extends FunctionAdapter implements InternalEnti
try {
keyObject = getClassObject(key, keyClass);
} catch (ClassNotFoundException e) {
- return DataCommandResult.createPutResult(key, null, e,
- CliStrings.format(CliStrings.PUT__MSG__KEY_NOT_FOUND_REGION, keyClass), false);
+ return DataCommandResult.createPutResult(key, null, null,
+ "ClassNotFoundException " + keyClass, false);
} catch (IllegalArgumentException e) {
return DataCommandResult.createPutResult(key, null, null,
"Error in converting JSON " + e.getMessage(), false);
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GetSubscriptionQueueSizeFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GetSubscriptionQueueSizeFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GetSubscriptionQueueSizeFunction.java
index 4fb295f..70b649c 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GetSubscriptionQueueSizeFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/GetSubscriptionQueueSizeFunction.java
@@ -85,7 +85,7 @@ public class GetSubscriptionQueueSizeFunction extends FunctionAdapter implements
}
} else {
result.setErrorMessage(
- CliStrings.format(CliStrings.DURABLE_CQ_CLIENT_NOT_FOUND, durableClientId));
+ CliStrings.format(CliStrings.NO_CLIENT_FOUND_WITH_CLIENT_ID, durableClientId));
}
} else {
result.setErrorMessage(CliStrings.NO_CLIENT_FOUND);
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
index ee9520d..6ae10a3 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/functions/RegionCreateFunction.java
@@ -43,7 +43,7 @@ import org.apache.geode.internal.cache.xmlcache.CacheXml;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.commands.CreateRegionCommand;
+import org.apache.geode.management.internal.cli.commands.CreateAlterDestroyRegionCommands;
import org.apache.geode.management.internal.cli.exceptions.CreateSubregionException;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.util.RegionPath;
@@ -100,9 +100,9 @@ public class RegionCreateFunction extends FunctionAdapter implements InternalEnt
String localizedString =
LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
if (localizedString.equals(e.getMessage())) {
- exceptionMsg = exceptionMsg + " "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
- new Object[] {String.valueOf(CreateRegionCommand.PERSISTENT_OVERFLOW_SHORTCUTS)});
+ exceptionMsg = exceptionMsg + " " + CliStrings
+ .format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0, new Object[] {
+ String.valueOf(CreateAlterDestroyRegionCommands.PERSISTENT_OVERFLOW_SHORTCUTS)});
}
resultSender.lastResult(handleException(memberNameOrId, exceptionMsg, null/* do not log */));
} catch (IllegalArgumentException e) {
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/help/Helper.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/help/Helper.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/help/Helper.java
index ba6d146..3525013 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/help/Helper.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/help/Helper.java
@@ -14,6 +14,15 @@
*/
package org.apache.geode.management.internal.cli.help;
+import org.apache.commons.lang.StringUtils;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.springframework.shell.core.MethodTarget;
+import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.ArrayList;
@@ -26,16 +35,6 @@ import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.MethodTarget;
-import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-
/**
*
*
@@ -86,7 +85,6 @@ public class Helper {
initTopic(CliStrings.TOPIC_GEODE_HELP, CliStrings.TOPIC_GEODE_HELP__DESC);
initTopic(CliStrings.TOPIC_GEODE_DEBUG_UTIL, CliStrings.TOPIC_GEODE_DEBUG_UTIL__DESC);
initTopic(CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GFSH__DESC);
- initTopic(CliStrings.TOPIC_SHARED_CONFIGURATION, CliStrings.TOPIC_SHARED_CONFIGURATION_DESC);
initTopic(CliStrings.TOPIC_LOGS, CliStrings.TOPIC_LOGS__DESC);
initTopic(CliStrings.TOPIC_CLIENT, CliStrings.TOPIC_CLIENT__DESC);
}
[07/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
deleted file mode 100644
index 7555a62..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMetricsCommand.java
+++ /dev/null
@@ -1,1085 +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 java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import javax.management.ObjectName;
-
-import org.apache.logging.log4j.Logger;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.management.CacheServerMXBean;
-import org.apache.geode.management.DistributedRegionMXBean;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.JVMMetrics;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.MemberMXBean;
-import org.apache.geode.management.RegionMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.ResultData;
-import org.apache.geode.management.internal.cli.result.ResultDataException;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ShowMetricsCommand implements GfshCommand {
- private final static Logger logger = LogService.getLogger();
-
- @CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result showMetrics(
- @CliOption(key = {CliStrings.MEMBER}, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.SHOW_METRICS__MEMBER__HELP) String memberNameOrId,
- @CliOption(key = {CliStrings.SHOW_METRICS__REGION}, optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.SHOW_METRICS__REGION__HELP) String regionName,
- @CliOption(key = {CliStrings.SHOW_METRICS__FILE},
- help = CliStrings.SHOW_METRICS__FILE__HELP) String export_to_report_to,
- @CliOption(key = {CliStrings.SHOW_METRICS__CACHESERVER__PORT},
- help = CliStrings.SHOW_METRICS__CACHESERVER__PORT__HELP) String cacheServerPortString,
- @CliOption(key = {CliStrings.SHOW_METRICS__CATEGORY},
- help = CliStrings.SHOW_METRICS__CATEGORY__HELP) String[] categories) {
-
- Result result;
- try {
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- if (!export_to_report_to.endsWith(".csv")) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".csv"));
- }
- }
- if (regionName != null && !regionName.isEmpty()) {
-
- if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
- }
-
- // MBean names contain the forward slash
- if (!regionName.startsWith("/")) {
- regionName = "/" + regionName;
- }
-
- if (memberNameOrId == null || memberNameOrId.isEmpty()) {
- result = ResultBuilder.buildResult(
- getDistributedRegionMetrics(regionName, export_to_report_to, categories));
- } else {
- DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-
- if (member != null) {
- result = ResultBuilder.buildResult(
- getRegionMetricsFromMember(regionName, member, export_to_report_to, categories));
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(
- CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
- result = ResultBuilder.buildResult(erd);
- }
- }
- } else if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
-
- DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-
- if (member != null) {
- int cacheServerPort = -1;
- if (cacheServerPortString != null && !cacheServerPortString.isEmpty()) {
- try {
- cacheServerPort = Integer.parseInt(cacheServerPortString);
- } catch (NumberFormatException nfe) {
- return ResultBuilder.createUserErrorResult("Invalid port");
- }
- }
- result = ResultBuilder.buildResult(
- getMemberMetrics(member, export_to_report_to, categories, cacheServerPort));
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
- result = ResultBuilder.buildResult(erd);
- }
- } else {
- if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
- }
- result = ResultBuilder.buildResult(getSystemWideMetrics(export_to_report_to, categories));
- }
- } catch (Exception e) {
- logger.error(e.getMessage(), e);
- return ResultBuilder.createGemFireErrorResult(CliUtil.stackTraceAsString(e));
- }
- return result;
- }
-
- /**
- * Gets the system wide metrics
- *
- * @return ResultData with required System wide statistics or ErrorResultData if DS MBean is not
- * found to gather metrics
- */
- private ResultData getSystemWideMetrics(String export_to_report_to, String[] categoriesArr) {
- final InternalCache cache = getCache();
- final ManagementService managementService = ManagementService.getManagementService(cache);
- DistributedSystemMXBean dsMxBean = managementService.getDistributedSystemMXBean();
- StringBuilder csvBuilder = null;
- if (dsMxBean != null) {
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- csvBuilder = new StringBuilder();
- csvBuilder.append("Category");
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
- csvBuilder.append('\n');
- }
-
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- CompositeResultData.SectionResultData section = crd.addSection();
- TabularResultData metricsTable = section.addTable();
- Map<String, Boolean> categoriesMap = getSystemMetricsCategories();
-
- if (categoriesArr != null && categoriesArr.length != 0) {
- Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
- Set<String> userCategories = getSetDifference(categories, checkSet);
-
- // Checking if the categories specified by the user are valid or not
-
- if (userCategories.isEmpty()) {
- for (String category : checkSet) {
- categoriesMap.put(category, false);
- }
- for (String category : categories) {
- categoriesMap.put(category.toLowerCase(), true);
- }
- } else {
- StringBuilder sb = new StringBuilder();
- sb.append("Invalid Categories\n");
-
- for (String category : userCategories) {
- sb.append(category);
- sb.append('\n');
- }
- return ResultBuilder.createErrorResultData().addLine(sb.toString());
- }
- }
- metricsTable.setHeader("Cluster-wide Metrics");
-
- if (categoriesMap.get("cluster")) {
- writeToTableAndCsv(metricsTable, "cluster", "totalHeapSize", dsMxBean.getTotalHeapSize(),
- csvBuilder);
- }
-
- if (categoriesMap.get("cache")) {
- writeToTableAndCsv(metricsTable, "cache", "totalRegionEntryCount",
- dsMxBean.getTotalRegionEntryCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalRegionCount", dsMxBean.getTotalRegionCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalMissCount", dsMxBean.getTotalMissCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalHitCount", dsMxBean.getTotalHitCount(),
- csvBuilder);
- }
-
- if (categoriesMap.get("diskstore")) {
- writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
- dsMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
- writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
- dsMxBean.getDiskReadsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskWritesRate", dsMxBean.getDiskWritesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
- dsMxBean.getDiskFlushAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
- dsMxBean.getTotalBackupInProgress(), csvBuilder);
- }
-
- if (categoriesMap.get("query")) {
- writeToTableAndCsv(metricsTable, "query", "activeCQCount", dsMxBean.getActiveCQCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "queryRequestRate", dsMxBean.getQueryRequestRate(),
- csvBuilder);
- }
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- crd.addAsFile(export_to_report_to, csvBuilder.toString(),
- "Cluster wide metrics exported to {0}.", false);
- }
-
- return crd;
- } else {
- String errorMessage =
- CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Distributed System MBean not found");
- return ResultBuilder.createErrorResultData().addLine(errorMessage);
- }
- }
-
- /**
- * Gets the Cluster wide metrics for a given member
- *
- * @return ResultData with required Member statistics or ErrorResultData if MemberMbean is not
- * found to gather metrics
- * @throws ResultDataException if building result fails
- */
- private ResultData getMemberMetrics(DistributedMember distributedMember,
- String export_to_report_to, String[] categoriesArr, int cacheServerPort)
- throws ResultDataException {
- final InternalCache cache = getCache();
- final SystemManagementService managementService =
- (SystemManagementService) ManagementService.getManagementService(cache);
-
- ObjectName memberMBeanName = managementService.getMemberMBeanName(distributedMember);
- MemberMXBean memberMxBean =
- managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
- ObjectName csMxBeanName;
- CacheServerMXBean csMxBean = null;
-
- if (memberMxBean != null) {
-
- if (cacheServerPort != -1) {
- csMxBeanName =
- managementService.getCacheServerMBeanName(cacheServerPort, distributedMember);
- csMxBean = managementService.getMBeanInstance(csMxBeanName, CacheServerMXBean.class);
-
- if (csMxBean == null) {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(CliStrings.format(CliStrings.SHOW_METRICS__CACHE__SERVER__NOT__FOUND,
- cacheServerPort, MBeanJMXAdapter.getMemberNameOrId(distributedMember)));
- return erd;
- }
- }
-
- JVMMetrics jvmMetrics = memberMxBean.showJVMMetrics();
-
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- CompositeResultData.SectionResultData section = crd.addSection();
- TabularResultData metricsTable = section.addTable();
- metricsTable.setHeader("Member Metrics");
- StringBuilder csvBuilder = null;
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- csvBuilder = new StringBuilder();
- csvBuilder.append("Category");
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
- csvBuilder.append('\n');
- }
-
- Map<String, Boolean> categoriesMap = getMemberMetricsCategories();
-
- if (categoriesArr != null && categoriesArr.length != 0) {
- Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
- Set<String> userCategories = getSetDifference(categories, checkSet);
-
- // Checking if the categories specified by the user are valid or not
- if (userCategories.isEmpty()) {
- for (String category : checkSet) {
- categoriesMap.put(category, false);
- }
- for (String category : categories) {
- categoriesMap.put(category.toLowerCase(), true);
- }
- } else {
- StringBuilder sb = new StringBuilder();
- sb.append("Invalid Categories\n");
-
- for (String category : userCategories) {
- sb.append(category);
- sb.append('\n');
- }
- return ResultBuilder.createErrorResultData().addLine(sb.toString());
- }
- }
-
- /*
- * Member Metrics
- */
- // member, jvm, region, serialization, communication, function, transaction, diskstore, lock,
- // eviction, distribution
- if (categoriesMap.get("member")) {
- writeToTableAndCsv(metricsTable, "member", "upTime", memberMxBean.getMemberUpTime(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "cpuUsage", memberMxBean.getCpuUsage(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "currentHeapSize", memberMxBean.getCurrentHeapSize(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "maximumHeapSize", memberMxBean.getMaximumHeapSize(),
- csvBuilder);
- }
- /*
- * JVM Metrics
- */
- if (categoriesMap.get("jvm")) {
- writeToTableAndCsv(metricsTable, "jvm ", "jvmThreads ", jvmMetrics.getTotalThreads(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "fileDescriptorLimit",
- memberMxBean.getFileDescriptorLimit(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalFileDescriptorOpen",
- memberMxBean.getTotalFileDescriptorOpen(), csvBuilder);
- }
- /*
- * Member wide region metrics
- */
- if (categoriesMap.get("region")) {
- writeToTableAndCsv(metricsTable, "region ", "totalRegionCount ",
- memberMxBean.getTotalRegionCount(), csvBuilder);
- String[] regionNames = memberMxBean.listRegions();
- if (regionNames != null) {
- for (int i = 0; i < regionNames.length; i++) {
- if (i == 0) {
- writeToTableAndCsv(metricsTable, "listOfRegions", regionNames[i].substring(1),
- csvBuilder);
- } else {
- writeToTableAndCsv(metricsTable, "", regionNames[i].substring(1), csvBuilder);
- }
- }
- }
-
- String[] rootRegionNames = memberMxBean.getRootRegionNames();
- if (rootRegionNames != null) {
- for (int i = 0; i < rootRegionNames.length; i++) {
- if (i == 0) {
- writeToTableAndCsv(metricsTable, "rootRegions", rootRegionNames[i], csvBuilder);
- } else {
- writeToTableAndCsv(metricsTable, "", rootRegionNames[i], csvBuilder);
- }
- }
- }
- writeToTableAndCsv(metricsTable, "", "totalRegionEntryCount",
- memberMxBean.getTotalRegionEntryCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalBucketCount", memberMxBean.getTotalBucketCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalPrimaryBucketCount",
- memberMxBean.getTotalPrimaryBucketCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getsAvgLatency", memberMxBean.getGetsAvgLatency(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putsAvgLatency", memberMxBean.getPutsAvgLatency(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "createsRate", memberMxBean.getCreatesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "destroyRate", memberMxBean.getDestroysRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putAllAvgLatency", memberMxBean.getPutAllAvgLatency(),
- csvBuilder);
- // Not available from stats. After Stats re-org it will be available
- // writeToTableAndCsv(metricsTable, "", "getAllAvgLatency",
- // memberMxBean.getGetAllAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalMissCount", memberMxBean.getTotalMissCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalHitCount", memberMxBean.getTotalHitCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getsRate", memberMxBean.getGetsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putsRate", memberMxBean.getPutsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "cacheWriterCallsAvgLatency",
- memberMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
- memberMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalLoadsCompleted",
- memberMxBean.getTotalLoadsCompleted(), csvBuilder);
- }
-
- /*
- * SERIALIZATION
- */
- if (categoriesMap.get("serialization")) {
- writeToTableAndCsv(metricsTable, "serialization", "serializationRate",
- memberMxBean.getSerializationRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "serializationLatency",
- memberMxBean.getSerializationRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "deserializationRate",
- memberMxBean.getDeserializationRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "deserializationLatency",
- memberMxBean.getDeserializationLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "deserializationAvgLatency",
- memberMxBean.getDeserializationAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "PDXDeserializationAvgLatency",
- memberMxBean.getPDXDeserializationAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "PDXDeserializationRate",
- memberMxBean.getPDXDeserializationRate(), csvBuilder);
- }
-
- /*
- * Communication Metrics
- */
- if (categoriesMap.get("communication")) {
- writeToTableAndCsv(metricsTable, "communication", "bytesSentRate",
- memberMxBean.getBytesSentRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "bytesReceivedRate",
- memberMxBean.getBytesReceivedRate(), csvBuilder);
- String[] connectedGatewayReceivers = memberMxBean.listConnectedGatewayReceivers();
- writeToTableAndCsv(metricsTable, "connectedGatewayReceivers", connectedGatewayReceivers,
- csvBuilder);
-
- String[] connectedGatewaySenders = memberMxBean.listConnectedGatewaySenders();
- writeToTableAndCsv(metricsTable, "connectedGatewaySenders", connectedGatewaySenders,
- csvBuilder);
- }
-
- /*
- * Member wide function metrics
- */
- if (categoriesMap.get("function")) {
- writeToTableAndCsv(metricsTable, "function", "numRunningFunctions",
- memberMxBean.getNumRunningFunctions(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "functionExecutionRate",
- memberMxBean.getFunctionExecutionRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "numRunningFunctionsHavingResults",
- memberMxBean.getNumRunningFunctionsHavingResults(), csvBuilder);
- }
-
- /*
- * totalTransactionsCount currentTransactionalThreadIds transactionCommitsAvgLatency
- * transactionCommittedTotalCount transactionRolledBackTotalCount transactionCommitsRate
- */
- if (categoriesMap.get("transaction")) {
- writeToTableAndCsv(metricsTable, "transaction", "totalTransactionsCount",
- memberMxBean.getTotalTransactionsCount(), csvBuilder);
-
- writeToTableAndCsv(metricsTable, "", "transactionCommitsAvgLatency",
- memberMxBean.getTransactionCommitsAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "transactionCommittedTotalCount",
- memberMxBean.getTransactionCommittedTotalCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "transactionRolledBackTotalCount",
- memberMxBean.getTransactionRolledBackTotalCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "transactionCommitsRate",
- memberMxBean.getTransactionCommitsRate(), csvBuilder);
- }
- /*
- * Member wide disk metrics
- */
- if (categoriesMap.get("diskstore")) {
- writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
- memberMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
- writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
- memberMxBean.getDiskReadsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskWritesRate", memberMxBean.getDiskWritesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
- memberMxBean.getDiskFlushAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalQueueSize",
- memberMxBean.getTotalDiskTasksWaiting(), csvBuilder); // deadcoded to workaround bug
- // 46397
- writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
- memberMxBean.getTotalBackupInProgress(), csvBuilder);
- }
- /*
- * Member wide Lock
- */
- if (categoriesMap.get("lock")) {
- writeToTableAndCsv(metricsTable, "lock", "lockWaitsInProgress",
- memberMxBean.getLockWaitsInProgress(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalLockWaitTime",
- memberMxBean.getTotalLockWaitTime(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalNumberOfLockService",
- memberMxBean.getTotalNumberOfLockService(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "requestQueues", memberMxBean.getLockRequestQueues(),
- csvBuilder);
- }
- /*
- * Eviction
- */
- if (categoriesMap.get("eviction")) {
- writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
- memberMxBean.getLruEvictionRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "lruDestroyRate", memberMxBean.getLruDestroyRate(),
- csvBuilder);
- }
- /*
- * Distribution
- */
- if (categoriesMap.get("distribution")) {
- writeToTableAndCsv(metricsTable, "distribution", "getInitialImagesInProgress",
- memberMxBean.getInitialImagesInProgress(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getInitialImageTime",
- memberMxBean.getInitialImageTime(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getInitialImageKeysReceived",
- memberMxBean.getInitialImageKeysReceived(), csvBuilder);
- }
-
- /*
- * OffHeap
- */
- if (categoriesMap.get("offheap")) {
- writeToTableAndCsv(metricsTable, "offheap", "maxMemory", memberMxBean.getOffHeapMaxMemory(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "freeMemory", memberMxBean.getOffHeapFreeMemory(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "usedMemory", memberMxBean.getOffHeapUsedMemory(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "objects", memberMxBean.getOffHeapObjects(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "fragmentation",
- memberMxBean.getOffHeapFragmentation(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "compactionTime",
- memberMxBean.getOffHeapCompactionTime(), csvBuilder);
- }
-
- /*
- * CacheServer stats
- */
- if (csMxBean != null) {
- writeToTableAndCsv(metricsTable, "cache-server", "clientConnectionCount",
- csMxBean.getClientConnectionCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "hostnameForClients", csMxBean.getHostNameForClients(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getRequestAvgLatency",
- csMxBean.getGetRequestAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRequestAvgLatency",
- csMxBean.getPutRequestAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalConnectionsTimedOut",
- csMxBean.getTotalConnectionsTimedOut(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "threadQueueSize", csMxBean.getPutRequestAvgLatency(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "connectionThreads", csMxBean.getConnectionThreads(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "connectionLoad", csMxBean.getConnectionLoad(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "loadPerConnection", csMxBean.getLoadPerConnection(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "queueLoad", csMxBean.getQueueLoad(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "loadPerQueue", csMxBean.getLoadPerQueue(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getRequestRate", csMxBean.getGetRequestRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRequestRate", csMxBean.getPutRequestRate(),
- csvBuilder);
-
- /*
- * Notification
- */
- writeToTableAndCsv(metricsTable, "notification", "numClientNotificationRequests",
- csMxBean.getNumClientNotificationRequests(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "clientNotificationRate",
- csMxBean.getClientNotificationRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "clientNotificationAvgLatency",
- csMxBean.getClientNotificationAvgLatency(), csvBuilder);
-
- /*
- * Query
- */
- writeToTableAndCsv(metricsTable, "query", "activeCQCount", csMxBean.getActiveCQCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "query", "queryRequestRate",
- csMxBean.getQueryRequestRate(), csvBuilder);
-
- writeToTableAndCsv(metricsTable, "", "indexCount", csMxBean.getIndexCount(), csvBuilder);
-
- String[] indexList = csMxBean.getIndexList();
- writeToTableAndCsv(metricsTable, "index list", indexList, csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalIndexMaintenanceTime",
- csMxBean.getTotalIndexMaintenanceTime(), csvBuilder);
- }
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- crd.addAsFile(export_to_report_to, csvBuilder != null ? csvBuilder.toString() : null,
- "Member metrics exported to {0}.", false);
- }
- return crd;
-
- } else {
- String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Member MBean for "
- + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
- return ResultBuilder.createErrorResultData().addLine(errorMessage);
- }
- }
-
- /**
- * Gets the Cluster-wide metrics for a region
- *
- * @return ResultData containing the table
- * @throws ResultDataException if building result fails
- */
- private ResultData getDistributedRegionMetrics(String regionName, String export_to_report_to,
- String[] categoriesArr) throws ResultDataException {
-
- final InternalCache cache = getCache();
- final ManagementService managementService = ManagementService.getManagementService(cache);
-
- DistributedRegionMXBean regionMxBean = managementService.getDistributedRegionMXBean(regionName);
-
- if (regionMxBean != null) {
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- CompositeResultData.SectionResultData section = crd.addSection();
- TabularResultData metricsTable = section.addTable();
- metricsTable.setHeader("Cluster-wide Region Metrics");
- StringBuilder csvBuilder = null;
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- csvBuilder = new StringBuilder();
- csvBuilder.append("Category");
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
- csvBuilder.append('\n');
- }
-
- Map<String, Boolean> categoriesMap = getSystemRegionMetricsCategories();
-
- if (categoriesArr != null && categoriesArr.length != 0) {
- Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
- Set<String> userCategories = getSetDifference(categories, checkSet);
-
- // Checking if the categories specified by the user are valid or not
- if (userCategories.isEmpty()) {
- for (String category : checkSet) {
- categoriesMap.put(category, false);
- }
- for (String category : categories) {
- categoriesMap.put(category.toLowerCase(), true);
- }
- } else {
- StringBuilder sb = new StringBuilder();
- sb.append("Invalid Categories\n");
-
- for (String category : userCategories) {
- sb.append(category);
- sb.append('\n');
- }
- return ResultBuilder.createErrorResultData().addLine(sb.toString());
- }
- }
- /*
- * General System metrics
- */
- // cluster, region, partition , diskstore, callback, eviction
- if (categoriesMap.get("cluster")) {
- writeToTableAndCsv(metricsTable, "cluster", "member count", regionMxBean.getMemberCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "region entry count",
- regionMxBean.getSystemRegionEntryCount(), csvBuilder);
- }
-
- if (categoriesMap.get("region")) {
- writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
- regionMxBean.getLastModifiedTime(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
- csvBuilder);
- }
-
- if (categoriesMap.get("partition")) {
- writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
- regionMxBean.getPutLocalRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
- regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
-
- writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
- regionMxBean.getPrimaryBucketCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
- regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "averageBucketSize", regionMxBean.getAvgBucketSize(),
- csvBuilder);
- }
- /*
- * Disk store
- */
- if (categoriesMap.get("diskstore")) {
- writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
- regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskReadsRate", regionMxBean.getDiskReadsRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
- regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
- csvBuilder);
-
- }
- /*
- * LISTENER
- */
- if (categoriesMap.get("callback")) {
- writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
- regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
- regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
- }
-
- /*
- * Eviction
- */
- if (categoriesMap.get("eviction")) {
- writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
- regionMxBean.getLruEvictionRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
- csvBuilder);
- }
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- crd.addAsFile(export_to_report_to, csvBuilder != null ? csvBuilder.toString() : null,
- "Aggregate Region Metrics exported to {0}.", false);
- }
-
- return crd;
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
- "Distributed Region MBean for " + regionName + " not found");
- erd.addLine(errorMessage);
- return erd;
- }
- }
-
- /**
- * Gets the metrics of region on a given member
- *
- * @return ResultData with required Region statistics or ErrorResultData if Region MBean is not
- * found to gather metrics
- * @throws ResultDataException if building result fails
- */
- private ResultData getRegionMetricsFromMember(String regionName,
- DistributedMember distributedMember, String export_to_report_to, String[] categoriesArr)
- throws ResultDataException {
-
- final InternalCache cache = getCache();
- final SystemManagementService managementService =
- (SystemManagementService) ManagementService.getManagementService(cache);
-
- ObjectName regionMBeanName =
- managementService.getRegionMBeanName(distributedMember, regionName);
- RegionMXBean regionMxBean =
- managementService.getMBeanInstance(regionMBeanName, RegionMXBean.class);
-
- if (regionMxBean != null) {
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- CompositeResultData.SectionResultData section = crd.addSection();
- TabularResultData metricsTable = section.addTable();
- metricsTable.setHeader("Metrics for region:" + regionName + " On Member "
- + MBeanJMXAdapter.getMemberNameOrId(distributedMember));
- StringBuilder csvBuilder = null;
-
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- csvBuilder = new StringBuilder();
- csvBuilder.append("Category");
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
- csvBuilder.append(',');
- csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
- csvBuilder.append('\n');
- }
-
- /*
- * Region Metrics
- */
- Map<String, Boolean> categoriesMap = getRegionMetricsCategories();
-
- if (categoriesArr != null && categoriesArr.length != 0) {
- Set<String> categories = createSet(categoriesArr);
- Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
- Set<String> userCategories = getSetDifference(categories, checkSet);
-
- // Checking if the categories specified by the user are valid or not
- if (userCategories.isEmpty()) {
- for (String category : checkSet) {
- categoriesMap.put(category, false);
- }
- for (String category : categories) {
- categoriesMap.put(category.toLowerCase(), true);
- }
- } else {
- StringBuilder sb = new StringBuilder();
- sb.append("Invalid Categories\n");
-
- for (String category : userCategories) {
- sb.append(category);
- sb.append('\n');
- }
- return ResultBuilder.createErrorResultData().addLine(sb.toString());
- }
- }
-
- if (categoriesMap.get("region")) {
- writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
- regionMxBean.getLastModifiedTime(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
- csvBuilder);
- }
-
- if (categoriesMap.get("partition")) {
- writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
- regionMxBean.getPutLocalRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
- regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
-
- writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
- regionMxBean.getPrimaryBucketCount(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "configuredRedundancy",
- regionMxBean.getConfiguredRedundancy(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "actualRedundancy", regionMxBean.getActualRedundancy(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
- regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
- csvBuilder);
- }
- /*
- * Disk store
- */
- if (categoriesMap.get("diskstore")) {
- writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
- regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
- writeToTableAndCsv(metricsTable, "diskReadsRate", "" + regionMxBean.getDiskReadsRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
- csvBuilder);
- writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
- regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
- csvBuilder);
- }
- /*
- * LISTENER
- */
- if (categoriesMap.get("callback")) {
- writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
- regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
- regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
- }
-
- /*
- * Eviction
- */
- if (categoriesMap.get("eviction")) {
- writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
- regionMxBean.getLruEvictionRate(), csvBuilder);
- writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
- csvBuilder);
- }
- if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
- crd.addAsFile(export_to_report_to, csvBuilder != null ? csvBuilder.toString() : null,
- "Region Metrics exported to {0}.", false);
- }
-
- return crd;
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
- "Region MBean for " + regionName + " on member "
- + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
- erd.addLine(errorMessage);
- return erd;
- }
- }
-
- /***
- * Writes an entry to a TabularResultData and writes a comma separated entry to a string builder
- */
- private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
- long metricValue, StringBuilder csvBuilder) {
- metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
- metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
- metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
-
- if (csvBuilder != null) {
- csvBuilder.append(type);
- csvBuilder.append(',');
- csvBuilder.append(metricName);
- csvBuilder.append(',');
- csvBuilder.append(metricValue);
- csvBuilder.append('\n');
- }
- }
-
- private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
- double metricValue, StringBuilder csvBuilder) {
- metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
- metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
- metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
-
- if (csvBuilder != null) {
- csvBuilder.append(type);
- csvBuilder.append(',');
- csvBuilder.append(metricName);
- csvBuilder.append(',');
- csvBuilder.append(metricValue);
- csvBuilder.append('\n');
- }
- }
-
- private Set<String> createSet(String[] categories) {
- Set<String> categoriesSet = new HashSet<>();
- Collections.addAll(categoriesSet, categories);
- return categoriesSet;
- }
-
- private Set<String> getSetDifference(Set<String> set1, Set<String> set2) {
- Set<String> setDifference = new HashSet<>();
- for (String element : set1) {
- if (!(set2.contains(element.toLowerCase()))) {
- setDifference.add(element);
- }
- }
- return setDifference;
- }
-
- private void writeToTableAndCsv(TabularResultData metricsTable, String metricName,
- String[] metricValue, StringBuilder csvBuilder) {
- if (metricValue != null) {
- for (int i = 0; i < metricValue.length; i++) {
- if (i == 0) {
- writeToTableAndCsv(metricsTable, metricName, metricValue[i], csvBuilder);
- } else {
- writeToTableAndCsv(metricsTable, "", metricValue[i], csvBuilder);
- }
- }
- }
- }
-
- /**
- * Writes to a TabularResultData and also appends a CSV string to a String builder
- */
- private void writeToTableAndCsv(TabularResultData metricsTable, String metricName,
- String metricValue, StringBuilder csvBuilder) {
- metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, "");
- metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
- metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
-
- if (csvBuilder != null) {
- csvBuilder.append("");
- csvBuilder.append(',');
- csvBuilder.append(metricName);
- csvBuilder.append(',');
- csvBuilder.append(metricValue);
- csvBuilder.append('\n');
- }
- }
-
- /**
- * Defines and returns map of categories for Region Metrics
- *
- * @return map with categories for region metrics and display flag set to true
- */
- private Map<String, Boolean> getRegionMetricsCategories() {
- Map<String, Boolean> categories = new HashMap<>();
-
- categories.put("region", true);
- categories.put("partition", true);
- categories.put("diskstore", true);
- categories.put("callback", true);
- categories.put("gatewayreceiver", true);
- categories.put("distribution", true);
- categories.put("query", true);
- categories.put("eviction", true);
- return categories;
- }
-
- /**
- * Defines and returns map of categories for System metrics.
- *
- * @return map with categories for system metrics and display flag set to true
- */
- private Map<String, Boolean> getSystemMetricsCategories() {
- Map<String, Boolean> categories = new HashMap<>();
- categories.put("cluster", true);
- categories.put("cache", true);
- categories.put("diskstore", true);
- categories.put("query", true);
- return categories;
- }
-
- /**
- * Defines and returns map of categories for system-wide region metrics
- *
- * @return map with categories for system wide region metrics and display flag set to true
- */
- private Map<String, Boolean> getSystemRegionMetricsCategories() {
- Map<String, Boolean> categories = getRegionMetricsCategories();
- categories.put("cluster", true);
- return categories;
- }
-
- /**
- * Defines and returns map of categories for member metrics
- *
- * @return map with categories for member metrics and display flag set to true
- */
- private Map<String, Boolean> getMemberMetricsCategories() {
- Map<String, Boolean> categories = new HashMap<>();
- categories.put("member", true);
- categories.put("jvm", true);
- categories.put("region", true);
- categories.put("serialization", true);
- categories.put("communication", true);
- categories.put("function", true);
- categories.put("transaction", true);
- categories.put("diskstore", true);
- categories.put("lock", true);
- categories.put("eviction", true);
- categories.put("distribution", true);
- categories.put("offheap", true);
- return categories;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
deleted file mode 100644
index 7b16581..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowMissingDiskStoreCommand.java
+++ /dev/null
@@ -1,150 +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 java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.internal.cache.partitioned.ColocatedRegionDetails;
-import org.apache.geode.internal.cache.persistence.PersistentMemberPattern;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.functions.ShowMissingDiskStoresFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.ResultDataException;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ShowMissingDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.SHOW_MISSING_DISK_STORE,
- help = CliStrings.SHOW_MISSING_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result showMissingDiskStore() {
-
- try {
- Set<DistributedMember> dataMembers = DiskStoreCommandsUtils.getNormalMembers(getCache());
-
- if (dataMembers.isEmpty()) {
- return ResultBuilder.createInfoResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
- }
- List<Object> results = getMissingDiskStoresList(dataMembers);
- return toMissingDiskStoresTabularResult(results);
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.SHOW_MISSING_DISK_STORE));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- if (t.getMessage() == null) {
- return ResultBuilder.createGemFireErrorResult(
- String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t));
- }
- return ResultBuilder.createGemFireErrorResult(
- String.format(CliStrings.SHOW_MISSING_DISK_STORE__ERROR_MESSAGE, t.getMessage()));
- }
- }
-
- private List<Object> getMissingDiskStoresList(Set<DistributedMember> members) {
- final Execution membersFunctionExecutor = getMembersFunctionExecutor(members);
- if (membersFunctionExecutor instanceof AbstractExecution) {
- ((AbstractExecution) membersFunctionExecutor).setIgnoreDepartedMembers(true);
- }
-
- final ResultCollector<?, ?> resultCollector =
- membersFunctionExecutor.execute(new ShowMissingDiskStoresFunction());
-
- final List<?> results = (List<?>) resultCollector.getResult();
- final List<Object> distributedPersistentRecoveryDetails = new ArrayList<>(results.size());
- for (final Object result : results) {
- if (result instanceof Set) { // ignore FunctionInvocationTargetExceptions and other
- // Exceptions...
- distributedPersistentRecoveryDetails.addAll((Set<Object>) result);
- }
- }
- return distributedPersistentRecoveryDetails;
- }
-
- private Result toMissingDiskStoresTabularResult(final List<Object> resultDetails)
- throws ResultDataException {
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- List<PersistentMemberPattern> missingDiskStores = new ArrayList<>();
- List<ColocatedRegionDetails> missingColocatedRegions = new ArrayList<>();
-
- for (Object detail : resultDetails) {
- if (detail instanceof PersistentMemberPattern) {
- missingDiskStores.add((PersistentMemberPattern) detail);
- } else if (detail instanceof ColocatedRegionDetails) {
- missingColocatedRegions.add((ColocatedRegionDetails) detail);
- } else {
- throw new ResultDataException("Unknown type of PersistentRecoveryFailures result");
- }
- }
-
- boolean hasMissingDiskStores = !missingDiskStores.isEmpty();
- boolean hasMissingColocatedRegions = !missingColocatedRegions.isEmpty();
- if (hasMissingDiskStores) {
- CompositeResultData.SectionResultData missingDiskStoresSection = crd.addSection();
- missingDiskStoresSection.setHeader("Missing Disk Stores");
- TabularResultData missingDiskStoreData = missingDiskStoresSection.addTable();
-
- for (PersistentMemberPattern persistentMemberDetails : missingDiskStores) {
- missingDiskStoreData.accumulate("Disk Store ID", persistentMemberDetails.getUUID());
- missingDiskStoreData.accumulate("Host", persistentMemberDetails.getHost());
- missingDiskStoreData.accumulate("Directory", persistentMemberDetails.getDirectory());
- }
- } else {
- CompositeResultData.SectionResultData noMissingDiskStores = crd.addSection();
- noMissingDiskStores.setHeader("No missing disk store found");
- }
- if (hasMissingDiskStores || hasMissingColocatedRegions) {
- // For clarity, separate disk store and colocated region information
- crd.addSection().setHeader("\n");
- }
-
- if (hasMissingColocatedRegions) {
- CompositeResultData.SectionResultData missingRegionsSection = crd.addSection();
- missingRegionsSection.setHeader("Missing Colocated Regions");
- TabularResultData missingRegionData = missingRegionsSection.addTable();
-
- for (ColocatedRegionDetails colocatedRegionDetails : missingColocatedRegions) {
- missingRegionData.accumulate("Host", colocatedRegionDetails.getHost());
- missingRegionData.accumulate("Distributed Member", colocatedRegionDetails.getMember());
- missingRegionData.accumulate("Parent Region", colocatedRegionDetails.getParent());
- missingRegionData.accumulate("Missing Colocated Region", colocatedRegionDetails.getChild());
- }
- } else {
- CompositeResultData.SectionResultData noMissingColocatedRegions = crd.addSection();
- noMissingColocatedRegions.setHeader("No missing colocated region found");
- }
- return ResultBuilder.buildResult(crd);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
deleted file mode 100644
index fcee9d8..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShutdownCommand.java
+++ /dev/null
@@ -1,209 +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 java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-import org.apache.logging.log4j.Logger;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionException;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.logging.LogService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.ShutDownFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ShutdownCommand implements GfshCommand {
- private final static String DEFAULT_TIME_OUT = "10";
- private final static Logger logger = LogService.getLogger();
-
- @CliCommand(value = CliStrings.SHUTDOWN, help = CliStrings.SHUTDOWN__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_LIFECYCLE},
- interceptor = "org.apache.geode.management.internal.cli.commands.ShutdownCommand$ShutdownCommandInterceptor")
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE)
- public Result shutdown(
- @CliOption(key = CliStrings.SHUTDOWN__TIMEOUT, unspecifiedDefaultValue = DEFAULT_TIME_OUT,
- help = CliStrings.SHUTDOWN__TIMEOUT__HELP) int userSpecifiedTimeout,
- @CliOption(key = CliStrings.INCLUDE_LOCATORS, unspecifiedDefaultValue = "false",
- help = CliStrings.INCLUDE_LOCATORS_HELP) boolean shutdownLocators) {
- try {
-
- if (userSpecifiedTimeout < Integer.parseInt(DEFAULT_TIME_OUT)) {
- return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__IMPROPER_TIMEOUT);
- }
-
- // convert to milliseconds
- long timeout = userSpecifiedTimeout * 1000;
- InternalCache cache = getCache();
- int numDataNodes = CliUtil.getAllNormalMembers(cache).size();
- Set<DistributedMember> locators = CliUtil.getAllMembers(cache);
- Set<DistributedMember> dataNodes = CliUtil.getAllNormalMembers(cache);
- locators.removeAll(dataNodes);
-
- if (!shutdownLocators && numDataNodes == 0) {
- return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__NO_DATA_NODE_FOUND);
- }
-
- String managerName = cache.getJmxManagerAdvisor().getDistributionManager().getId().getId();
-
- final DistributedMember manager = CliUtil.getDistributedMemberByNameOrId(managerName);
-
- dataNodes.remove(manager);
-
- // shut down all data members excluding this manager if manager is a data node
- long timeElapsed = shutDownNodeWithTimeOut(timeout, dataNodes);
- timeout = timeout - timeElapsed;
-
- // shut down locators one by one
- if (shutdownLocators) {
- if (manager == null) {
- return ResultBuilder.createUserErrorResult(CliStrings.SHUTDOWN__MSG__MANAGER_NOT_FOUND);
- }
-
- // remove current locator as that would get shutdown last
- if (locators.contains(manager)) {
- locators.remove(manager);
- }
-
- for (DistributedMember locator : locators) {
- Set<DistributedMember> lsSet = new HashSet<>();
- lsSet.add(locator);
- long elapsedTime = shutDownNodeWithTimeOut(timeout, lsSet);
- timeout = timeout - elapsedTime;
- }
- }
-
- if (locators.contains(manager) && !shutdownLocators) { // This means manager is a locator and
- // shutdownLocators is false. Hence we
- // should not stop the manager
- return ResultBuilder.createInfoResult("Shutdown is triggered");
- }
- // now shut down this manager
- Set<DistributedMember> mgrSet = new HashSet<>();
- mgrSet.add(manager);
- // No need to check further timeout as this is the last node we will be
- // shutting down
- shutDownNodeWithTimeOut(timeout, mgrSet);
-
- } catch (TimeoutException tex) {
- return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN_TIMEDOUT);
- } catch (Exception ex) {
- ex.printStackTrace();
- return ResultBuilder.createUserErrorResult(ex.getMessage());
- }
- // @TODO. List all the nodes which could be successfully shutdown
- return ResultBuilder.createInfoResult("Shutdown is triggered");
- }
-
- /**
- * @param timeout user specified timeout
- * @param nodesToBeStopped list of nodes to be stopped
- * @return Elapsed time to shutdown the given nodes;
- */
- private long shutDownNodeWithTimeOut(long timeout, Set<DistributedMember> nodesToBeStopped)
- throws TimeoutException, InterruptedException, ExecutionException {
-
- long shutDownTimeStart = System.currentTimeMillis();
- shutdownNode(timeout, nodesToBeStopped);
-
- long shutDownTimeEnd = System.currentTimeMillis();
-
- long timeElapsed = shutDownTimeEnd - shutDownTimeStart;
-
- if (timeElapsed > timeout || Boolean.getBoolean("ThrowTimeoutException")) {
- // The second check for ThrowTimeoutException is a test hook
- throw new TimeoutException();
- }
- return timeElapsed;
- }
-
- private void shutdownNode(final long timeout, final Set<DistributedMember> includeMembers)
- throws TimeoutException, InterruptedException, ExecutionException {
- ExecutorService exec = Executors.newSingleThreadExecutor();
- try {
- final Function shutDownFunction = new ShutDownFunction();
- logger.info("Gfsh executing shutdown on members " + includeMembers);
- Callable<String> shutdownNodes = new Callable<String>() {
-
- @Override
- public String call() {
- try {
- Execution execution = FunctionService.onMembers(includeMembers);
- execution.execute(shutDownFunction);
- } catch (FunctionException functionEx) {
- // Expected Exception as the function is shutting down the target members and the result
- // collector will get member departed exception
- }
- return "SUCCESS";
- }
- };
- Future<String> result = exec.submit(shutdownNodes);
- result.get(timeout, TimeUnit.MILLISECONDS);
- } catch (TimeoutException te) {
- logger.error("TimeoutException in shutting down members." + includeMembers);
- throw te;
- } catch (InterruptedException e) {
- logger.error("InterruptedException in shutting down members." + includeMembers);
- throw e;
- } catch (ExecutionException e) {
- logger.error("ExecutionException in shutting down members." + includeMembers);
- throw e;
- } finally {
- exec.shutdownNow();
- }
- }
-
- public static class ShutdownCommandInterceptor extends AbstractCliAroundInterceptor {
- @Override
- public Result preExecution(GfshParseResult parseResult) {
-
- // This hook is for testing purpose only.
- if (Boolean.getBoolean(CliStrings.IGNORE_INTERCEPTORS)) {
- return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
- }
-
- Response response = readYesNo(CliStrings.SHUTDOWN__MSG__WARN_USER, Response.YES);
- if (response == Response.NO) {
- return ResultBuilder
- .createShellClientAbortOperationResult(CliStrings.SHUTDOWN__MSG__ABORTING_SHUTDOWN);
- } else {
- return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
index 5e1df6f..72ccfbb 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartLocatorCommand.java
@@ -57,7 +57,7 @@ import org.apache.geode.management.internal.cli.util.HostUtils;
import org.apache.geode.management.internal.configuration.utils.ClusterConfigurationStatusRetriever;
import org.apache.geode.security.AuthenticationFailedException;
-public class StartLocatorCommand extends StartMemberCommand implements GfshCommand {
+public class StartLocatorCommand implements GfshCommand {
@CliCommand(value = CliStrings.START_LOCATOR, help = CliStrings.START_LOCATOR__HELP)
@CliMetaData(shellOnly = true,
relatedTopic = {CliStrings.TOPIC_GEODE_LOCATOR, CliStrings.TOPIC_GEODE_LIFECYCLE})
@@ -123,10 +123,10 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
try {
if (StringUtils.isBlank(memberName)) {
// when the user doesn't give us a name, we make one up!
- memberName = getNameGenerator().generate('-');
+ memberName = StartMemberUtils.getNameGenerator().generate('-');
}
- workingDirectory = resolveWorkingDir(workingDirectory, memberName);
+ workingDirectory = StartMemberUtils.resolveWorkingDir(workingDirectory, memberName);
if (gemfirePropertiesFile != null && !gemfirePropertiesFile.exists()) {
return ResultBuilder.createUserErrorResult(
@@ -142,28 +142,32 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
File locatorPidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
- final int oldPid = readPid(locatorPidFile);
+ final int oldPid = StartMemberUtils.readPid(locatorPidFile);
Properties gemfireProperties = new Properties();
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS, group);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS, locators);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOG_LEVEL, logLevel);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_ADDRESS,
- mcastBindAddress);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_PORT, mcastPort);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION,
- enableSharedConfiguration);
- setPropertyIfNotNull(gemfireProperties,
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.GROUPS,
+ group);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOCATORS,
+ locators);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.LOG_LEVEL,
+ logLevel);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.MCAST_ADDRESS, mcastBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.MCAST_PORT,
+ mcastPort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION, enableSharedConfiguration);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
ConfigurationProperties.LOAD_CLUSTER_CONFIGURATION_FROM_DIR,
loadSharedConfigurationFromDirectory);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.CLUSTER_CONFIGURATION_DIR,
- clusterConfigDir);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.HTTP_SERVICE_PORT,
- httpServicePort);
- setPropertyIfNotNull(gemfireProperties, ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS,
- httpServiceBindAddress);
- setPropertyIfNotNull(gemfireProperties,
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.CLUSTER_CONFIGURATION_DIR, clusterConfigDir);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.HTTP_SERVICE_PORT, httpServicePort);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
+ ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS, httpServiceBindAddress);
+ StartMemberUtils.setPropertyIfNotNull(gemfireProperties,
ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, jmxManagerHostnameForClients);
// read the OSProcess enable redirect system property here
@@ -254,7 +258,7 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
&& locatorState.isStartingOrNotResponding());
} finally {
// stop will close
- stderrReader.stopAsync(PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
+ stderrReader.stopAsync(StartMemberUtils.PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
// ErrorStream
getGfsh().getSignalHandler().unregisterListener(locatorSignalListener);
@@ -320,7 +324,6 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
SystemFailure.initiateFailure(e);
throw e;
} catch (Throwable t) {
- t.printStackTrace();
SystemFailure.checkFailure();
String errorMessage = String.format(CliStrings.START_LOCATOR__GENERAL_ERROR_MESSAGE,
StringUtils.defaultIfBlank(workingDirectory, memberName),
@@ -436,19 +439,19 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
final String maxHeap) throws MalformedObjectNameException {
List<String> commandLine = new ArrayList<>();
- commandLine.add(getJavaPath());
+ commandLine.add(StartMemberUtils.getJavaPath());
commandLine.add("-server");
commandLine.add("-classpath");
commandLine
.add(getLocatorClasspath(Boolean.TRUE.equals(includeSystemClasspath), userClasspath));
- addCurrentLocators(this, commandLine, gemfireProperties);
- addGemFirePropertyFile(commandLine, gemfirePropertiesFile);
- addGemFireSecurityPropertyFile(commandLine, gemfireSecurityPropertiesFile);
- addGemFireSystemProperties(commandLine, gemfireProperties);
- addJvmArgumentsAndOptions(commandLine, jvmArgsOpts);
- addInitialHeap(commandLine, initialHeap);
- addMaxHeap(commandLine, maxHeap);
+ StartMemberUtils.addCurrentLocators(this, commandLine, gemfireProperties);
+ StartMemberUtils.addGemFirePropertyFile(commandLine, gemfirePropertiesFile);
+ StartMemberUtils.addGemFireSecurityPropertyFile(commandLine, gemfireSecurityPropertiesFile);
+ StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
+ StartMemberUtils.addJvmArgumentsAndOptions(commandLine, jvmArgsOpts);
+ StartMemberUtils.addInitialHeap(commandLine, initialHeap);
+ StartMemberUtils.addMaxHeap(commandLine, maxHeap);
commandLine.add(
"-D".concat(AbstractLauncher.SIGNAL_HANDLER_REGISTRATION_SYSTEM_PROPERTY.concat("=true")));
@@ -489,7 +492,7 @@ public class StartLocatorCommand extends StartMemberCommand implements GfshComma
}
String getLocatorClasspath(final boolean includeSystemClasspath, final String userClasspath) {
- return toClasspath(includeSystemClasspath, new String[] {CORE_DEPENDENCIES_JAR_PATHNAME},
- userClasspath);
+ return StartMemberUtils.toClasspath(includeSystemClasspath,
+ new String[] {StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME}, userClasspath);
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java
deleted file mode 100644
index 6bdc25c..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/StartMemberCommand.java
+++ /dev/null
@@ -1,248 +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.LOCATORS;
-import static org.apache.geode.management.internal.cli.shell.MXBeanProvider.getDistributedSystemMXBean;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Properties;
-
-import javax.management.MalformedObjectNameException;
-
-import org.apache.commons.lang.ArrayUtils;
-
-import org.apache.geode.distributed.internal.DistributionConfig;
-import org.apache.geode.internal.GemFireVersion;
-import org.apache.geode.internal.process.ProcessLauncherContext;
-import org.apache.geode.internal.util.IOUtils;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.internal.cli.util.ThreePhraseGenerator;
-
-/**
- * Encapsulates methods used by StartServerCommand and StartLocatorCommand and their associated
- * tests.
- *
- * @see StartLocatorCommand
- * @see StartServerCommand
- */
-public class StartMemberCommand {
- public static final String GEODE_HOME = System.getenv("GEODE_HOME");
-
- private static final String JAVA_HOME = System.getProperty("java.home");
- static final int CMS_INITIAL_OCCUPANCY_FRACTION = 60;
- private static final ThreePhraseGenerator nameGenerator = new ThreePhraseGenerator();
-
- static final String CORE_DEPENDENCIES_JAR_PATHNAME =
- IOUtils.appendToPath(GEODE_HOME, "lib", "geode-dependencies.jar");
- static final String GEODE_JAR_PATHNAME =
- IOUtils.appendToPath(GEODE_HOME, "lib", GemFireVersion.getGemFireJarFileName());
- static final long PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS = 5 * 1000;
- static final int INVALID_PID = -1;
-
- static ThreePhraseGenerator getNameGenerator() {
- return nameGenerator;
- }
-
- void setPropertyIfNotNull(Properties properties, String key, Object value) {
- if (key != null && value != null) {
- properties.setProperty(key, value.toString());
- }
- }
-
- String resolveWorkingDir(String userSpecifiedDir, String memberName) {
- File workingDir =
- (userSpecifiedDir == null) ? new File(memberName) : new File(userSpecifiedDir);
- String workingDirPath = IOUtils.tryGetCanonicalPathElseGetAbsolutePath(workingDir);
- if (!workingDir.exists()) {
- if (!workingDir.mkdirs()) {
- throw new IllegalStateException(String.format(
- "Could not create directory %s. Please verify directory path or user permissions.",
- workingDirPath));
- }
- }
- return workingDirPath;
- }
-
- void addGemFirePropertyFile(final List<String> commandLine, final File gemfirePropertiesFile) {
- if (gemfirePropertiesFile != null) {
- commandLine.add("-DgemfirePropertyFile=" + gemfirePropertiesFile.getAbsolutePath());
- }
- }
-
- void addGemFireSecurityPropertyFile(final List<String> commandLine,
- final File gemfireSecurityPropertiesFile) {
- if (gemfireSecurityPropertiesFile != null) {
- commandLine
- .add("-DgemfireSecurityPropertyFile=" + gemfireSecurityPropertiesFile.getAbsolutePath());
- }
- }
-
- void addGemFireSystemProperties(final List<String> commandLine,
- final Properties gemfireProperties) {
- for (final Object property : gemfireProperties.keySet()) {
- final String propertyName = property.toString();
- final String propertyValue = gemfireProperties.getProperty(propertyName);
- if (org.apache.geode.internal.lang.StringUtils.isNotBlank(propertyValue)) {
- commandLine.add(
- "-D" + DistributionConfig.GEMFIRE_PREFIX + "" + propertyName + "=" + propertyValue);
- }
- }
- }
-
- void addJvmArgumentsAndOptions(final List<String> commandLine, final String[] jvmArgsOpts) {
- if (jvmArgsOpts != null) {
- commandLine.addAll(Arrays.asList(jvmArgsOpts));
- }
- }
-
- void addInitialHeap(final List<String> commandLine, final String initialHeap) {
- if (org.apache.geode.internal.lang.StringUtils.isNotBlank(initialHeap)) {
- commandLine.add("-Xms" + initialHeap);
- }
- }
-
- void addMaxHeap(final List<String> commandLine, final String maxHeap) {
- if (org.apache.geode.internal.lang.StringUtils.isNotBlank(maxHeap)) {
- commandLine.add("-Xmx" + maxHeap);
- commandLine.add("-XX:+UseConcMarkSweepGC");
- commandLine.add("-XX:CMSInitiatingOccupancyFraction=" + CMS_INITIAL_OCCUPANCY_FRACTION);
- // commandLine.add("-XX:MinHeapFreeRatio=" + MINIMUM_HEAP_FREE_RATIO);
- }
- }
-
- void addCurrentLocators(GfshCommand gfshCommand, final List<String> commandLine,
- final Properties gemfireProperties) throws MalformedObjectNameException {
- if (org.apache.geode.internal.lang.StringUtils
- .isBlank(gemfireProperties.getProperty(LOCATORS))) {
- String currentLocators = getCurrentLocators(gfshCommand);
- if (org.apache.geode.internal.lang.StringUtils.isNotBlank(currentLocators)) {
- commandLine.add("-D".concat(ProcessLauncherContext.OVERRIDDEN_DEFAULTS_PREFIX)
- .concat(LOCATORS).concat("=").concat(currentLocators));
- }
- }
- }
-
- String getCurrentLocators(GfshCommand gfshCommand) throws MalformedObjectNameException {
- String delimitedLocators = "";
- try {
- if (gfshCommand.isConnectedAndReady()) {
- final DistributedSystemMXBean dsMBeanProxy = getDistributedSystemMXBean();
- if (dsMBeanProxy != null) {
- final String[] locators = dsMBeanProxy.listLocators();
- if (locators != null && locators.length > 0) {
- final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < locators.length; i++) {
- if (i > 0) {
- sb.append(",");
- }
- sb.append(locators[i]);
- }
- delimitedLocators = sb.toString();
- }
- }
- }
- } catch (IOException e) { // thrown by getDistributedSystemMXBean
- // leave delimitedLocators = ""
- gfshCommand.getGfsh().logWarning("DistributedSystemMXBean is unavailable\n", e);
- }
- return delimitedLocators;
- }
-
- int readPid(final File pidFile) {
- assert pidFile != null : "The file from which to read the process ID (pid) cannot be null!";
- if (pidFile.isFile()) {
- BufferedReader fileReader = null;
- try {
- fileReader = new BufferedReader(new FileReader(pidFile));
- return Integer.parseInt(fileReader.readLine());
- } catch (IOException | NumberFormatException ignore) {
- } finally {
- IOUtils.close(fileReader);
- }
- }
- return INVALID_PID;
- }
-
- String getJavaPath() {
- return new File(new File(JAVA_HOME, "bin"), "java").getPath();
- }
-
- String getSystemClasspath() {
- return System.getProperty("java.class.path");
- }
-
- String toClasspath(final boolean includeSystemClasspath, String[] jarFilePathnames,
- String... userClasspaths) {
- // gemfire jar must absolutely be the first JAR file on the CLASSPATH!!!
- StringBuilder classpath = new StringBuilder(getGemFireJarPath());
-
- userClasspaths = (userClasspaths != null ? userClasspaths : ArrayUtils.EMPTY_STRING_ARRAY);
-
- // Then, include user-specified classes on CLASSPATH to enable the user to override GemFire JAR
- // dependencies
- // with application-specific versions; this logic/block corresponds to classes/jar-files
- // specified with the
- // --classpath option to the 'start locator' and 'start server commands'; also this will
- // override any
- // System CLASSPATH environment variable setting, which is consistent with the Java platform
- // behavior...
- for (String userClasspath : userClasspaths) {
- if (org.apache.geode.internal.lang.StringUtils.isNotBlank(userClasspath)) {
- classpath.append((classpath.length() == 0)
- ? org.apache.geode.internal.lang.StringUtils.EMPTY : File.pathSeparator);
- classpath.append(userClasspath);
- }
- }
-
- // Now, include any System-specified CLASSPATH environment variable setting...
- if (includeSystemClasspath) {
- classpath.append(File.pathSeparator);
- classpath.append(getSystemClasspath());
- }
-
- jarFilePathnames =
- (jarFilePathnames != null ? jarFilePathnames : ArrayUtils.EMPTY_STRING_ARRAY);
-
- // And finally, include all GemFire dependencies on the CLASSPATH...
- for (String jarFilePathname : jarFilePathnames) {
- if (org.apache.geode.internal.lang.StringUtils.isNotBlank(jarFilePathname)) {
- classpath.append((classpath.length() == 0)
- ? org.apache.geode.internal.lang.StringUtils.EMPTY : File.pathSeparator);
- classpath.append(jarFilePathname);
- }
- }
- return classpath.toString();
- }
-
- String getGemFireJarPath() {
- String classpath = getSystemClasspath();
- String gemfireJarPath = GEODE_JAR_PATHNAME;
- for (String classpathElement : classpath.split(File.pathSeparator)) {
- // MUST CHANGE THIS TO REGEX SINCE VERSION CHANGES IN JAR NAME
- if (classpathElement.endsWith("gemfire-core-8.2.0.0-SNAPSHOT.jar")) {
- gemfireJarPath = classpathElement;
- break;
- }
- }
- return gemfireJarPath;
- }
-}
[14/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java
deleted file mode 100644
index a3fe19c..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeDiskStoreCommand.java
+++ /dev/null
@@ -1,179 +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 java.util.Collections;
-import java.util.List;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.lang.ClassUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.domain.DiskStoreDetails;
-import org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.util.DiskStoreNotFoundException;
-import org.apache.geode.management.internal.cli.util.MemberNotFoundException;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DescribeDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.DESCRIBE_DISK_STORE, help = CliStrings.DESCRIBE_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result describeDiskStore(
- @CliOption(key = CliStrings.MEMBER, mandatory = true,
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.DESCRIBE_DISK_STORE__MEMBER__HELP) final String memberName,
- @CliOption(key = CliStrings.DESCRIBE_DISK_STORE__NAME, mandatory = true,
- optionContext = ConverterHint.DISKSTORE,
- help = CliStrings.DESCRIBE_DISK_STORE__NAME__HELP) final String diskStoreName) {
- try {
- return toCompositeResult(getDiskStoreDescription(memberName, diskStoreName));
- } catch (DiskStoreNotFoundException | MemberNotFoundException e) {
- return ResultBuilder.createShellClientErrorResult(e.getMessage());
- } catch (FunctionInvocationTargetException ignore) {
- return ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_DISK_STORE));
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder
- .createGemFireErrorResult(String.format(CliStrings.DESCRIBE_DISK_STORE__ERROR_MESSAGE,
- memberName, diskStoreName, toString(t, isDebugging())));
- }
- }
-
- private Result toCompositeResult(final DiskStoreDetails diskStoreDetails) {
- final CompositeResultData diskStoreData = ResultBuilder.createCompositeResultData();
-
- final CompositeResultData.SectionResultData diskStoreSection = diskStoreData.addSection();
-
- diskStoreSection.addData("Disk Store ID", diskStoreDetails.getId());
- diskStoreSection.addData("Disk Store Name", diskStoreDetails.getName());
- diskStoreSection.addData("Member ID", diskStoreDetails.getMemberId());
- diskStoreSection.addData("Member Name", diskStoreDetails.getMemberName());
- diskStoreSection.addData("Allow Force Compaction",
- toString(diskStoreDetails.isAllowForceCompaction(), "Yes", "No"));
- diskStoreSection.addData("Auto Compaction",
- toString(diskStoreDetails.isAutoCompact(), "Yes", "No"));
- diskStoreSection.addData("Compaction Threshold", diskStoreDetails.getCompactionThreshold());
- diskStoreSection.addData("Max Oplog Size", diskStoreDetails.getMaxOplogSize());
- diskStoreSection.addData("Queue Size", diskStoreDetails.getQueueSize());
- diskStoreSection.addData("Time Interval", diskStoreDetails.getTimeInterval());
- diskStoreSection.addData("Write Buffer Size", diskStoreDetails.getWriteBufferSize());
- diskStoreSection.addData("Disk Usage Warning Percentage",
- diskStoreDetails.getDiskUsageWarningPercentage());
- diskStoreSection.addData("Disk Usage Critical Percentage",
- diskStoreDetails.getDiskUsageCriticalPercentage());
- diskStoreSection.addData("PDX Serialization Meta-Data Stored",
- toString(diskStoreDetails.isPdxSerializationMetaDataStored(), "Yes", "No"));
-
- final TabularResultData diskDirTable = diskStoreData.addSection().addTable();
-
- for (DiskStoreDetails.DiskDirDetails diskDirDetails : diskStoreDetails) {
- diskDirTable.accumulate("Disk Directory", diskDirDetails.getAbsolutePath());
- diskDirTable.accumulate("Size", diskDirDetails.getSize());
- }
-
- final TabularResultData regionTable = diskStoreData.addSection().addTable();
-
- for (DiskStoreDetails.RegionDetails regionDetails : diskStoreDetails.iterateRegions()) {
- regionTable.accumulate("Region Path", regionDetails.getFullPath());
- regionTable.accumulate("Region Name", regionDetails.getName());
- regionTable.accumulate("Persistent", toString(regionDetails.isPersistent(), "Yes", "No"));
- regionTable.accumulate("Overflow To Disk",
- toString(regionDetails.isOverflowToDisk(), "Yes", "No"));
- }
-
- final TabularResultData cacheServerTable = diskStoreData.addSection().addTable();
-
- for (DiskStoreDetails.CacheServerDetails cacheServerDetails : diskStoreDetails
- .iterateCacheServers()) {
- cacheServerTable.accumulate("Bind Address", cacheServerDetails.getBindAddress());
- cacheServerTable.accumulate("Hostname for Clients", cacheServerDetails.getHostName());
- cacheServerTable.accumulate("Port", cacheServerDetails.getPort());
- }
-
- final TabularResultData gatewayTable = diskStoreData.addSection().addTable();
-
- for (DiskStoreDetails.GatewayDetails gatewayDetails : diskStoreDetails.iterateGateways()) {
- gatewayTable.accumulate("Gateway ID", gatewayDetails.getId());
- gatewayTable.accumulate("Persistent", toString(gatewayDetails.isPersistent(), "Yes", "No"));
- }
-
- final TabularResultData asyncEventQueueTable = diskStoreData.addSection().addTable();
-
- for (DiskStoreDetails.AsyncEventQueueDetails asyncEventQueueDetails : diskStoreDetails
- .iterateAsyncEventQueues()) {
- asyncEventQueueTable.accumulate("Async Event Queue ID", asyncEventQueueDetails.getId());
- }
-
- return ResultBuilder.buildResult(diskStoreData);
- }
-
- public DiskStoreDetails getDiskStoreDescription(final String memberName,
- final String diskStoreName) {
- final DistributedMember member = getMember(getCache(), memberName); // may throw a
- // MemberNotFoundException
-
- final ResultCollector<?, ?> resultCollector =
- getMembersFunctionExecutor(Collections.singleton(member)).setArguments(diskStoreName)
- .execute(new DescribeDiskStoreFunction());
-
- final Object result = ((List<?>) resultCollector.getResult()).get(0);
-
- if (result instanceof DiskStoreDetails) { // disk store details in hand...
- return (DiskStoreDetails) result;
- } else if (result instanceof DiskStoreNotFoundException) { // bad disk store name...
- throw (DiskStoreNotFoundException) result;
- } else { // unknown and unexpected return type...
- final Throwable cause = (result instanceof Throwable ? (Throwable) result : null);
-
- if (isLogging()) {
- if (cause != null) {
- getGfsh().logSevere(String.format(
- "Exception (%1$s) occurred while executing '%2$s' on member (%3$s) with disk store (%4$s).",
- ClassUtils.getClassName(cause), CliStrings.DESCRIBE_DISK_STORE, memberName,
- diskStoreName), cause);
- } else {
- getGfsh().logSevere(String.format(
- "Received an unexpected result of type (%1$s) while executing '%2$s' on member (%3$s) with disk store (%4$s).",
- ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE, memberName,
- diskStoreName), null);
- }
- }
-
- throw new RuntimeException(
- CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
- ClassUtils.getClassName(result), CliStrings.DESCRIBE_DISK_STORE),
- cause);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java
deleted file mode 100644
index 236dd23e..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeMemberCommand.java
+++ /dev/null
@@ -1,133 +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 java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.CacheClosedException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.CacheServerInfo;
-import org.apache.geode.management.internal.cli.domain.MemberInformation;
-import org.apache.geode.management.internal.cli.functions.GetMemberInformationFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DescribeMemberCommand implements GfshCommand {
- private static final GetMemberInformationFunction getMemberInformation =
- new GetMemberInformationFunction();
-
- @CliCommand(value = {CliStrings.DESCRIBE_MEMBER}, help = CliStrings.DESCRIBE_MEMBER__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result describeMember(@CliOption(key = CliStrings.DESCRIBE_MEMBER__IDENTIFIER,
- optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.DESCRIBE_MEMBER__IDENTIFIER__HELP,
- mandatory = true) String memberNameOrId) {
- Result result = null;
-
- try {
- DistributedMember memberToBeDescribed =
- CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
-
- if (memberToBeDescribed != null) {
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(getMemberInformation, null, memberToBeDescribed);
-
- ArrayList<?> output = (ArrayList<?>) rc.getResult();
- Object obj = output.get(0);
-
- if (obj != null && (obj instanceof MemberInformation)) {
-
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
-
- MemberInformation memberInformation = (MemberInformation) obj;
- memberInformation.setName(memberToBeDescribed.getName());
- memberInformation.setId(memberToBeDescribed.getId());
- memberInformation.setHost(memberToBeDescribed.getHost());
- memberInformation.setProcessId("" + memberToBeDescribed.getProcessId());
-
- CompositeResultData.SectionResultData section = crd.addSection();
- section.addData("Name", memberInformation.getName());
- section.addData("Id", memberInformation.getId());
- section.addData("Host", memberInformation.getHost());
- section.addData("Regions",
- CliUtil.convertStringSetToString(memberInformation.getHostedRegions(), '\n'));
- section.addData("PID", memberInformation.getProcessId());
- section.addData("Groups", memberInformation.getGroups());
- section.addData("Used Heap", memberInformation.getHeapUsage() + "M");
- section.addData("Max Heap", memberInformation.getMaxHeapSize() + "M");
-
- String offHeapMemorySize = memberInformation.getOffHeapMemorySize();
- if (offHeapMemorySize != null && !offHeapMemorySize.isEmpty()) {
- section.addData("Off Heap Size", offHeapMemorySize);
- }
-
- section.addData("Working Dir", memberInformation.getWorkingDirPath());
- section.addData("Log file", memberInformation.getLogFilePath());
-
- section.addData("Locators", memberInformation.getLocators());
-
- if (memberInformation.isServer()) {
- CompositeResultData.SectionResultData clientServiceSection = crd.addSection();
- List<CacheServerInfo> csList = memberInformation.getCacheServeInfo();
-
- if (csList != null) {
- Iterator<CacheServerInfo> iters = csList.iterator();
- clientServiceSection.setHeader("Cache Server Information");
-
- while (iters.hasNext()) {
- CacheServerInfo cacheServerInfo = iters.next();
- clientServiceSection.addData("Server Bind", cacheServerInfo.getBindAddress());
- clientServiceSection.addData("Server Port", cacheServerInfo.getPort());
- clientServiceSection.addData("Running", cacheServerInfo.isRunning());
- }
-
- clientServiceSection.addData("Client Connections",
- memberInformation.getClientCount());
- }
- }
- result = ResultBuilder.buildResult(crd);
-
- } else {
- result = ResultBuilder.createInfoResult(CliStrings.format(
- CliStrings.DESCRIBE_MEMBER__MSG__INFO_FOR__0__COULD_NOT_BE_RETRIEVED,
- new Object[] {memberNameOrId}));
- }
- } else {
- result = ResultBuilder.createInfoResult(CliStrings
- .format(CliStrings.DESCRIBE_MEMBER__MSG__NOT_FOUND, new Object[] {memberNameOrId}));
- }
- } catch (CacheClosedException ignored) {
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java
deleted file mode 100644
index 904a677..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeOfflineDiskStoreCommand.java
+++ /dev/null
@@ -1,75 +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 java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.PrintStream;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.Region;
-import org.apache.geode.internal.cache.DiskStoreImpl;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-
-public class DescribeOfflineDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.DESCRIBE_OFFLINE_DISK_STORE,
- help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- public Result describeOfflineDiskStore(
- @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
- help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
- @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
- help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
- @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES,
- help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__PDX_TYPES__HELP) Boolean listPdxTypes,
- @CliOption(key = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME,
- help = CliStrings.DESCRIBE_OFFLINE_DISK_STORE__REGIONNAME__HELP) String regionName) {
-
- try {
- final File[] dirs = new File[diskDirs.length];
- for (int i = 0; i < diskDirs.length; i++) {
- dirs[i] = new File((diskDirs[i]));
- }
-
- if (Region.SEPARATOR.equals(regionName)) {
- return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
- }
-
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(outputStream);
-
- DiskStoreImpl.dumpInfo(printStream, diskStoreName, dirs, regionName, listPdxTypes);
- return ResultBuilder.createInfoResult(outputStream.toString());
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- if (th.getMessage() == null) {
- return ResultBuilder.createGemFireErrorResult(
- "An error occurred while describing offline disk stores: " + th);
- }
- return ResultBuilder.createGemFireErrorResult(
- "An error occurred while describing offline disk stores: " + th.getMessage());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java
deleted file mode 100644
index 65a6153..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeRegionCommand.java
+++ /dev/null
@@ -1,364 +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 java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.domain.FixedPartitionAttributesInfo;
-import org.apache.geode.management.internal.cli.domain.RegionDescription;
-import org.apache.geode.management.internal.cli.domain.RegionDescriptionPerMember;
-import org.apache.geode.management.internal.cli.functions.GetRegionDescriptionFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.util.RegionAttributesNames;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DescribeRegionCommand implements GfshCommand {
- private static final GetRegionDescriptionFunction getRegionDescription =
- new GetRegionDescriptionFunction();
-
- @CliCommand(value = {CliStrings.DESCRIBE_REGION}, help = CliStrings.DESCRIBE_REGION__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result describeRegion(
- @CliOption(key = CliStrings.DESCRIBE_REGION__NAME, optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.DESCRIBE_REGION__NAME__HELP, mandatory = true) String regionName) {
-
- Result result;
- try {
-
- if (regionName == null || regionName.isEmpty()) {
- return ResultBuilder.createUserErrorResult("Please provide a region name");
- }
-
- if (regionName.equals(Region.SEPARATOR)) {
- return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
- }
-
- InternalCache cache = getCache();
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(getRegionDescription, regionName, CliUtil.getAllMembers(cache));
-
- List<?> resultList = (List<?>) rc.getResult();
-
- // The returned result could be a region description with per member and /or single local
- // region
- Object[] results = resultList.toArray();
- List<RegionDescription> regionDescriptionList = new ArrayList<>();
-
- for (int i = 0; i < results.length; i++) {
-
- if (results[i] instanceof RegionDescriptionPerMember) {
- RegionDescriptionPerMember regionDescPerMember = (RegionDescriptionPerMember) results[i];
-
- if (regionDescPerMember != null) {
- RegionDescription regionDescription = new RegionDescription();
- regionDescription.add(regionDescPerMember);
-
- for (int j = i + 1; j < results.length; j++) {
- if (results[j] != null && results[j] instanceof RegionDescriptionPerMember) {
- RegionDescriptionPerMember preyRegionDescPerMember =
- (RegionDescriptionPerMember) results[j];
- if (regionDescription.add(preyRegionDescPerMember)) {
- results[j] = null;
- }
- }
- }
- regionDescriptionList.add(regionDescription);
- }
- } else if (results[i] instanceof Throwable) {
- Throwable t = (Throwable) results[i];
- LogWrapper.getInstance().info(t.getMessage(), t);
- }
- }
-
- if (regionDescriptionList.isEmpty()) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.format(CliStrings.REGION_NOT_FOUND, regionName));
- }
-
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
-
- for (RegionDescription regionDescription : regionDescriptionList) {
- // No point in displaying the scope for PR's
- if (regionDescription.isPartition()) {
- regionDescription.getCndRegionAttributes().remove(RegionAttributesNames.SCOPE);
- } else {
- String scope =
- regionDescription.getCndRegionAttributes().get(RegionAttributesNames.SCOPE);
- if (scope != null) {
- scope = scope.toLowerCase().replace('_', '-');
- regionDescription.getCndRegionAttributes().put(RegionAttributesNames.SCOPE, scope);
- }
- }
- CompositeResultData.SectionResultData regionSection = crd.addSection();
- regionSection.addSeparator('-');
- regionSection.addData("Name", regionDescription.getName());
-
- String dataPolicy =
- regionDescription.getDataPolicy().toString().toLowerCase().replace('_', ' ');
- regionSection.addData("Data Policy", dataPolicy);
-
- String memberType;
-
- if (regionDescription.isAccessor()) {
- memberType = CliStrings.DESCRIBE_REGION__ACCESSOR__MEMBER;
- } else {
- memberType = CliStrings.DESCRIBE_REGION__HOSTING__MEMBER;
- }
- regionSection.addData(memberType,
- CliUtil.convertStringSetToString(regionDescription.getHostingMembers(), '\n'));
- regionSection.addSeparator('.');
-
- TabularResultData commonNonDefaultAttrTable = regionSection.addSection().addTable();
-
- commonNonDefaultAttrTable.setHeader(CliStrings
- .format(CliStrings.DESCRIBE_REGION__NONDEFAULT__COMMONATTRIBUTES__HEADER, memberType));
- // Common Non Default Region Attributes
- Map<String, String> cndRegionAttrsMap = regionDescription.getCndRegionAttributes();
-
- // Common Non Default Eviction Attributes
- Map<String, String> cndEvictionAttrsMap = regionDescription.getCndEvictionAttributes();
-
- // Common Non Default Partition Attributes
- Map<String, String> cndPartitionAttrsMap = regionDescription.getCndPartitionAttributes();
-
- writeCommonAttributesToTable(commonNonDefaultAttrTable,
- CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, cndRegionAttrsMap);
- writeCommonAttributesToTable(commonNonDefaultAttrTable,
- CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION, cndEvictionAttrsMap);
- writeCommonAttributesToTable(commonNonDefaultAttrTable,
- CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, cndPartitionAttrsMap);
-
- // Member-wise non default Attributes
- Map<String, RegionDescriptionPerMember> regDescPerMemberMap =
- regionDescription.getRegionDescriptionPerMemberMap();
- Set<String> members = regDescPerMemberMap.keySet();
-
- TabularResultData table = regionSection.addSection().addTable();
-
- boolean setHeader = false;
- for (String member : members) {
- RegionDescriptionPerMember regDescPerMem = regDescPerMemberMap.get(member);
- Map<String, String> ndRa = regDescPerMem.getNonDefaultRegionAttributes();
- Map<String, String> ndEa = regDescPerMem.getNonDefaultEvictionAttributes();
- Map<String, String> ndPa = regDescPerMem.getNonDefaultPartitionAttributes();
-
- // Get all the member-specific non-default attributes by removing the common keys
- ndRa.keySet().removeAll(cndRegionAttrsMap.keySet());
- ndEa.keySet().removeAll(cndEvictionAttrsMap.keySet());
- ndPa.keySet().removeAll(cndPartitionAttrsMap.keySet());
-
- // Scope is not valid for PR's
- if (regionDescription.isPartition()) {
- if (ndRa.get(RegionAttributesNames.SCOPE) != null) {
- ndRa.remove(RegionAttributesNames.SCOPE);
- }
- }
-
- List<FixedPartitionAttributesInfo> fpaList = regDescPerMem.getFixedPartitionAttributes();
-
- if (!(ndRa.isEmpty() && ndEa.isEmpty() && ndPa.isEmpty()) || fpaList != null) {
- setHeader = true;
- boolean memberNameAdded;
- memberNameAdded = writeAttributesToTable(table,
- CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, ndRa, member, false);
- memberNameAdded =
- writeAttributesToTable(table, CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION,
- ndEa, member, memberNameAdded);
- memberNameAdded = writeAttributesToTable(table,
- CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, ndPa, member,
- memberNameAdded);
-
- writeFixedPartitionAttributesToTable(table, fpaList, member, memberNameAdded);
- }
- }
-
- if (setHeader) {
- table.setHeader(CliStrings.format(
- CliStrings.DESCRIBE_REGION__NONDEFAULT__PERMEMBERATTRIBUTES__HEADER, memberType));
- }
- }
-
- result = ResultBuilder.buildResult(crd);
- } catch (FunctionInvocationTargetException e) {
- result = ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_REGION));
- } catch (Exception e) {
- String errorMessage = CliStrings.format(CliStrings.EXCEPTION_CLASS_AND_MESSAGE,
- e.getClass().getName(), e.getMessage());
- result = ResultBuilder.createGemFireErrorResult(errorMessage);
- }
- return result;
- }
-
- private void writeCommonAttributesToTable(TabularResultData table, String attributeType,
- Map<String, String> attributesMap) {
- if (!attributesMap.isEmpty()) {
- Set<String> attributes = attributesMap.keySet();
- boolean isTypeAdded = false;
- final String blank = "";
-
- for (String attributeName : attributes) {
- String attributeValue = attributesMap.get(attributeName);
- String type;
-
- if (!isTypeAdded) {
- type = attributeType;
- isTypeAdded = true;
- } else {
- type = blank;
- }
- writeCommonAttributeToTable(table, type, attributeName, attributeValue);
- }
- }
- }
-
- private void writeFixedPartitionAttributesToTable(TabularResultData table,
- List<FixedPartitionAttributesInfo> fpaList, String member, boolean isMemberNameAdded) {
- if (fpaList == null) {
- return;
- }
-
- boolean isTypeAdded = false;
- final String blank = "";
- String memName;
-
- for (FixedPartitionAttributesInfo fpa : fpaList) {
- StringBuilder fpaBuilder = new StringBuilder();
- fpaBuilder.append(fpa.getPartitionName());
- fpaBuilder.append(',');
-
- if (fpa.isPrimary()) {
- fpaBuilder.append("Primary");
- } else {
- fpaBuilder.append("Secondary");
- }
- fpaBuilder.append(',');
- fpaBuilder.append(fpa.getNumBuckets());
-
- if (!isTypeAdded) {
- isTypeAdded = true;
- }
-
- if (!isMemberNameAdded) {
- memName = member;
- isMemberNameAdded = true;
- } else {
- memName = blank;
- }
- writeAttributeToTable(table, memName, "", "Fixed Partition", fpaBuilder.toString());
- }
- }
-
- private boolean writeAttributesToTable(TabularResultData table, String attributeType,
- Map<String, String> attributesMap, String member, boolean isMemberNameAdded) {
- if (!attributesMap.isEmpty()) {
- Set<String> attributes = attributesMap.keySet();
- boolean isTypeAdded = false;
- final String blank = "";
-
- for (String attributeName : attributes) {
- String attributeValue = attributesMap.get(attributeName);
- String type, memName;
-
- if (!isTypeAdded) {
- type = attributeType;
- isTypeAdded = true;
- } else {
- type = blank;
- }
-
- if (!isMemberNameAdded) {
- memName = member;
- isMemberNameAdded = true;
- } else {
- memName = blank;
- }
-
- writeAttributeToTable(table, memName, type, attributeName, attributeValue);
- }
- }
-
- return isMemberNameAdded;
- }
-
- private void writeAttributeToTable(TabularResultData table, String member, String attributeType,
- String attributeName, String attributeValue) {
-
- final String blank = "";
- if (attributeValue != null) {
- // Tokenize the attributeValue
- String[] attributeValues = attributeValue.split(",");
- boolean isFirstValue = true;
-
- for (String value : attributeValues) {
- if (isFirstValue) {
- table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, member);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
- isFirstValue = false;
- } else {
- table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, blank);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
- }
- }
- }
- }
-
- private void writeCommonAttributeToTable(TabularResultData table, String attributeType,
- String attributeName, String attributeValue) {
- final String blank = "";
- if (attributeValue != null) {
- String[] attributeValues = attributeValue.split(",");
- boolean isFirstValue = true;
- for (String value : attributeValues) {
- if (isFirstValue) {
- isFirstValue = false;
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
- } else {
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
- table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java
deleted file mode 100644
index 2f24736..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyDiskStoreCommand.java
+++ /dev/null
@@ -1,106 +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 java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.DestroyDiskStoreFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DestroyDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.DESTROY_DISK_STORE, help = CliStrings.DESTROY_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
- public Result destroyDiskStore(
- @CliOption(key = CliStrings.DESTROY_DISK_STORE__NAME, mandatory = true,
- help = CliStrings.DESTROY_DISK_STORE__NAME__HELP) String name,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.DESTROY_DISK_STORE__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) String[] groups) {
- try {
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> rc = CliUtil.executeFunction(new DestroyDiskStoreFunction(),
- new Object[] {name}, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
- + ": " + result.getThrowable().getMessage());
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else if (result.getMessage() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", result.getMessage());
- accumulatedData = true;
-
- if (xmlEntity.get() == null) {
- xmlEntity.set(result.getXmlEntity());
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder.createInfoResult("No matching disk stores found.");
- }
-
- Result result = ResultBuilder.buildResult(tabularData);
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), groups));
- }
-
- return result;
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.DESTROY_DISK_STORE__ERROR_WHILE_DESTROYING_REASON_0,
- new Object[] {th.getMessage()}));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java
deleted file mode 100644
index 37beb97..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyFunctionCommand.java
+++ /dev/null
@@ -1,163 +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 java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionException;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.UnregisterFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DestroyFunctionCommand implements GfshCommand {
- @CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION},
- interceptor = "org.apache.geode.management.internal.cli.commands.DestroyFunctionCommand$Interceptor")
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
- // TODO: Add optioncontext for functionId
- public Result destroyFunction(
- @CliOption(key = CliStrings.DESTROY_FUNCTION__ID, mandatory = true,
- help = CliStrings.DESTROY_FUNCTION__HELP) String functionId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.DESTROY_FUNCTION__ONGROUPS__HELP) String[] groups,
- @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.DESTROY_FUNCTION__ONMEMBER__HELP) String memberId) {
- try {
- InternalCache cache = getCache();
- Set<DistributedMember> dsMembers = new HashSet<>();
- if (groups != null && memberId != null) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.DESTROY_FUNCTION__MSG__PROVIDE_OPTION);
- } else if (groups != null && groups.length > 0) {
- // execute on group members
- for (String grp : groups) {
- dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
- }
- @SuppressWarnings("unchecked")
- Result results = executeFunction(cache, dsMembers, functionId);
- return results;
- } else if (memberId != null) {
- // execute on member
- dsMembers.add(getMember(cache, memberId));
- @SuppressWarnings("unchecked")
- Result results = executeFunction(cache, dsMembers, functionId);
- return results;
- } else {
- // no option provided.
- @SuppressWarnings("unchecked")
- Result results = executeFunction(cache, cache.getMembers(), functionId);
- return results;
- }
- } catch (Exception e) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
- return ResultBuilder.buildResult(errorResultData);
- }
- }
-
- private Result executeFunction(InternalCache cache, Set<DistributedMember> DsMembers,
- String functionId) {
- // unregister on a set of of members
- Function unregisterFunction = new UnregisterFunction();
- FunctionService.registerFunction(unregisterFunction);
- List resultList;
-
- if (DsMembers.isEmpty()) {
- return ResultBuilder.createInfoResult("No members for execution");
- }
- Object[] obj = new Object[1];
- obj[0] = functionId;
-
- Execution execution = FunctionService.onMembers(DsMembers).setArguments(obj);
-
- if (execution == null) {
- cache.getLogger().error("executeUnregister execution is null");
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.DESTROY_FUNCTION__MSG__CANNOT_EXECUTE);
- return (ResultBuilder.buildResult(errorResultData));
- }
- try {
- resultList = (ArrayList) execution.execute(unregisterFunction).getResult();
- } catch (FunctionException ex) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(ex.getMessage());
- return (ResultBuilder.buildResult(errorResultData));
- }
- String resultStr = ((String) resultList.get(0));
- if (resultStr.equals("Succeeded in unregistering")) {
- StringBuilder members = new StringBuilder();
- for (DistributedMember member : DsMembers) {
- members.append(member.getId());
- members.append(",");
- }
- return ResultBuilder.createInfoResult("Destroyed " + functionId + " Successfully on "
- + members.toString().substring(0, members.toString().length() - 1));
- } else {
- return ResultBuilder.createInfoResult("Failed in unregistering");
- }
- }
-
- /**
- * Interceptor used by gfsh to intercept execution of destroy.
- */
- public static class Interceptor extends AbstractCliAroundInterceptor {
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- Map<String, String> paramValueMap = parseResult.getParamValueStrings();
- paramValueMap.entrySet();
- String onGroup = paramValueMap.get(CliStrings.GROUP);
- String onMember = paramValueMap.get(CliStrings.MEMBER);
-
- if ((onGroup == null && onMember == null)) {
- Response response = readYesNo("Do you really want to destroy "
- + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID) + " on entire DS?", Response.NO);
- if (response == Response.NO) {
- return ResultBuilder.createShellClientAbortOperationResult(
- "Aborted destroy of " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
- } else {
- return ResultBuilder
- .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
- }
- } else {
- return ResultBuilder
- .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java
deleted file mode 100644
index c9f2b64..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyIndexCommand.java
+++ /dev/null
@@ -1,174 +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 java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.DestroyIndexFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DestroyIndexCommand implements GfshCommand {
- private static final DestroyIndexFunction destroyIndexFunction = new DestroyIndexFunction();
-
- @CliCommand(value = CliStrings.DESTROY_INDEX, help = CliStrings.DESTROY_INDEX__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result destroyIndex(
- @CliOption(key = CliStrings.DESTROY_INDEX__NAME, unspecifiedDefaultValue = "",
- help = CliStrings.DESTROY_INDEX__NAME__HELP) final String indexName,
-
- @CliOption(key = CliStrings.DESTROY_INDEX__REGION, optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.DESTROY_INDEX__REGION__HELP) final String regionPath,
-
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.DESTROY_INDEX__MEMBER__HELP) final String[] memberNameOrID,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.DESTROY_INDEX__GROUP__HELP) final String[] group) {
-
- Result result;
-
- if (StringUtils.isBlank(indexName) && StringUtils.isBlank(regionPath)
- && ArrayUtils.isEmpty(group) && ArrayUtils.isEmpty(memberNameOrID)) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.PROVIDE_ATLEAST_ONE_OPTION, CliStrings.DESTROY_INDEX));
- }
-
- final Cache cache = CacheFactory.getAnyInstance();
- String regionName = null;
- if (regionPath != null) {
- regionName = regionPath.startsWith("/") ? regionPath.substring(1) : regionPath;
- }
- IndexInfo indexInfo = new IndexInfo(indexName, regionName);
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector rc = CliUtil.executeFunction(destroyIndexFunction, indexInfo, targetMembers);
- List<Object> funcResults = (List<Object>) rc.getResult();
-
- Set<String> successfulMembers = new TreeSet<>();
- Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- for (Object funcResult : funcResults) {
- if (!(funcResult instanceof CliFunctionResult)) {
- continue;
- }
- CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
- if (cliFunctionResult.isSuccessful()) {
- successfulMembers.add(cliFunctionResult.getMemberIdOrName());
- if (xmlEntity.get() == null) {
- xmlEntity.set(cliFunctionResult.getXmlEntity());
- }
- } else {
- String exceptionMessage = cliFunctionResult.getMessage();
- Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
- if (failedMembers == null) {
- failedMembers = new TreeSet<>();
- }
- failedMembers.add(cliFunctionResult.getMemberIdOrName());
- indexOpFailMap.put(exceptionMessage, failedMembers);
- }
- }
- if (!successfulMembers.isEmpty()) {
- InfoResultData infoResult = ResultBuilder.createInfoResultData();
- if (StringUtils.isNotBlank(indexName)) {
- if (StringUtils.isNotBlank(regionPath)) {
- infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__ON__REGION__SUCCESS__MSG,
- indexName, regionPath));
- } else {
- infoResult.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__SUCCESS__MSG, indexName));
- }
- } else {
- if (StringUtils.isNotBlank(regionPath)) {
- infoResult.addLine(CliStrings
- .format(CliStrings.DESTROY_INDEX__ON__REGION__ONLY__SUCCESS__MSG, regionPath));
- } else {
- infoResult.addLine(CliStrings.DESTROY_INDEX__ON__MEMBERS__ONLY__SUCCESS__MSG);
- }
- }
- int num = 0;
- for (String memberId : successfulMembers) {
- infoResult.addLine(CliStrings.format(
- CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
- }
- result = ResultBuilder.buildResult(infoResult);
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- if (StringUtils.isNotBlank(indexName)) {
- erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__FAILURE__MSG, indexName));
- } else {
- erd.addLine("Indexes could not be destroyed for following reasons");
- }
-
- Set<String> exceptionMessages = indexOpFailMap.keySet();
-
- for (String exceptionMessage : exceptionMessages) {
- erd.addLine(CliStrings.format(CliStrings.DESTROY_INDEX__REASON_MESSAGE, exceptionMessage));
- erd.addLine(CliStrings.DESTROY_INDEX__EXCEPTION__OCCURRED__ON);
-
- Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
- int num = 0;
-
- for (String memberId : memberIds) {
- erd.addLine(CliStrings.format(
- CliStrings.format(CliStrings.DESTROY_INDEX__NUMBER__AND__MEMBER, ++num, memberId)));
- }
- erd.addLine("");
- }
- result = ResultBuilder.buildResult(erd);
- }
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), group));
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java
deleted file mode 100644
index 12b6dc1..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommand.java
+++ /dev/null
@@ -1,222 +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 java.text.MessageFormat;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.LogWriter;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.Scope;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.RegionAttributesData;
-import org.apache.geode.management.RegionMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DestroyRegionCommand implements GfshCommand {
- @CliCommand(value = {CliStrings.DESTROY_REGION}, help = CliStrings.DESTROY_REGION__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = ResourcePermission.Resource.DATA,
- operation = ResourcePermission.Operation.MANAGE)
- public Result destroyRegion(
- @CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH,
- mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) {
-
- if (regionPath == null) {
- return ResultBuilder
- .createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY);
- }
-
- if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
- return ResultBuilder.createInfoResult(CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] {regionPath}));
- }
-
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- try {
- InternalCache cache = getCache();
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- String regionPathToUse = regionPath;
-
- if (!regionPathToUse.startsWith(Region.SEPARATOR)) {
- regionPathToUse = Region.SEPARATOR + regionPathToUse;
- }
-
- Set<DistributedMember> regionMembersList =
- findMembersForRegion(cache, managementService, regionPathToUse);
-
- if (regionMembersList.size() == 0) {
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULD_NOT_FIND_REGIONPATH_0_IN_GEODE,
- regionPath, "jmx-manager-update-rate milliseconds"));
- }
-
- CliFunctionResult destroyRegionResult;
-
- ResultCollector<?, ?> resultCollector =
- CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList);
- List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult();
- String message =
- CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, regionPath, "");
-
- // Only if there is an error is this set to false
- boolean isRegionDestroyed = true;
- for (CliFunctionResult aResultsList : resultsList) {
- destroyRegionResult = aResultsList;
- if (destroyRegionResult.isSuccessful()) {
- xmlEntity.set(destroyRegionResult.getXmlEntity());
- } else if (destroyRegionResult.getThrowable() != null) {
- Throwable t = destroyRegionResult.getThrowable();
- LogWrapper.getInstance().info(t.getMessage(), t);
- message = CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1,
- regionPath, t.getMessage());
- isRegionDestroyed = false;
- } else {
- message = CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1,
- regionPath, destroyRegionResult.getMessage());
- isRegionDestroyed = false;
- }
- }
- if (isRegionDestroyed) {
- result = ResultBuilder.createInfoResult(message);
- } else {
- result = ResultBuilder.createUserErrorResult(message);
- }
- } catch (IllegalStateException e) {
- result = ResultBuilder.createUserErrorResult(CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
- e.getMessage()));
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
- e.getMessage()));
- }
-
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
- }
-
- return result;
- }
-
- private Set<DistributedMember> findMembersForRegion(InternalCache cache,
- ManagementService managementService, String regionPath) {
- Set<DistributedMember> membersList = new HashSet<>();
- Set<String> regionMemberIds = new HashSet<>();
- MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
-
- // needs to be escaped with quotes if it contains a hyphen
- if (regionPath.contains("-")) {
- regionPath = "\"" + regionPath + "\"";
- }
-
- String queryExp =
- MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
-
- try {
- ObjectName queryExpON = new ObjectName(queryExp);
- Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON);
- if (queryNames == null || queryNames.isEmpty()) {
- return membersList; // protects against null pointer exception below
- }
-
- boolean addedOneRemote = false;
- for (ObjectName regionMBeanObjectName : queryNames) {
- try {
- RegionMXBean regionMXBean =
- managementService.getMBeanInstance(regionMBeanObjectName, RegionMXBean.class);
- if (regionMXBean != null) {
- RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes();
- String scope = regionAttributes.getScope();
- // For Scope.LOCAL regions we need to identify each hosting member, but for
- // other scopes we just need a single member as the region destroy will be
- // propagated.
- if (Scope.LOCAL.equals(Scope.fromString(scope))) {
- regionMemberIds.add(regionMXBean.getMember());
- } else {
- if (!addedOneRemote) {
- regionMemberIds.add(regionMXBean.getMember());
- addedOneRemote = true;
- }
- }
- }
- } catch (ClassCastException e) {
- LogWriter logger = cache.getLogger();
- if (logger.finerEnabled()) {
- logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(),
- e);
- }
- }
- }
-
- if (!regionMemberIds.isEmpty()) {
- membersList = getMembersByIds(cache, regionMemberIds);
- }
- } catch (MalformedObjectNameException | NullPointerException e) {
- LogWrapper.getInstance().info(e.getMessage(), e);
- }
-
- return membersList;
- }
-
- private Set<DistributedMember> getMembersByIds(InternalCache cache, Set<String> memberIds) {
- Set<DistributedMember> foundMembers = Collections.emptySet();
- if (memberIds != null && !memberIds.isEmpty()) {
- foundMembers = new HashSet<>();
- Set<DistributedMember> allNormalMembers = CliUtil.getAllNormalMembers(cache);
-
- for (String memberId : memberIds) {
- for (DistributedMember distributedMember : allNormalMembers) {
- if (memberId.equals(distributedMember.getId())
- || memberId.equals(distributedMember.getName())) {
- foundMembers.add(distributedMember);
- }
- }
- }
- }
- return foundMembers;
- }
-}
[05/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
index 4ab1567..7562005 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/i18n/CliStrings.java
@@ -47,47 +47,29 @@ import org.apache.geode.internal.cache.xmlcache.CacheXml;
import org.apache.geode.management.internal.cli.shell.Gfsh;
/**
- * Contains 'String' constants used as key to the Localized strings to be used in classes under
- * <code>org.apache.geode.management.internal.cli</code> for Command Line Interface (CLI).
- *
- * <pre>
- * NOTES:
- *
- * 1. CONVENTIONS: Defining constants for Command Name, option, argument, help:
- *
- * 1.1 Command Name: Command name in BOLD. Multiple words separated by single underscore ('_') E.g.
- * COMPACT_DISK_STORE
- *
+ * - * Contains 'String' constants used as key to the Localized strings to be used in classes under
+ * <code>org.apache.geode.management.internal.cli</code> for Command Line Interface (CLI). NOTES: 1.
+ * CONVENTIONS: Defining constants for Command Name, option, argument, help: 1.1 Command Name:
+ * Command name in BOLD. Multiple words separated by single underscore ('_') E.g. COMPACT_DISK_STORE
* 1.2 Command Help Text: Command name in BOLD followed by double underscore ('__') followed by HELP
- * in BOLD. E.g.COMPACT_DISK_STORE__HELP
- *
- * 1.3 Command Option: Command name in BOLD followed by double underscore ('__') followed by option
- * name in BOLD - multiple words concatenated by removing space. E.g. for option "--disk-dirs" -
- * COMPACT_DISK_STORE__DISKDIRS
- *
- * 1.4 Command Option Help: As mentioned in 1.3, followed by double underscore ('__') followed by
- * HELP in BOLD. E.g. COMPACT_DISK_STORE__DISKDIRS__HELP
- *
- * 1.5 Info/Error Message used in a command: Command name in BOLD followed by double underscore
- * ('__') followed by MSG in BOLD followed by brief name for the message (similar to used in
- * LocalizedStrings). E.g. COMPACT_DISK_STORE__MSG__ERROR_WHILE_COMPACTING = "Error occurred while
- * compacting disk store."
- *
+ * in BOLD. E.g.COMPACT_DISK_STORE__HELP 1.3 Command Option: Command name in BOLD followed by double
+ * underscore ('__') followed by option name in BOLD - multiple words concatenated by removing
+ * space. E.g. for option "--disk-dirs" - COMPACT_DISK_STORE__DISKDIRS 1.4 Command Option Help: As
+ * mentioned in 1.3, followed by double underscore ('__') followed by HELP in BOLD. E.g.
+ * COMPACT_DISK_STORE__DISKDIRS__HELP 1.5 Info/Error Message used in a command: Command name in BOLD
+ * followed by double underscore ('__') followed by MSG in BOLD followed by brief name for the
+ * message (Similar to used in LocalizedStrings). E.g.
+ * COMPACT_DISK_STORE__MSG__ERROR_WHILE_COMPACTING = "Error occurred while compacting disk store."
* 1.6 Parameterized messages are supposed to be handled by users. It's recommended to use the same
* conventions as used in LocalizedStrings. E.g. COMPACT_DISK_STORE__MSG__ERROR_WHILE_COMPACTING__0
* = "Error occurred while compacting disk store {0}."
*
- * 2. Defining Topic constants:
- *
- * 2.1 The constants' names should begin with "TOPIC_" E.g.
- * TOPIC_GEODE_REGION
- *
- * 2.2 Topic brief description should be defined with suffix "__DESC". E.g.
+ * 2. Defining Topic constants: 2.1 The constants' names should begin with "TOPIC_" E.g.
+ * TOPIC_GEODE_REGION 2.2 Topic brief description should be defined with suffix "__DESC". E.g.
* TOPIC_GEODE_REGION__DESC
*
* 3. Order for adding constants: It should be alphabetically sorted at least on the first name
* within the current group
- * </pre>
*
* @since GemFire 7.0
*/
@@ -157,7 +139,7 @@ public class CliStrings {
public static final String TOPIC_GFSH = "GFSH";
public static final String TOPIC_GFSH__DESC = "The Geode Shell";
public static final String TOPIC_SHARED_CONFIGURATION = "Cluster Configuration";
- public static final String TOPIC_SHARED_CONFIGURATION_DESC =
+ public static final String TOPIC_SHARED_CONFIGURATION_HELP =
"Configuration for cluster and various groups. It consists of cache.xml, geode properties and deployed jars.\nChanges due to gfsh command are persisted to the locator hosting the cluster configuration service.";
public static final String TOPIC_LOGS = "Logs";
public static final String TOPIC_LOGS__DESC = "Generate log contents as per the need";
@@ -172,23 +154,31 @@ public class CliStrings {
"Running desktop applications is not supported on %1$s.";
public static final String GEODE_HOME_NOT_FOUND_ERROR_MESSAGE =
"The GEODE environment variable was not defined. Please set the GEODE environment variable to the directory where GEODE is installed.";
+ public static final String JAVA_HOME_NOT_FOUND_ERROR_MESSAGE =
+ "Unable to locate the Java executables and dependencies. Please set the JAVA_HOME environment variable.";
public static final String CACHE_XML_NOT_FOUND_MESSAGE =
"Warning: The Geode cache XML file {0} could not be found.";
public static final String GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE =
"Warning: The Geode {0}properties file {1} could not be found.";
public static final String MEMBER_NOT_FOUND_ERROR_MESSAGE =
"Member {0} could not be found. Please verify the member name or ID and try again.";
+ public static final String NO_MEMBERS_IN_GROUP_ERROR_MESSAGE =
+ "No caching members for group {0} could be found. Please verify the group and try again.";
public static final String NO_MEMBERS_FOUND_MESSAGE = "No Members Found";
public static final String NO_CACHING_MEMBERS_FOUND_MESSAGE = "No caching members found.";
public static final String COMMAND_FAILURE_MESSAGE = "Error occurred while executing : {0}";
public static final String EXCEPTION_CLASS_AND_MESSAGE = "Exception : {0} , Message : {1}";
+ public static final String GROUP_EMPTY_ERROR_MESSAGE = "No members found in group : {0}";
public static final String REGION_NOT_FOUND = "Region : {0} not found";
public static final String INVALID_REGION_NAME = "Invalid region name";
public static final String INVALID_FILE_EXTENSION =
"Invalid file type, the file extension must be \"{0}\"";
public static final String GEODE_DATA_FILE_EXTENSION = ".gfd";
+ public static final String LOCATOR_HEADER = "Locator";
public static final String LOCATOR_TERM_NAME = "Locator";
+ public static final String ERROR__MSG__HEADER = "Error";
public static final String ZIP_FILE_EXTENSION = ".zip";
+ // This should be thrown for FunctionInvocationTargetException
public static final String COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN =
"Could not execute \" {0} \", please try again ";
public static final String UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE =
@@ -203,8 +193,13 @@ public class CliStrings {
"Please provide either \"member\" or \"group\" option.";
public static final String GFSH_MUST_BE_CONNECTED_FOR_LAUNCHING_0 =
"Gfsh must be connected for launching {0}";
+ public static final String GFSH_MUST_BE_CONNECTED_VIA_JMX_FOR_LAUNCHING_0 =
+ "Gfsh must be connected via JMX for launching {0}";
+ public static final String ATTACH_API_IN_0_NOT_FOUND_ERROR_MESSAGE =
+ "The JDK {0} is required by 'start', 'status' and 'stop' commands for Locators and Servers. Please set JAVA_HOME to the JDK Directory or add the JDK {0} to the classpath, restart Gfsh and try again.";
public static final String ASYNC_PROCESS_LAUNCH_MESSAGE =
"Broken out of wait... the %1$s process will continue to startup in the background.%n";
+ public static final String NO_NON_LOCATOR_MEMBERS_FOUND = "No non-locator members found.";
public static final String NO_CLIENT_FOUND = "No client found on this server";
public static final String NO_CLIENT_FOUND_WITH_CLIENT_ID =
"No client found with client-id : {0}";
@@ -212,11 +207,36 @@ public class CliStrings {
public static final String OCCURRED_ON_MEMBERS = "Occurred on members";
public static final String SHARED_CONFIGURATION_NOT_STARTED =
"Cluster configuration service is enabled but has not started yet.";
+ public static final String SHARED_CONFIGURATION_NO_LOCATORS_WITH_SHARED_CONFIGURATION =
+ "No locators with cluster configuration enabled.";
public static final String SHARED_CONFIGURATION_FAILED_TO_PERSIST_COMMAND_CHANGES =
"Failed to persist the configuration changes due to this command, Revert the command to maintain consistency.\nPlease use \"status cluster-config-service\" to determine whether Cluster configuration service is RUNNING.";
-
/* Other Constants */
public static final String GFSH__MSG__NO_LONGER_CONNECTED_TO_0 = "No longer connected to {0}.";
+ public static final String GFSHPARSER__MSG__REQUIRED_ARGUMENT_0 = "Required Argument: \"{0}\"";
+ public static final String GFSHPARSER__MSG__VALUE_REQUIRED_FOR_OPTION_0 =
+ "Value is required for parameter \"{0}\"";
+ public static final String GFSHPARSER__MSG__AMBIGUOUS_COMMAND_0_FOR_ASSISTANCE_USE_1_OR_HINT_HELP =
+ "Ambiguous command \"{0}\" (for assistance press \"{1}\" or type \"hint\" or \"help <command name>\" & then hit ENTER)";
+ public static final String GFSHPARSER__MSG__COMMAND_ARGUMENT_0_IS_REQUIRED_USE_HELP =
+ "Command parameter \"{0}\" is required. Use \"help <command name>\" for assistance.";
+ public static final String GFSHPARSER__MSG__COMMAND_OPTION_0_IS_REQUIRED_USE_HELP =
+ "Parameter \"{0}\" is required. Use \"help <command name>\" for assistance.";
+ public static final String GFSHPARSER__MSG__VALUE_0_IS_NOT_APPLICABLE_FOR_1 =
+ "Value \"{0}\" is not applicable for \"{1}\".";
+ public static final String GFSHPARSER__MSG__INVALID_COMMAND_STRING_0 =
+ "Invalid command String: {0}";
+ public static final String GFSHPARSER__MSG__COMMAND_0_IS_NOT_VALID =
+ "Command \"{0}\" is not valid.";
+ public static final String GFSHPARSER__MSG__NO_MATCHING_COMMAND = "No matching command";
+ public static final String GFSHPARSER__MSG__USE_0_HELP_COMMAND_TODISPLAY_DETAILS =
+ "Use {0}help <command name> to display detailed usage information for a specific command.";
+ public static final String GFSHPARSER__MSG__HELP_CAN_ALSO_BE_OBTAINED_BY_0_KEY =
+ "Help with command and parameter completion can also be obtained by entering all or a portion of either followed by the \"{0}\" key.";
+ public static final String GFSHPARSER__MSG__0_IS_NOT_AVAILABLE_REASON_1 =
+ "\"{0}\" is not available. Reason: {1}";
+ public static final String GFSHPARSER__MSG__OTHER_COMMANDS_STARTING_WITH_0_ARE =
+ "Other commands starting with \"{0}\" are: ";
public static final String ABSTRACTRESULTDATA__MSG__FILE_WITH_NAME_0_EXISTS_IN_1 =
"File with name \"{0}\" already exists in \"{1}\".";
@@ -227,9 +247,14 @@ public class CliStrings {
public static final String ABSTRACTRESULTDATA__MSG__PARENT_OF_0_IS_NOT_DIRECTORY =
"Parent of \"{0}\" is not a directory.";
+ public static final String AVAILABILITYTARGET_MSG_DEFAULT_UNAVAILABILITY_DESCRIPTION =
+ "Requires connection.";
+
public static final String LAUNCHERLIFECYCLECOMMANDS__MSG__FAILED_TO_START_0_REASON_1 =
"Failed to start {0}. Reason: {1}";
+ public static final String GFSH__PLEASE_CHECK_LOGS_AT_0 = "Please check logs {0}";
+
/*-**************************************************************************
* *********** COMMAND NAME, OPTION, ARGUMENT, HELP, MESSAGES ****************
* **************************************************************************/
@@ -325,7 +350,10 @@ public class CliStrings {
"Fully qualified class name of a plug-in to be instantiated for receiving before-event notification of changes to the region and its entries. The plug-in may cancel the event. At most, one cache writer can be defined in each member for the region.";
public static final String ALTER_REGION__ASYNCEVENTQUEUEID = "async-event-queue-id";
public static final String ALTER_REGION__ASYNCEVENTQUEUEID__HELP =
- "IDs of the Async Event Queues that will be used for write-behind operations.";
+ "IDs of the Async Event Queues that will be used for write-behind operations."; // TODO -
+ // Abhishek Is
+ // this
+ // correct?
public static final String ALTER_REGION__GATEWAYSENDERID = "gateway-sender-id";
public static final String ALTER_REGION__GATEWAYSENDERID__HELP =
"IDs of the Gateway Senders to which data will be routed.";
@@ -365,6 +393,7 @@ public class CliStrings {
"Alter a subset of member or members configuration properties while running.";
public static final String ALTER_RUNTIME_CONFIG__MEMBER__HELP =
"Name/Id of the member in whose configuration will be altered.";
+
public static final String ALTER_RUNTIME_CONFIG__GROUP__HELP =
"Group of members whose configuration will be altered.";
public static final String ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT =
@@ -426,6 +455,7 @@ public class CliStrings {
public static final String ALTER_RUNTIME_CONFIG__SUCCESS__MESSAGE =
"Runtime configuration altered successfully for the following member(s)";
+ public static final String ALTER_RUNTIME_CONFIG__MEMBER__NOT__FOUND = "Member : {0} not found";
public static final String ALTER_RUNTIME_CONFIG__RELEVANT__OPTION__MESSAGE =
"Please provide a relevant parameter(s)";
@@ -485,11 +515,14 @@ public class CliStrings {
public static final String COMPACT_OFFLINE_DISK_STORE__J = "J";
public static final String COMPACT_OFFLINE_DISK_STORE__J__HELP =
"Arguments passed to the Java Virtual Machine performing the compact operation on the disk store.";
+ public static final String COMPACT_OFFLINE_DISK_STORE__MSG__DISKSTORE_0_DOES_NOT_EXIST =
+ "Disk store \"{0}\" does not exist.";
+ public static final String COMPACT_OFFLINE_DISK_STORE__MSG__COMPACTION_ATTEMPTED_BUT_NOTHING_TO_COMPACT =
+ "Attempted to compact disk store, but there was nothing to do.";
public static final String COMPACT_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_REASON_0 =
"An error occurred while doing compaction: \"{0}\"";
public static final String COMPACT_OFFLINE_DISK_STORE__MSG__VERIFY_WHETHER_DISKSTORE_EXISTS_IN_0 =
- "Disk store in \"{0}\" does not seem to exist. "
- + "Verify whether the disk store exists in \"{0}\".";
+ "Verify whether the disk store exists in \"{0}\".";
public static final String COMPACT_OFFLINE_DISK_STORE__MSG__DISKSTORE_IN_USE_COMPACT_DISKSTORE_CAN_BE_USED =
"This disk store is in use by other process. \"" + CliStrings.COMPACT_DISK_STORE
+ "\" can be used to compact disk store that is current in use.";
@@ -554,14 +587,27 @@ public class CliStrings {
"Whether to use SSL for communication with Locator and/or JMX Manager. If set to \"true\", \"gfsecurity.properties\" will also be read. SSL Options take precedence over the properties file. If none are specified, defaults will be used. The default value for this options is \"false\".";
public static final String CONNECT__MSG__CONNECTING_TO_MANAGER_AT_0 =
"Connecting to Manager at {0} ..";
+ public static final String CONNECT__MSG__CONNECTING_TO_MANAGER_HTTP_SERVICE_AT_0 =
+ "Connecting to Manager's HTTP service at {0} ..";
public static final String CONNECT__MSG__LOCATOR_COULD_NOT_FIND_MANAGER =
"Locator could not find a JMX Manager";
public static final String CONNECT__MSG__JMX_PASSWORD_MUST_BE_SPECIFIED =
"password must be specified.";
+ public static final String CONNECT__MSG__ALREADY_CONNECTED = "Already connected to: {0}";
public static final String CONNECT__MSG__SUCCESS = "Successfully connected to: {0}";
public static final String CONNECT__MSG__ERROR = "Could not connect to : {0}. {1}";
+ public static final String CONNECT__MSG__SERVICE_UNAVAILABLE_ERROR =
+ "Could not find a Geode jmx-manager service at {0}.";
+ public static final String CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0 =
+ "Could not connect to Geode Locator service at {0}.";
public static final String CONNECT__MSG__COULD_NOT_READ_CONFIG_FROM_0 =
"Could not read config from {0}.";
+ public static final String CONNECT__MSG__COULD_NOT_CONNECT_TO_LOCATOR_0_POSSIBLY_SSL_CONFIG_ERROR =
+ "Could not connect to Locator at {0}." + Gfsh.LINE_SEPARATOR
+ + "Possible reason: Wrong or no SSL configuration provided.";
+ public static final String CONNECT__MSG__COULD_NOT_CONNECT_TO_MANAGER_0_POSSIBLY_SSL_CONFIG_ERROR =
+ "Could not connect to Manager at {0}." + Gfsh.LINE_SEPARATOR
+ + "Possible reason: Wrong or no SSL configuration provided.";
/* 'create async-event-queue' command */
public static final String CREATE_ASYNC_EVENT_QUEUE = "create async-event-queue";
@@ -697,10 +743,12 @@ public class CliStrings {
"Index successfully created with following details";
public static final String CREATE_INDEX__FAILURE__MSG =
"Failed to create index \"{0}\" due to following reasons";
+ public static final String CREATE_INDEX__ERROR__MSG =
+ "Exception \"{0}\" occurred on following members";
public static final String CREATE_INDEX__NAME__CONFLICT =
- "Index \"{0}\" already exists. Create failed due to duplicate name.";
+ "Index \"{0}\" already exists. " + "Create failed due to duplicate name.";
public static final String CREATE_INDEX__INDEX__EXISTS =
- "Index \"{0}\" already exists. Create failed due to duplicate definition.";
+ "Index \"{0}\" already exists. " + "Create failed due to duplicate definition.";
public static final String CREATE_INDEX__INVALID__EXPRESSION =
"Invalid indexed expression : \"{0}\"";
public static final String CREATE_INDEX__INVALID__REGIONPATH = "Region not found : \"{0}\"";
@@ -745,8 +793,12 @@ public class CliStrings {
"Failed to create some or all indexes \"{0}\" due to following reasons";
public static final String CREATE_DEFINED_INDEXES__MEMBER__HELP = CREATE_INDEX__MEMBER__HELP;
public static final String CREATE_DEFINED_INDEXES__GROUP__HELP = CREATE_INDEX__GROUP__HELP;
+ public static final String CREATE_DEFINED_INDEXES__MEMBER__MSG = CREATE_INDEX__MEMBER__MSG;
public static final String CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER =
CREATE_INDEX__NUMBER__AND__MEMBER;
+ public static final String CREATE_DEFINED_INDEXES__EXCEPTION__OCCURRED__ON =
+ CREATE_INDEX__EXCEPTION__OCCURRED__ON;
+
public static final String CLEAR_DEFINED_INDEXES = "clear defined indexes";
public static final String CLEAR_DEFINED__HELP = "Clears all the defined indexes.";
@@ -833,7 +885,10 @@ public class CliStrings {
"Fully qualified class name of a plug-in to be instantiated for receiving before-event notification of changes to the region and its entries. The plug-in may cancel the event. At most, one cache writer can be defined in each member for the region.";
public static final String CREATE_REGION__ASYNCEVENTQUEUEID = "async-event-queue-id";
public static final String CREATE_REGION__ASYNCEVENTQUEUEID__HELP =
- "IDs of the Async Event Queues that will be used for write-behind operations.";
+ "IDs of the Async Event Queues that will be used for write-behind operations."; // TODO -
+ // Abhishek Is
+ // this
+ // correct?
public static final String CREATE_REGION__GATEWAYSENDERID = "gateway-sender-id";
public static final String CREATE_REGION__GATEWAYSENDERID__HELP =
"IDs of the Gateway Senders to which data will be routed.";
@@ -877,6 +932,8 @@ public class CliStrings {
"Parent region for \"{0}\" doesn't exist. ";
public static final String CREATE_REGION__MSG__GROUPS_0_ARE_INVALID =
"Group(s) \"{0}\" are invalid.";
+ public static final String CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_USE_ATTR_FROM =
+ "Specify a valid region path for " + CliStrings.CREATE_REGION__USEATTRIBUTESFROM;
public static final String CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID =
"Specify a valid class name for " + CliStrings.CREATE_REGION__KEYCONSTRAINT
+ ". \"{0}\" is not valid.";
@@ -928,6 +985,14 @@ public class CliStrings {
"Could not access class \"{0}\" specified for \"{1}\".";
public static final String CREATE_REGION__MSG__EXPIRATION_ACTION_0_IS_NOT_VALID =
"Expiration action \"{0}\" is not valid.";
+ public static final String CREATE_REGION__MSG__ERROR_ON_MEMBER_0 = "Error on member: {0}. "; // leave
+ // space
+ // in
+ // the
+ // end
+ // for
+ // further
+ // message
public static final String CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1 =
"Could not retrieve region attributes for given path \"{0}\". Reason: {1}";
public static final String CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS =
@@ -968,6 +1033,8 @@ public class CliStrings {
public static final String CREATE_REGION__PARTITION_RESOLVER = "partition-resolver";
public static final String CREATE_REGION__PARTITION_RESOLVER__HELP =
"The fully-qualified class name of the region's partition resolver";
+ public static final String CREATE_REGION__MSG__PARTITION_RESOLVER_ONLY_FOR_REGION_TYPE_PARTITION =
+ "partition resolver property is only applicable to PARTITION region type";
public static final String CREATE_REGION_PARTITION_RESOLVER__MSG__COULD_NOT_FIND_CLASS_0_SPECIFIED_FOR_1 =
"Could not find class \"{0}\" specified for \"{1}\".";
@@ -1086,6 +1153,8 @@ public class CliStrings {
public static final String DESCRIBE_REGION__NAME = "name";
public static final String DESCRIBE_REGION__NAME__HELP =
"Name/Path of the region to be described.";
+ public static final String DESCRIBE_REGION__MSG__NOT_FOUND = "Region not found";
+ public static final String DESCRIBE_REGION__MSG__ERROR = "Error";
public static final String DESCRIBE_REGION__ATTRIBUTE__TYPE = "Type";
public static final String DESCRIBE_REGION__MEMBER = "Member";
public static final String DESCRIBE_REGION__ATTRIBUTE__NAME = "Name";
@@ -1150,6 +1219,7 @@ public class CliStrings {
"Index \"{0}\" could not be destroyed for following reasons";
public static final String DESTROY_INDEX__INDEX__NOT__FOUND = "Index named \"{0}\" not found";
public static final String DESTROY_INDEX__REGION__NOT__FOUND = "Region \"{0}\" not found";
+ public static final String DESTROY_INDEX__INVALID__NAME = "Invalid index name";
public static final String DESTROY_INDEX__REASON_MESSAGE = "{0}.";
public static final String DESTROY_INDEX__EXCEPTION__OCCURRED__ON =
"Occurred on following members";
@@ -1166,12 +1236,15 @@ public class CliStrings {
"Region path \"{0}\" is not valid.";
public static final String DESTROY_REGION__MSG__COULD_NOT_FIND_REGIONPATH_0_IN_GEODE =
"Could not find a Region with Region path \"{0}\" in this Geode cluster. If region was recently created, please wait for at least {1} to allow the associated Management resources to be federated.";
+ public static final String DESTROY_REGION__MSG__AND_ITS_SUBREGIONS = "and its subregions";
public static final String DESTROY_REGION__MSG__REGION_0_1_DESTROYED =
"\"{0}\" {1} destroyed successfully.";
public static final String DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1 =
"Error occurred while destroying region \"{0}\". Reason: {1}";
public static final String DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1 =
"Unknown result while destroying region \"{0}\". Reason: {1}";
+ public static final String DESTROY_REGION__MSG__COULD_NOT_FIND_MEMBER_WITH_REGION_0 =
+ "Could not find a Geode member which hosts a region with Region path \"{0}\"";
public static final String DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY =
"Please specify region path for the region to be destroyed.";
public static final String DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1 =
@@ -1216,10 +1289,17 @@ public class CliStrings {
public static final String EXECUTE_FUNCTION__FILTER__HELP =
"Key list which causes the function to only be executed on members which have entries with these keys.";
public static final String EXECUTE_FUNCTION__MSG__MISSING_FUNCTIONID = "Provide FunctionId";
+ public static final String EXECUTE_FUNCTION__MSG__MISSING_OPTIONS =
+ "Provide one of region/member/groups";
public static final String EXECUTE_FUNCTION__MSG__OPTIONS =
"Provide Only one of region/member/groups";
+ public static final String EXECUTE_FUNCTION__MSG__NO_FUNCTION_FOR_FUNCTIONID =
+ "For the functionId provided could not retrieve function. Function may not be registered";
+ public static final String EXECUTE_FUNCTION__MSG__NO_FUNCTION_EXECUTION =
+ "FunctionService could not create execution. Can not execute Function";
public static final String EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER =
"Could not find a member matching";
+ public static final String EXECUTE_FUNCTION__MSG__HAS_NO_MEMBER = "No member to execute on";
public static final String EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2 =
"Could not execute function :{0} on member : {1}. Details are : {2}";
public static final String EXECUTE_FUNCTION__MSG__DOES_NOT_HAVE_FUNCTION_0_REGISTERED =
@@ -1267,6 +1347,8 @@ public class CliStrings {
"Directory to which the exported configuration files will be written.";
public static final String EXPORT_CONFIG__MSG__EXCEPTION =
"Exception while exporting config: {0}";
+ public static final String EXPORT_CONFIG__MSG__MEMBER_EXCEPTION =
+ "Exception while exporting config for {0}: {0}";
public static final String EXPORT_CONFIG__MSG__NOT_A_DIRECTORY = "{0} is not a directory";
public static final String EXPORT_CONFIG__MSG__NOT_WRITEABLE = "{0} is not writeable";
public static final String EXPORT_CONFIG__MSG__CANNOT_CREATE_DIR =
@@ -1283,6 +1365,7 @@ public class CliStrings {
public static final String EXPORT_DATA__MEMBER__HELP =
"Name/Id of a member which hosts the region. The data will be exported to the specified file on the host where the member is running.";
public static final String EXPORT_DATA__MEMBER__NOT__FOUND = "Member {0} not found";
+ public static final String EXPORT_DATA__REGION__NOT__FOUND = "Region {0} not found";
public static final String EXPORT_DATA__SUCCESS__MESSAGE =
"Data successfully exported from region : {0} to file : {1} on host : {2}";
@@ -1296,6 +1379,7 @@ public class CliStrings {
"Name/Id of the member whose log files will be exported.";
public static final String EXPORT_LOGS__GROUP__HELP =
"Group of members whose log files will be exported.";
+ public static final String EXPORT_LOGS__MSG__CANNOT_EXECUTE = "Cannot execute";
public static final String EXPORT_LOGS__LOGLEVEL = LOG_LEVEL;
public static final String EXPORT_LOGS__LOGLEVEL__HELP =
"Minimum level of log entries to export. " + LOG_LEVEL_VALUES + " The default is ALL.";
@@ -1311,7 +1395,22 @@ public class CliStrings {
public static final String EXPORT_LOGS__MERGELOG = "merge-log";
public static final String EXPORT_LOGS__MERGELOG__HELP =
"Whether to merge logs after exporting to the target directory. Deprecated: Since Geode1.2, no longer used.";
+ public static final String EXPORT_LOGS__MSG__CANNOT_MERGE =
+ "Could not merge the files in target directory";
+ public static final String EXPORT_LOGS__MSG__SPECIFY_ONE_OF_OPTION =
+ "Specify one of group or member ID";
+ public static final String EXPORT_LOGS__MSG__FUNCTION_EXCEPTION = "Error in executing function";
public static final String EXPORT_LOGS__MSG__FILE_DOES_NOT_EXIST = "Does not exist";
+ public static final String EXPORT_LOGS__MSG__TARGET_DIR_CANNOT_BE_CREATED =
+ "Target Directory {0} cannot be created";
+ public static final String EXPORT_LOGS__MSG__SPECIFY_ENDTIME = "Specify End Time.";
+ public static final String EXPORT_LOGS__MSG__SPECIFY_STARTTIME = "Specify Start Time.";
+ public static final String EXPORT_LOGS__MSG__INVALID_TIMERANGE = "Invalid Time Range.";
+ public static final String EXPORT_LOGS__MSG__INVALID_MEMBERID = "Member : {0} is not valid.";
+ public static final String EXPORT_LOGS__MSG__NO_GROUPMEMBER_FOUND =
+ "Groups specified have no members";
+ public static final String EXPORT_LOGS__MSG__FAILED_TO_EXPORT_LOG_FILES_FOR_MEMBER_0 =
+ "Could not export log files for member {0}";
public static final String EXPORT_LOGS__LOGSONLY = "logs-only";
public static final String EXPORT_LOGS__STATSONLY = "stats-only";
public static final String EXPORT_LOGS__LOGSONLY__HELP = "Whether to only export logs";
@@ -1322,6 +1421,7 @@ public class CliStrings {
public static final String EXPORT_LOGS__FILESIZELIMIT__SPECIFIED_DEFAULT = "0";
public static final String EXPORT_LOGS__FILESIZELIMIT__UNSPECIFIED_DEFAULT = "100m";
+
/* export stack-trace command */
public static final String EXPORT_STACKTRACE = "export stack-traces";
public static final String EXPORT_STACKTRACE__HELP =
@@ -1330,13 +1430,17 @@ public class CliStrings {
"Name/Id of the member whose stack trace will be exported.";
public static final String EXPORT_STACKTRACE__GROUP__HELP =
"Group of members whose stack trace will be exported.";
+ public static final String EXPORT_STACKTRACE_ALL_STACKS = "all-stacks";
+ public static final String EXPORT_STACKTRACE_ALL_STACKS__HELP =
+ "When set to true exports all the stacktraces.";
public static final String EXPORT_STACKTRACE__FILE = "file";
public static final String EXPORT_STACKTRACE__FILE__HELP =
"Name of the file to which the stack traces will be written.";
public static final String EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT = "abort-if-file-exists";
public static final String EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP =
"Abort the command if already exists at locator directory";
- public static final String EXPORT_STACKTRACE__SUCCESS = "Stack-trace(s) exported to file: {0}";
+ public static final String EXPORT_STACKTRACE__MEMBER__NOT__FOUND = "Member not found";
+ public static final String EXPORT_STACKTRACE__SUCCESS = "stack-trace(s) exported to file: {0}";
public static final String EXPORT_STACKTRACE__ERROR = "Error occurred while showing stack-traces";
public static final String EXPORT_STACKTRACE__ERROR__FILE__PRESENT =
"Error occurred while exporting stack-traces, file {0} already present";
@@ -1354,11 +1458,13 @@ public class CliStrings {
public static final String GC__GROUP__HELP =
"Group(s) of members on which garbage collection will be done.";
public static final String GC__MSG__MEMBER_NOT_FOUND = "Member not found";
+ public static final String GC__MSG__CANNOT_EXECUTE = "Cannot execute";
public static final String GC__MSG__MEMBER_NAME = "Member ID/Name";
public static final String GC__MSG__HEAP_SIZE_BEFORE_GC = "HeapSize (MB) Before GC";
public static final String GC__MSG__HEAP_SIZE_AFTER_GC = "HeapSize(MB) After GC";
public static final String GC__MSG__TOTAL_TIME_IN_GC = "Time Taken for GC in ms";
+
/* get command */
public static final String GET = "get";
public static final String GET__HELP =
@@ -1379,6 +1485,7 @@ public class CliStrings {
public static final String GET__REGIONNAME__HELP = "Region from which to get the entry.";
public static final String GET__MSG__REGIONNAME_EMPTY = "Region name is either empty or Null";
public static final String GET__MSG__KEY_EMPTY = "Key is either empty or Null";
+ public static final String GET__MSG__VALUE_EMPTY = "Value is either empty or Null";
public static final String GET__MSG__REGION_NOT_FOUND_ON_ALL_MEMBERS =
"Region <{0}> not found in any of the members";
public static final String GET__MSG__REGION_NOT_FOUND = "Region <{0}> Not Found";
@@ -1388,6 +1495,10 @@ public class CliStrings {
public static final String HELP = "help";
public static final String HELP__HELP =
"Display syntax and usage information for all commands or list all available commands if <command> isn't specified.";
+ public static final String HELP__COMMAND = "command";
+ public static final String HELP__COMMAND__HELP =
+ "Name of the command for which help will be displayed.";
+ public static final String PARAM_CONTEXT_HELP = "help:disable-string-converter";
/* hint command */
public static final String HINT = "hint";
@@ -1396,6 +1507,8 @@ public class CliStrings {
public static final String HINT__TOPICNAME = "topic";
public static final String HINT__TOPICNAME__HELP =
"Name of the topic for which hints will be displayed.";
+ public static final String HINT__MSG__SHELL_NOT_INITIALIZED =
+ "Shell is not initialized properly. Please restart the shell. Check gfsh-<timestamp>.log for errors.";
public static final String HINT__MSG__UNKNOWN_TOPIC =
"Unknown topic: {0}. Use " + HINT + "; to view the list of available topics.";
public static final String HINT__MSG__TOPICS_AVAILABLE =
@@ -1407,6 +1520,7 @@ public class CliStrings {
public static final String HISTORY__HELP = "Display or export previously executed GFSH commands.";
public static final String HISTORY__FILE = "file";
public static final String HISTORY__FILE__HELP = "File to which the history will be written.";
+ public static final String HISTORY__MSG__FILE_NULL = "File should not be null";
public static final String HISTORY__MSG__FILE_DOES_NOT_EXISTS = "File does not exist";
public static final String HISTORY__MSG__FILE_SHOULD_NOT_BE_DIRECTORY =
"File Should not be a directory";
@@ -1415,6 +1529,8 @@ public class CliStrings {
public static final String HISTORY__CLEAR = "clear";
public static final String HISTORY__CLEAR__HELP =
"Clears the history of GFSH commands. Takes value as true or false";
+ public static final String HISTORY__MSG__DID_NOT_CLEAR_HISTORY =
+ "Did not clear history of GFSH commands";
public static final String HISTORY__MSG__CLEARED_HISTORY = "Successfully deleted history";
@@ -1429,6 +1545,7 @@ public class CliStrings {
public static final String IMPORT_DATA__MEMBER__HELP =
"Name/Id of a member which hosts the region. The data will be imported from the specified file on the host where the member is running.";
public static final String IMPORT_DATA__MEMBER__NOT__FOUND = "Member {0} not found.";
+ public static final String IMPORT_DATA__REGION__NOT__FOUND = "Region {0} not found.";
public static final String IMPORT_DATA__SUCCESS__MESSAGE =
"Data imported from file : {0} on host : {1} to region : {2}";
public static final String IMPORT_DATA__INVOKE_CALLBACKS = "invoke-callbacks";
@@ -1590,8 +1707,10 @@ public class CliStrings {
public static final String LOCATE_ENTRY__MSG__REGIONNAME_EMPTY =
"Region name is either empty or Null";
public static final String LOCATE_ENTRY__MSG__KEY_EMPTY = "Key is either empty or Null";
+ public static final String LOCATE_ENTRY__MSG__VALUE_EMPTY = "Value is either empty or Null";
public static final String LOCATE_ENTRY__MSG__REGION_NOT_FOUND_ON_ALL_MEMBERS =
"Region <{0}> not found in any of the members";
+ public static final String LOCATE_ENTRY__MSG__REGION_NOT_FOUND = "Region <{0}> Not Found";
public static final String LOCATE_ENTRY__MSG__KEY_NOT_FOUND_REGION =
"Key is not present in the region";
@@ -1662,8 +1781,7 @@ public class CliStrings {
public static final String PUT__MSG__REGION_NOT_FOUND_ON_ALL_MEMBERS =
"Region <{0}> not found in any of the members";
public static final String PUT__MSG__REGION_NOT_FOUND = "Region <{0}> Not Found";
- public static final String PUT__MSG__KEY_NOT_FOUND_REGION =
- "Key {0} is not present in the region";
+ public static final String PUT__MSG__KEY_NOT_FOUND_REGION = "Key is not present in the region";
public static final String QUERY = "query";
public static final String QUERY__HELP =
@@ -1680,6 +1798,8 @@ public class CliStrings {
public static final String QUERY__MSG__INVALID_QUERY = "Query is invalid due for error : <{0}>";
public static final String QUERY__MSG__REGIONS_NOT_FOUND =
"Cannot find regions <{0}> in any of the members";
+ public static final String QUERY__MSG__NOT_SUPPORTED_ON_MEMBERS = CliStrings.QUERY
+ + " command should be used only from shell. Use QueryService API for running query inside Geode VMs";
/* 'rebalance' command */
public static final String REBALANCE = "rebalance";
@@ -1697,6 +1817,13 @@ public class CliStrings {
public static final String REBALANCE__SIMULATE = "simulate";
public static final String REBALANCE__SIMULATE__HELP =
"Whether to only simulate rebalancing. The --time-out parameter is not available when simulating.";
+ public static final String REBALANCE__MSG__SIMULATED = "Simulated Successfully";
+ public static final String REBALANCE__MSG__TIMEOUT =
+ "Time out. Rebalance operation will continue on servers";
+ public static final String REBALANCE__MSG__REBALANCED = "Rebalanced Successfully";
+ public static final String REBALANCE__MSG__CANCELLED = "Rebalance Cancelled";
+ public static final String REBALANCE__MSG__WAIT_INTERRUPTED =
+ "Rebalance wait interrupted Cancelled";
public static final String REBALANCE__MSG__NO_ASSOCIATED_DISTRIBUTED_MEMBER =
"For the region {0}, no member was found";
public static final String REBALANCE__MSG__NO_EXECUTION = "Could not execute for member:{0}";
@@ -1724,13 +1851,19 @@ public class CliStrings {
"Exception occurred while rebalancing on member : {0} . Exception is ";
public static final String REBALANCE__MSG__EXCEPTION_IN_REBALANCE_FOR_MEMBER_0_Exception_1 =
"Exception occurred while rebalancing on member : {0} . Exception is : {1}";
+ public static final String REBALANCE__MSG__ERROR_IN_RETRIEVING_MBEAN =
+ "Could not retrieve MBean for region : {0}";
public static final String REBALANCE__MSG__NO_EXECUTION_FOR_REGION_0_ON_MEMBERS_1 =
"Could not execute rebalance for region: {0} on members : {1} ";
+ public static final String REBALANCE__MSG__NO_EXECUTION_FOR_REGION_0 =
+ "Could not execute rebalance for region: {0}";
public static final String REBALANCE__MSG__MEMBERS_MIGHT_BE_DEPARTED =
" Reason : Members may be departed";
public static final String REBALANCE__MSG__REASON = " Reason : ";
public static final String REBALANCE__MSG__REBALANCE_WILL_CONTINUE =
"Rebalance will continue in background";
+ public static final String REBALANCE__MSG__REGION_NOT_ASSOCIATED_WITH_MORE_THAN_ONE_MEMBER =
+ "No regions associated with more than 1 members";
public static final String REBALANCE__MSG__EXCEPTION_OCCURRED_WHILE_REBALANCING_0 =
"Exception occurred while rebalancing. Reason : {0}";
@@ -1751,6 +1884,7 @@ public class CliStrings {
"Clears the region by removing all entries. Partitioned region does not support remove-all";
public static final String REMOVE__MSG__REGIONNAME_EMPTY = "Region name is either empty or Null";
public static final String REMOVE__MSG__KEY_EMPTY = "Key is Null";
+ public static final String REMOVE__MSG__VALUE_EMPTY = "Value is either empty or Null";
public static final String REMOVE__MSG__REGION_NOT_FOUND_ON_ALL_MEMBERS =
"Region <{0}> not found in any of the members";
public static final String REMOVE__MSG__REGION_NOT_FOUND = "Region <{0}> Not Found";
@@ -1759,7 +1893,6 @@ public class CliStrings {
public static final String REMOVE__MSG__CLEARALL_NOT_SUPPORTED_FOR_PARTITIONREGION =
"Option --" + REMOVE__ALL + " is not supported on partitioned region";
-
/* resume gateway-sender */
public static final String RESUME_GATEWAYSENDER = "resume gateway-sender";
public static final String RESUME_GATEWAYSENDER__ID = "id";
@@ -1791,6 +1924,8 @@ public class CliStrings {
public static final String RUN__CONTINUEONERROR__HELP =
"Whether command execution should continue if an error is received.";
+ public static final String RUN__MSG_FILE_NOT_FOUND = "Could not find specified script file: ";
+
/* 'set variable' command */
public static final String SET_VARIABLE = "set variable";
public static final String SET_VARIABLE__HELP =
@@ -1805,6 +1940,22 @@ public class CliStrings {
public static final String SET_VARIABLE__VALUE = "value";
public static final String SET_VARIABLE__VALUE__HELP = "Value that the variable will be set to.";
+ public static final String USEFUL_VARIABLES = "[A] System Variables\n"
+ + "1. SYS_USER User name (read only)\n"
+ + "2. SYS_USER_HOME User's home directory (read only)\n"
+ + "3. SYS_HOST_NAME Host where GFSH is running (read only)\n"
+ + "4. SYS_CLASSPATH CLASSPATH of the GFSH JVM (read only)\n"
+ + "5. SYS_JAVA_VERSION Java version used by GFSH (read only)\n"
+ + "6. SYS_OS OS name for the host where GFSH is running (read only)\n"
+ + "7. SYS_PWD Current working directory (read only)\n\n"
+ + "[B] Application Variables\n"
+ + "1. APP_CONTEXT_PATH Current context path (read only)\n"
+ + "2. APP_FETCH_SIZE Fetch size used when querying. Valid values are: 1-100\n"
+ + "3. APP_LAST_EXIT_STATUS Numeric value for last command exit status. One of: 0 (success), 1 (error), 2 (crash) (read only)\n"
+ + "4. APP_COLLECTION_LIMIT Number of items in the embedded collection of a result to be iterated. Valid values are: 1-100.\n"
+ + "5. APP_QUERY_RESULTS_DISPLAY_MODE How command results should be shown. Valid values are: table and catalog.\n"
+ + "6. APP_QUIET_EXECUTION. Whether commands should be executed in quiet mode. Valid values are: true and false.\n";
+
/* 'sh' command */
public static final String SH = "sh";
public static final String SH__HELP =
@@ -1840,6 +1991,7 @@ public class CliStrings {
"Number of lines from the log file to display. The maximum is 100.";
public static final String SHOW_LOG_NO_LOG = "There is no log for this member";
public static final String SHOW_LOG_MSG_MEMBER_NOT_FOUND = "Member not found";
+ public static final String SHOW_LOG_MSG_INVALID_NUMBER = "Invalid number";
public static final String SHOW_LOG_ERROR = "Error";
/* show metrics */
@@ -1889,6 +2041,9 @@ public class CliStrings {
public static final String INCLUDE_LOCATORS = "include-locators";
public static final String INCLUDE_LOCATORS_HELP =
"To shutdown locators specify this option as true. Default is false";
+ public static final String SHUTDOWN__MSG__CANNOT_EXECUTE = "Cannot execute";
+ public static final String SHUTDOWN__MSG__ERROR =
+ "Exception occurred while shutdown. Reason : {0}";
public static final String SHUTDOWN__MSG__MANAGER_NOT_FOUND = "Could not locate Manager.";
public static final String SHUTDOWN__MSG__WARN_USER =
"As a lot of data in memory will be lost, including possibly events in queues, do you really want to shutdown the entire distributed system?";
@@ -1898,8 +2053,11 @@ public class CliStrings {
"Shutting down entire distributed system";
public static final String SHUTDOWN__MSG__IMPROPER_TIMEOUT =
"time-out should not be less than 10 sec.";
+ public static final String SHUTDOWN__MSG__CAN_NOT_SHUTDOWN_WITHIN_TIMEOUT =
+ "Could not shutdown within timeout. Shutdown will continue in background";
public static final String SHUTDOWN__MSG__NO_DATA_NODE_FOUND =
"No data node found for stopping. Please specify --include-locators option if you want locators to be stopped";
+
public static final String SHUTDOWN_TIMEDOUT =
"Shutdown command timedout. Please manually check node status";
@@ -1915,8 +2073,11 @@ public class CliStrings {
public static final String CHANGE_LOGLEVEL__LOGLEVEL__HELP = "Log level to change to";
public static final String CHANGE_LOGLEVEL__MSG__SPECIFY_GRP_OR_MEMBER =
"Specify one of group or member";
+ public static final String CHANGE_LOGLEVEL__MSG__INVALID_LOG_LEVEL =
+ "Specified log-level is invalid";
+ public static final String CHANGE_LOGLEVEL__MSG__SPECIFY_LOG_LEVEL = "Specify valid log-level";
public static final String CHANGE_LOGLEVEL__MSG__CANNOT_EXECUTE =
- "Cannot execute change log-level. The specified log-level may be invalid or missing.";
+ "Cannot execute change log-level.";
public static final String CHANGE_LOGLEVEL__COLUMN_MEMBER = "Member";
public static final String CHANGE_LOGLEVEL__COLUMN_STATUS = "Changed log-level";
public static final String CHANGE_LOGLEVEL__MSG_NO_MEMBERS =
@@ -2121,6 +2282,9 @@ public class CliStrings {
"An error occurred while launching Java VisualVM - %1$s";
public static final String START_JVISUALVM__EXPECTED_JDK_VERSION_ERROR_MESSAGE =
"Java VisualVM was not bundled with the JDK until version 1.6.\nDownload and install Java VisualVM to the JDK bin directory separately.";
+ public static final String START_JVISUALVM__J = "J";
+ public static final String START_JVISUALVM__J__HELP =
+ "Arguments passed to the JVM on which Java VisualVM will run.";
public static final String START_JVISUALVM__NOT_FOUND_ERROR_MESSAGE =
"Java VisualVM could not be found on this system.\nPlease ensure that \"jvisualvm\" is installed in the JDK bin directory and the JDK bin directory is in the system PATH.";
public static final String START_JVISUALVM__RUN = "Launched JVisualVM";
@@ -2218,6 +2382,40 @@ public class CliStrings {
public static final String START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS__HELP =
"The IP address on which the HTTP Service will be bound. By default, the Server is bound to all local addresses.";
+ /* 'start manager' command */
+ public static final String START_MANAGER = "start manager";
+ public static final String START_MANAGER__HELP =
+ "Start a Manager. Parameters --peer and --server will be removed for simplicity and Locator is always available for both.";
+ public static final String START_MANAGER__MEMBERNAME = "name";
+ public static final String START_MANAGER__MEMBERNAME__HELP =
+ "Member name for this Manager service.";
+ public static final String START_MANAGER__DIR = "dir";
+ public static final String START_MANAGER__DIR__HELP =
+ "Directory in which the Manager will be run. The default is the current directory.";
+ public static final String START_MANAGER__CLASSPATH = "classpath";
+ public static final String START_MANAGER__CLASSPATH__HELP =
+ "Location of user classes required by the Manager. This path is appended to the current classpath.";
+ public static final String START_MANAGER__PORT = "port";
+ public static final String START_MANAGER__PORT__HELP =
+ "Port the Manager will listen on for JMX-RMI client connections.";
+ public static final String START_MANAGER__BIND_ADDRESS = "bind-address";
+ public static final String START_MANAGER__BIND_ADDRESS__HELP =
+ "IP address the Manager listen on for JMX-RMI client connections. The default is to bind to all local addresses.";
+ public static final String START_MANAGER__GROUP__HELP =
+ "Group(s) this Manager will be a part of.";
+ public static final String START_MANAGER__MAXHEAP = "max-heap";
+ public static final String START_MANAGER__MAXHEAP__HELP =
+ "Maximum size of the heap in the same format as the JVM -Xmx parameter.";
+ public static final String START_MANAGER__INITIALHEAP = "initial-heap";
+ public static final String START_MANAGER__INITIALHEAP__HELP =
+ "Initial size of the heap in the same format as the JVM -Xms parameter.";
+ public static final String START_MANAGER__GEODEPROPS = "G";
+ public static final String START_MANAGER__GEODEPROPS__HELP =
+ "Geode property passed as a <name>=<value> pair.";
+ public static final String START_MANAGER__J = "J";
+ public static final String START_MANAGER__J__HELP =
+ "Argument passed to the JVM on which the Locator will run. For example, --J=-Dfoo.bar=true will set the property \"foo.bar\" to \"true\".";
+
/* 'start server' command */
public static final String START_SERVER = "start server";
public static final String START_SERVER__HELP = "Start a Geode Cache Server.";
@@ -2338,6 +2536,10 @@ public class CliStrings {
public static final String START_SERVER__STATISTIC_ARCHIVE_FILE = STATISTIC_ARCHIVE_FILE;
public static final String START_SERVER__STATISTIC_ARCHIVE_FILE__HELP =
"The file that statistic samples are written to. An empty string (default) disables statistic archival.";
+ // public static final String START_SERVER__START_LOCATOR = "start-locator";
+ // public static final String START_SERVER__START_LOCATOR__HELP =
+ // "To start embedded Locator with given endpoints in the format: host[port]. If no endpoints are
+ // given defaults (localhost[10334]) are assumed.";
public static final String START_SERVER__USE_CLUSTER_CONFIGURATION = USE_CLUSTER_CONFIGURATION;
public static final String START_SERVER__USE_CLUSTER_CONFIGURATION__HELP =
"When set to true, the server requests the configuration from locator's cluster configuration service.";
@@ -2367,6 +2569,15 @@ public class CliStrings {
public static final String START_SERVER__EVICTION_OFF_HEAP_PERCENTAGE__HELP =
"Set the percentage of off-heap memory at or above which the eviction should begin on Regions configured for off-heap and HeapLRU eviction. Changing this value may cause eviction to begin immediately."
+ " Only one change to this attribute or critical off-heap percentage will be allowed at any given time and its effect will be fully realized before the next change is allowed.";
+ // cacheServer.setLoadPollInterval(loadPollInterval)
+ // cacheServer.setLoadProbe(loadProbe);
+ // cacheServer.setMaxConnections(maxCons);
+ // cacheServer.setMaximumMessageCount(maxMessageCount);
+ // cacheServer.setMaximumTimeBetweenPings(maximumTimeBetweenPings);
+ // cacheServer.setMaxThreads(maxThreads);
+ // cacheServer.setMessageTimeToLive(messageTimeToLive);
+ // cacheServer.setSocketBufferSize(socketBufferSize)
+ // cacheServer.setTcpNoDelay(noDelay)
public static final String START_SERVER__HOSTNAME__FOR__CLIENTS = "hostname-for-clients";
public static final String START_SERVER__HOSTNAME__FOR__CLIENTS__HELP =
"Sets the ip address or host name that this cache server is to listen on for client connections."
@@ -2374,6 +2585,12 @@ public class CliStrings {
+ "The value \"\" causes the bind-address to be given to clients."
+ "A null value will be treated the same as the default \"\".";
+
+ public static final String START_SERVER__LOAD__POLL__INTERVAL = "load-poll-interval";
+ public static final String START_SERVER__LOAD__POLL__INTERVAL__HELP =
+ "Set the frequency in milliseconds to poll the load probe on this cache server";
+
+
public static final String START_SERVER__MAX__CONNECTIONS = "max-connections";
public static final String START_SERVER__MAX__CONNECTIONS__HELP =
"Sets the maximum number of client connections allowed. When the maximum is reached the cache server will stop accepting connections";
@@ -2394,6 +2611,11 @@ public class CliStrings {
public static final String START_SERVER__SOCKET__BUFFER__SIZE__HELP =
"Sets the buffer size in bytes of the socket connection for this CacheServer. The default is 32768 bytes.";
+ public static final String START_SERVER__TCP__NO__DELAY = "tcp-no-delay";
+ public static final String START_SERVER__TCP__NO__DELAY__HELP =
+ "Configures the tcpNoDelay setting of sockets used to send messages to clients. TcpNoDelay is enabled by default";
+
+
/* start vsd command */
public static final String START_VSD = "start vsd";
public static final String START_VSD__FILE = "file";
@@ -2407,6 +2629,16 @@ public class CliStrings {
public static final String START_VSD__RUN =
"Launched Geode Visual Statistics Display (VSD) (see Geode log files for issues on start)";
+ /* start databrowser command */
+ public static final String START_DATABROWSER = "start data-browser";
+ public static final String START_DATABROWSER__HELP = "Start Data Browser in a separate process.";
+ public static final String START_DATABROWSER__NOT_FOUND_ERROR_MESSAGE =
+ "The location of DataBrowser could not be found. Please ensure DataBrowser was properly installed under Geode home (%1$s).";
+ public static final String START_DATABROWSER__RUN =
+ "Launched Geode DataBrowser (see Geode log files for issues on start)";
+ public static final String START_DATABROWSER__ERROR =
+ "An error occurred while launching DataBrowser - %1$s";
+
/* status gateway-receiver */
public static final String STATUS_GATEWAYRECEIVER = "status gateway-receiver";
public static final String STATUS_GATEWAYRECEIVER__HELP =
@@ -2507,6 +2739,8 @@ public class CliStrings {
"No Locator with member name or ID {0} could be found.";
public static final String STOP_LOCATOR__NOT_LOCATOR_ERROR_MESSAGE =
"The Geode member identified by {0} is not a Locator and cannot be shutdown using 'stop locator'.";
+ public static final String STOP_LOCATOR__SHUTDOWN_MEMBER_MESSAGE =
+ "Locator {0} has been requested to stop.";
public static final String STOP_LOCATOR__STOPPING_LOCATOR_MESSAGE =
"Stopping Locator running in %1$s on %2$s as %3$s...%nProcess ID: %4$d%nLog File: %5$s";
@@ -2528,6 +2762,8 @@ public class CliStrings {
public static final String STOP_SERVER__PID = "pid";
public static final String STOP_SERVER__PID__HELP =
"Process ID (PID) of the running Geode Cache Server. Deprecated: Since Geode1.2. Requires the JDK tools.jar which is not included on the classpath by default. Use --dir instead.";
+ public static final String STOP_SERVER__SHUTDOWN_MEMBER_MESSAGE =
+ "Cache Server {0} has been requested to stop.";
public static final String STOP_SERVER__STOPPING_SERVER_MESSAGE =
"Stopping Cache Server running in %1$s on %2$s as %3$s...%nProcess ID: %4$d%nLog File: %5$s";
@@ -2556,6 +2792,12 @@ public class CliStrings {
public static final String UPGRADE_OFFLINE_DISK_STORE__J = "J";
public static final String UPGRADE_OFFLINE_DISK_STORE__J__HELP =
"Arguments passed to the Java Virtual Machine performing the upgrade operation on the disk store.";
+ public static final String UPGRADE_OFFLINE_DISK_STORE__DISKSTORE_0_DOES_NOT_EXIST =
+ "Disk store \"{0}\" does not exist.";
+ public static final String UPGRADE_OFFLINE_DISK_STORE__UPGRADE_ATTEMPTED_BUT_NOTHING_TO_UPGRADE =
+ "Upgradation was attempted but nothing to upgrade.";
+ public static final String UPGRADE_OFFLINE_DISK_STORE__ERROR_WHILE_UPGRADATION_REASON_0 =
+ "Error occurred while performing disk store upgrade. Reason: \"{0}\"";
public static final String UPGRADE_OFFLINE_DISK_STORE__MSG__CANNOT_LOCATE_0_DISKSTORE_IN_1 =
"Cannot locate disk store \"{0}\" in directory : \"{1}\"";
public static final String UPGRADE_OFFLINE_DISK_STORE__MSG__DISKSTORE_IN_USE_COMPACT_DISKSTORE_CAN_BE_USED =
@@ -2592,6 +2834,8 @@ public class CliStrings {
public static final String VERSION__FULL__HELP = "Whether to show the full version information.";
/* start gateway command messages */
+ public static final String GATEWAY__MSG__OPTIONS = "Provide only one of member/group";
+ public static final String GATEWAY_MSG_MEMBER_0_NOT_FOUND = "Member : {0} not found";
public static final String GATEWAY_MSG_MEMBERS_NOT_FOUND = "Members not found";
public static final String GATEWAY_ERROR = "Error";
public static final String GATEWAY_OK = "OK";
@@ -2633,6 +2877,8 @@ public class CliStrings {
public static final String GATEWAY_RECEIVER_IS_NOT_AVAILABLE_OR_STOPPED =
"GatewayReceiver is not available or already stopped";
+ public static final String GATEWAY_RECEIVER_IS_NOT_AVAILABLE_OR_STOPPED_ON_MEMBER =
+ "GatewayReceiver is not available or already stopped on member {0}";
public static final String GATEWAY_RECEIVER_IS_ALREADY_STARTED_ON_MEMBER_0 =
"GatewayReceiver is already started on member {0}";
public static final String GATEWAY_RECEIVER_IS_STARTED_ON_MEMBER_0 =
@@ -2675,11 +2921,13 @@ public class CliStrings {
"Could not start gateway sender {0} on member due to {1}";
/* end gateway command messages */
- /* Durable CQ Commands */
- public static final String DURABLE_CQ_CLIENT_NOT_FOUND =
- "No durable client found on server for durable client id {0}.";
+ /***
+ * CQ Commands
+ *
+ */
// List durable cqs
+
public static final String LIST_DURABLE_CQS = "list durable-cqs";
public static final String LIST_DURABLE_CQS__DURABLECLIENTID = DURABLE_CLIENT_ID;
public static final String LIST_DURABLE_CQS__DURABLECLIENTID__HELP =
@@ -2692,12 +2940,18 @@ public class CliStrings {
"Group of members for which the durable client is registered and durable cqs will be displayed.";
public static final String LIST_DURABLE_CQS__NO__CQS__FOR__CLIENT =
"No durable cqs found for durable-client-id : \"{0}\".";
+ public static final String LIST_DURABLE_CQS__PER__MEMBER__MSG =
+ "Durable cqs on member : \"{0}\".";
+ public static final String LIST_DURABLE_CQS__FAILURE__MSG =
+ "Errors while retrieving cqs for durable client \"{0}\".";
+ public static final String LIST_DURABLE_CQS__EXCEPTION__OCCURRED__ON =
+ "Members with exceptions while retrieving durable cqs.";
public static final String LIST_DURABLE_CQS__NO__CQS__REGISTERED =
"No durable cq's registered on this member.";
public static final String LIST_DURABLE_CQS__NAME = "durable-cq-name";
-
public static final String LIST_DURABLE_CQS__FAILURE__HEADER =
"Unable to list durable-cqs for durable-client-id : \"{0}\" due to following reasons.";
+
// Close Durable CQ's
public static final String CLOSE_DURABLE_CQS = "close durable-cq";
public static final String CLOSE_DURABLE_CQS__HELP =
@@ -2715,9 +2969,9 @@ public class CliStrings {
"Could not close the durable-cq : \"{0}\" for the durable-client-id : \"{1}\" due to following reasons.";
public static final String CLOSE_DURABLE_CQS__SUCCESS =
"Closed the durable cq : \"{0}\" for the durable client : \"{1}\".";
-
public static final String CLOSE_DURABLE_CQS__UNABLE__TO__CLOSE__CQ =
"Unable to close the durable cq : \"{0}\" for the durable client : \"{1}\".";
+
// Close Durable Clients
public static final String CLOSE_DURABLE_CLIENTS = "close durable-client";
public static final String CLOSE_DURABLE_CLIENTS__HELP =
@@ -2731,9 +2985,9 @@ public class CliStrings {
"Group of members for which the durable client is to be closed.";
public static final String CLOSE_DURABLE_CLIENTS__FAILURE__HEADER =
"Unable to close the durable client : \"{0}\" due to following reasons.";
-
public static final String CLOSE_DURABLE_CLIENTS__SUCCESS =
"Closed the durable client : \"{0}\".";
+
public static final String COUNT_DURABLE_CQ_EVENTS = "show subscription-queue-size";
public static final String COUNT_DURABLE_CQ_EVENTS__HELP =
"Shows the number of events in the subscription queue. If a cq name is provided, counts the number of events in the subscription queue for the specified cq.";
@@ -2747,12 +3001,16 @@ public class CliStrings {
"Name/Id of the member for which the subscription events are to be counted.";
public static final String COUNT_DURABLE_CQ_EVENTS__GROUP__HELP =
"Group of members for which the subscription queue events are to be counted.";
+ public static final String COUNT_DURABLE_CQ_EVENTS__DURABLE_CLIENT_NOT_FOUND =
+ "No durable client found on server for durable client id {0}.";
public static final String COUNT_DURABLE_CQ_EVENTS__DURABLE_CQ_NOT_FOUND =
"No cq found on server for client with durable-client-id : {0} with cq-name : {1}.";
public static final String COUNT_DURABLE_CQ_EVENTS__DURABLE_CQ_STATS_NOT_FOUND =
"No cq stats found on server for durable client id {0} with cq name {1}.";
public static final String COUNT_DURABLE_CQ_EVENTS__NO__CQS__REGISTERED =
"No cq's registered on this member";
+ public static final String COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CQ =
+ "subscription-queue-size for durable-cq : \"{0}\".";
public static final String COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT =
"subscription-queue-size for durable-client : \"{0}\".";
@@ -2766,8 +3024,15 @@ public class CliStrings {
public static final String EXPORT_SHARED_CONFIG__FILE = "zip-file-name";
public static final String EXPORT_SHARED_CONFIG__FILE__HELP =
"Path to the zip file containing the exported cluster configuration artifacts";
+ public static final String EXPORT_SHARED_CONFIG__MSG__NOT_A_DIRECTORY = "{0} is not a directory.";
+ public static final String EXPORT_SHARED_CONFIG__MSG__CANNOT_CREATE_DIR =
+ "Directory {0} could not be created.";
+ public static final String EXPORT_SHARED_CONFIG__MSG__NOT_WRITEABLE = "{0} is not writeable";
+ public static final String EXPORT_SHARED_CONFIG__FILE__NAME = "cluster-config-{0}.zip";
public static final String EXPORT_SHARED_CONFIG__DOWNLOAD__MSG =
"Downloading cluster configuration : {0}";
+ public static final String EXPORT_SHARED_CONFIG__LOCATOR_HEADER = "Locator";
+ public static final String EXPORT_SHARED_CONFIG__LOCATOR__ERROR__MSG__HEADER = "Error";
public static final String EXPORT_SHARED_CONFIG__UNABLE__TO__EXPORT__CONFIG =
"Unable to export config";
@@ -2777,8 +3042,18 @@ public class CliStrings {
public static final String IMPORT_SHARED_CONFIG__ZIP = "zip-file-name";
public static final String IMPORT_SHARED_CONFIG__ZIP__HELP =
"The zip file containing the cluster configuration artifacts, which are to be imported";
+ public static final String IMPORT_SHARED_CONFIG__DIR = "dir";
+ public static final String IMPORT_SHARED_CONFIG__DIR__HELP =
+ "The directory which contains the cluster configuration artifacts, which are to be imported.";
+ public static final String IMPORT_SHARED_CONFIG__PRE__IMPORT__MSG =
+ "Importing configuration into locator would overwrite the existing cluster configuration. Would you like to proceed ?";
+ public static final String IMPORT_SHARED_CONFIG__CANNOT__IMPORT__MSG =
+ "Cluster configuration cannot be imported when there are running data members present in the distributed system.\n"
+ + "Shutdown all the non locator members to import the cluster configuration, and restart them after the cluster configuration is successfully imported.";
public static final String NO_LOCATORS_WITH_SHARED_CONFIG =
"No locators found with \"enable-cluster-configuration=true\".";
+ public static final String IMPORT_SHARED_CONFIG__ARTIFACTS__COPIED =
+ "Cluster configuration artifacts successfully copied";
public static final String IMPORT_SHARED_CONFIG__SUCCESS__MSG =
"Cluster configuration successfully imported";
public static final String IMPORT_SHARED_CONFIG__PROVIDE__ZIP =
@@ -2788,6 +3063,8 @@ public class CliStrings {
public static final String STATUS_SHARED_CONFIG_HELP =
"Displays the status of cluster configuration service on all the locators with enable-cluster-configuration set to true.";
public static final String STATUS_SHARED_CONFIG_NAME_HEADER = "Name";
+ public static final String STATUS_SHARED_CONFIG_HOST_HEADER = "Hostname";
+ public static final String STATUS_SHARED_CONFIG_PORT_HEADER = "Port";
public static final String STATUS_SHARED_CONFIG_STATUS = "Status";
@@ -2802,10 +3079,16 @@ public class CliStrings {
"Control whether pdx ignores fields that were unread during deserialization. The default is to preserve unread fields be including their data during serialization. But if you configure the cache to ignore unread fields then their data will be lost during serialization."
+ "You should only set this attribute to true if you know this member will only be reading cache data. In this use case you do not need to pay the cost of preserving the unread fields since you will never be reserializing pdx data.";
public static final String CONFIGURE_PDX__PERSISTENT = "persistent";
+ public static final String CONFIGURE_PDX__PERSISTENT__HELP =
+ "Control whether the type metadata for PDX objects is persisted to disk. The default for this setting is false. If you are using persistent regions with PDX then you must set this to true. If you are using a GatewaySender or AsyncEventQueue with PDX then you should set this to true";
public static final String CONFIGURE_PDX__DISKSTORE = "disk-store";
public static final String CONFIGURE_PDX__DISKSTORE__HELP =
"Named disk store where the PDX type data will be stored";
+ public static final String CONFIGURE_PDX__CHECK__PORTABILITY = "check-portability";
+ public static final String CONFIGURE_PDX__CHECK__PORTABILITY__HELP =
+ "if true then an serialization done by this serializer will throw an exception if the object it not portable to non-java languages.";
+
public static final String CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES =
"portable-auto-serializable-classes";
public static final String CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES__HELP =
@@ -2836,8 +3119,18 @@ public class CliStrings {
public static final String PDX_RENAME__EMPTY = "No Pdx types found to rename.";
public static final String PDX_DELETE_FIELD = "pdx delete-field";
+ public static final String PDX_DELETE_FIELD__HELP =
+ "Deletes a field from a PDX type in an offline disk store. \n Any pdx types with a field deleted by this command will be listed in the output. \n If no deletes are done or the disk-store is online then this command will fail.";
public static final String PDX_CLASS = "class";
+ public static final String PDX_CLASS__HELP =
+ "The fully qualified class name of the pdx type to delete the field from.";
public static final String PDX_FIELD = "field";
+ public static final String PDX_FIELD__HELP = "Field name to delete";
+ public static final String PDX_DELETE_FIELD__SUCCESS =
+ "Successfully deleted field in types:\n{0}";
+ public static final String PDX_DELETE_FIELD__ERROR = "Error deleting field : {0}";
+ public static final String PDX_DELETE__EMPTY = "Field to be deleted not found in the class.";
+
public static final String START_SERVER__REST_API = "start-rest-api";
public static final String START_SERVER__REST_API__HELP =
@@ -2886,5 +3179,7 @@ public class CliStrings {
return MessageFormat.format(pattern, arguments);
}
+
public static final String IGNORE_INTERCEPTORS = "ignoreInterceptors";
+
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
index d223a9f..9f06ea3 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/ConfigCommandsController.java
@@ -14,9 +14,10 @@
*/
package org.apache.geode.management.internal.web.controllers;
-import java.io.IOException;
-import java.util.concurrent.Callable;
-
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.management.internal.web.util.ConvertUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
@@ -26,19 +27,15 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.management.internal.web.util.ConvertUtils;
+import java.io.IOException;
+import java.util.concurrent.Callable;
/**
* The ConfigCommandsController class implements GemFire Management REST API web service endpoints
* for the Gfsh Config Commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.AlterRuntimeConfigCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeConfigCommand
- * @see org.apache.geode.management.internal.cli.commands.ExportConfigCommand
+ * @see org.apache.geode.management.internal.cli.commands.ConfigCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractMultiPartCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
index 9d3e086..23c5083 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DeployCommandsController.java
@@ -14,8 +14,10 @@
*/
package org.apache.geode.management.internal.web.controllers;
-import java.io.IOException;
-
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import org.apache.geode.management.internal.web.util.ConvertUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@@ -23,19 +25,14 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-import org.apache.geode.management.internal.web.util.ConvertUtils;
+import java.io.IOException;
/**
* The DeployCommandsController class implements the GemFire Management REST API web service
* endpoints for the Gfsh Deploy Commands.
* <p/>
- *
- * @see org.apache.geode.management.internal.cli.commands.DeployCommand
- * @see org.apache.geode.management.internal.cli.commands.UndeployCommand
- * @see org.apache.geode.management.internal.cli.commands.ListDeployedCommand
+ *
+ * @see org.apache.geode.management.internal.cli.commands.ConfigCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractMultiPartCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.RequestMapping
@@ -64,6 +61,8 @@ public class DeployCommandsController extends AbstractMultiPartCommandsControlle
@RequestMapping(method = RequestMethod.POST, value = "/deployed")
@ResponseBody
+ // final MultipartHttpServletRequest request
+ // @RequestPart(RESOURCES_REQUEST_PARAMETER) final Resource[] jarFileResources,
public String deploy(
@RequestParam(RESOURCES_REQUEST_PARAMETER) final MultipartFile[] jarFileResources,
@RequestParam(value = CliStrings.GROUP, required = false) final String[] groups,
@@ -83,6 +82,9 @@ public class DeployCommandsController extends AbstractMultiPartCommandsControlle
if (hasValue(directory)) {
command.addOption(CliStrings.DEPLOY__DIR, directory);
}
+
+ // save(jarFileResources);
+
return processCommand(command.toString(), ConvertUtils.convert(jarFileResources));
}
@@ -101,6 +103,8 @@ public class DeployCommandsController extends AbstractMultiPartCommandsControlle
command.addOption(CliStrings.JAR,
StringUtils.join(jarFileNames, StringUtils.COMMA_DELIMITER));
}
+
return processCommand(command.toString());
}
+
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
index 1f646d6..2e06811 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DiskStoreCommandsController.java
@@ -25,7 +25,6 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.commands.ListDiskStoresCommand;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
@@ -33,21 +32,8 @@ import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
* The DiskStoreCommandsController class implements GemFire Management REST API web service
* endpoints for the Gfsh Disk Store Commands.
* <p/>
- *
- * @see org.apache.geode.management.internal.cli.commands.AlterOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.BackupDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.CompactDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.CompactOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.DestroyDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.ExportOfflineDiskStoreCommand
- * @see ListDiskStoresCommand
- * @see org.apache.geode.management.internal.cli.commands.RevokeMissingDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.ShowMissingDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.UpgradeOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.ValidateDiskStoreCommand
+ *
+ * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
index 0e62e71..4562cd5 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/DurableClientCommandsController.java
@@ -14,6 +14,10 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.distributed.ConfigurationProperties;
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -21,20 +25,13 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.distributed.ConfigurationProperties;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
* The DurableClientCommandsController class implements GemFire Management REST API web service
* endpoints for the durable client/CQs Gfsh commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.CloseDurableClientCommand
- * @see org.apache.geode.management.internal.cli.commands.CloseDurableCQsCommand
- * @see org.apache.geode.management.internal.cli.commands.CountDurableCQEventsCommand
- * @see org.apache.geode.management.internal.cli.commands.ListDurableClientCQsCommand
+ * @see org.apache.geode.management.internal.cli.commands.DurableClientCommands
+ * @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
* @see org.springframework.web.bind.annotation.RequestMapping
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
index da3fc65..855947e 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/FunctionCommandsController.java
@@ -14,8 +14,9 @@
*/
package org.apache.geode.management.internal.web.controllers;
-import java.util.concurrent.Callable;
-
+import org.apache.geode.internal.lang.StringUtils;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
@@ -24,18 +25,14 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+import java.util.concurrent.Callable;
/**
* The FunctionCommandsController class implements GemFire Management REST API web service endpoints
* for the Gfsh Function Commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.DestroyFunctionCommand
- * @see org.apache.geode.management.internal.cli.commands.ExecuteFunctionCommand
- * @see org.apache.geode.management.internal.cli.commands.ListFunctionCommand
+ * @see org.apache.geode.management.internal.cli.commands.FunctionCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
index 09d7f9a..296156f 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/IndexCommandsController.java
@@ -14,6 +14,9 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -21,19 +24,11 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
* The IndexCommandsController class implements the REST API calls for the Gfsh Index commands.
* </p>
*
- * @see org.apache.geode.management.internal.cli.commands.ClearDefinedIndexesCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateDefinedIndexesCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.DefineIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.DestroyIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.IndexCommands
* @see org.apache.geode.management.internal.cli.util.CommandStringBuilder
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
index ba5c788..66e82ee 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/web/controllers/MemberCommandsController.java
@@ -14,6 +14,9 @@
*/
package org.apache.geode.management.internal.web.controllers;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
+
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@@ -21,16 +24,12 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.util.CommandStringBuilder;
-
/**
* The MemberCommandsController class implements GemFire Management REST API web service endpoints
* for the Gfsh Member Commands.
* <p/>
*
- * @see org.apache.geode.management.internal.cli.commands.ListMemberCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeMemberCommand
+ * @see org.apache.geode.management.internal.cli.commands.MemberCommands
* @see org.apache.geode.management.internal.web.controllers.AbstractCommandsController
* @see org.springframework.stereotype.Controller
* @see org.springframework.web.bind.annotation.PathVariable
@@ -47,12 +46,25 @@ public class MemberCommandsController extends AbstractCommandsController {
@RequestMapping(method = RequestMethod.GET, value = "/members")
@ResponseBody
+ // public String listMembers(@RequestBody MultiValueMap<String, String> requestParameters) {
+ // public String listMembers(@RequestParam(value = "group", required = false) final String
+ // groupName,
+ // @RequestParam(value = "group", required = false) final String[] groupNames) {
public String listMembers(
@RequestParam(value = CliStrings.GROUP, required = false) final String groupName) {
CommandStringBuilder command = new CommandStringBuilder(CliStrings.LIST_MEMBER);
+
+ // logger.info(String.format("Request Body: %1$s", requestParameters));
+ // logger.info(String.format("Request Parameter (group): %1$s", groupName));
+ // logger.info(String.format("Request Parameter (group) as array: %1$s",
+ // ArrayUtils.toString(groupNames)));
+
+ // final String groupName = requestParameters.getFirst("group");
+
if (hasValue(groupName)) {
command.addOption(CliStrings.GROUP, groupName);
}
+
return processCommand(command.toString());
}
@@ -63,4 +75,5 @@ public class MemberCommandsController extends AbstractCommandsController {
command.addOption(CliStrings.DESCRIBE_MEMBER__IDENTIFIER, decode(memberNameId));
return processCommand(command.toString());
}
+
}
[10/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java
deleted file mode 100644
index 5e379b0..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ListRegionCommand.java
+++ /dev/null
@@ -1,86 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.LinkedHashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.RegionInformation;
-import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ListRegionCommand implements GfshCommand {
- private static final GetRegionsFunction getRegionsFunction = new GetRegionsFunction();
-
- @CliCommand(value = {CliStrings.LIST_REGION}, help = CliStrings.LIST_REGION__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result listRegion(
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.LIST_REGION__GROUP__HELP) String[] group,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.LIST_REGION__MEMBER__HELP) String[] memberNameOrId) {
- Result result = null;
- try {
- ResultCollector<?, ?> rc;
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- rc = CliUtil.executeFunction(getRegionsFunction, null, targetMembers);
- List<?> resultList = (ArrayList<?>) rc.getResult();
-
- if (resultList == null) {
- return null;
- }
-
- resultList.stream().filter(resultObj -> resultObj instanceof Object[])
- .map(resultObj -> (Object[]) resultObj).flatMap(Arrays::stream)
- .filter(regionInfo -> regionInfo instanceof RegionInformation)
- .map(regionInfo -> (RegionInformation) regionInfo)
- .collect(Collectors.toCollection(LinkedHashSet::new));
- } catch (FunctionInvocationTargetException e) {
- result = ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_REGION));
- } catch (Exception e) {
- result = ResultBuilder
- .createGemFireErrorResult(CliStrings.LIST_REGION__MSG__ERROR + " : " + e.getMessage());
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java
new file mode 100644
index 0000000..12820f2
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MemberCommands.java
@@ -0,0 +1,197 @@
+/*
+ * 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 org.apache.geode.cache.CacheClosedException;
+import org.apache.geode.cache.CacheFactory;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.domain.CacheServerInfo;
+import org.apache.geode.management.internal.cli.domain.MemberInformation;
+import org.apache.geode.management.internal.cli.functions.GetMemberInformationFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.springframework.shell.core.CommandMarker;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * @since GemFire 7.0
+ */
+public class MemberCommands implements GfshCommand {
+
+ private static final GetMemberInformationFunction getMemberInformation =
+ new GetMemberInformationFunction();
+
+ @CliCommand(value = {CliStrings.LIST_MEMBER}, help = CliStrings.LIST_MEMBER__HELP)
+ @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listMember(@CliOption(key = {CliStrings.GROUP}, unspecifiedDefaultValue = "",
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.LIST_MEMBER__GROUP__HELP) String group) {
+ Result result = null;
+
+ // TODO: Add the code for identifying the system services
+ try {
+ Set<DistributedMember> memberSet = new TreeSet<DistributedMember>();
+ InternalCache cache = getCache();
+
+ // default get all the members in the DS
+ if (group.isEmpty()) {
+ memberSet.addAll(CliUtil.getAllMembers(cache));
+ } else {
+ memberSet.addAll(cache.getDistributedSystem().getGroupMembers(group));
+ }
+
+ if (memberSet.isEmpty()) {
+ result = ResultBuilder.createInfoResult(CliStrings.LIST_MEMBER__MSG__NO_MEMBER_FOUND);
+ } else {
+ TabularResultData resultData = ResultBuilder.createTabularResultData();
+ Iterator<DistributedMember> memberIters = memberSet.iterator();
+ while (memberIters.hasNext()) {
+ DistributedMember member = memberIters.next();
+ resultData.accumulate("Name", member.getName());
+ resultData.accumulate("Id", member.getId());
+ }
+
+ result = ResultBuilder.buildResult(resultData);
+ }
+ } catch (Exception e) {
+
+ result = ResultBuilder
+ .createGemFireErrorResult("Could not fetch the list of members. " + e.getMessage());
+ LogWrapper.getInstance().warning(e.getMessage(), e);
+ }
+
+ return result;
+ }
+
+ @CliCommand(value = {CliStrings.DESCRIBE_MEMBER}, help = CliStrings.DESCRIBE_MEMBER__HELP)
+ @CliMetaData(shellOnly = false, relatedTopic = CliStrings.TOPIC_GEODE_SERVER)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result describeMember(@CliOption(key = CliStrings.DESCRIBE_MEMBER__IDENTIFIER,
+ optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.DESCRIBE_MEMBER__HELP,
+ mandatory = true) String memberNameOrId) {
+ Result result = null;
+
+ try {
+ DistributedMember memberToBeDescribed =
+ CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+
+ if (memberToBeDescribed != null) {
+ // This information should be available through the MBeans too. We might not need
+ // the function.
+
+ // Yes, but then the command is subject to Mbean availability, which would be
+ // affected once MBean filters are used.
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(getMemberInformation, null, memberToBeDescribed);
+
+ ArrayList<?> output = (ArrayList<?>) rc.getResult();
+ Object obj = output.get(0);
+
+ if (obj != null && (obj instanceof MemberInformation)) {
+
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+
+ MemberInformation memberInformation = (MemberInformation) obj;
+ memberInformation.setName(memberToBeDescribed.getName());
+ memberInformation.setId(memberToBeDescribed.getId());
+ memberInformation.setHost(memberToBeDescribed.getHost());
+ memberInformation.setProcessId("" + memberToBeDescribed.getProcessId());
+
+ SectionResultData section = crd.addSection();
+ section.addData("Name", memberInformation.getName());
+ section.addData("Id", memberInformation.getId());
+ section.addData("Host", memberInformation.getHost());
+ section.addData("Regions",
+ CliUtil.convertStringSetToString(memberInformation.getHostedRegions(), '\n'));
+ section.addData("PID", memberInformation.getProcessId());
+ section.addData("Groups", memberInformation.getGroups());
+ section.addData("Used Heap", memberInformation.getHeapUsage() + "M");
+ section.addData("Max Heap", memberInformation.getMaxHeapSize() + "M");
+
+ String offHeapMemorySize = memberInformation.getOffHeapMemorySize();
+ if (offHeapMemorySize != null && !offHeapMemorySize.isEmpty()) {
+ section.addData("Off Heap Size", offHeapMemorySize);
+ }
+
+ section.addData("Working Dir", memberInformation.getWorkingDirPath());
+ section.addData("Log file", memberInformation.getLogFilePath());
+
+ section.addData("Locators", memberInformation.getLocators());
+
+ if (memberInformation.isServer()) {
+ SectionResultData clientServiceSection = crd.addSection();
+ List<CacheServerInfo> csList = memberInformation.getCacheServeInfo();
+
+ if (csList != null) {
+ Iterator<CacheServerInfo> iters = csList.iterator();
+ clientServiceSection.setHeader("Cache Server Information");
+
+ while (iters.hasNext()) {
+ CacheServerInfo cacheServerInfo = iters.next();
+ clientServiceSection.addData("Server Bind", cacheServerInfo.getBindAddress());
+ clientServiceSection.addData("Server Port", cacheServerInfo.getPort());
+ clientServiceSection.addData("Running", cacheServerInfo.isRunning());
+ }
+
+ clientServiceSection.addData("Client Connections",
+ memberInformation.getClientCount());
+ }
+ }
+ result = ResultBuilder.buildResult(crd);
+
+ } else {
+ result = ResultBuilder.createInfoResult(CliStrings.format(
+ CliStrings.DESCRIBE_MEMBER__MSG__INFO_FOR__0__COULD_NOT_BE_RETRIEVED,
+ new Object[] {memberNameOrId}));
+ }
+ } else {
+ result = ResultBuilder.createInfoResult(CliStrings
+ .format(CliStrings.DESCRIBE_MEMBER__MSG__NOT_FOUND, new Object[] {memberNameOrId}));
+ }
+ } catch (CacheClosedException e) {
+
+ } catch (FunctionInvocationTargetException e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+ return result;
+ }
+
+}
[03/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsDUnitTest.java
----------------------------------------------------------------------
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
index a1b9ade..e913746 100644
--- 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
@@ -27,39 +27,37 @@ 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.assertFalse;
import static org.apache.geode.test.dunit.Assert.assertNotNull;
+import static org.apache.geode.test.dunit.Assert.assertNull;
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.PartitionAttributes;
+import org.apache.geode.cache.PartitionAttributesFactory;
+import org.apache.geode.cache.PartitionResolver;
import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionFactory;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.asyncqueue.AsyncEvent;
+import org.apache.geode.cache.asyncqueue.AsyncEventListener;
+import org.apache.geode.cache.wan.GatewaySenderFactory;
+import org.apache.geode.compression.SnappyCompressor;
import org.apache.geode.distributed.Locator;
import org.apache.geode.distributed.internal.ClusterConfigurationService;
import org.apache.geode.distributed.internal.InternalLocator;
import org.apache.geode.internal.AvailablePort;
import org.apache.geode.internal.AvailablePortHelper;
+import org.apache.geode.internal.ClassBuilder;
import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.PartitionedRegion;
+import org.apache.geode.internal.cache.RegionEntryContext;
import org.apache.geode.management.ManagementService;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.MBeanJMXAdapter;
@@ -72,26 +70,330 @@ 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.FlakyTest;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.text.MessageFormat;
+import java.util.Iterator;
+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;
@Category(DistributedTest.class)
public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBase {
+
private static final long serialVersionUID = 1L;
- private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
- private void waitForRegionMBeanCreation(final String regionPath) {
+ final String alterRegionName = "testAlterRegionRegion";
+ final String alterAsyncEventQueueId1 = "testAlterRegionQueue1";
+ final String alterAsyncEventQueueId2 = "testAlterRegionQueue2";
+ final String alterAsyncEventQueueId3 = "testAlterRegionQueue3";
+ final String alterGatewaySenderId1 = "testAlterRegionSender1";
+ final String alterGatewaySenderId2 = "testAlterRegionSender2";
+ final String alterGatewaySenderId3 = "testAlterRegionSender3";
+ final String region46391 = "region46391";
+ VM alterVm1;
+ String alterVm1Name;
+ VM alterVm2;
+ String alterVm2Name;
+
+ final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
+
+ /**
+ * Asserts that the "compressor" option for the "create region" command succeeds for a recognized
+ * compressor.
+ */
+ @Test
+ public void testCreateRegionWithGoodCompressor() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+ VM vm = Host.getHost(0).getVM(1);
+
+ // Create a cache in vm 1
+ vm.invoke(() -> {
+ assertNotNull(getCache());
+ });
+
+ // Run create region command with compression
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR,
+ RegionEntryContext.DEFAULT_COMPRESSION_PROVIDER);
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ // Make sure our region exists with compression enabled
+ vm.invoke(() -> {
+ Region region = getCache().getRegion("compressedRegion");
+ assertNotNull(region);
+ assertTrue(
+ SnappyCompressor.getDefaultInstance().equals(region.getAttributes().getCompressor()));
+ });
+
+ // cleanup
+ commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
+ commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "compressedRegion");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ }
+
+ /**
+ * Asserts that the "compressor" option for the "create region" command fails for an unrecognized
+ * compressorc.
+ */
+ @Test
+ public void testCreateRegionWithBadCompressor() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ VM vm = Host.getHost(0).getVM(1);
+
+ // Create a cache in vm 1
+ vm.invoke(() -> {
+ assertNotNull(getCache());
+ });
+
+ // Create a region with an unrecognized compressor
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR, "BAD_COMPRESSOR");
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ // Assert that our region was not created
+ vm.invoke(() -> {
+ Region region = getCache().getRegion("compressedRegion");
+ assertNull(region);
+ });
+ }
+
+ /**
+ * Asserts that a missing "compressor" option for the "create region" command results in a region
+ * with no compression.
+ */
+ @Test
+ public void testCreateRegionWithNoCompressor() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ VM vm = Host.getHost(0).getVM(1);
+
+ // Create a cache in vm 1
+ vm.invoke(() -> {
+ assertNotNull(getCache());
+ });
+
+ // Create a region with no compression
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "testRegion");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ // Assert that our newly created region has no compression
+ vm.invoke(() -> {
+ Region region = getCache().getRegion("testRegion");
+ assertNotNull(region);
+ assertNull(region.getAttributes().getCompressor());
+ });
+
+ // Cleanup
+ commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
+ commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "testRegion");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ }
+
+ @Test
+ public void testDestroyDistributedRegion() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ for (int i = 1; i <= 2; i++) {
+ Host.getHost(0).getVM(i).invoke(() -> {
+ final Cache cache = getCache();
+
+ RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
+ factory.create("Customer");
+
+ PartitionAttributesFactory paFactory = new PartitionAttributesFactory();
+ paFactory.setColocatedWith("Customer");
+ factory.setPartitionAttributes(paFactory.create());
+ factory.create("Order");
+ });
+ }
+
+ waitForRegionMBeanCreation("/Customer", 2);
+ waitForRegionMBeanCreation("/Order", 2);
+
+ // Test failure when region not found
+ String command = "destroy region --name=DOESNOTEXIST";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ CommandResult cmdResult = executeCommand(command);
+ String strr = commandResultToString(cmdResult);
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ // Test unable to destroy with co-location
+ command = "destroy region --name=/Customer";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ // Test success
+ command = "destroy region --name=/Order";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ assertTrue(stringContainsLine(strr, ".*Order.*destroyed successfully.*"));
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ command = "destroy region --name=/Customer";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ }
+
+ @Test
+ public void testDestroyLocalRegions() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ for (int i = 1; i <= 3; i++) {
+ Host.getHost(0).getVM(i).invoke(() -> {
+ final Cache cache = getCache();
+
+ RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ factory.setScope(Scope.LOCAL);
+ factory.create("Customer");
+ });
+ }
+
+ waitForRegionMBeanCreation("/Customer", 3);
+
+ // Test failure when region not found
+ String command = "destroy region --name=DOESNOTEXIST";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ CommandResult cmdResult = executeCommand(command);
+ String strr = commandResultToString(cmdResult);
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ command = "destroy region --name=/Customer";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ for (int i = 1; i <= 3; i++) {
+ final int x = i;
+ Host.getHost(0).getVM(i).invoke(() -> {
+ assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
+ });
+ }
+ }
+
+ @Test
+ public void testDestroyLocalAndDistributedRegions() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ for (int i = 1; i <= 2; i++) {
+ Host.getHost(0).getVM(i).invoke(() -> {
+ final Cache cache = getCache();
+ RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
+ factory.create("Customer");
+ factory.create("Customer-2");
+ factory.create("Customer_3");
+ });
+ }
+
+ Host.getHost(0).getVM(3).invoke(() -> {
+ final Cache cache = getCache();
+ RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
+ factory.setScope(Scope.LOCAL);
+ factory.create("Customer");
+ factory.create("Customer-2");
+ factory.create("Customer_3");
+ });
+
+ waitForRegionMBeanCreation("/Customer", 3);
+
+ // Test failure when region not found
+ String command = "destroy region --name=DOESNOTEXIST";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ CommandResult cmdResult = executeCommand(command);
+ String strr = commandResultToString(cmdResult);
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ command = "destroy region --name=/Customer";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ command = "destroy region --name=/Customer_3";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ assertTrue(stringContainsLine(strr, ".*Customer_3.*destroyed successfully.*"));
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ command = "destroy region --name=/Customer-2";
+ getLogWriter().info("testDestroyRegion command=" + command);
+ cmdResult = executeCommand(command);
+ strr = commandResultToString(cmdResult);
+ assertTrue(stringContainsLine(strr, ".*Customer-2.*destroyed successfully.*"));
+ getLogWriter().info("testDestroyRegion strr=" + strr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ for (int i = 1; i <= 3; i++) {
+ final int x = i;
+ Host.getHost(0).getVM(i).invoke(() -> {
+ assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
+ assertNull("Region still exists in VM " + x, getCache().getRegion("Customer-2"));
+ assertNull("Region still exists in VM " + x, getCache().getRegion("Customer_3"));
+ });
+ }
+ }
+
+ private void waitForRegionMBeanCreation(final String regionPath, final int mbeanCount) {
Host.getHost(0).getVM(0).invoke(() -> {
- waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath));
+ waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath, mbeanCount));
});
}
- private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath) {
+ private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath, final int mbeanCount) {
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;
+ return mbeanServer.queryNames(null, queryExpON).size() == mbeanCount;
} catch (MalformedObjectNameException mone) {
getLogWriter().error(mone);
fail(mone.getMessage());
@@ -100,6 +402,556 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
};
}
+ @Category(FlakyTest.class) // GEODE-973: random ports, BindException,
+ // java.rmi.server.ExportException: Port already in use
+ @Test
+ public void testCreateRegion46391() throws IOException {
+ setUpJmxManagerOnVm0ThenConnect(null); // GEODE-973: getRandomAvailablePort
+ String command = CliStrings.CREATE_REGION + " --" + CliStrings.CREATE_REGION__REGION + "="
+ + this.region46391 + " --" + CliStrings.CREATE_REGION__REGIONSHORTCUT + "=REPLICATE";
+
+ getLogWriter().info("testCreateRegion46391 create region command=" + command);
+
+ CommandResult cmdResult = executeCommand(command);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ command = CliStrings.PUT + " --" + CliStrings.PUT__KEY + "=k1" + " --" + CliStrings.PUT__VALUE
+ + "=k1" + " --" + CliStrings.PUT__REGIONNAME + "=" + this.region46391;
+
+ getLogWriter().info("testCreateRegion46391 put command=" + command);
+
+ CommandResult cmdResult2 = executeCommand(command);
+ assertEquals(Result.Status.OK, cmdResult2.getStatus());
+
+ getLogWriter().info("testCreateRegion46391 cmdResult2=" + commandResultToString(cmdResult2));
+ String str1 = "Result : true";
+ String str2 = "Key : k1";
+ String str3 = "Key Class : java.lang.String";
+ String str4 = "Value Class : java.lang.String";
+ String str5 = "Old Value : <NULL>";
+
+ assertTrue(commandResultToString(cmdResult)
+ .contains("Region \"/" + this.region46391 + "\" created on"));
+
+ assertTrue(commandResultToString(cmdResult2).contains(str1));
+ assertTrue(commandResultToString(cmdResult2).contains(str2));
+ assertTrue(commandResultToString(cmdResult2).contains(str3));
+ assertTrue(commandResultToString(cmdResult2).contains(str4));
+ assertTrue(commandResultToString(cmdResult2).contains(str5));
+ }
+
+ @Ignore("bug51924")
+ @Test
+ public void testAlterRegion() throws IOException {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
+
+ Host.getHost(0).getVM(0).invoke(() -> {
+ Cache cache = getCache();
+ cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+ .create(alterRegionName);
+ });
+
+ this.alterVm1 = Host.getHost(0).getVM(1);
+ this.alterVm1Name = "VM" + this.alterVm1.getPid();
+ this.alterVm1.invoke(() -> {
+ Properties localProps = new Properties();
+ localProps.setProperty(NAME, alterVm1Name);
+ localProps.setProperty(GROUPS, "Group1");
+ getSystem(localProps);
+ Cache cache = getCache();
+
+ // Setup queues and gateway senders to be used by all tests
+ cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+ .create(alterRegionName);
+ AsyncEventListener listener = new AsyncEventListener() {
+ @Override
+ public void close() {
+ // Nothing to do
+ }
+
+ @Override
+ public boolean processEvents(List<AsyncEvent> events) {
+ return true;
+ }
+ };
+ cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId1, listener);
+ cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId2, listener);
+ cache.createAsyncEventQueueFactory().create(alterAsyncEventQueueId3, listener);
+
+ GatewaySenderFactory gatewaySenderFactory = cache.createGatewaySenderFactory();
+ gatewaySenderFactory.setManualStart(true);
+ gatewaySenderFactory.create(alterGatewaySenderId1, 2);
+ gatewaySenderFactory.create(alterGatewaySenderId2, 3);
+ gatewaySenderFactory.create(alterGatewaySenderId3, 4);
+ });
+
+ this.alterVm2 = Host.getHost(0).getVM(2);
+ this.alterVm2Name = "VM" + this.alterVm2.getPid();
+ this.alterVm2.invoke(() -> {
+ Properties localProps = new Properties();
+ localProps.setProperty(NAME, alterVm2Name);
+ localProps.setProperty(GROUPS, "Group1,Group2");
+ getSystem(localProps);
+ Cache cache = getCache();
+
+ cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+ .create(alterRegionName);
+ });
+
+ deployJarFilesForRegionAlter();
+ regionAlterGroupTest();
+ regionAlterSetAllTest();
+ regionAlterNoChangeTest();
+ regionAlterSetDefaultsTest();
+ regionAlterManipulatePlugInsTest();
+
+ this.alterVm1.invoke(() -> {
+ getCache().getRegion(alterRegionName).destroyRegion();
+ });
+ }
+
+ private void regionAlterGroupTest() {
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "5764");
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
+ });
+
+ this.alterVm2.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
+ });
+
+ commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group2");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "6963");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(3, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertFalse(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(5764, attributes.getEvictionAttributes().getMaximum());
+ });
+
+ this.alterVm2.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(6963, attributes.getEvictionAttributes().getMaximum());
+ });
+ }
+
+ private void regionAlterSetAllTest() {
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX, "35464");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME, "3453");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
+ "DESTROY");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE, "7563");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION, "DESTROY");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerA");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER,
+ "com.cadrdunit.RegionAlterCacheLoader");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER,
+ "com.cadrdunit.RegionAlterCacheWriter");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME, "6234");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
+ "DESTROY");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, "4562");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION, "DESTROY");
+
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertEquals(5, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ "Manager.*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
+ assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
+ assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
+ assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
+ assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
+ assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
+ assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
+ assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
+ assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
+ assertEquals(1, attributes.getAsyncEventQueueIds().size());
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+ assertEquals(1, attributes.getGatewaySenderIds().size());
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+ assertEquals(1, attributes.getCacheListeners().length);
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+ attributes.getCacheListeners()[0].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheWriter",
+ attributes.getCacheWriter().getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheLoader",
+ attributes.getCacheLoader().getClass().getName());
+ });
+ }
+
+ private void regionAlterNoChangeTest() {
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED, "true");
+
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm2.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(35464, attributes.getEvictionAttributes().getMaximum());
+ assertEquals(3453, attributes.getEntryIdleTimeout().getTimeout());
+ assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
+ assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
+ assertTrue(attributes.getEntryTimeToLive().getAction().isDestroy());
+ assertEquals(6234, attributes.getRegionIdleTimeout().getTimeout());
+ assertTrue(attributes.getRegionIdleTimeout().getAction().isDestroy());
+ assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
+ assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
+ assertEquals(1, attributes.getAsyncEventQueueIds().size());
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+ assertEquals(1, attributes.getGatewaySenderIds().size());
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+ assertEquals(1, attributes.getCacheListeners().length);
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+ attributes.getCacheListeners()[0].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheWriter",
+ attributes.getCacheWriter().getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheLoader",
+ attributes.getCacheLoader().getClass().getName());
+ });
+ }
+
+ private void regionAlterSetDefaultsTest() {
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__EVICTIONMAX);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CLONINGENABLED);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELOADER);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHEWRITER);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION);
+
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ String stringResult = commandResultToString(cmdResult);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(0, attributes.getEvictionAttributes().getMaximum());
+ assertEquals(0, attributes.getEntryIdleTimeout().getTimeout());
+ assertTrue(attributes.getEntryIdleTimeout().getAction().isDestroy());
+ assertEquals(7563, attributes.getEntryTimeToLive().getTimeout());
+ assertTrue(attributes.getEntryTimeToLive().getAction().isInvalidate());
+ assertEquals(0, attributes.getRegionIdleTimeout().getTimeout());
+ assertTrue(attributes.getRegionIdleTimeout().getAction().isInvalidate());
+ assertEquals(4562, attributes.getRegionTimeToLive().getTimeout());
+ assertTrue(attributes.getRegionTimeToLive().getAction().isDestroy());
+ assertEquals(0, attributes.getAsyncEventQueueIds().size());
+ assertEquals(0, attributes.getGatewaySenderIds().size());
+ assertEquals(0, attributes.getCacheListeners().length);
+ });
+ }
+
+ private void regionAlterManipulatePlugInsTest() {
+
+ // Start out by putting 3 entries into each of the plug-in sets
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId2);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId3);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId2);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId3);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerA");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerB");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerC");
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(3, attributes.getAsyncEventQueueIds().size());
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
+ assertEquals(3, attributes.getGatewaySenderIds().size());
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
+ assertEquals(3, attributes.getCacheListeners().length);
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+ attributes.getCacheListeners()[0].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+ attributes.getCacheListeners()[1].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+ attributes.getCacheListeners()[2].getClass().getName());
+ });
+
+ // Now take 1 entry out of each of the sets
+ commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId2);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId3);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerB");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerC");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm2.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(2, attributes.getAsyncEventQueueIds().size());
+ Iterator iterator = attributes.getAsyncEventQueueIds().iterator();
+ assertEquals(alterAsyncEventQueueId1, iterator.next());
+ assertEquals(alterAsyncEventQueueId2, iterator.next());
+ assertEquals(2, attributes.getGatewaySenderIds().size());
+ iterator = attributes.getGatewaySenderIds().iterator();
+ assertEquals(alterGatewaySenderId1, iterator.next());
+ assertEquals(alterGatewaySenderId3, iterator.next());
+ assertEquals(2, attributes.getCacheListeners().length);
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+ attributes.getCacheListeners()[0].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+ attributes.getCacheListeners()[1].getClass().getName());
+ });
+
+ // Add 1 back to each of the sets
+ commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId2);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID,
+ this.alterAsyncEventQueueId3);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId1);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId3);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__GATEWAYSENDERID,
+ this.alterGatewaySenderId2);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerB");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerC");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerA");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(3, attributes.getAsyncEventQueueIds().size());
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId1));
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId2));
+ assertTrue(attributes.getAsyncEventQueueIds().contains(alterAsyncEventQueueId3));
+ assertEquals(3, attributes.getGatewaySenderIds().size());
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId1));
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId3));
+ assertTrue(attributes.getGatewaySenderIds().contains(alterGatewaySenderId2));
+ assertEquals(3, attributes.getCacheListeners().length);
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+ attributes.getCacheListeners()[0].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+ attributes.getCacheListeners()[1].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+ attributes.getCacheListeners()[2].getClass().getName());
+ });
+ }
+
+ @Category(FlakyTest.class) // GEODE-3018
+ @Test
+ public void testAlterRegionResetCacheListeners() throws IOException {
+ setUpJmxManagerOnVm0ThenConnect(null);
+
+ CommandResult cmdResult = executeCommand(CliStrings.LIST_REGION);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ assertTrue(commandResultToString(cmdResult).contains("No Regions Found"));
+
+ Host.getHost(0).getVM(0).invoke(() -> {
+ Cache cache = getCache();
+ cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+ .create(alterRegionName);
+ });
+
+ this.alterVm1 = Host.getHost(0).getVM(1);
+ this.alterVm1Name = "VM" + this.alterVm1.getPid();
+ this.alterVm1.invoke(() -> {
+ Properties localProps = new Properties();
+ localProps.setProperty(NAME, alterVm1Name);
+ localProps.setProperty(GROUPS, "Group1");
+ getSystem(localProps);
+ Cache cache = getCache();
+
+ // Setup queues and gateway senders to be used by all tests
+ cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+ .create(alterRegionName);
+ });
+
+ this.alterVm2 = Host.getHost(0).getVM(2);
+ this.alterVm2Name = "VM" + this.alterVm2.getPid();
+ this.alterVm2.invoke(() -> {
+ Properties localProps = new Properties();
+ localProps.setProperty(NAME, alterVm2Name);
+ localProps.setProperty(GROUPS, "Group1,Group2");
+ getSystem(localProps);
+ Cache cache = getCache();
+
+ cache.createRegionFactory(RegionShortcut.PARTITION).setStatisticsEnabled(true)
+ .create(alterRegionName);
+ });
+
+ deployJarFilesForRegionAlter();
+
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER,
+ "com.cadrdunit.RegionAlterCacheListenerA,com.cadrdunit.RegionAlterCacheListenerB,com.cadrdunit.RegionAlterCacheListenerC");
+
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ String stringResult = commandResultToString(cmdResult);
+
+ assertEquals(5, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(3, attributes.getCacheListeners().length);
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerA",
+ attributes.getCacheListeners()[0].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerB",
+ attributes.getCacheListeners()[1].getClass().getName());
+ assertEquals("com.cadrdunit.RegionAlterCacheListenerC",
+ attributes.getCacheListeners()[2].getClass().getName());
+ });
+
+ // Add 1 back to each of the sets
+ commandStringBuilder = new CommandStringBuilder(CliStrings.ALTER_REGION);
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__REGION, "/" + this.alterRegionName);
+ commandStringBuilder.addOption(CliStrings.GROUP, "Group1");
+ commandStringBuilder.addOption(CliStrings.ALTER_REGION__CACHELISTENER, "''");
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ stringResult = commandResultToString(cmdResult);
+ assertEquals(4, countLinesInString(stringResult, false));
+ assertEquals(false, stringResult.contains("ERROR"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm1Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+ assertTrue(stringContainsLine(stringResult,
+ this.alterVm2Name + ".*Region \"/" + this.alterRegionName + "\" altered.*"));
+
+ this.alterVm1.invoke(() -> {
+ RegionAttributes attributes = getCache().getRegion(alterRegionName).getAttributes();
+ assertEquals(0, attributes.getCacheListeners().length);
+ });
+ }
+
/**
* Asserts that creating, altering and destroying regions correctly updates the shared
* configuration.
@@ -117,6 +969,7 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
jmxHost = "localhost";
}
+
final String regionName = "testRegionSharedConfigRegion";
final String regionPath = "/" + regionName;
final String groupName = "testRegionSharedConfigGroup";
@@ -141,7 +994,7 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
final InternalLocator locator = (InternalLocator) Locator.startLocatorAndDS(locatorPort,
locatorLogFile, null, locatorProps);
- waitAtMost(5, TimeUnit.SECONDS).until(locator::isSharedConfigurationRunning);
+ waitAtMost(5, TimeUnit.SECONDS).until(() -> locator.isSharedConfigurationRunning());
ManagementService managementService =
ManagementService.getExistingManagementService(GemFireCacheImpl.getInstance());
@@ -177,7 +1030,7 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
assertEquals(Result.Status.OK, cmdResult.getStatus());
// Make sure that the region has been registered with the Manager MXBean
- waitForRegionMBeanCreation(regionPath);
+ waitForRegionMBeanCreation(regionPath, 1);
// Make sure the region exists in the shared config
Host.getHost(0).getVM(0).invoke(() -> {
@@ -256,8 +1109,251 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
return null;
}
});
+
+ }
+
+ @Test
+ public void testDestroyRegionWithSharedConfig() {
+ 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());
+ } 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, 1);
+
+ // Make sure the region exists in the shared config
+ Host.getHost(0).getVM(0).invoke(() -> {
+ ClusterConfigurationService sharedConfig =
+ ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
+ try {
+ assertTrue(
+ sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
+ } catch (Exception e) {
+ fail("Error occurred in cluster configuration service");
+ }
+ });
+
+ // Test destroying the region
+ commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
+ commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, regionName);
+ cmdResult = executeCommand(commandStringBuilder.toString());
+ getLogWriter().info("#SB" + commandResultToString(cmdResult));
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ // Make sure the region was removed from the shared config
+ Host.getHost(0).getVM(0).invoke(() -> {
+ ClusterConfigurationService sharedConfig =
+ ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
+ try {
+ assertFalse(
+ sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
+ } catch (Exception e) {
+ fail("Error occurred in cluster configuration service");
+ }
+ });
+
+
+ // Restart the data vm to make sure the region is not existing any more
+ 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);
+ assertNull(region);
+
+ return null;
+ });
}
+
+ final String PR_STRING = " package com.cadrdunit;"
+ + " public class TestPartitionResolver implements org.apache.geode.cache.PartitionResolver { "
+ + " @Override" + " public void close() {" + " }" + " @Override"
+ + " public Object getRoutingObject(org.apache.geode.cache.EntryOperation opDetails) { "
+ + " return null; " + " }" + " @Override" + " public String getName() { "
+ + " return \"TestPartitionResolver\";" + " }" + " }";
+
+ /**
+ * Test Description 1. Deploy a JAR with Custom Partition Resolver 2. Create Region with Partition
+ * Resolver 3. Region should get created with no Errors 4. Verify Region Partition Attributes for
+ * Partition Resolver
+ */
+ @Test
+ public void testCreateRegionWithPartitionResolver() throws IOException {
+ setUpJmxManagerOnVm0ThenConnect(null);
+ VM vm = Host.getHost(0).getVM(1);
+ // Create a cache in vm 1
+ vm.invoke(() -> {
+ assertNotNull(getCache());
+ });
+
+ ClassBuilder classBuilder = new ClassBuilder();
+ // classBuilder.addToClassPath(".");
+ final File prJarFile = new File(temporaryFolder.getRoot().getCanonicalPath() + File.separator,
+ "myPartitionResolver.jar");
+ this.filesToBeDeleted.add(prJarFile.getAbsolutePath());
+ byte[] jarBytes =
+ classBuilder.createJarFromClassContent("com/cadrdunit/TestPartitionResolver", PR_STRING);
+ writeJarBytesToFile(prJarFile, jarBytes);
+
+ CommandResult cmdResult = executeCommand("deploy --jar=" + prJarFile.getAbsolutePath());
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+
+ // Create a region with an unrecognized compressor
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "regionWithPartitionResolver");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER,
+ "com.cadrdunit.TestPartitionResolver");
+ CommandResult cmdResult1 = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.OK, cmdResult1.getStatus());
+
+ // Assert that our region was not created
+ vm.invoke(() -> {
+ Region region = getCache().getRegion("regionWithPartitionResolver");
+ assertNotNull(region);
+
+ PartitionedRegion pr = (PartitionedRegion) region;
+ PartitionAttributes partitionAttributes = pr.getPartitionAttributes();
+ assertNotNull(partitionAttributes);
+ PartitionResolver partitionResolver = partitionAttributes.getPartitionResolver();
+ assertNotNull(partitionResolver);
+ assertEquals("TestPartitionResolver", partitionResolver.getName());
+ });
+
+ vm.invoke(() -> {
+ getCache().getRegion("regionWithPartitionResolver").destroyRegion();
+ });
+ }
+
+ @Test
+ public void testCreateRegionWithInvalidPartitionResolver() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+ VM vm = Host.getHost(0).getVM(1);
+ // Create a cache in vm 1
+ vm.invoke(() -> {
+ assertNotNull(getCache());
+ });
+
+ // Create a region with an unrecognized compressor
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
+ "testCreateRegionWithInvalidPartitionResolver");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ // Assert that our region was not created
+ vm.invoke(() -> {
+ Region region = getCache().getRegion("testCreateRegionWithInvalidPartitionResolver");
+ assertNull(region);
+ });
+ }
+
+ /**
+ * Test Description Try creating region of type REPLICATED and specify partition resolver Region
+ * Creation should fail.
+ */
+ @Test
+ public void testCreateRegionForReplicatedRegionWithParitionResolver() {
+ setUpJmxManagerOnVm0ThenConnect(null);
+ VM vm = Host.getHost(0).getVM(1);
+ // Create a cache in vm 1
+ vm.invoke(() -> {
+ assertNotNull(getCache());
+ });
+
+ // Create a region with an unrecognized compressor
+ CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
+ "testCreateRegionForReplicatedRegionWithParitionResolver");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
+ commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
+ CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
+ assertEquals(Result.Status.ERROR, cmdResult.getStatus());
+
+ // Assert that our region was not created
+ vm.invoke(() -> {
+ Region region =
+ getCache().getRegion("testCreateRegionForReplicatedRegionWithParitionResolver");
+ assertNull(region);
+ });
+ }
+
+
@Override
protected final void preTearDownCliCommandTestBase() throws Exception {
for (String path : this.filesToBeDeleted) {
@@ -273,4 +1369,69 @@ public class CreateAlterDestroyRegionCommandsDUnitTest extends CliCommandTestBas
}
this.filesToBeDeleted.clear();
}
+
+ /**
+ * Deploys JAR files which contain classes to be instantiated by the "alter region" test.
+ */
+ private void deployJarFilesForRegionAlter() throws IOException {
+ ClassBuilder classBuilder = new ClassBuilder();
+ final File jarFile1 = new File(new File(".").getAbsolutePath(), "testAlterRegion1.jar");
+ this.filesToBeDeleted.add(jarFile1.getAbsolutePath());
+ final File jarFile2 = new File(new File(".").getAbsolutePath(), "testAlterRegion2.jar");
+ this.filesToBeDeleted.add(jarFile2.getAbsolutePath());
+ final File jarFile3 = new File(new File(".").getAbsolutePath(), "testAlterRegion3.jar");
+ this.filesToBeDeleted.add(jarFile3.getAbsolutePath());
+ final File jarFile4 = new File(new File(".").getAbsolutePath(), "testAlterRegion4.jar");
+ this.filesToBeDeleted.add(jarFile4.getAbsolutePath());
+ final File jarFile5 = new File(new File(".").getAbsolutePath(), "testAlterRegion5.jar");
+ this.filesToBeDeleted.add(jarFile5.getAbsolutePath());
+
+ byte[] jarBytes =
+ classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerA",
+ "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
+ + "public class RegionAlterCacheListenerA extends CacheListenerAdapter {}");
+ writeJarBytesToFile(jarFile1, jarBytes);
+ CommandResult cmdResult = executeCommand("deploy --jar=testAlterRegion1.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerB",
+ "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
+ + "public class RegionAlterCacheListenerB extends CacheListenerAdapter {}");
+ writeJarBytesToFile(jarFile2, jarBytes);
+ cmdResult = executeCommand("deploy --jar=testAlterRegion2.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheListenerC",
+ "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheListenerAdapter;"
+ + "public class RegionAlterCacheListenerC extends CacheListenerAdapter {}");
+ writeJarBytesToFile(jarFile3, jarBytes);
+ cmdResult = executeCommand("deploy --jar=testAlterRegion3.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheLoader",
+ "package com.cadrdunit;" + "import org.apache.geode.cache.CacheLoader;"
+ + "import org.apache.geode.cache.CacheLoaderException;"
+ + "import org.apache.geode.cache.LoaderHelper;"
+ + "public class RegionAlterCacheLoader implements CacheLoader {"
+ + "public void close() {}"
+ + "public Object load(LoaderHelper helper) throws CacheLoaderException {return null;}}");
+ writeJarBytesToFile(jarFile4, jarBytes);
+ cmdResult = executeCommand("deploy --jar=testAlterRegion4.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+
+ jarBytes = classBuilder.createJarFromClassContent("com/cadrdunit/RegionAlterCacheWriter",
+ "package com.cadrdunit;" + "import org.apache.geode.cache.util.CacheWriterAdapter;"
+ + "public class RegionAlterCacheWriter extends CacheWriterAdapter {}");
+ writeJarBytesToFile(jarFile5, jarBytes);
+ cmdResult = executeCommand("deploy --jar=testAlterRegion5.jar");
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ }
+
+ private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
+ final OutputStream outStream = new FileOutputStream(jarFile);
+ outStream.write(jarBytes);
+ outStream.flush();
+ outStream.close();
+ }
+
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
new file mode 100644
index 0000000..85b660d
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommandsTest.java
@@ -0,0 +1,53 @@
+/*
+ * 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.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.mockito.Mockito;
+
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.test.dunit.rules.GfshParserRule;
+import org.apache.geode.test.junit.categories.IntegrationTest;
+
+@Category(IntegrationTest.class)
+public class CreateAlterDestroyRegionCommandsTest {
+
+ @Rule
+ public GfshParserRule parser = new GfshParserRule();
+
+ @Test
+ public void testCreateRegionWithInvalidPartitionResolver() throws Exception {
+ InternalCache cache = mock(InternalCache.class);
+ DistributedSystemMXBean dsMBean = mock(DistributedSystemMXBean.class);
+ CreateAlterDestroyRegionCommands spy = Mockito.spy(CreateAlterDestroyRegionCommands.class);
+
+ doReturn(cache).when(spy).getCache();
+ doReturn(dsMBean).when(spy).getDSMBean(cache);
+
+ String command = "create region --name=region3 --type=PARTITION --partition-resolver=Foo";
+
+ assertThatThrownBy(() -> parser.executeCommandWithInstance(spy, command))
+ .hasMessageContaining("Foo is an invalid Partition Resolver");
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
deleted file mode 100644
index 04168d5..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandDUnitTest.java
+++ /dev/null
@@ -1,318 +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.test.dunit.LogWriterUtils.getLogWriter;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.List;
-import java.util.concurrent.CopyOnWriteArrayList;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.PartitionAttributes;
-import org.apache.geode.cache.PartitionResolver;
-import org.apache.geode.cache.Region;
-import org.apache.geode.compression.SnappyCompressor;
-import org.apache.geode.internal.ClassBuilder;
-import org.apache.geode.internal.cache.PartitionedRegion;
-import org.apache.geode.internal.cache.RegionEntryContext;
-import org.apache.geode.management.cli.Result;
-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.VM;
-import org.apache.geode.test.junit.categories.DistributedTest;
-import org.apache.geode.test.junit.categories.FlakyTest;
-
-@Category(DistributedTest.class)
-public class CreateRegionCommandDUnitTest extends CliCommandTestBase {
- private final List<String> filesToBeDeleted = new CopyOnWriteArrayList<String>();
-
- /**
- * Asserts that the "compressor" option for the "create region" command succeeds for a recognized
- * compressor.
- */
- @Test
- public void testCreateRegionWithGoodCompressor() {
- setUpJmxManagerOnVm0ThenConnect(null);
- VM vm = Host.getHost(0).getVM(1);
-
- // Create a cache in vm 1
- vm.invoke(() -> {
- assertNotNull(getCache());
- });
-
- // Run create region command with compression
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR,
- RegionEntryContext.DEFAULT_COMPRESSION_PROVIDER);
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- // Make sure our region exists with compression enabled
- vm.invoke(() -> {
- Region region = getCache().getRegion("compressedRegion");
- assertNotNull(region);
- assertTrue(
- SnappyCompressor.getDefaultInstance().equals(region.getAttributes().getCompressor()));
- });
-
- // cleanup
- commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
- commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "compressedRegion");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- }
-
- /**
- * Asserts that the "compressor" option for the "create region" command fails for an unrecognized
- * compressorc.
- */
- @Test
- public void testCreateRegionWithBadCompressor() {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- VM vm = Host.getHost(0).getVM(1);
-
- // Create a cache in vm 1
- vm.invoke(() -> {
- assertNotNull(getCache());
- });
-
- // Create a region with an unrecognized compressor
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "compressedRegion");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__COMPRESSOR, "BAD_COMPRESSOR");
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- // Assert that our region was not created
- vm.invoke(() -> {
- Region region = getCache().getRegion("compressedRegion");
- assertNull(region);
- });
- }
-
- /**
- * Asserts that a missing "compressor" option for the "create region" command results in a region
- * with no compression.
- */
- @Test
- public void testCreateRegionWithNoCompressor() {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- VM vm = Host.getHost(0).getVM(1);
-
- // Create a cache in vm 1
- vm.invoke(() -> {
- assertNotNull(getCache());
- });
-
- // Create a region with no compression
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "testRegion");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- // Assert that our newly created region has no compression
- vm.invoke(() -> {
- Region region = getCache().getRegion("testRegion");
- assertNotNull(region);
- assertNull(region.getAttributes().getCompressor());
- });
-
- // Cleanup
- commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
- commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, "testRegion");
- cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- }
-
- @Category(FlakyTest.class) // GEODE-973: random ports, BindException,
- // java.rmi.server.ExportException: Port already in use
- @Test
- public void testCreateRegion46391() throws IOException {
- setUpJmxManagerOnVm0ThenConnect(null); // GEODE-973: getRandomAvailablePort
- String region46391 = "region46391";
- String command = CliStrings.CREATE_REGION + " --" + CliStrings.CREATE_REGION__REGION + "="
- + region46391 + " --" + CliStrings.CREATE_REGION__REGIONSHORTCUT + "=REPLICATE";
-
- getLogWriter().info("testCreateRegion46391 create region command=" + command);
-
- CommandResult cmdResult = executeCommand(command);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- command = CliStrings.PUT + " --" + CliStrings.PUT__KEY + "=k1" + " --" + CliStrings.PUT__VALUE
- + "=k1" + " --" + CliStrings.PUT__REGIONNAME + "=" + region46391;
-
- getLogWriter().info("testCreateRegion46391 put command=" + command);
-
- CommandResult cmdResult2 = executeCommand(command);
- assertEquals(Result.Status.OK, cmdResult2.getStatus());
-
- getLogWriter().info("testCreateRegion46391 cmdResult2=" + commandResultToString(cmdResult2));
- String str1 = "Result : true";
- String str2 = "Key : k1";
- String str3 = "Key Class : java.lang.String";
- String str4 = "Value Class : java.lang.String";
- String str5 = "Old Value : <NULL>";
-
- assertTrue(
- commandResultToString(cmdResult).contains("Region \"/" + region46391 + "\" created on"));
-
- assertTrue(commandResultToString(cmdResult2).contains(str1));
- assertTrue(commandResultToString(cmdResult2).contains(str2));
- assertTrue(commandResultToString(cmdResult2).contains(str3));
- assertTrue(commandResultToString(cmdResult2).contains(str4));
- assertTrue(commandResultToString(cmdResult2).contains(str5));
- }
-
- /**
- * Test Description 1. Deploy a JAR with Custom Partition Resolver 2. Create Region with Partition
- * Resolver 3. Region should get created with no Errors 4. Verify Region Partition Attributes for
- * Partition Resolver
- */
- @Test
- public void testCreateRegionWithPartitionResolver() throws IOException {
- setUpJmxManagerOnVm0ThenConnect(null);
- VM vm = Host.getHost(0).getVM(1);
- // Create a cache in vm 1
- vm.invoke(() -> {
- assertNotNull(getCache());
- });
-
- ClassBuilder classBuilder = new ClassBuilder();
- // classBuilder.addToClassPath(".");
- final File prJarFile = new File(temporaryFolder.getRoot().getCanonicalPath() + File.separator,
- "myPartitionResolver.jar");
- this.filesToBeDeleted.add(prJarFile.getAbsolutePath());
- String PR_STRING = " package com.cadrdunit;"
- + " public class TestPartitionResolver implements org.apache.geode.cache.PartitionResolver { "
- + " @Override" + " public void close() {" + " }" + " @Override"
- + " public Object getRoutingObject(org.apache.geode.cache.EntryOperation opDetails) { "
- + " return null; " + " }" + " @Override" + " public String getName() { "
- + " return \"TestPartitionResolver\";" + " }" + " }";
- byte[] jarBytes =
- classBuilder.createJarFromClassContent("com/cadrdunit/TestPartitionResolver", PR_STRING);
- writeJarBytesToFile(prJarFile, jarBytes);
-
- CommandResult cmdResult = executeCommand("deploy --jar=" + prJarFile.getAbsolutePath());
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
-
- // Create a region with an unrecognized compressor
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION, "regionWithPartitionResolver");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER,
- "com.cadrdunit.TestPartitionResolver");
- CommandResult cmdResult1 = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.OK, cmdResult1.getStatus());
-
- // Assert that our region was not created
- vm.invoke(() -> {
- Region region = getCache().getRegion("regionWithPartitionResolver");
- assertNotNull(region);
-
- PartitionedRegion pr = (PartitionedRegion) region;
- PartitionAttributes partitionAttributes = pr.getPartitionAttributes();
- assertNotNull(partitionAttributes);
- PartitionResolver partitionResolver = partitionAttributes.getPartitionResolver();
- assertNotNull(partitionResolver);
- assertEquals("TestPartitionResolver", partitionResolver.getName());
- });
-
- vm.invoke(() -> {
- getCache().getRegion("regionWithPartitionResolver").destroyRegion();
- });
- }
-
- @Test
- public void testCreateRegionWithInvalidPartitionResolver() {
- setUpJmxManagerOnVm0ThenConnect(null);
- VM vm = Host.getHost(0).getVM(1);
- // Create a cache in vm 1
- vm.invoke(() -> {
- assertNotNull(getCache());
- });
-
- // Create a region with an unrecognized compressor
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
- "testCreateRegionWithInvalidPartitionResolver");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "PARTITION");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- // Assert that our region was not created
- vm.invoke(() -> {
- Region region = getCache().getRegion("testCreateRegionWithInvalidPartitionResolver");
- assertNull(region);
- });
- }
-
- /**
- * Test Description Try creating region of type REPLICATED and specify partition resolver Region
- * Creation should fail.
- */
- @Test
- public void testCreateRegionForReplicatedRegionWithParitionResolver() {
- setUpJmxManagerOnVm0ThenConnect(null);
- VM vm = Host.getHost(0).getVM(1);
- // Create a cache in vm 1
- vm.invoke(() -> {
- assertNotNull(getCache());
- });
-
- // Create a region with an unrecognized compressor
- CommandStringBuilder commandStringBuilder = new CommandStringBuilder(CliStrings.CREATE_REGION);
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGION,
- "testCreateRegionForReplicatedRegionWithParitionResolver");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__REGIONSHORTCUT, "REPLICATE");
- commandStringBuilder.addOption(CliStrings.CREATE_REGION__PARTITION_RESOLVER, "a.b.c.d");
- CommandResult cmdResult = executeCommand(commandStringBuilder.toString());
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- // Assert that our region was not created
- vm.invoke(() -> {
- Region region =
- getCache().getRegion("testCreateRegionForReplicatedRegionWithParitionResolver");
- assertNull(region);
- });
- }
-
- private void writeJarBytesToFile(File jarFile, byte[] jarBytes) throws IOException {
- final OutputStream outStream = new FileOutputStream(jarFile);
- outStream.write(jarBytes);
- outStream.flush();
- outStream.close();
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java
deleted file mode 100644
index 5011d78..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommandTest.java
+++ /dev/null
@@ -1,58 +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.management.internal.cli.commands.CreateRegionCommand.regionExists;
-import static org.assertj.core.api.Assertions.assertThat;
-import static org.assertj.core.api.Assertions.assertThatThrownBy;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.mockito.Mockito;
-
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.test.dunit.rules.GfshParserRule;
-import org.apache.geode.test.junit.categories.IntegrationTest;
-
-@Category(IntegrationTest.class)
-public class CreateRegionCommandTest {
- @Rule
- public GfshParserRule parser = new GfshParserRule();
-
- @Test
- public void testCreateRegionWithInvalidPartitionResolver() throws Exception {
- InternalCache cache = mock(InternalCache.class);
- DistributedSystemMXBean dsMBean = mock(DistributedSystemMXBean.class);
- CreateRegionCommand spy = Mockito.spy(CreateRegionCommand.class);
-
- doReturn(cache).when(spy).getCache();
- doReturn(dsMBean).when(spy).getDSMBean(cache);
-
- String command = "create region --name=region3 --type=PARTITION --partition-resolver=Foo";
- assertThatThrownBy(() -> parser.executeCommandWithInstance(spy, command))
- .hasMessageContaining("Foo is an invalid Partition Resolver");
- }
-
- @Test
- public void testRegionExistsReturnsCorrectValue() throws Exception {
- InternalCache cache = mock(InternalCache.class);
- assertThat(regionExists(cache, null)).isFalse();
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployCommandsDUnitTest.java
index 76541e2..89148d7 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DeployCommandsDUnitTest.java
@@ -36,7 +36,7 @@ import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
/**
- * Unit tests for DeployCommand, UndeployCommand, ListDeployedCommand
+ * Unit tests for the DeployCommands class
*
* @since GemFire 7.0
*/
[12/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
new file mode 100644
index 0000000..c5d859e
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommands.java
@@ -0,0 +1,420 @@
+/*
+ * 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 java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.DurableCqNamesResult;
+import org.apache.geode.management.internal.cli.domain.MemberResult;
+import org.apache.geode.management.internal.cli.domain.SubscriptionQueueSizeResult;
+import org.apache.geode.management.internal.cli.functions.CloseDurableClientFunction;
+import org.apache.geode.management.internal.cli.functions.CloseDurableCqFunction;
+import org.apache.geode.management.internal.cli.functions.GetSubscriptionQueueSizeFunction;
+import org.apache.geode.management.internal.cli.functions.ListDurableCqNamesFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+/**
+ * The DurableClientCommands class encapsulates all GemFire shell (Gfsh) commands related to durable
+ * clients and cqs defined in GemFire.
+ * </p>
+ */
+@SuppressWarnings("unused")
+public class DurableClientCommands implements GfshCommand {
+
+ private static final ListDurableCqNamesFunction listDurableCqNamesFunction =
+ new ListDurableCqNamesFunction();
+ private static final CloseDurableClientFunction closeDurableClientFunction =
+ new CloseDurableClientFunction();
+ private static final CloseDurableCqFunction closeDurableCqFunction = new CloseDurableCqFunction();
+ private static final GetSubscriptionQueueSizeFunction countDurableCqEvents =
+ new GetSubscriptionQueueSizeFunction();
+
+ @CliCommand(value = CliStrings.LIST_DURABLE_CQS, help = CliStrings.LIST_DURABLE_CQS__HELP)
+ @CliMetaData()
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listDurableClientCqs(
+ @CliOption(key = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID, mandatory = true,
+ help = CliStrings.LIST_DURABLE_CQS__DURABLECLIENTID__HELP) final String durableClientId,
+
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ help = CliStrings.LIST_DURABLE_CQS__MEMBER__HELP,
+ optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.LIST_DURABLE_CQS__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+ Result result;
+ try {
+
+ boolean noResults = true;
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ final ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(new ListDurableCqNamesFunction(), durableClientId, targetMembers);
+ final List<DurableCqNamesResult> results = (List<DurableCqNamesResult>) rc.getResult();
+ Map<String, List<String>> memberCqNamesMap = new TreeMap<>();
+ Map<String, List<String>> errorMessageNodes = new HashMap<>();
+ Map<String, List<String>> exceptionMessageNodes = new HashMap<>();
+
+ for (DurableCqNamesResult memberResult : results) {
+ if (memberResult != null) {
+ if (memberResult.isSuccessful()) {
+ memberCqNamesMap.put(memberResult.getMemberNameOrId(), memberResult.getCqNamesList());
+ } else {
+ if (memberResult.isOpPossible()) {
+ groupByMessage(memberResult.getExceptionMessage(), memberResult.getMemberNameOrId(),
+ exceptionMessageNodes);
+ } else {
+ groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
+ errorMessageNodes);
+ }
+ }
+ }
+ }
+
+ if (!memberCqNamesMap.isEmpty()) {
+ TabularResultData table = ResultBuilder.createTabularResultData();
+ Set<String> members = memberCqNamesMap.keySet();
+
+ for (String member : members) {
+ boolean isFirst = true;
+ List<String> cqNames = memberCqNamesMap.get(member);
+ for (String cqName : cqNames) {
+ if (isFirst) {
+ isFirst = false;
+ table.accumulate(CliStrings.MEMBER, member);
+ } else {
+ table.accumulate(CliStrings.MEMBER, "");
+ }
+ table.accumulate(CliStrings.LIST_DURABLE_CQS__NAME, cqName);
+ }
+ }
+ result = ResultBuilder.buildResult(table);
+ } else {
+ String errorHeader =
+ CliStrings.format(CliStrings.LIST_DURABLE_CQS__FAILURE__HEADER, durableClientId);
+ result = ResultBuilder.buildResult(
+ buildFailureData(null, exceptionMessageNodes, errorMessageNodes, errorHeader));
+ }
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.COUNT_DURABLE_CQ_EVENTS,
+ help = CliStrings.COUNT_DURABLE_CQ_EVENTS__HELP)
+ @CliMetaData()
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result countDurableCqEvents(
+ @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, mandatory = true,
+ help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
+ @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME,
+ help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME__HELP) final String cqName,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ help = CliStrings.COUNT_DURABLE_CQ_EVENTS__MEMBER__HELP,
+ optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+
+ Result result;
+ try {
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ String[] params = new String[2];
+ params[0] = durableClientId;
+ params[1] = cqName;
+ final ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(new GetSubscriptionQueueSizeFunction(), params, targetMembers);
+ final List<SubscriptionQueueSizeResult> funcResults =
+ (List<SubscriptionQueueSizeResult>) rc.getResult();
+
+ String queueSizeColumnName;
+
+ if (cqName != null && !cqName.isEmpty()) {
+ queueSizeColumnName = CliStrings
+ .format(CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, cqName);
+ } else {
+ queueSizeColumnName = CliStrings.format(
+ CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, durableClientId);
+ }
+ result = buildTableResultForQueueSize(funcResults, queueSizeColumnName);
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.CLOSE_DURABLE_CLIENTS,
+ help = CliStrings.CLOSE_DURABLE_CLIENTS__HELP)
+ @CliMetaData()
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ public Result closeDurableClient(
+ @CliOption(key = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID, mandatory = true,
+ help = CliStrings.CLOSE_DURABLE_CLIENTS__CLIENT__ID__HELP) final String durableClientId,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ help = CliStrings.CLOSE_DURABLE_CLIENTS__MEMBER__HELP,
+ optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+
+ Result result;
+ try {
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ final ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(new CloseDurableClientFunction(), durableClientId, targetMembers);
+ final List<MemberResult> results = (List<MemberResult>) rc.getResult();
+ String failureHeader =
+ CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__FAILURE__HEADER, durableClientId);
+ String successHeader =
+ CliStrings.format(CliStrings.CLOSE_DURABLE_CLIENTS__SUCCESS, durableClientId);
+ result = buildResult(results, successHeader, failureHeader);
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+ return result;
+ }
+
+
+ @CliCommand(value = CliStrings.CLOSE_DURABLE_CQS, help = CliStrings.CLOSE_DURABLE_CQS__HELP)
+ @CliMetaData()
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE,
+ target = Target.QUERY)
+ public Result closeDurableCqs(@CliOption(key = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID,
+ mandatory = true,
+ help = CliStrings.CLOSE_DURABLE_CQS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
+
+ @CliOption(key = CliStrings.CLOSE_DURABLE_CQS__NAME, mandatory = true,
+ help = CliStrings.CLOSE_DURABLE_CQS__NAME__HELP) final String cqName,
+
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ help = CliStrings.CLOSE_DURABLE_CQS__MEMBER__HELP,
+ optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
+
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.CLOSE_DURABLE_CQS__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
+ Result result;
+ try {
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ String[] params = new String[2];
+ params[0] = durableClientId;
+ params[1] = cqName;
+
+ final ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(new CloseDurableCqFunction(), params, targetMembers);
+ final List<MemberResult> results = (List<MemberResult>) rc.getResult();
+ String failureHeader =
+ CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__FAILURE__HEADER, cqName, durableClientId);
+ String successHeader =
+ CliStrings.format(CliStrings.CLOSE_DURABLE_CQS__SUCCESS, cqName, durableClientId);
+ result = buildResult(results, successHeader, failureHeader);
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+ return result;
+ }
+
+
+ private Result buildResult(List<MemberResult> results, String successHeader,
+ String failureHeader) {
+ Result result;
+ boolean failure = true;
+ boolean partialFailure = false;
+ Map<String, List<String>> errorMap = new HashMap<>();
+ Map<String, List<String>> successMap = new HashMap<>();
+ Map<String, List<String>> exceptionMap = new HashMap<>();
+
+ /*
+ * Aggregate the results from the members
+ */
+ for (MemberResult memberResult : results) {
+
+ if (memberResult.isSuccessful()) {
+ failure = false;
+ groupByMessage(memberResult.getSuccessMessage(), memberResult.getMemberNameOrId(),
+ successMap);
+ } else {
+
+ if (memberResult.isOpPossible()) {
+ partialFailure = true;
+ groupByMessage(memberResult.getExceptionMessage(), memberResult.getMemberNameOrId(),
+ exceptionMap);
+
+ } else {
+ groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
+ errorMap);
+ }
+ }
+ }
+
+ if (!failure && !partialFailure) {
+ result = ResultBuilder.buildResult(buildSuccessData(successMap));
+ } else {
+ result = ResultBuilder
+ .buildResult(buildFailureData(successMap, exceptionMap, errorMap, failureHeader));
+ }
+ return result;
+ }
+
+ private Result buildTableResultForQueueSize(List<SubscriptionQueueSizeResult> results,
+ String queueSizeColumnName) {
+ Result result;
+ boolean failure = true;
+
+ Map<String, List<String>> failureMap = new HashMap<>();
+ Map<String, Long> memberQueueSizeTable = new TreeMap<>();
+
+ /*
+ * Aggregate the results from the members
+ */
+ for (SubscriptionQueueSizeResult memberResult : results) {
+
+ if (memberResult.isSuccessful()) {
+ failure = false;
+ memberQueueSizeTable.put(memberResult.getMemberNameOrId(),
+ memberResult.getSubscriptionQueueSize());
+ } else {
+ groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
+ failureMap);
+ }
+ }
+
+ if (!failure) {
+ TabularResultData table = ResultBuilder.createTabularResultData();
+
+ Set<String> members = memberQueueSizeTable.keySet();
+
+ for (String member : members) {
+ long queueSize = memberQueueSizeTable.get(member);
+ table.accumulate(CliStrings.MEMBER, member);
+ table.accumulate(queueSizeColumnName, queueSize);
+ }
+ result = ResultBuilder.buildResult(table);
+
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ buildErrorResult(erd, failureMap);
+ result = ResultBuilder.buildResult(erd);
+ }
+ return result;
+ }
+
+ private void groupByMessage(String message, String memberNameOrId,
+ Map<String, List<String>> map) {
+ List<String> members = map.get(message);
+
+ if (members == null) {
+ members = new LinkedList<>();
+ }
+ members.add(memberNameOrId);
+ map.put(message, members);
+ }
+
+
+ private InfoResultData buildSuccessData(Map<String, List<String>> successMap) {
+ InfoResultData ird = ResultBuilder.createInfoResultData();
+ Set<String> successMessages = successMap.keySet();
+
+ for (String successMessage : successMessages) {
+ ird.addLine(CliStrings.format(CliStrings.ACTION_SUCCEEDED_ON_MEMBER, successMessage));
+
+ List<String> successfulMembers = successMap.get(successMessage);
+ int num = 0;
+ for (String member : successfulMembers) {
+ ird.addLine("" + ++num + "." + member);
+ }
+ ird.addLine("\n");
+ }
+ return ird;
+ }
+
+ private ErrorResultData buildFailureData(Map<String, List<String>> successMap,
+ Map<String, List<String>> exceptionMap, Map<String, List<String>> errorMap,
+ String errorHeader) {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ buildErrorResult(erd, successMap);
+ erd.addLine("\n");
+ erd.addLine(errorHeader);
+ buildErrorResult(erd, exceptionMap);
+ buildErrorResult(erd, errorMap);
+ return erd;
+ }
+
+ private void buildErrorResult(ErrorResultData erd, Map<String, List<String>> resultMap) {
+ if (resultMap != null && !resultMap.isEmpty()) {
+ Set<String> messages = resultMap.keySet();
+
+ for (String message : messages) {
+ erd.addLine("\n");
+ erd.addLine(message);
+ erd.addLine(CliStrings.OCCURRED_ON_MEMBERS);
+ List<String> members = resultMap.get(message);
+ int num = 0;
+ for (String member : members) {
+ ++num;
+ erd.addLine("" + num + "." + member);
+ }
+ }
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java
deleted file mode 100644
index 743602a..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DurableClientCommandsResultBuilder.java
+++ /dev/null
@@ -1,164 +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 java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.domain.MemberResult;
-import org.apache.geode.management.internal.cli.domain.SubscriptionQueueSizeResult;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-
-public class DurableClientCommandsResultBuilder {
- public Result buildResult(List<MemberResult> results, String successHeader,
- String failureHeader) {
- Result result;
- boolean failure = true;
- boolean partialFailure = false;
- Map<String, List<String>> errorMap = new HashMap<>();
- Map<String, List<String>> successMap = new HashMap<>();
- Map<String, List<String>> exceptionMap = new HashMap<>();
-
- // Aggregate the results from the members
- for (MemberResult memberResult : results) {
- if (memberResult.isSuccessful()) {
- failure = false;
- groupByMessage(memberResult.getSuccessMessage(), memberResult.getMemberNameOrId(),
- successMap);
- } else {
- if (memberResult.isOpPossible()) {
- partialFailure = true;
- groupByMessage(memberResult.getExceptionMessage(), memberResult.getMemberNameOrId(),
- exceptionMap);
- } else {
- groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
- errorMap);
- }
- }
- }
-
- if (!failure && !partialFailure) {
- result = ResultBuilder.buildResult(buildSuccessData(successMap));
- } else {
- result = ResultBuilder
- .buildResult(buildFailureData(successMap, exceptionMap, errorMap, failureHeader));
- }
- return result;
- }
-
- Result buildTableResultForQueueSize(List<SubscriptionQueueSizeResult> results,
- String queueSizeColumnName) {
- Result result;
- boolean failure = true;
-
- Map<String, List<String>> failureMap = new HashMap<>();
- Map<String, Long> memberQueueSizeTable = new TreeMap<>();
-
- // Aggregate the results from the members
- for (SubscriptionQueueSizeResult memberResult : results) {
- if (memberResult.isSuccessful()) {
- failure = false;
- memberQueueSizeTable.put(memberResult.getMemberNameOrId(),
- memberResult.getSubscriptionQueueSize());
- } else {
- groupByMessage(memberResult.getErrorMessage(), memberResult.getMemberNameOrId(),
- failureMap);
- }
- }
-
- if (!failure) {
- TabularResultData table = ResultBuilder.createTabularResultData();
- Set<String> members = memberQueueSizeTable.keySet();
-
- for (String member : members) {
- long queueSize = memberQueueSizeTable.get(member);
- table.accumulate(CliStrings.MEMBER, member);
- table.accumulate(queueSizeColumnName, queueSize);
- }
- result = ResultBuilder.buildResult(table);
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- buildErrorResult(erd, failureMap);
- result = ResultBuilder.buildResult(erd);
- }
- return result;
- }
-
- void groupByMessage(String message, String memberNameOrId, Map<String, List<String>> map) {
- List<String> members = map.get(message);
- if (members == null) {
- members = new LinkedList<>();
- }
- members.add(memberNameOrId);
- map.put(message, members);
- }
-
-
- private InfoResultData buildSuccessData(Map<String, List<String>> successMap) {
- InfoResultData ird = ResultBuilder.createInfoResultData();
- Set<String> successMessages = successMap.keySet();
-
- for (String successMessage : successMessages) {
- ird.addLine(CliStrings.format(CliStrings.ACTION_SUCCEEDED_ON_MEMBER, successMessage));
- List<String> successfulMembers = successMap.get(successMessage);
- int num = 0;
- for (String member : successfulMembers) {
- ird.addLine("" + ++num + "." + member);
- }
- ird.addLine("\n");
- }
- return ird;
- }
-
- ErrorResultData buildFailureData(Map<String, List<String>> successMap,
- Map<String, List<String>> exceptionMap, Map<String, List<String>> errorMap,
- String errorHeader) {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- buildErrorResult(erd, successMap);
- erd.addLine("\n");
- erd.addLine(errorHeader);
- buildErrorResult(erd, exceptionMap);
- buildErrorResult(erd, errorMap);
- return erd;
- }
-
- private void buildErrorResult(ErrorResultData erd, Map<String, List<String>> resultMap) {
- if (resultMap != null && !resultMap.isEmpty()) {
- Set<String> messages = resultMap.keySet();
-
- for (String message : messages) {
- erd.addLine("\n");
- erd.addLine(message);
- erd.addLine(CliStrings.OCCURRED_ON_MEMBERS);
- List<String> members = resultMap.get(message);
- int num = 0;
- for (String member : members) {
- ++num;
- erd.addLine("" + num + "." + member);
- }
- }
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
deleted file mode 100644
index dad9742..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExecuteFunctionCommand.java
+++ /dev/null
@@ -1,330 +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 java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Stream;
-
-import org.apache.commons.lang.BooleanUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.Function;
-import org.apache.geode.cache.execute.FunctionException;
-import org.apache.geode.cache.execute.FunctionService;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.ClassPathLoader;
-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.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.MBeanJMXAdapter;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.UserFunctionExecution;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ExecuteFunctionCommand implements GfshCommand {
- @CliCommand(value = CliStrings.EXECUTE_FUNCTION, help = CliStrings.EXECUTE_FUNCTION__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
- @ResourceOperation(resource = ResourcePermission.Resource.DATA,
- operation = ResourcePermission.Operation.WRITE)
- public Result executeFunction(
- // TODO: Add optioncontext for functionID
- @CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, mandatory = true,
- help = CliStrings.EXECUTE_FUNCTION__ID__HELP) String functionId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.EXECUTE_FUNCTION__ONGROUPS__HELP) String[] onGroups,
- @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.EXECUTE_FUNCTION__ONMEMBER__HELP) String onMember,
- @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONREGION,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.EXECUTE_FUNCTION__ONREGION__HELP) String onRegion,
- @CliOption(key = CliStrings.EXECUTE_FUNCTION__ARGUMENTS,
- help = CliStrings.EXECUTE_FUNCTION__ARGUMENTS__HELP) String[] arguments,
- @CliOption(key = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR,
- help = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR__HELP) String resultCollector,
- @CliOption(key = CliStrings.EXECUTE_FUNCTION__FILTER,
- help = CliStrings.EXECUTE_FUNCTION__FILTER__HELP) String filterString) {
- CompositeResultData executeFunctionResultTable = ResultBuilder.createCompositeResultData();
- TabularResultData resultTable = executeFunctionResultTable.addSection().addTable("Table1");
- String headerText = "Execution summary";
- resultTable.setHeader(headerText);
- ResultCollector resultCollectorInstance = null;
- Set<String> filters = new HashSet<>();
- Execution execution;
- if (functionId != null) {
- functionId = functionId.trim();
- }
- if (onRegion != null) {
- onRegion = onRegion.trim();
- }
- if (onMember != null) {
- onMember = onMember.trim();
- }
- if (filterString != null) {
- filterString = filterString.trim();
- }
-
- try {
- // validate otherwise return right away. no need to process anything
- if (functionId == null || functionId.length() == 0) {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MISSING_FUNCTIONID);
- return ResultBuilder.buildResult(errorResultData);
- }
-
- if (moreThanOneIsTrue(onRegion != null, onMember != null, onGroups != null)) {
- // Provide Only one of region/member/groups
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
- return ResultBuilder.buildResult(errorResultData);
- } else if ((onRegion == null || onRegion.length() == 0) && (filterString != null)) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MEMBER_SHOULD_NOT_HAVE_FILTER_FOR_EXECUTION);
- return ResultBuilder.buildResult(errorResultData);
- }
-
- InternalCache cache = getCache();
-
- if (resultCollector != null) {
- resultCollectorInstance =
- (ResultCollector) ClassPathLoader.getLatest().forName(resultCollector).newInstance();
- }
-
- if (filterString != null && filterString.length() > 0) {
- filters.add(filterString);
- }
-
- if (onRegion == null && onMember == null && onGroups == null) {
- // run function on all the members excluding locators bug#46113
- // if user wish to execute on locator then he can choose --member or --group option
- Set<DistributedMember> dsMembers = CliUtil.getAllNormalMembers(cache);
- if (dsMembers.size() > 0) {
- new UserFunctionExecution();
- LogWrapper.getInstance().info(CliStrings
- .format(CliStrings.EXECUTE_FUNCTION__MSG__EXECUTING_0_ON_ENTIRE_DS, functionId));
- for (DistributedMember member : dsMembers) {
- executeAndGetResults(functionId, null, resultCollector, arguments, member, resultTable,
- null);
- }
- return ResultBuilder.buildResult(resultTable);
- } else {
- return ResultBuilder
- .createUserErrorResult(CliStrings.EXECUTE_FUNCTION__MSG__DS_HAS_NO_MEMBERS);
- }
- } else if (onRegion != null && onRegion.length() > 0) {
- if (cache.getRegion(onRegion) == null) {
- // find a member where region is present
- DistributedRegionMXBean bean = ManagementService.getManagementService(getCache())
- .getDistributedRegionMXBean(onRegion);
- if (bean == null) {
- bean = ManagementService.getManagementService(getCache())
- .getDistributedRegionMXBean(Region.SEPARATOR + onRegion);
-
- if (bean == null) {
- return ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.EXECUTE_FUNCTION__MSG__MXBEAN_0_FOR_NOT_FOUND, onRegion));
- }
- }
-
- DistributedMember member = null;
- String[] membersName = bean.getMembers();
- Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
- Iterator it = dsMembers.iterator();
- boolean matchFound = false;
-
- if (membersName.length > 0) {
- while (it.hasNext() && !matchFound) {
- DistributedMember dsmember = (DistributedMember) it.next();
- for (String memberName : membersName) {
- if (MBeanJMXAdapter.getMemberNameOrId(dsmember).equals(memberName)) {
- member = dsmember;
- matchFound = true;
- break;
- }
- }
- }
- }
- if (matchFound) {
- executeAndGetResults(functionId, filterString, resultCollector, arguments, member,
- resultTable, onRegion);
- return ResultBuilder.buildResult(resultTable);
- } else {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER_REGION, " " + onRegion));
- }
- } else {
- execution = FunctionService.onRegion(cache.getRegion(onRegion));
- if (execution != null) {
- if (resultCollectorInstance != null) {
- execution = execution.withCollector(resultCollectorInstance);
- }
- if (filters.size() > 0) {
- execution = execution.withFilter(filters);
- }
- if (arguments != null && arguments.length > 0) {
- execution = execution.setArguments(arguments);
- }
-
- try {
- List<Object> results = (List<Object>) execution.execute(functionId).getResult();
- if (results.size() > 0) {
- StringBuilder strResult = new StringBuilder();
- for (Object obj : results) {
- strResult.append(obj);
- }
- toTabularResultData(resultTable,
- cache.getDistributedSystem().getDistributedMember().getId(),
- strResult.toString());
- }
- return ResultBuilder.buildResult(resultTable);
- } catch (FunctionException e) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
- functionId, onRegion, e.getMessage()));
- }
- } else {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
- functionId, onRegion,
- CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR));
- }
- }
- } else if (onGroups != null) {
- // execute on group members
- Set<DistributedMember> dsMembers = new HashSet<>();
- for (String grp : onGroups) {
- dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
- }
-
- if (dsMembers.size() > 0) {
- for (DistributedMember member : dsMembers) {
- executeAndGetResults(functionId, filterString, resultCollector, arguments, member,
- resultTable, onRegion);
- }
- return ResultBuilder.buildResult(resultTable);
- } else {
- StringBuilder grps = new StringBuilder();
- for (String grp : onGroups) {
- grps.append(grp);
- grps.append(", ");
- }
- return ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__GROUPS_0_HAS_NO_MEMBERS,
- grps.toString().substring(0, grps.toString().length() - 1)));
- }
- } else if (onMember != null && onMember.length() > 0) {
- DistributedMember member = CliUtil.getDistributedMemberByNameOrId(onMember); // fix for bug
- // 45658
- if (member != null) {
- executeAndGetResults(functionId, filterString, resultCollector, arguments, member,
- resultTable, onRegion);
- } else {
- toTabularResultData(resultTable, onMember, CliStrings
- .format(CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER + " " + onMember));
- }
- return ResultBuilder.buildResult(resultTable);
- }
- } catch (Exception e) {
- ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
- .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
- return ResultBuilder.buildResult(errorResultData);
- }
- return null;
- }
-
- private boolean moreThanOneIsTrue(Boolean... values) {
- return Stream.of(values).mapToInt(BooleanUtils::toInteger).sum() > 1;
- }
-
- private void executeAndGetResults(String functionId, String filterString, String resultCollector,
- String[] arguments, DistributedMember member, TabularResultData resultTable,
- String onRegion) {
- StringBuilder resultMessage = new StringBuilder();
- try {
- Function function = new UserFunctionExecution();
- Object[] args = new Object[5];
- args[0] = functionId;
- if (filterString != null) {
- args[1] = filterString;
- }
- if (resultCollector != null) {
- args[2] = resultCollector;
- }
- if (arguments != null && arguments.length > 0) {
- args[3] = "";
- for (String str : arguments) {
- // send via CSV separated value format
- if (str != null) {
- args[3] = args[3] + str + ",";
- }
- }
- }
- args[4] = onRegion;
-
- Execution execution = FunctionService.onMember(member).setArguments(args);
- if (execution != null) {
- List<Object> results = (List<Object>) execution.execute(function).getResult();
- if (results != null) {
- for (Object resultObj : results) {
- if (resultObj != null) {
- if (resultObj instanceof String) {
- resultMessage.append(((String) resultObj));
- } else if (resultObj instanceof Exception) {
- resultMessage.append(((Exception) resultObj).getMessage());
- } else {
- resultMessage.append(resultObj);
- }
- }
- }
- }
- toTabularResultData(resultTable, member.getId(), resultMessage.toString());
- } else {
- toTabularResultData(resultTable, member.getId(),
- CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR);
- }
- } catch (Exception e) {
- resultMessage.append(CliStrings.format(
- CliStrings.EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2,
- functionId, member.getId(), e.getMessage()));
- toTabularResultData(resultTable, member.getId(), resultMessage.toString());
- }
- }
-
- private void toTabularResultData(TabularResultData table, String memberId, String memberResult) {
- table.accumulate("Member ID/Name", memberId);
- table.accumulate("Function Execution Result", memberResult);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java
deleted file mode 100644
index 672ec88..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportConfigCommand.java
+++ /dev/null
@@ -1,159 +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 java.io.File;
-import java.io.IOException;
-import java.nio.file.Path;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.ExportConfigFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ExportConfigCommand implements GfshCommand {
- private final ExportConfigFunction exportConfigFunction = new ExportConfigFunction();
-
- /**
- * Export the cache configuration in XML format.
- *
- * @param member Member for which to write the configuration
- * @param group Group or groups for which to write the configuration
- * @return Results of the attempt to write the configuration
- */
- @CliCommand(value = {CliStrings.EXPORT_CONFIG}, help = CliStrings.EXPORT_CONFIG__HELP)
- @CliMetaData(
- interceptor = "org.apache.geode.management.internal.cli.commands.ExportConfigCommand$Interceptor",
- relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result exportConfig(
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.EXPORT_CONFIG__MEMBER__HELP) String[] member,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.EXPORT_CONFIG__GROUP__HELP) String[] group,
- @CliOption(key = {CliStrings.EXPORT_CONFIG__DIR},
- help = CliStrings.EXPORT_CONFIG__DIR__HELP) String dir) {
- InfoResultData infoData = ResultBuilder.createInfoResultData();
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, member);
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- try {
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(this.exportConfigFunction, null, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- infoData.addLine(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
- result.getMemberIdOrName(), result.getThrowable()));
- } else if (result.isSuccessful()) {
- String cacheFileName = result.getMemberIdOrName() + "-cache.xml";
- String propsFileName = result.getMemberIdOrName() + "-gf.properties";
- String[] fileContent = (String[]) result.getSerializables();
- infoData.addAsFile(cacheFileName, fileContent[0], "Downloading Cache XML file: {0}",
- false);
- infoData.addAsFile(propsFileName, fileContent[1], "Downloading properties file: {0}",
- false);
- }
- }
- return ResultBuilder.buildResult(infoData);
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- th.printStackTrace(System.err);
- return ResultBuilder
- .createGemFireErrorResult(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
- th.getClass().getName() + ": " + th.getMessage()));
- }
- }
-
- /**
- * Interceptor used by gfsh to intercept execution of export config command at "shell".
- */
- public static class Interceptor extends AbstractCliAroundInterceptor {
- private String saveDirString;
-
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- Map<String, String> paramValueMap = parseResult.getParamValueStrings();
- String dir = paramValueMap.get("dir");
- dir = (dir == null) ? null : dir.trim();
-
- File saveDirFile = new File(".");
- if (dir != null && !dir.isEmpty()) {
- saveDirFile = new File(dir);
- if (saveDirFile.exists()) {
- if (!saveDirFile.isDirectory())
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_A_DIRECTORY, dir));
- } else if (!saveDirFile.mkdirs()) {
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__CANNOT_CREATE_DIR, dir));
- }
- }
- try {
- if (!saveDirFile.canWrite()) {
- return ResultBuilder.createGemFireErrorResult(CliStrings.format(
- CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getCanonicalPath()));
- }
- } catch (IOException ioex) {
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getName()));
- }
-
- saveDirString = saveDirFile.getAbsolutePath();
- return ResultBuilder.createInfoResult("OK");
- }
-
- @Override
- public Result postExecution(GfshParseResult parseResult, Result commandResult, Path tempFile) {
- if (commandResult.hasIncomingFiles()) {
- try {
- commandResult.saveIncomingFiles(saveDirString);
- } catch (IOException ioex) {
- Gfsh.getCurrentInstance().logSevere("Unable to export config", ioex);
- }
- }
- return commandResult;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java
deleted file mode 100644
index c704364..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportOfflineDiskStoreCommand.java
+++ /dev/null
@@ -1,68 +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 java.io.File;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.internal.cache.DiskStoreImpl;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-
-public class ExportOfflineDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.EXPORT_OFFLINE_DISK_STORE,
- help = CliStrings.EXPORT_OFFLINE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- public Result exportOfflineDiskStore(
- @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME, mandatory = true,
- help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKSTORENAME__HELP) String diskStoreName,
- @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
- help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
- @CliOption(key = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR, mandatory = true,
- help = CliStrings.EXPORT_OFFLINE_DISK_STORE__DIR__HELP) String dir) {
-
- try {
- final File[] dirs = new File[diskDirs.length];
- for (int i = 0; i < diskDirs.length; i++) {
- dirs[i] = new File((diskDirs[i]));
- }
-
- File output = new File(dir);
-
- // Note, this can consume a lot of memory, so this should
- // not be moved to a separate process unless we provide a way for the user
- // to configure the size of that process.
- DiskStoreImpl.exportOfflineSnapshot(diskStoreName, dirs, output);
- String resultString =
- CliStrings.format(CliStrings.EXPORT_OFFLINE_DISK_STORE__SUCCESS, diskStoreName, dir);
- return ResultBuilder.createInfoResult(resultString);
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- LogWrapper.getInstance().warning(th.getMessage(), th);
- return ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.EXPORT_OFFLINE_DISK_STORE__ERROR, diskStoreName, th.toString()));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
deleted file mode 100644
index 4f8693d..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ExportStackTraceCommand.java
+++ /dev/null
@@ -1,157 +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 java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.zip.GZIPInputStream;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.StackTracesPerMember;
-import org.apache.geode.management.internal.cli.functions.GetStackTracesFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ExportStackTraceCommand implements GfshCommand {
- private final GetStackTracesFunction getStackTracesFunction = new GetStackTracesFunction();
-
- /**
- * Current implementation supports writing it to a file and returning the location of the file
- */
- @CliCommand(value = CliStrings.EXPORT_STACKTRACE, help = CliStrings.EXPORT_STACKTRACE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result exportStackTrace(@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.EXPORT_STACKTRACE__HELP) String[] memberNameOrId,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.GROUP) String[] group,
-
- @CliOption(key = CliStrings.EXPORT_STACKTRACE__FILE,
- help = CliStrings.EXPORT_STACKTRACE__FILE__HELP) String fileName,
-
- @CliOption(key = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
- unspecifiedDefaultValue = "false",
- help = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP) boolean failIfFilePresent) {
-
- Result result;
- StringBuilder filePrefix = new StringBuilder("stacktrace");
-
- if (fileName == null) {
- fileName = filePrefix.append("_").append(System.currentTimeMillis()).toString();
- }
- final File outFile = new File(fileName);
- try {
- if (outFile.exists() && failIfFilePresent) {
- return ResultBuilder.createShellClientErrorResult(CliStrings.format(
- CliStrings.EXPORT_STACKTRACE__ERROR__FILE__PRESENT, outFile.getCanonicalPath()));
- }
-
-
- InternalCache cache = getCache();
- InternalDistributedSystem ads = cache.getInternalDistributedSystem();
-
- InfoResultData resultData = ResultBuilder.createInfoResultData();
-
- Map<String, byte[]> dumps = new HashMap<>();
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(getStackTracesFunction, null, targetMembers);
- ArrayList<Object> resultList = (ArrayList<Object>) rc.getResult();
-
- for (Object resultObj : resultList) {
- if (resultObj instanceof StackTracesPerMember) {
- StackTracesPerMember stackTracePerMember = (StackTracesPerMember) resultObj;
- dumps.put(stackTracePerMember.getMemberNameOrId(), stackTracePerMember.getStackTraces());
- }
- }
-
- String filePath = writeStacksToFile(dumps, fileName);
- resultData.addLine(CliStrings.format(CliStrings.EXPORT_STACKTRACE__SUCCESS, filePath));
- resultData.addLine(CliStrings.EXPORT_STACKTRACE__HOST + ads.getDistributedMember().getHost());
-
- result = ResultBuilder.buildResult(resultData);
- } catch (IOException ex) {
- result = ResultBuilder
- .createGemFireErrorResult(CliStrings.EXPORT_STACKTRACE__ERROR + ex.getMessage());
- }
- return result;
- }
-
- /***
- * Writes the Stack traces member-wise to a text file
- *
- * @param dumps - Map containing key : member , value : zipped stack traces
- * @param fileName - Name of the file to which the stack-traces are written to
- * @return Canonical path of the file which contains the stack-traces
- * @throws IOException
- */
- private String writeStacksToFile(Map<String, byte[]> dumps, String fileName) throws IOException {
- String filePath;
- PrintWriter ps;
- File outputFile;
-
- outputFile = new File(fileName);
- try (OutputStream os = new FileOutputStream(outputFile)) {
- ps = new PrintWriter(os);
-
- for (Map.Entry<String, byte[]> entry : dumps.entrySet()) {
- ps.append("*** Stack-trace for member ").append(entry.getKey()).append(" ***");
- ps.flush();
- GZIPInputStream zipIn = new GZIPInputStream(new ByteArrayInputStream(entry.getValue()));
- BufferedInputStream bin = new BufferedInputStream(zipIn);
- byte[] buffer = new byte[10000];
- int count;
- while ((count = bin.read(buffer)) != -1) {
- os.write(buffer, 0, count);
- }
- ps.append('\n');
- }
- ps.flush();
- filePath = outputFile.getCanonicalPath();
- }
-
- return filePath;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
new file mode 100644
index 0000000..21d89c1
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/FunctionCommands.java
@@ -0,0 +1,537 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import org.apache.commons.lang.BooleanUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.ClassPathLoader;
+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.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ListFunctionFunction;
+import org.apache.geode.management.internal.cli.functions.UnregisterFunction;
+import org.apache.geode.management.internal.cli.functions.UserFunctionExecution;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+/**
+ * @since GemFire 7.0
+ */
+@SuppressWarnings("unused")
+public class FunctionCommands implements GfshCommand {
+
+ private final ListFunctionFunction listFunctionFunction = new ListFunctionFunction();
+
+ @CliCommand(value = CliStrings.EXECUTE_FUNCTION, help = CliStrings.EXECUTE_FUNCTION__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
+ @ResourceOperation(resource = Resource.DATA, operation = Operation.WRITE)
+ public Result executeFunction(
+ // TODO: Add optioncontext for functionID
+ @CliOption(key = CliStrings.EXECUTE_FUNCTION__ID, mandatory = true,
+ help = CliStrings.EXECUTE_FUNCTION__ID__HELP) String functionId,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.EXECUTE_FUNCTION__ONGROUPS__HELP) String[] onGroups,
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.EXECUTE_FUNCTION__ONMEMBER__HELP) String onMember,
+ @CliOption(key = CliStrings.EXECUTE_FUNCTION__ONREGION,
+ optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.EXECUTE_FUNCTION__ONREGION__HELP) String onRegion,
+ @CliOption(key = CliStrings.EXECUTE_FUNCTION__ARGUMENTS,
+ help = CliStrings.EXECUTE_FUNCTION__ARGUMENTS__HELP) String[] arguments,
+ @CliOption(key = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR,
+ help = CliStrings.EXECUTE_FUNCTION__RESULTCOLLECTOR__HELP) String resultCollector,
+ @CliOption(key = CliStrings.EXECUTE_FUNCTION__FILTER,
+ help = CliStrings.EXECUTE_FUNCTION__FILTER__HELP) String filterString) {
+
+ Result result = null;
+ CompositeResultData executeFunctionResultTable = ResultBuilder.createCompositeResultData();
+ TabularResultData resultTable = executeFunctionResultTable.addSection().addTable("Table1");
+ String headerText = "Execution summary";
+ resultTable.setHeader(headerText);
+ ResultCollector resultCollectorInstance = null;
+ Function function;
+ Set<String> filters = new HashSet<>();
+ Execution execution;
+ if (functionId != null) {
+ functionId = functionId.trim();
+ }
+ if (onRegion != null) {
+ onRegion = onRegion.trim();
+ }
+ if (onMember != null) {
+ onMember = onMember.trim();
+ }
+ if (filterString != null) {
+ filterString = filterString.trim();
+ }
+
+ try {
+ // validate otherwise return right away. no need to process anything
+ if (functionId == null || functionId.length() == 0) {
+ ErrorResultData errorResultData =
+ ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+ .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MISSING_FUNCTIONID);
+ result = ResultBuilder.buildResult(errorResultData);
+ return result;
+ }
+
+ if (isMoreThanOneIsTrue(onRegion != null, onMember != null, onGroups != null)) {
+ // Provide Only one of region/member/groups
+ ErrorResultData errorResultData =
+ ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+ .addLine(CliStrings.EXECUTE_FUNCTION__MSG__OPTIONS);
+ result = ResultBuilder.buildResult(errorResultData);
+ return result;
+ } else if ((onRegion == null || onRegion.length() == 0) && (filterString != null)) {
+ ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+ .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+ .addLine(CliStrings.EXECUTE_FUNCTION__MSG__MEMBER_SHOULD_NOT_HAVE_FILTER_FOR_EXECUTION);
+ result = ResultBuilder.buildResult(errorResultData);
+ return result;
+ }
+
+ InternalCache cache = getCache();
+
+ if (resultCollector != null) {
+ resultCollectorInstance =
+ (ResultCollector) ClassPathLoader.getLatest().forName(resultCollector).newInstance();
+ }
+
+ if (filterString != null && filterString.length() > 0) {
+ filters.add(filterString);
+ }
+
+ if (onRegion == null && onMember == null && onGroups == null) {
+ // run function on all the members excluding locators bug#46113
+ // if user wish to execute on locator then he can choose --member or --group option
+ Set<DistributedMember> dsMembers = CliUtil.getAllNormalMembers(cache);
+ if (dsMembers.size() > 0) {
+ function = new UserFunctionExecution();
+ LogWrapper.getInstance().info(CliStrings
+ .format(CliStrings.EXECUTE_FUNCTION__MSG__EXECUTING_0_ON_ENTIRE_DS, functionId));
+ for (DistributedMember member : dsMembers) {
+ executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
+ member, resultTable, onRegion);
+ }
+ return ResultBuilder.buildResult(resultTable);
+ } else {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.EXECUTE_FUNCTION__MSG__DS_HAS_NO_MEMBERS);
+ }
+ } else if (onRegion != null && onRegion.length() > 0) {
+ if (cache.getRegion(onRegion) == null) {
+ // find a member where region is present
+ DistributedRegionMXBean bean = ManagementService.getManagementService(getCache())
+ .getDistributedRegionMXBean(onRegion);
+ if (bean == null) {
+ bean = ManagementService.getManagementService(getCache())
+ .getDistributedRegionMXBean(Region.SEPARATOR + onRegion);
+
+ if (bean == null) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.EXECUTE_FUNCTION__MSG__MXBEAN_0_FOR_NOT_FOUND, onRegion));
+ }
+ }
+
+ DistributedMember member = null;
+ String[] membersName = bean.getMembers();
+ Set<DistributedMember> dsMembers = CliUtil.getAllMembers(cache);
+ Iterator it = dsMembers.iterator();
+ boolean matchFound = false;
+
+ if (membersName.length > 0) {
+ while (it.hasNext() && !matchFound) {
+ DistributedMember dsmember = (DistributedMember) it.next();
+ for (String memberName : membersName) {
+ if (MBeanJMXAdapter.getMemberNameOrId(dsmember).equals(memberName)) {
+ member = dsmember;
+ matchFound = true;
+ break;
+ }
+ }
+ }
+ }
+ if (matchFound) {
+ executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
+ member, resultTable, onRegion);
+ return ResultBuilder.buildResult(resultTable);
+ } else {
+ return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+ CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER_REGION, " " + onRegion));
+ }
+ } else {
+ execution = FunctionService.onRegion(cache.getRegion(onRegion));
+ if (execution != null) {
+ if (resultCollectorInstance != null) {
+ execution = execution.withCollector(resultCollectorInstance);
+ }
+ if (filters != null && filters.size() > 0) {
+ execution = execution.withFilter(filters);
+ }
+ if (arguments != null && arguments.length > 0) {
+ execution = execution.setArguments(arguments);
+ }
+
+ try {
+ List<Object> results = (List<Object>) execution.execute(functionId).getResult();
+ if (results.size() > 0) {
+ StringBuilder strResult = new StringBuilder();
+ for (Object obj : results) {
+ strResult.append(obj);
+ }
+ toTabularResultData(resultTable,
+ cache.getDistributedSystem().getDistributedMember().getId(),
+ strResult.toString());
+ }
+ return ResultBuilder.buildResult(resultTable);
+ } catch (FunctionException e) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+ CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
+ functionId, onRegion, e.getMessage()));
+ }
+ } else {
+ return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+ CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_EXECUTING_0_ON_REGION_1_DETAILS_2,
+ functionId, onRegion,
+ CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR));
+ }
+ }
+ } else if (onGroups != null) {
+ // execute on group members
+ Set<DistributedMember> dsMembers = new HashSet<>();
+ for (String grp : onGroups) {
+ dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
+ }
+
+ StringBuilder successMessage = new StringBuilder();
+ if (dsMembers.size() > 0) {
+ for (DistributedMember member : dsMembers) {
+ executeAndGetResults(functionId, filterString, resultCollector, arguments, cache,
+ member, resultTable, onRegion);
+ }
+ return ResultBuilder.buildResult(resultTable);
+ } else {
+ StringBuilder grps = new StringBuilder();
+ for (String grp : onGroups) {
+ grps.append(grp);
+ grps.append(", ");
+ }
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.EXECUTE_FUNCTION__MSG__GROUPS_0_HAS_NO_MEMBERS,
+ grps.toString().substring(0, grps.toString().length() - 1)));
+ }
+ } else if (onMember != null && onMember.length() > 0) {
+ DistributedMember member = CliUtil.getDistributedMemberByNameOrId(onMember); // fix for bug
+ // 45658
+ if (member != null) {
+ executeAndGetResults(functionId, filterString, resultCollector, arguments, cache, member,
+ resultTable, onRegion);
+ } else {
+ toTabularResultData(resultTable, onMember, CliStrings
+ .format(CliStrings.EXECUTE_FUNCTION__MSG__NO_ASSOCIATED_MEMBER + " " + onMember));
+ }
+ return ResultBuilder.buildResult(resultTable);
+ }
+ } catch (Exception e) {
+ ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+ .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
+ result = ResultBuilder.buildResult(errorResultData);
+ return result;
+ }
+
+ return result;
+ }
+
+ private boolean isMoreThanOneIsTrue(Boolean... values) {
+ return Stream.of(values).mapToInt(BooleanUtils::toInteger).sum() > 1;
+ }
+
+ void executeAndGetResults(String functionId, String filterString, String resultCollector,
+ String[] arguments, InternalCache cache, DistributedMember member,
+ TabularResultData resultTable, String onRegion) {
+ StringBuilder resultMessage = new StringBuilder();
+ try {
+ Function function = new UserFunctionExecution();
+ Object[] args = new Object[5];
+ args[0] = functionId;
+ if (filterString != null) {
+ args[1] = filterString;
+ }
+ if (resultCollector != null) {
+ args[2] = resultCollector;
+ }
+ if (arguments != null && arguments.length > 0) {
+ args[3] = "";
+ for (String str : arguments) {
+ // send via CSV separated value format
+ if (str != null) {
+ args[3] = args[3] + str + ",";
+ }
+ }
+ }
+ args[4] = onRegion;
+
+ Execution execution = FunctionService.onMember(member).setArguments(args);
+ if (execution != null) {
+ List<Object> results = (List<Object>) execution.execute(function).getResult();
+ if (results != null) {
+ for (Object resultObj : results) {
+ if (resultObj != null) {
+ if (resultObj instanceof String) {
+ resultMessage.append(((String) resultObj));
+ } else if (resultObj instanceof Exception) {
+ resultMessage.append(((Exception) resultObj).getMessage());
+ } else {
+ resultMessage.append(resultObj);
+ }
+ }
+ }
+ }
+ toTabularResultData(resultTable, member.getId(), resultMessage.toString());
+ } else {
+ toTabularResultData(resultTable, member.getId(),
+ CliStrings.EXECUTE_FUNCTION__MSG__ERROR_IN_RETRIEVING_EXECUTOR);
+ }
+ } catch (Exception e) {
+ resultMessage.append(CliStrings.format(
+ CliStrings.EXECUTE_FUNCTION__MSG__COULD_NOT_EXECUTE_FUNCTION_0_ON_MEMBER_1_ERROR_2,
+ functionId, member.getId(), e.getMessage()));
+ toTabularResultData(resultTable, member.getId(), resultMessage.toString());
+ }
+ }
+
+ protected void toTabularResultData(TabularResultData table, String memberId,
+ String memberResult) {
+ String newLine = System.getProperty("line.separator");
+ table.accumulate("Member ID/Name", memberId);
+ table.accumulate("Function Execution Result", memberResult);
+ }
+
+ @CliCommand(value = CliStrings.DESTROY_FUNCTION, help = CliStrings.DESTROY_FUNCTION__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION},
+ interceptor = "org.apache.geode.management.internal.cli.commands.FunctionCommands$Interceptor")
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
+ // TODO: Add optioncontext for functionId
+ public Result destroyFunction(
+ @CliOption(key = CliStrings.DESTROY_FUNCTION__ID, mandatory = true,
+ help = CliStrings.DESTROY_FUNCTION__HELP) String functionId,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.DESTROY_FUNCTION__ONGROUPS__HELP) String[] groups,
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.DESTROY_FUNCTION__ONMEMBER__HELP) String memberId) {
+ Result result;
+ try {
+ InternalCache cache = getCache();
+ Set<DistributedMember> dsMembers = new HashSet<>();
+ if (groups != null && memberId != null) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.DESTROY_FUNCTION__MSG__PROVIDE_OPTION);
+ } else if (groups != null && groups.length > 0) {
+ // execute on group members
+ for (String grp : groups) {
+ dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
+ }
+ @SuppressWarnings("unchecked")
+ Result results = executeFunction(cache, dsMembers, functionId);
+ return results;
+ } else if (memberId != null) {
+ // execute on member
+ dsMembers.add(getMember(cache, memberId));
+ @SuppressWarnings("unchecked")
+ Result results = executeFunction(cache, dsMembers, functionId);
+ return results;
+ } else {
+ // no option provided.
+ @SuppressWarnings("unchecked")
+ Result results = executeFunction(cache, cache.getMembers(), functionId);
+ return results;
+ }
+ } catch (Exception e) {
+ ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+ .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
+ result = ResultBuilder.buildResult(errorResultData);
+ return result;
+ }
+ }
+
+ /**
+ * Interceptor used by gfsh to intercept execution of destroy.
+ */
+ public static class Interceptor extends AbstractCliAroundInterceptor {
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+ Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+ Set<Entry<String, String>> setEnvMap = paramValueMap.entrySet();
+ String onGroup = paramValueMap.get(CliStrings.GROUP);
+ String onMember = paramValueMap.get(CliStrings.MEMBER);
+
+ if ((onGroup == null && onMember == null)) {
+ Response response = readYesNo("Do you really want to destroy "
+ + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID) + " on entire DS?", Response.NO);
+ if (response == Response.NO) {
+ return ResultBuilder.createShellClientAbortOperationResult(
+ "Aborted destroy of " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
+ } else {
+ return ResultBuilder
+ .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
+ }
+ } else {
+ return ResultBuilder
+ .createInfoResult("Destroying " + paramValueMap.get(CliStrings.DESTROY_FUNCTION__ID));
+ }
+ }
+ }
+
+ Result executeFunction(InternalCache cache, Set<DistributedMember> DsMembers, String functionId) {
+ // unregister on a set of of members
+ Function unregisterFunction = new UnregisterFunction();
+ FunctionService.registerFunction(unregisterFunction);
+ List resultList;
+
+ if (DsMembers.isEmpty()) {
+ return ResultBuilder.createInfoResult("No members for execution");
+ }
+ Object[] obj = new Object[1];
+ obj[0] = functionId;
+
+ Execution execution = FunctionService.onMembers(DsMembers).setArguments(obj);
+
+ if (execution == null) {
+ cache.getLogger().error("executeUnregister execution is null");
+ ErrorResultData errorResultData =
+ ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+ .addLine(CliStrings.DESTROY_FUNCTION__MSG__CANNOT_EXECUTE);
+ return (ResultBuilder.buildResult(errorResultData));
+ }
+ try {
+ resultList = (ArrayList) execution.execute(unregisterFunction).getResult();
+ } catch (FunctionException ex) {
+ ErrorResultData errorResultData = ResultBuilder.createErrorResultData()
+ .setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(ex.getMessage());
+ return (ResultBuilder.buildResult(errorResultData));
+ }
+ String resultStr = ((String) resultList.get(0));
+ if (resultStr.equals("Succeeded in unregistering")) {
+ StringBuilder members = new StringBuilder();
+ for (DistributedMember member : DsMembers) {
+ members.append(member.getId());
+ members.append(",");
+ }
+ return ResultBuilder.createInfoResult("Destroyed " + functionId + " Successfully on "
+ + members.toString().substring(0, members.toString().length() - 1));
+ } else {
+ return ResultBuilder.createInfoResult("Failed in unregistering");
+ }
+ }
+
+ @CliCommand(value = CliStrings.LIST_FUNCTION, help = CliStrings.LIST_FUNCTION__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_FUNCTION})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listFunction(
+ @CliOption(key = CliStrings.LIST_FUNCTION__MATCHES,
+ help = CliStrings.LIST_FUNCTION__MATCHES__HELP) String matches,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.LIST_FUNCTION__GROUP__HELP) String[] groups,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.LIST_FUNCTION__MEMBER__HELP) String[] members) {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ InternalCache cache = getCache();
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, members);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ try {
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(this.listFunctionFunction, new Object[] {matches}, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Function", "<ERROR: " + result.getThrowable().getMessage() + ">");
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else if (result.isSuccessful()) {
+ String[] strings = (String[]) result.getSerializables();
+ Arrays.sort(strings);
+ for (String string : strings) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Function", string);
+ accumulatedData = true;
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder
+ .createInfoResult(CliStrings.LIST_FUNCTION__NO_FUNCTIONS_FOUND_ERROR_MESSAGE);
+ }
+ return ResultBuilder.buildResult(tabularData);
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(
+ "Exception while attempting to list functions: " + th.getMessage());
+ }
+ }
+}
[16/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
new file mode 100644
index 0000000..2c61b73
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAlterDestroyRegionCommands.java
@@ -0,0 +1,1146 @@
+/*
+ * 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 java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Pattern;
+
+import javax.management.MBeanServer;
+import javax.management.MalformedObjectNameException;
+import javax.management.ObjectName;
+
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.LogWriter;
+import org.apache.geode.cache.DataPolicy;
+import org.apache.geode.cache.ExpirationAttributes;
+import org.apache.geode.cache.PartitionResolver;
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.RegionAttributes;
+import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.compression.Compressor;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.DistributionManager;
+import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
+import org.apache.geode.internal.ClassPathLoader;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.i18n.LocalizedStrings;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.RegionAttributesData;
+import org.apache.geode.management.RegionMXBean;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.MBeanJMXAdapter;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction;
+import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult;
+import org.apache.geode.management.internal.cli.functions.RegionAlterFunction;
+import org.apache.geode.management.internal.cli.functions.RegionCreateFunction;
+import org.apache.geode.management.internal.cli.functions.RegionDestroyFunction;
+import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.util.RegionPath;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+/**
+ * @since GemFire 7.0
+ */
+public class CreateAlterDestroyRegionCommands implements GfshCommand {
+
+ public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>();
+
+ static {
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW);
+ PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
+ }
+
+ /**
+ * Internally, we also verify the resource operation permissions CLUSTER:WRITE:DISK if the region
+ * is persistent
+ */
+ @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+ @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ public Result createRegion(
+ @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true,
+ help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath,
+ @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT,
+ help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut,
+ @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM,
+ optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups,
+ @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true",
+ specifiedDefaultValue = "true",
+ help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists,
+
+ // the following should all be in alphabetical order according to
+ // their key string
+ @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID,
+ help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
+ @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER,
+ help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener,
+ @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER,
+ help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader,
+ @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER,
+ help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter,
+ @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH,
+ optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith,
+ @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR,
+ help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor,
+ @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL,
+ help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel,
+ @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE,
+ help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore,
+ @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION,
+ help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation,
+ @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED,
+ help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
+ @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED,
+ help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled,
+ @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED,
+ help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled,
+ @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED,
+ help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled,
+ @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION,
+ help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation,
+ @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS,
+ help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
+ @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME,
+ help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
+ @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
+ help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
+ @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE,
+ help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
+ @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION,
+ help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
+ @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID,
+ help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
+ @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT,
+ help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint,
+ @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY,
+ help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory,
+ @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true",
+ help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap,
+ @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER,
+ help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver,
+ @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME,
+ help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
+ @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION,
+ help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
+ @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL,
+ help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
+ @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION,
+ help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
+ @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY,
+ help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay,
+ @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES,
+ help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies,
+ @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY,
+ help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay,
+ @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY,
+ help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory,
+ @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS,
+ help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets,
+ @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT,
+ help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint
+ // NOTICE: keep the region attributes params in alphabetical order
+ ) {
+ Result result;
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+ try {
+ InternalCache cache = getCache();
+
+ if (regionShortcut != null && useAttributesFrom != null) {
+ throw new IllegalArgumentException(
+ CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED);
+ } else if (regionShortcut == null && useAttributesFrom == null) {
+ throw new IllegalArgumentException(
+ CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUTESFROM_IS_REQUIRED);
+ }
+
+ validateRegionPathAndParent(cache, regionPath);
+ validateGroups(cache, groups);
+
+ RegionFunctionArgs.ExpirationAttrs entryIdle = null;
+ if (entryExpirationIdleTime != null) {
+ entryIdle = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
+ entryExpirationIdleTimeAction);
+ }
+ RegionFunctionArgs.ExpirationAttrs entryTTL = null;
+ if (entryExpirationTTL != null) {
+ entryTTL = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
+ entryExpirationTTLAction);
+ }
+ RegionFunctionArgs.ExpirationAttrs regionIdle = null;
+ if (regionExpirationIdleTime != null) {
+ regionIdle = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
+ regionExpirationIdleTimeAction);
+ }
+ RegionFunctionArgs.ExpirationAttrs regionTTL = null;
+ if (regionExpirationTTL != null) {
+ regionTTL = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
+ regionExpirationTTLAction);
+ }
+
+ RegionFunctionArgs regionFunctionArgs;
+ if (useAttributesFrom != null) {
+ if (!regionExists(cache, useAttributesFrom)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
+ new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
+ }
+
+ FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult =
+ getRegionAttributes(cache, useAttributesFrom);
+ RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes();
+
+ // give preference to user specified plugins than the ones retrieved from other region
+ String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0
+ ? cacheListener : regionAttributesResult.getCacheListenerClasses();
+ String cacheLoaderClass =
+ cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass();
+ String cacheWriterClass =
+ cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass();
+
+ regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists,
+ keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle,
+ regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
+ enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass,
+ asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
+ concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
+ prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled,
+ regionAttributes, partitionResolver);
+
+ if (regionAttributes.getPartitionAttributes() == null
+ && regionFunctionArgs.hasPartitionAttributes()) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
+ regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
+ + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
+ useAttributesFrom));
+ }
+ } else {
+ regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom,
+ skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL,
+ regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
+ enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter,
+ asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
+ concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
+ prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap,
+ mcastEnabled, partitionResolver);
+
+ if (!regionShortcut.name().startsWith("PARTITION")
+ && regionFunctionArgs.hasPartitionAttributes()) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
+ regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
+ + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
+ useAttributesFrom));
+ }
+ }
+
+ // Do we prefer to validate or authorize first?
+ validateRegionFunctionArgs(cache, regionFunctionArgs);
+ if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut())
+ || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) {
+ getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
+ }
+
+ Set<DistributedMember> membersToCreateRegionOn;
+ if (groups != null && groups.length != 0) {
+ membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups);
+ // have only normal members from the group
+ membersToCreateRegionOn
+ .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember)
+ .getVmKind() == DistributionManager.LOCATOR_DM_TYPE);
+ } else {
+ membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache);
+ }
+
+ if (membersToCreateRegionOn.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE,
+ regionFunctionArgs, membersToCreateRegionOn);
+ @SuppressWarnings("unchecked")
+ List<CliFunctionResult> regionCreateResults =
+ (List<CliFunctionResult>) resultCollector.getResult();
+
+ TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
+ final String errorPrefix = "ERROR: ";
+ for (CliFunctionResult regionCreateResult : regionCreateResults) {
+ boolean success = regionCreateResult.isSuccessful();
+ tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName());
+ tabularResultData.accumulate("Status",
+ (success ? "" : errorPrefix) + regionCreateResult.getMessage());
+
+ if (success) {
+ xmlEntity.set(regionCreateResult.getXmlEntity());
+ }
+ }
+ result = ResultBuilder.buildResult(tabularResultData);
+ verifyDistributedRegionMbean(cache, regionPath);
+
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ LogWrapper.getInstance().info(e.getMessage());
+ result = ResultBuilder.createUserErrorResult(e.getMessage());
+ }
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+ }
+
+ return result;
+ }
+
+ public boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) {
+ int federationInterval =
+ cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate();
+ long timeEnd = System.currentTimeMillis() + federationInterval + 50;
+
+ for (; System.currentTimeMillis() <= timeEnd;) {
+ try {
+ DistributedRegionMXBean bean =
+ ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName);
+ if (bean == null) {
+ bean = ManagementService.getManagementService(cache)
+ .getDistributedRegionMXBean(Region.SEPARATOR + regionName);
+ }
+ if (bean != null) {
+ return true;
+ } else {
+ Thread.sleep(2);
+ }
+ } catch (Exception ignored) {
+ }
+ }
+ return false;
+ }
+
+ @CliCommand(value = CliStrings.ALTER_REGION, help = CliStrings.ALTER_REGION__HELP)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+ public Result alterRegion(
+ @CliOption(key = CliStrings.ALTER_REGION__REGION, mandatory = true,
+ help = CliStrings.ALTER_REGION__REGION__HELP) String regionPath,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.ALTER_REGION__GROUP__HELP) String[] groups,
+ @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME,
+ specifiedDefaultValue = "-1",
+ help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
+ @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
+ specifiedDefaultValue = "INVALIDATE",
+ help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
+ @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE,
+ specifiedDefaultValue = "-1",
+ help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
+ @CliOption(key = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION,
+ specifiedDefaultValue = "INVALIDATE",
+ help = CliStrings.ALTER_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
+ @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME,
+ specifiedDefaultValue = "-1",
+ help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
+ @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION,
+ specifiedDefaultValue = "INVALIDATE",
+ help = CliStrings.ALTER_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
+ @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL, specifiedDefaultValue = "-1",
+ help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
+ @CliOption(key = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION,
+ specifiedDefaultValue = "INVALIDATE",
+ help = CliStrings.ALTER_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
+ @CliOption(key = CliStrings.ALTER_REGION__CACHELISTENER, specifiedDefaultValue = "",
+ help = CliStrings.ALTER_REGION__CACHELISTENER__HELP) String[] cacheListeners,
+ @CliOption(key = CliStrings.ALTER_REGION__CACHELOADER, specifiedDefaultValue = "",
+ help = CliStrings.ALTER_REGION__CACHELOADER__HELP) String cacheLoader,
+ @CliOption(key = CliStrings.ALTER_REGION__CACHEWRITER, specifiedDefaultValue = "",
+ help = CliStrings.ALTER_REGION__CACHEWRITER__HELP) String cacheWriter,
+ @CliOption(key = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID, specifiedDefaultValue = "",
+ help = CliStrings.ALTER_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
+ @CliOption(key = CliStrings.ALTER_REGION__GATEWAYSENDERID, specifiedDefaultValue = "",
+ help = CliStrings.ALTER_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
+ @CliOption(key = CliStrings.ALTER_REGION__CLONINGENABLED, specifiedDefaultValue = "false",
+ help = CliStrings.ALTER_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
+ @CliOption(key = CliStrings.ALTER_REGION__EVICTIONMAX, specifiedDefaultValue = "0",
+ help = CliStrings.ALTER_REGION__EVICTIONMAX__HELP) Integer evictionMax) {
+ Result result;
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+
+ getSecurityService().authorizeRegionManage(regionPath);
+
+ try {
+ InternalCache cache = getCache();
+
+ if (groups != null) {
+ validateGroups(cache, groups);
+ }
+
+ RegionFunctionArgs.ExpirationAttrs entryIdle = null;
+ if (entryExpirationIdleTime != null || entryExpirationIdleTimeAction != null) {
+ if (entryExpirationIdleTime != null && entryExpirationIdleTime == -1) {
+ entryExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
+ }
+ if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationIdleTimeAction)) {
+ entryExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
+ }
+ entryIdle = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
+ entryExpirationIdleTimeAction);
+ }
+ RegionFunctionArgs.ExpirationAttrs entryTTL = null;
+ if (entryExpirationTTL != null || entryExpirationTTLAction != null) {
+ if (entryExpirationTTL != null && entryExpirationTTL == -1) {
+ entryExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
+ }
+ if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(entryExpirationTTLAction)) {
+ entryExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
+ }
+ entryTTL = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
+ entryExpirationTTLAction);
+ }
+ RegionFunctionArgs.ExpirationAttrs regionIdle = null;
+ if (regionExpirationIdleTime != null || regionExpirationIdleTimeAction != null) {
+ if (regionExpirationIdleTime != null && regionExpirationIdleTime == -1) {
+ regionExpirationIdleTime = ExpirationAttributes.DEFAULT.getTimeout();
+ }
+ if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationIdleTimeAction)) {
+ regionExpirationIdleTimeAction = ExpirationAttributes.DEFAULT.getAction().toString();
+ }
+ regionIdle = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
+ regionExpirationIdleTimeAction);
+ }
+ RegionFunctionArgs.ExpirationAttrs regionTTL = null;
+ if (regionExpirationTTL != null || regionExpirationTTLAction != null) {
+ if (regionExpirationTTL != null && regionExpirationTTL == -1) {
+ regionExpirationTTL = ExpirationAttributes.DEFAULT.getTimeout();
+ }
+ if (CliMetaData.ANNOTATION_DEFAULT_VALUE.equals(regionExpirationTTLAction)) {
+ regionExpirationTTLAction = ExpirationAttributes.DEFAULT.getAction().toString();
+ }
+ regionTTL = new RegionFunctionArgs.ExpirationAttrs(
+ RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
+ regionExpirationTTLAction);
+ }
+
+ cacheLoader = convertDefaultValue(cacheLoader, StringUtils.EMPTY);
+ cacheWriter = convertDefaultValue(cacheWriter, StringUtils.EMPTY);
+
+ RegionFunctionArgs regionFunctionArgs;
+ regionFunctionArgs = new RegionFunctionArgs(regionPath, null, null, false, null, null, null,
+ entryIdle, entryTTL, regionIdle, regionTTL, null, null, null, null, cacheListeners,
+ cacheLoader, cacheWriter, asyncEventQueueIds, gatewaySenderIds, null, cloningEnabled,
+ null, null, null, null, null, null, null, null, evictionMax, null, null, null, null);
+
+ Set<String> cacheListenersSet = regionFunctionArgs.getCacheListeners();
+ if (cacheListenersSet != null && !cacheListenersSet.isEmpty()) {
+ for (String cacheListener : cacheListenersSet) {
+ if (!isClassNameValid(cacheListener)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
+ new Object[] {cacheListener}));
+ }
+ }
+ }
+
+ if (cacheLoader != null && !isClassNameValid(cacheLoader)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
+ new Object[] {cacheLoader}));
+ }
+
+ if (cacheWriter != null && !isClassNameValid(cacheWriter)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.ALTER_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
+ new Object[] {cacheWriter}));
+ }
+
+ if (evictionMax != null && evictionMax < 0) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.ALTER_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_EVICTIONMAX_0_IS_NOT_VALID,
+ new Object[] {evictionMax}));
+ }
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> resultCollector =
+ CliUtil.executeFunction(new RegionAlterFunction(), regionFunctionArgs, targetMembers);
+ List<CliFunctionResult> regionAlterResults =
+ (List<CliFunctionResult>) resultCollector.getResult();
+
+ TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
+ final String errorPrefix = "ERROR: ";
+ for (CliFunctionResult regionAlterResult : regionAlterResults) {
+ boolean success = regionAlterResult.isSuccessful();
+ tabularResultData.accumulate("Member", regionAlterResult.getMemberIdOrName());
+ if (success) {
+ tabularResultData.accumulate("Status", regionAlterResult.getMessage());
+ xmlEntity.set(regionAlterResult.getXmlEntity());
+ } else {
+ tabularResultData.accumulate("Status", errorPrefix + regionAlterResult.getMessage());
+ tabularResultData.setStatus(Status.ERROR);
+ }
+ }
+ result = ResultBuilder.buildResult(tabularResultData);
+ } catch (IllegalArgumentException | IllegalStateException e) {
+ LogWrapper.getInstance().info(e.getMessage());
+ result = ResultBuilder.createUserErrorResult(e.getMessage());
+ } catch (RuntimeException e) {
+ LogWrapper.getInstance().info(e.getMessage(), e);
+ result = ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+ }
+ return result;
+ }
+
+ private static boolean regionExists(InternalCache cache, String regionPath) {
+ boolean regionFound = false;
+ if (regionPath != null && !Region.SEPARATOR.equals(regionPath)) {
+ ManagementService managementService = ManagementService.getExistingManagementService(cache);
+ DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
+
+ String[] allRegionPaths = dsMBean.listAllRegionPaths();
+ for (String allRegionPath : allRegionPaths) {
+ if (allRegionPath.equals(regionPath)) {
+ regionFound = true;
+ break;
+ }
+ }
+ }
+ return regionFound;
+ }
+
+ private void validateRegionPathAndParent(InternalCache cache, String regionPath) {
+ if (StringUtils.isEmpty(regionPath)) {
+ throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
+ }
+ // If a region path indicates a sub-region, check whether the parent region exists
+ RegionPath regionPathData = new RegionPath(regionPath);
+ String parentRegionPath = regionPathData.getParent();
+ if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
+ if (!regionExists(cache, parentRegionPath)) {
+ throw new IllegalArgumentException(
+ CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOES_NOT_EXIST,
+ new Object[] {regionPath}));
+ }
+ }
+ }
+
+ private void validateGroups(InternalCache cache, String[] groups) {
+ if (groups != null && groups.length != 0) {
+ Set<String> existingGroups = new HashSet<>();
+ Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache);
+ for (DistributedMember distributedMember : members) {
+ List<String> memberGroups = distributedMember.getGroups();
+ existingGroups.addAll(memberGroups);
+ }
+ List<String> groupsList = new ArrayList<>(Arrays.asList(groups));
+ groupsList.removeAll(existingGroups);
+
+ if (!groupsList.isEmpty()) {
+ throw new IllegalArgumentException(
+ CliStrings.format(CliStrings.CREATE_REGION__MSG__GROUPS_0_ARE_INVALID,
+ new Object[] {String.valueOf(groupsList)}));
+ }
+ }
+ }
+
+ DistributedSystemMXBean getDSMBean(InternalCache cache) {
+ ManagementService managementService = ManagementService.getExistingManagementService(cache);
+ return managementService.getDistributedSystemMXBean();
+ }
+
+ void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) {
+ if (regionFunctionArgs.getRegionPath() == null) {
+ throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
+ }
+
+ DistributedSystemMXBean dsMBean = getDSMBean(cache);
+
+ String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom();
+ if (useAttributesFrom != null && !useAttributesFrom.isEmpty()
+ && regionExists(cache, useAttributesFrom)) {
+ if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!!
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
+ new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
+ }
+ if (!regionFunctionArgs.isSetUseAttributesFrom()
+ || regionFunctionArgs.getRegionAttributes() == null) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS,
+ useAttributesFrom));
+ }
+ }
+
+ if (regionFunctionArgs.hasPartitionAttributes()) {
+ RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs();
+ String colocatedWith = partitionArgs.getPrColocatedWith();
+ if (colocatedWith != null && !colocatedWith.isEmpty()) {
+ String[] listAllRegionPaths = dsMBean.listAllRegionPaths();
+ String foundRegionPath = null;
+ for (String regionPath : listAllRegionPaths) {
+ if (regionPath.equals(colocatedWith)) {
+ foundRegionPath = regionPath;
+ break;
+ }
+ }
+ if (foundRegionPath == null) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
+ new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith}));
+ }
+ ManagementService mgmtService = ManagementService.getExistingManagementService(cache);
+ DistributedRegionMXBean distributedRegionMXBean =
+ mgmtService.getDistributedRegionMXBean(foundRegionPath);
+ String regionType = distributedRegionMXBean.getRegionType();
+ if (!(DataPolicy.PARTITION.toString().equals(regionType)
+ || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION,
+ new Object[] {colocatedWith}));
+ }
+ }
+ if (partitionArgs.isSetPRLocalMaxMemory()) {
+ int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory();
+ if (prLocalMaxMemory < 0) {
+ throw new IllegalArgumentException(
+ LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE
+ .toLocalizedString());
+ }
+ }
+ if (partitionArgs.isSetPRTotalMaxMemory()) {
+ long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory();
+ if (prTotalMaxMemory <= 0) {
+ throw new IllegalArgumentException(
+ LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0
+ .toLocalizedString());
+ }
+ }
+ if (partitionArgs.isSetPRRedundantCopies()) {
+ int prRedundantCopies = partitionArgs.getPrRedundantCopies();
+ switch (prRedundantCopies) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ break;
+ default:
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123,
+ new Object[] {prRedundantCopies}));
+ }
+ }
+ }
+
+ String keyConstraint = regionFunctionArgs.getKeyConstraint();
+ if (keyConstraint != null && !isClassNameValid(keyConstraint)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID,
+ new Object[] {keyConstraint}));
+ }
+
+ String valueConstraint = regionFunctionArgs.getValueConstraint();
+ if (valueConstraint != null && !isClassNameValid(valueConstraint)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID,
+ new Object[] {valueConstraint}));
+ }
+
+ Set<String> cacheListeners = regionFunctionArgs.getCacheListeners();
+ if (cacheListeners != null && !cacheListeners.isEmpty()) {
+ for (String cacheListener : cacheListeners) {
+ if (!isClassNameValid(cacheListener)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
+ new Object[] {cacheListener}));
+ }
+ }
+ }
+
+ String cacheLoader = regionFunctionArgs.getCacheLoader();
+ if (cacheLoader != null && !isClassNameValid(cacheLoader)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
+ new Object[] {cacheLoader}));
+ }
+
+ String cacheWriter = regionFunctionArgs.getCacheWriter();
+ if (cacheWriter != null && !isClassNameValid(cacheWriter)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
+ new Object[] {cacheWriter}));
+ }
+
+ Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds();
+ if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) {
+ String[] gatewaySenders = dsMBean.listGatewaySenders();
+ if (gatewaySenders.length == 0) {
+ throw new IllegalArgumentException(
+ CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM);
+ } else {
+ List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders));
+ gatewaySenderIds = new HashSet<>(gatewaySenderIds);
+ gatewaySenderIds.removeAll(gatewaySendersList);
+ if (!gatewaySenderIds.isEmpty()) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0,
+ new Object[] {gatewaySenderIds}));
+ }
+ }
+ }
+
+ if (regionFunctionArgs.isSetConcurrencyLevel()) {
+ int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel();
+ if (concurrencyLevel < 0) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID,
+ new Object[] {concurrencyLevel}));
+ }
+ }
+
+ String diskStore = regionFunctionArgs.getDiskStore();
+ if (diskStore != null) {
+ RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut();
+ if (regionShortcut != null && !PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) {
+ String subMessage =
+ LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
+ String message = subMessage + ". "
+ + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
+ new Object[] {String.valueOf(PERSISTENT_OVERFLOW_SHORTCUTS)});
+
+ throw new IllegalArgumentException(message);
+ }
+
+ RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes();
+ if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) {
+ String subMessage =
+ LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
+ String message = subMessage + ". "
+ + CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE,
+ new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())});
+
+ throw new IllegalArgumentException(message);
+ }
+
+ if (!diskStoreExists(cache, diskStore)) {
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0,
+ new Object[] {diskStore}));
+ }
+ }
+
+ RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime =
+ regionFunctionArgs.getEntryExpirationIdleTime();
+ RegionFunctionArgs.ExpirationAttrs entryExpirationTTL =
+ regionFunctionArgs.getEntryExpirationTTL();
+ RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime =
+ regionFunctionArgs.getRegionExpirationIdleTime();
+ RegionFunctionArgs.ExpirationAttrs regionExpirationTTL =
+ regionFunctionArgs.getRegionExpirationTTL();
+
+ if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled())
+ && (entryExpirationIdleTime != null || entryExpirationTTL != null
+ || regionExpirationIdleTime != null || regionExpirationTTL != null)) {
+ String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION
+ .toLocalizedString();
+ throw new IllegalArgumentException(message + ".");
+ }
+
+ boolean compressorFailure = false;
+ if (regionFunctionArgs.isSetCompressor()) {
+ String compressorClassName = regionFunctionArgs.getCompressor();
+ Object compressor = null;
+ try {
+ Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName);
+ compressor = compressorClass.newInstance();
+ } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
+ compressorFailure = true;
+ }
+
+ if (compressorFailure || !(compressor instanceof Compressor)) {
+ throw new IllegalArgumentException(
+ CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR,
+ new Object[] {regionFunctionArgs.getCompressor()}));
+ }
+ }
+
+ if (regionFunctionArgs.hasPartitionAttributes()) {
+ if (regionFunctionArgs.isPartitionResolverSet()) {
+ String partitionResolverClassName = regionFunctionArgs.getPartitionResolver();
+ try {
+ Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader
+ .getLatest().forName(partitionResolverClassName);
+ PartitionResolver partitionResolver = resolverClass.newInstance();
+ } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
+ throw new IllegalArgumentException(
+ CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER,
+ new Object[] {regionFunctionArgs.getPartitionResolver()}),
+ e);
+ }
+ }
+ }
+ }
+
+ private boolean diskStoreExists(InternalCache cache, String diskStoreName) {
+ ManagementService managementService = ManagementService.getExistingManagementService(cache);
+ DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
+ Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
+
+ Set<Entry<String, String[]>> entrySet = diskstore.entrySet();
+
+ for (Entry<String, String[]> entry : entrySet) {
+ String[] value = entry.getValue();
+ if (CliUtil.contains(value, diskStoreName)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private static <K, V> FetchRegionAttributesFunctionResult<K, V> getRegionAttributes(
+ InternalCache cache, String regionPath) {
+ if (!isClusterWideSameConfig(cache, regionPath)) {
+ throw new IllegalStateException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0,
+ regionPath));
+ }
+ FetchRegionAttributesFunctionResult<K, V> attributes = null;
+
+ // First check whether the region exists on a this manager, if yes then no
+ // need to use FetchRegionAttributesFunction to fetch RegionAttributes
+ try {
+ attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath);
+ } catch (IllegalArgumentException e) {
+ /* region doesn't exist on the manager */
+ }
+
+ if (attributes == null) {
+ // find first member which has the region
+ Set<DistributedMember> regionAssociatedMembers =
+ CliUtil.getRegionAssociatedMembers(regionPath, cache, false);
+ if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) {
+ DistributedMember distributedMember = regionAssociatedMembers.iterator().next();
+ ResultCollector<?, ?> resultCollector = CliUtil
+ .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember);
+ List<?> resultsList = (List<?>) resultCollector.getResult();
+
+ if (resultsList != null && !resultsList.isEmpty()) {
+ for (Object object : resultsList) {
+ if (object instanceof IllegalArgumentException) {
+ throw (IllegalArgumentException) object;
+ } else if (object instanceof Throwable) {
+ Throwable th = (Throwable) object;
+ LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th)));
+ throw new IllegalArgumentException(CliStrings.format(
+ CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1,
+ new Object[] {regionPath, th.getMessage()}));
+ } else { // has to be RegionAttributes
+ @SuppressWarnings("unchecked") // to avoid warning :(
+ FetchRegionAttributesFunctionResult<K, V> regAttr =
+ ((FetchRegionAttributesFunctionResult<K, V>) object);
+ if (attributes == null) {
+ attributes = regAttr;
+ break;
+ } // attributes null check
+ } // not IllegalArgumentException or other throwable
+ } // iterate over list - there should be only one result in the list
+ } // result list is not null or empty
+ } // regionAssociatedMembers is not-empty
+ } // attributes are null because do not exist on local member
+
+ return attributes;
+ }
+
+ private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) {
+ ManagementService managementService = ManagementService.getExistingManagementService(cache);
+
+ DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
+
+ Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache);
+
+ RegionAttributesData regionAttributesToValidateAgainst = null;
+ for (DistributedMember distributedMember : allMembers) {
+ ObjectName regionObjectName;
+ try {
+ regionObjectName = dsMXBean
+ .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath);
+ RegionMXBean regionMBean =
+ managementService.getMBeanInstance(regionObjectName, RegionMXBean.class);
+ RegionAttributesData regionAttributes = regionMBean.listRegionAttributes();
+
+ if (regionAttributesToValidateAgainst == null) {
+ regionAttributesToValidateAgainst = regionAttributes;
+ } else if (!(regionAttributesToValidateAgainst.getScope()
+ .equals(regionAttributes.getScope())
+ || regionAttributesToValidateAgainst.getDataPolicy()
+ .equals(regionAttributes.getDataPolicy()))) {
+ return false;
+ }
+ } catch (Exception e) {
+ // ignore
+ }
+ }
+
+ return true;
+ }
+
+ private boolean isClassNameValid(String fqcn) {
+ if (fqcn.isEmpty()) {
+ return true;
+ }
+
+ String regex = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*";
+ return Pattern.matches(regex, fqcn);
+ }
+
+ @CliCommand(value = {CliStrings.DESTROY_REGION}, help = CliStrings.DESTROY_REGION__HELP)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+ @ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
+ public Result destroyRegion(
+ @CliOption(key = CliStrings.DESTROY_REGION__REGION, optionContext = ConverterHint.REGION_PATH,
+ mandatory = true, help = CliStrings.DESTROY_REGION__REGION__HELP) String regionPath) {
+
+ if (regionPath == null) {
+ return ResultBuilder
+ .createInfoResult(CliStrings.DESTROY_REGION__MSG__SPECIFY_REGIONPATH_TO_DESTROY);
+ }
+
+ if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
+ return ResultBuilder.createInfoResult(CliStrings.format(
+ CliStrings.DESTROY_REGION__MSG__REGIONPATH_0_NOT_VALID, new Object[] {regionPath}));
+ }
+
+ Result result;
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+ try {
+ InternalCache cache = getCache();
+ ManagementService managementService = ManagementService.getExistingManagementService(cache);
+ String regionPathToUse = regionPath;
+
+ if (!regionPathToUse.startsWith(Region.SEPARATOR)) {
+ regionPathToUse = Region.SEPARATOR + regionPathToUse;
+ }
+
+ Set<DistributedMember> regionMembersList =
+ findMembersForRegion(cache, managementService, regionPathToUse);
+
+ if (regionMembersList.size() == 0) {
+ return ResultBuilder.createUserErrorResult(
+ CliStrings.format(CliStrings.DESTROY_REGION__MSG__COULD_NOT_FIND_REGIONPATH_0_IN_GEODE,
+ regionPath, "jmx-manager-update-rate milliseconds"));
+ }
+
+ CliFunctionResult destroyRegionResult;
+
+ ResultCollector<?, ?> resultCollector =
+ CliUtil.executeFunction(RegionDestroyFunction.INSTANCE, regionPath, regionMembersList);
+ List<CliFunctionResult> resultsList = (List<CliFunctionResult>) resultCollector.getResult();
+ String message =
+ CliStrings.format(CliStrings.DESTROY_REGION__MSG__REGION_0_1_DESTROYED, regionPath, "");
+
+ // Only if there is an error is this set to false
+ boolean isRegionDestroyed = true;
+ for (CliFunctionResult aResultsList : resultsList) {
+ destroyRegionResult = aResultsList;
+ if (destroyRegionResult.isSuccessful()) {
+ xmlEntity.set(destroyRegionResult.getXmlEntity());
+ } else if (destroyRegionResult.getThrowable() != null) {
+ Throwable t = destroyRegionResult.getThrowable();
+ LogWrapper.getInstance().info(t.getMessage(), t);
+ message = CliStrings.format(
+ CliStrings.DESTROY_REGION__MSG__ERROR_OCCURRED_WHILE_DESTROYING_0_REASON_1,
+ regionPath, t.getMessage());
+ isRegionDestroyed = false;
+ } else {
+ message = CliStrings.format(
+ CliStrings.DESTROY_REGION__MSG__UNKNOWN_RESULT_WHILE_DESTROYING_REGION_0_REASON_1,
+ regionPath, destroyRegionResult.getMessage());
+ isRegionDestroyed = false;
+ }
+ }
+ if (isRegionDestroyed) {
+ result = ResultBuilder.createInfoResult(message);
+ } else {
+ result = ResultBuilder.createUserErrorResult(message);
+ }
+ } catch (IllegalStateException e) {
+ result = ResultBuilder.createUserErrorResult(CliStrings.format(
+ CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
+ e.getMessage()));
+ } catch (Exception e) {
+ result = ResultBuilder.createGemFireErrorResult(CliStrings.format(
+ CliStrings.DESTROY_REGION__MSG__ERROR_WHILE_DESTROYING_REGION_0_REASON_1, regionPath,
+ e.getMessage()));
+ }
+
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().deleteXmlEntity(xmlEntity.get(), null));
+ }
+
+ return result;
+ }
+
+ private Set<DistributedMember> findMembersForRegion(InternalCache cache,
+ ManagementService managementService, String regionPath) {
+ Set<DistributedMember> membersList = new HashSet<>();
+ Set<String> regionMemberIds = new HashSet<>();
+ MBeanServer mbeanServer = MBeanJMXAdapter.mbeanServer;
+
+ // needs to be escaped with quotes if it contains a hyphen
+ if (regionPath.contains("-")) {
+ regionPath = "\"" + regionPath + "\"";
+ }
+
+ String queryExp =
+ MessageFormat.format(MBeanJMXAdapter.OBJECTNAME__REGION_MXBEAN, regionPath, "*");
+
+ try {
+ ObjectName queryExpON = new ObjectName(queryExp);
+ Set<ObjectName> queryNames = mbeanServer.queryNames(null, queryExpON);
+ if (queryNames == null || queryNames.isEmpty()) {
+ return membersList; // protects against null pointer exception below
+ }
+
+ boolean addedOneRemote = false;
+ for (ObjectName regionMBeanObjectName : queryNames) {
+ try {
+ RegionMXBean regionMXBean =
+ managementService.getMBeanInstance(regionMBeanObjectName, RegionMXBean.class);
+ if (regionMXBean != null) {
+ RegionAttributesData regionAttributes = regionMXBean.listRegionAttributes();
+ String scope = regionAttributes.getScope();
+ // For Scope.LOCAL regions we need to identify each hosting member, but for
+ // other scopes we just need a single member as the region destroy will be
+ // propagated.
+ if (Scope.LOCAL.equals(Scope.fromString(scope))) {
+ regionMemberIds.add(regionMXBean.getMember());
+ } else {
+ if (!addedOneRemote) {
+ regionMemberIds.add(regionMXBean.getMember());
+ addedOneRemote = true;
+ }
+ }
+ }
+ } catch (ClassCastException e) {
+ LogWriter logger = cache.getLogger();
+ if (logger.finerEnabled()) {
+ logger.finer(regionMBeanObjectName + " is not a " + RegionMXBean.class.getSimpleName(),
+ e);
+ }
+ }
+ }
+
+ if (!regionMemberIds.isEmpty()) {
+ membersList = getMembersByIds(cache, regionMemberIds);
+ }
+ } catch (MalformedObjectNameException | NullPointerException e) {
+ LogWrapper.getInstance().info(e.getMessage(), e);
+ }
+
+ return membersList;
+ }
+
+ private Set<DistributedMember> getMembersByIds(InternalCache cache, Set<String> memberIds) {
+ Set<DistributedMember> foundMembers = Collections.emptySet();
+ if (memberIds != null && !memberIds.isEmpty()) {
+ foundMembers = new HashSet<>();
+ Set<DistributedMember> allNormalMembers = CliUtil.getAllNormalMembers(cache);
+
+ for (String memberId : memberIds) {
+ for (DistributedMember distributedMember : allNormalMembers) {
+ if (memberId.equals(distributedMember.getId())
+ || memberId.equals(distributedMember.getName())) {
+ foundMembers.add(distributedMember);
+ }
+ }
+ }
+ }
+ return foundMembers;
+ }
+
+ private boolean isPersistentShortcut(RegionShortcut shortcut) {
+ return shortcut == RegionShortcut.LOCAL_PERSISTENT
+ || shortcut == RegionShortcut.LOCAL_PERSISTENT_OVERFLOW
+ || shortcut == RegionShortcut.PARTITION_PERSISTENT
+ || shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW
+ || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT
+ || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW
+ || shortcut == RegionShortcut.REPLICATE_PERSISTENT
+ || shortcut == RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW;
+ }
+
+ private boolean isAttributePersistent(RegionAttributes attributes) {
+ return attributes != null && attributes.getDataPolicy() != null
+ && attributes.getDataPolicy().toString().contains("PERSISTENT");
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java
deleted file mode 100644
index ba9dc94..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateAsyncEventQueueCommand.java
+++ /dev/null
@@ -1,171 +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 java.util.List;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.AsyncEventQueueFunctionArgs;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateAsyncEventQueueFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateAsyncEventQueueCommand implements GfshCommand {
- @CliCommand(value = CliStrings.CREATE_ASYNC_EVENT_QUEUE,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__HELP)
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
- public Result createAsyncEventQueue(
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, mandatory = true,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID__HELP) String id,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP__HELP) String[] groups,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL,
- unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL__HELP) Boolean parallel,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION,
- unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION__HELP) Boolean enableBatchConflation,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE,
- unspecifiedDefaultValue = "100",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE__HELP) int batchSize,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL,
- unspecifiedDefaultValue = "1000",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL__HELP) int batchTimeInterval,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT,
- unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT__HELP) boolean persistent,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE__HELP) String diskStore,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS,
- unspecifiedDefaultValue = "true", specifiedDefaultValue = "true",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY,
- unspecifiedDefaultValue = "false", specifiedDefaultValue = "false",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY__HELP) Boolean ignoreEvictionAndExpiration,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY,
- unspecifiedDefaultValue = "100",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY__HELP) int maxQueueMemory,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS,
- unspecifiedDefaultValue = "1",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS__HELP) Integer dispatcherThreads,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY,
- unspecifiedDefaultValue = "KEY",
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY__HELP) String orderPolicy,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER__HELP) String[] gatewayEventFilters,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER__HELP) String gatewaySubstitutionListener,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER, mandatory = true,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER__HELP) String listener,
- @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE,
- help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE__HELP) String[] listenerParamsAndValues) {
-
- if (persistent) {
- getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
- ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
- }
- Properties listenerProperties = new Properties();
-
- try {
- if (listenerParamsAndValues != null) {
- for (String listenerParamsAndValue : listenerParamsAndValues) {
- final int hashPosition = listenerParamsAndValue.indexOf('#');
- if (hashPosition == -1) {
- listenerProperties.put(listenerParamsAndValue, "");
- } else {
- listenerProperties.put(listenerParamsAndValue.substring(0, hashPosition),
- listenerParamsAndValue.substring(hashPosition + 1));
- }
- }
- }
-
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- AsyncEventQueueFunctionArgs aeqArgs = new AsyncEventQueueFunctionArgs(id, parallel,
- enableBatchConflation, batchSize, batchTimeInterval, persistent, diskStore,
- diskSynchronous, maxQueueMemory, dispatcherThreads, orderPolicy, gatewayEventFilters,
- gatewaySubstitutionListener, listener, listenerProperties, ignoreEvictionAndExpiration);
-
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(new CreateAsyncEventQueueFunction(), aeqArgs, targetMembers);
-
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
- + ": " + result.getThrowable().getMessage());
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else if (result.isSuccessful()) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", result.getMessage());
- accumulatedData = true;
-
- if (xmlEntity.get() == null) {
- xmlEntity.set(result.getXmlEntity());
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder.createInfoResult("Unable to create async event queue(s).");
- }
-
- Result result = ResultBuilder.buildResult(tabularData);
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
- }
- return result;
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ERROR_WHILE_CREATING_REASON_0,
- new Object[] {th.getMessage()}));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
deleted file mode 100644
index da3ba46..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDefinedIndexesCommand.java
+++ /dev/null
@@ -1,154 +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 java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateDefinedIndexesFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateDefinedIndexesCommand implements GfshCommand {
- private static final CreateDefinedIndexesFunction createDefinedIndexesFunction =
- new CreateDefinedIndexesFunction();
-
- @CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- // TODO : Add optionContext for indexName
- public Result createDefinedIndexes(
-
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.CREATE_DEFINED_INDEXES__MEMBER__HELP) final String[] memberNameOrID,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.CREATE_DEFINED_INDEXES__GROUP__HELP) final String[] group) {
-
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
- if (IndexDefinition.indexDefinitions.isEmpty()) {
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.DEFINE_INDEX__FAILURE__MSG);
- return ResultBuilder.buildResult(infoResult);
- }
-
- try {
- final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- CacheFactory.getAnyInstance();
- final ResultCollector<?, ?> rc = CliUtil.executeFunction(createDefinedIndexesFunction,
- IndexDefinition.indexDefinitions, targetMembers);
-
- final List<Object> funcResults = (List<Object>) rc.getResult();
- final Set<String> successfulMembers = new TreeSet<>();
- final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
- for (final Object funcResult : funcResults) {
- if (funcResult instanceof CliFunctionResult) {
- final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
- if (cliFunctionResult.isSuccessful()) {
- successfulMembers.add(cliFunctionResult.getMemberIdOrName());
-
- if (xmlEntity.get() == null) {
- xmlEntity.set(cliFunctionResult.getXmlEntity());
- }
- } else {
- final String exceptionMessage = cliFunctionResult.getMessage();
- Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
- if (failedMembers == null) {
- failedMembers = new TreeSet<>();
- }
- failedMembers.add(cliFunctionResult.getMemberIdOrName());
- indexOpFailMap.put(exceptionMessage, failedMembers);
- }
- }
- }
-
- if (!successfulMembers.isEmpty()) {
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.CREATE_DEFINED_INDEXES__SUCCESS__MSG);
-
- int num = 0;
-
- for (final String memberId : successfulMembers) {
- ++num;
- infoResult.addLine(CliStrings
- .format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER, num, memberId));
- }
- result = ResultBuilder.buildResult(infoResult);
-
- } else {
- // Group members by the exception thrown.
- final ErrorResultData erd = ResultBuilder.createErrorResultData();
-
- final Set<String> exceptionMessages = indexOpFailMap.keySet();
-
- for (final String exceptionMessage : exceptionMessages) {
- erd.addLine(exceptionMessage);
- erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
- final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
-
- int num = 0;
- for (final String memberId : memberIds) {
- ++num;
- erd.addLine(CliStrings.format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER,
- num, memberId));
- }
- }
- result = ResultBuilder.buildResult(erd);
- }
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
-
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java
deleted file mode 100644
index 19784d6..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateDiskStoreCommand.java
+++ /dev/null
@@ -1,166 +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 java.io.File;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.DiskStoreAttributes;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateDiskStoreFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.CREATE_DISK_STORE, help = CliStrings.CREATE_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
- public Result createDiskStore(
- @CliOption(key = CliStrings.CREATE_DISK_STORE__NAME, mandatory = true,
- optionContext = ConverterHint.DISKSTORE,
- help = CliStrings.CREATE_DISK_STORE__NAME__HELP) String name,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION,
- specifiedDefaultValue = "true", unspecifiedDefaultValue = "false",
- help = CliStrings.CREATE_DISK_STORE__ALLOW_FORCE_COMPACTION__HELP) boolean allowForceCompaction,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT, specifiedDefaultValue = "true",
- unspecifiedDefaultValue = "true",
- help = CliStrings.CREATE_DISK_STORE__AUTO_COMPACT__HELP) boolean autoCompact,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD,
- unspecifiedDefaultValue = "50",
- help = CliStrings.CREATE_DISK_STORE__COMPACTION_THRESHOLD__HELP) int compactionThreshold,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE,
- unspecifiedDefaultValue = "1024",
- help = CliStrings.CREATE_DISK_STORE__MAX_OPLOG_SIZE__HELP) int maxOplogSize,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE, unspecifiedDefaultValue = "0",
- help = CliStrings.CREATE_DISK_STORE__QUEUE_SIZE__HELP) int queueSize,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL,
- unspecifiedDefaultValue = "1000",
- help = CliStrings.CREATE_DISK_STORE__TIME_INTERVAL__HELP) long timeInterval,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE,
- unspecifiedDefaultValue = "32768",
- help = CliStrings.CREATE_DISK_STORE__WRITE_BUFFER_SIZE__HELP) int writeBufferSize,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE, mandatory = true,
- help = CliStrings.CREATE_DISK_STORE__DIRECTORY_AND_SIZE__HELP) String[] directoriesAndSizes,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.CREATE_DISK_STORE__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) String[] groups,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT,
- unspecifiedDefaultValue = "90",
- help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_WARNING_PCT__HELP) float diskUsageWarningPercentage,
- @CliOption(key = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT,
- unspecifiedDefaultValue = "99",
- help = CliStrings.CREATE_DISK_STORE__DISK_USAGE_CRITICAL_PCT__HELP) float diskUsageCriticalPercentage) {
-
- try {
- DiskStoreAttributes diskStoreAttributes = new DiskStoreAttributes();
- diskStoreAttributes.allowForceCompaction = allowForceCompaction;
- diskStoreAttributes.autoCompact = autoCompact;
- diskStoreAttributes.compactionThreshold = compactionThreshold;
- diskStoreAttributes.maxOplogSizeInBytes = maxOplogSize * (1024 * 1024);
- diskStoreAttributes.queueSize = queueSize;
- diskStoreAttributes.timeInterval = timeInterval;
- diskStoreAttributes.writeBufferSize = writeBufferSize;
-
- File[] directories = new File[directoriesAndSizes.length];
- int[] sizes = new int[directoriesAndSizes.length];
- for (int i = 0; i < directoriesAndSizes.length; i++) {
- final int hashPosition = directoriesAndSizes[i].indexOf('#');
- if (hashPosition == -1) {
- directories[i] = new File(directoriesAndSizes[i]);
- sizes[i] = Integer.MAX_VALUE;
- } else {
- directories[i] = new File(directoriesAndSizes[i].substring(0, hashPosition));
- sizes[i] = Integer.parseInt(directoriesAndSizes[i].substring(hashPosition + 1));
- }
- }
- diskStoreAttributes.diskDirs = directories;
- diskStoreAttributes.diskDirSizes = sizes;
-
- diskStoreAttributes.setDiskUsageWarningPercentage(diskUsageWarningPercentage);
- diskStoreAttributes.setDiskUsageCriticalPercentage(diskUsageCriticalPercentage);
-
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
- boolean accumulatedData = false;
-
- Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> rc = CliUtil.executeFunction(new CreateDiskStoreFunction(),
- new Object[] {name, diskStoreAttributes}, targetMembers);
- List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
-
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
- + ": " + result.getThrowable().getMessage());
- accumulatedData = true;
- tabularData.setStatus(Result.Status.ERROR);
- } else if (result.isSuccessful()) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Result", result.getMessage());
- accumulatedData = true;
-
- if (xmlEntity.get() == null) {
- xmlEntity.set(result.getXmlEntity());
- }
- }
- }
-
- if (!accumulatedData) {
- return ResultBuilder.createInfoResult("Unable to create disk store(s).");
- }
-
- Result result = ResultBuilder.buildResult(tabularData);
-
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
- }
-
- return ResultBuilder.buildResult(tabularData);
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.CREATE_DISK_STORE__ERROR_WHILE_CREATING_REASON_0,
- new Object[] {th.getMessage()}));
- }
- }
-}
[09/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
new file mode 100644
index 0000000..1415bc6
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommands.java
@@ -0,0 +1,1926 @@
+/*
+ * 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 java.io.BufferedInputStream;
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.zip.DataFormatException;
+import java.util.zip.GZIPInputStream;
+
+import javax.management.ObjectName;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.logging.log4j.Logger;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.LogWriter;
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.Function;
+import org.apache.geode.cache.execute.FunctionException;
+import org.apache.geode.cache.execute.FunctionService;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.distributed.internal.InternalDistributedSystem;
+import org.apache.geode.distributed.internal.deadlock.DeadlockDetector;
+import org.apache.geode.distributed.internal.deadlock.Dependency;
+import org.apache.geode.distributed.internal.deadlock.DependencyGraph;
+import org.apache.geode.distributed.internal.deadlock.GemFireDeadlockDetector;
+import org.apache.geode.internal.cache.GemFireCacheImpl;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.internal.logging.log4j.LogLevel;
+import org.apache.geode.management.CacheServerMXBean;
+import org.apache.geode.management.DistributedRegionMXBean;
+import org.apache.geode.management.DistributedSystemMXBean;
+import org.apache.geode.management.JVMMetrics;
+import org.apache.geode.management.ManagementService;
+import org.apache.geode.management.MemberMXBean;
+import org.apache.geode.management.RegionMXBean;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+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.SystemManagementService;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.CliUtil.DeflaterInflaterData;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.GfshParser;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.domain.StackTracesPerMember;
+import org.apache.geode.management.internal.cli.functions.ChangeLogLevelFunction;
+import org.apache.geode.management.internal.cli.functions.GarbageCollectionFunction;
+import org.apache.geode.management.internal.cli.functions.GetStackTracesFunction;
+import org.apache.geode.management.internal.cli.functions.NetstatFunction;
+import org.apache.geode.management.internal.cli.functions.NetstatFunction.NetstatFunctionArgument;
+import org.apache.geode.management.internal.cli.functions.NetstatFunction.NetstatFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ShutDownFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.ResultData;
+import org.apache.geode.management.internal.cli.result.ResultDataException;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+
+/**
+ * @since GemFire 7.0
+ */
+public class MiscellaneousCommands implements GfshCommand {
+
+ public static final String NETSTAT_FILE_REQUIRED_EXTENSION = ".txt";
+ public final static String DEFAULT_TIME_OUT = "10";
+ private final static Logger logger = LogService.getLogger();
+
+ private final GetStackTracesFunction getStackTracesFunction = new GetStackTracesFunction();
+
+ public void shutdownNode(final long timeout, final Set<DistributedMember> includeMembers)
+ throws TimeoutException, InterruptedException, ExecutionException {
+ ExecutorService exec = Executors.newSingleThreadExecutor();
+ try {
+ final Function shutDownFunction = new ShutDownFunction();
+
+ logger.info("Gfsh executing shutdown on members " + includeMembers);
+
+ Callable<String> shutdownNodes = new Callable<String>() {
+
+ @Override
+ public String call() {
+ try {
+ Execution execution = FunctionService.onMembers(includeMembers);
+ execution.execute(shutDownFunction);
+ } catch (FunctionException functionEx) {
+ // Expected Exception as the function is shutting down the target members and the result
+ // collector will get member departed exception
+ }
+ return "SUCCESS";
+ }
+ };
+
+ Future<String> result = exec.submit(shutdownNodes);
+ result.get(timeout, TimeUnit.MILLISECONDS);
+
+ } catch (TimeoutException te) {
+ logger.error("TimeoutException in shutting down members." + includeMembers);
+ throw te;
+ } catch (InterruptedException e) {
+ logger.error("InterruptedException in shutting down members." + includeMembers);
+ throw e;
+ } catch (ExecutionException e) {
+ logger.error("ExecutionException in shutting down members." + includeMembers);
+ throw e;
+ } finally {
+ exec.shutdownNow();
+ }
+ }
+
+ @CliCommand(value = CliStrings.SHUTDOWN, help = CliStrings.SHUTDOWN__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_LIFECYCLE},
+ interceptor = "org.apache.geode.management.internal.cli.commands.MiscellaneousCommands$Interceptor")
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
+ public Result shutdown(
+ @CliOption(key = CliStrings.SHUTDOWN__TIMEOUT, unspecifiedDefaultValue = DEFAULT_TIME_OUT,
+ help = CliStrings.SHUTDOWN__TIMEOUT__HELP) int userSpecifiedTimeout,
+ @CliOption(key = CliStrings.INCLUDE_LOCATORS, unspecifiedDefaultValue = "false",
+ help = CliStrings.INCLUDE_LOCATORS_HELP) boolean shutdownLocators) {
+ try {
+
+ if (userSpecifiedTimeout < Integer.parseInt(DEFAULT_TIME_OUT)) {
+ return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__IMPROPER_TIMEOUT);
+ }
+
+ // convert to milliseconds
+ long timeout = userSpecifiedTimeout * 1000;
+
+ InternalCache cache = getCache();
+
+ int numDataNodes = CliUtil.getAllNormalMembers(cache).size();
+
+ Set<DistributedMember> locators = CliUtil.getAllMembers(cache);
+
+ Set<DistributedMember> dataNodes = CliUtil.getAllNormalMembers(cache);
+
+ locators.removeAll(dataNodes);
+
+ if (!shutdownLocators && numDataNodes == 0) {
+ return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__NO_DATA_NODE_FOUND);
+ }
+
+ String managerName = cache.getJmxManagerAdvisor().getDistributionManager().getId().getId();
+
+ final DistributedMember manager = CliUtil.getDistributedMemberByNameOrId(managerName);
+
+ dataNodes.remove(manager);
+
+ // shut down all data members excluding this manager if manager is a data node
+ long timeElapsed = shutDownNodeWithTimeOut(timeout, dataNodes);
+ timeout = timeout - timeElapsed;
+
+ // shut down locators one by one
+ if (shutdownLocators) {
+ if (manager == null) {
+ return ResultBuilder.createUserErrorResult(CliStrings.SHUTDOWN__MSG__MANAGER_NOT_FOUND);
+ }
+
+ // remove current locator as that would get shutdown last
+ if (locators.contains(manager)) {
+ locators.remove(manager);
+ }
+
+ for (DistributedMember locator : locators) {
+ Set<DistributedMember> lsSet = new HashSet<>();
+ lsSet.add(locator);
+ long elapsedTime = shutDownNodeWithTimeOut(timeout, lsSet);
+ timeout = timeout - elapsedTime;
+ }
+ }
+
+ if (locators.contains(manager) && !shutdownLocators) { // This means manager is a locator and
+ // shutdownLocators is false. Hence we
+ // should not stop the manager
+ return ResultBuilder.createInfoResult("Shutdown is triggered");
+ }
+ // now shut down this manager
+ Set<DistributedMember> mgrSet = new HashSet<>();
+ mgrSet.add(manager);
+ // No need to check further timeout as this is the last node we will be
+ // shutting down
+ shutDownNodeWithTimeOut(timeout, mgrSet);
+
+ } catch (TimeoutException tex) {
+ return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN_TIMEDOUT);
+ } catch (Exception ex) {
+ ex.printStackTrace();
+ return ResultBuilder.createUserErrorResult(ex.getMessage());
+ }
+
+ // @TODO. List all the nodes which could be successfully shutdown
+ return ResultBuilder.createInfoResult("Shutdown is triggered");
+ }
+
+ /**
+ * @param timeout user specified timeout
+ * @param nodesToBeStopped list of nodes to be stopped
+ * @return Elapsed time to shutdown the given nodes;
+ */
+ private long shutDownNodeWithTimeOut(long timeout, Set<DistributedMember> nodesToBeStopped)
+ throws TimeoutException, InterruptedException, ExecutionException {
+
+ long shutDownTimeStart = System.currentTimeMillis();
+ shutdownNode(timeout, nodesToBeStopped);
+
+ long shutDownTimeEnd = System.currentTimeMillis();
+
+ long timeElapsed = shutDownTimeEnd - shutDownTimeStart;
+
+ if (timeElapsed > timeout || Boolean.getBoolean("ThrowTimeoutException")) {
+ // The second check for ThrowTimeoutException is a test hook
+ throw new TimeoutException();
+ }
+ return timeElapsed;
+ }
+
+ /**
+ * Interceptor used by gfsh to intercept execution of shutdownall.
+ */
+ public static class Interceptor extends AbstractCliAroundInterceptor {
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+
+ // This hook is for testing purpose only.
+ if (Boolean.getBoolean(CliStrings.IGNORE_INTERCEPTORS)) {
+ return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
+ }
+
+ Response response = readYesNo(CliStrings.SHUTDOWN__MSG__WARN_USER, Response.YES);
+ if (response == Response.NO) {
+ return ResultBuilder
+ .createShellClientAbortOperationResult(CliStrings.SHUTDOWN__MSG__ABORTING_SHUTDOWN);
+ } else {
+ return ResultBuilder.createInfoResult(CliStrings.SHUTDOWN__MSG__SHUTDOWN_ENTIRE_DS);
+ }
+ }
+ }
+
+ @CliCommand(value = CliStrings.GC, help = CliStrings.GC__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
+ public Result gc(
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.GC__GROUP__HELP) String[] groups,
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.GC__MEMBER__HELP) String memberId) {
+ InternalCache cache = getCache();
+ Result result;
+ CompositeResultData gcResultTable = ResultBuilder.createCompositeResultData();
+ TabularResultData resultTable = gcResultTable.addSection().addTable("Table1");
+ String headerText = "GC Summary";
+ resultTable.setHeader(headerText);
+ Set<DistributedMember> dsMembers = new HashSet<>();
+ if (memberId != null && memberId.length() > 0) {
+ DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberId);
+ if (member == null) {
+ return ResultBuilder
+ .createGemFireErrorResult(memberId + CliStrings.GC__MSG__MEMBER_NOT_FOUND);
+ }
+ dsMembers.add(member);
+ result = executeAndBuildResult(resultTable, dsMembers);
+ } else if (groups != null && groups.length > 0) {
+ for (String group : groups) {
+ dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(group));
+ }
+ result = executeAndBuildResult(resultTable, dsMembers);
+
+ } else {
+ // gc on entire cluster
+ // exclude locators
+ dsMembers = CliUtil.getAllNormalMembers(cache);
+ result = executeAndBuildResult(resultTable, dsMembers);
+
+ }
+ return result;
+ }
+
+ Result executeAndBuildResult(TabularResultData resultTable, Set<DistributedMember> dsMembers) {
+ try {
+ List<?> resultList;
+ Function garbageCollectionFunction = new GarbageCollectionFunction();
+ resultList =
+ (List<?>) CliUtil.executeFunction(garbageCollectionFunction, null, dsMembers).getResult();
+
+ for (Object object : resultList) {
+ if (object instanceof Exception) {
+ LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
+ ((Throwable) object));
+ continue;
+ } else if (object instanceof Throwable) {
+ LogWrapper.getInstance().fine("Exception in GC " + ((Throwable) object).getMessage(),
+ ((Throwable) object));
+ continue;
+ }
+
+ if (object != null) {
+ if (object instanceof String) {
+ // unexpected exception string - cache may be closed or something
+ return ResultBuilder.createUserErrorResult((String) object);
+ } else {
+ Map<String, String> resultMap = (Map<String, String>) object;
+ toTabularResultData(resultTable, resultMap.get("MemberId"),
+ resultMap.get("HeapSizeBeforeGC"), resultMap.get("HeapSizeAfterGC"),
+ resultMap.get("TimeSpentInGC"));
+ }
+ } else {
+ LogWrapper.getInstance().fine("ResultMap was null ");
+ }
+ }
+ } catch (Exception e) {
+ String stack = CliUtil.stackTraceAsString(e);
+ LogWrapper.getInstance().info("GC exception is " + stack);
+ return ResultBuilder.createGemFireErrorResult(e.getMessage() + ": " + stack);
+ }
+ return ResultBuilder.buildResult(resultTable);
+ }
+
+ protected void toTabularResultData(TabularResultData table, String memberId,
+ String heapSizeBefore, String heapSizeAfter, String timeTaken) {
+ table.accumulate(CliStrings.GC__MSG__MEMBER_NAME, memberId);
+ table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_BEFORE_GC, heapSizeBefore);
+ table.accumulate(CliStrings.GC__MSG__HEAP_SIZE_AFTER_GC, heapSizeAfter);
+ table.accumulate(CliStrings.GC__MSG__TOTAL_TIME_IN_GC, timeTaken);
+ }
+
+ @CliCommand(value = CliStrings.NETSTAT, help = CliStrings.NETSTAT__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ // TODO : Verify the auto-completion for multiple values.
+ public Result netstat(
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.NETSTAT__MEMBER__HELP) String[] members,
+ @CliOption(key = CliStrings.GROUP, optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.NETSTAT__GROUP__HELP) String group,
+ @CliOption(key = CliStrings.NETSTAT__FILE,
+ help = CliStrings.NETSTAT__FILE__HELP) String saveAs,
+ @CliOption(key = CliStrings.NETSTAT__WITHLSOF, specifiedDefaultValue = "true",
+ unspecifiedDefaultValue = "false",
+ help = CliStrings.NETSTAT__WITHLSOF__HELP) boolean withlsof) {
+ Result result;
+
+ Map<String, DistributedMember> hostMemberMap = new HashMap<>();
+ Map<String, List<String>> hostMemberListMap = new HashMap<>();
+
+ try {
+ if (members != null && members.length > 0 && group != null) {
+ throw new IllegalArgumentException(
+ CliStrings.NETSTAT__MSG__ONLY_ONE_OF_MEMBER_OR_GROUP_SHOULD_BE_SPECIFIED);
+ }
+ StringBuilder resultInfo = new StringBuilder();
+
+ // Execute for remote members whose id or name matches
+ InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
+
+ if (members != null) {
+ Set<String> notFoundMembers = new HashSet<>();
+ for (String memberIdOrName : members) {
+ Set<DistributedMember> membersToExecuteOn = CliUtil.getAllMembers(system);
+ boolean memberFound = false;
+ for (DistributedMember distributedMember : membersToExecuteOn) {
+ String memberName = distributedMember.getName();
+ String memberId = distributedMember.getId();
+ if (memberName.equals(memberIdOrName) || memberId.equals(memberIdOrName)) {
+ buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
+
+ memberFound = true;
+ break;
+ }
+ }
+ if (!memberFound) {
+ notFoundMembers.add(memberIdOrName);
+ }
+ }
+ // if there are not found members, it's probably unknown member or member has departed
+ if (!notFoundMembers.isEmpty()) {
+ throw new IllegalArgumentException(
+ CliStrings.format(CliStrings.NETSTAT__MSG__COULD_NOT_FIND_MEMBERS_0,
+ new Object[] {CliUtil.collectionToString(notFoundMembers, -1)}));
+ }
+ } else {
+ Set<DistributedMember> membersToExecuteOn;
+ if (group != null) {
+ membersToExecuteOn = system.getGroupMembers(group);
+ } else {
+ // consider all members
+ membersToExecuteOn = CliUtil.getAllMembers(system);
+ }
+
+ for (DistributedMember distributedMember : membersToExecuteOn) {
+ String memberName = distributedMember.getName();
+ String memberId = distributedMember.getId();
+ String memberIdOrName =
+ memberName != null && !memberName.isEmpty() ? memberName : memberId;
+
+ buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
+ }
+ }
+
+ String lineSeparatorToUse;
+ lineSeparatorToUse = CommandExecutionContext.getShellLineSeparator();
+ if (lineSeparatorToUse == null) {
+ lineSeparatorToUse = GfshParser.LINE_SEPARATOR;
+ }
+ NetstatFunctionArgument nfa = new NetstatFunctionArgument(lineSeparatorToUse, withlsof);
+
+ if (!hostMemberMap.isEmpty()) {
+ Set<DistributedMember> membersToExecuteOn = new HashSet<>(hostMemberMap.values());
+ ResultCollector<?, ?> netstatResult =
+ CliUtil.executeFunction(NetstatFunction.INSTANCE, nfa, membersToExecuteOn);
+ List<?> resultList = (List<?>) netstatResult.getResult();
+ for (Object aResultList : resultList) {
+ NetstatFunctionResult netstatFunctionResult = (NetstatFunctionResult) aResultList;
+ DeflaterInflaterData deflaterInflaterData = netstatFunctionResult.getCompressedBytes();
+ try {
+ String remoteHost = netstatFunctionResult.getHost();
+ List<String> membersList = hostMemberListMap.get(remoteHost);
+ resultInfo.append(MessageFormat.format(netstatFunctionResult.getHeaderInfo(),
+ CliUtil.collectionToString(membersList, 120)));
+ DeflaterInflaterData uncompressedBytes = CliUtil.uncompressBytes(
+ deflaterInflaterData.getData(), deflaterInflaterData.getDataLength());
+ resultInfo.append(new String(uncompressedBytes.getData()));
+ } catch (DataFormatException e) {
+ resultInfo.append("Error in some data. Reason : " + e.getMessage());
+ }
+ }
+ }
+
+ InfoResultData resultData = ResultBuilder.createInfoResultData();
+ if (saveAs != null && !saveAs.isEmpty()) {
+ String saveToFile = saveAs;
+ if (!saveAs.endsWith(NETSTAT_FILE_REQUIRED_EXTENSION)) {
+ saveToFile = saveAs + NETSTAT_FILE_REQUIRED_EXTENSION;
+ }
+ resultData.addAsFile(saveToFile, resultInfo.toString(),
+ CliStrings.NETSTAT__MSG__SAVED_OUTPUT_IN_0, false); // Note: substitution for {0} will
+ // happen on client side.
+ } else {
+ resultData.addLine(resultInfo.toString());
+ }
+ result = ResultBuilder.buildResult(resultData);
+ } catch (IllegalArgumentException e) {
+ LogWrapper.getInstance()
+ .info(CliStrings.format(
+ CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
+ new Object[] {Arrays.toString(members)}));
+ result = ResultBuilder.createUserErrorResult(e.getMessage());
+ } catch (RuntimeException e) {
+ LogWrapper.getInstance()
+ .info(CliStrings.format(
+ CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
+ new Object[] {Arrays.toString(members)}), e);
+ result = ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
+ new Object[] {Arrays.toString(members)}));
+ } finally {
+ hostMemberMap.clear();
+ hostMemberListMap.clear();
+ }
+ return result;
+ }
+
+ private void buildMaps(Map<String, DistributedMember> hostMemberMap,
+ Map<String, List<String>> hostMemberListMap, String memberIdOrName,
+ DistributedMember distributedMember) {
+ String host = distributedMember.getHost();
+
+ // Maintain one member for a host - function execution purpose - once only for a host
+ if (!hostMemberMap.containsKey(host)) {
+ hostMemberMap.put(host, distributedMember);
+ }
+
+ // Maintain all members for a host - display purpose
+ List<String> list;
+ if (!hostMemberListMap.containsKey(host)) {
+ list = new ArrayList<>();
+ hostMemberListMap.put(host, list);
+ } else {
+ list = hostMemberListMap.get(host);
+ }
+ list.add(memberIdOrName);
+ }
+
+ @CliCommand(value = CliStrings.SHOW_DEADLOCK, help = CliStrings.SHOW_DEADLOCK__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result showDeadlock(@CliOption(key = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE,
+ help = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE__HELP,
+ mandatory = true) String filename) {
+
+ Result result;
+ try {
+ if (!filename.endsWith(".txt")) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".txt"));
+ }
+ InternalCache cache = getCache();
+
+ Set<DistributedMember> allMembers = CliUtil.getAllMembers(cache);
+ GemFireDeadlockDetector gfeDeadLockDetector = new GemFireDeadlockDetector(allMembers);
+ DependencyGraph dependencyGraph = gfeDeadLockDetector.find();
+ Collection<Dependency> deadlock = dependencyGraph.findCycle();
+ DependencyGraph deepest = null;
+ if (deadlock == null) {
+ deepest = dependencyGraph.findLongestCallChain();
+ if (deepest != null) {
+ deadlock = deepest.getEdges();
+ }
+ }
+ Set<Dependency> dependencies = (Set<Dependency>) dependencyGraph.getEdges();
+
+ InfoResultData resultData = ResultBuilder.createInfoResultData();
+
+ if (deadlock != null) {
+ if (deepest != null) {
+ resultData.addLine(CliStrings.SHOW_DEADLOCK__DEEPEST_FOUND);
+ } else {
+ resultData.addLine(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED);
+ }
+ resultData.addLine(DeadlockDetector.prettyFormat(deadlock));
+ } else {
+ resultData.addLine(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK);
+ }
+ resultData.addAsFile(filename, DeadlockDetector.prettyFormat(dependencies),
+ MessageFormat.format(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__REVIEW, filename), false);
+ result = ResultBuilder.buildResult(resultData);
+
+ } catch (Exception e) {
+ result = ResultBuilder
+ .createGemFireErrorResult(CliStrings.SHOW_DEADLOCK__ERROR + " : " + e.getMessage());
+ }
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.SHOW_LOG, help = CliStrings.SHOW_LOG_HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result showLog(
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.SHOW_LOG_MEMBER_HELP, mandatory = true) String memberNameOrId,
+ @CliOption(key = CliStrings.SHOW_LOG_LINE_NUM, unspecifiedDefaultValue = "0",
+ help = CliStrings.SHOW_LOG_LINE_NUM_HELP) int numberOfLines) {
+ Result result;
+ try {
+ InternalCache cache = getCache();
+ SystemManagementService service =
+ (SystemManagementService) ManagementService.getExistingManagementService(cache);
+ MemberMXBean bean;
+ DistributedMember memberToBeInvoked = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+ if (memberToBeInvoked != null) {
+ String memberId = memberToBeInvoked.getId();
+
+ if (cache.getDistributedSystem().getDistributedMember().getId().equals(memberId)) {
+ bean = service.getMemberMXBean();
+ } else {
+ ObjectName objectName = service.getMemberMBeanName(memberToBeInvoked);
+ bean = service.getMBeanProxy(objectName, MemberMXBean.class);
+ }
+
+ if (numberOfLines > ManagementConstants.MAX_SHOW_LOG_LINES) {
+ numberOfLines = ManagementConstants.MAX_SHOW_LOG_LINES;
+ }
+ if (numberOfLines == 0 || numberOfLines < 0) {
+ numberOfLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES;
+ }
+ InfoResultData resultData = ResultBuilder.createInfoResultData();
+ if (bean != null) {
+ String log = bean.showLog(numberOfLines);
+ if (log != null) {
+ resultData.addLine(log);
+ } else {
+ resultData.addLine(CliStrings.SHOW_LOG_NO_LOG);
+ }
+ } else {
+ ErrorResultData errorResultData =
+ ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+ .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
+ return (ResultBuilder.buildResult(errorResultData));
+ }
+
+ result = ResultBuilder.buildResult(resultData);
+ } else {
+ ErrorResultData errorResultData =
+ ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
+ .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
+ return (ResultBuilder.buildResult(errorResultData));
+ }
+
+ } catch (Exception e) {
+ result = ResultBuilder
+ .createGemFireErrorResult(CliStrings.SHOW_LOG_ERROR + CliUtil.stackTraceAsString(e));
+ }
+ return result;
+ }
+
+ /**
+ * Current implementation supports writing it to a file and returning the location of the file
+ */
+ @CliCommand(value = CliStrings.EXPORT_STACKTRACE, help = CliStrings.EXPORT_STACKTRACE__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result exportStackTrace(@CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.EXPORT_STACKTRACE__HELP) String[] memberNameOrId,
+
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.GROUP) String[] group,
+
+ @CliOption(key = CliStrings.EXPORT_STACKTRACE__FILE,
+ help = CliStrings.EXPORT_STACKTRACE__FILE__HELP) String fileName,
+
+ @CliOption(key = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT,
+ unspecifiedDefaultValue = "false",
+ help = CliStrings.EXPORT_STACKTRACE__FAIL__IF__FILE__PRESENT__HELP) boolean failIfFilePresent) {
+
+ Result result;
+ StringBuffer filePrefix = new StringBuffer("stacktrace");
+
+ if (fileName == null) {
+ fileName = filePrefix.append("_").append(System.currentTimeMillis()).toString();
+ }
+ final File outFile = new File(fileName);
+ try {
+ if (outFile.exists() && failIfFilePresent) {
+ return ResultBuilder.createShellClientErrorResult(CliStrings.format(
+ CliStrings.EXPORT_STACKTRACE__ERROR__FILE__PRESENT, outFile.getCanonicalPath()));
+ }
+
+
+ InternalCache cache = getCache();
+ InternalDistributedSystem ads = cache.getInternalDistributedSystem();
+
+ InfoResultData resultData = ResultBuilder.createInfoResultData();
+
+ Map<String, byte[]> dumps = new HashMap<>();
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(getStackTracesFunction, null, targetMembers);
+ ArrayList<Object> resultList = (ArrayList<Object>) rc.getResult();
+
+ for (Object resultObj : resultList) {
+ if (resultObj instanceof StackTracesPerMember) {
+ StackTracesPerMember stackTracePerMember = (StackTracesPerMember) resultObj;
+ dumps.put(stackTracePerMember.getMemberNameOrId(), stackTracePerMember.getStackTraces());
+ }
+ }
+
+ String filePath = writeStacksToFile(dumps, fileName);
+ resultData.addLine(CliStrings.format(CliStrings.EXPORT_STACKTRACE__SUCCESS, filePath));
+ resultData.addLine(CliStrings.EXPORT_STACKTRACE__HOST + ads.getDistributedMember().getHost());
+
+ result = ResultBuilder.buildResult(resultData);
+ } catch (IOException ex) {
+ result = ResultBuilder
+ .createGemFireErrorResult(CliStrings.EXPORT_STACKTRACE__ERROR + ex.getMessage());
+ }
+ return result;
+ }
+
+ /**
+ * Interceptor used by gfsh to intercept execution of shutdownall.
+ */
+ public static class ExportStackTraceInterceptor extends AbstractCliAroundInterceptor {
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+
+ Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+ String fileName = paramValueMap.get(CliStrings.EXPORT_STACKTRACE__FILE);
+
+ Response response = readYesNo(
+ CliStrings.format(CliStrings.EXPORT_STACKTRACE_WARN_USER, fileName), Response.YES);
+ if (response == Response.NO) {
+ return ResultBuilder
+ .createShellClientAbortOperationResult(CliStrings.EXPORT_STACKTRACE_MSG_ABORTING);
+ } else {
+ // we don't to show any info result
+ return ResultBuilder.createInfoResult("");
+ }
+ }
+ }
+
+ /***
+ * Writes the Stack traces member-wise to a text file
+ *
+ * @param dumps - Map containing key : member , value : zipped stack traces
+ * @param fileName - Name of the file to which the stack-traces are written to
+ * @return Canonical path of the file which contains the stack-traces
+ * @throws IOException
+ */
+ private String writeStacksToFile(Map<String, byte[]> dumps, String fileName) throws IOException {
+ String filePath;
+ PrintWriter ps;
+ File outputFile;
+
+ outputFile = new File(fileName);
+ try (OutputStream os = new FileOutputStream(outputFile)) {
+ ps = new PrintWriter(os);
+
+ for (Entry<String, byte[]> entry : dumps.entrySet()) {
+ ps.append("*** Stack-trace for member " + entry.getKey() + " ***");
+ ps.flush();
+ GZIPInputStream zipIn = new GZIPInputStream(new ByteArrayInputStream(entry.getValue()));
+ BufferedInputStream bin = new BufferedInputStream(zipIn);
+ byte[] buffer = new byte[10000];
+ int count;
+ while ((count = bin.read(buffer)) != -1) {
+ os.write(buffer, 0, count);
+ }
+ ps.append('\n');
+ }
+ ps.flush();
+ filePath = outputFile.getCanonicalPath();
+ }
+
+ return filePath;
+ }
+
+ @CliCommand(value = CliStrings.SHOW_METRICS, help = CliStrings.SHOW_METRICS__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_STATISTICS})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result showMetrics(
+ @CliOption(key = {CliStrings.MEMBER}, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.SHOW_METRICS__MEMBER__HELP) String memberNameOrId,
+ @CliOption(key = {CliStrings.SHOW_METRICS__REGION}, optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.SHOW_METRICS__REGION__HELP) String regionName,
+ @CliOption(key = {CliStrings.SHOW_METRICS__FILE},
+ help = CliStrings.SHOW_METRICS__FILE__HELP) String export_to_report_to,
+ @CliOption(key = {CliStrings.SHOW_METRICS__CACHESERVER__PORT},
+ help = CliStrings.SHOW_METRICS__CACHESERVER__PORT__HELP) String cacheServerPortString,
+ @CliOption(key = {CliStrings.SHOW_METRICS__CATEGORY},
+ help = CliStrings.SHOW_METRICS__CATEGORY__HELP) String[] categories) {
+
+ Result result;
+ try {
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ if (!export_to_report_to.endsWith(".csv")) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".csv"));
+ }
+ }
+ if (regionName != null && !regionName.isEmpty()) {
+
+ if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
+ }
+
+ // MBean names contain the forward slash
+ if (!regionName.startsWith("/")) {
+ regionName = "/" + regionName;
+ }
+
+ if (memberNameOrId == null || memberNameOrId.isEmpty()) {
+ result = ResultBuilder.buildResult(
+ getDistributedRegionMetrics(regionName, export_to_report_to, categories));
+ } else {
+ DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+
+ if (member != null) {
+ result = ResultBuilder.buildResult(
+ getRegionMetricsFromMember(regionName, member, export_to_report_to, categories));
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(
+ CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
+ result = ResultBuilder.buildResult(erd);
+ }
+ }
+ } else if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
+
+ DistributedMember member = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+
+ if (member != null) {
+ int cacheServerPort = -1;
+ if (cacheServerPortString != null && !cacheServerPortString.isEmpty()) {
+ try {
+ cacheServerPort = Integer.parseInt(cacheServerPortString);
+ } catch (NumberFormatException nfe) {
+ return ResultBuilder.createUserErrorResult("Invalid port");
+ }
+ }
+ result = ResultBuilder.buildResult(
+ getMemberMetrics(member, export_to_report_to, categories, cacheServerPort));
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberNameOrId));
+ result = ResultBuilder.buildResult(erd);
+ }
+ } else {
+ if (!org.apache.geode.internal.lang.StringUtils.isBlank(cacheServerPortString)) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.SHOW_METRICS__CANNOT__USE__CACHESERVERPORT);
+ }
+ result = ResultBuilder.buildResult(getSystemWideMetrics(export_to_report_to, categories));
+ }
+ } catch (Exception e) {
+ logger.error(e.getMessage(), e);
+ return ResultBuilder.createGemFireErrorResult(CliUtil.stackTraceAsString(e));
+ }
+ return result;
+ }
+
+ /**
+ * Gets the system wide metrics
+ *
+ * @return ResultData with required System wide statistics or ErrorResultData if DS MBean is not
+ * found to gather metrics
+ */
+ private ResultData getSystemWideMetrics(String export_to_report_to, String[] categoriesArr) {
+ final InternalCache cache = getCache();
+ final ManagementService managementService = ManagementService.getManagementService(cache);
+ DistributedSystemMXBean dsMxBean = managementService.getDistributedSystemMXBean();
+ StringBuilder csvBuilder = null;
+ if (dsMxBean != null) {
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ csvBuilder = new StringBuilder();
+ csvBuilder.append("Category");
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+ csvBuilder.append('\n');
+ }
+
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+ SectionResultData section = crd.addSection();
+ TabularResultData metricsTable = section.addTable();
+ Map<String, Boolean> categoriesMap = getSystemMetricsCategories();
+
+ if (categoriesArr != null && categoriesArr.length != 0) {
+ Set<String> categories = createSet(categoriesArr);
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+ Set<String> userCategories = getSetDifference(categories, checkSet);
+
+ // Checking if the categories specified by the user are valid or not
+
+ if (userCategories.isEmpty()) {
+ for (String category : checkSet) {
+ categoriesMap.put(category, false);
+ }
+ for (String category : categories) {
+ categoriesMap.put(category.toLowerCase(), true);
+ }
+ } else {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Invalid Categories\n");
+
+ for (String category : userCategories) {
+ sb.append(category);
+ sb.append('\n');
+ }
+ return ResultBuilder.createErrorResultData().addLine(sb.toString());
+ }
+ }
+ metricsTable.setHeader("Cluster-wide Metrics");
+
+ if (categoriesMap.get("cluster")) {
+ writeToTableAndCsv(metricsTable, "cluster", "totalHeapSize", dsMxBean.getTotalHeapSize(),
+ csvBuilder);
+ }
+
+ if (categoriesMap.get("cache")) {
+ writeToTableAndCsv(metricsTable, "cache", "totalRegionEntryCount",
+ dsMxBean.getTotalRegionEntryCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalRegionCount", dsMxBean.getTotalRegionCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalMissCount", dsMxBean.getTotalMissCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalHitCount", dsMxBean.getTotalHitCount(),
+ csvBuilder);
+ }
+
+ if (categoriesMap.get("diskstore")) {
+ writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
+ dsMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
+ writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
+ dsMxBean.getDiskReadsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskWritesRate", dsMxBean.getDiskWritesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
+ dsMxBean.getDiskFlushAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
+ dsMxBean.getTotalBackupInProgress(), csvBuilder);
+ }
+
+ if (categoriesMap.get("query")) {
+ writeToTableAndCsv(metricsTable, "query", "activeCQCount", dsMxBean.getActiveCQCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "queryRequestRate", dsMxBean.getQueryRequestRate(),
+ csvBuilder);
+ }
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ crd.addAsFile(export_to_report_to, csvBuilder.toString(),
+ "Cluster wide metrics exported to {0}.", false);
+ }
+
+ return crd;
+ } else {
+ String errorMessage =
+ CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Distributed System MBean not found");
+ return ResultBuilder.createErrorResultData().addLine(errorMessage);
+ }
+ }
+
+ /**
+ * Gets the Cluster wide metrics for a given member
+ *
+ * @return ResultData with required Member statistics or ErrorResultData if MemberMbean is not
+ * found to gather metrics
+ * @throws ResultDataException if building result fails
+ */
+ private ResultData getMemberMetrics(DistributedMember distributedMember,
+ String export_to_report_to, String[] categoriesArr, int cacheServerPort)
+ throws ResultDataException {
+ final InternalCache cache = getCache();
+ final SystemManagementService managementService =
+ (SystemManagementService) ManagementService.getManagementService(cache);
+
+ ObjectName memberMBeanName = managementService.getMemberMBeanName(distributedMember);
+ MemberMXBean memberMxBean =
+ managementService.getMBeanInstance(memberMBeanName, MemberMXBean.class);
+ ObjectName csMxBeanName;
+ CacheServerMXBean csMxBean = null;
+
+ if (memberMxBean != null) {
+
+ if (cacheServerPort != -1) {
+ csMxBeanName =
+ managementService.getCacheServerMBeanName(cacheServerPort, distributedMember);
+ csMxBean = managementService.getMBeanInstance(csMxBeanName, CacheServerMXBean.class);
+
+ if (csMxBean == null) {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(CliStrings.format(CliStrings.SHOW_METRICS__CACHE__SERVER__NOT__FOUND,
+ cacheServerPort, MBeanJMXAdapter.getMemberNameOrId(distributedMember)));
+ return erd;
+ }
+ }
+
+ JVMMetrics jvmMetrics = memberMxBean.showJVMMetrics();
+
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+ SectionResultData section = crd.addSection();
+ TabularResultData metricsTable = section.addTable();
+ metricsTable.setHeader("Member Metrics");
+ StringBuilder csvBuilder = null;
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ csvBuilder = new StringBuilder();
+ csvBuilder.append("Category");
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+ csvBuilder.append('\n');
+ }
+
+ Map<String, Boolean> categoriesMap = getMemberMetricsCategories();
+
+ if (categoriesArr != null && categoriesArr.length != 0) {
+ Set<String> categories = createSet(categoriesArr);
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+ Set<String> userCategories = getSetDifference(categories, checkSet);
+
+ // Checking if the categories specified by the user are valid or not
+ if (userCategories.isEmpty()) {
+ for (String category : checkSet) {
+ categoriesMap.put(category, false);
+ }
+ for (String category : categories) {
+ categoriesMap.put(category.toLowerCase(), true);
+ }
+ } else {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Invalid Categories\n");
+
+ for (String category : userCategories) {
+ sb.append(category);
+ sb.append('\n');
+ }
+ return ResultBuilder.createErrorResultData().addLine(sb.toString());
+ }
+ }
+
+ /*
+ * Member Metrics
+ */
+ // member, jvm, region, serialization, communication, function, transaction, diskstore, lock,
+ // eviction, distribution
+ if (categoriesMap.get("member")) {
+ writeToTableAndCsv(metricsTable, "member", "upTime", memberMxBean.getMemberUpTime(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "cpuUsage", memberMxBean.getCpuUsage(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "currentHeapSize", memberMxBean.getCurrentHeapSize(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "maximumHeapSize", memberMxBean.getMaximumHeapSize(),
+ csvBuilder);
+ }
+ /*
+ * JVM Metrics
+ */
+ if (categoriesMap.get("jvm")) {
+ writeToTableAndCsv(metricsTable, "jvm ", "jvmThreads ", jvmMetrics.getTotalThreads(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "fileDescriptorLimit",
+ memberMxBean.getFileDescriptorLimit(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalFileDescriptorOpen",
+ memberMxBean.getTotalFileDescriptorOpen(), csvBuilder);
+ }
+ /*
+ * Member wide region metrics
+ */
+ if (categoriesMap.get("region")) {
+ writeToTableAndCsv(metricsTable, "region ", "totalRegionCount ",
+ memberMxBean.getTotalRegionCount(), csvBuilder);
+ String[] regionNames = memberMxBean.listRegions();
+ if (regionNames != null) {
+ for (int i = 0; i < regionNames.length; i++) {
+ if (i == 0) {
+ writeToTableAndCsv(metricsTable, "", "listOfRegions", regionNames[i].substring(1),
+ csvBuilder);
+ } else {
+ writeToTableAndCsv(metricsTable, "", "", regionNames[i].substring(1), csvBuilder);
+ }
+ }
+ }
+
+ String[] rootRegionNames = memberMxBean.getRootRegionNames();
+ if (rootRegionNames != null) {
+ for (int i = 0; i < rootRegionNames.length; i++) {
+ if (i == 0) {
+ writeToTableAndCsv(metricsTable, "", "rootRegions", rootRegionNames[i], csvBuilder);
+ } else {
+ writeToTableAndCsv(metricsTable, "", "", rootRegionNames[i], csvBuilder);
+ }
+ }
+ }
+ writeToTableAndCsv(metricsTable, "", "totalRegionEntryCount",
+ memberMxBean.getTotalRegionEntryCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalBucketCount", memberMxBean.getTotalBucketCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalPrimaryBucketCount",
+ memberMxBean.getTotalPrimaryBucketCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getsAvgLatency", memberMxBean.getGetsAvgLatency(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putsAvgLatency", memberMxBean.getPutsAvgLatency(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "createsRate", memberMxBean.getCreatesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "destroyRate", memberMxBean.getDestroysRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putAllAvgLatency", memberMxBean.getPutAllAvgLatency(),
+ csvBuilder);
+ // Not available from stats. After Stats re-org it will be available
+ // writeToTableAndCsv(metricsTable, "", "getAllAvgLatency",
+ // memberMxBean.getGetAllAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalMissCount", memberMxBean.getTotalMissCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalHitCount", memberMxBean.getTotalHitCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getsRate", memberMxBean.getGetsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putsRate", memberMxBean.getPutsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "cacheWriterCallsAvgLatency",
+ memberMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
+ memberMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalLoadsCompleted",
+ memberMxBean.getTotalLoadsCompleted(), csvBuilder);
+ }
+
+ /*
+ * SERIALIZATION
+ */
+ if (categoriesMap.get("serialization")) {
+ writeToTableAndCsv(metricsTable, "serialization", "serializationRate",
+ memberMxBean.getSerializationRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "serializationLatency",
+ memberMxBean.getSerializationRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "deserializationRate",
+ memberMxBean.getDeserializationRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "deserializationLatency",
+ memberMxBean.getDeserializationLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "deserializationAvgLatency",
+ memberMxBean.getDeserializationAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "PDXDeserializationAvgLatency",
+ memberMxBean.getPDXDeserializationAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "PDXDeserializationRate",
+ memberMxBean.getPDXDeserializationRate(), csvBuilder);
+ }
+
+ /*
+ * Communication Metrics
+ */
+ if (categoriesMap.get("communication")) {
+ writeToTableAndCsv(metricsTable, "communication", "bytesSentRate",
+ memberMxBean.getBytesSentRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "bytesReceivedRate",
+ memberMxBean.getBytesReceivedRate(), csvBuilder);
+ String[] connectedGatewayReceivers = memberMxBean.listConnectedGatewayReceivers();
+ writeToTableAndCsv(metricsTable, "", "connectedGatewayReceivers", connectedGatewayReceivers,
+ csvBuilder);
+
+ String[] connectedGatewaySenders = memberMxBean.listConnectedGatewaySenders();
+ writeToTableAndCsv(metricsTable, "", "connectedGatewaySenders", connectedGatewaySenders,
+ csvBuilder);
+ }
+
+ /*
+ * Member wide function metrics
+ */
+ if (categoriesMap.get("function")) {
+ writeToTableAndCsv(metricsTable, "function", "numRunningFunctions",
+ memberMxBean.getNumRunningFunctions(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "functionExecutionRate",
+ memberMxBean.getFunctionExecutionRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "numRunningFunctionsHavingResults",
+ memberMxBean.getNumRunningFunctionsHavingResults(), csvBuilder);
+ }
+
+ /*
+ * totalTransactionsCount currentTransactionalThreadIds transactionCommitsAvgLatency
+ * transactionCommittedTotalCount transactionRolledBackTotalCount transactionCommitsRate
+ */
+ if (categoriesMap.get("transaction")) {
+ writeToTableAndCsv(metricsTable, "transaction", "totalTransactionsCount",
+ memberMxBean.getTotalTransactionsCount(), csvBuilder);
+
+ writeToTableAndCsv(metricsTable, "", "transactionCommitsAvgLatency",
+ memberMxBean.getTransactionCommitsAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "transactionCommittedTotalCount",
+ memberMxBean.getTransactionCommittedTotalCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "transactionRolledBackTotalCount",
+ memberMxBean.getTransactionRolledBackTotalCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "transactionCommitsRate",
+ memberMxBean.getTransactionCommitsRate(), csvBuilder);
+ }
+ /*
+ * Member wide disk metrics
+ */
+ if (categoriesMap.get("diskstore")) {
+ writeToTableAndCsv(metricsTable, "diskstore", "totalDiskUsage",
+ memberMxBean.getTotalDiskUsage(), csvBuilder); // deadcoded to workaround bug 46397
+ writeToTableAndCsv(metricsTable, ""/* 46608 */, "diskReadsRate",
+ memberMxBean.getDiskReadsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskWritesRate", memberMxBean.getDiskWritesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "flushTimeAvgLatency",
+ memberMxBean.getDiskFlushAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalQueueSize",
+ memberMxBean.getTotalDiskTasksWaiting(), csvBuilder); // deadcoded to workaround bug
+ // 46397
+ writeToTableAndCsv(metricsTable, "", "totalBackupInProgress",
+ memberMxBean.getTotalBackupInProgress(), csvBuilder);
+ }
+ /*
+ * Member wide Lock
+ */
+ if (categoriesMap.get("lock")) {
+ writeToTableAndCsv(metricsTable, "lock", "lockWaitsInProgress",
+ memberMxBean.getLockWaitsInProgress(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalLockWaitTime",
+ memberMxBean.getTotalLockWaitTime(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalNumberOfLockService",
+ memberMxBean.getTotalNumberOfLockService(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "requestQueues", memberMxBean.getLockRequestQueues(),
+ csvBuilder);
+ }
+ /*
+ * Eviction
+ */
+ if (categoriesMap.get("eviction")) {
+ writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
+ memberMxBean.getLruEvictionRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "lruDestroyRate", memberMxBean.getLruDestroyRate(),
+ csvBuilder);
+ }
+ /*
+ * Distribution
+ */
+ if (categoriesMap.get("distribution")) {
+ writeToTableAndCsv(metricsTable, "distribution", "getInitialImagesInProgress",
+ memberMxBean.getInitialImagesInProgress(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getInitialImageTime",
+ memberMxBean.getInitialImageTime(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getInitialImageKeysReceived",
+ memberMxBean.getInitialImageKeysReceived(), csvBuilder);
+ }
+
+ /*
+ * OffHeap
+ */
+ if (categoriesMap.get("offheap")) {
+ writeToTableAndCsv(metricsTable, "offheap", "maxMemory", memberMxBean.getOffHeapMaxMemory(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "freeMemory", memberMxBean.getOffHeapFreeMemory(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "usedMemory", memberMxBean.getOffHeapUsedMemory(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "objects", memberMxBean.getOffHeapObjects(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "fragmentation",
+ memberMxBean.getOffHeapFragmentation(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "compactionTime",
+ memberMxBean.getOffHeapCompactionTime(), csvBuilder);
+ }
+
+ /*
+ * CacheServer stats
+ */
+ if (csMxBean != null) {
+ writeToTableAndCsv(metricsTable, "cache-server", "clientConnectionCount",
+ csMxBean.getClientConnectionCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "hostnameForClients", csMxBean.getHostNameForClients(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getRequestAvgLatency",
+ csMxBean.getGetRequestAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRequestAvgLatency",
+ csMxBean.getPutRequestAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalConnectionsTimedOut",
+ csMxBean.getTotalConnectionsTimedOut(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "threadQueueSize", csMxBean.getPutRequestAvgLatency(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "connectionThreads", csMxBean.getConnectionThreads(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "connectionLoad", csMxBean.getConnectionLoad(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "loadPerConnection", csMxBean.getLoadPerConnection(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "queueLoad", csMxBean.getQueueLoad(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "loadPerQueue", csMxBean.getLoadPerQueue(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getRequestRate", csMxBean.getGetRequestRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRequestRate", csMxBean.getPutRequestRate(),
+ csvBuilder);
+
+ /*
+ * Notification
+ */
+ writeToTableAndCsv(metricsTable, "notification", "numClientNotificationRequests",
+ csMxBean.getNumClientNotificationRequests(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "clientNotificationRate",
+ csMxBean.getClientNotificationRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "clientNotificationAvgLatency",
+ csMxBean.getClientNotificationAvgLatency(), csvBuilder);
+
+ /*
+ * Query
+ */
+ writeToTableAndCsv(metricsTable, "query", "activeCQCount", csMxBean.getActiveCQCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "query", "queryRequestRate",
+ csMxBean.getQueryRequestRate(), csvBuilder);
+
+ writeToTableAndCsv(metricsTable, "", "indexCount", csMxBean.getIndexCount(), csvBuilder);
+
+ String[] indexList = csMxBean.getIndexList();
+ writeToTableAndCsv(metricsTable, "", "index list", indexList, csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalIndexMaintenanceTime",
+ csMxBean.getTotalIndexMaintenanceTime(), csvBuilder);
+ }
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ crd.addAsFile(export_to_report_to, csvBuilder.toString(), "Member metrics exported to {0}.",
+ false);
+ }
+ return crd;
+
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Member MBean for "
+ + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
+ return ResultBuilder.createErrorResultData().addLine(errorMessage);
+ }
+ }
+
+ /**
+ * Gets the Cluster-wide metrics for a region
+ *
+ * @return ResultData containing the table
+ * @throws ResultDataException if building result fails
+ */
+ private ResultData getDistributedRegionMetrics(String regionName, String export_to_report_to,
+ String[] categoriesArr) throws ResultDataException {
+
+ final InternalCache cache = getCache();
+ final ManagementService managementService = ManagementService.getManagementService(cache);
+
+ DistributedRegionMXBean regionMxBean = managementService.getDistributedRegionMXBean(regionName);
+
+ if (regionMxBean != null) {
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+ SectionResultData section = crd.addSection();
+ TabularResultData metricsTable = section.addTable();
+ metricsTable.setHeader("Cluster-wide Region Metrics");
+ StringBuilder csvBuilder = null;
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ csvBuilder = new StringBuilder();
+ csvBuilder.append("Category");
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+ csvBuilder.append('\n');
+ }
+
+ Map<String, Boolean> categoriesMap = getSystemRegionMetricsCategories();
+
+ if (categoriesArr != null && categoriesArr.length != 0) {
+ Set<String> categories = createSet(categoriesArr);
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+ Set<String> userCategories = getSetDifference(categories, checkSet);
+
+ // Checking if the categories specified by the user are valid or not
+ if (userCategories.isEmpty()) {
+ for (String category : checkSet) {
+ categoriesMap.put(category, false);
+ }
+ for (String category : categories) {
+ categoriesMap.put(category.toLowerCase(), true);
+ }
+ } else {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Invalid Categories\n");
+
+ for (String category : userCategories) {
+ sb.append(category);
+ sb.append('\n');
+ }
+ return ResultBuilder.createErrorResultData().addLine(sb.toString());
+ }
+ }
+ /*
+ * General System metrics
+ */
+ // cluster, region, partition , diskstore, callback, eviction
+ if (categoriesMap.get("cluster")) {
+ writeToTableAndCsv(metricsTable, "cluster", "member count", regionMxBean.getMemberCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "region entry count",
+ regionMxBean.getSystemRegionEntryCount(), csvBuilder);
+ }
+
+ if (categoriesMap.get("region")) {
+ writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
+ regionMxBean.getLastModifiedTime(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
+ csvBuilder);
+ }
+
+ if (categoriesMap.get("partition")) {
+ writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
+ regionMxBean.getPutLocalRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
+ regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
+
+ writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
+ regionMxBean.getPrimaryBucketCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
+ regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "averageBucketSize", regionMxBean.getAvgBucketSize(),
+ csvBuilder);
+ }
+ /*
+ * Disk store
+ */
+ if (categoriesMap.get("diskstore")) {
+ writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
+ regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskReadsRate", regionMxBean.getDiskReadsRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
+ regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
+ csvBuilder);
+
+ }
+ /*
+ * LISTENER
+ */
+ if (categoriesMap.get("callback")) {
+ writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
+ regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
+ regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
+ }
+
+ /*
+ * Eviction
+ */
+ if (categoriesMap.get("eviction")) {
+ writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
+ regionMxBean.getLruEvictionRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
+ csvBuilder);
+ }
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ crd.addAsFile(export_to_report_to, csvBuilder.toString(),
+ "Aggregate Region Metrics exported to {0}.", false);
+ }
+
+ return crd;
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
+ "Distributed Region MBean for " + regionName + " not found");
+ erd.addLine(errorMessage);
+ return erd;
+ }
+ }
+
+ /**
+ * Gets the metrics of region on a given member
+ *
+ * @return ResultData with required Region statistics or ErrorResultData if Region MBean is not
+ * found to gather metrics
+ * @throws ResultDataException if building result fails
+ */
+ private ResultData getRegionMetricsFromMember(String regionName,
+ DistributedMember distributedMember, String export_to_report_to, String[] categoriesArr)
+ throws ResultDataException {
+
+ final InternalCache cache = getCache();
+ final SystemManagementService managementService =
+ (SystemManagementService) ManagementService.getManagementService(cache);
+
+ ObjectName regionMBeanName =
+ managementService.getRegionMBeanName(distributedMember, regionName);
+ RegionMXBean regionMxBean =
+ managementService.getMBeanInstance(regionMBeanName, RegionMXBean.class);
+
+ if (regionMxBean != null) {
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+ SectionResultData section = crd.addSection();
+ TabularResultData metricsTable = section.addTable();
+ metricsTable.setHeader("Metrics for region:" + regionName + " On Member "
+ + MBeanJMXAdapter.getMemberNameOrId(distributedMember));
+ StringBuilder csvBuilder = null;
+
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ csvBuilder = new StringBuilder();
+ csvBuilder.append("Category");
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
+ csvBuilder.append(',');
+ csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
+ csvBuilder.append('\n');
+ }
+
+ /*
+ * Region Metrics
+ */
+ Map<String, Boolean> categoriesMap = getRegionMetricsCategories();
+
+ if (categoriesArr != null && categoriesArr.length != 0) {
+ Set<String> categories = createSet(categoriesArr);
+ Set<String> checkSet = new HashSet<>(categoriesMap.keySet());
+ Set<String> userCategories = getSetDifference(categories, checkSet);
+
+ // Checking if the categories specified by the user are valid or not
+ if (userCategories.isEmpty()) {
+ for (String category : checkSet) {
+ categoriesMap.put(category, false);
+ }
+ for (String category : categories) {
+ categoriesMap.put(category.toLowerCase(), true);
+ }
+ } else {
+ StringBuilder sb = new StringBuilder();
+ sb.append("Invalid Categories\n");
+
+ for (String category : userCategories) {
+ sb.append(category);
+ sb.append('\n');
+ }
+ return ResultBuilder.createErrorResultData().addLine(sb.toString());
+ }
+ }
+
+ if (categoriesMap.get("region")) {
+ writeToTableAndCsv(metricsTable, "region", "lastModifiedTime",
+ regionMxBean.getLastModifiedTime(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(),
+ csvBuilder);
+ }
+
+ if (categoriesMap.get("partition")) {
+ writeToTableAndCsv(metricsTable, "partition", "putLocalRate",
+ regionMxBean.getPutLocalRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency",
+ regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
+
+ writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "primaryBucketCount",
+ regionMxBean.getPrimaryBucketCount(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "configuredRedundancy",
+ regionMxBean.getConfiguredRedundancy(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "actualRedundancy", regionMxBean.getActualRedundancy(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy",
+ regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(),
+ csvBuilder);
+ }
+ /*
+ * Disk store
+ */
+ if (categoriesMap.get("diskstore")) {
+ writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk",
+ regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskReadsRate", "" + regionMxBean.getDiskReadsRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(),
+ csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress",
+ regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(),
+ csvBuilder);
+ }
+ /*
+ * LISTENER
+ */
+ if (categoriesMap.get("callback")) {
+ writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency",
+ regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency",
+ regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
+ }
+
+ /*
+ * Eviction
+ */
+ if (categoriesMap.get("eviction")) {
+ writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate",
+ regionMxBean.getLruEvictionRate(), csvBuilder);
+ writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(),
+ csvBuilder);
+ }
+ if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
+ crd.addAsFile(export_to_report_to, csvBuilder.toString(), "Region Metrics exported to {0}.",
+ false);
+ }
+
+ return crd;
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR,
+ "Region MBean for " + regionName + " on member "
+ + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
+ erd.addLine(errorMessage);
+ return erd;
+ }
+ }
+
+ /***
+ * Writes an entry to a TabularResultData and writes a comma separated entry to a string builder
+ */
+ private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
+ long metricValue, StringBuilder csvBuilder) {
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
+
+ if (csvBuilder != null) {
+ csvBuilder.append(type);
+ csvBuilder.append(',');
+ csvBuilder.append(metricName);
+ csvBuilder.append(',');
+ csvBuilder.append(metricValue);
+ csvBuilder.append('\n');
+ }
+ }
+
+ private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
+ double metricValue, StringBuilder csvBuilder) {
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
+
+ if (csvBuilder != null) {
+ csvBuilder.append(type);
+ csvBuilder.append(',');
+ csvBuilder.append(metricName);
+ csvBuilder.append(',');
+ csvBuilder.append(metricValue);
+ csvBuilder.append('\n');
+ }
+ }
+
+ private Set<String> createSet(String[] categories) {
+ Set<String> categoriesSet = new HashSet<>();
+ Collections.addAll(categoriesSet, categories);
+ return categoriesSet;
+ }
+
+ /**
+ * Defines and returns map of categories for System metrics.
+ *
+ * @return map with categories for system metrics and display flag set to true
+ */
+ private Map<String, Boolean> getSystemMetricsCategories() {
+ Map<String, Boolean> categories = new HashMap<>();
+ categories.put("cluster", true);
+ categories.put("cache", true);
+ categories.put("diskstore", true);
+ categories.put("query", true);
+ return categories;
+ }
+
+ /**
+ * Defines and returns map of categories for Region Metrics
+ *
+ * @return map with categories for region metrics and display flag set to true
+ */
+ private Map<String, Boolean> getRegionMetricsCategories() {
+ Map<String, Boolean> categories = new HashMap<>();
+
+ categories.put("region", true);
+ categories.put("partition", true);
+ categories.put("diskstore", true);
+ categories.put("callback", true);
+ categories.put("gatewayreceiver", true);
+ categories.put("distribution", true);
+ categories.put("query", true);
+ categories.put("eviction", true);
+ return categories;
+ }
+
+ /**
+ * Defines and returns map of categories for system-wide region metrics
+ *
+ * @return map with categories for system wide region metrics and display flag set to true
+ */
+ private Map<String, Boolean> getSystemRegionMetricsCategories() {
+ Map<String, Boolean> categories = getRegionMetricsCategories();
+ categories.put("cluster", true);
+ return categories;
+ }
+
+ /**
+ * Defines and returns map of categories for member metrics
+ *
+ * @return map with categories for member metrics and display flag set to true
+ */
+ private Map<String, Boolean> getMemberMetricsCategories() {
+ Map<String, Boolean> categories = new HashMap<>();
+ categories.put("member", true);
+ categories.put("jvm", true);
+ categories.put("region", true);
+ categories.put("serialization", true);
+ categories.put("communication", true);
+ categories.put("function", true);
+ categories.put("transaction", true);
+ categories.put("diskstore", true);
+ categories.put("lock", true);
+ categories.put("eviction", true);
+ categories.put("distribution", true);
+ categories.put("offheap", true);
+ return categories;
+ }
+
+ /**
+ * Converts an array of strings to a String delimited by a new line character for display purposes
+ *
+ * @return a String delimited by a new line character for display purposes
+ */
+ private String formatNames(String[] names, int startIndex) {
+ StringBuilder sb = new StringBuilder();
+
+ if (names != null) {
+ for (String name : names) {
+ sb.append(name.substring(startIndex));
+ sb.append('\n');
+ }
+ }
+ return sb.toString();
+ }
+
+ private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
+ String metricValue[], StringBuilder csvBuilder) {
+ if (metricValue != null) {
+ for (int i = 0; i < metricValue.length; i++) {
+ if (i == 0) {
+ writeToTableAndCsv(metricsTable, type, metricName, metricValue[i], csvBuilder);
+ } else {
+ writeToTableAndCsv(metricsTable, "", "", metricValue[i], csvBuilder);
+ }
+ }
+ }
+ }
+
+ /**
+ * Writes to a TabularResultData and also appends a CSV string to a String builder
+ */
+ private void writeToTableAndCsv(TabularResultData metricsTable, String type, String metricName,
+ String metricValue, StringBuilder csvBuilder) {
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__TYPE__HEADER, type);
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__METRIC__HEADER, metricName);
+ metricsTable.accumulate(CliStrings.SHOW_METRICS__VALUE__HEADER, metricValue);
+
+ if (csvBuilder != null) {
+ csvBuilder.append(type);
+ csvBuilder.append(',');
+ csvBuilder.append(metricName);
+ csvBuilder.append(',');
+ csvBuilder.append(metricValue);
+ csvBuilder.append('\n');
+ }
+ }
+
+ @CliCommand(value = CliStrings.CHANGE_LOGLEVEL, help = CliStrings.CHANGE_LOGLEVEL__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_LOGS},
+ interceptor = "org.apache.geode.management.internal.cli.commands.MiscellaneousCommands$ChangeLogLevelInterceptor")
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.WRITE)
+ public Result changeLogLevel(
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ help = CliStrings.CHANGE_LOGLEVEL__MEMBER__HELP) String[] memberIds,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, unspecifiedDefaultValue = "",
+ help = CliStrings.CHANGE_LOGLEVEL__GROUPS__HELP) String[] grps,
+ @CliOption(key = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL,
+ optionContext = ConverterHint.LOG_LEVEL, mandatory = true, unspecifiedDefaultValue = "",
+ help = CliStrings.CHANGE_LOGLEVEL__LOGLEVEL__HELP) String logLevel) {
+ try {
+ if ((memberIds == null || memberIds.length == 0) && (grps == null || grps.length == 0)) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__SPECIFY_GRP_OR_MEMBER);
+ }
+
+ InternalCache cache = GemFireCacheImpl.getInstance();
+ LogWriter logger = cache.getLogger();
+
+ Set<DistributedMember> dsMembers = new HashSet<>();
+ Set<DistributedMember> ds = CliUtil.getAllMembers(cache);
+
+ if (grps != null && grps.length > 0) {
+ for (String grp : grps) {
+ dsMembers.addAll(cache.getDistributedSystem().getGroupMembers(grp));
+ }
+ }
+
+ if (memberIds != null && memberIds.length > 0) {
+ for (String member : memberIds) {
+ for (DistributedMember mem : ds) {
+ if (mem.getName() != null
+ && (mem.getName().equals(member) || mem.getId().equals(member))) {
+ dsMembers.add(mem);
+ break;
+ }
+ }
+ }
+ }
+
+ if (dsMembers.size() == 0) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG_NO_MEMBERS);
+ }
+
+ Function logFunction = new ChangeLogLevelFunction();
+ FunctionService.registerFunction(logFunction);
+ Object[] functionArgs = new Object[1];
+ functionArgs[0] = logLevel;
+
+ CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
+ SectionResultData section = compositeResultData.addSection("section");
+ TabularResultData resultTable = section.addTable("ChangeLogLevel");
+ resultTable = resultTable.setHeader("Summary");
+
+ Execution execution = FunctionService.onMembers(dsMembers).setArguments(functionArgs);
+ if (execution == null) {
+ return ResultBuilder.createUserErrorResult(CliStrings.CHANGE_LOGLEVEL__MSG__CANNOT_EXECUTE);
+ }
+ List<?> resultList = (List<?>) execution.execute(logFunction).getResult();
+
+ for (Object object : resultList) {
+ try {
+ if (object instanceof Throwable) {
+ logger.warning(
+ "Exception in ChangeLogLevelFunction " + ((Throwable) object).getMessage(),
+ ((Throwable) object));
+ continue;
+ }
+
+ if (object != null) {
+ Map<String, String> resultMap = (Map<String, String>) object;
+ Entry<String, String> entry = resultMap.entrySet().iterator().next();
+
+ if (entry.getValue().contains("ChangeLogLevelFunction exception")) {
+ resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
+ resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "false");
+ } else {
+ resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_MEMBER, entry.getKey());
+ resultTable.accumulate(CliStrings.CHANGE_LOGLEVEL__COLUMN_STATUS, "true");
+ }
+
+ }
+ } catch (Exception ex) {
+ LogWrapper.getInstance().warning("change log level command exception " + ex);
+ }
+ }
+
+ Result result = ResultBuilder.buildResult(compositeResultData);
+ logger.info("change log-level command result=" + result);
+ return result;
+ } catch (Exception ex) {
+ GemFireCacheImpl.getInstance().getLogger().error("GFSH Changeloglevel exception: " + ex);
+ return ResultBuilder.createUserErrorResult(ex.getMessage());
+ }
+ }
+
+ public static class ChangeLogLevelInterceptor extends AbstractCliAroundInterceptor {
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+ Map<String, String> arguments = parseResult.getParamValueStrings();
+ // validate log level
+ String logLevel = arguments.get("loglevel");
+ if (StringUtils.isBlank(logLevel) || LogLevel.getLevel(logLevel) == null) {
+ return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
+ }
+
+ return ResultBuilder.createInfoResult("");
+ }
+ }
+
+ private Set<String> getSetDifference(Set<String> set1, Set<String> set2) {
+ Set<String> setDifference = new HashSet<>();
+ for (String element : set1) {
+ if (!(set2.contains(element.toLowerCase()))) {
+ setDifference.add(element);
+ }
+ }
+ return setDifference;
+ }
+}
[17/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java
deleted file mode 100644
index d20bfb2..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactDiskStoreCommand.java
+++ /dev/null
@@ -1,185 +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 java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.persistence.PersistentID;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.messages.CompactRequest;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CompactDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.COMPACT_DISK_STORE, help = CliStrings.COMPACT_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
- public Result compactDiskStore(
- @CliOption(key = CliStrings.COMPACT_DISK_STORE__NAME, mandatory = true,
- optionContext = ConverterHint.DISKSTORE,
- help = CliStrings.COMPACT_DISK_STORE__NAME__HELP) String diskStoreName,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.COMPACT_DISK_STORE__GROUP__HELP) String[] groups) {
- Result result;
-
- try {
- // disk store exists validation
- if (!diskStoreExists(diskStoreName)) {
- result = ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.COMPACT_DISK_STORE__DISKSTORE_0_DOES_NOT_EXIST,
- new Object[] {diskStoreName}));
- } else {
- InternalDistributedSystem ds = getCache().getInternalDistributedSystem();
-
- Map<DistributedMember, PersistentID> overallCompactInfo = new HashMap<>();
-
- Set<?> otherMembers = ds.getDistributionManager().getOtherNormalDistributionManagerIds();
- Set<InternalDistributedMember> allMembers = new HashSet<>();
-
- for (Object member : otherMembers) {
- allMembers.add((InternalDistributedMember) member);
- }
- allMembers.add(ds.getDistributedMember());
-
- String groupInfo = "";
- // if groups are specified, find members in the specified group
- if (groups != null && groups.length > 0) {
- groupInfo = CliStrings.format(CliStrings.COMPACT_DISK_STORE__MSG__FOR_GROUP,
- new Object[] {Arrays.toString(groups) + "."});
- final Set<InternalDistributedMember> selectedMembers = new HashSet<>();
- List<String> targetedGroups = Arrays.asList(groups);
- for (InternalDistributedMember member : allMembers) {
- List<String> memberGroups = member.getGroups();
- if (!Collections.disjoint(targetedGroups, memberGroups)) {
- selectedMembers.add(member);
- }
- }
-
- allMembers = selectedMembers;
- }
-
- // allMembers should not be empty when groups are not specified - it'll
- // have at least one member
- if (allMembers.isEmpty()) {
- result = ResultBuilder.createUserErrorResult(
- CliStrings.format(CliStrings.COMPACT_DISK_STORE__NO_MEMBERS_FOUND_IN_SPECIFED_GROUP,
- new Object[] {Arrays.toString(groups)}));
- } else {
- // first invoke on local member if it exists in the targeted set
- if (allMembers.remove(ds.getDistributedMember())) {
- PersistentID compactedDiskStoreId = CompactRequest.compactDiskStore(diskStoreName);
- if (compactedDiskStoreId != null) {
- overallCompactInfo.put(ds.getDistributedMember(), compactedDiskStoreId);
- }
- }
-
- // was this local member the only one? Then don't try to send
- // CompactRequest. Otherwise, send the request to others
- if (!allMembers.isEmpty()) {
- // Invoke compact on all 'other' members
- Map<DistributedMember, PersistentID> memberCompactInfo =
- CompactRequest.send(ds.getDistributionManager(), diskStoreName, allMembers);
- if (memberCompactInfo != null && !memberCompactInfo.isEmpty()) {
- overallCompactInfo.putAll(memberCompactInfo);
- memberCompactInfo.clear();
- }
- String notExecutedMembers = CompactRequest.getNotExecutedMembers();
- if (notExecutedMembers != null && !notExecutedMembers.isEmpty()) {
- LogWrapper.getInstance()
- .info("compact disk-store \"" + diskStoreName
- + "\" message was scheduled to be sent to " + notExecutedMembers
- + ", but was not sent.");
- }
- }
-
- // If compaction happened at all, then prepare the summary
- if (overallCompactInfo != null && !overallCompactInfo.isEmpty()) {
- CompositeResultData compositeResultData = ResultBuilder.createCompositeResultData();
- CompositeResultData.SectionResultData section;
-
- Set<Map.Entry<DistributedMember, PersistentID>> entries = overallCompactInfo.entrySet();
-
- for (Map.Entry<DistributedMember, PersistentID> entry : entries) {
- String memberId = entry.getKey().getId();
- section = compositeResultData.addSection(memberId);
- section.addData("On Member", memberId);
-
- PersistentID persistentID = entry.getValue();
- if (persistentID != null) {
- CompositeResultData.SectionResultData subSection =
- section.addSection("DiskStore" + memberId);
- subSection.addData("UUID", persistentID.getUUID());
- subSection.addData("Host", persistentID.getHost().getHostName());
- subSection.addData("Directory", persistentID.getDirectory());
- }
- }
- compositeResultData.setHeader("Compacted " + diskStoreName + groupInfo);
- result = ResultBuilder.buildResult(compositeResultData);
- } else {
- result = ResultBuilder.createInfoResult(
- CliStrings.COMPACT_DISK_STORE__COMPACTION_ATTEMPTED_BUT_NOTHING_TO_COMPACT);
- }
- } // all members' if
- } // disk store exists' if
- } catch (RuntimeException e) {
- LogWrapper.getInstance().info(e.getMessage(), e);
- result = ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.COMPACT_DISK_STORE__ERROR_WHILE_COMPACTING_REASON_0,
- new Object[] {e.getMessage()}));
- }
- return result;
- }
-
- private boolean diskStoreExists(String diskStoreName) {
- InternalCache cache = getCache();
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
- Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
-
- Set<Map.Entry<String, String[]>> entrySet = diskstore.entrySet();
-
- for (Map.Entry<String, String[]> entry : entrySet) {
- String[] value = entry.getValue();
- if (CliUtil.contains(value, diskStoreName)) {
- return true;
- }
- }
- return false;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java
deleted file mode 100644
index ae73440..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CompactOfflineDiskStoreCommand.java
+++ /dev/null
@@ -1,176 +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 java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.GemFireIOException;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.shell.Gfsh;
-import org.apache.geode.management.internal.cli.util.DiskStoreCompacter;
-
-public class CompactOfflineDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.COMPACT_OFFLINE_DISK_STORE,
- help = CliStrings.COMPACT_OFFLINE_DISK_STORE__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- public Result compactOfflineDiskStore(
- @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME, mandatory = true,
- help = CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME__HELP) String diskStoreName,
- @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS, mandatory = true,
- help = CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS__HELP) String[] diskDirs,
- @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE,
- unspecifiedDefaultValue = "-1",
- help = CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE__HELP) long maxOplogSize,
- @CliOption(key = CliStrings.COMPACT_OFFLINE_DISK_STORE__J,
- help = CliStrings.COMPACT_OFFLINE_DISK_STORE__J__HELP) String[] jvmProps) {
- Result result;
- LogWrapper logWrapper = LogWrapper.getInstance();
-
- StringBuilder output = new StringBuilder();
- StringBuilder error = new StringBuilder();
- StringBuilder errorMessage = new StringBuilder();
- Process compacterProcess = null;
-
- try {
- String validatedDirectories = DiskStoreCommandsUtils.validatedDirectories(diskDirs);
- if (validatedDirectories != null) {
- throw new IllegalArgumentException(
- "Could not find " + CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + ": \""
- + validatedDirectories + "\"");
- }
-
- List<String> commandList = new ArrayList<>();
- commandList.add(System.getProperty("java.home") + File.separatorChar + "bin"
- + File.separatorChar + "java");
-
- DiskStoreCommandsUtils.configureLogging(commandList);
-
- if (jvmProps != null && jvmProps.length != 0) {
- commandList.addAll(Arrays.asList(jvmProps));
- }
- commandList.add("-classpath");
- commandList.add(System.getProperty("java.class.path", "."));
- commandList.add(DiskStoreCompacter.class.getName());
-
- commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__NAME + "=" + diskStoreName);
-
- if (diskDirs != null && diskDirs.length != 0) {
- StringBuilder builder = new StringBuilder();
- int arrayLength = diskDirs.length;
- for (int i = 0; i < arrayLength; i++) {
- if (File.separatorChar == '\\') {
- builder.append(diskDirs[i].replace("\\", "/")); // see 46120
- } else {
- builder.append(diskDirs[i]);
- }
- if (i + 1 != arrayLength) {
- builder.append(',');
- }
- }
- commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__DISKDIRS + "=" + builder.toString());
- }
- // -1 is ignore as maxOplogSize
- commandList.add(CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize);
-
- ProcessBuilder procBuilder = new ProcessBuilder(commandList);
- compacterProcess = procBuilder.start();
- InputStream inputStream = compacterProcess.getInputStream();
- InputStream errorStream = compacterProcess.getErrorStream();
- BufferedReader inputReader = new BufferedReader(new InputStreamReader(inputStream));
- BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));
-
- String line;
- while ((line = inputReader.readLine()) != null) {
- output.append(line).append(GfshParser.LINE_SEPARATOR);
- }
-
- boolean switchToStackTrace = false;
- while ((line = errorReader.readLine()) != null) {
- if (!switchToStackTrace && DiskStoreCompacter.STACKTRACE_START.equals(line)) {
- switchToStackTrace = true;
- } else if (switchToStackTrace) {
- error.append(line).append(GfshParser.LINE_SEPARATOR);
- } else {
- errorMessage.append(line);
- }
- }
-
- if (errorMessage.length() > 0) {
- throw new GemFireIOException(errorMessage.toString());
- }
-
- // do we have to waitFor??
- compacterProcess.destroy();
- result = ResultBuilder.createInfoResult(output.toString());
- } catch (IOException e) {
- if (output.length() != 0) {
- Gfsh.println(output.toString());
- }
- String fieldsMessage = (maxOplogSize != -1
- ? CliStrings.COMPACT_OFFLINE_DISK_STORE__MAXOPLOGSIZE + "=" + maxOplogSize + "," : "");
- fieldsMessage += CliUtil.arrayToString(diskDirs);
- String errorString = CliStrings.format(
- CliStrings.COMPACT_OFFLINE_DISK_STORE__MSG__ERROR_WHILE_COMPACTING_DISKSTORE_0_WITH_1_REASON_2,
- diskStoreName, fieldsMessage);
- result = ResultBuilder.createUserErrorResult(errorString);
- if (logWrapper.fineEnabled()) {
- logWrapper.fine(e.getMessage(), e);
- }
- } catch (GemFireIOException e) {
- if (output.length() != 0) {
- Gfsh.println(output.toString());
- }
- result = ResultBuilder.createUserErrorResult(errorMessage.toString());
- if (logWrapper.fineEnabled()) {
- logWrapper.fine(error.toString());
- }
- } catch (IllegalArgumentException e) {
- if (output.length() != 0) {
- Gfsh.println(output.toString());
- }
- result = ResultBuilder.createUserErrorResult(e.getMessage());
- } finally {
- if (compacterProcess != null) {
- try {
- // just to check whether the process has exited
- // Process.exitValue() throws IllegalThreadStateException if Process
- // is alive
- compacterProcess.exitValue();
- } catch (IllegalThreadStateException ise) {
- // not yet terminated, destroy the process
- compacterProcess.destroy();
- }
- }
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java
new file mode 100644
index 0000000..a8afa7d
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigCommands.java
@@ -0,0 +1,490 @@
+/*
+ * 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.STATISTIC_SAMPLING_ENABLED;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.xmlcache.CacheXml;
+import org.apache.geode.internal.logging.LogService;
+import org.apache.geode.internal.logging.log4j.LogLevel;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.domain.MemberConfigurationInfo;
+import org.apache.geode.management.internal.cli.functions.AlterRuntimeConfigFunction;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.ExportConfigFunction;
+import org.apache.geode.management.internal.cli.functions.GetMemberConfigInformationFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CommandResultException;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
+import org.apache.geode.management.internal.cli.result.ErrorResultData;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.shell.Gfsh;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.logging.log4j.Logger;
+import org.springframework.shell.core.annotation.CliAvailabilityIndicator;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+
+/****
+ * @since GemFire 7.0
+ *
+ */
+public class ConfigCommands implements GfshCommand {
+ private final ExportConfigFunction exportConfigFunction = new ExportConfigFunction();
+ private final GetMemberConfigInformationFunction getMemberConfigFunction =
+ new GetMemberConfigInformationFunction();
+ private final AlterRuntimeConfigFunction alterRunTimeConfigFunction =
+ new AlterRuntimeConfigFunction();
+ private static Logger logger = LogService.getLogger();
+
+ @CliCommand(value = {CliStrings.DESCRIBE_CONFIG}, help = CliStrings.DESCRIBE_CONFIG__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result describeConfig(
+ @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.DESCRIBE_CONFIG__MEMBER__HELP, mandatory = true) String memberNameOrId,
+ @CliOption(key = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS,
+ help = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS__HELP, unspecifiedDefaultValue = "true",
+ specifiedDefaultValue = "true") boolean hideDefaults) {
+
+ Result result = null;
+ try {
+ DistributedMember targetMember = null;
+
+ if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
+ targetMember = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
+ }
+ if (targetMember != null) {
+ ResultCollector<?, ?> rc = CliUtil.executeFunction(getMemberConfigFunction,
+ new Boolean(hideDefaults), targetMember);
+ ArrayList<?> output = (ArrayList<?>) rc.getResult();
+ Object obj = output.get(0);
+
+ if (obj != null && obj instanceof MemberConfigurationInfo) {
+ MemberConfigurationInfo memberConfigInfo = (MemberConfigurationInfo) obj;
+
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+ crd.setHeader(
+ CliStrings.format(CliStrings.DESCRIBE_CONFIG__HEADER__TEXT, memberNameOrId));
+
+ List<String> jvmArgsList = memberConfigInfo.getJvmInputArguments();
+ TabularResultData jvmInputArgs = crd.addSection().addSection().addTable();
+
+ for (String jvmArg : jvmArgsList) {
+ jvmInputArgs.accumulate("JVM command line arguments", jvmArg);
+ }
+
+ addSection(crd, memberConfigInfo.getGfePropsSetUsingApi(),
+ "GemFire properties defined using the API");
+ addSection(crd, memberConfigInfo.getGfePropsRuntime(),
+ "GemFire properties defined at the runtime");
+ addSection(crd, memberConfigInfo.getGfePropsSetFromFile(),
+ "GemFire properties defined with the property file");
+ addSection(crd, memberConfigInfo.getGfePropsSetWithDefaults(),
+ "GemFire properties using default values");
+ addSection(crd, memberConfigInfo.getCacheAttributes(), "Cache attributes");
+
+ List<Map<String, String>> cacheServerAttributesList =
+ memberConfigInfo.getCacheServerAttributes();
+
+ if (cacheServerAttributesList != null && !cacheServerAttributesList.isEmpty()) {
+ SectionResultData cacheServerSection = crd.addSection();
+ cacheServerSection.setHeader("Cache-server attributes");
+
+ for (Map<String, String> cacheServerAttributes : cacheServerAttributesList) {
+ addSubSection(cacheServerSection, cacheServerAttributes, "");
+ }
+ }
+ result = ResultBuilder.buildResult(crd);
+ }
+
+ } else {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(CliStrings.format(CliStrings.DESCRIBE_CONFIG__MEMBER__NOT__FOUND,
+ new Object[] {memberNameOrId}));
+ result = ResultBuilder.buildResult(erd);
+ }
+ } catch (FunctionInvocationTargetException e) {
+ result = ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_CONFIG));
+ } catch (Exception e) {
+ ErrorResultData erd = ResultBuilder.createErrorResultData();
+ erd.addLine(e.getMessage());
+ result = ResultBuilder.buildResult(erd);
+ }
+ return result;
+ }
+
+
+ private void addSection(CompositeResultData crd, Map<String, String> attrMap, String headerText) {
+ if (attrMap != null && !attrMap.isEmpty()) {
+ SectionResultData section = crd.addSection();
+ section.setHeader(headerText);
+ section.addSeparator('.');
+ Set<String> attributes = new TreeSet<>(attrMap.keySet());
+
+ for (String attribute : attributes) {
+ String attributeValue = attrMap.get(attribute);
+ section.addData(attribute, attributeValue);
+ }
+ }
+ }
+
+ private void addSubSection(SectionResultData section, Map<String, String> attrMap,
+ String headerText) {
+ if (!attrMap.isEmpty()) {
+ SectionResultData subSection = section.addSection();
+ Set<String> attributes = new TreeSet<>(attrMap.keySet());
+ subSection.setHeader(headerText);
+
+ for (String attribute : attributes) {
+ String attributeValue = attrMap.get(attribute);
+ subSection.addData(attribute, attributeValue);
+ }
+ }
+ }
+
+ /**
+ * Export the cache configuration in XML format.
+ *
+ * @param member Member for which to write the configuration
+ * @param group Group or groups for which to write the configuration
+ * @return Results of the attempt to write the configuration
+ */
+ @CliCommand(value = {CliStrings.EXPORT_CONFIG}, help = CliStrings.EXPORT_CONFIG__HELP)
+ @CliMetaData(
+ interceptor = "org.apache.geode.management.internal.cli.commands.ConfigCommands$Interceptor",
+ relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result exportConfig(
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.EXPORT_CONFIG__MEMBER__HELP) String[] member,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.EXPORT_CONFIG__GROUP__HELP) String[] group,
+ @CliOption(key = {CliStrings.EXPORT_CONFIG__DIR},
+ help = CliStrings.EXPORT_CONFIG__DIR__HELP) String dir) {
+ InfoResultData infoData = ResultBuilder.createInfoResultData();
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, member);
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ try {
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(this.exportConfigFunction, null, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ infoData.addLine(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
+ result.getMemberIdOrName(), result.getThrowable()));
+ } else if (result.isSuccessful()) {
+ String cacheFileName = result.getMemberIdOrName() + "-cache.xml";
+ String propsFileName = result.getMemberIdOrName() + "-gf.properties";
+ String[] fileContent = (String[]) result.getSerializables();
+ infoData.addAsFile(cacheFileName, fileContent[0], "Downloading Cache XML file: {0}",
+ false);
+ infoData.addAsFile(propsFileName, fileContent[1], "Downloading properties file: {0}",
+ false);
+ }
+ }
+ return ResultBuilder.buildResult(infoData);
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ th.printStackTrace(System.err);
+ return ResultBuilder
+ .createGemFireErrorResult(CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__EXCEPTION,
+ th.getClass().getName() + ": " + th.getMessage()));
+ }
+ }
+
+
+ @CliCommand(value = {CliStrings.ALTER_RUNTIME_CONFIG},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG},
+ interceptor = "org.apache.geode.management.internal.cli.commands.ConfigCommands$AlterRuntimeInterceptor")
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
+ public Result alterRuntimeConfig(
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.ALL_MEMBER_IDNAME,
+ help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] memberNameOrId,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.ALTER_RUNTIME_CONFIG__MEMBER__HELP) String[] group,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT__HELP) Integer archiveDiskSpaceLimit,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT__HELP) Integer archiveFileSizeLimit,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT__HELP) Integer logDiskSpaceLimit,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT__HELP) Integer logFileSizeLimit,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL},
+ optionContext = ConverterHint.LOG_LEVEL,
+ help = CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL__HELP) String logLevel,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE__HELP) String statisticArchiveFile,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE__HELP) Integer statisticSampleRate,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLING__ENABLED__HELP) Boolean statisticSamplingEnabled,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ},
+ specifiedDefaultValue = "false",
+ help = CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ__HELP) Boolean setCopyOnRead,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE__HELP) Integer lockLease,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT__HELP) Integer lockTimeout,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL__HELP) Integer messageSyncInterval,
+ @CliOption(key = {CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT},
+ help = CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT__HELP) Integer searchTimeout) {
+
+ Map<String, String> runTimeDistributionConfigAttributes = new HashMap<>();
+ Map<String, String> rumTimeCacheAttributes = new HashMap<>();
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ if (archiveDiskSpaceLimit != null) {
+ runTimeDistributionConfigAttributes.put(
+ CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__DISK__SPACE__LIMIT,
+ archiveDiskSpaceLimit.toString());
+ }
+
+ if (archiveFileSizeLimit != null) {
+ runTimeDistributionConfigAttributes.put(
+ CliStrings.ALTER_RUNTIME_CONFIG__ARCHIVE__FILE__SIZE__LIMIT,
+ archiveFileSizeLimit.toString());
+ }
+
+ if (logDiskSpaceLimit != null) {
+ runTimeDistributionConfigAttributes.put(
+ CliStrings.ALTER_RUNTIME_CONFIG__LOG__DISK__SPACE__LIMIT, logDiskSpaceLimit.toString());
+ }
+
+ if (logFileSizeLimit != null) {
+ runTimeDistributionConfigAttributes.put(
+ CliStrings.ALTER_RUNTIME_CONFIG__LOG__FILE__SIZE__LIMIT, logFileSizeLimit.toString());
+ }
+
+ if (logLevel != null && !logLevel.isEmpty()) {
+ runTimeDistributionConfigAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOG__LEVEL,
+ logLevel);
+ }
+
+ if (statisticArchiveFile != null && !statisticArchiveFile.isEmpty()) {
+ runTimeDistributionConfigAttributes
+ .put(CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__ARCHIVE__FILE, statisticArchiveFile);
+ }
+
+ if (statisticSampleRate != null) {
+ runTimeDistributionConfigAttributes.put(
+ CliStrings.ALTER_RUNTIME_CONFIG__STATISTIC__SAMPLE__RATE, statisticSampleRate.toString());
+ }
+
+ if (statisticSamplingEnabled != null) {
+ runTimeDistributionConfigAttributes.put(STATISTIC_SAMPLING_ENABLED,
+ statisticSamplingEnabled.toString());
+ }
+
+
+ // Attributes that are set on the cache.
+ if (setCopyOnRead != null) {
+ rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__COPY__ON__READ,
+ setCopyOnRead.toString());
+ }
+
+ if (lockLease != null && lockLease > 0 && lockLease < Integer.MAX_VALUE) {
+ rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__LEASE,
+ lockLease.toString());
+ }
+
+ if (lockTimeout != null && lockTimeout > 0 && lockTimeout < Integer.MAX_VALUE) {
+ rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__LOCK__TIMEOUT,
+ lockTimeout.toString());
+ }
+
+ if (messageSyncInterval != null && messageSyncInterval > 0
+ && messageSyncInterval < Integer.MAX_VALUE) {
+ rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__MESSAGE__SYNC__INTERVAL,
+ messageSyncInterval.toString());
+ }
+
+ if (searchTimeout != null && searchTimeout > 0 && searchTimeout < Integer.MAX_VALUE) {
+ rumTimeCacheAttributes.put(CliStrings.ALTER_RUNTIME_CONFIG__SEARCH__TIMEOUT,
+ searchTimeout.toString());
+ }
+
+ if (runTimeDistributionConfigAttributes.isEmpty() && rumTimeCacheAttributes.isEmpty()) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.ALTER_RUNTIME_CONFIG__RELEVANT__OPTION__MESSAGE);
+ }
+
+ Map<String, String> allRunTimeAttributes = new HashMap<>();
+ allRunTimeAttributes.putAll(runTimeDistributionConfigAttributes);
+ allRunTimeAttributes.putAll(rumTimeCacheAttributes);
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(alterRunTimeConfigFunction, allRunTimeAttributes, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+ Set<String> successfulMembers = new TreeSet<>();
+ Set<String> errorMessages = new TreeSet<>();
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ logger.info("Function failed: " + result.getThrowable());
+ errorMessages.add(result.getThrowable().getMessage());
+ } else {
+ successfulMembers.add(result.getMemberIdOrName());
+ }
+ }
+ final String lineSeparator = System.getProperty("line.separator");
+ if (!successfulMembers.isEmpty()) {
+ StringBuilder successMessageBuilder = new StringBuilder();
+
+ successMessageBuilder.append(CliStrings.ALTER_RUNTIME_CONFIG__SUCCESS__MESSAGE);
+ successMessageBuilder.append(lineSeparator);
+
+ for (String member : successfulMembers) {
+ successMessageBuilder.append(member);
+ successMessageBuilder.append(lineSeparator);
+ }
+
+ Properties properties = new Properties();
+ properties.putAll(runTimeDistributionConfigAttributes);
+
+ Result result = ResultBuilder.createInfoResult(successMessageBuilder.toString());
+
+ // Set the Cache attributes to be modified
+ final XmlEntity xmlEntity = XmlEntity.builder().withType(CacheXml.CACHE)
+ .withAttributes(rumTimeCacheAttributes).build();
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().modifyXmlAndProperties(properties, xmlEntity, group));
+ return result;
+ } else {
+ StringBuilder errorMessageBuilder = new StringBuilder();
+ errorMessageBuilder.append("Following errors occurred while altering runtime config");
+ errorMessageBuilder.append(lineSeparator);
+
+ for (String errorMessage : errorMessages) {
+ errorMessageBuilder.append(errorMessage);
+ errorMessageBuilder.append(lineSeparator);
+ }
+ return ResultBuilder.createUserErrorResult(errorMessageBuilder.toString());
+ }
+ }
+
+ public static class AlterRuntimeInterceptor extends AbstractCliAroundInterceptor {
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+ Map<String, String> arguments = parseResult.getParamValueStrings();
+ // validate log level
+ String logLevel = arguments.get("log-level");
+ if (StringUtils.isNotBlank(logLevel) && (LogLevel.getLevel(logLevel) == null)) {
+ return ResultBuilder.createUserErrorResult("Invalid log level: " + logLevel);
+ }
+
+ return ResultBuilder.createInfoResult("");
+ }
+ }
+
+ /**
+ * Interceptor used by gfsh to intercept execution of export config command at "shell".
+ */
+ public static class Interceptor extends AbstractCliAroundInterceptor {
+ private String saveDirString;
+
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+ Map<String, String> paramValueMap = parseResult.getParamValueStrings();
+ String dir = paramValueMap.get("dir");
+ dir = (dir == null) ? null : dir.trim();
+
+ File saveDirFile = new File(".");
+ if (dir != null && !dir.isEmpty()) {
+ saveDirFile = new File(dir);
+ if (saveDirFile.exists()) {
+ if (!saveDirFile.isDirectory())
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_A_DIRECTORY, dir));
+ } else if (!saveDirFile.mkdirs()) {
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__CANNOT_CREATE_DIR, dir));
+ }
+ }
+ try {
+ if (!saveDirFile.canWrite()) {
+ return ResultBuilder.createGemFireErrorResult(CliStrings.format(
+ CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getCanonicalPath()));
+ }
+ } catch (IOException ioex) {
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.EXPORT_CONFIG__MSG__NOT_WRITEABLE, saveDirFile.getName()));
+ }
+
+ saveDirString = saveDirFile.getAbsolutePath();
+ return ResultBuilder.createInfoResult("OK");
+ }
+
+ @Override
+ public Result postExecution(GfshParseResult parseResult, Result commandResult, Path tempFile) {
+ if (commandResult.hasIncomingFiles()) {
+ try {
+ commandResult.saveIncomingFiles(saveDirString);
+ } catch (IOException ioex) {
+ Gfsh.getCurrentInstance().logSevere("Unable to export config", ioex);
+ }
+ }
+
+ return commandResult;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java
deleted file mode 100644
index 8c490f4..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ConfigurePDXCommand.java
+++ /dev/null
@@ -1,138 +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 java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.Arrays;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.internal.cache.CacheConfig;
-import org.apache.geode.internal.cache.xmlcache.CacheCreation;
-import org.apache.geode.internal.cache.xmlcache.CacheXml;
-import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
-import org.apache.geode.security.ResourcePermission;
-
-public class ConfigurePDXCommand implements GfshCommand {
- @CliCommand(value = CliStrings.CONFIGURE_PDX, help = CliStrings.CONFIGURE_PDX__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE)
- public Result configurePDX(
- @CliOption(key = CliStrings.CONFIGURE_PDX__READ__SERIALIZED,
- help = CliStrings.CONFIGURE_PDX__READ__SERIALIZED__HELP) Boolean readSerialized,
- @CliOption(key = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS,
- help = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS__HELP) Boolean ignoreUnreadFields,
- @CliOption(key = CliStrings.CONFIGURE_PDX__DISKSTORE, specifiedDefaultValue = "",
- help = CliStrings.CONFIGURE_PDX__DISKSTORE__HELP) String diskStore,
- @CliOption(key = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES,
- help = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES__HELP) String[] patterns,
- @CliOption(key = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES,
- help = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES__HELP) String[] portablePatterns) {
- Result result;
-
- try {
- InfoResultData ird = ResultBuilder.createInfoResultData();
- CacheCreation cache = new CacheCreation(true);
-
- if ((portablePatterns != null && portablePatterns.length > 0)
- && (patterns != null && patterns.length > 0)) {
- return ResultBuilder.createUserErrorResult(CliStrings.CONFIGURE_PDX__ERROR__MESSAGE);
- }
- if (!CliUtil.getAllNormalMembers(CliUtil.getCacheIfExists()).isEmpty()) {
- ird.addLine(CliStrings.CONFIGURE_PDX__NORMAL__MEMBERS__WARNING);
- }
- // Set persistent and the disk-store
- if (diskStore != null) {
- cache.setPdxPersistent(true);
- ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
- if (!diskStore.equals("")) {
- cache.setPdxDiskStore(diskStore);
- ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + cache.getPdxDiskStore());
- } else {
- ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + "DEFAULT");
- }
- } else {
- cache.setPdxPersistent(CacheConfig.DEFAULT_PDX_PERSISTENT);
- ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
- }
-
- // Set read-serialized
- if (readSerialized != null) {
- cache.setPdxReadSerialized(readSerialized);
- } else {
- cache.setPdxReadSerialized(CacheConfig.DEFAULT_PDX_READ_SERIALIZED);
- }
- ird.addLine(
- CliStrings.CONFIGURE_PDX__READ__SERIALIZED + " = " + cache.getPdxReadSerialized());
-
-
- // Set ignoreUnreadFields
- if (ignoreUnreadFields != null) {
- cache.setPdxIgnoreUnreadFields(ignoreUnreadFields);
- } else {
- cache.setPdxIgnoreUnreadFields(CacheConfig.DEFAULT_PDX_IGNORE_UNREAD_FIELDS);
- }
- ird.addLine(CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS + " = "
- + cache.getPdxIgnoreUnreadFields());
-
-
- if (portablePatterns != null) {
- ReflectionBasedAutoSerializer autoSerializer =
- new ReflectionBasedAutoSerializer(portablePatterns);
- cache.setPdxSerializer(autoSerializer);
- ird.addLine("PDX Serializer " + cache.getPdxSerializer().getClass().getName());
- ird.addLine("Portable classes " + Arrays.toString(portablePatterns));
- }
-
- if (patterns != null) {
- ReflectionBasedAutoSerializer nonPortableAutoSerializer =
- new ReflectionBasedAutoSerializer(true, patterns);
- cache.setPdxSerializer(nonPortableAutoSerializer);
- ird.addLine("PDX Serializer : " + cache.getPdxSerializer().getClass().getName());
- ird.addLine("Non portable classes :" + Arrays.toString(patterns));
- }
-
- final StringWriter stringWriter = new StringWriter();
- final PrintWriter printWriter = new PrintWriter(stringWriter);
- CacheXmlGenerator.generate(cache, printWriter, true, false, false);
- printWriter.close();
- String xmlDefinition = stringWriter.toString();
- // TODO jbarrett - shouldn't this use the same loadXmlDefinition that other constructors use?
- XmlEntity xmlEntity =
- XmlEntity.builder().withType(CacheXml.PDX).withConfig(xmlDefinition).build();
-
- result = ResultBuilder.buildResult(ird);
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity, null));
-
- } catch (Exception e) {
- return ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java
deleted file mode 100644
index 8ebc4da..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CountDurableCQEventsCommand.java
+++ /dev/null
@@ -1,88 +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 java.util.List;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.SubscriptionQueueSizeResult;
-import org.apache.geode.management.internal.cli.functions.GetSubscriptionQueueSizeFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CountDurableCQEventsCommand implements GfshCommand {
- DurableClientCommandsResultBuilder builder = new DurableClientCommandsResultBuilder();
-
- @CliCommand(value = CliStrings.COUNT_DURABLE_CQ_EVENTS,
- help = CliStrings.COUNT_DURABLE_CQ_EVENTS__HELP)
- @CliMetaData()
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result countDurableCqEvents(
- @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID, mandatory = true,
- help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CLIENT__ID__HELP) final String durableClientId,
- @CliOption(key = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME,
- help = CliStrings.COUNT_DURABLE_CQ_EVENTS__DURABLE__CQ__NAME__HELP) final String cqName,
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- help = CliStrings.COUNT_DURABLE_CQ_EVENTS__MEMBER__HELP,
- optionContext = ConverterHint.MEMBERIDNAME) final String[] memberNameOrId,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- help = CliStrings.COUNT_DURABLE_CQ_EVENTS__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) final String[] group) {
-
- Result result;
- try {
- Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- String[] params = new String[2];
- params[0] = durableClientId;
- params[1] = cqName;
- final ResultCollector<?, ?> rc =
- CliUtil.executeFunction(new GetSubscriptionQueueSizeFunction(), params, targetMembers);
- final List<SubscriptionQueueSizeResult> funcResults =
- (List<SubscriptionQueueSizeResult>) rc.getResult();
-
- String queueSizeColumnName;
-
- if (cqName != null && !cqName.isEmpty()) {
- queueSizeColumnName = CliStrings
- .format(CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, cqName);
- } else {
- queueSizeColumnName = CliStrings.format(
- CliStrings.COUNT_DURABLE_CQ_EVENTS__SUBSCRIPTION__QUEUE__SIZE__CLIENT, durableClientId);
- }
- result = builder.buildTableResultForQueueSize(funcResults, queueSizeColumnName);
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- return result;
- }
-}
[08/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java
deleted file mode 100644
index a5d62fa..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/NetstatCommand.java
+++ /dev/null
@@ -1,212 +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 java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.zip.DataFormatException;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.InternalDistributedSystem;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParser;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.NetstatFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class NetstatCommand implements GfshCommand {
- private static final String NETSTAT_FILE_REQUIRED_EXTENSION = ".txt";
-
- @CliCommand(value = CliStrings.NETSTAT, help = CliStrings.NETSTAT__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- // TODO : Verify the auto-completion for multiple values.
- public Result netstat(
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.NETSTAT__MEMBER__HELP) String[] members,
- @CliOption(key = CliStrings.GROUP, optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.NETSTAT__GROUP__HELP) String group,
- @CliOption(key = CliStrings.NETSTAT__FILE,
- help = CliStrings.NETSTAT__FILE__HELP) String saveAs,
- @CliOption(key = CliStrings.NETSTAT__WITHLSOF, specifiedDefaultValue = "true",
- unspecifiedDefaultValue = "false",
- help = CliStrings.NETSTAT__WITHLSOF__HELP) boolean withlsof) {
- Result result;
-
- Map<String, DistributedMember> hostMemberMap = new HashMap<>();
- Map<String, List<String>> hostMemberListMap = new HashMap<>();
-
- try {
- if (members != null && members.length > 0 && group != null) {
- throw new IllegalArgumentException(
- CliStrings.NETSTAT__MSG__ONLY_ONE_OF_MEMBER_OR_GROUP_SHOULD_BE_SPECIFIED);
- }
- StringBuilder resultInfo = new StringBuilder();
-
- // Execute for remote members whose id or name matches
- InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance();
-
- if (members != null) {
- Set<String> notFoundMembers = new HashSet<>();
- for (String memberIdOrName : members) {
- Set<DistributedMember> membersToExecuteOn = CliUtil.getAllMembers(system);
- boolean memberFound = false;
- for (DistributedMember distributedMember : membersToExecuteOn) {
- String memberName = distributedMember.getName();
- String memberId = distributedMember.getId();
- if (memberName.equals(memberIdOrName) || memberId.equals(memberIdOrName)) {
- buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
-
- memberFound = true;
- break;
- }
- }
- if (!memberFound) {
- notFoundMembers.add(memberIdOrName);
- }
- }
- // if there are not found members, it's probably unknown member or member has departed
- if (!notFoundMembers.isEmpty()) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.NETSTAT__MSG__COULD_NOT_FIND_MEMBERS_0,
- new Object[] {CliUtil.collectionToString(notFoundMembers, -1)}));
- }
- } else {
- Set<DistributedMember> membersToExecuteOn;
- if (group != null) {
- membersToExecuteOn = system.getGroupMembers(group);
- } else {
- // consider all members
- membersToExecuteOn = CliUtil.getAllMembers(system);
- }
-
- for (DistributedMember distributedMember : membersToExecuteOn) {
- String memberName = distributedMember.getName();
- String memberId = distributedMember.getId();
- String memberIdOrName =
- memberName != null && !memberName.isEmpty() ? memberName : memberId;
-
- buildMaps(hostMemberMap, hostMemberListMap, memberIdOrName, distributedMember);
- }
- }
-
- String lineSeparatorToUse;
- lineSeparatorToUse = CommandExecutionContext.getShellLineSeparator();
- if (lineSeparatorToUse == null) {
- lineSeparatorToUse = GfshParser.LINE_SEPARATOR;
- }
- NetstatFunction.NetstatFunctionArgument nfa =
- new NetstatFunction.NetstatFunctionArgument(lineSeparatorToUse, withlsof);
-
- if (!hostMemberMap.isEmpty()) {
- Set<DistributedMember> membersToExecuteOn = new HashSet<>(hostMemberMap.values());
- ResultCollector<?, ?> netstatResult =
- CliUtil.executeFunction(NetstatFunction.INSTANCE, nfa, membersToExecuteOn);
- List<?> resultList = (List<?>) netstatResult.getResult();
- for (Object aResultList : resultList) {
- NetstatFunction.NetstatFunctionResult netstatFunctionResult =
- (NetstatFunction.NetstatFunctionResult) aResultList;
- CliUtil.DeflaterInflaterData deflaterInflaterData =
- netstatFunctionResult.getCompressedBytes();
- try {
- String remoteHost = netstatFunctionResult.getHost();
- List<String> membersList = hostMemberListMap.get(remoteHost);
- resultInfo.append(MessageFormat.format(netstatFunctionResult.getHeaderInfo(),
- CliUtil.collectionToString(membersList, 120)));
- CliUtil.DeflaterInflaterData uncompressedBytes = CliUtil.uncompressBytes(
- deflaterInflaterData.getData(), deflaterInflaterData.getDataLength());
- resultInfo.append(new String(uncompressedBytes.getData()));
- } catch (DataFormatException e) {
- resultInfo.append("Error in some data. Reason : ").append(e.getMessage());
- }
- }
- }
-
- InfoResultData resultData = ResultBuilder.createInfoResultData();
- if (saveAs != null && !saveAs.isEmpty()) {
- String saveToFile = saveAs;
- if (!saveAs.endsWith(NETSTAT_FILE_REQUIRED_EXTENSION)) {
- saveToFile = saveAs + NETSTAT_FILE_REQUIRED_EXTENSION;
- }
- resultData.addAsFile(saveToFile, resultInfo.toString(),
- CliStrings.NETSTAT__MSG__SAVED_OUTPUT_IN_0, false); // Note: substitution for {0} will
- // happen on client side.
- } else {
- resultData.addLine(resultInfo.toString());
- }
- result = ResultBuilder.buildResult(resultData);
- } catch (IllegalArgumentException e) {
- LogWrapper.getInstance()
- .info(CliStrings.format(
- CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
- new Object[] {Arrays.toString(members)}));
- result = ResultBuilder.createUserErrorResult(e.getMessage());
- } catch (RuntimeException e) {
- LogWrapper.getInstance()
- .info(CliStrings.format(
- CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
- new Object[] {Arrays.toString(members)}), e);
- result = ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.NETSTAT__MSG__ERROR_OCCURRED_WHILE_EXECUTING_NETSTAT_ON_0,
- new Object[] {Arrays.toString(members)}));
- } finally {
- hostMemberMap.clear();
- hostMemberListMap.clear();
- }
- return result;
- }
-
- private void buildMaps(Map<String, DistributedMember> hostMemberMap,
- Map<String, List<String>> hostMemberListMap, String memberIdOrName,
- DistributedMember distributedMember) {
- String host = distributedMember.getHost();
-
- // Maintain one member for a host - function execution purpose - once only for a host
- if (!hostMemberMap.containsKey(host)) {
- hostMemberMap.put(host, distributedMember);
- }
-
- // Maintain all members for a host - display purpose
- List<String> list;
- if (!hostMemberListMap.containsKey(host)) {
- list = new ArrayList<>();
- hostMemberListMap.put(host, list);
- } else {
- list = hostMemberListMap.get(host);
- }
- list.add(memberIdOrName);
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
new file mode 100644
index 0000000..e0bad15
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXCommands.java
@@ -0,0 +1,195 @@
+/*
+ * 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 java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.Arrays;
+import java.util.Collection;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.internal.cache.CacheConfig;
+import org.apache.geode.internal.cache.DiskStoreImpl;
+import org.apache.geode.internal.cache.xmlcache.CacheCreation;
+import org.apache.geode.internal.cache.xmlcache.CacheXml;
+import org.apache.geode.internal.cache.xmlcache.CacheXmlGenerator;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.InfoResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.pdx.ReflectionBasedAutoSerializer;
+import org.apache.geode.pdx.internal.EnumInfo;
+import org.apache.geode.pdx.internal.PdxType;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+
+public class PDXCommands implements GfshCommand {
+
+
+ @CliCommand(value = CliStrings.CONFIGURE_PDX, help = CliStrings.CONFIGURE_PDX__HELP)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE)
+ public Result configurePDX(
+ @CliOption(key = CliStrings.CONFIGURE_PDX__READ__SERIALIZED,
+ help = CliStrings.CONFIGURE_PDX__READ__SERIALIZED__HELP) Boolean readSerialized,
+ @CliOption(key = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS,
+ help = CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS__HELP) Boolean ignoreUnreadFields,
+ @CliOption(key = CliStrings.CONFIGURE_PDX__DISKSTORE, specifiedDefaultValue = "",
+ help = CliStrings.CONFIGURE_PDX__DISKSTORE__HELP) String diskStore,
+ @CliOption(key = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES,
+ help = CliStrings.CONFIGURE_PDX__AUTO__SERIALIZER__CLASSES__HELP) String[] patterns,
+ @CliOption(key = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES,
+ help = CliStrings.CONFIGURE_PDX__PORTABLE__AUTO__SERIALIZER__CLASSES__HELP) String[] portablePatterns) {
+ Result result;
+
+ try {
+ InfoResultData ird = ResultBuilder.createInfoResultData();
+ CacheCreation cache = new CacheCreation(true);
+
+ if ((portablePatterns != null && portablePatterns.length > 0)
+ && (patterns != null && patterns.length > 0)) {
+ return ResultBuilder.createUserErrorResult(CliStrings.CONFIGURE_PDX__ERROR__MESSAGE);
+ }
+ if (!CliUtil.getAllNormalMembers(CliUtil.getCacheIfExists()).isEmpty()) {
+ ird.addLine(CliStrings.CONFIGURE_PDX__NORMAL__MEMBERS__WARNING);
+ }
+ // Set persistent and the disk-store
+ if (diskStore != null) {
+ cache.setPdxPersistent(true);
+ ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
+ if (!diskStore.equals("")) {
+ cache.setPdxDiskStore(diskStore);
+ ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + cache.getPdxDiskStore());
+ } else {
+ ird.addLine(CliStrings.CONFIGURE_PDX__DISKSTORE + " = " + "DEFAULT");
+ }
+ } else {
+ cache.setPdxPersistent(CacheConfig.DEFAULT_PDX_PERSISTENT);
+ ird.addLine(CliStrings.CONFIGURE_PDX__PERSISTENT + " = " + cache.getPdxPersistent());
+ }
+
+ // Set read-serialized
+ if (readSerialized != null) {
+ cache.setPdxReadSerialized(readSerialized);
+ } else {
+ cache.setPdxReadSerialized(CacheConfig.DEFAULT_PDX_READ_SERIALIZED);
+ }
+ ird.addLine(
+ CliStrings.CONFIGURE_PDX__READ__SERIALIZED + " = " + cache.getPdxReadSerialized());
+
+
+ // Set ignoreUnreadFields
+ if (ignoreUnreadFields != null) {
+ cache.setPdxIgnoreUnreadFields(ignoreUnreadFields);
+ } else {
+ cache.setPdxIgnoreUnreadFields(CacheConfig.DEFAULT_PDX_IGNORE_UNREAD_FIELDS);
+ }
+ ird.addLine(CliStrings.CONFIGURE_PDX__IGNORE__UNREAD_FIELDS + " = "
+ + cache.getPdxIgnoreUnreadFields());
+
+
+ if (portablePatterns != null) {
+ ReflectionBasedAutoSerializer autoSerializer =
+ new ReflectionBasedAutoSerializer(portablePatterns);
+ cache.setPdxSerializer(autoSerializer);
+ ird.addLine("PDX Serializer " + cache.getPdxSerializer().getClass().getName());
+ ird.addLine("Portable classes " + Arrays.toString(portablePatterns));
+ }
+
+ if (patterns != null) {
+ ReflectionBasedAutoSerializer nonPortableAutoSerializer =
+ new ReflectionBasedAutoSerializer(true, patterns);
+ cache.setPdxSerializer(nonPortableAutoSerializer);
+ ird.addLine("PDX Serializer : " + cache.getPdxSerializer().getClass().getName());
+ ird.addLine("Non portable classes :" + Arrays.toString(patterns));
+ }
+
+ final StringWriter stringWriter = new StringWriter();
+ final PrintWriter printWriter = new PrintWriter(stringWriter);
+ CacheXmlGenerator.generate(cache, printWriter, true, false, false);
+ printWriter.close();
+ String xmlDefinition = stringWriter.toString();
+ // TODO jbarrett - shouldn't this use the same loadXmlDefinition that other constructors use?
+ XmlEntity xmlEntity =
+ XmlEntity.builder().withType(CacheXml.PDX).withConfig(xmlDefinition).build();
+
+ result = ResultBuilder.buildResult(ird);
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity, null));
+
+ } catch (Exception e) {
+ return ResultBuilder.createGemFireErrorResult(e.getMessage());
+ }
+
+ return result;
+ }
+
+ @CliCommand(value = CliStrings.PDX_RENAME, help = CliStrings.PDX_RENAME__HELP)
+ @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
+ public Result pdxRename(@CliOption(key = CliStrings.PDX_RENAME_OLD, mandatory = true,
+ help = CliStrings.PDX_RENAME_OLD__HELP) String oldClassName,
+
+ @CliOption(key = CliStrings.PDX_RENAME_NEW, mandatory = true,
+ help = CliStrings.PDX_RENAME_NEW__HELP) String newClassName,
+
+ @CliOption(key = CliStrings.PDX_DISKSTORE, mandatory = true,
+ help = CliStrings.PDX_DISKSTORE__HELP) String diskStore,
+
+ @CliOption(key = CliStrings.PDX_DISKDIR, mandatory = true,
+ help = CliStrings.PDX_DISKDIR__HELP) String[] diskDirs) {
+
+ try {
+ final File[] dirs = new File[diskDirs.length];
+ for (int i = 0; i < diskDirs.length; i++) {
+ dirs[i] = new File((diskDirs[i]));
+ }
+
+ Collection<Object> results =
+ DiskStoreImpl.pdxRename(diskStore, dirs, oldClassName, newClassName);
+
+ if (results.isEmpty()) {
+ return ResultBuilder
+ .createGemFireErrorResult(CliStrings.format(CliStrings.PDX_RENAME__EMPTY));
+ }
+
+ ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+ PrintStream printStream = new PrintStream(outputStream);
+ for (Object p : results) {
+ if (p instanceof PdxType) {
+ ((PdxType) p).toStream(printStream, false);
+ } else {
+ ((EnumInfo) p).toStream(printStream);
+ }
+ }
+ String resultString =
+ CliStrings.format(CliStrings.PDX_RENAME__SUCCESS, outputStream.toString());
+ return ResultBuilder.createInfoResult(resultString);
+
+ } catch (Exception e) {
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.PDX_RENAME__ERROR, e.getMessage()));
+ }
+
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java
deleted file mode 100644
index 8831597..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/PDXRenameCommand.java
+++ /dev/null
@@ -1,81 +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 java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.PrintStream;
-import java.util.Collection;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.internal.cache.DiskStoreImpl;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.pdx.internal.EnumInfo;
-import org.apache.geode.pdx.internal.PdxType;
-
-public class PDXRenameCommand implements GfshCommand {
- @CliCommand(value = CliStrings.PDX_RENAME, help = CliStrings.PDX_RENAME__HELP)
- @CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- public Result pdxRename(@CliOption(key = CliStrings.PDX_RENAME_OLD, mandatory = true,
- help = CliStrings.PDX_RENAME_OLD__HELP) String oldClassName,
-
- @CliOption(key = CliStrings.PDX_RENAME_NEW, mandatory = true,
- help = CliStrings.PDX_RENAME_NEW__HELP) String newClassName,
-
- @CliOption(key = CliStrings.PDX_DISKSTORE, mandatory = true,
- help = CliStrings.PDX_DISKSTORE__HELP) String diskStore,
-
- @CliOption(key = CliStrings.PDX_DISKDIR, mandatory = true,
- help = CliStrings.PDX_DISKDIR__HELP) String[] diskDirs) {
-
- try {
- final File[] dirs = new File[diskDirs.length];
- for (int i = 0; i < diskDirs.length; i++) {
- dirs[i] = new File((diskDirs[i]));
- }
-
- Collection<Object> results =
- DiskStoreImpl.pdxRename(diskStore, dirs, oldClassName, newClassName);
-
- if (results.isEmpty()) {
- return ResultBuilder
- .createGemFireErrorResult(CliStrings.format(CliStrings.PDX_RENAME__EMPTY));
- }
-
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- PrintStream printStream = new PrintStream(outputStream);
- for (Object p : results) {
- if (p instanceof PdxType) {
- ((PdxType) p).toStream(printStream, false);
- } else {
- ((EnumInfo) p).toStream(printStream);
- }
- }
- String resultString =
- CliStrings.format(CliStrings.PDX_RENAME__SUCCESS, outputStream.toString());
- return ResultBuilder.createInfoResult(resultString);
-
- } catch (Exception e) {
- return ResultBuilder.createGemFireErrorResult(
- CliStrings.format(CliStrings.PDX_RENAME__ERROR, e.getMessage()));
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
new file mode 100644
index 0000000..87c5bbc
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/QueueCommands.java
@@ -0,0 +1,259 @@
+/*
+ * 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 java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.domain.AsyncEventQueueDetails;
+import org.apache.geode.management.internal.cli.functions.AsyncEventQueueFunctionArgs;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.CreateAsyncEventQueueFunction;
+import org.apache.geode.management.internal.cli.functions.ListAsyncEventQueuesFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.configuration.domain.XmlEntity;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+/**
+ * The QueueCommands class encapsulates all GemFire Queue commands in Gfsh.
+ * </p>
+ *
+ * @since GemFire 8.0
+ */
+public class QueueCommands implements GfshCommand {
+
+ @CliCommand(value = CliStrings.CREATE_ASYNC_EVENT_QUEUE,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__HELP)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
+ public Result createAsyncEventQueue(
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID, mandatory = true,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ID__HELP) String id,
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GROUP__HELP) String[] groups,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL,
+ unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PARALLEL__HELP) Boolean parallel,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION,
+ unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ENABLEBATCHCONFLATION__HELP) Boolean enableBatchConflation,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE,
+ unspecifiedDefaultValue = "100",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCH_SIZE__HELP) int batchSize,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL,
+ unspecifiedDefaultValue = "1000",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__BATCHTIMEINTERVAL__HELP) int batchTimeInterval,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT,
+ unspecifiedDefaultValue = "false", specifiedDefaultValue = "true",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__PERSISTENT__HELP) boolean persistent,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISK_STORE__HELP) String diskStore,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS,
+ unspecifiedDefaultValue = "true", specifiedDefaultValue = "true",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY,
+ unspecifiedDefaultValue = "false", specifiedDefaultValue = "false",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__FORWARD_EXPIRATION_DESTROY__HELP) Boolean ignoreEvictionAndExpiration,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY,
+ unspecifiedDefaultValue = "100",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__MAXIMUM_QUEUE_MEMORY__HELP) int maxQueueMemory,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS,
+ unspecifiedDefaultValue = "1",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__DISPATCHERTHREADS__HELP) Integer dispatcherThreads,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY,
+ unspecifiedDefaultValue = "KEY",
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__ORDERPOLICY__HELP) String orderPolicy,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__GATEWAYEVENTFILTER__HELP) String[] gatewayEventFilters,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__SUBSTITUTION_FILTER__HELP) String gatewaySubstitutionListener,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER, mandatory = true,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER__HELP) String listener,
+ @CliOption(key = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE,
+ help = CliStrings.CREATE_ASYNC_EVENT_QUEUE__LISTENER_PARAM_AND_VALUE__HELP) String[] listenerParamsAndValues) {
+
+ if (persistent) {
+ getSecurityService().authorize(Resource.CLUSTER, Operation.WRITE, Target.DISK);
+ }
+ Properties listenerProperties = new Properties();
+
+ try {
+ if (listenerParamsAndValues != null) {
+ for (String listenerParamsAndValue : listenerParamsAndValues) {
+ final int hashPosition = listenerParamsAndValue.indexOf('#');
+ if (hashPosition == -1) {
+ listenerProperties.put(listenerParamsAndValue, "");
+ } else {
+ listenerProperties.put(listenerParamsAndValue.substring(0, hashPosition),
+ listenerParamsAndValue.substring(hashPosition + 1));
+ }
+ }
+ }
+
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ AsyncEventQueueFunctionArgs aeqArgs = new AsyncEventQueueFunctionArgs(id, parallel,
+ enableBatchConflation, batchSize, batchTimeInterval, persistent, diskStore,
+ diskSynchronous, maxQueueMemory, dispatcherThreads, orderPolicy, gatewayEventFilters,
+ gatewaySubstitutionListener, listener, listenerProperties, ignoreEvictionAndExpiration);
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(new CreateAsyncEventQueueFunction(), aeqArgs, targetMembers);
+
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+ + ": " + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else if (result.isSuccessful()) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", result.getMessage());
+ accumulatedData = true;
+
+ if (xmlEntity.get() == null) {
+ xmlEntity.set(result.getXmlEntity());
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult("Unable to create async event queue(s).");
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+ if (xmlEntity.get() != null) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
+ }
+ return result;
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.CREATE_ASYNC_EVENT_QUEUE__ERROR_WHILE_CREATING_REASON_0,
+ new Object[] {th.getMessage()}));
+ }
+ }
+
+ @CliCommand(value = CliStrings.LIST_ASYNC_EVENT_QUEUES,
+ help = CliStrings.LIST_ASYNC_EVENT_QUEUES__HELP)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listAsyncEventQueues() {
+ try {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(null, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc = CliUtil.executeFunction(new ListAsyncEventQueuesFunction(),
+ new Object[] {}, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Result", "ERROR: " + result.getThrowable().getClass().getName()
+ + ": " + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ AsyncEventQueueDetails[] details = (AsyncEventQueueDetails[]) result.getSerializables();
+ for (AsyncEventQueueDetails detail : details) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("ID", detail.getId());
+ tabularData.accumulate("Batch Size", detail.getBatchSize());
+ tabularData.accumulate("Persistent", detail.isPersistent());
+ tabularData.accumulate("Disk Store", detail.getDiskStoreName());
+ tabularData.accumulate("Max Memory", detail.getMaxQueueMemory());
+
+ Properties listenerProperties = detail.getListenerProperties();
+ if (listenerProperties == null || listenerProperties.size() == 0) {
+ tabularData.accumulate("Listener", detail.getListener());
+ } else {
+ StringBuilder propsStringBuilder = new StringBuilder();
+ propsStringBuilder.append('(');
+ boolean firstProperty = true;
+ for (Map.Entry<Object, Object> property : listenerProperties.entrySet()) {
+ if (!firstProperty) {
+ propsStringBuilder.append(',');
+ } else {
+ firstProperty = false;
+ }
+ propsStringBuilder.append(property.getKey()).append('=')
+ .append(property.getValue());
+ }
+ propsStringBuilder.append(')');
+
+ tabularData.accumulate("Listener",
+ detail.getListener() + propsStringBuilder.toString());
+ }
+ accumulatedData = true;
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder
+ .createInfoResult(CliStrings.LIST_ASYNC_EVENT_QUEUES__NO_QUEUES_FOUND_MESSAGE);
+ }
+
+ return ResultBuilder.buildResult(tabularData);
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(
+ CliStrings.format(CliStrings.LIST_ASYNC_EVENT_QUEUES__ERROR_WHILE_LISTING_REASON_0,
+ new Object[] {th.getMessage()}));
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
new file mode 100644
index 0000000..3222666
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommands.java
@@ -0,0 +1,474 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.cache.Region;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.LogWrapper;
+import org.apache.geode.management.internal.cli.domain.FixedPartitionAttributesInfo;
+import org.apache.geode.management.internal.cli.domain.RegionDescription;
+import org.apache.geode.management.internal.cli.domain.RegionDescriptionPerMember;
+import org.apache.geode.management.internal.cli.domain.RegionInformation;
+import org.apache.geode.management.internal.cli.functions.GetRegionDescriptionFunction;
+import org.apache.geode.management.internal.cli.functions.GetRegionsFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.cli.util.RegionAttributesNames;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+
+/**
+ * Class containing implementation of commands based on region:
+ * <ul>
+ * <li>list region
+ * <li>describe region
+ * </ul>
+ *
+ * @since GemFire 7.0
+ */
+public class RegionCommands implements GfshCommand {
+ private static final GetRegionsFunction getRegionsFunction = new GetRegionsFunction();
+ private static final GetRegionDescriptionFunction getRegionDescription =
+ new GetRegionDescriptionFunction();
+
+ @CliCommand(value = {CliStrings.LIST_REGION}, help = CliStrings.LIST_REGION__HELP)
+ @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listRegion(
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ optionContext = ConverterHint.MEMBERGROUP,
+ help = CliStrings.LIST_REGION__GROUP__HELP) String[] group,
+ @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
+ optionContext = ConverterHint.MEMBERIDNAME,
+ help = CliStrings.LIST_REGION__MEMBER__HELP) String[] memberNameOrId) {
+ Result result = null;
+ try {
+ Set<RegionInformation> regionInfoSet = new LinkedHashSet<>();
+ ResultCollector<?, ?> rc;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrId);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ TabularResultData resultData = ResultBuilder.createTabularResultData();
+ rc = CliUtil.executeFunction(getRegionsFunction, null, targetMembers);
+
+ ArrayList<?> resultList = (ArrayList<?>) rc.getResult();
+
+ if (resultList != null) {
+
+ for (Object resultObj : resultList) {
+ if (resultObj != null) {
+ if (resultObj instanceof Object[]) {
+ Object[] resultObjectArray = (Object[]) resultObj;
+ for (Object regionInfo : resultObjectArray) {
+ if (regionInfo instanceof RegionInformation) {
+ regionInfoSet.add((RegionInformation) regionInfo);
+ }
+ }
+ }
+ }
+ }
+
+ Set<String> regionNames = new TreeSet<>();
+
+ for (RegionInformation regionInfo : regionInfoSet) {
+ regionNames.add(regionInfo.getName());
+ Set<String> subRegionNames = regionInfo.getSubRegionNames();
+
+ regionNames.addAll(subRegionNames);
+ }
+
+ for (String regionName : regionNames) {
+ resultData.accumulate("List of regions", regionName);
+ }
+
+ if (!regionNames.isEmpty()) {
+ result = ResultBuilder.buildResult(resultData);
+
+ } else {
+ result = ResultBuilder.createInfoResult(CliStrings.LIST_REGION__MSG__NOT_FOUND);
+ }
+ }
+ } catch (FunctionInvocationTargetException e) {
+ result = ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.LIST_REGION));
+ } catch (Exception e) {
+ result = ResultBuilder
+ .createGemFireErrorResult(CliStrings.LIST_REGION__MSG__ERROR + " : " + e.getMessage());
+ }
+ return result;
+ }
+
+ @CliCommand(value = {CliStrings.DESCRIBE_REGION}, help = CliStrings.DESCRIBE_REGION__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result describeRegion(
+ @CliOption(key = CliStrings.DESCRIBE_REGION__NAME, optionContext = ConverterHint.REGION_PATH,
+ help = CliStrings.DESCRIBE_REGION__NAME__HELP, mandatory = true) String regionName) {
+
+ Result result;
+ try {
+
+ if (regionName == null || regionName.isEmpty()) {
+ return ResultBuilder.createUserErrorResult("Please provide a region name");
+ }
+
+ if (regionName.equals(Region.SEPARATOR)) {
+ return ResultBuilder.createUserErrorResult(CliStrings.INVALID_REGION_NAME);
+ }
+
+ InternalCache cache = getCache();
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(getRegionDescription, regionName, CliUtil.getAllMembers(cache));
+
+ List<?> resultList = (List<?>) rc.getResult();
+
+ // The returned result could be a region description with per member and /or single local
+ // region
+ Object[] results = resultList.toArray();
+ List<RegionDescription> regionDescriptionList = new ArrayList<>();
+
+ for (int i = 0; i < results.length; i++) {
+
+ if (results[i] instanceof RegionDescriptionPerMember) {
+ RegionDescriptionPerMember regionDescPerMember = (RegionDescriptionPerMember) results[i];
+
+ if (regionDescPerMember != null) {
+ RegionDescription regionDescription = new RegionDescription();
+ regionDescription.add(regionDescPerMember);
+
+ for (int j = i + 1; j < results.length; j++) {
+ if (results[j] != null && results[j] instanceof RegionDescriptionPerMember) {
+ RegionDescriptionPerMember preyRegionDescPerMember =
+ (RegionDescriptionPerMember) results[j];
+ if (regionDescription.add(preyRegionDescPerMember)) {
+ results[j] = null;
+ }
+ }
+ }
+ regionDescriptionList.add(regionDescription);
+ }
+ } else if (results[i] instanceof Throwable) {
+ Throwable t = (Throwable) results[i];
+ LogWrapper.getInstance().info(t.getMessage(), t);
+ }
+ }
+
+ if (regionDescriptionList.isEmpty()) {
+ return ResultBuilder
+ .createUserErrorResult(CliStrings.format(CliStrings.REGION_NOT_FOUND, regionName));
+ }
+
+ CompositeResultData crd = ResultBuilder.createCompositeResultData();
+
+ for (RegionDescription regionDescription : regionDescriptionList) {
+ // No point in displaying the scope for PR's
+ if (regionDescription.isPartition()) {
+ regionDescription.getCndRegionAttributes().remove(RegionAttributesNames.SCOPE);
+ } else {
+ String scope =
+ regionDescription.getCndRegionAttributes().get(RegionAttributesNames.SCOPE);
+ if (scope != null) {
+ scope = scope.toLowerCase().replace('_', '-');
+ regionDescription.getCndRegionAttributes().put(RegionAttributesNames.SCOPE, scope);
+ }
+ }
+ SectionResultData regionSection = crd.addSection();
+ regionSection.addSeparator('-');
+ regionSection.addData("Name", regionDescription.getName());
+
+ String dataPolicy =
+ regionDescription.getDataPolicy().toString().toLowerCase().replace('_', ' ');
+ regionSection.addData("Data Policy", dataPolicy);
+
+ String memberType;
+
+ if (regionDescription.isAccessor()) {
+ memberType = CliStrings.DESCRIBE_REGION__ACCESSOR__MEMBER;
+ } else {
+ memberType = CliStrings.DESCRIBE_REGION__HOSTING__MEMBER;
+ }
+ regionSection.addData(memberType,
+ CliUtil.convertStringSetToString(regionDescription.getHostingMembers(), '\n'));
+ regionSection.addSeparator('.');
+
+ TabularResultData commonNonDefaultAttrTable = regionSection.addSection().addTable();
+
+ commonNonDefaultAttrTable.setHeader(CliStrings
+ .format(CliStrings.DESCRIBE_REGION__NONDEFAULT__COMMONATTRIBUTES__HEADER, memberType));
+ // Common Non Default Region Attributes
+ Map<String, String> cndRegionAttrsMap = regionDescription.getCndRegionAttributes();
+
+ // Common Non Default Eviction Attributes
+ Map<String, String> cndEvictionAttrsMap = regionDescription.getCndEvictionAttributes();
+
+ // Common Non Default Partition Attributes
+ Map<String, String> cndPartitionAttrsMap = regionDescription.getCndPartitionAttributes();
+
+ writeCommonAttributesToTable(commonNonDefaultAttrTable,
+ CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, cndRegionAttrsMap);
+ writeCommonAttributesToTable(commonNonDefaultAttrTable,
+ CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION, cndEvictionAttrsMap);
+ writeCommonAttributesToTable(commonNonDefaultAttrTable,
+ CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, cndPartitionAttrsMap);
+
+ // Member-wise non default Attributes
+ Map<String, RegionDescriptionPerMember> regDescPerMemberMap =
+ regionDescription.getRegionDescriptionPerMemberMap();
+ Set<String> members = regDescPerMemberMap.keySet();
+
+ TabularResultData table = regionSection.addSection().addTable();
+
+ boolean setHeader = false;
+ for (String member : members) {
+ RegionDescriptionPerMember regDescPerMem = regDescPerMemberMap.get(member);
+ Map<String, String> ndRa = regDescPerMem.getNonDefaultRegionAttributes();
+ Map<String, String> ndEa = regDescPerMem.getNonDefaultEvictionAttributes();
+ Map<String, String> ndPa = regDescPerMem.getNonDefaultPartitionAttributes();
+
+ // Get all the member-specific non-default attributes by removing the common keys
+ ndRa.keySet().removeAll(cndRegionAttrsMap.keySet());
+ ndEa.keySet().removeAll(cndEvictionAttrsMap.keySet());
+ ndPa.keySet().removeAll(cndPartitionAttrsMap.keySet());
+
+ // Scope is not valid for PR's
+ if (regionDescription.isPartition()) {
+ if (ndRa.get(RegionAttributesNames.SCOPE) != null) {
+ ndRa.remove(RegionAttributesNames.SCOPE);
+ }
+ }
+
+ List<FixedPartitionAttributesInfo> fpaList = regDescPerMem.getFixedPartitionAttributes();
+
+ if (!(ndRa.isEmpty() && ndEa.isEmpty() && ndPa.isEmpty()) || fpaList != null) {
+ setHeader = true;
+ boolean memberNameAdded;
+ memberNameAdded = writeAttributesToTable(table,
+ CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__REGION, ndRa, member, false);
+ memberNameAdded =
+ writeAttributesToTable(table, CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__EVICTION,
+ ndEa, member, memberNameAdded);
+ memberNameAdded = writeAttributesToTable(table,
+ CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE__PARTITION, ndPa, member,
+ memberNameAdded);
+
+ writeFixedPartitionAttributesToTable(table, "", fpaList, member, memberNameAdded);
+ }
+ }
+
+ if (setHeader) {
+ table.setHeader(CliStrings.format(
+ CliStrings.DESCRIBE_REGION__NONDEFAULT__PERMEMBERATTRIBUTES__HEADER, memberType));
+ }
+ }
+
+ result = ResultBuilder.buildResult(crd);
+ } catch (FunctionInvocationTargetException e) {
+ result = ResultBuilder.createGemFireErrorResult(CliStrings
+ .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_REGION));
+ } catch (Exception e) {
+ String errorMessage = CliStrings.format(CliStrings.EXCEPTION_CLASS_AND_MESSAGE,
+ e.getClass().getName(), e.getMessage());
+ result = ResultBuilder.createGemFireErrorResult(errorMessage);
+ }
+ return result;
+ }
+
+ private void writeCommonAttributesToTable(TabularResultData table, String attributeType,
+ Map<String, String> attributesMap) {
+ if (!attributesMap.isEmpty()) {
+ Set<String> attributes = attributesMap.keySet();
+ boolean isTypeAdded = false;
+ final String blank = "";
+
+ for (String attributeName : attributes) {
+ String attributeValue = attributesMap.get(attributeName);
+ String type, memName;
+
+ if (!isTypeAdded) {
+ type = attributeType;
+ isTypeAdded = true;
+ } else {
+ type = blank;
+ }
+ writeCommonAttributeToTable(table, type, attributeName, attributeValue);
+ }
+ }
+ }
+
+ private boolean writeFixedPartitionAttributesToTable(TabularResultData table,
+ String attributeType, List<FixedPartitionAttributesInfo> fpaList, String member,
+ boolean isMemberNameAdded) {
+
+ if (fpaList != null) {
+ boolean isTypeAdded = false;
+ final String blank = "";
+
+ Iterator<FixedPartitionAttributesInfo> fpaIter = fpaList.iterator();
+ String type, memName;
+
+ while (fpaIter.hasNext()) {
+ FixedPartitionAttributesInfo fpa = fpaIter.next();
+ StringBuilder fpaBuilder = new StringBuilder();
+ fpaBuilder.append(fpa.getPartitionName());
+ fpaBuilder.append(',');
+
+ if (fpa.isPrimary()) {
+ fpaBuilder.append("Primary");
+ } else {
+ fpaBuilder.append("Secondary");
+ }
+ fpaBuilder.append(',');
+ fpaBuilder.append(fpa.getNumBuckets());
+
+ if (!isTypeAdded) {
+ type = attributeType;
+ isTypeAdded = true;
+ } else {
+ type = blank;
+ }
+
+ if (!isMemberNameAdded) {
+ memName = member;
+ isMemberNameAdded = true;
+ } else {
+ memName = blank;
+ }
+
+ writeAttributeToTable(table, memName, type, "Fixed Partition", fpaBuilder.toString());
+ }
+ }
+
+ return isMemberNameAdded;
+ }
+
+ private boolean writeAttributesToTable(TabularResultData table, String attributeType,
+ Map<String, String> attributesMap, String member, boolean isMemberNameAdded) {
+ if (!attributesMap.isEmpty()) {
+ Set<String> attributes = attributesMap.keySet();
+ boolean isTypeAdded = false;
+ final String blank = "";
+
+ for (String attributeName : attributes) {
+ String attributeValue = attributesMap.get(attributeName);
+ String type, memName;
+
+ if (!isTypeAdded) {
+ type = attributeType;
+ isTypeAdded = true;
+ } else {
+ type = blank;
+ }
+
+ if (!isMemberNameAdded) {
+ memName = member;
+ isMemberNameAdded = true;
+ } else {
+ memName = blank;
+ }
+
+ writeAttributeToTable(table, memName, type, attributeName, attributeValue);
+ }
+ }
+
+ return isMemberNameAdded;
+ }
+
+ public void writeAttributeToTable(TabularResultData table, String member, String attributeType,
+ String attributeName, String attributeValue) {
+
+ final String blank = "";
+ if (attributeValue != null) {
+ // Tokenize the attributeValue
+ String[] attributeValues = attributeValue.split(",");
+ boolean isFirstValue = true;
+
+ for (String value : attributeValues) {
+ if (isFirstValue) {
+ table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, member);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+ isFirstValue = false;
+ } else {
+ table.accumulate(CliStrings.DESCRIBE_REGION__MEMBER, blank);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+ }
+ }
+ }
+ }
+
+
+ private void writeCommonAttributeToTable(TabularResultData table, String attributeType,
+ String attributeName, String attributeValue) {
+ final String blank = "";
+
+ if (attributeValue != null) {
+ String[] attributeValues = attributeValue.split(",");
+ boolean isFirstValue = true;
+ for (String value : attributeValues) {
+ if (isFirstValue) {
+ isFirstValue = false;
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, attributeType);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, attributeName);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+ } else {
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__TYPE, blank);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__NAME, blank);
+ table.accumulate(CliStrings.DESCRIBE_REGION__ATTRIBUTE__VALUE, value);
+ }
+ }
+ }
+ }
+
+ public void addChildSection(SectionResultData parentSection, Map<String, String> map,
+ String header) {
+ if (!map.isEmpty()) {
+ Set<String> attributes = map.keySet();
+ SectionResultData section = parentSection.addSection();
+ section.setHeader(header);
+ for (String attribute : attributes) {
+ section.addData(attribute, map.get(attribute));
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java
deleted file mode 100644
index 49eb520..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RegionCommandsUtils.java
+++ /dev/null
@@ -1,59 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Pattern;
-
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-
-public class RegionCommandsUtils {
-
- static void validateGroups(InternalCache cache, String[] groups) {
- if (groups != null && groups.length != 0) {
- Set<String> existingGroups = new HashSet<>();
- Set<DistributedMember> members = CliUtil.getAllNormalMembers(cache);
- for (DistributedMember distributedMember : members) {
- List<String> memberGroups = distributedMember.getGroups();
- existingGroups.addAll(memberGroups);
- }
- List<String> groupsList = new ArrayList<>(Arrays.asList(groups));
- groupsList.removeAll(existingGroups);
-
- if (!groupsList.isEmpty()) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__GROUPS_0_ARE_INVALID,
- new Object[] {String.valueOf(groupsList)}));
- }
- }
- }
-
- static boolean isClassNameValid(String fqcn) {
- if (fqcn.isEmpty()) {
- return true;
- }
- String regex = "([\\p{L}_$][\\p{L}\\p{N}_$]*\\.)*[\\p{L}_$][\\p{L}\\p{N}_$]*";
- return Pattern.matches(regex, fqcn);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java
deleted file mode 100644
index 98acf55..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/RevokeMissingDiskStoreCommand.java
+++ /dev/null
@@ -1,61 +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 org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class RevokeMissingDiskStoreCommand implements GfshCommand {
- @CliCommand(value = CliStrings.REVOKE_MISSING_DISK_STORE,
- help = CliStrings.REVOKE_MISSING_DISK_STORE__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DISKSTORE})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.DISK)
- public Result revokeMissingDiskStore(@CliOption(key = CliStrings.REVOKE_MISSING_DISK_STORE__ID,
- mandatory = true, help = CliStrings.REVOKE_MISSING_DISK_STORE__ID__HELP) String id) {
-
- try {
- DistributedSystemMXBean dsMXBean =
- ManagementService.getManagementService(getCache()).getDistributedSystemMXBean();
- if (dsMXBean.revokeMissingDiskStores(id)) {
- return ResultBuilder.createInfoResult("Missing disk store successfully revoked");
- }
-
- return ResultBuilder.createUserErrorResult("Unable to find missing disk store to revoke");
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable th) {
- SystemFailure.checkFailure();
- if (th.getMessage() == null) {
- return ResultBuilder.createGemFireErrorResult(
- "An error occurred while revoking missing disk stores: " + th);
- }
- return ResultBuilder.createGemFireErrorResult(
- "An error occurred while revoking missing disk stores: " + th.getMessage());
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
index 41e227b..84ee5db 100644
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShellCommands.java
@@ -319,6 +319,7 @@ public class ShellCommands implements GfshCommand {
@CliMetaData(shellOnly = true, relatedTopic = {CliStrings.TOPIC_GFSH})
public Result history(
@CliOption(key = {CliStrings.HISTORY__FILE},
+ unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE,
help = CliStrings.HISTORY__FILE__HELP) String saveHistoryTo,
@CliOption(key = {CliStrings.HISTORY__CLEAR}, specifiedDefaultValue = "true",
unspecifiedDefaultValue = "false",
@@ -330,7 +331,7 @@ public class ShellCommands implements GfshCommand {
} else {
// Process file option
Gfsh gfsh = Gfsh.getCurrentInstance();
- ErrorResultData errorResultData;
+ ErrorResultData errorResultData = null;
StringBuilder contents = new StringBuilder();
Writer output = null;
@@ -345,7 +346,7 @@ public class ShellCommands implements GfshCommand {
while (it.hasNext()) {
String line = it.next().toString();
- if (!line.isEmpty()) {
+ if (line.isEmpty() == false) {
if (flagForLineNumbers) {
lineNumber++;
contents.append(String.format("%" + historySizeWordLength + "s ", lineNumber));
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java
deleted file mode 100644
index 3b5fd78..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowDeadlockCommand.java
+++ /dev/null
@@ -1,92 +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 java.text.MessageFormat;
-import java.util.Collection;
-import java.util.Set;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.deadlock.DeadlockDetector;
-import org.apache.geode.distributed.internal.deadlock.Dependency;
-import org.apache.geode.distributed.internal.deadlock.DependencyGraph;
-import org.apache.geode.distributed.internal.deadlock.GemFireDeadlockDetector;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ShowDeadlockCommand implements GfshCommand {
- @CliCommand(value = CliStrings.SHOW_DEADLOCK, help = CliStrings.SHOW_DEADLOCK__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result showDeadlock(@CliOption(key = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE,
- help = CliStrings.SHOW_DEADLOCK__DEPENDENCIES__FILE__HELP,
- mandatory = true) String filename) {
-
- Result result;
- try {
- if (!filename.endsWith(".txt")) {
- return ResultBuilder
- .createUserErrorResult(CliStrings.format(CliStrings.INVALID_FILE_EXTENSION, ".txt"));
- }
- InternalCache cache = getCache();
-
- Set<DistributedMember> allMembers = CliUtil.getAllMembers(cache);
- GemFireDeadlockDetector gfeDeadLockDetector = new GemFireDeadlockDetector(allMembers);
- DependencyGraph dependencyGraph = gfeDeadLockDetector.find();
- Collection<Dependency> deadlock = dependencyGraph.findCycle();
- DependencyGraph deepest = null;
- if (deadlock == null) {
- deepest = dependencyGraph.findLongestCallChain();
- if (deepest != null) {
- deadlock = deepest.getEdges();
- }
- }
- Set<Dependency> dependencies = (Set<Dependency>) dependencyGraph.getEdges();
-
- InfoResultData resultData = ResultBuilder.createInfoResultData();
-
- if (deadlock != null) {
- if (deepest != null) {
- resultData.addLine(CliStrings.SHOW_DEADLOCK__DEEPEST_FOUND);
- } else {
- resultData.addLine(CliStrings.SHOW_DEADLOCK__DEADLOCK__DETECTED);
- }
- resultData.addLine(DeadlockDetector.prettyFormat(deadlock));
- } else {
- resultData.addLine(CliStrings.SHOW_DEADLOCK__NO__DEADLOCK);
- }
- resultData.addAsFile(filename, DeadlockDetector.prettyFormat(dependencies),
- MessageFormat.format(CliStrings.SHOW_DEADLOCK__DEPENDENCIES__REVIEW, filename), false);
- result = ResultBuilder.buildResult(resultData);
-
- } catch (Exception e) {
- result = ResultBuilder
- .createGemFireErrorResult(CliStrings.SHOW_DEADLOCK__ERROR + " : " + e.getMessage());
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java
deleted file mode 100644
index 7780479..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/ShowLogCommand.java
+++ /dev/null
@@ -1,102 +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 javax.management.ObjectName;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.MemberMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.ManagementConstants;
-import org.apache.geode.management.internal.SystemManagementService;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class ShowLogCommand implements GfshCommand {
- @CliCommand(value = CliStrings.SHOW_LOG, help = CliStrings.SHOW_LOG_HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_DEBUG_UTIL})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result showLog(
- @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.SHOW_LOG_MEMBER_HELP, mandatory = true) String memberNameOrId,
- @CliOption(key = CliStrings.SHOW_LOG_LINE_NUM, unspecifiedDefaultValue = "0",
- help = CliStrings.SHOW_LOG_LINE_NUM_HELP) int numberOfLines) {
- Result result;
- try {
- InternalCache cache = getCache();
- SystemManagementService service =
- (SystemManagementService) ManagementService.getExistingManagementService(cache);
- MemberMXBean bean;
- DistributedMember memberToBeInvoked = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
- if (memberToBeInvoked != null) {
- String memberId = memberToBeInvoked.getId();
-
- if (cache.getDistributedSystem().getDistributedMember().getId().equals(memberId)) {
- bean = service.getMemberMXBean();
- } else {
- ObjectName objectName = service.getMemberMBeanName(memberToBeInvoked);
- bean = service.getMBeanProxy(objectName, MemberMXBean.class);
- }
-
- if (numberOfLines > ManagementConstants.MAX_SHOW_LOG_LINES) {
- numberOfLines = ManagementConstants.MAX_SHOW_LOG_LINES;
- }
- if (numberOfLines == 0 || numberOfLines < 0) {
- numberOfLines = ManagementConstants.DEFAULT_SHOW_LOG_LINES;
- }
- InfoResultData resultData = ResultBuilder.createInfoResultData();
- if (bean != null) {
- String log = bean.showLog(numberOfLines);
- if (log != null) {
- resultData.addLine(log);
- } else {
- resultData.addLine(CliStrings.SHOW_LOG_NO_LOG);
- }
- } else {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
- return (ResultBuilder.buildResult(errorResultData));
- }
-
- result = ResultBuilder.buildResult(resultData);
- } else {
- ErrorResultData errorResultData =
- ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT)
- .addLine(memberNameOrId + CliStrings.SHOW_LOG_MSG_MEMBER_NOT_FOUND);
- return (ResultBuilder.buildResult(errorResultData));
- }
-
- } catch (Exception e) {
- result = ResultBuilder
- .createGemFireErrorResult(CliStrings.SHOW_LOG_ERROR + CliUtil.stackTraceAsString(e));
- }
- return result;
- }
-}
[15/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
deleted file mode 100644
index b160b99..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
+++ /dev/null
@@ -1,196 +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 java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateIndexCommand implements GfshCommand {
- private static final CreateIndexFunction createIndexFunction = new CreateIndexFunction();
-
- @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- // TODO : Add optionContext for indexName
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
- help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,
-
- @CliOption(key = CliStrings.CREATE_INDEX__EXPRESSION, mandatory = true,
- help = CliStrings.CREATE_INDEX__EXPRESSION__HELP) final String indexedExpression,
-
- @CliOption(key = CliStrings.CREATE_INDEX__REGION, mandatory = true,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,
-
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,
-
- @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
- optionContext = ConverterHint.INDEX_TYPE,
- help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
-
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
- try {
- CacheFactory.getAnyInstance();
- int idxType;
-
- // Index type check
- if ("range".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.RANGE_INDEX;
- } else if ("hash".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.HASH_INDEX;
- } else if ("key".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.KEY_INDEX;
- } else {
- return ResultBuilder
- .createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
- }
-
- if (indexName == null || indexName.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__NAME);
- }
-
- if (indexedExpression == null || indexedExpression.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__EXPRESSION);
- }
-
- if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
- return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__REGIONPATH);
- }
-
- if (!regionPath.startsWith(Region.SEPARATOR)) {
- regionPath = Region.SEPARATOR + regionPath;
- }
-
- IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
- final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- final ResultCollector<?, ?> rc =
- CliUtil.executeFunction(createIndexFunction, indexInfo, targetMembers);
-
- final List<Object> funcResults = (List<Object>) rc.getResult();
- final Set<String> successfulMembers = new TreeSet<>();
- final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
- for (final Object funcResult : funcResults) {
- if (funcResult instanceof CliFunctionResult) {
- final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
- if (cliFunctionResult.isSuccessful()) {
- successfulMembers.add(cliFunctionResult.getMemberIdOrName());
-
- if (xmlEntity.get() == null) {
- xmlEntity.set(cliFunctionResult.getXmlEntity());
- }
- } else {
- final String exceptionMessage = cliFunctionResult.getMessage();
- Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
- if (failedMembers == null) {
- failedMembers = new TreeSet<>();
- }
- failedMembers.add(cliFunctionResult.getMemberIdOrName());
- indexOpFailMap.put(exceptionMessage, failedMembers);
- }
- }
- }
-
- if (!successfulMembers.isEmpty()) {
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.CREATE_INDEX__SUCCESS__MSG);
- infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__NAME__MSG, indexName));
- infoResult.addLine(
- CliStrings.format(CliStrings.CREATE_INDEX__EXPRESSION__MSG, indexedExpression));
- infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__REGIONPATH__MSG, regionPath));
- infoResult.addLine(CliStrings.CREATE_INDEX__MEMBER__MSG);
-
- int num = 0;
-
- for (final String memberId : successfulMembers) {
- ++num;
- infoResult.addLine(
- CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
- }
- result = ResultBuilder.buildResult(infoResult);
-
- } else {
- // Group members by the exception thrown.
- final ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(CliStrings.format(CliStrings.CREATE_INDEX__FAILURE__MSG, indexName));
- final Set<String> exceptionMessages = indexOpFailMap.keySet();
-
- for (final String exceptionMessage : exceptionMessages) {
- erd.addLine(exceptionMessage);
- erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
- final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
- int num = 0;
- for (final String memberId : memberIds) {
- ++num;
- erd.addLine(
- CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
- }
- }
- result = ResultBuilder.buildResult(erd);
- }
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
deleted file mode 100644
index 8ba39b7..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
+++ /dev/null
@@ -1,741 +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 java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.management.ObjectName;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.PartitionResolver;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionAttributes;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.compression.Compressor;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DistributionManager;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.internal.ClassPathLoader;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.management.DistributedRegionMXBean;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.RegionAttributesData;
-import org.apache.geode.management.RegionMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction;
-import org.apache.geode.management.internal.cli.functions.RegionCreateFunction;
-import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.util.RegionPath;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateRegionCommand implements GfshCommand {
- public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>();
-
- static {
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
- }
-
- @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = ResourcePermission.Resource.DATA,
- operation = ResourcePermission.Operation.MANAGE)
- public Result createRegion(
- @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true,
- help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT,
- help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut,
- @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups,
- @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true",
- specifiedDefaultValue = "true",
- help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists,
-
- // the following should all be in alphabetical order according to
- // their key string
- @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID,
- help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
- @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER,
- help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener,
- @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER,
- help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader,
- @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER,
- help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter,
- @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith,
- @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR,
- help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor,
- @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL,
- help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel,
- @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE,
- help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore,
- @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION,
- help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation,
- @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED,
- help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED,
- help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED,
- help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED,
- help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION,
- help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation,
- @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS,
- help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
- @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID,
- help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
- @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT,
- help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint,
- @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY,
- help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory,
- @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true",
- help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap,
- @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER,
- help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
- @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY,
- help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay,
- @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES,
- help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies,
- @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY,
- help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay,
- @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY,
- help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory,
- @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS,
- help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets,
- @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT,
- help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint
- // NOTICE: keep the region attributes params in alphabetical order
- ) {
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
- try {
- InternalCache cache = getCache();
-
- if (regionShortcut != null && useAttributesFrom != null) {
- throw new IllegalArgumentException(
- CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED);
- } else if (regionShortcut == null && useAttributesFrom == null) {
- throw new IllegalArgumentException(
- CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUTESFROM_IS_REQUIRED);
- }
-
- validateRegionPathAndParent(cache, regionPath);
- RegionCommandsUtils.validateGroups(cache, groups);
-
- RegionFunctionArgs.ExpirationAttrs entryIdle = null;
- if (entryExpirationIdleTime != null) {
- entryIdle = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
- entryExpirationIdleTimeAction);
- }
- RegionFunctionArgs.ExpirationAttrs entryTTL = null;
- if (entryExpirationTTL != null) {
- entryTTL = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
- entryExpirationTTLAction);
- }
- RegionFunctionArgs.ExpirationAttrs regionIdle = null;
- if (regionExpirationIdleTime != null) {
- regionIdle = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
- regionExpirationIdleTimeAction);
- }
- RegionFunctionArgs.ExpirationAttrs regionTTL = null;
- if (regionExpirationTTL != null) {
- regionTTL = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
- regionExpirationTTLAction);
- }
-
- RegionFunctionArgs regionFunctionArgs;
- if (useAttributesFrom != null) {
- if (!regionExists(cache, useAttributesFrom)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
- new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
- }
-
- FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult =
- getRegionAttributes(cache, useAttributesFrom);
- RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes();
-
- // give preference to user specified plugins than the ones retrieved from other region
- String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0
- ? cacheListener : regionAttributesResult.getCacheListenerClasses();
- String cacheLoaderClass =
- cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass();
- String cacheWriterClass =
- cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass();
-
- regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists,
- keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle,
- regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
- enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass,
- asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
- concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
- prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled,
- regionAttributes, partitionResolver);
-
- if (regionAttributes.getPartitionAttributes() == null
- && regionFunctionArgs.hasPartitionAttributes()) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
- regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
- useAttributesFrom));
- }
- } else {
- regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom,
- skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL,
- regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
- enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter,
- asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
- concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
- prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap,
- mcastEnabled, partitionResolver);
-
- if (!regionShortcut.name().startsWith("PARTITION")
- && regionFunctionArgs.hasPartitionAttributes()) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
- regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
- useAttributesFrom));
- }
- }
-
- // Do we prefer to validate or authorize first?
- validateRegionFunctionArgs(cache, regionFunctionArgs);
- if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut())
- || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) {
- getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
- ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
- }
-
- Set<DistributedMember> membersToCreateRegionOn;
- if (groups != null && groups.length != 0) {
- membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups);
- // have only normal members from the group
- membersToCreateRegionOn
- .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember)
- .getVmKind() == DistributionManager.LOCATOR_DM_TYPE);
- } else {
- membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache);
- }
-
- if (membersToCreateRegionOn.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE,
- regionFunctionArgs, membersToCreateRegionOn);
- @SuppressWarnings("unchecked")
- List<CliFunctionResult> regionCreateResults =
- (List<CliFunctionResult>) resultCollector.getResult();
-
- TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
- final String errorPrefix = "ERROR: ";
- for (CliFunctionResult regionCreateResult : regionCreateResults) {
- boolean success = regionCreateResult.isSuccessful();
- tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName());
- tabularResultData.accumulate("Status",
- (success ? "" : errorPrefix) + regionCreateResult.getMessage());
-
- if (success) {
- xmlEntity.set(regionCreateResult.getXmlEntity());
- }
- }
- result = ResultBuilder.buildResult(tabularResultData);
- verifyDistributedRegionMbean(cache, regionPath);
-
- } catch (IllegalArgumentException | IllegalStateException e) {
- LogWrapper.getInstance().info(e.getMessage());
- result = ResultBuilder.createUserErrorResult(e.getMessage());
- }
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
- }
-
- return result;
- }
-
- public boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) {
- int federationInterval =
- cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate();
- long timeEnd = System.currentTimeMillis() + federationInterval + 50;
-
- for (; System.currentTimeMillis() <= timeEnd;) {
- try {
- DistributedRegionMXBean bean =
- ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName);
- if (bean == null) {
- bean = ManagementService.getManagementService(cache)
- .getDistributedRegionMXBean(Region.SEPARATOR + regionName);
- }
- if (bean != null) {
- return true;
- } else {
- Thread.sleep(2);
- }
- } catch (Exception ignored) {
- }
- }
- return false;
- }
-
- void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) {
- if (regionFunctionArgs.getRegionPath() == null) {
- throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
- }
-
- DistributedSystemMXBean dsMBean = getDSMBean(cache);
-
- String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom();
- if (useAttributesFrom != null && !useAttributesFrom.isEmpty()
- && regionExists(cache, useAttributesFrom)) {
- if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!!
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
- new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
- }
- if (!regionFunctionArgs.isSetUseAttributesFrom()
- || regionFunctionArgs.getRegionAttributes() == null) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS,
- useAttributesFrom));
- }
- }
-
- if (regionFunctionArgs.hasPartitionAttributes()) {
- RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs();
- String colocatedWith = partitionArgs.getPrColocatedWith();
- if (colocatedWith != null && !colocatedWith.isEmpty()) {
- String[] listAllRegionPaths = dsMBean.listAllRegionPaths();
- String foundRegionPath = null;
- for (String regionPath : listAllRegionPaths) {
- if (regionPath.equals(colocatedWith)) {
- foundRegionPath = regionPath;
- break;
- }
- }
- if (foundRegionPath == null) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
- new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith}));
- }
- ManagementService mgmtService = ManagementService.getExistingManagementService(cache);
- DistributedRegionMXBean distributedRegionMXBean =
- mgmtService.getDistributedRegionMXBean(foundRegionPath);
- String regionType = distributedRegionMXBean.getRegionType();
- if (!(DataPolicy.PARTITION.toString().equals(regionType)
- || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION,
- new Object[] {colocatedWith}));
- }
- }
- if (partitionArgs.isSetPRLocalMaxMemory()) {
- int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory();
- if (prLocalMaxMemory < 0) {
- throw new IllegalArgumentException(
- LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE
- .toLocalizedString());
- }
- }
- if (partitionArgs.isSetPRTotalMaxMemory()) {
- long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory();
- if (prTotalMaxMemory <= 0) {
- throw new IllegalArgumentException(
- LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0
- .toLocalizedString());
- }
- }
- if (partitionArgs.isSetPRRedundantCopies()) {
- int prRedundantCopies = partitionArgs.getPrRedundantCopies();
- switch (prRedundantCopies) {
- case 0:
- case 1:
- case 2:
- case 3:
- break;
- default:
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123,
- new Object[] {prRedundantCopies}));
- }
- }
- }
-
- String keyConstraint = regionFunctionArgs.getKeyConstraint();
- if (keyConstraint != null && !RegionCommandsUtils.isClassNameValid(keyConstraint)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID,
- new Object[] {keyConstraint}));
- }
-
- String valueConstraint = regionFunctionArgs.getValueConstraint();
- if (valueConstraint != null && !RegionCommandsUtils.isClassNameValid(valueConstraint)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID,
- new Object[] {valueConstraint}));
- }
-
- Set<String> cacheListeners = regionFunctionArgs.getCacheListeners();
- if (cacheListeners != null && !cacheListeners.isEmpty()) {
- for (String cacheListener : cacheListeners) {
- if (!RegionCommandsUtils.isClassNameValid(cacheListener)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
- new Object[] {cacheListener}));
- }
- }
- }
-
- String cacheLoader = regionFunctionArgs.getCacheLoader();
- if (cacheLoader != null && !RegionCommandsUtils.isClassNameValid(cacheLoader)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
- new Object[] {cacheLoader}));
- }
-
- String cacheWriter = regionFunctionArgs.getCacheWriter();
- if (cacheWriter != null && !RegionCommandsUtils.isClassNameValid(cacheWriter)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
- new Object[] {cacheWriter}));
- }
-
- Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds();
- if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) {
- String[] gatewaySenders = dsMBean.listGatewaySenders();
- if (gatewaySenders.length == 0) {
- throw new IllegalArgumentException(
- CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM);
- } else {
- List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders));
- gatewaySenderIds = new HashSet<>(gatewaySenderIds);
- gatewaySenderIds.removeAll(gatewaySendersList);
- if (!gatewaySenderIds.isEmpty()) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0,
- new Object[] {gatewaySenderIds}));
- }
- }
- }
-
- if (regionFunctionArgs.isSetConcurrencyLevel()) {
- int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel();
- if (concurrencyLevel < 0) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID,
- new Object[] {concurrencyLevel}));
- }
- }
-
- String diskStore = regionFunctionArgs.getDiskStore();
- if (diskStore != null) {
- RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut();
- if (regionShortcut != null && !PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) {
- String subMessage =
- LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
- String message = subMessage + ". "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
- new Object[] {String.valueOf(PERSISTENT_OVERFLOW_SHORTCUTS)});
-
- throw new IllegalArgumentException(message);
- }
-
- RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes();
- if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) {
- String subMessage =
- LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
- String message = subMessage + ". "
- + CliStrings.format(
- CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE,
- new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())});
-
- throw new IllegalArgumentException(message);
- }
-
- if (!diskStoreExists(cache, diskStore)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0,
- new Object[] {diskStore}));
- }
- }
-
- RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime =
- regionFunctionArgs.getEntryExpirationIdleTime();
- RegionFunctionArgs.ExpirationAttrs entryExpirationTTL =
- regionFunctionArgs.getEntryExpirationTTL();
- RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime =
- regionFunctionArgs.getRegionExpirationIdleTime();
- RegionFunctionArgs.ExpirationAttrs regionExpirationTTL =
- regionFunctionArgs.getRegionExpirationTTL();
-
- if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled())
- && (entryExpirationIdleTime != null || entryExpirationTTL != null
- || regionExpirationIdleTime != null || regionExpirationTTL != null)) {
- String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION
- .toLocalizedString();
- throw new IllegalArgumentException(message + ".");
- }
-
- boolean compressorFailure = false;
- if (regionFunctionArgs.isSetCompressor()) {
- String compressorClassName = regionFunctionArgs.getCompressor();
- Object compressor = null;
- try {
- Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName);
- compressor = compressorClass.newInstance();
- } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
- compressorFailure = true;
- }
-
- if (compressorFailure || !(compressor instanceof Compressor)) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR,
- new Object[] {regionFunctionArgs.getCompressor()}));
- }
- }
-
- if (regionFunctionArgs.hasPartitionAttributes()) {
- if (regionFunctionArgs.isPartitionResolverSet()) {
- String partitionResolverClassName = regionFunctionArgs.getPartitionResolver();
- try {
- Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader
- .getLatest().forName(partitionResolverClassName);
- PartitionResolver partitionResolver = resolverClass.newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER,
- new Object[] {regionFunctionArgs.getPartitionResolver()}),
- e);
- }
- }
- }
- }
-
- private boolean diskStoreExists(InternalCache cache, String diskStoreName) {
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
- Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
-
- Set<Map.Entry<String, String[]>> entrySet = diskstore.entrySet();
-
- for (Map.Entry<String, String[]> entry : entrySet) {
- String[] value = entry.getValue();
- if (CliUtil.contains(value, diskStoreName)) {
- return true;
- }
- }
-
- return false;
- }
-
- private void validateRegionPathAndParent(InternalCache cache, String regionPath) {
- if (StringUtils.isEmpty(regionPath)) {
- throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
- }
- // If a region path indicates a sub-region, check whether the parent region exists
- RegionPath regionPathData = new RegionPath(regionPath);
- String parentRegionPath = regionPathData.getParent();
- if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
- if (!regionExists(cache, parentRegionPath)) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOES_NOT_EXIST,
- new Object[] {regionPath}));
- }
- }
- }
-
- private static <K, V> FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> getRegionAttributes(
- InternalCache cache, String regionPath) {
- if (!isClusterWideSameConfig(cache, regionPath)) {
- throw new IllegalStateException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0,
- regionPath));
- }
- FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> attributes = null;
-
- // First check whether the region exists on a this manager, if yes then no
- // need to use FetchRegionAttributesFunction to fetch RegionAttributes
- try {
- attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath);
- } catch (IllegalArgumentException e) {
- /* region doesn't exist on the manager */
- }
-
- if (attributes == null) {
- // find first member which has the region
- Set<DistributedMember> regionAssociatedMembers =
- CliUtil.getRegionAssociatedMembers(regionPath, cache, false);
- if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) {
- DistributedMember distributedMember = regionAssociatedMembers.iterator().next();
- ResultCollector<?, ?> resultCollector = CliUtil
- .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember);
- List<?> resultsList = (List<?>) resultCollector.getResult();
-
- if (resultsList != null && !resultsList.isEmpty()) {
- for (Object object : resultsList) {
- if (object instanceof IllegalArgumentException) {
- throw (IllegalArgumentException) object;
- } else if (object instanceof Throwable) {
- Throwable th = (Throwable) object;
- LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th)));
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1,
- new Object[] {regionPath, th.getMessage()}));
- } else { // has to be RegionAttributes
- @SuppressWarnings("unchecked") // to avoid warning :(
- FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> regAttr =
- ((FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V>) object);
- if (attributes == null) {
- attributes = regAttr;
- break;
- } // attributes null check
- } // not IllegalArgumentException or other throwable
- } // iterate over list - there should be only one result in the list
- } // result list is not null or empty
- } // regionAssociatedMembers is not-empty
- } // attributes are null because do not exist on local member
-
- return attributes;
- }
-
- private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) {
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
-
- DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
-
- Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache);
-
- RegionAttributesData regionAttributesToValidateAgainst = null;
- for (DistributedMember distributedMember : allMembers) {
- ObjectName regionObjectName;
- try {
- regionObjectName = dsMXBean
- .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath);
- RegionMXBean regionMBean =
- managementService.getMBeanInstance(regionObjectName, RegionMXBean.class);
- RegionAttributesData regionAttributes = regionMBean.listRegionAttributes();
-
- if (regionAttributesToValidateAgainst == null) {
- regionAttributesToValidateAgainst = regionAttributes;
- } else if (!(regionAttributesToValidateAgainst.getScope()
- .equals(regionAttributes.getScope())
- || regionAttributesToValidateAgainst.getDataPolicy()
- .equals(regionAttributes.getDataPolicy()))) {
- return false;
- }
- } catch (Exception e) {
- // ignore
- }
- }
-
- return true;
- }
-
- private boolean isPersistentShortcut(RegionShortcut shortcut) {
- return shortcut == RegionShortcut.LOCAL_PERSISTENT
- || shortcut == RegionShortcut.LOCAL_PERSISTENT_OVERFLOW
- || shortcut == RegionShortcut.PARTITION_PERSISTENT
- || shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW
- || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT
- || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW
- || shortcut == RegionShortcut.REPLICATE_PERSISTENT
- || shortcut == RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW;
- }
-
- private boolean isAttributePersistent(RegionAttributes attributes) {
- return attributes != null && attributes.getDataPolicy() != null
- && attributes.getDataPolicy().toString().contains("PERSISTENT");
- }
-
- public static boolean regionExists(InternalCache cache, String regionPath) {
- if (regionPath == null || Region.SEPARATOR.equals(regionPath)) {
- return false;
- }
-
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
-
- String[] allRegionPaths = dsMBean.listAllRegionPaths();
- return Arrays.stream(allRegionPaths).anyMatch(regionPath::equals);
- }
-
- public DistributedSystemMXBean getDSMBean(InternalCache cache) {
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- return managementService.getDistributedSystemMXBean();
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
deleted file mode 100644
index 1102cd8..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
+++ /dev/null
@@ -1,95 +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 org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.Region;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DefineIndexCommand implements GfshCommand {
- @CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- // TODO : Add optionContext for indexName
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result defineIndex(
- @CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true,
- help = CliStrings.DEFINE_INDEX__HELP) final String indexName,
- @CliOption(key = CliStrings.DEFINE_INDEX__EXPRESSION, mandatory = true,
- help = CliStrings.DEFINE_INDEX__EXPRESSION__HELP) final String indexedExpression,
- @CliOption(key = CliStrings.DEFINE_INDEX__REGION, mandatory = true,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath,
- @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, unspecifiedDefaultValue = "range",
- optionContext = ConverterHint.INDEX_TYPE,
- help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
-
- Result result;
- int idxType;
-
- // Index type check
- if ("range".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.RANGE_INDEX;
- } else if ("hash".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.HASH_INDEX;
- } else if ("key".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.KEY_INDEX;
- } else {
- return ResultBuilder
- .createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
- }
-
- if (indexName == null || indexName.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__NAME);
- }
-
- if (indexedExpression == null || indexedExpression.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__EXPRESSION);
- }
-
- if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
- return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__REGIONPATH);
- }
-
- if (!regionPath.startsWith(Region.SEPARATOR)) {
- regionPath = Region.SEPARATOR + regionPath;
- }
-
- IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
- IndexDefinition.indexDefinitions.add(indexInfo);
-
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.DEFINE_INDEX__SUCCESS__MSG);
- infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__NAME__MSG, indexName));
- infoResult
- .addLine(CliStrings.format(CliStrings.DEFINE_INDEX__EXPRESSION__MSG, indexedExpression));
- infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__REGIONPATH__MSG, regionPath));
- result = ResultBuilder.buildResult(infoResult);
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
deleted file mode 100644
index 4f46539..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
+++ /dev/null
@@ -1,190 +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.commons.io.FileUtils.ONE_MB;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.text.DecimalFormat;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.DeployFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
-import org.apache.geode.management.internal.cli.result.FileResult;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.NotAuthorizedException;
-import org.apache.geode.security.ResourcePermission;
-
-public class DeployCommand implements GfshCommand {
- private final DeployFunction deployFunction = new DeployFunction();
-
- /**
- * Deploy one or more JAR files to members of a group or all members.
- *
- * @param groups Group(s) to deploy the JAR to or null for all members
- * @param jars JAR file to deploy
- * @param dir Directory of JAR files to deploy
- * @return The result of the attempt to deploy
- */
- @CliCommand(value = {CliStrings.DEPLOY}, help = CliStrings.DEPLOY__HELP)
- @CliMetaData(
- interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommand$Interceptor",
- relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
- public Result deploy(
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) String[] groups,
- @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
- help = CliStrings.DEPLOY__JAR__HELP) String[] jars,
- @CliOption(key = {CliStrings.DEPLOY__DIR}, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
- try {
-
- // since deploy function can potentially do a lot of damage to security, this action should
- // require these following privileges
- SecurityService securityService = getSecurityService();
-
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
-
- byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
- String[] jarNames = CliUtil.bytesToNames(shellBytesData);
- byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
-
- Set<DistributedMember> targetMembers;
-
- targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.size() > 0) {
- // this deploys the jars to all the matching servers
- ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction,
- new Object[] {jarNames, jarBytes}, targetMembers);
-
- List<CliFunctionResult> results =
- CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Deployed JAR", "");
- tabularData.accumulate("Deployed JAR Location",
- "ERROR: " + result.getThrowable().getClass().getName() + ": "
- + result.getThrowable().getMessage());
- tabularData.setStatus(Result.Status.ERROR);
- } else {
- String[] strings = (String[]) result.getSerializables();
- for (int i = 0; i < strings.length; i += 2) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Deployed JAR", strings[i]);
- tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
- }
- }
- }
- }
-
- Result result = ResultBuilder.buildResult(tabularData);
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
- return result;
- } catch (NotAuthorizedException e) {
- // for NotAuthorizedException, will catch this later in the code
- throw e;
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(String
- .format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
- }
- }
-
- /**
- * Interceptor used by gfsh to intercept execution of deploy command at "shell".
- */
- public static class Interceptor extends AbstractCliAroundInterceptor {
- private final DecimalFormat numFormatter = new DecimalFormat("###,##0.00");
-
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- // 2nd argument is the jar
- String[] jars = (String[]) parseResult.getArguments()[1];
- // 3rd argument is the dir
- String dir = (String) parseResult.getArguments()[2];
-
- if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
- return ResultBuilder.createUserErrorResult(
- "Parameter \"jar\" or \"dir\" is required. Use \"help <command name>\" for assistance.");
- }
-
- if (ArrayUtils.isNotEmpty(jars) && StringUtils.isNotBlank(dir)) {
- return ResultBuilder
- .createUserErrorResult("Parameters \"jar\" and \"dir\" can not both be specified.");
- }
-
- FileResult fileResult;
- String[] filesToUpload = jars;
- if (filesToUpload == null) {
- filesToUpload = new String[] {dir};
- }
- try {
-
- fileResult = new FileResult(filesToUpload);
- } catch (FileNotFoundException fnfex) {
- return ResultBuilder
- .createGemFireErrorResult("'" + Arrays.toString(filesToUpload) + "' not found.");
- } catch (IOException ioex) {
- return ResultBuilder.createGemFireErrorResult("I/O error when reading jar/dir: "
- + ioex.getClass().getName() + ": " + ioex.getMessage());
- }
-
- // Only do this additional check if a dir was provided
- if (dir != null) {
- String message =
- "\nDeploying files: " + fileResult.getFormattedFileList() + "\nTotal file size is: "
- + this.numFormatter.format((double) fileResult.computeFileSizeTotal() / ONE_MB)
- + "MB\n\nContinue? ";
-
- if (readYesNo(message, Response.YES) == Response.NO) {
- return ResultBuilder.createShellClientAbortOperationResult(
- "Aborted deploy of " + Arrays.toString(filesToUpload) + ".");
- }
- }
- return fileResult;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
new file mode 100644
index 0000000..e502154
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
@@ -0,0 +1,336 @@
+/*
+ * 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.commons.io.FileUtils.ONE_MB;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.text.DecimalFormat;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.security.SecurityService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.DeployFunction;
+import org.apache.geode.management.internal.cli.functions.ListDeployedFunction;
+import org.apache.geode.management.internal.cli.functions.UndeployFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
+import org.apache.geode.management.internal.cli.result.FileResult;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.NotAuthorizedException;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+
+
+/**
+ * Commands for deploying, un-deploying and listing files deployed using the command line shell.
+ *
+ * @see GfshCommand
+ * @since GemFire 7.0
+ */
+public class DeployCommands implements GfshCommand {
+
+ private final DeployFunction deployFunction = new DeployFunction();
+ private final UndeployFunction undeployFunction = new UndeployFunction();
+ private final ListDeployedFunction listDeployedFunction = new ListDeployedFunction();
+
+ /**
+ * Deploy one or more JAR files to members of a group or all members.
+ *
+ * @param groups Group(s) to deploy the JAR to or null for all members
+ * @param jars JAR file to deploy
+ * @param dir Directory of JAR files to deploy
+ * @return The result of the attempt to deploy
+ */
+ @CliCommand(value = {CliStrings.DEPLOY}, help = CliStrings.DEPLOY__HELP)
+ @CliMetaData(
+ interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommands$Interceptor",
+ relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
+ public Result deploy(
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+ @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+ help = CliStrings.DEPLOY__JAR__HELP) String[] jars,
+ @CliOption(key = {CliStrings.DEPLOY__DIR}, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
+ try {
+
+ // since deploy function can potentially do a lot of damage to security, this action should
+ // require these following privileges
+ SecurityService securityService = getSecurityService();
+
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+
+ byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
+ String[] jarNames = CliUtil.bytesToNames(shellBytesData);
+ byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
+
+ Set<DistributedMember> targetMembers;
+
+ targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.size() > 0) {
+ // this deploys the jars to all the matching servers
+ ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction,
+ new Object[] {jarNames, jarBytes}, targetMembers);
+
+ List<CliFunctionResult> results =
+ CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Deployed JAR", "");
+ tabularData.accumulate("Deployed JAR Location",
+ "ERROR: " + result.getThrowable().getClass().getName() + ": "
+ + result.getThrowable().getMessage());
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ String[] strings = (String[]) result.getSerializables();
+ for (int i = 0; i < strings.length; i += 2) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Deployed JAR", strings[i]);
+ tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
+ }
+ }
+ }
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
+ return result;
+ } catch (NotAuthorizedException e) {
+ // for NotAuthorizedException, will catch this later in the code
+ throw e;
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(String
+ .format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
+ }
+ }
+
+ /**
+ * Undeploy one or more JAR files from members of a group or all members.
+ *
+ * @param groups Group(s) to undeploy the JAR from or null for all members
+ * @param jars JAR(s) to undeploy (separated by comma)
+ * @return The result of the attempt to undeploy
+ */
+ @CliCommand(value = {CliStrings.UNDEPLOY}, help = CliStrings.UNDEPLOY__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
+ public Result undeploy(
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.UNDEPLOY__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+ @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+ help = CliStrings.UNDEPLOY__JAR__HELP) String[] jars) {
+
+ try {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(this.undeployFunction, new Object[] {jars}, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Un-Deployed JAR", "");
+ tabularData.accumulate("Un-Deployed JAR Location",
+ "ERROR: " + result.getThrowable().getClass().getName() + ": "
+ + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ String[] strings = (String[]) result.getSerializables();
+ for (int i = 0; i < strings.length; i += 2) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Un-Deployed JAR", strings[i]);
+ tabularData.accumulate("Un-Deployed From JAR Location", strings[i + 1]);
+ accumulatedData = true;
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult(CliStrings.UNDEPLOY__NO_JARS_FOUND_MESSAGE);
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+ if (tabularData.getStatus().equals(Status.OK)) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().removeJars(jars, groups));
+ }
+ return result;
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult("Exception while attempting to un-deploy: "
+ + th.getClass().getName() + ": " + th.getMessage());
+ }
+ }
+
+ /**
+ * List all currently deployed JARs for members of a group or for all members.
+ *
+ * @param group Group for which to list JARs or null for all members
+ * @return List of deployed JAR files
+ */
+ @CliCommand(value = {CliStrings.LIST_DEPLOYED}, help = CliStrings.LIST_DEPLOYED__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listDeployed(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.LIST_DEPLOYED__GROUP__HELP) String[] group) {
+
+ try {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(this.listDeployedFunction, null, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("JAR", "");
+ tabularData.accumulate("JAR Location",
+ "ERROR: " + result.getThrowable().getClass().getName() + ": "
+ + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ String[] strings = (String[]) result.getSerializables();
+ for (int i = 0; i < strings.length; i += 2) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("JAR", strings[i]);
+ tabularData.accumulate("JAR Location", strings[i + 1]);
+ accumulatedData = true;
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult(CliStrings.LIST_DEPLOYED__NO_JARS_FOUND_MESSAGE);
+ }
+ return ResultBuilder.buildResult(tabularData);
+
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult("Exception while attempting to list deployed: "
+ + th.getClass().getName() + ": " + th.getMessage());
+ }
+ }
+
+ /**
+ * Interceptor used by gfsh to intercept execution of deploy command at "shell".
+ */
+ public static class Interceptor extends AbstractCliAroundInterceptor {
+ private final DecimalFormat numFormatter = new DecimalFormat("###,##0.00");
+
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+ // 2nd argument is the jar
+ String[] jars = (String[]) parseResult.getArguments()[1];
+ // 3rd argument is the dir
+ String dir = (String) parseResult.getArguments()[2];
+
+ if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
+ return ResultBuilder.createUserErrorResult(
+ "Parameter \"jar\" or \"dir\" is required. Use \"help <command name>\" for assistance.");
+ }
+
+ if (ArrayUtils.isNotEmpty(jars) && StringUtils.isNotBlank(dir)) {
+ return ResultBuilder
+ .createUserErrorResult("Parameters \"jar\" and \"dir\" can not both be specified.");
+ }
+
+ FileResult fileResult;
+ String[] filesToUpload = jars;
+ if (filesToUpload == null) {
+ filesToUpload = new String[] {dir};
+ }
+ try {
+
+ fileResult = new FileResult(filesToUpload);
+ } catch (FileNotFoundException fnfex) {
+ return ResultBuilder.createGemFireErrorResult("'" + filesToUpload + "' not found.");
+ } catch (IOException ioex) {
+ return ResultBuilder.createGemFireErrorResult("I/O error when reading jar/dir: "
+ + ioex.getClass().getName() + ": " + ioex.getMessage());
+ }
+
+ // Only do this additional check if a dir was provided
+ if (dir != null) {
+ String message =
+ "\nDeploying files: " + fileResult.getFormattedFileList() + "\nTotal file size is: "
+ + this.numFormatter.format((double) fileResult.computeFileSizeTotal() / ONE_MB)
+ + "MB\n\nContinue? ";
+
+ if (readYesNo(message, Response.YES) == Response.NO) {
+ return ResultBuilder
+ .createShellClientAbortOperationResult("Aborted deploy of " + filesToUpload + ".");
+ }
+ }
+
+ return fileResult;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
deleted file mode 100644
index 824063a..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
+++ /dev/null
@@ -1,153 +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 java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.MemberConfigurationInfo;
-import org.apache.geode.management.internal.cli.functions.GetMemberConfigInformationFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DescribeConfigCommand implements GfshCommand {
- private final GetMemberConfigInformationFunction getMemberConfigFunction =
- new GetMemberConfigInformationFunction();
-
- @CliCommand(value = {CliStrings.DESCRIBE_CONFIG}, help = CliStrings.DESCRIBE_CONFIG__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result describeConfig(
- @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.DESCRIBE_CONFIG__MEMBER__HELP, mandatory = true) String memberNameOrId,
- @CliOption(key = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS,
- help = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS__HELP, unspecifiedDefaultValue = "true",
- specifiedDefaultValue = "true") boolean hideDefaults) {
-
- Result result = null;
- try {
- DistributedMember targetMember = null;
-
- if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
- targetMember = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
- }
- if (targetMember != null) {
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(getMemberConfigFunction, hideDefaults, targetMember);
- ArrayList<?> output = (ArrayList<?>) rc.getResult();
- Object obj = output.get(0);
-
- if (obj != null && obj instanceof MemberConfigurationInfo) {
- MemberConfigurationInfo memberConfigInfo = (MemberConfigurationInfo) obj;
-
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- crd.setHeader(
- CliStrings.format(CliStrings.DESCRIBE_CONFIG__HEADER__TEXT, memberNameOrId));
-
- List<String> jvmArgsList = memberConfigInfo.getJvmInputArguments();
- TabularResultData jvmInputArgs = crd.addSection().addSection().addTable();
-
- for (String jvmArg : jvmArgsList) {
- jvmInputArgs.accumulate("JVM command line arguments", jvmArg);
- }
-
- addSection(crd, memberConfigInfo.getGfePropsSetUsingApi(),
- "GemFire properties defined using the API");
- addSection(crd, memberConfigInfo.getGfePropsRuntime(),
- "GemFire properties defined at the runtime");
- addSection(crd, memberConfigInfo.getGfePropsSetFromFile(),
- "GemFire properties defined with the property file");
- addSection(crd, memberConfigInfo.getGfePropsSetWithDefaults(),
- "GemFire properties using default values");
- addSection(crd, memberConfigInfo.getCacheAttributes(), "Cache attributes");
-
- List<Map<String, String>> cacheServerAttributesList =
- memberConfigInfo.getCacheServerAttributes();
-
- if (cacheServerAttributesList != null && !cacheServerAttributesList.isEmpty()) {
- CompositeResultData.SectionResultData cacheServerSection = crd.addSection();
- cacheServerSection.setHeader("Cache-server attributes");
-
- for (Map<String, String> cacheServerAttributes : cacheServerAttributesList) {
- addSubSection(cacheServerSection, cacheServerAttributes);
- }
- }
- result = ResultBuilder.buildResult(crd);
- }
-
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(CliStrings.format(CliStrings.DESCRIBE_CONFIG__MEMBER__NOT__FOUND,
- new Object[] {memberNameOrId}));
- result = ResultBuilder.buildResult(erd);
- }
- } catch (FunctionInvocationTargetException e) {
- result = ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_CONFIG));
- } catch (Exception e) {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(e.getMessage());
- result = ResultBuilder.buildResult(erd);
- }
- return result;
- }
-
- private void addSection(CompositeResultData crd, Map<String, String> attrMap, String headerText) {
- if (attrMap != null && !attrMap.isEmpty()) {
- CompositeResultData.SectionResultData section = crd.addSection();
- section.setHeader(headerText);
- section.addSeparator('.');
- Set<String> attributes = new TreeSet<>(attrMap.keySet());
-
- for (String attribute : attributes) {
- String attributeValue = attrMap.get(attribute);
- section.addData(attribute, attributeValue);
- }
- }
- }
-
- private void addSubSection(CompositeResultData.SectionResultData section,
- Map<String, String> attrMap) {
- if (!attrMap.isEmpty()) {
- CompositeResultData.SectionResultData subSection = section.addSection();
- Set<String> attributes = new TreeSet<>(attrMap.keySet());
- subSection.setHeader("");
-
- for (String attribute : attributes) {
- String attributeValue = attrMap.get(attribute);
- subSection.addData(attribute, attributeValue);
- }
- }
- }
-}
[02/19] geode git commit: GEODE-3436: revert recent refactoring of
GFSH commands
Posted by kl...@apache.org.
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
deleted file mode 100644
index e178d8c..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DestroyRegionCommandDUnitTest.java
+++ /dev/null
@@ -1,388 +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.LogWriterUtils.getLogWriter;
-import static org.awaitility.Awaitility.waitAtMost;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.text.MessageFormat;
-import java.util.Properties;
-import java.util.concurrent.Callable;
-import java.util.concurrent.TimeUnit;
-
-import javax.management.MBeanServer;
-import javax.management.MalformedObjectNameException;
-import javax.management.ObjectName;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.Cache;
-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.Scope;
-import org.apache.geode.distributed.Locator;
-import org.apache.geode.distributed.internal.ClusterConfigurationService;
-import org.apache.geode.distributed.internal.InternalLocator;
-import org.apache.geode.internal.AvailablePort;
-import org.apache.geode.internal.AvailablePortHelper;
-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.VM;
-import org.apache.geode.test.junit.categories.DistributedTest;
-
-@Category(DistributedTest.class)
-public class DestroyRegionCommandDUnitTest extends CliCommandTestBase {
- @Test
- public void testDestroyDistributedRegion() {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- for (int i = 1; i <= 2; i++) {
- Host.getHost(0).getVM(i).invoke(() -> {
- final Cache cache = getCache();
-
- RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
- factory.create("Customer");
-
- PartitionAttributesFactory paFactory = new PartitionAttributesFactory();
- paFactory.setColocatedWith("Customer");
- factory.setPartitionAttributes(paFactory.create());
- factory.create("Order");
- });
- }
-
- waitForRegionMBeanCreation("/Customer", 2);
- waitForRegionMBeanCreation("/Order", 2);
-
- // Test failure when region not found
- String command = "destroy region --name=DOESNOTEXIST";
- getLogWriter().info("testDestroyRegion command=" + command);
- CommandResult cmdResult = executeCommand(command);
- String strr = commandResultToString(cmdResult);
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- // Test unable to destroy with co-location
- command = "destroy region --name=/Customer";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- // Test success
- command = "destroy region --name=/Order";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- assertTrue(stringContainsLine(strr, ".*Order.*destroyed successfully.*"));
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- command = "destroy region --name=/Customer";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
- }
-
- @Test
- public void testDestroyLocalRegions() {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- for (int i = 1; i <= 3; i++) {
- Host.getHost(0).getVM(i).invoke(() -> {
- final Cache cache = getCache();
-
- RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
- factory.setScope(Scope.LOCAL);
- factory.create("Customer");
- });
- }
-
- waitForRegionMBeanCreation("/Customer", 3);
-
- // Test failure when region not found
- String command = "destroy region --name=DOESNOTEXIST";
- getLogWriter().info("testDestroyRegion command=" + command);
- CommandResult cmdResult = executeCommand(command);
- String strr = commandResultToString(cmdResult);
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- command = "destroy region --name=/Customer";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- for (int i = 1; i <= 3; i++) {
- final int x = i;
- Host.getHost(0).getVM(i).invoke(() -> {
- assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
- });
- }
- }
-
- @Test
- public void testDestroyLocalAndDistributedRegions() {
- setUpJmxManagerOnVm0ThenConnect(null);
-
- for (int i = 1; i <= 2; i++) {
- Host.getHost(0).getVM(i).invoke(() -> {
- final Cache cache = getCache();
- RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.PARTITION);
- factory.create("Customer");
- factory.create("Customer-2");
- factory.create("Customer_3");
- });
- }
-
- Host.getHost(0).getVM(3).invoke(() -> {
- final Cache cache = getCache();
- RegionFactory<Object, Object> factory = cache.createRegionFactory(RegionShortcut.REPLICATE);
- factory.setScope(Scope.LOCAL);
- factory.create("Customer");
- factory.create("Customer-2");
- factory.create("Customer_3");
- });
-
- waitForRegionMBeanCreation("/Customer", 3);
-
- // Test failure when region not found
- String command = "destroy region --name=DOESNOTEXIST";
- getLogWriter().info("testDestroyRegion command=" + command);
- CommandResult cmdResult = executeCommand(command);
- String strr = commandResultToString(cmdResult);
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertTrue(stringContainsLine(strr, "Could not find.*\"DOESNOTEXIST\".*"));
- assertEquals(Result.Status.ERROR, cmdResult.getStatus());
-
- command = "destroy region --name=/Customer";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- assertTrue(stringContainsLine(strr, ".*Customer.*destroyed successfully.*"));
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- command = "destroy region --name=/Customer_3";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- assertTrue(stringContainsLine(strr, ".*Customer_3.*destroyed successfully.*"));
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- command = "destroy region --name=/Customer-2";
- getLogWriter().info("testDestroyRegion command=" + command);
- cmdResult = executeCommand(command);
- strr = commandResultToString(cmdResult);
- assertTrue(stringContainsLine(strr, ".*Customer-2.*destroyed successfully.*"));
- getLogWriter().info("testDestroyRegion strr=" + strr);
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- for (int i = 1; i <= 3; i++) {
- final int x = i;
- Host.getHost(0).getVM(i).invoke(() -> {
- assertNull("Region still exists in VM " + x, getCache().getRegion("Customer"));
- assertNull("Region still exists in VM " + x, getCache().getRegion("Customer-2"));
- assertNull("Region still exists in VM " + x, getCache().getRegion("Customer_3"));
- });
- }
- }
-
- @Test
- public void testDestroyRegionWithSharedConfig() {
- 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);
- } 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, 1);
-
- // Make sure the region exists in the shared config
- Host.getHost(0).getVM(0).invoke(() -> {
- ClusterConfigurationService sharedConfig =
- ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
- try {
- assertTrue(
- sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
- } catch (Exception e) {
- fail("Error occurred in cluster configuration service");
- }
- });
-
- // Test destroying the region
- commandStringBuilder = new CommandStringBuilder(CliStrings.DESTROY_REGION);
- commandStringBuilder.addOption(CliStrings.DESTROY_REGION__REGION, regionName);
- cmdResult = executeCommand(commandStringBuilder.toString());
- getLogWriter().info("#SB" + commandResultToString(cmdResult));
- assertEquals(Result.Status.OK, cmdResult.getStatus());
-
- // Make sure the region was removed from the shared config
- Host.getHost(0).getVM(0).invoke(() -> {
- ClusterConfigurationService sharedConfig =
- ((InternalLocator) Locator.getLocator()).getSharedConfiguration();
- try {
- assertFalse(
- sharedConfig.getConfiguration(groupName).getCacheXmlContent().contains(regionName));
- } catch (Exception e) {
- fail("Error occurred in cluster configuration service");
- }
- });
-
-
- // Restart the data vm to make sure the region is not existing any more
- 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);
- assertNull(region);
-
- return null;
- });
- }
-
- private void waitForRegionMBeanCreation(final String regionPath, final int mbeanCount) {
- Host.getHost(0).getVM(0).invoke(() -> {
- waitAtMost(5, TimeUnit.SECONDS).until(newRegionMBeanIsCreated(regionPath, mbeanCount));
- });
- }
-
- private Callable<Boolean> newRegionMBeanIsCreated(final String regionPath, final int mbeanCount) {
- 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() == mbeanCount;
- } catch (MalformedObjectNameException mone) {
- getLogWriter().error(mone);
- fail(mone.getMessage());
- return false;
- }
- };
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
index 1002f5d..07cdb11 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsDUnitTest.java
@@ -36,23 +36,7 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.io.IOException;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.StringTokenizer;
-import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.TimeUnit;
-
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.CacheFactory;
import org.apache.geode.cache.DataPolicy;
@@ -92,26 +76,28 @@ import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.WaitCriterion;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
/**
* The DiskStoreCommandsDUnitTest class is a distributed test suite of test cases for testing the
* disk store commands that are part of Gfsh.
* </p>
*
- * @see org.apache.geode.management.internal.cli.commands.AlterOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.BackupDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.CompactDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.CompactOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.DestroyDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.ExportOfflineDiskStoreCommand
- * @see ListDiskStoresCommand
- * @see org.apache.geode.management.internal.cli.commands.RevokeMissingDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.ShowMissingDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.UpgradeOfflineDiskStoreCommand
- * @see org.apache.geode.management.internal.cli.commands.ValidateDiskStoreCommand
+ * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
* @see org.junit.Assert
* @see org.junit.Test
* @since GemFire 7.0
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
index f8cd657..1902656 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/DiskStoreCommandsJUnitTest.java
@@ -14,10 +14,7 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
@@ -52,11 +49,10 @@ import org.apache.geode.test.junit.categories.UnitTest;
/**
* The DiskStoreCommandsJUnitTest class is a test suite of test cases testing the contract and
- * functionality of the command classes relating to disk stores that implement commands in the
- * GemFire shell (gfsh) that access and modify disk stores in GemFire.
+ * functionality of the DiskStoreCommands class implementing commands in the GemFire shell (gfsh)
+ * that access and modify disk stores in GemFire.
*
- * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
- * @see ListDiskStoresCommand
+ * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
* @see org.apache.geode.management.internal.cli.domain.DiskStoreDetails
* @see org.apache.geode.management.internal.cli.functions.DescribeDiskStoreFunction
* @see org.apache.geode.management.internal.cli.functions.ListDiskStoresFunction
@@ -65,7 +61,6 @@ import org.apache.geode.test.junit.categories.UnitTest;
* @see org.jmock.lib.legacy.ClassImposteriser
* @see org.junit.Assert
* @see org.junit.Test
- *
* @since GemFire 7.0
*/
@Category(UnitTest.class)
@@ -89,14 +84,9 @@ public class DiskStoreCommandsJUnitTest {
mockContext = null;
}
- private DescribeDiskStoreCommand createDescribeDiskStoreCommand(final InternalCache cache,
- final DistributedMember distributedMember, final Execution functionExecutor) {
- return new TestDescribeDiskStoreCommand(cache, distributedMember, functionExecutor);
- }
-
- private ListDiskStoresCommand createListDiskStoreCommand(final InternalCache cache,
+ private DiskStoreCommands createDiskStoreCommands(final InternalCache cache,
final DistributedMember distributedMember, final Execution functionExecutor) {
- return new TestListDiskStoresCommand(cache, distributedMember, functionExecutor);
+ return new TestDiskStoreCommands(cache, distributedMember, functionExecutor);
}
private DiskStoreDetails createDiskStoreDetails(final String memberId,
@@ -133,15 +123,15 @@ public class DiskStoreCommandsJUnitTest {
oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
will(returnValue(mockResultCollector));
oneOf(mockResultCollector).getResult();
- will(returnValue(Collections.singletonList(expectedDiskStoredDetails)));
+ will(returnValue(Arrays.asList(expectedDiskStoredDetails)));
}
});
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
final DiskStoreDetails actualDiskStoreDetails =
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
+ commands.getDiskStoreDescription(memberId, diskStoreName);
assertNotNull(actualDiskStoreDetails);
assertEquals(expectedDiskStoredDetails, actualDiskStoreDetails);
@@ -166,11 +156,10 @@ public class DiskStoreCommandsJUnitTest {
}
});
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, null);
+ final DiskStoreCommands commands = createDiskStoreCommands(mockCache, mockMember, null);
try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
+ commands.getDiskStoreDescription(memberId, diskStoreName);
} catch (MemberNotFoundException expected) {
assertEquals(CliStrings.format(CliStrings.MEMBER_NOT_FOUND_ERROR_MESSAGE, memberId),
expected.getMessage());
@@ -203,11 +192,11 @@ public class DiskStoreCommandsJUnitTest {
}
});
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
+ commands.getDiskStoreDescription(memberId, diskStoreName);
} catch (DiskStoreNotFoundException expected) {
assertEquals("expected", expected.getMessage());
throw expected;
@@ -239,11 +228,11 @@ public class DiskStoreCommandsJUnitTest {
}
});
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
+ commands.getDiskStoreDescription(memberId, diskStoreName);
} catch (RuntimeException expected) {
assertEquals("expected", expected.getMessage());
throw expected;
@@ -276,15 +265,15 @@ public class DiskStoreCommandsJUnitTest {
oneOf(mockFunctionExecutor).execute(with(aNonNull(DescribeDiskStoreFunction.class)));
will(returnValue(mockResultCollector));
oneOf(mockResultCollector).getResult();
- will(returnValue(Collections.singletonList(new Object())));
+ will(returnValue(Arrays.asList(new Object())));
}
});
- final DescribeDiskStoreCommand describeCommand =
- createDescribeDiskStoreCommand(mockCache, mockMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockMember, mockFunctionExecutor);
try {
- describeCommand.getDiskStoreDescription(memberId, diskStoreName);
+ commands.getDiskStoreDescription(memberId, diskStoreName);
} catch (RuntimeException expected) {
assertEquals(
CliStrings.format(CliStrings.UNEXPECTED_RETURN_TYPE_EXECUTING_COMMAND_ERROR_MESSAGE,
@@ -319,7 +308,7 @@ public class DiskStoreCommandsJUnitTest {
final List<DiskStoreDetails> expectedDiskStores =
Arrays.asList(diskStoreDetails1, diskStoreDetails2, diskStoreDetails3, diskStoreDetails4);
- final List<Set<DiskStoreDetails>> results = new ArrayList<>();
+ final List<Set<DiskStoreDetails>> results = new ArrayList<Set<DiskStoreDetails>>();
results.add(CollectionUtils.asSet(diskStoreDetails4, diskStoreDetails3));
results.add(CollectionUtils.asSet(diskStoreDetails1, diskStoreDetails2));
@@ -334,11 +323,11 @@ public class DiskStoreCommandsJUnitTest {
}
});
- final ListDiskStoresCommand listCommand =
- createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockDistributedMember, mockFunctionExecutor);
final List<DiskStoreDetails> actualDiskStores =
- listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
+ commands.getDiskStoreListing(commands.getNormalMembers(mockCache));
Assert.assertNotNull(actualDiskStores);
assertEquals(expectedDiskStores, actualDiskStores);
@@ -360,11 +349,11 @@ public class DiskStoreCommandsJUnitTest {
}
});
- final ListDiskStoresCommand listCommand =
- createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockDistributedMember, mockFunctionExecutor);
try {
- listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
+ commands.getDiskStoreListing(commands.getNormalMembers(mockCache));
} catch (RuntimeException expected) {
assertEquals("expected", expected.getMessage());
throw expected;
@@ -387,9 +376,9 @@ public class DiskStoreCommandsJUnitTest {
final DiskStoreDetails diskStoreDetails =
createDiskStoreDetails("memberOne", "cacheServerDiskStore");
- final List<DiskStoreDetails> expectedDiskStores = Collections.singletonList(diskStoreDetails);
+ final List<DiskStoreDetails> expectedDiskStores = Arrays.asList(diskStoreDetails);
- final List<Object> results = new ArrayList<>();
+ final List<Object> results = new ArrayList<Object>();
results.add(CollectionUtils.asSet(diskStoreDetails));
results.add(new FunctionInvocationTargetException("expected"));
@@ -404,23 +393,23 @@ public class DiskStoreCommandsJUnitTest {
}
});
- final ListDiskStoresCommand listCommand =
- createListDiskStoreCommand(mockCache, mockDistributedMember, mockFunctionExecutor);
+ final DiskStoreCommands commands =
+ createDiskStoreCommands(mockCache, mockDistributedMember, mockFunctionExecutor);
final List<DiskStoreDetails> actualDiskStores =
- listCommand.getDiskStoreListing(Collections.singleton(mockDistributedMember));
+ commands.getDiskStoreListing(commands.getNormalMembers(mockCache));
Assert.assertNotNull(actualDiskStores);
assertEquals(expectedDiskStores, actualDiskStores);
}
- private static class TestDescribeDiskStoreCommand extends DescribeDiskStoreCommand {
+ private static class TestDiskStoreCommands extends DiskStoreCommands {
private final InternalCache cache;
private final DistributedMember distributedMember;
private final Execution functionExecutor;
- TestDescribeDiskStoreCommand(final InternalCache cache,
+ public TestDiskStoreCommands(final InternalCache cache,
final DistributedMember distributedMember, final Execution functionExecutor) {
assert cache != null : "The Cache cannot be null!";
this.cache = cache;
@@ -444,37 +433,12 @@ public class DiskStoreCommandsJUnitTest {
Assert.assertNotNull(members);
return this.functionExecutor;
}
- }
-
- private static class TestListDiskStoresCommand extends ListDiskStoresCommand {
-
- private final InternalCache cache;
- private final DistributedMember distributedMember;
- private final Execution functionExecutor;
-
- TestListDiskStoresCommand(final InternalCache cache, final DistributedMember distributedMember,
- final Execution functionExecutor) {
- assert cache != null : "The Cache cannot be null!";
- this.cache = cache;
- this.distributedMember = distributedMember;
- this.functionExecutor = functionExecutor;
- }
@Override
- public InternalCache getCache() {
- return this.cache;
- }
-
- @Override
- public Set<DistributedMember> getMembers(final InternalCache cache) {
+ protected Set<DistributedMember> getNormalMembers(final InternalCache cache) {
assertSame(getCache(), cache);
return Collections.singleton(this.distributedMember);
}
-
- @Override
- public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
- Assert.assertNotNull(members);
- return this.functionExecutor;
- }
}
+
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
index e3b6ad4..da60c7a 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/GfshCommandJUnitTest.java
@@ -14,6 +14,14 @@
*/
package org.apache.geode.management.internal.cli.commands;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_BIND_ADDRESS;
+import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT;
+import static org.apache.geode.distributed.ConfigurationProperties.LOCATORS;
+import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
+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.START_DEV_REST_API;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -27,6 +35,7 @@ import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.Properties;
import java.util.Set;
import org.jmock.Expectations;
@@ -42,6 +51,7 @@ import org.apache.geode.cache.execute.Function;
import org.apache.geode.cache.execute.FunctionService;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.DistributedSystem;
+import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.lang.StringUtils;
import org.apache.geode.internal.util.CollectionUtils;
@@ -399,15 +409,216 @@ public class GfshCommandJUnitTest {
@Test
public void testAddGemFirePropertyFileToCommandLine() {
- StartMemberCommand startMemberCommand = new StartMemberCommand();
-
final List<String> commandLine = new ArrayList<>();
assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFirePropertyFile(commandLine, null);
+ StartMemberUtils.addGemFirePropertyFile(commandLine, null);
assertTrue(commandLine.isEmpty());
- startMemberCommand.addGemFirePropertyFile(commandLine, new File("/path/to/gemfire.properties"));
+ StartMemberUtils.addGemFirePropertyFile(commandLine, new File("/path/to/gemfire.properties"));
assertFalse(commandLine.isEmpty());
assertTrue(commandLine.contains("-DgemfirePropertyFile=/path/to/gemfire.properties"));
}
+ @Test
+ public void testAddGemFireSystemPropertiesToCommandLine() {
+ final List<String> commandLine = new ArrayList<>();
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addGemFireSystemProperties(commandLine, new Properties());
+ assertTrue(commandLine.isEmpty());
+
+ final Properties gemfireProperties = new Properties();
+ gemfireProperties.setProperty(LOCATORS, "localhost[11235]");
+ gemfireProperties.setProperty(LOG_LEVEL, "config");
+ gemfireProperties.setProperty(LOG_FILE, org.apache.commons.lang.StringUtils.EMPTY);
+ gemfireProperties.setProperty(MCAST_PORT, "0");
+ gemfireProperties.setProperty(NAME, "machine");
+ StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
+
+ assertFalse(commandLine.isEmpty());
+ assertEquals(4, commandLine.size());
+
+ for (final String propertyName : gemfireProperties.stringPropertyNames()) {
+ final String propertyValue = gemfireProperties.getProperty(propertyName);
+ if (org.apache.commons.lang.StringUtils.isBlank(propertyValue)) {
+ for (final String systemProperty : commandLine) {
+ assertFalse(systemProperty.startsWith(
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=")));
+ }
+ } else {
+ assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX
+ + "".concat(propertyName).concat("=").concat(propertyValue)));
+ }
+ }
+ }
+
+ @Test
+ public void testAddGemFireSystemPropertiesToCommandLineWithRestAPI() {
+ final List<String> commandLine = new ArrayList<>();
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addGemFireSystemProperties(commandLine, new Properties());
+ assertTrue(commandLine.isEmpty());
+ final Properties gemfireProperties = new Properties();
+ gemfireProperties.setProperty(LOCATORS, "localhost[11235]");
+ gemfireProperties.setProperty(LOG_LEVEL, "config");
+ gemfireProperties.setProperty(LOG_FILE, StringUtils.EMPTY);
+ gemfireProperties.setProperty(MCAST_PORT, "0");
+ gemfireProperties.setProperty(NAME, "machine");
+ gemfireProperties.setProperty(START_DEV_REST_API, "true");
+ gemfireProperties.setProperty(HTTP_SERVICE_PORT, "8080");
+ gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, "localhost");
+
+ StartMemberUtils.addGemFireSystemProperties(commandLine, gemfireProperties);
+
+ assertFalse(commandLine.isEmpty());
+ assertEquals(7, commandLine.size());
+
+ for (final String propertyName : gemfireProperties.stringPropertyNames()) {
+ final String propertyValue = gemfireProperties.getProperty(propertyName);
+ if (StringUtils.isBlank(propertyValue)) {
+ for (final String systemProperty : commandLine) {
+ assertFalse(systemProperty.startsWith(
+ "-D" + DistributionConfig.GEMFIRE_PREFIX + "".concat(propertyName).concat("=")));
+ }
+ } else {
+ assertTrue(commandLine.contains("-D" + DistributionConfig.GEMFIRE_PREFIX
+ + "".concat(propertyName).concat("=").concat(propertyValue)));
+ }
+ }
+ }
+
+ @Test
+ public void testAddInitialHeapToCommandLine() {
+ final List<String> commandLine = new ArrayList<>();
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addInitialHeap(commandLine, null);
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addInitialHeap(commandLine, org.apache.commons.lang.StringUtils.EMPTY);
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addInitialHeap(commandLine, " ");
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addInitialHeap(commandLine, "512M");
+ assertFalse(commandLine.isEmpty());
+ assertEquals("-Xms512M", commandLine.get(0));
+ }
+
+ @Test
+ public void testAddJvmArgumentsAndOptionsToCommandLine() {
+ final List<String> commandLine = new ArrayList<>();
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addJvmArgumentsAndOptions(commandLine, null);
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addJvmArgumentsAndOptions(commandLine, new String[] {});
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addJvmArgumentsAndOptions(commandLine,
+ new String[] {"-DmyProp=myVal", "-d64", "-server", "-Xprof"});
+ assertFalse(commandLine.isEmpty());
+ assertEquals(4, commandLine.size());
+ assertEquals("-DmyProp=myVal", commandLine.get(0));
+ assertEquals("-d64", commandLine.get(1));
+ assertEquals("-server", commandLine.get(2));
+ assertEquals("-Xprof", commandLine.get(3));
+ }
+
+ @Test
+ public void testAddMaxHeapToCommandLine() {
+ final List<String> commandLine = new ArrayList<>();
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addMaxHeap(commandLine, null);
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addMaxHeap(commandLine, org.apache.commons.lang.StringUtils.EMPTY);
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addMaxHeap(commandLine, " ");
+ assertTrue(commandLine.isEmpty());
+ StartMemberUtils.addMaxHeap(commandLine, "1024M");
+ assertFalse(commandLine.isEmpty());
+ assertEquals(3, commandLine.size());
+ assertEquals("-Xmx1024M", commandLine.get(0));
+ assertEquals("-XX:+UseConcMarkSweepGC", commandLine.get(1));
+ assertEquals(
+ "-XX:CMSInitiatingOccupancyFraction=" + StartMemberUtils.CMS_INITIAL_OCCUPANCY_FRACTION,
+ commandLine.get(2));
+ }
+
+ @Test(expected = AssertionError.class)
+ public void testReadPidWithNull() {
+ try {
+ StartMemberUtils.readPid(null);
+ } catch (AssertionError expected) {
+ assertEquals("The file from which to read the process ID (pid) cannot be null!",
+ expected.getMessage());
+ throw expected;
+ }
+ }
+
+ @Test
+ public void testReadPidWithNonExistingFile() {
+ assertEquals(StartMemberUtils.INVALID_PID,
+ StartMemberUtils.readPid(new File("/path/to/non_existing/pid.file")));
+ }
+
+ @Test
+ public void testGetSystemClasspath() {
+ assertEquals(System.getProperty("java.class.path"), StartMemberUtils.getSystemClasspath());
+ }
+
+ @Test
+ public void testToClasspath() {
+ final boolean EXCLUDE_SYSTEM_CLASSPATH = false;
+ final boolean INCLUDE_SYSTEM_CLASSPATH = true;
+ String[] jarFilePathnames =
+ {"/path/to/user/libs/A.jar", "/path/to/user/libs/B.jar", "/path/to/user/libs/C.jar"};
+ String[] userClasspaths = {"/path/to/classes:/path/to/libs/1.jar:/path/to/libs/2.jar",
+ "/path/to/ext/libs/1.jar:/path/to/ext/classes:/path/to/ext/lib/10.jar"};
+ String expectedClasspath = StartMemberUtils.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
+ .concat(toClasspath(userClasspaths)).concat(File.pathSeparator)
+ .concat(toClasspath(jarFilePathnames));
+ assertEquals(expectedClasspath,
+ StartMemberUtils.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, jarFilePathnames, userClasspaths));
+ expectedClasspath = StartMemberUtils.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
+ .concat(toClasspath(userClasspaths)).concat(File.pathSeparator)
+ .concat(System.getProperty("java.class.path")).concat(File.pathSeparator)
+ .concat(toClasspath(jarFilePathnames));
+ assertEquals(expectedClasspath,
+ StartMemberUtils.toClasspath(INCLUDE_SYSTEM_CLASSPATH, jarFilePathnames, userClasspaths));
+ expectedClasspath = StartMemberUtils.GEODE_JAR_PATHNAME.concat(File.pathSeparator)
+ .concat(System.getProperty("java.class.path"));
+ assertEquals(expectedClasspath,
+ StartMemberUtils.toClasspath(INCLUDE_SYSTEM_CLASSPATH, null, (String[]) null));
+ assertEquals(StartMemberUtils.GEODE_JAR_PATHNAME,
+ StartMemberUtils.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, null, (String[]) null));
+ assertEquals(StartMemberUtils.GEODE_JAR_PATHNAME,
+ StartMemberUtils.toClasspath(EXCLUDE_SYSTEM_CLASSPATH, new String[0], ""));
+ }
+
+ @Test
+ public void testToClassPathOrder() {
+ String userClasspathOne = "/path/to/user/lib/a.jar:/path/to/user/classes";
+ String userClasspathTwo =
+ "/path/to/user/lib/x.jar:/path/to/user/lib/y.jar:/path/to/user/lib/z.jar";
+
+ String expectedClasspath = StartMemberUtils.getGemFireJarPath().concat(File.pathSeparator)
+ .concat(userClasspathOne).concat(File.pathSeparator).concat(userClasspathTwo)
+ .concat(File.pathSeparator).concat(System.getProperty("java.class.path"))
+ .concat(File.pathSeparator).concat(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME)
+ .concat(File.pathSeparator).concat(StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME);
+
+ String actualClasspath =
+ StartMemberUtils.toClasspath(true,
+ new String[] {StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME,
+ StartMemberUtils.CORE_DEPENDENCIES_JAR_PATHNAME},
+ userClasspathOne, userClasspathTwo);
+
+ assertEquals(expectedClasspath, actualClasspath);
+ }
+
+ private String toClasspath(final String... jarFilePathnames) {
+ String classpath = org.apache.commons.lang.StringUtils.EMPTY;
+ if (jarFilePathnames != null) {
+ for (final String jarFilePathname : jarFilePathnames) {
+ classpath +=
+ (classpath.isEmpty() ? org.apache.commons.lang.StringUtils.EMPTY : File.pathSeparator);
+ classpath += jarFilePathname;
+ }
+ }
+ return classpath;
+ }
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java
new file mode 100644
index 0000000..0d1f340
--- /dev/null
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/IndexCommandsJUnitTest.java
@@ -0,0 +1,223 @@
+/*
+ * 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.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import org.jmock.Expectations;
+import org.jmock.Mockery;
+import org.jmock.lib.concurrent.Synchroniser;
+import org.jmock.lib.legacy.ClassImposteriser;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import org.apache.geode.cache.execute.Execution;
+import org.apache.geode.cache.execute.FunctionInvocationTargetException;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.cache.InternalCache;
+import org.apache.geode.internal.cache.execute.AbstractExecution;
+import org.apache.geode.internal.util.CollectionUtils;
+import org.apache.geode.management.internal.cli.domain.IndexDetails;
+import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
+import org.apache.geode.test.junit.categories.UnitTest;
+
+/**
+ * The IndexCommandsJUnitTest class is a test suite of test cases testing the contract and
+ * functionality of the IndexCommands class.
+ * </p>
+ *
+ * @see org.apache.geode.management.internal.cli.commands.IndexCommands
+ * @see org.apache.geode.management.internal.cli.domain.IndexDetails
+ * @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
+ * @see org.jmock.Expectations
+ * @see org.jmock.Mockery
+ * @see org.jmock.lib.legacy.ClassImposteriser
+ * @see org.junit.Assert
+ * @see org.junit.Test
+ * @since GemFire 7.0
+ */
+@Category(UnitTest.class)
+public class IndexCommandsJUnitTest {
+
+ private Mockery mockContext;
+
+ @Before
+ public void setup() {
+ mockContext = new Mockery() {
+ {
+ setImposteriser(ClassImposteriser.INSTANCE);
+ setThreadingPolicy(new Synchroniser());
+ }
+ };
+ }
+
+ @After
+ public void tearDown() {
+ mockContext.assertIsSatisfied();
+ mockContext = null;
+ }
+
+ private IndexCommands createIndexCommands(final InternalCache cache,
+ final Execution functionExecutor) {
+ return new TestIndexCommands(cache, functionExecutor);
+ }
+
+ private IndexDetails createIndexDetails(final String memberId, final String regionPath,
+ final String indexName) {
+ return new IndexDetails(memberId, regionPath, indexName);
+ }
+
+ @Test
+ public void testGetIndexListing() {
+ final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
+
+ final AbstractExecution mockFunctionExecutor =
+ mockContext.mock(AbstractExecution.class, "Function Executor");
+
+ final ResultCollector mockResultCollector =
+ mockContext.mock(ResultCollector.class, "ResultCollector");
+
+ final IndexDetails indexDetails1 = createIndexDetails("memberOne", "/Employees", "empIdIdx");
+ final IndexDetails indexDetails2 =
+ createIndexDetails("memberOne", "/Employees", "empLastNameIdx");
+ final IndexDetails indexDetails3 = createIndexDetails("memberTwo", "/Employees", "empDobIdx");
+
+ final List<IndexDetails> expectedIndexDetails =
+ Arrays.asList(indexDetails1, indexDetails2, indexDetails3);
+
+ final List<Set<IndexDetails>> results = new ArrayList<Set<IndexDetails>>(2);
+
+ results.add(CollectionUtils.asSet(indexDetails2, indexDetails1));
+ results.add(CollectionUtils.asSet(indexDetails3));
+
+ mockContext.checking(new Expectations() {
+ {
+ oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
+ oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
+ will(returnValue(mockResultCollector));
+ oneOf(mockResultCollector).getResult();
+ will(returnValue(results));
+ }
+ });
+
+ final IndexCommands commands = createIndexCommands(mockCache, mockFunctionExecutor);
+
+ final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
+
+ assertNotNull(actualIndexDetails);
+ assertEquals(expectedIndexDetails, actualIndexDetails);
+ }
+
+ @Test(expected = RuntimeException.class)
+ public void testGetIndexListingThrowsRuntimeException() {
+ final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
+
+ final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
+
+ mockContext.checking(new Expectations() {
+ {
+ oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
+ will(throwException(new RuntimeException("expected")));
+ }
+ });
+
+ final IndexCommands commands = createIndexCommands(mockCache, mockFunctionExecutor);
+
+ try {
+ commands.getIndexListing();
+ } catch (RuntimeException expected) {
+ assertEquals("expected", expected.getMessage());
+ throw expected;
+ }
+ }
+
+ @Test
+ public void testGetIndexListingReturnsFunctionInvocationTargetExceptionInResults() {
+ final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
+
+ final AbstractExecution mockFunctionExecutor =
+ mockContext.mock(AbstractExecution.class, "Function Executor");
+
+ final ResultCollector mockResultCollector =
+ mockContext.mock(ResultCollector.class, "ResultCollector");
+
+ final IndexDetails indexDetails = createIndexDetails("memberOne", "/Employees", "empIdIdx");
+
+ final List<IndexDetails> expectedIndexDetails = Arrays.asList(indexDetails);
+
+ final List<Object> results = new ArrayList<Object>(2);
+
+ results.add(CollectionUtils.asSet(indexDetails));
+ results.add(new FunctionInvocationTargetException("expected"));
+
+ mockContext.checking(new Expectations() {
+ {
+ oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
+ oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
+ will(returnValue(mockResultCollector));
+ oneOf(mockResultCollector).getResult();
+ will(returnValue(results));
+ }
+ });
+
+ final IndexCommands commands = createIndexCommands(mockCache, mockFunctionExecutor);
+
+ final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
+
+ assertNotNull(actualIndexDetails);
+ assertEquals(expectedIndexDetails, actualIndexDetails);
+ }
+
+ private static class TestIndexCommands extends IndexCommands {
+
+ private final InternalCache cache;
+ private final Execution functionExecutor;
+
+ protected TestIndexCommands(final InternalCache cache, final Execution functionExecutor) {
+ assert cache != null : "The InternalCache cannot be null!";
+ assert functionExecutor != null : "The function executor cannot be null!";
+ this.cache = cache;
+ this.functionExecutor = functionExecutor;
+ }
+
+ @Override
+ public InternalCache getCache() {
+ return this.cache;
+ }
+
+ @Override
+ public Set<DistributedMember> getMembers(final InternalCache cache) {
+ assertSame(getCache(), cache);
+ return Collections.emptySet();
+ }
+
+ @Override
+ public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
+ Assert.assertNotNull(members);
+ return functionExecutor;
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
index 1fe0bd1..8d4be8b 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListAndDescribeDiskStoreCommandsDUnitTest.java
@@ -14,25 +14,7 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.apache.geode.distributed.ConfigurationProperties.NAME;
-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.Host.getHost;
-import static org.apache.geode.test.dunit.LogWriterUtils.getDUnitLogLevel;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-
-import java.io.Serializable;
-import java.util.Properties;
-
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.DiskStore;
-import org.apache.geode.cache.DiskStoreFactory;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.Scope;
+import org.apache.geode.cache.*;
import org.apache.geode.distributed.ConfigurationProperties;
import org.apache.geode.management.cli.Result;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
@@ -40,6 +22,18 @@ import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.SerializableRunnableIF;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.Serializable;
+import java.util.Properties;
+
+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.Host.getHost;
+import static org.apache.geode.test.dunit.LogWriterUtils.getDUnitLogLevel;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
/**
* The ListAndDescribeDiskStoreCommandsDUnitTest class is a test suite of functional tests cases
@@ -47,9 +41,7 @@ import org.apache.geode.test.junit.categories.DistributedTest;
* </p>
*
* @see org.apache.geode.management.internal.cli.commands.CliCommandTestBase
- * @see ListDiskStoresCommand
- * @see org.apache.geode.management.internal.cli.commands.DescribeDiskStoreCommand
- *
+ * @see org.apache.geode.management.internal.cli.commands.DiskStoreCommands
* @since GemFire 7.0
*/
@Category(DistributedTest.class)
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
index 6dc23ce..5ff0a67 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandDUnitTest.java
@@ -23,22 +23,7 @@ import static org.apache.geode.test.dunit.Assert.assertTrue;
import static org.apache.geode.test.dunit.LogWriterUtils.getDUnitLogLevel;
import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Properties;
-import java.util.Random;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicLong;
-
import org.apache.commons.lang.StringUtils;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DataPolicy;
import org.apache.geode.cache.Region;
@@ -58,18 +43,27 @@ import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.SerializableRunnableIF;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.junit.categories.DistributedTest;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Properties;
+import java.util.Random;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicLong;
/**
* The ListIndexCommandDUnitTest class is distributed test suite of test cases for testing the
* index-based GemFire shell (Gfsh) commands.
*
* @see org.apache.geode.management.internal.cli.commands.CliCommandTestBase
- * @see org.apache.geode.management.internal.cli.commands.ClearDefinedIndexesCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateDefinedIndexesCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.DefineIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.DestroyIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
+ * @see org.apache.geode.management.internal.cli.commands.IndexCommands
* @since GemFire 7.0
*/
@SuppressWarnings("unused")
@@ -696,7 +690,7 @@ public class ListIndexCommandDUnitTest extends CliCommandTestBase {
}
}
- private enum CrudOperation {
+ private static enum CrudOperation {
CREATE, RETRIEVE, UPDATE, DELETE
}
}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
deleted file mode 100644
index 8deb4ae..0000000
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ListIndexCommandJUnitTest.java
+++ /dev/null
@@ -1,223 +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.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import org.jmock.Expectations;
-import org.jmock.Mockery;
-import org.jmock.lib.concurrent.Synchroniser;
-import org.jmock.lib.legacy.ClassImposteriser;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.execute.Execution;
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.cache.execute.AbstractExecution;
-import org.apache.geode.internal.util.CollectionUtils;
-import org.apache.geode.management.internal.cli.domain.IndexDetails;
-import org.apache.geode.management.internal.cli.functions.ListIndexFunction;
-import org.apache.geode.test.junit.categories.UnitTest;
-
-/**
- * The ListIndexCommandJUnitTest class is a test suite of test cases testing the contract and
- * functionality of the ListIndexCommand class.
- * </p>
- *
- * @see org.apache.geode.management.internal.cli.commands.ClearDefinedIndexesCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateDefinedIndexesCommand
- * @see org.apache.geode.management.internal.cli.commands.CreateIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.DefineIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.DestroyIndexCommand
- * @see org.apache.geode.management.internal.cli.commands.ListIndexCommand
- * @see org.apache.geode.management.internal.cli.domain.IndexDetails
- * @see org.apache.geode.management.internal.cli.functions.ListIndexFunction
- * @see org.jmock.Expectations
- * @see org.jmock.Mockery
- * @see org.jmock.lib.legacy.ClassImposteriser
- * @see org.junit.Assert
- * @see org.junit.Test
- * @since GemFire 7.0
- */
-@Category(UnitTest.class)
-public class ListIndexCommandJUnitTest {
- private Mockery mockContext;
-
- @Before
- public void setup() {
- mockContext = new Mockery() {
- {
- setImposteriser(ClassImposteriser.INSTANCE);
- setThreadingPolicy(new Synchroniser());
- }
- };
- }
-
- @After
- public void tearDown() {
- mockContext.assertIsSatisfied();
- mockContext = null;
- }
-
- private ListIndexCommand createListIndexCommand(final InternalCache cache,
- final Execution functionExecutor) {
- return new TestListIndexCommands(cache, functionExecutor);
- }
-
- private IndexDetails createIndexDetails(final String memberId, final String indexName) {
- return new IndexDetails(memberId, "/Employees", indexName);
- }
-
- @Test
- public void testGetIndexListing() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final AbstractExecution mockFunctionExecutor =
- mockContext.mock(AbstractExecution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
- final IndexDetails indexDetails1 = createIndexDetails("memberOne", "empIdIdx");
- final IndexDetails indexDetails2 = createIndexDetails("memberOne", "empLastNameIdx");
- final IndexDetails indexDetails3 = createIndexDetails("memberTwo", "empDobIdx");
-
- final List<IndexDetails> expectedIndexDetails =
- Arrays.asList(indexDetails1, indexDetails2, indexDetails3);
-
- final List<Set<IndexDetails>> results = new ArrayList<Set<IndexDetails>>(2);
-
- results.add(CollectionUtils.asSet(indexDetails2, indexDetails1));
- results.add(CollectionUtils.asSet(indexDetails3));
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(results));
- }
- });
-
- final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
- final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
-
- assertNotNull(actualIndexDetails);
- assertEquals(expectedIndexDetails, actualIndexDetails);
- }
-
- @Test(expected = RuntimeException.class)
- public void testGetIndexListingThrowsRuntimeException() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
- final Execution mockFunctionExecutor = mockContext.mock(Execution.class, "Function Executor");
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
- will(throwException(new RuntimeException("expected")));
- }
- });
-
- final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
-
- try {
- commands.getIndexListing();
- } catch (RuntimeException expected) {
- assertEquals("expected", expected.getMessage());
- throw expected;
- }
- }
-
- @Test
- public void testGetIndexListingReturnsFunctionInvocationTargetExceptionInResults() {
- final InternalCache mockCache = mockContext.mock(InternalCache.class, "InternalCache");
-
- final AbstractExecution mockFunctionExecutor =
- mockContext.mock(AbstractExecution.class, "Function Executor");
-
- final ResultCollector mockResultCollector =
- mockContext.mock(ResultCollector.class, "ResultCollector");
-
- final IndexDetails indexDetails = createIndexDetails("memberOne", "empIdIdx");
-
- final List<IndexDetails> expectedIndexDetails = Collections.singletonList(indexDetails);
-
- final List<Object> results = new ArrayList<Object>(2);
-
- results.add(CollectionUtils.asSet(indexDetails));
- results.add(new FunctionInvocationTargetException("expected"));
-
- mockContext.checking(new Expectations() {
- {
- oneOf(mockFunctionExecutor).setIgnoreDepartedMembers(with(equal(true)));
- oneOf(mockFunctionExecutor).execute(with(aNonNull(ListIndexFunction.class)));
- will(returnValue(mockResultCollector));
- oneOf(mockResultCollector).getResult();
- will(returnValue(results));
- }
- });
-
- final ListIndexCommand commands = createListIndexCommand(mockCache, mockFunctionExecutor);
-
- final List<IndexDetails> actualIndexDetails = commands.getIndexListing();
-
- assertNotNull(actualIndexDetails);
- assertEquals(expectedIndexDetails, actualIndexDetails);
- }
-
- private static class TestListIndexCommands extends ListIndexCommand {
- private final InternalCache cache;
- private final Execution functionExecutor;
-
- TestListIndexCommands(final InternalCache cache, final Execution functionExecutor) {
- assert cache != null : "The InternalCache cannot be null!";
- assert functionExecutor != null : "The function executor cannot be null!";
- this.cache = cache;
- this.functionExecutor = functionExecutor;
- }
-
- @Override
- public InternalCache getCache() {
- return this.cache;
- }
-
- @Override
- public Set<DistributedMember> getMembers(final InternalCache cache) {
- assertSame(getCache(), cache);
- return Collections.emptySet();
- }
-
- @Override
- public Execution getMembersFunctionExecutor(final Set<DistributedMember> members) {
- Assert.assertNotNull(members);
- return functionExecutor;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
index 9188582..bcbe07c 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/LogLevelInterceptorTest.java
@@ -18,20 +18,19 @@ package org.apache.geode.management.internal.cli.commands;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.test.junit.categories.UnitTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mockito.Mockito;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.test.junit.categories.UnitTest;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
@Category(UnitTest.class)
public class LogLevelInterceptorTest {
@@ -43,8 +42,8 @@ public class LogLevelInterceptorTest {
@Before
public void before() {
interceptors.add(new ExportLogsInterceptor());
- interceptors.add(new AlterRuntimeInterceptor());
- interceptors.add(new ChangeLogLevelCommand.ChangeLogLevelCommandInterceptor());
+ interceptors.add(new ConfigCommands.AlterRuntimeInterceptor());
+ interceptors.add(new MiscellaneousCommands.ChangeLogLevelInterceptor());
parseResult = Mockito.mock(GfshParseResult.class);
arguments = new HashMap<>();
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
index 674a0b6..f0c2c2f 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/MiscellaneousCommandsDUnitTest.java
@@ -14,34 +14,9 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_FILE;
-import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL;
-import static org.apache.geode.distributed.ConfigurationProperties.NAME;
-import static org.apache.geode.test.dunit.Assert.assertEquals;
-import static org.apache.geode.test.dunit.Assert.assertFalse;
-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.Invoke.invokeInEveryVM;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
-import static org.apache.geode.test.dunit.Wait.waitForCriterion;
-
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-
-import org.apache.geode.cache.Cache;
-import org.apache.geode.cache.CacheClosedException;
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionFactory;
-import org.apache.geode.cache.RegionShortcut;
+import org.apache.geode.cache.*;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.internal.cache.GemFireCacheImpl;
import org.apache.geode.internal.lang.ThreadUtils;
@@ -49,22 +24,27 @@ import org.apache.geode.management.cli.Result;
import org.apache.geode.management.cli.Result.Status;
import org.apache.geode.management.internal.cli.HeadlessGfsh;
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.result.CompositeResultData;
+import org.apache.geode.management.internal.cli.result.*;
import org.apache.geode.management.internal.cli.result.CompositeResultData.SectionResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.ResultData;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-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.WaitCriterion;
+import org.apache.geode.test.dunit.*;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.categories.FlakyTest;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
+
+import static org.apache.geode.test.dunit.Assert.*;
+import static org.apache.geode.test.dunit.IgnoredException.addIgnoredException;
+import static org.apache.geode.test.dunit.Invoke.invokeInEveryVM;
+import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.test.dunit.Wait.waitForCriterion;
/**
- * DUnit class for testing gemfire function commands : GC, Shutdown
+ * Dunit class for testing gemfire function commands : GC, Shutdown
*/
@Category(DistributedTest.class)
public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
@@ -95,15 +75,20 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
String command = "gc --group=Group1";
CommandResult cmdResult = executeCommand(command);
cmdResult.resetToFirstLine();
- String cmdResultStr = commandResultToString(cmdResult);
- getLogWriter().info("testGCForGroup cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
- assertEquals(Status.OK, cmdResult.getStatus());
- if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
- TabularResultData table = (TabularResultData) cmdResult.getResultData();
- List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
- assertEquals(true, memberNames.size() == 1);
+ if (cmdResult != null) {
+ String cmdResultStr = commandResultToString(cmdResult);
+ getLogWriter()
+ .info("testGCForGroup cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
+ TabularResultData table = (TabularResultData) cmdResult.getResultData();
+ List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
+ assertEquals(true, memberNames.size() == 1);
+ } else {
+ fail("testGCForGroup failed as CommandResult should be table type");
+ }
} else {
- fail("testGCForGroup failed as CommandResult should be table type");
+ fail("testGCForGroup failed as did not get CommandResult");
}
}
@@ -116,19 +101,23 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
public void testGCForMemberID() {
setUpJmxManagerOnVm0ThenConnect(null);
final VM vm1 = Host.getHost(0).getVM(1);
- final String vm1MemberId = vm1.invoke(this::getMemberId);
+ final String vm1MemberId = vm1.invoke(() -> getMemberId());
String command = "gc --member=" + vm1MemberId;
CommandResult cmdResult = executeCommand(command);
cmdResult.resetToFirstLine();
- String cmdResultStr = commandResultToString(cmdResult);
- getLogWriter().info("testGCForMemberID cmdResultStr=" + cmdResultStr);
- assertEquals(Status.OK, cmdResult.getStatus());
- if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
- TabularResultData table = (TabularResultData) cmdResult.getResultData();
- List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
- assertEquals(true, memberNames.size() == 1);
+ if (cmdResult != null) {
+ String cmdResultStr = commandResultToString(cmdResult);
+ getLogWriter().info("testGCForMemberID cmdResultStr=" + cmdResultStr);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
+ TabularResultData table = (TabularResultData) cmdResult.getResultData();
+ List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
+ assertEquals(true, memberNames.size() == 1);
+ } else {
+ fail("testGCForGroup failed as CommandResult should be table type");
+ }
} else {
- fail("testGCForGroup failed as CommandResult should be table type");
+ fail("testGCForCluster failed as did not get CommandResult");
}
}
@@ -139,7 +128,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
props.setProperty(LOG_FILE, "testShowLogDefault.log");
setUpJmxManagerOnVm0ThenConnect(props);
final VM vm1 = Host.getHost(0).getVM(0);
- final String vm1MemberId = vm1.invoke(this::getMemberId);
+ final String vm1MemberId = vm1.invoke(() -> getMemberId());
String command = "show log --member=" + vm1MemberId;
CommandResult cmdResult = executeCommand(command);
if (cmdResult != null) {
@@ -163,7 +152,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
try {
setUpJmxManagerOnVm0ThenConnect(props);
final VM vm1 = Host.getHost(0).getVM(0);
- final String vm1MemberId = vm1.invoke(this::getMemberId);
+ final String vm1MemberId = vm1.invoke(() -> getMemberId());
String command = "show log --member=" + vm1MemberId + " --lines=50";
CommandResult cmdResult = executeCommand(command);
if (cmdResult != null) {
@@ -185,20 +174,24 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
String command = "gc";
CommandResult cmdResult = executeCommand(command);
cmdResult.resetToFirstLine();
- String cmdResultStr = commandResultToString(cmdResult);
- getLogWriter()
- .info("testGCForEntireCluster cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
- assertEquals(Status.OK, cmdResult.getStatus());
- if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
- TabularResultData table = (TabularResultData) cmdResult.getResultData();
- List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
- assertEquals(3, memberNames.size());
+ if (cmdResult != null) {
+ String cmdResultStr = commandResultToString(cmdResult);
+ getLogWriter()
+ .info("testGCForEntireCluster cmdResultStr=" + cmdResultStr + "; cmdResult=" + cmdResult);
+ assertEquals(Result.Status.OK, cmdResult.getStatus());
+ if (cmdResult.getType().equals(ResultData.TYPE_TABULAR)) {
+ TabularResultData table = (TabularResultData) cmdResult.getResultData();
+ List<String> memberNames = table.retrieveAllValues(CliStrings.GC__MSG__MEMBER_NAME);
+ assertEquals(3, memberNames.size());
+ } else {
+ fail("testGCForGroup failed as CommandResult should be table type");
+ }
} else {
- fail("testGCForGroup failed as CommandResult should be table type");
+ fail("testGCForGroup failed as did not get CommandResult");
}
}
- private void setupForGC() {
+ void setupForGC() {
disconnectAllFromDS();
final VM vm1 = Host.getHost(0).getVM(1);
@@ -314,6 +307,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
}
});
+
String command = "shutdown --time-out=15";
CommandResult cmdResult = executeCommand(command);
@@ -332,7 +326,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
});
}
- private void setupForChangeLogLevel() {
+ void setupForChangeLogLelvel() {
final VM vm0 = Host.getHost(0).getVM(0);
final VM vm1 = Host.getHost(0).getVM(1);
@@ -352,7 +346,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
});
}
- private void setupForShutDown() {
+ void setupForShutDown() {
final VM vm0 = Host.getHost(0).getVM(0);
final VM vm1 = Host.getHost(0).getVM(1);
@@ -373,7 +367,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
});
}
- private void verifyShutDown() {
+ void verifyShutDown() {
final VM vm0 = Host.getHost(0).getVM(0);
final VM vm1 = Host.getHost(0).getVM(1);
@@ -416,7 +410,7 @@ public class MiscellaneousCommandsDUnitTest extends CliCommandTestBase {
final VM vm0 = Host.getHost(0).getVM(0);
final VM vm1 = Host.getHost(0).getVM(1);
- setupForChangeLogLevel();
+ setupForChangeLogLelvel();
String serverName1 = (String) vm0.invoke(new SerializableCallable() {
@Override
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
----------------------------------------------------------------------
diff --git a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
index eaa4f80..51653a4 100644
--- a/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
+++ b/geode-core/src/test/java/org/apache/geode/management/internal/cli/commands/ShowStackTraceDUnitTest.java
@@ -14,25 +14,14 @@
*/
package org.apache.geode.management.internal.cli.commands;
-import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_TIME_STATISTICS;
-import static org.apache.geode.distributed.ConfigurationProperties.GROUPS;
-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.STATISTIC_SAMPLING_ENABLED;
-import static org.apache.geode.test.dunit.Assert.assertFalse;
-import static org.apache.geode.test.dunit.Assert.assertTrue;
-import static org.apache.geode.test.dunit.LogWriterUtils.getLogWriter;
+import static org.apache.geode.distributed.ConfigurationProperties.*;
+import static org.apache.geode.test.dunit.Assert.*;
+import static org.apache.geode.test.dunit.LogWriterUtils.*;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.experimental.categories.Category;
-import org.junit.rules.TemporaryFolder;
-
import org.apache.geode.management.cli.Result.Status;
import org.apache.geode.management.internal.cli.i18n.CliStrings;
import org.apache.geode.management.internal.cli.json.GfJsonException;
@@ -43,6 +32,10 @@ import org.apache.geode.test.dunit.SerializableRunnable;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.experimental.categories.Category;
+import org.junit.rules.TemporaryFolder;
/***
* DUnit test for 'show stack-trace' command
@@ -263,7 +256,7 @@ public class ShowStackTraceDUnitTest extends CliCommandTestBase {
assertTrue(exportCommandResult.getStatus().equals(Status.OK));
assertTrue(
((String) exportCommandResult.getResultData().getGfJsonObject().getJSONObject("content")
- .getJSONArray("message").get(0)).contains("Stack-trace(s) exported to file:"));
+ .getJSONArray("message").get(0)).contains("stack-trace(s) exported to file:"));
}
}