#!/usr/bin/env bash # awr_snap.sh: cron wrapper for awr_snap.sql: one snapshot, optional RDS CPU, optional purge # Copyright (c) HASHJOIN. MIT License (https://hashjoin.com/kb/license/) # https://hashjoin.com/kb/mysql/awr-statement-digest-snapshots/ # # Usage: awr_snap.sh [--rds-instance ID] [--keep-days N] [-- MYSQL_CLIENT_OPTIONS...] # # --rds-instance ID also record the instance's CPU (CloudWatch CPUUtilization, the highest # 1-minute value of the last 5 minutes); needs the aws CLI # --keep-days N afterwards, delete snapshots older than N days (awr_purge.sql) # -- ... passed to the mysql client: --defaults-file=..., --host=..., etc. # # Every 5 minutes, from cron: # */5 * * * * /opt/awr/awr_snap.sh --rds-instance mydb --keep-days 14 -- --defaults-file=/opt/awr/.my.cnf --host=mydb.xxxx.us-east-1.rds.amazonaws.com >> /var/log/awr_snap.log 2>&1 set -euo pipefail DIR="$(cd "$(dirname "$0")" && pwd)" RDS=""; KEEP="" while [ $# -gt 0 ]; do case "$1" in --rds-instance) RDS="$2"; shift 2 ;; --keep-days) KEEP="$2"; shift 2 ;; --) shift; break ;; *) echo "usage: $0 [--rds-instance ID] [--keep-days N] [-- mysql options]" >&2; exit 2 ;; esac done CPU="" if [ -n "$RDS" ]; then # GNU date on Linux, BSD date on a Mac. START=$(date -u -d '5 minutes ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-5M +%Y-%m-%dT%H:%M:%SZ) END=$(date -u +%Y-%m-%dT%H:%M:%SZ) CPU=$(aws cloudwatch get-metric-statistics --namespace AWS/RDS --metric-name CPUUtilization \ --dimensions Name=DBInstanceIdentifier,Value="$RDS" \ --start-time "$START" --end-time "$END" --period 60 --statistics Maximum \ --query 'max(Datapoints[].Maximum)' --output text 2>/dev/null || true) # No datapoint yet comes back as "None": record no CPU rather than fail the snapshot. case "$CPU" in ''|None|*[!0-9.]*) echo "$(date): no CPU datapoint for $RDS" >&2; CPU="" ;; esac fi echo "$(date): snapshot${CPU:+ (cpu $CPU%)}" mysql "$@" -t -e "set @cpu = '${CPU}'; source $DIR/awr_snap.sql;" if [ -n "$KEEP" ]; then mysql "$@" -t -e "set @keep_days = ${KEEP}; source $DIR/awr_purge.sql;" fi