fix build calc to take into account sub directories
[spider.git] / perl / cluster.pl
1 #!/usr/bin/perl -w
2 #
3 # This is the DX cluster 'daemon'. It sits in the middle of its little
4 # web of client routines sucking and blowing data where it may.
5 #
6 # Hence the name of 'spider' (although it may become 'dxspider')
7 #
8 # Copyright (c) 1998 Dirk Koopman G1TLH
9 #
10 # $Id$
11
12
13 require 5.004;
14
15 # make sure that modules are searched in the order local then perl
16 BEGIN {
17         umask 002;
18         
19         # root of directory tree for this system
20         $root = "/spider"; 
21         $root = $ENV{'DXSPIDER_ROOT'} if $ENV{'DXSPIDER_ROOT'};
22         
23         unshift @INC, "$root/perl";     # this IS the right way round!
24         unshift @INC, "$root/local";
25
26         # try to create and lock a lockfile (this isn't atomic but 
27         # should do for now
28         $lockfn = "$root/perl/cluster.lck";       # lock file name
29         if (-e $lockfn) {
30                 open(CLLOCK, "$lockfn") or die "Can't open Lockfile ($lockfn) $!";
31                 my $pid = <CLLOCK>;
32                 chomp $pid;
33                 die "Lockfile ($lockfn) and process $pid exist, another cluster running?" if kill 0, $pid;
34                 close CLLOCK;
35         }
36         open(CLLOCK, ">$lockfn") or die "Can't open Lockfile ($lockfn) $!";
37         print CLLOCK "$$\n";
38         close CLLOCK;
39
40         $is_win = ($^O =~ /^MS/ || $^O =~ /^OS-2/) ? 1 : 0; # is it Windows?
41         $systime = time;
42 }
43
44 use DXVars;
45 use Msg;
46 use IntMsg;
47 use Internet;
48 use Listeners;
49 use ExtMsg;
50 use AGWConnect;
51 use AGWMsg;
52 use DXDebug;
53 use DXLog;
54 use DXLogPrint;
55 use DXUtil;
56 use DXChannel;
57 use DXUser;
58 use DXM;
59 use DXCommandmode;
60 use DXProtVars;
61 use DXProtout;
62 use DXProt;
63 use DXMsg;
64 use DXCluster;
65 use DXCron;
66 use DXConnect;
67 use DXBearing;
68 use DXDb;
69 use DXHash;
70 use DXDupe;
71 use Prefix;
72 use Spot;
73 use Bands;
74 use Keps;
75 use Minimuf;
76 use Sun;
77 use Geomag;
78 use CmdAlias;
79 use Filter;
80 use AnnTalk;
81 use BBS;
82 use WCY;
83 use BadWords;
84 use Timer;
85 use Route;
86 use Route::Node;
87 use Route::User;
88
89 use Data::Dumper;
90 use IO::File;
91 use Fcntl ':flock'; 
92 use POSIX ":sys_wait_h";
93
94 use Local;
95
96 package main;
97
98 use strict;
99 use vars qw(@inqueue $systime $version $starttime $lockfn @outstanding_connects 
100                         $zombies $root @listeners $lang $myalias @debug $userfn $clusteraddr 
101                         $clusterport $mycall $decease $build $is_win $routeroot 
102                    );
103
104 @inqueue = ();                                  # the main input queue, an array of hashes
105 $systime = 0;                                   # the time now (in seconds)
106 $version = "1.48";                              # the version no of the software
107 $starttime = 0;                 # the starting time of the cluster   
108 #@outstanding_connects = ();     # list of outstanding connects
109 @listeners = ();                                # list of listeners
110
111       
112 # send a message to call on conn and disconnect
113 sub already_conn
114 {
115         my ($conn, $call, $mess) = @_;
116
117         $conn->disable_read(1);
118         dbg('chan', "-> D $call $mess\n"); 
119         $conn->send_now("D$call|$mess");
120         sleep(2);
121         $conn->disconnect;
122 }
123
124 sub error_handler
125 {
126         my $dxchan = shift;
127         $dxchan->{conn}->set_error(undef) if exists $dxchan->{conn};
128         $dxchan->disconnect(1);
129 }
130
131 # handle incoming messages
132 sub new_channel
133 {
134         my ($conn, $msg) = @_;
135         my ($sort, $call, $line) = DXChannel::decode_input(0, $msg);
136         return unless defined $sort;
137         
138         # set up the basic channel info
139         # is there one already connected to me - locally? 
140         my $user = DXUser->get($call);
141         my $dxchan = DXChannel->get($call);
142         if ($dxchan) {
143                 my $mess = DXM::msg($lang, ($user && $user->is_node) ? 'concluster' : 'conother', $call, $main::mycall);
144                 already_conn($conn, $call, $mess);
145                 return;
146         }
147         
148         # is there one already connected elsewhere in the cluster?
149         if ($user) {
150                 if (($user->is_node || $call eq $myalias) && !DXCluster->get_exact($call)) {
151                         ;
152                 } else {
153                         if (my $ref = DXCluster->get_exact($call)) {
154                                 my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->dxchancall);
155                                 already_conn($conn, $call, $mess);
156                                 return;
157                         }
158                 }
159                 $user->{lang} = $main::lang if !$user->{lang}; # to autoupdate old systems
160         } else {
161                 if (my $ref = DXCluster->get_exact($call)) {
162                         my $mess = DXM::msg($lang, 'concluster', $call, $ref->mynode->dxchancall);
163                         already_conn($conn, $call, $mess);
164                         return;
165                 }
166                 $user = DXUser->new($call);
167         }
168         
169         # is he locked out ?
170         if ($user->lockout) {
171                 Log('DXCommand', "$call is locked out, disconnected");
172                 $conn->disconnect;
173                 return;
174         }
175
176         # create the channel
177         $dxchan = DXCommandmode->new($call, $conn, $user) if $user->is_user;
178         $dxchan = DXProt->new($call, $conn, $user) if $user->is_node;
179         $dxchan = BBS->new($call, $conn, $user) if $user->is_bbs;
180         die "Invalid sort of user on $call = $sort" if !$dxchan;
181
182         # check that the conn has a callsign
183         $conn->conns($call) if $conn->isa('IntMsg');
184
185         # set callbacks
186         $conn->set_error(sub {error_handler($dxchan)});
187         $conn->set_rproc(sub {my ($conn,$msg) = @_; rec($dxchan, $conn, $msg);});
188         rec($dxchan, $conn, $msg);
189 }
190
191 sub rec 
192 {
193         my ($dxchan, $conn, $msg) = @_;
194         
195         # queue the message and the channel object for later processing
196         if (defined $msg) {
197                 my $self = bless {}, "inqueue";
198                 $self->{dxchan} = $dxchan;
199                 $self->{data} = $msg;
200                 push @inqueue, $self;
201         }
202 }
203
204 sub login
205 {
206         return \&new_channel;
207 }
208
209 # cease running this program, close down all the connections nicely
210 sub cease
211 {
212         my $dxchan;
213
214         unless ($is_win) {
215                 $SIG{'TERM'} = 'IGNORE';
216                 $SIG{'INT'} = 'IGNORE';
217         }
218         
219         DXUser::sync;
220
221         eval {
222                 Local::finish();   # end local processing
223         };
224         dbg('local', "Local::finish error $@") if $@;
225
226         # disconnect nodes
227         foreach $dxchan (DXChannel->get_all_nodes) {
228             $dxchan->disconnect(2) unless $dxchan == $DXProt::me;
229         }
230         Msg->event_loop(100, 0.01);
231
232         # disconnect users
233         foreach $dxchan (DXChannel->get_all_users) {
234                 $dxchan->disconnect;
235         }
236
237         # disconnect AGW
238         AGWMsg::finish();
239
240         # end everything else
241         Msg->event_loop(100, 0.01);
242         DXUser::finish();
243         DXDupe::finish();
244
245         # close all databases
246         DXDb::closeall;
247
248         # close all listeners
249         foreach my $l (@listeners) {
250                 $l->close_server;
251         }
252
253         dbg('chan', "DXSpider version $version, build $build ended");
254         Log('cluster', "DXSpider V$version, build $build ended");
255         dbgclose();
256         Logclose();
257         unlink $lockfn;
258 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
259         exit(0);
260 }
261
262 # the reaper of children
263 sub reap
264 {
265         my $cpid;
266         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
267                 dbg('reap', "cpid: $cpid");
268 #               Msg->pid_gone($cpid);
269                 $zombies-- if $zombies > 0;
270         }
271         dbg('reap', "cpid: $cpid");
272 }
273
274 # this is where the input queue is dealt with and things are dispatched off to other parts of
275 # the cluster
276 sub process_inqueue
277 {
278         my $self = shift @inqueue;
279         return if !$self;
280         
281         my $data = $self->{data};
282         my $dxchan = $self->{dxchan};
283         my $error;
284         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
285         return unless defined $sort;
286         
287         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
288         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
289
290         # handle A records
291         my $user = $dxchan->user;
292         if ($sort eq 'A' || $sort eq 'O') {
293                 $dxchan->start($line, $sort);  
294         } elsif ($sort eq 'I') {
295                 die "\$user not defined for $call" if !defined $user;
296                 # normal input
297                 $dxchan->normal($line);
298                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
299         } elsif ($sort eq 'Z') {
300                 $dxchan->disconnect;
301         } elsif ($sort eq 'D') {
302                 ;                       # ignored (an echo)
303         } else {
304                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
305         }
306 }
307
308 sub uptime
309 {
310         my $t = $systime - $starttime;
311         my $days = int $t / 86400;
312         $t -= $days * 86400;
313         my $hours = int $t / 3600;
314         $t -= $hours * 3600;
315         my $mins = int $t / 60;
316         return sprintf "%d %02d:%02d", $days, $hours, $mins;
317 }
318
319 sub AGWrestart
320 {
321         AGWMsg::init(\&new_channel);
322 }
323
324 #############################################################
325 #
326 # The start of the main line of code 
327 #
328 #############################################################
329
330 $starttime = $systime = time;
331 $lang = 'en' unless $lang;
332
333 # open the debug file, set various FHs to be unbuffered
334 dbginit();
335 foreach (@debug) {
336         dbgadd($_);
337 }
338 STDOUT->autoflush(1);
339
340 # calculate build number
341 $build = $main::version;
342
343 my @fn;
344 open(CL, "$main::root/perl/cluster.pl") or die "Cannot open cluster.pl $!";
345 while (<CL>) {
346         next unless /^use\s+([\w:_]+)/;
347         push @fn, $1;
348 }
349 close CL;
350 foreach my $fn (@fn) {
351         $fn =~ s|::|/|g;
352         open(CL, "$main::root/perl/${fn}.pm") or next;
353         while (<CL>) {
354                 if (/^#\s+\$Id:\s+[\w\._]+,v\s+(\d+\.\d+)/ ) {
355                         $build += $1;
356                         last;
357                 }
358         }
359         close CL;
360 }
361
362 Log('cluster', "DXSpider V$version, build $build started");
363
364 # banner
365 dbg('err', "DXSpider Version $version, build $build started", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
366
367 # load Prefixes
368 dbg('err', "loading prefixes ...");
369 Prefix::load();
370
371 # load band data
372 dbg('err', "loading band data ...");
373 Bands::load();
374
375 # initialise User file system
376 dbg('err', "loading user file system ..."); 
377 DXUser->init($userfn, 1);
378
379 # start listening for incoming messages/connects
380 dbg('err', "starting listeners ...");
381 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
382 $conn->conns("Server $clusteraddr/$clusterport");
383 push @listeners, $conn;
384 dbg('err', "Internal port: $clusteraddr $clusterport");
385 foreach my $l (@main::listen) {
386         $conn = ExtMsg->new_server($l->[0], $l->[1], \&login);
387         $conn->conns("Server $l->[0]/$l->[1]");
388         push @listeners, $conn;
389         dbg('err', "External Port: $l->[0] $l->[1]");
390 }
391 AGWrestart();
392
393 # load bad words
394 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
395
396 # prime some signals
397 unless ($DB::VERSION) {
398         $SIG{INT} = $SIG{TERM} = sub { $decease = 1 };
399 }
400
401 unless ($is_win) {
402         $SIG{HUP} = 'IGNORE';
403         $SIG{CHLD} = sub { $zombies++ };
404         
405         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
406         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
407         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
408         $SIG{KILL} = 'DEFAULT';     # as if it matters....
409
410         # catch the rest with a hopeful message
411         for (keys %SIG) {
412                 if (!$SIG{$_}) {
413                         #               dbg('chan', "Catching SIG $_");
414                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
415                 }
416         }
417 }
418
419 # start dupe system
420 DXDupe::init();
421
422 # read in system messages
423 DXM->init();
424
425 # read in command aliases
426 CmdAlias->init();
427
428 # initialise the Geomagnetic data engine
429 Geomag->init();
430 WCY->init();
431
432 # initial the Spot stuff
433 Spot->init();
434
435 # initialise the protocol engine
436 dbg('err', "reading in duplicate spot and WWV info ...");
437 DXProt->init();
438
439 # put in a DXCluster node for us here so we can add users and take them away
440 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
441 $routeroot = Route::Node->new($mycall, $version, Route::here($DXProt::me->here)|Route::conf($DXProt::me->confmode));
442
443 # read in any existing message headers and clean out old crap
444 dbg('err', "reading existing message headers ...");
445 DXMsg->init();
446 DXMsg::clean_old();
447
448 # read in any cron jobs
449 dbg('err', "reading cron jobs ...");
450 DXCron->init();
451
452 # read in database descriptors
453 dbg('err', "reading database descriptors ...");
454 DXDb::load();
455
456 # starting local stuff
457 dbg('err', "doing local initialisation ...");
458 eval {
459         Local::init();
460 };
461 dbg('local', "Local::init error $@") if $@;
462
463 # print various flags
464 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
465
466 # this, such as it is, is the main loop!
467 dbg('err', "orft we jolly well go ...");
468
469 #open(DB::OUT, "|tee /tmp/aa");
470
471 for (;;) {
472 #       $DB::trace = 1;
473         
474         Msg->event_loop(10, 0.010);
475         my $timenow = time;
476         process_inqueue();                      # read in lines from the input queue and despatch them
477 #       $DB::trace = 0;
478         
479         # do timed stuff, ongoing processing happens one a second
480         if ($timenow != $systime) {
481                 reap if $zombies;
482                 $systime = $timenow;
483                 DXCron::process();      # do cron jobs
484                 DXCommandmode::process(); # process ongoing command mode stuff
485                 DXProt::process();              # process ongoing ak1a pcxx stuff
486                 DXConnect::process();
487                 DXMsg::process();
488                 DXDb::process();
489                 DXUser::process();
490                 DXDupe::process();
491                 AGWMsg::process();
492                                 
493                 eval { 
494                         Local::process();       # do any localised processing
495                 };
496                 dbg('local', "Local::process error $@") if $@;
497         }
498         if ($decease) {
499                 last if --$decease <= 0;
500         }
501 }
502 cease(0);
503 exit(0);
504
505