Internal: Update signatures for EnvironmentAwareCommand (elastic/elasticsearch#4367)

This is the xplugins side of elastic/elasticsearchelastic/elasticsearch#22175

Original commit: elastic/x-pack-elasticsearch@4359cb1947
This commit is contained in:
Ryan Ernst 2016-12-19 15:23:53 -08:00 committed by GitHub
parent adf22c3d24
commit 789df7d2fa
11 changed files with 52 additions and 68 deletions

View File

@ -11,7 +11,7 @@ import org.apache.lucene.util.IOUtils;
import org.elasticsearch.SpecialPermission;
import org.elasticsearch.bootstrap.JarHell;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.io.FileSystemUtils;
@ -66,7 +66,7 @@ import static org.elasticsearch.xpack.XPackPlugin.resolveXPackExtensionsFile;
* <li>If the extension contains extra security permissions, the policy file is validated</li>
* </ul>
*/
final class InstallXPackExtensionCommand extends SettingCommand {
final class InstallXPackExtensionCommand extends EnvironmentAwareCommand {
private final OptionSpec<Void> batchOption;
private final OptionSpec<String> arguments;
@ -79,7 +79,7 @@ final class InstallXPackExtensionCommand extends SettingCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
// TODO: in jopt-simple 5.0 we can enforce a min/max number of positional args
List<String> args = arguments.values(options);
if (args.size() != 1) {
@ -87,13 +87,12 @@ final class InstallXPackExtensionCommand extends SettingCommand {
}
String extensionURL = args.get(0);
boolean isBatch = options.has(batchOption) || System.console() == null;
execute(terminal, extensionURL, isBatch, settings);
execute(terminal, extensionURL, isBatch, env);
}
// pkg private for testing
void execute(Terminal terminal, String extensionId, boolean isBatch, Map<String, String> properties) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, properties);
void execute(Terminal terminal, String extensionId, boolean isBatch, Environment env) throws Exception {
if (Files.exists(resolveXPackExtensionsFile(env)) == false) {
terminal.println("xpack extensions directory [" + resolveXPackExtensionsFile(env) + "] does not exist. Creating...");
Files.createDirectories(resolveXPackExtensionsFile(env));

View File

@ -6,7 +6,7 @@
package org.elasticsearch.xpack.extensions;
import joptsimple.OptionSet;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.env.Environment;
@ -27,15 +27,14 @@ import static org.elasticsearch.xpack.XPackPlugin.resolveXPackExtensionsFile;
/**
* A command for the extension cli to list extensions installed in x-pack.
*/
class ListXPackExtensionCommand extends SettingCommand {
class ListXPackExtensionCommand extends EnvironmentAwareCommand {
ListXPackExtensionCommand() {
super("Lists installed x-pack extensions");
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
if (Files.exists(resolveXPackExtensionsFile(env)) == false) {
throw new IOException("Extensions directory missing: " + resolveXPackExtensionsFile(env));
}

View File

@ -9,7 +9,7 @@ import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.Strings;
@ -30,7 +30,7 @@ import static org.elasticsearch.xpack.XPackPlugin.resolveXPackExtensionsFile;
/**
* A command for the extension cli to remove an extension from x-pack.
*/
class RemoveXPackExtensionCommand extends SettingCommand {
class RemoveXPackExtensionCommand extends EnvironmentAwareCommand {
private final OptionSpec<String> arguments;
RemoveXPackExtensionCommand() {
@ -39,21 +39,20 @@ class RemoveXPackExtensionCommand extends SettingCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
// TODO: in jopt-simple 5.0 we can enforce a min/max number of positional args
List<String> args = arguments.values(options);
if (args.size() != 1) {
throw new UserException(ExitCodes.USAGE, "Must supply a single extension id argument");
}
execute(terminal, args.get(0), settings);
execute(terminal, args.get(0), env);
}
// pkg private for testing
void execute(Terminal terminal, String extensionName, Map<String, String> settings) throws Exception {
void execute(Terminal terminal, String extensionName, Environment env) throws Exception {
terminal.println("-> Removing " + Strings.coalesceToEmpty(extensionName) + "...");
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
Path extensionDir = resolveXPackExtensionsFile(env).resolve(extensionName);
if (Files.exists(extensionDir) == false) {
throw new UserException(ExitCodes.USAGE,

View File

@ -22,7 +22,7 @@ import org.apache.logging.log4j.core.config.LoggerConfig;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.cli.MultiCommand;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.Terminal.Verbosity;
import org.elasticsearch.common.Nullable;
@ -80,7 +80,7 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
}
/** Command to migrate users and roles to the native realm */
public static class MigrateUserOrRoles extends SettingCommand {
public static class MigrateUserOrRoles extends EnvironmentAwareCommand {
private final OptionSpec<String> username;
private final OptionSpec<String> password;
@ -121,14 +121,10 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
// Visible for testing
@Override
public void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
public void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
terminal.println("starting migration of users and roles...");
Settings.Builder sb = Settings.builder();
sb.put(settings);
Settings shieldSettings = sb.build();
Environment shieldEnv = new Environment(shieldSettings);
importUsers(terminal, shieldSettings, shieldEnv, options);
importRoles(terminal, shieldSettings, shieldEnv, options);
importUsers(terminal, env, options);
importRoles(terminal, env, options);
terminal.println("users and roles imported.");
}
@ -231,7 +227,7 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
return builder.string();
}
void importUsers(Terminal terminal, Settings settings, Environment env, OptionSet options) throws FileNotFoundException {
void importUsers(Terminal terminal, Environment env, OptionSet options) throws FileNotFoundException {
String usersCsv = usersToMigrateCsv.value(options);
String[] usersToMigrate = (usersCsv != null) ? usersCsv.split(",") : Strings.EMPTY_ARRAY;
Path usersFile = FileUserPasswdStore.resolveFile(env);
@ -244,11 +240,11 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
terminal.println("importing users from [" + usersFile + "]...");
final Logger logger = getTerminalLogger(terminal);
Map<String, char[]> userToHashedPW = FileUserPasswdStore.parseFile(usersFile, logger, settings);
Map<String, char[]> userToHashedPW = FileUserPasswdStore.parseFile(usersFile, logger, env.settings());
Map<String, String[]> userToRoles = FileUserRolesStore.parseFile(usersRolesFile, logger);
Set<String> existingUsers;
try {
existingUsers = getUsersThatExist(terminal, settings, env, options);
existingUsers = getUsersThatExist(terminal, env.settings(), env, options);
} catch (Exception e) {
throw new ElasticsearchException("failed to get users that already exist, skipping user import", e);
}
@ -267,7 +263,7 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
String reqBody = "n/a";
try {
reqBody = createUserJson(userToRoles.get(user), userToHashedPW.get(user));
String resp = postURL(settings, env, "POST",
String resp = postURL(env.settings(), env, "POST",
this.url.value(options) + "/_xpack/security/user/" + user, options, reqBody);
terminal.println(resp);
} catch (Exception e) {
@ -303,7 +299,7 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
return builder.string();
}
void importRoles(Terminal terminal, Settings settings, Environment env, OptionSet options) throws FileNotFoundException {
void importRoles(Terminal terminal, Environment env, OptionSet options) throws FileNotFoundException {
String rolesCsv = rolesToMigrateCsv.value(options);
String[] rolesToMigrate = (rolesCsv != null) ? rolesCsv.split(",") : Strings.EMPTY_ARRAY;
Path rolesFile = FileRolesStore.resolveFile(env).toAbsolutePath();
@ -312,10 +308,10 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
}
terminal.println("importing roles from [" + rolesFile + "]...");
Logger logger = getTerminalLogger(terminal);
Map<String, RoleDescriptor> roles = FileRolesStore.parseRoleDescriptors(rolesFile, logger, true, settings);
Map<String, RoleDescriptor> roles = FileRolesStore.parseRoleDescriptors(rolesFile, logger, true, env.settings());
Set<String> existingRoles;
try {
existingRoles = getRolesThatExist(terminal, settings, env, options);
existingRoles = getRolesThatExist(terminal, env.settings(), env, options);
} catch (Exception e) {
throw new ElasticsearchException("failed to get roles that already exist, skipping role import", e);
}
@ -334,7 +330,7 @@ public class ESNativeRealmMigrateTool extends MultiCommand {
String reqBody = "n/a";
try {
reqBody = createRoleJson(roles.get(roleName));;
String resp = postURL(settings, env, "POST",
String resp = postURL(env.settings(), env, "POST",
this.url.value(options) + "/_xpack/security/role/" + roleName, options, reqBody);
terminal.println(resp);
} catch (Exception e) {

View File

@ -9,7 +9,7 @@ import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.MultiCommand;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.Strings;
@ -55,7 +55,7 @@ public class UsersTool extends MultiCommand {
subcommands.put("list", new ListCommand());
}
static class AddUserCommand extends SettingCommand {
static class AddUserCommand extends EnvironmentAwareCommand {
private final OptionSpec<String> passwordOption;
private final OptionSpec<String> rolesOption;
@ -84,8 +84,7 @@ public class UsersTool extends MultiCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
String username = parseUsername(arguments.values(options), env.settings());
final boolean allowReserved = XPackSettings.RESERVED_REALM_ENABLED_SETTING.get(env.settings()) == false;
@ -119,7 +118,7 @@ public class UsersTool extends MultiCommand {
}
}
static class DeleteUserCommand extends SettingCommand {
static class DeleteUserCommand extends EnvironmentAwareCommand {
private final OptionSpec<String> arguments;
@ -140,8 +139,7 @@ public class UsersTool extends MultiCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
String username = parseUsername(arguments.values(options), env.settings());
Path passwordFile = FileUserPasswdStore.resolveFile(env);
Path rolesFile = FileUserRolesStore.resolveFile(env);
@ -170,7 +168,7 @@ public class UsersTool extends MultiCommand {
}
}
static class PasswordCommand extends SettingCommand {
static class PasswordCommand extends EnvironmentAwareCommand {
private final OptionSpec<String> passwordOption;
private final OptionSpec<String> arguments;
@ -195,8 +193,7 @@ public class UsersTool extends MultiCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
String username = parseUsername(arguments.values(options), env.settings());
char[] password = parsePassword(terminal, passwordOption.value(options));
@ -213,7 +210,7 @@ public class UsersTool extends MultiCommand {
}
}
static class RolesCommand extends SettingCommand {
static class RolesCommand extends EnvironmentAwareCommand {
private final OptionSpec<String> addOption;
private final OptionSpec<String> removeOption;
@ -239,8 +236,7 @@ public class UsersTool extends MultiCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
String username = parseUsername(arguments.values(options), env.settings());
String[] addRoles = parseRoles(terminal, env, addOption.value(options));
String[] removeRoles = parseRoles(terminal, env, removeOption.value(options));
@ -283,7 +279,7 @@ public class UsersTool extends MultiCommand {
}
}
static class ListCommand extends SettingCommand {
static class ListCommand extends EnvironmentAwareCommand {
private final OptionSpec<String> arguments;
@ -299,12 +295,11 @@ public class UsersTool extends MultiCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
String username = null;
if (options.has(arguments)) {
username = arguments.value(options);
}
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
listUsersAndRoles(terminal, env, username);
}
}

View File

@ -8,7 +8,7 @@ package org.elasticsearch.xpack.security.crypto.tool;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.elasticsearch.cli.ExitCodes;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.cli.UserException;
import org.elasticsearch.common.SuppressForbidden;
@ -29,7 +29,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
public class SystemKeyTool extends SettingCommand {
public class SystemKeyTool extends EnvironmentAwareCommand {
private final OptionSpec<String> arguments;
@ -54,11 +54,9 @@ public class SystemKeyTool extends SettingCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
final Path keyPath;
final Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
if (options.hasArgument(arguments)) {
List<String> args = arguments.values(options);
if (args.size() > 1) {

View File

@ -15,7 +15,7 @@ import org.bouncycastle.openssl.jcajce.JcaPEMWriter;
import org.bouncycastle.openssl.jcajce.JcePEMEncryptorBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.cli.SettingCommand;
import org.elasticsearch.cli.EnvironmentAwareCommand;
import org.elasticsearch.cli.Terminal;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher;
@ -64,7 +64,7 @@ import java.util.zip.ZipOutputStream;
/**
* CLI tool to make generation of certificates or certificate requests easier for users
*/
public class CertificateTool extends SettingCommand {
public class CertificateTool extends EnvironmentAwareCommand {
private static final String AUTO_GEN_CA_DN = "CN=Elastic Certificate Tool Autogenerated CA";
private static final String DESCRIPTION = "Simplifies certificate creation for use with the Elastic Stack";
@ -128,8 +128,7 @@ public class CertificateTool extends SettingCommand {
}
@Override
protected void execute(Terminal terminal, OptionSet options, Map<String, String> settings) throws Exception {
Environment env = InternalSettingsPreparer.prepareEnvironment(Settings.EMPTY, terminal, settings);
protected void execute(Terminal terminal, OptionSet options, Environment env) throws Exception {
final boolean csrOnly = options.has(csrSpec);
printIntro(terminal, csrOnly);
final Path outputFile = getOutputFile(terminal, outputPathSpec.value(options), env, csrOnly ? DEFAULT_CSR_FILE : DEFAULT_CERT_FILE);

View File

@ -88,10 +88,9 @@ public class InstallXPackExtensionCommandTests extends ESTestCase {
}
static MockTerminal installExtension(String extensionUrl, Path home) throws Exception {
Map<String, String> settings = new HashMap<>();
settings.put("path.home", home.toString());
Environment env = new Environment(Settings.builder().put("path.home", home).build());
MockTerminal terminal = new MockTerminal();
new InstallXPackExtensionCommand().execute(terminal, extensionUrl, true, settings);
new InstallXPackExtensionCommand().execute(terminal, extensionUrl, true, env);
return terminal;
}

View File

@ -39,10 +39,9 @@ public class RemoveXPackExtensionCommandTests extends ESTestCase {
}
static MockTerminal removeExtension(String name, Path home) throws Exception {
Map<String, String> settings = new HashMap<>();
settings.put("path.home", home.toString());
Environment env = new Environment(Settings.builder().put("path.home", home).build());
MockTerminal terminal = new MockTerminal();
new RemoveXPackExtensionCommand().execute(terminal, name, settings);
new RemoveXPackExtensionCommand().execute(terminal, name, env);
return terminal;
}

View File

@ -113,16 +113,16 @@ public class ESNativeRealmMigrateToolTests extends CommandTestCase {
MockTerminal mockTerminal = new MockTerminal();
FileNotFoundException fnfe = expectThrows(FileNotFoundException.class,
() -> muor.importUsers(mockTerminal, settings, environment, options));
() -> muor.importUsers(mockTerminal, environment, options));
assertThat(fnfe.getMessage(), containsString("users file"));
Files.createFile(xpackConfDir.resolve("users"));
fnfe = expectThrows(FileNotFoundException.class,
() -> muor.importUsers(mockTerminal, settings, environment, options));
() -> muor.importUsers(mockTerminal, environment, options));
assertThat(fnfe.getMessage(), containsString("users_roles file"));
fnfe = expectThrows(FileNotFoundException.class,
() -> muor.importRoles(mockTerminal, settings, environment, options));
() -> muor.importRoles(mockTerminal, environment, options));
assertThat(fnfe.getMessage(), containsString("roles.yml file"));
}
}

View File

@ -15,6 +15,7 @@ import org.elasticsearch.common.Priority;
import org.elasticsearch.common.io.PathUtils;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.env.Environment;
import org.elasticsearch.xpack.security.action.role.GetRolesResponse;
import org.elasticsearch.xpack.security.action.user.GetUsersResponse;
import org.elasticsearch.xpack.security.action.user.PutUserResponse;
@ -59,7 +60,7 @@ public class MigrateToolIT extends MigrateToolTestCase {
ESNativeRealmMigrateTool.MigrateUserOrRoles muor = new ESNativeRealmMigrateTool.MigrateUserOrRoles();
OptionParser parser = muor.getParser();
OptionSet options = parser.parse("-u", "test_admin", "-p", "changeme", "-U", url);
muor.execute(t, options, settings.getAsMap());
muor.execute(t, options, new Environment(settings));
logger.info("--> output:\n{}", t.getOutput());