-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathviotop.sge
executable file
·4024 lines (3642 loc) · 92.5 KB
/
viotop.sge
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/sh
# vi: set ft=sh noet ts=8 sw=8 :: Vi/ViM
############################################################ IDENT(1)
#
# $Title: Script to generate top-like statistics for VFS I/O under Linux $
# $Copyright: 2020-2021 Devin Teske. All rights reserved. $
# $FrauBSD: viotop/viotop.sge 2021-10-14 15:51:01 -0700 freebsdfrau $
#
############################################################ INFORMATION
#
# In viotop, a ``view'' is the user's choice between -c, -p, -g, -s, -t, or -u.
# For example, `-u' asks viotop to display the ``user view'' where statistics
# displayed are on a per-user basis.
#
# The ``mode'' is the user's choice between viewing data input/output (this is
# the default) and metadata operations (-m). When presenting data in JSON (-j)
# use -M to get both data and metadata options.
#
# The code is broken down into:
# - Mode selection (user choice)
# - View selection (user choice)
# - Filter selection (user choice)
# - Inspection of running system
# - bpftrace and bpftool execution
# - awk to process bpftrace output
#
# Code navigating Search Terms/ST:
# BPFTRACE Start of bpftrace
# FILTERS Data filters
# JSONDATA JSON data generation
# OPS Data operations (read vs write)
# POST bpftrace post-processor (awk)
# PRE Start of pre-processor (sh)
# SORTING Sort routines
# SUBTOTALS Subtotal generation
# TRACEDATA bpftrace data generation and processing
# VIEWDATA View data generation
# VIEWS View processing
#
############################################################ DEFAULTS
DEFAULT_INTERVAL=2.0 # seconds
#
# Sorting choices (case-insensitive):
# total (in any mode; default sort column)
# read write in out (without `-m')
# good fail (with `-m')
#
DEFAULT_SORT=total
############################################################ GLOBALS
VERSION='$Version: 9.1 $'
pgm="${0##*/}" # Program basename
#
# Global exit status
#
SUCCESS=0
FAILURE=1
#
# Command-line options
#
COLOR=1 # -C
DEBUG= # -d
DEBUGGER= # -D
FILTER_FOLLOW= # -f
FILTER_GROUP= # -G group
FILTER_PID= # -P pid
FILTER_SGE= # -S job
FILTER_TYPE= # -T type
FILTER_USER= # -U user
IGNORE_RUNNING= # -I
INTERVAL=$DEFAULT_INTERVAL # -i sec
MODE=data # vs `meta' (-m) or `both' (-M)
NO_NAMES= # -n
NSAMPLES= # -N num
OUTPUT_JSON= # -j
QUIET= # -q
RAW_VIEW= # -r
REDACT=${VIOTOP_REDACT:+1} # -R
SHOW_AGGREGATES= # -a
SHOW_BASIC= # -b
SORT=$DEFAULT_SORT # -k col
TIMEOUT_LSOF= # -L time
VIEW_AGGREGATES= # -A
VIEW_COMM= # -c
VIEW_GROUP= # -g
VIEW_PID= # -p (default)
VIEW_SGE= # -s
VIEW_TYPE= # -t
VIEW_USER= # -u
WIDE_VIEW= # -w
#
# Probes
# NB: Dependent on kernel version
# NB: export'd for awk(1) `ENVIRON' access
#
export KPROBE_EXECVE=kprobe:do_execve
export KRETPROBE_EXECVE=kretprobe:do_execve
export KPROBE_EXECVE_LEGACY=kprobe:SyS_execve
export KRETPROBE_EXECVE_LEGACY=kretprobe:SyS_execve
export KPROBE_VFS_FSTAT=kprobe:vfs_fstat
export KRETPROBE_VFS_FSTAT=kretprobe:vfs_fstat
export KPROBE_VFS_FSTAT_PRE_da9aa5d=kprobe:vfs_statx_fd
export KRETPROBE_VFS_FSTAT_PRE_da9aa5d=kretprobe:vfs_statx_fd
#
# Miscellaneous
#
CB='}'
CONS=1
[ -t 1 ] || CONS= COLOR= # stdout is not a tty
DQ='"'
FILTER_COMM=
FILTER_GID=
FILTER_UID=
FOLLOW_PIDS=
FORK_CONDITION=
INTERVAL_PROBE= # Calculated
INTERVAL_SECONDS= # Raw value for awk
MAP_ID_FOLLOW=
MAP_ID_SGE=
MAP_ID_TRACE=
MODE_DATA=
MODE_META=
OPEN_CONDITION=
OPEN_FDS=
SGE_CONDITION=
SGE_JOBS=
VIEW=
############################################################ FUNCTIONS
die()
{
local fmt="$1"
if [ "$fmt" ]; then
shift 1 # fmt
printf "%s: $fmt\n" "$pgm" "$@" >&2
fi
exit $FAILURE
}
usage()
{
local fmt="$1"
local optfmt="\t%-11s %s\n"
exec >&2
if [ "$fmt" ]; then
shift 1 # fmt
printf "%s: $fmt\n" "$pgm" "$@"
fi
printf "Usage: %s [OPTIONS] [--] [comm]\n" "$pgm"
printf "Options:\n"
printf "$optfmt" "-A" "Only show aggregate subtotals."
printf "$optfmt" "-a" "Show aggregate subtotals."
printf "$optfmt" "-b" "Show basic counts instead of rates."
printf "$optfmt" "-C" "Always enable color."
printf "$optfmt" "-c" "View read/write activity by command name."
printf "$optfmt" "-D" "Enable debugger."
printf "$optfmt" "-d" "Debug. Print bpftrace script and exit."
printf "$optfmt" "-G group" "Group filter (name or id)."
printf "$optfmt" "-g" "View read/write activity by group."
printf "$optfmt" "-h" "Print usage statement and exit."
printf "$optfmt" "-I" "Ignore already-running processes."
printf "$optfmt" "-i sec" \
"Set interval seconds. Default \`$DEFAULT_INTERVAL'."
printf "$optfmt" "-J" "Output most JSON data. Same as \`-agjMstu'."
printf "$optfmt" "-j" "Output JSON formatted data."
printf "$optfmt" "-k col" "Sort column (default \`$DEFAULT_SORT')."
printf "$optfmt" "-L time" \
"lsof(8) timeout duration. Default is no timeout."
printf "$optfmt" "-M" \
"Show metadata statistics (requires \`-j'). Implies \`-a'."
printf "$optfmt" "-m" "Only show metadata statistics. Implies \`-a'."
printf "$optfmt" "-N num" "Perform num samples and exit."
printf "$optfmt" "-n" "Do not attempt to map uid/gid to names."
printf "$optfmt" "-o" "Force non-console output."
printf "$optfmt" "-P pid" "Process ID filter."
printf "$optfmt" "-p" "View read/write activity by PID (default)."
printf "$optfmt" "-q" "Quiet. Hide informational messages."
printf "$optfmt" "-R" "Redact potentially sensitive information."
printf "$optfmt" "-r" "Raw view. Do not format output of bpftrace."
printf "$optfmt" "-S job" "Filter on SGE job id (regex)."
printf "$optfmt" "-s" "View read/write activity by SGE job."
printf "$optfmt" "-T type" "Filter on filesystem type."
printf "$optfmt" "-t" "View read/write activity by VFS type."
printf "$optfmt" "-U user" "User filter (name or id)."
printf "$optfmt" "-u" "View read/write activity by user."
printf "$optfmt" "-v" "Print version and exit."
printf "$optfmt" "-w" "Wide view. Maximize width of first column."
die
}
run_lsof()
{
[ "$DEBUG" ] && return
case "$FILTER_TYPE" in
""|nfs*) ${TIMEOUT_LSOF:+timeout "$TIMEOUT_LSOF"} lsof -X -N +c 0 ;;
esac
case "$FILTER_TYPE" in
nfs*) : skip ;;
*) ${TIMEOUT_LSOF:+timeout "$TIMEOUT_LSOF"} lsof -X +c 0 +e /
esac
}
run_bpftrace()
{
if [ "$DEBUG" ]; then
cat
return
fi
bpftrace -B none /dev/stdin "$@"
}
count()
{
local OPTIND=1 OPTARG __flag
local __delim="$IFS"
local __var_to_set=
while getopts d:s: __flag; do
case "$__flag" in
d) __delim="$OPTARG" ;;
s) __var_to_set="$OPTARG" ;;
esac
done
shift $(( $OPTIND - 1 ))
local IFS="$__delim"
set -- $*
if [ "$__var_to_set" ]; then
eval $__var_to_set=$#
else
echo $#
fi
}
getword()
{
local funcname=getword
local OPTIND=1 OPTARG __flag
local __delim="$IFS"
local __var_to_set=
local __word=
while getopts d:s:w: __flag; do
case "$__flag" in
d) __delim="$OPTARG" ;;
s) __var_to_set="$OPTARG" ;;
w) __word="$OPTARG" ;;
esac
done
shift $(( $OPTIND - 1 ))
case "$__word" in
""|*[!0-9]*) die "$funcname: \`-w' requires a number" ;;
esac
local IFS="$__delim"
set -- $*
if [ "$__var_to_set" ]; then
eval $__var_to_set=\"\$\{$__word\}\"
else
eval echo \"\$\{$__word\}\"
fi
}
num2bytes()
{
local __num="$1" __size="${2%B}" __var_to_set="$3"
local __out=
while [ $__size -gt 0 ]; do
__out="$__out $(( $__num % 256 ))"
__num=$(( $__num >> 8 ))
__size=$(( $__size - 1 ))
done
__out="${__out# }"
if [ "$__var_to_set" ]; then
eval $__var_to_set=\"\$__out\"
else
echo "$__out"
fi
}
bpf_prog_id()
{
local __pid="$1" __prog="$2" __var_to_set="$3"
local __ls __out __res
[ "$__pid" -a "$__prog" ] || return ${FAILURE:-1}
__ls=$( ls -l /proc/$__pid/fd 2> /dev/null ) || return
__out=$( echo "$__ls" | awk -v pid=$__pid -v prog="$__prog" '
$NF == "anon_inode:bpf-prog" {
fd = $(NF-2)
fdinfo = sprintf("/proc/%d/fdinfo/%d", pid, fd)
id = ""
while (getline < fdinfo > 0) {
if ($1 != "prog_id:") continue
id = $2
break
}
close(fdinfo)
if (id == "") next
cmd = sprintf("bpftool prog show id %d", id)
if (cmd | getline <= 0 || $4 != prog) {
close(cmd)
next
}
print id
exit found = 1
}
END { exit found ? 0 : 3 }
' )
__res=$?
if [ "$__var_to_set" ]; then
eval $__var_to_set=\"\$__out\"
else
echo "$__out"
fi
return $__res
}
bpf_map_ids()
{
local __prog="$1" __var_to_set="$2"
local __out __res
[ "$__prog" ] || return ${FAILURE:-1}
__out=$( bpftool prog show id $__prog ) || return
__out=$( echo "$__out" | awk '
$(NF-1) == "map_ids" {
print $NF
found = 1
exit
}
END { exit found ? 0 : 3 }
' )
__res=$?
if [ "$__var_to_set" ]; then
eval $__var_to_set=\"\$__out\"
else
echo "$__out"
fi
return $__res
}
#
# ST: CALLS
#
send_user()
{
local type="$1"
shift 1 # type
printf "%s|%s\n" "$type" "$*"
}
info() { send_user info "$*"; }
info_n() { send_user info-n "$*"; }
msg() { send_user msg "$*"; }
warn() { send_user warn "$*"; }
resize()
{
local size
if [ -e /dev/tty ]; then
size=$( { stty size < /dev/tty; } 2> /dev/null )
else
size=$( stty size 2> /dev/null )
fi
send_user resize "${size:-24 80}"
}
############################################################ MAIN
#
# Process command-line options
#
while getopts AabCcDdfG:ghIi:Jjk:L:MmN:noP:pqRrS:sT:tU:uvw flag; do
case "$flag" in
A) VIEW_AGGREGATES=1 SHOW_AGGREGATES=1 ;;
a) SHOW_AGGREGATES=1 ;;
b) SHOW_BASIC=1 ;;
C) COLOR=1 ;;
c) VIEW=COMM VIEW_COMM=1 ;;
D) DEBUGGER=1 RAW_VIEW=1 ;;
d) DEBUG=1 RAW_VIEW=1 ;;
f) FILTER_FOLLOW=1 ;;
G) FILTER_GROUP="$OPTARG" ;;
g) VIEW=GROUP VIEW_GROUP=1 ;;
I) IGNORE_RUNNING=1 ;;
i) INTERVAL="$OPTARG" ;;
J) VIEW=JSON OUTPUT_JSON=1 SHOW_AGGREGATES=1 MODE=both \
VIEW_GROUP=1 VIEW_SGE=1 VIEW_TYPE=1 VIEW_USER=1 ;;
j) OUTPUT_JSON=1 ;;
k) SORT="$OPTARG" ;;
L) TIMEOUT_LSOF="$OPTARG" ;;
M) MODE=both SHOW_AGGREGATES=1 ;;
m) MODE=meta SHOW_AGGREGATES=1 ;;
N) [ "$OPTARG" ] || usage "-N option requires an argument" # NOTREACHED
NSAMPLES="$OPTARG" ;;
n) NO_NAMES=1 ;;
o) CONS= COLOR= ;;
P) FILTER_PID="$OPTARG" ;;
p) VIEW=PID VIEW_PID=1 ;;
q) QUIET=1 ;;
R) REDACT=1 ;;
r) RAW_VIEW=1 ;;
S) FILTER_SGE="$OPTARG" ;;
s) VIEW=SGE VIEW_SGE=1 ;;
T) FILTER_TYPE="$OPTARG" ;;
t) VIEW=TYPE VIEW_TYPE=1 ;;
U) FILTER_USER="$OPTARG" ;;
u) VIEW=USER VIEW_USER=1 ;;
v) VERSION="${VERSION#*: }"
echo "${VERSION% $}"
exit $SUCCESS ;;
w) WIDE_VIEW=1 ;;
*) usage # NOTREACHED
esac
done
shift $(( $OPTIND - 1 ))
#
# Process command-line arguments
#
[ $# -le 1 ] || usage "Too many arguments" # NOTREACHED
FILTER_COMM="$1"
#
# Prevent non-functional option combinations
#
if [ "$SHOW_BASIC" ]; then
[ "$VIEW" != "JSON" ] || die "-b cannot be combined with -J"
[ ! "$OUTPUT_JSON" ] || die "-b cannot be combined with -j"
fi
case "$MODE" in
both) [ "$OUTPUT_JSON" ] || die "-M requires -j or -J" ;;
esac
case "$VIEW" in
PID) [ "$OUTPUT_JSON" ] || die "-p requires either -j or -J" ;;
esac
#
# Silently ignore previous view options unless JSON output
#
[ "$VIEW" ] || VIEW=PID VIEW_PID=1
if [ ! "$OUTPUT_JSON" ]; then
case "$VIEW" in # ST: VIEWS
COMM) VIEW_GROUP= VIEW_PID= VIEW_SGE= VIEW_TYPE= VIEW_USER= ;;
GROUP) VIEW_COMM= VIEW_PID= VIEW_SGE= VIEW_TYPE= VIEW_USER= ;;
PID) VIEW_COMM= VIEW_GROUP= VIEW_SGE= VIEW_TYPE= VIEW_USER= ;;
SGE) VIEW_COMM= VIEW_GROUP= VIEW_PID= VIEW_TYPE= VIEW_USER= ;;
TYPE) VIEW_COMM= VIEW_GROUP= VIEW_PID= VIEW_SGE= VIEW_USER= ;;
USER) VIEW_COMM= VIEW_GROUP= VIEW_PID= VIEW_SGE= VIEW_TYPE= ;;
esac
fi
#
# Process `-f' option
#
if [ "$FILTER_FOLLOW" ]; then
[ "$FILTER_COMM$FILTER_GROUP$FILTER_PID$FILTER_SGE$FILTER_USER" ] ||
die "-f requires at least one -G, -P, -S, -U, or comm argument"
fi
#
# Validate `-i sec' option
#
case "$INTERVAL" in
"") usage "missing -i argument" ;; # NOTREACHED
0) die "-i sec must be non-zero" ;;
*[!0-9.]*|*.*.*|.) die "-i sec must be a number" ;;
*.*)
INTERVAL_SECONDS=$INTERVAL
ms=$( echo "$INTERVAL * 1000" | bc )
ms="${ms%%.*}"
#
# If, after multiplying by 1000 to convert sec to msec,
# the leading [non-decimal] digit is either missing or zero,
# the input was too small to produce timing of at least 1 msec
#
case "$ms" in
""|0) die "-i sec must be at least 0.001" ;;
esac
INTERVAL_PROBE=interval:ms:$ms
;;
*)
INTERVAL_SECONDS=$INTERVAL
INTERVAL_PROBE=interval:s:$INTERVAL_SECONDS
esac
#
# Validate `-k col' option
# ST: SORTING
#
if [ "$MODE" = data ]; then
case "$SORT" in
"") usage "missing -k argument" ;; # NOTREACHED
[Tt][Oo][Tt][Aa][Ll]) SORT=total ;; # TOTAL
[Rr][Ee][Aa][Dd]|[Ii][Nn]) SORT=read ;; # READ(IN)
[Ww][Rr][Ii][Tt][Ee]|[Oo][Uu][Tt]) SORT=write ;; # WRITE(OUT)
*) die "-k col must be one of: total read write in out"
esac
elif [ "$MODE" = meta ]; then
case "$SORT" in
"") usage "missing -k argument" ;; # NOTREACHED
[Tt][Oo][Tt][Aa][Ll]) SORT=total ;; # TOTAL
[Gg][Oo][Oo][Dd]) SORT=good ;; # STAT(GOOD)
[Ff][Aa][Ii][Ll]) SORT=fail ;; # STAT(FAIL)
*) die "-k col must be one of: total good fail"
esac
elif [ "$MODE" = both ]; then
case "$SORT" in
"") usage "missing -k argument" ;; # NOTREACHED
[Tt][Oo][Tt][Aa][Ll]) SORT=total ;; # TOTAL
[Rr][Ee][Aa][Dd]|[Ii][Nn]) SORT=read ;; # READ(IN)
[Ww][Rr][Ii][Tt][Ee]|[Oo][Uu][Tt]) SORT=write ;; # WRITE(OUT)
[Gg][Oo][Oo][Dd]) SORT=good ;; # STAT(GOOD)
[Ff][Aa][Ii][Ll]) SORT=fail ;; # STAT(FAIL)
*) die "-k col must be one of: total read write in out good fail"
esac
fi
#
# Validate `-L sec' option
#
case "$TIMEOUT_LSOF" in
"") : ok ;;
*[smhd])
case "${TIMEOUT_LSOF%?}" in
""|*[!0-9.]*|*.*.*|.) die "bad -L argument" ;;
esac
;;
*[!0-9.]*|*.*.*|.) die "bad -L argument" ;;
esac
#
# Process `-m' and `-M' options
#
case "$MODE" in
both) MODE_DATA=1 MODE_META=1 ;;
data) MODE_DATA=1 MODE_META= ;;
meta) MODE_META=1 MODE_DATA= ;;
esac
#
# Validate `-N num' option
#
case "$NSAMPLES" in
0) die "-N num must be non-zero" ;;
*[!0-9]*) die "-N num must be a positive integer" ;;
esac
#
# Process `-G group'/`-U user' option
#
case "$FILTER_GROUP" in
"") : leave-empty ;;
*[!0-9]*) # Translate from name to GID
FILTER_GID=$( getent group "$FILTER_GROUP" ) ||
die "Unknown group \`%s'" "$FILTER_GROUP"
FILTER_GID=$( echo "$FILTER_GID" | awk -F: '{print $3}' )
;;
*) # Translate from GID to name
FILTER_GID=$FILTER_GROUP
FILTER_GROUP=$( getent group $FILTER_GID ) ||
die "Unknown group id %d" "$FILTER_GID"
FILTER_GROUP=$( echo "$FILTER_GROUP" | awk -F: '{print $1}' )
esac
case "$FILTER_USER" in
"") : leave-empty ;;
*[!0-9]*) # Translate from name to UID
FILTER_UID=$( getent passwd "$FILTER_USER" ) ||
die "Unknown user \`%s'" "$FILTER_USER"
FILTER_UID=$( echo "$FILTER_UID" | awk -F: '{print $3}' )
;;
*) # Translate from UID to name
FILTER_UID=$FILTER_USER
FILTER_USER=$( getent passwd $FILTER_UID ) ||
die "Unknown user id %d" "$FILTER_UID"
FILTER_USER=$( echo "$FILTER_USER" | awk -F: '{print $1}' )
esac
#
# Validate `-P pid' option
#
case "$FILTER_PID" in
"") : leave-empty ;;
0) die "-P pid must be non-zero" ;;
*[!0-9]*) die "-P pid must be a positive integer" ;;
esac
#
# Get terminal size
#
size=$( resize )
size="${size#*|}"
if [ "$size" ]; then
cols="${size#*[$IFS]}"
rows="${size%%[$IFS]*}"
fi
case "$rows$cols" in
""|*[!0-9]*)
cols=80
rows=24
;;
esac
#
# Fixup PATH
#
case "$PATH" in
/usr/sbin:*|*:/usr/sbin:*|*:/usr/sbin) : ok ;;
*) PATH="${PATH:+$PATH:}/usr/sbin"
esac
#
# Run script
# ST: PRE
#
{
exec 3<&1
trap resize WINCH # ST: SIGWINCH
#
# Find SGE processes and their children
#
if [ ! "$IGNORE_RUNNING$FILTER_PID$DEBUG" ]; then
info_n "Gathering SGE job info... "
SGE_JOBS=$( pgrep sge_shepherd | xargs -r -n1 pgrep \
${FILTER_GROUP:+-G "$FILTER_GROUP"} \
${FILTER_USER:+-U "$FILTER_USER"} -P 2> /dev/null |
xargs -r -n1 pstree -p 2> /dev/null | awk \
-v debug=${DEBUG:-0} \
-v filter_sge="$FILTER_SGE" \
-v sq="'" \
-v stderr=/dev/stderr \
'####################################### BEGIN
BEGIN {
job_pid = job_name = ""
nactive = njobs = job_found = 0
delete jobs_seen
want_sge = ""
if (filter_sge ~ /^[0-9]+$/) {
want_sge = "id"
} else if (filter_sge != "") {
want_sge = "regex"
gsub(/\\/, "&&", filter_sge)
}
}
######################################## FUNCTIONS
function emit(str)
{
if (debug) return
printf "%s\n", str
fflush()
}
function send_user(type, str)
{
emit(sprintf("%s|%s", type, str))
}
function info(str) { send_user("info", str) }
function info_n(str) { send_user("info-n", str) }
function msg(str) { send_user("msg", str) }
function warn(str) { send_user("warn", str) }
function getstatus(pid, file, L)
{
comm = pcomm = ""
uid = gid = puid = pgid = ppid = 0
file = sprintf("/proc/%d/status", pid)
while (getline L < file > 0) {
if (sub(/^PPid:[[:space:]]*/, "", L)) {
ppid = L
} else if (sub(/^Name:[[:space:]]*/, "", L)) {
comm = L
} else if (sub(/^Uid:[[:space:]]*/, "", L)) {
sub(/[[:space:]].*/, "", L)
uid = L
} else if (sub(/^Gid:[[:space:]]*/, "", L)) {
sub(/[[:space:]].*/, "", L)
gid = L
}
}
close(file)
if (ppid == 0) return 0
file = sprintf("/proc/%d/status", ppid)
while (getline L < file > 0) {
if (sub(/^Name:[[:space:]]*/, "", L)) {
pcomm = L
} else if (sub(/^Uid:[[:space:]]*/, "", L)) {
sub(/[[:space:]].*/, "", L)
puid = L
} else if (sub(/^Gid:[[:space:]]*/, "", L)) {
sub(/[[:space:]].*/, "", L)
pgid = L
}
}
close(file)
return 1
}
function checkjob(pid, file, L, nv, env, n, ev, found)
{
found = 0
job_id = 0
jop_name = ""
file = sprintf("/proc/%d/environ", pid)
while (getline L < file > 0) {
nv = split(L, env, /\0/)
for (n = 1; n <= nv; n++) {
ev = env[n]
if (sub(/^JOB_ID=/, "", ev)) {
job_id = ev
} else if (sub(/^JOB_NAME=/, "", ev)) {
job_name = ev
}
if (job_id > 0 && job_name != "") {
found = 1
break
}
}
if (found) break
}
close(file)
return job_id != ""
}
######################################## MAIN
match($0, /^[^[:space:](]+\([0-9]+\)/) {
njobs++
job_pid = $0
sub(/^[^(]*\(/, "", job_pid)
sub(/\).*/, "", job_pid)
if (!checkjob(job_pid)) next
if (want_sge == "id") {
if (job_id != filter_sge) next
job_found = 1
} else if (want_sge == "regex") {
if (job_id !~ filter_sge &&
job_name !~ filter_sge) next
job_found = 1
}
}
job_pid != "" {
gsub(/[^0-9]/, " ")
gsub(/[[:space:]]+/, " ")
gsub(/(^[[:space:]]+|[[:space:]]+$)/, "")
npids = split($0, pids, /[[:space:]]+/)
for (n = 1; n <= npids; n++) {
if (!getstatus(pids[n])) continue
nactive++
#
# Print to stdout
# NB: default = awk, raw [-r] = stdout
#
if (pids[n] == job_pid) {
emit(sprintf("fork_job|%d", job_pid))
}
# To bpftool map update
printf "%d=%d\n", pids[n], job_pid > stderr
}
if (job_found) exit
}
######################################## END
END {
msg(sprintf("%d %s found", njobs,
njobs == 1 ? "job" : "jobs"))
if (want_sge != "" && !job_found) {
if (want_sge == "regex") {
fmt = "No SGE jobs matching `%s" sq
} else if (want_sge == "id") {
fmt = "SGE job %d not found"
}
warn(sprintf(fmt, filter_sge))
}
}
' 2>&1 >&3 ) || die "%s" "$SGE_JOBS"
fi
#
# Find matching processes and their children
#
if [ "$FILTER_FOLLOW" -a ! "$IGNORE_RUNNING$DEBUG" ]; then
info "Gathering active process info..."
if [ "$FILTER_PID" ]; then
FOLLOW_PIDS=$( pstree -p $FILTER_PID | awk \
-v filter_group="$FILTER_GROUP" \
-v filter_user="$FILTER_USER" '
BEGIN { delete seen }
function del(re){gsub(re,"")}
function space(re){gsub(re," ")}
function check_group(pid, file, gid, L) {
if (filter_group == "") return 1 # STAT(GOOD)
gid = ""
file = sprintf("/proc/%d/status", pid)
while (getline L < file > 0) {
if (L !~ /^Gid:/) next
sub(/^Gid:[[:space:]]*/, "", L)
sub(/[^0-9].*/, "", L)
gid = L
break
}
close(file)
return gid == filter_group
}
function check_user(pid, file, uid, L) {
if (filter_user == "") return 1 # STAT(GOOD)
uid = ""
file = sprintf("/proc/%d/status", pid)
while (getline L < file > 0) {
if (L !~ /^Uid:/) next
sub(/^Uid:[[:space:]]*/, "", L)
sub(/[^0-9].*/, "", L)
uid = L
break
}
close(file)
return uid == filter_user
}
match($0, /^[^[:space:](]+\([0-9]+\)/) {
pid = substr($0, 1, RLENGTH - 1)
$0 = substr($0, RLENGTH + 1)
sub(/.*\(/, "", pid)
if (!(pid in seen)) pids = pids " " pid
}
{
space("[^0-9]")
space("[[:space:]]+")
del("(^[[:space:]]+|[[:space:]]+$)")
npids = split($0, list)
for (n = 1; n <= npids; n++) {
if ((pid = list[n]) in seen) continue
# group filter
if (!check_group(pid)) continue
# user filter
if (!check_user(pid)) continue
pids = pids " " pid
seen[pid]
}
}
END { print substr(pids, 2) }
' )
elif [ "$FILTER_COMM$FILTER_USER$FILTER_GROUP" ]; then
FOLLOW_PIDS=$( pgrep ${FILTER_COMM:+"$FILTER_COMM"} \
${FILTER_USER:+-U "$FILTER_USER"} \
${FILTER_GROUP:+-G "$FILTER_GROUP"} |
awk '
BEGIN { delete seen }
function del(re){gsub(re,"")}
function space(re){gsub(re," ")}
match($0, /^[^[:space:](]+\([0-9]+\)/) {
pid = substr($0, 1, RLENGTH - 1)
$0 = substr($0, RLENGTH + 1)
sub(/.*\(/, "", pid)
if (!(pid in seen)) pids = pids " " pid
}
{
space("[^0-9]")
space("[[:space:]]+")
del("(^[[:space:]]+|[[:space:]]+$)")
npids = split($0, list)
for (n = 1; n <= npids; n++) {
if ((pid = list[n]) in seen) continue
pids = pids " " pid
seen[pid]
}
}
END { print substr(pids, 2) }
' )
fi
fi
#
# Find open *file* descriptors
#
if [ ! "$IGNORE_RUNNING$DEBUG" ]; then
info "Gathering open file-descriptor info" \
"(this may take a while)..."
OPEN_FDS=$( run_lsof | awk \
-v debug=${DEBUG:-0} \
-v filter_comm="$FILTER_COMM" \
-v filter_follow=${FILTER_FOLLOW:-0} \
-v filter_gid="$FILTER_GID" \
-v filter_sge="$FILTER_SGE" \
-v filter_pid="$FILTER_PID" \
-v filter_type="$FILTER_TYPE" \
-v filter_user="$FILTER_USER" \
-v follow_pids="$FOLLOW_PIDS" \
-v sge_jobs="$SGE_JOBS" \
-v stderr=/dev/stderr \
'####################################### BEGIN
BEGIN {
delete follow
nfollow = split(follow_pids, list)
for (n = 1; n <= nfollow; n++) {
follow[list[n]]
}
delete mounts
delete mount_type
file = "/proc/mounts"
nmounts = 0
root_mount = ""
root_mount_type = ""
flen = length(filter_type)
while (getline < file > 0) {
if (filter_type != "" &&
substr($3, 1, flen) != filter_type)
continue
if ($2 == "/") {
root_mount = $2
root_mount_type = $3
} else {
mounts[++nmounts] = $2
sub("/+$", "", mounts[nmounts])
mount_type[nmounts] = $3
}
}
close(file)
if (root_mount != "") {
mounts[++nmounts] = root_mount
mount_type[nmounts] = root_mount_type
}
delete job_pids
njobs = split(sge_jobs, list)
for (n = 1; n <= njobs; n++) {
pid = job_pid = list[n]
sub(/=.*/, "", pid)
sub(/.*=/, "", job_pid)
job_pids[pid] = job_pid
}
delete seen
}
######################################## FUNCTIONS
function key(a, b) { return a "," b }
function emit(str)
{
if (debug) return
printf "%s\n", str
fflush()
}
function send_user(type, str)
{
emit(sprintf("%s|%s", type, str))
}
function info(str) { send_user("info", str) }
function info_n(str) { send_user("info-n", str) }