summaryrefslogtreecommitdiff
path: root/example/ivystat.pl
blob: f81da881e2ced5fc876f41017f1e43e1ba4b9f71 (plain)
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
#!/usr/bin/perl -w
#
#	This program is free software; you can redistribute it and/or
#	modify it under the terms of the GNU GPL General Public License
#	as published by the Free Software Foundation; either version 2
#	of the License, or (at your option) any later version.
#
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program; if not, write to the Free Software
#	Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA,
#	or refer to http://www.gnu.org/copyleft/gpl.html
#

#TODO :
# ° pour les simili rpc : fichier de config avec des templates de question et des templates
#   de réponse pour qu'ivystat mesure les temps entre la question et la réponse
#
# ° version multithread pour ne pas ralentir les agents que l'on observe si
#   le traitement est long : pas possible partout car sous mandriva perl est compilé
#   sans support des threads par exemple.
#
# ° version avec une interface graphique mise à jour en temps reel ?


use strict;
use IvyN;
use Getopt::Long;
use Carp;



sub usage (;$);
sub statusFunc ($$$$$$$);
sub newMessageCb ($$);
sub writeLogs ();
sub sigHandler ();

my $appliname = "IVYSTAT.PL";
my %options;

#  my %regexpByApp = (); # $regexpByApp{"app"} = [liste de regexp]
my %appByRegexp = (); # $appByRegexp{"regexp"} = [{app1=>1 or 0 if unsubscribe, app2=>1or0, ...],
#			\&matchProcedure]
my %compteurByApp = (); # $compteurByApp{"app from"}->{"app to"}->[nb msg, nb octets]
my %appNameByhostAndPort = ();
my $startTime = time();
my $stopTime;

my $totalMess = 0;
my $totalBytes = 0;
my $nbActiveAgent = 0;
my $nbDeconnecteedAgent = 0;

my %sendMessByApp;
my %sendBytesByApp;
my %receiveMessByApp;
my %receiveBytesByApp;
my %connectedAppByAppFrom;
my %connectedAppByAppTo;



END { writeLogs ();}
$SIG{'QUIT'} = $SIG{'INT'}  = \&sigHandler;


# on traite la ligne de commande
GetOptions(\%options, "help", "bus:s", "file:s", "interval:i", "running:i");

usage () if (defined $options{help});
usage ("log file name is mandatory") unless defined  $options{file};

if ($options{file} eq '-') {
   open (LOG, ">&", STDOUT) ||  usage ("cannot output to stdout");
} elsif (!open (LOG, ">$options{file}")) {
  usage ("cannot create writable file $options{file}");
}

Ivy->init (-ivyBus => (defined $options{bus}) ? $options{bus} : undef,
	   -appName => $appliname,
	   -loopMode => 'LOCAL',
	   -messWhenReady => "$appliname READY"
	   );

my $Ivyobj = Ivy->new (-statusFunc => \&statusFunc);
$Ivyobj->start;

$Ivyobj->bindRegexp ('(.*)', [\&newMessageCb], 1);
$Ivyobj->repeat ($options{interval}*1000, [\&writeLogs]) if exists $options{interval};
$Ivyobj->after ($options{running}*1000, sub {exit 0;}) if exists $options{running};
$Ivyobj->mainLoop();


#==========================================================================================
#                _              _                     ______
#               | |            | |                   |  ____|
#         ___   | |_     __ _  | |_    _   _   ___   | |__     _   _   _ __     ___
#        / __|  | __|   / _` | | __|  | | | | / __|  |  __|   | | | | | '_ \   / __|
#        \__ \  \ |_   | (_| | \ |_   | |_| | \__ \  | |      | |_| | | | | | | (__
#        |___/   \__|   \__,_|  \__|   \__,_| |___/  |_|       \__,_| |_| |_|  \___|
sub statusFunc ($$$$$$$) {
  my ($ref_ready, $ref_nonReady, $ref_hashReady, $appname, $status, $host, $regexp) = @_;

  if ($status eq "new") {
    print  "$appname connected from $host\n";
    $appNameByhostAndPort{$host} = $appname;
    $nbActiveAgent ++;
    $sendMessByApp{$host} = 0;
    $sendBytesByApp{$host} = 0;
    $receiveMessByApp{$host} = 0;
    $receiveBytesByApp{$host} = 0;
    $connectedAppByAppFrom{$host} =0;
    $receiveMessByApp{$host} =0;
    #	$regexpByApp{$host} = [];
  } elsif ($status eq "died") {
    print  "$appname disconnected from $host\n";
    $nbDeconnecteedAgent ++;
    $nbActiveAgent --;
  } elsif ($status eq 'subscribing') {
    print  "$appname subscribed to '$regexp'\n";
    unless (exists $appByRegexp{$regexp}) {
      $appByRegexp{$regexp} = [{$host => 1},
			    #	sub {@{$_[1]} =  ${$_[0]} =~ /$regexp/i;}];
			    eval ('sub {@{$_[1]} =  ${$_[0]} =~ /$regexp/io;}')];
    } else {
      ${$appByRegexp{$regexp}->[0]}{$host} = 1;
    }
  } elsif ($status eq 'unsubscribing') {
    print  "$appname unsubscribed to '$regexp'\n";
    ${$appByRegexp{$regexp}->[0]}{$regexp} = 0;
  } elsif ($status eq 'filtered') {
    print  "$appname subscribed to *FILTERED* '$regexp'\n";
  } else {
    warn  "Bug: unkown status; $status in &statusFunc\n";
  }
}


#                                   __  __                         _____   _
#                                  |  \/  |                       / ____| | |
#         _ __     ___  __      __ | \  / |   ___   ___    ___   | |      | |__
#        | '_ \   / _ \ \ \ /\ / / | |\/| |  / _ \ / __|  / __|  | |      | '_ \
#        | | | | |  __/  \ V  V /  | |  | | |  __/ \__ \  \__ \  | |____  | |_) |
#        |_| |_|  \___|   \_/\_/   |_|  |_|  \___| |___/  |___/   \_____| |_.__/
sub newMessageCb ($$) {
  my ($app, $msg) = @_;
  my ($reg, $func, $hostRef, $appTo, @match, $bytes, $incMess, $incBytes);
  my $appFrom = "$app->[1]:$app->[2]";

  return unless defined $msg;
  study ($msg);
  #print ("DBG> $app->[0] [$app->[1]:$app->[2]] has sent \"$msg\"\n");

  foreach $reg (keys %appByRegexp) {
    ($hostRef, $func) = @{$appByRegexp{$reg}};
    &$func(\$msg, \@match) ;
    if (scalar (@match)) {
      $bytes = 0;
      map (($bytes+= length ($_)) && undef, @match);
      $compteurByApp{$appFrom} = {} unless (exists $compteurByApp{$appFrom});

      foreach $appTo (keys %$hostRef) {
	next if $appFrom eq $appTo;
	unless (exists $compteurByApp{$appFrom}->{$appTo}) {
	  $compteurByApp{$appFrom}->{$appTo} = [];
	  $connectedAppByAppTo{$appTo}++;
	  $connectedAppByAppFrom{$appFrom}++;
	}
	
	$incMess = $$hostRef{$appTo};
	$incBytes = $incMess ? $bytes : 0;
	$compteurByApp{$appFrom}->{$appTo}->[1] += $incBytes;
	$compteurByApp{$appFrom}->{$appTo}->[0] += $incMess;

	$totalMess += $incMess;
	$totalBytes += $incBytes;

	$sendMessByApp{$appFrom} += $incMess;
	$sendBytesByApp{$appFrom}+= $incBytes;
	$receiveMessByApp{$appTo} += $incMess;
	$receiveBytesByApp{$appTo} += $incBytes;

	# DEBUG
#	if ($$hostRef{$appTo}) {
#	  printf "DBG> %s@%s a envoyé %s [%s] à %s@%s\n", 
#		  $appNameByhostAndPort{$appFrom}, $appFrom, $msg, $bytes,
#		  $appNameByhostAndPort{$appTo}, $appTo;
#	}
	# END DEBUG
      }
    }
  }
}


#                           _    _             _                 __ _
#                          (_)  | |           | |               / _` |
#        __      __  _ __   _   | |_     ___  | |        ___   | (_| |  ___
#        \ \ /\ / / | '__| | |  | __|   / _ \ | |       / _ \   \__, | / __|
#         \ V  V /  | |    | |  \ |_   |  __/ | |____  | (_) |   __/ | \__ \
#          \_/\_/   |_|    |_|   \__|   \___| |______|  \___/   |___/  |___/
sub writeLogs ()
{
  # général :
  #  time, nb agent, nb mess, nb octets
  # details :
  #  pour chaque agent, par ordre de nb octets envoyés  :
  #   total : nb octets envoyés, nb mess envoyés, nb octets reçus, nb mess reçus
  #   pour chaque agents en receptions :
  #	 nb octets envoyés, nb mess envoyés,
  my (@sortedApp, $appf, $appt);

  # il faut que le filehandle LOG soit valide
  return unless fileno LOG;

  seek (LOG, 0, 0);
  $stopTime = time();
  my $stdout = select (LOG);
  printf "log from %s to %s (%d seconds)\n", localtime ($startTime).'',
          localtime ($stopTime).'', $stopTime-$startTime;
  print  "active:$nbActiveAgent, disconnected:$nbDeconnecteedAgent, " .
	 "messages:$totalMess, bytes:$totalBytes\n\n";

  goto "EXIT_writeLogs" unless scalar (%appNameByhostAndPort);

  @sortedApp = reverse sort {
    $sendBytesByApp{$a} <=> $sendBytesByApp{$b}
  } keys (%appNameByhostAndPort);

  foreach $appf (@sortedApp) {
    print "----------------------------------------------\n";
    printf "%s@%s ",$appNameByhostAndPort{$appf}, $appf;
    printf "has sent %d messages [%d bytes] to %d agents\n", $sendMessByApp{$appf},
      $sendBytesByApp{$appf}, $connectedAppByAppFrom{$appf}
	      if  $sendBytesByApp{$appf};
    printf "\t\t\ has received %d messages [%d bytes] from %d agents\n",
            $receiveMessByApp{$appf}, $receiveBytesByApp{$appf}, $connectedAppByAppTo{$appf}
	      if  $receiveMessByApp{$appf};

    foreach $appt (keys %{$compteurByApp{$appf}}) {
       printf "\t\t\t has sent %d messages [%d bytes] to %s@%s\n",
	 $compteurByApp{$appf}->{$appt}->[0], $compteurByApp{$appf}->{$appt}->[1],
	   $appNameByhostAndPort{$appt}, $appt;
     }
    print "\n\n";
  }

 EXIT_writeLogs:
  select ($stdout);
}


#                _     __ _   _    _                       _    _
#               (_)   / _` | | |  | |                     | |  | |
#         ___    _   | (_| | | |__| |   __ _   _ __     __| |  | |    ___   _ __
#        / __|  | |   \__, | |  __  |  / _` | | '_ \   / _` |  | |   / _ \ | '__|
#        \__ \  | |    __/ | | |  | | | (_| | | | | | | (_| |  | |  |  __/ | |
#        |___/  |_|   |___/  |_|  |_|  \__,_| |_| |_|  \__,_|  |_|   \___| |_|
sub sigHandler ()
{
  # ça parrait servir à rien, mais en fait le fait d'appeler exit dans le handler de signaux
  # permet d'appeler le bloc END{}, alors que sinon le ctrl C non trappé arrète l'execution sans
  # appeler le bloc END{}
  exit (0);
}

sub usage (;$) {
    print  "error : $_[0]\n" if defined $_[0];
    print  "ivystat [-h] [ -b <network>:<port> ] -i [interval] -r running time -f logfile\n";
    print  "   -h   print this help\n";
    print  "   -b   <network>:<port>\n";
    print  "        to defined the network adress and the port number\n";
    print  "        defaulted to 127:2010\n";
    print  "   -i   interval\n";
    print  "        interval in seconds between regeneration of logfile\n";
    print  "   -f   logfile\n";
    print  "        mandatory filename for the log, use - to dump on stdout\n";
    print  "   -r   running time\n";
    print  "        run 'running time' second, generate log and exit\n";
    print  "   \n";
    exit;
}