77import com .google .gson .Gson ;
88import com .google .gson .JsonSyntaxException ;
99import hudson .Extension ;
10- import hudson .model .UnprotectedRootAction ;
10+ import hudson .model .*;
11+ import hudson .scm .SCMRevisionState ;
12+ import hudson .triggers .SCMTrigger ;
13+ import hudson .triggers .Trigger ;
1114import hudson .util .HttpResponses ;
1215import jenkins .model .Jenkins ;
1316import org .apache .commons .io .IOUtils ;
3235import java .security .NoSuchAlgorithmException ;
3336import java .security .cert .CertificateException ;
3437import java .security .cert .X509Certificate ;
38+ import java .util .ArrayList ;
39+ import java .util .Collection ;
40+ import java .util .HashMap ;
3541
3642@ Extension
3743public class GithubWebhookNotifyAction implements UnprotectedRootAction {
@@ -56,65 +62,60 @@ public String getDisplayName() {
5662 */
5763 @ RequirePOST
5864 public HttpResponse doReceive (HttpServletRequest request , StaplerRequest staplerRequest ) throws IOException , ServletException {
59- String jenkinsRootUrl = Jenkins .getInstance ().getRootUrl (); // will return something like: http://localhost:8080/jenkins/
6065 BufferedReader reader = request .getReader ();
6166 Gson gson = new Gson ();
6267 try {
6368 GithubWebhookPayload githubWebhookPayload = gson .fromJson (reader , GithubWebhookPayload .class );
64- // Trigger Git-Plugins notify push SCM Polling Endpoint
65- String gitPluginNotifyUrl = jenkinsRootUrl +
66- "git/notifyCommit?url=" +
67- githubWebhookPayload .getRepository ().getClone_url () +
68- "&branches=" +
69- this .normalizeBranchNameForJenkins (githubWebhookPayload .getRef ()) +
70- "&sha1=" +
71- githubWebhookPayload .getAfter ();
72- SSLContext sslContext = new SSLContextBuilder ()
73- .loadTrustMaterial (null , new TrustStrategy () {
74- @ Override
75- public boolean isTrusted (X509Certificate [] certificate , String authType ) throws CertificateException {
76- return true ;
77- }
78- }).build ();
79- CloseableHttpClient client = HttpClients .custom ()
80- .setSSLContext (sslContext )
81- .setSSLHostnameVerifier (new NoopHostnameVerifier ())
82- .build ();
83- HttpGet httpGet = new HttpGet (gitPluginNotifyUrl );
84- CloseableHttpResponse response = client .execute (httpGet );
85- int statusCode = response .getStatusLine ().getStatusCode ();
86- String gitNotificationResponse = IOUtils .toString (response .getEntity ().getContent (), "UTF-8" );
87- StringBuilder responseText = new StringBuilder ();
88- responseText .append ("----------------------------------------------------------------------------------\n " );
89- responseText .append ("github-webhook-notifier-plugin - parsed webhook payload:\n " );
90- responseText .append (" ref: " ).append (githubWebhookPayload .getRef ()).append ("\n " );
91- responseText .append (" before: " ).append (githubWebhookPayload .getBefore ()).append ("\n " );
92- responseText .append (" after: " ).append (githubWebhookPayload .getAfter ()).append ("\n " );
93- responseText .append (" clone_url: " ).append (githubWebhookPayload .getRepository ().getClone_url ()).append ("\n " );
94- responseText .append ("----------------------------------------------------------------------------------\n " );
95- responseText .append (">> REQUEST\n " ).append (gitPluginNotifyUrl ).append ("\n \n " );
96- responseText .append ("<< RESPONSE HTTP " ).append (statusCode ).append ("\n " );
97- responseText .append (gitNotificationResponse );
98- if (statusCode != 200 ) {
99- return HttpResponses .error (400 , responseText .toString ());
69+ GithubWebhookEnvironmentContributionAction environmentContributionAction = new GithubWebhookEnvironmentContributionAction (githubWebhookPayload );
70+ String jobNamePrefix = this .normalizeRepoFullName (githubWebhookPayload .getRepository ().getFull_name ());
71+ StringBuilder jobsTriggered = new StringBuilder ();
72+ ArrayList <String > jobsAlreadyTriggered = new ArrayList <>();
73+ StringBuilder causeNote = new StringBuilder ();
74+ causeNote .append ("github-webhook-notifier-plugin:\n " );
75+ causeNote .append (githubWebhookPayload .getAfter ()).append ("\n " );
76+ causeNote .append (githubWebhookPayload .getRef ()).append ("\n " );
77+ causeNote .append (githubWebhookPayload .getRepository ().getClone_url ());
78+ Cause cause = new Cause .RemoteCause ("github.com" , causeNote .toString ());
79+ Collection <Job > jobs = Jenkins .getInstance ().getAllItems (Job .class );
80+ if (jobs .isEmpty ()) {
81+ jobsTriggered .append ("WARNING NO JOBS FOUND!\n " );
82+ jobsTriggered .append ("If you are using matrix-based security, please give the following rights to 'Anonymous'.\n " );
83+ jobsTriggered .append ("'Job' -> build, discover, read.\n " );
10084 }
101- return HttpResponses .plainText (responseText .toString ());
85+ for (Job job : jobs ) {
86+ if (job .getName ().startsWith (jobNamePrefix ) && ! jobsAlreadyTriggered .contains (job .getName ())) {
87+ jobsTriggered .append (" " ).append (job .getName ()).append ("\n " );
88+ jobsAlreadyTriggered .add (job .getName ());
89+ AbstractProject projectScheduable = (AbstractProject ) job ;
90+ projectScheduable .scheduleBuild (0 , cause , environmentContributionAction );
91+ }
92+ }
93+ StringBuilder info = new StringBuilder ();
94+ info .append (">> webhook content to env vars" ).append ("\n " );
95+ info .append (environmentContributionAction .getEnvVarInfo ());
96+ info .append ("\n " );
97+ info .append (">> jobs triggered with name matching '" ).append (jobNamePrefix ).append ("*'" ).append ("\n " );
98+ info .append (jobsTriggered .toString ());
99+ return HttpResponses .plainText (this .getTextEnvelopedInBanner (info .toString ()));
102100 } catch (JsonSyntaxException ex ) {
103- return HttpResponses .error (500 , "github-webhook-notifier-plugin: github webhook json invalid" );
104- } catch (NoSuchAlgorithmException ex ) {
105- return HttpResponses .error (500 , "github-webhook-notifier-plugin: internal error NoSuchAlgorithmException" );
106- } catch (KeyStoreException ex ) {
107- return HttpResponses .error (500 , "github-webhook-notifier-plugin: internal error KeyStoreException" );
108- } catch (KeyManagementException ex ) {
109- return HttpResponses .error (500 , "github-webhook-notifier-plugin: internal error KeyManagementException" );
101+ return HttpResponses .error (500 , this .getTextEnvelopedInBanner ("github webhook json invalid" ));
110102 }
111103 }
112104
113105 /*
114- * converts "refs/heads/develop " to "origin/develop "
106+ * converts "codeclou/foo " to "codeclou---foo "
115107 */
116- private String normalizeBranchNameForJenkins (String branchname ) {
117- return branchname .replace ("refs/heads/ " , "origin/ " );
108+ private String normalizeRepoFullName (String reponame ) {
109+ return reponame .replace ("/ " , "--- " );
118110 }
119111
112+ private String getTextEnvelopedInBanner (String text ) {
113+ StringBuilder banner = new StringBuilder ();
114+ banner .append ("----------------------------------------------------------------------------------\n " );
115+ banner .append ("github-webhook-notifier-plugin" ).append ("\n " );
116+ banner .append ("----------------------------------------------------------------------------------\n " );
117+ banner .append (text );
118+ banner .append ("\n ----------------------------------------------------------------------------------\n " );
119+ return banner .toString ();
120+ }
120121}
0 commit comments