Python rc.d with daemon(8), python and virtualenv

Hi,

I'd like to create an rc.d script that uses daemon(8) to manage a python(3) script with dependencies from virtualenv (daemonization, logging and be automatically restarted on exit).

I am not sure what's the right way to approach this.

My initial version used the script as command, together with the command_interpreter, which was python inside the virtualenv. However this would fail because it seems that command_interpreter looks at the shebang which is #!/usr/bin/env python3.

So I wonder whether I should use daemon as a command. But here I am unsure if the right way would be to use -P or -p for the pidfile. An automatically restarting would probably make more sense with -P (so the pid of daemon, rather than python). However, if I do this I have a Operation not permitted error on restart, which is strange, because I have root access.

Did anyone solve something like this yet?

I also saw the zeronet port, which uses /bin/true as the command but I am not sure if I do something wrong then.

Is there a good example, best practice for this? I don't find much regarding interpreted languages. Only that it makes sense to use command_interpreter.

PS: I know I could use something like supervisord, etc. However, I'd like to prevent dependencies. Would it make sense to use something like monit for restarting?
 
Personally I prefer to run all daemon under runit supervision, but the FreeBSD rc can handle your usecase just fine. You can use daemon() to daemonize (and optionally supervise) your script. This article provides a good introduction to FreeBSD rc scripting including writing non-trivial rc scripts for special cases like the one you described. You may want to look at the rc script installed by the www/gatling port as an example.
 
#!/bin/sh

# PROVIDE: xxx
# REQUIRE: LOGIN DAEMON NETWORKING FILESYSTEMS
# KEYWORD: jail python

. /etc/rc.subr

name="xxx"
rcvar=${name}_enable
xxx_chdir="/usr/local/xxx"
pidfile="/var/run/${name}.pid"
logfile="/var/log/xxx/${name}.log"
start_precmd="xxx_prestart"

xxx_chdir=/usr/local/xxx
xxx_conf=${xxx_chdir}/conf

command="/usr/sbin/daemon"
command_args="-u xxx -o ${logfile} -P ${pidfile} -r /usr/local/xxx/venv/bin/xxx --userdir ${xxx_conf}"

xxx_prestart() {
echo "activate python venv"
cd ${xxx_chdir}
. ./venv/bin/activate
}
load_rc_config $name
run_rc_command "$1"
 
Back
Top