VBTK/Controller.pm untested

filter: Statementstmt 0.0% 0 / 196 Branchbran 0.0% 0 / 64 Conditioncond 0.0% 0 / 34 MC/DCmcdc 0.0% 0 / 21 Subroutinesub 0.0% 0 / 17 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 339 CC 33 SCAR 41.7
CC
33
Cov
0%
doSync
132.0
run
110.0
doStart
56.0
CRAP 64.6
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/Controller.pm,v $
8 # $Revision: 1.12 $
9 # $Date: 2002/03/04 20:53:06 $
10 # $Author: bhenry $
11 # $Locker: $
12 # $State: Exp $
13 #
14 # Purpose: A common perl library used to start and stop the vb
15 # monitoring processes.
16 #
17 # Copyright (C) 1996 - 2002 Brent Henry
18 #
19 # This program is free software; you can redistribute it and/or
20 # modify it under the terms of version 2 of the GNU General Public
21 # License as published by the Free Software Foundation available at:
22 # http://www.gnu.org/copyleft/gpl.html
23 #
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 # GNU General Public License for more details.
28 #
29 #############################################################################
30 #
31 #
32 # REVISION HISTORY:
33 #
34 # $Log: Controller.pm,v $
35 # Revision 1.12 2002/03/04 20:53:06 bhenry
36 # *** empty log message ***
37 #
38 # Revision 1.11 2002/03/04 16:49:09 bhenry
39 # Changed requirement back to perl 5.6.0
40 #
41 # Revision 1.10 2002/03/02 00:53:54 bhenry
42 # Documentation updates
43 #
44 # Revision 1.9 2002/02/13 07:38:15 bhenry
45 # Moved write_pid_file functionality from Common into Controller
46 #
47 # Revision 1.8 2002/02/09 08:47:14 bhenry
48 # Major overhaul to better support syncing
49 #
50 # Revision 1.7 2002/02/08 02:16:04 bhenry
51 # *** empty log message ***
52 #
53 # Revision 1.6 2002/01/26 06:15:59 bhenry
54 # *** empty log message ***
55 #
56 # Revision 1.5 2002/01/25 07:18:22 bhenry
57 # Added call to checkDateManipTZ
58 #
59  
60 package VBTK::Controller;
61  
62 use 5.6.0;
63 use strict;
64 use warnings;
65 # I like using undef as a value so I'm turning off the uninitialized warnings
66 no warnings qw(uninitialized);
67  
68 use VBTK::Common;
69 use VBTK::Client;
70 use VBTK::File;
71 use POSIX "sys_wait_h";
72 use FileHandle;
73 use Getopt::Std;
74  
75 our $VERBOSE=$ENV{'VERBOSE'};
76  
77 #-------------------------------------------------------------------------------
78 # Function: new
79 # Description: Object constructor. Allocates memory for all class members
80 # Input Parms: Configuration filename
81 # Output Parms: Pointer to class
82 #-------------------------------------------------------------------------------
83 sub new
84 {
85 my $type = shift;
86 my $self = {};
87 bless $self, $type;
88  
89 &log("Creating new controller") if ($VERBOSE);
90  
91 # Store all passed input name pairs in the object
92 $self->set(@_);
93  
94 # Setup a hash of default parameters
95 my $defaultParms = {
96 MasterVBServer => $::REQUIRED,
97 SlaveVBServers => undef,
98 LogDir => $::VBLOGS,
99 };
100  
101 # Run a validation on the passed parms, using the default parms
102 $self->validateParms($defaultParms) || &fatal("Exiting");
103
104 # Setup a place to store VBServerURI's
105 $self->{VBServerURIHash} = {};
106
107 # Setup an index of SlaveVBServers after splitting the SlaveVBServers value
108 # into an array if it isn't already one.
109 my $slaveList = $self->{SlaveVBServers};
110 $slaveList = [ split(/[\s,]+/,$slaveList) ] if (ref($slaveList) ne 'ARRAY');
111 $self->{slaveVBServerIdx} = { map { $_ => 1 } @{$slaveList} };
112 $self->{isSlave} = $self->{slaveVBServerIdx}->{$::HOST};
113  
114 $self;
115 }
116  
117 #-------------------------------------------------------------------------------
118 # Function: addHostGroup
119 # Description: Add a group of hosts which share the same VBServer.
120 # Input Parms: None
121 # Output Parms: None
122 #-------------------------------------------------------------------------------
123 sub addHostGroup
124 {
125 my $self = shift;
126 my $VBServerURIHash = $self->{VBServerURIHash};
127 my %args = @_;
128
129 my $defaultParms = {
130 VBServerURI => $::REQUIRED,
131 HostList => $::REQUIRED,
132 };
133
134 # Run a validation on the passed parms, using the default parms.
135 &validateParms(\%args,$defaultParms) || &fatal("Exiting");
136  
137 my $HostList = $args{HostList};
138 my $VBServerURI = $args{VBServerURI};
139 my ($host,$progList);
140  
141 # Make sure hostlist is a reference to a hash
142 if (ref($HostList) ne 'HASH')
143 {
144 &fatal("HostList parm must be a reference to a HASH");
145 }
146  
147 foreach $host (keys %{$HostList})
148 {
149 # Check to see if this host was already defined somewhere else
150 if ($VBServerURIHash->{$host})
151 {
152 &fatal("Host '$host' cannot be listed twice in the Controller config!");
153 }
154
155 # Store the VBServerURI to use for this host
156 $VBServerURIHash->{$host} = $VBServerURI;
157  
158 # Just skip to the next one if we're not on this host.
159 next unless ($host eq $::HOST);
160
161 # Set the VBURI variable based on the VBServerURI
162 $self->{vbServerURI} = $VBServerURI;
163  
164 # If the progList isn't already an array, then make it one using split
165 $progList = $HostList->{$host};
166 $progList = [ split(/[\s,]+/,$progList) ] if (ref($progList) ne 'ARRAY');
167 $self->{progList} = $progList;
168  
169 # Mark each specified program as being configured to run on this host
170 $self->{canRun} = { map { $_ => 1 } @{$progList} };
171 }
172 }
173  
174 #-------------------------------------------------------------------------------
175 # Function: run
176 # Description: Start/stop the specified programs
177 # Input Parms: None
178 # Output Parms: None
179 #-------------------------------------------------------------------------------
180 sub run
181 {
182 my $self = shift;
183 my $LogDir = $self->{LogDir};
184 my $canRun = $self->{canRun};
185 my $progList = $self->{progList};
186 my ($alias,$cmd,$prog);
187  
188 # Make sure that fork works
189 &testFork || die "Unable to 'fork', can't continue";
190  
191 # Get the basename of the name this program was started with
192 $0 =~ /([^\/]+)$/;
193 $alias = $1;
194  
195 # If program was called as anything other than 'pmc' (for example as a
196 # symbolic link named 'start') then assume the name is a command.
197 $cmd = $alias if (($alias ne '')&&($alias =~ /^(start|stop|restart|sync)$/));
198  
199 # If program was not called with a different name, then use the first
200 # command line argument as the command
201 $cmd ||= shift(@ARGV);
202  
203 # If no command was specified, then die, showing the usage
204 &show_usage if(!$cmd);
205  
206 # Switch to the VBCONF directory
207 chdir "$::VBCONF" or die "Can't cd to $::VBCONF: $!\n";
208  
209 # Create a log dir if it doesn't exist
210 mkdir $LogDir, 0755 unless (-d $LogDir);
211  
212 # If there are still entries on the command line, then override the default
213 # program list
214 if (@ARGV > 0)
215 {
216 # Make sure everything listed on the command line is configured to
217 # run on this host.
218 foreach $prog (@ARGV)
219 {
220 &fatal("$prog is not configured to run on $::HOST")
221 if (! $canRun->{$prog});
222 }
223  
224 # Now store it back in the object
225 $self->{progList} = [ @ARGV ];
226 }
227  
228 if ($cmd eq 'start') { $self->doStart; }
229 elsif ($cmd eq 'stop') { $self->doStop; }
230 elsif ($cmd eq 'restart') { $self->doStop; $self->doStart; }
231 elsif ($cmd eq 'sync') { $self->doSync; }
232 else { &show_usage; }
233  
234 (0);
235 }
236  
237 #-------------------------------------------------------------------------------
238 # Function: show_usage
239 # Description: Show the program usage statement
240 # Input Parms: None
241 # Output Parms: None
242 #-------------------------------------------------------------------------------
243 sub show_usage
244 {
245 print STDOUT "Usage: $0 <start|stop|restart|sync>\n";
246 exit 1;
247 }
248  
249 #-------------------------------------------------------------------------------
250 # Function: doStop
251 # Description: For each program specified, search for a corresponding '.pid'
252 # file and kill all processes specified there which correspond
253 # to the current server.
254 # Input Parms: None
255 # Output Parms: None
256 #-------------------------------------------------------------------------------
257 sub doStop
258 {
259 my $self = shift;
260 my $progList = $self->{progList};
261 my $LogDir = $self->{LogDir};
262 my ($pidFile,@pidList,$prog);
263  
264 # Step through each configured program
265 foreach $prog (@{$progList})
266 {
267 $pidFile = "$LogDir/$prog.$::HOST.pid";
268  
269 if (-f $pidFile )
270 {
271 # Read in a list of pids to kill
272 open(PID,"< $pidFile") or
273 &fatal("Cant read '$pidFile'");
274 @pidList = grep(s/\s*//g || 1,<PID>);
275 close(PID);
276  
277 # Make sure we don't kill ourself
278 my $mypid = $$;
279 @pidList = grep(! /^$mypid$/, @pidList);
280  
281 print STDOUT "Stopping $prog - pid @pidList\n";
282 kill 15, @pidList;
283 unlink($pidFile);
284 }
285 }
286 }
287  
288 #-------------------------------------------------------------------------------
289 # Function: doStart
290 # Description: For each program specified startup the program.
291 # Input Parms: None
292 # Output Parms: None
293 #-------------------------------------------------------------------------------
294 sub doStart
295 {
296 my $self = shift;
297 my $progList = $self->{progList};
298 my $vbServerURI = $self->{vbServerURI};
299 my $LogDir = $self->{LogDir};
300 my ($logFile,$prog,$timestamp,$pid,$pidFileObj);
301  
302 # For each of the startable programs
303 foreach $prog (@{$progList})
304 {
305 # Check to see if there is already a '.pid' file, indicating that either the
306 # program is still running, or it terminated abnormally.
307 if (-f "$LogDir/$prog.$::HOST.pid")
308 {
309 print STDOUT "\nSome '$prog' processes may still be running\n";
310 print STDOUT "Use 'stop' to clear all processes first\n";
311 next;
312 }
313  
314 $logFile = "$LogDir/$prog.$::HOST.log";
315 $pidFileObj = new VBTK::File("$LogDir/$prog.$::HOST.pid");
316 $timestamp = &log_datestamp;
317 $timestamp =~ s/:/-/g;
318  
319 print STDOUT "\n";
320  
321 if (-f "$logFile")
322 {
323 &log("Renaming $logFile to $logFile.$timestamp");
324 rename $logFile, "$logFile.$timestamp";
325 }
326  
327 &fatal("Can't read '$::VBCONF/$prog'") unless (-f "$::VBCONF/$prog");
328  
329 # Parent process
330 if($pid = fork)
331 {
332 &log("Started '$::VBCONF/$prog' - pid $pid");
333 }
334 # Child process
335 elsif(defined $pid)
336 {
337 # Insulate this process from the vbc controller process
338 setpgrp(0,$$);
339  
340 # Write the current pid out to the pid file
341 $pidFileObj->put("$$\n") || &fatal("Exiting");
342
343 # Set the VBURI environment variable
344 $ENV{VBURI} = $vbServerURI if ($vbServerURI);
345  
346 # Close STDOUT and STDIN and make a copy of STDERR
347 open(OLDSTDERR, ">&STDERR");
348 STDOUT->close();
349 STDIN->close();
350  
351 # Redirect stdout to the logfile and setup autoflush
352 open(STDOUT, '>', "$logFile") ||
353 die("Can't write to logFile '$logFile'");
354 open(STDERR, ">&STDOUT") ||
355 die("Can't redirect STDERR to '$logFile'");
356 STDOUT->autoflush(1);
357 STDERR->autoflush(1);
358  
359 # Close the old STDERR
360 OLDSTDERR->close();
361  
362 # Execute the program
363 exec "$^X", "$::VBCONF/$prog" ||
364 &fatal("Can't run '$^X $::VBCONF/$prog' - $!");
365 # do $::VBCONF/$prog || &error("Can't run '$::VBCONF/$prog' - $!$@");
366 }
367 else
368 {
369 &fatal("Can't fork!");
370 }
371 }
372 }
373  
374 #-------------------------------------------------------------------------------
375 # Function: doSync
376 # Description: Sync files from the VB Server
377 # Input Parms: None
378 # Output Parms: Number of files updated
379 #-------------------------------------------------------------------------------
380 sub doSync
381 {
382 my $VBServerURI;
383  
384 # If we're passed a reference, then it's an object
385 if(ref($_[0]))
386 {
387 my $self = shift;
388 my $VBServerURIHash = $self->{VBServerURIHash};
389 my $MasterVBServer = $self->{MasterVBServer};
390 my $isSlave = $self->{isSlave};
391 $VBServerURI = $VBServerURIHash->{$::HOST} || $::VBURI;
392  
393 # If this is a slave server, then ignore the setting for the VBServerURI
394 # and instead use the URI of the MasterVBServer, since that's where we
395 # should be syncing files from.
396 $VBServerURI = $VBServerURIHash->{$MasterVBServer} if ($isSlave);
397  
398 # If we're on the master VBServer, then there's no point in syncing onto
399 # ourself.
400 if($MasterVBServer eq $::HOST)
401 {
402 &fatal("Can't use 'sync' command on Master Server");
403 }
404 }
405 # Otherwise, they're probably passing in a URI to sync from
406 else
407 {
408 $VBServerURI = shift;
409 }
410  
411 # Skip the sync if we weren't able to determine a remote URI
412 if(! $VBServerURI)
413 {
414 &log("Can't determine VBServerURI, skipping sync");
415 return undef;
416 }
417
418 # Try to connect to the VBServer
419 &log("Setting up VBClient connection to $VBServerURI") if ($VERBOSE);
420 my $vbClientObj = new VBTK::Client(RemoteURI => $VBServerURI);
421  
422 if (! $vbClientObj)
423 {
424 &error("Can't setup VBClient connection to $VBServerURI");
425 return undef;
426 }
427  
428 # Get a list of file objects to sync.
429 my ($rmtVBHome,@syncList) = $vbClientObj->getSyncList();
430  
431 if (@syncList < 1)
432 {
433 &error("Can't retrieve sync list from $VBServerURI, skipping sync");
434 return undef;
435 }
436
437 # Step through the sync list, comparing files and syncing the ones which are
438 # out of sync.
439 my $filesChangedCount = 0;
440 my($fileObj,$fileName,$origFileName,$fullFileObj);
441 foreach $fileObj (@syncList)
442 {
443 # Adjust the base path if VBHOME is different on this machine
444 $fileObj->changeBasePath($::VBHOME);
445 $fileName = $fileObj->getFileName();
446
447 # Skip to the next file unless there are differences
448 next unless ($fileObj->hasChanged());
449
450 # See if the local file is newer and if so, then skip it
451 if($fileObj->isNewer())
452 {
453 &log("Warning, local file '$fileName' is newer than on VBServer, skipping sync");
454 next;
455 }
456
457 &log("Updating file '$fileName' from VBServer at '$VBServerURI'");
458 $origFileName = $fileObj->getOrigFileName();
459 $fullFileObj = $vbClientObj->getSyncFileObj($origFileName);
460
461 if(! $fullFileObj)
462 {
463 &error("Can't retrieve '$origFileName' from VBServer");
464 next;
465 }
466
467 $fullFileObj->changeBasePath($::VBHOME);
468 $fullFileObj->sync();
469 $filesChangedCount++;
470 }
471
472 ($filesChangedCount);
473 }
474  
475 1;
476 __END__