-
Notifications
You must be signed in to change notification settings - Fork 4
/
colmux
executable file
·2395 lines (2067 loc) · 79.8 KB
/
colmux
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
# problems
# pattern match for -i recognition/removal (in -test) not robust enough
# Copyright 2005-2017 Hewlett-Packard Development Company, LP
#
# colmux 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 Values
# 1 - print interesting stuff
# 2 - print more instersting stuff
# 4 - do NOT start collectl. real handy for debugging collectl side
# 8 - replaced functionality with -noescape
# 16 - show selected hostname/addresses and exit
# 32 - echo chars received on STDIN
# 64 - echo comments from collectl. useful when inserting debugging comments
# 128 - echo everything from collectl
# 256 - async double-buffering
# 512 - echo collectl version checking commands
# 1024 - print remote host's datetime as yyyymmddhhmmss
# KNOWN PROBLEMS
#
# pdsh format is not handled correctly by csh and you will need to quote expressions
#
# The format of the process data may vary based on whether or not a system provides
# I/O stats as well. If not all systems provide a consistent format, you will get
# some unaligned columns, the headers based on the first system configuration.
#
# Lustre FS and OST names can vary in width so if you're monitoring systems with
# different name widths the columns won't line up. However, since one typically
# wouldn't monitor mixed lustre environments at the same time, they should all be
# consistent in width, unlike netnames whose widths do and you may need to
# include --netopts w in your collectl command
#
# colmux will sort columns as numeric or string. Numeric preserves sort order whereas
# string sorts will go by the leftmost digits, giving 10 a higher sort order than 9.
# If colmux sees a column that does contain a digit it will do a string sort. This
# will affect any number fields, eg process priorities can also be RT
use File::Basename;
use Getopt::Long;
use IO::Socket;
use IO::Select;
use Net::Ping;
use Time::Local;
use Cwd 'abs_path';
use strict 'vars';
use threads;
use threads::shared;
my @dates:shared;
my @threadFailure:shared;
my $firstHostName:shared;
my $firstColVersion:shared;
# This construct allows us to run in playback mode w/o readkey
# being installed by explicitly declaring the 2 routines below.
my $readkeyFlag=(eval {require "Term/ReadKey.pm" or die}) ? 1 : 0;
# it was discovered that the threads::join doesn't work with earlier versions
my $threadsVersion=threads->VERSION;
# Make sure we flush buffers on print.
$|=1;
# If running the '.pl' version of colmux, which I typically do during
# development, assume collectl lives in /usr/bin. The rest of the time use
# the same directory as colmux since the both might be on a network share
my $BinDir=($0=~/pl$/) ? '/usr/bin' : dirname(abs_path($0));
my $Collectl="$BinDir/collectl";
my $Program='colmux';
my $Version='5.0.0';
my $Copyright='Copyright 2005-2018 Hewlett-Packard Development Company, L.P.';
my $License="colmux 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";
my $Ping='/bin/ping';
my $ResizePath='/usr/bin/resize:/usr/X11R6/bin/resize';
my $Route='/sbin/route';
my $Ifconfig='/sbin/ifconfig';
my $Grep='/bin/grep';
my $DefPort=2655;
my $K=1024;
my $M=1024*1024;
my $G=1024*1024*1024;
my $ESC=sprintf("%c", 27);
my $Home=sprintf("%c[H", 27); # top of display
my $Bol=sprintf("%c[99;0f", 27); # beginning of current line
my $Clr=sprintf("%c[J", 27); # clear to end of display
my $Clscr="$Home$Clr"; # clear screen
my $Cleol=sprintf("%c[K", 27); # clear to end of line
my $bold=sprintf("%c[7m", 27);
my $noBold=sprintf("%c[0m", 27);
my $bell=sprintf("%c", 7);
my $pingTimeout=5;
my $hiResFlag=(eval {require "Time/HiRes.pm" or die}) ? 1 : 0;
error('this tool requires the perl-time-hires module') if !$hiResFlag;
# Let's see if we can find resize
my $resize;
foreach my $bin (split/:/, $ResizePath)
{ $resize=$bin if -e $bin; }
my $termHeight=24;
my $termWidth=80;
if (defined($resize))
{
`$resize`=~/LINES.*?(\d+)/m;
$termHeight=$1;
`$resize`=~/COLUMNS.*?(\d+)/m;
$termWidth=$1;
}
# This controls real-time, multi-line sorting.
my %sort;
# Don't use unless you know all collectl versions support it
my $timeout='';
# Default parameter settings.
my $address='';
my $age=2;
my $noboldFlag=0;
my $nosortFlag=0;
my $noEscapeFlag=0;
my $column=1;
my $cols='';
my $colwidth=6;
my $command='';
my $debug=0;
my $delay=0;
my $freezeFlag=0;
my $homeFlag=0;
my $hostFilter='';
my $hostFormat='';
my $hostWidth=8;
my $keepalive='';
my $nocheckFlag=0;
my $port=$DefPort;
my $negdataval;
my $nodataval=-1;
my $maxLines=$termHeight;
my $username='';
my $sudoFlag=0;
my $sshkey='';
my $colhelp;
my ($helpFlag,$verFlag)=(0,0);
my ($revFlag,$zeroFlag)=(0,0);
my ($colhelpFlag,$colnodetFlag,$testFlag,$colTotalFlag,$col1Flag, $colKFlag, $reachableFlag, $quietFlag)=(0,0,0,0,0,0,0,0,0);
my $colnoinstFlag=0;
my $colLogFlag=0;
my $colnodiv='';
my $finalCr=0;
my $retaddr='';
my $timerange=1;
GetOptions("address=s" =>\$address,
"age=i" =>\$age,
"colbin=s" =>\$Collectl,
"colk!" =>\$colKFlag,
"collog10!" =>\$colLogFlag,
"col1000!" =>\$col1Flag,
"column=s" =>\$column,
"cols=s" =>\$cols,
"colhelp!" =>\$colhelpFlag,
"colnodet!" =>\$colnodetFlag,
"colnoinst!" =>\$colnoinstFlag,
"colnodiv=s" =>\$colnodiv,
"coltotal!" =>\$colTotalFlag,
"colwidth=i" =>\$colwidth,
"command=s" =>\$command,
"debug=i" =>\$debug,
"delay=s" =>\$delay,
"finalcr!" =>\$finalCr,
"lines=i" =>\$maxLines,
"help!" =>\$helpFlag,
"homeFlag!" =>\$homeFlag,
"hostfilter=s" =>\$hostFilter,
"hostformat=s" =>\$hostFormat,
"hostwidth=i" =>\$hostWidth,
"keepalive=i" =>\$keepalive,
"negdataval=i" =>\$negdataval,
"nodataval=i" =>\$nodataval,
"nocheck!" =>\$nocheckFlag,
"nobold!" =>\$noboldFlag,
"noescape!" =>\$noEscapeFlag,
"nosort!" =>\$nosortFlag,
"port=i" =>\$port,
"quiet!" =>\$quietFlag,
"reachable!" =>\$reachableFlag,
"retaddr=s" =>\$retaddr,
"reverse!" =>\$revFlag,
"sshkey=s" =>\$sshkey,
"timerange=i" =>\$timerange,
"sudo!" =>\$sudoFlag,
"test!" =>\$testFlag,
"timeout=i" =>\$timeout,
"username=s" =>\$username,
"version!" =>\$verFlag,
"zero!" =>\$zeroFlag,
) or error("type -help for help");
help() if $helpFlag;
if ($verFlag)
{
my $readkeyVer=($readkeyFlag) ? 'V'.Term::ReadKey->VERSION : 'not installed';
print "$Program: $Version (Term::ReadKey: $readkeyVer Threads: $threadsVersion)\n\n$Copyright\n$License\n";
exit;
}
if ($noEscapeFlag)
{
$readkeyFlag=0;
$Home=$Bol=$Clr=$Clscr=$Cleol=$bold=$noBold=$bell='';
}
# This may evolve over time
my ($hostDelim, $hostPiece)=('','');
if ($hostFormat ne '')
{
error('only valid format is char:pos') if $hostFormat!~/^\S{1}:\d+$/;
($hostDelim, $hostPiece)=split(':', $hostFormat)
}
# if sudo mode
$Collectl="sudo $Collectl" if $sudoFlag;
# ok if host not in known_hosts and when not debugging be sure to turn off motd
my $Ssh='/usr/bin/ssh -o StrictHostKeyChecking=no -o BatchMode=yes';
$Ssh.=" -o ServerAliveInterval=$keepalive" if $keepalive ne '';
$Ssh.=" -q" unless $debug;
error('-nocheck and -recheck are mutually exclusive') if $nocheckFlag && $reachableFlag;
error('-nocheck and -quiet are mutually exclusive') if $nocheckFlag && $quietFlag;
# P a r s e T h e C o m m a n d
error('--top not allowed') if $command=~/--top/;
# any imports? we HAVE to deal with these before looking at -s because if there
# are and no -s, we have NO subsystems selected. We need to count them and also
# set a flag if ANY of them have specifice a 'd' parameter
$command=~/--imp.*?\s+(\S+)/;
my $imports=(defined($1)) ? $1 : '';
my $numImports=0;
my $importDetail=0;
foreach my $import (split(/:/, $imports))
{
$numImports++;
# here'e where we check for a 'd'
foreach my $param (split(/,/, $import))
{
if ($param=~/^[sd]+$/)
{
$importDetail=1 if $param=~/d/; # see if detail data
$numImports++ if length($param)==2; # if both, we have 2 subsys, not 1
}
}
}
# default subsys depends on whether any imports
my $defSubsys=($imports ne '') ? '' : 'cdn';
my $subsys=($command=~/-s\s*(\S+)/) ? $1 : $defSubsys;
my $expFlag= ($command=~/--exp/) ? 1 : 0;
my $verbFlag=($command=~/--verb/) ? 1 : 0;
my $plotFlag=($command=~/-P/) ? 1 : 0;
my ($fromTime, $thruTime)=split(/-/, $1) if $command=~/--fr\S*\s+(\S+)/;
$thruTime=$1 if $command=~/--th\S*\s+(\S+)/;
#error("invalid from/thru time") if !checkTime($fromTime) || !checkTime($thruTime);
# Get options from command string being sure to IGNORE hostname in playback mode which could
# contain within but removing all occurances of {char}-o from original command
my $temp=$command;
$temp=~s/\S-o//i;
my $options=($temp=~/-o\s*(\S+)/) ? $1 : '';
# get today's date as well as building one in the standard format if specified in command
# note - $year, $mon and $day must not be changed!
my ($date, $day, $mon, $year, $today, $yesterday);
($day, $mon, $year)=(localtime(time-86400))[3..5];
$yesterday=sprintf("%d%02d%02d", $year+1900, $mon+1, $day);
($day, $mon, $year)=(localtime(time))[3..5];
$today=sprintf("%d%02d%02d", $year+1900, $mon+1, $day);
$date=($options=~/d/) ? sprintf("%02d/%02d", $mon+1, $day) : sprintf("%d%02d%02d", $year+1900, $mon+1, $day);
$command=~s/TODAY/*$today*/i;
$command=~s/YESTERDAY/*$yesterday*/i;
# Surrounding the command with spaces makes the parsing easier below. We're looking
# for playback filenames and then surrounding them with "s
$command=" $command ";
my ($playbackFile, $playbackFlag);
error('-p in collectl command requires an argument') if $command=~/-p\s+\-|--pla\S+\s+-/;
$playbackFile=$1 if $command=~s/\s-p\s*(\S+)(.*)/ -p "$1"$2/;
$playbackFile=$2 if $command=~s/\s(--pla.*?)\s+(\S+)(.*)/ $1 "$2"$3/;
$playbackFlag=(defined($playbackFile)) ? 1 : 0;
$command=~s/^ (.*) $/$1/; # remove leading/trailing spaces
error('-P only allowed with -cols') if $plotFlag && $cols eq '' && !$testFlag;
error('-colnodiv only applies to -cols') if $colnodiv ne '' && $cols eq '';
error('only valid -o values are mndDT') if $options ne '' && $options!~/^[mndDT]+$/;
error('-o only allows 1 of dDT') if $options ne '' && $options=~/([dDT]+)/ && length($1)>1;
error('-om requires at least 1 of dDT') if $options eq 'm';
error('-hostfilter only applies to local playback files') if $hostFilter ne '' && (!$playbackFlag || $address ne '');
error('-home only applies to multi-line playback data') if $homeFlag && $cols eq '' && !$playbackFlag;
error('cannot mix slab/process data with anything else') if $subsys=~/[YZ]/ && $subsys=~/[a-zA-X]/;
# real-time, multi-line default is -home
$homeFlag=1 if $cols eq '' && !$playbackFlag;
if (!$plotFlag)
{
# how many subsys, including imports, are being reported?
# note that if an uppercase subsys OR an import with a 'd', we have detail data present
my $numSubsys=$numImports+(($subsys ne '-all') ? length($subsys) : 0);
my $detailFlag=($subsys=~/^[A-X]+$/ || $importDetail) ? 1 : 0;
error('--verbose not allowed with multiple subsystems w/o -P') if $verbFlag && $numSubsys>1;
error('cannot mix summary and detail data w/o -P') if $subsys=~/[a-x]/ && $subsys=~/[A-X]/;
error('cannot specify detail data when multiple subsystems w/o -P') if $numSubsys>1 && $detailFlag;
}
my $localFlag=1;
my (@hostnames, $firstAddress);
if (!$playbackFlag || $address ne '')
{
$address='localhost' if $address eq ''; # use 'localhost' for real-time mode
$localFlag=0;
if (-f $address)
{
open ADDR, "<$address" or die "Couldn't open '$address'";
while (my $line=<ADDR>)
{
next if $line=~/^#|^\s*$/;
chomp $line;
$line=~s/^\s*//; # strip leading whitespace
push @hostnames, $line;
}
close ADDR;
}
else
{
@hostnames=pdshFormat($address);
}
}
my $numHosts=scalar(@hostnames);
# See if any host specs contain 'username@' & reset 'localhost' and
# adjust maximum hostname length if necessary.
my $hostlen=$hostWidth;
my $myhost=`hostname`;
chomp $myhost;
my (%usernames, %sshswitch, %aliases);
for (my $i=0; $i<@hostnames; $i++)
{
# $hostnames[] is typically just the hostname, but sometimes it's more complex and in those cases
# we need to pull out the optional ssh prefix, username and aliases.
my $host=$hostnames[$i];
# NOTE - to use sshswitches you MUST use @ as well so strip everything
# preceding hostname and save host (ignoring alias if there is one)
my ($prefix, $user, $alias)=('','','');
if ($hostnames[$i]=~s/(.*)@(\S+)/$2/)
{
$user=$1;
$host=$2;
# if whitespace, the it's really a prefix and username
if ($user=~/(.*)\s+(\S+)/)
{
$prefix=$1;
$user=$2;
}
#print "PREFIX: $prefix USER: $user HOST: $host\n";
}
error("-i and/or usernames in addr file conflict with -sshkey") if $prefix ne '' && $sshkey ne '';
if ($hostnames[$i]=~/(\S+)\s+(\S+)/)
{
$host=$1;
$alias=$2;
#print "ALIAS[$host]: $alias\n";
}
# if -username, initially associate it with ALL hosts
$usernames{$host}=$username if $username ne '';
$usernames{$host}=$user if $user ne '';
$sshswitch{$host}=$prefix if $prefix ne '';
$sshswitch{$host}="-i $sshkey" if $sshkey ne '';
$aliases{$alias}=$i if $alias ne '';
# make sure this only contains a hostname
$hostnames[$i]=$host;
# force local hostname if 'localhost'
$hostnames[$i]=$myhost if $hostnames[$i] eq 'localhost';
# determine the maximum host's name and if a real name vs an address, remove
# the domain portion as well.
my $tempname=$host;
$tempname=(split(/\./, $tempname))[0] if $tempname=~/^[a-z]/i;
$hostlen=length($tempname) if length($tempname)>$hostlen;
}
#########################################################################################
# C h e c k A l l H o s t s F o r R e a c h a b i l i t y / C o n f i g
#########################################################################################
# make sure all remote hosts are reachable and properly configured
my @threads;
if ($address ne '' && !$nocheckFlag)
{
# seems that even though a timeout of 1 second if long enough to detect failed pings,
# we need longer or else good nodes will get failed trying to connect back to us
my $ping=Net::Ping->new();
for (my $i=0; $i<@hostnames; $i++)
{ $threads[$i]=threads->create('check', $i); }
# Wait for ping responses in 10ths of a second
for (my $i=0; $i<$pingTimeout*10; $i++)
{
last if threadsDone($numHosts);
Time::HiRes::usleep(100000);
}
# make sure dates within --timerange secs
my $minSecs=9999999999;
my $maxSecs=0;
for (my $i=0; $i<@hostnames; $i++)
{
# some checks may have failed so only look at 'good' nodes
if (!$threadFailure[$i])
{
my $year=substr($dates[$i], 0, 4);
my $mon= substr($dates[$i], 4, 2);
my $day= substr($dates[$i], 6, 2);
my $hour=substr($dates[$i], 8, 2);
my $mins=substr($dates[$i], 10, 2);
my $secs=substr($dates[$i], 12, 2);
my $seconds=(timelocal($secs, $mins, $hour, $day, $mon-1, $year-1900));
$minSecs=$seconds if $seconds<$minSecs;
$maxSecs=$seconds if $seconds>$maxSecs;
print "$hostnames[$i]: $dates[$i]" if $debug & 1024;
if ($maxSecs-$minSecs>$timerange)
{
my $plural=($timerange>1) ? 's' : '';
print "WARNING: $hostnames[$i]'s time differs by more than $timerange second$plural with at least one other\n";
print " run again with -debug 1024 and/or use -timerange or -quiet to suppress this message\n";
}
}
}
# Finally go back through hosts list in reverse order so we don't shift things
# on top of each other, removing any that report unsuitability for use
my $killSsh=0;
my $allReachableFlag=1;
my $printedReturnFlag=0;
for (my $i=@hostnames-1; $i>=0; $i--)
{
if ($threadFailure[$i])
{
$allReachableFlag=0;
# If ping failed, thread already gone but if ssh it's still there so we need to kill
# the ssh. Set a flag so we can do them all at once.
$killSsh=1 if $threadFailure[$i]==-1;
print "\n" if !$printedReturnFlag; # because ssh failures doesn't return carriage
my $reason;
$reason='passwordless ssh failed' if $threadFailure[$i]==-1;
$reason='ping failed' if $threadFailure[$i]==1;
$reason='collectl not installed' if $threadFailure[$i]==2;
$reason='ssh: connection refused' if $threadFailure[$i]==4;
$reason='ssh: permission denied' if $threadFailure[$i]==8;
$reason='could not resolve name' if $threadFailure[$i]==16;
$reason='timed out during banner exchange' if $threadFailure[$i]==32;
$reason='collectl version < 3.5' if $threadFailure[$i]==64;
$reason='collectl not installed' if $threadFailure[$i]==128;
printf "$hostnames[$i] removed from list: $reason\n";
$printedReturnFlag=1;
splice(@hostnames, $i, 1);
$numHosts--;
}
}
if ($killSsh)
{
# We need to look for a ps command w/o the -q
my $tempSsh=$Ssh;
$tempSsh=~s/ -q//;
print "Killing hung ssh(s)\n" if $debug & 1;
open PS, "ps axo pid,command|" or error("couldn't execute 'ps' to find ssh processes");
while (my $line=<PS>)
{
next if $line!~/$tempSsh/;
$line=~s/^\s+//; # can have leading space
my $pid=(split(/\s+/, $line))[0];
print "Killing ssh with pid: $pid\n" if $debug & 1;
`kill $pid`;
}
sleep 1; # wait a tad for ssh in thread to exit
close PS;
}
# for newer threads versions, all must be joined or we'll get errors when we exit
if ($threadsVersion>'1.59')
{
foreach my $thread (threads->list(threads::joinable))
{ $thread->join(); }
}
# if nobody reachable!
error('no accessible addresses in list') if !$numHosts;
# a couple of reasons to exit, but only report message if due to
# unreachability
if (!$allReachableFlag && $reachableFlag)
{
Term::ReadKey::ReadMode(0) if $readkeyFlag;
print "Not all hosts configured correctly or reachable and so exiting...\n";
exit;
}
}
if ($debug & 16)
{
# the print is over-the-top, but IS useful for verifying usernames parsed correctly
print ">>> addresses <<<\n";
printf "%-${hostlen}s %s\n", 'HOST', 'USERNAME';
for (my $i=0; $i<$numHosts; $i++)
{ printf "%-${hostlen}s %s\n", $hostnames[$i], defined($usernames{$hostnames[$i]}) ? $usernames{$hostnames[$i]} : ''; }
exit;
}
###############################
# C o m m o n S t u f f
###############################
error('-lines cannot be negative') if $maxLines<0;
# Makes a little easier to reference later.
my $timeFlag=($options=~/[dDT]+/) ? 1 : 0;
# These switches are common to both real-time and playback modes, but
# some of those mode-specific switches not allowed in this mode.
my @columns;
my $maxColNum=0;
my $maxDataAge;
my $interval=($command=~/-i\s*:*(\d+)/) ? $1 : 1; # tricky because of --import
my @colsNoDiv;
if ($cols ne '')
{
# make sure all data numeric
$command.=' -w';
# any data older than this is consider invalid, noting if secondary interval
# just use 1.
my $ageInterval=($interval=~/:/) ? 1 : $interval;
$maxDataAge=$age*$ageInterval;
# We need to set this first so -test will work right
@columns=split(/,/,$cols);
# Skip ALL cols related validation with -test
if (!$testFlag)
{
error('-nosort not allowed in column mode') if $nosortFlag;
error('-delay not allowed in column mode unless -p') if $delay && !$playbackFlag;
error('-colnodet requires -coltotal') if $colnodetFlag && !$colTotalFlag;
error('detailed data not allowed unless -P') if $subsys=~/[A-X]/ && !$plotFlag;
foreach my $col (@columns)
{
error('you cannot select host column with -cols, verify with -test') if $col==0;
error('-cols incorrectly specifies date/time field. verify with --test')
if ($col==1 && $timeFlag) || ($col==2 && $options=~/[dD]/) || ($col<3 && $plotFlag);
$maxColNum=$col if $col>$maxColNum;
}
}
if ($colnodiv ne '')
{
my @cols=split(/,/, $colnodiv);
foreach my $col (@cols)
{
error("non-numeric column in -colnodiv: $col") if $col!~/^\d+$/;
my $match=0;
for my $i (@columns)
{ $match=1 if $col==$i; }
error("specified column $col with -colnodiv but not with -cols") if !$match;
$colsNoDiv[$col]=1;
}
}
}
else
{
error('-colk only applies to -columns') if $colKFlag;
error('-collog only applies to -columns') if $colLogFlag;
error('-col1000 only applies to -columns') if $col1Flag;
error('-colnodet only applies to -columns') if $colnodetFlag;
error('-coltotal only applies to -columns') if $colTotalFlag;
error('-nodataval only applies to -columns') if $nodataval!=-1;
error('-negdataval only applies to -columns') if defined($negdataval);
error("-o not allowed for 'real-time', non-cols format") if !$playbackFlag && $timeFlag;
}
# force -oT if time not specified by either appending to command OR adding
# to -o if that has been specified
if (!$timeFlag)
{
$command=~s/-o/-oT/ if $options ne '';
$command.=' -oT' if $options eq '';
}
# Additional globals, may only be needed by one mode
my $input;
my $ctrlCFlag=0;
my $numCols=0;
my $numLines=-1;
my $numReporting=0;
my $somethingPrintedFlag;
my $boldFlag=($noboldFlag) ? 0 : 1;
my $oldColFlag;
my (@printStack, @hostdata);
my (@host, @hostVars, @sample, %files);
# if in 'local' mode we don't yet know the max host name length for reformHeaders()
# so get it here first and while we're at is save the hostnames for later too
if ($playbackFlag && $localFlag)
{
my (%temp, $host);
my @hostFilters=pdshFormat($hostFilter) if $hostFilter ne '';
my $globSpec=$playbackFile;
$numHosts=0;
$globSpec=~s/"//g;
foreach my $file (glob($globSpec))
{
# When we glob, we expand the string as would the shell. If no wildards it just
# returns itself which may NOT be a valid filename so we have to test
next if !-f $file;
next if $file!~/\d{8}-\d{6}\.raw/;
$file=basename($file);
$file=~/(.*)-\d{8}-\d{6}\.raw/;
$host=$1;
next if defined($temp{$host}); # if already seen/kept this hostname
# if using host filters, only identify keep those that match
if ($hostFilter ne '')
{
my $filterMatch=0;
foreach my $filter (@hostFilters)
{ $filterMatch=1 if $filter eq $host; }
next if !$filterMatch;
}
# keep this host and add ONCE to list of hosts to be processed
$numHosts++;
$temp{$host}='';
push @hostnames, $host;
$hostlen=length($host) if $hostlen<length($host);
}
error('no files match playback file specification') if scalar(@hostnames)==0;
}
# build command to get headers noting in real-time mode
my (@headers, @headernames, @headerPos);
my $switch=(!defined($sshswitch{$hostnames[0]})) ? '' : $sshswitch{$hostnames[0]};
my $uname= (!defined($usernames{$hostnames[0]})) ? '' : "$usernames{$hostnames[0]}\@" if !$localFlag;
my $access=($localFlag) ? "$Ssh -n $myhost" : "$Ssh -n $switch $uname$hostnames[0]";
@headers=getHeaders($access, $command);
# get last header line
my $gotHeadersFlag=(defined($headers[0])) ? 1 : 0;
print "GotHeader: $gotHeadersFlag\n" if $debug & 1;
my $lastHeader=$headers[-1];
if ($gotHeadersFlag)
{
exit if !reformatHeaders();
foreach my $col (split(/\s+/, $lastHeader))
{
# strip detail field names including surrounding []s
$col=~s/\[.*\]// if $colnoinstFlag;
push @headernames, $col;
}
}
# need room for headers and possible help line for JD
my $bodyLines=$maxLines-scalar(@headers);
$bodyLines-- if $colhelpFlag;
if ($testFlag)
{
showHeaders();
Term::ReadKey::ReadMode(0) if $readkeyFlag;
exit;
}
# if readkey there, change terminal characteristics to handle raw
# mode as well as disabling echo
Term::ReadKey::ReadMode(4) if $readkeyFlag;
#################################
# R e a l t i m e M o d e
#################################
# this global give stdin() visibility into how many lines of output are available
my $totalLines;
my $startLine=1;
if (!$playbackFlag)
{
error('-nosort only applies to playback mode') if $nosortFlag;
error('--from/--thru not allowed in real-time mode') if defined($fromTime) || defined($thruTime);
error('-delay only applies to playback mode') if $delay;
# never in single line format.
$homeFlag=0 if $cols ne '';
# Pull out addresses from address file (or list or whatever form
# these came to us in.
my (%hostNumMap, %addrhost);
for (my $i=0; $i<$numHosts; $i++)
{
# Could be an address OR a simply host name
my $host=$hostnames[$i];
my $gbn=gethostbyname($host);
error("cannot resolve '$host' to a network address") if !defined($gbn) || $gbn eq '';
my $netaddr=inet_ntoa(scalar($gbn));
error("'$host' resolves to 127.0.0.1! use a different host") if $netaddr eq '127.0.0.1';
$addrhost{$netaddr}=$i;
$firstAddress=$netaddr if !defined($firstAddress);
$hostVars[$i]->{bufptr}=0;
$hostVars[$i]->{maxinst}->[0]=-1; $hostVars[$i]->{lastinst}->[0]=-1; $hostVars[$i]->{lasttime}->[0]='';
$hostVars[$i]->{maxinst}->[1]=-1; $hostVars[$i]->{lastinst}->[1]=-1; $hostVars[$i]->{lasttime}->[1]='';
}
# O p e n O u r S o c k e t ( s )
my $myReturnAddr=($retaddr eq '') ? getReturnAddress($firstAddress) : $retaddr;
my $mySocket = new IO::Socket::INET(Type=>SOCK_STREAM,
Reuse=>1, Listen => 1,
LocalPort => $port)
or error("couldn't create local socket on port: $port");
my $sel = new IO::Select($mySocket);
print "Listening for connections on $port\n" if $debug & 1;
# S e t A l a r m
# if interval specified in command, use that; otherwise 1
my $interval=(defined($interval)) ? $interval : 1;
$interval=~s/.*://; # In case sub-intervals
$SIG{"ALRM"}=\&alarm;
my $uInterval=$interval*10**6;
Time::HiRes::ualarm($uInterval, $uInterval);
# S t a r t R e m o t e c o l l e c t l s
for (my $i=0; $i<$numHosts; $i++)
{
my $switch=(!defined($sshswitch{$hostnames[$i]})) ? '' : $sshswitch{$hostnames[$i]};
my $uname= (!defined($usernames{$hostnames[$i]})) ? '' : "$usernames{$hostnames[$i]}\@";
my $access=($localFlag) ? '$Ssh -n localhost' : "$Ssh -n $switch $uname$hostnames[$i]";
# MUST include timestamps
my $colCommand= "$access $Collectl $command -A $myReturnAddr:$port";
$colCommand.=":$timeout" if $timeout ne '';
$colCommand.=" --quiet" if !$debug;
$colCommand.=" &";
print "Command: $colCommand\n" if $debug & 1;
system($colCommand) unless $debug & 4;
}
# start with a clear screen
print "$Home$Clscr" if $homeFlag;
# add STDIN to list of handles to look for input on.
$sel->add(STDIN);
my $Record='';
my $hostNum=0;
my $headerHost=-1;
my $lastHost=-1;
my ($remoteAddr, %sockHandle);
while(!$ctrlCFlag)
{
# NOTE - since much of collectl's multiline prints are via multiple socket
# writes, the data may come back as separate lines here, and not
# necessary all together so we need to track the last one seen
# NOTE2 - the can_read() below will prematurely wake up when the timer goes
# off but that's ok because it will simply fall through the loop and
# come right back...
while(my @ready = $sel->can_read(1))
{
foreach my $filehandle (@ready)
{
if ($filehandle eq 'STDIN')
{
stdin();
next;
}
# NOTE - logic for handling hosts by socket stolen from colgui
if ($filehandle==$mySocket)
{
# Create a new socket
my $new = $mySocket->accept;
$remoteAddr=inet_ntoa((sockaddr_in(getpeername($new)))[1]);
$sockHandle{$new}=$addrhost{$remoteAddr};
$sockHandle{$new}=(defined($addrhost{$remoteAddr})) ? $addrhost{$remoteAddr} : $aliases{$remoteAddr};
$sel->add($new);
# if we do get a connection from an unexpected place, accept it in case we
# keep getting it, but then ignore it!
if (!defined($addrhost{$remoteAddr}))
{
print "*** connection from unknown source: $remoteAddr! ***\n" unless $quietFlag;
next;
}
printf "New socket connection from Host: %d Addr: %s\n",
$sockHandle{$new}, $remoteAddr
if $debug & 1;
$numReporting++;
}
else
{
my ($host, $time, $therest);
$Record=<$filehandle>;
if ($Record)
{
chomp $Record;
print ">>> $Record\n" if $debug & 128;
($host, $therest)=split(/ /, $Record, 2); # preserve leading spaces in 'therest'
$hostNum=$sockHandle{$filehandle};
if (!defined($hostNum))
{
print "Ignoring records from '$host' which is not ";
print "recognizable. Is the alias wrong or missing?\n";
$remoteAddr=inet_ntoa((sockaddr_in(getpeername($filehandle)))[1]);
$sel->remove($filehandle);
$filehandle->close;
$numReporting--;
next;
}
$hostNumMap{$filehandle}=$hostNum;
$host[$hostNum]=($hostFormat eq '') ? $host : (split(/$hostDelim/, $host))[$hostPiece];
if ($therest=~/^#/)
{
print "$therest\n" if $debug & 64;
# when first starting up, not all hosts necessarily respond during initial
# cycle so let's save the header from the first one who does
next if ($gotHeadersFlag || ($headerHost!=-1 && $headerHost!=$hostNum));
# We want to skip the first line of the process data header
next if $therest=~/^###/ && $subsys=~/Z/;
$headerHost=$hostNum;
push @headers, $therest if !$gotHeadersFlag;
#print "HostNum: $hostNum TheRest: $therest\n";
}
else
{
# Once we see data from the host we got the header from, we're done setting it.
# but if an error with -cols (only discoverable at this point with older collectls)
# treat as a ^C.
next if $therest eq '';
if (!$gotHeadersFlag && $headerHost==$hostNum && scalar(@headers))
{
$gotHeadersFlag=1;
$ctrlCFlag=1 if !reformatHeaders();
}
# Typically the data piece contains a timestamp as first field, but if date is
# requested to be displayed as well we'll pull the time out of the first field
# in '$therest', later on. But if it IS plot format we always start with date/time
if (!$plotFlag)
{
($time, $therest)=split(/ /, $therest, 2);
}
else
{
($date, $time, $therest)=split(/ /, $therest, 3);
}
# since we know the instance of the last entry stored for this host, we now want the next one
# however, if the times have changed we need to reset to 0 since this is all new data. Also need
# to reset 'maxinst' to make sure we don't include any stale data which may also be in different
# positions.
my $bufptr=$hostVars[$hostNum]->{bufptr};
my $index=$hostVars[$hostNum]->{lastinst}->[$bufptr]+1;
#print "BUFPTR: $bufptr INDEX: $index TIME: $time LTIME: $hostVars[$hostNum]->{lasttime}->[$bufptr]\n";
if ($time ne $hostVars[$hostNum]->{lasttime}->[$bufptr])
{
$bufptr=($bufptr+1) % 2;
$hostVars[$hostNum]->{bufptr}=$bufptr;
$index=$hostVars[$hostNum]->{maxinst}->[$bufptr]=0;
}
$lastHost=$hostNum;
$hostVars[$hostNum]->{lasttime}->[$bufptr]=($plotFlag || $options!~/[dD]/) ? $time : (split(/\s+/, $therest))[0];
# Be sure to update sample BEFORE updating pointers
my $key=(split(/\s+/, $therest))[0];
$sample[$hostNum]->[$index]->[$bufptr]=($plotFlag || $timeFlag) ? "$time $therest": $therest;
#print "SAMPLE[$hostNum][$index][$bufptr]: $sample[$hostNum]->[$index]->[$bufptr]\n";
# when doing plot mode we always reconstruct the original record as we also do in non-plot
# mode when the user specifies a time format option. Remember, the ONLY time options can
# be set are in cols mode so that's why we don't have to add that to the test below.
$hostVars[$hostNum]->{lastinst}->[$bufptr]=$index;
$hostVars[$hostNum]->{maxinst}->[$bufptr]=$index if $index>$hostVars[$hostNum]->{maxinst}->[$bufptr];
print "B Host[$hostNum]: $host BUF: $bufptr MAXINST: $hostVars[$hostNum]->{maxinst}->[$bufptr] ".
"LASTINST: $hostVars[$hostNum]->{lastinst}->[$bufptr] TIME: $time LASTTIME: ".
"$hostVars[$hostNum]->{lasttime}->[$bufptr] KEY: $key\n" if $debug & 256
}
next;
}
# Sending socket must have gone away so clean it up
$remoteAddr=inet_ntoa((sockaddr_in(getpeername($filehandle)))[1]);
$sel->remove($filehandle);
$filehandle->close;
$numReporting--;
printf "Disconnected host #$hostNumMap{$filehandle}: $remoteAddr. %d remaining\n", $numReporting
if $debug & 1;
# Remove this address from @host which probably should have been built from $remoteAddr
# rather than name in record returned by collectl, but it's too late now
delete $host[$hostNumMap{$filehandle}];
# when all sockets have been closed, time to exit
if ($numReporting==0 && !($debug & 4))
{
$ctrlCFlag=1;
last;
}
}
}
}
}
$mySocket->close();
# this probably isn't necessary but just to be sure all the ssh sessions are dead,
# kill them off, noting since multiple ones would have to have unique ports, there
# is no danger of killing the wrong ones.
open PS, "ps axo pid,command|";
while (my $line=<PS>)
{
next if $line!~/$myReturnAddr:$port/;
# pid can have leading spaces
$line=~s/^\s+//;
my $pid=(split(/\s+/, $line))[0];
print "Killing ssh with pid: $pid\n" if $debug & 1;
`kill $pid`;
}
}
#################################
# P l a y b a c k M o d e
#################################
else
{
# Control-C trap
$SIG{"INT"}=\&sigInt;
my $sel = new IO::Select(STDIN);