forked from chamilad/process-metrics-collector
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplot-metrics.sh
More file actions
95 lines (77 loc) · 2.25 KB
/
plot-metrics.sh
File metadata and controls
95 lines (77 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/bin/bash
scriptdir="$(dirname "${BASH_SOURCE[0]}")"
case "$scriptdir" in
/*)
true
;;
.)
scriptdir="$PWD"
;;
*)
scriptdir="${PWD}/scriptdir"
;;
esac
# Import the plotGraph function and timestamp_format constant
source "${scriptdir}"/plotGraph.sh
# This global variable must be assigned later
csv_filename="/dev/null"
function plotMyGraph() {
plotGraph "$csv_filename"
}
function process_metrics_collector_original() {
local pid="$1"
local reldatadir="$2"
local sleep_secs="$3"
# check if process exists
kill -0 $pid > /dev/null 2>&1
local pid_exist=$?
if [ $pid_exist != 0 ]; then
echo "ERROR: Process ID $pid not found."
return 1
fi
local current_time=$(date +"%Y_%m_%d-%H_%M")
local dir_name="${reldatadir}/${current_time}-${pid}"
# This global variable is initialized here
csv_filename="${dir_name}/metrics-${pid}.csv"
local command_filename="${dir_name}/command-${pid}.txt"
# create data directory
mkdir -p "$dir_name"
tr '\0' ' ' < /proc/"$pid"/cmdline > "$command_filename"
# add SIGINT & SIGTERM trap
trap "plotMyGraph" SIGINT SIGTERM SIGKILL
echo "Writing data to CSV file $csv_filename..."
# write CSV headers
echo "Time,PID,Virt,Res,CPU,Memory,TCP Connections,Thread Count" > "$csv_filename"
# check if process exists
kill -0 $pid > /dev/null 2>&1
pid_exist=$?
# collect until process exits
while [ $pid_exist == 0 ]; do
# check if process exists
kill -0 $pid > /dev/null 2>&1
pid_exist=$?
if [ $pid_exist == 0 ]; then
# read cpu and mem percentages
local timestamp=$(date +"$timestamp_format")
local cpu_mem_usage=$(top -b -n 1 | grep -w -E "^ *$pid" | awk '{print $5 "," $6 "," $9 "," $10}')
local tcp_cons=$(lsof -i -a -p $pid -w | tail -n +2 | wc -l)
local tcount=$(ps -o nlwp h $pid | tr -d ' ')
# write CSV row
echo "$timestamp,$pid,$cpu_mem_usage,$tcp_cons,$tcount" >> $csv_filename
sleep "$sleep_secs"
fi
done
}
if [ "$0" == "${BASH_SOURCE[0]}" ] ; then
if [ -z $1 ]; then
echo "ERROR: Process ID not specified."
echo
echo "Usage: $(basename "$0") <PID>"
exit 1
fi
# process id to monitor
pid="$1"
process_metrics_collector_original "$pid" data 1
# draw graph
plotMyGraph
fi