You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by ji...@apache.org on 2018/09/13 21:32:24 UTC
[geode] branch develop updated: GEODE-5716: GfshRule improvement
(#2454)
This is an automated email from the ASF dual-hosted git repository.
jinmeiliao pushed a commit to branch develop
in repository https://gitbox.apache.org/repos/asf/geode.git
The following commit(s) were added to refs/heads/develop by this push:
new 5e35490 GEODE-5716: GfshRule improvement (#2454)
5e35490 is described below
commit 5e3549038d7371dd8a1350efa55a5be784340a5f
Author: jinmeiliao <ji...@pivotal.io>
AuthorDate: Thu Sep 13 14:32:16 2018 -0700
GEODE-5716: GfshRule improvement (#2454)
* simplify process output to stdout/stderr
* rework debuggable command API
* be more specific about each gfshScript execution in the output.
---
.../geode/test/junit/rules/gfsh/GfshExecution.java | 59 ++++++++
.../geode/test/junit/rules/gfsh/GfshRule.java | 82 +++---------
.../geode/test/junit/rules/gfsh/GfshScript.java | 148 ++++++++++-----------
.../junit/rules/gfsh/internal/ProcessLogger.java | 39 +-----
4 files changed, 148 insertions(+), 180 deletions(-)
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshExecution.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshExecution.java
index 5420a83..ba2508e 100644
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshExecution.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshExecution.java
@@ -14,6 +14,8 @@
*/
package org.apache.geode.test.junit.rules.gfsh;
+import static org.assertj.core.api.Assertions.assertThat;
+
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
@@ -21,16 +23,21 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
+import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.base.Charsets;
+import com.google.common.collect.Streams;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.geode.test.junit.rules.gfsh.internal.ProcessLogger;
public class GfshExecution {
+
+ private static final String DOUBLE_QUOTE = "\"";
+
private final Process process;
private final File workingDir;
private final ProcessLogger processLogger;
@@ -108,4 +115,56 @@ public class GfshExecution {
return Arrays.stream(memberDir.listFiles()).filter(File::isFile)
.filter(file -> file.getName().toLowerCase().endsWith(".log"));
}
+
+ protected void awaitTermination(GfshScript script) throws InterruptedException {
+ boolean exited = process.waitFor(script.getTimeout(), script.getTimeoutTimeUnit());
+
+ try {
+ assertThat(exited).isTrue();
+ assertThat(process.exitValue()).isEqualTo(script.getExpectedExitValue());
+ } catch (AssertionError error) {
+ printLogFiles();
+ throw error;
+ }
+ }
+
+ /**
+ * this only kills the process of "gfsh -e command", it does not kill the child processes started
+ * by this command.
+ */
+ public void killProcess() {
+ process.destroyForcibly();
+ if (process.isAlive()) {
+ // process may not terminate immediately after destroyForcibly
+ boolean exited = false;
+ try {
+ exited = process.waitFor(1, TimeUnit.MINUTES);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e.getMessage(), e);
+ }
+ if (!exited) {
+ throw new RuntimeException("failed to destroy the process of " + workingDir.getName());
+ }
+ }
+ }
+
+ String[] getStopMemberCommands() {
+ Stream<String> stopServers =
+ getServerDirs().stream().map(f -> "stop server --dir=" + quoteArgument(f.toString()));
+ Stream<String> stopLocators =
+ getLocatorDirs().stream().map(f -> "stop locator --dir=" + quoteArgument(f.toString()));
+ return Streams.concat(stopServers, stopLocators).toArray(String[]::new);
+ }
+
+ private String quoteArgument(String argument) {
+ if (!argument.startsWith(DOUBLE_QUOTE)) {
+ argument = DOUBLE_QUOTE + argument;
+ }
+
+ if (!argument.endsWith(DOUBLE_QUOTE)) {
+ argument = argument + DOUBLE_QUOTE;
+ }
+
+ return argument;
+ }
}
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshRule.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshRule.java
index 5e1e01a..043f008 100644
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshRule.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshRule.java
@@ -19,13 +19,11 @@ import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
-import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.junit.rules.ExternalResource;
@@ -40,17 +38,12 @@ import org.apache.geode.test.junit.rules.RequiresGeodeHome;
* a forked JVM. The {@link GfshRule#after()} method will attempt to clean up all forked JVMs.
*
* if you want to debug into the gfsh or the locator/servers started using this rule, you can do:
+ * GfshScript.of("start locator", 30000).and("start server", 30001).withDebugPort(30002).execute
*
- * GfshScript.of(new DebuggableCommand("start locator", 30001)).execute(gfshRule, 30000);
- *
- * this will set the gfsh to be debuggable at port 30000, and the locator started to be debuggable
- * at port 30001
+ * this will set the gfsh to be debuggable at port 30002, and the locator started to be debuggable
+ * at port 30000, and the server to be debuggable at 30001
*/
public class GfshRule extends ExternalResource {
-
- private static final String DOUBLE_QUOTE = "\"";
- private static final String LINE_SEPARATOR = System.getProperty("line.separator");
-
private TemporaryFolder temporaryFolder = new TemporaryFolder();
private List<GfshExecution> gfshExecutions;
private Path gfsh;
@@ -77,24 +70,12 @@ public class GfshRule extends ExternalResource {
*/
@Override
protected void after() {
- gfshExecutions.stream().collect(Collectors.toList()).forEach(this::stopMembersQuietly);
+ // this would not include the "stopMemberQuietly" executions
+ gfshExecutions.stream().collect(Collectors.toList()).forEach(this::stopMembers);
- final List<String> shutdownExceptions = new ArrayList<>();
+ // this will include the "stopMemberQuietly" executions
try {
- gfshExecutions.stream().map(GfshExecution::getProcess).map(Process::destroyForcibly)
- .forEach((Process process) -> {
- try {
- // Process.destroyForcibly() may not terminate immediately
- process.waitFor(1, TimeUnit.MINUTES);
- } catch (InterruptedException ie) {
- shutdownExceptions
- .add(process.toString() + " failed to shutdown: " + ie.getMessage());
- }
- });
- if (!shutdownExceptions.isEmpty()) {
- throw new RuntimeException("gfshExecutions processes failed to shutdown" + LINE_SEPARATOR
- + String.join(LINE_SEPARATOR, shutdownExceptions));
- }
+ gfshExecutions.stream().forEach(gfshExecution -> gfshExecution.killProcess());
} finally {
temporaryFolder.delete();
}
@@ -132,20 +113,18 @@ public class GfshRule extends ExternalResource {
}
public GfshExecution execute(GfshScript gfshScript) {
- return execute(gfshScript, -1);
- }
-
- public GfshExecution execute(GfshScript gfshScript, int gfshDebugPort) {
GfshExecution gfshExecution;
+ System.out.println("Executing " + gfshScript);
try {
File workingDir = new File(temporaryFolder.getRoot(), gfshScript.getName());
workingDir.mkdirs();
- Process process = toProcessBuilder(gfshScript, gfsh, workingDir, gfshDebugPort).start();
+ Process process =
+ toProcessBuilder(gfshScript, gfsh, workingDir, gfshScript.getDebugPort()).start();
gfshExecution = new GfshExecution(process, workingDir);
gfshExecutions.add(gfshExecution);
- gfshScript.awaitIfNecessary(gfshExecution);
- } catch (IOException e) {
- throw new UncheckedIOException(e);
+ gfshExecution.awaitTermination(gfshScript);
+ } catch (Exception e) {
+ throw new RuntimeException(e);
}
return gfshExecution;
@@ -193,36 +172,11 @@ public class GfshRule extends ExternalResource {
return processBuilder;
}
- private void stopMembersQuietly(GfshExecution gfshExecution) {
- gfshExecution.getServerDirs().forEach(this::stopServerInDir);
- gfshExecution.getLocatorDirs().forEach(this::stopLocatorInDir);
- }
-
- private void stopServerInDir(File dir) {
- String stopServerCommand = "stop server --dir=" + quoteArgument(dir.toString());
-
- GfshScript stopServerScript =
- GfshScript.of(stopServerCommand).withName("teardown-stop-server").awaitQuietly();
- execute(stopServerScript);
- }
-
- private void stopLocatorInDir(File dir) {
- String stopLocatorCommand = "stop locator --dir=" + quoteArgument(dir.toString());
-
- GfshScript stopServerScript =
- GfshScript.of(stopLocatorCommand).withName("teardown-stop-locator").awaitQuietly();
- execute(stopServerScript);
- }
-
- private String quoteArgument(String argument) {
- if (!argument.startsWith(DOUBLE_QUOTE)) {
- argument = DOUBLE_QUOTE + argument;
- }
-
- if (!argument.endsWith(DOUBLE_QUOTE)) {
- argument = argument + DOUBLE_QUOTE;
+ private void stopMembers(GfshExecution gfshExecution) {
+ String[] stopMemberScripts = gfshExecution.getStopMemberCommands();
+ if (stopMemberScripts.length == 0) {
+ return;
}
-
- return argument;
+ execute(GfshScript.of(stopMemberScripts).withName("Stop-Members"));
}
}
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshScript.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshScript.java
index 0eb8b32..0d50990 100644
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshScript.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/GfshScript.java
@@ -17,36 +17,69 @@ package org.apache.geode.test.junit.rules.gfsh;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+/**
+ * All the commands represented in this script is executed within one gfsh session.
+ *
+ * all the commands in this script are executed using this bash command:
+ * gfsh -e command1 -e command2 -e command3 ....
+ *
+ * You can chain commands together to create a gfshScript
+ * GfshScript.of("command1").and("command2").and("command3", "command4")
+ *
+ * If your command started another process and you want to that process to be debuggable, you can do
+ * GfshScript.of("start locator", 30000).and("start server", 30001)
+ * this will allow locator to be debuggable at 30000 and the server to be debuggable at 30001
+ *
+ * By default, each scripts await at most 4 minutes for all the commands to finish
+ * and will expect success. if you want to change this, you can use:
+ * gfshScript.awaitAtMost(1, TimeUnit.MINUTES).expectFailure()
+ *
+ * if you want this gfsh session to be debuggable, you can use:
+ * gfshScript.withDebugPort(30000)
+ * This will allow gfsh to be debuggable at port 30000.
+ *
+ */
public class GfshScript {
- private final DebuggableCommand[] commands;
+ private List<DebuggableCommand> commands = new ArrayList<>();
private String name;
private TimeUnit timeoutTimeUnit = TimeUnit.MINUTES;
private int timeout = 4;
- private boolean awaitQuietly = false;
private int expectedExitValue = 0;
private List<String> extendedClasspath = new ArrayList<>();
private Random random = new Random();
+ private int debugPort = -1;
- public GfshScript(DebuggableCommand... commands) {
- this.commands = commands;
+ public GfshScript() {
this.name = defaultName();
}
- /**
- * By default, this GfshScript will await at most 2 minutes and will expect success.
- */
public static GfshScript of(String... commands) {
- return new GfshScript(
- Arrays.stream(commands).map(DebuggableCommand::new).toArray(DebuggableCommand[]::new));
+ GfshScript script = new GfshScript();
+ script.and(commands);
+ return script;
}
- public static GfshScript of(DebuggableCommand... commands) {
- return new GfshScript(commands);
+ public static GfshScript of(String command, int debugPort) {
+ GfshScript script = new GfshScript();
+ script.and(command, debugPort);
+ return script;
+ }
+
+ public GfshScript and(String... commands) {
+ for (String command : commands) {
+ this.commands.add(new DebuggableCommand(command));
+ }
+ return this;
+ }
+
+ public GfshScript and(String command, int debugPort) {
+ this.commands.add(new DebuggableCommand(command, debugPort));
+ return this;
}
public GfshScript withName(String name) {
@@ -67,7 +100,7 @@ public class GfshScript {
}
/**
- * Will cause the thread that executes {@link GfshScript#awaitIfNecessary} to wait, if necessary,
+ * Will cause the thread that executes to wait, if necessary,
* until the subprocess executing this Gfsh script has terminated, or the specified waiting time
* elapses.
*
@@ -91,92 +124,47 @@ public class GfshScript {
return this;
}
- /**
- * Will cause the thread that executes {@link GfshScript#awaitIfNecessary} to wait, if necessary,
- * until the subprocess executing this Gfsh script has terminated, or the specified waiting time
- * elapses.
- */
- public GfshScript awaitQuietlyAtMost(int timeout, TimeUnit timeUnit) {
- this.awaitQuietly = true;
-
- return awaitAtMost(timeout, timeUnit);
- }
-
- public GfshScript awaitQuietly() {
- this.awaitQuietly = true;
-
+ public GfshScript withDebugPort(int debugPort) {
+ this.debugPort = debugPort;
return this;
}
public GfshExecution execute(GfshRule gfshRule) {
- return execute(gfshRule, -1);
- }
-
- public GfshExecution execute(GfshRule gfshRule, int gfshDebugPort) {
- return gfshRule.execute(this, gfshDebugPort);
- }
-
- protected void awaitIfNecessary(GfshExecution gfshExecution) {
- if (shouldAwaitQuietly()) {
- awaitQuietly(gfshExecution);
- } else if (shouldAwaitLoudly()) {
- awaitLoudly(gfshExecution);
- }
-
- try {
- assertThat(gfshExecution.getProcess().exitValue()).isEqualTo(expectedExitValue);
- } catch (AssertionError e) {
- gfshExecution.printLogFiles();
- throw e;
- }
-
- }
-
- private void awaitQuietly(GfshExecution gfshExecution) {
- try {
- gfshExecution.getProcess().waitFor(timeout, timeoutTimeUnit);
- } catch (InterruptedException ignore) {
- // ignore since we are waiting *quietly*
- }
+ return gfshRule.execute(this);
}
- private void awaitLoudly(GfshExecution gfshExecution) {
- boolean exited;
- try {
- exited = gfshExecution.getProcess().waitFor(timeout, timeoutTimeUnit);
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
-
- try {
- assertThat(exited).isTrue();
- } catch (AssertionError e) {
- gfshExecution.printLogFiles();
- throw e;
- }
+ public List<DebuggableCommand> getCommands() {
+ return commands;
}
- private boolean shouldAwait() {
- return timeoutTimeUnit != null;
+ public String getName() {
+ return name;
}
- private boolean shouldAwaitQuietly() {
- return shouldAwait() && awaitQuietly;
+ public TimeUnit getTimeoutTimeUnit() {
+ return timeoutTimeUnit;
}
- private boolean shouldAwaitLoudly() {
- return shouldAwait() && !awaitQuietly;
+ public int getTimeout() {
+ return timeout;
}
- public DebuggableCommand[] getCommands() {
- return commands;
+ public int getExpectedExitValue() {
+ return expectedExitValue;
}
- public String getName() {
- return name;
+ public int getDebugPort() {
+ return debugPort;
}
private String defaultName() {
return Long.toHexString(random.nextLong());
}
+
+ public String toString() {
+ StringBuilder builder = new StringBuilder();
+ builder.append(name).append(": gfsh ");
+ builder.append(commands.stream().map(c -> "-e " + c.command).collect(Collectors.joining(" ")));
+ return builder.toString();
+ }
}
diff --git a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/internal/ProcessLogger.java b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/internal/ProcessLogger.java
index 34ae27d..9ec81d9 100644
--- a/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/internal/ProcessLogger.java
+++ b/geode-junit/src/main/java/org/apache/geode/test/junit/rules/gfsh/internal/ProcessLogger.java
@@ -22,26 +22,13 @@ import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.apache.commons.lang.SystemUtils;
-import org.apache.logging.log4j.Level;
-import org.apache.logging.log4j.Logger;
-import org.apache.logging.log4j.core.Filter;
-import org.apache.logging.log4j.core.LoggerContext;
-import org.apache.logging.log4j.core.appender.ConsoleAppender;
-import org.apache.logging.log4j.core.config.Configurator;
-import org.apache.logging.log4j.core.config.builder.api.AppenderComponentBuilder;
-import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilder;
-import org.apache.logging.log4j.core.config.builder.api.ConfigurationBuilderFactory;
-import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
public class ProcessLogger {
- private static final LoggerContext LOGGER_CONTEXT = createLoggerContext();
- private final Logger logger;
+
private final Queue<OutputLine> outputLines = new ConcurrentLinkedQueue<>();
public ProcessLogger(Process process, String name) {
- this.logger = LOGGER_CONTEXT.getLogger(name);
-
StreamGobbler stdOutGobbler =
new StreamGobbler(process.getInputStream(), this::consumeInfoMessage);
StreamGobbler stdErrGobbler =
@@ -52,35 +39,15 @@ public class ProcessLogger {
}
private void consumeInfoMessage(String message) {
- logger.info(message);
+ System.out.println(message);
outputLines.add(OutputLine.fromStdOut(message));
}
private void consumeErrorMessage(String message) {
- logger.error(message);
+ System.err.println(message);
outputLines.add(OutputLine.fromStdErr(message));
}
- private static LoggerContext createLoggerContext() {
- ConfigurationBuilder<BuiltConfiguration> builder =
- ConfigurationBuilderFactory.newConfigurationBuilder();
- builder.setStatusLevel(Level.ERROR);
- builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
- .addAttribute("level", Level.DEBUG));
- AppenderComponentBuilder appenderBuilder = builder.newAppender("Stdout", "CONSOLE")
- .addAttribute("target", ConsoleAppender.Target.SYSTEM_OUT);
- appenderBuilder.add(builder.newLayout("PatternLayout").addAttribute("pattern",
- "[%-5level %d{HH:mm:ss.SSS z}] (%c): %msg%n%throwable"));
- appenderBuilder.add(builder.newFilter("MarkerFilter", Filter.Result.DENY, Filter.Result.NEUTRAL)
- .addAttribute("marker", "FLOW"));
- builder.add(appenderBuilder);
- builder.add(builder.newLogger("org.apache.logging.log4j", Level.ERROR)
- .add(builder.newAppenderRef("Stdout")).addAttribute("additivity", false));
- builder.add(builder.newRootLogger(Level.ERROR).add(builder.newAppenderRef("Stdout")));
-
- return Configurator.initialize(builder.build());
- }
-
public List<String> getStdOutLines() {
return getOutputLines(OutputLine.OutputSource.STD_OUT);
}