Plaggerで監視

Test::Harnessを使う

以前からPlaggerでシステムとかサービスの監視をしたいなと思ってました.どういう風にすると汎用的になるのかを考えていたんですが,Net::SSL::ExpireDateを使って証明書の期限切れをチェックするツールを書いている際にTest::Harnessの結果をPlaggerに渡すことを思いつきました.といってもTest::Harnessを使ったPluinモジュールを書くのは荷が重かったので,CustomFeed::Scriptを使ってみました.参考にしたのは宮川さんのSSL の更新期限を iCal へ - Bulknews::Subtech - subtechという記事です.

スクリプト

CustomFeed::Scriptで呼び出すスクリプトは,実行結果をYAML形式で出力する必要があります.ここではこんな感じ

---
title: RESULTS
entry:
  - body: All tests OK
    title: 'PASS: t/01-json.t'
  - body: All tests OK
    title: 'PASS: t/02-json.t'
  - body: ''
    title: 'FAIL : t/03-camelize.t plan 2'

に出力するようにしてみました.

#!/usr/local/bin/perl

use Test::Harness::Straps;
use YAML;
use warnings;
use strict;

my ( @tests, $straps, $output );

@tests = @ARGV
  or die "Usage: yaml_harness.pl test1 test2 ...\n";

$straps = new Test::Harness::Straps;

$output = {
    title => "RESULTS",
    entry => [],
};

for my $file (@tests) {
    my ( %result, $i );

    %result = $straps->analyze_file($file);
    if ( $result{passing} ) {
        push @{ $output->{entry} },
          {
            title => "PASS: $file",
            body  => "All tests OK",
          };
    }
    else {
        map {
            my $detailRef = $_;
            $i++;
            if ( !$$detailRef{ok} ) {
                my $title = sprintf "FAIL : %s plan %d", $file, $i;
                my $body = $$detailRef{name} ? $$detailRef{name} : "";
                push @{ $output->{entry} },
                  {
                    title => $title,
                    body  => $body,
                  };
            }
        } @{ $result{details} };
    }
}

print YAML::Dump $output;

Plaggerでこのスクリプトを呼び出すと,IRCでこんな出力が出ます.

(bot1) RESULTS: PASS: t/01-json.t (All tests OK)
(bot1) RESULTS: PASS: t/02-json.t (All tests OK)
(bot1) RESULTS: FAIL: t/03-camelize.t plan2

設定ファイルは以下のように作りました.

global:
  plugin_path:
    - plugins
  timezone: Asia/Tokyo
  log:
    level: error
  assets_path: ./

plugins:
  - module: Subscription::Config
    config:
      feed:
        - script:./yaml_harness.pl t/*
  - module: CustomFeed::Script
  - module: Notify::IRC
    config:
      assets_path: ./
      daemon_port: 9992
      nickname: bot1
      server_host: localhost
      server_port: 6667
      server_channels:
        - #test1
      charset: iso-2022-jp
      announce: action