LoginSignup
2
7

More than 5 years have passed since last update.

systemdで管理するサービスが落ちたときにHipchat(他のSNSやメールも可)にアラートを飛ばす

Last updated at Posted at 2017-01-24

目標: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
2
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
7