Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script for publishing buildbox build wait times as an AWS cloudwatch metric
#!/bin/bash
#
# Publishes CloudWatch metrics about Buildbox queue length
set -e
API='https://api.buildbox.io'
BUILDS_ROUTE='v1/accounts/ACCOUNT_NAME/projects/PROJECT_NAME/builds'
# Determines whether a binary exists on the current $PATH
#
# Exits 0 if the binary was found in $PATH, or 1 if not found.
function in_path {
local binary="$1"
which "$binary" > /dev/null
}
# Echoes a JSON object representing the current build to stdout
function current_build {
local url="$API/$BUILDS_ROUTE/$BUILDBOX_BUILD_NUMBER?api_key=$BUILDBOX_API_KEY"
curl --fail "$url"
}
# Converts a Buildbox-style date to a Unix timestamp
function date_to_timestamp {
local date="$1"
if date --version 2> /dev/null | grep GNU > /dev/null; then
# GNU date
date --date="$date" '+%s'
else
# POSIX date
date -ujf '%F %T UTC' "$date" '+%s'
fi
}
# Echoes the number of seconds this build was scheduled for to stdout
function current_build_wait_time {
local output='/tmp/curl-output'
local scheduled_at
local started_at
# Save current build to avoid two requests
current_build > "$output"
# Pull out the scheduled_at and started_at fields
scheduled_at="$(< "$output" jq -r '. | .scheduled_at')"
started_at="$(< "$output" jq -r '. | .started_at')"
# Echo the difference
expr $(date_to_timestamp "$started_at") - $(date_to_timestamp "$scheduled_at")
}
echo "--- Determining this build's wait time"
wait_time=$(current_build_wait_time)
echo "This build had a wait time of $wait_time seconds."
echo '--- Publishing data point to CloudWatch'
aws cloudwatch put-metric-data \
--metric-name ContestsBuildWaitTime \
--namespace buildbox \
--value "$wait_time" \
--timestamp "$(date -u +'%FT%T.000Z')"
@bradfeehan

This comment has been minimized.

Copy link

@bradfeehan bradfeehan commented May 20, 2015

Could be improved by deriving the timestamp from the Buildkite job, rather than the "current time" at the point where it's submitted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment