8000 fix: refining arg handling by shawkins · Pull Request #44579 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
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
8000

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import java.io.File;
import java.io.FilenameFilter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
Expand Down Expand Up @@ -119,7 +120,7 @@ public static void forceDevProfile() {
public static Map<String, File> getProviderFiles() {
Path providersPath = Environment.getProvidersPath().orElse(null);

if (providersPath == null) {
if (providersPath == null || !Files.exists(providersPath)) {
return Collections.emptyMap();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

package org.keycloak.quarkus.runtime;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ForkJoinPool;

Expand All @@ -27,7 +26,6 @@
import org.keycloak.infinispan.util.InfinispanUtils;
import org.keycloak.quarkus.runtime.cli.ExecutionExceptionHandler;
import org.keycloak.quarkus.runtime.cli.Picocli;
import org.keycloak.quarkus.runtime.cli.PropertyException;
import org.keycloak.quarkus.runtime.cli.command.AbstractNonServerCommand;
import org.keycloak.quarkus.runtime.cli.command.DryRunMixin;
import org.keycloak.quarkus.runtime.configuration.PersistedConfigSource;
Expand Down Expand Up @@ -80,24 +78,12 @@ public void exit(int exitCode) {
}

public static void main(String[] args, Picocli picocli) {
List<String> cliArgs = null;
try {
cliArgs = Picocli.parseArgs(args);
} catch (PropertyException e) {
picocli.usageException(e.getMessage(), e.getCause());
return;
}
List<String> cliArgs = List.of(args.length == 0 ? new String[] {"-h"} : args);

if (DryRunMixin.isDryRunBuild() && (cliArgs.contains(DryRunMixin.DRYRUN_OPTION_LONG) || Boolean.valueOf(System.getenv().get(DryRunMixin.KC_DRY_RUN_ENV)))) {
PersistedConfigSource.getInstance().useDryRunProperties();
}

if (cliArgs.isEmpty()) {
cliArgs = new ArrayList<>(cliArgs);
// default to show help message
cliArgs.add("-h");
}

// parse arguments and execute any of the configured commands
picocli.parseAndRun(cliArgs);
}
Expand Down
10000
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ private record IncludeOptions(boolean includeRuntime, boolean includeBuildTime,

private Ansi colorMode = hasColorSupport() ? Ansi.ON : Ansi.OFF;
private IncludeOptions options;
private Set<String> duplicatedOptionsNames = new HashSet<String>();

public static boolean hasColorSupport() {
return QuarkusConsole.hasColorSupport();
Expand Down Expand Up @@ -139,31 +140,37 @@ public void parseAndRun(List<String> cliArgs) {
} else {
currentCommand = null;
}

// any unrecognized args can now be normalized to our property mapper based argument expectations
Map<String, String> normalizedArgs = new LinkedHashMap<String, String>();
List<String> unknown = new ArrayList<String>();
ConfigArgsConfigSource.parseConfigArgs(unrecognizedArgs, (k, v) -> {
if (normalizedArgs.put(k, v) != null) {
duplicatedOptionsNames.add(k);
}
}, unknown::add);
unrecognizedArgs = null;

ConfigArgsConfigSource.setCliArgs(normalizedArgs.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).toArray(String[]::new));

initConfig(currentCommand);

if (!unrecognizedArgs.isEmpty() && options.allowUnrecognized) {
// TODO: further refactor this as these args should be the source for ConfigArgsConfigSource
unrecognizedArgs.removeIf(arg -> {
boolean hasArg = false;
if (arg.contains("=")) {
arg = arg.substring(0, arg.indexOf("="));
hasArg = true;
}
PropertyMapper<?> mapper = PropertyMappers.getMapperByCliKey(arg);
if (mapper != null) {
if (!hasArg) {
addCommandOptions(cl, currentCommand);
throw new MissingParameterException(cl, cl.getCommandSpec().optionsMap().get(arg), null);
}
return true;
}
return false;
});
// now that the property mappers are properly initalized further refine the args
if (options.allowUnrecognized) {
normalizedArgs.keySet().removeIf(arg -> PropertyMappers.getMapperByCliKey(arg) != null || arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX));
}

if (!unrecognizedArgs.isEmpty()) {
unknown.forEach(arg -> {
if (PropertyMappers.getMapperByCliKey(arg) != null) {
addCommandOptions(cl, currentCommand);
throw new MissingParameterException(cl, cl.getCommandSpec().optionsMap().get(arg), null);
} else if (arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX)) {
throw new PropertyException(format("spi argument %s requires a value.", arg));
}
});
unknown.addAll(normalizedArgs.keySet());
if (!unknown.isEmpty()) {
addCommandOptions(cl, currentCommand);
throw new KcUnmatchedArgumentException(cl, unrecognizedArgs);
throw new KcUnmatchedArgumentException(cl, unknown);
}

if (isHelpRequested(result)) {
Expand Down Expand Up @@ -823,33 +830,6 @@ public void println(String message) {
getOutWriter().println(message);
}

public static List<String> parseArgs(String[] rawArgs) throws PropertyException {
if (rawArgs.length == 0) {
return List.of();
}

// makes sure cli args are available to the config source
ConfigArgsConfigSource.setCliArgs(rawArgs);

// TODO: ignore properties for providers for now, need to fetch them from the providers, otherwise CLI will complain about invalid options
// also ignores system properties as they are set when starting the JVM
// change this once we are able to obtain properties from providers
List<String> args = new ArrayList<>();
ConfigArgsConfigSource.parseConfigArgs(List.of(rawArgs), (arg, value) -> {
if (!arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX) && !arg.startsWith("-D")) {
args.add(arg + "=" + value);
}
}, arg -> {
if (arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX)) {
throw new PropertyException(format("spi argument %s requires a value.", arg));
}
if (!arg.startsWith("-D")) {
args.add(arg);
}
});
return args;
}

public void checkChangesInBuildOptionsDuringAutoBuild(PrintWriter out) {
StringBuilder options = new StringBuilder();

Expand Down Expand Up @@ -913,6 +893,7 @@ public void start() {
}

public void build() throws Throwable {
Environment.setRebuild();
QuarkusEntryPoint.main();
}

Expand All @@ -923,10 +904,8 @@ public void initConfig(AbstractCommand command) {
this.parsedCommand = Optional.ofNullable(command);
options = getIncludeOptions(command);

if (!Environment.isRebuilt() && command instanceof AbstractAutoBuildCommand
&& !command.isOptimized()) {
Environment.setRebuildCheck(true);
}
Environment.setRebuildCheck(!Environment.isRebuilt() && command instanceof AbstractAutoBuildCommand
&& !command.isOptimized());

String profile = Optional.ofNullable(org.keycloak.common.util.Environment.getProfile())
.or(() -> parsedCommand.map(AbstractCommand::getInitProfile)).orElse(Environment.PROD_PROFILE_VALUE);
Expand All @@ -939,10 +918,8 @@ public void initConfig(AbstractCommand command) {

// Show warning about duplicated options in CLI
public void warnOnDuplicatedOptionsInCli() {
var duplicatedOptionsNames = ConfigArgsConfigSource.getDuplicatedArgNames();
if (!duplicatedOptionsNames.isEmpty()) {
warn("Duplicated options present in CLI: %s".formatted(String.join(", ", duplicatedOptionsNames)));
ConfigArgsConfigSource.clearDuplicatedArgNames();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,26 +17,19 @@

package org.keycloak.quarkus.runtime.cli.command;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.quarkus.runtime.cli.Picocli;
import org.keycloak.quarkus.runtime.configuration.ConfigArgsConfigSource;
import org.keycloak.quarkus.runtime.configuration.Configuration;
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper;
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers;

import picocli.CommandLine;

import static org.keycloak.quarkus.runtime.Environment.isDevMode;
import static org.keycloak.quarkus.runtime.Environment.isDevProfile;
import static org.keycloak.quarkus.runtime.Environment.isRebuildCheck;
import static org.keycloak.quarkus.runtime.configuration.ConfigArgsConfigSource.parseConfigArgs;
import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.maskValue;

public abstract class AbstractAutoBuildCommand extends AbstractCommand {

Expand Down Expand Up @@ -94,7 +87,7 @@ private void runReAugmentation() {
directBuild();

if(!isDevMode()) {
spec.commandLine().getOut().printf("Next time you run the server, just run:%n%n\t%s %s %s%n%n", Environment.getCommand(), String.join(" ", getSanitizedRuntimeCliOptions()), OPTIMIZED_BUILD_OPTION_LONG);
spec.commandLine().getOut().printf("Next time you run the server, just add %s to the command to ensure this build is used.\n", OPTIMIZED_BUILD_OPTION_LONG);
}
}

Expand All @@ -106,26 +99,6 @@ void directBuild() {
build.runCommand();
}

/**
* checks the raw cli input for possible credentials / properties which should be masked,
* and masks them.
* @return a list of potentially masked properties in CLI format, e.g. `--db-password=*******`
* instead of the actual passwords value.
*/
private static List<String> getSanitizedRuntimeCliOptions() {
List<String> properties = new ArrayList<>();

parseConfigArgs(ConfigArgsConfigSource.getAllCliArgs(), (key, value) -> {
PropertyMapper<?> mapper = PropertyMappers.getMapperByCliKey(key);

if (mapper == null || mapper.isRunTime()) {
properties.add(key + "=" + maskValue(value, mapper));
}
}, properties::add);

return properties;
}

@Override
protected void runCommand() {
doBeforeRun();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,17 @@

package org.keycloak.quarkus.runtime.cli.command;

import java.util.Optional;

import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.quarkus.runtime.Messages;
import org.keycloak.quarkus.runtime.configuration.Configuration;
import org.keycloak.quarkus.runtime.configuration.IgnoredArtifacts;
import org.keycloak.quarkus.runtime.configuration.PersistedConfigSource;

import io.quarkus.bootstrap.runner.RunnerClassLoader;
import io.quarkus.runtime.LaunchMode;
import io.smallrye.config.ConfigValue;
import picocli.CommandLine;
import picocli.CommandLine.Command;

import static org.keycloak.config.ClassLoaderOptions.QUARKUS_REMOVED_ARTIFACTS_PROPERTY;
import static org.keycloak.config.DatabaseOptions.DB;
import static org.keycloak.quarkus.runtime.Environment.getHomePath;
import static org.keycloak.quarkus.runtime.Environment.isDevProfile;
Expand Down Expand Up @@ -59,6 +56,8 @@ public final class Build extends AbstractCommand {

public static final String NAME = "build";

public static final String QUARKUS_REMOVED_ARTIFACTS_PROPERTY = "quarkus.class-loading.removed-artifacts";

@CommandLine.Mixin
HelpAllMixin helpAllMixin;

Expand All @@ -70,17 +69,15 @@ protected void runCommand() {
checkProfileAndDb();

// validate before setting that we're rebuilding so that runtime options are still seen
// the validation and setting the artifacts to remove need to be done without the current persisted properties
PersistedConfigSource.getInstance().runWithDisabled(() -> {
validateConfig();
System.setProperty(QUARKUS_REMOVED_ARTIFACTS_PROPERTY, String.join(",", IgnoredArtifacts.getDefaultIgnoredArtifacts()));
return null;
});
Environment.setRebuild();

picocli.println("Updating the configuration and installing your custom providers, if any. Please wait.");

try {
configureBuildClassLoader();

beforeReaugmentationOnWindows();
if (!Boolean.TRUE.equals(dryRunMixin.dryRun)) {
picocli.build();
Expand All @@ -99,13 +96,6 @@ protected void runCommand() {
}
}

private static void configureBuildClassLoader() {
// ignored artifacts must be set prior to starting re-augmentation
Optional.ofNullable(Configuration.getNonPersistedConfigValue(QUARKUS_REMOVED_ARTIFACTS_PROPERTY))
.map(ConfigValue::getValue)
.ifPresent(s -> System.setProperty(QUARKUS_REMOVED_ARTIFACTS_PROPERTY, s));
}

private void checkProfileAndDb() {
if (Environment.isDevProfile()) {
String cmd = picocli.getParsedCommand().map(AbstractCommand::getName).orElse(getName());
Expand Down
Loading
0