暫定 - 技術メモなど

今のところはRaspberry Piを使ったIoTが話題の中心です

homebridgeがネットワークに接続できない時に自動でリブート

前回の記事では、homebridgeサーバを別のサーバからノード監視し、ノードダウンしたらLINEで知らせてくれるようにしました。
今回はhomebridge自体がデフォルトゲートウェイに通信できなくなったとき、自動的にリブートし、起動したことをLINEで通知してくれるようにしました。そのときの記録です。

参考サイトは前回と同様にこちらと
www.tapun.net

下記になります。
www.asahi-net.or.jp

1.概要

今回の要件を満たすために2つのスクリプトを用意しました。

No. スクリプト 用途 設置場所 自動実行の方法
1 nodedownreboot.sh homebridgeサーバからデフォルトゲートウェイpingしたときに応答しなかった≒ネットワークから切断されていたらリブートを行う /usr/local/bin/ crontab ※10分に1回実行
2 notify-reboot.sh homebridgeサーバが起動したときにLINEで通知する /usr/local/bin/ systemd ※起動時に1回だけ実行

2.スクリプトの準備

2つのスクリプトをそれぞれ準備します。

$ sudo vim /usr/local/bin/nodedownreboot.sh
#!/bin/bash

NUM01=3
IPLIST="デフォルトゲートウェイのIPアドレス"

### PING check
for IPL in ${IPLIST}
do
   ping ${IPL} -c ${NUM01}
   if [ $? -eq 1 ];then
      if [ -e /tmp/pingfile${IPL}.tmp ];then
         echo "TMP file already exsists"
      else
         touch /tmp/pingfile${IPL}.tmp
         sudo shutdown -r now
      fi
   else
      rm -f /tmp/pingfile${IPL}.tmp
   fi
done

exit 0
$ sudo vim /usr/local/bin/notify-reboot.sh
#!/bin/bash

sleep 45
curl -XPOST -H 'Authorization: Bearer LINEのトークンを記入' -F 'message=通知メッセージを記入' https://notify-api.line.me/api/notify
$ sudo chmod 744 /usr/local/bin/nodedownreboot.sh
$ sudo chmod 744 /usr/local/bin/notify-reboot.sh

3.自動実行の設定

スクリプトを作成したところで、自動起動の設定を行います。
まずは、nodedownreboot.sh を crontab に登録し、定期的に起動するように設定します。

$ sudo crontab -e

スクリプトに含まれる ping を実行する為にroot権限が必要となるので、sudo をつけて crontab を起動します。
最終行に下記を記述し、10分に1回スクリプトを実行するように設定します。

*/10 * * * * nodedownreboot.sh

次に notify-reboot.sh を systemd に登録し、homebridgeサーバの起動時に1回だけ実行するようにします。
.serviceのファイルを下記のように作成します。

$ sudo vim /etc/systemd/system/notify-reboot.service
[Unit]
Description = notify reboot

[Service]
Type=simple
ExecStart=/usr/local/bin/notify-reboot.sh

[Install]
WantedBy=multi-user.target

作成が完了したら、systemd への登録と enable、 start を行います。

$ sudo systemctl daemon-reload
$ sudo systemctl enable notify-reboot.service
$ sudo systemctl start notify-reboot.service

enableになっていることを確認します。

$ sudo systemctl status notify-reboot.service
● notify-reboot.service - notify reboot
   Loaded: loaded (/etc/systemd/system/notify-reboot.service; enabled)
   Active: active (running) since Thu 2018-01-04 20:57:45 JST; 3s ago
 Main PID: 13840 (notify-reboot.s)
   CGroup: /system.slice/notify-reboot.service
           ├─13840 /bin/bash /usr/local/bin/notify-reboot.sh
           └─13841 sleep 45

以上です。