-
Notifications
You must be signed in to change notification settings - Fork 355
/
Copy pathBitbucketBuildStatusNotifications.java
305 lines (273 loc) · 13.1 KB
/
BitbucketBuildStatusNotifications.java
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
/*
* The MIT License
*
* Copyright (c) 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 com.cloudbees.jenkins.plugins.bitbucket;
import com.cloudbees.jenkins.plugins.bitbucket.BranchDiscoveryTrait.ExcludeOriginPRBranchesSCMHeadFilter;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketApi;
import com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketBuildStatus;
import com.cloudbees.jenkins.plugins.bitbucket.client.BitbucketCloudApiClient;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.model.listeners.RunListener;
import hudson.model.listeners.SCMListener;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.annotation.CheckForNull;
import jenkins.model.JenkinsLocationConfiguration;
import jenkins.plugins.git.AbstractGitSCMSource;
import jenkins.scm.api.SCMHeadObserver;
import jenkins.scm.api.SCMRevision;
import jenkins.scm.api.SCMRevisionAction;
import jenkins.scm.api.SCMSource;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.plugins.displayurlapi.DisplayURLProvider;
/**
* This class encapsulates all Bitbucket notifications logic.
* {@link JobCompletedListener} sends a notification to Bitbucket after a build finishes.
* Only builds derived from a job that was created as part of a multi branch project will be processed by this listener.
*/
public class BitbucketBuildStatusNotifications {
private static final String SUCCESSFUL_STATE = "SUCCESSFUL";
private static final String FAILED_STATE = "FAILED";
private static final String STOPPED_STATE = "STOPPED";
private static final String INPROGRESS_STATE = "INPROGRESS";
private static String getRootURL() {
return DisplayURLProvider.get().getRoot();
}
private static String getRunURL(@NonNull Run<?, ?> build) {
JenkinsLocationConfiguration cfg = JenkinsLocationConfiguration.get();
if (cfg == null || cfg.getUrl() == null) {
throw new IllegalStateException("Could not determine job URL.");
}
return DisplayURLProvider.get().getRunURL(build);
}
/**
* Check if the build URL is compatible with Bitbucket API.
* For example, Bitbucket Cloud API requires fully qualified or IP
* Where we actively do not allow localhost
* Throws an IllegalStateException if it is not valid, or return the url otherwise
*
* @param url the URL of the build to check
* @param bitbucket the bitbucket client we are facing.
*/
static String checkURL(@NonNull String url, BitbucketApi bitbucket) {
try {
URL anURL = new URL(url);
if ("localhost".equals(anURL.getHost())) {
throw new IllegalStateException("Jenkins URL cannot start with http://localhost");
}
if ("unconfigured-jenkins-location".equals(anURL.getHost())) {
throw new IllegalStateException("Could not determine Jenkins URL.");
}
if (bitbucket instanceof BitbucketCloudApiClient && !anURL.getHost().contains(".")) {
throw new IllegalStateException(
"Please use a fully qualified name or an IP address for Jenkins URL, this is required by Bitbucket cloud");
}
return url;
} catch (MalformedURLException e) {
throw new IllegalStateException("Bad Jenkins URL");
}
}
private static void createStatus(@NonNull Run<?, ?> build, @NonNull TaskListener listener,
@NonNull BitbucketApi bitbucket, @NonNull String key, @NonNull String hash)
throws IOException, InterruptedException {
final SCMSource s = SCMSource.SourceByItem.findSource(build.getParent());
if (!(s instanceof BitbucketSCMSource)) {
return;
}
String rootUrl, url;
try {
rootUrl = getRootURL();
url = getRunURL(build);
checkURL(url, bitbucket);
} catch (IllegalStateException e) {
listener.getLogger().println("Can not determine Jenkins root URL " +
"or Jenkins URL is not a valid URL regarding Bitbucket API. " +
"Commit status notifications are disabled until a root URL is " +
"configured in Jenkins global configuration. \n" +
"IllegalStateException: " + e.getMessage());
return;
}
BitbucketSCMSource source = (BitbucketSCMSource) s;
BitbucketSCMSourceContext sourceContext = new BitbucketSCMSourceContext(null, SCMHeadObserver.none())
.withTraits(source.getTraits());
String name = build.getFullDisplayName(); // use the build number as the display name of the status
BitbucketBuildStatus status;
Result result = build.getResult();
String buildDescription = build.getDescription();
String statusDescriptionSuffix = "";
String statusDescription;
String state;
if (Result.SUCCESS.equals(result)) {
statusDescription = StringUtils.defaultIfBlank(buildDescription, "This commit looks good.");
state = SUCCESSFUL_STATE;
} else if (Result.UNSTABLE.equals(result)) {
statusDescription = StringUtils.defaultIfBlank(buildDescription, "This commit has test failures.");
if (sourceContext.sendSuccessNotificationForUnstableBuild()) {
state = SUCCESSFUL_STATE;
} else {
state = FAILED_STATE;
}
} else if (Result.FAILURE.equals(result)) {
statusDescription = StringUtils.defaultIfBlank(buildDescription, "There was a failure building this commit.");
state = FAILED_STATE;
} else if (Result.NOT_BUILT.equals(result)) {
// Bitbucket Cloud and Server support different build states.
state = (bitbucket instanceof BitbucketCloudApiClient) ? STOPPED_STATE : SUCCESSFUL_STATE;
statusDescription = StringUtils.defaultIfBlank(buildDescription, "This commit was not built (probably the build was skipped)");
} else if (result != null) { // ABORTED etc.
statusDescription = StringUtils.defaultIfBlank(buildDescription, "Something is wrong with the build of this commit.");
state = FAILED_STATE;
} else {
statusDescription = StringUtils.defaultIfBlank(buildDescription, "The build is in progress...");
state = INPROGRESS_STATE;
}
if (sourceContext.buildStatusIncludeJenkinsURL()) {
statusDescriptionSuffix = "\n" + rootUrl;
}
status = new BitbucketBuildStatus(hash, statusDescription + statusDescriptionSuffix, state, url, key, name);
new BitbucketChangesetCommentNotifier(bitbucket).buildStatus(status);
if (result != null) {
listener.getLogger().println("[Bitbucket] Build result notified");
}
}
private static @CheckForNull BitbucketSCMSource findBitbucketSCMSource(Run<?, ?> build) {
SCMSource s = SCMSource.SourceByItem.findSource(build.getParent());
return s instanceof BitbucketSCMSource ? (BitbucketSCMSource) s : null;
}
private static void sendNotifications(BitbucketSCMSource source, Run<?, ?> build, TaskListener listener)
throws IOException, InterruptedException {
String rootUrl = getRootURL();
BitbucketSCMSourceContext sourceContext = new BitbucketSCMSourceContext(null,
SCMHeadObserver.none()).withTraits(source.getTraits());
if (sourceContext.notificationsDisabled()) {
return;
}
SCMRevision r = SCMRevisionAction.getRevision(source, build);
if (r == null) {
return;
}
String hash = getHash(r);
if (hash == null) {
return;
}
boolean shareBuildKeyBetweenBranchAndPR = sourceContext
.filters().stream()
.anyMatch(filter -> filter instanceof ExcludeOriginPRBranchesSCMHeadFilter);
String key;
BitbucketApi bitbucket;
if (r instanceof PullRequestSCMRevision) {
listener.getLogger().println("[Bitbucket] Notifying pull request build result");
PullRequestSCMHead head = (PullRequestSCMHead) r.getHead();
key = getBuildKey(build, rootUrl, head.getOriginName(),
shareBuildKeyBetweenBranchAndPR, sourceContext.buildStatusIncludeJenkinsURL());
bitbucket = source.buildBitbucketClient(head);
} else {
listener.getLogger().println("[Bitbucket] Notifying commit build result");
key = getBuildKey(build, rootUrl, r.getHead().getName(),
shareBuildKeyBetweenBranchAndPR, sourceContext.buildStatusIncludeJenkinsURL());
bitbucket = source.buildBitbucketClient();
}
createStatus(build, listener, bitbucket, key, hash);
}
@CheckForNull
private static String getHash(@CheckForNull SCMRevision revision) {
if (revision instanceof PullRequestSCMRevision) {
// unwrap
revision = ((PullRequestSCMRevision) revision).getPull();
}
if (revision instanceof AbstractGitSCMSource.SCMRevisionImpl) {
return ((AbstractGitSCMSource.SCMRevisionImpl) revision).getHash();
}
return null;
}
private static String getBuildKey(@NonNull Run<?, ?> build, String rootUrl, String branch,
boolean shareBuildKeyBetweenBranchAndPR, boolean includeJenkinsURL) {
// When the ExcludeOriginPRBranchesSCMHeadFilter filter is active, we want the
// build status key to be the same between the branch project and the PR project.
// This is to avoid having two build statuses when a branch goes into PR and
// it was already built at least once as a branch.
// So the key we use is the branch name.
String key;
if (shareBuildKeyBetweenBranchAndPR) {
String folderName = build.getParent().getParent().getFullName();
key = String.format("%s/%s", folderName, branch);
} else {
key = build.getParent().getFullName(); // use the job full name as the key for the status
}
if (includeJenkinsURL) {
key = rootUrl + "/" + key;
}
return key;
}
/**
* Sends notifications to Bitbucket on Checkout (for the "In Progress" Status).
*/
@Extension
public static class JobCheckOutListener extends SCMListener {
@Override
public void onCheckout(Run<?, ?> build, SCM scm, FilePath workspace, TaskListener listener, File changelogFile,
SCMRevisionState pollingBaseline) throws Exception {
BitbucketSCMSource source = findBitbucketSCMSource(build);
if (source == null) {
return;
}
boolean hasCompletedCheckoutBefore =
build.getAction(FirstCheckoutCompletedInvisibleAction.class) != null;
if (!hasCompletedCheckoutBefore) {
build.addAction(new FirstCheckoutCompletedInvisibleAction());
try {
sendNotifications(source, build, listener);
} catch (IOException | InterruptedException e) {
e.printStackTrace(listener.error("Could not send notifications"));
}
}
}
}
/**
* Sends notifications to Bitbucket on Run completed.
*/
@Extension
public static class JobCompletedListener extends RunListener<Run<?, ?>> {
@Override
public void onCompleted(Run<?, ?> build, TaskListener listener) {
BitbucketSCMSource source = findBitbucketSCMSource(build);
if (source == null) {
return;
}
try {
sendNotifications(source, build, listener);
} catch (IOException | InterruptedException e) {
e.printStackTrace(listener.error("Could not send notifications"));
}
}
}
}