forked from jenkinsci/pipeline-graph-view-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPipelineConsoleViewAction.java
More file actions
419 lines (364 loc) · 14.6 KB
/
PipelineConsoleViewAction.java
File metadata and controls
419 lines (364 loc) · 14.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package io.jenkins.plugins.pipelinegraphview.consoleview;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Plugin;
import hudson.console.AnnotatedLargeText;
import hudson.model.BallColor;
import hudson.model.Item;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Queue;
import hudson.model.Result;
import hudson.security.Permission;
import hudson.util.HttpResponses;
import io.jenkins.plugins.pipelinegraphview.Messages;
import io.jenkins.plugins.pipelinegraphview.PipelineGraphViewConfiguration;
import io.jenkins.plugins.pipelinegraphview.cards.RunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.cards.items.ArtifactRunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.cards.items.ChangesRunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.cards.items.TestResultRunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.utils.PipelineGraph;
import io.jenkins.plugins.pipelinegraphview.utils.PipelineGraphApi;
import io.jenkins.plugins.pipelinegraphview.utils.PipelineNodeUtil;
import io.jenkins.plugins.pipelinegraphview.utils.PipelineStep;
import io.jenkins.plugins.pipelinegraphview.utils.PipelineStepApi;
import io.jenkins.plugins.pipelinegraphview.utils.PipelineStepList;
import jakarta.servlet.ServletException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import jenkins.model.Jenkins;
import jenkins.model.Tab;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.jenkinsci.plugins.pipeline.modeldefinition.actions.RestartDeclarativePipelineAction;
import org.jenkinsci.plugins.workflow.cps.replay.ReplayAction;
import org.jenkinsci.plugins.workflow.flow.FlowExecution;
import org.jenkinsci.plugins.workflow.graph.FlowNode;
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.bind.JavaScriptMethod;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.kohsuke.stapler.verb.GET;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PipelineConsoleViewAction extends Tab {
public static final String URL_NAME = "stages";
public static final int CACHE_AGE = (int) TimeUnit.DAYS.toSeconds(1);
private static final Logger logger = LoggerFactory.getLogger(PipelineConsoleViewAction.class);
private static final JsonConfig jsonConfig = new JsonConfig();
static {
PipelineStepList.PipelineStepListJsonProcessor.configure(jsonConfig);
PipelineGraph.PipelineGraphJsonProcessor.configure(jsonConfig);
}
private final PipelineGraphApi graphApi;
private final WorkflowRun run;
private final PipelineStepApi stepApi;
public PipelineConsoleViewAction(WorkflowRun target) {
super(target);
this.run = target;
this.graphApi = new PipelineGraphApi(this.run);
this.stepApi = new PipelineStepApi(this.run);
}
@Override
public String getDisplayName() {
return Messages.stages();
}
@Override
public String getUrlName() {
return URL_NAME;
}
// Legacy - leave in case we want to update a sub section of steps (e.g. if a stage is still
// running).
@GET
@WebMethod(name = "steps")
public HttpResponse getSteps(StaplerRequest2 req) {
run.checkPermission(Item.READ);
String nodeId = req.getParameter("nodeId");
if (nodeId != null) {
return HttpResponses.okJSON(getSteps(nodeId));
} else {
return HttpResponses.errorJSON("Error getting console text");
}
}
private JSONObject getSteps(String nodeId) {
logger.debug("getSteps was passed nodeId '{}'.", nodeId);
PipelineStepList steps = stepApi.getSteps(nodeId);
JSONObject json = JSONObject.fromObject(steps, jsonConfig);
logger.debug("Steps for {}: '{}'.", nodeId, json);
return json;
}
// Return all steps to:
// - reduce number of API calls
// - remove dependency of getting list of stages in frontend.
@GET
@WebMethod(name = "allSteps")
public void getAllSteps(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
run.checkPermission(Item.READ);
PipelineStepList steps = stepApi.getAllSteps();
JSONObject json = JSONObject.fromObject(steps, jsonConfig);
logger.debug("Steps: '{}'.", json);
HttpResponse response = HttpResponses.okJSON(json);
rsp.setStatus(200);
setCache(rsp, steps.runIsComplete);
response.generateResponse(req, rsp, null);
}
private void setCache(StaplerResponse2 rsp, boolean complete) {
if (complete) {
rsp.setHeader("Cache-Control", "private, immutable, max-age=" + CACHE_AGE);
} else {
rsp.setHeader("Cache-Control", "private, no-store");
}
}
@WebMethod(name = "log")
@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressFBWarnings(
value = "RV_RETURN_VALUE_IGNORED",
justification =
"Doesn't seem to matter in practice, docs aren't clear on how to handle and most places ignore it")
public void getConsoleText(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
run.checkPermission(Item.READ);
String nodeId = req.getParameter("nodeId");
rsp.setContentType("text/plain;charset=UTF-8");
if (nodeId == null) {
logger.error("'consoleText' was not passed 'nodeId'.");
rsp.getWriter().write("Error getting console text\n");
return;
}
logger.debug("getConsoleText was passed node id '{}'.", nodeId);
// This will be a step, so return its log output.
AnnotatedLargeText<? extends FlowNode> logText = getLogForNode(nodeId);
if (logText != null) {
logText.writeLogTo(0L, rsp.getOutputStream());
return;
}
// Potentially a stage, so get the log text for the stage.
boolean foundLogs = false;
PipelineStepList steps = stepApi.getSteps(nodeId);
for (PipelineStep step : steps.steps) {
logText = getLogForNode(step.id);
if (logText != null) {
foundLogs = true;
logText.writeLogTo(0L, rsp.getOutputStream());
}
}
if (!foundLogs) {
rsp.getWriter().write("No logs found\n");
}
}
@GET
@WebMethod(name = "consoleBuildOutput")
@SuppressWarnings("ResultOfMethodCallIgnored")
@SuppressFBWarnings(
value = "RV_RETURN_VALUE_IGNORED",
justification =
"Doesn't seem to matter in practice, docs aren't clear on how to handle and most places ignore it")
public void getBuildConsole(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
run.checkPermission(Item.READ);
run.getLogText().writeHtmlTo(0L, rsp.getWriter());
}
@GET
@WebMethod(name = "exceptionText")
public HttpResponse getExceptionText(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
run.checkPermission(Item.READ);
String nodeId = req.getParameter("nodeId");
if (nodeId == null) return HttpResponses.error(400, "missing ?nodeId");
String exceptionText = getNodeExceptionText(nodeId);
return HttpResponses.text(exceptionText != null ? exceptionText : "");
}
private AnnotatedLargeText<? extends FlowNode> getLogForNode(String nodeId) throws IOException {
FlowExecution execution = run.getExecution();
if (execution != null) {
logger.debug("getLogForNode found execution.");
return PipelineNodeUtil.getLogText(execution.getNode(nodeId));
}
return null;
}
protected String getNodeExceptionText(String nodeId) throws IOException {
FlowExecution execution = run.getExecution();
if (execution != null) {
logger.debug("getNodeException found execution.");
return PipelineNodeUtil.getExceptionText(execution.getNode(nodeId));
}
return null;
}
private boolean isUnhandledException(String nodeId) throws IOException {
FlowExecution execution = run.getExecution();
if (execution != null) {
return PipelineNodeUtil.isUnhandledException(execution.getNode(nodeId));
}
return false;
}
private static long parseIntWithDefault(String s, long defaultValue) {
try {
logger.debug("Parsing user provided value of '{}'", s);
return Long.parseLong(s);
} catch (NumberFormatException e) {
logger.debug("Using default value of '{}'", defaultValue);
return defaultValue;
}
}
@SuppressWarnings("unused")
public List<RunDetailsItem> getRunDetailsItems() {
List<RunDetailsItem> runDetailsItems = new ArrayList<>();
ChangesRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
TestResultRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
ArtifactRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
return runDetailsItems;
}
public boolean isShowGraphOnBuildPage() {
return PipelineGraphViewConfiguration.get().isShowGraphOnBuildPage();
}
public boolean isBuildable() {
return run.getParent().isBuildable();
}
public boolean isBuildInProgress() {
return run.isBuilding();
}
public Permission getPermission() {
return Item.BUILD;
}
public Permission getCancelPermission() {
return Item.CANCEL;
}
public Permission getConfigurePermission() {
return Item.CONFIGURE;
}
public WorkflowRun getRun() {
return run;
}
public String getBuildDisplayName() {
return run.getDisplayName();
}
public String getBuildFullDisplayName() {
return run.getFullDisplayName();
}
public boolean isRebuildAvailable() {
Plugin rebuildPlugin = Jenkins.get().getPlugin("rebuild");
if (rebuildPlugin != null && rebuildPlugin.getWrapper().isEnabled()) {
// limit rebuild to parameterized jobs otherwise it duplicates rerun's behaviour
return run.getParent().getProperty(ParametersDefinitionProperty.class) != null;
}
return false;
}
public boolean isRestartFromStageAvailable() {
RestartDeclarativePipelineAction action = run.getAction(RestartDeclarativePipelineAction.class);
if (action != null) {
return action.isRestartEnabled();
}
return false;
}
/**
* Handles the rerun request using ReplayAction feature
*/
@RequirePOST
@JavaScriptMethod
public HttpResponse doRerun() {
run.checkPermission(Item.BUILD);
if (!run.getParent().isBuildable()) {
return HttpResponses.errorJSON(Messages.scheduled_failure());
}
ReplayAction replayAction = run.getAction(ReplayAction.class);
Queue.Item item = replayAction.run2(replayAction.getOriginalScript(), replayAction.getOriginalLoadedScripts());
if (item == null) {
return HttpResponses.errorJSON(Messages.scheduled_failure());
}
JSONObject obj = new JSONObject();
obj.put("message", Messages.scheduled_success());
obj.put("queueId", item.getId());
return HttpResponses.okJSON(obj);
}
@SuppressWarnings("unused")
@GET
@WebMethod(name = "nextBuild")
public HttpResponse hasNextBuild(StaplerRequest2 req) {
run.checkPermission(Item.READ);
String queueId = req.getParameter("queueId");
if (queueId == null || queueId.isBlank()) {
return HttpResponses.errorJSON("No queueId provided");
}
long id = Long.parseLong(queueId);
logger.debug("Searching for build with queueId: {}", id);
WorkflowRun nextRun = findBuildByQueueId(id);
if (nextRun == null) {
return HttpResponses.okJSON();
}
JSONObject obj = new JSONObject();
obj.put("nextBuildUrl", nextRun.getUrl() + URL_NAME + "/");
return HttpResponses.okJSON(obj);
}
private @CheckForNull WorkflowRun findBuildByQueueId(long queueId) {
for (WorkflowRun build : run.getParent().getBuilds()) {
if (build.getNumber() <= this.run.getNumber()) {
break;
}
if (build.getQueueId() == queueId) {
return build;
}
}
return null;
}
/**
* Handles the cancel request.
*/
@RequirePOST
@JavaScriptMethod
public HttpResponse doCancel() {
run.checkPermission(getCancelPermission());
if (run.isBuilding()) {
run.doStop();
return HttpResponses.okJSON();
}
String message =
Result.ABORTED.equals(run.getResult()) ? Messages.run_alreadyCancelled() : Messages.run_isFinished();
return HttpResponses.errorJSON(message);
}
public String getFullProjectDisplayName() {
return run.getParent().getFullDisplayName();
}
private String getBuildNumber(WorkflowRun run) {
if (run != null) {
return String.valueOf(run.getNumber());
}
return null;
}
public String getBuildUrl() {
return run.getUrl();
}
public String getPreviousBuildNumber() {
return getBuildNumber(run.getPreviousBuild());
}
public String getPreviousBuildUrl() {
WorkflowRun previousBuild = run.getPreviousBuild();
return previousBuild == null ? null : previousBuild.getUrl();
}
public String getNextBuildNumber() {
return getBuildNumber(run.getNextBuild());
}
@GET
@WebMethod(name = "tree")
public void getTree(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
run.checkPermission(Item.READ);
PipelineGraph tree = graphApi.createTree();
HttpResponse response = HttpResponses.okJSON(JSONObject.fromObject(tree, jsonConfig));
rsp.setStatus(200);
setCache(rsp, tree.complete);
response.generateResponse(req, rsp, null);
}
// Icon related methods these may appear as unused but are used by /lib/hudson/buildCaption.jelly
@SuppressWarnings("unused")
public String getUrl() {
return run.getUrl();
}
@SuppressWarnings("unused")
public BallColor getIconColor() {
return run.getIconColor();
}
@Override
public String getIconFileName() {
return "symbol-git-network-outline plugin-ionicons-api";
}
}