root/lib/Resmon/Status.pm

Revision b8a0dde68f080c69c14356da7389df58b328801e, 12.8 kB (checked in by Mark Harrison <mark@omniti.com>, 10 years ago)

Add links from the index page to individual services

git-svn-id: https://labs.omniti.com/resmon/trunk@175 8c0face9-b7db-6ec6-c4b3-d5f7145c7d55

  • Property mode set to 100644
Line 
1 package Resmon::Status;
2
3 use strict;
4 use POSIX qw/:sys_wait_h/;
5 use IO::Handle;
6 use IO::File;
7 use IO::Socket;
8 use Socket;
9 use Fcntl qw/:flock/;
10 use IPC::SysV qw /IPC_PRIVATE IPC_CREAT IPC_RMID ftok S_IRWXU S_IRWXG S_IRWXO/;
11 use Data::Dumper;
12
13 my $SEGSIZE = 1024*256;
14 my $KEEPALIVE_TIMEOUT = 5;
15 my $REQUEST_TIMEOUT = 60;
16 sub new {
17   my $class = shift;
18   my $file = shift;
19   return bless {
20     file => $file
21   }, $class;
22 }
23 sub get_shared_state {
24   my $self = shift;
25   my $blob;
26   my $len;
27   return unless(defined($self->{shared_state}));
28   # Lock shared segment
29   # Read in
30   shmread($self->{shared_state}, $len, 0, length(pack('i', 0)));
31   $len = unpack('i', $len);
32   shmread($self->{shared_state}, $blob, length(pack('i', 0)), $len);
33   # unlock
34   my $VAR1;
35   eval $blob;
36   die $@ if ($@);
37   $self->{store} = $VAR1;
38   return $self->{store};
39 }
40 sub store_shared_state {
41   my $self = shift;
42   return unless(defined($self->{shared_state}));
43   my $blob = Dumper($self->{store});
44
45   # Lock shared segment
46   # Write state and flush
47   shmwrite($self->{shared_state}, pack('i', length($blob)),
48            0, length(pack('i', 0))) || die "$!";
49   shmwrite($self->{shared_state}, $blob, length(pack('i', 0)),
50            length($blob)) || die "$!";
51   # unlock
52 }
53 sub xml_kv_dump {
54   my $info = shift;
55   my $indent = shift || 0;
56   my $rv = '';
57   while(my ($key, $value) = each %$info) {
58     $rv .= " " x $indent;
59     if(ref $value eq 'HASH') {
60       $rv .= "<$key>\n";
61       $rv .= xml_kv_dump($value, $indent + 2);
62       $rv .= " " x $indent;
63       $rv .= "</$key>\n";
64     }
65     else {
66       $value =~ s/&/&amp;/g;
67       $value =~ s/</&lt;/g;
68       $value =~ s/>/&gt;/g;
69       $value =~ s/'/&apos;/g;
70       $rv .= "<$key>$value</$key>\n";
71     }
72   }
73   return $rv;
74 }
75 sub xml_info {
76   my ($module, $service, $info) = @_;
77   my $rv = '';
78   $rv .= "  <ResmonResult module=\"$module\" service=\"$service\">\n";
79   $rv .= xml_kv_dump($info, 4);
80   $rv .= "  </ResmonResult>\n";
81   return $rv;
82 }
83 sub dump_generic {
84   my $self = shift;
85   my $dumper = shift;
86   my $rv = '';
87   while(my ($module, $services) = each %{$self->{store}}) {
88     while(my ($service, $info) = each %$services) {
89       $rv .= $dumper->($module,$service,$info);
90     }
91   }
92   return $rv;
93 }
94 sub dump_oldstyle {
95   my $self = shift;
96   my $response = $self->dump_generic(sub {
97     my($module,$service,$info) = @_;
98     return "$service($module) :: $info->{state}($info->{message})\n";
99   });
100   return $response;
101 }
102 sub dump_xml {
103   my $self = shift;
104   my $response = <<EOF
105 <?xml version="1.0" encoding="UTF-8"?>
106 <?xml-stylesheet type="text/xsl" href="/resmon.xsl"?>
107 <ResmonResults>
108 EOF
109   ;
110   $response .= $self->dump_generic(\&xml_info);
111   $response .= "</ResmonResults>\n";
112   return $response;
113 }
114 sub get_xsl() {
115   my $response = <<EOF
116 <?xml version="1.0" encoding="ISO-8859-1"?>
117 <xsl:stylesheet version="1.0"
118     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
119 <xsl:template match="ResmonResults">
120 <html>
121 <head>
122     <title>Resmon Results</title>
123     <link rel="stylesheet" type="text/css" href="/resmon.css" />
124 </head>
125 <body>
126     <xsl:for-each select="ResmonResult">
127         <div class="item">
128                 <xsl:attribute name="class">
129                     item <xsl:value-of select="state" />
130                 </xsl:attribute>
131             <h1>
132                 <a>
133                     <xsl:attribute name="href">
134                         /<xsl:value-of select="\@module"
135                             />/<xsl:value-of select="\@service" />
136                     </xsl:attribute>
137                     <xsl:value-of select="\@module" /> -
138                     <xsl:value-of select="\@service" />
139                 </a>
140             </h1>
141             <h2>
142                 <xsl:value-of select="state"/>:
143                 <xsl:value-of select="message" />
144             </h2>
145             <ul>
146                 <li>Time taken for last check:
147                     <xsl:value-of select="last_runtime_seconds" /></li>
148                 <li>Last updated:
149                     <xsl:value-of select="last_update" /></li>
150             </ul>
151             <h2>Configuration</h2>
152             <table>
153                 <tr>
154                     <th>Name</th>
155                     <th>Value</th>
156                 </tr>
157                 <xsl:for-each select="configuration/*">
158                     <tr>
159                         <td><xsl:value-of select="name(.)" /></td>
160                         <td><xsl:value-of select="." /></td>
161                     </tr>
162                 </xsl:for-each>
163             </table>
164         </div>
165     </xsl:for-each>
166 </body>
167 </html>
168 </xsl:template>
169 </xsl:stylesheet>
170 EOF
171   ;
172   return $response;
173 }
174 sub get_css() {
175   my $response=<<EOF
176 body {
177     font-family: Verdana, Arial, helvetica, sans-serif;
178 }
179 h1 {
180     margin: 0;
181     font-size: 120%;
182 }
183
184 h2 {
185     margin: 0;
186     font-sizE: 110%;
187 }
188
189 .item {
190     border: 1px solid black;
191     padding: 1em;
192     margin: 2em;
193     background-color: #eeeeee;
194 }
195
196 .OK {
197     background-color: #afa;
198 }
199
200 .WARNING {
201     background-color: #ffa;
202 }
203
204 .BAD {
205     background-color: #faa;
206 }
207
208 table {
209     border: 1px solid black;
210     background-color: #eeeeee;
211     border-collapse: collapse;
212     margin: 1em;
213     font-size: 80%;
214 }
215
216 th {
217     font-size: 100%;
218     font-weight: bold;
219     background-color: black;
220     color: white;
221 }
222
223 td {
224     padding-left: 1em;
225     padding-right: 1em;
226 }
227
228 a {
229     text-decoration: none;
230 }
231 EOF
232   ;
233   return $response;
234 }
235 sub service {
236   my $self = shift;
237   my ($client, $req, $proto, $snip) = @_;
238   my $state = $self->get_shared_state();
239   if($req eq '/' or $req eq '/status') {
240     my $response .= $self->dump_xml();
241     $client->print(http_header(200, length($response), 'text/xml', $snip));
242     $client->print($response . "\r\n");
243     return;
244   } elsif($req eq '/status.txt') {
245     my $response = $self->dump_oldstyle();
246     $client->print(http_header(200, length($response), 'text/plain', $snip));
247     $client->print($response . "\r\n");
248     return;
249   } elsif($req eq '/resmon.xsl') {
250     my $response = $self->get_xsl();
251     $client->print(http_header(200, length($response), 'text/xml', $snip));
252     $client->print($response . "\r\n");
253     return;
254   } elsif($req eq '/resmon.css') {
255     my $response = $self->get_css();
256     $client->print(http_header(200, length($response), 'text/css', $snip));
257     $client->print($response . "\r\n");
258     return;
259   } else {
260     if($req =~ /^\/([^\/]+)\/(.+)$/) {
261       if(exists($self->{store}->{$1}) &&
262          exists($self->{store}->{$1}->{$2})) {
263         my $info = $self->{store}->{$1}->{$2};
264         my $response = qq^<?xml version="1.0" encoding="UTF-8"?>\n^;
265         my $response .= qq^<?xml-stylesheet type="text/xsl" href="/resmon.xsl"?>^;
266         $response .= "<ResmonResults>\n".
267                      xml_info($1,$2,$info).
268                      "</ResmonResults>\n";
269         $client->print(http_header(200, length($response), 'text/xml', $snip));
270         $client->print( $response . "\r\n");
271         return;
272       }
273     }
274   }
275   die "Request not understood\n";
276 }
277 sub http_header {
278   my $code = shift;
279   my $len = shift;
280   my $type = shift || 'text/xml';
281   my $close_connection = shift || 1;
282   return qq^HTTP/1.0 $code OK
283 Server: resmon
284 ^ . (defined($len) ? "Content-length: $len\n" : "") .
285     (($close_connection || !$len) ? "Connection: close\n" : "") .
286 qq^Content-Type: $type; charset=utf-8
287
288 ^;
289 }
290 sub serve_http_on {
291   my $self = shift;
292   my $ip = shift;
293   my $port = shift;
294   $ip = INADDR_ANY if(!defined($ip) || $ip eq '' || $ip eq '*');
295   $port ||= 81;
296
297   my $handle = IO::Socket->new();
298   socket($handle, PF_INET, SOCK_STREAM, getprotobyname('tcp'))
299     || die "socket: $!";
300   setsockopt($handle, SOL_SOCKET, SO_REUSEADDR, pack("l", 1))
301     || die "setsockopt: $!";
302   bind($handle, sockaddr_in($port, $ip))
303     || die "bind: $!";
304   listen($handle,SOMAXCONN);
305
306   $self->{zindex} = 0;
307   if (-x "/usr/sbin/zoneadm") {
308     open(Z, "/usr/sbin/zoneadm list -p |");
309     my $firstline = <Z>;
310     close(Z);
311     ($self->{zindex}) = split /:/, $firstline, 2;
312   }
313   $self->{http_port} = $port;
314   $self->{http_ip} = $ip;
315   $self->{ftok_number} = $port * (1 + $self->{zindex});
316
317   $self->{child} = fork();
318   if($self->{child} == 0) {
319     eval {
320       $SIG{'HUP'} = 'IGNORE';
321       while(my $client = $handle->accept) {
322         my $req;
323         my $proto;
324         my $close_connection;
325         local $SIG{ALRM} = sub { die "timeout\n" };
326         eval {
327           alarm($KEEPALIVE_TIMEOUT);
328           while(<$client>) {
329             alarm($REQUEST_TIMEOUT);
330             eval {
331               s/\r\n/\n/g;
332               chomp;
333               if(!$req) {
334                 if(/^GET \s*(\S+)\s*?(?: HTTP\/(0\.9|1\.0|1\.1)\s*)?$/) {
335                   $req = $1;
336                   $proto = $2;
337                   # Protocol 1.1 and high are keep-alive by default
338                   $close_connection = ($proto <= 1.0)?1:0;
339                 }
340                 elsif(/./) {
341                   die "protocol deviations.\n";
342                 }
343               }
344               else {
345                 if(/^$/) {
346                   $self->service($client, $req, $proto, $close_connection);
347                   last if ($close_connection);
348                   alarm($KEEPALIVE_TIMEOUT);
349                   $req = undef;
350                   $proto = undef;
351                 }
352                 elsif(/^\S+\s*:\s*.{1,4096}$/) {
353                   # Valid request header... noop
354                   if(/^Connection: (\S+)/) {
355                     if(($proto <= 1.0 && lc($2) eq 'keep-alive') ||
356                        ($proto == 1.1 && lc($2) ne 'close')) {
357                       $close_connection = 0;
358                     }
359                   }
360                 }
361                 else {
362                   die "protocol deviations.\n";
363                 }
364               }
365             };
366             if($@) {
367               print $client http_header(500, 0, 'text/plain', 1);
368               print $client "$@\r\n";
369               last;
370             }
371           }
372           alarm(0);
373         };
374         alarm(0) if($@);
375         $client->close();
376       }
377     };
378     if($@) {
379       print STDERR "Error in listener: $@\n";
380     }
381     exit(0);
382   }
383   close($handle);
384   return;
385 }
386 sub open {
387   my $self = shift;
388   return 0 unless(ref $self);
389   return 1 if($self->{handle});  # Alread open
390   if($self->{file} eq '-' || !defined($self->{file})) {
391     $self->{handle_is_stdout} = 1;
392     $self->{handle} = IO::File->new_from_fd(fileno(STDOUT), "w");
393     return 1;
394   }
395   $self->{handle} = IO::File->new("> $self->{file}.swap");
396   die "open $self->{file}.swap failed: $!\n" unless($self->{handle});
397   $self->{swap_on_close} = 1; # move this to a non .swap version on close
398   chmod 0644, "$self->{file}.swap";
399
400   unless(defined($self->{shared_state})) {
401     $self->{shared_state} = shmget(IPC_PRIVATE, $SEGSIZE,
402                                    IPC_CREAT|S_IRWXU|S_IRWXG|S_IRWXO);
403     die "$0: $!" if($self->{shared_state} == -1);
404   }
405   return 1;
406 }
407 sub store {
408   my ($self, $type, $name, $info) = @_;
409   %{$self->{store}->{$type}->{$name}} = %$info;
410   $self->{store}->{$type}->{$name}->{last_update} = time;
411   $self->store_shared_state();
412   if($self->{handle}) {
413     $self->{handle}->print("$name($type) :: $info->{state}($info->{message})\n");
414   } else {
415     print "$name($type) :: $info->{state}($info->{message})\n";
416   }
417 }
418 sub purge {
419     # This removes status information for modules that are no longer loaded
420
421     # Generate list of current modules
422     my %loaded = ();
423     my ($self, $config) = @_;
424     while (my ($type, $mods) = each(%{$config->{Module}}) ) {
425         $loaded{$type} = ();
426         foreach (@$mods) {
427             $loaded{$type}{$_->{'object'}} = 1;
428         }
429     }
430
431     # Debugging
432     #while (my ($key, $value) = each(%loaded) ) {
433     #    print STDERR "$key: ";
434     #    while (my ($mod, $dummy) = each (%$value) ) {
435     #        print STDERR "$mod ";
436     #    }
437     #    print "\n";
438     #}
439
440     # Compare $self->{store} with list of loaded modules
441     while (my ($type, $value) = each (%{$self->{store}})) {
442         while (my ($name, $value2) = each (%$value)) {
443             if (!exists($loaded{$type}) || !exists($loaded{$type}{$name})) {
444                 #print STDERR "$type $name\n";
445                 delete $self->{store}->{$type}->{$name};
446                 if (scalar(keys %{$self->{store}->{$type}}) == 0) {
447                     #print STDERR "$type has no more objects, deleting\n";
448                     delete $self->{store}->{$type};
449                 }
450             }
451         }
452     }
453 }
454 sub close {
455   my $self = shift;
456   return if($self->{handle_is_stdout});
457   $self->{handle}->close() if($self->{handle});
458   $self->{handle} = undef;
459   if($self->{swap_on_close}) {
460     unlink("$self->{file}");
461     link("$self->{file}.swap", $self->{file});
462     unlink("$self->{file}.swap");
463     delete($self->{swap_on_close});
464   }
465 }
466 sub DESTROY {
467   my $self = shift;
468   my $child = $self->{child};
469   if($child) {
470     kill 15, $child;
471     sleep 1;
472     kill 9, $child if(kill 0, $child);
473     waitpid(-1,WNOHANG);
474   }
475   if(defined($self->{shared_state})) {
476     shmctl($self->{shared_state}, IPC_RMID, 0);
477   }
478 }
479 1;
Note: See TracBrowser for help on using the browser.