Skip to content

Instantly share code, notes, and snippets.

@joakimk
Created March 30, 2012 11:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joakimk/2250943 to your computer and use it in GitHub Desktop.
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
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
#!/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