FreeBSD 12.1 Guide with rc.d script to start OctoPrint Automatically and as a Service

Hi,
I haven't seen much mention of using OctoPrint with FreeBSD so I just wanted to let people know that OctoPrint works perfectly on the FreeBSD 12.1 operating system! It is pretty straight forward to install using a virtual python environment but what people may not know is how to write a script in FreeBSD to have OctoPrint start automatically at startup and also to allow it to be controlled like a normal FreeBSD system service with "service octoprint {start,status,reset,stop,start}". So here is an rc.d startup script that I made that uses a non-privileged user instead of root with "iknowhatiamdoing" flag because it's not good to run OctoPrint as root for many reasons but especially security. Notes I wrote for myself are included at the top of the script may be helpful. Remember to add the user to the "dialer" group so it can access the USB serial port that connects to the 3D Printer. Enjoy!

#!/bin/sh

# PROVIDE: octoprint
# REQUIRE: NETWORKING
# KEYWORD: shutdown

# *******DESCRIPTION: FreeBSD 12.1 - rc.d script for the 3D Printer Software OctoPrint. This script takes advantage of FreeBSD's rc.subr framework to start OctoPrint automatically at startup and to allow it to be controlled as a FreeBSD service (eg. service octoprint start).  This script assumes you are running OctoPrint as a virtual python environment (py27-virtualenv), but it can easily be changed if you want.
# *******HELP:
# 1. To increase security we want to avoid running it as root so create a user named "octoprint" (or any name you want but then change the script to reflect the change) and add the user to the "dialer" group so it can access the USB serial port that connects to the 3D Printer.
# 2. Add the line "octoprint_enable=yes" to the end of "etc/rc.conf" this will enable and start OctoPrint at boot time.
# 3. Place this rc.d script file in "usr/local/etc/rc.d/"  (make sure this file is executable, if not run: "chmod +x /usr/local/etc/rc.d/octoprint")
# 4. Make sure the variables below such as, "command", "octoprint_basedir", "command_interpreter", etc..., reflect the correct paths to your octoprint executable, base directory, and virtual python executable (if you are using a virtual python environment like this script does). 
# 5. After startup the service can be controlled like any other service "service octoprint {start,status,reset,stop,start}"

. /etc/rc.subr

name=octoprint
rcvar="octoprint_enable"

: ${octoprint_enable:=no}

octoprint_user=octoprint
octoprint_group=${octoprint_user}
octoprint_user_path="/usr/home/${octoprint_user}"
octoprint_basedir="${octoprint_user_path}/.octoprint"

command_interpreter="${octoprint_user_path}/OctoPrint/venv/bin/python2.7"
command="${octoprint_user_path}/OctoPrint/venv/bin/${name}"
command_args="serve --basedir ${octoprint_basedir} > /dev/null 2>&1 &"

load_rc_config $name
run_rc_command "$1"
2 Likes