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;
}
}
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);
}
}
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"));
}
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());
}
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"));
}
}
Aggregations