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
363 lines (323 loc) · 14.2 KB
/
PipelineConsoleViewAction.java
File metadata and controls
363 lines (323 loc) · 14.2 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
package io.jenkins.plugins.pipelinegraphview.consoleview;
import static io.jenkins.plugins.pipelinegraphview.utils.PipelineGraphApi.BuildScheduleResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.console.AnnotatedLargeText;
import hudson.model.Result;
import hudson.util.HttpResponses;
import io.jenkins.plugins.pipelinegraphview.Messages;
import io.jenkins.plugins.pipelinegraphview.PipelineGraphViewConfiguration;
import io.jenkins.plugins.pipelinegraphview.cards.RunDetailsCard;
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.SCMRunDetailsItems;
import io.jenkins.plugins.pipelinegraphview.cards.items.TestResultRunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.cards.items.TimingRunDetailsItems;
import io.jenkins.plugins.pipelinegraphview.cards.items.UpstreamCauseRunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.cards.items.UserIdCauseRunDetailsItem;
import io.jenkins.plugins.pipelinegraphview.utils.AbstractPipelineViewAction;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import net.sf.json.JSONObject;
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 AbstractPipelineViewAction {
public static final long LOG_THRESHOLD = 150 * 1024; // 150KB
public static final String URL_NAME = "pipeline-overview";
private static final Logger logger = LoggerFactory.getLogger(PipelineConsoleViewAction.class);
private final WorkflowRun target;
private final PipelineStepApi stepApi;
private static final ObjectMapper MAPPER = new ObjectMapper();
public PipelineConsoleViewAction(WorkflowRun target) {
super(target);
this.target = target;
this.stepApi = new PipelineStepApi(target);
}
@Override
public String getDisplayName() {
return "Pipeline Overview";
}
@Override
public String getUrlName() {
return URL_NAME;
}
@Override
public String getIconClassName() {
return "symbol-git-network-outline plugin-ionicons-api";
}
public String getDurationString() {
return run.getDurationString();
}
public String getStartTimeString() {
return run.getTimestampString();
}
public String getUrl() {
return target.getUrl();
}
/**
* Handles the rerun request using ReplayAction feature
*/
@RequirePOST
@JavaScriptMethod
public HttpResponse doRerun() {
BuildScheduleResult result = api.scheduleBuild(run -> {
ReplayAction replayAction = run.getAction(ReplayAction.class);
return replayAction.run2(replayAction.getOriginalScript(), replayAction.getOriginalLoadedScripts());
});
if (result instanceof BuildScheduleResult.NotScheduled nope) {
return HttpResponses.errorJSON(nope.message());
}
JSONObject obj = new JSONObject();
BuildScheduleResult.Scheduled scheduled = (BuildScheduleResult.Scheduled) result;
obj.put("buildNumber", scheduled.buildNumber());
obj.put("message", scheduled.message());
return HttpResponses.okJSON(obj);
}
/**
* Handles the cancel request.
*/
@RequirePOST
@JavaScriptMethod
public HttpResponse doCancel() {
if (run == null) {
return HttpResponses.errorJSON("No run to cancel");
}
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);
}
// 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) throws IOException {
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) throws IOException {
logger.debug("getSteps was passed nodeId '{}'.", nodeId);
PipelineStepList steps = stepApi.getSteps(nodeId);
String stepsJson = MAPPER.writeValueAsString(steps);
if (logger.isDebugEnabled()) {
logger.debug("Steps for {}: '{}'.", nodeId, stepsJson);
}
return JSONObject.fromObject(stepsJson);
}
// Return all steps to:
// - reduce number of API calls
// - remove dependency of getting list of stages in frontend.
@GET
@WebMethod(name = "allSteps")
public HttpResponse getAllSteps(StaplerRequest2 req) throws IOException {
return HttpResponses.okJSON(getAllSteps());
}
// Private method for testing.
protected JSONObject getAllSteps() throws IOException {
PipelineStepList steps = stepApi.getAllSteps();
String stepsJson = MAPPER.writeValueAsString(steps);
if (logger.isDebugEnabled()) {
logger.debug("Steps: '{}'.", stepsJson);
}
return JSONObject.fromObject(stepsJson);
}
@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 {
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.getSteps()) {
logText = getLogForNode(step.getId());
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.getLogText().writeHtmlTo(0L, rsp.getWriter());
}
/*
* The default behavior of this functions differs from 'getConsoleOutput' in that it will use LOG_THRESHOLD from the end of the string.
* Note: if 'startByte' is negative and falls outside of the console text then we will start from byte 0.
*
* FIXME: This is not performant and needs to be re-written to not buffer in memory. Avoiding JSON for log text.
*
* Example:
* {
* "startByte": 0,
* "endByte": 13,
* "text": "Hello, world!"
* }
*/
@GET
@WebMethod(name = "consoleOutput")
public HttpResponse getConsoleOutput(StaplerRequest2 req) throws IOException {
String nodeId = req.getParameter("nodeId");
if (nodeId == null) {
logger.error("'consoleJson' was not passed 'nodeId'.");
return HttpResponses.errorJSON("Error getting console json");
}
logger.debug("getConsoleOutput was passed node id '{}'.", nodeId);
// This will be a step, so return it's log output.
// startByte to start getting data from. If negative will startByte from end of string with
// LOG_THRESHOLD.
Long startByte = parseIntWithDefault(req.getParameter("startByte"), -LOG_THRESHOLD);
JSONObject data = getConsoleOutputJson(nodeId, startByte);
if (data == null) {
return HttpResponses.errorJSON("Something went wrong - check Jenkins logs.");
}
return HttpResponses.okJSON(data);
}
protected JSONObject getConsoleOutputJson(String nodeId, Long requestStartByte) throws IOException {
Long startByte = 0L;
long endByte = 0L;
long textLength;
String text = "";
AnnotatedLargeText<? extends FlowNode> logText = getLogForNode(nodeId);
if (logText != null) {
textLength = logText.length();
// positive startByte
if (requestStartByte > textLength) {
// Avoid resource leak.
logger.error("consoleJson - user requested startByte larger than console output.");
return null;
}
// if startByte is negative make sure we don't try and get a byte before 0.
if (requestStartByte < 0L) {
logger.debug("consoleJson - requested negative startByte '{}'.", requestStartByte);
startByte = textLength + requestStartByte;
if (startByte < 0L) {
logger.debug(
"consoleJson - requested negative startByte '{}' out of bounds, starting at 0.",
requestStartByte);
startByte = 0L;
}
} else {
startByte = requestStartByte;
}
logger.debug("Returning '{}' bytes from 'getConsoleOutput'.", textLength - startByte);
text = PipelineNodeUtil.convertLogToString(logText, startByte);
endByte = textLength;
}
// If has an exception, return the exception text (inc. stacktrace).
if (isUnhandledException(nodeId)) {
// Set logText to exception text. This is a little hacky - maybe it would be better update the
// frontend to handle steps and exceptions differently?
String nodeExceptionText = getNodeExceptionText(nodeId);
if (nodeExceptionText != null) {
text += nodeExceptionText;
}
endByte += text.length();
}
HashMap<String, Object> response = new HashMap<>();
response.put("text", text);
response.put("startByte", startByte);
response.put("endByte", endByte);
return JSONObject.fromObject(response);
}
private AnnotatedLargeText<? extends FlowNode> getLogForNode(String nodeId) throws IOException {
FlowExecution execution = target.getExecution();
if (execution != null) {
logger.debug("getLogForNode found execution.");
return PipelineNodeUtil.getLogText(execution.getNode(nodeId));
}
return null;
}
private String getNodeExceptionText(String nodeId) throws IOException {
FlowExecution execution = target.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 = target.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 RunDetailsCard getRunDetailsCard() {
List<RunDetailsItem> runDetailsItems = new ArrayList<>(SCMRunDetailsItems.get(run));
if (!runDetailsItems.isEmpty()) {
runDetailsItems.add(RunDetailsItem.SEPARATOR);
}
UpstreamCauseRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
UserIdCauseRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
runDetailsItems.addAll(TimingRunDetailsItems.get(run));
ChangesRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
TestResultRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
ArtifactRunDetailsItem.get(run).ifPresent(runDetailsItems::add);
return new RunDetailsCard(runDetailsItems);
}
public boolean isShowGraphOnBuildPage() {
return PipelineGraphViewConfiguration.get().isShowGraphOnBuildPage();
}
}