Skip to content

Instantly share code, notes, and snippets.

@masaki
Created January 28, 2012 16:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masaki/1695018 to your computer and use it in GitHub Desktop.
Save masaki/1695018 to your computer and use it in GitHub Desktop.
Jenkins WebHook Receiver (w/ Jenkins Notification Plugin's JSON)
#!/usr/bin/env perl
use strict;
use warnings;
use Plack::Request;
use HTTP::Status qw(:constants status_message);
use JSON qw(from_json);
use LWP::UserAgent;
sub to_psgi_res {
my $status = shift;
return [
$status, [ 'Content-Type' => 'text/plain' ], [ status_message($status) ],
];
}
my $color_table = { A => 8, S => 3, F => 4 };
sub get_color {
my $status = shift;
my $key = uc substr $status, 0, 1;
return $color_table->{$key};
}
sub build_message {
my ($project_name, $job_url, $status) = @_;
return sprintf "Jenkins [%s]: %s - %s", $project_name, $status, $job_url;
}
my $app = sub {
my $env = shift;
my $req = Plack::Request->new($env);
unless ($req->content_type =~ m!application/json!) {
return to_psgi_res(HTTP_BAD_REQUEST);
}
my $ping = from_json($req->content, { utf8 => 1, allow_nonref => 1 });
# {
# "name": "MyJob",
# "url": "job/MyJob/",
# "build": {
# "number": 1,
# "phase": "STARTED", // STARTED, COMPLETED, FINISHED
# "status": "FAILURE", // SUCCESS, FAILURE, ABORTED
# "url": "job/MyJob/1/",
# "full_url": "http://example.com/jenkins/job/MyJob/1/",
# "parameters": { "branch": "master" }
# }
# }
my $phase = uc $ping->{build}->{phase};
unless ($phase =~ /(?:START|FINISH)/) {
return to_psgi_res(HTTP_ACCEPTED);
}
my $status = $phase;
if ($phase eq 'FINISHED') {
my $color = get_color($ping->{build}->{status});
$status = sprintf "\x02\x03%02d,15 %s \x0f", $color, $ping->{build}->{status};
}
if ($ENV{JENKINS_WEBHOOK_IKACHAN_HOST} && $ENV{JENKINS_WEBHOOK_IKACHAN_CHANNEL}) {
my $url = "http://$ENV{JENKINS_WEBHOOK_IKACHAN_HOST}/notice";
my $message = build_message($ping->{name}, $ping->{build}->{full_url}, $status);
LWP::UserAgent->new->post($url, {
channel => $ENV{JENKINS_WEBHOOK_IKACHAN_CHANNEL},
message => $message,
});
}
return to_psgi_res(HTTP_OK);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment