Skip to content

Instantly share code, notes, and snippets.

@ruoat
Created January 18, 2016 16:03
Show Gist options
  • Save ruoat/3ea350e4390640010d46 to your computer and use it in GitHub Desktop.
Save ruoat/3ea350e4390640010d46 to your computer and use it in GitHub Desktop.
How to simulate network failures using socat proxies
  • ./port-proxy-prepare.sh to create PID directory for running proxy
  • ./sample-google-proxy.sh start to start listening 8443 and proxying traffic to google
  • Configure client application to perform requests to localhost:8443 instead of www.google.com:443
  • ./sample-google-proxy.sh stop to simulate situation when google is down
  • Do client testing
  • ./sample-google-proxy.sh start to simulate service up again
#!/bin/sh -e
USER=$(whoami)
PID_DIR=/var/run/test-proxy
sudo mkdir -p $PID_DIR
sudo chown $USER $PID_DIR
echo Created PID directory for test-proxy
#!/bin/bash
SOCAT=socat
if [ "$#" -ne 5 ]; then
echo Usage:
echo "$(basename $0) NAME SOURCE_PORT TARGET TARGET_PORT [start|stop]"
exit 1
fi
NAME=$1
SOURCE_PORT=$2
TARGET=$3
TARGET_PORT=$4
COMMAND=$5
PID_FILE=/var/run/test-proxy/socat-$SOURCE_PORT
if [ "$COMMAND" = "start" ]; then
if [ -e $PID_FILE ]; then
PID_IN_PID_FILE=$(/bin/cat $PID_FILE)
PID_STATUS=$(ps -p$PID_IN_PID_FILE -o pid=)
if [ -n "$PID_STATUS" ]; then
echo -e "[$NAME]\t\tProxy in $SOURCE_PORT is already started!"
exit 0
else
rm $PID_FILE
echo -e [$NAME]\t\tRemoved stale $PID_FILE
fi
fi
$SOCAT TCP4-LISTEN:${SOURCE_PORT},reuseaddr,fork TCP4:$TARGET:$TARGET_PORT &
echo $! > $PID_FILE
echo -e "[$NAME]\t\tStarted proxy from $SOURCE_PORT to $TARGET:$TARGET_PORT"
elif [ "$COMMAND" = "stop" ]; then
if [ -e $PID_FILE ]; then
PID_IN_PID_FILE=$(/bin/cat $PID_FILE)
PID_STATUS=$(ps -p$PID_IN_PID_FILE -o pid=)
if [ -z "$PID_STATUS" ]; then
echo -e "[$NAME]\t\tProxy in $SOURCE_PORT is already stopped!"
rm $PID_FILE
echo Removed stale $PID_FILE
exit 1
fi
kill -9 -$(ps -o pgid= $PID_IN_PID_FILE| grep -o '[0-9]*')
rm $PID_FILE
echo -e "[$NAME]\t\tStopped proxy from $SOURCE_PORT to $TARGET:$TARGET_PORT"
else
echo -e "[$NAME]\t\tCould not find $PID_FILE. Proxy in $SOURCE_PORT is already stopped?"
exit 0
fi
else
echo Unknown command: $COMMAND
fi
#!/bin/sh
if [ "$#" -ne 1 ]; then
echo Usage:
echo "$(basename $0) [start|stop]"
exit 1
fi
SOURCE_PORT=8443
TARGET=www.google.com
TARGET_PORT=443
./port-proxy.sh http-proxy $SOURCE_PORT $TARGET $TARGET_PORT $1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment