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

Add WithConsoleUrl interface #9645

Merged
merged 5 commits into from
Sep 9, 2024
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
20 changes: 7 additions & 13 deletions core/src/main/java/hudson/Functions.java
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@
import hudson.model.ParameterDefinition;
import hudson.model.ParameterDefinition.ParameterDescriptor;
import hudson.model.PasswordParameterDefinition;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.Slave;
import hudson.model.TimeZoneProperty;
Expand Down Expand Up @@ -157,6 +156,7 @@
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import jenkins.console.ConsoleUrlProvider;
import jenkins.console.WithConsoleUrl;
import jenkins.model.GlobalConfiguration;
import jenkins.model.GlobalConfigurationCategory;
import jenkins.model.Jenkins;
Expand Down Expand Up @@ -427,209 +427,209 @@
* @since 1.213
*/
public static Area getScreenResolution() {
Cookie res = Functions.getCookie(Stapler.getCurrentRequest2(), "screenResolution");
if (res != null)
return Area.parse(res.getValue());
return null;
}

@Restricted(NoExternalUse.class)
public static boolean useHidingPasswordFields() {
return SystemProperties.getBoolean(Functions.class.getName() + ".hidingPasswordFields", true);
}

/**
* URL decomposed for easier computation of relevant URLs.
*
* <p>
* The decomposed URL will be of the form:
* <pre>
* aaaaaa/524/bbbbb/cccc
* -head-| N |---rest---
* ----- base -----|
* </pre>
*
* <p>
* The head portion is the part of the URL from the {@link Jenkins}
* object to the first {@link Run} subtype. When "next/prev build"
* is chosen, this part remains intact.
*
* <p>
* The {@code 524} is the path from {@link Job} to {@link Run}.
*
* <p>
* The {@code bbb} portion is the path after that till the last
* {@link Run} subtype. The {@code ccc} portion is the part
* after that.
*/
public static final class RunUrl {
private final String head, base, rest;
private final Run run;


public RunUrl(Run run, String head, String base, String rest) {
this.run = run;
this.head = head;
this.base = base;
this.rest = rest;
}

public String getBaseUrl() {
return base;
}

/**
* Returns the same page in the next build.
*/
public String getNextBuildUrl() {
return getUrl(run.getNextBuild());
}

/**
* Returns the same page in the previous build.
*/
public String getPreviousBuildUrl() {
return getUrl(run.getPreviousBuild());
}

private String getUrl(Run n) {
if (n == null)
return null;
else {
return head + n.getNumber() + rest;
}
}
}

public static Node.Mode[] getNodeModes() {
return Node.Mode.values();
}

public static String getProjectListString(List<AbstractProject> projects) {
return Items.toNameList(projects);
}

/**
* @deprecated as of 1.294
* JEXL now supports the real ternary operator "x?y:z", so this work around
* is no longer necessary.
*/
@Deprecated
public static Object ifThenElse(boolean cond, Object thenValue, Object elseValue) {
return cond ? thenValue : elseValue;
}

public static String appendIfNotNull(String text, String suffix, String nullText) {
return text == null ? nullText : text + suffix;
}

public static Map getSystemProperties() {
return new TreeMap<>(System.getProperties());
}

/**
* Gets the system property indicated by the specified key.
*
* Delegates to {@link SystemProperties#getString(String)}.
*/
@Restricted(DoNotUse.class)
public static String getSystemProperty(String key) {
return SystemProperties.getString(key);
}

public static Map getEnvVars() {
return new TreeMap<>(EnvVars.masterEnvVars);
}

public static boolean isWindows() {
return File.pathSeparatorChar == ';';
}

public static boolean isGlibcSupported() {
try {
GNUCLibrary.LIBC.getpid();
return true;
} catch (Throwable t) {
return false;
}
}

public static List<LogRecord> getLogRecords() {
return Jenkins.logRecords;
}

public static String printLogRecord(LogRecord r) {
return formatter.format(r);
}

@Restricted(NoExternalUse.class)
public static String[] printLogRecordHtml(LogRecord r, LogRecord prior) {
String[] oldParts = prior == null ? new String[4] : logRecordPreformat(prior);
String[] newParts = logRecordPreformat(r);
for (int i = 0; i < /* not 4 */3; i++) {
newParts[i] = "<span class='" + (newParts[i].equals(oldParts[i]) ? "logrecord-metadata-old" : "logrecord-metadata-new") + "'>" + newParts[i] + "</span>";
}
newParts[3] = Util.xmlEscape(newParts[3]);
return newParts;
}
/**
* Partially formats a log record.
* @return date, source, level, message+thrown
* @see SimpleFormatter#format(LogRecord)
*/

private static String[] logRecordPreformat(LogRecord r) {
String source;
if (r.getSourceClassName() == null) {
source = r.getLoggerName() == null ? "" : r.getLoggerName();
} else {
if (r.getSourceMethodName() == null) {
source = r.getSourceClassName();
} else {
source = r.getSourceClassName() + " " + r.getSourceMethodName();
}
}
String message = new SimpleFormatter().formatMessage(r) + "\n";
Throwable x = r.getThrown();
return new String[] {
String.format("%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp", new Date(r.getMillis())),
source,
r.getLevel().getLocalizedName(),
x == null ? message : message + printThrowable(x) + "\n",
};
}

/**
* Reverses a collection so that it can be easily walked in reverse order.
* @since 1.525
*/
public static <T> Iterable<T> reverse(Collection<T> collection) {
List<T> list = new ArrayList<>(collection);
Collections.reverse(list);
return list;
}

/**
* @since TODO
*/
public static Cookie getCookie(HttpServletRequest req, String name) {
Cookie[] cookies = req.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals(name)) {
return cookie;
}
}
}
return null;
}

/**
* @deprecated use {@link #getCookie(HttpServletRequest, String)}
*/
@Deprecated
public static javax.servlet.http.Cookie getCookie(javax.servlet.http.HttpServletRequest req, String name) {
return CookieWrapper.fromJakartaServletHttpCookie(getCookie(HttpServletRequestWrapper.toJakartaHttpServletRequest(req), name));

Check warning on line 632 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 430-632 are not covered by tests
}

/**
Expand Down Expand Up @@ -986,29 +986,29 @@
public static void adminCheck(StaplerRequest2 req, StaplerResponse2 rsp, Object required, Permission permission) throws IOException, ServletException {
// this is legacy --- all views should be eventually converted to
// the permission based model.
if (required != null && !Hudson.adminCheck(StaplerRequest.fromStaplerRequest2(req), StaplerResponse.fromStaplerResponse2(rsp))) {
// check failed. commit the FORBIDDEN response, then abort.
rsp.setStatus(HttpServletResponse.SC_FORBIDDEN);
rsp.getOutputStream().close();
throw new ServletException("Unauthorized access");
}

// make sure the user owns the necessary permission to access this page.
if (permission != null)
checkPermission(permission);
}

/**
* @deprecated use {@link #adminCheck(StaplerRequest2, StaplerResponse2, Object, Permission)}
*/
@Deprecated
public static void adminCheck(StaplerRequest req, StaplerResponse rsp, Object required, Permission permission) throws IOException, javax.servlet.ServletException {
try {
adminCheck(StaplerRequest.toStaplerRequest2(req), StaplerResponse.toStaplerResponse2(rsp), required, permission);
} catch (ServletException e) {
throw ServletExceptionWrapper.fromJakartaServletException(e);
}
}

Check warning on line 1011 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 989-1011 are not covered by tests

/**
* Infers the hudson installation URL from the given request.
Expand Down Expand Up @@ -1755,7 +1755,7 @@
if (it instanceof Descriptor)
clazz = ((Descriptor) it).clazz;

String buf = Stapler.getCurrentRequest2().getContextPath() + Jenkins.VIEW_RESOURCE_PATH + '/' +

Check warning on line 1758 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 1758 is not covered by tests
clazz.getName().replace('.', '/').replace('$', '/') +
'/' + path;
return buf;
Expand All @@ -1763,7 +1763,7 @@

public static boolean hasView(Object it, String path) throws IOException {
if (it == null) return false;
return Stapler.getCurrentRequest2().getView(it, path) != null;

Check warning on line 1766 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 1766 is only partially covered, one branch is missing
}

/**
Expand Down Expand Up @@ -1981,20 +1981,14 @@
}

/**
* Computes the link to the console for the run for the specified executable, taking {@link ConsoleUrlProvider} into account.
* @param executable the executable (normally a {@link Run})
* @return the absolute URL for accessing the build console for the executable, or null if there is no build associated with the executable
* Computes the link to the console for the run for the specified object, taking {@link ConsoleUrlProvider} into account.
* @param withConsoleUrl the object to compute a console url for (can be {@link Run}, a {@code PlaceholderExecutable}...)
Copy link
Contributor

Choose a reason for hiding this comment

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

After the last rework it isn't an object any longer, maybe also adjust the javadoc here

Copy link
Member

Choose a reason for hiding this comment

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

Well, a “model object”. Seems OK to me.

* @return the absolute URL for accessing the build console for the given object, or null if there is no console URL defined for the object.
* @since 2.433
*/
public static @CheckForNull String getConsoleUrl(Queue.Executable executable) {
if (executable == null) {
return null;
} else if (executable instanceof Run) {
return ConsoleUrlProvider.getRedirectUrl((Run<?, ?>) executable);
} else {
// Handles cases such as PlaceholderExecutable for Pipeline node steps.
return getConsoleUrl(executable.getParentExecutable());
}
public static @CheckForNull String getConsoleUrl(WithConsoleUrl withConsoleUrl) {
String consoleUrl = withConsoleUrl.getConsoleUrl();
return consoleUrl != null ? Stapler.getCurrentRequest().getContextPath() + '/' + consoleUrl : null;

Check warning on line 1991 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 1991 is only partially covered, one branch is missing
}

/**
Expand Down Expand Up @@ -2040,7 +2034,7 @@
} catch (MalformedURLException e) {
// fall back to HTTP request
}
return Stapler.getCurrentRequest2().getServerName();

Check warning on line 2037 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 2037 is not covered by tests
}

/**
Expand Down Expand Up @@ -2151,7 +2145,7 @@
*/
@Deprecated
public static String getCrumb(StaplerRequest req) {
return getCrumb(req != null ? StaplerRequest.toStaplerRequest2(req) : null);

Check warning on line 2148 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 2148 is only partially covered, one branch is missing
}

public static String getCrumbRequestField() {
Expand Down Expand Up @@ -2328,7 +2322,7 @@

@Deprecated
public static String createRenderOnDemandProxy(JellyContext context, String attributesToCapture) {
return Stapler.getCurrentRequest2().createJavaScriptProxy(new RenderOnDemandClosure(context, attributesToCapture));

Check warning on line 2325 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 2325 is not covered by tests
}

/**
Expand All @@ -2347,13 +2341,13 @@

public static String setCurrentDescriptorByNameUrl(String value) {
String o = getCurrentDescriptorByNameUrl();
Stapler.getCurrentRequest2().setAttribute("currentDescriptorByNameUrl", value);

return o;
}

public static void restoreCurrentDescriptorByNameUrl(String old) {
Stapler.getCurrentRequest2().setAttribute("currentDescriptorByNameUrl", old);

Check warning on line 2350 in core/src/main/java/hudson/Functions.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 2344-2350 are not covered by tests
}

public static List<String> getRequestHeaders(String name) {
Expand Down
13 changes: 12 additions & 1 deletion core/src/main/java/hudson/model/Queue.java
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import jenkins.console.WithConsoleUrl;
import jenkins.model.Jenkins;
import jenkins.model.queue.AsynchronousExecution;
import jenkins.model.queue.CompositeCauseOfBlockage;
Expand Down Expand Up @@ -2088,7 +2089,7 @@
* used to render the HTML that indicates this executable is executing.
*/
@StaplerAccessibleType
public interface Executable extends Runnable {
public interface Executable extends Runnable, WithConsoleUrl {
/**
* Task from which this executable was created.
*
Expand Down Expand Up @@ -2131,6 +2132,16 @@
return Executables.getParentOf(this).getEstimatedDuration();
}

/**
* Handles cases such as {@code PlaceholderExecutable} for Pipeline node steps.
Copy link
Member

Choose a reason for hiding this comment

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

Did you test this case to make sure it works?

Copy link
Member Author

Choose a reason for hiding this comment

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

This is actually moved code from Functions#getConsoleUrl but I doublechecked to make sure.

Copy link
Member

Choose a reason for hiding this comment

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

Ok, thanks, it just wasn't obvious to me that the recursion was quite the same.

* @return by default, that of {@link #getParentExecutable} if defined
*/
@Override
default String getConsoleUrl() {
Executable parent = getParentExecutable();
return parent != null ? parent.getConsoleUrl() : null;

Check warning on line 2142 in core/src/main/java/hudson/model/Queue.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 2141-2142 are not covered by tests
}

/**
* Used to render the HTML. Should be a human readable text of what this executable is.
*/
Expand Down
12 changes: 11 additions & 1 deletion core/src/main/java/hudson/model/Run.java
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import jenkins.console.ConsoleUrlProvider;
import jenkins.console.WithConsoleUrl;
import jenkins.model.ArtifactManager;
import jenkins.model.ArtifactManagerConfiguration;
import jenkins.model.ArtifactManagerFactory;
Expand Down Expand Up @@ -156,8 +158,8 @@
* @see RunListener
*/
@ExportedBean
public abstract class Run<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, RunT>>

Check warning on line 161 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Java Compiler

compiler:compile

NORMAL: Note: Generating hudson/model/Run.javadoc

Check warning on line 161 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Java Compiler

compiler:testCompile

NORMAL: Note: Generating hudson/model/Run.javadoc
extends Actionable implements ExtensionPoint, Comparable<RunT>, AccessControlled, PersistenceRoot, DescriptorByNameOwner, OnMaster, StaplerProxy {
extends Actionable implements ExtensionPoint, Comparable<RunT>, AccessControlled, PersistenceRoot, DescriptorByNameOwner, OnMaster, StaplerProxy, WithConsoleUrl {

/**
* The original {@link Queue.Item#getId()} has not yet been mapped onto the {@link Run} instance.
Expand Down Expand Up @@ -1059,6 +1061,14 @@
return project.getUrl() + getNumber() + '/';
}

/**
* @see ConsoleUrlProvider#consoleUrlOf
*/
@Override
public String getConsoleUrl() {
return ConsoleUrlProvider.consoleUrlOf(this);
}

/**
* Obtains the absolute URL to this build.
*
Expand Down Expand Up @@ -2274,7 +2284,7 @@
/**
* Returns the build time stamp in the body.
*/
public void doBuildTimestamp(StaplerRequest2 req, StaplerResponse2 rsp, @QueryParameter String format) throws IOException {

Check warning on line 2287 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Java Compiler

compiler:compile

NORMAL: Note: Generating hudson/model/Run/doBuildTimestamp.stapler

Check warning on line 2287 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Java Compiler

compiler:testCompile

NORMAL: Note: Generating hudson/model/Run/doBuildTimestamp.stapler
rsp.setContentType("text/plain");
rsp.setCharacterEncoding("US-ASCII");
rsp.setStatus(HttpServletResponse.SC_OK);
Expand All @@ -2290,8 +2300,8 @@
* @since TODO
*/
public void doConsoleText(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
if (Util.isOverridden(Run.class, getClass(), "doConsoleText", StaplerRequest.class, StaplerResponse.class)) {

Check warning on line 2303 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 2303 is only partially covered, one branch is missing
doConsoleText(StaplerRequest.fromStaplerRequest2(req), StaplerResponse.fromStaplerResponse2(rsp));

Check warning on line 2304 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 2304 is not covered by tests
} else {
doConsoleTextImpl(req, rsp);
}
Expand All @@ -2303,96 +2313,96 @@
@Deprecated
@StaplerNotDispatchable
public void doConsoleText(StaplerRequest req, StaplerResponse rsp) throws IOException {
doConsoleTextImpl(StaplerRequest.toStaplerRequest2(req), StaplerResponse.toStaplerResponse2(rsp));
}

private void doConsoleTextImpl(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
rsp.setContentType("text/plain;charset=UTF-8");
try (InputStream input = getLogInputStream();
OutputStream os = rsp.getOutputStream();
PlainTextConsoleOutputStream out = new PlainTextConsoleOutputStream(os)) {
IOUtils.copy(input, out);
}
}

/**
* Handles incremental log output.
* @deprecated as of 1.352
* Use {@code getLogText().doProgressiveText(req,rsp)}
*/
@Deprecated
public void doProgressiveLog(StaplerRequest req, StaplerResponse rsp) throws IOException {
getLogText().doProgressText(StaplerRequest.toStaplerRequest2(req), StaplerResponse.toStaplerResponse2(rsp));
}

/**
* Checks whether keep status can be toggled.
* Normally it can, but if there is a complex reason (from subclasses) why this build must be kept, the toggle is meaningless.
* @return true if {@link #doToggleLogKeep} and {@link #keepLog(boolean)} and {@link #keepLog()} are options
* @since 1.510
*/
public boolean canToggleLogKeep() {
if (!keepLog && isKeepLog()) {
// Definitely prevented.
return false;
}
// TODO may be that keepLog is on (perhaps toggler earlier) yet isKeepLog() would be true anyway.
// In such a case this will incorrectly return true and logKeep.jelly will allow the toggle.
// However at least then (after redirecting to the same page) the toggle button will correctly disappear.
return true;
}

@RequirePOST
public void doToggleLogKeep(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
keepLog(!keepLog);
rsp.forwardToPreviousPage(req);
}

/**
* Marks this build to be kept.
*/
@CLIMethod(name = "keep-build")
public final void keepLog() throws IOException {
keepLog(true);
}

public void keepLog(boolean newValue) throws IOException {
checkPermission(newValue ? UPDATE : DELETE);
keepLog = newValue;
save();
}

/**
* Deletes the build when the button is pressed.
*
* @since TODO
*/
@RequirePOST
public void doDoDelete(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
if (Util.isOverridden(Run.class, getClass(), "doDoDelete", StaplerRequest.class, StaplerResponse.class)) {
try {
doDoDelete(StaplerRequest.fromStaplerRequest2(req), StaplerResponse.fromStaplerResponse2(rsp));
} catch (javax.servlet.ServletException e) {
throw ServletExceptionWrapper.toJakartaServletException(e);
}
return;
} else {
doDoDeleteImpl(req, rsp);
}
}

/**
* @deprecated use {@link #doDoDelete(StaplerRequest2, StaplerResponse2)}
*/
@Deprecated
@StaplerNotDispatchable
public void doDoDelete(StaplerRequest req, StaplerResponse rsp) throws IOException, javax.servlet.ServletException {
try {
doDoDeleteImpl(StaplerRequest.toStaplerRequest2(req), StaplerResponse.toStaplerResponse2(rsp));
} catch (ServletException e) {
throw ServletExceptionWrapper.fromJakartaServletException(e);
}
}

Check warning on line 2405 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered lines

Lines 2316-2405 are not covered by tests

private void doDoDeleteImpl(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
checkPermission(DELETE);
Expand Down Expand Up @@ -2678,8 +2688,8 @@

@Override
public Object getDynamic(String token, StaplerRequest2 req, StaplerResponse2 rsp) {
if (Util.isOverridden(Run.class, getClass(), "getDynamic", String.class, StaplerRequest.class, StaplerResponse.class)) {

Check warning on line 2691 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Partially covered line

Line 2691 is only partially covered, one branch is missing
return getDynamic(token, StaplerRequest.fromStaplerRequest2(req), StaplerResponse.fromStaplerResponse2(rsp));

Check warning on line 2692 in core/src/main/java/hudson/model/Run.java

View check run for this annotation

ci.jenkins.io / Code Coverage

Not covered line

Line 2692 is not covered by tests
} else {
Object returnedResult = super.getDynamic(token, req, rsp);
return getDynamicImpl(token, returnedResult);
Expand Down
20 changes: 13 additions & 7 deletions core/src/main/java/jenkins/console/ConsoleUrlProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ public interface ConsoleUrlProvider extends Describable<ConsoleUrlProvider> {
* Get a URL relative to the context path of Jenkins which should be used to link to the console for the specified build.
* <p>Should only be used in the context of serving an HTTP request.
* @param run the build
* @return the URL for the console for the specified build, relative to the context of Jenkins, or {@code null}
* if this implementation does not want to server a special console view for this build.
* @return the URL for the console for the specified build, relative to the context of Jenkins (should not start with {@code /}), or {@code null}
* if this implementation does not want to serve a special console view for this build.
*/
@CheckForNull String getConsoleUrl(Run<?, ?> run);

Expand All @@ -80,6 +80,14 @@ default Descriptor<ConsoleUrlProvider> getDescriptor() {
* @return the URL for the console for the specified build, relative to the web server root
*/
static @NonNull String getRedirectUrl(Run<?, ?> run) {
return Stapler.getCurrentRequest().getContextPath() + '/' + run.getConsoleUrl();
}

/**
* Looks up the {@link #getConsoleUrl} value from the first provider to offer one.
* @since TODO
*/
static @NonNull String consoleUrlOf(Run<?, ?> run) {
final List<ConsoleUrlProvider> providers = new ArrayList<>();
User currentUser = User.current();
if (currentUser != null) {
Expand All @@ -104,6 +112,8 @@ default Descriptor<ConsoleUrlProvider> getDescriptor() {
if (tempUrl != null) {
if (new URI(tempUrl).isAbsolute()) {
LOGGER.warning(() -> "Ignoring absolute console URL " + tempUrl + " for " + run + " from " + provider.getClass());
} else if (tempUrl.startsWith("/")) {
LOGGER.warning(() -> "Ignoring URL " + tempUrl + " starting with / for " + run + " from " + provider.getClass());
} else {
// Found a valid non-null URL.
url = tempUrl;
Expand All @@ -118,11 +128,7 @@ default Descriptor<ConsoleUrlProvider> getDescriptor() {
// Reachable if DefaultConsoleUrlProvider is not one of the configured providers, including if no providers are configured at all.
url = run.getUrl() + "console";
}
if (url.startsWith("/")) {
return Stapler.getCurrentRequest2().getContextPath() + url;
} else {
return Stapler.getCurrentRequest2().getContextPath() + '/' + url;
}
return url;
}

/**
Expand Down
43 changes: 43 additions & 0 deletions core/src/main/java/jenkins/console/WithConsoleUrl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* The MIT License
*
* Copyright 2024 CloudBees, Inc.
*
* 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 jenkins.console;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.Beta;

/**
* A model object that may have a console URL.
*/
@Restricted(Beta.class)
public interface WithConsoleUrl {

/**
* @return a URL relative to the context root without leading slash, such as {@code job/xxx/123/console};
* or null if unknown or not applicable
*/
@CheckForNull
String getConsoleUrl();
}
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ public void getRedirectUrl() throws Exception {
// Custom URL without leading slash
b.setDescription("custom my/build/console");
assertCustomConsoleUrl(r.contextPath + "/my/build/console", b);
// Custom URL with leading slash
// Custom URL with leading slash -> not supported, falls back to default
b.setDescription("custom /my/build/console");
assertCustomConsoleUrl(r.contextPath + "/my/build/console", b);
assertCustomConsoleUrl(r.contextPath + '/' + b.getUrl() + "console", b);
// Default URL is used when extensions throw exceptions.
b.setDescription("NullPointerException");
assertCustomConsoleUrl(r.contextPath + '/' + b.getUrl() + "console", b);
Expand Down
Loading