Using postgres with launchd without constant issues

apachehomebrewlaunchdpostgresql

I have postgres and passenger installed from homebrew, and use the os x built in apache. I have several rails apps that use postgres which are managed by passenger which in turn is managed by apache.

Currently apache is started by launchd at boot from /System/Library/LaunchDaemons/org.apache.httpd.plist, apache starts passenger via /etc/apache2/other/passenger.conf and once I've logged in postgres is started via ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist.

Everything starts fine and works great until I need to shut down or reboot my mac; then I run into a problem with how launchd tears down everything. Basically Launchd sends SIGTERM to every user process and then 20 seconds later (http://www.opensource.apple.com/source/launchd/launchd-842.92.1/src/core.c) sends SIGKILL, but postgres treats SIGTERM as a "smart shutdown" signal (http://www.postgresql.org/docs/9.5/static/server-shutdown.html) and waits for all it's existing sessions to close themselves before quitting. The problem is that the sessions are owned by the rails apps running under passenger and therefore won't shut down until apache shuts down. And apache doesn't shutdown until the system is shutting down. Which means postgres gets SIGKILLed and leaves it's postmaster.pid file lying around which prevents postgres from starting up the next boot until I rm that file.

Would moving postgres's launchd plist to /Library/LaunchDaemons/ be a better idea? It would potentially make postgres and apache be shut down at the same time, which given 20 seconds to stop should be enough time for postgres to exit cleanly. But I could be missing an easier solution.

Best Answer

I wound up moving the postgres launchd plist to /Library/LaunchDaemons and adding a UserName key/value pair (postgres won't run as root).