Search in sources :

Example 36 with UserException

use of org.opensearch.cli.UserException in project OpenSearch by opensearch-project.

the class OpenSearchCliTestCase method runTest.

void runTest(final int expectedStatus, final boolean expectedInit, final BiConsumer<String, String> outputConsumer, final InitConsumer initConsumer, final String... args) throws Exception {
    final MockTerminal terminal = new MockTerminal();
    final Path home = createTempDir();
    try {
        final AtomicBoolean init = new AtomicBoolean();
        final int status = OpenSearch.main(args, new OpenSearch() {

            @Override
            protected Environment createEnv(final Map<String, String> settings) throws UserException {
                Settings.Builder builder = Settings.builder().put("path.home", home);
                settings.forEach((k, v) -> builder.put(k, v));
                final Settings realSettings = builder.build();
                return new Environment(realSettings, home.resolve("config"));
            }

            @Override
            void init(final boolean daemonize, final Path pidFile, final boolean quiet, Environment initialEnv) {
                init.set(true);
                initConsumer.accept(!daemonize, pidFile, quiet, initialEnv);
            }

            @Override
            protected boolean addShutdownHook() {
                return false;
            }
        }, terminal);
        assertThat(status, equalTo(expectedStatus));
        assertThat(init.get(), equalTo(expectedInit));
        outputConsumer.accept(terminal.getOutput(), terminal.getErrorOutput());
    } catch (Exception e) {
        // if an unexpected exception is thrown, we log
        // terminal output to aid debugging
        logger.info("Stdout:\n" + terminal.getOutput());
        logger.info("Stderr:\n" + terminal.getErrorOutput());
        // rethrow so the test fails
        throw e;
    }
}
Also used : Path(java.nio.file.Path) Environment(org.opensearch.env.Environment) UserException(org.opensearch.cli.UserException) MockTerminal(org.opensearch.cli.MockTerminal) CoreMatchers.equalTo(org.hamcrest.CoreMatchers.equalTo) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Settings(org.opensearch.common.settings.Settings) Path(java.nio.file.Path) MockTerminal(org.opensearch.cli.MockTerminal) UserException(org.opensearch.cli.UserException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Environment(org.opensearch.env.Environment) UserException(org.opensearch.cli.UserException) Settings(org.opensearch.common.settings.Settings)

Example 37 with UserException

use of org.opensearch.cli.UserException in project OpenSearch by opensearch-project.

the class OpenSearchNodeCommand method processNodePaths.

protected void processNodePaths(Terminal terminal, OptionSet options, Environment env) throws IOException, UserException {
    terminal.println(Terminal.Verbosity.VERBOSE, "Obtaining lock for node");
    Integer nodeOrdinal = nodeOrdinalOption.value(options);
    if (nodeOrdinal == null) {
        nodeOrdinal = 0;
    }
    try (NodeEnvironment.NodeLock lock = new NodeEnvironment.NodeLock(nodeOrdinal, logger, env, Files::exists)) {
        final Path[] dataPaths = Arrays.stream(lock.getNodePaths()).filter(Objects::nonNull).map(p -> p.path).toArray(Path[]::new);
        if (dataPaths.length == 0) {
            throw new OpenSearchException(NO_NODE_FOLDER_FOUND_MSG);
        }
        processNodePaths(terminal, dataPaths, nodeOrdinal, options, env);
    } catch (LockObtainFailedException e) {
        throw new OpenSearchException(FAILED_TO_OBTAIN_NODE_LOCK_MSG, e);
    }
}
Also used : Path(java.nio.file.Path) UserException(org.opensearch.cli.UserException) Arrays(java.util.Arrays) Metadata(org.opensearch.cluster.metadata.Metadata) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) Version(org.opensearch.Version) StreamOutput(org.opensearch.common.io.stream.StreamOutput) OpenSearchException(org.opensearch.OpenSearchException) XContentParser(org.opensearch.common.xcontent.XContentParser) PersistedClusterStateService(org.opensearch.gateway.PersistedClusterStateService) ClusterState(org.opensearch.cluster.ClusterState) NodeMetadata(org.opensearch.env.NodeMetadata) Map(java.util.Map) OptionParser(joptsimple.OptionParser) ClusterSettings(org.opensearch.common.settings.ClusterSettings) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) OptionSet(joptsimple.OptionSet) OptionSpec(joptsimple.OptionSpec) Environment(org.opensearch.env.Environment) NodeEnvironment(org.opensearch.env.NodeEnvironment) Terminal(org.opensearch.cli.Terminal) Files(java.nio.file.Files) Condition(org.opensearch.action.admin.indices.rollover.Condition) Settings(org.opensearch.common.settings.Settings) IOException(java.io.IOException) ClusterModule(org.opensearch.cluster.ClusterModule) Tuple(org.opensearch.common.collect.Tuple) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) Objects(java.util.Objects) Logger(org.apache.logging.log4j.Logger) DataStreamMetadata(org.opensearch.cluster.metadata.DataStreamMetadata) Diff(org.opensearch.cluster.Diff) EnvironmentAwareCommand(org.opensearch.cli.EnvironmentAwareCommand) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ClusterName(org.opensearch.cluster.ClusterName) BigArrays(org.opensearch.common.util.BigArrays) LogManager(org.apache.logging.log4j.LogManager) NodeEnvironment(org.opensearch.env.NodeEnvironment) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) Objects(java.util.Objects) OpenSearchException(org.opensearch.OpenSearchException) Files(java.nio.file.Files)

Example 38 with UserException

use of org.opensearch.cli.UserException in project OpenSearch by opensearch-project.

the class RemoveSettingsCommandIT method testSettingDoesNotMatch.

public void testSettingDoesNotMatch() throws Exception {
    internalCluster().setBootstrapClusterManagerNodeIndex(0);
    String node = internalCluster().startNode();
    client().admin().cluster().prepareUpdateSettings().setPersistentSettings(Settings.builder().put(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING.getKey(), false).build()).get();
    assertThat(client().admin().cluster().prepareState().get().getState().metadata().persistentSettings().keySet(), contains(DiskThresholdSettings.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED_SETTING.getKey()));
    Settings dataPathSettings = internalCluster().dataPathSettings(node);
    ensureStableCluster(1);
    internalCluster().stopRandomDataNode();
    Environment environment = TestEnvironment.newEnvironment(Settings.builder().put(internalCluster().getDefaultSettings()).put(dataPathSettings).build());
    UserException ex = expectThrows(UserException.class, () -> removeSettings(environment, false, new String[] { "cluster.routing.allocation.disk.bla.*" }));
    assertThat(ex.getMessage(), containsString("No persistent cluster settings matching [cluster.routing.allocation.disk.bla.*] were " + "found on this node"));
}
Also used : Environment(org.opensearch.env.Environment) TestEnvironment(org.opensearch.env.TestEnvironment) Matchers.containsString(org.hamcrest.Matchers.containsString) UserException(org.opensearch.cli.UserException) Settings(org.opensearch.common.settings.Settings) DiskThresholdSettings(org.opensearch.cluster.routing.allocation.DiskThresholdSettings)

Example 39 with UserException

use of org.opensearch.cli.UserException in project OpenSearch by opensearch-project.

the class AddStringKeyStoreCommand method executeCommand.

@Override
protected void executeCommand(Terminal terminal, OptionSet options, Environment env) throws Exception {
    final List<String> settings = arguments.values(options);
    if (settings.isEmpty()) {
        throw new UserException(ExitCodes.USAGE, "the setting names can not be empty");
    }
    final KeyStoreWrapper keyStore = getKeyStore();
    final Closeable closeable;
    final CheckedFunction<String, char[], IOException> valueSupplier;
    if (options.has(stdinOption)) {
        final BufferedReader stdinReader = new BufferedReader(new InputStreamReader(getStdin(), StandardCharsets.UTF_8));
        valueSupplier = s -> {
            try (CharArrayWriter writer = new CharArrayWriter()) {
                int c;
                while ((c = stdinReader.read()) != -1) {
                    if ((char) c == '\r' || (char) c == '\n') {
                        break;
                    }
                    writer.write((char) c);
                }
                return writer.toCharArray();
            }
        };
        closeable = stdinReader;
    } else {
        valueSupplier = s -> terminal.readSecret("Enter value for " + s + ": ");
        closeable = () -> {
        };
    }
    try (Closeable ignored = closeable) {
        for (final String setting : settings) {
            if (keyStore.getSettingNames().contains(setting) && options.has(forceOption) == false) {
                if (terminal.promptYesNo("Setting " + setting + " already exists. Overwrite?", false) == false) {
                    terminal.println("Exiting without modifying keystore.");
                    return;
                }
            }
            try {
                keyStore.setString(setting, valueSupplier.apply(setting));
            } catch (final IllegalArgumentException e) {
                throw new UserException(ExitCodes.DATA_ERROR, e.getMessage());
            }
        }
    }
    keyStore.save(env.configDir(), getKeyStorePassword().getChars());
}
Also used : InputStreamReader(java.io.InputStreamReader) Closeable(java.io.Closeable) BufferedReader(java.io.BufferedReader) UserException(org.opensearch.cli.UserException) IOException(java.io.IOException) CharArrayWriter(java.io.CharArrayWriter)

Example 40 with UserException

use of org.opensearch.cli.UserException in project OpenSearch by opensearch-project.

the class EvilLoggerTests method testPrefixLogger.

public void testPrefixLogger() throws IOException, IllegalAccessException, UserException {
    setupLogging("prefix");
    final String prefix = randomAlphaOfLength(16);
    final Logger logger = new PrefixLogger(LogManager.getLogger("prefix_test"), prefix);
    logger.info("test");
    logger.info("{}", "test");
    final Exception e = new Exception("exception");
    logger.info(new ParameterizedMessage("{}", "test"), e);
    final String path = System.getProperty("opensearch.logs.base_path") + System.getProperty("file.separator") + System.getProperty("opensearch.logs.cluster_name") + ".log";
    final List<String> events = Files.readAllLines(PathUtils.get(path));
    final StringWriter sw = new StringWriter();
    final PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    final int stackTraceLength = sw.toString().split(System.getProperty("line.separator")).length;
    final int expectedLogLines = 3;
    assertThat(events.size(), equalTo(expectedLogLines + stackTraceLength));
    for (int i = 0; i < expectedLogLines; i++) {
        assertThat("Contents of [" + path + "] are wrong", events.get(i), startsWith("[" + getTestName() + "]" + prefix + " test"));
    }
}
Also used : StringWriter(java.io.StringWriter) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) Logger(org.apache.logging.log4j.Logger) UserException(org.opensearch.cli.UserException) IOException(java.io.IOException) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) PrintWriter(java.io.PrintWriter)

Aggregations

UserException (org.opensearch.cli.UserException)76 Path (java.nio.file.Path)44 Matchers.containsString (org.hamcrest.Matchers.containsString)38 Environment (org.opensearch.env.Environment)29 Matchers.hasToString (org.hamcrest.Matchers.hasToString)25 TestEnvironment (org.opensearch.env.TestEnvironment)25 IOException (java.io.IOException)16 Settings (org.opensearch.common.settings.Settings)16 ArrayList (java.util.ArrayList)12 BufferedReader (java.io.BufferedReader)11 Files (java.nio.file.Files)11 MockTerminal (org.opensearch.cli.MockTerminal)11 OpenSearchTestCase (org.opensearch.test.OpenSearchTestCase)11 InputStream (java.io.InputStream)10 List (java.util.List)10 Collectors (java.util.stream.Collectors)10 Terminal (org.opensearch.cli.Terminal)10 Tuple (org.opensearch.common.collect.Tuple)10 StringReader (java.io.StringReader)9 URL (java.net.URL)9