haproxyrunit

How can I have a custom restart script for runit?


I'm using runit to manage an HAProxy and want to do a safe restart to reload a configuration file (specifically: haproxy -f /etc/haproxy/haproxy.cfg -sf $OLD_PROCESS_ID). I figure that I could run sv restart haproxy and tried to add a custom script named /etc/service/haproxy/restart, but it never seems to execute. How do I have a special restart script? Is my approach even good here? How do I reload my config with minimal impact using runit?


Solution

  • HAProxy runit service script

    /etc/service/haproxy/run

    #!/bin/sh
    #
    # runit haproxy
    #
    
    # forward stderr to stdout for use with runit svlogd
    exec 2>&1
    
    PID_PATH=/var/run/haproxy/haproxy.pid
    BIN_PATH=/opt/haproxy/sbin/haproxy
    CFG_PATH=/opt/haproxy/etc/haproxy.cfg
    
    exec /bin/bash <<EOF
    $BIN_PATH -f $CFG_PATH -D -p $PID_PATH
    
    trap "echo SIGHUP caught; $BIN_PATH -f $CFG_PATH -D -p $PID_PATH -sf \\\$(cat $PID_PATH)" SIGHUP
    trap "echo SIGTERM caught; kill -TERM \\\$(cat $PID_PATH) && exit 0" SIGTERM SIGINT
    
    while true; do # Iterate to keep job running.
      sleep 1 # Wake up to handle signals
    done
    EOF
    

    Graceful reload that keeps things up and running.

    sv reload haproxy
    

    Full stop and start.

    sv restart haproxy
    

    This solution was inspired by https://gist.github.com/gfrey/8472007