3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

fabricでバックグラウンドジョブを実行する

Last updated at Posted at 2016-05-22

サーバ構築後、確認のためアプリケーションの起動・停止をして、その時のログを切り出して回収したかったのだけど、ちょっとはまったのでメモ。

run()が一度呼び出される毎に疑似端末を作成しているので、単純に"[command] &"などの方法でバックグラウンドで実行しただけではrun()を抜けたときにプロセスが終了してしまう。
"nohup"や"disdown"でデーモンとして実行させて、fabricのrun()が疑似端末を作成しないようpty=Falseを設定すると期待通り動作した。

以下サンプル。

# 実行
fab test_tail_logfile -H localhost -u xxxxx -p xxxxx --port 2222
fabfile.py
from fabric.api import run, get, quiet


def kill_background_job(command):
    with quiet():
        run(u"pkill -f '%s'" % command)


def background_run(command, stdout):
    run(u"nohup %s > %s 2>&1 &" % (command, stdout), pty=False)


def test_tail_logfile():
    '''
    バックグランドでログをtailしつつほかの処理を実行、
    処理終了後にtailを止めてログを回収するサンプル
    '''
    # テスト用のログファイルを作る
    run(u"echo '**********************' > work.log")

    # ログのtail開始
    background_run(u"tail -f work.log", u"out.log")

    # ログに何か書き込んでみる
    run("echo 'piyo piyo' >> work.log")
    run("echo 'hoge' >> work.log")

    # tailを止める
    kill_background_job(u"tail -f work.log")

    # ログが取れてるか確認
    run(u"cat %s" % u"out.log")
    # ログを回収
    get(r"out.log", u".\\log\\out.log")

3
4
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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?