Skip to content

Instantly share code, notes, and snippets.

@kvelarde
Forked from thbkrkr/Dockerfile
Created August 16, 2017 00:21
Show Gist options
  • Save kvelarde/a5da66579b5a18635cfd7382428239dc to your computer and use it in GitHub Desktop.
Save kvelarde/a5da66579b5a18635cfd7382428239dc to your computer and use it in GitHub Desktop.
Get containers info and stats using the Docker Remote API
#!/bin/bash -eu
#
# @description Get containers info and stats using the Docker Remote API
# @deps curl, jq
# @usage docker-stats.sh host-42 101.0.0.42
DOCKER_HOSTNAME=$1
DOCKER_IP=$2
DOCKER_PORT=2376
CERT_DIR=~/.docker/machines/.client
VERBOSE=1
[[ "$(which curl 2>/dev/null)" == "" ]] && echo "error: install curl (http://curl.haxx.se/download.html)" && exit 1
[[ "$(which jq 2>/dev/null)" == "" ]] && echo "error: install jq (http://stedolan.github.io/jq/download/)" && exit 1
api() {
local endpoint=$1
local options=$2
curl -sk $options \
https://$DOCKER_IP:$DOCKER_PORT/$endpoint \
--cert $CERT_DIR/cert.pem \
--key $CERT_DIR/key.pem \
--cacert $CERT_DIR/ca.pem
}
PREFIX=/tmp/docker-container-$(date +%s)
w_container_json() {
local id=$1
log "GET containers/$id/json"
api containers/$id/json "" > $PREFIX-$id-json
name=$(r "$(cat $PREFIX-$id-json)" ".Name" | sed -e 's|"||' -e 's|/||')
echo "$name" > $PREFIX-$id-name
log "SET name $name"
}
w_container_stats() {
local id=$1
log "GET /containers/$containerId/stats"
api containers/$id/stats "-m 2" | tail -1 > $PREFIX-$id-stats
}
wf() {
local id=$1
local kind=$2
cat $PREFIX-$id-$kind >> JSON
}
w() {
echo "$1" >> JSON
}
r() {
local json="$1"
local jqexpr="$2"
echo "$json" | jq -r "$jqexpr"
}
log() {
[[ $VERBOSE -eq 1 ]] && echo " [dstats] $1" || nothing=todo
}
################################
> JSON
log "GET /containers/json"
containers="$(api containers/json "")"
total_containers=$(r "$containers" '. | length')
w '{
"'$DOCKER_HOSTNAME'": {
"total_containers": '$total_containers',
"containers": ['
s=""; nb_proc=0
while read containerId; do
w_container_json $containerId &
sleep 0.0$RANDOM
w_container_stats $containerId &
nb_proc=$(($nb_proc+2))
if [ "$nb_proc" -ge $((total_containers*2)) ]; then
wait
nb_proc=0
fi
s=","
done < <(r "$containers" '.[] | .Id')
wait
log "Write JSON"
s=""
while read containerId; do
name=$(cat $PREFIX-$containerId-name)
w $s' {
"'$name'": {
"info": '
wf $containerId json
w ',
"stats": '
wf $containerId stats
w '
}
}'
s=","
done < <(r "$containers" '.[] | .Id')
w ' ]
}
}'
rm -f $PREFIX*
cat JSON | jq . >/dev/null 2>&1 \
&& log "Successful" || log "Error"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment