eclipse.preferences.version=1
+editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
formatter_profile=_Spaces
formatter_settings_version=12
+sp_cleanup.add_default_serial_version_id=true
+sp_cleanup.add_generated_serial_version_id=false
+sp_cleanup.add_missing_annotations=false
+sp_cleanup.add_missing_deprecated_annotations=true
+sp_cleanup.add_missing_methods=false
+sp_cleanup.add_missing_nls_tags=false
+sp_cleanup.add_missing_override_annotations=true
+sp_cleanup.add_missing_override_annotations_interface_methods=true
+sp_cleanup.add_serial_version_id=false
+sp_cleanup.always_use_blocks=true
+sp_cleanup.always_use_parentheses_in_expressions=false
+sp_cleanup.always_use_this_for_non_static_field_access=false
+sp_cleanup.always_use_this_for_non_static_method_access=false
+sp_cleanup.convert_functional_interfaces=false
+sp_cleanup.convert_to_enhanced_for_loop=false
+sp_cleanup.correct_indentation=false
+sp_cleanup.format_source_code=false
+sp_cleanup.format_source_code_changes_only=false
+sp_cleanup.insert_inferred_type_arguments=false
+sp_cleanup.make_local_variable_final=true
+sp_cleanup.make_parameters_final=false
+sp_cleanup.make_private_fields_final=true
+sp_cleanup.make_type_abstract_if_missing_method=false
+sp_cleanup.make_variable_declarations_final=false
+sp_cleanup.never_use_blocks=false
+sp_cleanup.never_use_parentheses_in_expressions=true
+sp_cleanup.on_save_use_additional_actions=true
+sp_cleanup.organize_imports=false
+sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
+sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
+sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
+sp_cleanup.remove_private_constructors=true
+sp_cleanup.remove_redundant_type_arguments=true
+sp_cleanup.remove_trailing_whitespaces=true
+sp_cleanup.remove_trailing_whitespaces_all=true
+sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
+sp_cleanup.remove_unnecessary_casts=false
+sp_cleanup.remove_unnecessary_nls_tags=false
+sp_cleanup.remove_unused_imports=false
+sp_cleanup.remove_unused_local_variables=false
+sp_cleanup.remove_unused_private_fields=true
+sp_cleanup.remove_unused_private_members=false
+sp_cleanup.remove_unused_private_methods=true
+sp_cleanup.remove_unused_private_types=true
+sp_cleanup.sort_members=false
+sp_cleanup.sort_members_all=false
+sp_cleanup.use_anonymous_class_creation=false
+sp_cleanup.use_blocks=false
+sp_cleanup.use_blocks_only_for_return_and_throw=false
+sp_cleanup.use_lambda=true
+sp_cleanup.use_parentheses_in_expressions=false
+sp_cleanup.use_this_for_non_static_field_access=false
+sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
+sp_cleanup.use_this_for_non_static_method_access=false
+sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true
+sp_cleanup.use_type_arguments=false
--- /dev/null
+/*
+ * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package org.lttng.tools;
+
+import java.util.List;
+
+/**
+ * Java representation of a LTTng tracing session.
+ *
+ * @author Alexandre Montplaisir
+ */
+public interface ILttngSession extends AutoCloseable {
+
+ /**
+ * Tracing domains as they are defined by lttng-tools
+ */
+ enum Domain {
+ /** The JUL (java.util.logging) domain */
+ JUL("-j"), /** The log4j (org.apache.log4j) domain */
+ LOG4J("-l");
+
+ private final String flag;
+
+ private Domain(String flag) {
+ this.flag = flag;
+ }
+
+ /**
+ * @return The corresponding command-line flag to pass to options like
+ * "lttng enable-event"
+ */
+ public String flag() {
+ return flag;
+ }
+ }
+
+ // ------------------------------------------------------------------------
+ // Factory methods
+ // ------------------------------------------------------------------------
+
+ /**
+ * Constructor to create a new LTTng tracing session, which will use the
+ * command-line "lttng" utility.
+ *
+ * @param sessionName
+ * The name of the session to use. It can be null, in which case
+ * we will provide a unique random name.
+ * @param domain
+ * The tracing domain of this session
+ * @return The new session object
+ */
+ static ILttngSession newCommandLineSession(String sessionName, Domain domain) {
+ return new LttngCommandLineSession(sessionName, domain);
+ }
+
+ // ------------------------------------------------------------------------
+ // AutoCloseable
+ // ------------------------------------------------------------------------
+
+ /**
+ * Should be used to destroy the LTTng session.
+ */
+ @Override
+ void close();
+
+ // ------------------------------------------------------------------------
+ // Session management
+ // ------------------------------------------------------------------------
+
+ /**
+ * Enable all events in the session (as with "enable-event -a").
+ *
+ * @return If the command executed successfully (return code = 0).
+ */
+ boolean enableAllEvents();
+
+ /**
+ * Enable individual event(s).
+ *
+ * @param enabledEvents
+ * The list of events to enable. Should not be null or empty
+ * @return If the command executed successfully (return code = 0).
+ */
+ boolean enableEvents(String... enabledEvents);
+
+ /**
+ * Send a disable-event command. Used to disable events that were previously
+ * enabled.
+ *
+ * @param disabledEvents
+ * The list of disabled events. Should not be null or empty
+ * @return If the command executed successfully (return code = 0).
+ */
+ boolean disableEvents(String... disabledEvents);
+
+ /**
+ * Start tracing
+ *
+ * @return If the command executed successfully (return code = 0).
+ */
+ boolean start();
+
+ /**
+ * Stop the tracing session
+ *
+ * @return If the command executed successfully (return code = 0).
+ */
+ boolean stop();
+
+ /**
+ * Issue a "lttng view" command on the session, and returns its output. This
+ * effectively returns the current content of the trace in text form.
+ *
+ * @return The output of Babeltrace on the session's current trace
+ */
+ List<String> view();
+}
--- /dev/null
+/*
+ * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package org.lttng.tools;
+
+import static org.lttng.tools.utils.ShellUtils.executeCommand;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.UUID;
+import java.util.stream.Collectors;
+
+import org.lttng.tools.utils.ShellUtils;
+
+/**
+ * Implementation of {@link ILttngSession} which uses the command-line "lttng"
+ * tool to manipulate the session. Creating an instance will run "lttng create",
+ * close()'ing it will run "lttng destroy".
+ *
+ * @author Alexandre Montplaisir
+ */
+class LttngCommandLineSession implements ILttngSession {
+
+ private final String sessionName;
+ private final Domain domain;
+
+ private volatile boolean channelCreated = false;
+
+ /**
+ * Constructor to create a new LTTng tracing session.
+ *
+ * @param sessionName
+ * The name of the session to use. It can be null, in which case
+ * we will provide a unique random name.
+ * @param domain
+ * The tracing domain of this session
+ */
+ public LttngCommandLineSession(String sessionName, Domain domain) {
+ if (sessionName != null) {
+ this.sessionName = sessionName;
+ } else {
+ this.sessionName = UUID.randomUUID().toString();
+ }
+ this.domain = domain;
+
+ /* Create the session in LTTng */
+ executeCommand(Arrays.asList("lttng", "create", this.sessionName));
+ }
+
+ @Override
+ public void close() {
+ /* Destroy the session */
+ executeCommand(Arrays.asList("lttng", "destroy", sessionName));
+ // FIXME also delete the trace we generated ?
+ }
+
+ @Override
+ public boolean enableAllEvents() {
+ channelCreated = true;
+ return executeCommand(Arrays.asList(
+ "lttng", "enable-event", domain.flag(), "-a", "-s", sessionName));
+ }
+
+ @Override
+ public boolean enableEvents(String... enabledEvents) {
+ if (enabledEvents == null || enabledEvents.length == 0) {
+ throw new IllegalArgumentException();
+ }
+ channelCreated = true;
+ return executeCommand(Arrays.asList(
+ "lttng", "enable-event", domain.flag(),
+ Arrays.stream(enabledEvents).collect(Collectors.joining(",")),
+ "-s", sessionName));
+ }
+
+ @Override
+ public boolean disableEvents(String... disabledEvents) {
+ if (disabledEvents == null || disabledEvents.length == 0) {
+ throw new IllegalArgumentException();
+ }
+ return executeCommand(Arrays.asList(
+ "lttng", "disable-event", domain.flag(),
+ Arrays.stream(disabledEvents).collect(Collectors.joining(",")),
+ "-s", sessionName));
+ }
+
+ @Override
+ public boolean start() {
+ /*
+ * We have to enable a channel for 'lttng start' to work. However, we
+ * cannot enable a channel directly, see
+ * https://bugs.lttng.org/issues/894 . Instead we will enable an event
+ * we know does not exist
+ */
+ if (!channelCreated) {
+ enableEvents("non-event");
+ }
+ return executeCommand(Arrays.asList("lttng", "start", sessionName));
+ }
+
+ @Override
+ public boolean stop() {
+ return executeCommand(Arrays.asList("lttng", "stop", sessionName));
+ }
+
+ @Override
+ public List<String> view() {
+ return ShellUtils.getOutputFromCommand(true, Arrays.asList("lttng", "view", sessionName));
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package org.lttng.tools;
+
+import static org.lttng.tools.utils.ShellUtils.executeCommand;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.Arrays;
+
+/**
+ * Helper class to issue LTTng commands that do not affect a single session, and
+ * as such, do not fit into the scope of one {@link ILttngSession}.
+ *
+ * @author Alexandre Montplaisir
+ */
+public final class LttngToolsHelper {
+
+ private LttngToolsHelper() {}
+
+ /**
+ * Utility method to destroy all existing sessions. Useful when first
+ * setting up a test to make sure no existing session interferes.
+ *
+ * @return If the command completed successfully
+ */
+ public static boolean destroyAllSessions() {
+ return executeCommand(Arrays.asList("lttng", "destroy", "-a"));
+ }
+
+ /**
+ * Outside of the scope of lttng-tools, but this utility method can be used
+ * to delete all traces currently under ~/lttng-traces/. This can be used by
+ * tests to cleanup a trace they have created.
+ *
+ * @return True if the command completes successfully, false if there was an
+ * error.
+ */
+ public static boolean deleteAllTraces() {
+ String tracesDir = new String(System.getProperty("user.home") + "/lttng-traces/");
+ return deleteDirectory(Paths.get(tracesDir));
+ }
+
+ // ------------------------------------------------------------------------
+ // Private helper methods
+ // ------------------------------------------------------------------------
+
+ private static boolean deleteDirectory(Path directory) {
+ try {
+ Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+ Files.delete(file);
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+ Files.delete(dir);
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ } catch (IOException e) {
+ /* At least we tried... */
+ return false;
+ }
+ return true;
+ }
+}
--- /dev/null
+/*
+ * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package org.lttng.tools.utils;
+
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.ust.agent.jul.LttngLogHandler;
+import org.lttng.ust.agent.log4j.LttngLogAppender;
+
+/**
+ * Utility methods to test the presence of certain LTTng tools or libraries in
+ * the runtime environment.
+ */
+public final class LttngUtils {
+
+ private LttngUtils() {}
+
+ /**
+ * Check the the JUL native library is available, effectively allowing LTTng
+ * JUL handlers to be used.
+ *
+ * @return True if JUL works fine, false if it does not.
+ */
+ public static boolean checkForJulLibrary() {
+ try {
+ LttngLogHandler testHandler = new LttngLogHandler();
+ testHandler.close();
+ } catch (SecurityException | IOException e) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Check the the Log4j native library is available, effectively allowing
+ * LTTng Log4j appenders to be used.
+ *
+ * @return True if Log4j works fine, false if it does not.
+ */
+ public static boolean checkForLog4jLibrary() {
+ try {
+ LttngLogAppender testAppender = new LttngLogAppender();
+ testAppender.close();
+ } catch (SecurityException | IOException e) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Check that lttng-tools and babeltrace are installed on the system and
+ * working.
+ *
+ * @param domain
+ * The tracing domain to test for (we will try to setup a session
+ * with this domain)
+ * @return True if the environment should allow tracing fine, false if there
+ * was an error
+ */
+ public static boolean checkForLttngTools(Domain domain) {
+ try (ILttngSession session = ILttngSession.newCommandLineSession(null, domain)) {
+ boolean ret1 = session.enableAllEvents();
+ boolean ret2 = session.start();
+ boolean ret3 = session.stop();
+ /*
+ * "lttng view" also tests that Babeltrace is installed and working
+ */
+ List<String> contents = session.view();
+ return (ret1 && ret2 && ret3 && contents.isEmpty());
+ }
+ }
+
+ /**
+ * Check if there is a user session daemon currently running on the system.
+ * It needs to be of the same user as the application running this program.
+ *
+ * @return If there is a user session daemon currently running
+ */
+ public static boolean checkForUserSessiond() {
+ String userName = System.getProperty("user.name");
+
+ /* The user name is truncated to 7 characters in "ps" */
+ String shortUserName = userName.substring(0, Math.min(userName.length(), 7));
+
+ List<String> command = Arrays.asList("ps", "-e", "u");
+ List<String> output = ShellUtils.getOutputFromCommand(false, command);
+ return output.stream()
+ .filter(s -> s.contains("lttng-sessiond"))
+ .anyMatch(s -> s.startsWith(shortUserName));
+ }
+
+ /**
+ * Check if there is a root user session daemon daemon currently running on
+ * the system.
+ *
+ * @return If there is a root session daemon currently running
+ */
+ public static boolean checkForRootSessiond() {
+ List<String> command = Arrays.asList("ps", "-e", "u");
+ List<String> output = ShellUtils.getOutputFromCommand(false, command);
+ return output.stream()
+ .filter(s -> s.contains("lttng-sessiond"))
+ .anyMatch(s -> s.startsWith("root"));
+ }
+
+}
--- /dev/null
+/*
+ * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program; if not, write to the Free Software Foundation, Inc.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+package org.lttng.tools.utils;
+
+import java.io.IOException;
+import java.lang.ProcessBuilder.Redirect;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.StringJoiner;
+
+/**
+ * Utility methods to execute commands on the command line.
+ *
+ * @author Alexandre Montplaisir
+ */
+public final class ShellUtils {
+
+ private ShellUtils() {}
+
+ /**
+ * Simple command to test that the environment / stdout are working
+ * correctly.
+ *
+ * @param args
+ * Command-line arguments
+ */
+ public static void main(String[] args) {
+ List<String> command = Arrays.asList("ls", "-l");
+ executeCommand(command);
+ }
+
+ /**
+ * Execute a shell command and retrieve its return value.
+ *
+ * @param command
+ * The command to execute, as a list of individual arguments (do
+ * not use spaces)
+ * @return If the command returned successfully (ret code = 0)
+ */
+ public static boolean executeCommand(List<String> command) {
+ try {
+ /* "echo" the command to stdout */
+ StringJoiner sj = new StringJoiner(" ", "$ ", "");
+ command.stream().forEach(sj::add);
+ System.out.println(sj.toString());
+
+ ProcessBuilder builder = new ProcessBuilder(command);
+ builder.redirectErrorStream(true);
+ builder.redirectOutput(Redirect.INHERIT);
+
+ Process p = builder.start();
+ int ret = p.waitFor();
+
+ System.out.println("(returned from command)");
+
+ return (ret == 0);
+
+ } catch (IOException | InterruptedException e) {
+ return false;
+ }
+ }
+
+ /**
+ * Execute a shell command and retrieve its output.
+ *
+ * @param print
+ * Should the output also be printed to stdout as usual
+ * @param command
+ * The command to execute, as a list of individual arguments (do
+ * not use spaces)
+ * @return The output of the command, as one list element per line
+ */
+ public static List<String> getOutputFromCommand(boolean print, List<String> command) {
+ try {
+ /* "echo" the command to stdout */
+ StringJoiner sj = new StringJoiner(" ", "$ ", "");
+ command.stream().forEach(sj::add);
+ System.out.println(sj.toString());
+
+ Path tempFile = Files.createTempFile("test-output", null);
+
+ ProcessBuilder builder = new ProcessBuilder(command);
+ builder.redirectErrorStream(true);
+ builder.redirectOutput(Redirect.to(tempFile.toFile()));
+
+ Process p = builder.start();
+ p.waitFor();
+
+ List<String> lines = Files.readAllLines(tempFile);
+ Files.delete(tempFile);
+
+ if (print) {
+ /* Also print the output to the console */
+ lines.stream().forEach(System.out::println);
+ } else {
+ System.out.println("(output silenced)");
+ }
+
+ System.out.println("(returned from command)");
+ return lines;
+
+ } catch (IOException | InterruptedException e) {
+ return null;
+ }
+ }
+}
import org.junit.After;
import org.junit.Before;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
import org.lttng.ust.agent.benchmarks.jul.handler.JulHandlerBenchmarkBase;
import org.lttng.ust.agent.jul.LttngLogHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
/**
* Benchmark the LTTng-JUL handler, but with tracing disabled in the tracing
*/
public class LttngJulHandlerTracingDisabledBenchmark extends JulHandlerBenchmarkBase {
- private LttngSession session;
+ private ILttngSession session;
/**
* Test setup
public void testSetup() throws IOException {
handler = new LttngLogHandler();
- session = new LttngSession(null, Domain.JUL);
+ session = ILttngSession.newCommandLineSession(null, Domain.JUL);
assertTrue(session.enableEvents("non-event"));
assertTrue(session.start());
}
import org.junit.After;
import org.junit.Before;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
import org.lttng.ust.agent.benchmarks.jul.handler.JulHandlerBenchmarkBase;
import org.lttng.ust.agent.jul.LttngLogHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
/**
* Test the LTTng-JUL handler, with it actually sending events to the tracer.
*/
public class LttngJulHandlerTracingEnabledBenchmark extends JulHandlerBenchmarkBase {
- private LttngSession session;
+ private ILttngSession session;
/**
* Test setup
public void testSetup() throws IOException {
handler = new LttngLogHandler();
- session = new LttngSession(null, Domain.JUL);
+ session = ILttngSession.newCommandLineSession(null, Domain.JUL);
assertTrue(session.enableAllEvents());
assertTrue(session.start());
}
import org.junit.After;
import org.junit.Before;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
import org.lttng.ust.agent.LTTngAgent;
import org.lttng.ust.agent.benchmarks.jul.handler.JulHandlerBenchmarkBase;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
/**
* Benchmark for the LTTng-UST handler, using the legacy API. Tracing is
@SuppressWarnings("deprecation")
public class OldLttngJulHandlerTracingDisabledBenchmark extends JulHandlerBenchmarkBase {
- private LttngSession session;
+ private ILttngSession session;
/**
* Test setup
public void testSetup() {
LTTngAgent.getLTTngAgent();
- session = new LttngSession(null, Domain.JUL);
+ session = ILttngSession.newCommandLineSession(null, Domain.JUL);
assertTrue(session.enableEvents("non-event"));
assertTrue(session.start());
}
import org.junit.After;
import org.junit.Before;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
import org.lttng.ust.agent.LTTngAgent;
import org.lttng.ust.agent.benchmarks.jul.handler.JulHandlerBenchmarkBase;
import org.lttng.ust.agent.jul.LttngLogHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
/**
* Benchmark for the LTTng-UST handler, using the legacy API. Tracing is
@SuppressWarnings("deprecation")
public class OldLttngJulHandlerTracingEnabledBenchmark extends JulHandlerBenchmarkBase {
- private LttngSession session;
+ private ILttngSession session;
private LttngLogHandler agentHandler;
fail();
}
- session = new LttngSession(null, Domain.JUL);
+ session = ILttngSession.newCommandLineSession(null, Domain.JUL);
assertTrue(session.enableAllEvents());
assertTrue(session.start());
}
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
import org.lttng.ust.agent.ILttngHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
import org.lttng.ust.agent.utils.TestPrintRunner;
/**
protected static final String EVENT_NAME_C = "EventABC";
protected static final String EVENT_NAME_D = "EventABCD";
- private LttngSession session;
+ private ILttngSession session;
/* Fields defined by the sub-class */
protected ILttngHandler handlerA;
*/
@Before
public void testSetup() {
- session = new LttngSession(null, getDomain());
+ session = ILttngSession.newCommandLineSession(null, getDomain());
}
/**
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
import org.lttng.ust.agent.ILttngHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
import org.lttng.ust.agent.utils.TestPrintRunner;
/**
protected static final String EVENT_NAME_C = "EventABC";
protected static final String EVENT_NAME_D = "EventABCD";
- private LttngSession session1;
- private LttngSession session2;
- private LttngSession session3;
+ private ILttngSession session1;
+ private ILttngSession session2;
+ private ILttngSession session3;
/* Fields defined by the sub-class */
protected ILttngHandler handlerA;
*/
@Before
public void testSetup() {
- session1 = new LttngSession(null, getDomain());
- session2 = new LttngSession(null, getDomain());
- session3 = new LttngSession(null, getDomain());
+ session1 = ILttngSession.newCommandLineSession(null, getDomain());
+ session2 = ILttngSession.newCommandLineSession(null, getDomain());
+ session3 = ILttngSession.newCommandLineSession(null, getDomain());
}
/**
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.tools.LttngToolsHelper;
+import org.lttng.tools.utils.LttngUtils;
import org.lttng.ust.agent.integration.EnabledEventsTestBase;
import org.lttng.ust.agent.jul.LttngLogHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-import org.lttng.ust.agent.utils.MiscTestUtils;
/**
* Enabled events test for the LTTng-UST JUL log handler.
@BeforeClass
public static void julClassSetup() {
/* Skip tests if we can't find the JNI library or lttng-tools */
- assumeTrue(MiscTestUtils.checkForJulLibrary());
- assumeTrue(MiscTestUtils.checkForLttngTools(Domain.JUL));
+ assumeTrue(LttngUtils.checkForJulLibrary());
+ assumeTrue(LttngUtils.checkForLttngTools(Domain.JUL));
- LttngSession.destroyAllSessions();
+ LttngToolsHelper.destroyAllSessions();
}
/**
*/
@AfterClass
public static void julClassCleanup() {
- LttngSession.deleteAllTracee();
+ LttngToolsHelper.deleteAllTraces();
}
/**
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.tools.LttngToolsHelper;
+import org.lttng.tools.utils.LttngUtils;
import org.lttng.ust.agent.ILttngHandler;
import org.lttng.ust.agent.LTTngAgent;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-import org.lttng.ust.agent.utils.MiscTestUtils;
import org.lttng.ust.agent.utils.TestPrintRunner;
/**
private static final String EVENT_NAME_A = "EventA";
private static final String EVENT_NAME_B = "EventB";
- private LttngSession session;
+ private ILttngSession session;
private Logger loggerA;
private Logger loggerB;
@BeforeClass
public static void julClassSetup() {
/* Skip tests if we can't find the JNI library or lttng-tools */
- assumeTrue(MiscTestUtils.checkForJulLibrary());
- assumeTrue(MiscTestUtils.checkForLttngTools(Domain.JUL));
+ assumeTrue(LttngUtils.checkForJulLibrary());
+ assumeTrue(LttngUtils.checkForLttngTools(Domain.JUL));
- LttngSession.destroyAllSessions();
+ LttngToolsHelper.destroyAllSessions();
}
/**
*/
@AfterClass
public static void julClassCleanup() {
- LttngSession.deleteAllTracee();
+ LttngToolsHelper.deleteAllTraces();
}
/**
loggerA.setLevel(Level.ALL);
loggerB.setLevel(Level.ALL);
- session = new LttngSession(null, DOMAIN);
+ session = ILttngSession.newCommandLineSession(null, DOMAIN);
}
/**
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.tools.LttngToolsHelper;
+import org.lttng.tools.utils.LttngUtils;
import org.lttng.ust.agent.integration.MultiSessionTestBase;
import org.lttng.ust.agent.jul.LttngLogHandler;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-import org.lttng.ust.agent.utils.MiscTestUtils;
/**
* JUL tests for multiple concurrent tracing sessions
@BeforeClass
public static void julClassSetup() {
/* Skip tests if we can't find the JNI library or lttng-tools */
- assumeTrue(MiscTestUtils.checkForJulLibrary());
- assumeTrue(MiscTestUtils.checkForLttngTools(Domain.JUL));
+ assumeTrue(LttngUtils.checkForJulLibrary());
+ assumeTrue(LttngUtils.checkForLttngTools(Domain.JUL));
- LttngSession.destroyAllSessions();
+ LttngToolsHelper.destroyAllSessions();
}
/**
*/
@AfterClass
public static void julClassCleanup() {
- LttngSession.deleteAllTracee();
+ LttngToolsHelper.deleteAllTraces();
}
/**
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.tools.LttngToolsHelper;
+import org.lttng.tools.utils.LttngUtils;
import org.lttng.ust.agent.integration.EnabledEventsTestBase;
import org.lttng.ust.agent.log4j.LttngLogAppender;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-import org.lttng.ust.agent.utils.MiscTestUtils;
/**
* Enabled events test for the LTTng-UST Log4j log handler.
@BeforeClass
public static void log4jClassSetup() {
/* Skip tests if we can't find the JNI library or lttng-tools */
- assumeTrue(MiscTestUtils.checkForLog4jLibrary());
- assumeTrue(MiscTestUtils.checkForLttngTools(Domain.LOG4J));
+ assumeTrue(LttngUtils.checkForLog4jLibrary());
+ assumeTrue(LttngUtils.checkForLttngTools(Domain.LOG4J));
- LttngSession.destroyAllSessions();
+ LttngToolsHelper.destroyAllSessions();
}
/**
*/
@AfterClass
public static void log4jClassCleanup() {
- LttngSession.deleteAllTracee();
+ LttngToolsHelper.deleteAllTraces();
}
/**
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
+import org.lttng.tools.ILttngSession;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.tools.LttngToolsHelper;
+import org.lttng.tools.utils.LttngUtils;
import org.lttng.ust.agent.ILttngHandler;
import org.lttng.ust.agent.LTTngAgent;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-import org.lttng.ust.agent.utils.MiscTestUtils;
import org.lttng.ust.agent.utils.TestPrintRunner;
/**
private static final String EVENT_NAME_A = "EventA";
private static final String EVENT_NAME_B = "EventB";
- private LttngSession session;
+ private ILttngSession session;
private Logger loggerA;
private Logger loggerB;
@BeforeClass
public static void classSetup() {
/* Skip tests if we can't find the JNI library or lttng-tools */
- assumeTrue(MiscTestUtils.checkForLog4jLibrary());
- assumeTrue(MiscTestUtils.checkForLttngTools(Domain.LOG4J));
+ assumeTrue(LttngUtils.checkForLog4jLibrary());
+ assumeTrue(LttngUtils.checkForLttngTools(Domain.LOG4J));
- LttngSession.destroyAllSessions();
+ LttngToolsHelper.destroyAllSessions();
}
/**
*/
@AfterClass
public static void classCleanup() {
- LttngSession.deleteAllTracee();
+ LttngToolsHelper.deleteAllTraces();
}
/**
loggerA.setLevel(Level.ALL);
loggerB.setLevel(Level.ALL);
- session = new LttngSession(null, DOMAIN);
+ session = ILttngSession.newCommandLineSession(null, DOMAIN);
}
/**
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
+import org.lttng.tools.ILttngSession.Domain;
+import org.lttng.tools.LttngToolsHelper;
+import org.lttng.tools.utils.LttngUtils;
import org.lttng.ust.agent.integration.MultiSessionTestBase;
import org.lttng.ust.agent.log4j.LttngLogAppender;
-import org.lttng.ust.agent.utils.LttngSession;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-import org.lttng.ust.agent.utils.MiscTestUtils;
/**
* Log4j tests for multiple concurrent tracing sessions
@BeforeClass
public static void log4jClassSetup() {
/* Skip tests if we can't find the JNI library or lttng-tools */
- assumeTrue(MiscTestUtils.checkForLog4jLibrary());
- assumeTrue(MiscTestUtils.checkForLttngTools(Domain.LOG4J));
+ assumeTrue(LttngUtils.checkForLog4jLibrary());
+ assumeTrue(LttngUtils.checkForLttngTools(Domain.LOG4J));
- LttngSession.destroyAllSessions();
+ LttngToolsHelper.destroyAllSessions();
}
/**
*/
@AfterClass
public static void log4jClassCleanup() {
- LttngSession.deleteAllTracee();
+ LttngToolsHelper.deleteAllTraces();
}
/**
+++ /dev/null
-/*
- * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
- */
-
-package org.lttng.ust.agent.utils;
-
-import static org.lttng.ust.agent.utils.ShellUtils.executeCommand;
-
-import java.io.IOException;
-import java.nio.file.FileVisitResult;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.SimpleFileVisitor;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.util.Arrays;
-import java.util.List;
-import java.util.UUID;
-import java.util.stream.Collectors;
-
-/**
- * Java representation of a LTTng tracing session. It uses the command-line
- * "lttng" tool to manipulate the session. Creating an instance will run
- * "lttng create", close()'ing it will run "lttng destroy".
- *
- * @author Alexandre Montplaisir
- */
-public class LttngSession implements AutoCloseable {
-
- /**
- * Tracing domains as they are defined by lttng-tools
- */
- public enum Domain {
- /** The JUL (java.util.logging) domain */
- JUL("-j"), /** The log4j (org.apache.log4j) domain */
- LOG4J("-l");
-
- private final String flag;
-
- private Domain(String flag) {
- this.flag = flag;
- }
-
- /**
- * @return The corresponding command-line flag to pass to options like
- * "lttng enable-event"
- */
- public String flag() {
- return flag;
- }
- }
-
- private final String sessionName;
- private final Domain domain;
-
- private volatile boolean channelCreated = false;
-
- /**
- * Constructor to create a new LTTng tracing session.
- *
- * @param sessionName
- * The name of the session to use. It can be null, in which case
- * we will provide a unique random name.
- * @param domain
- * The tracing domain of this session
- */
- public LttngSession(String sessionName, Domain domain) {
- if (sessionName != null) {
- this.sessionName = sessionName;
- } else {
- this.sessionName = UUID.randomUUID().toString();
- }
- this.domain = domain;
-
- /* Create the session in LTTng */
- executeCommand(Arrays.asList("lttng", "create", this.sessionName));
- }
-
- @Override
- public void close() {
- /* Destroy the session */
- executeCommand(Arrays.asList("lttng", "destroy", sessionName));
- // FIXME also delete the trace we generated ?
- }
-
- // ------------------------------------------------------------------------
- // Public methods
- // ------------------------------------------------------------------------
-
- /**
- * Enable all events in the given session (enable-event -a)
- *
- * @return If the command executed successfully (return code = 0).
- */
- public boolean enableAllEvents() {
- channelCreated = true;
- return executeCommand(Arrays.asList(
- "lttng", "enable-event", domain.flag(), "-a", "-s", sessionName));
- }
-
- /**
- * Enable individual event(s).
- *
- * @param enabledEvents
- * The list of events to enable. Should not be null or empty
- * @return If the command executed successfully (return code = 0).
- */
- public boolean enableEvents(String... enabledEvents) {
- if (enabledEvents == null || enabledEvents.length == 0) {
- throw new IllegalArgumentException();
- }
- channelCreated = true;
- return executeCommand(Arrays.asList(
- "lttng", "enable-event", domain.flag(),
- Arrays.stream(enabledEvents).collect(Collectors.joining(",")),
- "-s", sessionName));
- }
-
- /**
- * Send a disable-event command. Used to disable events that were previously
- * enabled.
- *
- * @param disabledEvents
- * The list of disabled events. Should not be null or empty
- * @return If the command executed successfully (return code = 0).
- */
- public boolean disableEvents(String... disabledEvents) {
- if (disabledEvents == null || disabledEvents.length == 0) {
- throw new IllegalArgumentException();
- }
- return executeCommand(Arrays.asList(
- "lttng", "disable-event", domain.flag(),
- Arrays.stream(disabledEvents).collect(Collectors.joining(",")),
- "-s", sessionName));
- }
-
- /**
- * Start tracing
- *
- * @return If the command executed successfully (return code = 0).
- */
- public boolean start() {
- /*
- * We have to enable a channel for 'lttng start' to work. However, we
- * cannot enable a channel directly, see
- * https://bugs.lttng.org/issues/894 . Instead we will enable an event
- * we know does not exist
- */
- if (!channelCreated) {
- enableEvents("non-event");
- }
- return executeCommand(Arrays.asList("lttng", "start", sessionName));
- }
-
- /**
- * Stop the tracing session
- *
- * @return If the command executed successfully (return code = 0).
- */
- public boolean stop() {
- return executeCommand(Arrays.asList("lttng", "stop", sessionName));
- }
-
- /**
- * Issue a "lttng view" command on the session, and returns its output. This
- * effectively returns the current content of the trace in text form.
- *
- * @return The output of Babeltrace on the session's current trace
- */
- public List<String> view() {
- return ShellUtils.getOutputFromCommand(true, Arrays.asList("lttng", "view", sessionName));
- }
-
- /**
- * Utility method to destroy all existing sessions. Useful when first
- * setting up a test to make sure no existing session interferes.
- */
- public static void destroyAllSessions() {
- executeCommand(Arrays.asList("lttng", "destroy", "-a"));
- }
-
- /**
- * Outside of the scope of lttng-tools, but this utility method can be used
- * to delete all traces currently under ~/lttng-traces/. This can be used by
- * tests to cleanup a trace they have created.
- *
- * @return True if the command completes successfully, false if there was an
- * error.
- */
- public static boolean deleteAllTracee() {
- String tracesDir = new String(System.getProperty("user.home") + "/lttng-traces/");
- return deleteDirectory(Paths.get(tracesDir));
- }
-
- // ------------------------------------------------------------------------
- // Private helper methods
- // ------------------------------------------------------------------------
-
- private static boolean deleteDirectory(Path directory) {
- try {
- Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
- @Override
- public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
- Files.delete(file);
- return FileVisitResult.CONTINUE;
- }
-
- @Override
- public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
- Files.delete(dir);
- return FileVisitResult.CONTINUE;
- }
- });
- } catch (IOException e) {
- /* At least we tried... */
- return false;
- }
- return true;
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
- */
-
-package org.lttng.ust.agent.utils;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-import org.lttng.ust.agent.jul.LttngLogHandler;
-import org.lttng.ust.agent.log4j.LttngLogAppender;
-import org.lttng.ust.agent.utils.LttngSession.Domain;
-
-/**
- * Utility methods to help with UST-Java tests
- */
-public final class MiscTestUtils {
-
- private MiscTestUtils() {}
-
- /**
- * Check the the JUL native library is available, effectively allowing LTTng
- * JUL handlers to be used.
- *
- * @return True if JUL works fine, false if it does not.
- */
- public static boolean checkForJulLibrary() {
- try {
- LttngLogHandler testHandler = new LttngLogHandler();
- testHandler.close();
- } catch (SecurityException | IOException e) {
- return false;
- }
- return true;
- }
-
- /**
- * Check the the Log4j native library is available, effectively allowing
- * LTTng Log4j appenders to be used.
- *
- * @return True if Log4j works fine, false if it does not.
- */
- public static boolean checkForLog4jLibrary() {
- try {
- LttngLogAppender testAppender = new LttngLogAppender();
- testAppender.close();
- } catch (SecurityException | IOException e) {
- return false;
- }
- return true;
- }
-
- /**
- * Check that lttng-tools and babeltrace are installed on the system and
- * working.
- *
- * @param domain
- * The tracing domain to test for (we will try to setup a session
- * with this domain)
- * @return True if the environment should allow tracing fine, false if there
- * was an error
- */
- public static boolean checkForLttngTools(Domain domain) {
- try (LttngSession session = new LttngSession(null, domain)) {
- boolean ret1 = session.enableAllEvents();
- boolean ret2 = session.start();
- boolean ret3 = session.stop();
- /*
- * "lttng view" also tests that Babeltrace is installed and working
- */
- List<String> contents = session.view();
- return (ret1 && ret2 && ret3 && contents.isEmpty());
- }
- }
-
- /**
- * Check if there is a user session daemon currently running on the system.
- * It needs to be of the same user as the application running this program.
- *
- * @return If there is a user session daemon currently running
- */
- public static boolean checkForUserSessiond() {
- String userName = System.getProperty("user.name");
-
- /* The user name is truncated to 7 characters in "ps" */
- String shortUserName = userName.substring(0, Math.min(userName.length(), 7));
-
- List<String> command = Arrays.asList("ps", "-e", "u");
- List<String> output = ShellUtils.getOutputFromCommand(false, command);
- return output.stream()
- .filter(s -> s.contains("lttng-sessiond"))
- .anyMatch(s -> s.startsWith(shortUserName));
- }
-
- /**
- * Check if there is a root user session daemon daemon currently running on
- * the system.
- *
- * @return If there is a root session daemon currently running
- */
- public static boolean checkForRootSessiond() {
- List<String> command = Arrays.asList("ps", "-e", "u");
- List<String> output = ShellUtils.getOutputFromCommand(false, command);
- return output.stream()
- .filter(s -> s.contains("lttng-sessiond"))
- .anyMatch(s -> s.startsWith("root"));
- }
-
-}
+++ /dev/null
-/*
- * Copyright (C) 2015, EfficiOS Inc., Alexandre Montplaisir <alexmonthy@efficios.com>
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
- */
-
-package org.lttng.ust.agent.utils;
-
-import java.io.IOException;
-import java.lang.ProcessBuilder.Redirect;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.StringJoiner;
-
-/**
- * Utility methods to execute commands on the command line.
- *
- * @author Alexandre Montplaisir
- */
-public final class ShellUtils {
-
- private ShellUtils() {}
-
- /**
- * Simple command to test that the environment / stdout are working
- * correctly.
- *
- * @param args
- * Command-line arguments
- */
- public static void main(String[] args) {
- List<String> command = Arrays.asList("ls", "-l");
- executeCommand(command);
- }
-
- /**
- * Execute a shell command and retrieve its return value.
- *
- * @param command
- * The command to execute, as a list of individual arguments (do
- * not use spaces)
- * @return If the command returned successfully (ret code = 0)
- */
- public static boolean executeCommand(List<String> command) {
- try {
- /* "echo" the command to stdout */
- StringJoiner sj = new StringJoiner(" ", "$ ", "");
- command.stream().forEach(sj::add);
- System.out.println(sj.toString());
-
- ProcessBuilder builder = new ProcessBuilder(command);
- builder.redirectErrorStream(true);
- builder.redirectOutput(Redirect.INHERIT);
-
- Process p = builder.start();
- int ret = p.waitFor();
-
- System.out.println("(returned from command)");
-
- return (ret == 0);
-
- } catch (IOException | InterruptedException e) {
- return false;
- }
- }
-
- /**
- * Execute a shell command and retrieve its output.
- *
- * @param print
- * Should the output also be printed to stdout as usual
- * @param command
- * The command to execute, as a list of individual arguments (do
- * not use spaces)
- * @return The output of the command, as one list element per line
- */
- public static List<String> getOutputFromCommand(boolean print, List<String> command) {
- try {
- /* "echo" the command to stdout */
- StringJoiner sj = new StringJoiner(" ", "$ ", "");
- command.stream().forEach(sj::add);
- System.out.println(sj.toString());
-
- Path tempFile = Files.createTempFile("test-output", null);
-
- ProcessBuilder builder = new ProcessBuilder(command);
- builder.redirectErrorStream(true);
- builder.redirectOutput(Redirect.to(tempFile.toFile()));
-
- Process p = builder.start();
- p.waitFor();
-
- List<String> lines = Files.readAllLines(tempFile);
- Files.delete(tempFile);
-
- if (print) {
- /* Also print the output to the console */
- lines.stream().forEach(System.out::println);
- } else {
- System.out.println("(output silenced)");
- }
-
- System.out.println("(returned from command)");
- return lines;
-
- } catch (IOException | InterruptedException e) {
- return null;
- }
- }
-}