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