-
-
Notifications
You must be signed in to change notification settings - Fork 295
Expand file tree
/
Copy pathJiraCreateIssueNotifier.java
More file actions
547 lines (473 loc) · 18.6 KB
/
JiraCreateIssueNotifier.java
File metadata and controls
547 lines (473 loc) · 18.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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
package hudson.plugins.jira;
import static hudson.plugins.jira.JiraRestService.BUG_ISSUE_TYPE_ID;
import com.atlassian.jira.rest.client.api.RestClientException;
import com.atlassian.jira.rest.client.api.StatusCategory;
import com.atlassian.jira.rest.client.api.domain.Issue;
import com.atlassian.jira.rest.client.api.domain.IssueType;
import com.atlassian.jira.rest.client.api.domain.Priority;
import com.atlassian.jira.rest.client.api.domain.Status;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Item;
import hudson.model.Result;
import hudson.model.TaskListener;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest2;
/**
* When a build fails it creates jira issues.
* Repeated failures does not create a new issue but update the existing issue
* until the issue is closed.
*
* @author Rupali Behera rupali@vertisinfotech.com
*/
public class JiraCreateIssueNotifier extends Notifier {
private static final Logger LOG = Logger.getLogger(JiraCreateIssueNotifier.class.getName());
private String projectKey;
private String testDescription;
private String assignee;
private String component;
private Long typeId;
private Long priorityId;
private Integer actionIdOnSuccess;
enum finishedStatuses {
Closed,
Done,
Resolved
}
@DataBoundConstructor
public JiraCreateIssueNotifier(
String projectKey,
String testDescription,
String assignee,
String component,
Long typeId,
Long priorityId,
Integer actionIdOnSuccess) {
if (projectKey == null) {
throw new IllegalArgumentException("Project key cannot be null");
}
this.projectKey = projectKey;
this.testDescription = testDescription;
this.assignee = assignee;
this.component = component;
this.typeId = typeId;
this.priorityId = priorityId;
this.actionIdOnSuccess = actionIdOnSuccess;
}
public String getProjectKey() {
return projectKey;
}
public void setProjectKey(String projectKey) {
this.projectKey = projectKey;
}
public String getTestDescription() {
return testDescription;
}
public void setTestDescription(String testDescription) {
this.testDescription = testDescription;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public Long getTypeId() {
return typeId;
}
public Long getPriorityId() {
return priorityId;
}
public Integer getActionIdOnSuccess() {
return actionIdOnSuccess;
}
@Override
public BuildStepDescriptor<Publisher> getDescriptor() {
return DESCRIPTOR;
}
@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)
throws IOException, InterruptedException {
String jobDirPath = build.getProject().getBuildDir().getPath();
String filename = jobDirPath + File.separator + "issue.txt";
EnvVars vars = build.getEnvironment(TaskListener.NULL);
Result currentBuildResult = build.getResult();
Result previousBuildResult = null;
AbstractBuild<?, ?> previousBuild = build.getPreviousCompletedBuild();
if (previousBuild != null) {
previousBuildResult = previousBuild.getResult();
}
if (currentBuildResult != Result.ABORTED && previousBuild != null) {
try {
if (currentBuildResult == Result.FAILURE) {
currentBuildResultFailure(build, listener, previousBuildResult, filename, vars);
}
if (currentBuildResult == Result.SUCCESS) {
currentBuildResultSuccess(build, listener, previousBuildResult, filename, vars);
}
} catch (RestClientException e) {
listener.getLogger().println(e.getMessage());
}
}
return true;
}
/**
* It creates a issue in the given project, with the given description,
* assignee,components and summary.
* The created issue ID is saved to the file at "filename".
*
* @param build
* @param filename
* @return issue id
* @throws IOException
* @throws InterruptedException
*/
private Issue createJiraIssue(AbstractBuild<?, ?> build, String filename) throws IOException, InterruptedException {
EnvVars vars = build.getEnvironment(TaskListener.NULL);
JiraSession session = getJiraSession(build);
String buildName = getBuildName(vars);
String summary = String.format("Build %s failed", buildName);
String description = String.format(
"%s%n%nThe build %s has failed.%nFirst failed run: %s",
(this.testDescription.equals("")) ? "No description is provided" : vars.expand(this.testDescription),
buildName,
getBuildDetailsString(vars));
Iterable<String> components = Arrays.stream(component.split(","))
.filter(s -> !StringUtils.isEmpty(s))
.map(StringUtils::trim)
.collect(Collectors.toList());
Long type = typeId;
if (type == null || type == 0) { // zero is default / invalid selection
LOG.info("Returning default issue type id " + BUG_ISSUE_TYPE_ID);
type = BUG_ISSUE_TYPE_ID;
}
Long priority = priorityId;
if (priority != null && priority == 0) {
priority = null; // remove invalid priority selection
}
Issue issue = session.createIssue(projectKey, description, assignee, components, summary, type, priority);
writeInFile(filename, issue);
return issue;
}
/**
* Returns the status of the issue.
*
* @param build
* @param id
* @return Status of the issue
* @throws IOException
*/
private Status getStatus(AbstractBuild<?, ?> build, String id) throws IOException {
JiraSession session = getJiraSession(build);
Issue issue = session.getIssueByKey(id);
return issue.getStatus();
}
/**
* Adds a comment to the existing issue.
*
* @param build
* @param listener
* @param id
* @param comment
* @throws IOException
*/
private void addComment(AbstractBuild<?, ?> build, BuildListener listener, String id, String comment)
throws IOException {
JiraSession session = getJiraSession(build);
session.addCommentWithoutConstrains(id, comment);
listener.getLogger().println(String.format("[%s] Commented issue", id));
}
/**
* Returns the issue id
*
* @param filename
* @return
* @throws IOException
* @throws InterruptedException
*/
private String getIssue(String filename) throws IOException, InterruptedException {
String issueId = "";
Path path = Paths.get(filename);
if (Files.notExists(path)) {
return null;
}
try (BufferedReader br = Files.newBufferedReader(path)) {
String issue;
while ((issue = br.readLine()) != null) {
issueId = issue;
}
return StringUtils.trimToNull(issueId);
} catch (FileNotFoundException e) {
return null;
}
}
JiraSite getSiteForProject(AbstractProject<?, ?> project) {
return JiraSite.get(project);
}
/**
* Returns the jira session.
*
* @param build
* @return JiraSession
* @throws IOException
*/
private JiraSession getJiraSession(AbstractBuild<?, ?> build) throws IOException {
JiraSite site = getSiteForProject(build.getProject());
if (site == null) {
throw new IllegalStateException(
"Jira site needs to be configured in the project " + build.getFullDisplayName());
}
JiraSession session = site.getSession(build.getProject());
if (session == null) {
throw new IllegalStateException("Remote access for Jira isn't configured in Jenkins");
}
return session;
}
/**
* @param filename
*/
private void deleteFile(String filename) {
File file = new File(filename);
if (file.exists() && !file.delete()) {
LOG.warning("WARNING: couldn't delete file: " + filename);
}
}
/**
* write's the issue id in the file, which is stored in the Job's directory
*
* @param filename
* @param issue
* @throws FileNotFoundException
*/
private void writeInFile(String filename, Issue issue) throws IOException {
// olamy really weird to write an empty file especially with null
// but backward compat and unit tests assert that.....
// can't believe such stuff has been merged......
try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(filename))) {
bw.write(issue.getKey() == null ? "null" : issue.getKey());
}
}
/**
* when the current build fails it checks for the previous build's result,
* creates jira issue if the result was "success" and adds comment if the result
* was "fail".
* It adds comment until the previously created issue is closed.
*/
private void currentBuildResultFailure(
AbstractBuild<?, ?> build,
BuildListener listener,
Result previousBuildResult,
String filename,
EnvVars vars)
throws InterruptedException, IOException, RestClientException {
if (previousBuildResult == Result.FAILURE) {
String comment = String.format("Build is still failing.%nFailed run: %s", getBuildDetailsString(vars));
// Get the issue-id which was filed when the previous built failed
String issueId = getIssue(filename);
if (issueId != null) {
try {
// The status of the issue which was filed when the previous build failed
Status status = getStatus(build, issueId);
// Issue Closed, need to open new one
if (isDone(status)) {
listener.getLogger().println("The previous build also failed but the issue is closed");
deleteFile(filename);
Issue issue = createJiraIssue(build, filename);
LOG.info(String.format("[%s] created.", issue.getKey()));
listener.getLogger().println("Build failed, created Jira issue " + issue.getKey());
} else {
addComment(build, listener, issueId, comment);
LOG.info(String.format("[%s] The previous build also failed, comment added.", issueId));
}
} catch (IOException e) {
LOG.warning(String.format("[%s] - error processing Jira change: %s", issueId, e.getMessage()));
}
}
}
if (previousBuildResult == Result.SUCCESS || previousBuildResult == Result.ABORTED) {
try {
Issue issue = createJiraIssue(build, filename);
LOG.info(String.format("[%s] created.", issue.getKey()));
listener.getLogger().println("Build failed, created Jira issue " + issue.getKey());
} catch (IOException e) {
listener.error("Error creating Jira issue : " + e.getMessage());
LOG.warning("Error creating Jira issue\n" + e.getMessage());
}
}
}
/**
* when the current build's result is "success",
* it checks for the previous build's result and adds comment until the
* previously created issue is closed.
*
* @param build
* @param previousBuildResult
* @param filename
* @param vars
* @throws InterruptedException
* @throws IOException
*/
private void currentBuildResultSuccess(
AbstractBuild<?, ?> build,
BuildListener listener,
Result previousBuildResult,
String filename,
EnvVars vars)
throws InterruptedException, IOException {
if (previousBuildResult == Result.FAILURE || previousBuildResult == Result.SUCCESS) {
String comment =
String.format("Previously failing build now is OK.%n Passed run: %s", getBuildDetailsString(vars));
String issueId = getIssue(filename);
// if issue exists it will check the status and comment or delete the file
// accordingly
if (issueId != null) {
try {
Status status = getStatus(build, issueId);
// if issue is in closed status
if (isDone(status)) {
LOG.info(String.format("%s is closed", issueId));
deleteFile(filename);
} else {
LOG.info(String.format("%s is not closed, comment was added.", issueId));
addComment(build, listener, issueId, comment);
if (actionIdOnSuccess != null && actionIdOnSuccess > 0) {
progressWorkflowAction(build, issueId, actionIdOnSuccess);
}
}
} catch (IOException e) {
listener.error("Error updating Jira issue " + issueId + " : " + e.getMessage());
LOG.warning("Error updating Jira issue " + issueId + "\n" + e);
}
}
}
}
static boolean isDone(Status status) {
if (status.getName().equalsIgnoreCase(finishedStatuses.Closed.toString())
|| status.getName().equalsIgnoreCase(finishedStatuses.Resolved.toString())
|| status.getName().equalsIgnoreCase(finishedStatuses.Done.toString())) {
return true;
}
StatusCategory category = status.getStatusCategory();
if (category == null) {
return false;
}
return "done".equals(category.getKey());
}
private void progressWorkflowAction(AbstractBuild<?, ?> build, String issueId, Integer actionId)
throws IOException {
JiraSession session = getJiraSession(build);
session.progressWorkflowAction(issueId, actionId);
}
/**
* Returns build details string in wiki format, with hyperlinks.
*
* @param vars
* @return
*/
private String getBuildDetailsString(EnvVars vars) {
final String buildURL = vars.get("BUILD_URL");
return String.format("[%s|%s] [console log|%s]", getBuildName(vars), buildURL, buildURL.concat("console"));
}
/**
* Returns build name in format BUILD#10
*
* @param vars
* @return String
*/
private String getBuildName(EnvVars vars) {
final String jobName = vars.get("JOB_NAME");
final String buildNumber = vars.get("BUILD_NUMBER");
return String.format("%s #%s", jobName, buildNumber);
}
public static class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public DescriptorImpl() {
super(JiraCreateIssueNotifier.class);
}
public FormValidation doCheckProjectKey(@QueryParameter String value) throws IOException {
if (value.length() == 0) {
return FormValidation.error("Please set the project key");
}
return FormValidation.ok();
}
public ListBoxModel doFillPriorityIdItems(@AncestorInPath final Item item) {
ListBoxModel items = new ListBoxModel().add(""); // optional field
List<JiraSite> sites = JiraSite.getJiraSites(item);
for (JiraSite site : sites) {
JiraSession session = site.getSession(item);
if (session != null) {
for (Priority priority : session.getPriorities()) {
items.add("[" + site.getName() + "] " + priority.getName(), String.valueOf(priority.getId()));
}
}
}
return items;
}
public ListBoxModel doFillTypeIdItems(@AncestorInPath final Item item) {
ListBoxModel items = new ListBoxModel().add(""); // optional field
List<JiraSite> sites = JiraSite.getJiraSites(item);
for (JiraSite site : sites) {
JiraSession session = site.getSession(item);
if (session != null) {
for (IssueType type : session.getIssueTypes()) {
items.add("[" + site.getName() + "] " + type.getName(), String.valueOf(type.getId()));
}
}
}
return items;
}
@Override
public JiraCreateIssueNotifier newInstance(StaplerRequest2 req, JSONObject formData) throws FormException {
return req.bindJSON(JiraCreateIssueNotifier.class, formData);
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@Override
public String getDisplayName() {
return Messages.JiraCreateIssueNotifier_DisplayName();
}
@Override
public String getHelpFile() {
return "/plugin/jira/help-jira-create-issue.html";
}
}
}