-
Notifications
You must be signed in to change notification settings - Fork 0
/
collectl.pl
executable file
·6702 lines (5866 loc) · 243 KB
/
collectl.pl
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
#!/usr/bin/perl -w
# Copyright 2003-2013Hewlett-Packard Development Company, L.P.
#
# collectl may be copied only under the terms of either the Artistic License
# or the GNU General Public License, which may be found in the source kit
# debug
# 1 - print interesting stuff
# 2 - print Interconnect specific checks (mostly Infiniband)
# 4 - show each line processed by record(), replaces -H
# 8 - print lustre specific checks
# 16 - print headers of each file processed
# 32 - skip call to dataAnalyze during interactive processing
# 64 - socket processing
# 128 - show collectl.conf processing
# 256 - show detailed pid processing (this generates a LOT of output)
# 512 - show more pid details, specifically hash contents
# NOTE - output from 256/512 are prefaced with %%% if from collectl.pl
# and ### if from formatit.ph
# 1024 - show list of SLABS to be monitored
# 2048 - playback preprocessing
# 4096 - report pidNew() management of pidSkip{}
# 8192 - show creation of RAW, PLOT and files
# debug tricks
# - use '-d36' to see each line of raw data as it would be logged but not
# generate any other output
# Equivalent Utilities
# -s c mpstat, iostat -c, vmstat
# -s C mpstat
# -s d/D iostat -d
# -s f/F nfsstat -c/s [c if -o C]
# -s i sar -v
# -s m sar -rB, free, vmstat (note - sar does pages by pagesizsie NOT bytes)
# -s n/N netstat -i
# -s s sar -n SOCK
# -s y/Y slabtop
# -s Z ps or top
# Subsystems
# b - buddy
# c - cpu
# d - disks
# E - environmental
# i - inodes (and other file stuff)
# f - NFS
# l - lustre
# m - memory
# n - network
# s - socket
# t - tcp
# x - interconnect
# Z - processes (-sP now available but -P taken!)
use POSIX;
use Config;
use English;
use 5.008000;
use Getopt::Long;
Getopt::Long::Configure ("bundling");
Getopt::Long::Configure ("no_ignore_case");
Getopt::Long::Configure ("pass_through");
use File::Basename;
use Time::Local;
use IO::Socket;
use IO::Select;
$Cat= '/bin/cat';
$Grep= '/bin/grep';
$Egrep= '/bin/egrep';
$Ps= '/bin/ps';
$Rpm= '/bin/rpm';
$Lspci= '/sbin/lspci';
$Lctl= '/usr/sbin/lctl';
$Dmidecode= '/usr/sbin/dmidecode';
$ReqDir= '/usr/share/collectl'; # may not exist
%TopProcTypes=qw(vsz '' rss '' syst '' usrt '' time '' accum '' rkb '' wkb '' iokb ''
rkbc '' wkbc '' iokbc '' ioall '' rsys '' wsys '' iosys ''
iocncl '' majf '' minf '' flt '' pid '' cpu '' thread '' vctx '' nctx '');
%TopSlabTypes=qw(numobj '' name '' actobj '' objsize '' numslab '' objslab '' totsize '' totchg '' totpct '');
# Constants and removing -w warnings
$miniDateFlag=0;
$PageSize=0;
$Memory=$Swap=$Hyper=$Distro=$ProductName='';
$CpuVendor=$CpuMHz=$CpuCores=$CpuSiblings=$CpuNodes='';
$PidFile='/var/run/collectl.pid'; # default, unless --pname
$PQuery=$PCounter=$VStat=$VoltaireStats=$IBVersion=$HCALids=$OfedInfo='';
$numBrwBuckets=$cfsVersion=$sfsVersion='';
$Resize=$IpmiCache=$IpmiTypes=$ipmiExec='';
$i1DataFlag=$i2DataFlag=$i3DataFlag=0;
$lastSecs=$interval2Print=0;
$diskRemapFlag=$diskChangeFlag=$cpuDisabledFlag=$cpusDisabled=$cpusEnabled=$noCpusFlag=0;
$boottime=0;
# only used once here, but set in formatit.ph
our %netSpeeds;
# Find out ASAP if we're linux or WNT based as well as whether or not XC based
$PcFlag=($Config{"osname"}=~/MSWin32/) ? 1 : 0;
$XCFlag=(!$PcFlag && -e '/etc/hptc-release') ? 1 : 0;
# If we ever want to write something to /var/log/messages, we need this which
# we obviously can't include on a pc.
require "Sys/Syslog.pm" if !$PcFlag;
# Always nice to know if we're root
$rootFlag=(!$PcFlag && `whoami`=~/root/) ? 1 : 0;
$SrcArch= $Config{"archname"};
$Version= '3.6.9-1';
$Copyright='Copyright 2003-2013 Hewlett-Packard Development Company, L.P.';
$License= "collectl may be copied only under the terms of either the Artistic License\n";
$License.= "or the GNU General Public License, which may be found in the source kit";
# get the path to the exe from the program location, noting different handling
# of path resolution for XC and non-XC, noting if a link and not XC, we
# need to follow it, possibly multiple times! Furthermore, if the link is
# a relative one, we need to prepend with the original program location or
# $BinDir will be wrong.
if (!$XCFlag)
{
$link=$0;
$ExeName='';
until($link eq $ExeName)
{
$ExeName=$link; # possible exename
$link=(!defined(readlink($link))) ? $link : readlink($link);
}
}
else
{
$ExeName=(!defined(readlink($0))) ? $0 : readlink($0);
$ExeName=dirname($0).'/'.$ExeName if $ExeName=~/^\.\.\//;
}
$BinDir=dirname($ExeName);
$Program=basename($ExeName);
$Program=~s/\.pl$//; # remove extension for production
# Note that if someone redirects stdin or runs it out of a script it will look like
# we're in the background. We also need to know if STDOUT connected to a terminal.
if (!$PcFlag)
{
$MyDir=`pwd`;
$Cat= 'cat';
$Sep= '/';
$backFlag=(getpgrp()!=tcgetpgrp(0)) ? 1 : 0;
$termFlag= (-t STDOUT) ? 1 : 0;
}
else
{
$MyDir=`cd`;
$Cat= 'type';
$Sep= '\\';
$backFlag=0;
$termFlag=0;
}
chomp $MyDir;
# This is a little messy. In playback mode of process data, we want to use
# usernames instead of UIDs, so we need to know if we need to know if it's
# the same node and hence we need our name. This could be different than $Host
# which was recorded with the data file and WILL override in playback mode.
# We also need our host name before calling initRecord() so we can log it at
# startup as well as for naming the logfile.
$myHost=($PcFlag) ? `hostname` : `/bin/hostname`;
$myHost=(split(/\./, $myHost))[0];
chomp $myHost;
$Host=$myHost;
# may be overkill, but we want to throttle max errors/day to prevent runaway.
$zlibErrors=0;
# These variables only used once in this module and hence generate warnings
undef @dskOrder;
undef @netOrder;
undef @lustreCltDirs;
undef @lustreCltOstDirs;
undef @lustreOstSubdirs;
undef %playbackSettings;
$recHdr1=$recHeader=$miniDateTime=$miniFiller=$DaemonOptions='';
$OstNames=$MdsNames=$LusDiskNames=$LusDiskDir='';
$NumLustreCltOsts=$NumLusDisks=$MdsFlag=0;
$NumSlabs=$SlabGetProc=$newSlabFlag=0;
$wideFlag=$coreFlag=$newRawSlabFlag=0;
$totalCounter=$separatorCounter=0;
$NumCpus=$HZ='';
$NumOst=$NumBud=0;
$FS=$ScsiInfo=$HCAPortStates='';
$SlabVersion=$XType=$XVersion='';
$dentryFlag=$inodeFlag=$filenrFlag=$allThreadFlag=$procCmdWidth=0;
$clr=$clscr=$cleol=$home='';
$dskIndexNext=$netIndexNext=0;
# This tells us we have not yet made our first pass through the data
# collection loop and gets reset to 0 at the bottom.
$firstPass=1;
# Check the switches to make sure none requiring -- were specified with -
# since getopts doesn't! Also save the list of switches we were called with.
$cmdSwitches=preprocSwitches();
# These are the defaults for interactive and daemon subsystems
$SubsysDefInt='cdn';
$SubsysDefDaemon='bcdfijlmnstx';
# We want to load any default settings so that user can selectively
# override them. We're giving these starting values in case not
# enabled in .conf file. We later override subsys if interactive
$SubsysDef=$SubsysCore=$SubsysDefDaemon;
$Interval= 10;
$Interval2= 60;
$Interval3= 120;
$LimSVC= 30;
$LimIOS= 10 ;
$LimLusKBS= 100;
$LimLusReints=1000;
$LimBool= 0;
$Port= 2655;
$Timeout= 10;
$MaxZlibErrors=20;
$LustreSvcLunMax=10;
$LustreMaxBlkSize=512;
$LustreConfigInt=1;
$InterConnectInt=900;
$TermHeight=24;
$DefNetSpeed=10000;
$IbDupCheckFlag=1;
$TimeHiResCheck=1;
$PasswdFile='/etc/passwd';
$umask='';
$DiskMaxValue=-1; # disabled
# NOTE - the following line should match what is in collectl.conf. If uncommented there, it will be replaced
$DiskFilter='cciss/c\d+d\d+ |hd[ab] | sd[a-z]+ |dm-\d+ |xvd[a-z] |fio[a-z]+ | vd[a-z]+ |emcpower[a-z]+ |psv\d+ ';
$DiskFilterFlag=0; # only set when filter set in collectl.conf
$ProcReadTest='yes';
# Standard locations
$SysIB='/sys/class/infiniband';
# These aren't user settable but are needed to build the list of ALL valid
# subsystems
$SubsysDet= "BCDEFJLMNTXYZ";
$SubsysExcore='y';
# These are the subsystems allowed in brief mode
$BriefSubsys="bcdfijlmnstx";
# And the default environmentals
$envOpts='fpt';
$envRules='';
$envDebug=0;
$envTestFile='';
$envFilt=$envRemap='';
$hiResFlag=0; # must be initialized before ANY calls to error/logmsg
$configFile='';
$ConfigFile='collectl.conf';
$daemonFlag=$debug=$formatitLoaded=0;
GetOptions('C=s' => \$configFile,
'D!' => \$daemonFlag,
'd=i' => \$debug,
'config=s' => \$configFile,
'daemon!' => \$daemonFlag,
'debug=i' => \$debug
) or error("type -h for help");
# if config file specified and a directory, prepend to default name otherwise
# use the whole thing as the name.
$filename='';
$configFile.="/$ConfigFile" if $configFile ne '' && -d $configFile;;
loadConfig();
# Very unlikely but I hate programs that silently exit. We have to figure out
# where formatit.ph lives, out first choice always being '$BinDir'.
$BinDir=dirname($ExeName);
if (!-e "$BinDir/formatit.ph" && !-e "$ReqDir/formatit.ph")
{
# Let's not get too carried away for something that probably won't ever happen on a PC,
# but there's no point displaying $ReqDir since it in unix format and will never exist!
my $msg=sprintf("can't find 'formatit.ph' in '$BinDir'%s. Corrupted installation!", !$PcFlag ? " OR '$ReqDir'" : '');
print "$msg\n"; # can't call logmsg() before formatit.ph not yet loaded
logsys($msg,1); # force it because $filename not yet set
exit(1);
}
# Now that we've loaded collectl.conf and have possibly reset '$ReqDir', it's time to
# load it, changing $ReqDir to $BinDir if we find it there.
$ReqDir=$BinDir if -e "$BinDir/formatit.ph";
print "BinDir: $BinDir ReqDir: $ReqDir\n" if $debug & 1;
# Load include files and optional PMs if there
require "$ReqDir/formatit.ph";
$zlibFlag= (eval {require "Compress/Zlib.pm" or die}) ? 1 : 0;
$hiResFlag= (eval {require "Time/HiRes.pm" or die}) ? 1 : 0;
$diskRemapFlag=(eval {require "$ReqDir/diskremap.ph" or die}) ? 1 : 0;
$formatitLoaded=1;
# These can get overridden after loadConfig(). Others can as well but this is
# a good place to reset those that don't need any further manipulation
$limSVC=$LimSVC;
$limIOS=$LimIOS;
$limBool=$LimBool;
$limLusKBS=$LimLusKBS;
$limLusReints=$LimLusReints;
$termHeight=$TermHeight;
# On LINUX and only if associated with a terminal in the foreground and we can find 'resize',
# use the value of LINES to set the terminal height
if (!$PcFlag && !$daemonFlag && !$backFlag && $Resize ne '' && $termFlag && defined($ENV{TERM}) && $ENV{TERM}=~/xterm/)
{
# IF the user typed a CR after collectl started but before it started, flush input buffer
my $selTemp=new IO::Select(STDIN);
while ($selTemp->can_read(0))
{ my $temp=<STDIN>; }
$selTemp->remove();
`$Resize`=~/LINES.*?(\d+)/m;
$termHeight=$1;
}
# let's also see if there is a terminal attached. this is currently only
# an issue for 'brief mode', but we may need to know some day for other
# reasons too. but PCs can only run on a terminal...
$termFlag=(open TMP, "</dev/tty") ? 1 : 0;
$termFlag=0 if $daemonFlag;
$termFlag=1 if $PcFlag;
close TMP;
$count=-1;
$numTop=0;
$briefFlag=1;
$showColFlag=$showMergedFlag=$showHeaderFlag=$showSlabAliasesFlag=$showRootSlabsFlag=0;
$verboseFlag=$vmstatFlag=$alignFlag=$whatsnewFlag=0;
$quietFlag=$utcFlag=$statsFlag=0;
$address=$flush=$fileRoot=$statOpts='';
$limits=$lustreSvcs=$runTime=$playback=$playbackFile=$rollLog='';
$groupFlag=$tworawFlag=$msgFlag=$niceFlag=$plotFlag=$nohupFlag=$wideFlag=$rawFlag=$ioSizeFlag=0;
$userOptions=$userInterval=$userSubsys='';
$import=$export=$expName=$expOpts=$topOpts=$topType='';
$impNumMods=0; # also acts as a flag to tell us --import code loaded
$homeFlag=$rawtooFlag=$tworaw=$tworaw=$autoFlush=$allFlag=0;
$procOpts=$procFilt=$procState='';
$slabOpts=$slabFilt='';
$procAnalFlag=$procAnalCounter=$slabAnalFlag=$slabAnalCounter=$lastInt2Secs=0;
$lastLogPrefix=$passwdFile='';
$memOpts=$nfsOpts=$nfsFilt=$lustOpts=$userEnvOpts='';
$grepPattern=$pname='';
$dskFilt=$intFilt=$netFilt=$tcpFilt='';
$cpuOpts=$dskOpts=$netOpts=$xOpts='';
$utimeMask=0;
$comment=$runas='';
$rawDskFilter=$rawDskIgnore=$rawNetFilter=$rawNetIgnore='';
$tcpFiltDefault='ituc';
my ($extract,$extractMode)=('',0);
# Since --top has optionals arguments, we need to see if it was specified without
# one and stick in the defaults noting -1 means to use the window size for size
$topFlag=0;
$plotFlag=0;
for (my $i=0; $i<scalar(@ARGV); $i++)
{
$plotFlag=1 if $ARGV[$i]=~/-P|--plo/; # see if -P specified for setting --hr below
if ($ARGV[$i]=~/--to/)
{
$topFlag=1;
splice(@ARGV, $i+1, 0, 'time,-1') if $i==(scalar(@ARGV)-1) || $ARGV[$i+1]=~/^-/;
last;
}
}
$scrollEnd=0;
$headerRepeat=(!$topFlag) ? $termHeight-2 : 5;
$headerRepeat=0 if $plotFlag;
# now that we've made it through first call fo Getopt, disable pass_through so
# we can catch any errors in parameter names.
Getopt::Long::Configure('no_pass_through');
GetOptions('align!' => \$alignFlag,
'A=s' => \$address,
'address=s' => \$address,
'c=i' => \$count,
'count=i' => \$count,
'f=s' => \$filename,
'filename=s' => \$filename,
'F=i' => \$flush,
'flush=i' => \$flush,
'G!' => \$groupFlag,
'group!' => \$groupFlag,
'tworaw!' => \$tworawFlag,
'home!' => \$homeFlag,
'i=s' => \$userInterval,
'interval=s' => \$userInterval,
'h!' => \$hSwitch,
'help!' => \$hSwitch,
'iosize!' => \$ioSizeFlag,
'l=s' => \$limits,
'limits=s' => \$limits,
'L=s' => \$lustreSvcs,
'lustsvcs=s' => \$lustreSvcs,
'm!' => \$msgFlag,
'messages!' => \$msgFlag,
'o=s' => \$userOptions,
'options=s' => \$userOptions,
'N!' => \$niceFlag,
'nice!' => \$niceFlag,
'nohup!' => \$nohupFlag,
'passwd=s' => \$passwdFile,
'p=s' => \$playback,
'playback=s' => \$playback,
'P!' => \$plotFlag,
'quiet!' => \$quietFlag,
'plot!' => \$plotFlag,
'r=s' => \$rollLog,
'rolllogs=s' => \$rollLog,
'R=s' => \$runTime,
'runtime=s' => \$runTime,
's=s' => \$userSubsys,
'sep=s' => \$SEP,
'stats!' => \$statsFlag,
'statopts=s' => \$statOpts,
'subsys=s' => \$userSubsys,
'top=s' => \$topOpts,
'utc!' => \$utcFlag,
'umask=s' => \$umask,
'utime=i' => \$utimeMask,
'v!' => \$vSwitch,
'version!' => \$vSwitch,
'V!' => \$VSwitch,
'showdefs!' => \$VSwitch,
'w!' => \$wideFlag,
'x!' => \$xSwitch,
'helpextend!'=> \$xSwitch,
'X!' => \$XSwitch,
'helpall!' => \$XSwitch,
'slabfilt=s' => \$slabFilt,
'procfilt=s' => \$procFilt,
'all!' => \$allFlag,
'comment=s' => \$comment,
'cpuopts=s' => \$cpuOpts,
'dskfilt=s' => \$dskFilt,
'dskopts=s' => \$dskOpts,
'export=s' => \$export,
'from=s' => \$from,
'thru=s' => \$thru,
'headerrepeat=i'=> \$headerRepeat,
'hr=i' => \$headerRepeat,
'import=s' => \$import,
'intfilt=s' => \$intFilt,
'lustopts=s' => \$lustOpts,
'memopts=s' => \$memOpts,
'netfilt=s' => \$netFilt,
'netopts=s' => \$netOpts,
'nfsopts=s' => \$nfsOpts,
'nfsfilt=s' => \$nfsFilt,
'envopts=s' => \$userEnvOpts,
'envrules=s' => \$envRules,
'envdebug!' => \$envDebug,
'envtest=s' => \$envTestFile,
'envfilt=s' => \$envFilt,
'envremap=s' => \$envRemap,
'extract=s' => \$extract,
'grep=s' => \$grepPattern,
'offsettime=s' => \$offsetTime,
'pname=s' => \$pname,
'procanalyze!' => \$procAnalFlag,
'procopts=s' => \$procOpts,
'procstate=s' => \$procState,
'rawtoo!' => \$rawtooFlag,
'rawdskfilter=s'=> \$rawDskFilter,
'rawdskignore=s'=> \$rawDskIgnore,
'rawnetfilter=s'=> \$rawNetFilter,
'rawnetignore=s'=> \$rawNetIgnore,
'runas=s' => \$runas,
'showsubsys!' => \$showSubsysFlag,
'showoptions!' => \$showOptionsFlag,
'showsubopts!' => \$showSuboptsFlag,
'showtopopts!' => \$showTopoptsFlag,
'showheader!' => \$showHeaderFlag,
'showcolheaders!' =>\$showColFlag,
'showslabaliases!' =>\$showSlabAliasesFlag,
'showrootslabs!' =>\$showRootSlabsFlag,
'slabanalyze!' => \$slabAnalFlag,
'slabopts=s' => \$slabOpts,
'tcpfilt=s' => \$tcpFilt,
'verbose!' => \$verboseFlag,
'vmstat!' => \$vmstatFlag,
'whatsnew!' => \$whatsnewFlag,
'xopts=s' => \$xOpts,
) or error("type -h for help");
# This needs to be done BEFORE processing --pname since we end up changing $PidFile
if ($runas ne '')
{
error("canot use --runas without -D") if !$daemonFlag;
# temporariluy disable daemon mode in debug mode so we can see messages on terminal.
$daemonFlag=0 if $debug;
my ($runasUser,$runasGroup)=split(/:/, $runas);
error("--runas must at least specify a user") if $runasUser eq '';
if ($runasUser!~/^\d+$/)
{
$runasUid=(split(/:/, `grep $runasUser /etc/passwd`))[2];
error("can't find '$runasUser' in /etc/passwd. Consider UID.") if !defined($runasUid);
}
if (defined($runasGroup) && $runasGroup!~/^\d+$/)
{
$runasGid=(split(/:/, `grep $runasGroup /etc/group`))[2];
error("can't find '$runasGroup' in /etc/group. Consider GID.") if !defined($runasGid);
}
$runasUid=$runasUser if $runasUser=~/^\d+/;
$runasGid=$runasGroup if defined($runasGroup) && $runasGroup=~/^\d+/;
# let's make sure the owner/group of the logging directory match
my $logdir=dirname("$filename/collectl");
($uid,$gid)=(stat($logdir))[4,5];
error("Ownership of '$logdir' doesn't match '$runas'")
if ($uid!=$runasUid) || (defined($runasGid) && $gid!=$runasGid);
# Daemon also means --nohup
$daemonFlag=$nohupFlag=1;
}
if ($pname ne '')
{
# We need to include switches because collectl-generic expects to find them in the process name
$0="collectl-$pname $cmdSwitches";
$PidFile=~s/collectl\.pid/collectl-$pname.pid/;
print "Set PName to collectl-$pname\n" if $debug & 1;
}
# O p e n A S o c k e t ?
# It's real important we do this as soon as possible because if someone runs
# us in 'client' mode, and an error occurs the server would still be hanging
# around waiting for someone to connect to that socket! This way we connect,
# report the error and exit and the caller is able to detect it.
$sockFlag=$clientFlag=$serverFlag=0;
if ($address ne '')
{
if ($address=~/\./)
{
($address,$port,$timeout)=split(/:/, $address);
$port=$Port if !defined($port) || $port eq '';
$Timeout=$timeout if defined($timeout);
$socket=new IO::Socket::INET(
PeerAddr => $address,
PeerPort => $port,
Proto => 'tcp',
Timeout => $Timeout) or
error("Could not create socket to $address:$port. Reason: $!")
if !defined($socket);
print "Socket opened on $address:$port\n" if $debug & 64;
push @sockets, $socket;
$clientFlag=1;
}
elsif ($address=~/^server/i)
{
($port, $port, $options)=split(/:/, $address, 3);
$port=$Port if !defined($port);
# Note this socket uses a different variable because when we get
# a connection we use the SAME one to talk to client as we do in
# client mode.
$sockServer = new IO::Socket::INET(
Type=>SOCK_STREAM,
Reuse=>1, Listen => 1,
LocalPort => $port) ||
error("Could not create local socket on port $port Reason: $!");
print "Server socket opened on port $port\n" if $debug & 64;
$select=new IO::Select($sockServer);
$serverFlag=1;
}
else
{
logmsg('F', 'Invalid -A option');
}
$sockFlag=1;
}
# I'm probably the only one who cares, but in -p --top -s, don't default
# to a --hr of 5, use 20
$headerRepeat=20 if $topFlag && $playback ne '' && $headerRepeat==5;
# If we used to trap these before we opened the socket, but then we couldn't
# send the message back to the called cleanly!
if ($sockFlag)
{
error("-p not allowed with -A") if $playback ne '';
error("-D not allowed with -A address") if $daemonFlag && !$serverFlag;
}
# Since the output could be intended for a socket (called from colgui/colmux),
# we need to do after we open the socket.
error() if $hSwitch;
showVersion() if $vSwitch;
showDefaults() if $VSwitch;
extendHelp() if $xSwitch;
showSubsys() if $showSubsysFlag;
showOptions() if $showOptionsFlag;
showSubopts() if $showSuboptsFlag;
showTopopts() if $showTopoptsFlag;
showSlabAliases($slabFilt) if $showSlabAliasesFlag || $showRootSlabsFlag;
whatsnew() if $whatsnewFlag;
if ($XSwitch)
{
extendHelp(1);
showSubsys(1);
showOptions(1);
showSubopts(1);
showTopopts(1);
printText("$Copyright\n");
printText("$License\n");
exit(0);
}
# in playback mode all we're really doing is verifying the options
setNFSFlags($nfsFilt);
if ($vmstatFlag)
{
error("can't mix --vmstat with --export") if $vmstatFlag && $export ne '';
error("can't mix --vmstat with --all") if $vmstatFlag && $allFlag;
$export='vmstat';
}
error("can't use --export with --verbose") if $verboseFlag && $export ne '';
error("can't use -P with --verbose") if $verboseFlag && $plotFlag;
error("can't use -f with --verbose") if $verboseFlag && $filename ne '';
error("--utime requires HiRes timer") if $utimeMask && !$hiResFlag;
error("--utime requires -f") if $utimeMask && $filename eq '';
error("max value for --utime is 7") if $utimeMask>7;
# --all is shortcut for all summary data
if ($allFlag)
{
error("can't mix -s with -all") if $userSubsys ne '';
$userSubsys="$SubsysCore$SubsysExcore";
$userSubsys=~s/y//;
}
# As part of the conversion to getopt::long, we need to know the actual switch
# values as entered by the user. Those are stored in '$userXXX' and then that
# is treated as one used to handle opt_XXX.
$options= $userOptions;
$interval=($userInterval ne '') ? $userInterval : $Interval;
$subsys= ($userSubsys ne '') ? $userSubsys : $SubsysCore;
error('invalid value for --lustopts') if $lustOpts ne '' && $lustOpts!~/^[BDMOR]+$/;
error('invalid value for --nfsopts') if $nfsOpts ne '' && $nfsOpts ne 'z';
error('invalid value for --memopts') if $memOpts ne '' && $memOpts!~/^[pPsRV]+$/;
error('--memopts R cannot be user with any of [psPV]') if $memOpts=~/R/ && $memOpts=~/[psPV]/;
error("--tcpfilt only applies to -st or -sT") if $tcpFilt ne '' && $subsys!~/t/i;
error("only valid --tcpopts values are 'cituIT'") if $tcpFilt ne '' && $tcpFilt!~/^[cituIT]+$/;
$tcpFilt=$tcpFiltDefault if $tcpFilt eq '' && $playback eq '';
# NOTE - technically we could allow fractional polling intervals without
# HiRes, but then we couldn't properly report the times.
if ($interval=~/\./ && !$hiResFlag)
{
$interval=int($interval+.5);
$interval=1 if $interval==0;
print "need to install HiRes to use fractional intervals, so rounding to $interval\n";
}
# ultimately we only use when doing process data
error("password file '$passwdFile' doesn't exist") if $passwdFile ne '' && !-e $passwdFile;
$passwdFile=$PasswdFile if $passwdFile eq '';
# S u b s y s / I n t e r v a l R e s o l u t i o n
# This needs to get done as soon a possible...
# Set default interval and subsystems for interactive mode unless already
# set, noting the default values above are for daemon mode. To be consistent,
# we also need to reset $Interval and $SubsysDef noting if one sets a
# secondary interval but not the primary, we need to prepend it with 1 and
# keep the secondary
if (!$daemonFlag)
{
$interval=$Interval=1 if $userInterval eq '' && !$showColFlag;
if ($showColFlag)
{
error('-c conflicts with --showcolheaders') if $count!=-1;
error('-i conflicts with --showcolheaders') if $userInterval ne '';
$interval=0;
$interval='0:0' if $subsys=~/[YZ]/;
$interval='0:0:0' if $subsys=~/E/;
$quietFlag=1; # suppress 'waiting...' startup message
}
if ($userInterval ne '' && $userInterval=~/^(:.*)/)
{
$interval="1$userInterval";
$Interval=1;
}
$SubsysDef=$SubsysDefInt;
$subsys=$SubsysDef if $userSubsys eq '';
}
# subsystems - must preceed +
# special option -s-all disables ALL subsystems which is basically the only way to
# disable all subsystems when you want to play back one or more explicit imports
# so we need to to allow if the ONLY thing that follows -s
error("+/- must start -s arguments if used") if $subsys=~/[+-]/ && $subsys!~/^[+-]/;
error("-s-all only allowed with -p") if $subsys eq '-all' && $playback eq '';
error("invalid subsystem '$subsys'") if $userSubsys ne '-all' && $subsys!~/^[-+$SubsysCore$SubsysExcore$SubsysDet]+$/;
$subsys=mergeSubsys($SubsysDef);
# note that -p, --procanalyze, --slabanalyze and --top can change $subsys
# also be sure to note if the user typed --verbose
$userVerbose=$verboseFlag;
setOutputFormat();
# switch validations once we know whether brief or verbose
error("only choose 1 of -oA and --stats") if $statsFlag>1;
error("statistics not allowed in verbose mode") if $statsFlag && $verboseFlag;
error("statistics not allowed interactively") if $statsFlag && $playback eq '';
error("--statopts required --stats") if $statOpts ne '' && !$statsFlag;
error("valid --statopts are [ais]") if $statOpts ne '' && $statOpts!~/[ais]/;
$headerRepeat=0 if $statsFlag && $statOpts!~/i/; # force single header line when not including interval data
# S p e c i a l F o r m a t s
if ($procAnalFlag || $slabAnalFlag)
{
error("--procanalyze/--slabanalyze require -p") if $playback eq '';
error("--procanalyze/--slabanalyze require -f") if $filename eq '';
error("--procanalyze/--slabanalyze do not support --utc") if $utcFlag;
error("--procanalyze/--slabanalyze with -P requires -s") if $plotFlag && $userSubsys eq '';
error("sorry, but no + or - with -s and analyze mode") if $userSubsys=~/[+-]/;
# No default from playback file in this mode, so go by whatever user
# specificed with -s and if no Y/Z, stick one in there and then make
# user $userSubsys and $subsys agree so initFormat() won't diddle
# the values.
$slabAnalOnlyFlag=($slabAnalFlag && $userSubsys!~/Y/) ? 1 : 0;
$procAnalOnlyFlag=($procAnalFlag && $userSubsys!~/Z/) ? 1 : 0;
$userSubsys.='Y' if $slabAnalOnlyFlag;
$userSubsys.='Z' if $procAnalOnlyFlag;
$subsys=$userSubsys;
$plotFlag=1;
}
# We have to wait for '$subsys' to be defined before handling top and it
# felt right to keep the code together with --procanalyze/--slabanalyze.
# --top forces $homeFlag if not in playback mode. if no process interval
# specified set it to the monitoring one.
$temp=$SubsysDet;
$temp=~s/YZ//;
$detailFlag=($subsys=~/[$temp]/) ? 1 : 0;
if ($topOpts ne '')
{
# Don't diddle original setting in '$userSubsys', use a copy!
# Subtle - the verbose flag wouldn't have been set if ONLY processes or slabs and
# it should be. Similarly, Y/Z should not be considered when looking to see is
# same columns in verbose mode.
my $tempSubsys=$userSubsys;
$tempSubsys=~s/[YZ]//g;
$verboseFlag=1 if $tempSubsys eq '';
$sameColsFlag=1 if $verboseFlag && length($tempSubsys)==1;
$briefFlag=($verboseFlag) ? 0 : 1;
my $subsysSize=0;
if ($tempSubsys ne '' && $playback eq '')
{
if (!$verboseFlag || $sameColsFlag)
{
# in brief or single-subsys verbose mode the area size if fixed by --hr
$subsysSize=$headerRepeat+2;
}
else
{
# multi-subsys verbose mode is driven by the number of subsystems but if
# there are any details, it's up to the users choice of --hr
$subsysSize=length($tempSubsys)*3;
$subsysSize++ if $tempSubsys=~/m/;
$subsysSize=$headerRepeat if $detailFlag;
}
$scrollEnd=$subsysSize+1;
}
($topType, $numTop)=split(/,/, $topOpts);
$topType='time' if $topType eq '';
# enough of these to warrant setting a flag
$topIOFlag=($topType=~/io|kb|sys$|cncl/) ? 1 : 0;
$termHeight=12 if $playback ne '';
$numTop=$termHeight-$scrollEnd-2 if !defined($numTop) || $numTop==-1;
#print "HEIGHT: $termHeight SUBSIZE: $subsysSize HR: $headerRepeat NUMTOP: $numTop\n";
$topProcFlag=(defined($TopProcTypes{$topType})) ? 1 : 0;
$topSlabFlag=(defined($TopSlabTypes{$topType})) ? 1 : 0;
error("not enough lines in window for display")
if $numTop<1;
error("invalid --top type. see --showtopopts for list")
if $topProcFlag==0 && $topSlabFlag==0;
error("you cannot select process and slab subsystems in --top mode")
if ($subsys=~/Y/ && $subsys=~/Z/) ||
($subsys=~/Y/ && $topProcFlag) || ($subsys=~/Z/ && $topSlabFlag);
# if sorting by v/n context switches, force --procopts x if not specified
$procOpts.='x' if $topType=~/vctx|nctx/ && $procOpts!~/x/;
if ($playback eq '')
{
$homeFlag=1;
$subsys=(defined($TopProcTypes{$topType})) ? "${tempSubsys}Z" : "${tempSubsys}Y";
$interval.=":$interval" if $interval!~/:/;
}
}
# I m p o r t
if ($import ne '')
{
# Default mode for --import is NO user defined subsystem in interactive mode.
# All must be explicitly defined
$subsys='' if !$daemonFlag && $userSubsys eq '';
foreach my $imp (split(/:/, $import))
{
$impString=$imp;
$impDetFlag[$impNumMods]=0;
$impNumMods++;
# The following chunks based somewhat on --export code, except OPTS is a string
($impName, $impOpts)=split(/,/, $impString, 2);
$impName.=".ph" if $impName!~/\./;
# If the import file itself doesn't exist in current directory, try $ReqDir
my $tempName=$impName;
$impName="$ReqDir/$impName" if !-e $impName;
if (!-e "$impName")
{
my $temp="can't find import file '$tempName' in ./";
$temp.=" OR $ReqDir/" if $ReqDir ne '.';
error($temp) if !-e "$impName";
}
require $impName;
# the basename is the name of the function and also remove extension.
$impName=basename($impName);
$impName=(split(/\./, $impName))[0];
push @impOpts, $impOpts;
push @impInit, "${impName}Init";
push @impGetData, "${impName}GetData";
push @impGetHeader, "${impName}GetHeader";
push @impInitInterval, "${impName}InitInterval";
push @impIntervalEnd, "${impName}IntervalEnd";
push @impAnalyze, "${impName}Analyze";
push @impUpdateHeader, "${impName}UpdateHeader";
push @impPrintBrief, "${impName}PrintBrief";
push @impPrintVerbose, "${impName}PrintVerbose";
push @impPrintPlot, "${impName}PrintPlot";
push @impPrintExport, "${impName}PrintExport";
}
# Call REQUIRED initialization routines in reverse so if we have to
# delete anything we won't have to deal with overlap
$impSummaryFlag=$impDetailFlag=0;
for (my $i=($impNumMods-1); $i>=0; $i--)
{
my $status=&{$impInit[$i]}(\$impOpts[$i], \$impKey[$i]);
if ($status==-1)
{
splice(@impOpts, $i, 1);
splice(@impKey, $i, 1);
splice(@impInit, $i, 1);
splice(@impGetData, $i, 1);
splice(@impGetHeader, $i, 1);
splice(@impInitInterval, $i, 1);
splice(@impIntervalEnd, $i, 1);
splice(@impAnalyze, $i, 1);
splice(@impUpdateHeader, $i, 1);
splice(@impPrintBrief, $i, 1);
splice(@impPrintVerbose, $i, 1);
splice(@impPrintPlot, $i, 1);
splice(@impPrintExport, $i, 1);
$impNumMods--;
next;
}
# We need to know if any module has summary or data in case one one else does
# and we're in plot format so newlog() will know to open tab file. This also
# helps optimize some of the print routines.
$impSummaryFlag++ if $impOpts[$i]=~/s/;
$impDetailFlag++ if $impOpts[$i]=~/d/;
}
# Reset output formatting based on the modules we just loaded
print "Reset output flags\n" if $debug & 1;
setOutputFormat();
}
# E x p o r t M o d u l e s
# since we might want to diddle with things like $subsys or fake out other
# switches, we need to load/initialize things early. We may also need a
# call to a pre-execution init module later...
# This one needs more explanation. Most export modules expect to either log
# to a file or send their output over a socket and so collectl will generate
# an error if you try to do so without -f or -A. BUT modules like ganglia
# or graphite do their own communications and so need to set this flag to
# defeat that message in case they don't want to locally log data.
$exportComm=0;
if ($export ne '')
{
# By design, if you specify --export and -f and have a socket open, the exported
# data goes over the socket and we write either a raw or plot file to the dir
# pointed to by -f. If not -P, we always write a raw file
$rawtooFlag=1 if $sockFlag && $filename ne '' && !$plotFlag;
$verboseFlag=1;
($expName, @expOpts)=split(/,/, $export);
$expName.=".ph" if $expName!~/\./;
# If the export file itself doesn't exist in current directory, try $ReqDir
my $tempName=$expName;
$expName="$ReqDir/$expName" if !-e $expName;
if (!-e "$expName")
{
my $temp="can't find export file '$tempName' in ./";
$temp.=" OR $ReqDir/" if $ReqDir ne '.';
error($temp);
}
require $expName;
# the basename is the name of the function and also remove extension.
$expName=basename($expName);
$expName=(split(/\./, $expName))[0];
}
# S i m p l e S w i t c h C h e c k s
$utcFlag=1 if $options=~/U/;
# should I migrate a lot of other simple tests here?
error("you cannot specify -f with --top") if $topOpts ne '' && $filename ne '';
error("--home does not apply to -p") if $homeFlag && $playback ne '';
error("--envopts M does not apply to -P") if $userEnvOpts ne '' && $userEnvOpts=~/M/ && $plotFlag;
error("--envopts are only fptCFMT and/or a number") if $userEnvOpts ne '' && $userEnvOpts!~/^[fptCFMT0-9]+$/;
error("--envrules does not exist") if $envRules ne '' && !-e $envRules;
error("--grep only applies to -p") if $grepPattern ne '' && $playback eq '';
error('--headerrepeat must be an integer') if $headerRepeat!~/^[\-]?\d+$/;
error('--headerrepeat must be >= -1') if $headerRepeat<-1;
error("-i not allowed with -p") if $userInterval ne '' && $playback ne '';
error("--rawtoo does not work in playback mode") if $rawtooFlag && $playback ne '';
error("--rawtoo requires -f") if $rawtooFlag && $filename eq '';
error("--rawtoo requires -P or --export") if $rawtooFlag && !$plotFlag && $export eq '';
error("--rawtoo and -P requires -f") if $rawtooFlag && $plotFlag && $filename eq '';
error("--rawtoo cannot be used with -p") if $rawtooFlag && $playback ne '';
error("-ou/--utc only apply to -P format") if $utcFlag && !$plotFlag;
error("can't mix UTC time with other time formats") if $utcFlag && $options=~/[dDT]/;
error("-oz only applies to -P files") if $options=~/z/ && !$plotFlag;
error("--sep cannot be a '%'") if defined($SEP) && $SEP eq '%';
error("--sep only applies to plot format") if defined($SEP) && !$plotFlag;
error("--sep much be 1 character or a number") if defined($SEP) && length($SEP)>1 && $SEP!~/^\d+$/;
error('--showheader not allowed with -f') if $filename ne '' && $showHeaderFlag;
error("--showheader in collection mode only supported on linux")
if $PcFlag && $playback eq '' && $showHeaderFlag;
error('--showmergedheader not allowed with -f') if $filename ne '' && $showMergedFlag;
error('--showcolheaders not allowed with -f') if $filename ne '' && $showColFlag;
error('--showcolheaders -sE can only be run by root') if $showColFlag && $subsys=~/E/ && !$rootFlag;
error("--align require HiRes time module") if $alignFlag && !$hiResFlag;
error('--umask can only be set by root') if $umask ne '' && !$rootFlag;
error('-sT can only be used with -f or -P') if $subsys=~/T/ && !$plotFlag && $filename eq '';
# if user enters --envOpts
if ($userEnvOpts ne '')
{
# remove ALL ipmi data types if user specified any, then add in ALL user options
# which could include formatting options
$envOpts=~s/[fpt]+//g if $userEnvOpts=~/[fpt]/;
$envOpts.=$userEnvOpts;