Skip to content

Commit

Permalink
Merge pull request #2 from seatgeek/colinodell-improved-logging
Browse files Browse the repository at this point in the history
Improved logging
  • Loading branch information
colinodell authored Sep 19, 2024
2 parents ed464d3 + c522e7b commit 6673f3a
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions buildkit-prestop.sh
Original file line number Diff line number Diff line change
Expand Up @@ -29,36 +29,49 @@
# Because this is a somewhat naive approach that only looks at individual points in time,
# we will check multiple times just to be sure that we're not missing any builds.

# Variables
# Variables (change these as needed)
CHECK_FREQUENCY_MS=500 # How often we should for running build processes (in milliseconds)
WAIT_UNTIL_NO_BUILDS_SEEN_FOR_X_SECONDS=10 # If no build processes are seen for this many seconds, we assume that all builds have stopped
BUILDKITD_PORT=1234 # Port on which buildkitd is listening for buildx clients
LOG_FORMAT="json" # Log format to use (either "json" or "text")
LOG_PREFIX="[PreStop Hook]" # Optional prefix to add to log messages

# Calculate the number of checks required based on the wait time and sleep period
REQUIRED_CHECK_COUNT=$((WAIT_UNTIL_NO_BUILDS_SEEN_FOR_X_SECONDS * 1000 / CHECK_FREQUENCY_MS))

# How many consecutive times we've seen no running builds
times=0

# Print logs both locally as in pod logs
print_logs() {
# If we're running in a Kubernetes pod, write logs to stdout of the container
message=$1
level=${2:-"info"}

if [ -n "$LOG_PREFIX" ]; then
message="$LOG_PREFIX $message"
fi

if [ "$LOG_FORMAT" = "json" ]; then
message="{\"message\": \"$message\", \"timestamp\": \"$(date -u +"%Y-%m-%dT%H:%M:%SZ")\", \"level\": \"$level\"}"
fi

# If we're running in a Kubernetes pod, write logs to stderr of the container
if [ -n "$KUBERNETES_SERVICE_HOST" ]; then
echo "PreStop Hook: $1" >> /proc/1/fd/1
echo "$message" >> /proc/1/fd/2
else
echo "$1"
echo "$message" >&2
fi
}

# Function to print a message conditionally based on DEBUG environment variable
print_debug() {
if [ -n "$DEBUG" ]; then
print_logs "$1"
print_logs "$1" "debug"
fi
}

print_logs "Waiting for build processes to finish..."

# How many consecutive times we've seen no running builds
times=0

# Loop until we see zero active connections REQUIRED_CHECK_COUNT consecutive times
while true; do
ACTIVE_CONNECTIONS=$(netstat -tnp | grep buildkitd | grep ":${BUILDKITD_PORT}" | grep -c ESTABLISHED)
Expand Down

0 comments on commit 6673f3a

Please sign in to comment.