Skip to content

Instantly share code, notes, and snippets.

@ilyaevseev
Last active December 26, 2015 11:59
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 ilyaevseev/7147228 to your computer and use it in GitHub Desktop.
Save ilyaevseev/7147228 to your computer and use it in GitHub Desktop.
Script for restarting Django on-the-fly -- creates new instance on another port, switches nginx to it, kills old instance.
#!/bin/sh
# Should be called on system startup from /etc/rc.local
# for restoring default backend ports previously switched by restart_django.sh
fix_nginx_port() {
local nginx_config="/etc/nginx/sites-available/$1.conf"
test -w "$nginx_config" || { logger "ERROR: $nginx_config not writable."; return 1; }
local main_port="$2" backup_port="$3"
grep -q -- ":$backup_port;" $nginx_config || return
sed -i -e "s,:$backup_port;,:$main_port;," $nginx_config
nginx -s reload
}
# Usage sample..
fix_nginx_port site1 8100 8101
fix_nginx_port site2 8200 8201
#!/bin/sh
test $# = 3 || { echo "Usage: ${0##*/} /path/to/nginx.conf port1 port2"; exit 1; }
nginx_config="$1"
port1="$2"
port2="$3"
Die() { echo "Error: $*"; exit 1; }
test -w "$nginx_config" || Die "$nginx_config is not writable."
listens_on() { pgrep -f "/manage.py runfcgi host=127.0.0.1 port=$1 pidfile=/" > /dev/null; }
fix_nginx() {
local old_port="$1" new_port="$2"
sed -i "s,:$old_port;,:$new_port;," $nginx_config
grep -q ":$new_port;" $nginx_config ||
Die "cannot set port $new_port in $nginx_config"
nginx -s reload
}
swap_ports() {
local old_port="$1"
local new_port="$2"
local old_pid=`pgrep -f "/manage.py runfcgi host=127.0.0.1 port=$old_port pidfile=/"`
local new_pid=`pgrep -f "/manage.py runfcgi host=127.0.0.1 port=$new_port pidfile=/"`
test -n "$old_pid" || Die "nothing listens on $old_port?"
test -n "$new_pid" && Die "already listens on $new_port?"
local user="$(ps ho user $old_pid)"
local old_cmd="$(ps hwwo cmd $old_pid)"
local new_cmd="$(echo $old_cmd | sed -e s,port=$old_port,port=$new_port,)"
local pid_file="$(echo $old_cmd | sed -e 's,.* pidfile=,,' -e 's, .*,,')"
# echo DEBUG: pid_file = $pid_file
# echo DEBUG: old_port = $old_port, old_cmd = $old_cmd
# echo DEBUG: new_port = $new_port, new_cmd = $new_cmd
# return
sudo -H -b -n -u "$user" -- $new_cmd # >/dev/null 2>&1
sleep 1
new_pid=`pgrep -f "/manage.py runfcgi host=127.0.0.1 port=$new_port pidfile=/"`
test -n "$new_pid" || Die "nothing listens on new $new_port?"
echo $new_pid > "$pid_file"
fix_nginx $old_port $new_port
sleep 1
kill "$old_pid"
}
if test "${0#*restart}" = "$0"; then
fix_nginx "$port2" "$port1"
elif listens_on "$port1"; then
swap_ports "$port1" "$port2"
elif listens_on "$port2"; then
swap_ports "$port2" "$port1"
else
Die "Nothing listens on $port1 nor $port2?"
fi
## END ##
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment