Search in sources :

Example 1 with InputListener

use of org.apache.geode.internal.process.ProcessStreamReader.InputListener in project geode by apache.

the class BlockingProcessStreamReaderJUnitTest method capturesBothWhileProcessIsAlive.

@Test
public void capturesBothWhileProcessIsAlive() throws Exception {
    assumeFalse(SystemUtils.isWindows());
    this.process = new ProcessBuilder(createCommandLine(ProcessPrintsToBoth.class)).start();
    final StringBuffer stderrBuffer = new StringBuffer();
    InputListener stderrListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stderrBuffer.append(line);
        }
    };
    final StringBuffer stdoutBuffer = new StringBuffer();
    InputListener stdoutListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stdoutBuffer.append(line);
        }
    };
    this.stderr = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getErrorStream()).inputListener(stderrListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stdout = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getInputStream()).inputListener(stdoutListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stderr.start();
    this.stdout.start();
    // wait for process to die
    assertEventuallyFalse("Process never died", new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return ProcessUtils.isProcessAlive(process);
        }
    }, WAIT_FOR_PROCESS_TO_DIE_TIMEOUT, INTERVAL);
    final int exitValue = this.process.exitValue();
    assertEquals(0, exitValue);
    this.stderr.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stderr.isRunning());
    this.stdout.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stdout.isRunning());
    // System.out.println("Stopping ProcessStreamReader");
    this.stderr.stop();
    this.stdout.stop();
    // System.out.println("stderr=\n" + stderrBuffer.toString());
    StringBuilder sb = new StringBuilder().append(ProcessPrintsToBoth.ERR_LINES[0]).append(ProcessPrintsToBoth.ERR_LINES[1]).append(ProcessPrintsToBoth.ERR_LINES[2]);
    assertEquals(sb.toString(), stderrBuffer.toString());
    // System.out.println("stdout=\n" + stdoutBuffer.toString());
    sb = new StringBuilder().append(ProcessPrintsToBoth.OUT_LINES[0]).append(ProcessPrintsToBoth.OUT_LINES[1]).append(ProcessPrintsToBoth.OUT_LINES[2]);
    assertEquals(sb.toString(), stdoutBuffer.toString());
    // System.out.println("Closing streams");
    this.process.getErrorStream().close();
    this.process.getInputStream().close();
    this.process.destroy();
}
Also used : TimeoutException(java.util.concurrent.TimeoutException) IOException(java.io.IOException) InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 2 with InputListener

use of org.apache.geode.internal.process.ProcessStreamReader.InputListener in project geode by apache.

the class NonBlockingProcessStreamReaderJUnitTest method capturesStderrWhenProcessFailsDuringStart.

@Test
public void capturesStderrWhenProcessFailsDuringStart() throws Exception {
    this.process = new ProcessBuilder(createCommandLine(ProcessThrowsError.class)).start();
    final StringBuffer stderrBuffer = new StringBuffer();
    InputListener stderrListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stderrBuffer.append(line);
        }
    };
    final StringBuffer stdoutBuffer = new StringBuffer();
    InputListener stdoutListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stdoutBuffer.append(line);
        }
    };
    this.stderr = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getErrorStream()).inputListener(stderrListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stdout = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getInputStream()).inputListener(stdoutListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stderr.start();
    this.stdout.start();
    // wait for process to die
    assertEventuallyFalse("Process never died", new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return ProcessUtils.isProcessAlive(process);
        }
    }, WAIT_FOR_PROCESS_TO_DIE_TIMEOUT, INTERVAL);
    final int exitValue = this.process.exitValue();
    assertNotEquals(0, exitValue);
    this.stderr.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stderr.isRunning());
    this.stdout.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stdout.isRunning());
    // System.out.println("Stopping ProcessStreamReader");
    this.stderr.stop();
    this.stdout.stop();
    // System.out.println("stderr=\n" + stderrBuffer.toString());
    assertTrue(stderrBuffer.toString() + " does not contain " + ProcessThrowsError.ERROR_MSG, stderrBuffer.toString().contains(ProcessThrowsError.ERROR_MSG));
    // System.out.println("stdout=\n" + stdoutBuffer.toString());
    // System.out.println("Closing streams");
    this.process.getErrorStream().close();
    this.process.getInputStream().close();
    this.process.destroy();
}
Also used : InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 3 with InputListener

use of org.apache.geode.internal.process.ProcessStreamReader.InputListener in project geode by apache.

the class LauncherLifecycleCommands method startLocator.

@CliCommand(value = CliStrings.START_LOCATOR, help = CliStrings.START_LOCATOR__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GEODE_LOCATOR, CliStrings.TOPIC_GEODE_LIFECYCLE })
public Result startLocator(@CliOption(key = CliStrings.START_LOCATOR__MEMBER_NAME, help = CliStrings.START_LOCATOR__MEMBER_NAME__HELP) String memberName, @CliOption(key = CliStrings.START_LOCATOR__BIND_ADDRESS, help = CliStrings.START_LOCATOR__BIND_ADDRESS__HELP) final String bindAddress, @CliOption(key = CliStrings.START_LOCATOR__CLASSPATH, help = CliStrings.START_LOCATOR__CLASSPATH__HELP) final String classpath, @CliOption(key = CliStrings.START_LOCATOR__FORCE, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.START_LOCATOR__FORCE__HELP) final Boolean force, @CliOption(key = CliStrings.START_LOCATOR__GROUP, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.START_LOCATOR__GROUP__HELP) final String group, @CliOption(key = CliStrings.START_LOCATOR__HOSTNAME_FOR_CLIENTS, help = CliStrings.START_LOCATOR__HOSTNAME_FOR_CLIENTS__HELP) final String hostnameForClients, @CliOption(key = CliStrings.START_LOCATOR__INCLUDE_SYSTEM_CLASSPATH, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = CliStrings.START_LOCATOR__INCLUDE_SYSTEM_CLASSPATH__HELP) final Boolean includeSystemClasspath, @CliOption(key = CliStrings.START_LOCATOR__LOCATORS, optionContext = ConverterHint.LOCATOR_DISCOVERY_CONFIG, help = CliStrings.START_LOCATOR__LOCATORS__HELP) final String locators, @CliOption(key = CliStrings.START_LOCATOR__LOG_LEVEL, optionContext = ConverterHint.LOG_LEVEL, help = CliStrings.START_LOCATOR__LOG_LEVEL__HELP) final String logLevel, @CliOption(key = CliStrings.START_LOCATOR__MCAST_ADDRESS, help = CliStrings.START_LOCATOR__MCAST_ADDRESS__HELP) final String mcastBindAddress, @CliOption(key = CliStrings.START_LOCATOR__MCAST_PORT, help = CliStrings.START_LOCATOR__MCAST_PORT__HELP) final Integer mcastPort, @CliOption(key = CliStrings.START_LOCATOR__PORT, help = CliStrings.START_LOCATOR__PORT__HELP) final Integer port, @CliOption(key = CliStrings.START_LOCATOR__DIR, help = CliStrings.START_LOCATOR__DIR__HELP) String workingDirectory, @CliOption(key = CliStrings.START_LOCATOR__PROPERTIES, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_LOCATOR__PROPERTIES__HELP) String gemfirePropertiesPathname, @CliOption(key = CliStrings.START_LOCATOR__SECURITY_PROPERTIES, optionContext = ConverterHint.FILE_PATH, help = CliStrings.START_LOCATOR__SECURITY_PROPERTIES__HELP) String gemfireSecurityPropertiesPathname, @CliOption(key = CliStrings.START_LOCATOR__INITIALHEAP, help = CliStrings.START_LOCATOR__INITIALHEAP__HELP) final String initialHeap, @CliOption(key = CliStrings.START_LOCATOR__MAXHEAP, help = CliStrings.START_LOCATOR__MAXHEAP__HELP) final String maxHeap, @CliOption(key = CliStrings.START_LOCATOR__J, optionContext = GfshParser.J_OPTION_CONTEXT, help = CliStrings.START_LOCATOR__J__HELP) final String[] jvmArgsOpts, @CliOption(key = CliStrings.START_LOCATOR__CONNECT, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.START_LOCATOR__CONNECT__HELP) final boolean connect, @CliOption(key = CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION, unspecifiedDefaultValue = "true", specifiedDefaultValue = "true", help = CliStrings.START_LOCATOR__ENABLE__SHARED__CONFIGURATION__HELP) final boolean enableSharedConfiguration, @CliOption(key = CliStrings.START_LOCATOR__LOAD__SHARED_CONFIGURATION__FROM__FILESYSTEM, unspecifiedDefaultValue = "false", help = CliStrings.START_LOCATOR__LOAD__SHARED_CONFIGURATION__FROM__FILESYSTEM__HELP) final boolean loadSharedConfigurationFromDirectory, @CliOption(key = CliStrings.START_LOCATOR__CLUSTER__CONFIG__DIR, unspecifiedDefaultValue = "", help = CliStrings.START_LOCATOR__CLUSTER__CONFIG__DIR__HELP) final String clusterConfigDir, @CliOption(key = CliStrings.START_LOCATOR__HTTP_SERVICE_PORT, help = CliStrings.START_LOCATOR__HTTP_SERVICE_PORT__HELP) final Integer httpServicePort, @CliOption(key = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS, help = CliStrings.START_LOCATOR__HTTP_SERVICE_BIND_ADDRESS__HELP) final String httpServiceBindAddress) {
    try {
        if (StringUtils.isBlank(memberName)) {
            // when the user doesn't give us a name, we make one up!
            memberName = nameGenerator.generate('-');
        }
        workingDirectory = resolveWorkingDir(workingDirectory, memberName);
        gemfirePropertiesPathname = CliUtil.resolvePathname(gemfirePropertiesPathname);
        if (StringUtils.isNotBlank(gemfirePropertiesPathname) && !IOUtils.isExistingPathname(gemfirePropertiesPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, StringUtils.EMPTY, gemfirePropertiesPathname));
        }
        gemfireSecurityPropertiesPathname = CliUtil.resolvePathname(gemfireSecurityPropertiesPathname);
        if (StringUtils.isNotBlank(gemfireSecurityPropertiesPathname) && !IOUtils.isExistingPathname(gemfireSecurityPropertiesPathname)) {
            return ResultBuilder.createUserErrorResult(CliStrings.format(CliStrings.GEODE_0_PROPERTIES_1_NOT_FOUND_MESSAGE, "Security ", gemfireSecurityPropertiesPathname));
        }
        File locatorPidFile = new File(workingDirectory, ProcessType.LOCATOR.getPidFileName());
        final int oldPid = readPid(locatorPidFile);
        Properties gemfireProperties = new Properties();
        gemfireProperties.setProperty(GROUPS, StringUtils.defaultString(group));
        gemfireProperties.setProperty(LOCATORS, StringUtils.defaultString(locators));
        gemfireProperties.setProperty(LOG_LEVEL, StringUtils.defaultString(logLevel));
        gemfireProperties.setProperty(MCAST_ADDRESS, StringUtils.defaultString(mcastBindAddress));
        gemfireProperties.setProperty(MCAST_PORT, StringUtils.defaultString(mcastPort));
        gemfireProperties.setProperty(ENABLE_CLUSTER_CONFIGURATION, StringUtils.defaultString(enableSharedConfiguration));
        gemfireProperties.setProperty(LOAD_CLUSTER_CONFIGURATION_FROM_DIR, StringUtils.defaultString(loadSharedConfigurationFromDirectory));
        gemfireProperties.setProperty(CLUSTER_CONFIGURATION_DIR, StringUtils.defaultString(clusterConfigDir));
        gemfireProperties.setProperty(HTTP_SERVICE_PORT, StringUtils.defaultString(httpServicePort));
        gemfireProperties.setProperty(HTTP_SERVICE_BIND_ADDRESS, StringUtils.defaultString(httpServiceBindAddress));
        // read the OSProcess enable redirect system property here -- TODO: replace with new GFSH
        // argument
        final boolean redirectOutput = Boolean.getBoolean(OSProcess.ENABLE_OUTPUT_REDIRECTION_PROPERTY);
        LocatorLauncher.Builder locatorLauncherBuilder = new LocatorLauncher.Builder().setBindAddress(bindAddress).setForce(force).setPort(port).setRedirectOutput(redirectOutput).setWorkingDirectory(workingDirectory);
        if (hostnameForClients != null) {
            locatorLauncherBuilder.setHostnameForClients(hostnameForClients);
        }
        if (memberName != null) {
            locatorLauncherBuilder.setMemberName(memberName);
        }
        LocatorLauncher locatorLauncher = locatorLauncherBuilder.build();
        String[] locatorCommandLine = createStartLocatorCommandLine(locatorLauncher, gemfirePropertiesPathname, gemfireSecurityPropertiesPathname, gemfireProperties, classpath, includeSystemClasspath, jvmArgsOpts, initialHeap, maxHeap);
        final Process locatorProcess = new ProcessBuilder(locatorCommandLine).directory(new File(locatorLauncher.getWorkingDirectory())).start();
        locatorProcess.getInputStream().close();
        locatorProcess.getOutputStream().close();
        // fix TRAC bug #51967 by using NON_BLOCKING on Windows
        final ReadingMode readingMode = SystemUtils.isWindows() ? ReadingMode.NON_BLOCKING : ReadingMode.BLOCKING;
        // need thread-safe StringBuffer
        final StringBuffer message = new StringBuffer();
        InputListener inputListener = new InputListener() {

            @Override
            public void notifyInputLine(String line) {
                message.append(line);
                if (readingMode == ReadingMode.BLOCKING) {
                    message.append(StringUtils.LINE_SEPARATOR);
                }
            }
        };
        ProcessStreamReader stderrReader = new ProcessStreamReader.Builder(locatorProcess).inputStream(locatorProcess.getErrorStream()).inputListener(inputListener).readingMode(readingMode).continueReadingMillis(2 * 1000).build().start();
        LocatorState locatorState;
        String previousLocatorStatusMessage = null;
        LauncherSignalListener locatorSignalListener = new LauncherSignalListener();
        final boolean registeredLocatorSignalListener = getGfsh().getSignalHandler().registerListener(locatorSignalListener);
        try {
            getGfsh().logInfo(String.format(CliStrings.START_LOCATOR__RUN_MESSAGE, IOUtils.tryGetCanonicalPathElseGetAbsolutePath(new File(locatorLauncher.getWorkingDirectory()))), null);
            locatorState = LocatorState.fromDirectory(workingDirectory, memberName);
            do {
                if (locatorProcess.isAlive()) {
                    Gfsh.print(".");
                    synchronized (this) {
                        TimeUnit.MILLISECONDS.timedWait(this, 500);
                    }
                    locatorState = LocatorState.fromDirectory(workingDirectory, memberName);
                    String currentLocatorStatusMessage = locatorState.getStatusMessage();
                    if (locatorState.isStartingOrNotResponding() && !(StringUtils.isBlank(currentLocatorStatusMessage) || currentLocatorStatusMessage.equalsIgnoreCase(previousLocatorStatusMessage) || currentLocatorStatusMessage.trim().toLowerCase().equals("null"))) {
                        Gfsh.println();
                        Gfsh.println(currentLocatorStatusMessage);
                        previousLocatorStatusMessage = currentLocatorStatusMessage;
                    }
                } else {
                    final int exitValue = locatorProcess.exitValue();
                    return ResultBuilder.createShellClientErrorResult(String.format(CliStrings.START_LOCATOR__PROCESS_TERMINATED_ABNORMALLY_ERROR_MESSAGE, exitValue, locatorLauncher.getWorkingDirectory(), message.toString()));
                }
            } while (!(registeredLocatorSignalListener && locatorSignalListener.isSignaled()) && locatorState.isStartingOrNotResponding());
        } finally {
            // stop will close
            stderrReader.stopAsync(PROCESS_STREAM_READER_ASYNC_STOP_TIMEOUT_MILLIS);
            // ErrorStream
            getGfsh().getSignalHandler().unregisterListener(locatorSignalListener);
        }
        Gfsh.println();
        final boolean asyncStart = (registeredLocatorSignalListener && locatorSignalListener.isSignaled() && ServerState.isStartingNotRespondingOrNull(locatorState));
        InfoResultData infoResultData = ResultBuilder.createInfoResultData();
        if (asyncStart) {
            infoResultData.addLine(String.format(CliStrings.ASYNC_PROCESS_LAUNCH_MESSAGE, LOCATOR_TERM_NAME));
        } else {
            infoResultData.addLine(locatorState.toString());
            String locatorHostName;
            InetAddress bindAddr = locatorLauncher.getBindAddress();
            if (bindAddr != null) {
                locatorHostName = bindAddr.getCanonicalHostName();
            } else {
                locatorHostName = StringUtils.defaultIfBlank(locatorLauncher.getHostnameForClients(), HostUtils.getLocalHost());
            }
            int locatorPort = Integer.parseInt(locatorState.getPort());
            // Else, ask the user to use the "connect" command to connect to the Locator.
            if (shouldAutoConnect(connect)) {
                doAutoConnect(locatorHostName, locatorPort, gemfirePropertiesPathname, gemfireSecurityPropertiesPathname, infoResultData);
            }
            // Report on the state of the Shared Configuration service if enabled...
            if (enableSharedConfiguration) {
                infoResultData.addLine(ClusterConfigurationStatusRetriever.fromLocator(locatorHostName, locatorPort));
            }
        }
        return ResultBuilder.buildResult(infoResultData);
    } catch (IllegalArgumentException e) {
        String message = e.getMessage();
        if (message != null && message.matches(LocalizedStrings.Launcher_Builder_UNKNOWN_HOST_ERROR_MESSAGE.toLocalizedString(".+"))) {
            message = CliStrings.format(CliStrings.LAUNCHERLIFECYCLECOMMANDS__MSG__FAILED_TO_START_0_REASON_1, LOCATOR_TERM_NAME, message);
        }
        return ResultBuilder.createUserErrorResult(message);
    } catch (IllegalStateException e) {
        return ResultBuilder.createUserErrorResult(e.getMessage());
    } catch (VirtualMachineError e) {
        SystemFailure.initiateFailure(e);
        throw e;
    } catch (Throwable t) {
        SystemFailure.checkFailure();
        String errorMessage = String.format(CliStrings.START_LOCATOR__GENERAL_ERROR_MESSAGE, StringUtils.defaultIfBlank(workingDirectory, memberName), getLocatorId(bindAddress, port), toString(t, getGfsh().getDebug()));
        getGfsh().logToFile(errorMessage, t);
        return ResultBuilder.createShellClientErrorResult(errorMessage);
    } finally {
        Gfsh.redirectInternalJavaLoggers();
    }
}
Also used : LocatorLauncher(org.apache.geode.distributed.LocatorLauncher) InfoResultData(org.apache.geode.management.internal.cli.result.InfoResultData) CommandStringBuilder(org.apache.geode.management.internal.cli.util.CommandStringBuilder) ResultBuilder(org.apache.geode.management.internal.cli.result.ResultBuilder) OSProcess(org.apache.geode.internal.OSProcess) Properties(java.util.Properties) ConnectionEndpoint(org.apache.geode.management.internal.cli.util.ConnectionEndpoint) ConverterHint(org.apache.geode.management.cli.ConverterHint) InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) ProcessStreamReader(org.apache.geode.internal.process.ProcessStreamReader) LocatorState(org.apache.geode.distributed.LocatorLauncher.LocatorState) File(java.io.File) InetAddress(java.net.InetAddress) ReadingMode(org.apache.geode.internal.process.ProcessStreamReader.ReadingMode) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData)

Example 4 with InputListener

use of org.apache.geode.internal.process.ProcessStreamReader.InputListener in project geode by apache.

the class NonBlockingProcessStreamReaderJUnitTest method capturesBothWhileProcessIsAlive.

@Test
public void capturesBothWhileProcessIsAlive() throws Exception {
    this.process = new ProcessBuilder(createCommandLine(ProcessPrintsToBoth.class)).start();
    final StringBuffer stderrBuffer = new StringBuffer();
    InputListener stderrListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stderrBuffer.append(line);
        }
    };
    final StringBuffer stdoutBuffer = new StringBuffer();
    InputListener stdoutListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stdoutBuffer.append(line);
        }
    };
    this.stderr = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getErrorStream()).inputListener(stderrListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stdout = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getInputStream()).inputListener(stdoutListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stderr.start();
    this.stdout.start();
    // wait for process to die
    assertEventuallyFalse("Process never died", new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return ProcessUtils.isProcessAlive(process);
        }
    }, WAIT_FOR_PROCESS_TO_DIE_TIMEOUT, INTERVAL);
    final int exitValue = this.process.exitValue();
    assertEquals(0, exitValue);
    this.stderr.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stderr.isRunning());
    this.stdout.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stdout.isRunning());
    // System.out.println("Stopping ProcessStreamReader");
    this.stderr.stop();
    this.stdout.stop();
    // System.out.println("stderr=\n" + stderrBuffer.toString());
    StringBuilder sb = new StringBuilder().append(ProcessPrintsToBoth.ERR_LINES[0]).append(ProcessPrintsToBoth.ERR_LINES[1]).append(ProcessPrintsToBoth.ERR_LINES[2]);
    assertEquals(sb.toString(), stderrBuffer.toString());
    // System.out.println("stdout=\n" + stdoutBuffer.toString());
    sb = new StringBuilder().append(ProcessPrintsToBoth.OUT_LINES[0]).append(ProcessPrintsToBoth.OUT_LINES[1]).append(ProcessPrintsToBoth.OUT_LINES[2]);
    assertEquals(sb.toString(), stdoutBuffer.toString());
    // System.out.println("Closing streams");
    this.process.getErrorStream().close();
    this.process.getInputStream().close();
    this.process.destroy();
}
Also used : InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 5 with InputListener

use of org.apache.geode.internal.process.ProcessStreamReader.InputListener in project geode by apache.

the class NonBlockingProcessStreamReaderJUnitTest method capturesStdoutWhileProcessIsAlive.

@Test
public void capturesStdoutWhileProcessIsAlive() throws Exception {
    this.process = new ProcessBuilder(createCommandLine(ProcessPrintsToStdout.class)).start();
    final StringBuffer stderrBuffer = new StringBuffer();
    InputListener stderrListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stderrBuffer.append(line);
        }
    };
    final StringBuffer stdoutBuffer = new StringBuffer();
    InputListener stdoutListener = new InputListener() {

        @Override
        public void notifyInputLine(String line) {
            stdoutBuffer.append(line);
        }
    };
    this.stderr = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getErrorStream()).inputListener(stderrListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stdout = new ProcessStreamReader.Builder(this.process).inputStream(this.process.getInputStream()).inputListener(stdoutListener).readingMode(ReadingMode.NON_BLOCKING).build();
    this.stderr.start();
    this.stdout.start();
    // wait for process to die
    assertEventuallyFalse("Process never died", new Callable<Boolean>() {

        @Override
        public Boolean call() throws Exception {
            return ProcessUtils.isProcessAlive(process);
        }
    }, WAIT_FOR_PROCESS_TO_DIE_TIMEOUT, INTERVAL);
    final int exitValue = this.process.exitValue();
    assertEquals(0, exitValue);
    this.stderr.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stderr.isRunning());
    this.stdout.join(READER_JOIN_TIMEOUT);
    assertFalse(this.stdout.isRunning());
    // System.out.println("Stopping ProcessStreamReader");
    this.stderr.stop();
    this.stdout.stop();
    // System.out.println("stderr=\n" + stderrBuffer.toString());
    assertEquals("", stderrBuffer.toString());
    // System.out.println("stdout=\n" + stdoutBuffer.toString());
    StringBuilder sb = new StringBuilder().append(ProcessPrintsToStdout.LINES[0]).append(ProcessPrintsToStdout.LINES[1]).append(ProcessPrintsToStdout.LINES[2]);
    assertEquals(sb.toString(), stdoutBuffer.toString());
    // System.out.println("Closing streams");
    this.process.getErrorStream().close();
    this.process.getInputStream().close();
    this.process.destroy();
}
Also used : InputListener(org.apache.geode.internal.process.ProcessStreamReader.InputListener) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Aggregations

InputListener (org.apache.geode.internal.process.ProcessStreamReader.InputListener)10 IntegrationTest (org.apache.geode.test.junit.categories.IntegrationTest)8 Test (org.junit.Test)8 IOException (java.io.IOException)4 TimeoutException (java.util.concurrent.TimeoutException)4 File (java.io.File)2 Properties (java.util.Properties)2 OSProcess (org.apache.geode.internal.OSProcess)2 ProcessStreamReader (org.apache.geode.internal.process.ProcessStreamReader)2 ReadingMode (org.apache.geode.internal.process.ProcessStreamReader.ReadingMode)2 CliMetaData (org.apache.geode.management.cli.CliMetaData)2 ConverterHint (org.apache.geode.management.cli.ConverterHint)2 ResultBuilder (org.apache.geode.management.internal.cli.result.ResultBuilder)2 CommandStringBuilder (org.apache.geode.management.internal.cli.util.CommandStringBuilder)2 ConnectionEndpoint (org.apache.geode.management.internal.cli.util.ConnectionEndpoint)2 CliCommand (org.springframework.shell.core.annotation.CliCommand)2 InetAddress (java.net.InetAddress)1 LocatorLauncher (org.apache.geode.distributed.LocatorLauncher)1 LocatorState (org.apache.geode.distributed.LocatorLauncher.LocatorState)1 ServerLauncher (org.apache.geode.distributed.ServerLauncher)1