Skip to content

Instantly share code, notes, and snippets.

@stevenkaras
Last active October 12, 2015 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevenkaras/a731e7c956e8139f4eaf to your computer and use it in GitHub Desktop.
Save stevenkaras/a731e7c956e8139f4eaf to your computer and use it in GitHub Desktop.
Local service instrumentation
#!/usr/bin/env bash
# This script runs services in the background, logs their output, and spins them down gently
#
# I use it in development, since I don't want to have databases and message brokers running
# all the time on my laptop.
#
# Reads a list of services either from ARGV or from a ".services" file
# Alternatively, can take a list of services (from either source) in label=command format
function cleanup_from_pid_file() {
# send a SIGINT for a graceful shutdown
kill -2 $(cat $1) >/dev/null 2>&1
sleep 3
kill -0 $(cat $1) >/dev/null 2>&1
if [[ $? -eq 1 ]]; then
rm $1
exit 0
fi
# a bit more insistent this time, send them SIGTERM
kill -15 $(cat $1) >/dev/null 2>&1
sleep 10
kill -0 $(cat $1) >/dev/null 2>&1
if [[ $? -eq 1 ]]; then
rm $1
exit 0
fi
# leave it to the user to send SIGKILL
exit 1
}
function cleanup() {
for label in "$@"; do
cleanup_from_pid_file ".${label}.pid" &
done
}
function map_service() {
case "$1" in
postgresql|postgres|pgsql|pg|psql)
echo "postgres=postgres -D /usr/local/var/postgres"
;;
redis)
echo "redis=redis-server /usr/local/etc/redis.conf"
;;
memcached|memcache|mcache|memc)
echo "memcached=memcached"
;;
rabbitmq|rmq)
echo "rabbitmq=rabbitmq-server"
;;
mongodb|mongo)
echo "mongodb=mongod --dbpath=.mongodb"
;;
mailcatcher|mailc)
echo "mailcatcher=mailcatcher -f"
;;
*)
echo "$1=$@"
;;
esac
}
function main() {
if [[ $# -gt 0 ]]; then
local services=( "$@" )
elif [[ -s "./.services" ]]; then
local -a services
mapfile services < ./.services
else
local services=( )
fi
if [[ ${#services[@]} -eq 0 ]]; then
echo "Usage: run_services SERVICES"
echo "Or list services to run in a .services file"
exit 1
fi
local -a labels
local -a commands
for i in ${!services[@]}; do
services[$i]=$( map_service ${services[$i]} )
labels[$i]="${services[$i]/%=*/}"
commands[$i]="${services[$i]:((${#labels[$i]} + 1))}"
done
trap "cleanup ${labels[@]}; exit" SIGHUP SIGINT SIGTERM
for i in ${!services[@]}; do
${commands[$i]} > .${labels[$i]}.log &
echo $! > .${labels[$i]}.pid
done
while true; do
sleep 10
done
}
main "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment