Created
March 30, 2012 11:31
-
-
Save joakimk/2250943 to your computer and use it in GitHub Desktop.
Jenkins tool to remove old builds from queues so that only the latest commit gets run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'httparty' | |
require 'nokogiri' | |
# This tool removes old builds from queues so that only the latest commit gets run. | |
# This way slow jobs won't fall behind, they will just skip commits upto the latest | |
# available commit that was successful in upstream projects. | |
class JenkinsQueueOptimizer | |
class Api | |
include HTTParty | |
base_uri "http://localhost:8080" | |
end | |
def self.run | |
loop do | |
begin | |
projects_with_more_than_one_item_in_queue.each do |project| | |
old_item_ids_for_project(project).each do |item_id| | |
puts "Clearing out old queue item #{item_id} for #{project}." | |
cancel_queue_item(item_id) | |
end | |
end | |
rescue Exception => ex | |
puts 'Error:' | |
puts ex.message | |
puts ex.backtrace | |
end | |
sleep 5 | |
end | |
end | |
def self.projects_with_more_than_one_item_in_queue | |
puts "Checking for old items in build queues..." | |
data = Api.get("/queue/api/json", :format => :json).to_hash | |
projects = {} | |
data["items"].each do |item| | |
project = item["task"]["name"] | |
projects[project] ||= 0 | |
projects[project] += 1 | |
end | |
projects.find_all { |project, queue_size| queue_size > 1 }.map { |project, _| project } | |
end | |
def self.old_item_ids_for_project(project) | |
page = Api.get("/job/#{project}").body | |
doc = Nokogiri::HTML(page) | |
queue_item_ids = [] | |
doc.css("td > div > a").each do |link| | |
link = link.attributes["href"].value | |
if link =~ /queue\/item\/(.+?)\// | |
queue_item_ids << $1.to_i | |
end | |
end | |
queue_item_ids.sort[0...-1] | |
end | |
def self.cancel_queue_item(item_id) | |
Api.get("/queue/item/#{item_id}/cancelQueue") | |
end | |
end | |
JenkinsQueueOptimizer.run |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'rubygems' | |
require 'daemons' | |
Daemons.run(File.expand_path(File.join(File.dirname(__FILE__), "jenkins_queue_optimizer.rb"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment