8000 fix: refining arg handling (#44579) · zivadler/keycloak@a4df602 · GitHub
[go: up one dir, main page]

Skip to content

Commit a4df602

Browse files
authored
fix: refining arg handling (keycloak#44579)
relying on picocli parsing as much as possible closes: keycloak#44578 Signed-off-by: Steve Hawkins <shawkins@redhat.com>
1 parent f09c906 commit a4df602

18 files changed

Lines changed: 94 additions & 241 deletions

File tree

‎quarkus/config-api/src/main/java/org/keycloak/config/ClassLoaderOptions.java‎

Lines changed: 0 additions & 12 deletions
This file was deleted.

‎quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/Environment.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
import java.io.File;
2121
import java.io.FilenameFilter;
22+
import java.nio.file.Files;
2223
import java.nio.file.Path;
2324
import java.nio.file.Paths;
2425
import java.util.Arrays;
@@ -119,7 +120,7 @@ public static void forceDevProfile() {
119120
public static Map<String, File> getProviderFiles() {
120121
Path providersPath = Environment.getProvidersPath().orElse(null);
121122

122-
if (providersPath == null) {
123+
if (providersPath == null || !Files.exists(providersPath)) {
123124
return Collections.emptyMap();
124125
}
125126

‎quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakMain.java‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

1818
package org.keycloak.quarkus.runtime;
1919

20-
import java.util.ArrayList;
2120
import java.util.List;
2221
import java.util.concurrent.ForkJoinPool;
2322

@@ -27,7 +26,6 @@
2726
import org.keycloak.infinispan.util.InfinispanUtils;
2827
import org.keycloak.quarkus.runtime.cli.ExecutionExceptionHandler;
2928
import org.keycloak.quarkus.runtime.cli.Picocli;
30-
import org.keycloak.quarkus.runtime.cli.PropertyException;
3129
import org.keycloak.quarkus.runtime.cli.command.AbstractNonServerCommand;
3230
import org.keycloak.quarkus.runtime.cli.command.DryRunMixin;
3331
import org.keycloak.quarkus.runtime.configuration.PersistedConfigSource;
@@ -80,24 +78,12 @@ public void exit(int exitCode) {
8078
}
8179

8280
public static void main(String[] args, Picocli picocli) {
83-
List<String> cliArgs = null;
84-
try {
85-
cliArgs = Picocli.parseArgs(args);
86-
} catch (PropertyException e) {
87-
picocli.usageException(e.getMessage(), e.getCause());
88-
return;
89-
}
81+
List<String> cliArgs = List.of(args.length == 0 ? new String[] {"-h"} : args);
9082

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

95-
if (cliArgs.isEmpty()) {
96-
cliArgs = new ArrayList<>(cliArgs);
97-
// default to show help message
98-
cliArgs.add("-h");
99-
}
100-
10187
// parse arguments and execute any of the configured commands
10288
picocli.parseAndRun(cliArgs);
10389
}

‎quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/Picocli.java‎

Lines changed: 31 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ private record IncludeOptions(boolean includeRuntime, boolean includeBuildTime,
103103

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

107108
public static boolean hasColorSupport() {
108109
return QuarkusConsole.hasColorSupport();
@@ -139,31 +140,37 @@ public void parseAndRun(List<String> cliArgs) {
139140
} else {
140141
currentCommand = null;
141142
}
143+
144+
// any unrecognized args can now be normalized to our property mapper based argument expectations
145+
Map<String, String> normalizedArgs = new LinkedHashMap<String, String>();
146+
List<String> unknown = new ArrayList<String>();
147+
ConfigArgsConfigSource.parseConfigArgs(unrecognizedArgs, (k, v) -> {
148+
if (normalizedArgs.put(k, v) != null) {
149+
duplicatedOptionsNames.add(k);
150+
}
151+
}, unknown::add);
152+
unrecognizedArgs = null;
153+
154+
ConfigArgsConfigSource.setCliArgs(normalizedArgs.entrySet().stream().map(e -> e.getKey() + "=" + e.getValue()).toArray(String[]::new));
155+
142156
initConfig(currentCommand);
143157

144-
if (!unrecognizedArgs.isEmpty() && options.allowUnrecognized) {
145-
// TODO: further refactor this as these args should be the source for ConfigArgsConfigSource
146-
unrecognizedArgs.removeIf(arg -> {
147-
boolean hasArg = false;
148-
if (arg.contains("=")) {
149-
arg = arg.substring(0, arg.indexOf("="));
150-
hasArg = true;
151-
}
152-
PropertyMapper<?> mapper = PropertyMappers.getMapperByCliKey(arg);
153-
if (mapper != null) {
154-
if (!hasArg) {
155-
addCommandOptions(cl, currentCommand);
156-
throw new MissingParameterException(cl, cl.getCommandSpec().optionsMap().get(arg), null);
157-
}
158-
return true;
159-
}
160-
return false;
161-
});
158+
// now that the property mappers are properly initalized further refine the args
159+
if (options.allowUnrecognized) {
160+
normalizedArgs.keySet().removeIf(arg -> PropertyMappers.getMapperByCliKey(arg) != null || arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX));
162161
}
163-
164-
if (!unrecognizedArgs.isEmpty()) {
162+
unknown.forEach(arg -> {
163+
if (PropertyMappers.getMapperByCliKey(arg) != null) {
164+
addCommandOptions(cl, currentCommand);
165+
throw new MissingParameterException(cl, cl.getCommandSpec().optionsMap().get(arg), null);
166+
} else if (arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX)) {
167+
throw new PropertyException(format("spi argument %s requires a value.", arg));
168+
}
169+
});
170+
unknown.addAll(normalizedArgs.keySet());
171+
if (!unknown.isEmpty()) {
165172
addCommandOptions(cl, currentCommand);
166-
throw new KcUnmatchedArgumentException(cl, unrecognizedArgs);
173+
throw new KcUnmatchedArgumentException(cl, unknown);
167174
}
168175

169176
if (isHelpRequested(result)) {
@@ -823,33 +830,6 @@ public void println(String message) {
823830
getOutWriter().println(message);
824831
}
825832

826-
public static List<String> parseArgs(String[] rawArgs) throws PropertyException {
827-
if (rawArgs.length == 0) {
828-
return List.of();
829-
}
830-
831-
// makes sure cli args are available to the config source
832-
ConfigArgsConfigSource.setCliArgs(rawArgs);
833-
834-
// TODO: ignore properties for providers for now, need to fetch them from the providers, otherwise CLI will complain about invalid options
835-
// also ignores system properties as they are set when starting the JVM
836-
// change this once we are able to obtain properties from providers
837-
List<String> args = new ArrayList<>();
838-
ConfigArgsConfigSource.parseConfigArgs(List.of(rawArgs), (arg, value) -> {
839-
if (!arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX) && !arg.startsWith("-D")) {
840-
args.add(arg + "=" + value);
841-
}
842-
}, arg -> {
843-
if (arg.startsWith(ConfigArgsConfigSource.SPI_OPTION_PREFIX)) {
844-
throw new PropertyException(format("spi argument %s requires a value.", arg));
845-
}
846-
if (!arg.startsWith("-D")) {
847-
args.add(arg);
848-
}
849-
});
850-
return args;
851-
}
852-
853833
public void checkChangesInBuildOptionsDuringAutoBuild(PrintWriter out) {
854834
StringBuilder options = new StringBuilder();
855835

@@ -913,6 +893,7 @@ public void start() {
913893
}
914894

915895
public void build() throws Throwable {
896+
Environment.setRebuild();
916897
QuarkusEntryPoint.main();
917898
}
918899

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

926-
if (!Environment.isRebuilt() && command instanceof AbstractAutoBuildCommand
927-
&& !command.isOptimized()) {
928-
Environment.setRebuildCheck(true);
929-
}
907+
Environment.setRebuildCheck(!Environment.isRebuilt() && command instanceof AbstractAutoBuildCommand
908+
&& !command.isOptimized());
930909

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

940919
// Show warning about duplicated options in CLI
941920
public void warnOnDuplicatedOptionsInCli() {
942-
var duplicatedOptionsNames = ConfigArgsConfigSource.getDuplicatedArgNames();
943921
if (!duplicatedOptionsNames.isEmpty()) {
944922
warn("Duplicated options present in CLI: %s".formatted(String.join(", ", duplicatedOptionsNames)));
945-
ConfigArgsConfigSource.clearDuplicatedArgNames();
946923
}
947924
}
948925

‎quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/AbstractAutoBuildCommand.java‎

Lines changed: 1 addition & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,19 @@
1717

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

20-
import java.util.ArrayList;
21-
import java.util.List;
2220
import java.util.Map;
2321
import java.util.Objects;
2422
import java.util.Optional;
2523

2624
import org.keycloak.quarkus.runtime.Environment;
2725
import org.keycloak.quarkus.runtime.cli.Picocli;
28-
import org.keycloak.quarkus.runtime.configuration.ConfigArgsConfigSource;
2926
import org.keycloak.quarkus.runtime.configuration.Configuration;
30-
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMapper;
31-
import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers;
3227

3328
import picocli.CommandLine;
3429

3530
import static org.keycloak.quarkus.runtime.Environment.isDevMode;
3631
import static org.keycloak.quarkus.runtime.Environment.isDevProfile;
3732
import static org.keycloak.quarkus.runtime.Environment.isRebuildCheck;
38-
import static org.keycloak.quarkus.runtime.configuration.ConfigArgsConfigSource.parseConfigArgs;
39-
import static org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers.maskValue;
4033

4134
public abstract class AbstractAutoBuildCommand extends AbstractCommand {
4235

@@ -94,7 +87,7 @@ private void runReAugmentation() {
9487
directBuild();
9588

9689
if(!isDevMode()) {
97-
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);
90+
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);
9891
}
9992
}
10093

@@ -106,26 +99,6 @@ void directBuild() {
10699
build.runCommand();
107100
}
108101

109-
/**
110-
* checks the raw cli input for possible credentials / properties which should be masked,
111-
* and masks them.
112-
* @return a list of potentially masked properties in CLI format, e.g. `--db-password=*******`
113-
* instead of the actual passwords value.
114-
*/
115-
private static List<String> getSanitizedRuntimeCliOptions() {
116-
List<String> properties = new ArrayList<>();
117-
118-
parseConfigArgs(ConfigArgsConfigSource.getAllCliArgs(), (key, value) -> {
119-
PropertyMapper<?> mapper = PropertyMappers.getMapperByCliKey(key);
120-
121-
if (mapper == null || mapper.isRunTime()) {
122-
properties.add(key + "=" + maskValue(value, mapper));
123-
}
124-
}, properties::add);
125-
126-
return properties;
127-
}
128-
129102
@Override
130103
protected void runCommand() {
131104
doBeforeRun();

‎quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/cli/command/Build.java‎

Lines changed: 5 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,20 +17,17 @@
1717

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

20-
import java.util.Optional;
21-
2220
import org.keycloak.quarkus.runtime.Environment;
2321
import org.keycloak.quarkus.runtime.Messages;
2422
import org.keycloak.quarkus.runtime.configuration.Configuration;
23+
import org.keycloak.quarkus.runtime.configuration.IgnoredArtifacts;
2524
import org.keycloak.quarkus.runtime.configuration.PersistedConfigSource;
2625

2726
import io.quarkus.bootstrap.runner.RunnerClassLoader;
2827
import io.quarkus.runtime.LaunchMode;
29-
import io.smallrye.config.ConfigValue;
3028
import picocli.CommandLine;
3129
import picocli.CommandLine.Command;
3230

33-
import static org.keycloak.config.ClassLoaderOptions.QUARKUS_REMOVED_ARTIFACTS_PROPERTY;
3431
import static org.keycloak.config.DatabaseOptions.DB;
3532
import static org.keycloak.quarkus.runtime.Environment.getHomePath;
3633
import static org.keycloak.quarkus.runtime.Environment.isDevProfile;
@@ -59,6 +56,8 @@ public final class Build extends AbstractCommand {
5956

6057
public static final String NAME = "build";
6158

59+
public static final String QUARKUS_REMOVED_ARTIFACTS_PROPERTY = "quarkus.class-loading.removed-artifacts";
60+
6261
@CommandLine.Mixin
6362
HelpAllMixin helpAllMixin;
6463

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

7271
// validate before setting that we're rebuilding so that runtime options are still seen
72+
// the validation and setting the artifacts to remove need to be done without the current persisted properties
7373
PersistedConfigSource.getInstance().runWithDisabled(() -> {
7474
validateConfig();
75+
System.setProperty(QUARKUS_REMOVED_ARTIFACTS_PROPERTY, String.join(",", IgnoredArtifacts.getDefaultIgnoredArtifacts()));
7576
return null;
7677
});
77-
Environment.setRebuild();
78-
7978
picocli.println("Updating the configuration and installing your custom providers, if any. Please wait.");
8079

8180
try {
82-
configureBuildClassLoader();
83-
8481
beforeReaugmentationOnWindows();
8582
if (!Boolean.TRUE.equals(dryRunMixin.dryRun)) {
8683
picocli.build();
@@ -99,13 +96,6 @@ protected void runCommand() {
9996
}
10097
}
10198

102-
private static void configureBuildClassLoader() {
103-
// ignored artifacts must be set prior to starting re-augmentation
104-
Optional.ofNullable(Configuration.getNonPersistedConfigValue(QUARKUS_REMOVED_ARTIFACTS_PROPERTY))
105-
.map(ConfigValue::getValue)
106-
.ifPresent(s -> System.setProperty(QUARKUS_REMOVED_ARTIFACTS_PROPERTY, s));
107-
}
108-
10999
private void checkProfileAndDb() {
110100
if (Environment.isDevProfile()) {
111101
String cmd = picocli.getParsedCommand().map(AbstractCommand::getName).orElse(getName());

0 commit comments

Comments
 (0)
0