Skip to content

Instantly share code, notes, and snippets.

@missasan
Last active December 16, 2020 01:09
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 missasan/942408a7d5fa1379c1558c3bbea5fa73 to your computer and use it in GitHub Desktop.
Save missasan/942408a7d5fa1379c1558c3bbea5fa73 to your computer and use it in GitHub Desktop.
#!/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