# script for kloudbuster

# Tune the Linux kernel for scale test
echo "* soft nofile 102400" >> /etc/security/limits.conf
echo "* hard nofile 102400" >> /etc/security/limits.conf

cat << EOF >> /etc/sysctl.conf
fs.file-max=6553550
net.core.wmem_max=8388608
net.core.wmem_default=8388608
net.core.rmem_max=33554432
net.core.rmem_default=33554432
net.core.netdev_max_backlog=100000
net.ipv4.icmp_ratelimit=0
net.ipv4.tcp_tw_recycle=1
net.ipv4.tcp_tw_reuse=1
net.ipv4.tcp_max_tw_buckets=65536
net.ipv4.tcp_fin_timeout=15
net.ipv4.tcp_max_syn_backlog=65536
net.ipv4.tcp_syncookies=1
net.ipv4.neigh.default.gc_thresh1=4096
net.ipv4.neigh.default.gc_thresh2=4096
net.ipv4.neigh.default.gc_thresh3=4096
net.ipv4.conf.all.rp_filter=0
net.ipv4.conf.all.arp_filter=0
net.ipv4.conf.default.rp_filter=0
net.ipv4.conf.default.arp_filter=0
net.ipv4.conf.eth0.rp_filter=0
net.ipv4.conf.eth0.arp_filter=0
EOF
sysctl -p

# do not autostart the redis server or the nginx server
# let the KB agent start the appropriate server (if applicable)
update-rc.d -f redis-server remove
update-rc.d -f nginx remove

# Change permission to 777 for kb_test
chmod -R 777 /kb_test

# Generate a 32K HTML files
mkdir -p /data/www
cd /data/www/
dd if=/dev/zero of=index.html bs=32K count=1
chmod -R 777 /data
cd -

# redis server should listen on all interfaces
sed -i "s/127.0.0.1/0.0.0.0/g" /etc/redis/redis.conf

# if started nginx should be allowed to open more file descriptors
sed -i 's/start-stop-daemon\ --start/ulimit\ \-n\ 102400\n\t\0/g' /etc/init.d/nginx

# Auto start the KloudBuster Agent, with user-data
sed -i "s/^exit\s0/cd \/kb_test\n\0/g" /etc/rc.local
sed -i "s/^exit\s0/wget http\:\/\/169.254.169.254\/latest\/user-data\n\0/g" /etc/rc.local
sed -i "s/^exit\s0/python \/kb_test\/kb_vm_agent.py \&\n\0/g" /etc/rc.local


# ======
# Client
# ======

# python redis client
pip install redis

# Download cmake
cd /tmp
wget http://www.cmake.org/files/v3.3/cmake-3.3.0-Linux-x86_64.tar.gz
tar xzf cmake-3.3.0-Linux-x86_64.tar.gz

# Install HdrHistorgram_c
git clone git://github.com/HdrHistogram/HdrHistogram_c.git
cd HdrHistogram_c
/tmp/cmake-3.3.0-Linux-x86_64/bin/cmake .
make install

# Remove cmake and HdrHistogram_c builds
rm /tmp/cmake-3.3.0-Linux-x86_64.tar.gz
rm -rf /tmp/cmake-3.3.0-Linux-x86_64
rm -rf HdrHistogram_c

# Install the http traffic generator
git clone git://github.com/yicwang/wrk2.git
cd wrk2
make
mv wrk /usr/local/bin/wrk2
cd ..
rm -rf wrk2

# Move the HdrHistogram library to /usr/lib
mv /usr/local/lib/libhdr_histogram.so /usr/lib/

# Uninstall unneeded packages
apt-get -y --purge remove git
apt-get -y --purge remove python-pip
apt-get -y --purge remove build-essential
apt-get -y --purge autoremove
apt-get -y autoclean
