Skip to content
This repository was archived by the owner on Mar 14, 2023. It is now read-only.

Commit 2e23e55

Browse files
author
Bernhard Grünewaldt
committed
1.1.0 support pipeline jobs. support gh webhook ping event.
1 parent 2154466 commit 2e23e55

File tree

7 files changed

+286
-14
lines changed

7 files changed

+286
-14
lines changed

DEVELOPMENT.md

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,45 @@
22

33
```bash
44
mvn compile && rm -rf work/ && mvn hpi:run
5+
// configure GitHub Secret to `foobar23` via webui
6+
```
7+
8+
9+
**Testcase: Push Event**
510

11+
```bash
612
curl -X POST \
713
-H "Content-Type: application/json" \
814
-H "x-hub-signature: sha1=5b8a54ee48efb1fbe06e3e4fc5d120680eaa2a22" \
915
-d @test-webhook-payload.json \
1016
http://localhost:8080/jenkins/github-webhook-build-trigger/receive
1117
```
1218

13-
* With GitHub Secret being: `foobar23`
19+
 
20+
21+
22+
**Testcase: Ping Event**
23+
24+
Initial webhook created request.
25+
Only fired once when you setup the webhook on github. See: https://developer.github.com/webhooks/#ping-event
26+
27+
```bash
28+
curl -X POST \
29+
-H "Content-Type: application/json" \
30+
-H "x-hub-signature: sha1=c203f51e9317264c6716ee0c6fed59d604674885" \
31+
-d @test-webhook-init-payload.json \
32+
http://localhost:8080/jenkins/github-webhook-build-trigger/receive
33+
```
34+
35+
 
36+
37+
**x-hub-signature**
38+
39+
Create an sha1 hash for a payload.json:
40+
41+
```bash
42+
cat test-webhook-init-payload.json | openssl dgst -sha1 -hmac "foobar23"
43+
```
1444

1545
### Build hpi
1646

README.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,37 @@ git clone --single-branch \
195195
source
196196
```
197197

198+
 
199+
200+
**Usage with Pipeline Jobs**
201+
202+
Since version 1.1.0 [Pipeline Job Types](https://jenkins.io/doc/book/pipeline/) (NOT MultiBranch Pipeline) are supported.
203+
204+
Make sure you have at least the following Plugins installed
205+
206+
```
207+
Pipeline: Groovy
208+
Pipeline: Job
209+
Pipeline: API
210+
Pipeline: Step API
211+
Pipeline: Stage Step
212+
Pipeline: Basic Steps
213+
Pipeline: Model API
214+
```
215+
216+
A simple **`Jenkinsfile`** could look like this:
217+
218+
```
219+
node {
220+
stage('foo') {
221+
sh 'git clone --single-branch --branch ${env.GWBT_BRANCH} https://github.com/${env.GWBT_REPO_FULL_NAME}.git source'
222+
dir('source') {
223+
sh 'npm install'
224+
}
225+
}
226+
}
227+
```
228+
198229
-----
199230

200231
 

pom.xml

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,12 @@
66
<parent>
77
<groupId>org.jenkins-ci.plugins</groupId>
88
<artifactId>plugin</artifactId>
9-
<version>2.25</version>
9+
<version>2.33</version>
1010
<relativePath/>
1111
</parent>
1212
<groupId>io.codeclou.jenkins.github.webhook.notifier.plugin</groupId>
1313
<artifactId>github-webhook-notifier-plugin</artifactId>
14-
<version>1.0.1</version>
14+
<version>1.1.0</version>
1515
<packaging>hpi</packaging>
1616

1717
<name>github-webhook-notifier-plugin</name>
@@ -52,5 +52,15 @@
5252
<artifactId>commons-io</artifactId>
5353
<version>2.5</version>
5454
</dependency>
55+
<dependency>
56+
<groupId>org.jenkins-ci.plugins.workflow</groupId>
57+
<artifactId>workflow-job</artifactId>
58+
<version>2.5</version>
59+
<optional>true</optional>
60+
</dependency>
5561
</dependencies>
62+
<!-- https://wiki.jenkins.io/display/JENKINS/Choosing+Jenkins+version+to+build+against -->
63+
<properties>
64+
<jenkins.version>2.73</jenkins.version>
65+
</properties>
5666
</project>

src/main/java/io/codeclou/jenkins/githubwebhookbuildtriggerplugin/EnvironmentContributionAction.java

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,11 @@
55
package io.codeclou.jenkins.githubwebhookbuildtriggerplugin;
66

77
import hudson.EnvVars;
8-
import hudson.model.AbstractBuild;
9-
import hudson.model.EnvironmentContributingAction;
8+
import hudson.model.*;
109

10+
import java.util.ArrayList;
1111
import java.util.HashMap;
12+
import java.util.List;
1213
import java.util.Map;
1314

1415
/*
@@ -48,7 +49,7 @@ public EnvironmentContributionAction(GithubWebhookPayload payload) {
4849
* converts "refs/heads/develop" to "develop"
4950
*/
5051
private String normalizeBranchNameOrEmptyString(String branchname) {
51-
if (branchname.startsWith("refs/heads/")) {
52+
if (branchname != null && branchname.startsWith("refs/heads/")) {
5253
return branchname.replace("refs/heads/", "");
5354
}
5455
return "";
@@ -58,7 +59,7 @@ private String normalizeBranchNameOrEmptyString(String branchname) {
5859
* converts "refs/tags/1.0.0" to "1.0.0"
5960
*/
6061
private String normalizeTagNameOrEmptyString(String tagname) {
61-
if (tagname.startsWith("refs/tags/")) {
62+
if (tagname != null && tagname.startsWith("refs/tags/")) {
6263
return tagname.replace("refs/tags/", "");
6364
}
6465
return "";
@@ -90,4 +91,19 @@ public void buildEnvVars(AbstractBuild<?, ?> build, EnvVars env) {
9091
env.putAll(environmentVariables);
9192
}
9293
}
94+
95+
/**
96+
* Since WorkflowJob does not support EnvironmentContributionAction yet,
97+
* we need a ParametersAction filled with List ParameterValue
98+
* See: https://github.com/jenkinsci/workflow-job-plugin/blob/124b171b76394728f9c8504829cf6857abc8bdb5/src/main/java/org/jenkinsci/plugins/workflow/job/WorkflowRun.java#L435
99+
*/
100+
public ParametersAction transform() {
101+
List<ParameterValue> paramValues = new ArrayList<>();
102+
List<String> safeParams = new ArrayList<>();
103+
for (Map.Entry<String, String> envVar : environmentVariables.entrySet()) {
104+
paramValues.add(new StringParameterValue(envVar.getKey(), envVar.getValue(), envVar.getValue()));
105+
safeParams.add(envVar.getKey());
106+
}
107+
return new ParametersAction(paramValues, safeParams);
108+
}
93109
}

src/main/java/io/codeclou/jenkins/githubwebhookbuildtriggerplugin/GithubWebhookBuildTriggerAction.java

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,30 @@
66

77
import com.google.gson.Gson;
88
import com.google.gson.JsonSyntaxException;
9+
import hudson.EnvVars;
910
import hudson.Extension;
1011
import hudson.model.*;
12+
import hudson.model.queue.QueueTaskFuture;
1113
import hudson.util.HttpResponses;
1214
import io.codeclou.jenkins.githubwebhookbuildtriggerplugin.config.GithubWebhookBuildTriggerPluginBuilder;
1315
import io.codeclou.jenkins.githubwebhookbuildtriggerplugin.webhooksecret.GitHubWebhookUtility;
1416
import jenkins.model.Jenkins;
1517
import org.apache.commons.io.IOUtils;
18+
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
19+
import org.jenkinsci.plugins.workflow.job.WorkflowRun;
1620
import org.kohsuke.stapler.HttpResponse;
1721
import org.kohsuke.stapler.StaplerRequest;
1822
import org.kohsuke.stapler.interceptor.RequirePOST;
1923

2024
import javax.servlet.ServletException;
2125
import javax.servlet.http.HttpServletRequest;
22-
import javax.swing.plaf.basic.BasicToolTipUI;
2326
import java.io.IOException;
2427
import java.io.StringWriter;
2528
import java.util.ArrayList;
2629
import java.util.Collection;
2730

2831
@Extension
29-
public class GithubWebhookBuildTriggerAction implements UnprotectedRootAction {
32+
public class GithubWebhookBuildTriggerAction implements UnprotectedRootAction, EnvironmentContributingAction {
3033

3134
@Override
3235
public String getUrlName() {
@@ -65,7 +68,7 @@ public HttpResponse doReceive(HttpServletRequest request, StaplerRequest stapler
6568
String webhookSecretAsConfiguredByUser = GithubWebhookBuildTriggerPluginBuilder.DescriptorImpl.getDescriptor().getWebhookSecret();
6669
String webhookSecretMessage ="validating webhook payload against wevhook secret.";
6770
info.append(">> webhook secret validation").append("\n");
68-
if (webhookSecretAsConfiguredByUser == null) {
71+
if (webhookSecretAsConfiguredByUser == null || webhookSecretAsConfiguredByUser.isEmpty()) {
6972
webhookSecretMessage = " skipping validation since no webhook secret is configured in \n" +
7073
" 'Jenkins' -> 'Configure' tab under 'Github Webhook Build Trigger' section.";
7174
} else {
@@ -77,11 +80,23 @@ public HttpResponse doReceive(HttpServletRequest request, StaplerRequest stapler
7780
webhookSecretMessage = " ok. Webhook secret validates against " + githubSignature + "\n";
7881
}
7982
info.append(webhookSecretMessage).append("\n\n");
83+
8084
//
81-
// PAYLOAD TO ENVVARS
85+
// CHECK IF INITIAL REQUEST (see test-webhook-init-payload.json)
86+
// See: https://developer.github.com/webhooks/#ping-event
8287
//
88+
if (githubWebhookPayload.getHook_id() != null) {
89+
info.append(">> ping request received: your webhook with ID ");
90+
info.append(githubWebhookPayload.getHook_id());
91+
info.append(" is working :)\n");
92+
return HttpResponses.plainText(this.getTextEnvelopedInBanner(info.toString()));
93+
}
8394

95+
//
96+
// PAYLOAD TO ENVVARS
97+
//
8498
EnvironmentContributionAction environmentContributionAction = new EnvironmentContributionAction(githubWebhookPayload);
99+
85100
//
86101
// TRIGGER JOBS
87102
//
@@ -103,10 +118,25 @@ public HttpResponse doReceive(HttpServletRequest request, StaplerRequest stapler
103118
}
104119
for (Job job: jobs) {
105120
if (job.getName().startsWith(jobNamePrefix) && ! jobsAlreadyTriggered.contains(job.getName())) {
106-
jobsTriggered.append(" ").append(job.getName()).append("\n");
107121
jobsAlreadyTriggered.add(job.getName());
108-
AbstractProject projectScheduable = (AbstractProject) job;
109-
projectScheduable.scheduleBuild(0, cause, environmentContributionAction);
122+
if (job instanceof WorkflowJob) {
123+
WorkflowJob wjob = (WorkflowJob) job;
124+
if (wjob.isBuildable()) {
125+
jobsTriggered.append(" WORKFLOWJOB> ").append(job.getName()).append(" TRIGGERED\n");
126+
wjob.addAction(environmentContributionAction.transform());
127+
wjob.scheduleBuild(0, cause);
128+
} else {
129+
jobsTriggered.append(" WORKFLOWJOB> ").append(job.getName()).append(" NOT BUILDABLE. SKIPPING.\n");
130+
}
131+
} else {
132+
AbstractProject projectScheduable = (AbstractProject) job;
133+
if (job.isBuildable()) {
134+
jobsTriggered.append(" CLASSICJOB> ").append(job.getName()).append(" TRIGGERED\n");
135+
projectScheduable.scheduleBuild(0, cause, environmentContributionAction);
136+
} else {
137+
jobsTriggered.append(" CLASSICJOB> ").append(job.getName()).append(" NOT BUILDABLE. SKIPPING.\n");
138+
}
139+
}
110140
}
111141
}
112142
//
@@ -139,4 +169,9 @@ private String getTextEnvelopedInBanner(String text) {
139169
banner.append("\n----------------------------------------------------------------------------------\n");
140170
return banner.toString();
141171
}
172+
173+
@Override
174+
public void buildEnvVars(AbstractBuild<?, ?> abstractBuild, EnvVars envVars) {
175+
176+
}
142177
}

src/main/java/io/codeclou/jenkins/githubwebhookbuildtriggerplugin/GithubWebhookPayload.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,11 @@
1010
*/
1111
public class GithubWebhookPayload {
1212

13+
/*
14+
* hook_id is only set on initial request when the webhook is created.
15+
* See: https://developer.github.com/webhooks/#ping-event
16+
*/
17+
private Long hook_id;
1318
private String ref;
1419
private String before;
1520
private String after;
@@ -51,6 +56,14 @@ public void setRepository(GithubWebhookPayloadRepository repository) {
5156
this.repository = repository;
5257
}
5358

59+
public Long getHook_id() {
60+
return hook_id;
61+
}
62+
63+
public void setHook_id(Long hook_id) {
64+
this.hook_id = hook_id;
65+
}
66+
5467
public class GithubWebhookPayloadRepository {
5568
private String clone_url;
5669
private String html_url;

0 commit comments

Comments
 (0)