Skip to content

Instantly share code, notes, and snippets.

@andynu
Created September 23, 2011 17:05
Show Gist options
  • Save andynu/1237898 to your computer and use it in GitHub Desktop.
Save andynu/1237898 to your computer and use it in GitHub Desktop.
Jenkins CI External Task Submission Perl Script
#!/usr/bin/env perl
#
# A job run submission script for
# Jenkins (http://jenkins-ci.org/)
#
# Your command will run regardless of if the jenkins server is up or
# not. However there is no buffering so if your jenkins server is not
# up when the task completes then the run won't be recorded.
#
use strict;
use warnings;
use Time::HiRes qw( time );
# arguments
my $job_name = shift(@ARGV);
my $command = join(" ", @ARGV);
# jenkins configuration
my $host = "yourserver";
my $path = "/jenkins";
my $user = "yourusername";
my $pass = "secret";
my ($output, $result, $duration) = run_command($command);
notify_jenkins($job_name, $output, $result, $duration);
exit $result;
##############################
# Subs
sub run_command {
my ($command) = @_;
my $start = time();
# Run the command!
my $output = `$command`;
my $result = $?;
my $end = time();
my $duration_milli = ($end - $start) * 1000;
my $duration = sprintf("%0.0f", $duration_milli);
return $output, $result, $duration;
}
sub asc2bin {
my ($str) = @_;
my $string;
my $byte = 0;
my @bytes;
for (split //, $str) {
vec($byte, 0, 8) = ord;
push @bytes, unpack "B8", $byte;
}
return wantarray ? @bytes : join " ", @bytes;
}
sub notify_jenkins {
my ($job_name, $output, $result, $duration) = @_;
my @bin = asc2bin("$output\n");
my @hex = map { sprintf('%02X',oct("0b$_")) } @bin;
my $hex_str = join "", @hex;
my $description = "";
my $XML = <<XML;
<run>
<log encoding="hexBinary">$hex_str</log>
<result>$result</result>
<duration>$duration</duration>
<displayName>$job_name</displayName>
<description>$description</description>
</run>
XML
my $url = "http://$user:$pass\@$host$path/job/${job_name}/postBuildResult";
`curl -X POST -d '$XML' $url 2>&1 >/dev/null`;
if($? != 0){
print STDERR "Could not notify jenkins\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment