zuntan02のはてなブログ

備忘録的なものです。時々職場の技術者ブログにも転記してますが、メインはこちらで。

【さくらのクラウド】日次アーカイブで削除に失敗したときにメール通知させる

【前提】

SCHotBackup
https://github.com/hsur/SCHotBackup/blob/master/daily_archive.sh
を利用してアーカイブを取得しているとき、アーカイブタイムアウト→前々日の削除処理ができないでアーカイブがたまってしまって請求が!!!みたいなことがあったので、ログをチェックして処理の衝突ログ(Conflict)があったらメールするようにしています。

【チェック対象となるアーカイブのログについて】

上記アーカイブスクリプトをcronで実行する際、以下の様にしてログを出力しています
ex.crontabで以下の様な設定

05 01 * * * /bin/bash -l /home/hoge/bin/daily_archive.sh > /home/hoge/log/sakura_auto_archive_`date +\%Y\%m\%d`.log

失敗したときのログ

20xx-xx-xx 01:05:02 [18516]: ===== START =====
20xx-xx-xx 01:05:02 [18516]: get_disk_list()
20xx-xx-xx 01:05:04 [18516]: ----- START: xxxxxxxxxxxx (hogehoge.jp) -----
20xx-xx-xx 01:05:04 [18516]: archive:xxxx.archive.json
20xx-xx-xx 01:05:04 [18516]: create_archive()
20xx-xx-xx 01:05:06 [18516]: ARCHIVE_ID: xxxxxxxxxxxx
20xx-xx-xx 01:05:37 [18516]: waiting... (0/512000MB)
(中略)
20xx-xx-xx 05:05:30 [18516]: waiting... (326208/512000MB)
20xx-xx-xx 05:05:30 [18516]: [ERROR] Timed out!: xxxxxxxxxxxx
20xx-xx-xx 05:05:30 [18516]: [ERROR] Failed to create archive.
20xx-xx-xx 05:05:30 [18516]: delete_archive()
20xx-xx-xx 05:05:30 [18516]: {"is_fatal":true,"serial":"xxxxxxxxxx","status":"409 Conflict","error_code":"disk_is_copying","error_msg":"(省略)"}

【チェック&メール通知スクリプト

#!/bin/sh

# メール送信設定
_to="fuga@hogehoge.jp"
_from="sakurabackup@hogehoge.jp"

# メール件名設定
_hostname=`hostname`
_application="SAKURA Cloud Daily BackUP"
_subject="Fatal error!!"
_title="[${_application}][${_hostname}]${_subject}"

# エラー条件
_error_conditions="Conflict"

for file in `find /home/hoge/log/* -type f -mtime -1`; do
        err_line=`cat $file | grep -a ${_error_conditions}`
        if [[ ${err_line} = *${_error_conditions}* ]]; then
                /usr/sbin/sendmail -t <<- EOS
                MIME-Version: 1.0
                Content-Type: text/plain; charset=iso-2022-jp
                From: ${_from}
                To: ${_to}
                Subject: ${_title}
                SAKURA Cloud Backup Failed
                ----------
                log_file:
                ${file}

                error_message:
                ${err_line}
                ----------
                Please check with a administrator for details.
EOS
        fi
done

上記を

00 12 * * * /bin/bash -l /home/hoge/bin/sakurabkup-notice.sh  2>&1

のようにして実行してヒットがあれば見に行く。
連続するようならアーカイブスクリプトタイムアウト時間(MAX_SLEEP_SECS=)を延ばすなどの対応をしています。