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