Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/bin/bash
MACKEREL_APIKEY=<YOUR_MACKEREL_APIKEY>
LIMIT=100
DATE_FROM=$(date -d "2020-12-15 23:00:00" +%s) #取得したいアラートの開始日時
DATE_TO=$(date -d "2020-12-16 00:00:00" +%s) #取得したいアラートの終了日時
# ヘッダーを出力
echo -e "hostid\tstatus\tmonitorId\ttype\thostId\tvalue\tmessage\treason\topenedAt\tclosedAt"
# 一回目
JSON_FIRST=$(
curl -GsS \
-X GET \
-H 'X-Api-Key: '${MACKEREL_APIKEY} \
-H 'Content-Type: application/json' \
-d withClosed=true \
-d limit=${LIMIT} \
https://api.mackerelio.com/api/v0/alerts
)
TSV_FIRST=$(
echo "$JSON_FIRST" |
jq -r ' .alerts[]|[
.id,
.status,
.monitorId,
.type,
.hostId,
.value,
.message,
.reason,
.openedAt,
.closedAt
] | @tsv'
)
NEXT_ID=$(
echo "$JSON_FIRST" | jq -r '.nextId'
)
while read LINE
do
for OPEN_AT in $(echo "$LINE" | cut -f 9);do
if [ $DATE_FROM -le $OPEN_AT -a $DATE_TO -gt $OPEN_AT ]; then
echo -e "$(echo "$LINE" | cut -f 1-7)\t$(date -d @$OPEN_AT +"%Y-%m-%d %H:%M:%S")\t$(date -d @$(echo "$LINE" | cut -f 10) +"%Y-%m-%d %H:%M:%S")"
elif [ $DATE_FROM -ge $OPEN_AT ]; then
exit
fi
done
done <<END
$TSV_FIRST
END
# 二回目以降
while :
do
if [ -z $NEXT_ID ]; then
break
fi
JSON_NEXT=$(
curl -GsS \
-X GET \
-H 'X-Api-Key: '${MACKEREL_APIKEY} \
-H 'Content-Type: application/json' \
-d withClosed=true \
-d limit=${LIMIT} \
-d nextId=${NEXT_ID} \
https://api.mackerelio.com/api/v0/alerts
)
TSV_NEXT=$(
echo "$JSON_NEXT" |
jq -r ' .alerts[]|[
.id,
.status,
.monitorId,
.type,
.hostId,
.value,
.message,
.reason,
.openedAt,
.closedAt
] | @tsv'
)
NEXT_ID=$(
echo "$JSON_NEXT" | jq -r '.nextId'
)
while read LINE
do
for OPEN_AT in $(echo "$LINE" | cut -f 9);do
if [ $DATE_FROM -le $OPEN_AT -a $DATE_TO -gt $OPEN_AT ]; then
echo -e "$(echo "$LINE" | cut -f 1-7)\t$(date -d @$OPEN_AT +"%Y-%m-%d %H:%M:%S")\t$(date -d @$(echo "$LINE" | cut -f 10) +"%Y-%m-%d %H:%M:%S")"
elif [ $DATE_FROM -ge $OPEN_AT ]; then
exit
fi
done
done <<END
$TSV_NEXT
END
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment