Skip to content

Commit

Permalink
Rewrite rebuild actions using javascript java injection
Browse files Browse the repository at this point in the history
First version of rebuild that includes all the job parameters.
Some improvements should be done like have just one common.jelly but
not clear how jelly include logic works.

Tested using gerrit-trigger
Signed-off-by: Michael Trimarchi <michael@amarulasolutions.com>
  • Loading branch information
panicking committed Feb 3, 2025
1 parent 0687136 commit 8f3d2ac
Show file tree
Hide file tree
Showing 11 changed files with 409 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,54 @@

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.ExtensionList;
import hudson.model.Action;
import hudson.model.BallColor;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.PasswordParameterValue;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Failure;
import hudson.model.Item;
import hudson.model.queue.QueueTaskFuture;
import hudson.model.Queue;
import hudson.security.Permission;
import hudson.util.HttpResponses;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.scm.api.SCMRevisionAction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.sf.json.JSONObject;
import org.jenkins.ui.icon.IconSpec;
import org.jenkinsci.plugins.scriptsecurity.scripts.ApprovalContext;
import org.jenkinsci.plugins.scriptsecurity.scripts.ScriptApproval;
import org.jenkinsci.plugins.scriptsecurity.scripts.UnapprovedUsageException;
import org.jenkinsci.plugins.scriptsecurity.scripts.languages.GroovyLanguage;
import org.jenkinsci.plugins.workflow.cps.CpsFlowExecution;
import org.jenkinsci.plugins.workflow.cps.replay.OriginalLoadedScripts;
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
import org.jenkinsci.plugins.workflow.flow.FlowExecutionOwner;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import org.kohsuke.stapler.interceptor.RequirePOST;

public abstract class AbstractPipelineViewAction implements Action, IconSpec {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
Expand All @@ -26,6 +58,100 @@ public abstract class AbstractPipelineViewAction implements Action, IconSpec {
protected final transient PipelineGraphApi api;
protected final transient WorkflowRun run;

/** Fetches execution, blocking if needed while we wait for some of the loading process. */
@Restricted(NoExternalUse.class)
public @CheckForNull CpsFlowExecution getExecutionBlocking() {
FlowExecutionOwner owner = ((FlowExecutionOwner.Executable) run).asFlowExecutionOwner();
if (owner == null) {
return null;
}
try {
FlowExecution exec = owner.get();
return exec instanceof CpsFlowExecution ? (CpsFlowExecution) exec : null;
} catch (IOException ioe) {
LOGGER.log(Level.WARNING, "Error fetching execution for replay", ioe);
}
return null;
}

/** @see CpsFlowExecution#getScript */
/* accessible to Jelly */ public String getOriginalScript() {
CpsFlowExecution execution = (CpsFlowExecution) getExecutionBlocking();
return execution != null ? execution.getScript() : "???";
}

/** @see CpsFlowExecution#getLoadedScripts */
/* accessible to Jelly */ public Map<String,String> getOriginalLoadedScripts() {
CpsFlowExecution execution = (CpsFlowExecution) getExecutionBlocking();
if (execution == null) { // ?
return Collections.<String,String>emptyMap();
}
Map<String,String> scripts = new TreeMap<>();
for (OriginalLoadedScripts replayer : ExtensionList.lookup(OriginalLoadedScripts.class)) {
scripts.putAll(replayer.loadScripts(execution));
}
return scripts;
}

private boolean hasPasswordParameter() {
ParametersAction pa = run.getAction(ParametersAction.class);
return pa != null && pa.getParameters().stream().anyMatch(PasswordParameterValue.class::isInstance);
}

private static final Iterable<Class<? extends Action>> COPIED_ACTIONS = List.of(
ParametersAction.class,
SCMRevisionAction.class
);

/**
* For whitebox testing.
* @param replacementMainScript main script; replacement for {@link #getOriginalScript}
* @param replacementLoadedScripts auxiliary scripts, keyed by class name; replacement for {@link #getOriginalLoadedScripts}
* @return a way to wait for the replayed build to complete
*/
@SuppressWarnings("rawtypes")
public @CheckForNull QueueTaskFuture/*<Run>*/ run(@NonNull String replacementMainScript, @NonNull Map<String,String> replacementLoadedScripts) {
Queue.Item item = run2(replacementMainScript, replacementLoadedScripts);
return item == null ? null : item.getFuture();
}

/**
* For use in projects that want initiate a replay via the Java API.
*
* @param replacementMainScript main script; replacement for {@link #getOriginalScript}
* @param replacementLoadedScripts auxiliary scripts, keyed by class name; replacement for {@link #getOriginalLoadedScripts}
* @return build queue item
*/
public @CheckForNull Queue.Item run2(@NonNull String replacementMainScript, @NonNull Map<String,String> replacementLoadedScripts) {
List<Action> actions = new ArrayList<>();
CpsFlowExecution execution = getExecutionBlocking();
if (execution == null) {
return null;
}

if (!execution.isSandbox()) {
ScriptApproval.get().configuring(replacementMainScript,GroovyLanguage.get(), ApprovalContext.create(), true);
try {
ScriptApproval.get().using(replacementMainScript, GroovyLanguage.get());
} catch (UnapprovedUsageException e) {
throw new Failure("The script is not approved.");
}
}

actions.add(new ReplayFlowFactoryAction(replacementMainScript, replacementLoadedScripts, execution.isSandbox()));
actions.add(new CauseAction(new Cause.UserIdCause(), new ReplayCause(run)));

if (hasPasswordParameter()) {
throw new Failure("Replay is not allowed when password parameters are used.");
}

for (Class<? extends Action> c : COPIED_ACTIONS) {
actions.addAll(run.getActions(c));
}

return ParameterizedJobMixIn.scheduleBuild2(run.getParent(), 0, actions.toArray(new Action[actions.size()]));
}

public AbstractPipelineViewAction(WorkflowRun target) {
this.api = new PipelineGraphApi(target);
this.run = target;
Expand Down Expand Up @@ -57,6 +183,23 @@ public boolean isParameterized() {
return property != null && !property.getParameterDefinitions().isEmpty();
}

/**
* Handles the rebuild request and redirects to parameterized
* and non parameterized build when needed.
* @throws ExecutionException
* @throws IOException
*/
@RequirePOST
@JavaScriptMethod
public void doRebuildjob() throws IOException, ExecutionException {
if (run != null) {
run.checkPermission(Item.BUILD);
if (run(getOriginalScript(), getOriginalLoadedScripts()) == null) {
throw new IOException(run.getParent().getFullName() + " is not buildable");
}
}
}

public String getFullBuildDisplayName() {
return run.getFullDisplayName();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* The MIT License
*
* Copyright 2016 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 io.jenkins.plugins.pipelinegraphview.utils;

import hudson.ExtensionPoint;
import java.util.Collections;
import java.util.Map;
import edu.umd.cs.findbugs.annotations.NonNull;
import org.jenkinsci.plugins.workflow.cps.CpsFlowExecution;

/**
* Defines which scripts are eligible to be replaced by {@link ReplayAction#run}.
*/
public abstract class OriginalLoadedScripts implements ExtensionPoint {

/**
* Finds scripts which are eligible for replacement.
* @param execution a build
* @return a map from Groovy class names to their original texts, as in {@link ReplayAction#replace}
*/
public @NonNull Map<String,String> loadScripts(@NonNull CpsFlowExecution execution) {
return Collections.emptyMap();
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
* The MIT License
*
* Copyright 2016 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 io.jenkins.plugins.pipelinegraphview.utils;

import hudson.console.ModelHyperlinkNote;
import hudson.model.Cause;
import hudson.model.Run;
import hudson.model.TaskListener;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;

/**
* Marker that a run is a replay of an earlier one.
*/
public class ReplayCause extends Cause {

private final int originalNumber;
private transient Run<?,?> run;

ReplayCause(@NonNull Run<?,?> original) {
this.originalNumber = original.getNumber();
}

@Override public void onAddedTo(Run run) {
super.onAddedTo(run);
this.run = run;
}

@Override public void onLoad(Run<?,?> run) {
super.onLoad(run);
this.run = run;
}

public Run<?,?> getRun() {
return run;
}

public int getOriginalNumber() {
return originalNumber;
}

public @CheckForNull Run<?,?> getOriginal() {
return run.getParent().getBuildByNumber(originalNumber);
}

@Override public String getShortDescription() {
return "Replayed " + getOriginalNumber();
}

@Override public void print(TaskListener listener) {
Run<?,?> original = getOriginal();
if (original != null) {
listener.getLogger().println("Replayed " + getOriginalNumber());
} else {
super.print(listener); // same, without hyperlink
}
}

}
Loading

0 comments on commit 8f3d2ac

Please sign in to comment.