[Linux] 無聊練 Shell 2 - http 體力戰

朋友最近把主機移到 google 上面了
但用的是免費的份量
於是就很好奇這樣真的OK嗎
在經過同意之下跑了簡單的壓力測試
原本跑靜態的檔案還沒有什麼問題
跑一下首頁的動態內容結果 database 馬上就爆掉了 XD

用的方法只是用多個 curl 同時執行去請求

sh

Run

隨手寫的 shell script
執行是這樣執行的

./concurrent.sh 5 ./while.sh curl http://example.com

第一個參數 ./a.sh 是只要同時執行的程式
第二個參數 30 是說同時執行 30 個
第三個參數 是用來傳給第一個參數的程式的

script

concurrent.sh

concurrent.sh

#! /bin/bash

pids=( )
program="$2"
count="$1"

shift
shift

args=( )
for i in "$@"
do
  args+=("$i")
done

function kill_all() {
  for pid in ${pids[@]}
  do
    echo killing $pid
    kill -$1 $pid 
  done
  exit $1
}

trap 'kill_all 15' 2
trap 'kill_all 15' 15

function new_process() {
  $program "${args[@]}" &
  local pid=$!
  pids+=($pid)
  echo new ${pid}
}

function recreate_process() {
  local i=$1
  echo ${pids[$i]} dead
  $program "$args" &
  pids[$i]=$!
  echo new ${pids[$i]}
}

echo program: \[$program\]
echo count: \[$count\]
echo args: \[$args\]

if [ -z "$program" -o -z "$count" ] || ! [[ "$count" =~ ^[0-9]+$ ]] || [ "$count" -lt 1 ]; then
  echo ':('
  exit 1
fi

for ((i = 0; i < $count; ++i))
do
  new_process
done

while :
do
  for i in ${!pids[@]}
  do
    kill -0 ${pids[$i]} 2>/dev/null || recreate_process $1
  done
  sleep 1
done

echo end

while.sh

while.sh

#! /bin/bash

if [ "$#" -gt 0 ]; then
  while :
  do
    "$@" >/dev/null 2>/dev/null || echo fail 1>&2
  done
fi

功能

while.sh

while.sh 的部份比較簡單

只是一個無限迴圈一直跑 curl

concurrent.sh

while.sh 的部份就有趣多了
主要功能是同時執行同樣的程式
如果有提前結束的就在開新的

Reference

https://www.cyberciti.biz/faq/unix-linux-iterate-over-a-variable-range-of-numbers-in-bash/
https://www.cyberciti.biz/faq/bash-for-loop/
https://stackoverflow.com/questions/6212219/passing-parameters-to-a-bash-function
https://stackoverflow.com/questions/3112687/how-to-iterate-over-associative-arrays-in-bash
https://stackoverflow.com/questions/3043978/how-to-check-if-a-process-id-pid-exists
https://stackoverflow.com/questions/1951506/add-a-new-element-to-an-array-without-specifying-the-index-in-bash
https://stackoverflow.com/questions/16860877/remove-an-element-from-a-bash-array
https://notes.imyz.tw/shell-script-handle-signal/
https://www.cyberciti.biz/faq/finding-bash-shell-array-length-elements/
https://www.cyberciti.biz/faq/bash-for-loop-array/
https://stackoverflow.com/questions/1878882/arrays-in-unix-shell
https://serverfault.com/questions/205498/how-to-get-pid-of-just-started-process

Show Comments