Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow TokenMacro in Stash server URL Fixes [JENKINS-31117] #153

Merged
merged 3 commits into from May 2, 2017
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions pom.xml
Expand Up @@ -3,7 +3,7 @@
<parent>
<groupId>org.jenkins-ci.plugins</groupId>
<artifactId>plugin</artifactId>
<version>2.11</version>
<version>2.26</version>
<relativePath />
</parent>
<packaging>hpi</packaging>
Expand All @@ -14,7 +14,7 @@
<java.level>7</java.level>
<!-- Jenkins Test Harness version you use to test the plugin. -->
<!-- For Jenkins version >= 1.580.1 use JTH 2.x or higher. -->
<jenkins-test-harness.version>2.13</jenkins-test-harness.version>
<jenkins-test-harness.version>2.19</jenkins-test-harness.version>
<!-- Other properties you may want to use:
~ hpi-plugin.version: The HPI Maven Plugin version used by the plugin..
~ stapler-plugin.version: The Stapler Maven plugin version required by the plugin.
Expand Down
Expand Up @@ -132,6 +132,7 @@ public class StashNotifier extends Notifier implements SimpleBuildStep {

// public members ----------------------------------------------------------

@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
Expand Down Expand Up @@ -376,19 +377,16 @@ protected Collection<String> lookupCommitSha1s(
*
* @param logger the logger to log messages to
* @param run
* @param stashServer
* @return the HttpClient
*/
protected HttpClient getHttpClient(PrintStream logger, Run<?, ?> run) throws Exception {
protected HttpClient getHttpClient(PrintStream logger, Run<?, ?> run, String stashServer) throws Exception {
boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer;
String stashServer = stashServerBaseUrl;

DescriptorImpl descriptor = getDescriptor();

CertificateCredentials certificateCredentials = getCredentials(CertificateCredentials.class, run.getParent());

if ("".equals(stashServer) || stashServer == null) {
stashServer = descriptor.getStashRootUrl();
}

URL url = new URL(stashServer);
HttpClientBuilder builder = HttpClientBuilder.create();
RequestConfig.Builder requestBuilder = RequestConfig.custom();
Expand Down Expand Up @@ -452,6 +450,7 @@ private SSLContext buildSslContext(boolean ignoreUnverifiedSSL, Credentials cred
}
if (ignoreUnverifiedSSL) {
TrustStrategy easyStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
Expand Down Expand Up @@ -562,7 +561,7 @@ public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project) {
}

public String getStashRootUrl() {
if ((stashRootUrl == null) || (stashRootUrl.trim().equals(""))) {
if ((stashRootUrl == null) || (stashRootUrl.trim().isEmpty())) {
return null;
} else {
return stashRootUrl;
Expand Down Expand Up @@ -610,13 +609,13 @@ public FormValidation doCheckStashServerBaseUrl(

// calculate effective url from global and local config
String url = value;
if ((url != null) && (!url.trim().equals(""))) {
if ((url != null) && (!url.trim().isEmpty())) {
url = url.trim();
} else {
url = stashRootUrl != null ? stashRootUrl.trim() : null;
}

if ((url == null) || url.equals("")) {
if ((url == null) || url.isEmpty()) {
return FormValidation.error(
"Please specify a valid URL here or in the global "
+ "configuration");
Expand All @@ -633,10 +632,12 @@ public FormValidation doCheckStashServerBaseUrl(
}

@SuppressWarnings("rawtypes")
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}

@Override
public String getDisplayName() {
return "Notify Stash Instance";
}
Expand Down Expand Up @@ -687,9 +688,13 @@ protected NotificationResult notifyStash(
final StashBuildState state) throws Exception {
HttpEntity stashBuildNotificationEntity
= newStashBuildNotificationEntity(run, state, listener);

String stashURL= expandStashURL(run, listener);

logger.println("Notifying Stash at \""+stashURL+"\"");

HttpPost req = createRequest(stashBuildNotificationEntity, run.getParent(), commitSha1);
HttpClient client = getHttpClient(logger, run);
HttpPost req = createRequest(stashBuildNotificationEntity, run.getParent(), commitSha1, stashURL);
HttpClient client = getHttpClient(logger, run, stashURL);
try {
HttpResponse res = client.execute(req);
if (res.getStatusLine().getStatusCode() != 204) {
Expand All @@ -708,7 +713,7 @@ protected NotificationResult notifyStash(
*
* @param clazz The type of {@link com.cloudbees.plugins.credentials.Credentials} to return.
* @param project The hierarchical project context within which the credentials are searched for.
* @return The first credentials of the given type that are found withing the project hierarchy, or null otherwise.
* @return The first credentials of the given type that are found within the project hierarchy, or null otherwise.
*/
private <T extends Credentials> T getCredentials(final Class<T> clazz, final Item project) {

Expand Down Expand Up @@ -777,19 +782,16 @@ protected <C extends Credentials> List<C> lookupCredentials(Class<C> type, Item
* @param stashBuildNotificationEntity a entity containing the parameters
* for Stash
* @param commitSha1 the SHA1 of the commit that was built
* @param url
* @return the HTTP POST request to the Stash build API
*/
protected HttpPost createRequest(
final HttpEntity stashBuildNotificationEntity,
final Item project,
final String commitSha1) throws AuthenticationException {

String url = stashServerBaseUrl;
DescriptorImpl descriptor = getDescriptor();

if ("".equals(url) || url == null)
url = descriptor.getStashRootUrl();

final Item project,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indentation

final String commitSha1,
final String url) throws AuthenticationException {


HttpPost req = new HttpPost(
url
+ "/rest/build-status/1.0/commits/"
Expand All @@ -815,6 +817,28 @@ protected HttpPost createRequest(
return req;
}

private String expandStashURL(Run<?, ?> run, final TaskListener listener) {
String url = stashServerBaseUrl;
DescriptorImpl descriptor = getDescriptor();
if ("".equals(url) || url == null) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be (url == null || url.isEmpty() ) as same as above changes?

url = descriptor.getStashRootUrl();
}

try {
if (!(run instanceof AbstractBuild<?, ?>)) {
url = TokenMacro.expandAll(run, new FilePath(run.getRootDir()), listener, url);
} else {
url = TokenMacro.expandAll((AbstractBuild<?, ?>) run, listener, url);
}

} catch (IOException | InterruptedException | MacroEvaluationException ex) {
PrintStream logger = listener.getLogger();
logger.println("Unable to expand Stash Server URL");
ex.printStackTrace(logger);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indentation

return url;
}

/**
* Returns the HTTP POST entity body with the JSON representation of the
* run result to be sent to the Stash build API.
Expand Down
Expand Up @@ -198,7 +198,7 @@ public void test_build_http_client_with_proxy() throws Exception {
PrintStream logger = mock(PrintStream.class);

//when
sn.getHttpClient(logger, build);
sn.getHttpClient(logger, build, "http://localhost");

//then
ArgumentCaptor<HttpHost> proxyCaptor = ArgumentCaptor.forClass(HttpHost.class);
Expand Down Expand Up @@ -239,7 +239,7 @@ public void test_build_http_client_https() throws Exception {
PrintStream logger = mock(PrintStream.class);

//when
sn.getHttpClient(logger, build);
sn.getHttpClient(logger, build,"https://localhost");

//then
verify(httpClientBuilder).setSSLSocketFactory(any(SSLConnectionSocketFactory.class));
Expand Down Expand Up @@ -535,7 +535,7 @@ public void test_createRequest() throws AuthenticationException {
when(CredentialsMatchers.firstOrNull(anyCollection(), any(CredentialsMatcher.class))).thenReturn(credential);

//when
HttpPost request = sn.createRequest(mock(HttpEntity.class), mock(Item.class), sha1);
HttpPost request = sn.createRequest(mock(HttpEntity.class), mock(Item.class), sha1, "http://localhost");

//then
assertThat(request, is(not(nullValue())));
Expand Down Expand Up @@ -682,14 +682,14 @@ private NotificationResult notifyStash(int statusCode) throws Exception {
when(buildListener.getLogger()).thenReturn(logger);
doReturn("someKey1").when(sn).getBuildKey(eq(build), eq(buildListener));
HttpPost httpPost = mock(HttpPost.class);
doReturn(httpPost).when(sn).createRequest(any(HttpEntity.class), any(Item.class), anyString());
doReturn(httpPost).when(sn).createRequest(any(HttpEntity.class), any(Item.class), anyString(), anyString());
CloseableHttpResponse resp = mock(CloseableHttpResponse.class);
StatusLine sl = mock(StatusLine.class);
when(sl.getStatusCode()).thenReturn(statusCode);
when(resp.getStatusLine()).thenReturn(sl);
when(resp.getEntity()).thenReturn(new StringEntity(""));
when(client.execute(eq(httpPost))).thenReturn(resp);
doReturn(client).when(sn).getHttpClient(any(PrintStream.class), any(AbstractBuild.class));
doReturn(client).when(sn).getHttpClient(any(PrintStream.class), any(AbstractBuild.class), anyString());
return sn.notifyStash(logger, build, sha1, buildListener, StashBuildState.FAILED);
}

Expand Down