at_yasu's blog

ロード的なことを

PythonでMuninのプラグイン作成

Muninというソフトを「サーバ監視、何使ってる? | スラド Slashdotに聞け」で知ったので、インストールしてみました。インストールはportsで、sysutils/munin-main, sysutils/munin-nodeをがしょがしょと。

それで、Apacheの転送量をアクセスログから拾うプラグインが無かったので、さくさくと書きました。VartualHostを作りまくってると、apache_accessesでは物足りないのよね。どのホストがどれだけ食っているのかわからないし。


まず、Muninのプラグインの仕組み。

設定とプラグインディレクトリーは、etc/munin/plugin-conf.d/plugins.conf というファイルがプラグインの設定ファイル、etc/munin/plugins/ がプラグインディレクトリーになります。plugins/の下には、全てシンボリックリンクがはられており、muninがそれぞれを呼び出します。


Muninがプラグインに渡す物リスト

第一引数 config
Muninが設定情報を知りたい時に問い合わせるっぽい。
plugins.conf
中身にenvと書かれた物は環境変数として渡します。下記のスクリプトだと、env.logfileにログファイル一覧をスペース区切りで書きます。


プラグインがMuninへ情報を渡す方法は、単純にstdoutへ出力させてやればいいだけです。

graph_title
グラフのタイトル
graph_args
グラフ作成時の引数。--baseに1024だと、1024=1kとなります。1000だと1000=1kに。-lとかもあるそうな。*1
graph_vlabel
縦軸の単位。${graph_period}で、勝手にsecondなどの文字を入れます。
graph_categry
graphのカテゴリーを指定します。これはApachenの物なので、apacheと。
access*.label
グラフの線の意味付けを。
access*.type
グラフのタイプを指定。ここに詳しく書いてます
access*.max
グラフの最大値
access*.min
グラフの最小値


下のスクリプトは、Apacheのログファイルから、転送量を返す物です。

設定例

env.logfile /path/to/logfile1 /path/to/logfile2
#!/usr/bin/env python2.5
# -*- encoding: utf8 -*-
#
# Parameters supported:
# 
# config
# autoconf
#
# Magic makers:
#%# family=auto
#%# capabilities=autoconf

import sys,os,re

_GRAPH = [('title',    'Apache traffic bytes.'),
		  ('args',     '--base 1024'),
		  ('vlabel',   'byte / ${graph_period}'),
		  ('category', 'apache')
]

logs = ['/var/log/httpd/access_log']
try:
	if os.environ['logfile']:
		logs = re.split(r'\s+', os.environ['logfile'])
except:
	pass

# drop the none file
_logs = [e for e in logs if os.path.exists(e)]

# show config
if len(sys.argv) > 1 and sys.argv[1] and sys.argv[1] == 'config':
	for g in _GRAPH:
		print "graph_%s %s" % g
	
	cnt = 0
	for p in _logs:
		name = os.path.basename(p)
		print 'accesses%s.label Path %s' % (cnt, p)
		print 'accesses%s.type DERIVE' % (cnt)
		print 'accesses%s.max 1048576' % (cnt)
		print 'accesses%s.min 0' % (cnt)
		cnt += 1
	sys.exit(0)

cnt = 0
for p in _logs:
	buff = 0
	for line in open(p,'r'):
		w = re.split(r'\s+', line)
		try :
			if re.match(r'\d+', w[9]):
				buff += int(w[9])
		except e:
			print e
	print "accesses%s.value %d" % (cnt, buff)
	cnt += 1


参考サイト: http://munin.projects.linpro.no/wiki/HowToWritePlugins

*1:参考先を参照

Postgresを監視

何か去年まではPostgresのスクリプトが無かったみたいですけど、今はsvnのtrunkにマージされています。採集のアップデートが11ヶ月前とかなので、安定はしているみたいです。ただ、ちょっとコツがいりましたけど…


svn で取得する前に、DBI::Pgのインストールが必要です。インストールしてください。


そして、svnで取得してきてmakeだけします。インストールしません。

# svn co svn://munin.projects.linpro.no/munin/trunk munin
A    munin/RELEASE
A    munin/Makefile.config
A    munin/Makefile.config-dist
...
 U   munin
Checked out revision 1768.
# ls
./        ../       CVS/      munin/    original/
# cd munin
# ls                                                                     
./                     Makefile               RELEASE                logo.svg
../                    Makefile.config        contrib/               monkeywrench/
.svn/                  Makefile.config-dist   dists/                 node/
COPYING                Makefile.config-maint  getversion*            resources/
ChangeLog              README                 install-sh*            server/
Checklist              README.HP-UX           logo-horizontal.svg    t/
INSTALL                README.OSX             logo.eps               test-mktemp*
# make
"Makefile", line 343: Missing dependency operator
"Makefile", line 348: Need an operator
"Makefile", line 364: Missing dependency operator
"Makefile", line 368: Need an operator
"Makefile", line 374: warning: duplicate script for target "test" ignored
"Makefile", line 375: Need an operator
make: fatal errors encountered -- cannot continue
# gmake
touch build-stamp
rm -rf build
Generating build/./node/node.d.freebsd/coretemp..
...
Generating build/./resources/solaris-init.d_munin-node..
Generating build/./resources/linux-cron.d_munin-node..
# ls
./                     Makefile.config        build-stamp            monkeywrench/
../                    Makefile.config-dist   contrib/               node/
.svn/                  Makefile.config-maint  dists/                 resources/
COPYING                README                 getversion*            server/
ChangeLog              README.HP-UX           install-sh*            t/
Checklist              README.OSX             logo-horizontal.svg    test-mktemp*
INSTALL                RELEASE                logo.eps
Makefile               build/                 logo.svg
#

というわけで、buildと言うディレクトリが出来ています。この中には作成済みのプラグインとかコマンドがぎっしりかっつり入ってます。プラグインは、「build/node/node.d」に入っています。その中にある postgres-* を「/usr/local/share/munin/plugins」へコピーしませう。


さて、移動したpostgres-*の設定例

[postgres_*]
env.PGHOST localhost
env.PGUSER postgres
env.PGPASSWORD ****** 


さて動くかと言ったら、FreeBSDではこのままでは動きません。少なくとも、「postgres_queries」と「postgres_commits」はそれぞれ二カ所ほど、同じような変更が必要になります。

1c1
< #!/bin/bash
---
> #!/bin/sh
54c54
< psql_comm='psql -c'
---
> psql_comm='/usr/local/pgsql/bin/psql -c'


後はリスタートで動きます。


以下、trunkから取ってきたプラグインの事

postgres_queries
postgresサーバのクエリー数をカウント
postgres_queries_
postgresサーバにあるデータベースのクエリー数をカウント。ファイル名の最後にはデータベース名を記入します。
postgres_block_read_
メモリーやらディスクから取ってきたブロック数をデータベース単位でカウント。ファイル名の最後にはデータベース名を記入します。何か、postgres.conf で stats_start_collector と stats_block_level の値を true に設定する必要があるよんと書いてるけど本当かどうか知りません。だって、7.4 のドキュメントを参考にしてるって書いてるし…
postgres_commits_
データベース単位でのコミットを数えてくれるみたい。ファイル名の最後にはデータベース名を記入。
postgres_commits
設定で指定したサーバのコミットを数えてくれるみたい。
postgres_connections
サーバへの接続数を数えてくれる
postgres_space_
ディスクの使用量をデータベース単位で見てくれる。ファイル名の最後にはデータベース名を記入。

余談:Snortをインストールしているのですが、出力先をpostgresにしているのです。コネクションが平均2M5.73Mになってます。出すSnortも凄けりゃ耐えれるPostgresもすげぇ……

おまけにselectの実行回数が0なんだ。