systemdサービスまたはtmpfiles.dを使用してランタイムフォルダを自動的に作成する方法は?

systemdサービスまたはtmpfiles.dを使用してランタイムフォルダを自動的に作成する方法は?

/run/gunicornDjangoアプリケーションで使用されるいくつかのGunicornソケット/ PIDファイルのランタイムフォルダを作成しようとしています。ディレクトリを手動で作成すると、すべてがうまく機能します。しかし、私はこれを強力な設定にし、最終的にAnsibleを使用してすべてを自動化しようとしています。

これに基づいて2つの選択肢があると思います。質問

オプション1 - ランタイムディレクトリ

最初のオプションはシステムサービスファイルで使用することですが、RuntimeDirectory=フォルダを作成することはできません。サービスファイルには以下が含まれます。

#/etc/systemd/system/gunicorn_django_test.service
[Unit]
Description=gunicorn_django daemon
After=network.target

[Service]
User=gunicorn
Group=www-data
RuntimeDirectory=gunicorn #This line is supposed to create a directory
RuntimeDirectoryMode=755
PIDFile=/run/gunicorn/django_test_pid
WorkingDirectory=/vagrant/webapps/django_venv/django_test
ExecStart=/vagrant/webapps/django_venv/bin/gunicorn --pid /run/gunicorn/django_test_pid --workers 3 --bind unix:/run/gunicorn/django_test_socket django_test.wsgi --error-logfile /var/log/gunicorn/django_test_error.log
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
PrivateTmp=true

[Install]
WantedBy=multi-user.target

を実行するとsystemctl start gunicorn_django_test.serviceサービスは開始されません。 Exec行を切り取り、手動で実行すると、次のメッセージが表示されます。Error: /run/gunicorn doesn't exist. Can't create pidfile.If I create /run/gunicornthefolder Manual, I can get things to work.

オプション2 - tmpfiles.d

2番目のオプションは、tmpfiles.d起動時にpid / socketファイル用のフォルダを作成することです。私はこのファイルを試しました:

#/etc/tmpfiles.d/gunicorn.conf
d /run/gunicorn 0755 gunicorn www-data -

これによりディレクトリが作成されますが、すばやく削除され、サービスを起動するとそのフォルダを使用できなくなります。

いくつかのPreExecコマンドをサービスファイルに手動で追加できますが、mkdirRuntimeDirectory / tmpfiles.dが機能しない理由を知りたいです。ありがとうございます。

バージョン/情報: Ubuntu 16.04 Server/systemd 229/Gunicorn 19.7.1/ランタイム ディレクトリ=/run

ベストアンサー1

提案されているように、PermissionsStartOnly=True各サービスのランタイムフォルダを追加して設定しました。0フォルダモードの起動も追加しました。

[Unit]
Description=gunicorn_django daemon
After=network.target

[Service]
PermissionsStartOnly=True
User=gunicorn
Group=www-data
RuntimeDirectory=gunicorn_django
RuntimeDirectoryMode=0775
PIDFile=/run/gunicorn_django/django_test_pid
WorkingDirectory=/vagrant/webapps/django_venv/django_test
ExecStart=/vagrant/webapps/django_venv/bin/gunicorn --pid /run/gunicorn_django/django_test_pid --workers 3 --bind unix:/run/gunicorn_django/django_test_socket django_test.wsgi --error-logfile /var/log/gunicorn/django_test_error.log
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

これで正しい権限を持つフォルダが作成されます。

drwxrwxrw-  2 gunicorn www-data   40 Mar 30 07:11 gunicorn_django/

@quixoticと@mark-stosbergに感謝します。

おすすめ記事