verfuegbarkeit einer website ueber proxy-strecke pruefen


#!/bin/bash
#
# Check Proxy Chain - Request via Proxy prüfen
#
# Läuft auf nem HAproxy Loadbalancer vor ein paar Web Proxies
# die über zwei verschiedene Internet-Leitungen ins Web gehen
# und nimmt Proxies aus dem Balancing, die sich nicht ordentlich
# benehmen (überhaupt nicht oder zu spät liefern). xD
#
# Den Load Balancer hab ich als Keepalive Cluster gebaut, dann
# ist der auch redundant. Aber das ist eine andere Story...
#
# Ach ja: Ich empfehle Debian (stable oder testing).
#
# Benötigte Pakete:
# - haproxy
# - curl
# - socat
# - bc
#
# curlformat.txt:
#
#    time_namelookup:  %{time_namelookup}s\n
#       time_connect:  %{time_connect}s\n
#    time_appconnect:  %{time_appconnect}s\n
#   time_pretransfer:  %{time_pretransfer}s\n
#      time_redirect:  %{time_redirect}s\n
# time_starttransfer:  %{time_starttransfer}s\n
#                    ----------\n
#         time_total:  %{time_total}s\n
#
# dj0Nz 2020

squid1="http://192.168.2.101:8080"
squid2="http://192.168.2.102:8080"
squid3="http://192.168.3.101:8080"
squid4="http://192.168.3.102:8080"

target="https://www.web.de/"
tegrat="https://www.telekom.de/"
curlfmt=curlformat.txt
reqstats=/tmp/reqstats
backend="proxies"
lamelimit=4.0
ctimeout=8
logfile=/var/log/check-proxy.log

echo -n "-- proxy check - " >> $logfile 2>&1
date >> $logfile 2>&1

for ((i=1; i<5; i++)); do
   node="squid$i"
   proxy="${!node}"
   curl -x $proxy -sI -w "@$curlfmt" --connect-timeout $ctimeout $target > $reqstats.$node 2>&1
   status=`head -1 $reqstats.$node | awk '{print $2}'`
   reqtime=`grep time_total $reqstats.$node | awk '{print $2}' | tr -d 's'`
   lame=`echo $reqtime'<'$lamelimit|bc -l`
   if [ "$status" = "200" ]; then
      if [ "$lame" = "0" ]; then
         printf "%-17s %s\n" "$node: Lame" "[$reqtime]" >> $logfile 2>&1
         echo "set weight $backend/$node 0" | socat unix-connect:/var/run/haproxy/admin.sock stdio
      else
         printf "%-17s %s\n" "$node: OK" "[$reqtime]" >> $logfile 2>&1
	 echo "set weight $backend/$node 100" | socat unix-connect:/var/run/haproxy/admin.sock stdio
         if [ -f /tmp/$node.disabled ]; then
            rm /tmp/$node.disabled
            echo "enable server $backend/$node" | socat unix-connect:/var/run/haproxy/admin.sock stdio
         fi
      fi
   else
      secondchance=`curl -x $proxy -sI --connect-timeout $ctimeout $tegrat | head -1 | awk '{print $2}'`
      if [ "$secondchance" = "200" ]; then
         echo "$node: Primary check failed" >> $logfile 2>&1
      else
         echo "$node: Error" >> $logfile 2>&1
         echo "disable server $backend/$node" | socat unix-connect:/var/run/haproxy/admin.sock stdio
         touch /tmp/$node.disabled
      fi
   fi
done