Merges George changes
[p2p-testing-infrastructure.git] / ControlScripts / hook_monitor_pid_udp.sh
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         ps -ef
21         echo -e "PID $pid does not exists.\nUsage: $0 <pid>" 1>&2
22         exit 1
23 fi
24
25 # use _DEBUG="off" to turn off debug printing
26 _DEBUG="off"
27
28 # Read the global configuration file
29 # Check if the global configuration file exists
30 if [ ! -e globalconfig ]; then
31         echo "Warning: The global config file globalconfig does not exist."
32 else
33         source globalconfig
34 fi
35
36 # cleanup code (run as signal handler)
37 cleanup()
38 {
39         kill -TERM $pidstat_pid
40         kill -TERM $iostat_pid
41         kill -TERM $free_pid
42         kill -TERM $timer_callback_pid
43 }
44
45 # function acting like a periodic callback
46 timer_callback()
47 {
48         while true; do
49                 date +%F-%X
50                 sudo iptables -t filter -L -n -v
51                 cat /sys/class/net/eth0/statistics/rx_bytes /sys/class/net/eth0/statistics/tx_bytes
52                 sleep 1
53         done
54 }
55
56 # run cleanup on signal receive
57 trap cleanup 0 1 2 3 15
58
59 # per-process processor (-u), disk (-d) and memory usage (-r)
60 pidstat -u -d -r -p $pid 1 &
61 pidstat_pid=$!
62
63 # per-system (iostat and free)
64 iostat -d -c 1 &
65 iostat_pid=$!
66 free -s 1 &
67 free_pid=$!
68
69 # per-process network bandwidth usage (iptables)
70 # /sys/class/net/$iface/statistics/{tx,rx}_bytes (per system)
71
72 # remove old iptables rules/chains
73 sudo iptables -t filter -F udp_out > /dev/null 2>&1
74 sudo iptables -t filter -F udp_in > /dev/null 2>&1
75 sudo iptables -t filter -X udp_out > /dev/null 2>&1
76 sudo iptables -t filter -X udp_in > /dev/null 2>&1
77 sudo iptables -t filter -F OUTPUT > /dev/null 2>&1
78
79 # add iptables rule
80 sudo iptables -t filter -N udp_out
81 sudo iptables -t filter -N udp_in
82 sudo iptables -t filter -A OUTPUT -p udp -j udp_out
83 sudo iptables -t filter -A udp_out -j ACCEPT
84 sudo iptables -t filter -A OUTPUT -p udp -j udp_in
85 sudo iptables -t filter -A udp_in -j ACCEPT
86
87 timer_callback &
88 timer_callback_pid=$!
89
90 # wait for child processes to end (shouldn't happen)
91 wait