45e7e62a439a8c5841465ffd0126d408dfd8fc85
[utp-swift.git] / hook_monitor_pid
1 #!/bin/bash
2
3 #
4 # monitor process resources using systat (/proc), free, iptables and /sys
5 #
6 # 2010, Razvan Deaconescu, razvan.deaconescu@cs.pub.ro
7 #
8
9 # command line argument must be a process id
10 if test $# -ne 1; then
11         echo "Usage: $0 <pid>" 1>&2
12         exit 1
13 fi
14
15 pid=$1
16
17 # check if pid exists
18 kill -0 $pid > /dev/null 2>&1
19 if test $? -ne 0; then
20         echo -e "PID $pid does not exists.\nUsage: $0 <pid>" 1>&2
21         exit 1
22 fi
23
24 # use _DEBUG="off" to turn off debug printing
25 _DEBUG="off"
26
27 # cleanup code (run as signal handler)
28 cleanup()
29 {
30         kill -TERM $pidstat_pid
31         kill -TERM $iostat_pid
32         kill -TERM $free_pid
33         kill -TERM $timer_callback_pid
34 }
35
36 # function acting like a periodic callback
37 timer_callback()
38 {
39         while true; do
40                 date +%F-%X
41                 sudo iptables -t filter -L -n -v
42                 cat /sys/class/net/eth0/statistics/rx_bytes /sys/class/net/eth0/statistics/tx_bytes
43                 sleep 1
44         done
45 }
46
47 # run cleanup on signal receive
48 trap cleanup 0 1 2 3 15
49
50 # per-process processor (-u), disk (-d) and memory usage (-r)
51 pidstat -u -d -r -p $pid 1 &
52 pidstat_pid=$!
53
54 # per-system (iostat and free)
55 iostat -d -c 1 &
56 iostat_pid=$!
57 free -s 1 &
58 free_pid=$!
59
60 # per-process network bandwidth usage (iptables)
61 # /sys/class/net/$iface/statistics/{tx,rx}_bytes (per system)
62
63 # remove old iptables rules/chains
64 sudo iptables -t filter -F udp_out > /dev/null 2>&1
65 sudo iptables -t filter -F udp_in > /dev/null 2>&1
66 sudo iptables -t filter -X udp_out > /dev/null 2>&1
67 sudo iptables -t filter -X udp_in > /dev/null 2>&1
68 sudo iptables -t filter -F OUTPUT > /dev/null 2>&1
69 sudo iptables -t filter -F INPUT > /dev/null 2>&1
70
71 # add iptables rule
72 sudo iptables -t filter -N udp_out
73 sudo iptables -t filter -N udp_in
74 sudo iptables -t filter -A OUTPUT -p udp -o br0 -j udp_out
75 sudo iptables -t filter -A udp_out -j ACCEPT
76 sudo iptables -t filter -A INPUT -p udp -i br0 -j udp_in
77 sudo iptables -t filter -A udp_in -j ACCEPT
78
79 timer_callback &
80 timer_callback_pid=$!
81
82 # wait for child processes to end (shouldn't happen)
83 wait