Skip to content

Instantly share code, notes, and snippets.

@jnewland
Created May 22, 2023 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnewland/308309f9c879111b22ab217e1cb5f7f1 to your computer and use it in GitHub Desktop.
Save jnewland/308309f9c879111b22ab217e1cb5f7f1 to your computer and use it in GitHub Desktop.
require 'net/http'
require 'json'
require 'time'
# Set the API token, organization, pipeline, and created_from date
API_TOKEN = ENV['API_TOKEN']
ORG_SLUG = ENV['BUILDKITE_ORGANIZATION_SLUG'] || 'your-org'
PIPELINE_SLUG = ENV['BUILDKITE_PIPELINE_SLUG'] || 'your-pipeline'
PER_PAGE = 100
# Calculate the created_from date in the ISO 8601 format for the past 30 days
created_from = (Time.now - 30 * 24 * 60 * 60).iso8601
# Function to calculate the agent runtime in minutes
def calculate_agent_runtime(started_at, finished_at)
start_time = Time.parse(started_at)
finish_time = Time.parse(finished_at)
runtime_minutes = ((finish_time - start_time) / 60).to_f.ceil
runtime_minutes
rescue
0
end
# Retrieve the list of builds for the pipeline in the past 30 days
builds_url = "https://api.buildkite.com/v2/organizations/#{ORG_SLUG}/pipelines/#{PIPELINE_SLUG}/builds?created_from=#{created_from}&per_page=#{PER_PAGE}"
uri = URI.parse(builds_url)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
request['Authorization'] = "Bearer #{API_TOKEN}"
response = http.request(request)
builds = JSON.parse(response.body)
total_agent_runtime_minutes = 0
while builds.any?
builds.each do |build|
build_number = build['number']
jobs = build['jobs']
jobs.each do |job|
started_at = job['started_at']
finished_at = job['finished_at']
agent_runtime_minutes = calculate_agent_runtime(started_at, finished_at)
if agent_runtime_minutes == 0
next
end
total_agent_runtime_minutes += agent_runtime_minutes
end
end
puts "#{total_agent_runtime_minutes} so far"
next_page_url = response['Link'].scan(/<([^>]+)>;\s*rel="next"/).flatten.first
break unless next_page_url
uri = URI.parse(next_page_url)
request = Net::HTTP::Get.new(uri.request_uri)
request['Authorization'] = "Bearer #{API_TOKEN}"
response = http.request(request)
builds = JSON.parse(response.body)
end
puts "Total agent runtime in minutes: #{total_agent_runtime_minutes}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment