-
-
Notifications
You must be signed in to change notification settings - Fork 9.4k
[JENKINS-75378] Adding a CLI command listener #10382
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
Changes from 6 commits
b41633f
99ba771
5cb32e0
7b9cb0a
b1e15c4
32ead10
b8f360a
206147e
5433f59
751313c
dcbbdf6
b5c3f70
1138c0d
4d7e35a
3679a4d
676835c
bdf2895
737c08d
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,6 +35,7 @@ | |
| import hudson.Functions; | ||
| import hudson.cli.declarative.CLIMethod; | ||
| import hudson.cli.declarative.OptionHandlerExtension; | ||
| import hudson.cli.listeners.CliListener; | ||
| import hudson.remoting.Channel; | ||
| import hudson.security.SecurityRealm; | ||
| import java.io.BufferedInputStream; | ||
|
|
@@ -49,8 +50,6 @@ | |
| import java.util.List; | ||
| import java.util.Locale; | ||
| import java.util.UUID; | ||
| import java.util.logging.Level; | ||
| import java.util.logging.Logger; | ||
| import jenkins.model.Jenkins; | ||
| import jenkins.util.SystemProperties; | ||
| import org.jvnet.hudson.annotation_indexer.Index; | ||
|
|
@@ -239,6 +238,9 @@ | |
| this.locale = locale; | ||
| CmdLineParser p = getCmdLineParser(); | ||
|
|
||
| final String correlationId = UUID.randomUUID().toString(); | ||
| final int argsSize = args.size(); | ||
|
|
||
| // add options from the authenticator | ||
| SecurityContext sc = null; | ||
| Authentication old = null; | ||
|
|
@@ -253,56 +255,59 @@ | |
| if (!(this instanceof HelpCommand || this instanceof WhoAmICommand)) | ||
| Jenkins.get().checkPermission(Jenkins.READ); | ||
| p.parseArgument(args.toArray(new String[0])); | ||
| LOGGER.log(Level.FINE, "Invoking CLI command {0}, with {1} arguments, as user {2}.", | ||
| new Object[] {getName(), args.size(), auth.getName()}); | ||
|
|
||
| CliListener.fireExecution(correlationId, getName(), argsSize, auth); | ||
| int res = run(); | ||
| LOGGER.log(Level.FINE, "Executed CLI command {0}, with {1} arguments, as user {2}, return code {3}", | ||
| new Object[] {getName(), args.size(), auth.getName(), res}); | ||
| CliListener.fireCompleted(correlationId, getName(), argsSize, auth, res); | ||
|
|
||
| return res; | ||
| } catch (CmdLineException e) { | ||
| logFailedCommandAndPrintExceptionErrorMessage(args, e); | ||
| printUsage(stderr, p); | ||
| return 2; | ||
| } catch (IllegalStateException e) { | ||
| logFailedCommandAndPrintExceptionErrorMessage(args, e); | ||
| return 4; | ||
| } catch (IllegalArgumentException e) { | ||
| logFailedCommandAndPrintExceptionErrorMessage(args, e); | ||
| return 3; | ||
| } catch (AbortException e) { | ||
| logFailedCommandAndPrintExceptionErrorMessage(args, e); | ||
| return 5; | ||
| } catch (AccessDeniedException e) { | ||
| logFailedCommandAndPrintExceptionErrorMessage(args, e); | ||
| return 6; | ||
| } catch (BadCredentialsException e) { | ||
| // to the caller, we can't reveal whether the user didn't exist or the password didn't match. | ||
| // do that to the server log instead | ||
| String id = UUID.randomUUID().toString(); | ||
| logAndPrintError(e, "Bad Credentials. Search the server log for " + id + " for more details.", | ||
| "CLI login attempt failed: " + id, Level.INFO); | ||
| return 7; | ||
| } catch (Throwable e) { | ||
| String errorMsg = "Unexpected exception occurred while performing " + getName() + " command."; | ||
| logAndPrintError(e, errorMsg, errorMsg, Level.WARNING); | ||
| Functions.printStackTrace(e, stderr); | ||
| return 1; | ||
| int exitCode = handleException(e, correlationId, p); | ||
| CliListener.fireError(correlationId, getName(), argsSize, getTransportAuthentication2(), exitCode, e); | ||
| return exitCode; | ||
| } finally { | ||
| if (sc != null) | ||
| sc.setAuthentication(old); // restore | ||
| } | ||
| } | ||
|
|
||
| private void logFailedCommandAndPrintExceptionErrorMessage(List<String> args, Throwable e) { | ||
| Authentication auth = getTransportAuthentication2(); | ||
| String logMessage = String.format("Failed call to CLI command %s, with %d arguments, as user %s.", | ||
| getName(), args.size(), auth != null ? auth.getName() : "<unknown>"); | ||
|
|
||
| logAndPrintError(e, e.getMessage(), logMessage, Level.FINE); | ||
| /** | ||
| * Determines command stderr output and return the exit code as described on {@link #main(List, Locale, InputStream, PrintStream, PrintStream)} | ||
| * */ | ||
| protected int handleException(Throwable e, String correlationId, CmdLineParser p) { | ||
| int exitCode; | ||
| if (e instanceof CmdLineException) { | ||
| exitCode = 2; | ||
| printError(e.getMessage()); | ||
| printUsage(stderr, p); | ||
| } else if (e instanceof IllegalArgumentException) { | ||
| exitCode = 3; | ||
| printError(e.getMessage()); | ||
| } else if (e instanceof IllegalStateException) { | ||
| exitCode = 4; | ||
| printError(e.getMessage()); | ||
| } else if (e instanceof AbortException) { | ||
| exitCode = 5; | ||
| printError(e.getMessage()); | ||
| } else if (e instanceof AccessDeniedException) { | ||
| exitCode = 6; | ||
| printError(e.getMessage()); | ||
| } else if (e instanceof BadCredentialsException) { | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Looks like
b1803a9 I can't find CliAuthenticationTest, may not apply anymore. EDIT: this branch is only possible if a CLICommand implementation throws a |
||
| exitCode = 7; | ||
| // to the caller, we can't reveal whether the user didn't exist or the password didn't match. | ||
| // do that to the server log instead | ||
apuig marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| printError("Bad Credentials. Search the server log for " + correlationId + " for more details."); | ||
| } else { | ||
| exitCode = 1; | ||
| printError("Unexpected exception occurred while performing " + getName() + " command."); | ||
| Functions.printStackTrace(e, stderr); | ||
| } | ||
| return exitCode; | ||
| } | ||
|
|
||
| private void logAndPrintError(Throwable e, String errorMessage, String logMessage, Level logLevel) { | ||
| LOGGER.log(logLevel, logMessage, e); | ||
|
|
||
krisstern marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| private void printError(String errorMessage) { | ||
| this.stderr.println(); | ||
| this.stderr.println("ERROR: " + errorMessage); | ||
| } | ||
|
|
@@ -538,8 +543,6 @@ | |
| return null; | ||
| } | ||
|
|
||
| private static final Logger LOGGER = Logger.getLogger(CLICommand.class.getName()); | ||
|
|
||
| private static final ThreadLocal<CLICommand> CURRENT_COMMAND = new ThreadLocal<>(); | ||
|
|
||
| /*package*/ static CLICommand setCurrent(CLICommand cmd) { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| /* | ||
| * The MIT License | ||
| * | ||
| * Copyright (c) 2025 | ||
| * | ||
| * Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| * of this software and associated documentation files (the "Software"), to deal | ||
| * in the Software without restriction, including without limitation the rights | ||
| * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| * copies of the Software, and to permit persons to whom the Software is | ||
| * furnished to do so, subject to the following conditions: | ||
| * | ||
| * The above copyright notice and this permission notice shall be included in | ||
| * all copies or substantial portions of the Software. | ||
| * | ||
| * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
| * THE SOFTWARE. | ||
| */ | ||
|
|
||
| package hudson.cli.listeners; | ||
|
|
||
| import edu.umd.cs.findbugs.annotations.CheckForNull; | ||
| import edu.umd.cs.findbugs.annotations.NonNull; | ||
| import hudson.ExtensionPoint; | ||
| import hudson.cli.CLICommand; | ||
| import jenkins.util.Listeners; | ||
| import org.springframework.security.core.Authentication; | ||
|
|
||
| /** | ||
| * Callback around {@link CLICommand#run()}, each execution generates a new `correlationId` in order to group related events. | ||
| * | ||
| * @since TODO | ||
| */ | ||
| public interface CliListener extends ExtensionPoint { | ||
apuig marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Called before. | ||
| * | ||
| * @param correlationId This value is used to correlate this command event to other, related command events. | ||
apuig marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * @param command The command to be executed. | ||
| * @param argsSize Number of arguments passed to the command. | ||
apuig marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| * @param auth Authenticated user performing the execution. | ||
| * | ||
| * */ | ||
| default void onExecution( | ||
| @NonNull String correlationId, @NonNull String command, int argsSize, @CheckForNull Authentication auth) {} | ||
apuig marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| /** | ||
| * Called after. | ||
| * | ||
| * @param correlationId This value is used to correlate this command event to other, related command events. | ||
| * @param command The executed command. | ||
| * @param argsSize Number of arguments passed to the command. | ||
| * @param auth Authenticated user executing the command. | ||
| * @param exitCode `run` returned exit code. | ||
|
||
| * */ | ||
| default void onCompleted( | ||
| @NonNull String correlationId, | ||
| @NonNull String command, | ||
| int argsSize, | ||
| @CheckForNull Authentication auth, | ||
| int exitCode) {} | ||
|
|
||
| /** | ||
| * Catch exceptions. | ||
| * | ||
| * @param correlationId This value is used to correlate this command event to other, related command events. | ||
| * @param command The executed command. | ||
| * @param argsSize Number of arguments passed to the command. | ||
| * @param auth Authenticated user executing the command | ||
| * @param exitCode `run` returned exit code. | ||
|
||
| * @param t Any error during the execution of the command. | ||
| * */ | ||
| default void onError( | ||
| @NonNull String correlationId, | ||
| @NonNull String command, | ||
| int argsSize, | ||
| @CheckForNull Authentication auth, | ||
| int exitCode, | ||
| @NonNull Throwable t) {} | ||
|
|
||
| /** | ||
| * Fires the {@link #onExecution} event. | ||
| * | ||
| * @param correlationId This value is used to correlate this command event to other, related command events. | ||
| * @param command The command to be executed. | ||
| * @param argsSize Number of arguments passed to the command. | ||
| * @param auth Authenticated user performing the execution. | ||
| * | ||
| * */ | ||
| static void fireExecution( | ||
| @NonNull String correlationId, @NonNull String command, int argsSize, @CheckForNull Authentication auth) { | ||
| Listeners.notify( | ||
| CliListener.class, true, listener -> listener.onExecution(correlationId, command, argsSize, auth)); | ||
| } | ||
|
|
||
| /** | ||
| * Fires the {@link #onCompleted} event. | ||
| * | ||
| * @param correlationId This value is used to correlate this command event to other, related command events. | ||
| * @param command The executed command. | ||
| * @param argsSize Number of arguments passed to the command. | ||
| * @param auth Authenticated user executing the command. | ||
| * @param exitCode `run` returned exit code. | ||
| * */ | ||
| static void fireCompleted( | ||
| @NonNull String correlationId, | ||
| @NonNull String command, | ||
| int argsSize, | ||
| @CheckForNull Authentication auth, | ||
| int exitCode) { | ||
| Listeners.notify( | ||
| CliListener.class, | ||
| true, | ||
| listener -> listener.onCompleted(correlationId, command, argsSize, auth, exitCode)); | ||
| } | ||
|
|
||
| /** | ||
| * Fires the {@link #onError} event. | ||
| * | ||
| * @param correlationId This value is used to correlate this command event to other, related command events. | ||
| * @param command The executed command. | ||
| * @param argsSize Number of arguments passed to the command. | ||
| * @param auth Authenticated user executing the command | ||
| * @param exitCode `run` returned exit code. | ||
| * @param t Any error during the execution of the command. | ||
| * */ | ||
| static void fireError( | ||
| @NonNull String correlationId, | ||
| @NonNull String command, | ||
| int argsSize, | ||
| @CheckForNull Authentication auth, | ||
| int exitCode, | ||
| @NonNull Throwable t) { | ||
| Listeners.notify( | ||
| CliListener.class, | ||
| true, | ||
| listener -> listener.onError(correlationId, command, argsSize, auth, exitCode, t)); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: The introduction of
correlationIdcommon to all events could be highlighted in the PR description.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
At this point
correlationIdis only used inBadCredentialsExceptionhandling. (where the original randomUUID comes form)