VBTK/Server.pm

filter: Statementstmt 90.0% 18 / 20 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.5% 25 / 27 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« VBTK/Actions/Email.pm ↑ Summary
1 #! /bin/perl
2 #############################################################################
3 #
4 # NOTE: This file under revision control using RCS
5 # Any changes made without RCS will be lost
6 #
7 # $Source: /usr/local/cvsroot/vbtk/VBTK/Server.pm,v $
8 # $Revision: 1.10 $
9 # $Date: 2002/03/02 00:53:55 $
10 # $Author: bhenry $
11 # $Locker: $
12 # $State: Exp $
13 #
14 # Purpose: A perl library used to define a VB server.
15 #
16 # Copyright (C) 1996 - 2002 Brent Henry
17 #
18 # This program is free software; you can redistribute it and/or
19 # modify it under the terms of version 2 of the GNU General Public
20 # License as published by the Free Software Foundation available at:
21 # http://www.gnu.org/copyleft/gpl.html
22 #
23 # This program is distributed in the hope that it will be useful,
24 # but WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 # GNU General Public License for more details.
27 #
28 #############################################################################
29 #
30 #
31 # REVISION HISTORY:
32 #
33 # $Log: Server.pm,v $
34 # Revision 1.10 2002/03/02 00:53:55 bhenry
35 # Documentation updates
36 #
37 # Revision 1.9 2002/02/20 19:25:18 bhenry
38 # *** empty log message ***
39 #
40 # Revision 1.8 2002/02/19 19:10:15 bhenry
41 # Added ability to pass email-related parms in constructor
42 #
43 # Revision 1.7 2002/02/13 07:39:28 bhenry
44 # Moved write_pid_file functionality from Common into Controller
45 #
46 # Revision 1.6 2002/02/08 02:16:04 bhenry
47 # *** empty log message ***
48 #
49 #
50  
51 package VBTK::Server;
52  
53 1 ▶use 5.004;
Subroutine BEGIN: called CC=1 SCAR=0.0
54 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
55 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
56 # I like using undef as a value so I'm turning off the uninitialized warnings
57 1 ▶no warnings qw(uninitialized);
Subroutine BEGIN: called CC=1 SCAR=0.0
58  
59 1 ▶use VBTK::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
60 1 ▶use VBTK::Actions;
Subroutine BEGIN: called CC=1 SCAR=0.0
61 0 ▶use VBTK::Actions::Email;
Subroutine BEGIN: called CC=1 SCAR=2.6
62 use VBTK::Actions::Email::Page;
63 use VBTK::Templates;
64 use VBTK::Objects;
65 use VBTK::Client;
66 use VBTK::RmtServer;
67 use VBTK::DynPod2Html;
68 use VBTK::AdminLog;
69 use File::Find;
70  
71 use POSIX;
72  
73 use Date::Manip;
74  
75 use VBTK::PHtml;
76 use VBTK::PHttpd;
77  
78 our $VERBOSE=$ENV{'VERBOSE'};
79 our @CHILD_PIDS;
80 our $SIGNAL_CAUGHT;
81 our $CURR_SERVER;
82  
83 # Make sure Date::Manip knows the timezone
84 &VBTK::Common::checkDateManipTZ();
85  
86 #-------------------------------------------------------------------------------
87 # Function: new
88 # Description: Object constructor. Allocates memory for all class members
89 # Input Parms: Configuration filename
90 # Output Parms: Pointer to class
91 #-------------------------------------------------------------------------------
92 sub new
93 {
94 my $type = shift;
95 my $self = {};
96 bless $self, $type;
97  
98 # Store all passed input name pairs in the object
99 $self->set(@_);
100  
101 my $defaultParms = {
102 LocalPort => $::VBPORT,
103 LocalAddr => undef,
104 ObjectDir => "$::VBHOME/vbobj",
105 DocRoot => "$::VBHOME/web",
106 ObjectPrefix => 'local',
107 ExternalURL => "$::VBURI/status.phtml",
108 SmtpHost => 'localhost',
109 EmailFrom => 'vbtk@settomydomain.com',
110 CompanyName => undef,
111 AdminEmail => undef,
112 Redirects => undef,
113 IndexNames => 'index.html,index.htm,index.phtml,matrix.phtml',
114 HousekeepingInterval => 60,
115 UseWatchDog => undef,
116 ForkRrdUpdate => 0,
117 SyncDirs => 'conf,examples,web,bin,etc',
118 SyncExclude => '/conf/\.|/CVS/|/pod2htm.*~~',
119 };
120  
121 # Validate the passed parameters
122 $self->validateParms($defaultParms) || &fatal("Exiting");
123  
124 # Check for a valid docRoot directory
125 &fatal("Can't find DocRoot directory '$self->{DocRoot}'")
126 unless (-d $self->{DocRoot});
127  
128 # Check for a valid object dir, if not found, try to create it.
129 if (! -d $self->{ObjectDir})
130 {
131 mkdir $self->{ObjectDir} ||
132 fatal("Can't create ObjectDir directory '$self->{ObjectDir}'");
133 }
134  
135 # Make a list of urls which change data in the engine. These should be
136 # processed without forking
137 # my $dontForkList = [ 'setStatusRaw.phtml' ];
138  
139 # Changed to not do any forking, since it doesn't appear to be any faster.
140 my $dontForkList = [ '.*' ];
141  
142 # Pass most of the parameters on to create a PHttpd object
143 $self->{phttpd} = new VBTK::PHttpd(
144 LocalPort => $self->{LocalPort},
145 LocalAddr => $self->{LocalAddr},
146 DocRoot => $self->{DocRoot},
147 Handlers => $self->{Handlers},
148 IndexNames => $self->{IndexNames},
149 Redirects => $self->{Redirects},
150 DontForkList => $dontForkList
151 );
152  
153 &fatal("Exiting") unless ($self->{phttpd});
154  
155 # Now create the top-level node in the VBTK::Objects hierarchy.
156 &log("Setting up object hierarchy");
157 $self->{vbObj} = new VBTK::Objects(
158 Name => $::MASTER_NODE,
159 SegmentName => $::MASTER_NODE,
160 ObjectDir => $self->{ObjectDir},
161 ExternalURL => $self->{ExternalURL},
162 DefaultPrefix => $self->{ObjectPrefix},
163 ForkRrdUpdate => $self->{ForkRrdUpdate},
164 );
165
166 # Setup some global values for the Sendmail module
167 $Mail::Sendmail::mailcfg{smtp} = [ $self->{SmtpHost} ] if ($self->{SmtpHost});
168 $Mail::Sendmail::mailcfg{from} = $self->{EmailFrom} if ($self->{EmailFrom});
169
170 # Setup an array to store a list of remote servers to show locally.
171 $self->{showRemoteServerMatrixList} = [];
172  
173 return $self;
174 }
175  
176 #-------------------------------------------------------------------------------
177 # Function: addRemoteServer
178 # Description: Setup the connection to any remote VB servers
179 # Input Parms:
180 # Output Parms:
181 #-------------------------------------------------------------------------------
182 sub addRemoteServer
183 {
184 my $self = shift;
185 my $LocalPort = $self->{LocalPort};
186 my $LocalAddr = $self->{LocalAddr};
187 my $Interval = $self->{HousekeepingInterval};
188 my $showRemoteServerMatrixList = $self->{showRemoteServerMatrixList};
189 my $localURI = ($LocalAddr) ? "http://$LocalAddr:$LocalPort" :
190 "http://$::HOST:$LocalPort";
191
192 my %args = @_;
193  
194 # If the 'ShowMatrixLocally' parm was specified, then add the server URI to
195 # the list of matrices to show on the local instance.
196 push(@{$showRemoteServerMatrixList},$args{RemoteURI})
197 unless ($args{DontShowMatrix});
198 delete $args{DontShowMatrix};
199  
200 # Pass along the passed parameters to the RmtServer class
201 my $rmtServer = new VBTK::RmtServer(
202 LocalURI => $localURI,
203 Interval => $Interval,
204 %args,
205 );
206  
207 (0);
208 }
209  
210 #-------------------------------------------------------------------------------
211 # Function: addTemplate
212 # Description: Add a template to the template list.
213 # Input Parms:
214 # Output Parms:
215 #-------------------------------------------------------------------------------
216 sub addTemplate
217 {
218 my $self = shift;
219 my $vbObj = $self->{vbObj};
220  
221 my $template = new VBTK::Templates(@_);
222 $vbObj->addObjectTemplate($template);
223  
224 ($template);
225 }
226  
227  
228 #-------------------------------------------------------------------------------
229 # Function: addAction
230 # Description: Add an action to the template list.
231 # Input Parms:
232 # Output Parms:
233 #-------------------------------------------------------------------------------
234 sub addAction
235 {
236 my $self = shift;
237 my $vbObj = $self->{vbObj};
238 my $action = $vbObj->addAction(@_);
239  
240 ($action);
241 }
242  
243 #-------------------------------------------------------------------------------
244 # Function: run
245 # Description: Begin listening for and handling requests
246 # Input Parms:
247 # Output Parms:
248 #-------------------------------------------------------------------------------
249 sub run
250 {
251 my $self = shift;
252 my $returnAfter = shift;
253 my $sock = $self->{sock};
254 my $Interval = $self->{HousekeepingInterval};
255 my $UseWatchDog = $self->{UseWatchDog};
256 my $vbObj = $self->{vbObj};
257 my $phttpd = $self->{phttpd};
258 my ($pid);
259  
260 my ($status,$htmlStruct,$now,$alarmTime,$maxWaitTime,$subReturnAfter,$timeLeft);
261  
262 # Add a default template. We always have to match at least one.
263 $self->addTemplate (
264 Pattern => '.*',
265 ExpireAfter => undef,
266 StatusHistoryLimit => '50',
267 Description => qq( No matching template - Using defaults ) );
268  
269 # Setup signal handlers
270 $SIG{INT} = \&catchSignal;
271 $SIG{TERM} = \&catchSignal;
272  
273 # If the watchdog option was specified, then fork a child process to handle
274 # the VBTK::Server duties and re-start it if it dies.
275 if($UseWatchDog)
276 {
277 # Loop forever, restarting the server process as needed
278 while($pid = fork)
279 {
280 # This is the parent, so just wait for the child to die.
281 # @CHILD_PIDS = ($pid);
282 waitpid($pid,0);
283 &error("VBTK::Server process exited abnormally - watchdog will restart");
284 sleep 5;
285 }
286  
287 &fatal("Can't fork - $!") if(! defined $pid);
288 }
289  
290 # Import all objects from the VBTKObj directory
291 $vbObj->importObjects();
292  
293 &log("Accepting connections");
294 my $lastHousekeepingTime = time;
295  
296 # Calculate when to return from this routine, if the 'returnAfter' value
297 # was set.
298 my $returnTime = time + $returnAfter;
299  
300 # Send the heartbeat first.
301 $self->forkHeartbeat;
302
303 # Store the current server object in a global variable
304 $CURR_SERVER = $self;
305  
306 # Accept and process connections
307 for(;;)
308 {
309 # Calculate how much time left before we have to return to caller
310 $timeLeft = $returnTime - time if ($returnAfter);
311  
312 # Calculate how long to let the phttpd daemon handle requests before
313 # returning to this loop.
314 $subReturnAfter = $Interval - (time - $lastHousekeepingTime);
315  
316 # Don't set the subReturnAfter be larger than timeLeft
317 $subReturnAfter = $timeLeft if (($returnAfter) && ($timeLeft < $subReturnAfter));
318 $phttpd->run($subReturnAfter);
319  
320 # Check for any signals previously caught
321 &catchSignal($SIGNAL_CAUGHT) if (defined $SIGNAL_CAUGHT);
322  
323 &log("Doing housekeeping") if ($VERBOSE > 1);
324  
325 $lastHousekeepingTime = time;
326  
327 # Do housekeeping
328 $vbObj->checkForExpiration();
329 &VBTK::Actions::triggerAll();
330  
331 # Check for any signals previously caught
332 &catchSignal($SIGNAL_CAUGHT) if (defined $SIGNAL_CAUGHT);
333  
334 # Cleanup zombies
335 while(($pid = waitpid(-1,&WNOHANG)) > 0)
336 {
337 &log("VBTK::Server - Reaping pid $pid") if ($VERBOSE > 1);
338 }
339
340 # If we've exceeded our time limit then return
341 if(($returnAfter)&&(time >= $returnTime))
342 {
343 &log("VBTK::Server::run, time to return") if ($VERBOSE > 1);
344 undef $CURR_SERVER;
345 return 0;
346 }
347 }
348 }
349  
350 #-------------------------------------------------------------------------------
351 # Function: getSyncList
352 # Description: Build a list of file objects for all files specified in the
353 # SyncInclude and SyncExclude strings.
354 # Input Parms: None
355 # Output Parms: Reference to an array of file objects to be syncronized, VBHOME
356 #-------------------------------------------------------------------------------
357 sub getSyncList
358 {
359 my $self = shift;
360
361 # If no reference was passed then use the value in the global variable
362 # $CURR_SERVER.
363 if((! defined $self) || (! ref($self)))
364 {
365 $self = $CURR_SERVER || return undef;
366 }
367
368 my $SyncDirs = $self->{SyncDirs};
369 my $SyncExclude = $self->{SyncExclude};
370 my $currSyncListIndex = $self->{currSyncListIndex} = {};
371 my ($fileObj,$fileName,@fileObjList);
372  
373 # Make sure a valid list of directories was passed.
374 if(! $SyncDirs)
375 {
376 &error("SyncDirs parm must be set before calling 'buildSyncList'");
377 return undef;
378 }
379  
380 # If an array ref was passed for SyncDirs, then just use it. If it's a string,
381 # then split it at ','.
382 my @syncDirs = (ref($SyncDirs) eq 'ARRAY') ? @{$SyncDirs} : split(/,/,$SyncDirs);
383
384 # Also, add VBHOME onto the front of each directory.
385 grep(s/^/$::VBHOME\// , @syncDirs);
386  
387 &log("Building list of dirs to sync from @syncDirs") if ($VERBOSE > 1);
388
389 # Setup a subroutine for the call to 'find'.
390 my $filter = sub {
391 # Skip if not a file, or if a symlink, or if matches the exclude pattern
392 return if (! -f or -l or (defined $SyncExclude && /$SyncExclude/));
393  
394 # Create a file object for this file and load it's 'stat' info
395 if($fileObj = new VBTK::File ($_))
396 {
397 push(@fileObjList,$fileObj);
398 $fileName = $fileObj->getFileName();
399 $currSyncListIndex->{$fileName} = 1;
400 $fileObj->loadStat();
401 &log("Including file $fileName") if ($VERBOSE > 2);
402 }
403 (0);
404 };
405  
406 # Run the find command
407 &find({ wanted => $filter, no_chdir => 1},@syncDirs);
408  
409 # Return a list of file objects to sync
410 (@fileObjList);
411 }
412  
413 #-------------------------------------------------------------------------------
414 # Function: getSyncFileObj
415 # Description: Retrieve the specified file after making sure that it's in the
416 # allowed Sync list.
417 # Input Parms: None
418 # Output Parms: Reference to an array of file objects to be syncronized, VBHOME
419 #-------------------------------------------------------------------------------
420 sub getSyncFileObj
421 {
422 my $self = shift;
423 my $fileName = shift;
424 # If nothing was passed in, then just return
425 return undef unless ($self);
426
427 # If no reference was passed then use the value in the global variable
428 # $CURR_SERVER and load the first passed value into filename.
429 if(! ref($self))
430 {
431 $fileName = $self;
432 $self = $CURR_SERVER || return undef;
433 }
434
435 # If we couldn't determine the requested filename, then just return undef
436 return undef unless ($fileName);
437
438 # Now see if the file really exists and cause an error if not.
439 if(! -f $fileName)
440 {
441 &error("Can't find requested file '$fileName' in call to getSyncFile");
442 return undef;
443 }
444
445 my $currSyncListIndex = $self->{currSyncListIndex};
446  
447 # See if the file is in the sync list, if not then error out.
448 if(! $currSyncListIndex->{$fileName})
449 {
450 &error("Requested file '$fileName' is not in allowed sync list");
451 return undef;
452 }
453
454 # If we've made it this far, then let's load up the object.
455 my $fileObj = new VBTK::File ($fileName);
456 $fileObj->load() || return undef;
457  
458 ($fileObj);
459 }
460  
461 #-------------------------------------------------------------------------------
462 # Function: forkHeartbeat
463 # Description: Fork off a child process to transmit any heartbeat messages
464 # Input Parms: None
465 # Output Parms: None
466 #-------------------------------------------------------------------------------
467 sub forkHeartbeat
468 {
469 my $self = shift;
470 my $Interval = $self->{HousekeepingInterval};
471  
472 # See how many remote servers were configured and if none, then don't
473 # fork the heartbeat process.
474 my $RemoteServerCount = &VBTK::RmtServer::getCount();
475 return unless ($RemoteServerCount > 0);
476  
477 my($pid,$nextHeartbeat,$sleepTime);
478  
479 # Parent process
480 if ($pid = fork)
481 {
482 &log("Forked heartbeat process - pid $pid") if ($VERBOSE > 1);
483 # push(@CHILD_PIDS,$pid);
484 }
485 # Child process
486 elsif (defined $pid)
487 {
488 # Set signal handlers back to defaults
489 $SIG{INT} = 'DEFAULT';
490 $SIG{TERM} = 'DEFAULT';
491  
492 for(;;)
493 {
494 $nextHeartbeat = time + $Interval;
495 &VBTK::RmtServer::sendAllHeartbeats;
496 $sleepTime = $nextHeartbeat-time;
497 sleep $sleepTime if ($sleepTime > 0);
498 }
499 exit 0;
500 }
501 else
502 {
503 &fatal("Can't fork heartbeat process - $!")
504 }
505 (0);
506 }
507  
508 #-------------------------------------------------------------------------------
509 # Function: catchSignal
510 # Description: Handle any INT or TERM signals.
511 # Input Parms: None
512 # Output Parms: None
513 #-------------------------------------------------------------------------------
514 sub catchSignal
515 {
516 my ($signal) = @_;
517 my ($pgrp);
518  
519 print STDOUT "Caught signal $signal\n";
520  
521 # Ignore all but TERM and INT signals
522 if($signal =~ /^TERM|^INT/)
523 {
524 # If signal was caught once already, then kill all child procs and
525 # exit immediately
526 if($SIGNAL_CAUGHT eq $signal)
527 {
528 # Now kill anything else in the process group before we exit
529 $SIG{'TERM'} = 'IGNORE';
530  
531 # Run 'getpgrp' in an eval, just in case it's not supported
532 eval { $pgrp = getpgrp; };
533  
534 if ($pgrp > 0)
535 {
536 print STDOUT "Killing pgrp $pgrp\n";
537 kill 15, -$pgrp;
538 }
539  
540 exit(1);
541 }
542 # Otherwise, just mark the signal as caught, so that the main program
543 # can exit when it's convenient.
544 else
545 {
546 $SIGNAL_CAUGHT = $signal;
547 }
548 }
549 }
550  
551 # Simple Get Methods
552 sub getCompanyName { my $self = shift || $CURR_SERVER; $self->{CompanyName}; }
553 sub getAdminEmail { my $self = shift || $CURR_SERVER; $self->{AdminEmail}; }
554 sub getShowRemoteServerMatrixList {
555 my $self = shift || $CURR_SERVER; @{$self->{showRemoteServerMatrixList}} };
556  
557 1;
558 __END__
« VBTK/Actions/Email.pm ↑ Summary