Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HDDS-12012. Defer ozone repair prompt after subcommand validation #7653

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.StringWriter;
Expand All @@ -34,6 +35,7 @@

import com.google.common.base.Preconditions;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.input.CharSequenceInputStream;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
Expand Down Expand Up @@ -440,6 +442,19 @@ public SystemOutCapturer() {
}
}

/**
* Replaces {@link System#in} with a stream that provides {@code lines} as input.
* @return an {@code AutoCloseable} to restore the original {@link System#in} stream
*/
public static AutoCloseable supplyOnSystemIn(String... lines) {
final InputStream original = System.in;
final InputStream in = CharSequenceInputStream.builder()
.setCharSequence(String.join("\n", lines))
.get();
System.setIn(in);
return () -> System.setIn(original);
}

/**
* Prints output to one {@link PrintStream} while copying to the other.
* <p>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ozone.test;

import java.util.function.IntSupplier;

/** Test utilities for working with lambdas returning int value. */
public interface IntLambda {

static ToIntExecutable withTextFromSystemIn(String... lines) {
return runnable -> {
try (AutoCloseable ignored = GenericTestUtils.supplyOnSystemIn(lines)) {
return runnable.getAsInt();
} catch (RuntimeException e) {
throw e;
Comment on lines +29 to +30
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can remove this catch block as we are not doing anything with the caught exception other than throwing it again.

Copy link
Contributor Author

@adoroszlai adoroszlai Jan 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nandakumar131 The goal of this catch block is to avoid wrapping RuntimeException in RuntimeException in the following block:

} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}

} catch (Exception e) {
throw new RuntimeException(e);
}
};
}

/** Function that takes a block of code returning int, executes it, and returns the value. */
@FunctionalInterface
interface ToIntExecutable {
int execute(IntSupplier code);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import static org.apache.hadoop.ozone.OzoneConsts.OM_DB_NAME;
import static org.apache.hadoop.ozone.OzoneConsts.OZONE_OFS_URI_SCHEME;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
import static org.apache.ozone.test.IntLambda.withTextFromSystemIn;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
Expand Down Expand Up @@ -350,7 +351,8 @@ private int execute(boolean dryRun, String... args) {
}
argList.addAll(Arrays.asList(args));

return cmd.execute(argList.toArray(new String[0]));
return withTextFromSystemIn("y")
.execute(() -> cmd.execute(argList.toArray(new String[0])));
}

private <K, V> int countTableEntries(Table<K, V> table) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

import static org.apache.hadoop.ozone.OzoneConsts.OM_DB_NAME;
import static org.apache.hadoop.ozone.om.OMConfigKeys.OZONE_OM_ADDRESS_KEY;
import static org.apache.ozone.test.IntLambda.withTextFromSystemIn;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

Expand Down Expand Up @@ -89,7 +90,11 @@ public void testUpdateTransactionInfoTable() throws Exception {

String testTerm = "1111";
String testIndex = "1111";
int exitCode = cmd.execute("om", "update-transaction", "--db", dbPath, "--term", testTerm, "--index", testIndex);
int exitCode = withTextFromSystemIn("y")
.execute(() -> cmd.execute("om", "update-transaction",
"--db", dbPath,
"--term", testTerm,
"--index", testIndex));
assertEquals(0, exitCode, err);
assertThat(out.get())
.contains(
Expand All @@ -101,8 +106,11 @@ public void testUpdateTransactionInfoTable() throws Exception {
String cmdOut2 = scanTransactionInfoTable(dbPath);
assertThat(cmdOut2).contains(testTerm + "#" + testIndex);

cmd.execute("om", "update-transaction", "--db", dbPath, "--term",
originalHighestTermIndex[0], "--index", originalHighestTermIndex[1]);
withTextFromSystemIn("y")
.execute(() -> cmd.execute("om", "update-transaction",
"--db", dbPath,
"--term", originalHighestTermIndex[0],
"--index", originalHighestTermIndex[1]));
cluster.getOzoneManager().restart();
try (OzoneClient ozoneClient = cluster.newClient()) {
ozoneClient.getObjectStore().createVolume("vol1");
Expand Down Expand Up @@ -130,8 +138,11 @@ public void testQuotaRepair() throws Exception {

int exitCode = cmd.execute("om", "quota", "status", "--service-host", conf.get(OZONE_OM_ADDRESS_KEY));
assertEquals(0, exitCode, err);
exitCode = cmd.execute("om", "quota", "start", "--service-host", conf.get(OZONE_OM_ADDRESS_KEY));

exitCode = withTextFromSystemIn("y")
.execute(() -> cmd.execute("om", "quota", "start", "--service-host", conf.get(OZONE_OM_ADDRESS_KEY)));
assertEquals(0, exitCode, err);

GenericTestUtils.waitFor(() -> {
out.reset();
// verify quota trigger is completed having non-zero lastRunFinishedTime
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,6 @@
import org.apache.hadoop.hdds.cli.RepairSubcommand;
import picocli.CommandLine;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

/**
* Ozone Repair Command line tool.
*/
Expand All @@ -37,39 +34,10 @@
mixinStandardHelpOptions = true)
public class OzoneRepair extends GenericCli implements ExtensibleParentCommand {

public static final String WARNING_SYS_USER_MESSAGE =
"ATTENTION: Running as user %s. Make sure this is the same user used to run the Ozone process." +
" Are you sure you want to continue (y/N)? ";

public static void main(String[] argv) {
new OzoneRepair().run(argv);
}

@Override
public int execute(String[] argv) {
if (argv.length == 0 || argv[0].equals("--help") || argv[0].equals("-h")) {
return super.execute(argv);
}

String currentUser = getSystemUserName();
if (!("y".equalsIgnoreCase(getConsoleReadLineWithFormat(currentUser)))) {
System.out.println("Aborting command.");
return 1;
}
System.out.println("Run as user: " + currentUser);

return super.execute(argv);
}

public String getSystemUserName() {
return System.getProperty("user.name");
}

public String getConsoleReadLineWithFormat(String currentUser) {
System.err.printf(WARNING_SYS_USER_MESSAGE, currentUser);
return (new Scanner(System.in, StandardCharsets.UTF_8.name())).nextLine().trim();
}

@Override
public Class<?> subcommandType() {
return RepairSubcommand.class;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,17 @@
import picocli.CommandLine;

import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
import java.util.concurrent.Callable;

/** Parent class for all actionable repair commands. */
public abstract class RepairTool extends AbstractSubcommand implements Callable<Void> {

private static final String WARNING_SYS_USER_MESSAGE =
"ATTENTION: Running as user %s. Make sure this is the same user used to run the Ozone process." +
" Are you sure you want to continue (y/N)? ";

@CommandLine.Option(names = {"--force"},
description = "Use this flag if you want to bypass the check in false-positive cases.")
private boolean force;
Expand All @@ -35,6 +41,7 @@ public abstract class RepairTool extends AbstractSubcommand implements Callable<

@Override
public final Void call() throws Exception {
confirmUser();
execute();
return null;
}
Expand Down Expand Up @@ -84,4 +91,25 @@ private String formatMessage(String msg, Object[] args) {
return msg;
}

protected void confirmUser() {
final String currentUser = getSystemUserName();
final boolean confirmed = "y".equalsIgnoreCase(getConsoleReadLineWithFormat(currentUser));

if (!confirmed) {
throw new IllegalStateException("Aborting command.");
}

info("Run as user: " + currentUser);
}

private String getSystemUserName() {
return System.getProperty("user.name");
}

private String getConsoleReadLineWithFormat(String currentUser) {
err().printf(WARNING_SYS_USER_MESSAGE, currentUser);
return new Scanner(System.in, StandardCharsets.UTF_8.name())
.nextLine()
.trim();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,20 @@
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import picocli.CommandLine;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

/**
* Tests the ozone repair command.
Expand Down Expand Up @@ -67,9 +73,9 @@ void testOzoneRepairWhenUserIsRemindedSystemUserAndDeclinesToProceed() throws Ex
OzoneRepair ozoneRepair = new OzoneRepair();
System.setIn(new ByteArrayInputStream("N".getBytes(DEFAULT_ENCODING)));

int res = ozoneRepair.execute(new String[]{"om", "fso-tree"});
assertEquals(1, res);
assertThat(out.toString(DEFAULT_ENCODING)).contains("Aborting command.");
int res = ozoneRepair.execute(new String[]{"om", "fso-tree", "--db", "/dev/null"});
assertThat(res).isNotEqualTo(CommandLine.ExitCode.OK);
assertThat(err.toString(DEFAULT_ENCODING)).contains("Aborting command.");
// prompt should contain the current user name as well
assertThat(err.toString(DEFAULT_ENCODING)).contains("ATTENTION: Running as user " + OZONE_USER);
}
Expand All @@ -79,30 +85,30 @@ void testOzoneRepairWhenUserIsRemindedSystemUserAndAgreesToProceed() throws Exce
OzoneRepair ozoneRepair = new OzoneRepair();
System.setIn(new ByteArrayInputStream("y".getBytes(DEFAULT_ENCODING)));

ozoneRepair.execute(new String[]{"om", "fso-tree"});
ozoneRepair.execute(new String[]{"om", "fso-tree", "--db", "/dev/null"});
assertThat(out.toString(DEFAULT_ENCODING)).contains("Run as user: " + OZONE_USER);
// prompt should contain the current user name as well
assertThat(err.toString(DEFAULT_ENCODING)).contains("ATTENTION: Running as user " + OZONE_USER);
}

@Test
void testOzoneRepairSkipsPromptWhenNoSubcommandProvided() throws Exception {
OzoneRepair ozoneRepair = new OzoneRepair();

// when no argument is passed, prompt should not be displayed
ozoneRepair.execute(new String[]{});
assertThat(err.toString(DEFAULT_ENCODING)).doesNotContain("ATTENTION: Running as user " + OZONE_USER);
/** Arguments for which confirmation prompt should not be displayed. */
static List<List<String>> skipPromptParams() {
return asList(
emptyList(),
singletonList("om"),
asList("om", "fso-tree"),
asList("om", "fso-tree", "-h"),
asList("om", "fso-tree", "--help")
);
}

@Test
void testOzoneRepairSkipsPromptWhenHelpFlagProvided() throws Exception {
@ParameterizedTest
@MethodSource("skipPromptParams")
void testSkipsPrompt(List<String> args) throws Exception {
OzoneRepair ozoneRepair = new OzoneRepair();

// when --help or -h flag is passed, prompt should not be displayed
ozoneRepair.execute(new String[]{"--help"});
assertThat(err.toString(DEFAULT_ENCODING)).doesNotContain("ATTENTION: Running as user " + OZONE_USER);
ozoneRepair.execute(args.toArray(new String[0]));

ozoneRepair.execute(new String[]{"-h"});
assertThat(err.toString(DEFAULT_ENCODING)).doesNotContain("ATTENTION: Running as user " + OZONE_USER);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.rocksdb.RocksDBException;
import picocli.CommandLine;

import static org.apache.ozone.test.IntLambda.withTextFromSystemIn;
import static org.apache.hadoop.ozone.OzoneConsts.TRANSACTION_INFO_KEY;
import static org.apache.hadoop.ozone.om.OmMetadataManagerImpl.TRANSACTION_INFO_TABLE;
import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -125,12 +126,14 @@ private void testCommand(ManagedRocksDB mdb, ColumnFamilyHandle columnFamilyHand
.thenReturn(transactionInfo2);

CommandLine cli = new OzoneRepair().getCmd();
cli.execute(
"om",
"update-transaction",
"--db", DB_PATH,
"--term", String.valueOf(TEST_TERM),
"--index", String.valueOf(TEST_INDEX));
withTextFromSystemIn("y")
adoroszlai marked this conversation as resolved.
Show resolved Hide resolved
.execute(() -> cli.execute(
"om",
"update-transaction",
"--db", DB_PATH,
"--term", String.valueOf(TEST_TERM),
"--index", String.valueOf(TEST_INDEX)
));
}
}

Expand Down
Loading