init.dの書き方
更新日:
投稿日:
投稿日:
Ubuntuでサービスを書く場合これが一番汎用性がある。
確認環境
Ubuntu 22.04.5 LTS
書き方
細かいことは書いていないので適当に解釈すること。
/etc/init.dにパーミッション755でサービス名のファイルを作成sudo touch /etc/init.d/prometheus_node_exporter sudo chmod 755 /etc/init.d/prometheus_node_exporter作成したファイルに以下のようなコードを書く
#! /usr/bin/env bash ### BEGIN INIT INFO # Provides: Prometheus Node exporter # Required-Start: $remote_fs $network $syslog # Required-Stop: $remote_fs $network $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Prometheus exporter for hardware and OS. # Description: Prometheus exporter for hardware and OS metrics exposed. ### END INIT INFO # Do NOT "set -e" # PATH should only include /usr/* if it runs after the mountnfs.sh script PATH=/sbin:/usr/sbin:/bin:/usr/bin:/usr/local/bin DESC="Prometheus Node exporter - Prometheus exporter for hardware and OS metrics exposed" NAME=prometheus_node_exporter PIDFILE=/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME WORKINGDIR=/var/lib/prometheus DAEMON=/usr/local/bin/node_exporter DAEMON_ARGS="--path.rootfs=/host --web.listen-address=[::]:9100" USER=prometheus # Exit if the package is not installed [ -x "$DAEMON" ] || exit 0 do_start() { PRM_ENVS="USER=$USER HOME=$WORKINGDIR" PRM_EXEC="$DAEMON $DAEMON_ARGS" sh -c "start-stop-daemon --start --quiet --pidfile $PIDFILE --make-pidfile \\ --background --chdir $WORKINGDIR --chuid $USER \\ --exec /bin/bash -- -c '/usr/bin/env $PRM_ENVS $PRM_EXEC'" } do_stop() { start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME --oknodo rm -f $PIDFILE } do_status() { if [ -f $PIDFILE ]; then if kill -0 $(cat "$PIDFILE"); then echo "$NAME is running, PID is $(cat $PIDFILE)" else echo "$NAME process is dead, but pidfile exists" fi else echo "$NAME is not running" fi } case "$1" in start) echo "Starting $DESC" "$NAME" do_start ;; stop) echo "Stopping $DESC" "$NAME" do_stop ;; status) do_status ;; restart) echo "Restarting $DESC" "$NAME" do_stop do_start ;; *) echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2 exit 2 ;; esac exit 0- サービスに登録
sudo update-rc.d prometheus_node_exporter defaults - 後は条件分岐に書かれているコマンドに沿ってserviceを蹴れば動くようになる。止めたりするときはinit.dに定義したものを使う(init.dそのものは単にコマンド名で分岐処理しているだけ)
sudo service prometheus_node_exporter start
消し方
update-rc.d prometheus_node_exporter remove