fix pc39 properly on shutdown?
[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         $SIG{'TERM'} = 'IGNORE';
210         $SIG{'INT'} = 'IGNORE';
211         
212         DXUser::sync;
213
214         eval {
215                 Local::finish();   # end local processing
216         };
217         dbg('local', "Local::finish error $@") if $@;
218
219         # disconnect nodes
220         foreach $dxchan (DXChannel->get_all_nodes) {
221             $dxchan->disconnect(2) unless $dxchan == $DXProt::me;
222         }
223         Msg->event_loop(100, 0.01);
224
225         # disconnect users
226         foreach $dxchan (DXChannel->get_all_users) {
227                 $dxchan->disconnect;
228         }
229
230         # disconnect AGW
231         AGWMsg::finish();
232
233         # end everything else
234         Msg->event_loop(100, 0.01);
235         DXUser::finish();
236         DXDupe::finish();
237
238         # close all databases
239         DXDb::closeall;
240
241         # close all listeners
242         foreach my $l (@listeners) {
243                 $l->close_server;
244         }
245
246         dbg('chan', "DXSpider version $version, build $build ended");
247         Log('cluster', "DXSpider V$version, build $build ended");
248         dbgclose();
249         Logclose();
250         unlink $lockfn;
251 #       $SIG{__WARN__} = $SIG{__DIE__} =  sub {my $a = shift; cluck($a); };
252         exit(0);
253 }
254
255 # the reaper of children
256 sub reap
257 {
258         my $cpid;
259         while (($cpid = waitpid(-1, WNOHANG)) > 0) {
260                 dbg('reap', "cpid: $cpid");
261 #               Msg->pid_gone($cpid);
262                 $zombies-- if $zombies > 0;
263         }
264         dbg('reap', "cpid: $cpid");
265 }
266
267 # this is where the input queue is dealt with and things are dispatched off to other parts of
268 # the cluster
269 sub process_inqueue
270 {
271         my $self = shift @inqueue;
272         return if !$self;
273         
274         my $data = $self->{data};
275         my $dxchan = $self->{dxchan};
276         my $error;
277         my ($sort, $call, $line) = DXChannel::decode_input($dxchan, $data);
278         return unless defined $sort;
279         
280         # do the really sexy console interface bit! (Who is going to do the TK interface then?)
281         dbg('chan', "<- $sort $call $line\n") unless $sort eq 'D';
282
283         # handle A records
284         my $user = $dxchan->user;
285         if ($sort eq 'A' || $sort eq 'O') {
286                 $dxchan->start($line, $sort);  
287         } elsif ($sort eq 'I') {
288                 die "\$user not defined for $call" if !defined $user;
289                 # normal input
290                 $dxchan->normal($line);
291                 $dxchan->disconnect if ($dxchan->{state} eq 'bye');
292         } elsif ($sort eq 'Z') {
293                 $dxchan->disconnect;
294         } elsif ($sort eq 'D') {
295                 ;                       # ignored (an echo)
296         } else {
297                 print STDERR atime, " Unknown command letter ($sort) received from $call\n";
298         }
299 }
300
301 sub uptime
302 {
303         my $t = $systime - $starttime;
304         my $days = int $t / 86400;
305         $t -= $days * 86400;
306         my $hours = int $t / 3600;
307         $t -= $hours * 3600;
308         my $mins = int $t / 60;
309         return sprintf "%d %02d:%02d", $days, $hours, $mins;
310 }
311
312 sub AGWrestart
313 {
314         AGWMsg::init(\&new_channel);
315 }
316
317 #############################################################
318 #
319 # The start of the main line of code 
320 #
321 #############################################################
322
323 $starttime = $systime = time;
324 $lang = 'en' unless $lang;
325
326 # open the debug file, set various FHs to be unbuffered
327 dbginit();
328 foreach (@debug) {
329         dbgadd($_);
330 }
331 STDOUT->autoflush(1);
332
333 # calculate build number
334 $build = $main::version;
335
336 my @fn;
337 open(CL, "$main::root/perl/cluster.pl") or die "Cannot open cluster.pl $!";
338 while (<CL>) {
339         next unless /^use\s+([\w:_]+)/;
340         push @fn, $1;
341 }
342 close CL;
343 foreach my $fn (@fn) {
344         open(CL, "$main::root/perl/${fn}.pm") or next;
345         while (<CL>) {
346                 if (/^#\s+\$Id:\s+[\w\._]+,v\s+(\d+\.\d+)/ ) {
347                         $build += $1;
348                         last;
349                 }
350         }
351         close CL;
352 }
353
354 Log('cluster', "DXSpider V$version, build $build started");
355
356 # banner
357 dbg('err', "DXSpider Version $version, build $build started", "Copyright (c) 1998-2001 Dirk Koopman G1TLH");
358
359 # load Prefixes
360 dbg('err', "loading prefixes ...");
361 Prefix::load();
362
363 # load band data
364 dbg('err', "loading band data ...");
365 Bands::load();
366
367 # initialise User file system
368 dbg('err', "loading user file system ..."); 
369 DXUser->init($userfn, 1);
370
371 # start listening for incoming messages/connects
372 dbg('err', "starting listeners ...");
373 my $conn = IntMsg->new_server($clusteraddr, $clusterport, \&login);
374 $conn->conns("Server $clusteraddr/$clusterport");
375 push @listeners, $conn;
376 dbg('err', "Internal port: $clusteraddr $clusterport");
377 foreach my $l (@main::listen) {
378         $conn = ExtMsg->new_server($l->[0], $l->[1], \&login);
379         $conn->conns("Server $l->[0]/$l->[1]");
380         push @listeners, $conn;
381         dbg('err', "External Port: $l->[0] $l->[1]");
382 }
383 AGWrestart();
384
385 # load bad words
386 dbg('err', "load badwords: " . (BadWords::load or "Ok"));
387
388 # prime some signals
389 unless ($is_win) {
390         unless ($DB::VERSION) {
391                 $SIG{INT} = \&cease;
392                 $SIG{TERM} = \&cease;
393         }
394         $SIG{HUP} = 'IGNORE';
395         $SIG{CHLD} = sub { $zombies++ };
396         
397         $SIG{PIPE} = sub {      dbg('err', "Broken PIPE signal received"); };
398         $SIG{IO} = sub {        dbg('err', "SIGIO received"); };
399         $SIG{WINCH} = $SIG{STOP} = $SIG{CONT} = 'IGNORE';
400         $SIG{KILL} = 'DEFAULT';     # as if it matters....
401
402         # catch the rest with a hopeful message
403         for (keys %SIG) {
404                 if (!$SIG{$_}) {
405                         #               dbg('chan', "Catching SIG $_");
406                         $SIG{$_} = sub { my $sig = shift;       DXDebug::confess("Caught signal $sig");  }; 
407                 }
408         }
409 }
410
411 # start dupe system
412 DXDupe::init();
413
414 # read in system messages
415 DXM->init();
416
417 # read in command aliases
418 CmdAlias->init();
419
420 # initialise the Geomagnetic data engine
421 Geomag->init();
422 WCY->init();
423
424 # initial the Spot stuff
425 Spot->init();
426
427 # initialise the protocol engine
428 dbg('err', "reading in duplicate spot and WWV info ...");
429 DXProt->init();
430
431 # put in a DXCluster node for us here so we can add users and take them away
432 DXNode->new($DXProt::me, $mycall, 0, 1, $DXProt::myprot_version); 
433
434 # read in any existing message headers and clean out old crap
435 dbg('err', "reading existing message headers ...");
436 DXMsg->init();
437 DXMsg::clean_old();
438
439 # read in any cron jobs
440 dbg('err', "reading cron jobs ...");
441 DXCron->init();
442
443 # read in database descriptors
444 dbg('err', "reading database descriptors ...");
445 DXDb::load();
446
447 # starting local stuff
448 dbg('err', "doing local initialisation ...");
449 eval {
450         Local::init();
451 };
452 dbg('local', "Local::init error $@") if $@;
453
454 # print various flags
455 #dbg('err', "seful info - \$^D: $^D \$^W: $^W \$^S: $^S \$^P: $^P");
456
457 # this, such as it is, is the main loop!
458 dbg('err', "orft we jolly well go ...");
459
460 #open(DB::OUT, "|tee /tmp/aa");
461
462 for (;;) {
463 #       $DB::trace = 1;
464         
465         Msg->event_loop(10, 0.010);
466         my $timenow = time;
467         process_inqueue();                      # read in lines from the input queue and despatch them
468 #       $DB::trace = 0;
469         
470         # do timed stuff, ongoing processing happens one a second
471         if ($timenow != $systime) {
472                 reap if $zombies;
473                 $systime = $timenow;
474                 DXCron::process();      # do cron jobs
475                 DXCommandmode::process(); # process ongoing command mode stuff
476                 DXProt::process();              # process ongoing ak1a pcxx stuff
477                 DXConnect::process();
478                 DXMsg::process();
479                 DXDb::process();
480                 DXUser::process();
481                 DXDupe::process();
482                 AGWMsg::process();
483                                 
484                 eval { 
485                         Local::process();       # do any localised processing
486                 };
487                 dbg('local', "Local::process error $@") if $@;
488         }
489         if ($decease) {
490                 last if --$decease <= 0;
491         }
492 }
493 cease(0);
494 exit(0);
495
496