目標:jenkinsがたまに勝手に落ちているが気づかないので、落ちたときにNotificationを飛ばす!
落ちたときに、また復活するようにするするためには、以下のように書いておく。(300sは任意の時間に変更可能)
[Service]
Restart=always
RestartSec=300s
参考ページ:http://northernlightlabs.se/systemd.status.mail.on.unit.failure
1. Notificationを飛ばしたいServiceのUnitファイル編集
[Unit]の中に、OnFailure=unit-status-notification@%n.serviceとかく
[Unit]
...
OnFailure=unit-status-notification@%n.service
...
2. notification用のサービスを作る
/etc/systemd/system/unit-status-notification@.serviceをつくる
/etc/systemd/system/unit-status-notification@.service
[Unit]
Description="unit status notification"
After=network.target
[Service]
Type=simple
ExecStart=/path/to/notification_run %I
%Iは、サービス名が入るので、このunit-status-notification@.serviceはいろいろなサービスに使いまわしできる。(1.の部分を追加するだけで良い。)
2. notification_runというスクリプトを準備する
(今回はRubyを実行するScript)
notification_run
cd path/to/<notification.rbを置いてる場所>
/path/to/your/ruby notification.rb %I
注意:ここでgem install bundler
をされてるRubyを指定しないと、DefaultのRubyになって、Systemdで、bundler not foundというエラーにハマるので注意!
3. rubyのファイルには、Notificationの実行内容を書く。
今回はHipchatへのNotificationだが、SlackやEmailへのNotificationの場合はも適宜変更。
notification.rb
require 'hipchat_util.rb'
unit = ARGV[0]
msg = "the status of #{unit} is on failure."
HipchatUtil.new.send_msg('hipchat-room-name', 'Unit Status', msg, notify: true, color: 'red')
Hipchatは、メッセージを送れるように以下のように定義しておいた。
hipchat_util.rb
class HipchatUtil
def initialize
api_keys = "<API_KEYS>"
@hipchat_client = HipChat::Client.new(api_keys)
end
def send_msg(room, title, body, msg_format: :text, notify: false, color: 'gray')
@hipchat_client[room]
.send(title, body, message_format: msg_format, notify: notify, color: color)
end
end
(4. 最後に一応notification_runを実行可能にしておく)
必要かどうかわからないが、以下を実行しておいた。
chmod +x /path/to/notifiation_run
git でこのchmodの変更が反映されない場合は、以下を実行:
git update-index chmod=+x /path/to/notifiation_run