もりはやメモφ(・ω・ )

ITとか読書感想文とか

digdagでファイルシステム上のファイルをチェックして if> operator につなげるサンプル

既存システムとの連携などが、ファイルシステム上のファイルの有無による「フラグファイル」で行われることがままあります。

ファイルの存在のチェックし、その結果をdigdagの if> operator でやってみたという小ネタです。

Document - if>: Conditional execution

ファイル構成はシンプルに以下。

  • isfile.dig
  • bin/init.py
  • bin/check_file.py

digファイル

digファイルでは

  • チェックするファイルのパスflg_file_path を設定し
  • python オペレータでファイルチェックの結果をTrue or False で返す bin.check_file.CheckFile.check_file を呼び出します
_export:
  flg_file_path: /tmp/flg

+check:
  py>: bin.check_file.CheckFile.check_file

+judge:
  if>: ${check_result}
  _do:
    +exists:
      echo>: The file exists!
  _else_do:
    +nothing:
      echo>: The file does not exist.

Python

ファイルをチェックし、結果を返すPythonです。とてもシンプル。

以下の1行がほぼ全てです。 "check_result": os.path.isfile(digdag.env.params['flg_file_path']) }

digdag.env.storecheck_result 変数に os.path.isfile の結果を返しています。

# -*- coding: utf-8 -*-

import digdag
import os

class CheckFile(object):
    def check_file(self, check_result=""):
        digdag.env.store(
            {
                "check_result": os.path.isfile(digdag.env.params['flg_file_path'])
            }
        )

実行例

ファイルがある場合は "The file exists!" が表示されます。

bash-3.2$ digdag run --rerun isfile.dig
2020-07-31 22:54:45 +0900: Digdag v0.9.42
2020-07-31 22:54:47 +0900 [WARN] (main): Reusing the last session time 2020-07-31T00:00:00+00:00.
2020-07-31 22:54:47 +0900 [INFO] (main): Using session /Users/morihaya/work/testdig/.digdag/status/20200731T000000+0000.
2020-07-31 22:54:47 +0900 [INFO] (main): Starting a new session project id=1 workflow name=isfile session_time=2020-07-31T00:00:00+00:00
2020-07-31 22:54:48 +0900 [INFO] (0017@[0:default]+isfile+check): py>: bin.check_file.CheckFile.check_file
2020-07-31 22:54:49 +0900 [INFO] (0017@[0:default]+isfile+judge): if>: true
2020-07-31 22:54:49 +0900 [INFO] (0017@[0:default]+isfile+judge^sub+exists): echo>: The file exists!
The file exists!

ファイルがない場合は "The file does not exist." が表示されます。

bash-3.2$ digdag run --rerun isfile.dig
2020-07-31 22:56:01 +0900: Digdag v0.9.42
2020-07-31 22:56:04 +0900 [WARN] (main): Reusing the last session time 2020-07-31T00:00:00+00:00.
2020-07-31 22:56:04 +0900 [INFO] (main): Using session /Users/morihaya/work/testdig/.digdag/status/20200731T000000+0000.
2020-07-31 22:56:04 +0900 [INFO] (main): Starting a new session project id=1 workflow name=isfile session_time=2020-07-31T00:00:00+00:00
2020-07-31 22:56:06 +0900 [INFO] (0017@[0:default]+isfile+check): py>: bin.check_file.CheckFile.check_file
2020-07-31 22:56:07 +0900 [INFO] (0017@[0:default]+isfile+judge): if>: false
2020-07-31 22:56:07 +0900 [INFO] (0017@[0:default]+isfile+judge^sub+nothing): echo>: The file does not exist.
The file does not exist.